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

+114
View File
@@ -0,0 +1,114 @@
import { OpenAPIHono } from "@hono/zod-openapi";
import type { DB } from "@umt/db";
import { type Kysely, sql } from "@umt/db";
import { cors } from "hono/cors";
import { HTTPException } from "hono/http-exception";
import { requestId } from "hono/request-id";
import type { Logger } from "pino";
import type { Config } from "../config";
import { isDev } from "../config";
import { redactString } from "../logger";
import { type ApiKeyStore, type AuthEnv, apiKeyAuth, kyselyApiKeyStore, requireScope } from "./auth";
import { ApiException, errorBody } from "./errors";
import { healthRoutes } from "./routes/health";
import { mountOpenApi } from "./routes/openapi";
import { type EventBus, sseRoutes } from "./sse";
export interface AppDeps {
config: Pick<Config, "NODE_ENV" | "DEV_ADMIN_KEY">;
logger: Logger;
bus: EventBus;
version: string;
role: "api" | "worker" | "all";
startedAt?: number;
db?: Kysely<DB>;
/** 测试可注入;默认用 db 构造 */
apiKeyStore?: ApiKeyStore;
}
export const API_PREFIX = "/api/v1";
export function createApp(deps: AppDeps) {
const { config, logger, bus, db } = deps;
const dev = isDev(config);
const app = new OpenAPIHono<AuthEnv>({
// zod 校验失败统一成 validation_failed 信封
defaultHook: (result, c) => {
if (!result.success) {
const msg = result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
return c.json(errorBody("validation_failed", msg), 422);
}
},
});
app.use("*", requestId());
// 访问日志:路径中的 passkey/token 参数脱敏
app.use("*", async (c, next) => {
const t0 = performance.now();
await next();
logger.info(
{
reqId: c.get("requestId"),
method: c.req.method,
url: redactString(c.req.url.replace(/^https?:\/\/[^/]+/, "")),
status: c.res.status,
ms: Math.round(performance.now() - t0),
},
"http",
);
});
if (dev) {
app.use("/api/*", cors({ origin: ["http://localhost:5180", "http://127.0.0.1:5180"], credentials: true }));
}
app.onError((err, c) => {
if (err instanceof ApiException) return c.json(errorBody(err.code, err.message), err.status as 400);
if (err instanceof HTTPException) {
const code = err.status === 401 ? "unauthorized" : err.status === 404 ? "not_found" : "bad_request";
return c.json(errorBody(code, err.message), err.status);
}
logger.error({ err, reqId: c.get("requestId") }, "unhandled error");
return c.json(errorBody("internal", "服务器内部错误"), 500);
});
app.notFound((c) => c.json(errorBody("not_found", `未找到 ${c.req.method} ${c.req.path}`), 404));
// ── 免鉴权 ──
app.route(
API_PREFIX,
healthRoutes({
version: deps.version,
role: deps.role,
startedAt: deps.startedAt ?? Date.now(),
...(db
? {
pingDb: async () => {
await sql`select 1`.execute(db);
return true;
},
}
: {}),
}),
);
mountOpenApi(app, deps.version);
// ── 需鉴权:/api/v1 下除 health 外全部 ──
const store = deps.apiKeyStore ?? (db ? kyselyApiKeyStore(db) : null);
const auth = apiKeyAuth({ store, devAdminKey: dev ? config.DEV_ADMIN_KEY : undefined });
app.use(`${API_PREFIX}/*`, async (c, next) => {
if (c.req.path === `${API_PREFIX}/health`) return next();
return auth(c, next);
});
app.use(`${API_PREFIX}/events`, requireScope("read"));
app.route(API_PREFIX, sseRoutes({ bus }));
// 鉴权自检:返回当前调用者
app.get(`${API_PREFIX}/auth/whoami`, requireScope("read"), (c) => {
const p = c.get("principal");
return c.json({ ok: true, data: { id: p.id, name: p.name, kind: p.kind, scopes: p.scopes } });
});
return app;
}
export type App = ReturnType<typeof createApp>;