acc_invoices: вход через Keycloak (PKCE, Google, только @khbuild.pro) вместо вставки токена
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -72,6 +72,8 @@ export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth
|
||||
throw new AuthError("токен не принят", 401);
|
||||
}
|
||||
if (!email) throw new AuthError("в токене нет email", 401);
|
||||
const dom = (settings.auth.emailDomain ?? "khbuild.pro").toLowerCase();
|
||||
if (!email.toLowerCase().endsWith("@" + dom)) throw new AuthError(`доступ только для адресов @${dom}`, 403);
|
||||
const p = (
|
||||
await pool.query(
|
||||
`select id from person
|
||||
|
||||
@@ -101,6 +101,9 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
return row;
|
||||
}
|
||||
|
||||
// настройки входа для браузера (без авторизации): куда перенаправлять на Keycloak
|
||||
app.get("/api/auth-config", async () => ({ issuer: settings.auth.issuer ?? null, clientId: settings.auth.clientId }));
|
||||
|
||||
app.get("/api/me", async (req) => {
|
||||
const a = await need(req);
|
||||
return { person_id: a.personId, name: a.displayName, roles: a.roles, is_staff: isStaff(a), filters: QUICK_FILTERS };
|
||||
|
||||
@@ -7,6 +7,10 @@ export const accInvoicesSchema = z.object({
|
||||
.object({
|
||||
/** Издатель Keycloak: токен из заголовка Authorization проверяется по его JWKS, person ищется по email. */
|
||||
issuer: z.string().optional(),
|
||||
/** Клиент Keycloak (public, PKCE) для входа из браузера. */
|
||||
clientId: z.string().default("acc-invoices"),
|
||||
/** Пускаются только адреса этого домена (вход Keycloak через Google). */
|
||||
emailDomain: z.string().default("khbuild.pro"),
|
||||
/** Статические токены (человек -> токен): для тестов и сотрудников без Keycloak. */
|
||||
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string() })).default([]),
|
||||
})
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import * as Ariakit from "@ariakit/react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ApiError, api, getToken, setToken, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js";
|
||||
import { ApiError, api, getToken, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js";
|
||||
import { FormDialog } from "./FormDialog.js";
|
||||
import { Login } from "./Login.js";
|
||||
import { finishLogin, logout, relogin } from "./oidc.js";
|
||||
import { day, money, shortDate } from "./format.js";
|
||||
|
||||
interface ListResp { items: Row[]; counts: Record<string, number> }
|
||||
@@ -11,20 +12,26 @@ const hashFilter = (): string => new URLSearchParams(location.hash.slice(1)).get
|
||||
|
||||
export function App() {
|
||||
const [authed, setAuthed] = useState(!!getToken());
|
||||
const [ready, setReady] = useState(!new URLSearchParams(location.search).has("code") && !new URLSearchParams(location.search).has("error"));
|
||||
useEffect(() => {
|
||||
if (ready) return;
|
||||
void finishLogin().then((err) => { if (err) setAuthErr(err); setAuthed(!!getToken()); setReady(true); });
|
||||
}, [ready]);
|
||||
const [me, setMe] = useState<Me | null>(null);
|
||||
const [authErr, setAuthErr] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!authed) return;
|
||||
if (!authed || !ready) return;
|
||||
api<Me>("me").then(setMe).catch((e) => {
|
||||
if (e instanceof ApiError && (e.status === 401 || e.status === 403)) { setToken(""); setAuthed(false); setAuthErr(e.message); }
|
||||
if (e instanceof ApiError && (e.status === 401 || e.status === 403)) { if (e.status === 401) void relogin(); else setAuthErr(e.message); }
|
||||
else setAuthErr(String(e));
|
||||
});
|
||||
}, [authed]);
|
||||
}, [authed, ready]);
|
||||
|
||||
if (!authed) return <Login onDone={() => { setAuthErr(undefined); setAuthed(true); }} error={authErr} />;
|
||||
if (!ready) return <div className="center">Вход…</div>;
|
||||
if (!authed) return <Login error={authErr} />;
|
||||
if (!me) return <div className="center">{authErr ?? "Загрузка…"}</div>;
|
||||
return <Main me={me} onLogout={() => { setToken(""); setAuthed(false); setMe(null); }} />;
|
||||
return <Main me={me} onLogout={() => { void logout(); setAuthed(false); setMe(null); }} />;
|
||||
}
|
||||
|
||||
function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
|
||||
|
||||
@@ -1,22 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import { setToken } from "./api.js";
|
||||
import { useEffect } from "react";
|
||||
import { relogin } from "./oidc.js";
|
||||
|
||||
export function Login({ onDone, error }: { onDone: () => void; error?: string }) {
|
||||
const [t, setT] = useState("");
|
||||
export function Login({ error }: { error?: string }) {
|
||||
// без ошибки сразу уходим на Keycloak; с ошибкой показываем её и кнопку повторного входа
|
||||
useEffect(() => { if (!error) void relogin(); }, [error]);
|
||||
return (
|
||||
<form
|
||||
className="login"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setToken(t.trim());
|
||||
onDone();
|
||||
}}
|
||||
>
|
||||
<div className="login">
|
||||
<h1>Инвойсы и платежи</h1>
|
||||
<p>Вставьте токен доступа (JWT Keycloak или выданный статический токен).</p>
|
||||
<input type="password" autoFocus value={t} onChange={(e) => setT(e.target.value)} placeholder="токен" aria-label="токен доступа" />
|
||||
{error && <p className="err">{error}</p>}
|
||||
<button type="submit" className="btn primary" disabled={!t.trim()}>Войти</button>
|
||||
</form>
|
||||
{error ? <p className="err">{error}</p> : <p>Переход на страницу входа…</p>}
|
||||
<button type="button" className="btn primary" onClick={() => void relogin()}>Войти через Keycloak (Google, @khbuild.pro)</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,9 +18,8 @@ export interface Detail { invoice: Row; details: Line[]; approves: Approve[]; co
|
||||
export type Named = { id: string; name: string };
|
||||
export interface Lookups { projects: Named[]; vendors: Named[]; people: Named[]; categories: Named[]; contracts: { id: string; vendor_name: string; project_customer_id: string; total_amount: number }[] }
|
||||
|
||||
const KEY = "acc_invoices_token";
|
||||
export const getToken = (): string => { try { return localStorage.getItem(KEY) ?? ""; } catch { return ""; } };
|
||||
export const setToken = (t: string): void => { try { t ? localStorage.setItem(KEY, t) : localStorage.removeItem(KEY); } catch { /* без хранилища токен живёт до перезагрузки */ } };
|
||||
import { freshToken, hasSession } from "./oidc.js";
|
||||
export const getToken = (): string => (hasSession() ? "1" : "");
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, readonly status: number, readonly problems?: string[]) { super(message); }
|
||||
@@ -30,7 +29,7 @@ export class ApiError extends Error {
|
||||
export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
|
||||
const r = await fetch(`api/${path}`, {
|
||||
method: init.method ?? "GET",
|
||||
headers: { Authorization: `Bearer ${getToken()}`, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
|
||||
headers: { Authorization: `Bearer ${await freshToken()}`, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
|
||||
body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
|
||||
});
|
||||
const text = await r.text();
|
||||
|
||||
72
packages/acc_invoices/web/src/oidc.ts
Normal file
72
packages/acc_invoices/web/src/oidc.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
/** Вход через Keycloak (Authorization Code + PKCE, публичный клиент). Токены живут в sessionStorage вкладки. */
|
||||
interface Session { access: string; refresh?: string; exp: number }
|
||||
const SK = "acc_invoices_session";
|
||||
const PK = "acc_invoices_pkce";
|
||||
let cfg: { issuer: string; clientId: string } | null = null;
|
||||
let session: Session | null = load();
|
||||
|
||||
function load(): Session | null { try { const s = sessionStorage.getItem(SK); return s ? (JSON.parse(s) as Session) : null; } catch { return null; } }
|
||||
function save(s: Session | null): void { session = s; try { if (s) sessionStorage.setItem(SK, JSON.stringify(s)); else sessionStorage.removeItem(SK); } catch { /* без хранилища сессия живёт до перезагрузки */ } }
|
||||
const redirectUri = (): string => location.origin + location.pathname;
|
||||
const b64 = (b: Uint8Array | ArrayBuffer): string => btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
|
||||
async function config(): Promise<{ issuer: string; clientId: string }> {
|
||||
if (cfg) return cfg;
|
||||
const r = await fetch("api/auth-config");
|
||||
const d = (await r.json()) as { issuer: string | null; clientId: string };
|
||||
if (!d.issuer) throw new Error("на сервере не задан Keycloak (auth.issuer)");
|
||||
return (cfg = { issuer: d.issuer.replace(/\/$/, ""), clientId: d.clientId });
|
||||
}
|
||||
|
||||
export const hasSession = (): boolean => !!session;
|
||||
|
||||
/** Перенаправляет на страницу входа Keycloak (там кнопка Google). */
|
||||
export async function relogin(): Promise<void> {
|
||||
save(null);
|
||||
const c = await config();
|
||||
const verifier = b64(crypto.getRandomValues(new Uint8Array(32)));
|
||||
const state = b64(crypto.getRandomValues(new Uint8Array(16)));
|
||||
const challenge = b64(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
|
||||
try { sessionStorage.setItem(PK, JSON.stringify({ verifier, state, hash: location.hash })); } catch { /* ignore */ }
|
||||
const q = new URLSearchParams({ client_id: c.clientId, redirect_uri: redirectUri(), response_type: "code", scope: "openid email profile", code_challenge: challenge, code_challenge_method: "S256", state });
|
||||
location.assign(`${c.issuer}/protocol/openid-connect/auth?${q}`);
|
||||
}
|
||||
|
||||
async function tokenCall(body: Record<string, string>): Promise<Session> {
|
||||
const c = await config();
|
||||
const r = await fetch(`${c.issuer}/protocol/openid-connect/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: c.clientId, ...body }) });
|
||||
const d = (await r.json()) as { access_token?: string; refresh_token?: string; expires_in?: number; error_description?: string };
|
||||
if (!r.ok || !d.access_token) throw new Error(d.error_description ?? "Keycloak не выдал токен");
|
||||
return { access: d.access_token, refresh: d.refresh_token, exp: Date.now() + (d.expires_in ?? 60) * 1000 };
|
||||
}
|
||||
|
||||
/** Если адрес содержит ?code=... от Keycloak - меняет его на токены. Возвращает текст ошибки или undefined. */
|
||||
export async function finishLogin(): Promise<string | undefined> {
|
||||
const p = new URLSearchParams(location.search);
|
||||
if (p.get("error")) { history.replaceState(null, "", redirectUri()); return p.get("error_description") ?? p.get("error") ?? "ошибка входа"; }
|
||||
const code = p.get("code");
|
||||
if (!code) return undefined;
|
||||
let saved: { verifier: string; state: string; hash?: string } | null = null;
|
||||
try { saved = JSON.parse(sessionStorage.getItem(PK) ?? "null"); sessionStorage.removeItem(PK); } catch { /* ignore */ }
|
||||
history.replaceState(null, "", redirectUri() + (saved?.hash ?? ""));
|
||||
if (!saved || saved.state !== p.get("state")) return "вход прерван, попробуйте ещё раз";
|
||||
try { save(await tokenCall({ grant_type: "authorization_code", code, redirect_uri: redirectUri(), code_verifier: saved.verifier })); } catch (e) { return (e as Error).message; }
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Актуальный access token (при необходимости обновляется по refresh token; иначе - новый вход). */
|
||||
export async function freshToken(): Promise<string> {
|
||||
if (!session) { await relogin(); throw new Error("вход…"); }
|
||||
if (session.exp - Date.now() > 30_000) return session.access;
|
||||
if (session.refresh) {
|
||||
try { save(await tokenCall({ grant_type: "refresh_token", refresh_token: session.refresh })); return session!.access; } catch { /* сессия истекла */ }
|
||||
}
|
||||
await relogin();
|
||||
throw new Error("вход…");
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
const c = await config().catch(() => null);
|
||||
save(null);
|
||||
if (c) location.assign(`${c.issuer}/protocol/openid-connect/logout?${new URLSearchParams({ client_id: c.clientId, post_logout_redirect_uri: redirectUri() })}`);
|
||||
}
|
||||
Reference in New Issue
Block a user