v3: the backend gets a test suite, and the bugs it turned up are fixed — deno task test runs 186 tests over api/ in about 18s, against a throwaway database and uploads directory (GERBEUR_DB_PATH and GERBEUR_UPLOADS_DIR now override the defaults; api/test/setup.ts sets them before any app module loads), with requests sent through the whole middleware stack in-process via app.handle, outbound fetches and DNS stubbed, and the socket tests on a real Oak listener since an upgraded request has no response for handle() to return. It covers auth (token purposes, revocation after a password change, live roles, login rate limiting, invites claimed once even under parallel registrations, password resets), dumps end to end (create, privacy, by-url matching on the canonical key, backlinks, categories, edits, file replacement, thumbnails, refresh, delete), file serving headers and ranges, attachments, avatars, comments and likes, playlists, follows and feeds, notifications and mentions, categories, search, chat cursors and read markers, link previews and the SSRF guard on every redirect hop, the Bandcamp and YouTube resolvers, migrations (a fresh schema is left untouched; the data rewrites in 0004/0005 and 0010–0013 do what they say), CORS, OG tags, static caching, and the WebSocket protocol. Fixed along the way: an unknown category id on a new dump returned 400 but kept the dump row, and for a file dump deleted the file while keeping the row; an edit or file replacement with one was half-applied before the 400 — categories are now checked before anything is written. A suffix range (bytes=-3) was read as an end offset and got a 416 instead of the last three bytes. Reordering a playlist accepted a list naming a member twice. verifyPassword threw on a stored hash without a salt instead of answering false. And a request with no Accept-Encoding, which RFC 9110 lets a server treat as accepting anything, was sent the brotli sibling; curl and bots now get the plain file.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 46s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-27 12:31:05 +00:00
parent 16b510764c
commit 25601edaf8
29 changed files with 5521 additions and 19 deletions

204
api/test/players.test.ts Normal file
View File

@@ -0,0 +1,204 @@
// Play-time resolution: Bandcamp tracklists and YouTube playlist tracklists,
// their parsers and their routes. All network access is stubbed.
import { get, html, stubNetwork } from "./helpers.ts";
import { assert, assertEquals, assertFalse } from "@std/assert";
import { parseTralbum } from "../services/bandcamp-tralbum.ts";
import { parsePlaylistPage } from "../services/youtube-playlist-service.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("parseTralbum: tracks, streamability and art", () => {
const album = parseTralbum(
tralbumPage(ALBUM),
"https://a.bandcamp.com/album/x",
);
assert(album);
assertEquals(album.itemType, "album");
assertEquals(album.artist, "Artist");
// A title containing a literal &amp; survives the single-pass decode.
assertEquals(album.title, 'The "Album" &amp; more');
assertEquals(album.artworkUrl, "https://f4.bcbits.com/img/a12345_16.jpg");
assertEquals(album.tracks.map((t) => t.streamable), [
true,
false,
false,
true,
]);
assertEquals(album.tracks[0].streamUrl, STREAM);
assertEquals(album.tracks[0].duration, 180.5);
// A non-bcbits stream host is never relayed.
assertEquals(album.tracks[2].streamUrl, null);
assertEquals(album.tracks[2].title, "Track 3");
assert(album.tracks[3].capped);
});
Deno.test("parseTralbum: pages it can't use", () => {
assertEquals(parseTralbum("<html></html>", "u"), null);
assertEquals(parseTralbum(`<div data-tralbum="{oops"></div>`, "u"), null);
assertEquals(
parseTralbum(tralbumPage({ ...ALBUM, hasAudio: false }), "u"),
null,
);
assertEquals(
parseTralbum(
tralbumPage({ ...ALBUM, trackinfo: [ALBUM.trackinfo[1]] }),
"u",
),
null,
);
});
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("parsePlaylistPage: current and legacy rows", () => {
assertEquals(parsePlaylistPage(ytPage(YT_DATA), "PLx"), {
listId: "PLx",
title: "My mix",
tracks: [
{ videoId: "vid1", title: "First", duration: 3723 },
{ videoId: "vid2", title: "Second", duration: 235 },
],
});
assertEquals(parsePlaylistPage("<html></html>", "PLx"), null);
assertEquals(parsePlaylistPage(ytPage({ contents: {} }), "PLx"), null);
});
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(`/api/bandcamp/tracks?url=${encodeURIComponent(url)}`);
assertEquals(res.status, 200);
assertEquals(res.headers.get("cache-control"), "private, max-age=3600");
assertEquals(res.body.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);
});
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("/api/youtube/playlist?list=PLgood");
assertEquals(ok.status, 200);
assertEquals(ok.body.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"));
});