Files
Homelab-manager/server/src/integrations/authentik/adapter.ts
T
bobbanandClaude Sonnet 5.5 aa95d6b314 Make Authentik users from Apps → Authentik, with a one-time recovery link
An administrator can make a user (user name, name, optional email, groups)
and gets a recovery link to send them, so they choose their own password;
no password is set or seen here. Uses a separate optional "Token for making
users" on the Authentik integration; reading never uses it, and it can be
removed again from the page. The link is shown once and never stored or
audited; the audit log records who made which user and link.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 00:18:25 +01:00

219 lines
9.9 KiB
TypeScript

/**
* Authentik adapter. Config: url, token (an API token made in Authentik under Directory → Tokens and App passwords, intent "API Token"); optional: insecure.
*
* Reading only: Authentik's version (and whether a newer one exists), whether a worker is connected, how each outpost is (the proxy outpost that guards your apps, an LDAP one) —
* how many instances report in and whether they are the right version — the certificates and their expiry, the API tokens and app passwords that expire, and how many sign-ins and
* flows failed lately (from the events log). Nothing is sent to Authentik but GET requests for these; making a user is ./users.ts, with a token of its own.
*
* Endpoints and field names are from Authentik's published API (`/api/v3/admin/version/`, `/admin/workers/`, `/outposts/instances/` and its `/health/`, `/crypto/certificatekeypairs/`,
* `/core/tokens/`, `/events/events/`) and have not been checked against a live server here; every field is read defensively, and a part that cannot be read is left out.
*/
import { requestJson } from "../httpJson.js";
import { withDiagLogging } from "../../services/diagLog.js";
export interface AuthentikConfig {
url: string;
token: string;
insecure?: boolean;
}
export interface AuthentikOutpost {
name: string;
/** proxy, ldap, radius, rac. */
type: string;
/** How many applications (providers) it serves; one with none has nothing to do and is not worth an alert. */
providers: number;
/** Instances that have reported in lately, and all that ever did. */
healthy: number;
instances: number;
/** Any instance running a different version from the one it should. */
outdated: boolean;
lastSeen: string | null;
}
export interface AuthentikCertificate {
name: string;
expires: string;
}
export interface AuthentikToken {
identifier: string;
/** api, app_password, … */
intent: string;
user: string | null;
expires: string;
}
export interface AuthentikRead {
version: string | null;
latestVersion: string | null;
outdated: boolean;
/** Null when the workers could not be asked — which is not the same as none. */
workers: number | null;
outposts: AuthentikOutpost[];
certificates: AuthentikCertificate[];
tokens: AuthentikToken[];
/** In the last day; null when the events could not be read. A count of 100 means "at least". */
failedLogins24h: number | null;
configErrors24h: number | null;
lastConfigError: string | null;
}
export interface AuthentikAdapter {
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
read(now?: Date): Promise<AuthentikRead>;
}
/** An outpost that reported in within this long counts as connected. */
export const OUTPOST_SEEN_WITHIN_MS = 5 * 60_000;
const PAGE = 200;
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
const iso = (v: unknown): string | null => {
const s = str(v);
return s && Number.isFinite(Date.parse(s)) ? new Date(s).toISOString() : null;
};
/** Authentik lists come as `{ pagination, results }`; a bare array is read too. */
const results = (raw: unknown): unknown[] => (Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : []);
/** Pure: what /admin/version says. */
export function parseVersion(raw: unknown): Pick<AuthentikRead, "version" | "latestVersion" | "outdated"> {
const o = obj(raw);
return { version: str(o.version_current), latestVersion: str(o.version_latest), outdated: o.outdated === true };
}
/** Pure: how many workers answered; null when the answer is not a list. */
export function parseWorkers(raw: unknown): number | null {
const list = Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : null;
return list ? list.length : null;
}
/** Pure: an outpost with the health its instances reported. */
export function parseOutpost(raw: unknown, health: unknown, now: Date): AuthentikOutpost | null {
const o = obj(raw);
const name = str(o.name);
if (!name) return null;
const instances = Array.isArray(health) ? health.map(obj) : [];
const seen = instances.map((i) => iso(i.last_seen)).filter((t): t is string => t !== null);
const healthy = seen.filter((t) => now.getTime() - Date.parse(t) <= OUTPOST_SEEN_WITHIN_MS).length;
return {
name,
type: str(o.type) ?? "outpost",
providers: Array.isArray(o.providers) ? o.providers.length : Array.isArray(o.providers_obj) ? o.providers_obj.length : 1,
healthy,
instances: instances.length,
outdated: instances.some((i) => i.version_outdated === true),
lastSeen: seen.sort().at(-1) ?? null,
};
}
/** Pure: the certificates that Authentik does not renew itself (a managed one is its own business), with when they run out. */
export function parseCertificates(raw: unknown): AuthentikCertificate[] {
const out: AuthentikCertificate[] = [];
for (const item of results(raw)) {
const c = obj(item);
const name = str(c.name);
const expires = iso(c.cert_expiry);
if (!name || !expires || str(c.managed)) continue;
out.push({ name, expires });
}
return out;
}
/** Pure: the tokens that expire and are meant to last — API tokens and app passwords; a verification token lives for minutes and is no concern. */
export function parseTokens(raw: unknown): AuthentikToken[] {
const out: AuthentikToken[] = [];
for (const item of results(raw)) {
const t = obj(item);
const identifier = str(t.identifier);
const intent = str(t.intent);
const expires = iso(t.expires);
if (!identifier || !expires || t.expiring === false) continue;
if (intent !== "api" && intent !== "app_password") continue;
const user = obj(t.user_obj);
out.push({ identifier, intent, user: str(user.username) ?? str(user.name), expires });
}
return out;
}
/** Pure: how many events of the page are from the last day (the page is the newest first, so a full page of them means "at least"), and the newest one's words. */
export function countRecentEvents(raw: unknown, now: Date): { count: number | null; latest: string | null } {
if (!Array.isArray(obj(raw).results) && !Array.isArray(raw)) return { count: null, latest: null };
const since = now.getTime() - 86_400_000;
let count = 0;
let latest: string | null = null;
for (const item of results(raw)) {
const e = obj(item);
const at = Date.parse(String(e.created ?? ""));
if (Number.isFinite(at) && at < since) continue;
count += 1;
if (latest === null) {
const ctx = obj(e.context);
latest = str(ctx.message) ?? str(ctx.error) ?? str(ctx.reason) ?? null;
}
}
return { count, latest };
}
export function createAuthentikAdapter(config: AuthentikConfig): AuthentikAdapter {
const base = String(config.url ?? "").replace(/\/+$/, "");
const insecure = config.insecure === true;
const headers = { Authorization: `Bearer ${config.token}`, Accept: "application/json" };
async function get(path: string): Promise<unknown> {
const res = await requestJson(`${base}/api/v3${path}`, { headers, insecure });
if (res.status === 401 || res.status === 403) throw new Error(`Authentik did not accept the token (HTTP ${res.status}) — it needs to be an API token of a user who may read`);
if (res.status === 404) throw new Error("Authentik has no API at this address — check the address");
if (res.status < 200 || res.status >= 300) throw new Error(`Authentik error: HTTP ${res.status}`);
if (res.json === null) throw new Error("Authentik answered with something that isn't JSON — is the address its own?");
return res.json;
}
async function read(now: Date = new Date()): Promise<AuthentikRead> {
const info = parseVersion(await get("/admin/version/"));
// The rest is worth having but not worth failing for: an Authentik that answers about itself and not about its tokens still says it is up.
const soft = async <T>(path: string, parse: (raw: unknown) => T, fallback: T): Promise<T> => {
try {
return parse(await get(path));
} catch {
return fallback;
}
};
const outposts = await soft(
`/outposts/instances/?page_size=${PAGE}`,
(raw) => raw,
null as unknown,
).then(async (raw) => {
const list: AuthentikOutpost[] = [];
for (const item of results(raw)) {
const pk = str(obj(item).pk);
const health = pk ? await soft(`/outposts/instances/${encodeURIComponent(pk)}/health/`, (r) => r, [] as unknown) : [];
const o = parseOutpost(item, health, now);
if (o) list.push(o);
}
return list;
});
const [workers, certificates, tokens, failed, configErrors] = await Promise.all([
soft("/admin/workers/", parseWorkers, null as number | null),
soft(`/crypto/certificatekeypairs/?page_size=${PAGE}&has_key=false`, parseCertificates, [] as AuthentikCertificate[]),
soft(`/core/tokens/?page_size=${PAGE}`, parseTokens, [] as AuthentikToken[]),
soft("/events/events/?action=login_failed&ordering=-created&page_size=100", (r) => countRecentEvents(r, now), { count: null, latest: null } as { count: number | null; latest: string | null }),
soft("/events/events/?action=configuration_error&ordering=-created&page_size=100", (r) => countRecentEvents(r, now), { count: null, latest: null } as { count: number | null; latest: string | null }),
]);
return { ...info, workers, outposts, certificates, tokens, failedLogins24h: failed.count, configErrors24h: configErrors.count, lastConfigError: configErrors.latest };
}
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
const start = Date.now();
try {
await get("/admin/version/");
return { ok: true, latencyMs: Date.now() - start };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
return withDiagLogging("authentik", { ping, read });
}