- pnpm workspace: apps/{web,server}, packages/{contracts,db,domain,adapters,tasks,agent,testkit}
- server: Hono + zod-openapi, API Key auth with scopes, redacting pino logger, SSE event bus with replay, worker heartbeat
- db: Kysely + pg, file migrator, 0001_init (settings/api_key/audit_event/outbox_event)
- web: React Router 7 SPA console shell with 12 workspace placeholders, uhd_web tokens/ui/guard scripts
- docs: ADR-001 (Node over Deno), dev runbook, design system rules
Co-Authored-By: Claude Fable 5.1 <[email protected]>
50 lines
1.9 KiB
TypeScript
50 lines
1.9 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import { hasScope } from "../src/http/auth";
|
|
import { DEV_KEY, json, memoryStore, testApp } from "./helpers";
|
|
|
|
const store = memoryStore({
|
|
"key-read": { id: "k1", scopes: ["read"] },
|
|
"key-org": { id: "k2", scopes: ["organize.execute"] },
|
|
"key-revoked": { id: "k3", scopes: ["admin"], revoked: true },
|
|
});
|
|
const whoami = (app: ReturnType<typeof testApp>["app"], key?: string) =>
|
|
app.request("/api/v1/auth/whoami", key ? { headers: { Authorization: `Bearer ${key}` } } : {});
|
|
|
|
describe("API Key 鉴权", () => {
|
|
it("缺少 Key → 401", async () => {
|
|
const res = await whoami(testApp({ store }).app);
|
|
expect(res.status).toBe(401);
|
|
expect((await json(res)).error.code).toBe("unauthorized");
|
|
});
|
|
|
|
it("有效 Key 通过,返回 principal", async () => {
|
|
const res = await whoami(testApp({ store }).app, "key-read");
|
|
expect(res.status).toBe(200);
|
|
expect((await json(res)).data.id).toBe("k1");
|
|
});
|
|
|
|
it("未知或已撤销 Key → 401", async () => {
|
|
const { app } = testApp({ store });
|
|
expect((await whoami(app, "bogus")).status).toBe(401);
|
|
expect((await whoami(app, "key-revoked")).status).toBe(401);
|
|
});
|
|
|
|
it("scope 不足 → 403", async () => {
|
|
const res = await whoami(testApp({ store }).app, "key-org");
|
|
expect(res.status).toBe(403);
|
|
expect((await json(res)).error.code).toBe("forbidden");
|
|
});
|
|
|
|
it("开发模式 DEV_ADMIN_KEY 可用,生产模式不可用", async () => {
|
|
expect((await whoami(testApp({ store }).app, DEV_KEY)).status).toBe(200);
|
|
expect((await whoami(testApp({ store, nodeEnv: "production" }).app, DEV_KEY)).status).toBe(401);
|
|
});
|
|
|
|
it("scope 蕴含关系", () => {
|
|
expect(hasScope(["admin"], "organize.execute")).toBe(true);
|
|
expect(hasScope(["organize.execute"], "organize.read")).toBe(true);
|
|
expect(hasScope(["organize.read"], "organize.execute")).toBe(false);
|
|
expect(hasScope(["read"], "organize.read")).toBe(false);
|
|
});
|
|
});
|