- root deno.json workspace (nodeModulesDir auto), npm versions registered once in imports, deno.lock; remove pnpm-lock/pnpm-workspace/root package.json; members keep minimal package.json (name/type/exports) - tasks: dev, typecheck (tsc 7.0.2 per member + deno check), lint/fmt (biome, useImportExtensions), test (vitest via deno), check:tokens, build (web + deno compile), ci, db:migrate/reset, gen:types - tsconfig base moved to config/ (no root tsconfig.json); deno types -> types/deno.d.ts; web drops baseUrl - server: Deno.serve entry with graceful shutdown, --role migrate|preflight|probe, WEB_ROOT static SPA hosting; drop @hono/node-server, tsx, esbuild build.mjs - logger: redact child() bindings and serialize err by message/stack; sync stdout destination; tests - relative imports get explicit extensions (sites/mp-sync paths left for follow-up) - crash-recovery tests spawn `deno run -A`; tasks tests use unique per-file schemas - single-container Dockerfile + entrypoint (migrate -> preflight -> api+worker watchdog), docker-compose.yml - docs: README, runbook, ADR-001 superseded, plan §1 validation row Co-Authored-By: Claude Fable 5.1 <[email protected]>
120 lines
4.0 KiB
TypeScript
120 lines
4.0 KiB
TypeScript
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.ts";
|
|
import { isDev } from "../config.ts";
|
|
import { redactString } from "../logger.ts";
|
|
import { type ApiKeyStore, type AuthEnv, apiKeyAuth, kyselyApiKeyStore, requireScope } from "./auth.ts";
|
|
import { ApiException, errorBody } from "./errors.ts";
|
|
import { healthRoutes } from "./routes/health.ts";
|
|
import { mountOpenApi } from "./routes/openapi.ts";
|
|
import { type EventBus, sseRoutes } from "./sse.ts";
|
|
import { mountWebRoot } from "./static.ts";
|
|
|
|
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;
|
|
/** 单容器模式:托管 web 静态产物的目录 */
|
|
webRoot?: string;
|
|
}
|
|
|
|
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 } });
|
|
});
|
|
|
|
if (deps.webRoot) mountWebRoot(app, deps.webRoot);
|
|
|
|
return app;
|
|
}
|
|
export type App = ReturnType<typeof createApp>;
|