feat(server): W2-A login gate, secrets, settings, instances, audit, engine panel API and PG-backed SSE bus
- Admin login gate (docs/design/auth-reference.md): admin_user/admin_session/login_attempt
(migration 0015), one-time setup token logged once + conditional UPDATE, argon2id via
hash-wasm (WASM; compiled binary has no --allow-ffi), sha256-stored sessions in HttpOnly
SameSite=Lax cookie umt_session (fixed 12h TTL, soft revoke), HMAC-derived double-submit
CSRF, IP (5) + account (15) failure limits per 15 min, password change revokes other
sessions, optional TOTP with replay counter, AuditAction enum.
- Unified auth middleware: cookie session or Bearer API key -> c.var.actor
{type: admin|api_key, id, name, scopes}; requireScope works for both; requireAdminSession.
- ctx.secrets: AES-256-GCM, per-secret HKDF-SHA256 key from SECRET_MASTER_KEY, AAD bound
to (id, purpose); ctx.settings: 30s cache invalidated by settings.changed events.
- Endpoints: /auth/*, /settings, /api-keys, /secrets, /audit-events, library-roots,
downloader/media-server instances (+test), path-mappings (+verify),
PUT /sites/{id}/credentials, /engine/runs|stats|cancel (read-only openworkflow schema).
- SSE: PgEventBus (sse_event table, migration 0016, LISTEN/NOTIFY umt_events, catch-up by
seq, pruning, resync); EventBusPort is now async.
- Tests: login/rate limit/revocation/CSRF/TOTP, secrets round trip and no log leakage,
admin APIs against mock qB/Emby, SSE across two Deno subprocesses.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
07db0dac5b
commit
ff230e5da7
34 files changed
+4363
-78
No files matched your search
@@ -0,0 +1,73 @@
|
||||
import { Api, GlobalSettings, type GlobalSettingsUpdate, mergeSettings, type SettingsKey } from "@umt/contracts";
|
||||
import { ApiException } from "../../http/errors.ts";
|
||||
import type { ModuleApp, ServerContext } from "../types.ts";
|
||||
import { audit, endpoint } from "./endpoint.ts";
|
||||
import { type CachedSettingsReader, SETTINGS_CHANGED_EVENT } from "./provided.ts";
|
||||
|
||||
// GET/PATCH /settings:按分组部分更新 → mergeSettings → GlobalSettings 整体校验 → 逐组 upsert;
|
||||
// Pi 上游密钥(pi.apiKey 只写)存为 secret,设置里只留 apiKeySecretRef;变更经 SSE 总线广播 settings.changed,
|
||||
// 各进程的 ctx.settings 缓存随之失效。自动化总开关 automation.enabled / 只读对账 automation.readOnlyReconcile 也走这里。
|
||||
|
||||
const isCached = (s: unknown): s is CachedSettingsReader =>
|
||||
typeof (s as CachedSettingsReader)?.invalidate === "function";
|
||||
|
||||
export function registerSettingsRoutes(app: ModuleApp, ctx: ServerContext) {
|
||||
endpoint(app, { ...Api.settings.get, tags: ["settings"] }, async () => {
|
||||
if (isCached(ctx.settings)) return await ctx.settings.fresh();
|
||||
return await ctx.settings.all();
|
||||
});
|
||||
|
||||
endpoint(app, { ...Api.settings.update, tags: ["settings"] }, async ({ body, actor }) => {
|
||||
const patch = body as GlobalSettingsUpdate;
|
||||
const current = isCached(ctx.settings) ? await ctx.settings.fresh() : await ctx.settings.all();
|
||||
const merged = mergeSettings(current, patch);
|
||||
const oldRef = current.pi.apiKeySecretRef;
|
||||
let dropRef: string | null = null;
|
||||
let newRef: string | null = null;
|
||||
const apiKey = patch.pi?.apiKey;
|
||||
if (apiKey === null) {
|
||||
merged.pi.apiKeySecretRef = null;
|
||||
dropRef = oldRef;
|
||||
}
|
||||
const parsed = GlobalSettings.safeParse(merged);
|
||||
if (!parsed.success) {
|
||||
const msg = parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
||||
throw new ApiException("validation_failed", msg);
|
||||
}
|
||||
const next = parsed.data;
|
||||
if (typeof apiKey === "string") {
|
||||
if (oldRef) {
|
||||
await ctx.secrets.replace(oldRef, apiKey);
|
||||
next.pi.apiKeySecretRef = oldRef;
|
||||
} else {
|
||||
newRef = await ctx.secrets.create({ purpose: "llm_api_key", plaintext: apiKey });
|
||||
next.pi.apiKeySecretRef = newRef;
|
||||
}
|
||||
}
|
||||
const keys = (Object.keys(patch) as SettingsKey[]).filter((k) => patch[k] !== undefined);
|
||||
try {
|
||||
await ctx.db.transaction().execute(async (trx) => {
|
||||
for (const key of keys) {
|
||||
await trx
|
||||
.insertInto("settings")
|
||||
.values({ key, value: JSON.stringify(next[key]), updated_at: new Date() })
|
||||
.onConflict((oc) =>
|
||||
oc.column("key").doUpdateSet({ value: JSON.stringify(next[key]), updated_at: new Date() }),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
if (newRef) await ctx.secrets.remove(newRef).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
if (dropRef) await ctx.secrets.remove(dropRef).catch(() => {});
|
||||
if (isCached(ctx.settings)) ctx.settings.invalidate();
|
||||
void ctx.events.publish(SETTINGS_CHANGED_EVENT, { keys });
|
||||
// 审计里不留明文密钥
|
||||
const logged: Record<string, unknown> = { ...patch };
|
||||
if (patch.pi && "apiKey" in patch.pi) logged.pi = { ...patch.pi, apiKey: apiKey === null ? "(cleared)" : "(set)" };
|
||||
await audit(ctx, actor, "settings.update", { type: "settings", id: keys.join(",") }, { patch: logged });
|
||||
return next;
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user