chore: scaffold monorepo and migrate uhd_web design system (W0-A)

- 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]>
This commit is contained in:
umtandClaude Fable 5.1 committed 2026-09-27 17:36:26 +08:00
commit b22c440139
138 files changed
+14455

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
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);
});
});
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { json, testApp } from "./helpers";
describe("GET /api/v1/health", () => {
it("免鉴权返回 ok 信封", async () => {
const { app } = testApp();
const res = await app.request("/api/v1/health");
expect(res.status).toBe(200);
const body = await json(res);
expect(body.ok).toBe(true);
expect(body.data.status).toBe("ok");
expect(body.data.db).toBe("unknown");
expect(body.data.role).toBe("all");
});
it("未知路由返回 not_found 信封", async () => {
const { app } = testApp();
const res = await app.request("/nope");
expect(res.status).toBe(404);
expect((await json(res)).error.code).toBe("not_found");
});
it("OpenAPI 文档包含 health", async () => {
const { app } = testApp();
const doc = await json(await app.request("/api/openapi.json"));
expect(doc.paths["/api/v1/health"]).toBeDefined();
});
});
+49
View File
@@ -0,0 +1,49 @@
import { Writable } from "node:stream";
import { createApp } from "../src/http/app";
import { type ApiKeyStore, hashApiKey } from "../src/http/auth";
import { EventBus } from "../src/http/sse";
import { createLogger } from "../src/logger";
export const DEV_KEY = "dev-admin-test-key";
/** 收集日志行 */
export function memoryLogger() {
const lines: string[] = [];
const dest = new Writable({
write(chunk, _enc, cb) {
lines.push(chunk.toString());
cb();
},
});
return { logger: createLogger({ level: "info", destination: dest }), lines };
}
/** 内存 API Key 仓库 */
export function memoryStore(keys: Record<string, { id: string; scopes: string[]; revoked?: boolean }>): ApiKeyStore {
const byHash = new Map(Object.entries(keys).map(([k, v]) => [hashApiKey(k), v]));
return {
async findByHash(h) {
const v = byHash.get(h);
return v ? { id: v.id, name: v.id, scopes: v.scopes, revokedAt: v.revoked ? new Date() : null } : null;
},
async touch() {},
};
}
export function testApp(opts: { nodeEnv?: "development" | "production"; store?: ApiKeyStore } = {}) {
const bus = new EventBus(5);
const { logger, lines } = memoryLogger();
const app = createApp({
config: { NODE_ENV: opts.nodeEnv ?? "development", DEV_ADMIN_KEY: DEV_KEY },
logger,
bus,
role: "all",
version: "0.0.0-test",
...(opts.store ? { apiKeyStore: opts.store } : {}),
});
return { app, bus, lines };
}
/** 读取 JSON 响应体(测试里不做类型收窄) */
// biome-ignore lint/suspicious/noExplicitAny: 测试断言用
export const json = (res: Response): Promise<any> => res.json();
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { redact, redactString } from "../src/logger";
import { memoryLogger } from "./helpers";
describe("日志脱敏", () => {
it("URL query 中的 passkey/token 被替换", () => {
expect(redactString("https://pt.example/rss?passkey=abc123&x=1")).toBe(
"https://pt.example/rss?passkey=[REDACTED]&x=1",
);
expect(redactString("/dl?id=1&token=zzz")).toBe("/dl?id=1&token=[REDACTED]");
});
it("敏感字段整体替换,数值计数保留", () => {
expect(redact({ cookie: "a=b", nested: { Authorization: "Bearer x", password: "p" }, inputTokens: 12 })).toEqual({
cookie: "[REDACTED]",
nested: { Authorization: "[REDACTED]", password: "[REDACTED]" },
inputTokens: 12,
});
});
it("logger 输出不含明文", () => {
const { logger, lines } = memoryLogger();
logger.info({ url: "https://x/rss?passkey=SECRET1", token: "SECRET2" }, "fetch https://y/?token=SECRET3");
logger.error({ err: new Error("GET https://x/dl?passkey=SECRET4 failed") }, "boom");
const out = lines.join("");
for (const s of ["SECRET1", "SECRET2", "SECRET3", "SECRET4"]) expect(out).not.toContain(s);
});
});
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { EventBus } from "../src/http/sse";
import { DEV_KEY, testApp } from "./helpers";
describe("EventBus", () => {
it("序号自增并按 after 补读,淘汰后标记 gap", () => {
const bus = new EventBus(3);
for (let i = 0; i < 5; i++) bus.publish("t", { i });
expect(bus.latestSeq).toBe(5);
expect(bus.since(3).events.map((e) => e.seq)).toEqual([4, 5]);
expect(bus.since(3).gap).toBe(false);
expect(bus.since(1).gap).toBe(true);
});
});
describe("GET /api/v1/events", () => {
it("需要鉴权", async () => {
const { app } = testApp();
expect((await app.request("/api/v1/events")).status).toBe(401);
});
it("补读 after 之后的事件", async () => {
const { app, bus } = testApp();
bus.publish("a", 1);
bus.publish("b", 2);
const ac = new AbortController();
const res = await app.request("/api/v1/events?after=1", {
headers: { Authorization: `Bearer ${DEV_KEY}` },
signal: ac.signal,
});
expect(res.headers.get("content-type")).toContain("text/event-stream");
const reader = res.body!.getReader();
const { value } = await reader.read();
const text = new TextDecoder().decode(value);
expect(text).toContain("id: 2");
expect(text).toContain("event: b");
expect(text).not.toContain("event: a");
ac.abort();
await reader.cancel();
});
});