v4: every page and API URL follows one of two rules, written down in API.md — pages are a hierarchy where @name is a user and any other root word a category or an app page, tabs and views are plain segments and a default view is the bare path; API resources are /api/<plural>/<key>, a user's key being an id or @name, the caller's things under /api/me, media a sub-resource, lookups by another key a query filter. ~ is gone: the feed is /, /hot, /new, /journal, /follow and /music/hot, a profile /@bob with its overview and the tabs dumps, upvoted, playlists (her own only), follow (users, and /follow/playlists), invitees and manage (role and name, for user:manage), which replace the separate UserDumps, UserUpvoted and UserPlaylists pages; /settings holds the account (now with the username) and /manage the category manager, both linked from the user menu and one's profile. Dumps and playlists live under their owner, /@bob/dumps/<slug> and /@bob/playlists/<slug>, named by slug alone: migration 0021 re-slugs them to the bare slugify(title), unique per owner and kind (the oldest keeps it, clashes get -2), renames the categories whose slug v4 reserves (hot, follow, settings…), and rewrites this site's v3 links in dump notes, comments, chat, and playlist and profile descriptions. A slug changes only when edited, through the edit forms' new link field, which proposes slugify(title) as the title changes; a username changes from /settings or, for user:manage, from /@name/manage. Every slug or name left behind stays an alias of its item or user for good (dump_slug_aliases, playlist_slug_aliases, user_aliases), so old links redirect without chaining and nobody else can take one; slugs change 3 times a day per item, names once in 30 days, moderators exempt. An alias, or a name in another case, answers the item with its current path: the pages put it in their URL (useCanonicalPath, without fetching again), and the OG middleware answers a 301. shared/paths.ts builds and parses every page path, for the client's links, the emails' (digest-service lost its own builders and its id fallbacks, and links /follow and /settings) and the server's matchers (OG tags, self previews, backlinks, self-url); shared/slug.ts holds slugify and the format categories share. Dumps and playlists carry ownerUsername and a required slug, and notifications join their users' current names and their items' paths each time they are sent or read, so renames reach them and a deleted item's has no link. The API was renamed per the plan's table: POST /api/users and /api/sessions, /api/password-resets, /api/me (with settings, password, avatar, media-token, playlists?contains=, follow, feed?from=, notifications), /api/users/:key/{dumps,upvoted,playlists,follow/users,follow/playlists,invitees,avatar} and by path /api/users/:key/{dumps,playlists}/:slug, /api/dumps?url= and ?category=, /api/dumps/:id/{file,thumbnail,metadata}, /api/playlists/:id/cover, /api/remote/{preview,image,bandcamp,youtube} (one router), and /api/unsubscribe, the v3 POST /api/users/unsubscribe staying for the digests already sent. A stored default feed tab "followed" reads as "follow" once. dumps.slug and playlists.slug stay nullable, since SQLite can't add NOT NULL without rebuilding tables others reference; every writer sets them and unique (user_id, slug) indexes hold them. 254 backend tests (new: migration 0021 on a v3 fixture, slug aliases, swaps and rate limits, username renames, aliases and limits, reads by path and their privacy, the OG 301s, both unsubscribe paths, v4-shaped digest links with no ids, notification joins, shared paths and slugs) and 668 frontend tests (new: the profile's tabs and follow views, Settings, Manage, the link field, canonical URLs on the dump, playlist and profile pages, bare default feed paths) pass, and tsc, eslint, deno check, deno lint, deno fmt and doc:lint are clean; the migration was also run on a copy of the development database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-06 16:08:59 +00:00
parent fd0d81fe66
commit 4468438ba7
228 changed files with 7320 additions and 5193 deletions

View File

@@ -28,14 +28,14 @@ Deno.test("runMigrations: a fresh database is left as schema.sql made it", () =>
.get() as {
n: number;
};
assertEquals(applied.n, 20);
assertEquals(applied.n, 21);
// Running again applies nothing.
runMigrations(db);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
n: number;
}).n,
20,
21,
);
db.close();
});

View File

@@ -0,0 +1,168 @@
import "../../setup.ts";
import { assertEquals } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { up as up0021 } from "../../../db/migrations/0021_page_urls.ts";
/** A database as v3 left it: schema.sql without 0021's tables and indexes. */
function v3Db(): DatabaseSync {
const db = new DatabaseSync(":memory:");
db.exec(
Deno.readTextFileSync(new URL("../../../db/schema.sql", import.meta.url)),
);
db.exec(`
DROP TABLE dump_slug_aliases;
DROP TABLE playlist_slug_aliases;
DROP TABLE user_aliases;
DROP INDEX idx_dumps_user_slug;
DROP INDEX idx_playlists_user_slug;
CREATE INDEX idx_dumps_slug ON dumps(slug);
CREATE INDEX idx_playlists_slug ON playlists(slug);
`);
return db;
}
const NOW = "2024-01-01T00:00:00.000Z";
const later = (n: number) => new Date(Date.parse(NOW) + n * 1000).toISOString();
function user(db: DatabaseSync, username: string): string {
const id = crypto.randomUUID();
db.prepare(
`INSERT INTO users (id, username, password_hash, created_at, email) VALUES (?, ?, 'x', ?, ?);`,
).run(id, username, NOW, `${username}@example.test`);
return id;
}
/** Inserts a dump or playlist with its v3 slug, and returns its id and slug. */
function item(
db: DatabaseSync,
table: "dumps" | "playlists",
userId: string,
title: string,
at: number,
): { id: string; v3: string } {
const id = crypto.randomUUID();
const v3 = `${title.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-${
id.slice(0, 8)
}`;
db.prepare(
table === "dumps"
? `INSERT INTO dumps (id, kind, title, slug, user_id, created_at, url) VALUES (?, 'url', ?, ?, ?, ?, 'https://x.test');`
: `INSERT INTO playlists (id, title, slug, user_id, created_at) VALUES (?, ?, ?, ?, ?);`,
).run(id, title, v3, userId, later(at));
return { id, v3 };
}
const slugOf = (db: DatabaseSync, table: string, id: string) =>
(db.prepare(`SELECT slug FROM ${table} WHERE id = ?;`).get(id) as {
slug: string;
}).slug;
Deno.test("migration 0021: bare slugs unique per owner, reserved categories renamed", () => {
const db = v3Db();
const bob = user(db, "Bob");
const ann = user(db, "ann");
const first = item(db, "dumps", bob, "Never Gonna", 0);
const second = item(db, "dumps", bob, "Never gonna!", 1);
const anns = item(db, "dumps", ann, "Never Gonna", 2);
const mix = item(db, "playlists", bob, "Never Gonna", 3);
for (
const [slug, name] of [
["hot", "Hot"],
["hot-2", "Hot 2"],
["follow", "F"],
["music", "M"],
]
) {
db.prepare(
`INSERT INTO categories (id, slug, name, created_at) VALUES (?, ?, ?, ?);`,
).run(crypto.randomUUID(), slug, name, NOW);
}
up0021(db);
// The oldest keeps the bare slug; each kind and owner is its own space.
assertEquals(slugOf(db, "dumps", first.id), "never-gonna");
assertEquals(slugOf(db, "dumps", second.id), "never-gonna-2");
assertEquals(slugOf(db, "dumps", anns.id), "never-gonna");
assertEquals(slugOf(db, "playlists", mix.id), "never-gonna");
assertEquals(
(db.prepare(`SELECT slug FROM categories ORDER BY slug;`).all() as {
slug: string;
}[]).map((r) => r.slug),
["follow-2", "hot-2", "hot-3", "music"],
);
// The new index holds.
let clash = false;
try {
db.prepare(`UPDATE dumps SET slug = 'never-gonna' WHERE id = ?;`).run(
second.id,
);
} catch {
clash = true;
}
assertEquals(clash, true);
db.close();
});
Deno.test("migration 0021: v3 links in notes, comments and chat become v4 paths", () => {
const db = v3Db();
const bob = user(db, "Bob");
const dump = item(db, "dumps", bob, "Never Gonna", 0);
const mix = item(db, "playlists", bob, "Sunday Mix", 1);
const text = [
`[by slug](http://gerbeur.test/dumps/${dump.v3}#comment-1)`,
`[relative by id](/dumps/${dump.id}/edit)`,
`http://gerbeur.test/playlists/${mix.id}?x=1`,
`<http://gerbeur.test/users/bob/~/followed>`,
`[list](/users/BOB/upvoted) [settings](/users/bob/~/settings)`,
`[feed](/~/followed) [search](/search/~/users?q=a)`,
// Another site's, a bare path in prose and a deleted dump stay as they are.
`https://elsewhere.test/dumps/${dump.v3} see /dumps/${dump.v3}`,
`http://gerbeur.test/dumps/gone-12345678`,
].join("\n");
const expected = [
`[by slug](http://gerbeur.test/@Bob/dumps/never-gonna#comment-1)`,
`[relative by id](/@Bob/dumps/never-gonna/edit)`,
`http://gerbeur.test/@Bob/playlists/sunday-mix?x=1`,
`<http://gerbeur.test/@Bob/follow>`,
`[list](/@Bob/upvoted) [settings](/settings)`,
`[feed](/follow) [search](/search/users?q=a)`,
`https://elsewhere.test/dumps/${dump.v3} see /dumps/${dump.v3}`,
`http://gerbeur.test/dumps/gone-12345678`,
].join("\n");
const commentId = crypto.randomUUID();
const messageId = crypto.randomUUID();
db.prepare(`UPDATE dumps SET comment = ? WHERE id = ?;`).run(text, dump.id);
db.prepare(`UPDATE playlists SET description = ? WHERE id = ?;`).run(
text,
mix.id,
);
db.prepare(
`INSERT INTO comments (id, dump_id, user_id, body, created_at) VALUES (?, ?, ?, ?, ?);`,
).run(commentId, dump.id, bob, text, NOW);
db.prepare(
`INSERT INTO chat_messages (id, user_id, body, created_at) VALUES (?, ?, ?, ?);`,
).run(messageId, bob, text, NOW);
up0021(db);
const read = (sql: string, id: string) =>
(db.prepare(sql).get(id) as { text: string }).text;
assertEquals(
read(`SELECT comment AS text FROM dumps WHERE id = ?;`, dump.id),
expected,
);
assertEquals(
read(`SELECT body AS text FROM comments WHERE id = ?;`, commentId),
expected,
);
assertEquals(
read(`SELECT body AS text FROM chat_messages WHERE id = ?;`, messageId),
expected,
);
assertEquals(
read(`SELECT description AS text FROM playlists WHERE id = ?;`, mix.id),
expected,
);
db.close();
});

View File

@@ -6,7 +6,9 @@ import { app } from "../main.ts";
import { db } from "../db/connection.ts";
import { createJWT, createMediaToken } from "../lib/jwt.ts";
import { hashPassword } from "../lib/password.ts";
import { makeSlug } from "../lib/slugify.ts";
import { uniqueSlug } from "../lib/slugify.ts";
import { slugify } from "../../shared/slug.ts";
import { dumpPath, playlistPath } from "../../shared/paths.ts";
import { canonicalizeUrl } from "../lib/canonical-url.ts";
import { clearRichContentCache } from "../services/rich-content-service.ts";
import { clearImageCache } from "../remote/image-proxy.ts";
@@ -36,6 +38,9 @@ const TABLES = [
"chat_messages",
"user_settings",
"digest_schedule",
"dump_slug_aliases",
"playlist_slug_aliases",
"user_aliases",
"categories",
"playlists",
"dumps",
@@ -147,16 +152,24 @@ export interface InsertDumpOptions {
richContent?: Record<string, unknown>;
}
/** Returns the name of user `userId`, for the page paths of their things. */
function usernameOf(userId: string): string {
return (db.prepare(`SELECT username FROM users WHERE id = ?;`).get(
userId,
) as { username: string }).username;
}
/**
* Inserts a dump row directly, skipping the metadata fetch the create route
* does. Returns its id and slug.
* does, with a slug made from its title as the service would. Returns its id,
* slug and page path.
*/
export function insertDump(
opts: InsertDumpOptions,
): { id: string; slug: string } {
): { id: string; slug: string; path: string } {
const id = crypto.randomUUID();
const title = opts.title ?? "A dump";
const slug = makeSlug(title, id);
const slug = uniqueSlug(db, "dump", opts.userId, slugify(title));
const kind = opts.kind ?? (opts.fileName ? "file" : "url");
const url = kind === "url" ? (opts.url ?? `https://example.com/${id}`) : null;
const data = opts.fileData ?? new TextEncoder().encode("hello");
@@ -184,15 +197,20 @@ export function insertDump(
Deno.mkdirSync(`${TEST_DIR}/uploads/dumps`, { recursive: true });
Deno.writeFileSync(`${TEST_DIR}/uploads/dumps/${id}`, data);
}
return { id, slug };
return {
id,
slug,
path: dumpPath({ ownerUsername: usernameOf(opts.userId), slug }),
};
}
/** Inserts a playlist row as {@link insertDump} does a dump. */
export function insertPlaylist(
opts: { userId: string; title?: string; isPublic?: boolean },
): { id: string; slug: string } {
): { id: string; slug: string; path: string } {
const id = crypto.randomUUID();
const title = opts.title ?? "A playlist";
const slug = makeSlug(title, id);
const slug = uniqueSlug(db, "playlist", opts.userId, slugify(title));
db.prepare(
`INSERT INTO playlists (id, user_id, title, slug, is_public, created_at)
VALUES (?, ?, ?, ?, ?, ?);`,
@@ -204,7 +222,11 @@ export function insertPlaylist(
opts.isPublic === false ? 0 : 1,
new Date().toISOString(),
);
return { id, slug };
return {
id,
slug,
path: playlistPath({ ownerUsername: usernameOf(opts.userId), slug }),
};
}
export function insertComment(

View File

@@ -12,7 +12,7 @@ test("authenticate: a deleted user's token is refused", async () => {
const user = await createUser();
db.prepare(`DELETE FROM users WHERE id = ?;`).run(user.id);
assertEquals(await authenticate(user.token), null);
assertEquals((await get("/api/users/me", { auth: user.auth })).status, 401);
assertEquals((await get("/api/me", { auth: user.auth })).status, 401);
});
test("authenticate: tokens issued before tokens_valid_after are revoked", async () => {
@@ -43,7 +43,7 @@ test("authenticateMedia: takes a media token or a legacy session token", async (
test("optional auth: a missing or placeholder token is anonymous, a bad one is 401", async () => {
const owner = await createUser();
// A public listing that reads optional auth.
const path = `/api/users/${owner.username}/dumps`;
const path = `/api/users/@${owner.username}/dumps`;
assertEquals((await get(path)).status, 200);
for (const placeholder of ["Bearer undefined", "Bearer null", "Bearer "]) {
assertEquals(

View File

@@ -1,16 +1,13 @@
import "../setup.ts";
import { assert, assertFalse } from "@std/assert";
import { isReservedSlug, isValidSlugFormat } from "../../lib/reserved-slugs.ts";
import { isReservedSlug } from "../../lib/reserved-slugs.ts";
Deno.test("category slugs: format and reserved words", () => {
assert(isValidSlugFormat("music"));
assert(isValidSlugFormat("lo-fi-2"));
for (const bad of ["Music", "-music", "music-", "lo--fi", "lo fi", ""]) {
assertFalse(isValidSlugFormat(bad), bad);
Deno.test("category slugs: the feed tabs, app pages and server paths are reserved", () => {
for (const word of ["hot", "follow", "settings", "manage", "api", "ws"]) {
assert(isReservedSlug(word), word);
}
// v3's words are free again: nothing lives at /dumps or /users now.
for (const word of ["music", "dumps", "users", "playlists", "~"]) {
assertFalse(isReservedSlug(word), word);
}
assert(isReservedSlug("dumps"));
assert(isReservedSlug("api"));
assert(isReservedSlug("ws"));
assert(isReservedSlug("emojibase"));
assertFalse(isReservedSlug("music"));
});

View File

@@ -4,10 +4,12 @@ import { isSelfUrl } from "../../lib/self-url.ts";
Deno.test("isSelfUrl: this site's dump, user and playlist pages only", () => {
// GERBEUR_PUBLIC_URL is http://gerbeur.test in the suite.
assert(isSelfUrl(new URL("http://gerbeur.test/dumps/abc")));
assert(isSelfUrl(new URL("https://GERBEUR.test/users/bob")));
assert(isSelfUrl(new URL("http://gerbeur.test/playlists/p-1")));
assertFalse(isSelfUrl(new URL("http://gerbeur.test/dumps/abc/edit")));
assert(isSelfUrl(new URL("http://gerbeur.test/@bob/dumps/abc")));
assert(isSelfUrl(new URL("https://GERBEUR.test/@bob")));
assert(isSelfUrl(new URL("http://gerbeur.test/@bob/playlists")));
assert(isSelfUrl(new URL("http://gerbeur.test/@bob/playlists/p-1")));
assertFalse(isSelfUrl(new URL("http://gerbeur.test/@bob/dumps/abc/edit")));
assertFalse(isSelfUrl(new URL("http://gerbeur.test/search")));
assertFalse(isSelfUrl(new URL("http://elsewhere.test/users/bob")));
assertFalse(isSelfUrl(new URL("http://gerbeur.test/dumps/abc")));
assertFalse(isSelfUrl(new URL("http://elsewhere.test/@bob")));
});

View File

@@ -1,19 +1,31 @@
import "../setup.ts";
import { assert, assertEquals, assertFalse } from "@std/assert";
import { makeSlug, slugify, UUID_RE } from "../../lib/slugify.ts";
import { assertEquals, assertThrows } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { uniqueSlug, validateSlug } from "../../lib/slugify.ts";
import { APIException } from "../../lib/api-exception.ts";
Deno.test("slugify: lowercases, strips accents, dashes the rest", () => {
assertEquals(slugify("Hello, World!"), "hello-world");
assertEquals(slugify("Crème brûlée à Paris"), "creme-brulee-a-paris");
assertEquals(slugify(" --already--dashed-- "), "already-dashed");
assertEquals(slugify("日本語"), "untitled");
assertEquals(slugify(""), "untitled");
assertEquals(slugify("x".repeat(100)).length, 60);
Deno.test("uniqueSlug: numbers a clash within the owner's space, aliases included", () => {
const db = new DatabaseSync(":memory:");
db.exec(`
CREATE TABLE dumps (id TEXT, user_id TEXT, slug TEXT);
CREATE TABLE dump_slug_aliases (user_id TEXT, slug TEXT, dump_id TEXT);
INSERT INTO dumps VALUES ('1', 'bob', 'mix'), ('2', 'bob', 'mix-2');
INSERT INTO dump_slug_aliases VALUES ('bob', 'mix-3', '1');
`);
assertEquals(uniqueSlug(db, "dump", "bob", "mix"), "mix-4");
assertEquals(uniqueSlug(db, "dump", "ann", "mix"), "mix");
// The suffix still fits in 60 characters, cut at no hyphen.
db.prepare(`INSERT INTO dumps VALUES ('3', 'bob', ?);`).run("a".repeat(60));
assertEquals(
uniqueSlug(db, "dump", "bob", "a".repeat(60)),
"a".repeat(58) + "-2",
);
db.close();
});
Deno.test("makeSlug: suffixes the first 8 characters of the id", () => {
const id = "0123abcd-0000-4000-8000-000000000000";
assertEquals(makeSlug("My Song", id), "my-song-0123abcd");
assert(UUID_RE.test(id));
assertFalse(UUID_RE.test("my-song-0123abcd"));
Deno.test("validateSlug: lowercase words joined by hyphens, 60 at most", () => {
validateSlug("never-gonna-2");
for (const bad of ["Never", "-a", "a-", "a--b", "a b", "", "a".repeat(61)]) {
assertThrows(() => validateSlug(bad), APIException, undefined, bad);
}
});

View File

@@ -14,7 +14,7 @@ const dump = (title: string, over = {}) => ({
url: "https://g.test/dumps/x",
poster: "bob",
domain: "example.com",
thumbnail: "https://g.test/api/thumbnails/x?v=1",
thumbnail: "https://g.test/api/dumps/x/thumbnail?v=1",
votes: 1,
comments: 0,
mine: false,

View File

@@ -2,15 +2,15 @@ import { createUser, get, test } from "../helpers.ts";
import { assertEquals } from "@std/assert";
test("required auth: missing, malformed and forged tokens are 401", async () => {
assertEquals((await get("/api/users/me")).status, 401);
assertEquals((await get("/api/me")).status, 401);
assertEquals(
(await get("/api/users/me", { headers: { Authorization: "Token x" } }))
(await get("/api/me", { headers: { Authorization: "Token x" } }))
.status,
401,
);
const media = (await createUser()).mediaToken;
assertEquals(
(await get("/api/users/me", {
(await get("/api/me", {
headers: { Authorization: `Bearer ${media}` },
})).status,
401,

View File

@@ -1,6 +1,7 @@
import {
BASE_URL,
createUser,
db,
insertDump,
insertPlaylist,
test,
@@ -40,7 +41,7 @@ test("ogMiddleware: dump pages get escaped OG tags", async () => {
thumbnailUrl: "https://img.test/a.jpg",
},
});
const { res, text } = await handle(ogApp(), `/dumps/${dump.slug}`);
const { res, text } = await handle(ogApp(), dump.path);
assertEquals(res.headers.get("content-type"), "text/html; charset=utf-8");
assertStringIncludes(
text,
@@ -61,7 +62,7 @@ test("ogMiddleware: dump pages get escaped OG tags", async () => {
assertStringIncludes(text, `content="summary_large_image"`);
assertStringIncludes(
text,
`<meta property="og:url" content="${BASE_URL}/dumps/${dump.slug}" />`,
`<meta property="og:url" content="${BASE_URL}${dump.path}" />`,
);
// The index's own title is replaced, not duplicated.
assertEquals(text.match(/<title>/g)?.length, 1);
@@ -71,7 +72,7 @@ test("ogMiddleware: dump pages get escaped OG tags", async () => {
test("ogMiddleware: no artwork falls back to the site icon as a small card", async () => {
const user = await createUser();
const dump = insertDump({ userId: user.id, title: "Plain" });
const { text } = await handle(ogApp(), `/dumps/${dump.id}`);
const { text } = await handle(ogApp(), dump.path);
assertStringIncludes(text, `content="${BASE_URL}/apple-touch-icon.png"`);
assertStringIncludes(text, `<meta name="twitter:card" content="summary" />`);
const file = insertDump({
@@ -80,8 +81,8 @@ test("ogMiddleware: no artwork falls back to the site icon as a small card", asy
fileMime: "image/png",
});
assertStringIncludes(
(await handle(ogApp(), `/dumps/${file.id}`)).text,
`content="${BASE_URL}/api/files/${file.id}"`,
(await handle(ogApp(), file.path)).text,
`content="${BASE_URL}/api/dumps/${file.id}/file"`,
);
});
@@ -89,12 +90,16 @@ test("ogMiddleware: users and public playlists; private things fall through", as
const user = await createUser();
const app = ogApp();
assertStringIncludes(
(await handle(app, `/users/${user.username}/~/votes`)).text,
(await handle(app, `/@${user.username}/upvoted`)).text,
`<meta property="og:title" content="${user.username}" />`,
);
assertEquals(
(await handle(app, `/@${user.username}/nope`)).text,
"fallthrough",
);
const pub = insertPlaylist({ userId: user.id, title: "Open list" });
assertStringIncludes(
(await handle(app, `/playlists/${pub.slug}`)).text,
(await handle(app, pub.path)).text,
"Open list",
);
const priv = insertPlaylist({
@@ -103,7 +108,7 @@ test("ogMiddleware: users and public playlists; private things fall through", as
isPublic: false,
});
assertEquals(
(await handle(app, `/playlists/${priv.slug}`)).text,
(await handle(app, priv.path)).text,
"fallthrough",
);
const secret = insertDump({
@@ -111,11 +116,48 @@ test("ogMiddleware: users and public playlists; private things fall through", as
title: "Secret",
isPrivate: true,
});
assertEquals((await handle(app, secret.path)).text, "fallthrough");
assertEquals(
(await handle(app, `/@${user.username}/dumps/nope`)).text,
"fallthrough",
);
// v3 paths aren't redirected.
assertEquals((await handle(app, `/dumps/${secret.id}`)).text, "fallthrough");
assertEquals((await handle(app, `/dumps/nope`)).text, "fallthrough");
assertEquals(
(await handle(app, `/api/dumps/${secret.id}`)).text,
"fallthrough",
);
assertEquals((await handle(app, `/favicon.ico`)).text, "fallthrough");
});
test("ogMiddleware: a former slug, a former name or another case gets a 301", async () => {
const user = await createUser();
const dump = insertDump({ userId: user.id, title: "Now" });
db.prepare(
`INSERT INTO dump_slug_aliases (user_id, slug, dump_id, created_at) VALUES (?, 'before', ?, ?);`,
).run(user.id, dump.id, new Date().toISOString());
db.prepare(
`INSERT INTO user_aliases (username, user_id, created_at) VALUES ('old_name', ?, ?);`,
).run(user.id, new Date().toISOString());
for (
const [from, to] of [
[`/@${user.username}/dumps/before?x=1`, `${dump.path}?x=1`],
[`/@OLD_NAME/dumps/now`, dump.path],
[`/@old_name/follow/playlists`, `/@${user.username}/follow/playlists`],
[`/@${user.username.toUpperCase()}`, `/@${user.username}`],
]
) {
const { res } = await handle(ogApp(), from);
assertEquals(res.status, 301, from);
assertEquals(res.headers.get("location"), `${BASE_URL}${to}`, from);
}
// A private dump's former slug tells nothing.
const secret = insertDump({ userId: user.id, title: "S", isPrivate: true });
db.prepare(
`INSERT INTO dump_slug_aliases (user_id, slug, dump_id, created_at) VALUES (?, 'hush', ?, ?);`,
).run(user.id, secret.id, new Date().toISOString());
assertEquals(
(await handle(ogApp(), `/@${user.username}/dumps/hush`)).text,
"fallthrough",
);
});

View File

@@ -19,6 +19,7 @@ Deno.test("dump rows round-trip through the API shape", () => {
file_size: null,
vote_count: 3,
comment_count: 2,
owner_username: "bob",
is_private: 1,
custom_thumbnail_mime: null,
};

View File

@@ -20,14 +20,14 @@ test("self provider: our own dump, user and playlist pages come from the DB", as
throw new Error("no network for self links");
});
const content = await fetchRichContent(
`http://gerbeur.test/dumps/${dump.slug}`,
`http://gerbeur.test${dump.path}`,
);
assertEquals(content?.title, "Local dump");
assertEquals(content?.description, "About it");
assertEquals(content?.thumbnailUrl, "https://t/x.jpg");
assertEquals(content?.siteName, "gerbeur");
const profile = await fetchRichContent(
`http://gerbeur.test/users/${user.username}`,
`http://gerbeur.test/@${user.username}/playlists`,
);
assertEquals(profile?.title, user.username);
assertEquals(net.calls.length, 0);
@@ -44,7 +44,7 @@ test("self provider: a private playlist gets no preview", async () => {
throw new Error("no network for self links");
});
const content = await fetchRichContent(
`http://gerbeur.test/playlists/${playlist.id}`,
`http://gerbeur.test${playlist.path}`,
);
assertEquals(content?.title, undefined);
});

View File

@@ -1,23 +1,26 @@
import { createUser, formWithFile, get, PNG, post, test } from "../helpers.ts";
import { createUser, formWithFile, get, PNG, put, test } from "../helpers.ts";
import type { SelfUser } from "../../../shared/user.ts";
import { assertEquals, assertFalse } from "@std/assert";
test("avatars: upload, serve, and 404 when there is none", async () => {
const user = await createUser();
assertEquals((await get(`/api/avatars/${user.id}`)).status, 404);
assertEquals((await get(`/api/avatars/${crypto.randomUUID()}`)).status, 404);
const res = await post<SelfUser>("/api/avatars/me", {
assertEquals((await get(`/api/users/${user.id}/avatar`)).status, 404);
assertEquals(
(await get(`/api/users/${crypto.randomUUID()}/avatar`)).status,
404,
);
const res = await put<SelfUser>("/api/me/avatar", {
auth: user.auth,
form: formWithFile(PNG),
});
assertEquals(res.status, 200);
assertEquals(res.data.avatarMime, "image/png");
assertFalse("passwordHash" in res.data);
const served = await get(`/api/avatars/${user.id}`);
const served = await get(`/api/users/${user.id}/avatar`);
assertEquals(served.status, 200);
assertEquals(served.bytes, PNG);
assertEquals(
(await post("/api/avatars/me", {
(await put("/api/me/avatar", {
auth: user.auth,
form: formWithFile(new Uint8Array([1, 2, 3])),
})).status,

View File

@@ -1,89 +0,0 @@
import { get, html, stubNetwork } from "../helpers.ts";
import { assertEquals } from "@std/assert";
import type { Tralbum } from "../../../shared/player.ts";
function escapeAttr(s: string): string {
return s.replaceAll("&", "&amp;").replaceAll('"', "&quot;");
}
function tralbumPage(data: unknown): string {
return `<div id="player" data-tralbum="${
escapeAttr(JSON.stringify(data))
}"></div>`;
}
const STREAM = "https://t4.bcbits.com/stream/abc/mp3-128/1?p=0&ts=1&t=x";
const ALBUM = {
item_type: "album",
artist: "Artist",
art_id: 12345,
current: { title: 'The "Album" &amp; more' },
trackinfo: [
{
track_num: 1,
title: "One",
duration: 180.5,
streaming: 1,
file: { "mp3-128": STREAM },
},
{
track_num: 2,
title: "Preorder",
streaming: 1,
unreleased_track: true,
file: null,
},
{
track_num: 3,
title: "",
streaming: 1,
file: { "mp3-128": "https://evil.test/x.mp3" },
},
{
track_num: 4,
title: "Capped",
streaming: 1,
is_capped: true,
file: { "mp3-128": STREAM },
},
],
};
Deno.test("GET /api/bandcamp/tracks: resolves, caches, and forces a refetch", async () => {
using net = stubNetwork(() => html(tralbumPage(ALBUM)));
const url = "https://cached.bandcamp.com/album/x";
const res = await get<Tralbum>(
`/api/bandcamp/tracks?url=${encodeURIComponent(url)}`,
);
assertEquals(res.status, 200);
assertEquals(res.headers.get("cache-control"), "private, max-age=3600");
assertEquals(res.data.tracks.length, 4);
// Same page (different query/case/trailing slash) → cache hit.
await get(
`/api/bandcamp/tracks?url=${
encodeURIComponent("https://CACHED.bandcamp.com/album/x/?from=y")
}`,
);
assertEquals(net.calls.length, 1);
await get(`/api/bandcamp/tracks?url=${encodeURIComponent(url)}&force=1`);
assertEquals(net.calls.length, 2);
});
Deno.test("GET /api/bandcamp/tracks: refusals and upstream failures", async () => {
using _ = stubNetwork((url) => {
if (url.hostname.startsWith("down")) {
return new Response("", { status: 503 });
}
if (url.hostname.startsWith("json")) return Response.json({});
return html("<html>no tralbum</html>");
});
const status = async (url: string) =>
(await get(`/api/bandcamp/tracks?url=${encodeURIComponent(url)}`)).status;
assertEquals(await status("https://example.com/album/x"), 400);
assertEquals(await status("https://bandcamp.com.evil.test/album/x"), 400);
assertEquals(await status("http://localhost/album/x"), 400);
assertEquals(await status("https://down.bandcamp.com/album/x"), 502);
assertEquals(await status("https://json.bandcamp.com/album/x"), 502);
assertEquals(await status("https://empty.bandcamp.com/album/x"), 404);
});

View File

@@ -14,7 +14,7 @@ import type { Dump } from "../../../shared/dump.ts";
import type { PaginatedData } from "../../../shared/api.ts";
import { assertEquals, assertStringIncludes } from "@std/assert";
test("categories: listed by position, then slug; found by slug", async () => {
test("categories: listed by position, then slug", async () => {
insertCategory({ slug: "zeta", position: 0 });
insertCategory({ slug: "alpha", position: 1 });
insertCategory({ slug: "beta", position: 0 });
@@ -24,11 +24,6 @@ test("categories: listed by position, then slug; found by slug", async () => {
"zeta",
"alpha",
]);
assertEquals(
(await get<Category>("/api/categories/alpha")).data.slug,
"alpha",
);
assertEquals((await get("/api/categories/nope")).status, 404);
});
test("categories: only category:manage may create, update or delete", async () => {
@@ -74,7 +69,8 @@ test("categories: slug and name rules, and friendly conflicts", async () => {
for (
const [json, message] of [
[{ slug: "Bad Slug", name: "x" }, "lowercase"],
[{ slug: "users", name: "x" }, "reserved"],
[{ slug: "hot", name: "x" }, "reserved"],
[{ slug: "settings", name: "x" }, "reserved"],
[{ slug: "a".repeat(51), name: "x" }, "at most 50"],
[{ slug: "ok", name: " " }, "Name is required"],
[{ slug: "ok", name: "x".repeat(51) }, "at most 50"],
@@ -110,7 +106,7 @@ test("categories: slug and name rules, and friendly conflicts", async () => {
assertEquals(ok.data.position, 3);
});
test("GET /api/categories/:slug/dumps: members only, private for the owner", async () => {
test("GET /api/dumps?category=: members only, private for the owner", async () => {
const owner = await createUser();
const cat = insertCategory({ slug: "music" });
const inCat = insertDump({ userId: owner.id, title: "in" });
@@ -126,19 +122,19 @@ test("GET /api/categories/:slug/dumps: members only, private for the owner", asy
)
.run(d.id, cat);
}
const anon = await get<PaginatedData<Dump>>("/api/categories/music/dumps");
const anon = await get<PaginatedData<Dump>>("/api/dumps?category=music");
assertEquals(anon.data.items.map((d) => d.title), [
"in",
]);
assertEquals(anon.data.items[0].categoryIds, [cat]);
assertEquals(
(await get<PaginatedData<Dump>>("/api/categories/music/dumps", {
(await get<PaginatedData<Dump>>("/api/dumps?category=music", {
auth: owner.auth,
})).data
.items.length,
2,
);
assertEquals((await get("/api/categories/nope/dumps")).status, 404);
assertEquals((await get("/api/dumps?category=nope")).status, 404);
// Deleting the category unlinks its dumps without deleting them.
const admin = await createUser({ role: "admin" });

View File

@@ -21,13 +21,7 @@ import type { Dump, DumpUrlMatch } from "../../../shared/dump.ts";
import type { PaginatedData } from "../../../shared/api.ts";
import type { Playlist } from "../../../shared/playlist.ts";
import type { PublicUser } from "../../../shared/user.ts";
import {
assertEquals,
assertExists,
assertFalse,
assertMatch,
assertNotEquals,
} from "@std/assert";
import { assertEquals, assertExists, assertFalse } from "@std/assert";
const PAGE = html(`<title>Scraped title</title>
<meta property="og:image" content="https://example.com/cover.jpg">`);
@@ -53,8 +47,9 @@ test("POST /api/dumps: a URL dump takes its title from the page", async () => {
const dump = res.data;
assertEquals(dump.kind, "url");
assertEquals(dump.title, "Scraped title");
assertMatch(dump.slug ?? "", /^scraped-title-[0-9a-f]{8}$/);
assertEquals(dump.slug, "scraped-title");
assertEquals(dump.userId, user.id);
assertEquals(dump.ownerUsername, user.username);
assertEquals(dump.isPrivate, false);
assertEquals(dump.richContent?.thumbnailUrl, "https://example.com/cover.jpg");
const row = db.prepare(`SELECT url, url_canonical FROM dumps WHERE id = ?;`)
@@ -149,7 +144,7 @@ test("POST /api/dumps: a file dump is stored and served back", async () => {
assertEquals(dump.fileSize, PNG.byteLength);
assertEquals(dump.comment, "tiny");
assertEquals(readFile(`dumps/${dump.id}`), PNG);
const file = await get(`/api/files/${dump.id}`);
const file = await get(`/api/dumps/${dump.id}/file`);
assertEquals(file.status, 200);
assertEquals(file.bytes, PNG);
});
@@ -221,11 +216,12 @@ test("POST /api/dumps: followers are notified of public dumps, not private ones"
// ── Read ─────────────────────────────────────────────────────────────────────
test("GET /api/dumps/:id works by id and by slug", async () => {
test("GET /api/dumps/:id works by id only", async () => {
const user = await createUser();
const { id, slug } = insertDump({ userId: user.id, title: "Hello" });
assertEquals((await get<Dump>(`/api/dumps/${id}`)).data.id, id);
assertEquals((await get<Dump>(`/api/dumps/${slug}`)).data.id, id);
// A slug is only unique under its owner: it is read by page path.
assertEquals((await get(`/api/dumps/${slug}`)).status, 404);
assertEquals((await get(`/api/dumps/nope`)).status, 404);
assertEquals((await get(`/api/dumps/${crypto.randomUUID()}`)).status, 404);
});
@@ -293,7 +289,7 @@ test("GET /api/dumps: newest first, paginated, private ones for the owner only",
);
});
test("GET /api/dumps/by-url: matches on the canonical key, respects privacy", async () => {
test("GET /api/dumps?url=: matches on the canonical key, respects privacy", async () => {
const owner = await createUser();
const other = await createUser();
insertDump({
@@ -308,24 +304,24 @@ test("GET /api/dumps/by-url: matches on the canonical key, respects privacy", as
isPrivate: true,
});
const q = encodeURIComponent("https://m.youtube.com/watch?v=abc&t=10");
const anon = await get<DumpUrlMatch[]>(`/api/dumps/by-url?url=${q}`);
const anon = await get<DumpUrlMatch[]>(`/api/dumps?url=${q}`);
assertEquals(anon.data.map((d) => d.title), [
"public",
]);
assertEquals(anon.data[0].username, owner.username);
const mine = await get<DumpUrlMatch[]>(`/api/dumps/by-url?url=${q}`, {
assertEquals(anon.data[0].ownerUsername, owner.username);
const mine = await get<DumpUrlMatch[]>(`/api/dumps?url=${q}`, {
auth: owner.auth,
});
assertEquals(mine.data.length, 2);
assertEquals(
(await get<DumpUrlMatch[]>(`/api/dumps/by-url?url=${q}`, {
(await get<DumpUrlMatch[]>(`/api/dumps?url=${q}`, {
auth: other.auth,
})).data
.length,
1,
);
assertEquals(
(await get<DumpUrlMatch[]>(`/api/dumps/by-url?url=garbage`)).data,
(await get<DumpUrlMatch[]>(`/api/dumps?url=garbage`)).data,
[],
);
});
@@ -365,7 +361,7 @@ test("GET /api/dumps/:id/related: links in both directions, hiding private ones"
json: {
url: "https://example.com/src",
comment:
`see https://www.x.test/t/?utm_source=feed and http://anywhere/dumps/${secret.slug} and http://gerbeur.test/dumps/self`,
`see https://www.x.test/t/?utm_source=feed and http://anywhere${secret.path}#comment-x and http://gerbeur.test/@${other.username}/dumps/scraped-title`,
},
});
const srcId = src.data.id;
@@ -416,6 +412,48 @@ test("GET /api/dumps/:id/playlists: public playlists, plus the viewer's private
// ── Update ───────────────────────────────────────────────────────────────────
test("PUT /api/dumps/:id: a slug changes when sent, the old one stays an alias, 3 a day", async () => {
const owner = await createUser();
const mod = await createUser({ role: "moderator" });
const { id } = insertDump({ userId: owner.id, title: "First" });
const other = insertDump({ userId: owner.id, title: "Taken" });
const byPath = (slug: string) =>
get<Dump>(`/api/users/@${owner.username}/dumps/${slug}`, {
auth: owner.auth,
});
const setSlug = (slug: string, auth = owner.auth) =>
put<Dump>(`/api/dumps/${id}`, { auth, json: { slug } });
assertEquals((await setSlug("Not A Slug")).status, 400);
// Another dump's slug, current or former, is refused.
assertEquals((await setSlug(other.slug)).status, 409);
assertEquals((await setSlug("second")).data.slug, "second");
// The old slug answers the dump, which carries its current one.
assertEquals((await byPath("first")).data.slug, "second");
assertEquals((await byPath("second")).data.id, id);
// Taking back its own former slug swaps them; the limit counts the aliases
// left, so a swap doesn't add to it.
assertEquals((await setSlug("first")).data.slug, "first");
assertEquals((await byPath("second")).data.slug, "first");
assertEquals((await setSlug("third")).data.slug, "third");
assertEquals((await setSlug("fourth")).data.slug, "fourth");
// A fourth alias in a day is refused, but not to a moderator.
assertEquals((await setSlug("fifth")).status, 429);
assertEquals((await setSlug("fifth", mod.auth)).data.slug, "fifth");
// Every former slug still leads to it, without chaining.
for (const slug of ["first", "second", "third", "fourth", "fifth"]) {
assertEquals((await byPath(slug)).data.slug, "fifth", slug);
}
// Deleting the dump frees its aliases.
await del(`/api/dumps/${id}`, { auth: owner.auth });
assertEquals(
count(`SELECT COUNT(*) AS n FROM dump_slug_aliases WHERE dump_id = ?;`, id),
0,
);
const reborn = insertDump({ userId: owner.id, title: "Second" });
assertEquals(reborn.slug, "second");
});
test("PUT /api/dumps/:id: owner and moderator may edit, others may not", async () => {
const owner = await createUser();
const other = await createUser();
@@ -430,14 +468,14 @@ test("PUT /api/dumps/:id: owner and moderator may edit, others may not", async (
(await put(`/api/dumps/${id}`, { json: { title: "X" } })).status,
401,
);
const res = await put<Dump>(`/api/dumps/${slug}`, {
const res = await put<Dump>(`/api/dumps/${id}`, {
auth: owner.auth,
json: { title: "New title", comment: "hello" },
});
assertEquals(res.status, 200);
assertEquals(res.data.title, "New title");
assertMatch(res.data.slug ?? "", /^new-title-/);
assertNotEquals(res.data.slug, slug);
// A new title never changes the slug by itself.
assertEquals(res.data.slug, slug);
assertExists(res.data.updatedAt);
const byMod = await put(`/api/dumps/${id}`, {
auth: mod.auth,
@@ -635,7 +673,7 @@ test("PUT /api/dumps/:id/file: visibility changes with the file, or stays", asyn
let res = await replace({ isPrivate: "true" });
assertEquals(res.data.isPrivate, true);
assertEquals(await visible(), false);
assertEquals((await get(`/api/files/${id}`)).status, 404);
assertEquals((await get(`/api/dumps/${id}/file`)).status, 404);
// Left out, it stays private.
res = await replace({});
assertEquals(res.data.isPrivate, true);
@@ -677,7 +715,7 @@ test("custom thumbnails: set, served, removed", async () => {
});
assertEquals(set.status, 200);
assertEquals(set.data.thumbnailMime, "image/png");
const thumb = await get(`/api/thumbnails/${id}`);
const thumb = await get(`/api/dumps/${id}/thumbnail`);
assertEquals(thumb.status, 200);
assertEquals(thumb.headers.get("content-type"), "image/png");
assertEquals(thumb.bytes, PNG);
@@ -688,10 +726,10 @@ test("custom thumbnails: set, served, removed", async () => {
assertEquals(removed.data.thumbnailMime, undefined);
assertEquals(readFile(`thumbnails/${id}-custom`), null);
// A URL dump without its own thumbnail has none to serve.
assertEquals((await get(`/api/thumbnails/${id}`)).status, 404);
assertEquals((await get(`/api/dumps/${id}/thumbnail`)).status, 404);
});
test("POST /api/dumps/:id/refresh-metadata: updates, or keeps what it had on failure", async () => {
test("POST /api/dumps/:id/metadata: updates, or keeps what it had on failure", async () => {
const owner = await createUser();
const { id } = insertDump({
userId: owner.id,
@@ -707,7 +745,7 @@ test("POST /api/dumps/:id/refresh-metadata: updates, or keeps what it had on fai
using _ = stubNetwork(() => {
throw new TypeError("down");
});
const res = await post<Dump>(`/api/dumps/${id}/refresh-metadata`, {
const res = await post<Dump>(`/api/dumps/${id}/metadata`, {
auth: owner.auth,
});
assertEquals(res.status, 502);
@@ -715,7 +753,7 @@ test("POST /api/dumps/:id/refresh-metadata: updates, or keeps what it had on fai
}
{
using _ = stubNetwork(() => PAGE.clone());
const res = await post<Dump>(`/api/dumps/${id}/refresh-metadata`, {
const res = await post<Dump>(`/api/dumps/${id}/metadata`, {
auth: owner.auth,
});
assertEquals(res.status, 200);
@@ -723,7 +761,7 @@ test("POST /api/dumps/:id/refresh-metadata: updates, or keeps what it had on fai
}
const file = insertDump({ userId: owner.id, fileName: "f.txt" });
assertEquals(
(await post(`/api/dumps/${file.id}/refresh-metadata`, { auth: owner.auth }))
(await post(`/api/dumps/${file.id}/metadata`, { auth: owner.auth }))
.status,
400,
);

View File

@@ -9,7 +9,7 @@ function createdAtOf(id: string): string {
}).created_at;
}
test("GET /api/files/:id: headers for a safe inline type", async () => {
test("GET /api/dumps/:id/file: headers for a safe inline type", async () => {
const user = await createUser();
const { id } = insertDump({
userId: user.id,
@@ -17,7 +17,7 @@ test("GET /api/files/:id: headers for a safe inline type", async () => {
fileMime: "text/plain",
fileData: BYTES,
});
const res = await get(`/api/files/${id}`);
const res = await get(`/api/dumps/${id}/file`);
assertEquals(res.status, 200);
assertEquals(res.bytes, BYTES);
assertEquals(res.headers.get("content-type"), "text/plain");
@@ -33,7 +33,7 @@ test("GET /api/files/:id: headers for a safe inline type", async () => {
assertStringIncludes(etag, 'W/"');
// The client already has it: a 304, no bytes.
const again = await get(`/api/files/${id}`, {
const again = await get(`/api/dumps/${id}/file`, {
headers: { "If-None-Match": etag },
});
assertEquals(again.status, 304);
@@ -42,17 +42,17 @@ test("GET /api/files/:id: headers for a safe inline type", async () => {
// The app's URL names the file's current version, which never changes.
const v = `${BYTES.byteLength}-${Date.parse(createdAtOf(id))}`;
assertEquals(
(await get(`/api/files/${id}?v=${v}`)).headers.get("cache-control"),
(await get(`/api/dumps/${id}/file?v=${v}`)).headers.get("cache-control"),
"public, max-age=31536000, immutable",
);
// A stale version is revalidated like no version at all.
assertEquals(
(await get(`/api/files/${id}?v=10-0`)).headers.get("cache-control"),
(await get(`/api/dumps/${id}/file?v=10-0`)).headers.get("cache-control"),
"public, no-cache",
);
});
test("GET /api/files/:id: active content downloads instead of rendering", async () => {
test("GET /api/dumps/:id/file: active content downloads instead of rendering", async () => {
const user = await createUser();
for (const mime of ["text/html", "image/svg+xml", "application/xml"]) {
const { id } = insertDump({
@@ -60,7 +60,7 @@ test("GET /api/files/:id: active content downloads instead of rendering", async
fileName: "x",
fileMime: mime,
});
const res = await get(`/api/files/${id}`);
const res = await get(`/api/dumps/${id}/file`);
assertStringIncludes(
res.headers.get("content-disposition")!,
"attachment;",
@@ -72,19 +72,19 @@ test("GET /api/files/:id: active content downloads instead of rendering", async
fileName: "a.pdf",
fileMime: "application/pdf",
});
const res = await get(`/api/files/${pdf.id}`);
const res = await get(`/api/dumps/${pdf.id}/file`);
assertStringIncludes(res.headers.get("content-disposition")!, "inline;");
assertEquals(res.headers.get("content-security-policy"), null);
});
test("GET /api/files/:id: a non-Latin-1 filename doesn't break the header", async () => {
test("GET /api/dumps/:id/file: a non-Latin-1 filename doesn't break the header", async () => {
const user = await createUser();
const { id } = insertDump({
userId: user.id,
fileName: 'mix "été" 🎵.mp3',
fileMime: "audio/mpeg",
});
const res = await get(`/api/files/${id}`);
const res = await get(`/api/dumps/${id}/file`);
assertEquals(res.status, 200);
assertEquals(
res.headers.get("content-disposition"),
@@ -94,7 +94,7 @@ test("GET /api/files/:id: a non-Latin-1 filename doesn't break the header", asyn
);
});
test("GET /api/files/:id: byte ranges", async () => {
test("GET /api/dumps/:id/file: byte ranges", async () => {
const user = await createUser();
const { id } = insertDump({
userId: user.id,
@@ -102,7 +102,7 @@ test("GET /api/files/:id: byte ranges", async () => {
fileData: BYTES,
});
const range = (r: string) =>
get(`/api/files/${id}`, { headers: { Range: r } });
get(`/api/dumps/${id}/file`, { headers: { Range: r } });
let res = await range("bytes=2-5");
assertEquals(res.status, 206);
@@ -156,7 +156,7 @@ test("GET /api/files/:id: byte ranges", async () => {
}
});
test("GET /api/files/:id: private files need the owner's media token", async () => {
test("GET /api/dumps/:id/file: private files need the owner's media token", async () => {
const owner = await createUser();
const other = await createUser();
const { id } = insertDump({
@@ -164,28 +164,31 @@ test("GET /api/files/:id: private files need the owner's media token", async ()
fileName: "p",
isPrivate: true,
});
assertEquals((await get(`/api/files/${id}`)).status, 404);
assertEquals((await get(`/api/dumps/${id}/file`)).status, 404);
assertEquals(
(await get(`/api/files/${id}?token=${other.mediaToken}`)).status,
(await get(`/api/dumps/${id}/file?token=${other.mediaToken}`)).status,
404,
);
assertEquals((await get(`/api/files/${id}?token=garbage`)).status, 404);
const res = await get(`/api/files/${id}?token=${owner.mediaToken}`);
assertEquals((await get(`/api/dumps/${id}/file?token=garbage`)).status, 404);
const res = await get(`/api/dumps/${id}/file?token=${owner.mediaToken}`);
assertEquals(res.status, 200);
assertEquals(res.headers.get("cache-control"), "private, no-cache");
// A legacy session token still works in the query string.
assertEquals(
(await get(`/api/files/${id}?token=${owner.token}`)).status,
(await get(`/api/dumps/${id}/file?token=${owner.token}`)).status,
200,
);
});
test("GET /api/files/:id: bad ids, URL dumps and missing bytes", async () => {
test("GET /api/dumps/:id/file: bad ids, URL dumps and missing bytes", async () => {
const user = await createUser();
assertEquals((await get(`/api/files/..%2F..%2Fetc%2Fpasswd`)).status, 400);
assertEquals(
(await get(`/api/dumps/..%2F..%2Fetc%2Fpasswd/file`)).status,
400,
);
const url = insertDump({ userId: user.id });
assertEquals((await get(`/api/files/${url.id}`)).status, 404);
assertEquals((await get(`/api/dumps/${url.id}/file`)).status, 404);
const gone = insertDump({ userId: user.id, fileName: "g" });
Deno.removeSync(`${TEST_DIR}/uploads/dumps/${gone.id}`);
assertEquals((await get(`/api/files/${gone.id}`)).status, 404);
assertEquals((await get(`/api/dumps/${gone.id}/file`)).status, 404);
});

View File

@@ -9,6 +9,7 @@ import {
insertDump,
insertPlaylist,
post,
put,
test,
} from "../helpers.ts";
import type { Dump } from "../../../shared/dump.ts";
@@ -26,35 +27,35 @@ test("following users: status, idempotence, no self-follow, one notification", a
const me = await createUser();
const them = await createUser();
assertEquals(
(await post(`/api/follows/users/${them.id}`, { auth: me.auth })).status,
(await put(`/api/me/follow/users/${them.id}`, { auth: me.auth })).status,
204,
);
assertEquals(
(await post(`/api/follows/users/${them.id}`, { auth: me.auth })).status,
(await put(`/api/me/follow/users/${them.id}`, { auth: me.auth })).status,
204,
);
assertEquals(
(await post(`/api/follows/users/${me.id}`, { auth: me.auth })).status,
(await put(`/api/me/follow/users/${me.id}`, { auth: me.auth })).status,
400,
);
assertEquals(
(await post(`/api/follows/users/${crypto.randomUUID()}`, {
(await put(`/api/me/follow/users/${crypto.randomUUID()}`, {
auth: me.auth,
})).status,
404,
);
assertEquals(
(await get<FollowStatus>("/api/follows/status", { auth: me.auth })).data,
(await get<FollowStatus>("/api/me/follow", { auth: me.auth })).data,
{ followedUserIds: [them.id], followedPlaylistIds: [] },
);
// Unfollow and follow again: still just the one notification.
await del(`/api/follows/users/${them.id}`, { auth: me.auth });
await del(`/api/me/follow/users/${them.id}`, { auth: me.auth });
assertEquals(
(await get<FollowStatus>("/api/follows/status", { auth: me.auth })).data
(await get<FollowStatus>("/api/me/follow", { auth: me.auth })).data
.followedUserIds,
[],
);
await post(`/api/follows/users/${them.id}`, { auth: me.auth });
await put(`/api/me/follow/users/${them.id}`, { auth: me.auth });
assertEquals(
count(
`SELECT COUNT(*) as n FROM notifications WHERE user_id = ? AND type = 'user_followed';`,
@@ -63,7 +64,7 @@ test("following users: status, idempotence, no self-follow, one notification", a
1,
);
const list = await get<PaginatedData<PublicUser>>(
`/api/users/${me.username}/followed-users`,
`/api/users/@${me.username}/follow/users`,
);
assertEquals(list.data.items.map((u) => u.id), [
them.id,
@@ -77,20 +78,21 @@ test("following playlists: public ones only, and not your own notification", asy
const pub = insertPlaylist({ userId: owner.id });
const priv = insertPlaylist({ userId: owner.id, isPublic: false });
assertEquals(
(await post(`/api/follows/playlists/${pub.id}`, { auth: me.auth })).status,
(await put(`/api/me/follow/playlists/${pub.id}`, { auth: me.auth })).status,
204,
);
assertEquals(
(await post(`/api/follows/playlists/${priv.id}`, { auth: me.auth })).status,
(await put(`/api/me/follow/playlists/${priv.id}`, { auth: me.auth }))
.status,
404,
);
assertEquals(
(await post(`/api/follows/playlists/${crypto.randomUUID()}`, {
(await put(`/api/me/follow/playlists/${crypto.randomUUID()}`, {
auth: me.auth,
})).status,
404,
);
await post(`/api/follows/playlists/${pub.id}`, { auth: owner.auth });
await put(`/api/me/follow/playlists/${pub.id}`, { auth: owner.auth });
assertEquals(
count(
`SELECT COUNT(*) as n FROM notifications WHERE type = 'playlist_followed';`,
@@ -99,14 +101,14 @@ test("following playlists: public ones only, and not your own notification", asy
);
assertEquals(
(await get<PaginatedData<Playlist>>(
`/api/users/${me.username}/followed-playlists`,
`/api/users/@${me.username}/follow/playlists`,
)).data
.items[0].id,
pub.id,
);
await del(`/api/follows/playlists/${pub.id}`, { auth: me.auth });
await del(`/api/me/follow/playlists/${pub.id}`, { auth: me.auth });
assertEquals(
(await get<FollowStatus>("/api/follows/status", { auth: me.auth })).data
(await get<FollowStatus>("/api/me/follow", { auth: me.auth })).data
.followedPlaylistIds,
[],
);
@@ -133,27 +135,27 @@ test("followed-users feed: public dumps of the people I follow, newest first", a
.run(tagged.id, music);
insertDump({ userId: followed.id, title: "private", isPrivate: true });
insertDump({ userId: stranger.id, title: "stranger" });
await post(`/api/follows/users/${followed.id}`, { auth: me.auth });
await put(`/api/me/follow/users/${followed.id}`, { auth: me.auth });
const feed = await get<PaginatedData<Dump>>("/api/follows/feed/users", {
const feed = await get<PaginatedData<Dump>>("/api/me/feed?from=users", {
auth: me.auth,
});
assertEquals(titles(feed), ["new", "old"]);
assertEquals(feed.data.items[0].categoryIds, [music]);
assertEquals(
titles(
await get("/api/follows/feed/users?category=music", { auth: me.auth }),
await get("/api/me/feed?from=users&category=music", { auth: me.auth }),
),
["new"],
);
// An unknown category filters everything out rather than nothing.
assertEquals(
(await get<PaginatedData<Dump>>("/api/follows/feed/users?category=nope", {
(await get<PaginatedData<Dump>>("/api/me/feed?from=users&category=nope", {
auth: me.auth,
})).data,
{ items: [], hasMore: false },
);
assertEquals((await get("/api/follows/feed/users")).status, 401);
assertEquals((await get("/api/me/feed?from=users")).status, 401);
});
test("followed-playlists feed: each dump once, public playlists only", async () => {
@@ -168,11 +170,11 @@ test("followed-playlists feed: each dump once, public playlists only", async ()
isPrivate: true,
});
for (const p of [p1, p2]) {
await post(`/api/follows/playlists/${p.id}`, { auth: me.auth });
await put(`/api/me/follow/playlists/${p.id}`, { auth: me.auth });
await post(`/api/playlists/${p.id}/dumps/${d.id}`, { auth: owner.auth });
}
await post(`/api/playlists/${p1.id}/dumps/${priv.id}`, { auth: owner.auth });
const feed = await get<PaginatedData<Dump>>("/api/follows/feed/playlists", {
const feed = await get<PaginatedData<Dump>>("/api/me/feed?from=playlists", {
auth: me.auth,
});
assertEquals(titles(feed), ["shared"]);
@@ -181,7 +183,7 @@ test("followed-playlists feed: each dump once, public playlists only", async ()
// A playlist gone private drops out of the feed.
db.prepare(`UPDATE playlists SET is_public = 0;`).run();
assertEquals(
(await get<PaginatedData<Dump>>("/api/follows/feed/playlists", {
(await get<PaginatedData<Dump>>("/api/me/feed?from=playlists", {
auth: me.auth,
})).data
.items.length,

View File

@@ -1,5 +1,18 @@
import { count, createUser, get, insertDump, post, test } from "../helpers.ts";
import type { Notification } from "../../../shared/notification.ts";
import {
count,
createUser,
db,
get,
insertDump,
post,
put,
test,
} from "../helpers.ts";
import type {
DumpCommentedData,
DumpUpvotedData,
Notification,
} from "../../../shared/notification.ts";
import type { PaginatedData } from "../../../shared/api.ts";
import { assertEquals } from "@std/assert";
@@ -8,14 +21,14 @@ test("notifications: listed newest first, marked read one or all, never someone
const other = await createUser();
const { id: dumpId } = insertDump({ userId: me.id, title: "Mine" });
// Two notifications for me, one for other.
await post(`/api/follows/users/${me.id}`, { auth: other.auth });
await put(`/api/me/follow/users/${me.id}`, { auth: other.auth });
await post(`/api/dumps/${dumpId}/comments`, {
auth: other.auth,
json: { body: "hey" },
});
await post(`/api/follows/users/${other.id}`, { auth: me.auth });
await put(`/api/me/follow/users/${other.id}`, { auth: me.auth });
const list = await get<PaginatedData<Notification>>("/api/notifications", {
const list = await get<PaginatedData<Notification>>("/api/me/notifications", {
auth: me.auth,
});
assertEquals(list.data.items.length, 2);
@@ -29,7 +42,7 @@ test("notifications: listed newest first, marked read one or all, never someone
);
assertEquals(
(await post("/api/notifications/read-all", { auth: me.auth })).status,
(await post("/api/me/notifications/read", { auth: me.auth })).status,
204,
);
assertEquals(
@@ -39,5 +52,49 @@ test("notifications: listed newest first, marked read one or all, never someone
),
0,
);
assertEquals((await get("/api/notifications")).status, 401);
assertEquals((await get("/api/me/notifications")).status, 401);
});
test("notifications: names and item paths are joined when read, so they follow renames", async () => {
const me = await createUser();
const fan = await createUser();
const { id: dumpId } = insertDump({ userId: me.id, title: "Mine" });
await post(`/api/dumps/${dumpId}/comments`, {
auth: fan.auth,
json: { body: "nice" },
});
db.prepare(`UPDATE users SET username = 'fan_renamed' WHERE id = ?;`)
.run(fan.id);
db.prepare(`UPDATE dumps SET slug = 'mine-now' WHERE id = ?;`).run(dumpId);
const [note] = (await get<PaginatedData<Notification>>(
"/api/me/notifications",
{ auth: me.auth },
)).data.items;
assertEquals(note.type, "dump_commented");
const data = note.data as DumpCommentedData;
assertEquals(data.commenterUsername, "fan_renamed");
assertEquals([data.dumpOwnerUsername, data.dumpSlug], [
me.username,
"mine-now",
]);
// Once the dump is gone, the notification has no path to it.
db.prepare(`DELETE FROM dumps WHERE id = ?;`).run(dumpId);
db.prepare(
`INSERT INTO notifications (id, user_id, type, data, created_at) VALUES (?, ?, 'dump_upvoted', ?, ?);`,
).run(
crypto.randomUUID(),
me.id,
JSON.stringify({
voterId: fan.id,
voterUsername: "x",
dumpId,
dumpTitle: "Mine",
}),
new Date().toISOString(),
);
const [upvote] = (await get<PaginatedData<Notification>>(
"/api/me/notifications",
{ auth: me.auth },
)).data.items;
assertEquals((upvote.data as DumpUpvotedData).dumpSlug, undefined);
});

View File

@@ -26,7 +26,7 @@ function ids(res: ApiResponse<PlaylistWithDumps>): string[] {
return res.data.dumps.map((d) => d.id);
}
test("POST /api/playlists creates; GET finds it by id or slug", async () => {
test("POST /api/playlists creates; GET finds it by id, or by path under its owner", async () => {
const user = await createUser();
const res = await post<Playlist>("/api/playlists", {
auth: user.auth,
@@ -34,12 +34,16 @@ test("POST /api/playlists creates; GET finds it by id or slug", async () => {
});
assertEquals(res.status, 201);
const { id, slug } = res.data;
assertMatch(slug ?? "", /^road-trip-/);
assertEquals(slug, "road-trip");
assertEquals(res.data.ownerUsername, user.username);
assertEquals(
(await get<PlaylistWithDumps>(`/api/playlists/${id}`)).data.title,
"Road Trip",
);
const bySlug = await get<PlaylistWithDumps>(`/api/playlists/${slug}`);
assertEquals((await get(`/api/playlists/${slug}`)).status, 404);
const bySlug = await get<PlaylistWithDumps>(
`/api/users/@${user.username}/playlists/${slug}`,
);
assertEquals(bySlug.data.id, id);
assertEquals(bySlug.data.ownerUsername, user.username);
assertEquals(bySlug.data.dumps, []);
@@ -69,7 +73,7 @@ test("private playlists are the owner's alone", async () => {
200,
);
insertPlaylist({ userId: owner.id });
const path = `/api/users/${owner.username}/playlists`;
const path = `/api/users/@${owner.username}/playlists`;
assertEquals((await get<PaginatedData<Playlist>>(path)).data.items.length, 1);
assertEquals(
(await get<PaginatedData<Playlist>>(path, { auth: owner.auth })).data.items
@@ -220,8 +224,28 @@ test("removing a dump; updating; deleting", async () => {
json: { title: "New", description: "d", isPublic: false },
});
assertEquals(updated.data.title, "New");
assertMatch(updated.data.slug ?? "", /^new-/);
// A new title never changes the slug by itself; a slug sent does.
assertEquals(updated.data.slug, "old");
assertEquals(updated.data.isPublic, false);
const reslugged = await put<Playlist>(`/api/playlists/${id}`, {
auth: owner.auth,
json: { slug: "new" },
});
assertEquals(reslugged.data.slug, "new");
assertEquals(
(await get<PlaylistWithDumps>(
`/api/users/@${owner.username}/playlists/old`,
{ auth: owner.auth },
)).data.slug,
"new",
);
assertEquals(
(await put(`/api/playlists/${id}`, {
auth: owner.auth,
json: { slug: "Bad slug" },
})).status,
400,
);
const cleared = await put<Playlist>(`/api/playlists/${id}`, {
auth: owner.auth,
json: { description: null },
@@ -253,7 +277,7 @@ test("memberships: which of my playlists hold this dump", async () => {
const d = insertDump({ userId: owner.id });
await post(`/api/playlists/${p1.id}/dumps/${d.id}`, { auth: owner.auth });
const res = await get<PlaylistMembership[]>(
`/api/playlists/by-dump/${d.id}/memberships`,
`/api/me/playlists?contains=${d.id}`,
{
auth: owner.auth,
},
@@ -273,7 +297,7 @@ test("adding to a followed public playlist notifies followers, private dumps exc
const owner = await createUser();
const follower = await createUser();
const { id } = insertPlaylist({ userId: owner.id, title: "Mix" });
await post(`/api/follows/playlists/${id}`, { auth: follower.auth });
await put(`/api/me/follow/playlists/${id}`, { auth: follower.auth });
db.exec(`DELETE FROM notifications;`); // the follow notified the owner
const priv = insertDump({ userId: owner.id, isPrivate: true });
await post(`/api/playlists/${id}/dumps/${priv.id}`, { auth: owner.auth });
@@ -296,20 +320,20 @@ test("adding to a followed public playlist notifies followers, private dumps exc
});
});
test("playlist images: upload and serve", async () => {
test("playlist covers: upload and serve", async () => {
const owner = await createUser();
const other = await createUser();
const { id, slug } = insertPlaylist({ userId: owner.id });
assertEquals((await get(`/api/playlists/${id}/image`)).status, 404);
const { id } = insertPlaylist({ userId: owner.id });
assertEquals((await get(`/api/playlists/${id}/cover`)).status, 404);
assertEquals(
(await post(`/api/playlists/${id}/image`, {
(await put(`/api/playlists/${id}/cover`, {
auth: other.auth,
form: formWithFile(PNG),
}))
.status,
403,
);
const res = await post<Playlist>(`/api/playlists/${slug}/image`, {
const res = await put<Playlist>(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(PNG),
});
@@ -317,37 +341,37 @@ test("playlist images: upload and serve", async () => {
assertEquals(res.data.imageMime, "image/png");
// A new cover counts as an edit, so image URLs versioned on it change.
assert(res.data.updatedAt);
const served = await get(`/api/playlists/${slug}/image`);
const served = await get(`/api/playlists/${id}/cover`);
assertEquals(served.status, 200);
assertEquals(served.bytes, PNG);
});
test("playlist images: a private playlist's cover only for its owner's media token", async () => {
test("playlist covers: a private playlist's cover only for its owner's media token", async () => {
const owner = await createUser();
const other = await createUser();
const { id } = insertPlaylist({ userId: owner.id, isPublic: false });
await post(`/api/playlists/${id}/image`, {
await put(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(PNG),
});
assertEquals((await get(`/api/playlists/${id}/image`)).status, 404);
assertEquals((await get(`/api/playlists/${id}/cover`)).status, 404);
assertEquals(
(await get(`/api/playlists/${id}/image?token=${other.mediaToken}`)).status,
(await get(`/api/playlists/${id}/cover?token=${other.mediaToken}`)).status,
404,
);
assertEquals(
(await get(`/api/playlists/${id}/image?token=garbage`)).status,
(await get(`/api/playlists/${id}/cover?token=garbage`)).status,
404,
);
const served = await get(
`/api/playlists/${id}/image?token=${owner.mediaToken}`,
`/api/playlists/${id}/cover?token=${owner.mediaToken}`,
);
assertEquals(served.status, 200);
assertEquals(served.bytes, PNG);
assertMatch(served.headers.get("cache-control") ?? "", /^private/);
});
test("playlist images: a failed write leaves the row and the old cover alone", async () => {
test("playlist covers: a failed write leaves the row and the old cover alone", async () => {
const owner = await createUser();
const { id } = insertPlaylist({ userId: owner.id });
const dir = `${TEST_DIR}/uploads/playlist-images`;
@@ -359,27 +383,27 @@ test("playlist images: a failed write leaves the row and the old cover alone", a
// the playlist mustn't claim a cover it hasn't got.
await Deno.mkdir(`${dir}/${id}/blocker`, { recursive: true });
try {
const failed = await post(`/api/playlists/${id}/image`, {
const failed = await put(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(PNG),
});
assertEquals(failed.status, 500);
assertEquals(row(), { image_mime: null, updated_at: null });
assertEquals((await get(`/api/playlists/${id}/image`)).status, 404);
assertEquals((await get(`/api/playlists/${id}/cover`)).status, 404);
} finally {
await Deno.remove(`${dir}/${id}`, { recursive: true });
}
// With a cover in place, a failed replacement keeps serving the old one
// under the old version, and leaves no stray temporary file behind.
await post(`/api/playlists/${id}/image`, {
await put(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(PNG),
});
const before = row();
await Deno.chmod(dir, 0o555);
try {
const failed = await post(`/api/playlists/${id}/image`, {
const failed = await put(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(new Uint8Array([...PNG, 0])),
});
@@ -388,28 +412,28 @@ test("playlist images: a failed write leaves the row and the old cover alone", a
await Deno.chmod(dir, 0o755);
}
assertEquals(row(), before);
assertEquals((await get(`/api/playlists/${id}/image`)).bytes, PNG);
assertEquals((await get(`/api/playlists/${id}/cover`)).bytes, PNG);
const left = [...Deno.readDirSync(dir)]
.map((e) => e.name)
.filter((name) => name.startsWith(id));
assertEquals(left, [id]);
});
test("playlist images: a replaced cover is served under the new version", async () => {
test("playlist covers: a replaced cover is served under the new version", async () => {
const owner = await createUser();
const { id } = insertPlaylist({ userId: owner.id });
const first = await post<Playlist>(`/api/playlists/${id}/image`, {
const first = await put<Playlist>(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(PNG),
});
await new Promise((r) => setTimeout(r, 5)); // a distinct updated_at
const other = new Uint8Array([...PNG, 1, 2, 3]);
const second = await post<Playlist>(`/api/playlists/${id}/image`, {
const second = await put<Playlist>(`/api/playlists/${id}/cover`, {
auth: owner.auth,
form: formWithFile(other),
});
assert(second.data.updatedAt !== first.data.updatedAt);
assertEquals((await get(`/api/playlists/${id}/image`)).bytes, other);
assertEquals((await get(`/api/playlists/${id}/cover`)).bytes, other);
});
test("reorder: someone else's dump that went private keeps its slot", async () => {

View File

@@ -1,46 +0,0 @@
import { get, PNG, stubNetwork } from "../helpers.ts";
import { assertEquals } from "@std/assert";
Deno.test("GET /api/proxy-image: rasters only, fetched once for everyone", async () => {
using net = stubNetwork((url) =>
url.pathname.endsWith(".svg")
? new Response("<svg/>", { headers: { "content-type": "image/svg+xml" } })
: new Response(PNG, { headers: { "content-type": "image/png" } })
);
const path = `/api/proxy-image?url=${
encodeURIComponent("https://cdn.example.com/a.png")
}`;
const first = await get(path);
assertEquals(first.status, 200);
assertEquals(first.headers.get("content-type"), "image/png");
assertEquals(first.bytes, PNG);
const second = await get(path);
assertEquals(second.bytes, PNG);
assertEquals(net.calls.length, 1);
const svg = await get(
`/api/proxy-image?url=${
encodeURIComponent("https://cdn.example.com/a.svg")
}`,
);
assertEquals(svg.status, 400);
});
Deno.test("GET /api/proxy-image: an error answer is never served nor cached", async () => {
let failing = true;
using net = stubNetwork(() =>
failing
? new Response(PNG, {
status: 503,
headers: { "content-type": "image/png" },
})
: new Response(PNG, { headers: { "content-type": "image/png" } })
);
const path = `/api/proxy-image?url=${
encodeURIComponent("https://cdn.example.com/flaky.png")
}`;
assertEquals((await get(path)).status, 400);
failing = false;
assertEquals((await get(path)).status, 200);
assertEquals(net.calls.length, 2);
});

View File

@@ -0,0 +1,199 @@
import { get, html, PNG, stubNetwork } from "../helpers.ts";
import { assertEquals, assertFalse } from "@std/assert";
import type { Tralbum, YouTubePlaylist } from "../../../shared/player.ts";
// ── Images ───────────────────────────────────────────────────────────────────
Deno.test("GET /api/remote/image: rasters only, fetched once for everyone", async () => {
using net = stubNetwork((url) =>
url.pathname.endsWith(".svg")
? new Response("<svg/>", { headers: { "content-type": "image/svg+xml" } })
: new Response(PNG, { headers: { "content-type": "image/png" } })
);
const path = `/api/remote/image?url=${
encodeURIComponent("https://cdn.example.com/a.png")
}`;
const first = await get(path);
assertEquals(first.status, 200);
assertEquals(first.headers.get("content-type"), "image/png");
assertEquals(first.bytes, PNG);
const second = await get(path);
assertEquals(second.bytes, PNG);
assertEquals(net.calls.length, 1);
const svg = await get(
`/api/remote/image?url=${
encodeURIComponent("https://cdn.example.com/a.svg")
}`,
);
assertEquals(svg.status, 400);
});
Deno.test("GET /api/remote/image: an error answer is never served nor cached", async () => {
let failing = true;
using net = stubNetwork(() =>
failing
? new Response(PNG, {
status: 503,
headers: { "content-type": "image/png" },
})
: new Response(PNG, { headers: { "content-type": "image/png" } })
);
const path = `/api/remote/image?url=${
encodeURIComponent("https://cdn.example.com/flaky.png")
}`;
assertEquals((await get(path)).status, 400);
failing = false;
assertEquals((await get(path)).status, 200);
assertEquals(net.calls.length, 2);
});
// ── Bandcamp ─────────────────────────────────────────────────────────────────
function escapeAttr(s: string): string {
return s.replaceAll("&", "&amp;").replaceAll('"', "&quot;");
}
function tralbumPage(data: unknown): string {
return `<div id="player" data-tralbum="${
escapeAttr(JSON.stringify(data))
}"></div>`;
}
const STREAM = "https://t4.bcbits.com/stream/abc/mp3-128/1?p=0&ts=1&t=x";
const ALBUM = {
item_type: "album",
artist: "Artist",
art_id: 12345,
current: { title: 'The "Album" &amp; more' },
trackinfo: [
{
track_num: 1,
title: "One",
duration: 180.5,
streaming: 1,
file: { "mp3-128": STREAM },
},
{
track_num: 2,
title: "Preorder",
streaming: 1,
unreleased_track: true,
file: null,
},
{
track_num: 3,
title: "",
streaming: 1,
file: { "mp3-128": "https://evil.test/x.mp3" },
},
{
track_num: 4,
title: "Capped",
streaming: 1,
is_capped: true,
file: { "mp3-128": STREAM },
},
],
};
Deno.test("GET /api/remote/bandcamp: resolves, caches, and forces a refetch", async () => {
using net = stubNetwork(() => html(tralbumPage(ALBUM)));
const url = "https://cached.bandcamp.com/album/x";
const res = await get<Tralbum>(
`/api/remote/bandcamp?url=${encodeURIComponent(url)}`,
);
assertEquals(res.status, 200);
assertEquals(res.headers.get("cache-control"), "private, max-age=3600");
assertEquals(res.data.tracks.length, 4);
// Same page (different query/case/trailing slash) → cache hit.
await get(
`/api/remote/bandcamp?url=${
encodeURIComponent("https://CACHED.bandcamp.com/album/x/?from=y")
}`,
);
assertEquals(net.calls.length, 1);
await get(`/api/remote/bandcamp?url=${encodeURIComponent(url)}&force=1`);
assertEquals(net.calls.length, 2);
});
Deno.test("GET /api/remote/bandcamp: refusals and upstream failures", async () => {
using _ = stubNetwork((url) => {
if (url.hostname.startsWith("down")) {
return new Response("", { status: 503 });
}
if (url.hostname.startsWith("json")) return Response.json({});
return html("<html>no tralbum</html>");
});
const status = async (url: string) =>
(await get(`/api/remote/bandcamp?url=${encodeURIComponent(url)}`)).status;
assertEquals(await status("https://example.com/album/x"), 400);
assertEquals(await status("https://bandcamp.com.evil.test/album/x"), 400);
assertEquals(await status("http://localhost/album/x"), 400);
assertEquals(await status("https://down.bandcamp.com/album/x"), 502);
assertEquals(await status("https://json.bandcamp.com/album/x"), 502);
assertEquals(await status("https://empty.bandcamp.com/album/x"), 404);
});
// ── YouTube ──────────────────────────────────────────────────────────────────
function ytPage(data: unknown): string {
return `<script>var ytInitialData = ${JSON.stringify(data)};</script>`;
}
const YT_DATA = {
metadata: { playlistMetadataRenderer: { title: "My mix" } },
contents: {
list: [
{
lockupViewModel: {
contentType: "LOCKUP_CONTENT_TYPE_VIDEO",
contentId: "vid1",
metadata: {
lockupMetadataViewModel: { title: { content: "First" } },
},
contentImage: {
overlays: [{ thumbnailBadgeViewModel: { text: "1:02:03" } }],
},
},
},
{
lockupViewModel: {
contentType: "LOCKUP_CONTENT_TYPE_PLAYLIST",
contentId: "ignored",
},
},
{
playlistVideoRenderer: {
videoId: "vid2",
title: { runs: [{ text: "Second" }] },
lengthSeconds: "235",
},
},
],
},
};
Deno.test("GET /api/remote/youtube: resolves and validates the id", async () => {
let cookie: string | null = null;
using net = stubNetwork((url, init) => {
cookie = new Headers(init?.headers).get("cookie");
return url.searchParams.get("list") === "PLgone"
? new Response("", { status: 404 })
: html(ytPage(YT_DATA));
});
const ok = await get<YouTubePlaylist>("/api/remote/youtube?list=PLgood");
assertEquals(ok.status, 200);
assertEquals(ok.data.tracks.length, 2);
assertEquals(ok.headers.get("cache-control"), "public, max-age=3600");
// The pre-answered consent cookie keeps EU requests off the consent page.
assertEquals(cookie, "SOCS=CAI");
await get("/api/remote/youtube?list=PLgood"); // cached
assertEquals(net.calls.length, 1);
assertEquals((await get("/api/remote/youtube?list=bad%20id")).status, 400);
assertEquals((await get("/api/remote/youtube")).status, 400);
assertEquals((await get("/api/remote/youtube?list=PLgone")).status, 502);
assertFalse(net.calls.some((u) => u.searchParams.get("list") === "bad id"));
});

View File

@@ -37,7 +37,7 @@ function readDir(path: string): string[] {
}
}
test("GET /api/thumbnails/:id: serves a cached video still, with privacy", async () => {
test("GET /api/dumps/:id/thumbnail: serves a cached video still, with privacy", async () => {
const owner = await createUser();
const video = insertDump({
userId: owner.id,
@@ -54,20 +54,21 @@ test("GET /api/thumbnails/:id: serves a cached video still, with privacy", async
for (const { id } of [video, priv]) {
Deno.writeFileSync(`${TEST_DIR}/uploads/thumbnails/${id}.jpg`, PNG);
}
const res = await get(`/api/thumbnails/${video.id}`);
const res = await get(`/api/dumps/${video.id}/thumbnail`);
assertEquals(res.status, 200);
assertEquals(res.headers.get("content-type"), "image/jpeg");
assertEquals(res.headers.get("cache-control"), "public, no-cache");
const v = (id: string) => `5-${Date.parse(createdAtOf(id))}`;
assertEquals(
(await get(`/api/thumbnails/${video.id}?v=${v(video.id)}`)).headers.get(
"cache-control",
),
(await get(`/api/dumps/${video.id}/thumbnail?v=${v(video.id)}`)).headers
.get(
"cache-control",
),
"public, max-age=31536000, immutable",
);
assertEquals((await get(`/api/thumbnails/${priv.id}`)).status, 404);
assertEquals((await get(`/api/dumps/${priv.id}/thumbnail`)).status, 404);
const own = await get(
`/api/thumbnails/${priv.id}?v=${v(priv.id)}&token=${owner.mediaToken}`,
`/api/dumps/${priv.id}/thumbnail?v=${v(priv.id)}&token=${owner.mediaToken}`,
);
assertEquals(own.status, 200);
assertEquals(
@@ -76,11 +77,11 @@ test("GET /api/thumbnails/:id: serves a cached video still, with privacy", async
);
const text = insertDump({ userId: owner.id, fileName: "t.txt" });
assertEquals((await get(`/api/thumbnails/${text.id}`)).status, 404);
assertEquals((await get(`/api/thumbnails/nope`)).status, 400);
assertEquals((await get(`/api/dumps/${text.id}/thumbnail`)).status, 404);
assertEquals((await get(`/api/dumps/nope/thumbnail`)).status, 400);
});
test("GET /api/thumbnails/:id: an image dump gets a preview, a GIF itself", async () => {
test("GET /api/dumps/:id/thumbnail: an image dump gets a preview, a GIF itself", async () => {
const owner = await createUser();
const gif = new TextEncoder().encode("GIF89a-not-really");
const animated = insertDump({
@@ -89,7 +90,7 @@ test("GET /api/thumbnails/:id: an image dump gets a preview, a GIF itself", asyn
fileMime: "image/gif",
fileData: gif,
});
const res = await get(`/api/thumbnails/${animated.id}`);
const res = await get(`/api/dumps/${animated.id}/thumbnail`);
assertEquals(res.status, 200);
assertEquals(res.headers.get("content-type"), "image/gif");
assertEquals(res.bytes, gif);
@@ -101,7 +102,7 @@ test("GET /api/thumbnails/:id: an image dump gets a preview, a GIF itself", asyn
fileMime: "image/png",
fileData: PNG,
});
const preview = await get(`/api/thumbnails/${photo.id}`);
const preview = await get(`/api/dumps/${photo.id}/thumbnail`);
assertEquals(preview.status, 200);
assertEquals(preview.headers.get("content-type"), "image/png");
if (await hasFfmpeg()) {
@@ -120,7 +121,7 @@ test("GET /api/thumbnails/:id: an image dump gets a preview, a GIF itself", asyn
fileMime: "image/png",
fileData: BYTES,
});
const fallback = await get(`/api/thumbnails/${broken.id}`);
const fallback = await get(`/api/dumps/${broken.id}/thumbnail`);
assertEquals(fallback.status, 200);
assertEquals(fallback.headers.get("content-type"), "image/png");
assertEquals(fallback.bytes, BYTES);

View File

@@ -6,10 +6,13 @@ import {
del,
get,
insertDump,
insertPlaylist,
PASSWORD,
patch,
post,
put,
test,
uniqueName,
} from "../helpers.ts";
import type {
AuthResponse,
@@ -28,6 +31,7 @@ import {
} from "../../lib/jwt.ts";
import { authenticateMedia } from "../../lib/auth.ts";
import type { Dump } from "../../../shared/dump.ts";
import type { Playlist } from "../../../shared/playlist.ts";
import type { PaginatedData } from "../../../shared/api.ts";
import {
DEFAULT_SETTINGS,
@@ -42,10 +46,14 @@ function invite(inviterId: string, createdAt = new Date()): string {
return token;
}
test("public profile: by username or id, without private fields", async () => {
test("public profile: by @name in any case or id, without private fields", async () => {
const user = await createUser();
for (
const path of [`/api/users/${user.username}`, `/api/users/by-id/${user.id}`]
const path of [
`/api/users/@${user.username}`,
`/api/users/@${user.username.toUpperCase()}`,
`/api/users/${user.id}`,
]
) {
const res = await get<PublicUser>(path);
assertEquals(res.status, 200, path);
@@ -53,53 +61,55 @@ test("public profile: by username or id, without private fields", async () => {
assertFalse("email" in res.data);
assertFalse("passwordHash" in res.data);
}
assertEquals((await get(`/api/users/no_one_here`)).status, 404);
const me = await get<SelfUser>("/api/users/me", { auth: user.auth });
assertEquals((await get(`/api/users/@no_one_here`)).status, 404);
// Without the `@`, the key is an id.
assertEquals((await get(`/api/users/${user.username}`)).status, 404);
const me = await get<SelfUser>("/api/me", { auth: user.auth });
assertEquals(me.data.email, user.email);
assertFalse("passwordHash" in me.data);
});
test("PATCH /api/users/me: description and email only", async () => {
test("PATCH /api/me: description, email and username only", async () => {
const user = await createUser();
const taken = await createUser();
const res = await patch<PublicUser>("/api/users/me", {
const res = await patch<SelfUser>("/api/me", {
auth: user.auth,
json: { description: "about me", email: "new@example.test" },
});
assertEquals(res.status, 200);
assertEquals(res.data.description, "about me");
assertFalse("email" in res.data);
assertEquals(
(await get<SelfUser>("/api/users/me", { auth: user.auth })).data.email,
"new@example.test",
);
// A role, username or password in the body is ignored, not applied.
await patch("/api/users/me", {
assertEquals(res.data.email, "new@example.test");
assertFalse("passwordHash" in res.data);
// A role or password in the body is ignored, not applied.
const hash = () =>
(db.prepare(`SELECT password_hash FROM users WHERE id = ?;`).get(
user.id,
) as { password_hash: string }).password_hash;
const before = hash();
await patch("/api/me", {
auth: user.auth,
json: { role: "admin", username: "hijack", password: "whatever-long" },
json: { role: "admin", password: "whatever-long" },
});
const row = db.prepare(`SELECT role, username FROM users WHERE id = ?;`).get(
const row = db.prepare(`SELECT role FROM users WHERE id = ?;`).get(
user.id,
) as {
role: string;
username: string;
};
assertEquals(row, { role: "user", username: user.username });
) as { role: string };
assertEquals(row.role, "user");
assertEquals(hash(), before);
assertEquals(
(await patch("/api/users/me", {
(await patch("/api/me", {
auth: user.auth,
json: { email: taken.email },
})).status,
409,
);
assertEquals(
(await patch("/api/users/me", { auth: user.auth, json: { email: "bad" } }))
(await patch("/api/me", { auth: user.auth, json: { email: "bad" } }))
.status,
400,
);
assertEquals(
(await patch("/api/users/me", {
(await patch("/api/me", {
auth: user.auth,
json: { description: "x".repeat(2001) },
})).status,
@@ -107,7 +117,7 @@ test("PATCH /api/users/me: description and email only", async () => {
);
});
test("PATCH /api/users/:id/role: admins only, never their own", async () => {
test("PATCH /api/users/:key/role: admins only, never their own", async () => {
const admin = await createUser({ role: "admin" });
const mod = await createUser({ role: "moderator" });
const user = await createUser();
@@ -157,28 +167,28 @@ test("PATCH /api/users/:id/role: admins only, never their own", async () => {
);
});
test("GET /api/users/search: prefix match for mentions, capped at 8", async () => {
test("GET /api/users?q=: prefix match for mentions, capped at 8", async () => {
for (let i = 0; i < 10; i++) await createUser({ username: `zed_${i}` });
await createUser({ username: "other_zed" });
const res = await get<UserSuggestion[]>("/api/users/search?q=zed");
const res = await get<UserSuggestion[]>("/api/users?q=zed");
assertEquals(res.data.length, 8);
assertEquals(res.data[0], {
id: res.data[0].id,
username: "zed_0",
avatarMime: null,
});
assertEquals((await get<UserSuggestion[]>("/api/users/search?q=")).data, []);
assertEquals((await get<UserSuggestion[]>("/api/users?q=")).data, []);
// An underscore is a letter of the name, not a wildcard.
await createUser({ username: "zedx9" });
assertEquals(
(await get<UserSuggestion[]>("/api/users/search?q=zed_9")).data.map((u) =>
(await get<UserSuggestion[]>("/api/users?q=zed_9")).data.map((u) =>
u.username
),
["zed_9"],
);
});
test("GET /api/users/:username/invitees: the invite tree below a user", async () => {
test("GET /api/users/:key/invitees: the invite tree below a user", async () => {
const root = await createUser();
const child = await createUser({
invitedBy: root.id,
@@ -189,18 +199,18 @@ test("GET /api/users/:username/invitees: the invite tree below a user", async ()
createdAt: "2024-01-02T00:00:00Z",
});
const tree =
(await get<Invitee[]>(`/api/users/${root.username}/invitees`)).data;
(await get<Invitee[]>(`/api/users/@${root.username}/invitees`)).data;
assertEquals(
tree.map((
n: { username: string; invitedById: string },
) => [n.username, n.invitedById]),
[[child.username, root.id], [grandchild.username, child.id]],
);
const profile = await get<PublicUser>(`/api/users/${child.username}`);
const profile = await get<PublicUser>(`/api/users/@${child.username}`);
assertEquals(profile.data.invitedByUsername, root.username);
});
test("GET /api/users/:username/dumps and /votes respect privacy", async () => {
test("GET /api/users/:key/dumps and /upvoted respect privacy", async () => {
const owner = await createUser();
const other = await createUser();
const pub = insertDump({ userId: owner.id, title: "pub" });
@@ -211,8 +221,8 @@ test("GET /api/users/:username/dumps and /votes respect privacy", async () => {
)
.run(d.id, owner.id, new Date().toISOString());
}
for (const sub of ["dumps", "votes"]) {
const path = `/api/users/${owner.username}/${sub}`;
for (const sub of ["dumps", "upvoted"]) {
const path = `/api/users/@${owner.username}/${sub}`;
const total = async (opts?: { auth: { Authorization: string } }) =>
(await get<PaginatedData<Dump>>(path, opts)).data.items.length;
assertEquals(await total(), 1, sub);
@@ -223,14 +233,14 @@ test("GET /api/users/:username/dumps and /votes respect privacy", async () => {
sub,
);
}
assert((await get(`/api/users/nobody_at_all/dumps`)).status === 404);
assert((await get(`/api/users/@nobody_at_all/dumps`)).status === 404);
});
// ── Login and register ───────────────────────────────────────────────────────
test("POST /api/users/login: right password logs in, wrong one doesn't say which", async () => {
test("POST /api/sessions: right password logs in, wrong one doesn't say which", async () => {
const user = await createUser();
const ok = await post<AuthResponse>("/api/users/login", {
const ok = await post<AuthResponse>("/api/sessions", {
json: { username: user.username, password: PASSWORD },
});
assertEquals(ok.status, 200);
@@ -242,10 +252,10 @@ test("POST /api/users/login: right password logs in, wrong one doesn't say which
user.id,
);
const wrong = await post("/api/users/login", {
const wrong = await post("/api/sessions", {
json: { username: user.username, password: "nope" },
});
const unknown = await post("/api/users/login", {
const unknown = await post("/api/sessions", {
json: { username: "no_such_user_here", password: "nope" },
});
assertEquals(wrong.status, 401);
@@ -253,19 +263,19 @@ test("POST /api/users/login: right password logs in, wrong one doesn't say which
assertEquals(wrong.error.message, unknown.error.message);
assertEquals(
(await post("/api/users/login", { json: { username: user.username } }))
(await post("/api/sessions", { json: { username: user.username } }))
.status,
400,
);
});
test("POST /api/users/login: rate limited per account, case-insensitively", async () => {
test("POST /api/sessions: rate limited per account, case-insensitively", async () => {
const user = await createUser();
const statuses: number[] = [];
for (let i = 0; i < 11; i++) {
const username = i % 2 ? user.username.toUpperCase() : user.username;
statuses.push(
(await post("/api/users/login", {
(await post("/api/sessions", {
json: { username, password: "wrong" },
})).status,
);
@@ -274,18 +284,18 @@ test("POST /api/users/login: rate limited per account, case-insensitively", asyn
assertEquals(statuses[10], 429);
// Even the right password is held back now.
assertEquals(
(await post("/api/users/login", {
(await post("/api/sessions", {
json: { username: user.username, password: PASSWORD },
})).status,
429,
);
});
test("POST /api/users/register: an invite opens one account", async () => {
test("POST /api/users: an invite opens one account", async () => {
using mail = captureEmails();
const inviter = await createUser();
const inviteToken = invite(inviter.id);
const res = await post<AuthResponse>("/api/users/register", {
const res = await post<AuthResponse>("/api/users", {
json: {
username: "newbie_reg",
password: "longenough",
@@ -306,7 +316,7 @@ test("POST /api/users/register: an invite opens one account", async () => {
assertEquals(mail.sent.map((m) => m.to), ["newbie@example.test"]);
assert(mail.sent[0].html.includes("newbie_reg"));
const again = await post("/api/users/register", {
const again = await post("/api/users", {
json: {
username: "second_reg",
password: "longenough",
@@ -317,7 +327,7 @@ test("POST /api/users/register: an invite opens one account", async () => {
assertEquals(again.status, 409);
});
test("POST /api/users/register: validation and unknown invites", async () => {
test("POST /api/users: validation and unknown invites", async () => {
const inviter = await createUser();
const inviteToken = invite(inviter.id);
const base = {
@@ -335,11 +345,11 @@ test("POST /api/users/register: validation and unknown invites", async () => {
[{ ...base, inviteToken: 42 }, /Invalid request/],
];
for (const [json, message] of cases) {
const res = await post("/api/users/register", { json });
const res = await post("/api/users", { json });
assertEquals(res.status, 400, JSON.stringify(json));
assert(message.test(res.error.message), res.error.message);
}
const unknown = await post("/api/users/register", {
const unknown = await post("/api/users", {
json: { ...base, inviteToken: "made-up" },
});
assertEquals(unknown.status, 404);
@@ -350,11 +360,11 @@ test("POST /api/users/register: validation and unknown invites", async () => {
);
});
test("POST /api/users/register: a taken name or email hands the invite back", async () => {
test("POST /api/users: a taken name or email hands the invite back", async () => {
const inviter = await createUser();
const taken = await createUser();
const inviteToken = invite(inviter.id);
const byName = await post("/api/users/register", {
const byName = await post("/api/users", {
json: {
username: taken.username.toUpperCase(),
password: "longenough",
@@ -363,7 +373,7 @@ test("POST /api/users/register: a taken name or email hands the invite back", as
},
});
assertEquals(byName.status, 409);
const byEmail = await post("/api/users/register", {
const byEmail = await post("/api/users", {
json: {
username: "fresh_name",
password: "longenough",
@@ -381,13 +391,13 @@ test("POST /api/users/register: a taken name or email hands the invite back", as
);
});
test("POST /api/users/register: an invite older than 7 days is refused", async () => {
test("POST /api/users: an invite older than 7 days is refused", async () => {
const inviter = await createUser();
const inviteToken = invite(
inviter.id,
new Date(Date.now() - 8 * 24 * 60 * 60 * 1000),
);
const res = await post("/api/users/register", {
const res = await post("/api/users", {
json: {
username: "late_comer",
password: "longenough",
@@ -398,12 +408,12 @@ test("POST /api/users/register: an invite older than 7 days is refused", async (
assertEquals(res.status, 404);
});
test("POST /api/users/register: parallel registrations can't share an invite", async () => {
test("POST /api/users: parallel registrations can't share an invite", async () => {
const inviter = await createUser();
const inviteToken = invite(inviter.id);
const results = await Promise.all(
[1, 2, 3].map((i) =>
post("/api/users/register", {
post("/api/users", {
json: {
username: `racer_${i}`,
password: "longenough",
@@ -424,12 +434,12 @@ test("POST /api/users/register: parallel registrations can't share an invite", a
test("change-password: needs the current one, revokes old tokens, returns new ones", async () => {
const user = await createUser();
const wrong = await post("/api/users/me/change-password", {
const wrong = await put("/api/me/password", {
auth: user.auth,
json: { currentPassword: "nope", newPassword: "brand-new-pass" },
});
assertEquals(wrong.status, 403);
const short = await post("/api/users/me/change-password", {
const short = await put("/api/me/password", {
auth: user.auth,
json: { currentPassword: PASSWORD, newPassword: "short" },
});
@@ -438,18 +448,18 @@ test("change-password: needs the current one, revokes old tokens, returns new on
// iat has one-second resolution: make sure the old token is from an earlier
// second than the change.
await new Promise((r) => setTimeout(r, 1100));
const ok = await post<AuthTokens>("/api/users/me/change-password", {
const ok = await put<AuthTokens>("/api/me/password", {
auth: user.auth,
json: { currentPassword: PASSWORD, newPassword: "brand-new-pass" },
});
assertEquals(ok.status, 200);
assertEquals((await get("/api/users/me", { auth: user.auth })).status, 401);
assertEquals((await get("/api/me", { auth: user.auth })).status, 401);
assertEquals(await authenticateMedia(user.mediaToken), null);
const fresh = { Authorization: `Bearer ${ok.data.token}` };
assertEquals((await get("/api/users/me", { auth: fresh })).status, 200);
assertEquals((await get("/api/me", { auth: fresh })).status, 200);
assertEquals(await authenticateMedia(ok.data.mediaToken), user.id);
const login = await post("/api/users/login", {
const login = await post("/api/sessions", {
json: { username: user.username, password: "brand-new-pass" },
});
assertEquals(login.status, 200);
@@ -458,7 +468,7 @@ test("change-password: needs the current one, revokes old tokens, returns new on
test("request-password-reset: always 200, stores nothing without SMTP", async () => {
const user = await createUser();
for (const email of [user.email, "nobody@example.test", "", undefined]) {
const res = await post("/api/users/request-password-reset", {
const res = await post("/api/password-resets", {
json: { email },
});
assertEquals(res.status, 200);
@@ -469,10 +479,10 @@ test("request-password-reset: always 200, stores nothing without SMTP", async ()
test("request-password-reset: emails a link that resets the password", async () => {
using mail = captureEmails();
const user = await createUser();
await post("/api/users/request-password-reset", {
await post("/api/password-resets", {
json: { email: user.email },
});
await post("/api/users/request-password-reset", {
await post("/api/password-resets", {
json: { email: "nobody@example.test" },
});
await new Promise((r) => setTimeout(r, 0));
@@ -481,8 +491,8 @@ test("request-password-reset: emails a link that resets the password", async ()
const token = decodeURIComponent(
mail.sent[0].text.match(/token=([^\s)]+)/)![1],
);
const res = await post("/api/users/reset-password", {
json: { token, newPassword: "from-the-email" },
const res = await put(`/api/password-resets/${token}`, {
json: { newPassword: "from-the-email" },
});
assertEquals(res.status, 200);
});
@@ -494,22 +504,22 @@ test("reset-password: a stored token works once", async () => {
`INSERT INTO password_reset_tokens (token, user_id, expires_at) VALUES (?, ?, ?);`,
).run(token, user.id, new Date(Date.now() + 3600_000).toISOString());
const short = await post("/api/users/reset-password", {
json: { token, newPassword: "short" },
const short = await put(`/api/password-resets/${token}`, {
json: { newPassword: "short" },
});
assertEquals(short.status, 400);
const ok = await post("/api/users/reset-password", {
json: { token, newPassword: "reset-password-1" },
const ok = await put(`/api/password-resets/${token}`, {
json: { newPassword: "reset-password-1" },
});
assertEquals(ok.status, 200);
const login = await post("/api/users/login", {
const login = await post("/api/sessions", {
json: { username: user.username, password: "reset-password-1" },
});
assertEquals(login.status, 200);
const reuse = await post("/api/users/reset-password", {
json: { token, newPassword: "reset-password-2" },
const reuse = await put(`/api/password-resets/${token}`, {
json: { newPassword: "reset-password-2" },
});
assertEquals(reuse.status, 409);
});
@@ -518,28 +528,28 @@ test("reset-password: an unstored, forged or wrong-purpose token fails", async (
const user = await createUser();
const unstored = await createPasswordResetToken(user.id);
assertEquals(
(await post("/api/users/reset-password", {
json: { token: unstored, newPassword: "whatever-123" },
(await put(`/api/password-resets/${unstored}`, {
json: { newPassword: "whatever-123" },
})).status,
404,
);
for (const token of ["garbage", user.token, user.mediaToken]) {
assertEquals(
(await post("/api/users/reset-password", {
json: { token, newPassword: "whatever-123" },
(await put(`/api/password-resets/${token}`, {
json: { newPassword: "whatever-123" },
})).status,
400,
);
}
assertEquals(
(await post("/api/users/reset-password", { json: { token: 1 } })).status,
(await put(`/api/password-resets/${unstored}`, { json: {} })).status,
400,
);
});
test("GET /api/users/me/media-token issues a media token for the caller", async () => {
test("GET /api/me/media-token issues a media token for the caller", async () => {
const user = await createUser();
const res = await get<MediaTokenResponse>("/api/users/me/media-token", {
const res = await get<MediaTokenResponse>("/api/me/media-token", {
auth: user.auth,
});
assertEquals(res.status, 200);
@@ -551,12 +561,12 @@ test("GET /api/users/me/media-token issues a media token for the caller", async
test("settings: defaults until changed, a patch keeps the rest, each user their own", async () => {
const ann = await createUser();
const bob = await createUser();
const initial = await get<UserSettings>("/api/users/me/settings", {
const initial = await get<UserSettings>("/api/me/settings", {
auth: ann.auth,
});
assertEquals(initial.data, DEFAULT_SETTINGS);
const changed = await patch<UserSettings>("/api/users/me/settings", {
const changed = await patch<UserSettings>("/api/me/settings", {
auth: ann.auth,
json: { style: "kanagawa", digestWeekly: false },
});
@@ -565,7 +575,7 @@ test("settings: defaults until changed, a patch keeps the rest, each user their
style: "kanagawa",
digestWeekly: false,
});
const scheme = await patch<UserSettings>("/api/users/me/settings", {
const scheme = await patch<UserSettings>("/api/me/settings", {
auth: ann.auth,
json: { colorScheme: "dark" },
});
@@ -573,7 +583,7 @@ test("settings: defaults until changed, a patch keeps the rest, each user their
assertEquals(scheme.data.colorScheme, "dark");
assertEquals(scheme.data.digestWeekly, false);
const bobs = await get<UserSettings>("/api/users/me/settings", {
const bobs = await get<UserSettings>("/api/me/settings", {
auth: bob.auth,
});
assertEquals(bobs.data, DEFAULT_SETTINGS);
@@ -584,7 +594,7 @@ test("settings: defaults until changed, a patch keeps the rest, each user their
test("settings: signed in only, and a bad value or unknown key is refused", async () => {
const ann = await createUser();
assertEquals((await get("/api/users/me/settings")).status, 401);
assertEquals((await get("/api/me/settings")).status, 401);
for (
const json of [
{ style: "comic" },
@@ -594,13 +604,182 @@ test("settings: signed in only, and a bad value or unknown key is refused", asyn
[],
]
) {
const res = await patch("/api/users/me/settings", { auth: ann.auth, json });
const res = await patch("/api/me/settings", { auth: ann.auth, json });
assertEquals(res.status, 400, JSON.stringify(json));
}
// Null hands the style back to the instance's.
const reset = await patch<UserSettings>("/api/users/me/settings", {
const reset = await patch<UserSettings>("/api/me/settings", {
auth: ann.auth,
json: { style: null },
});
assertEquals(reset.data.style, null);
});
// ── Usernames and paths ──────────────────────────────────────────────────────
test("renaming: the old name redirects for good, and nobody else can take it", async () => {
const bob = await createUser();
const old = bob.username;
const renamed = uniqueName("robert");
const dump = insertDump({ userId: bob.id, title: "Never gonna" });
const playlist = insertPlaylist({ userId: bob.id, title: "Sunday mix" });
const res = await patch<SelfUser>("/api/me", {
auth: bob.auth,
json: { username: renamed },
});
assertEquals(res.data.username, renamed);
// The old name, in any case, still answers the user, under the new one.
for (const name of [old, old.toUpperCase(), renamed]) {
assertEquals(
(await get<PublicUser>(`/api/users/@${name}`)).data.username,
renamed,
name,
);
}
// Their dumps and playlists follow them to the new name.
for (const name of [old, renamed]) {
const d = await get<Dump>(`/api/users/@${name}/dumps/${dump.slug}`);
assertEquals([d.data.id, d.data.ownerUsername], [dump.id, renamed]);
const p = await get<Playlist>(
`/api/users/@${name}/playlists/${playlist.slug}`,
);
assertEquals([p.data.id, p.data.ownerUsername], [playlist.id, renamed]);
}
// Nobody can register or rename to the old name, in any case.
const other = await createUser();
const register = await post("/api/users", {
json: {
username: old.toUpperCase(),
password: PASSWORD,
email: `${uniqueName()}@example.test`,
inviteToken: invite(other.id),
},
});
assertEquals(register.status, 409);
assertEquals(
(await patch("/api/me", { auth: other.auth, json: { username: old } }))
.status,
409,
);
// Nor to a current one.
assertEquals(
(await patch("/api/me", {
auth: other.auth,
json: { username: renamed },
})).status,
409,
);
// Signing in takes the current name only.
assertEquals(
(await post("/api/sessions", {
json: { username: old, password: PASSWORD },
})).status,
401,
);
});
test("renaming: once in 30 days, a case change aside, and a moderator is exempt", async () => {
const user = await createUser();
const first = uniqueName("first");
assertEquals(
(await patch("/api/me", { auth: user.auth, json: { username: first } }))
.status,
200,
);
// A change of case alone leaves no alias, so it isn't counted.
assertEquals(
(await patch<SelfUser>("/api/me", {
auth: user.auth,
json: { username: first.toUpperCase() },
})).data.username,
first.toUpperCase(),
);
const again = await patch("/api/me", {
auth: user.auth,
json: { username: uniqueName("second") },
});
assertEquals(again.status, 429);
assertEquals(
(await patch("/api/me", { auth: user.auth, json: { username: "a b" } }))
.status,
400,
);
// An admin renames anyone at any time, and themselves too.
const admin = await createUser({ role: "admin" });
const third = uniqueName("third");
assertEquals(
(await patch<PublicUser>(`/api/users/${user.id}/username`, {
auth: admin.auth,
json: { username: third },
})).data.username,
third,
);
assertEquals(
(await patch<PublicUser>(`/api/users/@${third}/username`, {
auth: admin.auth,
json: { username: first },
})).data.username,
first,
"a former name of one's own can be taken back",
);
for (let i = 0; i < 2; i++) {
assertEquals(
(await patch("/api/me", {
auth: admin.auth,
json: { username: uniqueName("admin") },
})).status,
200,
);
}
// Others may not.
const moderator = await createUser({ role: "moderator" });
assertEquals(
(await patch(`/api/users/${user.id}/username`, {
auth: moderator.auth,
json: { username: uniqueName() },
})).status,
403,
);
});
test("GET /api/users/:key/dumps/:slug and /playlists/:slug: by path, privacy kept", async () => {
const owner = await createUser();
const other = await createUser();
const dump = insertDump({ userId: owner.id, title: "Hello there" });
const secret = insertDump({
userId: owner.id,
title: "Secret",
isPrivate: true,
});
const hidden = insertPlaylist({
userId: owner.id,
title: "Hidden",
isPublic: false,
});
assertEquals(dump.slug, "hello-there");
assertEquals(
(await get<Dump>(`/api/users/@${owner.username}/dumps/hello-there`)).data
.id,
dump.id,
);
assertEquals(
(await get(`/api/users/${owner.id}/dumps/hello-there`)).status,
200,
);
// Another user's space holds none of it.
assertEquals(
(await get(`/api/users/@${other.username}/dumps/hello-there`)).status,
404,
);
const secretPath = `/api/users/@${owner.username}/dumps/${secret.slug}`;
assertEquals((await get(secretPath)).status, 404);
assertEquals((await get(secretPath, { auth: other.auth })).status, 404);
assertEquals((await get(secretPath, { auth: owner.auth })).status, 200);
const hiddenPath = `/api/users/@${owner.username}/playlists/${hidden.slug}`;
assertEquals((await get(hiddenPath)).status, 404);
assertEquals((await get(hiddenPath, { auth: owner.auth })).status, 200);
});

View File

@@ -578,7 +578,7 @@ wsTest("a password change closes the user's sockets", async (connect) => {
const user = await createUser();
const c = await connect(user);
await new Promise((r) => setTimeout(r, 1100)); // see auth.test.ts
const res = await post<AuthTokens>("/api/users/me/change-password", {
const res = await put<AuthTokens>("/api/me/password", {
auth: user.auth,
json: { currentPassword: PASSWORD, newPassword: "a-new-password" },
});
@@ -642,14 +642,14 @@ wsTest(
const pl = insertPlaylist({ userId: owner.id });
const c = await connect();
const cover = new Uint8Array([...PNG, 9, 9, 9]);
const upload = post(`/api/playlists/${pl.id}/image`, {
const upload = put(`/api/playlists/${pl.id}/cover`, {
auth: owner.auth,
form: formWithFile(cover),
});
// Fetch the image the moment the socket says it changed, as a client would.
const msg = await c.next("playlist_updated");
const served = await get(
`/api/playlists/${pl.id}/image?v=${msg.playlist.updatedAt}`,
`/api/playlists/${pl.id}/cover?v=${msg.playlist.updatedAt}`,
);
assertEquals(served.status, 200);
assertEquals(served.bytes, cover);

View File

@@ -1,63 +0,0 @@
import { get, html, stubNetwork } from "../helpers.ts";
import { assertEquals, assertFalse } from "@std/assert";
import type { YouTubePlaylist } from "../../../shared/player.ts";
function ytPage(data: unknown): string {
return `<script>var ytInitialData = ${JSON.stringify(data)};</script>`;
}
const YT_DATA = {
metadata: { playlistMetadataRenderer: { title: "My mix" } },
contents: {
list: [
{
lockupViewModel: {
contentType: "LOCKUP_CONTENT_TYPE_VIDEO",
contentId: "vid1",
metadata: {
lockupMetadataViewModel: { title: { content: "First" } },
},
contentImage: {
overlays: [{ thumbnailBadgeViewModel: { text: "1:02:03" } }],
},
},
},
{
lockupViewModel: {
contentType: "LOCKUP_CONTENT_TYPE_PLAYLIST",
contentId: "ignored",
},
},
{
playlistVideoRenderer: {
videoId: "vid2",
title: { runs: [{ text: "Second" }] },
lengthSeconds: "235",
},
},
],
},
};
Deno.test("GET /api/youtube/playlist: resolves and validates the id", async () => {
let cookie: string | null = null;
using net = stubNetwork((url, init) => {
cookie = new Headers(init?.headers).get("cookie");
return url.searchParams.get("list") === "PLgone"
? new Response("", { status: 404 })
: html(ytPage(YT_DATA));
});
const ok = await get<YouTubePlaylist>("/api/youtube/playlist?list=PLgood");
assertEquals(ok.status, 200);
assertEquals(ok.data.tracks.length, 2);
assertEquals(ok.headers.get("cache-control"), "public, max-age=3600");
// The pre-answered consent cookie keeps EU requests off the consent page.
assertEquals(cookie, "SOCS=CAI");
await get("/api/youtube/playlist?list=PLgood"); // cached
assertEquals(net.calls.length, 1);
assertEquals((await get("/api/youtube/playlist?list=bad%20id")).status, 400);
assertEquals((await get("/api/youtube/playlist")).status, 400);
assertEquals((await get("/api/youtube/playlist?list=PLgone")).status, 502);
assertFalse(net.calls.some((u) => u.searchParams.get("list") === "bad id"));
});

View File

@@ -19,6 +19,7 @@ import {
getSettings,
updateSettings,
} from "../../services/settings-service.ts";
import { createUnsubscribeToken } from "../../lib/jwt.ts";
const DAY = 86_400_000;
const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
@@ -148,6 +149,77 @@ test("buildDigest: the weekly digest gathers activity, network, top and communit
);
assertEquals(digest.community?.totals.dumps, 3);
assert(digest.links.unsubscribe.includes("/unsubscribe?token="));
// Every page link has a v4 shape, and none names anything by its id.
const pageLinks = [
...digest.activity!.highlights.flatMap((h) =>
h.target?.url ? [h.target.url] : []
),
...digest.network!.dumps.map((d) => d.url),
...digest.top.map((d) => d.url),
...digest.community!.playlists.map((p) => p.url),
digest.links.followed,
digest.links.settings,
];
assertEquals(pageLinks.length, 8);
for (const link of pageLinks) {
assert(
/^\/@\w+\/(dumps|playlists)\/[a-z0-9-]+$|^\/follow$|^\/settings$/.test(
new URL(link).pathname,
),
link,
);
for (const id of [reader.id, mine.id, posted.id, added.id, mix.id]) {
assertFalse(link.includes(id), link);
}
}
assertEquals(
new URL(digest.top[1].url).pathname,
`/@${reader.username}/dumps/my-dump`,
);
});
test("buildDigest: names and links follow renames, and a deleted dump is unlinked", async () => {
const reader = await createUser();
const friend = await createUser();
const kept = insertDump({ userId: reader.id, title: "Kept" });
const gone = insertDump({ userId: reader.id, title: "Gone" });
for (const d of [kept, gone]) {
notify(reader.id, "dump_upvoted", {
voterId: friend.id,
voterUsername: friend.username,
dumpId: d.id,
dumpTitle: d.id === kept.id ? "Kept" : "Gone",
});
notify(reader.id, "dump_commented", {
commenterId: friend.id,
commenterUsername: friend.username,
commentId: crypto.randomUUID(),
dumpId: d.id,
dumpTitle: d.id === kept.id ? "Kept" : "Gone",
});
}
db.prepare(`UPDATE users SET username = 'renamed_friend' WHERE id = ?;`)
.run(friend.id);
db.prepare(`UPDATE dumps SET slug = 'still-kept' WHERE id = ?;`)
.run(kept.id);
db.prepare(`DELETE FROM dumps WHERE id = ?;`).run(gone.id);
const [from, to] = week();
const digest =
(buildDigest(reader.id, reader.username, "weekly", from, to, "tok"))!;
const targets = digest.activity!.highlights.map((h) => [
h.who,
h.target?.title,
h.target?.url && new URL(h.target.url).pathname,
]);
assertEquals(
targets.sort((a, b) => String(a[1]).localeCompare(String(b[1]))),
[
["renamed_friend", "Gone", null],
["renamed_friend", "Kept", `/@${reader.username}/dumps/still-kept`],
],
);
});
test("buildDigest: the monthly recap has no personal sections, and nothing makes no digest", async () => {
@@ -261,10 +333,28 @@ test("syncDigestSchedules: new users start now, a turned-off cadence loses its r
test("unsubscribe: a bad or other kind of token is refused", async () => {
const user = await createUser();
assertEquals((await post("/api/users/unsubscribe?token=nope")).status, 400);
assertEquals(
(await post(`/api/users/unsubscribe?token=${user.token}`)).status,
400,
);
assertEquals((await post("/api/users/unsubscribe")).status, 400);
for (const path of ["/api/unsubscribe", "/api/users/unsubscribe"]) {
assertEquals((await post(`${path}?token=nope`)).status, 400, path);
assertEquals(
(await post(`${path}?token=${user.token}`)).status,
400,
path,
);
assertEquals((await post(path)).status, 400, path);
}
});
test("unsubscribe: the v4 path and the v3 one sent emails carry both work", async () => {
const user = await createUser();
for (
const [path, cadence, setting] of [
["/api/unsubscribe", "weekly", "digestWeekly"],
["/api/users/unsubscribe", "monthly", "digestMonthly"],
] as const
) {
const token = await createUnsubscribeToken(user.id, cadence);
const res = await post<{ cadence: string }>(`${path}?token=${token}`);
assertEquals(res.data.cadence, cadence);
assertEquals(getSettings(user.id)[setting], false, path);
}
});