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:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 00:18:25 +01:00
1 parent 9ca83994fb
commit aa95d6b314
13 files changed
+892 -18

No files matched your search

+7 -1
View File
@@ -518,9 +518,15 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
### Authentik ### Authentik
- **Config fields:** the **address** of Authentik (`https://auth.example.lan`), an **API token** (Authentik → Directory → Tokens and App passwords → *Create*, intent **API Token**, for a user who may read; stored encrypted) and, for an https address with a certificate you made yourself, *insecure*. - **Config fields:** the **address** of Authentik (`https://auth.example.lan`), an **API token** (Authentik → Directory → Tokens and App passwords → *Create*, intent **API Token**, for a user who may read; stored encrypted), optionally a **token for making users** (below) and, for an https address with a certificate you made yourself, *insecure*.
- **Required access:** read only. This app only ever sends GET requests: the version, the workers, the outposts and their health, the certificates, the tokens and the events log. **Nothing is ever changed.** Give the token a user with just enough to read these (an administrator, or a user in a role that may view them); - **Required access:** read only. This app only ever sends GET requests: the version, the workers, the outposts and their health, the certificates, the tokens and the events log. **Nothing is ever changed.** Give the token a user with just enough to read these (an administrator, or a user in a role that may view them);
if one of the lists is refused, that part is left out and the rest still works. if one of the lists is refused, that part is left out and the rest still works.
- **Making a user (optional, administrators only):** with a second, separate token in *Token for making users* — an API token of an account that may add users, which is close to an administrator of Authentik, so give it only if you want this — **Apps → Authentik → New user** makes a user
(user name, name, an email if there is one, and groups, which are read from Authentik when the form opens; a group that makes members administrators of Authentik is marked) and then a **one-time recovery link** for them. They open the link and **choose their own password**: this app never sets, sees or keeps one.
The link is in the answer to that one request and nowhere else (not stored, not in the audit log); the audit log has *who made which user* and *who made a link for whom*, never the link or a token. If the user is made and the link is not (Authentik needs a **recovery flow** on the brand — System → Brands),
the page says so and the link is made in Authentik (the user → *Create recovery link*). Authentik builds the link from the address it was called at, so the integration's address should be the one people use. The token for making users is only used for this; reading Authentik never uses it,
and *Stop allowing this* on the page removes it again (the reading token stays). Without it nothing about the page changes for anyone but an administrator, who sees where to add one. The calls (`GET /core/groups/`, `POST /core/users/`, `POST /core/users/{id}/recovery/`, asking for a link that lasts a day, which a version of
Authentik that does not take that sets for itself) are **not verified against a live Authentik**; the tests use a pretend one.
- **What it does:** every **five minutes** Authentik is read and stored — its version (and whether a newer one is out), whether a **worker** is connected, each **outpost** (the proxy outpost that guards your apps, an LDAP one) with how many instances reported in during the last five minutes and whether they run the right version, the - **What it does:** every **five minutes** Authentik is read and stored — its version (and whether a newer one is out), whether a **worker** is connected, each **outpost** (the proxy outpost that guards your apps, an LDAP one) with how many instances reported in during the last five minutes and whether they run the right version, the
**certificates** (those Authentik does not renew by itself) with their expiry, the **API tokens and app passwords** that expire, and how many **sign-ins failed** and **configuration errors** happened in the last day. **Apps → Authentik** shows it, with what runs out soonest first. **certificates** (those Authentik does not renew by itself) with their expiry, the **API tokens and app passwords** that expire, and how many **sign-ins failed** and **configuration errors** happened in the last day. **Apps → Authentik** shows it, with what runs out soonest first.
- **Alerts** (source *Authentik*; held back by maintenance on the integration): **an outpost that serves applications has not reported in** (critical — the apps behind it stop letting anyone in; an outpost with no applications is left alone), **an outpost runs another version** (warning), - **Alerts** (source *Authentik*; held back by maintenance on the integration): **an outpost that serves applications has not reported in** (critical — the apps behind it stop letting anyone in; an outpost with no applications is left alone), **an outpost runs another version** (warning),
+1
View File
@@ -572,6 +572,7 @@ quietly never made. The page shows the photo and video counts, what the library
**Authentik** (Apps → Authentik). Add an Authentik integration (its address and an API token) and the app watches the sign-in in front of everything else: it raises a **critical** alert when an **outpost** that guards applications stops reporting, and warns when a **certificate** or an **API token** is **Authentik** (Apps → Authentik). Add an Authentik integration (its address and an API token) and the app watches the sign-in in front of everything else: it raises a **critical** alert when an **outpost** that guards applications stops reporting, and warns when a **certificate** or an **API token** is
about to run out (the token it reads Authentik with included), when **no worker** is connected, and when **sign-ins are failing** or flows are misconfigured. The page lists the outposts, what runs out soonest and the failed sign-ins of the last day. See INTEGRATIONS.md and docs/MONITORING.md. about to run out (the token it reads Authentik with included), when **no worker** is connected, and when **sign-ins are failing** or flows are misconfigured. The page lists the outposts, what runs out soonest and the failed sign-ins of the last day. See INTEGRATIONS.md and docs/MONITORING.md.
An administrator can also **make a user** from that page — with a second, optional token for it — and gets a **one-time recovery link** to send them, so they choose their own password; no password is ever set or seen here, and the link is shown once and not kept.
**Jellyfin** (Apps → Jellyfin). Add a Jellyfin integration (its address and an API key) and the app shows whether it is up, **who is streaming what** and whether it is being transcoded, the scheduled tasks that failed, and a chart of how many watched at once; it warns when Jellyfin **wants a restart**, a **Jellyfin** (Apps → Jellyfin). Add a Jellyfin integration (its address and an API key) and the app shows whether it is up, **who is streaming what** and whether it is being transcoded, the scheduled tasks that failed, and a chart of how many watched at once; it warns when Jellyfin **wants a restart**, a
**task failed** or **sign-ins are failing**. And when the Jellyfin runs on a server the app manages, **an update run asks first if people are watching**, and a patch plan **waits for them (up to two hours)** instead of restarting the machine in the middle of a film. See INTEGRATIONS.md and docs/MONITORING.md. **task failed** or **sign-ins are failing**. And when the Jellyfin runs on a server the app manages, **an update run asks first if people are watching**, and a patch plan **waits for them (up to two hours)** instead of restarting the machine in the middle of a film. See INTEGRATIONS.md and docs/MONITORING.md.
+1 -1
View File
@@ -163,7 +163,7 @@ even further, to admin only:
- **Immich** (Apps → Immich): everyone signed in sees the counts, the disk and the job queues; adding one (its address and API key) is an administrator's job, like any integration. - **Immich** (Apps → Immich): everyone signed in sees the counts, the disk and the job queues; adding one (its address and API key) is an administrator's job, like any integration.
- **Paperless-ngx** (Apps → Paperless): everyone signed in sees the counts, the system status and the names of the files that failed to import; adding one (its address and a superuser's token) is an administrator's job, like any integration. - **Paperless-ngx** (Apps → Paperless): everyone signed in sees the counts, the system status and the names of the files that failed to import; adding one (its address and a superuser's token) is an administrator's job, like any integration.
- **Prometheus** (Monitoring → Prometheus): everyone signed in sees the targets, what is down and the alerts firing; adding one (its address, and a token if it needs one) is an administrator's job, like any integration. - **Prometheus** (Monitoring → Prometheus): everyone signed in sees the targets, what is down and the alerts firing; adding one (its address, and a token if it needs one) is an administrator's job, like any integration.
- **Authentik** (Apps → Authentik): everyone signed in sees the outposts, what runs out and the failed-sign-in count (the names of tokens and certificates, not their values); adding one (its address and API token) is an administrator's job, like any integration. - **Authentik** (Apps → Authentik): everyone signed in sees the outposts, what runs out and the failed-sign-in count (the names of tokens and certificates, not their values); adding one (its address and API token) is an administrator's job, like any integration. **Making a user** there (and the groups to offer) is an administrator's alone, and only for an Authentik that was given a token for it; it is written in the audit log (who made which user, and who made a recovery link), never the link.
- **Jellyfin** (Apps → Jellyfin): everyone signed in sees who is streaming and what is wrong; adding one (its address and API key) is an administrator's job, like any integration. Starting an update run on a server people are streaming from needs `startAnyway` — the update drawer asks (operators). - **Jellyfin** (Apps → Jellyfin): everyone signed in sees who is streaming and what is wrong; adding one (its address and API key) is an administrator's job, like any integration. Starting an update run on a server people are streaming from needs `startAnyway` — the update drawer asks (operators).
- **Media managers** (Apps → Media managers, for Sonarr, Radarr and Prowlarr): everyone signed in sees what each says is wrong, its queue, disks and indexers; adding one (its API key) is an administrator's job, like any integration. Nothing on the page changes anything in them. - **Media managers** (Apps → Media managers, for Sonarr, Radarr and Prowlarr): everyone signed in sees what each says is wrong, its queue, disks and indexers; adding one (its API key) is an administrator's job, like any integration. Nothing on the page changes anything in them.
- **App versions** (Operations → App versions): everyone signed in sees what each application runs against the newest release; switching the lookup of releases on and off, and the number of days after which a newer release is a warning, are an administrator's. - **App versions** (Operations → App versions): everyone signed in sees what each application runs against the newest release; switching the lookup of releases on and off, and the number of days after which a newer release is a warning, are an administrator's.
+1 -1
View File
@@ -110,7 +110,7 @@ changing `.env`.
**The first person to sign in becomes the administrator**, so sign in yourself first on a new installation. Everyone after that starts as a **viewer** until an administrator **The first person to sign in becomes the administrator**, so sign in yourself first on a new installation. Everyone after that starts as a **viewer** until an administrator
changes their role under **Administration → Users** — or until their groups decide it ([below](#roles)). changes their role under **Administration → Users** — or until their groups decide it ([below](#roles)).
Only people Authentik lets into the application can sign in at all, which is why the application's access policy matters: the first account is whoever you let in first. Only people Authentik lets into the application can sign in at all, which is why the application's access policy matters: the first account is whoever you let in first. A person an administrator makes from **Apps → Authentik** is a new Authentik user, no more: to sign in here they still have to be allowed into the application (its group binding or policy), and they start as a viewer like anyone else.
## Roles ## Roles
+1 -1
View File
@@ -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) — * 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 * 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/`, * 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. * `/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.
+149
View File
@@ -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 });
}
+1
View File
@@ -187,6 +187,7 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
authentik: [ authentik: [
{ key: "url", label: "Authentik URL", secret: false, placeholder: "https://auth.example.lan" }, { 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: "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" }, { key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
], ],
jellyfin: [ jellyfin: [
+131 -3
View File
@@ -1,14 +1,71 @@
import { Router } from "express"; import { Router, type Response } from "express";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { authentikState, integrations } from "../db/schema.js"; import { authentikState, integrationCredentials, integrations } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.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 { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
import { asyncHandler } from "../utils/asyncHandler.js"; import { asyncHandler } from "../utils/asyncHandler.js";
export const authentikRouter = Router(); export const authentikRouter = Router();
authentikRouter.use(requireAuth); 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. */ /** 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) => { authentikRouter.get("/", asyncHandler(async (_req, res) => {
const [rows, states, statuses] = await Promise.all([ const [rows, states, statuses] = await Promise.all([
@@ -17,6 +74,7 @@ authentikRouter.get("/", asyncHandler(async (_req, res) => {
authentikSyncStatuses(), authentikSyncStatuses(),
]); ]);
const byId = new Map(states.map((s) => [s.integrationId, s])); 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(); const now = new Date();
res.json({ res.json({
authentiks: rows.map((r) => { authentiks: rows.map((r) => {
@@ -27,6 +85,7 @@ authentikRouter.get("/", asyncHandler(async (_req, res) => {
id: r.id, id: r.id,
name: r.name, name: r.name,
enabled: r.enabled, enabled: r.enabled,
canCreateUsers: r.enabled && writable.get(r.id) === true,
status, status,
fresh, fresh,
state: state 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();
}));
+372
View File
@@ -0,0 +1,372 @@
/**
* Making a user in Authentik: what its answers are read as, the three calls it takes (groups, the user, a recovery link), that a token of its own is used and the one that reads never is, the
* admin-only routes, what is written in the audit log (never the link), and taking the token away.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer as createHttpServer, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-authentik-users-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, integrations, integrationCredentials, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js");
const { INTEGRATION_FIELDS } = await import("../src/integrations/fieldSchemas.js");
const { loadIntegrationConfig } = await import("../src/integrations/loadIntegration.js");
const usersApi = await import("../src/integrations/authentik/users.js");
const { createAuthentikAdapter } = await import("../src/integrations/authentik/adapter.js");
const { authentikRouter } = await import("../src/routes/authentik.js");
await runMigrations();
const GROUP_A = "11111111-1111-4111-8111-111111111111";
const GROUP_ADMIN = "22222222-2222-4222-8222-222222222222";
describe("what Authentik's answers are read as", () => {
test("groups: by name, with the ones that make an administrator marked; a row without a real id or a name is left out", () => {
const groups = usersApi.parseGroups({
results: [
{ pk: GROUP_ADMIN, name: "authentik Admins", is_superuser: true },
{ pk: GROUP_A, name: "Family", is_superuser: false },
{ pk: "not-a-uuid", name: "Broken" },
{ pk: "33333333-3333-4333-8333-333333333333", name: " " },
],
});
assert.deepEqual(groups, [{ id: GROUP_ADMIN, name: "authentik Admins", admin: true }, { id: GROUP_A, name: "Family", admin: false }]);
assert.deepEqual(usersApi.parseGroups("nonsense"), []);
});
test("the user it made needs a whole-number id and a name; the display name falls back to the user name", () => {
assert.deepEqual(usersApi.parseCreatedUser({ pk: 7, username: "ada", name: "Ada L" }), { pk: 7, username: "ada", name: "Ada L" });
assert.deepEqual(usersApi.parseCreatedUser({ pk: 7, username: "ada" }), { pk: 7, username: "ada", name: "ada" });
assert.equal(usersApi.parseCreatedUser({ pk: "7", username: "ada" }), null);
assert.equal(usersApi.parseCreatedUser({ pk: 0, username: "ada" }), null);
assert.equal(usersApi.parseCreatedUser({ pk: 3 }), null);
});
test("the link must be a web address", () => {
assert.equal(usersApi.parseRecoveryLink({ link: "https://auth.example.lan/if/flow/recovery/?token=abc" }), "https://auth.example.lan/if/flow/recovery/?token=abc");
assert.equal(usersApi.parseRecoveryLink({ link: "javascript:alert(1)" }), null);
assert.equal(usersApi.parseRecoveryLink({ link: "not a url" }), null);
assert.equal(usersApi.parseRecoveryLink({}), null);
});
test("a complaint is put in words, field by field, and kept short", () => {
assert.equal(usersApi.describeComplaint({ username: ["A user with that username already exists."] }), "username: A user with that username already exists.");
assert.equal(usersApi.describeComplaint({ detail: "Not allowed." }), "Not allowed.");
assert.equal(usersApi.describeComplaint({ non_field_errors: ["No recovery flow set."] }), "No recovery flow set.");
assert.equal(usersApi.describeComplaint({ email: ["x".repeat(900)] })?.length, 300);
assert.equal(usersApi.describeComplaint({}), null);
assert.equal(usersApi.describeComplaint(null), null);
});
});
/** An Authentik that remembers what it was asked. */
interface Seen {
method: string;
path: string;
auth: string;
body: string;
}
const seen: Seen[] = [];
let createStatus = 201;
let createAnswer: unknown = null;
let recoveryStatus = 200;
let recoveryAnswer: unknown = null;
let nextPk = 40;
let fake: Server;
let fakeUrl = "";
before(async () => {
fake = createHttpServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
const path = req.url ?? "";
seen.push({ method: req.method ?? "", path, auth: String(req.headers.authorization ?? ""), body });
const send = (status: number, json: unknown) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(json));
};
if (req.method === "GET" && path.startsWith("/api/v3/core/groups/")) {
return send(200, { results: [{ pk: GROUP_A, name: "Family", is_superuser: false }, { pk: GROUP_ADMIN, name: "authentik Admins", is_superuser: true }] });
}
if (req.method === "POST" && path === "/api/v3/core/users/") {
if (createStatus !== 201) return send(createStatus, createAnswer ?? {});
const b = JSON.parse(body) as { username: string; name: string };
return send(201, createAnswer ?? { pk: nextPk++, username: b.username, name: b.name });
}
const rec = /^\/api\/v3\/core\/users\/(\d+)\/recovery\/$/.exec(path);
if (req.method === "POST" && rec) return send(recoveryStatus, recoveryAnswer ?? { link: `${fakeUrl}/if/flow/recovery/?token=secret-${rec[1]}` });
// What the read adapter asks: anything else answers with something that parses as empty.
if (req.method === "GET" && path.startsWith("/api/v3/admin/version/")) return send(200, { version_current: "2025.2.1", version_latest: "2025.2.1", outdated: false });
return send(200, { results: [] });
});
});
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
});
after(() => {
fake.close();
});
const adapterFor = (writeToken = "write-tok") => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken });
describe("the three calls", () => {
test("the groups are asked for with the token for making users", async () => {
seen.length = 0;
const groups = await adapterFor().listGroups();
assert.deepEqual(groups.map((g) => g.name), ["authentik Admins", "Family"]);
assert.deepEqual(seen.map((s) => [s.method, s.path.split("?")[0], s.auth]), [["GET", "/api/v3/core/groups/", "Bearer write-tok"]]);
});
test("a user is a POST of the name, the user name, the email if there is one and the groups — and no password", async () => {
seen.length = 0;
const user = await adapterFor().createUser({ username: "ada", name: "Ada L", email: "ada@example.com", groups: [GROUP_A, "not-a-uuid"] });
assert.equal(user.username, "ada");
assert.equal(seen.length, 1);
assert.deepEqual([seen[0].method, seen[0].path], ["POST", "/api/v3/core/users/"]);
const body = JSON.parse(seen[0].body);
assert.deepEqual(body, { username: "ada", name: "Ada L", is_active: true, groups: [GROUP_A], email: "ada@example.com" });
assert.equal("password" in body, false);
await adapterFor().createUser({ username: "bo", name: "Bo", groups: [] });
assert.equal("email" in JSON.parse(seen[1].body), false, "no email, no email field");
});
test("the link is a POST to that user's recovery, and a user id that is not a whole number is never put in the address", async () => {
seen.length = 0;
const link = await adapterFor().recoveryLink(41);
assert.match(link, /\/if\/flow\/recovery\/\?token=secret-41$/);
assert.deepEqual(seen.map((s) => [s.method, s.path]), [["POST", "/api/v3/core/users/41/recovery/"]]);
await assert.rejects(() => adapterFor().recoveryLink(1.5), /not a user id/);
await assert.rejects(() => adapterFor().recoveryLink(Number.NaN), /not a user id/);
assert.equal(seen.length, 1);
});
test("what goes wrong is said in kind: refused (the words Authentik used), not accepted, nothing sensible back, nobody there", async () => {
createStatus = 400;
createAnswer = { username: ["A user with that username already exists."] };
await assert.rejects(
() => adapterFor().createUser({ username: "ada", name: "Ada", groups: [] }),
(err: Error & { kind?: string }) => err.kind === "invalid" && /username: A user with that username already exists\./.test(err.message),
);
createStatus = 403;
createAnswer = { detail: "You do not have permission." };
await assert.rejects(
() => adapterFor().createUser({ username: "ada", name: "Ada", groups: [] }),
(err: Error & { kind?: string }) => err.kind === "denied" && /may add users/.test(err.message),
);
createStatus = 201;
createAnswer = { nothing: "useful" };
await assert.rejects(() => adapterFor().createUser({ username: "ada", name: "Ada", groups: [] }), /not with the user it made/);
createAnswer = null;
recoveryAnswer = { link: "" };
await assert.rejects(() => adapterFor().recoveryLink(5), /recovery flow/);
recoveryAnswer = null;
await assert.rejects(() => usersApi.createAuthentikUsersAdapter({ url: "http://127.0.0.1:1", writeToken: "x" }).listGroups(), /could not be reached/);
});
});
describe("the integration form and the reading", () => {
test("the token for making users is an optional secret of the Authentik integration", () => {
const field = INTEGRATION_FIELDS.authentik!.find((f) => f.key === "writeToken");
assert.deepEqual([field?.secret, field?.optional, field?.type], [true, true, "password"]);
});
test("reading Authentik sends nothing but GET requests, with the token that reads — the one for making users is not used", async () => {
seen.length = 0;
await createAuthentikAdapter({ url: fakeUrl, token: "read-tok", writeToken: "write-tok" } as never).read();
assert.ok(seen.length > 0);
assert.deepEqual([...new Set(seen.map((s) => s.method))], ["GET"]);
assert.deepEqual([...new Set(seen.map((s) => s.auth))], ["Bearer read-tok"]);
});
});
describe("the routes", () => {
let app: Server;
let base = "";
let withToken = 0;
let withoutToken = 0;
let otherType = 0;
let off = 0;
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
const post = (id: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/users`, { method: "POST", headers: as(sub), body: JSON.stringify(body) });
const valid = { username: "ada", name: "Ada Lovelace", email: "ada@example.com", groups: [GROUP_A] };
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Alma", role: "admin" },
{ oidcSub: "operator", name: "Olle", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
const cred = (await db.insert(integrationCredentials).values({ name: "authentik:Front door", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok", writeToken: "write-tok" })) }).returning({ id: integrationCredentials.id }))[0];
const credOnlyRead = (await db.insert(integrationCredentials).values({ name: "authentik:Watched", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok" })) }).returning({ id: integrationCredentials.id }))[0];
const config = JSON.stringify({ url: fakeUrl });
withToken = (await db.insert(integrations).values({ type: "authentik", name: "Front door", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id;
withoutToken = (await db.insert(integrations).values({ type: "authentik", name: "Watched", baseUrl: fakeUrl, config, credentialId: credOnlyRead.id }).returning({ id: integrations.id }))[0].id;
off = (await db.insert(integrations).values({ type: "authentik", name: "Switched off", baseUrl: fakeUrl, config, credentialId: cred.id, enabled: false }).returning({ id: integrations.id }))[0].id;
otherType = (await db.insert(integrations).values({ type: "jellyfin", name: "Media", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id;
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
next();
});
a.use("/api/authentik", authentikRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/authentik`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("the page says which Authentik can make users — only a yes or no, never the token — and a switched-off one cannot", async () => {
const res = await fetch(base, { headers: as("viewer") });
assert.equal(res.status, 200);
const text = await res.text();
assert.equal(/write-tok|read-tok/.test(text), false);
const body = JSON.parse(text) as { authentiks: { id: number; canCreateUsers: boolean }[] };
const can = Object.fromEntries(body.authentiks.map((a) => [a.id, a.canCreateUsers]));
assert.deepEqual([can[withToken], can[withoutToken], can[off]], [true, false, false]);
});
test("only an administrator makes users or sees the groups; nothing reaches Authentik for anyone else", async () => {
seen.length = 0;
for (const sub of ["viewer", "operator"]) {
assert.equal((await post(withToken, valid, sub)).status, 403, sub);
assert.equal((await fetch(`${base}/${withToken}/groups`, { headers: as(sub) })).status, 403, sub);
assert.equal((await fetch(`${base}/${withToken}/write-token`, { method: "DELETE", headers: as(sub) })).status, 403, sub);
}
assert.deepEqual(seen, []);
});
test("the groups come from the Authentik asked", async () => {
seen.length = 0;
const res = await fetch(`${base}/${withToken}/groups`, { headers: as("admin") });
assert.equal(res.status, 200);
const body = (await res.json()) as { groups: { name: string; admin: boolean }[] };
assert.deepEqual(body.groups.map((g) => [g.name, g.admin]), [["authentik Admins", true], ["Family", false]]);
assert.equal(seen[0].auth, "Bearer write-tok");
});
test("a user is made with a link for them; the link is in the answer only, and the audit log says who made whom but not the link", async () => {
seen.length = 0;
const res = await post(withToken, valid);
assert.equal(res.status, 201);
assert.equal(res.headers.get("cache-control"), "no-store");
const body = (await res.json()) as { user: { pk: number; username: string }; link: string | null; linkError: string | null };
assert.equal(body.user.username, "ada");
assert.match(body.link ?? "", /\/if\/flow\/recovery\/\?token=secret-/);
assert.equal(body.linkError, null);
assert.deepEqual(seen.map((s) => `${s.method} ${s.path}`), ["POST /api/v3/core/users/", `POST /api/v3/core/users/${body.user.pk}/recovery/`]);
const entries = (await db.select().from(auditLog)).filter((e) => e.action === "create_authentik_user" || e.action === "make_authentik_recovery_link");
assert.deepEqual(entries.map((e) => e.action).sort(), ["create_authentik_user", "make_authentik_recovery_link"]);
for (const e of entries) {
assert.deepEqual([e.category, e.targetType, e.targetId], ["integration", "authentik_user", String(body.user.pk)]);
assert.match(e.detail ?? "", /ada/);
assert.equal(/secret-|token|write-tok|recovery\/\?/.test(e.detail ?? ""), false, "the link and the tokens are not written down");
}
});
test("what is wrong with the form is said before Authentik is asked", async () => {
seen.length = 0;
for (const bad of [{ ...valid, username: " " }, { ...valid, name: "" }, { ...valid, email: "not-an-email" }, { ...valid, groups: ["not-a-uuid"] }, { ...valid, username: "a\nb" }, { name: "x" }]) {
const res = await post(withToken, bad);
assert.equal(res.status, 400, JSON.stringify(bad));
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
}
assert.equal((await post(withToken, { ...valid, email: "" })).status, 201, "the email may be left empty");
assert.deepEqual(seen.filter((s) => !s.path.includes("/recovery/")).length, 1, "only the valid one was passed on");
});
test("an Authentik without a token for making users, a switched-off one, another kind of integration and an unknown one are not written to", async () => {
seen.length = 0;
const r1 = await post(withoutToken, valid);
assert.equal(r1.status, 400);
assert.equal(((await r1.json()) as { error: string }).error, "no_write_token");
assert.equal(((await (await post(off, valid)).json()) as { error: string }).error, "integration_disabled");
assert.equal(((await (await post(otherType, valid)).json()) as { error: string }).error, "wrong_type");
assert.equal((await post(999999, valid)).status, 404);
assert.equal((await fetch(`${base}/abc/users`, { method: "POST", headers: as("admin"), body: JSON.stringify(valid) })).status, 400);
assert.equal((await fetch(`${base}/${withoutToken}/groups`, { headers: as("admin") })).status, 400);
assert.deepEqual(seen, []);
});
test("a name that is taken is Authentik's own words; no link is asked for", async () => {
seen.length = 0;
createStatus = 400;
createAnswer = { username: ["A user with that username already exists."] };
const res = await post(withToken, valid);
assert.equal(res.status, 400);
assert.match(((await res.json()) as { message: string }).message, /already exists/);
assert.deepEqual(seen.map((s) => s.path), ["/api/v3/core/users/"]);
createStatus = 201;
createAnswer = null;
});
test("a token that is not accepted is a bad gateway, not a refusal of the form", async () => {
createStatus = 403;
createAnswer = { detail: "nope" };
const res = await post(withToken, valid);
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /did not accept the token/);
createStatus = 201;
createAnswer = null;
});
test("a user made without a link is said so, and the user is still written down", async () => {
recoveryStatus = 400;
recoveryAnswer = { non_field_errors: ["No recovery flow set."] };
const res = await post(withToken, { ...valid, username: "nolink" });
assert.equal(res.status, 201);
const body = (await res.json()) as { user: { pk: number }; link: string | null; linkError: string | null };
assert.equal(body.link, null);
assert.match(body.linkError ?? "", /No recovery flow set/);
const entries = (await db.select().from(auditLog)).filter((e) => e.targetId === String(body.user.pk));
assert.deepEqual(entries.map((e) => e.action), ["create_authentik_user"], "no link was made, so none is written down");
recoveryStatus = 200;
recoveryAnswer = null;
});
test("the token for making users can be taken away; the one that reads stays, and the page says it can no longer make users", async () => {
const res = await fetch(`${base}/${withToken}/write-token`, { method: "DELETE", headers: as("admin") });
assert.equal(res.status, 204);
const loaded = await loadIntegrationConfig(withToken);
assert.equal(loaded?.config.token, "read-tok");
assert.equal(loaded?.config.writeToken, undefined);
const body = (await (await fetch(base, { headers: as("viewer") })).json()) as { authentiks: { id: number; canCreateUsers: boolean }[] };
assert.equal(body.authentiks.find((a) => a.id === withToken)?.canCreateUsers, false);
seen.length = 0;
assert.equal((await post(withToken, valid)).status, 400);
assert.deepEqual(seen, []);
const entry = (await db.select().from(auditLog)).find((e) => e.action === "remove_authentik_write_token");
assert.deepEqual([entry?.category, entry?.targetType], ["integration", "integration"]);
// Again: nothing to take away, and nothing more is written down.
assert.equal((await fetch(`${base}/${withToken}/write-token`, { method: "DELETE", headers: as("admin") })).status, 204);
assert.equal((await db.select().from(auditLog)).filter((e) => e.action === "remove_authentik_write_token").length, 1);
assert.equal((await fetch(`${base}/${otherType}/write-token`, { method: "DELETE", headers: as("admin") })).status, 400);
assert.equal((await fetch(`${base}/999999/write-token`, { method: "DELETE", headers: as("admin") })).status, 404);
});
});
+1 -1
View File
@@ -175,7 +175,7 @@ function Shelled({ user }: { user: CurrentUser }) {
<Route path="/home-assistant" element={<HomeAssistant user={user} />} /> <Route path="/home-assistant" element={<HomeAssistant user={user} />} />
<Route path="/ups" element={<Ups user={user} />} /> <Route path="/ups" element={<Ups user={user} />} />
<Route path="/jellyfin" element={<Jellyfin />} /> <Route path="/jellyfin" element={<Jellyfin />} />
<Route path="/authentik" element={<Authentik />} /> <Route path="/authentik" element={<Authentik user={user} />} />
<Route path="/prometheus" element={<Prometheus />} /> <Route path="/prometheus" element={<Prometheus />} />
<Route path="/immich" element={<Immich />} /> <Route path="/immich" element={<Immich />} />
<Route path="/paperless" element={<Paperless />} /> <Route path="/paperless" element={<Paperless />} />
+26
View File
@@ -1737,6 +1737,8 @@ export interface AuthentikInfo {
id: number; id: number;
name: string; name: string;
enabled: boolean; enabled: boolean;
/** Whether it was given a token to make users with. */
canCreateUsers: boolean;
status: { at: string; ok: boolean; error: string | null } | null; status: { at: string; ok: boolean; error: string | null } | null;
fresh: boolean; fresh: boolean;
state: { state: {
@@ -1755,6 +1757,27 @@ export interface AuthentikInfo {
problems: { key: string; message: string; severity: "warning" | "critical" }[]; problems: { key: string; message: string; severity: "warning" | "critical" }[];
} }
/** A group in Authentik a new user can be put in; `admin` ones make the user an administrator there. */
export interface AuthentikGroup {
id: string;
name: string;
admin: boolean;
}
export interface AuthentikNewUser {
username: string;
name: string;
email: string;
groups: string[];
}
/** A user Authentik made, and the one-time link for them to choose a password with (null, with the reason, when that could not be made). */
export interface AuthentikUserMade {
user: { pk: number; username: string; name: string };
link: string | null;
linkError: string | null;
}
export interface JellyfinHistory { export interface JellyfinHistory {
jellyfin: { id: number; name: string }; jellyfin: { id: number; name: string };
days: number; days: number;
@@ -3387,6 +3410,9 @@ export const api = {
}, },
authentik: { authentik: {
list: () => request<{ authentiks: AuthentikInfo[] }>("/api/authentik"), list: () => request<{ authentiks: AuthentikInfo[] }>("/api/authentik"),
groups: (id: number) => request<{ groups: AuthentikGroup[] }>(`/api/authentik/${id}/groups`),
createUser: (id: number, body: AuthentikNewUser) => request<AuthentikUserMade>(`/api/authentik/${id}/users`, { method: "POST", body: JSON.stringify(body) }),
removeWriteToken: (id: number) => request<void>(`/api/authentik/${id}/write-token`, { method: "DELETE" }),
}, },
jellyfin: { jellyfin: {
list: () => request<{ jellyfins: JellyfinInfo[] }>("/api/jellyfin"), list: () => request<{ jellyfins: JellyfinInfo[] }>("/api/jellyfin"),
+186
View File
@@ -0,0 +1,186 @@
import { useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
import { api, type AuthentikGroup, type AuthentikInfo, type AuthentikUserMade } from "../api/client";
import CopyButton from "./CopyButton";
import { ErrorNotice } from "./Notice";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
const EMPTY = { username: "", name: "", email: "" };
/**
* Making a user in Authentik, for an administrator: a name, an email if there is one, the groups, and out comes a one-time link for them to choose their own password with. The app never
* sees or sets a password, and the link is shown here once — it is not kept anywhere.
*/
export default function AuthentikNewUser({ a, onChanged }: { a: AuthentikInfo; onChanged: () => void }) {
const [open, setOpen] = useState(false);
const [fields, setFields] = useState(EMPTY);
const [groups, setGroups] = useState<AuthentikGroup[] | null>(null);
const [groupsError, setGroupsError] = useState<string | null>(null);
const [picked, setPicked] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [made, setMade] = useState<AuthentikUserMade | null>(null);
if (!a.canCreateUsers) {
return (
<div className="text-secondary small mt-3">
To make users from here, give this Authentik a token that may add users: <Link to="/integrations">Integrations</Link> → edit → <em>Token for making users</em>.
</div>
);
}
async function show() {
setOpen(true);
setMade(null);
setError(null);
setGroupsError(null);
try {
setGroups((await api.authentik.groups(a.id)).groups);
} catch (err) {
setGroups([]);
setGroupsError(readableError(err));
}
}
function close() {
setOpen(false);
setFields(EMPTY);
setPicked([]);
setMade(null);
setError(null);
}
async function submit(e: FormEvent) {
e.preventDefault();
if (busy) return;
setBusy(true);
setError(null);
try {
setMade(await api.authentik.createUser(a.id, { ...fields, groups: picked }));
setFields(EMPTY);
setPicked([]);
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function stopAllowing() {
if (!(await confirmDialog({ title: "Stop making users", message: `Remove the token for making users from "${a.name}"? Reading it carries on. You can add one again under Integrations.`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.authentik.removeWriteToken(a.id);
close();
onChanged();
} catch (err) {
setError(readableError(err));
}
}
const toggle = (id: string) => setPicked((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));
return (
<div className="mt-3">
<h4>New user</h4>
{!open && (
<div className="d-flex flex-wrap align-items-center gap-2">
<button type="button" className="btn btn-sm btn-primary" onClick={() => void show()}>
New user…
</button>
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={() => void stopAllowing()}>
Stop allowing this
</button>
</div>
)}
{open && made && (
<div className="card card-sm">
<div className="card-body">
<div className="mb-2">
<strong>{made.user.username}</strong> was made in {a.name}.
</div>
{made.link ? (
<>
<div className="input-group mb-2">
<input className="form-control" readOnly value={made.link} aria-label="Recovery link" onFocus={(e) => e.currentTarget.select()} />
<CopyButton text={made.link} />
</div>
<div className="text-secondary small mb-3">
Send them this link. They open it and choose their own password; it works once. It is shown here only and kept nowhere, so copy it now. It points at the address this app reaches Authentik at, so the Authentik address in Integrations should be
the one people use.
</div>
</>
) : (
<div className="alert alert-warning mb-3">
The user exists, but no link could be made: {made.linkError ?? "no answer"}. Make one in Authentik: Directory → Users → {made.user.username} → Create recovery link.
</div>
)}
<button type="button" className="btn btn-sm btn-outline-secondary me-2" onClick={() => void show()}>
Make another
</button>
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={close}>
Done
</button>
</div>
</div>
)}
{open && !made && (
<form onSubmit={submit} className="card card-sm">
<div className="card-body">
<ErrorNotice error={error} />
<div className="row g-2 mb-3">
<div className="col-md-4">
<label className="form-label" htmlFor={`ak-user-${a.id}`}>
User name
</label>
<input id={`ak-user-${a.id}`} className="form-control" required maxLength={150} autoComplete="off" value={fields.username} onChange={(e) => setFields({ ...fields, username: e.target.value })} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor={`ak-name-${a.id}`}>
Name
</label>
<input id={`ak-name-${a.id}`} className="form-control" required maxLength={200} autoComplete="off" value={fields.name} onChange={(e) => setFields({ ...fields, name: e.target.value })} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor={`ak-email-${a.id}`}>
Email <span className="text-secondary">(optional)</span>
</label>
<input id={`ak-email-${a.id}`} type="email" className="form-control" maxLength={254} autoComplete="off" value={fields.email} onChange={(e) => setFields({ ...fields, email: e.target.value })} />
</div>
</div>
<div className="form-label">Groups</div>
{groups === null && <div className="text-secondary small mb-3">Reading the groups…</div>}
{groupsError && <div className="text-yellow small mb-2">The groups could not be read: {groupsError}. The user can still be made, without groups.</div>}
{groups && groups.length === 0 && !groupsError && <div className="text-secondary small mb-3">There are no groups.</div>}
{groups && groups.length > 0 && (
<div className="mb-3">
{groups.map((g) => (
<label key={g.id} className="form-check">
<input type="checkbox" className="form-check-input" checked={picked.includes(g.id)} onChange={() => toggle(g.id)} />
<span className="form-check-label">
{g.name}
{g.admin && <span className="badge bg-yellow-lt text-yellow ms-2">administrators</span>}
</span>
</label>
))}
</div>
)}
<div className="d-flex flex-wrap align-items-center gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || groups === null}>
{busy ? "Making…" : "Make user and link"}
</button>
<button type="button" className="btn btn-link text-secondary" onClick={close} disabled={busy}>
Cancel
</button>
<span className="text-secondary small">They choose their own password with the link; none is set here.</span>
</div>
</div>
</form>
)}
</div>
);
}
+15 -10
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { api, type AuthentikInfo } from "../api/client"; import { api, type AuthentikInfo, type CurrentUser } from "../api/client";
import AuthentikNewUser from "../components/AuthentikNewUser";
import EmptyState from "../components/EmptyState"; import EmptyState from "../components/EmptyState";
import TimeAgo from "../components/TimeAgo"; import TimeAgo from "../components/TimeAgo";
import { BlockSkeleton } from "../components/Skeleton"; import { BlockSkeleton } from "../components/Skeleton";
@@ -22,7 +23,7 @@ function Left({ days, warn, critical }: { days: number; warn: number; critical:
return <span className={days <= critical ? "text-red" : days <= warn ? "text-yellow" : "text-secondary"}>{text}</span>; return <span className={days <= critical ? "text-red" : days <= warn ? "text-yellow" : "text-secondary"}>{text}</span>;
} }
function Card({ a }: { a: AuthentikInfo }) { function Card({ a, isAdmin, onChanged }: { a: AuthentikInfo; isAdmin: boolean; onChanged: () => void }) {
const s = a.state; const s = a.state;
return ( return (
<div className="card mb-3"> <div className="card mb-3">
@@ -126,34 +127,38 @@ function Card({ a }: { a: AuthentikInfo }) {
{s.lastConfigError && <div className="text-secondary small">Latest configuration error: {s.lastConfigError}</div>} {s.lastConfigError && <div className="text-secondary small">Latest configuration error: {s.lastConfigError}</div>}
</> </>
)} )}
{isAdmin && a.enabled && <AuthentikNewUser a={a} onChanged={onChanged} />}
</div> </div>
</div> </div>
); );
} }
/** Authentik, the front door: whether its outposts are reporting, what is about to run out, whether a worker is connected, and who is failing to sign in. */ /** Authentik, the front door: whether its outposts are reporting, what is about to run out, whether a worker is connected, and who is failing to sign in. */
export default function Authentik() { export default function Authentik({ user }: { user: CurrentUser }) {
const [data, setData] = useState<AuthentikInfo[] | null>(null); const [data, setData] = useState<AuthentikInfo[] | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { const load = useCallback(
const load = () => () =>
api.authentik api.authentik
.list() .list()
.then((r) => { .then((r) => {
setData(r.authentiks); setData(r.authentiks);
setError(null); setError(null);
}) })
.catch((err) => setError(readableError(err))); .catch((err) => setError(readableError(err))),
[],
);
useEffect(() => {
void load(); void load();
const t = setInterval(load, 60_000); const t = setInterval(load, 60_000);
return () => clearInterval(t); return () => clearInterval(t);
}, []); }, [load]);
return ( return (
<> <>
<h2 className="page-title">Authentik</h2> <h2 className="page-title">Authentik</h2>
<p className="text-secondary"> <p className="text-secondary">
The sign-in in front of everything else. It is read every few minutes with an API token (see <Link to="/integrations">Integrations</Link>). An <strong>outpost that goes quiet</strong> (the apps it guards stop letting anyone in), a <strong>certificate</strong> or an{" "} The sign-in in front of everything else. It is read every few minutes with an API token (see <Link to="/integrations">Integrations</Link>). An <strong>outpost that goes quiet</strong> (the apps it guards stop letting anyone in), a <strong>certificate</strong> or an{" "}
<strong>API token</strong> that is about to run out, <strong>no worker</strong> and a burst of <strong>failed sign-ins</strong> are alerts — see <Link to="/alerts">Alerts</Link>. <strong>API token</strong> that is about to run out, <strong>no worker</strong> and a burst of <strong>failed sign-ins</strong> are alerts — see <Link to="/alerts">Alerts</Link>.{user.role === "admin" && " An administrator can also make a user here, with a one-time link for them to choose a password."}
</p> </p>
<ErrorNotice error={error} /> <ErrorNotice error={error} />
{!data && !error && <BlockSkeleton lines={4} />} {!data && !error && <BlockSkeleton lines={4} />}
@@ -164,7 +169,7 @@ export default function Authentik() {
</div> </div>
</div> </div>
)} )}
{data?.map((a) => <Card key={a.id} a={a} />)} {data?.map((a) => <Card key={a.id} a={a} isAdmin={user.role === "admin"} onChanged={() => void load()} />)}
</> </>
); );
} }