Files
STCourses/packages/core/test/media.test.ts
T
Lucas WintherandClaude Opus 5.5 777ae2cc37 feat: resolve Phase 1 contract requests and compose every feature
Contracts and core:
- Feature gains auth and stop; FeatureFactory; core composeServer builds the
  context, runs the factories, then the job queue from the union of their jobs
  (R8/R14). startServer uses it; main.ts composes learner, import, studio, AI.
- AppConfig/loadConfig own the layout and settings: courseDirs include
  <dataDir>/courses and <dataDir>/worktrees, studioReposDir, cacheDir,
  importRoots, uploadMaxMb, aiAllowedBaseUrls, transcribeUrl, python.
  resolveConfig derives the same for tests; cachePaths shares the importer's
  cache layout.
- canView: the global author role views every course (R14); the learner,
  studio and AI packages all call it.
- migrate(db, packages): core first, then packages in name order.
- Media: nosniff on every response, a sandbox CSP on svg/html/js; a Range on
  an empty file is 416.
- courseUrl/lessonUrl and the lesson route patterns live in @stc/contracts.

Packages:
- import, studio and AI read AppConfig instead of process.env; the importer
  refuses ids used by studio/repos.
- learner migrations run through core migrate; library covers fall back to
  the importer's cached candidate behind a canView-checked route.
- studio preview renders through the learner LessonView (anchors honoured,
  draft URLs); AI drafts go to the studio draft branch for studio courses (as
  the requesting user) and to <dataDir>/drafts otherwise, and the generator
  page says which.

Web: tsconfig paths for @stc/<feature>/web browser entries; features.ts
imports them by package name; nav.roles hides links by role.

Tests: compose, config, canView, media headers, migrations order, covers,
preview, nav, SPA bundle without server code, and an end-to-end flow on
SQLite and Postgres.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:02:46 +01:00

93 lines
3.9 KiB
TypeScript

import { expect, test } from "bun:test";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { serveMedia } from "../src";
const dir = mkdtempSync(join(tmpdir(), "stc-media-"));
const file = join(dir, "clip.mp4");
const bytes = new Uint8Array(1000).map((_, i) => i % 251);
writeFileSync(file, bytes);
const req = (range?: string) => new Request("http://x/m", { headers: range ? { Range: range } : {} });
test("full file gives 200", async () => {
const r = await serveMedia(req(), file);
expect(r.status).toBe(200);
expect(r.headers.get("content-type")).toBe("video/mp4");
expect(r.headers.get("accept-ranges")).toBe("bytes");
expect(r.headers.get("content-length")).toBe("1000");
expect((await r.arrayBuffer()).byteLength).toBe(1000);
});
test("bytes=0-99 gives 206 with Content-Range", async () => {
const r = await serveMedia(req("bytes=0-99"), file);
expect(r.status).toBe(206);
expect(r.headers.get("content-range")).toBe("bytes 0-99/1000");
expect(r.headers.get("content-length")).toBe("100");
expect(new Uint8Array(await r.arrayBuffer())).toEqual(bytes.slice(0, 100));
});
test("open-ended, suffix and clamped ranges", async () => {
let r = await serveMedia(req("bytes=900-"), file);
expect(r.status).toBe(206);
expect(r.headers.get("content-range")).toBe("bytes 900-999/1000");
r = await serveMedia(req("bytes=-10"), file);
expect(r.headers.get("content-range")).toBe("bytes 990-999/1000");
expect(new Uint8Array(await r.arrayBuffer())).toEqual(bytes.slice(990));
r = await serveMedia(req("bytes=990-5000"), file);
expect(r.headers.get("content-range")).toBe("bytes 990-999/1000");
});
test("unsatisfiable range gives 416", async () => {
const r = await serveMedia(req("bytes=999999999-"), file);
expect(r.status).toBe(416);
expect(r.headers.get("content-range")).toBe("bytes */1000");
});
test("non-ASCII filename gets a valid filename*", async () => {
const f = join(dir, "Æble notes.pdf");
writeFileSync(f, "pdf");
const r = await serveMedia(req(), f, { download: true });
expect(r.headers.get("content-type")).toBe("application/pdf");
const cd = r.headers.get("content-disposition")!;
expect(cd).toContain("filename*=UTF-8''%C3%86ble%20notes.pdf");
expect(cd).toContain('filename="_ble notes.pdf"');
});
test("missing file is 404", async () => {
expect((await serveMedia(req(), join(dir, "nope.mp4"))).status).toBe(404);
});
test("every response is nosniff; script-capable types get a sandbox CSP", async () => {
const d = mkdtempSync(join(tmpdir(), "stc-media-csp-"));
const { MEDIA_SANDBOX_CSP } = await import("../src");
for (const [name, body, sandboxed] of [
["x.svg", "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>", true],
["page.html", "<script>alert(1)</script>", true],
["Page.HTM", "<p>x</p>", true],
["code.js", "alert(1)", true],
["mod.mjs", "export {}", true],
["notes.md", "# hi", false],
["clip.mp4", "x", false],
] as const) {
writeFileSync(join(d, name), body);
for (const r of [await serveMedia(req(), join(d, name)), await serveMedia(req("bytes=0-0"), join(d, name))]) {
expect(r.headers.get("x-content-type-options")).toBe("nosniff");
expect([name, r.headers.get("content-security-policy")]).toEqual([name, sandboxed ? MEDIA_SANDBOX_CSP : null]);
}
}
expect(MEDIA_SANDBOX_CSP).toMatch(/^sandbox;/);
expect(MEDIA_SANDBOX_CSP).not.toContain("allow-scripts");
});
test("a range on an empty file is 416, never a negative Content-Range", async () => {
const d = mkdtempSync(join(tmpdir(), "stc-media-empty-"));
writeFileSync(join(d, "empty.txt"), "");
for (const range of ["bytes=0-", "bytes=-5", "bytes=0-0"]) {
const r = await serveMedia(req(range), join(d, "empty.txt"));
expect(r.status).toBe(416);
expect(r.headers.get("content-range")).toBe("bytes */0");
}
expect((await serveMedia(req(), join(d, "empty.txt"))).status).toBe(200);
});