Files
UHD_Media_Tool/apps/server/src/modules/agent/http.ts
T
rootandClaude Opus 5.5 f48e1aac96 fix(security): W4-E1 approvals admin-session only, shared redact table, TMDB key redaction, prod mock gate
- POST /approvals and PATCH /approvals/{id} require a console admin session
  (EndpointDef auth:"session"); API keys incl. admin scope get 403, so an
  organize.execute key can no longer approve its own plan (S1)
- tests for single-use approval checks: expired, revision/payload hash
  mismatch, consumed, revoked, pending/rejected, plan mismatch; re-approve
  after plan change succeeds once and cannot be replayed (S4)
- one redact key table in @umt/contracts shared by server logger and agent
  redactForModel: rsskey, torrent_pass, authkey, downhash, c_secure_pass,
  passkey variants, x-api-key, cookie headers, nested objects/arrays (S2)
- TMDB network errors: message and cause redacted via redactUrl (S3)
- web Agent ?mock=1 only in DEV builds or when pi.provider is fake (S7)
- EndpointDef auth annotations for /auth/*, asserted against
  PUBLIC_AUTH_PATHS (S10); doc drift fixes (S11)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-27 22:24:44 +08:00

73 lines
2.9 KiB
TypeScript

import { createRoute, type RouteConfig } from "@hono/zod-openapi";
import { type Actor, type ApiScope, apiResponse, type EndpointDef } from "@umt/contracts";
import type { Context } from "hono";
import type { z } from "zod";
import { type AuthEnv, requireAdminSession, requireScope } from "../../http/auth.ts";
import type { ModuleApp } from "../types.ts";
// 本模块路由封装:吃 contracts 的 EndpointDef(Api.xxx),createRoute 进 OpenAPI + requireScope + 入参校验,
// 出参按合同 parse(剥掉多余列)。
// crud() 生成的端点 schema 类型被擦成 z.ZodType(输出 unknown):这时退化为 any,处理器按合同自行使用
// biome-ignore lint/suspicious/noExplicitAny: 见上
type Loose<O> = unknown extends O ? any : O;
type Infer<T> = T extends z.ZodType ? Loose<z.infer<T>> : Record<string, never>;
export interface Input<D extends EndpointDef> {
params: Infer<D["params"]>;
query: Infer<D["query"]>;
body: Infer<D["body"]>;
actor: Actor;
/** 能力/审计用的调用者 ID:管理员会话 user:<id>,API Key api_key:<id> */
actorId: string;
c: Context<AuthEnv>;
}
export function actorIdOf(a: Actor | undefined): string {
if (!a) return "system:unknown";
return `${a.type === "api_key" ? "api_key" : "user"}:${a.id ?? a.name ?? "?"}`;
}
export function route<D extends EndpointDef>(
app: ModuleApp,
def: D,
handler: (input: Input<D>) => Promise<unknown>,
opts: { tag?: string; status?: 200 | 201 } = {},
) {
const request: RouteConfig["request"] = {};
if (def.params) request.params = def.params as never;
if (def.query) request.query = def.query as never;
if (def.body) request.body = { content: { "application/json": { schema: def.body as never } }, required: true };
const status = opts.status ?? 200;
const r = createRoute({
method: def.method,
path: def.path,
summary: def.summary,
tags: [opts.tag ?? "agent"],
// auth: "session" 的端点(审批申请/决定)在 scope 之外再要求控制台管理员会话,API Key 一律 403
middleware: [
requireScope(def.scope as ApiScope),
...(def.auth === "session" ? [requireAdminSession()] : []),
] as never,
request,
responses: {
[status]: { description: def.summary, content: { "application/json": { schema: apiResponse(def.response) } } },
},
});
// biome-ignore lint/suspicious/noExplicitAny: 路由泛型在封装里擦除,入参已由 zod-openapi 校验
app.openapi(r, (async (c: any) => {
const actor = c.get("actor") as Actor | undefined;
const input = {
params: def.params ? c.req.valid("param") : {},
query: def.query ? c.req.valid("query") : {},
body: def.body ? c.req.valid("json") : {},
actor,
actorId: actorIdOf(actor),
c,
} as Input<D>;
const data = def.response.parse(await handler(input));
return c.json({ ok: true, data }, status);
// biome-ignore lint/suspicious/noExplicitAny: 同上
}) as any);
}