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>
This commit is contained in:
1 parent
9ca83994fb
commit
aa95d6b314
13 files changed
+892
-18
No files matched your search
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* 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.
|
||||
* 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.
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Making a user in Authentik: the one thing this app does there that is not reading. It is kept apart from the adapter that reads (./adapter.ts, which sends nothing but GET requests with
|
||||
* the integration's own token) and it has a token of its own — `writeToken`, optional, from an account that may add users — so an Authentik that is only watched is never written to.
|
||||
*
|
||||
* Three calls: the groups to offer (`GET /core/groups/`), the user (`POST /core/users/`) and a one-time recovery link for that user (`POST /core/users/{pk}/recovery/`), which is how the
|
||||
* person gets to choose their own password: this app never sets, sees or keeps one. The link is handed back once and not stored.
|
||||
*
|
||||
* Endpoints and field names are from Authentik's published API and have not been checked against a live server here; every field is read defensively. The link is built by Authentik from
|
||||
* the address it was asked at, so it is only as good as the address in the integration.
|
||||
*/
|
||||
import { requestJson } from "../httpJson.js";
|
||||
import { withDiagLogging } from "../../services/diagLog.js";
|
||||
|
||||
export interface AuthentikUsersConfig {
|
||||
url: string;
|
||||
writeToken?: string;
|
||||
insecure?: boolean;
|
||||
}
|
||||
|
||||
export interface AuthentikGroup {
|
||||
/** A UUID. */
|
||||
id: string;
|
||||
name: string;
|
||||
/** Members of a superuser group are administrators of Authentik. */
|
||||
admin: boolean;
|
||||
}
|
||||
|
||||
export interface NewAuthentikUser {
|
||||
username: string;
|
||||
name: string;
|
||||
email?: string;
|
||||
/** Group ids. */
|
||||
groups: string[];
|
||||
}
|
||||
|
||||
export interface CreatedAuthentikUser {
|
||||
pk: number;
|
||||
username: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** How a call failed: `invalid` — Authentik looked at it and said no (a name taken, a bad address); `denied` — the token is not accepted or may not; `failed` — no answer, or one that makes no sense. */
|
||||
export class AuthentikUserError extends Error {
|
||||
constructor(message: string, readonly kind: "invalid" | "denied" | "failed") {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
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);
|
||||
|
||||
/** Pure: the groups of a `/core/groups/` page, by name. */
|
||||
export function parseGroups(raw: unknown): AuthentikGroup[] {
|
||||
const list = Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : [];
|
||||
const out: AuthentikGroup[] = [];
|
||||
for (const item of list) {
|
||||
const g = obj(item);
|
||||
const id = str(g.pk);
|
||||
const name = str(g.name);
|
||||
if (!id || !name || !UUID.test(id)) continue;
|
||||
out.push({ id, name, admin: g.is_superuser === true });
|
||||
}
|
||||
return out.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Pure: the user Authentik says it made. Null when the answer is not a user. */
|
||||
export function parseCreatedUser(raw: unknown): CreatedAuthentikUser | null {
|
||||
const u = obj(raw);
|
||||
const pk = typeof u.pk === "number" ? u.pk : Number.NaN;
|
||||
const username = str(u.username);
|
||||
if (!Number.isInteger(pk) || pk <= 0 || !username) return null;
|
||||
return { pk, username, name: str(u.name) ?? username };
|
||||
}
|
||||
|
||||
/** Pure: the link out of `/recovery/`'s answer; only a web address counts. */
|
||||
export function parseRecoveryLink(raw: unknown): string | null {
|
||||
const link = str(obj(raw).link);
|
||||
if (!link) return null;
|
||||
try {
|
||||
const url = new URL(link);
|
||||
return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Pure: what Authentik's complaint says, in words. It answers `{"username": ["…"]}`, `{"detail": "…"}` or `{"non_field_errors": ["…"]}`; the longest it is allowed to be is a sentence or two. */
|
||||
export function describeComplaint(raw: unknown): string | null {
|
||||
const o = obj(raw);
|
||||
const parts: string[] = [];
|
||||
for (const [key, value] of Object.entries(o)) {
|
||||
const text = Array.isArray(value) ? value.filter((v): v is string => typeof v === "string").join(" ") : typeof value === "string" ? value : "";
|
||||
if (!text.trim()) continue;
|
||||
parts.push(key === "detail" || key === "non_field_errors" ? text.trim() : `${key}: ${text.trim()}`);
|
||||
}
|
||||
return parts.length > 0 ? parts.join("; ").slice(0, 300) : null;
|
||||
}
|
||||
|
||||
export interface AuthentikUsersAdapter {
|
||||
listGroups(): Promise<AuthentikGroup[]>;
|
||||
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
|
||||
recoveryLink(pk: number): Promise<string>;
|
||||
}
|
||||
|
||||
export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): AuthentikUsersAdapter {
|
||||
const base = String(config.url ?? "").replace(/\/+$/, "");
|
||||
const insecure = config.insecure === true;
|
||||
const headers = { Authorization: `Bearer ${config.writeToken ?? ""}`, Accept: "application/json" };
|
||||
|
||||
async function call(method: "GET" | "POST", path: string, body?: unknown): Promise<unknown> {
|
||||
let res;
|
||||
try {
|
||||
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
|
||||
} catch (err) {
|
||||
throw new AuthentikUserError(`Authentik could not be reached: ${err instanceof Error ? err.message : String(err)}`, "failed");
|
||||
}
|
||||
if (res.status === 401 || res.status === 403) throw new AuthentikUserError(`Authentik did not accept the token for making users (HTTP ${res.status}) — it must be an API token of an account that may add users`, "denied");
|
||||
if (res.status === 404) throw new AuthentikUserError("Authentik has no API at this address, or no such thing there — check the address", "failed");
|
||||
if (res.status === 400) throw new AuthentikUserError(describeComplaint(res.json) ?? "Authentik did not accept that", "invalid");
|
||||
if (res.status < 200 || res.status >= 300) throw new AuthentikUserError(`Authentik error: HTTP ${res.status}`, "failed");
|
||||
if (res.json === null) throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
|
||||
return res.json;
|
||||
}
|
||||
|
||||
async function listGroups(): Promise<AuthentikGroup[]> {
|
||||
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name`));
|
||||
}
|
||||
|
||||
async function createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser> {
|
||||
const body: Record<string, unknown> = { username: input.username, name: input.name, is_active: true, groups: input.groups.filter((g) => UUID.test(g)) };
|
||||
if (input.email) body.email = input.email;
|
||||
const user = parseCreatedUser(await call("POST", "/core/users/", body));
|
||||
if (!user) throw new AuthentikUserError("Authentik answered, but not with the user it made", "failed");
|
||||
return user;
|
||||
}
|
||||
|
||||
async function recoveryLink(pk: number): Promise<string> {
|
||||
if (!Number.isInteger(pk) || pk <= 0) throw new AuthentikUserError("That is not a user id", "invalid");
|
||||
// Asking for a day: a link nobody used should not stay good for weeks. A version of Authentik that does not take the duration uses its own.
|
||||
const link = parseRecoveryLink(await call("POST", `/core/users/${pk}/recovery/`, { token_duration: "days=1" }));
|
||||
if (!link) throw new AuthentikUserError("Authentik did not give a recovery link — a recovery flow has to be set for the brand (System → Brands)", "failed");
|
||||
return link;
|
||||
}
|
||||
|
||||
return withDiagLogging("authentik", { listGroups, createUser, recoveryLink });
|
||||
}
|
||||
@@ -187,6 +187,7 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
|
||||
authentik: [
|
||||
{ key: "url", label: "Authentik URL", secret: false, placeholder: "https://auth.example.lan" },
|
||||
{ key: "token", label: "API token", secret: true, type: "password", placeholder: "Directory → Tokens and App passwords, intent API Token" },
|
||||
{ key: "writeToken", label: "Token for making users (optional)", secret: true, optional: true, type: "password", placeholder: "only to make users from here; an account that may add users. Leave blank to only watch" },
|
||||
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
||||
],
|
||||
jellyfin: [
|
||||
|
||||
@@ -1,14 +1,71 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Response } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { authentikState, integrations } from "../db/schema.js";
|
||||
import { requireAuth } from "../auth/middleware.js";
|
||||
import { authentikState, integrationCredentials, integrations } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { decryptSecret, encryptSecret } from "../crypto.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { AuthentikUserError, createAuthentikUsersAdapter, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const authentikRouter = Router();
|
||||
authentikRouter.use(requireAuth);
|
||||
|
||||
const hasWriteToken = (config: Record<string, unknown>) => typeof config.writeToken === "string" && config.writeToken.trim() !== "";
|
||||
|
||||
/** Whether this Authentik was given a token to make users with. Never says more than that; a credential that cannot be opened counts as none. */
|
||||
async function canCreateUsers(id: number): Promise<boolean> {
|
||||
try {
|
||||
const loaded = await loadIntegrationConfig(id);
|
||||
return !!loaded && hasWriteToken(loaded.config);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The adapter that makes users for one Authentik, or the answer to send when there is not one to use. Only an enabled Authentik with a token for it. */
|
||||
async function usersAdapterFor(rawId: string, res: Response): Promise<{ adapter: AuthentikUsersAdapter; id: number; name: string } | null> {
|
||||
const id = /^\d+$/.test(rawId) ? Number(rawId) : NaN;
|
||||
if (!Number.isInteger(id)) {
|
||||
res.status(400).json({ error: "invalid_id" });
|
||||
return null;
|
||||
}
|
||||
const loaded = await loadIntegrationConfig(id);
|
||||
if (!loaded) {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return null;
|
||||
}
|
||||
if (loaded.integration.type !== "authentik") {
|
||||
res.status(400).json({ error: "wrong_type" });
|
||||
return null;
|
||||
}
|
||||
if (!loaded.integration.enabled) {
|
||||
res.status(400).json({ error: "integration_disabled", message: "This Authentik is switched off." });
|
||||
return null;
|
||||
}
|
||||
if (!hasWriteToken(loaded.config)) {
|
||||
res.status(400).json({ error: "no_write_token", message: "This Authentik has no token for making users. Add one under Integrations → edit." });
|
||||
return null;
|
||||
}
|
||||
return { adapter: createAuthentikUsersAdapter(loaded.config as never), id, name: loaded.integration.name };
|
||||
}
|
||||
|
||||
/** What a failed call to Authentik is answered with: what it said when it looked and refused, a bad gateway otherwise. */
|
||||
function sendFailure(res: Response, err: unknown) {
|
||||
if (err instanceof AuthentikUserError) return res.status(err.kind === "invalid" ? 400 : 502).json({ error: `authentik_${err.kind}`, message: err.message });
|
||||
return res.status(502).json({ error: "authentik_failed", message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
|
||||
const newUserSchema = z.object({
|
||||
username: z.string().trim().min(1, "A user name is needed.").max(150).regex(/^[^\x00-\x1f\x7f]+$/, "A user name can't hold control characters."),
|
||||
name: z.string().trim().min(1, "A name is needed.").max(200),
|
||||
email: z.union([z.literal(""), z.string().trim().email("That is not an email address.").max(254)]).optional(),
|
||||
groups: z.array(z.string().uuid()).max(50).default([]),
|
||||
});
|
||||
|
||||
/** Every Authentik, how it is, from what the last read stored: its outposts, certificates and tokens that run out, and what is wrong. Everyone signed in can see it, like the other pages made of stored readings. */
|
||||
authentikRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const [rows, states, statuses] = await Promise.all([
|
||||
@@ -17,6 +74,7 @@ authentikRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
authentikSyncStatuses(),
|
||||
]);
|
||||
const byId = new Map(states.map((s) => [s.integrationId, s]));
|
||||
const writable = new Map(await Promise.all(rows.map(async (r) => [r.id, await canCreateUsers(r.id)] as const)));
|
||||
const now = new Date();
|
||||
res.json({
|
||||
authentiks: rows.map((r) => {
|
||||
@@ -27,6 +85,7 @@ authentikRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
enabled: r.enabled,
|
||||
canCreateUsers: r.enabled && writable.get(r.id) === true,
|
||||
status,
|
||||
fresh,
|
||||
state: state
|
||||
@@ -49,3 +108,72 @@ authentikRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
}),
|
||||
});
|
||||
}));
|
||||
|
||||
/** The groups a new user can be put in, as the Authentik being asked has them. Only an administrator, and only where a token for making users was given. */
|
||||
authentikRouter.get("/:id/groups", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const target = await usersAdapterFor(req.params.id, res);
|
||||
if (!target) return;
|
||||
try {
|
||||
res.json({ groups: await target.adapter.listGroups() });
|
||||
} catch (err) {
|
||||
sendFailure(res, err);
|
||||
}
|
||||
}));
|
||||
|
||||
/**
|
||||
* Makes a user and a one-time recovery link for them, which is how they choose their own password: no password passes through here. The link is in this answer and nowhere else — not stored,
|
||||
* not in the audit log. When the user is made and the link is not, the answer says so and the link is made in Authentik (the user's page → Create recovery link).
|
||||
*/
|
||||
authentikRouter.post("/:id/users", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = newUserSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a user.", details: parsed.error.flatten() });
|
||||
const target = await usersAdapterFor(req.params.id, res);
|
||||
if (!target) return;
|
||||
|
||||
let user;
|
||||
try {
|
||||
user = await target.adapter.createUser({ username: parsed.data.username, name: parsed.data.name, email: parsed.data.email || undefined, groups: parsed.data.groups });
|
||||
} catch (err) {
|
||||
return sendFailure(res, err);
|
||||
}
|
||||
await recordAudit({
|
||||
actor: req.currentUser!,
|
||||
category: "integration",
|
||||
action: "create_authentik_user",
|
||||
targetType: "authentik_user",
|
||||
targetId: user.pk,
|
||||
detail: { integrationId: target.id, integration: target.name, username: user.username, groups: parsed.data.groups.length },
|
||||
});
|
||||
|
||||
let link: string | null = null;
|
||||
let linkError: string | null = null;
|
||||
try {
|
||||
link = await target.adapter.recoveryLink(user.pk);
|
||||
await recordAudit({ actor: req.currentUser!, category: "integration", action: "make_authentik_recovery_link", targetType: "authentik_user", targetId: user.pk, detail: { integrationId: target.id, username: user.username } });
|
||||
} catch (err) {
|
||||
linkError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.status(201).json({ user, link, linkError });
|
||||
}));
|
||||
|
||||
/** Takes the token for making users away again, leaving the one that reads. */
|
||||
authentikRouter.delete("/:id/write-token", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const [row] = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1);
|
||||
if (!row) return res.status(404).json({ error: "not_found" });
|
||||
if (row.type !== "authentik") return res.status(400).json({ error: "wrong_type" });
|
||||
if (row.credentialId) {
|
||||
const [cred] = await db.select().from(integrationCredentials).where(eq(integrationCredentials.id, row.credentialId)).limit(1);
|
||||
if (cred) {
|
||||
const secrets = JSON.parse(decryptSecret(cred.encryptedSecret)) as Record<string, unknown>;
|
||||
if ("writeToken" in secrets) {
|
||||
delete secrets.writeToken;
|
||||
await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify(secrets)) }).where(eq(integrationCredentials.id, cred.id));
|
||||
await recordAudit({ actor: req.currentUser!, category: "integration", action: "remove_authentik_write_token", targetType: "integration", targetId: id, detail: { name: row.name } });
|
||||
}
|
||||
}
|
||||
}
|
||||
res.status(204).end();
|
||||
}));
|
||||
Reference in new issue
Block a user