Repository Public
1import { existsSync, readdirSync } from "node:fs";2import path from "node:path";3import { afterAll, describe, expect, it } from "vitest";4import { BASE, Client, fixture, setupTokenFromFile, sleep, sql, STORAGE, tokenOf } from "./helpers";56const owner = new Client();7const listener = new Client();8const anon = new Client();9let trackA = "", trackB = "", albumId = "", listenerId = "";10let recoveryCodes: string[] = [];1112afterAll(async () => { await sql.end(); });1314describe("signed-out visitors", () => {15 it("cannot read the library, a track, a cover or the administration", async () => {16 for (const p of ["/api/v1/library/home", "/api/v1/library/tracks", "/api/v1/admin/health", "/api/v1/admin/users", "/api/v1/me/passkeys"]) expect((await anon.req(p)).status, p).toBe(401);17 expect((await anon.req("/api/v1/stream/00000000-0000-4000-8000-000000000000")).status).toBe(401);18 expect((await anon.req("/api/v1/art/00000000-0000-4000-8000-000000000000")).status).toBe(401);19 expect((await anon.json("/api/v1/admin/uploads", { json: { filename: "x.flac", size: 10 } })).status).toBe(401);20 });21 it("are redirected to the sign-in page", async () => {22 for (const p of ["/", "/admin", "/bibliotheque"]) { const r = await anon.req(p); expect(r.status, p).toBe(307); expect(r.headers.get("location")).toContain("/login"); }23 });24 it("get the security headers", async () => {25 const r = await anon.req("/login");26 expect(r.status).toBe(200);27 expect(r.headers.get("content-security-policy")).toContain("frame-ancestors 'none'");28 expect(r.headers.get("x-content-type-options")).toBe("nosniff");29 expect(r.headers.get("x-frame-options")).toBe("DENY");30 expect(r.headers.get("strict-transport-security")).toContain("max-age");31 expect(r.headers.get("referrer-policy")).toBeTruthy();32 });33 it("cannot enrol a passkey without a token", async () => {34 expect((await anon.json("/api/v1/auth/register/options", { json: {} })).status).toBe(403);35 expect((await anon.json("/api/v1/auth/register/options", { json: { setupToken: "x".repeat(43) } })).status).toBe(403);36 });37});3839describe("owner setup with a passkey", () => {40 const token = setupTokenFromFile();41 it("rejects a registration from the wrong origin, a wrong RP ID, or without user verification", async () => {42 expect((await owner.enrol(token, { origin: "https://evil.example" })).status).toBe(400);43 expect((await owner.enrol(token, { rpId: "evil.example" })).status).toBe(400);44 expect((await owner.enrol(token, { noUserVerification: true })).status).toBe(400);45 expect((await sql`SELECT count(*)::int AS n FROM authenticators`)[0].n).toBe(0);46 });47 it("enrols the first passkey, opens a session and hands out recovery codes once", async () => {48 const r = await owner.enrol(token);49 expect(r.status).toBe(200);50 recoveryCodes = (r.body as { recoveryCodes: string[] }).recoveryCodes;51 expect(recoveryCodes).toHaveLength(8);52 const s = await owner.refreshSession();53 expect(s.authenticated).toBe(true); expect(s.user!.role).toBe("admin");54 // replaying the same challenge and response is refused55 const replay = await owner.json("/api/v1/auth/register/verify", { json: { challengeId: r.challengeId, response: r.response, setupToken: token } });56 expect(replay.status).toBe(400); expect(replay.body.error!.code).toBe("challenge_expired");57 });58 it("closes setup mode: the token is single-use", async () => {59 const again = new Client();60 expect((await again.enrol(token)).status).toBe(403);61 expect((await again.json("/api/v1/auth/setup/info", { json: { setupToken: token } })).status).toBe(403);62 });63 it("stores only public credential data", async () => {64 const cols = (await sql`SELECT column_name FROM information_schema.columns WHERE table_name = 'authenticators'`).map((c) => c.column_name).sort();65 expect(cols).toEqual(["backed_up", "counter", "created_at", "credential_id", "device_type", "id", "last_used_at", "name", "public_key", "transports", "user_id"]);66 });67});6869describe("sign-in", () => {70 it("rejects a wrong origin, a wrong RP ID, a bad signature and a missing user verification", async () => {71 const c = new Client(); c.auth = owner.auth;72 expect((await c.login(undefined, { origin: "https://evil.example" })).status).toBe(401);73 expect((await c.login(undefined, { rpId: "evil.example" })).status).toBe(401);74 expect((await c.login(undefined, { badSignature: true })).status).toBe(401);75 expect((await c.login(undefined, { noUserVerification: true })).status).toBe(401);76 expect(c.cookie).toBe("");77 });78 it("accepts a valid assertion, rotates the session, and refuses a replayed or expired challenge", async () => {79 const c = new Client(); c.auth = owner.auth;80 const r = await c.login();81 expect(r.status).toBe(200);82 expect(c.cookie).not.toBe(""); expect(c.cookie).not.toBe(owner.cookie);83 const replay = await new Client().json("/api/v1/auth/login/verify", { json: { challengeId: r.challengeId, response: r.response } });84 expect(replay.status).toBe(401);85 // expired challenge86 const d = new Client(); d.auth = owner.auth;87 const o = await d.json<{ challengeId: string; options: { challenge: string } }>("/api/v1/auth/login/options", { json: {} });88 await sql`UPDATE webauthn_challenges SET expires_at = now() - interval '1 second' WHERE id = ${o.body.challengeId}`;89 expect((await d.json("/api/v1/auth/login/verify", { json: { challengeId: o.body.challengeId, response: d.auth.get(o.body.options) } })).status).toBe(401);90 expect((await sql`SELECT count(*)::int AS n FROM audit_events WHERE action = 'login.failed'`)[0].n).toBeGreaterThanOrEqual(5);91 });92 it("sets an HttpOnly, Secure, SameSite cookie", async () => {93 const c = new Client(); c.auth = owner.auth;94 const o = await c.json<{ challengeId: string; options: { challenge: string } }>("/api/v1/auth/login/options", { json: {} });95 const res = await c.req("/api/v1/auth/login/verify", { json: { challengeId: o.body.challengeId, response: c.auth.get(o.body.options) } });96 const sc = (res.headers.getSetCookie() ?? []).join(";").toLowerCase();97 expect(sc).toContain("httponly"); expect(sc).toContain("secure"); expect(sc).toContain("samesite=lax"); expect(sc).not.toContain("domain=");98 });99 it("refuses state-changing requests without the CSRF token or from another origin", async () => {100 expect((await owner.json("/api/v1/admin/uploads", { json: { filename: "x.flac", size: 10 }, noCsrf: true })).body.error!.code).toBe("csrf");101 const r = await owner.json("/api/v1/admin/uploads", { json: { filename: "x.flac", size: 10 }, headers: { Origin: "https://evil.example" } });102 expect(r.status).toBe(403); expect(r.body.error!.code).toBe("bad_origin");103 });104});105106describe("import", () => {107 it("uploads in chunks, resumes from the server's offset, analyses and indexes a FLAC", async () => {108 const data = fixture("a.flac");109 const c = await owner.json<{ id: string }>("/api/v1/admin/uploads", { json: { filename: "../../01 Onde.flac", size: data.length } });110 expect(c.status).toBe(200);111 const half = Math.floor(data.length / 2);112 expect((await owner.json(`/api/v1/admin/uploads/${c.body.id}?offset=0`, { method: "PATCH", raw: data.subarray(0, half) })).status).toBe(200);113 const wrong = await owner.json(`/api/v1/admin/uploads/${c.body.id}?offset=0`, { method: "PATCH", raw: data.subarray(0, half) });114 expect(wrong.status).toBe(409); expect(wrong.body.error!.details!.receivedBytes).toBe(half);115 const tooMuch = await owner.json(`/api/v1/admin/uploads/${c.body.id}?offset=${half}`, { method: "PATCH", raw: Buffer.concat([data.subarray(half), Buffer.alloc(10)]) });116 expect(tooMuch.status).toBe(413);117 expect((await owner.json(`/api/v1/admin/uploads/${c.body.id}?offset=${half}`, { method: "PATCH", raw: data.subarray(half) })).status).toBe(200);118 const u = await owner.waitUpload(c.body.id);119 expect(u.status, JSON.stringify(u)).toBe("ready");120 trackA = u.trackId!;121 const [row] = await sql`SELECT filename FROM uploads WHERE id = ${c.body.id}`;122 expect(row.filename).toBe("01 Onde.flac");123 const b = await owner.upload("b.flac", fixture("b.flac"));124 expect(b.body.status).toBe("ready"); trackB = (b.body as { trackId: string }).trackId;125 });126 it("exposes tags, technical data and the embedded cover", async () => {127 const t = (await owner.json<Record<string, never>>(`/api/v1/library/tracks/${trackA}`)).body as unknown as { title: string; codec: string; sampleRate: number; bitDepth: number; trackNo: number; year: number; genre: string; webPlayable: string; artist: { name: string }; album: { id: string; title: string; artworkId: string } };128 expect(t).toMatchObject({ title: "Onde À", codec: "flac", sampleRate: 44100, bitDepth: 16, trackNo: 1, year: 2024, genre: "Test", webPlayable: "yes" });129 expect(t.artist.name).toBe("Les Sinusoïdes"); expect(t.album.title).toBe("Fréquences");130 albumId = t.album.id;131 const al = await owner.json<{ tracks: { id: string }[] }>(`/api/v1/library/albums/${albumId}`);132 expect(al.body.tracks.map((x) => x.id)).toEqual([trackA, trackB]);133 for (const s of ["96", "320", "640", "orig"]) { const r = await owner.req(`/api/v1/art/${t.album.artworkId}?s=${s}`); expect(r.status, s).toBe(200); expect(r.headers.get("content-type")).toMatch(/^image\//); expect(r.headers.get("cache-control")).toContain("private"); }134 const found = await owner.json<{ tracks: { id: string }[]; albums: unknown[]; artists: unknown[] }>(`/api/v1/library/search?q=${encodeURIComponent("sinusoides")}`);135 expect(found.body.artists).toHaveLength(1); expect(found.body.tracks.length).toBe(2);136 expect((await owner.json<{ tracks: unknown[] }>("/api/v1/library/search?q=test")).body.tracks.length).toBeGreaterThan(0); // by genre137 });138 it("detects duplicates by content hash and by track identity, and replaces only on confirmation", async () => {139 const same = await owner.upload("copy.flac", fixture("a.flac"));140 expect(same.body).toMatchObject({ status: "duplicate", errorCode: "same_file", duplicateOf: trackA });141 expect((await owner.json(`/api/v1/admin/uploads/${same.id}`, { method: "DELETE" })).status).toBe(200);142 const twin = await owner.upload("other.flac", fixture("a-other-encoding.flac"));143 expect(twin.body).toMatchObject({ status: "duplicate", errorCode: "same_track", duplicateOf: trackA });144 const [before] = await sql`SELECT storage_key, sha256 FROM media_assets WHERE track_id = ${trackA} AND kind = 'original'`;145 expect((await owner.json(`/api/v1/admin/uploads/${twin.id}/replace`, { json: {} })).status).toBe(200);146 expect((await owner.waitUpload(twin.id)).status).toBe("ready");147 const [after] = await sql`SELECT storage_key, sha256 FROM media_assets WHERE track_id = ${trackA} AND kind = 'original'`;148 expect(after.sha256).not.toBe(before.sha256);149 expect(existsSync(path.join(STORAGE, before.storage_key))).toBe(false);150 expect(existsSync(path.join(STORAGE, after.storage_key))).toBe(true);151 expect((await sql`SELECT count(*)::int AS n FROM audit_events WHERE action = 'track.replaced'`)[0].n).toBe(1);152 expect((await sql`SELECT count(*)::int AS n FROM tracks`)[0].n).toBe(2);153 });154 it("refuses impostors, broken files and oversized files cleanly", async () => {155 expect((await owner.upload("program.flac", fixture("program.flac"))).body).toMatchObject({ status: "error", errorCode: "unsupported_type" });156 expect((await owner.upload("text.mp3", fixture("text.mp3"))).body).toMatchObject({ status: "error", errorCode: "unsupported_type" });157 expect((await owner.upload("broken.flac", fixture("broken.flac"))).body).toMatchObject({ status: "error", errorCode: "undecodable" });158 const big = await owner.json("/api/v1/admin/uploads", { json: { filename: "huge.flac", size: 51 * 1024 * 1024 } });159 expect(big.status).toBe(413); expect(big.body.error!.code).toBe("file_too_large");160 expect((await owner.json("/api/v1/admin/uploads", { json: { filename: "zero.flac", size: 0 } })).status).toBe(400);161 expect((await sql`SELECT count(*)::int AS n FROM tracks`)[0].n).toBe(2);162 const err = await owner.json<{ raw?: string }>("/api/v1/admin/uploads/not-a-uuid");163 expect(err.status).toBe(400); expect(JSON.stringify(err.body)).not.toMatch(/\/tmp|\/Users|at .*\.ts/);164 });165 it("imports MP3 and untagged WAV, and prepares an AAC rendition for ALAC", async () => {166 expect((await owner.upload("c.mp3", fixture("c.mp3"))).body.status).toBe("ready");167 const wav = await owner.upload("03 Sans Tags.wav", fixture("03 Sans Tags.wav"));168 const w = (await owner.json(`/api/v1/library/tracks/${(wav.body as { trackId: string }).trackId}`)).body as unknown as { title: string; trackNo: number; album: { title: string } };169 expect(w).toMatchObject({ title: "Sans Tags", trackNo: 3 }); expect(w.album.title).toBe("Album inconnu");170 const alac = await owner.upload("d.m4a", fixture("d.m4a"));171 const id = (alac.body as { trackId: string }).trackId;172 let t: { codec: string; webPlayable: string; compatState: string } = { codec: "", webPlayable: "", compatState: "" };173 for (let i = 0; i < 100; i++) { t = (await owner.json(`/api/v1/library/tracks/${id}`)).body as never; if (t.compatState === "ready" || t.compatState === "error") break; await sleep(300); }174 expect(t).toMatchObject({ codec: "alac", webPlayable: "some", compatState: "ready" });175 const r = await owner.req(`/api/v1/stream/${id}?v=compat`, { headers: { Range: "bytes=0-99" } });176 expect(r.status).toBe(206); expect(r.headers.get("content-type")).toBe("audio/mp4");177 expect((await owner.req(`/api/v1/stream/${trackA}?v=compat`)).status).toBe(404);178 expect((await owner.req(`/api/v1/stream/${trackA}`, { method: "POST" })).status).toBe(405);179 });180 it("expands a ZIP safely (no path traversal) and refuses bombs and empty archives", async () => {181 const z = await owner.upload("album.zip", fixture("album.zip"));182 expect(z.body.status, JSON.stringify(z.body)).toBe("ready");183 for (let i = 0; i < 100; i++) { const [{ n }] = await sql`SELECT count(*)::int AS n FROM uploads WHERE parent_id = ${z.id} AND status NOT IN ('ready', 'error', 'duplicate')`; if (n === 0) break; await sleep(300); }184 const kids = await sql`SELECT filename, status FROM uploads WHERE parent_id = ${z.id} ORDER BY filename`;185 expect(kids.map((k) => [k.filename, k.status])).toEqual([["01 un.flac", "ready"], ["02 deux.flac", "ready"]]);186 // an archive carrying a "../" entry is refused whole, and nothing is written outside the storage187 const before = (await sql`SELECT count(*)::int AS n FROM tracks`)[0].n;188 expect((await owner.upload("evil.zip", fixture("evil.zip"))).body).toMatchObject({ status: "error", errorCode: "archive_invalid" });189 expect((await sql`SELECT count(*)::int AS n FROM tracks`)[0].n).toBe(before);190 for (const dir of [path.dirname(STORAGE), path.dirname(path.dirname(STORAGE)), "/tmp"]) expect(readdirSync(dir).filter((f) => f.includes("evil-escape"))).toEqual([]);191 expect((await owner.upload("bomb.zip", fixture("bomb.zip"))).body).toMatchObject({ status: "error", errorCode: "archive_too_large" });192 expect((await owner.upload("noaudio.zip", fixture("noaudio.zip"))).body).toMatchObject({ status: "error", errorCode: "archive_no_audio" });193 });194});195196describe("private streaming", () => {197 it("serves the whole file and byte ranges with correct headers", async () => {198 const [asset] = await sql`SELECT storage_key, size_bytes FROM media_assets WHERE track_id = ${trackB} AND kind = 'original'`;199 const size = Number(asset.size_bytes); const data = fixture("b.flac");200 const full = await owner.req(`/api/v1/stream/${trackB}`);201 expect(full.status).toBe(200);202 expect(full.headers.get("content-type")).toBe("audio/flac"); expect(full.headers.get("accept-ranges")).toBe("bytes");203 expect(full.headers.get("content-length")).toBe(String(size)); expect(full.headers.get("cache-control")).toContain("private");204 expect(Buffer.from(await full.arrayBuffer()).equals(data)).toBe(true);205 const part = await owner.req(`/api/v1/stream/${trackB}`, { headers: { Range: "bytes=100-299" } });206 expect(part.status).toBe(206); expect(part.headers.get("content-range")).toBe(`bytes 100-299/${size}`); expect(part.headers.get("content-length")).toBe("200");207 expect(Buffer.from(await part.arrayBuffer()).equals(data.subarray(100, 300))).toBe(true);208 const tail = await owner.req(`/api/v1/stream/${trackB}`, { headers: { Range: "bytes=-50" } });209 expect(tail.status).toBe(206); expect(Buffer.from(await tail.arrayBuffer()).equals(data.subarray(size - 50))).toBe(true);210 const open = await owner.req(`/api/v1/stream/${trackB}`, { headers: { Range: `bytes=${size - 10}-` } });211 expect(open.status).toBe(206); expect(open.headers.get("content-length")).toBe("10");212 const bad = await owner.req(`/api/v1/stream/${trackB}`, { headers: { Range: `bytes=${size + 5}-` } });213 expect(bad.status).toBe(416); expect(bad.headers.get("content-range")).toBe(`bytes */${size}`);214 const etag = full.headers.get("etag")!;215 expect((await owner.req(`/api/v1/stream/${trackB}`, { headers: { "If-None-Match": etag } })).status).toBe(304);216 const head = await owner.req(`/api/v1/stream/${trackB}`, { method: "HEAD" });217 expect(head.status).toBe(200); expect(head.headers.get("content-length")).toBe(String(size));218 });219 it("never resolves anything but an opaque track id", async () => {220 for (const p of ["..%2F..%2Fetc%2Fpasswd", "originals", "not-a-uuid"]) expect((await owner.req(`/api/v1/stream/${p}`)).status).toBe(404);221 expect((await owner.req("/api/v1/stream/00000000-0000-4000-8000-000000000000")).status).toBe(404);222 expect((await fetch(`${BASE}/originals/`)).status).toBeGreaterThanOrEqual(300);223 });224});225226describe("listener role", () => {227 it("is created by invitation only and can listen", async () => {228 const inv = await owner.json<{ id: string; inviteUrl: string }>("/api/v1/admin/users", { json: { email: "auditeur@example.test", displayName: "Auditeur", role: "listener" } });229 expect(inv.status).toBe(200); listenerId = inv.body.id;230 expect((await listener.enrol(tokenOf(inv.body.inviteUrl))).status).toBe(200);231 expect((await listener.refreshSession()).user!.role).toBe("listener");232 expect((await listener.json("/api/v1/library/home")).status).toBe(200);233 expect((await listener.req(`/api/v1/stream/${trackB}`, { headers: { Range: "bytes=0-9" } })).status).toBe(206);234 expect((await listener.json(`/api/v1/library/albums/${albumId}`)).status).toBe(200);235 });236 it("is refused by every administration endpoint, server-side", async () => {237 const calls: [string, string, unknown?][] = [238 ["POST", "/api/v1/admin/uploads", { filename: "x.flac", size: 10 }], ["GET", "/api/v1/admin/uploads"], ["GET", "/api/v1/admin/uploads/limits"],239 ["PATCH", "/api/v1/admin/tracks", { ids: [trackA], patch: { title: "Piraté" } }], ["POST", "/api/v1/admin/tracks/delete", { ids: [trackA], confirm: true }],240 ["POST", "/api/v1/admin/tracks/reanalyse", { ids: [trackA] }], ["PATCH", `/api/v1/admin/albums/${albumId}`, { title: "Piraté" }],241 ["POST", `/api/v1/admin/albums/${albumId}/delete`, { confirm: true }], ["PUT", `/api/v1/admin/albums/${albumId}/order`, { trackIds: [trackB, trackA] }],242 ["GET", "/api/v1/admin/users"], ["POST", "/api/v1/admin/users", { email: "x@example.test", displayName: "X", role: "admin" }],243 ["PATCH", `/api/v1/admin/users/${listenerId}`, { role: "admin" }], ["GET", "/api/v1/admin/health"], ["GET", "/api/v1/admin/audit"], ["POST", "/api/v1/admin/uploads/clear", {}],244 ];245 for (const [method, p, json] of calls) { const r = await listener.json(p, { method, json }); expect(r.status, `${method} ${p}`).toBe(403); expect(r.body.error!.code).toBe("forbidden"); }246 expect((await listener.req(`/api/v1/admin/albums/${albumId}/artwork`, { method: "PUT", raw: fixture("cover2.jpg") })).status).toBe(403);247 const page = await listener.req("/admin"); expect(page.status).toBe(307); expect(page.headers.get("location")).not.toContain("/admin");248 expect((await sql`SELECT title FROM tracks WHERE id = ${trackA}`)[0].title).toBe("Onde À");249 });250 it("owns its favourites, playlists and playback state; another account cannot reach them", async () => {251 expect((await listener.json(`/api/v1/library/favorites/track/${trackB}`, { method: "PUT" })).status).toBe(200);252 expect(((await listener.json<{ tracks: unknown[] }>("/api/v1/library/favorites")).body.tracks).length).toBe(1);253 expect(((await owner.json<{ tracks: unknown[] }>("/api/v1/library/favorites")).body.tracks).length).toBe(0);254 const pl = await listener.json<{ id: string }>("/api/v1/library/playlists", { json: { name: "Ma liste", trackIds: [trackA, trackB] } });255 expect(pl.status).toBe(200);256 const mine = await listener.json<{ tracks: { id: string; entryId: string }[] }>(`/api/v1/library/playlists/${pl.body.id}`);257 expect(mine.body.tracks.map((t) => t.id)).toEqual([trackA, trackB]);258 expect((await listener.json(`/api/v1/library/playlists/${pl.body.id}/order`, { method: "PUT", json: { entryIds: mine.body.tracks.map((t) => t.entryId).reverse() } })).status).toBe(200);259 expect((await listener.json<{ tracks: { id: string }[] }>(`/api/v1/library/playlists/${pl.body.id}`)).body.tracks.map((t) => t.id)).toEqual([trackB, trackA]);260 for (const [m, p, j] of [["GET", ""], ["PATCH", "", { name: "volée" }], ["DELETE", ""], ["POST", "/tracks", { trackIds: [trackA] }]] as [string, string, unknown?][])261 expect((await owner.json(`/api/v1/library/playlists/${pl.body.id}${p}`, { method: m, json: j })).status, `${m} ${p}`).toBe(404);262 const state = { queue: [trackA, trackB], index: 1, positionMs: 2500, shuffle: false, repeat: "all", volume: 0.6 };263 expect((await listener.json("/api/v1/library/playback", { method: "PUT", json: state })).status).toBe(200);264 const back = (await listener.json("/api/v1/library/playback")).body as unknown as { queue: { id: string }[]; index: number; positionMs: number; repeat: string; volume: number };265 expect(back.queue.map((t) => t.id)).toEqual([trackA, trackB]); expect(back).toMatchObject({ index: 1, positionMs: 2500, repeat: "all" });266 expect(((await owner.json("/api/v1/library/playback")).body as unknown as { queue: unknown[] }).queue).toEqual([]);267 });268});269270describe("passkeys and sessions", () => {271 it("adds a second passkey, signs in with it, revokes it; the last one cannot be removed", async () => {272 const o = await owner.json<{ challengeId: string; options: { challenge: string; user: { id: string } } }>("/api/v1/auth/register/options", { json: {} });273 const second = owner.auth.create(o.body.options);274 expect((await owner.json("/api/v1/auth/register/verify", { json: { challengeId: o.body.challengeId, response: second, name: "Deuxième" } })).status).toBe(200);275 const list = await owner.json<{ items: { id: string; name: string; createdAt: string; lastUsedAt: string | null }[] }>("/api/v1/me/passkeys");276 expect(list.body.items).toHaveLength(2);277 const c = new Client(); c.auth = owner.auth;278 expect((await c.login(second.id)).status).toBe(200);279 const pk = list.body.items.find((k) => k.name === "Deuxième")!;280 expect((await owner.json(`/api/v1/me/passkeys/${pk.id}`, { method: "DELETE" })).status).toBe(200);281 const d = new Client(); d.auth = owner.auth;282 expect((await d.login(second.id)).status).toBe(401);283 const last = (await owner.json<{ items: { id: string; lastUsedAt: string | null }[] }>("/api/v1/me/passkeys")).body.items;284 expect(last).toHaveLength(1); expect(last[0].lastUsedAt).not.toBeNull();285 const r = await owner.json(`/api/v1/me/passkeys/${last[0].id}`, { method: "DELETE" });286 expect(r.status).toBe(409); expect(r.body.error!.code).toBe("last_passkey");287 // the revoked passkey's session is still listed and can be closed288 const sessions = (await owner.json<{ items: { id: string; current: boolean }[] }>("/api/v1/me/sessions")).body.items;289 expect(sessions.filter((s) => s.current)).toHaveLength(1);290 expect((await c.json("/api/v1/library/home")).status).toBe(200);291 expect((await owner.json("/api/v1/me/sessions/revoke-others", { json: {} })).status).toBe(200);292 expect((await c.json("/api/v1/library/home")).status).toBe(401);293 expect((await owner.json("/api/v1/library/home")).status).toBe(200);294 });295 it("lets an administrator close a listener's sessions and suspend the account", async () => {296 expect((await owner.json(`/api/v1/admin/users/${listenerId}/revoke-sessions`, { json: {} })).status).toBe(200);297 expect((await listener.json("/api/v1/library/home")).status).toBe(401);298 expect((await listener.login()).status).toBe(200);299 expect((await owner.json(`/api/v1/admin/users/${listenerId}`, { method: "PATCH", json: { disabled: true } })).status).toBe(200);300 expect((await listener.json("/api/v1/library/home")).status).toBe(401);301 expect((await listener.login()).status).toBe(401);302 expect((await owner.json(`/api/v1/admin/users/${listenerId}`, { method: "PATCH", json: { disabled: false } })).status).toBe(200);303 expect((await listener.login()).status).toBe(200);304 });305 it("protects the owner account and accepts each recovery code once", async () => {306 const me = (await owner.refreshSession()).user!.id;307 expect((await owner.json(`/api/v1/admin/users/${me}`, { method: "PATCH", json: { role: "listener" } })).status).toBe(403);308 expect((await owner.json(`/api/v1/admin/users/${me}`, { method: "DELETE" })).status).toBe(403);309 const c = new Client();310 expect((await c.json("/api/v1/auth/recovery", { json: { code: "0000-0000-0000" } })).status).toBe(401);311 expect((await c.json("/api/v1/auth/recovery", { json: { code: recoveryCodes[0] } })).status).toBe(200);312 expect((await new Client().json("/api/v1/auth/recovery", { json: { code: recoveryCodes[0] } })).status).toBe(401);313 // brute force is throttled per address314 const b = new Client(); let limited = false;315 for (let i = 0; i < 8; i++) if ((await b.json("/api/v1/auth/recovery", { json: { code: `aaaa-bbbb-${1000 + i}` } })).status === 429) limited = true;316 expect(limited).toBe(true);317 });318});319320describe("library management", () => {321 it("edits tags, moves a track to another album, reorders, and sets a cover", async () => {322 expect((await owner.json("/api/v1/admin/tracks", { method: "PATCH", json: { ids: [trackB], patch: { title: "Onde B (corrigée)", year: 2025, genre: "Électro" } } })).status).toBe(200);323 expect((await owner.json(`/api/v1/library/tracks/${trackB}`)).body).toMatchObject({ title: "Onde B (corrigée)", year: 2025, genre: "Électro" });324 expect((await owner.json(`/api/v1/admin/albums/${albumId}/order`, { method: "PUT", json: { trackIds: [trackB, trackA] } })).status).toBe(200);325 expect((await owner.json<{ tracks: { id: string; trackNo: number }[] }>(`/api/v1/library/albums/${albumId}`)).body.tracks.map((t) => [t.id, t.trackNo])).toEqual([[trackB, 1], [trackA, 2]]);326 expect((await owner.json(`/api/v1/admin/albums/${albumId}/order`, { method: "PUT", json: { trackIds: [trackB] } })).status).toBe(400);327 const cover = await owner.json<{ artworkId: string }>(`/api/v1/admin/albums/${albumId}/artwork`, { method: "PUT", raw: fixture("cover2.jpg") });328 expect(cover.status).toBe(200);329 expect((await owner.req(`/api/v1/art/${cover.body.artworkId}?s=320`)).status).toBe(200);330 expect((await owner.json(`/api/v1/admin/albums/${albumId}/artwork`, { method: "PUT", raw: fixture("program.flac") })).status).toBe(400);331 expect((await owner.json("/api/v1/admin/tracks", { method: "PATCH", json: { ids: [trackA], patch: { album: "Nouvel album", albumArtist: "Les Sinusoïdes" } } })).status).toBe(200);332 const moved = (await owner.json(`/api/v1/library/tracks/${trackA}`)).body as unknown as { album: { id: string; title: string } };333 expect(moved.album.title).toBe("Nouvel album"); expect(moved.album.id).not.toBe(albumId);334 expect((await owner.json("/api/v1/admin/tracks", { method: "PATCH", json: { ids: [trackA], patch: { year: 99999 } } })).status).toBe(400);335 expect((await owner.json("/api/v1/admin/tracks", { method: "PATCH", json: { ids: [trackA], patch: { path: "/etc/passwd" } } })).status).toBe(400);336 });337 it("deletes a track: rows, files and playlist entries go; nothing else does; the deletion is audited", async () => {338 const assets = await sql`SELECT storage_key FROM media_assets WHERE track_id = ${trackA}`;339 const others = await sql`SELECT storage_key FROM media_assets WHERE track_id <> ${trackA} AND track_id IS NOT NULL`;340 expect((await owner.json("/api/v1/admin/tracks/delete", { json: { ids: [trackA] } })).status).toBe(400); // needs the explicit confirmation341 const r = await owner.json<{ deleted: number; fileErrors: number }>("/api/v1/admin/tracks/delete", { json: { ids: [trackA], confirm: true } });342 expect(r.body).toMatchObject({ deleted: 1, fileErrors: 0 });343 for (const a of assets) expect(existsSync(path.join(STORAGE, a.storage_key)), a.storage_key).toBe(false);344 for (const a of others) expect(existsSync(path.join(STORAGE, a.storage_key)), a.storage_key).toBe(true);345 expect((await owner.req(`/api/v1/stream/${trackA}`)).status).toBe(404);346 expect((await sql`SELECT count(*)::int AS n FROM albums WHERE title = 'Nouvel album'`)[0].n).toBe(0); // emptied album pruned347 expect((await sql`SELECT count(*)::int AS n FROM playlist_tracks WHERE track_id = ${trackA}`)[0].n).toBe(0);348 const [ev] = await sql`SELECT meta FROM audit_events WHERE action = 'track.deleted' AND entity_id = ${trackA}`;349 expect(ev.meta.title).toBe("Onde À"); expect(ev.meta.sha256).toMatch(/^[0-9a-f]{64}$/);350 const log = JSON.stringify((await owner.json("/api/v1/admin/audit?limit=200")).body);351 expect(log).not.toMatch(/spmusic_session|csrfToken|token_hash|clientDataJSON/);352 for (const c of recoveryCodes) expect(log).not.toContain(c);353 });354 it("reports system health", async () => {355 const h = (await owner.json("/api/v1/admin/health")).body as unknown as { storage: { available: boolean; usedBytes: number }; library: { tracks: number }; worker: { ok: boolean } };356 expect(h.storage.available).toBe(true); expect(h.storage.usedBytes).toBeGreaterThan(0); expect(h.worker.ok).toBe(true); expect(h.library.tracks).toBeGreaterThanOrEqual(5);357 });358});359360describe("native clients", () => {361 const web = new Client(); // a browser, signed in with a passkey362 const app = new Client(); // the native app: no browser session, only what device linking hands it363 type Sync = { since: number; rev: number; more: boolean; artists: { id: string; name: string }[]; albums: { id: string; title: string; artistId: string }[];364 tracks: { id: string; title: string; albumId: string; lyricsState: string | null; file: { assetId: string; sha256: string; sizeBytes: number; mime: string } | null }[];365 deleted: { kind: string; id: string }[]; counts: { artists: number; albums: number; tracks: number } };366 let cursor = 0, playlistId = "", stamp = "", someTrack = "";367368 it("publishes the app-site-association file for native passkeys", async () => {369 const r = await anon.req("/.well-known/apple-app-site-association");370 expect(r.status).toBe(200); expect(r.headers.get("content-type")).toBe("application/json");371 expect((await r.json()).webcredentials.apps).toEqual(["3YM54G49SN.ai.spboucher.spmusic", "3YM54G49SN.ai.spboucher.spmusic.ios"]);372 });373374 it("links a device: the app shows a code, a signed-in browser approves it, the app gets its own session", async () => {375 const inv = await owner.json<{ inviteUrl: string }>("/api/v1/admin/users", { json: { email: "natif@example.test", displayName: "Natif", role: "listener" } });376 expect((await web.enrol(tokenOf(inv.body.inviteUrl))).status).toBe(200);377 const start = await app.json<{ deviceCode: string; userCode: string; verificationUrl: string }>("/api/v1/auth/device/start", { json: { deviceName: "MacBook de test" } });378 expect(start.status).toBe(200); expect(start.body.userCode).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/); expect(start.body.verificationUrl).toContain(`/appareil?code=${start.body.userCode}`);379 expect((await app.json("/api/v1/auth/device/poll", { json: { deviceCode: start.body.deviceCode } })).body).toMatchObject({ status: "pending" });380 // The approval needs a session and its CSRF token; a signed-out visitor is sent to sign in and comes back to the code.381 expect((await anon.json("/api/v1/auth/device/decide", { json: { userCode: start.body.userCode, approve: true } })).status).toBe(401);382 expect((await web.json("/api/v1/auth/device/decide", { json: { userCode: start.body.userCode, approve: true }, noCsrf: true })).status).toBe(403);383 const page = await anon.req(`/appareil?code=${start.body.userCode}`); expect(page.status).toBe(307);384 expect(decodeURIComponent(page.headers.get("location")!)).toContain(`/login?next=/appareil?code=${start.body.userCode}`);385 expect((await web.req(`/appareil?code=${start.body.userCode}`)).status).toBe(200);386 expect((await web.json("/api/v1/auth/device/info", { json: { userCode: "ZZZZ-ZZZZ" } })).status).toBe(404);387 expect((await web.json("/api/v1/auth/device/info", { json: { userCode: start.body.userCode.toLowerCase().replace("-", " ") } })).body).toMatchObject({ deviceName: "MacBook de test" });388 expect((await web.json("/api/v1/auth/device/decide", { json: { userCode: start.body.userCode, approve: true } })).status).toBe(200);389 expect((await web.json("/api/v1/auth/device/decide", { json: { userCode: start.body.userCode, approve: true } })).status).toBe(404); // decided once390 const done = await app.json<{ status: string; sessionToken: string; csrfToken: string }>("/api/v1/auth/device/poll", { json: { deviceCode: start.body.deviceCode } });391 expect(done.body.status).toBe("approved"); expect(done.body.sessionToken.length).toBeGreaterThan(30);392 expect((await app.json("/api/v1/auth/device/poll", { json: { deviceCode: start.body.deviceCode } })).status).toBe(404); // consumed once393 app.cookie = `spmusic_session=${done.body.sessionToken}`;394 const me = await app.refreshSession();395 expect(me.authenticated).toBe(true); expect(me.user!.role).toBe("listener"); expect(app.csrf).toBe(done.body.csrfToken);396 const [row] = await sql`SELECT s.method, s.expires_at > now() + interval '60 days' AS long FROM sessions s JOIN users u ON u.id = s.user_id WHERE u.email = 'natif@example.test' AND s.method = 'device'`;397 expect(row).toMatchObject({ method: "device", long: true });398 expect((await sql`SELECT device_hash FROM device_links WHERE user_code = ${start.body.userCode}`)[0].device_hash).not.toBe(start.body.deviceCode);399 // The browser can see and revoke the device's session like any other.400 const sessions = await web.json<{ items: { id: string; method: string; userAgent: string }[] }>("/api/v1/me/sessions");401 expect(sessions.body.items.some((x) => x.method === "device")).toBe(true);402 });403404 it("refuses a denied or expired pairing and never signs in an unapproved one", async () => {405 const a = await anon.json<{ deviceCode: string; userCode: string }>("/api/v1/auth/device/start", { json: {} });406 expect((await web.json("/api/v1/auth/device/decide", { json: { userCode: a.body.userCode, approve: false } })).body).toMatchObject({ approved: false });407 expect((await anon.json("/api/v1/auth/device/poll", { json: { deviceCode: a.body.deviceCode } })).status).toBe(403);408 const b = await anon.json<{ deviceCode: string; userCode: string }>("/api/v1/auth/device/start", { json: {} });409 await sql`UPDATE device_links SET expires_at = now() - interval '1 second' WHERE user_code = ${b.body.userCode}`;410 expect((await web.json("/api/v1/auth/device/decide", { json: { userCode: b.body.userCode, approve: true } })).status).toBe(404);411 expect((await anon.json("/api/v1/auth/device/poll", { json: { deviceCode: b.body.deviceCode } })).status).toBe(410);412 expect((await anon.json("/api/v1/auth/device/poll", { json: { deviceCode: "x".repeat(43) } })).status).toBe(404);413 });414415 it("sends the whole catalogue first, with what a client needs to download and verify each file", async () => {416 expect((await anon.req("/api/v1/library/sync")).status).toBe(401);417 const full = (await app.json<Sync>("/api/v1/library/sync?since=0")).body;418 const n = (await sql`SELECT (SELECT count(*)::int FROM tracks) AS tracks, (SELECT count(*)::int FROM albums) AS albums, (SELECT count(*)::int FROM artists) AS artists`)[0];419 expect(full.more).toBe(false); expect(full.counts).toEqual({ artists: n.artists, albums: n.albums, tracks: n.tracks });420 expect(full.tracks.length).toBe(n.tracks); expect(full.albums.length).toBe(n.albums); expect(full.artists.length).toBe(n.artists);421 const t = full.tracks.find((x) => x.id === trackB)!; someTrack = t.id;422 expect(t.file!.sha256).toMatch(/^[0-9a-f]{64}$/); expect(t.file!.mime).toBe("audio/flac");423 const bytes = Buffer.from(await (await app.req(`/api/v1/stream/${t.id}`)).arrayBuffer());424 expect(bytes.length).toBe(t.file!.sizeBytes);425 expect((await import("node:crypto")).createHash("sha256").update(bytes).digest("hex")).toBe(t.file!.sha256);426 expect(full.albums.every((a) => full.artists.some((x) => x.id === a.artistId))).toBe(true);427 cursor = full.rev;428 expect((await app.json<Sync>(`/api/v1/library/sync?since=${cursor}`)).body).toMatchObject({ rev: cursor, tracks: [], albums: [], artists: [], deleted: [] });429 expect((await app.json("/api/v1/library/sync?since=-1")).status).toBe(400);430 });431432 it("then sends only what changed: edits, new files, lyrics and deletions", async () => {433 await owner.json("/api/v1/admin/tracks", { method: "PATCH", json: { ids: [someTrack], patch: { title: "Onde B (sync)" } } });434 let d = (await app.json<Sync>(`/api/v1/library/sync?since=${cursor}`)).body;435 expect(d.tracks.map((t) => [t.id, t.title])).toEqual([[someTrack, "Onde B (sync)"]]); expect(d.rev).toBeGreaterThan(cursor); cursor = d.rev;436437 const up = await owner.upload("z-sync.flac", fixture("z1.flac").subarray(0)); // same content as an indexed file → duplicate, no change438 expect(up.body.status).toBe("duplicate");439 expect((await app.json<Sync>(`/api/v1/library/sync?since=${cursor}`)).body.tracks).toEqual([]);440441 await sql`INSERT INTO lyrics (track_id, state, source, lines) VALUES (${someTrack}, 'ready', 'manual', '[]') ON CONFLICT (track_id) DO UPDATE SET state = 'ready'`;442 d = (await app.json<Sync>(`/api/v1/library/sync?since=${cursor}`)).body;443 expect(d.tracks.map((t) => [t.id, t.lyricsState])).toEqual([[someTrack, "ready"]]); cursor = d.rev;444 await sql`DELETE FROM lyrics WHERE track_id = ${someTrack}`;445 cursor = (await app.json<Sync>(`/api/v1/library/sync?since=${cursor}`)).body.rev;446447 const [victim] = await sql<{ id: string; album_id: string }[]>`SELECT t.id, t.album_id FROM tracks t JOIN albums al ON al.id = t.album_id WHERE al.title = 'Zippé' ORDER BY t.track_no LIMIT 1`;448 await owner.json("/api/v1/admin/tracks/delete", { json: { ids: [victim.id], confirm: true } });449 d = (await app.json<Sync>(`/api/v1/library/sync?since=${cursor}`)).body;450 expect(d.deleted).toContainEqual(expect.objectContaining({ kind: "track", id: victim.id }));451 expect(d.counts.tracks).toBe((await sql`SELECT count(*)::int AS n FROM tracks`)[0].n); cursor = d.rev;452 // Revisions are strictly increasing and unique across the three tables.453 const revs = await sql<{ rev: string }[]>`SELECT rev FROM artists UNION ALL SELECT rev FROM albums UNION ALL SELECT rev FROM tracks UNION ALL SELECT rev FROM library_tombstones`;454 expect(new Set(revs.map((r) => r.rev)).size).toBe(revs.length);455 });456457 it("sends an account's playlists, favourites and playback state in one answer, and only its own", async () => {458 const pl = await app.json<{ id: string; updatedAt: string }>("/api/v1/library/playlists", { json: { name: "Hors ligne", trackIds: [someTrack] } });459 expect(pl.status).toBe(200); playlistId = pl.body.id; stamp = pl.body.updatedAt;460 await app.json(`/api/v1/library/favorites/track/${someTrack}`, { method: "PUT" });461 const me = (await app.json<{ playlists: { id: string; name: string; updatedAt: string; entries: { entryId: string; trackId: string; position: number }[] }[]; favoriteTracks: { id: string }[]; favoriteAlbums: unknown[]; playback: unknown }>("/api/v1/library/sync/me")).body;462 expect(me.playlists).toHaveLength(1); expect(me.playlists[0]).toMatchObject({ id: playlistId, name: "Hors ligne", updatedAt: stamp });463 expect(me.playlists[0].entries.map((e) => e.trackId)).toEqual([someTrack]); expect(me.favoriteTracks.map((f) => f.id)).toEqual([someTrack]);464 const other = (await owner.json<{ playlists: { id: string }[] }>("/api/v1/library/sync/me")).body;465 expect(other.playlists.some((p) => p.id === playlistId)).toBe(false);466 });467468 it("refuses an offline playlist edit made on a stale copy instead of overwriting the newer one", async () => {469 await sleep(5);470 const renamed = await app.json<{ updatedAt: string }>(`/api/v1/library/playlists/${playlistId}`, { method: "PATCH", json: { name: "Renommée ailleurs" } });471 expect(new Date(renamed.body.updatedAt).getTime()).toBeGreaterThan(new Date(stamp).getTime());472 const stale = await app.json(`/api/v1/library/playlists/${playlistId}/order`, { method: "PUT", json: { entryIds: [], baseUpdatedAt: stamp } });473 expect(stale.status).toBe(409); expect(stale.body.error!.code).toBe("conflict");474 expect((await app.json(`/api/v1/library/playlists/${playlistId}`, { method: "PATCH", json: { name: "Écrasée", baseUpdatedAt: stamp } })).status).toBe(409);475 expect((await sql`SELECT count(*)::int AS n FROM playlist_tracks WHERE playlist_id = ${playlistId}`)[0].n).toBe(1); // untouched476 const fresh = await app.json<{ updatedAt: string }>(`/api/v1/library/playlists/${playlistId}/order`, { method: "PUT", json: { entryIds: [], baseUpdatedAt: renamed.body.updatedAt } });477 expect(fresh.status).toBe(200); expect(fresh.body.updatedAt).toBeTruthy();478 });479480 it("stores listening history once per event, per account", async () => {481 const ev = { id: "11111111-1111-4111-8111-111111111111", trackId: someTrack, playedAt: new Date(Date.now() - 60_000).toISOString(), listenedMs: 4200, completed: true, source: "local" };482 const gone = { ...ev, id: "22222222-2222-4222-8222-222222222222", trackId: "00000000-0000-4000-8000-000000000000" };483 expect((await app.json("/api/v1/library/history", { json: { events: [ev, gone] } })).body).toMatchObject({ stored: 1, skipped: 1 });484 expect((await app.json("/api/v1/library/history", { json: { events: [ev] } })).body).toMatchObject({ stored: 0, skipped: 1 }); // retry: no duplicate485 const h = (await app.json<{ items: { id: string; trackId: string; completed: boolean; source: string }[]; total: number }>("/api/v1/library/history")).body;486 expect(h.total).toBe(1); expect(h.items[0]).toMatchObject({ id: ev.id, trackId: someTrack, completed: true, source: "local" });487 expect((await owner.json<{ total: number }>("/api/v1/library/history")).body.total).toBe(0);488 expect((await app.json("/api/v1/library/history", { json: { events: [{ ...ev, extra: 1 }] } })).status).toBe(400);489 });490491 it("ends when the account revokes the device's session", async () => {492 const sessions = await web.json<{ items: { id: string; method: string }[] }>("/api/v1/me/sessions");493 const dev = sessions.body.items.find((x) => x.method === "device")!;494 expect((await web.json(`/api/v1/me/sessions/${dev.id}`, { method: "DELETE" })).status).toBe(200);495 expect((await app.req("/api/v1/library/sync")).status).toBe(401);496 expect((await app.req(`/api/v1/stream/${someTrack}`)).status).toBe(401);497 });498});499500describe("lyrics", () => {501 const enabled = process.env.LYRICS === "manual" && existsSync(`${process.env.TEST_FIXTURES}/speech.flac`);502 it.skipIf(!enabled)("transcribes a track with word timings, marks an instrumental as empty, and keeps hand corrections", async () => {503 const up = await owner.upload("speech.flac", fixture("speech.flac"));504 expect(up.body.status).toBe("ready");505 const id = up.body.trackId as string;506 expect((await owner.json(`/api/v1/library/tracks/${id}/lyrics`)).body).toMatchObject({ state: "none", enabled: true });507 // a listener can read lyrics but never ask for or edit them508 expect((await listener.json("/api/v1/admin/lyrics/generate", { json: { ids: [id] } })).status).toBe(403);509 expect((await listener.json(`/api/v1/admin/tracks/${id}/lyrics`, { method: "PUT", json: { lines: [] } })).status).toBe(403);510 expect((await owner.json("/api/v1/admin/lyrics/generate", { json: { ids: [id, trackB], language: "en" } })).body).toMatchObject({ queued: 2 });511 type L = { state: string; lines: { t: number; e: number; text: string; w?: [number, number, string][] }[]; edited?: boolean };512 const wait = async (tid: string) => { for (let i = 0; i < 200; i++) { const l = (await owner.json(`/api/v1/library/tracks/${tid}/lyrics`)).body as unknown as L; if (!["queued", "working"].includes(l.state)) return l; await sleep(500); } throw new Error("lyrics timeout"); };513 const spoken = await wait(id);514 expect(spoken.state).toBe("ready");515 const all = spoken.lines.map((l) => l.text).join(" ").toLowerCase();516 expect(all).toContain("fox"); expect(all).toContain("cluster");517 const words = spoken.lines.flatMap((l) => l.w ?? []);518 expect(words.length).toBeGreaterThan(8);519 for (let i = 1; i < words.length; i++) expect(words[i][0]).toBeGreaterThanOrEqual(words[i - 1][0]); // monotonic timings520 expect(spoken.lines[0].t).toBeLessThan(2000);521 expect((await wait(trackB)).state).toBe("empty"); // a sine wave has no words522 expect(((await listener.json(`/api/v1/library/tracks/${id}/lyrics`)).body as unknown as L).state).toBe("ready");523 expect(((await owner.json(`/api/v1/library/tracks/${id}`)).body as unknown as { lyricsState: string }).lyricsState).toBe("ready");524 // correction by hand: unchanged lines keep their word timings, the edited one loses them525 const edited = spoken.lines.map((l, i) => ({ t: l.t, e: l.e, text: i === 0 ? "Texte corrigé" : l.text }));526 expect((await owner.json(`/api/v1/admin/tracks/${id}/lyrics`, { method: "PUT", json: { lines: edited } })).status).toBe(200);527 const after = (await owner.json(`/api/v1/library/tracks/${id}/lyrics`)).body as unknown as L;528 expect(after.edited).toBe(true); expect(after.lines[0].text).toBe("Texte corrigé"); expect(after.lines[0].w).toBeUndefined();529 if (after.lines.length > 1) expect(after.lines[1].w!.length).toBeGreaterThan(0);530 // regenerating does not overwrite a correction unless asked to531 expect((await owner.json("/api/v1/admin/lyrics/generate", { json: { ids: [id] } })).body).toMatchObject({ queued: 0, skipped: 1 });532 expect((await owner.json(`/api/v1/admin/tracks/${id}/lyrics`, { method: "DELETE" })).status).toBe(200);533 expect((await owner.json(`/api/v1/library/tracks/${id}/lyrics`)).body).toMatchObject({ state: "none" });534 });535 it.skipIf(enabled)("is skipped: no local mlx-whisper virtualenv", () => { console.warn("lyrics tests skipped (LYRICS_PYTHON not available)"); });536});537