70 lines
4.0 KiB
TypeScript
70 lines
4.0 KiB
TypeScript
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) {}
|
||
|
||
/** Токен -> права: административный (без заголовка - администратор) или агентский (всегда конкретный person). null - токен не наш. */
|
||
private async byServiceToken(t: string, callerPerson: string | undefined): Promise<Caller | null> {
|
||
if (safeEqual(t, this.s.http.token)) return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
|
||
const at = this.s.http.agentTokens.find((x) => safeEqual(t, x.token));
|
||
if (!at) return null;
|
||
if (at.personId) {
|
||
if (callerPerson && callerPerson.toLowerCase() !== at.personId.toLowerCase()) throw new AccessError("X-Caller-Person не совпадает с person токена", 403);
|
||
return resolveCaller(this.pool, at.personId);
|
||
}
|
||
if (!callerPerson) throw new AccessError("агентскому токену нужен заголовок X-Caller-Person", 403);
|
||
return resolveCaller(this.pool, callerPerson);
|
||
}
|
||
|
||
/** REST: административный или агентский токен; person передаётся заголовком X-Caller-Person. */
|
||
async internal(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
|
||
const t = bearer(authorization);
|
||
const c = t ? await this.byServiceToken(t, callerPerson) : null;
|
||
if (!c) throw new AccessError("unauthorized", 401);
|
||
return c;
|
||
}
|
||
|
||
/** 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);
|
||
const sc = await this.byServiceToken(t, callerPerson);
|
||
if (sc) return sc;
|
||
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));
|
||
}
|
||
}
|