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]>
110 lines
5.7 KiB
TypeScript
110 lines
5.7 KiB
TypeScript
import { expect, test } from "bun:test";
|
|
import { cpSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join, resolve } from "node:path";
|
|
import type { AuthUser, Feature, ServerContext } from "@stc/contracts";
|
|
import { createCourseRepository } from "@stc/course-format";
|
|
import { connect, migrate } from "@stc/db";
|
|
import { canView, createApp } from "../src";
|
|
|
|
const SAMPLE = resolve(import.meta.dir, "../../../fixtures/courses/sample");
|
|
|
|
async function setup(user: AuthUser | null = null) {
|
|
const dir = mkdtempSync(join(tmpdir(), "stc-app-"));
|
|
cpSync(SAMPLE, join(dir, "pub"), { recursive: true });
|
|
const manifest = await Bun.file(join(SAMPLE, "stcourse.yaml")).text();
|
|
mkdirSync(join(dir, "priv"));
|
|
cpSync(SAMPLE, join(dir, "priv"), { recursive: true });
|
|
writeFileSync(join(dir, "priv/stcourse.yaml"), manifest.replace("id: sample", "id: secret").replace("visibility: public", "visibility: restricted"));
|
|
mkdirSync(join(dir, "broken"));
|
|
writeFileSync(join(dir, "broken/stcourse.yaml"), "schema: 1\nid: broken\ntitle: Broken\nroot: /does/not/exist\nmodules: []\n");
|
|
symlinkSync("/etc", join(dir, "pub/escape"));
|
|
const db = await connect("sqlite://:memory:");
|
|
await migrate(db);
|
|
const courses = await createCourseRepository([dir]);
|
|
const ctx = { db, courses, auth: { userFromRequest: async () => user } } as unknown as ServerContext;
|
|
return { ctx, db, dir };
|
|
}
|
|
const feat = (name: string): Feature => ({ name, routes: { "/api/x": { GET: () => new Response(name) } } });
|
|
const user = (over: Partial<AuthUser> = {}): AuthUser => ({ id: "u1", email: "u@x", name: "U", roles: ["learner"], groups: [], ...over });
|
|
|
|
test("health ok, and an error course does not break it", async () => {
|
|
const { ctx, db } = await setup();
|
|
expect(ctx.courses.get("broken")?.status).toBe("error");
|
|
const app = createApp(ctx, []);
|
|
const r = await app.fetch(new Request("http://x/api/health"));
|
|
expect(r.status).toBe(200);
|
|
expect(await r.json()).toEqual({ ok: true, courses: ctx.courses.list().length, db: "sqlite" });
|
|
expect(ctx.courses.list().length).toBe(3);
|
|
await db.close();
|
|
});
|
|
|
|
test("media serves a file with Range, and a missing/broken course is 404", async () => {
|
|
const { ctx, db } = await setup();
|
|
const app = createApp(ctx, []);
|
|
const r = await app.fetch(new Request("http://x/api/media/sample/media/clip.mp4", { headers: { Range: "bytes=0-9" } }));
|
|
expect(r.status).toBe(206);
|
|
expect((await app.fetch(new Request("http://x/api/media/broken/anything"))).status).toBe(404);
|
|
expect((await app.fetch(new Request("http://x/api/media/nope/a"))).status).toBe(404);
|
|
await db.close();
|
|
});
|
|
|
|
test("traversal, absolute and symlink escapes are 404", async () => {
|
|
const { ctx, db } = await setup();
|
|
const app = createApp(ctx, []);
|
|
for (const p of ["..%2F..%2Fetc%2Fpasswd", "%2Fetc%2Fpasswd", "escape/passwd", "../priv/stcourse.yaml", "%E0%A4%A"]) {
|
|
const r = await app.fetch(new Request(`http://x/api/media/sample/${p}`));
|
|
expect(r.status).toBe(404);
|
|
}
|
|
await db.close();
|
|
});
|
|
|
|
test("restricted course: 404 anonymous, visible to owner, author, ACL user and group", async () => {
|
|
const url = "http://x/api/media/secret/media/clip.mp4";
|
|
const run = async (u: AuthUser | null, seed?: (db: Awaited<ReturnType<typeof setup>>["db"]) => Promise<unknown>) => {
|
|
const { ctx, db } = await setup(u);
|
|
await seed?.(db);
|
|
const s = (await createApp(ctx, []).fetch(new Request(url))).status;
|
|
await db.close();
|
|
return s;
|
|
};
|
|
expect(await run(null)).toBe(404);
|
|
expect(await run(user())).toBe(404);
|
|
expect(await run(user({ roles: ["owner"] }))).toBe(200);
|
|
expect(await run(user(), (db) => db.sql`INSERT INTO course_authors (course_id, user_id) VALUES ('secret', 'u1')`)).toBe(200);
|
|
expect(await run(user(), (db) => db.sql`INSERT INTO course_acl VALUES ('secret', 'user', 'u1')`)).toBe(200);
|
|
expect(await run(user({ groups: ["g"] }), (db) => db.sql`INSERT INTO course_acl VALUES ('secret', 'group', 'g')`)).toBe(200);
|
|
expect(await run(user({ groups: ["h"] }), (db) => db.sql`INSERT INTO course_acl VALUES ('secret', 'group', 'g')`)).toBe(404);
|
|
});
|
|
|
|
test("duplicate method+path across features throws", async () => {
|
|
const { ctx, db } = await setup();
|
|
expect(() => createApp(ctx, [feat("a"), feat("b")])).toThrow(/Duplicate route GET \/api\/x/);
|
|
await db.close();
|
|
});
|
|
|
|
test("feature routes receive RequestContext with the user", async () => {
|
|
const u = user();
|
|
const { ctx, db } = await setup(u);
|
|
const f: Feature = { name: "a", routes: { "/api/who/:id": { GET: (_r, rc) => Response.json({ u: rc.user?.id, id: rc.params.id }) } } };
|
|
const app = createApp(ctx, [f]);
|
|
expect(await (await app.fetch(new Request("http://x/api/who/42"))).json()).toEqual({ u: "u1", id: "42" });
|
|
await db.close();
|
|
});
|
|
|
|
test("canView matrix", async () => {
|
|
const { ctx, db } = await setup();
|
|
const pub = ctx.courses.get("sample")!, priv = ctx.courses.get("secret")!;
|
|
expect(canView(null, pub, [])).toBe(true);
|
|
expect(canView(null, priv, [])).toBe(false);
|
|
const u = (roles: AuthUser["roles"], groups: string[] = []): AuthUser => ({ id: "u1", email: "u@x", name: "U", roles, groups });
|
|
expect(canView(u(["learner"]), priv, [])).toBe(false);
|
|
expect(canView(u(["owner"]), priv, [])).toBe(true);
|
|
expect(canView(u(["author"]), priv, [])).toBe(true); // R14: the global author role views every course
|
|
expect(canView(u(["learner"]), priv, [], true)).toBe(true); // per-course author
|
|
expect(canView(u(["learner"]), priv, [{ principal_type: "user", principal_id: "u1" }])).toBe(true);
|
|
expect(canView(u(["learner"], ["g"]), priv, [{ principal_type: "group", principal_id: "g" }])).toBe(true);
|
|
expect(canView(u(["learner"], ["h"]), priv, [{ principal_type: "group", principal_id: "g" }])).toBe(false);
|
|
await db.close();
|
|
});
|