todo_service: новый сервис todo (надстройка над JobTread, REST, MCP, вебхуки, слежение Control), миграция 024, docs в proposed
All checks were successful
ci / test (push) Successful in 27s
ci / deploy (push) Successful in 2m10s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 11:08:54 +03:00
parent 816164902e
commit ad17e8364f
40 changed files with 2601 additions and 4 deletions

View File

@@ -0,0 +1,54 @@
import { timingSafeEqual } from "node:crypto";
import { createRemoteJWKSet, jwtVerify } from "jose";
import type { Pool } from "khb_common";
import { ADMIN, AccessError, resolveCaller, type Caller } from "./access.js";
import type { TodoServiceSettings } from "./settings.js";
export const safeEqual = (a: string, b: string): boolean => {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
};
const bearer = (h: string | undefined): string | null => (h && h.startsWith("Bearer ") ? h.slice(7).trim() : null);
/** Права по токену: внутренний токен сервиса (+ X-Caller-Person), статические токены и JWT Keycloak (для MCP). */
export class Auth {
private jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
constructor(private readonly pool: Pool, private readonly s: TodoServiceSettings) {}
/** REST: только внутренний токен; person передаётся заголовком X-Caller-Person. */
async internal(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
const t = bearer(authorization);
if (!t || !safeEqual(t, this.s.http.token)) throw new AccessError("unauthorized", 401);
return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
}
/** MCP: внутренний токен, статический токен или JWT Keycloak; JWT без известного person отклоняется. */
async mcp(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
const t = bearer(authorization);
if (!t) throw new AccessError("unauthorized", 401);
if (safeEqual(t, this.s.http.token)) return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
const st = this.s.mcp.staticTokens.find((x) => safeEqual(t, x.token));
if (st) return st.personId ? resolveCaller(this.pool, st.personId) : { ...ADMIN, name: st.name ?? "mcp-token" };
if (!this.s.mcp.issuer) throw new AccessError("unauthorized", 401);
this.jwks ??= createRemoteJWKSet(new URL(`${this.s.mcp.issuer.replace(/\/$/, "")}/protocol/openid-connect/certs`));
let email: string | undefined;
try {
const { payload } = await jwtVerify(t, this.jwks, { issuer: this.s.mcp.issuer, ...(this.s.mcp.audience ? { audience: this.s.mcp.audience } : {}) });
if (payload.email_verified === false) throw new Error("email не подтверждён");
email = typeof payload.email === "string" ? payload.email : undefined;
} catch {
throw new AccessError("unauthorized", 401);
}
if (!email) throw new AccessError("в токене нет email", 401);
const p = (
await this.pool.query(
"select id from person where is_active and (lower(email) = lower($1) or position(lower($1) in lower(coalesce(additional_emails, ''))) > 0) limit 1",
[email],
)
).rows[0];
if (!p) throw new AccessError(`для ${email} нет person: доступ запрещён`, 403);
return resolveCaller(this.pool, String(p.id));
}
}