Files
khb_microservices/packages/accounting_automation/src/mcp-auth.ts

82 lines
3.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { timingSafeEqual } from "node:crypto";
import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from "jose";
import type { Pool } from "khb_common";
import type { AccountingSettings } from "./settings.js";
/** Ошибка аутентификации MCP: status 401 (токен не принят) или 403 (токен верный, но человека в системе нет). */
export class McpAuthError extends Error {
constructor(message: string, readonly status: 401 | 403 = 401) {
super(message);
}
}
/** Содержимое проверенного JWT, нужное нам. */
export interface VerifiedJwt {
email?: string;
emailVerified?: boolean;
}
/** Проверка JWT (подпись, срок, issuer). Бросает исключение, если токен не годится. Внедряется для тестов. */
export type JwtVerifier = (token: string) => Promise<VerifiedJwt>;
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);
};
export const bearerToken = (h: string | undefined): string | null => (h && /^Bearer\s/i.test(h) ? h.slice(7).trim() || null : null);
/** Проверка JWT Keycloak: ключи берутся из getKey (по умолчанию - JWKS издателя; в тестах - локальный набор ключей). */
export function keycloakVerifier(issuer: string, getKey?: JWTVerifyGetKey, audience?: string): JwtVerifier {
const iss = issuer.replace(/\/$/, "");
const keys = getKey ?? createRemoteJWKSet(new URL(`${iss}/protocol/openid-connect/certs`));
return async (token) => {
const { payload } = await jwtVerify(token, keys, { issuer: [iss, `${iss}/`], ...(audience ? { audience } : {}) });
return {
email: typeof payload.email === "string" ? payload.email : undefined,
emailVerified: typeof payload.email_verified === "boolean" ? payload.email_verified : undefined,
};
};
}
export interface McpAuthDeps {
pool: Pool;
settings: Pick<AccountingSettings, "mcp">;
/** Если не задана, а в настройках есть mcp.issuer - используется keycloakVerifier(issuer). */
verifyJwt?: JwtVerifier;
}
/** Возвращает функцию «заголовок Authorization -> person_id». Статические токены, затем JWT Keycloak (person по email). */
export function createMcpAuth(deps: McpAuthDeps): (authorization: string | undefined) => Promise<{ personId: string }> {
const { pool, settings } = deps;
const verify = deps.verifyJwt ?? (settings.mcp.issuer ? keycloakVerifier(settings.mcp.issuer) : undefined);
return async (authorization) => {
const t = bearerToken(authorization);
if (!t) throw new McpAuthError("нужен заголовок Authorization: Bearer <токен>", 401);
const st = settings.mcp.staticTokens.find((x) => safeEqual(t, x.token));
if (st) return { personId: st.personId };
if (!verify) throw new McpAuthError("токен не принят", 401);
let email: string | undefined;
try {
const v = await verify(t);
if (v.emailVerified === false) throw new Error("email не подтверждён");
email = v.email;
} catch {
throw new McpAuthError("токен не принят", 401);
}
if (!email) throw new McpAuthError("в токене нет email", 401);
const p = (
await pool.query(
`select id from person
where is_active
and (lower(email) = lower($1)
or exists (select 1 from unnest(string_to_array(lower(coalesce(additional_emails, '')), ';')) e where btrim(e) = lower($1)))
limit 1`,
[email],
)
).rows[0];
if (!p) throw new McpAuthError(`для ${email} нет активного person: доступ запрещён`, 403);
return { personId: String(p.id) };
};
}