Rename the admin example plugin to auth-admin, and let config/menu.ts hide or rename a profile-menu entry
CI / full-gate (push) Successful in 3m32s
CI / full-gate (push) Successful in 3m32s
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
# auth-admin — the plugin that administers users, groups, permissions and OAuth2 clients
|
||||
|
||||
The Users / Groups / OAuth2-clients screens for running Plainpages itself, shipped as a **drop-in
|
||||
example plugin** so a fresh clone has no admin GUI until you opt in. Copy this folder into `plugins/`
|
||||
(it keeps the id and mount path `auth-admin`, so the screens live at `/auth-admin/*`) and restart:
|
||||
|
||||
```bash
|
||||
cp -r examples/plugins/auth-admin plugins/auth-admin
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The bootstrap grants the seeded `admin@plainpages.local` every permission this plugin declares, so
|
||||
the section appears in the menu and the screens work immediately. An older copy already in
|
||||
`plugins/` is yours — the host never updates it — so re-copy after a pull; a stale one stops the boot
|
||||
with a message naming it ([README → Upgrading](../../../README.md#upgrading)).
|
||||
|
||||
Every string it renders comes from its own catalogs (`i18n/en-US.ts`, `i18n/sv-SE.ts`), the nav
|
||||
labels included. Each pure view-model builder takes an optional `t` defaulting to the plugin's own
|
||||
English, so a unit test reads in words rather than keys.
|
||||
|
||||
## What it demonstrates — a *system* plugin
|
||||
|
||||
Most plugins fetch their data from an upstream service of their own (see the [scheduling
|
||||
reference](../scheduling/README.md)). The admin screens instead administer **Plainpages' own identity
|
||||
stack**, so they use the privileged **`ctx.system`** surface the host exposes to a system plugin:
|
||||
|
||||
- **`ctx.system.kratosAdmin`** — create/edit/deactivate/delete Kratos identities (Users).
|
||||
- **`ctx.system.keto`** — read/write the Keto relationship graph (group membership, permission grants).
|
||||
- **`ctx.system.hydra`** — register/list/delete Ory Hydra OAuth2 clients.
|
||||
- **`ctx.system.revoke(sub)`** — the optional instant-revoke hook: a deactivate/delete or a
|
||||
user's permission change kills that subject's live tokens at once instead of waiting out the JWT TTL.
|
||||
|
||||
`ctx.system` is populated only when the host wired those services. Where a capability is absent the
|
||||
screen degrades to a themed 503 rather than crashing. Everything else is an ordinary plugin:
|
||||
folder-discovered, gated per route by its screen's `<resource>:<action>` permission, rendering the
|
||||
core building blocks in `views/`.
|
||||
|
||||
Each screen is its own resource — `users`, `groups`, `oauth2-clients` — split into `:read` and
|
||||
`:write`, so a helpdesk account can be given `users:read` alone. Holding none of the six hides the
|
||||
Admin section entirely.
|
||||
|
||||
There is **no Permissions screen**. Permission names are declared in plugin code, not created in a
|
||||
GUI, so the host's catalog (`ctx.declaredPermissions`) is the fixed list — and holding one is a
|
||||
property of a user or a group, edited as a checkbox list on those two screens (`admin-grants.ts`).
|
||||
|
||||
## Layout
|
||||
|
||||
- `plugin.ts` — the manifest: the Admin nav fragment, the six permissions the plugin declares, and
|
||||
the route table — one thin handler per method+path, gated via `permissionName(resource, actionForMethod(method))`
|
||||
so a GET needs `:read` and a POST `:write`.
|
||||
- `admin-grants.ts` — the permission picker and the grant diff, shared by the Users and Groups
|
||||
screens: what a submitted checkbox set grants and revokes, against the host's declared catalog.
|
||||
- `admin-users.ts` · `admin-groups.ts` · `admin-clients.ts` — each a set of pure
|
||||
view-model builders (unit-tested in the matching `*.test.ts`) plus thin per-route handlers keyed on
|
||||
`ctx.params` (the host extracts `:id`/`:name`), sharing a small `withX` wrapper that resolves the
|
||||
screen's permission gate + the needed `ctx.system` clients once.
|
||||
- `admin-shared.ts` — the permission naming (`permissionName` / `actionForMethod`), the shared gate
|
||||
(`requirePermission`), CSRF form reader (`guardedForm`), confirm
|
||||
model, nav fragment, and the not-found / unavailable helpers.
|
||||
- `views/` — the screens' EJS, plus the admin-specific body partials under `views/partials/`. They
|
||||
`include()` the core building-block partials (shell, data-table, filter-bar, field, …).
|
||||
|
||||
The three screens hold **no state** — everything lives in Ory. Handlers are thin, so their builders
|
||||
unit-test as pure functions with no host; the HTTP routing/gate/CSRF is covered in
|
||||
`src/http/app-admin.test.ts` (which mounts this plugin) and end-to-end in `e2e-tests/full-flow.spec.ts`.
|
||||
@@ -0,0 +1,105 @@
|
||||
// Built-in OAuth2 clients admin screen: the pure view-model + Hydra-payload builders. A client
|
||||
// is an Ory Hydra OAuth2 client (apps that log in *through* us); writes go only to Hydra. The
|
||||
// HTTP routing/gate/CSRF + live Hydra calls (incl. the one-time secret) are exercised in src/http/app-admin.test.ts.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
buildClientDetailModel,
|
||||
buildClientFormModel,
|
||||
buildClientsListModel,
|
||||
type ClientInput,
|
||||
clientPayload,
|
||||
parseRedirectUris,
|
||||
toClientView,
|
||||
validateClientInput,
|
||||
} from "./admin-clients.ts";
|
||||
|
||||
const input = (over: Partial<ClientInput> = {}): ClientInput =>
|
||||
({ firstParty: false, name: "Acme", public: false, redirectUris: ["https://acme.example/cb"], scope: "openid offline_access", ...over });
|
||||
|
||||
test("toClientView maps Hydra fields → view (public from auth method, first-party from metadata, scopes split)", () => {
|
||||
assert.deepEqual(
|
||||
toClientView({ client_id: "c1", client_name: "Acme", metadata: { first_party: true }, redirect_uris: ["https://a/cb"], scope: "openid email", token_endpoint_auth_method: "client_secret_basic" }),
|
||||
{ firstParty: true, id: "c1", name: "Acme", public: false, redirectUris: ["https://a/cb"], scopes: ["openid", "email"] },
|
||||
);
|
||||
// A public client + no name → falls back to the id; absent metadata/scope tolerated.
|
||||
assert.deepEqual(
|
||||
toClientView({ client_id: "c2", token_endpoint_auth_method: "none" }),
|
||||
{ firstParty: false, id: "c2", name: "c2", public: true, redirectUris: [], scopes: [] },
|
||||
);
|
||||
});
|
||||
|
||||
test("parseRedirectUris splits on newlines/whitespace/commas and drops empties", () => {
|
||||
assert.deepEqual(parseRedirectUris("https://a/cb\n https://b/cb \n\n, https://c/cb"), ["https://a/cb", "https://b/cb", "https://c/cb"]);
|
||||
assert.deepEqual(parseRedirectUris(" "), []);
|
||||
});
|
||||
|
||||
test("clientPayload maps the input to Hydra's create body (auth-code + refresh, type via auth method)", () => {
|
||||
assert.deepEqual(clientPayload(input()), {
|
||||
client_name: "Acme",
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
metadata: { first_party: false },
|
||||
redirect_uris: ["https://acme.example/cb"],
|
||||
response_types: ["code"],
|
||||
scope: "openid offline_access",
|
||||
token_endpoint_auth_method: "client_secret_basic",
|
||||
});
|
||||
const pub = clientPayload(input({ firstParty: true, public: true }));
|
||||
assert.equal(pub.token_endpoint_auth_method, "none");
|
||||
assert.deepEqual(pub.metadata, { first_party: true });
|
||||
});
|
||||
|
||||
test("validateClientInput requires a name, ≥1 redirect URI, and absolute redirect URLs", () => {
|
||||
assert.equal(validateClientInput(input()), null);
|
||||
assert.match(validateClientInput(input({ name: "" }))!, /name/i);
|
||||
assert.match(validateClientInput(input({ redirectUris: [] }))!, /redirect/i);
|
||||
assert.match(validateClientInput(input({ redirectUris: ["not a url"] }))!, /redirect URI/i);
|
||||
});
|
||||
|
||||
test("buildClientsListModel filters by search, paginates; the name links to the detail page", () => {
|
||||
const clients = Array.from({ length: 30 }, (_, i) => ({ client_id: `id-${String(i).padStart(2, "0")}`, client_name: `app-${String(i).padStart(2, "0")}`, token_endpoint_auth_method: "client_secret_basic" }));
|
||||
|
||||
const all = buildClientsListModel({ clients, url: "http://x/auth-admin/clients" });
|
||||
assert.equal(all.pagination.summary.total, 30);
|
||||
assert.equal(all.table.rows.length, 25); // default page size
|
||||
assert.equal(all.title, "OAuth2 clients");
|
||||
const first = all.table.rows[0]!.cells[0] as { rowHeader: { href: string; text: string } };
|
||||
assert.equal(first.rowHeader.text, "app-00");
|
||||
assert.equal(first.rowHeader.href, "/auth-admin/clients/id-00");
|
||||
|
||||
const one = buildClientsListModel({ clients, url: "http://x/auth-admin/clients?q=app-07" });
|
||||
assert.equal(one.pagination.summary.total, 1);
|
||||
assert.deepEqual(one.filterBar.pills.map((p) => p.label), ["Search"]);
|
||||
});
|
||||
|
||||
test("buildClientFormModel: a register form with name + scope fields; values reflected on error", () => {
|
||||
const m = buildClientFormModel({ csrfToken: "tok.sig" });
|
||||
assert.equal(m.title, "Register client");
|
||||
assert.equal(m.form.action, "/auth-admin/clients");
|
||||
assert.equal(m.form.submitLabel, "Register client");
|
||||
assert.equal(m.form.csrfToken, "tok.sig");
|
||||
assert.equal(m.form.nameField.required, true);
|
||||
assert.equal(m.form.scopeField.value, "openid offline_access"); // sensible default
|
||||
|
||||
const err = buildClientFormModel({ error: "Add at least one redirect URI.", values: { firstParty: true, name: "Acme", public: true, redirectUris: ["https://a/cb"], scope: "openid" } });
|
||||
assert.equal(err.error, "Add at least one redirect URI.");
|
||||
assert.equal(err.form.nameField.value, "Acme");
|
||||
assert.equal(err.form.redirectUris, "https://a/cb");
|
||||
assert.equal(err.form.public, true);
|
||||
assert.equal(err.form.firstParty, true);
|
||||
});
|
||||
|
||||
test("buildClientDetailModel: client info + delete action; the one-time secret + created banner show only right after create", () => {
|
||||
const client = toClientView({ client_id: "c1", client_name: "Acme", redirect_uris: ["https://a/cb"], scope: "openid", token_endpoint_auth_method: "client_secret_basic" });
|
||||
|
||||
const plain = buildClientDetailModel({ client });
|
||||
assert.equal(plain.title, "Acme");
|
||||
assert.equal(plain.delete.action, "/auth-admin/clients/c1/delete");
|
||||
assert.equal(plain.created, false);
|
||||
assert.equal(plain.secret, undefined);
|
||||
|
||||
const fresh = buildClientDetailModel({ client, created: true, secret: "s3cr3t" });
|
||||
assert.equal(fresh.created, true);
|
||||
assert.equal(fresh.secret, "s3cr3t");
|
||||
assert.equal(fresh.title, "Client registered");
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
// OAuth2 clients admin screen: register / list / delete the OAuth2 clients other
|
||||
// apps log in *through* us with (Ory Hydra, the login+consent handlers). A client is an Ory Hydra
|
||||
// OAuth2 client; writes go only to Hydra. Hydra returns the client_secret once, on create — so the
|
||||
// register POST renders the new client's detail page (with the one-time secret) directly instead of a
|
||||
// PRG redirect (mirrors the Users "trigger recovery" one-time code). Below the builders are thin
|
||||
// per-route handlers (keyed on ctx.params) over a shared `withClients` gate — admin-only, CSRF-guarded.
|
||||
|
||||
import { buildPaginationModel, can, type HydraAdmin, HydraError, type OAuth2Client, paginate, parseListQuery, type RequestContext, type RouteHandler, type RouteResult, type Translate, type User } from "@plainpages/plugin-api";
|
||||
import { ADMIN_CLIENTS_BASE, ADMIN_EN, type AdminAction, buildConfirmModel, guardedForm, notFound, permissionName, requirePermission, unavailable } from "./admin-shared.ts";
|
||||
import type { FieldConfig } from "./admin-users.ts";
|
||||
|
||||
const DEFAULT_PAGE_SIZE = 25;
|
||||
const PAGE_SIZES = [25, 50, 100];
|
||||
// One Hydra page is fetched and filtered/paged in memory — its list API has no search. Ample for an
|
||||
// admin tool (the OAuth2 clients of a deployment number in the dozens); raise if one outgrows it.
|
||||
const LIST_FETCH_SIZE = 250;
|
||||
const DEFAULT_SCOPE = "openid offline_access";
|
||||
|
||||
export interface ClientView {
|
||||
firstParty: boolean;
|
||||
id: string; // client_id
|
||||
name: string;
|
||||
public: boolean; // public (PKCE, no secret) vs confidential
|
||||
redirectUris: string[];
|
||||
scopes: string[];
|
||||
}
|
||||
|
||||
export interface ClientInput {
|
||||
firstParty: boolean;
|
||||
name: string;
|
||||
public: boolean;
|
||||
redirectUris: string[];
|
||||
scope: string;
|
||||
}
|
||||
|
||||
export function toClientView(client: OAuth2Client): ClientView {
|
||||
const id = client.client_id ?? "";
|
||||
return {
|
||||
firstParty: (client.metadata as { first_party?: unknown } | undefined)?.first_party === true,
|
||||
id,
|
||||
name: client.client_name?.trim() || id || "(unnamed)",
|
||||
public: client.token_endpoint_auth_method === "none",
|
||||
redirectUris: client.redirect_uris ?? [],
|
||||
scopes: (client.scope ?? "").split(/\s+/).filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
// Split a textarea value into redirect URIs (one per line / whitespace / comma), dropping empties.
|
||||
export function parseRedirectUris(raw: string): string[] {
|
||||
return raw.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
// Hydra's create body. We register a standard authorization-code web/native client (+ refresh);
|
||||
// the type (confidential vs public/PKCE) and auto-consent ride the auth method + metadata.
|
||||
export function clientPayload(input: ClientInput): Record<string, unknown> {
|
||||
return {
|
||||
client_name: input.name,
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
metadata: { first_party: input.firstParty },
|
||||
redirect_uris: input.redirectUris,
|
||||
response_types: ["code"],
|
||||
scope: input.scope,
|
||||
token_endpoint_auth_method: input.public ? "none" : "client_secret_basic",
|
||||
};
|
||||
}
|
||||
|
||||
export function validateClientInput(input: ClientInput, t: Translate = ADMIN_EN): string | null {
|
||||
if (!input.name) return t("admin.clients.validation.name");
|
||||
if (!input.redirectUris.length) return t("admin.clients.validation.redirectUris");
|
||||
for (const uri of input.redirectUris) {
|
||||
try {
|
||||
new URL(uri); // must be an absolute URL — any scheme (public/native clients use custom ones)
|
||||
} catch {
|
||||
return t("admin.clients.validation.redirectUri", { uri });
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- list view model ----
|
||||
|
||||
interface ListState {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
q: string;
|
||||
}
|
||||
|
||||
function detailHref(id: string): string {
|
||||
return `${ADMIN_CLIENTS_BASE}/${encodeURIComponent(id)}`;
|
||||
}
|
||||
|
||||
function listHref(state: ListState, overrides: Partial<ListState> = {}): string {
|
||||
const s = { ...state, ...overrides };
|
||||
const p = new URLSearchParams();
|
||||
if (s.q) p.set("q", s.q);
|
||||
if (s.page > 1) p.set("page", String(s.page));
|
||||
if (s.pageSize !== DEFAULT_PAGE_SIZE) p.set("pageSize", String(s.pageSize));
|
||||
const qs = p.toString();
|
||||
return qs ? `${ADMIN_CLIENTS_BASE}?${qs}` : ADMIN_CLIENTS_BASE;
|
||||
}
|
||||
|
||||
export function buildClientsListModel(opts: {
|
||||
canWrite?: boolean;
|
||||
clients: OAuth2Client[];
|
||||
csrfToken?: string;
|
||||
t?: Translate;
|
||||
url: URL | URLSearchParams | string;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const query = parseListQuery(opts.url, { defaultPageSize: DEFAULT_PAGE_SIZE });
|
||||
const needle = query.q.toLowerCase();
|
||||
|
||||
const all = opts.clients.map(toClientView);
|
||||
const list = all.filter((c) => !needle || c.name.toLowerCase().includes(needle) || c.id.toLowerCase().includes(needle));
|
||||
|
||||
const page = paginate(list.length, query.page, query.pageSize, { boundaries: 1, siblings: 1 });
|
||||
const start = (page.page - 1) * page.pageSize;
|
||||
const rows = list.slice(start, start + page.pageSize);
|
||||
const state: ListState = { page: page.page, pageSize: page.pageSize, q: query.q };
|
||||
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_CLIENTS_BASE, label: t("admin.nav.section") }, { label: t("admin.clients.title") }],
|
||||
canWrite: opts.canWrite !== false,
|
||||
filterBar: listFilterBar(state, t),
|
||||
pagination: buildPaginationModel(page, (n) => listHref(state, { page: n }), { label: t("admin.clients.pagination"), pageSizes: PAGE_SIZES }),
|
||||
table: listTable(rows, t),
|
||||
title: t("admin.clients.title"),
|
||||
};
|
||||
}
|
||||
|
||||
function listTable(rows: ClientView[], t: Translate) {
|
||||
return {
|
||||
caption: t("admin.clients.title"),
|
||||
columns: [{ label: t("admin.clients.column.name") }, { label: t("admin.clients.column.id") }, { label: t("admin.clients.column.type") }],
|
||||
rows: rows.map((c) => ({
|
||||
cells: [
|
||||
{ rowHeader: { href: detailHref(c.id), text: c.name } },
|
||||
{ className: "cell-muted", text: c.id },
|
||||
{ badge: { label: c.public ? t("admin.clients.public") : t("admin.clients.confidential"), tone: c.public ? "warn" : "info" } },
|
||||
],
|
||||
name: c.name,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function listFilterBar(state: ListState, t: Translate) {
|
||||
const pills: { label: string; remove: string; value: string }[] = [];
|
||||
if (state.q) pills.push({ label: t("filter.search"), remove: listHref(state, { page: 1, q: "" }), value: state.q });
|
||||
return {
|
||||
applyLabel: t("filter.apply"),
|
||||
clearHref: ADMIN_CLIENTS_BASE,
|
||||
label: t("admin.clients.filter"),
|
||||
pills,
|
||||
rows: [[
|
||||
{ label: t("admin.clients.searchLabel"), name: "q", placeholder: t("admin.clients.searchPlaceholder"), type: "search", value: state.q },
|
||||
{ type: "spacer" },
|
||||
]],
|
||||
};
|
||||
}
|
||||
|
||||
// ---- register form + detail view models ----
|
||||
|
||||
export function buildClientFormModel(opts: {
|
||||
csrfToken?: string;
|
||||
error?: string;
|
||||
t?: Translate;
|
||||
values?: Partial<ClientInput>;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const v = opts.values;
|
||||
const nameField: FieldConfig = {
|
||||
autocomplete: "off", icon: "i-box", id: "name", label: t("admin.clients.field.name"), name: "name", required: true, value: v?.name ?? "",
|
||||
};
|
||||
const scopeField: FieldConfig = {
|
||||
hint: t("admin.clients.field.scopesHint"), id: "scope", label: t("admin.clients.field.scopes"), name: "scope",
|
||||
value: v?.scope ?? DEFAULT_SCOPE,
|
||||
};
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_CLIENTS_BASE, label: t("admin.clients.title") }, { label: t("admin.clients.register") }],
|
||||
error: opts.error,
|
||||
form: {
|
||||
action: ADMIN_CLIENTS_BASE,
|
||||
cancelHref: ADMIN_CLIENTS_BASE,
|
||||
csrfToken: opts.csrfToken ?? "",
|
||||
firstParty: v?.firstParty ?? false,
|
||||
nameField,
|
||||
public: v?.public ?? false,
|
||||
redirectUris: (v?.redirectUris ?? []).join("\n"),
|
||||
scopeField,
|
||||
submitLabel: t("admin.clients.registerClient"),
|
||||
},
|
||||
title: t("admin.clients.registerTitle"),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildClientDetailModel(opts: {
|
||||
canWrite?: boolean;
|
||||
client: ClientView;
|
||||
created?: boolean; // just registered → success banner + the one-time secret (if any)
|
||||
csrfToken?: string;
|
||||
secret?: string; // one-time client_secret (confidential clients), shown once right after create
|
||||
t?: Translate;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const base = detailHref(opts.client.id);
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_CLIENTS_BASE, label: t("admin.clients.title") }, { label: opts.client.name }],
|
||||
canWrite: opts.canWrite !== false,
|
||||
client: opts.client,
|
||||
created: opts.created ?? false,
|
||||
csrfToken: opts.csrfToken ?? "",
|
||||
delete: { action: `${base}/delete` },
|
||||
secret: opts.secret,
|
||||
title: opts.created ? t("admin.clients.created") : opts.client.name,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- request handler (imperative shell) ----
|
||||
|
||||
function readClientInput(form: URLSearchParams): ClientInput {
|
||||
return {
|
||||
firstParty: form.get("firstParty") === "on",
|
||||
name: (form.get("name") ?? "").trim(),
|
||||
public: form.get("public") === "on",
|
||||
redirectUris: parseRedirectUris(form.get("redirectUris") ?? ""),
|
||||
scope: (form.get("scope") ?? "").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
// Shared per-request deps for the OAuth2-clients screen, resolved by `withClients`: the gate + the
|
||||
// Hydra capability (else a themed 503). Each route below is a thin handler over these.
|
||||
interface ClientsDeps { ctx: RequestContext; hydra: HydraAdmin; user: User; }
|
||||
|
||||
function withClients(inner: (deps: ClientsDeps) => Promise<RouteResult>, action?: AdminAction): RouteHandler {
|
||||
return async (ctx) => {
|
||||
const user = requirePermission(ctx, "oauth2-clients", action);
|
||||
const hydra = ctx.system?.hydra;
|
||||
if (!hydra) return unavailable(ctx, ctx.t("admin.capability.hydra"));
|
||||
return inner({ ctx, hydra, user });
|
||||
};
|
||||
}
|
||||
|
||||
// Same, plus the target client from ctx.params.id (unknown → themed 404).
|
||||
function withClient(inner: (deps: ClientsDeps, client: OAuth2Client, id: string) => Promise<RouteResult>, action?: AdminAction): RouteHandler {
|
||||
return withClients(async (deps) => {
|
||||
const id = deps.ctx.params["id"] ?? "";
|
||||
const client = await deps.hydra.getClient(id);
|
||||
if (!client) return notFound(deps.ctx);
|
||||
return inner(deps, client, id);
|
||||
}, action);
|
||||
}
|
||||
|
||||
const clientFormResult = (ctx: RequestContext, extra: { error?: string; values?: Partial<ClientInput> }): RouteResult =>
|
||||
({ data: { chrome: ctx.chrome, model: buildClientFormModel({ csrfToken: ctx.chrome.csrfToken, t: ctx.t, ...extra }) }, view: "client-form" });
|
||||
const canWriteClients = (ctx: RequestContext): boolean => can(ctx, permissionName("oauth2-clients", "write"));
|
||||
|
||||
const clientDetailResult = (ctx: RequestContext, client: OAuth2Client, extra: { created?: boolean; secret?: string } = {}): RouteResult =>
|
||||
({ data: { chrome: ctx.chrome, model: buildClientDetailModel({ canWrite: canWriteClients(ctx), client: toClientView(client), csrfToken: ctx.chrome.csrfToken, t: ctx.t, ...extra }) }, view: "client-detail" });
|
||||
|
||||
// GET /auth-admin/clients — the list.
|
||||
export const clientsList = withClients(async ({ ctx, hydra }) => {
|
||||
const { clients } = await hydra.listClients({ pageSize: LIST_FETCH_SIZE });
|
||||
return { data: { chrome: ctx.chrome, model: buildClientsListModel({ canWrite: canWriteClients(ctx), clients, csrfToken: ctx.chrome.csrfToken, t: ctx.t, url: ctx.url }) }, view: "clients" };
|
||||
});
|
||||
|
||||
// POST /auth-admin/clients — register; on success show the one-time secret directly (no PRG, Hydra never
|
||||
// returns it again). A Hydra 4xx (bad redirect/scope) re-renders the form (400); a 5xx rethrows → 500.
|
||||
export const clientsCreate = withClients(async ({ ctx, hydra, user }) => {
|
||||
const input = readClientInput((await guardedForm(ctx))!);
|
||||
const error = validateClientInput(input, ctx.t);
|
||||
if (error) return { ...clientFormResult(ctx, { error, values: input }), status: 400 };
|
||||
let created: OAuth2Client;
|
||||
try {
|
||||
created = await hydra.createClient(clientPayload(input));
|
||||
} catch (err) {
|
||||
if (err instanceof HydraError && err.status < 500) return { ...clientFormResult(ctx, { error: ctx.t("admin.clients.error.rejected"), values: input }), status: 400 };
|
||||
throw err;
|
||||
}
|
||||
ctx.log.info("admin: oauth2 client registered", { actor: user.id, client: created.client_id ?? "" });
|
||||
return clientDetailResult(ctx, created, { created: true, ...(created.client_secret ? { secret: created.client_secret } : {}) });
|
||||
});
|
||||
|
||||
// GET /auth-admin/clients/new — the register form.
|
||||
export const clientsNewForm = withClients(({ ctx }) => Promise.resolve(clientFormResult(ctx, {})), "write");
|
||||
|
||||
// GET /auth-admin/clients/:id — the detail (read-only; the secret is shown only once, at creation).
|
||||
export const clientsDetail = withClient((deps, client) => Promise.resolve(clientDetailResult(deps.ctx, client)));
|
||||
|
||||
// GET /auth-admin/clients/:id/delete — the deliberate confirm step.
|
||||
export const clientsDeleteConfirm = withClient((deps, client, id) => {
|
||||
const base = detailHref(id);
|
||||
const name = toClientView(client).name;
|
||||
const tt = deps.ctx.t;
|
||||
return Promise.resolve({ data: { chrome: deps.ctx.chrome, model: buildConfirmModel({
|
||||
breadcrumbs: [{ href: ADMIN_CLIENTS_BASE, label: tt("admin.clients.title") }, { href: base, label: name }, { label: tt("common.delete") }],
|
||||
cancelHref: base, confirmAction: `${base}/delete`, confirmLabel: tt("admin.clients.delete"),
|
||||
message: tt("admin.clients.deleteMessage", { name }), title: tt("admin.clients.delete"),
|
||||
}) }, view: "confirm" });
|
||||
}, "write");
|
||||
|
||||
// POST /auth-admin/clients/:id/delete — perform it.
|
||||
export const clientsDelete = withClient(async ({ ctx, hydra, user }, _client, id) => {
|
||||
await guardedForm(ctx); // CSRF-verify the POST
|
||||
await hydra.deleteClient(id);
|
||||
ctx.log.info("admin: oauth2 client deleted", { actor: user.id, client: id });
|
||||
return { redirect: ADMIN_CLIENTS_BASE };
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
// The pure half of permission granting: what a submitted checkbox set changes, and the picker the
|
||||
// two screens render from it. The Keto writes and the HTTP round trip are covered in src/http/app-admin.test.ts.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { PermissionDecl } from "@plainpages/plugin-api";
|
||||
import type { KetoClient } from "@plainpages/plugin-api";
|
||||
import { applyGrants, baselineToken, buildPermissionPicker, grantDiff, grantTuple, groupSubject, isStale, userSubject } from "./admin-grants.ts";
|
||||
|
||||
const declared: PermissionDecl[] = [
|
||||
{ description: "View users", name: "users:read" },
|
||||
{ description: "Edit users", name: "users:write" },
|
||||
{ name: "groups:read" },
|
||||
];
|
||||
|
||||
test("grantTuple targets a user by subject_id and a group by subject_set", () => {
|
||||
assert.deepEqual(grantTuple("users:read", userSubject("u1")), { namespace: "Permission", object: "users:read", relation: "granted", subject_id: "user:u1" });
|
||||
assert.deepEqual(grantTuple("users:read", groupSubject("eng")), {
|
||||
namespace: "Permission", object: "users:read", relation: "granted",
|
||||
subject_set: { namespace: "Group", object: "eng", relation: "members" },
|
||||
});
|
||||
});
|
||||
|
||||
test("grantDiff: the submitted set is the desired state — tick grants, untick revokes, unchanged is a no-op", () => {
|
||||
assert.deepEqual(grantDiff(declared, ["users:read"], ["users:read", "users:write"]), { grant: ["users:write"], revoke: [] });
|
||||
assert.deepEqual(grantDiff(declared, ["users:read", "users:write"], ["users:read"]), { grant: [], revoke: ["users:write"] });
|
||||
assert.deepEqual(grantDiff(declared, ["users:read"], ["users:read"]), { grant: [], revoke: [] });
|
||||
assert.deepEqual(grantDiff(declared, ["users:read"], []), { grant: [], revoke: ["users:read"] }); // every box cleared
|
||||
});
|
||||
|
||||
test("grantDiff ignores anything the plugins don't declare, in both directions", () => {
|
||||
// A crafted POST can't grant a name no plugin gates on…
|
||||
assert.deepEqual(grantDiff(declared, [], ["superuser:all"]), { grant: [], revoke: [] });
|
||||
// …and a held name that is no longer declared (its plugin was uninstalled) is left alone rather
|
||||
// than silently revoked by an unrelated save — this screen only speaks for what it offered.
|
||||
assert.deepEqual(grantDiff(declared, ["legacy:thing"], ["users:read"]), { grant: ["users:read"], revoke: [] });
|
||||
});
|
||||
|
||||
test("buildPermissionPicker ticks what is held and carries each declaration's description", () => {
|
||||
const picker = buildPermissionPicker({ action: "/auth-admin/users/u1/permissions", declared, direct: ["users:write"] });
|
||||
assert.equal(picker.action, "/auth-admin/users/u1/permissions");
|
||||
assert.deepEqual(picker.choices.map((c) => c.name), ["users:read", "users:write", "groups:read"]);
|
||||
assert.deepEqual(picker.choices.map((c) => c.checked), [false, true, false]);
|
||||
assert.equal(picker.choices[0]?.description, "View users");
|
||||
assert.equal(picker.choices[2]?.description, ""); // a declaration may omit one
|
||||
assert.equal(picker.empty, undefined);
|
||||
assert.equal(picker.readOnly, false);
|
||||
assert.equal(picker.inheritedNote, undefined); // nothing is group-held here
|
||||
});
|
||||
|
||||
// An inherited permission rendered unticked would say "not held" about a grant that reaches the JWT,
|
||||
// and unticking it writes nothing, reading as a successful revoke. So inherited rows are ticked,
|
||||
// disabled, and never posted.
|
||||
test("buildPermissionPicker distinguishes a direct grant from one inherited through a group", () => {
|
||||
const picker = buildPermissionPicker({ action: "/x", declared, direct: ["users:write"], effective: ["users:read", "users:write"] });
|
||||
assert.deepEqual(picker.choices.map((c) => [c.name, c.checked, c.inherited]), [
|
||||
["users:read", true, true], // effective but not direct → shown as held, not editable here
|
||||
["users:write", true, false], // direct → editable
|
||||
["groups:read", false, false],
|
||||
]);
|
||||
assert.ok(picker.inheritedNote, "the disabled row needs an explanation");
|
||||
});
|
||||
|
||||
test("buildPermissionPicker in read-only mode still shows the state, and marks itself unwritable", () => {
|
||||
const picker = buildPermissionPicker({ action: "/x", declared, direct: ["users:read"], effective: ["users:read", "groups:read"], readOnly: true });
|
||||
assert.equal(picker.readOnly, true);
|
||||
assert.deepEqual(picker.choices.map((c) => c.checked), [true, false, true]); // a reader still sees who holds what
|
||||
// Every row renders disabled for a reader, so the writable copy would be wrong twice over: "tick to
|
||||
// grant" is false, and "greyed-out means group-held" would misattribute the direct grant.
|
||||
assert.equal(picker.inheritedNote, undefined);
|
||||
assert.notEqual(picker.hint, buildPermissionPicker({ action: "/x", declared, direct: [] }).hint);
|
||||
});
|
||||
|
||||
test("buildPermissionPicker notes the transitive lag for a group, and stays quiet for a user", () => {
|
||||
// A group's members inherit, so the change reaches them at their next re-mint; a user's own grant
|
||||
// change revokes their live tokens, so there is nothing to warn about.
|
||||
assert.ok(buildPermissionPicker({ action: "/x", declared, direct: [], transitive: true }).pending);
|
||||
assert.equal(buildPermissionPicker({ action: "/x", declared, direct: [] }).pending, undefined);
|
||||
});
|
||||
|
||||
test("buildPermissionPicker says so when no plugin declares a permission, rather than rendering an empty box", () => {
|
||||
const picker = buildPermissionPicker({ action: "/x", declared: [], direct: [] });
|
||||
assert.deepEqual(picker.choices, []);
|
||||
assert.ok(picker.empty);
|
||||
});
|
||||
|
||||
test("baselineToken depends on the offered grants held, not on their order or on undeclared ones", () => {
|
||||
const token = baselineToken(declared, ["users:read", "users:write"]);
|
||||
assert.match(token, /^[0-9a-f]+$/);
|
||||
assert.equal(baselineToken(declared, ["users:write", "users:read"]), token);
|
||||
assert.equal(baselineToken(declared, ["users:read", "users:write", "legacy:thing"]), token); // undeclared: never shown, never saved
|
||||
assert.notEqual(baselineToken(declared, ["users:read"]), token);
|
||||
assert.notEqual(baselineToken(declared, []), token);
|
||||
assert.notEqual(baselineToken(declared, []), ""); // an empty set is a state too, not an absent token
|
||||
assert.equal(buildPermissionPicker({ action: "/x", declared, direct: ["users:read", "users:write"] }).baseline, token);
|
||||
});
|
||||
|
||||
test("isStale refuses a missing or old token, but only for a save that would change something", () => {
|
||||
const held = ["users:read"];
|
||||
const change = grantDiff(declared, held, ["users:read", "users:write"]);
|
||||
const nothing = grantDiff(declared, held, ["users:read"]);
|
||||
const current = new URLSearchParams({ baseline: baselineToken(declared, held) });
|
||||
const old = new URLSearchParams({ baseline: baselineToken(declared, []) });
|
||||
assert.equal(isStale(current, declared, held, change), false);
|
||||
assert.equal(isStale(old, declared, held, change), true);
|
||||
assert.equal(isStale(new URLSearchParams(), declared, held, change), true); // no token at all
|
||||
assert.equal(isStale(old, declared, held, nothing), false); // a repeated save has nothing to refuse
|
||||
});
|
||||
|
||||
test("applyGrants applies writes then deletes, and on a Keto failure stops and reports what was applied", async () => {
|
||||
const log: string[] = [];
|
||||
const keto = (failOn?: string): KetoClient => ({
|
||||
check: async () => false,
|
||||
deleteTuple: async (tp) => { if (tp.object === failOn) throw new Error("boom"); log.push(`delete ${tp.object}`); },
|
||||
expand: async () => ({ type: "leaf" }),
|
||||
listRelations: async () => ({ nextPageToken: null, tuples: [] }),
|
||||
writeTuple: async (tp) => { if (tp.object === failOn) throw new Error("boom"); log.push(`write ${tp.object}`); },
|
||||
});
|
||||
const diff = { grant: ["a:read", "b:read"], revoke: ["c:read"] };
|
||||
|
||||
const ok = await applyGrants(keto(), userSubject("u1"), diff);
|
||||
assert.deepEqual(ok, { applied: diff });
|
||||
assert.deepEqual(log, ["write a:read", "write b:read", "delete c:read"]);
|
||||
|
||||
log.length = 0;
|
||||
const failed = await applyGrants(keto("b:read"), userSubject("u1"), diff);
|
||||
assert.deepEqual(failed.applied, { grant: ["a:read"], revoke: [] });
|
||||
assert.ok(failed.error instanceof Error);
|
||||
assert.deepEqual(log, ["write a:read"]); // nothing after the failure was attempted
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
// Permission grants, shared by the Users and Groups screens. A permission is held by a user
|
||||
// (`Permission:<name>#granted@user:<id>`) or by a whole group (`…@Group:<name>#members`), and Keto
|
||||
// resolves a group's grant transitively at login.
|
||||
//
|
||||
// The set of permissions that *exist* is `ctx.declaredPermissions` — the host's catalog, built from
|
||||
// what the installed plugins declare in code. Nothing here invents a name, which is why the old
|
||||
// Permissions screen is gone: a grant is a property of a user or a group, edited where they are.
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import type { KetoClient, PermissionDecl, RelationTuple, SubjectSet, Translate } from "@plainpages/plugin-api";
|
||||
|
||||
const PERMISSION_NS = "Permission";
|
||||
const GRANTED = "granted";
|
||||
export const PERMISSIONS_FIELD = "permission"; // the checkbox name the two forms post
|
||||
export const BASELINE_FIELD = "baseline"; // the hidden field carrying baselineToken
|
||||
export const SAVED_NOTICE = "permissions-saved"; // the `info-msg` a successful save redirects with
|
||||
|
||||
// Only that exact value counts, so a crafted link can't put words on the page.
|
||||
export const isSavedNotice = (url: URL): boolean => url.searchParams.get("info-msg") === SAVED_NOTICE;
|
||||
|
||||
export type GrantSubject = { subject_id: string } | { subject_set: SubjectSet };
|
||||
|
||||
export const userSubject = (id: string): GrantSubject => ({ subject_id: `user:${id}` });
|
||||
export const groupSubject = (name: string): GrantSubject => ({ subject_set: { namespace: "Group", object: name, relation: "members" } });
|
||||
|
||||
export function grantTuple(permission: string, subject: GrantSubject): RelationTuple {
|
||||
return { namespace: PERMISSION_NS, object: permission, relation: GRANTED, ...subject };
|
||||
}
|
||||
|
||||
// The permissions this subject holds *directly* — one Keto read filtered by the subject, not one per
|
||||
// declared name. This is the edge the picker edits; `effectivePermissions` adds what a group confers.
|
||||
export async function heldPermissions(keto: KetoClient, subject: GrantSubject): Promise<string[]> {
|
||||
const held = new Set<string>();
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const page = await keto.listRelations({ namespace: PERMISSION_NS, relation: GRANTED, ...subject, ...(pageToken ? { pageToken } : {}) });
|
||||
for (const tuple of page.tuples) held.add(tuple.object);
|
||||
pageToken = page.nextPageToken ?? undefined;
|
||||
} while (pageToken);
|
||||
return [...held].sort();
|
||||
}
|
||||
|
||||
// Every declared permission the subject effectively holds — direct grants *plus* anything reached
|
||||
// through a group, which is what actually lands in their JWT. One Keto check per declared name;
|
||||
// the catalog is small and this is an admin screen (login does the same walk).
|
||||
export async function effectivePermissions(keto: KetoClient, subject: GrantSubject, declared: readonly PermissionDecl[]): Promise<string[]> {
|
||||
const held = await Promise.all(declared.map((decl) => keto.check({ namespace: PERMISSION_NS, object: decl.name, relation: GRANTED, ...subject })));
|
||||
return declared.filter((_, i) => held[i]).map((decl) => decl.name);
|
||||
}
|
||||
|
||||
export interface PermissionChoice {
|
||||
checked: boolean; // held directly — the only state this form can change
|
||||
description: string;
|
||||
// Effective through a group, not granted directly. Rendered ticked but disabled: the grant is real
|
||||
// (it reaches the JWT), and it is removed by editing the group, not this subject.
|
||||
inherited: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface PermissionPicker {
|
||||
action: string;
|
||||
baseline: string; // baselineToken of the direct grants this form was rendered from
|
||||
choices: PermissionChoice[];
|
||||
empty: string | undefined; // set when no plugin declares a permission — the picker has nothing to offer
|
||||
error?: string; // a rejected save (e.g. the self-revoke guard), rendered above the list
|
||||
field: string;
|
||||
hint: string;
|
||||
inheritedNote: string | undefined; // set when at least one choice is group-held, to explain the disabled row
|
||||
legend: string;
|
||||
notice?: string; // a confirmation, rendered above the list
|
||||
// Set for a group: its members hold these transitively, so a change reaches them at their next
|
||||
// re-mint rather than at once. The user picker revokes live tokens, so it says nothing.
|
||||
pending: string | undefined;
|
||||
readOnly: boolean; // the viewer holds :read but not :write — show the state, offer no save
|
||||
submit: string;
|
||||
}
|
||||
|
||||
// The checkbox list: every declared permission, ticked where this subject holds it. A fixed list
|
||||
// means the form is the whole truth — what it posts back *is* the desired set of *direct* grants
|
||||
// (grantDiff). An inherited row is disabled, so it never posts and can never be diffed into a revoke.
|
||||
export function buildPermissionPicker(opts: {
|
||||
action: string;
|
||||
declared: readonly PermissionDecl[];
|
||||
direct: string[];
|
||||
effective?: string[]; // omit when the caller can't resolve group-held grants; then only direct shows
|
||||
readOnly?: boolean;
|
||||
t?: Translate;
|
||||
transitive?: boolean; // a group: its members inherit, so the change lands at their next re-mint
|
||||
}): PermissionPicker {
|
||||
const t = opts.t ?? ((k: string) => k);
|
||||
const directSet = new Set(opts.direct);
|
||||
const effectiveSet = new Set(opts.effective ?? opts.direct);
|
||||
const choices = opts.declared.map((decl) => ({
|
||||
checked: directSet.has(decl.name) || effectiveSet.has(decl.name),
|
||||
description: decl.description ?? "",
|
||||
inherited: !directSet.has(decl.name) && effectiveSet.has(decl.name),
|
||||
name: decl.name,
|
||||
}));
|
||||
return {
|
||||
action: opts.action,
|
||||
baseline: baselineToken(opts.declared, opts.direct),
|
||||
choices,
|
||||
empty: opts.declared.length === 0 ? t("admin.grants.none") : undefined,
|
||||
field: PERMISSIONS_FIELD,
|
||||
// A reader sees every row disabled, so "tick to grant" is false and "greyed-out means group-held"
|
||||
// is worse than false — it would misattribute a *direct* grant to a group that doesn't hold it.
|
||||
hint: t(opts.readOnly === true ? "admin.grants.hintReadOnly" : "admin.grants.hint"),
|
||||
inheritedNote: opts.readOnly !== true && choices.some((c) => c.inherited) ? t("admin.grants.inherited") : undefined,
|
||||
legend: t("admin.grants.legend"),
|
||||
pending: opts.transitive === true ? t("admin.grants.pending") : undefined,
|
||||
readOnly: opts.readOnly === true,
|
||||
submit: t("admin.grants.save"),
|
||||
};
|
||||
}
|
||||
|
||||
// What a submitted set changes. Pure so the diff is testable without Keto: only declared names are
|
||||
// considered, so a crafted POST cannot grant something no plugin gates on, and a held-but-undeclared
|
||||
// name (left over from an uninstalled plugin) is never silently revoked by an unrelated save.
|
||||
export function grantDiff(declared: readonly PermissionDecl[], held: string[], wanted: string[]): GrantChange {
|
||||
const offered = new Set(declared.map((d) => d.name));
|
||||
const heldSet = new Set(held);
|
||||
const wantedSet = new Set(wanted.filter((name) => offered.has(name)));
|
||||
return {
|
||||
grant: [...wantedSet].filter((name) => !heldSet.has(name)).sort(),
|
||||
revoke: [...heldSet].filter((name) => offered.has(name) && !wantedSet.has(name)).sort(),
|
||||
};
|
||||
}
|
||||
|
||||
// A token for the direct grants a form was rendered from. Like grantDiff it covers only the declared
|
||||
// names the form offered. It is a digest so an empty set is still a token; it is a guard against a
|
||||
// stale page, not a secret, since anyone who can read the page can compute it.
|
||||
export function baselineToken(declared: readonly PermissionDecl[], held: string[]): string {
|
||||
const offered = new Set(declared.map((d) => d.name));
|
||||
return createHash("sha256").update(held.filter((name) => offered.has(name)).sort().join("\n")).digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
// True when the form's token is missing or no longer matches Keto *and* the save would change
|
||||
// something. A save that changes nothing, such as a double-clicked Save whose first POST landed, is
|
||||
// harmless, so it is not refused.
|
||||
export const isStale = (form: { get(name: string): string | null }, declared: readonly PermissionDecl[], held: string[], diff: GrantChange): boolean =>
|
||||
(diff.grant.length > 0 || diff.revoke.length > 0) && form.get(BASELINE_FIELD) !== baselineToken(declared, held);
|
||||
|
||||
export interface GrantChange { grant: string[]; revoke: string[] }
|
||||
|
||||
// KetoClient writes one tuple per call, so the writes and deletes run one by one and stop at the first
|
||||
// failure. What was applied by then is returned beside the error, so the caller can still revoke live
|
||||
// tokens and tell the admin the save is only partly done.
|
||||
export async function applyGrants(keto: KetoClient, subject: GrantSubject, diff: GrantChange): Promise<{ applied: GrantChange; error?: unknown }> {
|
||||
const applied: GrantChange = { grant: [], revoke: [] };
|
||||
try {
|
||||
for (const name of diff.grant) { await keto.writeTuple(grantTuple(name, subject)); applied.grant.push(name); }
|
||||
for (const name of diff.revoke) { await keto.deleteTuple(grantTuple(name, subject)); applied.revoke.push(name); }
|
||||
} catch (error) {
|
||||
return { applied, error };
|
||||
}
|
||||
return { applied };
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// Built-in Groups admin screen: the pure view-model + Keto-tuple builders. A group is a
|
||||
// Keto subject set (Group:<name>#members); membership tuples carry users (subject_id) or nested
|
||||
// groups (subject_set). The HTTP routing/gate/CSRF + live Keto/Kratos calls are exercised over
|
||||
// HTTP in src/http/app-admin.test.ts.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
buildGroupDetailModel,
|
||||
buildGroupFormModel,
|
||||
buildGroupsListModel,
|
||||
groupsFromTuples,
|
||||
isValidGroupName,
|
||||
memberTuple,
|
||||
memberView,
|
||||
parseSubject,
|
||||
} from "./admin-groups.ts";
|
||||
import type { RelationTuple } from "@plainpages/plugin-api";
|
||||
|
||||
const uid = (n: number) => `01902d5e-7b6c-7e3a-9f21-3c8d1e0a4b${String(n).padStart(2, "0")}`;
|
||||
const userTuple = (group: string, n: number): RelationTuple =>
|
||||
({ namespace: "Group", object: group, relation: "members", subject_id: `user:${uid(n)}` });
|
||||
const groupTuple = (group: string, child: string): RelationTuple =>
|
||||
({ namespace: "Group", object: group, relation: "members", subject_set: { namespace: "Group", object: child, relation: "members" } });
|
||||
|
||||
test("isValidGroupName accepts URL-safe names, rejects empties/spaces/uppercase/leading punctuation", () => {
|
||||
for (const ok of ["eng", "team-a", "a1_b9", "x"]) assert.equal(isValidGroupName(ok), true, ok);
|
||||
for (const bad of ["", "Eng", "a b", "-bad", "_bad", "a/b", "a".repeat(65)]) assert.equal(isValidGroupName(bad), false, bad);
|
||||
});
|
||||
|
||||
test("parseSubject + memberTuple map the form value to the user/nested-group subject (else null)", () => {
|
||||
assert.deepEqual(parseSubject(`user:${uid(1)}`), { subject_id: `user:${uid(1)}` });
|
||||
assert.deepEqual(parseSubject("group:eng"), { subject_set: { namespace: "Group", object: "eng", relation: "members" } });
|
||||
// Both forms are validated: a non-UUID user / invalid group name is rejected, not written blindly.
|
||||
for (const bad of ["", "user:", "user:not-a-uuid", "group:", "group:Bad Name", "nope:x", "plain"]) assert.equal(parseSubject(bad), null, bad);
|
||||
|
||||
assert.deepEqual(memberTuple("design", `user:${uid(2)}`), { namespace: "Group", object: "design", relation: "members", subject_id: `user:${uid(2)}` });
|
||||
assert.deepEqual(memberTuple("design", "group:eng"), { namespace: "Group", object: "design", relation: "members", subject_set: { namespace: "Group", object: "eng", relation: "members" } });
|
||||
assert.equal(memberTuple("design", "bad"), null);
|
||||
});
|
||||
|
||||
test("groupsFromTuples collapses membership tuples → distinct groups + member counts, sorted by name", () => {
|
||||
const tuples = [userTuple("eng", 1), userTuple("eng", 2), groupTuple("eng", "design"), userTuple("design", 3)];
|
||||
assert.deepEqual(groupsFromTuples(tuples), [
|
||||
{ memberCount: 1, name: "design" },
|
||||
{ memberCount: 3, name: "eng" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("memberView resolves a user subject to its email (else the raw id) and a subject_set to the group", () => {
|
||||
const emails = new Map([[uid(1), "ada@example.com"]]);
|
||||
assert.deepEqual(memberView(userTuple("eng", 1), emails), { kind: "user", label: "ada@example.com", subject: `user:${uid(1)}` });
|
||||
assert.deepEqual(memberView(userTuple("eng", 9), emails), { kind: "user", label: `user:${uid(9)}`, subject: `user:${uid(9)}` });
|
||||
assert.deepEqual(memberView(groupTuple("eng", "design"), emails), { kind: "group", label: "design", subject: "group:design" });
|
||||
});
|
||||
|
||||
test("buildGroupsListModel filters by search, sorts, paginates; the name links to the detail page", () => {
|
||||
const groups = Array.from({ length: 30 }, (_, i) => ({ memberCount: i + 1, name: `team-${String(i).padStart(2, "0")}` }));
|
||||
|
||||
const all = buildGroupsListModel({ groups, url: "http://x/auth-admin/groups" });
|
||||
assert.equal(all.pagination.summary.total, 30);
|
||||
assert.equal(all.table.rows.length, 25); // default page size
|
||||
assert.equal(all.title, "Groups");
|
||||
// The group name is the row header, linking to its detail page.
|
||||
const first = all.table.rows[0]!.cells[0] as { rowHeader: { href: string; text: string } };
|
||||
assert.equal(first.rowHeader.text, "team-00");
|
||||
assert.equal(first.rowHeader.href, "/auth-admin/groups/team-00");
|
||||
|
||||
// Search narrows + shows a pill.
|
||||
const one = buildGroupsListModel({ groups, url: "http://x/auth-admin/groups?q=team-07" });
|
||||
assert.equal(one.pagination.summary.total, 1);
|
||||
assert.deepEqual(one.filterBar.pills.map((p) => p.label), ["Search"]);
|
||||
|
||||
// Sort by members descending puts the biggest group first.
|
||||
const desc = buildGroupsListModel({ groups, url: "http://x/auth-admin/groups?sort=-members" });
|
||||
assert.equal((desc.table.rows[0]!.cells[0] as { rowHeader: { text: string } }).rowHeader.text, "team-29");
|
||||
});
|
||||
|
||||
test("buildGroupFormModel: a create form with a required name field + member options, no group of its own", () => {
|
||||
const options = [{ label: "ada@example.com", value: `user:${uid(1)}` }, { label: "eng (group)", value: "group:eng" }];
|
||||
const m = buildGroupFormModel({ csrfToken: "tok.sig", memberOptions: options });
|
||||
assert.equal(m.title, "New group");
|
||||
assert.equal(m.form.action, "/auth-admin/groups");
|
||||
assert.equal(m.form.submitLabel, "Create group");
|
||||
assert.equal(m.form.csrfToken, "tok.sig");
|
||||
assert.equal(m.form.nameField.name, "name");
|
||||
assert.equal(m.form.nameField.required, true);
|
||||
assert.deepEqual(m.form.memberOptions, options);
|
||||
|
||||
// An error (e.g. a taken/invalid name) re-renders with the submitted values.
|
||||
const err = buildGroupFormModel({ error: "That name is taken.", memberOptions: options, values: { member: "group:eng", name: "Eng" } });
|
||||
assert.equal(err.error, "That name is taken.");
|
||||
assert.equal(err.form.nameField.value, "Eng");
|
||||
assert.equal(err.form.selectedMember, "group:eng");
|
||||
});
|
||||
|
||||
test("buildGroupDetailModel: members → rows, add-options exclude current members + the group itself, delete/remove wired", () => {
|
||||
const members = [memberView(userTuple("eng", 1), new Map([[uid(1), "ada@example.com"]])), memberView(groupTuple("eng", "design"), new Map())];
|
||||
const candidates = [
|
||||
{ label: "ada@example.com", value: `user:${uid(1)}` }, // already a member → excluded
|
||||
{ label: "grace@example.com", value: `user:${uid(2)}` },
|
||||
{ label: "design (group)", value: "group:design" }, // already a member → excluded
|
||||
{ label: "eng (group)", value: "group:eng" }, // the group itself → excluded
|
||||
{ label: "ops (group)", value: "group:ops" },
|
||||
];
|
||||
const m = buildGroupDetailModel({ candidates, group: { name: "eng" }, members });
|
||||
assert.equal(m.title, "eng");
|
||||
assert.equal(m.members.rows.length, 2);
|
||||
assert.equal(m.members.action, "/auth-admin/groups/eng/members/delete");
|
||||
assert.equal(m.add.action, "/auth-admin/groups/eng/members");
|
||||
assert.deepEqual(m.add.options.map((o) => o.value), [`user:${uid(2)}`, "group:ops"]);
|
||||
assert.equal(m.delete.action, "/auth-admin/groups/eng/delete");
|
||||
});
|
||||
@@ -0,0 +1,459 @@
|
||||
// Groups admin screen: list / create / delete Keto groups and manage membership.
|
||||
// A group is a Keto subject set `Group:<name>#members`; a member is a user or a nested group (see
|
||||
// parseSubject). Writes go only to Keto (README "stateless"). Keto has no "create object" — a group
|
||||
// exists exactly while it has ≥1 member, so create writes its first-member tuple and delete removes
|
||||
// every member tuple. Pure builders turn tuples + the request URL into view models; below them are thin
|
||||
// per-route handlers (keyed on ctx.params) over a shared `withGroups` gate — admin-only, CSRF-guarded,
|
||||
// each returning a RouteResult.
|
||||
|
||||
import { buildPaginationModel, can, type KetoClient, type KratosAdmin, paginate, parseListQuery, type RelationQuery, type RelationTuple, type RequestContext, type RouteHandler, type RouteResult, type SubjectSet, type Translate, type User } from "@plainpages/plugin-api";
|
||||
import { applyGrants, buildPermissionPicker, effectivePermissions, grantDiff, grantTuple, groupSubject, heldPermissions, isSavedNotice, isStale, type PermissionPicker, PERMISSIONS_FIELD, SAVED_NOTICE, userSubject } from "./admin-grants.ts";
|
||||
import { ADMIN_EN, type AdminAction, ADMIN_GROUPS_BASE, buildConfirmModel, guardedForm, notFound, partialSave, permissionName, requirePermission, unavailable } from "./admin-shared.ts";
|
||||
import type { FieldConfig } from "./admin-users.ts";
|
||||
|
||||
const GROUP_NS = "Group";
|
||||
const MEMBERS = "members";
|
||||
const DEFAULT_PAGE_SIZE = 25;
|
||||
const PAGE_SIZES = [25, 50, 100];
|
||||
// One Keto page of candidate users is fetched for the member pickers (mirrors admin-users).
|
||||
const LIST_FETCH_SIZE = 250;
|
||||
const GROUP_NAME = /^[a-z0-9][a-z0-9_-]*$/; // URL-safe; doubles as the path segment
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; // a Kratos identity id
|
||||
|
||||
export interface GroupView {
|
||||
memberCount: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
// A member's view model: a user (label = email) or a nested group (label = group name). `subject`
|
||||
// is the form value that round-trips it — `user:<id>` or `group:<name>` (see parseSubject).
|
||||
export interface MemberView {
|
||||
kind: "group" | "user";
|
||||
label: string;
|
||||
subject: string;
|
||||
}
|
||||
|
||||
// One option in a member <select>.
|
||||
export interface MemberOption {
|
||||
label: string;
|
||||
value: string; // `user:<id>` | `group:<name>`
|
||||
}
|
||||
|
||||
export function isValidGroupName(name: string): boolean {
|
||||
return name.length <= 64 && GROUP_NAME.test(name);
|
||||
}
|
||||
|
||||
// Map a member-picker value → the Keto subject (subject_id for a user, subject_set for a nested
|
||||
// group). Returns null for anything unrecognised (a crafted/empty POST).
|
||||
export function parseSubject(value: string): { subject_id: string } | { subject_set: SubjectSet } | null {
|
||||
const sep = value.indexOf(":");
|
||||
if (sep <= 0) return null;
|
||||
const rest = value.slice(sep + 1);
|
||||
if (!rest) return null;
|
||||
// Validate both subject forms so a crafted POST can't write a dangling tuple (the pickers only
|
||||
// ever offer real users/groups): a user id is a Kratos UUID, a nested group a valid group name.
|
||||
if (value.slice(0, sep) === "user") return UUID.test(rest) ? { subject_id: `user:${rest}` } : null;
|
||||
if (value.slice(0, sep) === "group") return isValidGroupName(rest) ? { subject_set: { namespace: GROUP_NS, object: rest, relation: MEMBERS } } : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
// The full membership tuple for adding/removing `value` to/from `group` (null if value is invalid).
|
||||
export function memberTuple(group: string, value: string): RelationTuple | null {
|
||||
const subject = parseSubject(value);
|
||||
return subject ? { namespace: GROUP_NS, object: group, relation: MEMBERS, ...subject } : null;
|
||||
}
|
||||
|
||||
// Collapse the namespace's membership tuples → distinct groups + member counts, sorted by name.
|
||||
export function groupsFromTuples(tuples: RelationTuple[]): GroupView[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const t of tuples) counts.set(t.object, (counts.get(t.object) ?? 0) + 1);
|
||||
return [...counts].map(([name, memberCount]) => ({ memberCount, name })).sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
export function memberView(tuple: RelationTuple, emailById: Map<string, string>): MemberView {
|
||||
if (tuple.subject_set) return { kind: "group", label: tuple.subject_set.object, subject: `group:${tuple.subject_set.object}` };
|
||||
const subjectId = tuple.subject_id ?? "";
|
||||
const id = subjectId.startsWith("user:") ? subjectId.slice("user:".length) : subjectId;
|
||||
return { kind: "user", label: emailById.get(id) ?? subjectId, subject: subjectId };
|
||||
}
|
||||
|
||||
// ---- list view model ----
|
||||
|
||||
interface ListState {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
q: string;
|
||||
sort: string | null;
|
||||
}
|
||||
|
||||
const SORT: Record<string, (g: GroupView) => number | string> = {
|
||||
members: (g) => g.memberCount,
|
||||
name: (g) => g.name,
|
||||
};
|
||||
const COLUMNS = [
|
||||
{ key: "name", label: "admin.groups.column.name" },
|
||||
{ key: "members", label: "admin.groups.column.members" },
|
||||
];
|
||||
|
||||
function detailHref(name: string): string {
|
||||
return `${ADMIN_GROUPS_BASE}/${encodeURIComponent(name)}`;
|
||||
}
|
||||
|
||||
function listHref(state: ListState, overrides: Partial<ListState> = {}): string {
|
||||
const s = { ...state, ...overrides };
|
||||
const p = new URLSearchParams();
|
||||
if (s.q) p.set("q", s.q);
|
||||
if (s.sort) p.set("sort", s.sort);
|
||||
if (s.page > 1) p.set("page", String(s.page));
|
||||
if (s.pageSize !== DEFAULT_PAGE_SIZE) p.set("pageSize", String(s.pageSize));
|
||||
const qs = p.toString();
|
||||
return qs ? `${ADMIN_GROUPS_BASE}?${qs}` : ADMIN_GROUPS_BASE;
|
||||
}
|
||||
|
||||
export function buildGroupsListModel(opts: {
|
||||
canWrite?: boolean;
|
||||
csrfToken?: string;
|
||||
groups: GroupView[];
|
||||
t?: Translate;
|
||||
url: URL | URLSearchParams | string;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const query = parseListQuery(opts.url, { defaultPageSize: DEFAULT_PAGE_SIZE });
|
||||
const sort = query.sort && SORT[query.sort.field] ? query.sort : null;
|
||||
const sortToken = sort ? (sort.dir === "desc" ? `-${sort.field}` : sort.field) : null;
|
||||
const needle = query.q.toLowerCase();
|
||||
|
||||
let list = opts.groups.filter((g) => !needle || g.name.toLowerCase().includes(needle));
|
||||
if (sort) {
|
||||
const get = SORT[sort.field]!;
|
||||
const dir = sort.dir === "desc" ? -1 : 1;
|
||||
list = [...list].sort((a, b) => {
|
||||
const av = get(a), bv = get(b);
|
||||
const cmp = typeof av === "number" && typeof bv === "number" ? av - bv : String(av).localeCompare(String(bv));
|
||||
return cmp * dir;
|
||||
});
|
||||
}
|
||||
|
||||
const page = paginate(list.length, query.page, query.pageSize, { boundaries: 1, siblings: 1 });
|
||||
const start = (page.page - 1) * page.pageSize;
|
||||
const rows = list.slice(start, start + page.pageSize);
|
||||
const state: ListState = { page: page.page, pageSize: page.pageSize, q: query.q, sort: sortToken };
|
||||
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_GROUPS_BASE, label: t("admin.nav.section") }, { label: t("admin.groups.title") }],
|
||||
canWrite: opts.canWrite !== false,
|
||||
filterBar: listFilterBar(state, t),
|
||||
pagination: buildPaginationModel(page, (n) => listHref(state, { page: n }), { label: t("admin.groups.pagination"), pageSizes: PAGE_SIZES }),
|
||||
table: listTable(rows, state, sort, t),
|
||||
title: t("admin.groups.title"),
|
||||
};
|
||||
}
|
||||
|
||||
function listTable(rows: GroupView[], state: ListState, sort: { dir: "asc" | "desc"; field: string } | null, t: Translate) {
|
||||
return {
|
||||
caption: t("admin.groups.title"),
|
||||
columns: COLUMNS.map((c) => {
|
||||
const dir = sort && sort.field === c.key ? sort.dir : undefined;
|
||||
const next = dir === "asc" ? `-${c.key}` : c.key;
|
||||
return { href: listHref(state, { page: 1, sort: next }), label: t(c.label), sort: dir, sortable: true };
|
||||
}),
|
||||
rows: rows.map((g) => ({
|
||||
cells: [{ rowHeader: { href: detailHref(g.name), text: g.name } }, String(g.memberCount)],
|
||||
name: g.name,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function listFilterBar(state: ListState, t: Translate) {
|
||||
const pills: { label: string; remove: string; value: string }[] = [];
|
||||
if (state.q) pills.push({ label: t("filter.search"), remove: listHref(state, { page: 1, q: "" }), value: state.q });
|
||||
return {
|
||||
applyLabel: t("filter.apply"),
|
||||
clearHref: ADMIN_GROUPS_BASE,
|
||||
label: t("admin.groups.filter"),
|
||||
pills,
|
||||
rows: [[
|
||||
{ label: t("admin.groups.searchLabel"), name: "q", placeholder: t("admin.groups.searchPlaceholder"), type: "search", value: state.q },
|
||||
{ type: "spacer" },
|
||||
]],
|
||||
};
|
||||
}
|
||||
|
||||
// ---- create form + detail view models ----
|
||||
|
||||
export function buildGroupFormModel(opts: {
|
||||
csrfToken?: string;
|
||||
error?: string;
|
||||
memberOptions: MemberOption[];
|
||||
t?: Translate;
|
||||
values?: { member?: string; name?: string };
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const nameField: FieldConfig = {
|
||||
autocomplete: "off", hint: t("admin.groups.field.nameHint"), icon: "i-layers",
|
||||
id: "name", label: t("admin.groups.field.name"), name: "name", required: true, value: opts.values?.name ?? "",
|
||||
};
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_GROUPS_BASE, label: t("admin.groups.title") }, { label: t("common.new") }],
|
||||
error: opts.error,
|
||||
form: {
|
||||
action: ADMIN_GROUPS_BASE,
|
||||
cancelHref: ADMIN_GROUPS_BASE,
|
||||
csrfToken: opts.csrfToken ?? "",
|
||||
memberOptions: opts.memberOptions,
|
||||
nameField,
|
||||
selectedMember: opts.values?.member ?? "",
|
||||
submitLabel: t("admin.groups.create"),
|
||||
},
|
||||
title: t("admin.groups.new"),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildGroupDetailModel(opts: {
|
||||
canWrite?: boolean; // false ⇒ a `groups:read` holder: show the members, offer no edit
|
||||
candidates: MemberOption[];
|
||||
csrfToken?: string;
|
||||
error?: string;
|
||||
group: { name: string };
|
||||
members: MemberView[];
|
||||
permissions?: PermissionPicker;
|
||||
t?: Translate;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const name = opts.group.name;
|
||||
const base = detailHref(name);
|
||||
const taken = new Set(opts.members.map((m) => m.subject));
|
||||
const self = `group:${name}`; // a group can't be a member of itself
|
||||
const options = opts.candidates.filter((c) => c.value !== self && !taken.has(c.value));
|
||||
const canWrite = opts.canWrite !== false;
|
||||
return {
|
||||
add: { action: `${base}/members`, options },
|
||||
breadcrumbs: [{ href: ADMIN_GROUPS_BASE, label: t("admin.groups.title") }, { label: name }],
|
||||
canWrite, // the view drops add/remove/delete when false; the host already 403s those POSTs
|
||||
csrfToken: opts.csrfToken ?? "",
|
||||
delete: { action: `${base}/delete` },
|
||||
error: opts.error,
|
||||
group: { name },
|
||||
members: { action: `${base}/members/delete`, rows: opts.members },
|
||||
permissions: opts.permissions,
|
||||
title: name,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- request handler (imperative shell) ----
|
||||
|
||||
// Drain every page of a relation-tuple query.
|
||||
export async function pagedTuples(keto: KetoClient, query: RelationQuery): Promise<RelationTuple[]> {
|
||||
const out: RelationTuple[] = [];
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const page = await keto.listRelations({ ...query, ...(pageToken ? { pageToken } : {}) });
|
||||
out.push(...page.tuples);
|
||||
pageToken = page.nextPageToken ?? undefined;
|
||||
} while (pageToken);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Build the member-picker options (every user by email + every existing group) and the id→email map
|
||||
// detail rows render with. One Kratos page + one Keto scan; ample for an admin tool.
|
||||
export async function memberCandidates(keto: KetoClient, kratosAdmin: KratosAdmin): Promise<{ emailById: Map<string, string>; options: MemberOption[] }> {
|
||||
const { identities } = await kratosAdmin.listIdentities({ pageSize: LIST_FETCH_SIZE });
|
||||
const emailById = new Map<string, string>();
|
||||
const userOptions: MemberOption[] = [];
|
||||
for (const it of identities) {
|
||||
const trait = it.traits?.["email"];
|
||||
const email = typeof trait === "string" ? trait : it.id;
|
||||
emailById.set(it.id, email);
|
||||
userOptions.push({ label: email, value: `user:${it.id}` });
|
||||
}
|
||||
const groups = groupsFromTuples(await pagedTuples(keto, { namespace: GROUP_NS, relation: MEMBERS }));
|
||||
return { emailById, options: [...userOptions, ...groups.map((g) => ({ label: `${g.name} (group)`, value: `group:${g.name}` }))] };
|
||||
}
|
||||
|
||||
// A group exists exactly while it has ≥1 member.
|
||||
async function groupExists(keto: KetoClient, name: string): Promise<boolean> {
|
||||
const page = await keto.listRelations({ namespace: GROUP_NS, object: name, relation: MEMBERS, pageSize: 1 });
|
||||
return page.tuples.length > 0;
|
||||
}
|
||||
|
||||
const isMember = (keto: KetoClient, actor: string, group: string): Promise<boolean> =>
|
||||
keto.check({ namespace: GROUP_NS, object: group, relation: MEMBERS, subject_id: `user:${actor}` });
|
||||
|
||||
// The self-lockout guard, the group-side twin of the Users screen's self-revoke one: of the permissions
|
||||
// a change takes from a group the actor is in, those they don't hold directly. One they also hold
|
||||
// through another group is included, since telling those apart needs a reverse Keto query.
|
||||
async function lostToSelf(keto: KetoClient, actor: string, taken: readonly string[]): Promise<string[]> {
|
||||
if (taken.length === 0) return [];
|
||||
const direct = new Set(await heldPermissions(keto, userSubject(actor)));
|
||||
return taken.filter((name) => !direct.has(name));
|
||||
}
|
||||
|
||||
// Leaving a group takes everything it confers, including through its own parents.
|
||||
async function lostOnLeaving({ ctx, keto, user }: GroupsDeps, group: string): Promise<string[]> {
|
||||
return lostToSelf(keto, user.id, await effectivePermissions(keto, groupSubject(group), ctx.declaredPermissions));
|
||||
}
|
||||
|
||||
async function lostOnDelete(deps: GroupsDeps, group: string): Promise<string[]> {
|
||||
return (await isMember(deps.keto, deps.user.id, group)) ? lostOnLeaving(deps, group) : [];
|
||||
}
|
||||
|
||||
async function refuseSelfLockout(deps: GroupsDeps, name: string, action: string, lost: string[]): Promise<RouteResult> {
|
||||
deps.ctx.log.warn("admin: refused a group change that would lock the actor out", { action, actor: deps.user.id, group: name, lost: lost.join(",") });
|
||||
return { ...(await groupDetailPage(deps, name, { pageError: deps.ctx.t("admin.groups.error.selfLockout", { permissions: lost.join(", ") }) })), status: 400 };
|
||||
}
|
||||
|
||||
// Shared per-request deps for the Groups screen, resolved by `withGroups`: the gate (`groups:read` on
|
||||
// a GET, `groups:write` on a POST) + the Keto and Kratos capabilities (else a themed 503). Each route
|
||||
// below is a thin handler over these.
|
||||
interface GroupsDeps { ctx: RequestContext; keto: KetoClient; kratosAdmin: KratosAdmin; user: User; }
|
||||
|
||||
function withGroups(inner: (deps: GroupsDeps) => Promise<RouteResult>, action?: AdminAction): RouteHandler {
|
||||
return async (ctx) => {
|
||||
const user = requirePermission(ctx, "groups", action);
|
||||
const keto = ctx.system?.keto;
|
||||
const kratosAdmin = ctx.system?.kratosAdmin;
|
||||
if (!keto || !kratosAdmin) return unavailable(ctx, ctx.t("admin.capability.keto"));
|
||||
return inner({ ctx, keto, kratosAdmin, user });
|
||||
};
|
||||
}
|
||||
|
||||
// Same, plus the validated :name from ctx.params (an invalid group name → themed 404).
|
||||
function withGroupName(inner: (deps: GroupsDeps, name: string) => Promise<RouteResult>, action?: AdminAction): RouteHandler {
|
||||
return withGroups((deps) => {
|
||||
const name = deps.ctx.params["name"] ?? "";
|
||||
if (!isValidGroupName(name)) return Promise.resolve(notFound(deps.ctx));
|
||||
return inner(deps, name);
|
||||
}, action);
|
||||
}
|
||||
|
||||
const groupFormResult = async (deps: GroupsDeps, extra: { error?: string; values?: { member?: string; name?: string } }): Promise<RouteResult> => {
|
||||
const { options } = await memberCandidates(deps.keto, deps.kratosAdmin);
|
||||
return { data: { chrome: deps.ctx.chrome, model: buildGroupFormModel({ csrfToken: deps.ctx.chrome.csrfToken, memberOptions: options, t: deps.ctx.t, ...extra }) }, view: "group-form" };
|
||||
};
|
||||
|
||||
// GET /auth-admin/groups — the list.
|
||||
export const groupsList = withGroups(async ({ ctx, keto }) => {
|
||||
const groups = groupsFromTuples(await pagedTuples(keto, { namespace: GROUP_NS, relation: MEMBERS }));
|
||||
return { data: { chrome: ctx.chrome, model: buildGroupsListModel({ canWrite: can(ctx, permissionName("groups", "write")), csrfToken: ctx.chrome.csrfToken, groups, t: ctx.t, url: ctx.url }) }, view: "groups" };
|
||||
});
|
||||
|
||||
// POST /auth-admin/groups — create (a group exists once it has ≥1 member, so this writes the first tuple).
|
||||
export const groupsCreate = withGroups(async (deps) => {
|
||||
const { ctx, keto, user } = deps;
|
||||
const form = (await guardedForm(ctx))!;
|
||||
const name = (form.get("name") ?? "").trim();
|
||||
const member = (form.get("member") ?? "").trim();
|
||||
const tuple = memberTuple(name, member);
|
||||
const reject = async (error: string): Promise<RouteResult> => ({ ...(await groupFormResult(deps, { error, values: { member, name } })), status: 400 });
|
||||
if (!isValidGroupName(name)) return reject(ctx.t("admin.groups.validation.name"));
|
||||
if (!tuple) return reject(ctx.t("admin.groups.validation.member"));
|
||||
if (await groupExists(keto, name)) return reject(ctx.t("admin.groups.error.duplicate"));
|
||||
await keto.writeTuple(tuple);
|
||||
ctx.log.info("admin: group created", { actor: user.id, group: name });
|
||||
return { redirect: detailHref(name) };
|
||||
});
|
||||
|
||||
// GET /auth-admin/groups/new — the create form.
|
||||
export const groupsNewForm = withGroups((deps) => groupFormResult(deps, {}), "write");
|
||||
|
||||
// The detail + membership page. `notice` and `error` ride the permission picker; `pageError` tops the
|
||||
// page, for any change refused because it would lock the actor out.
|
||||
async function groupDetailPage({ ctx, keto, kratosAdmin }: GroupsDeps, name: string, say: { error?: string; notice?: string; pageError?: string } = {}): Promise<RouteResult> {
|
||||
const { emailById, options } = await memberCandidates(keto, kratosAdmin);
|
||||
const members = (await pagedTuples(keto, { namespace: GROUP_NS, object: name, relation: MEMBERS })).map((t) => memberView(t, emailById));
|
||||
const subject = groupSubject(name);
|
||||
const [direct, effective] = await Promise.all([heldPermissions(keto, subject), effectivePermissions(keto, subject, ctx.declaredPermissions)]);
|
||||
const permissions: PermissionPicker = {
|
||||
...buildPermissionPicker({
|
||||
action: `${detailHref(name)}/permissions`,
|
||||
declared: ctx.declaredPermissions,
|
||||
direct,
|
||||
effective, // a group nested in another group inherits its permissions too
|
||||
readOnly: !can(ctx, permissionName("groups", "write")),
|
||||
t: ctx.t,
|
||||
transitive: true, // members inherit, so a change here lands at their next re-mint, not at once
|
||||
}),
|
||||
...(say.error ? { error: say.error } : {}),
|
||||
...(say.notice ? { notice: say.notice } : {}),
|
||||
};
|
||||
return { data: { chrome: ctx.chrome, model: buildGroupDetailModel({ canWrite: !permissions.readOnly, candidates: options, csrfToken: ctx.chrome.csrfToken, group: { name }, members, permissions, t: ctx.t, ...(say.pageError ? { error: say.pageError } : {}) }) }, view: "group-detail" };
|
||||
}
|
||||
|
||||
// GET /auth-admin/groups/:name — the detail + membership page.
|
||||
export const groupsDetail = withGroupName((deps, name) =>
|
||||
groupDetailPage(deps, name, isSavedNotice(deps.ctx.url) ? { notice: deps.ctx.t("admin.grants.saved") } : {}));
|
||||
|
||||
// POST /auth-admin/groups/:name/permissions — the submitted checkboxes are the desired set. Members hold
|
||||
// a group's permissions transitively, so the change reaches them at their next login or re-mint —
|
||||
// the documented instant-revoke tradeoff for anything held through a group.
|
||||
export const groupsPermissions = withGroupName(async (deps, name) => {
|
||||
const { ctx, keto, user } = deps;
|
||||
const form = (await guardedForm(ctx))!;
|
||||
const subject = groupSubject(name);
|
||||
const held = await heldPermissions(keto, subject);
|
||||
const diff = grantDiff(ctx.declaredPermissions, held, form.getAll(PERMISSIONS_FIELD));
|
||||
if (isStale(form, ctx.declaredPermissions, held, diff)) return { ...(await groupDetailPage(deps, name, { error: ctx.t("admin.grants.stale") })), status: 409 };
|
||||
const lost = diff.revoke.length > 0 && await isMember(keto, user.id, name) ? await lostToSelf(keto, user.id, diff.revoke) : [];
|
||||
if (lost.length > 0) return refuseSelfLockout(deps, name, "save", lost);
|
||||
const { applied, error } = await applyGrants(keto, subject, diff);
|
||||
if (applied.grant.length > 0 || applied.revoke.length > 0) {
|
||||
ctx.log.info("admin: group permissions changed", { actor: user.id, granted: applied.grant.join(","), group: name, revoked: applied.revoke.join(",") });
|
||||
}
|
||||
if (error) {
|
||||
ctx.log.error("admin: group permissions only partly saved", { actor: user.id, error: String(error), group: name });
|
||||
return partialSave(ctx, async () => ({ ...(await groupDetailPage(deps, name, { error: ctx.t("admin.grants.partial") })), status: 502 }));
|
||||
}
|
||||
return { redirect: `${detailHref(name)}?info-msg=${SAVED_NOTICE}` };
|
||||
});
|
||||
|
||||
// POST /auth-admin/groups/:name/members — add a member (skip an invalid member or a self-nest).
|
||||
export const groupsAddMember = withGroupName(async ({ ctx, keto }, name) => {
|
||||
const form = (await guardedForm(ctx))!;
|
||||
const tuple = memberTuple(name, (form.get("member") ?? "").trim());
|
||||
if (tuple && tuple.subject_set?.object !== name) await keto.writeTuple(tuple);
|
||||
return { redirect: detailHref(name) };
|
||||
});
|
||||
|
||||
// GET /auth-admin/groups/:name/delete — the deliberate confirm step.
|
||||
export const groupsDeleteConfirm = withGroupName(async (deps, name) => {
|
||||
const lost = await lostOnDelete(deps, name);
|
||||
if (lost.length > 0) return refuseSelfLockout(deps, name, "delete", lost);
|
||||
const base = detailHref(name);
|
||||
const tt = deps.ctx.t;
|
||||
return { data: { chrome: deps.ctx.chrome, model: buildConfirmModel({
|
||||
breadcrumbs: [{ href: ADMIN_GROUPS_BASE, label: tt("admin.groups.title") }, { href: base, label: name }, { label: tt("common.delete") }],
|
||||
cancelHref: base, confirmAction: `${base}/delete`, confirmLabel: tt("admin.groups.delete"),
|
||||
message: tt("admin.groups.deleteMessage", { name }), title: tt("admin.groups.delete"),
|
||||
}) }, view: "confirm" };
|
||||
}, "write");
|
||||
|
||||
// POST /auth-admin/groups/:name/delete — remove every member tuple (the group ceases to exist).
|
||||
export const groupsDelete = withGroupName(async (deps, name) => {
|
||||
const { ctx, keto, user } = deps;
|
||||
await guardedForm(ctx); // CSRF-verify the POST
|
||||
const lost = await lostOnDelete(deps, name);
|
||||
if (lost.length > 0) return refuseSelfLockout(deps, name, "delete", lost);
|
||||
// Drop what the group *holds* before what it *contains*: a Keto set exists only through its
|
||||
// tuples, so leaving the grants behind would resurrect every permission the moment someone
|
||||
// re-created a group with the same name.
|
||||
const subject = groupSubject(name);
|
||||
const held = await heldPermissions(keto, subject);
|
||||
for (const permission of held) await keto.deleteTuple(grantTuple(permission, subject));
|
||||
await keto.deleteTuple({ namespace: GROUP_NS, object: name, relation: MEMBERS });
|
||||
ctx.log.info("admin: group deleted", { actor: user.id, group: name, revoked: held.join(",") });
|
||||
return { redirect: ADMIN_GROUPS_BASE };
|
||||
});
|
||||
|
||||
// POST /auth-admin/groups/:name/members/delete — remove one member.
|
||||
export const groupsRemoveMember = withGroupName(async (deps, name) => {
|
||||
const { ctx, keto, user } = deps;
|
||||
const form = (await guardedForm(ctx))!;
|
||||
const tuple = memberTuple(name, (form.get("member") ?? "").trim());
|
||||
if (!tuple) return { redirect: detailHref(name) };
|
||||
// Removing the actor, or a nested group they are in, can take them out of this group.
|
||||
const removesSelf = tuple.subject_set ? await isMember(keto, user.id, tuple.subject_set.object) : tuple.subject_id === `user:${user.id}`;
|
||||
const lost = removesSelf ? await lostOnLeaving(deps, name) : [];
|
||||
if (lost.length > 0) return refuseSelfLockout(deps, name, "remove", lost);
|
||||
await keto.deleteTuple(tuple);
|
||||
return { redirect: detailHref(name) };
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { PageChrome, PluginSettings } from "@plainpages/plugin-api";
|
||||
import { buildPluginSettingsModel } from "./admin-plugin-settings.ts";
|
||||
|
||||
const CHROME: PageChrome = { brand: { name: "Test" }, csrfToken: "tok", nav: [], signInHref: "/login", user: { email: "", initials: "T", name: "Tester" } };
|
||||
|
||||
const CATALOG: readonly PluginSettings[] = [
|
||||
{
|
||||
pluginId: "scheduling",
|
||||
settings: [
|
||||
{ description: "Where shifts come from", envName: "PLUGIN_SETTING_SCHEDULING_UPSTREAM", key: "upstream", required: true, secret: false, source: "env", type: "url", value: "https://shifts.test" },
|
||||
{ envName: "PLUGIN_SETTING_SCHEDULING_MODE", key: "mode", required: false, secret: false, source: "default", type: "enum", value: "strict", values: ["strict", "lenient"] },
|
||||
{ envName: "PLUGIN_SETTING_SCHEDULING_NOTE", key: "note", required: false, secret: false, source: "unset", type: "string" },
|
||||
],
|
||||
},
|
||||
{ pluginId: "quiet", settings: [] },
|
||||
];
|
||||
|
||||
test("a row carries the variable to set and where the value came from", () => {
|
||||
const model = buildPluginSettingsModel({ chrome: CHROME, settings: CATALOG });
|
||||
const rows = model.groups[0]?.table.rows ?? [];
|
||||
assert.deepEqual(rows.map((r) => r.name), ["upstream", "mode", "note"]);
|
||||
assert.deepEqual(rows[0]?.cells, [
|
||||
{ rowHeader: { text: "upstream" } }, "Where shifts come from", "url", "Yes", "PLUGIN_SETTING_SCHEDULING_UPSTREAM", "Environment", "https://shifts.test",
|
||||
]);
|
||||
assert.equal(rows[1]?.cells[2], "enum (strict, lenient)"); // the choices are the useful half of the type
|
||||
assert.equal(rows[2]?.cells[5], "Not set");
|
||||
});
|
||||
|
||||
test("a plugin declaring nothing still gets a section, so it is visibly installed", () => {
|
||||
const model = buildPluginSettingsModel({ chrome: CHROME, settings: CATALOG });
|
||||
assert.deepEqual(model.groups.map((g) => g.pluginId), ["scheduling", "quiet"]);
|
||||
assert.deepEqual(model.groups[1]?.table.rows, []);
|
||||
assert.match(model.groups[1]?.emptyText ?? "", /no settings/i);
|
||||
});
|
||||
|
||||
test("a secret renders as set-or-not, never as a value, a mask or a length", () => {
|
||||
const settings: readonly PluginSettings[] = [{
|
||||
pluginId: "billing",
|
||||
settings: [
|
||||
{ envName: "PLUGIN_SETTING_BILLING_API_KEY", key: "apiKey", required: false, secret: true, source: "env", type: "string" },
|
||||
{ envName: "PLUGIN_SETTING_BILLING_WEBHOOK_KEY", key: "webhookKey", required: false, secret: true, source: "unset", type: "string" },
|
||||
],
|
||||
}];
|
||||
const rows = buildPluginSettingsModel({ chrome: CHROME, settings }).groups[0]?.table.rows ?? [];
|
||||
assert.equal(rows[0]?.cells[6], "Secret — set");
|
||||
assert.equal(rows[1]?.cells[6], "Secret — not set");
|
||||
});
|
||||
|
||||
test("two tables on one page need distinct row-action id stems", () => {
|
||||
const model = buildPluginSettingsModel({ chrome: CHROME, settings: CATALOG });
|
||||
const stems = model.groups.map((g) => g.table.actionsId);
|
||||
assert.equal(new Set(stems).size, stems.length);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
// Plugin settings admin screen: what each installed plugin declares it can be configured with, the
|
||||
// variable that sets it, and how each key resolved. Read-only — the host reads settings from the
|
||||
// environment at boot, so changing one is a deploy, not a form.
|
||||
|
||||
import { type PageChrome, type PluginSettings, type RouteHandler, type SettingSummary, type Translate } from "@plainpages/plugin-api";
|
||||
import { ADMIN_EN, requirePermission } from "./admin-shared.ts";
|
||||
|
||||
interface SettingsGroup {
|
||||
emptyText: string;
|
||||
pluginId: string;
|
||||
table: {
|
||||
actionsId: string;
|
||||
caption: string;
|
||||
columns: { label: string }[];
|
||||
rows: { cells: (string | { rowHeader: { text: string } })[]; name: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
// One group per installed plugin, including those declaring nothing — an operator who cannot find
|
||||
// their plugin here has not installed it, which is the other half of what this screen answers.
|
||||
export function buildPluginSettingsModel(opts: { chrome: PageChrome; settings: readonly PluginSettings[]; t?: Translate }) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
return {
|
||||
breadcrumbs: [{ label: t("admin.pluginSettings.title") }],
|
||||
chrome: opts.chrome,
|
||||
groups: opts.settings.map((plugin): SettingsGroup => ({
|
||||
emptyText: t("admin.pluginSettings.none"),
|
||||
pluginId: plugin.pluginId,
|
||||
table: {
|
||||
actionsId: `settings-${plugin.pluginId}`, // two tables share this page, so the stem must differ
|
||||
caption: t("admin.pluginSettings.caption", { plugin: plugin.pluginId }),
|
||||
columns: [
|
||||
{ label: t("admin.pluginSettings.column.key") },
|
||||
{ label: t("admin.pluginSettings.column.description") },
|
||||
{ label: t("admin.pluginSettings.column.type") },
|
||||
{ label: t("admin.pluginSettings.column.required") },
|
||||
{ label: t("admin.pluginSettings.column.variable") },
|
||||
{ label: t("admin.pluginSettings.column.source") },
|
||||
{ label: t("admin.pluginSettings.column.value") },
|
||||
],
|
||||
rows: plugin.settings.map((setting) => ({
|
||||
cells: [
|
||||
{ rowHeader: { text: setting.key } },
|
||||
setting.description ?? "",
|
||||
typeLabel(setting),
|
||||
t(setting.required ? "admin.pluginSettings.yes" : "admin.pluginSettings.no"),
|
||||
setting.envName,
|
||||
t(`admin.pluginSettings.source.${setting.source}`),
|
||||
valueLabel(setting, t),
|
||||
],
|
||||
name: setting.key,
|
||||
})),
|
||||
},
|
||||
})),
|
||||
title: t("admin.pluginSettings.title"),
|
||||
};
|
||||
}
|
||||
|
||||
// An enum's choices are the useful half of its type — they are what the operator must pick from.
|
||||
function typeLabel(setting: SettingSummary): string {
|
||||
return setting.type === "enum" && setting.values ? `${setting.type} (${setting.values.join(", ")})` : setting.type;
|
||||
}
|
||||
|
||||
// A secret never renders its value — not the value, not a mask of it, not its length. Whether it
|
||||
// resolved and from where is what an operator needs, and the source column already says the rest.
|
||||
function valueLabel(setting: SettingSummary, t: Translate): string {
|
||||
if (setting.secret) return t(setting.source === "unset" ? "admin.pluginSettings.secretUnset" : "admin.pluginSettings.secretSet");
|
||||
return setting.value ?? t("admin.pluginSettings.unset");
|
||||
}
|
||||
|
||||
// GET /auth-admin/plugin-settings
|
||||
export const pluginSettingsList: RouteHandler = (ctx) => {
|
||||
requirePermission(ctx, "plugin-settings");
|
||||
return { data: { chrome: ctx.chrome, model: buildPluginSettingsModel({ chrome: ctx.chrome, settings: ctx.declaredSettings, t: ctx.t }) }, view: "plugin-settings" };
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
// Direct units for the admin plugin's shared nav + auth helpers. They're security-critical
|
||||
// (requirePermission/guardedForm gate every admin write) and reused across all three screens, so pin the
|
||||
// contract here in isolation; the HTTP routing/gate/CSRF is exercised end-to-end in src/http/app-admin.test.ts.
|
||||
// Import only from the @plainpages/plugin-api barrel — the same contract boundary the plugin code uses.
|
||||
import assert from "node:assert/strict";
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { Readable } from "node:stream";
|
||||
import { test } from "node:test";
|
||||
import { GuardError, isValidPermissionName, type Log, type PageChrome, type RequestContext, type User } from "@plainpages/plugin-api";
|
||||
import { ADMIN_EN, ADMIN_NAV, ADMIN_USERS_BASE, actionForMethod, buildConfirmModel, guardedForm, permissionName, requirePermission } from "./admin-shared.ts";
|
||||
|
||||
const reader: User = { email: "ada@x.io", id: "u1", permissions: ["users:read"] };
|
||||
const writer: User = { email: "cy@x.io", id: "u3", permissions: ["users:read", "users:write"] };
|
||||
const member: User = { email: "bo@x.io", id: "u2", permissions: ["scheduling:read"] };
|
||||
const CHROME = { brand: { name: "Test" }, csrfToken: "tok", nav: [], signInHref: "/login", user: { email: "", initials: "T", name: "Tester" } } as PageChrome;
|
||||
|
||||
function fakeCtx(opts: { body?: string; method?: string; user?: User | null; verifyCsrf?: (s: string | null | undefined) => boolean } = {}): RequestContext {
|
||||
const url = new URL("http://localhost/auth-admin/users");
|
||||
const req = Readable.from(opts.body != null ? [Buffer.from(opts.body)] : []) as unknown as IncomingMessage;
|
||||
req.method = opts.method ?? "GET";
|
||||
return {
|
||||
assetHref: (href) => href, chrome: CHROME, declaredPermissions: [], declaredSettings: [], user: opts.user ?? null, locale: "en-US", localeHref: (href) => href, locales: ["en-US"], log: {} as Log, params: {},
|
||||
query: url.searchParams, req, res: {} as ServerResponse, permissions: opts.user?.permissions ?? [], t: ADMIN_EN, url,
|
||||
verifyCsrf: opts.verifyCsrf ?? (() => true),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- nav fragment ----
|
||||
|
||||
test("ADMIN_NAV: an ungated Admin header whose screens each gate on their own read permission", () => {
|
||||
assert.equal(ADMIN_NAV.id, "admin");
|
||||
// No gate on the header: a user may hold one screen's permission and not another's. composeNav
|
||||
// drops a header left with no visible children, so holding none of them hides the section.
|
||||
// Both halves matter — give the header an `href` and it survives the filter as a visible leaf,
|
||||
// ungated, for anonymous visitors included.
|
||||
assert.equal(ADMIN_NAV.permission, undefined);
|
||||
assert.equal(ADMIN_NAV.href, undefined);
|
||||
assert.equal(ADMIN_NAV.open, undefined); // the host current-marks + opens; the fragment stays static
|
||||
assert.deepEqual(ADMIN_NAV.children?.map((c) => c.href), ["/auth-admin/users", "/auth-admin/groups", "/auth-admin/clients", "/auth-admin/plugin-settings"]);
|
||||
assert.deepEqual(ADMIN_NAV.children?.map((c) => c.permission), ["users:read", "groups:read", "oauth2-clients:read", "plugin-settings:read"]);
|
||||
// Labels are catalog keys; the host translates them with this plugin's catalog when it composes
|
||||
// the menu, so what a visitor sees is the en-US (or sv-SE …) wording behind these keys.
|
||||
assert.deepEqual(ADMIN_NAV.children?.map((c) => c.label), ["admin.nav.users", "admin.nav.groups", "admin.nav.clients", "admin.nav.pluginSettings"]);
|
||||
assert.deepEqual(ADMIN_NAV.children?.map((c) => ADMIN_EN(c.label)), ["Users", "Groups", "OAuth2 clients", "Plugin settings"]);
|
||||
assert.ok(ADMIN_NAV.children?.every((c) => c.current === undefined));
|
||||
});
|
||||
|
||||
// ---- permission naming ----
|
||||
|
||||
test("permissionName builds <resource>:<action>, and the host agrees the result is well-formed", () => {
|
||||
assert.equal(permissionName("users", "read"), "users:read");
|
||||
assert.equal(permissionName("oauth2-clients", "write"), "oauth2-clients:write");
|
||||
assert.ok(isValidPermissionName(permissionName("oauth2-clients", "write"))); // the rule discovery enforces
|
||||
});
|
||||
|
||||
test("actionForMethod: read for GET/HEAD, write for every mutation", () => {
|
||||
assert.equal(actionForMethod("GET"), "read");
|
||||
assert.equal(actionForMethod("HEAD"), "read"); // a GET route also answers HEAD
|
||||
assert.equal(actionForMethod("POST"), "write");
|
||||
assert.equal(actionForMethod("DELETE"), "write"); // anything that isn't a read is a write
|
||||
assert.equal(actionForMethod("get"), "read"); // method case is the caller's
|
||||
});
|
||||
|
||||
// ---- auth gates ----
|
||||
|
||||
test("requirePermission: anonymous → 401→/login, wrong permission → 403, and read never grants write", () => {
|
||||
assert.throws(() => requirePermission(fakeCtx({ user: null }), "users"), (e: unknown) => e instanceof GuardError && e.status === 401 && e.location === "/login?return_to=%2Fauth-admin%2Fusers"); // bounce remembers the page
|
||||
assert.throws(() => requirePermission(fakeCtx({ user: member }), "users"), (e: unknown) => e instanceof GuardError && e.status === 403);
|
||||
assert.equal(requirePermission(fakeCtx({ user: reader }), "users"), reader);
|
||||
// The whole point of the split: users:read opens the list but not the create/delete POSTs.
|
||||
assert.throws(() => requirePermission(fakeCtx({ method: "POST", user: reader }), "users"), (e: unknown) => e instanceof GuardError && e.status === 403);
|
||||
assert.equal(requirePermission(fakeCtx({ method: "POST", user: writer }), "users"), writer);
|
||||
// Resources don't leak into each other: a users holder is not a groups holder.
|
||||
assert.throws(() => requirePermission(fakeCtx({ user: writer }), "groups"), (e: unknown) => e instanceof GuardError && e.status === 403);
|
||||
});
|
||||
|
||||
test("guardedForm: valid double-submit → the parsed body, bad token → 403, non-POST → undefined", async () => {
|
||||
const post = (over: { body?: string; verifyCsrf?: (s: string | null | undefined) => boolean }) => fakeCtx({ method: "POST", ...over });
|
||||
|
||||
const ok = await guardedForm(post({ body: "_csrf=tok&name=Bo", verifyCsrf: () => true }));
|
||||
assert.equal(ok?.get("name"), "Bo");
|
||||
|
||||
await assert.rejects(guardedForm(post({ body: "_csrf=nope&name=Bo", verifyCsrf: () => false })), // ctx.verifyCsrf rejects
|
||||
(e: unknown) => e instanceof GuardError && e.status === 403);
|
||||
|
||||
assert.equal(await guardedForm(fakeCtx({ method: "GET" })), undefined); // not a mutation → no gate, no body read
|
||||
});
|
||||
|
||||
// ---- confirm-page model ----
|
||||
|
||||
test("buildConfirmModel wires the danger action, message, breadcrumbs and title (shell comes from ctx.chrome)", () => {
|
||||
const model = buildConfirmModel({
|
||||
breadcrumbs: [{ href: ADMIN_USERS_BASE, label: "Users" }, { label: "Delete" }],
|
||||
cancelHref: ADMIN_USERS_BASE, confirmAction: `${ADMIN_USERS_BASE}/u1/delete`, confirmLabel: "Delete user",
|
||||
message: "Delete ada@x.io?", title: "Delete user",
|
||||
});
|
||||
assert.deepEqual(model.confirm, { action: `${ADMIN_USERS_BASE}/u1/delete`, label: "Delete user" });
|
||||
assert.equal(model.message, "Delete ada@x.io?");
|
||||
assert.equal(model.cancelHref, ADMIN_USERS_BASE);
|
||||
assert.equal(model.title, "Delete user");
|
||||
assert.deepEqual(model.breadcrumbs.at(-1), { label: "Delete" });
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
// Shared plumbing for the admin example plugin: the section nav fragment, the screen gate, the
|
||||
// CSRF-guarded form reader, the destructive-confirm model builder, and small RouteResult helpers.
|
||||
// Everything imports the host only through the @plainpages/plugin-api barrel.
|
||||
|
||||
import { can, CSRF_FIELD, englishTranslator, GuardError, type NavNode, readFormBody, type RequestContext, requireSession, type RouteResult, type Translate, type User } from "@plainpages/plugin-api";
|
||||
import enUS from "./i18n/en-US.ts";
|
||||
|
||||
// This plugin's English — its catalog, then the host's — for a view model built outside a request,
|
||||
// i.e. its unit tests. At runtime the handlers pass ctx.t instead.
|
||||
export const ADMIN_EN: Translate = englishTranslator(enUS);
|
||||
|
||||
export const ADMIN_USERS_BASE = "/auth-admin/users";
|
||||
export const ADMIN_GROUPS_BASE = "/auth-admin/groups";
|
||||
export const ADMIN_CLIENTS_BASE = "/auth-admin/clients";
|
||||
export const ADMIN_PLUGIN_SETTINGS_BASE = "/auth-admin/plugin-settings";
|
||||
|
||||
// One resource per screen — the `<resource>` half of every permission this plugin gates on.
|
||||
// `oauth2-clients` rather than `clients` because permission names are one global namespace.
|
||||
// There is no `permissions` resource: permissions are declared in plugin code, not created here, so
|
||||
// holding a grant is a property of a user or a group and is edited on those two screens.
|
||||
export type AdminResource = "groups" | "oauth2-clients" | "plugin-settings" | "users";
|
||||
|
||||
export type AdminAction = "read" | "write";
|
||||
|
||||
// `<resource>:<action>` (README → Naming a permission).
|
||||
export function permissionName(resource: AdminResource, action: AdminAction): string {
|
||||
return `${resource}:${action}`;
|
||||
}
|
||||
|
||||
// Every screen reads on GET/HEAD and mutates on POST. The route table and the in-handler guard both
|
||||
// go through this rather than each spelling the permission out, so they cannot drift. Deliberately
|
||||
// local: generalised, it would make authorization a function of the transport verb
|
||||
// (docs/decisions.md → "`actionForMethod` is plugin-local and stays out of
|
||||
// `@plainpages/plugin-api`").
|
||||
export function actionForMethod(method: string): AdminAction {
|
||||
const verb = method.toUpperCase();
|
||||
return verb === "GET" || verb === "HEAD" ? "read" : "write";
|
||||
}
|
||||
|
||||
// The plugin's nav fragment: the "Admin" header + its four screens, each gated on its own read
|
||||
// permission. composeNav drops a header left with no visible children, so a user holding none of
|
||||
// them never sees the section. The host current-marks the active item — no `current`/`open` here.
|
||||
export const ADMIN_NAV: NavNode = {
|
||||
children: [
|
||||
{ href: ADMIN_USERS_BASE, icon: "i-users", id: "users", label: "admin.nav.users", permission: permissionName("users", "read") },
|
||||
{ href: ADMIN_GROUPS_BASE, icon: "i-layers", id: "groups", label: "admin.nav.groups", permission: permissionName("groups", "read") },
|
||||
{ href: ADMIN_CLIENTS_BASE, icon: "i-globe", id: "clients", label: "admin.nav.clients", permission: permissionName("oauth2-clients", "read") },
|
||||
{ href: ADMIN_PLUGIN_SETTINGS_BASE, icon: "i-sliders", id: "plugin-settings", label: "admin.nav.pluginSettings", permission: permissionName("plugin-settings", "read") },
|
||||
],
|
||||
icon: "i-shield",
|
||||
id: "admin",
|
||||
label: "admin.nav.section", // a key in this plugin's catalog; the host translates nav labels
|
||||
public: true, // the header gates nothing; every child needs a permission, and an empty header is dropped
|
||||
};
|
||||
|
||||
// The screen gate: a signed-in user holding this request's `<resource>:<action>`. Each route already
|
||||
// declares the same permission, so this is defence-in-depth and what a direct unit test relies on.
|
||||
// `action` defaults to the method's, and is passed explicitly by a *write-intent GET* — a create
|
||||
// form or a delete-confirm page — which refuses a reader rather than rendering a form whose submit
|
||||
// would 403. The route table declares the same override, so the two cannot disagree.
|
||||
export function requirePermission(ctx: RequestContext, resource: AdminResource, action?: AdminAction): User {
|
||||
const user = requireSession(ctx); // anonymous → GuardError → /login (return_to kept)
|
||||
const permission = permissionName(resource, action ?? actionForMethod(ctx.req.method ?? "GET"));
|
||||
if (!can(ctx, permission)) throw new GuardError(403, `${permission} required`);
|
||||
return user;
|
||||
}
|
||||
|
||||
// Read + CSRF-verify a mutation's form body once (double-submit via ctx.verifyCsrf); non-POST ⇒
|
||||
// undefined. A POST without a valid token is refused (GuardError → 403).
|
||||
export async function guardedForm(ctx: RequestContext): Promise<URLSearchParams | undefined> {
|
||||
if ((ctx.req.method ?? "GET").toUpperCase() !== "POST") return undefined;
|
||||
const form = await readFormBody(ctx.req);
|
||||
if (!ctx.verifyCsrf(form.get(CSRF_FIELD))) throw new GuardError(403, "invalid CSRF token");
|
||||
return form;
|
||||
}
|
||||
|
||||
// A themed "not found" (bad id/name in the path) rendered in the admin shell — 404, never a 500.
|
||||
export function notFound(ctx: RequestContext): RouteResult {
|
||||
return { data: { chrome: ctx.chrome, message: ctx.t("admin.notFound.message"), title: ctx.t("admin.notFound.title") }, status: 404, view: "notice" };
|
||||
}
|
||||
|
||||
// A capability the plugin needs isn't on ctx.system (Ory not wired). Login already requires these in
|
||||
// a real deployment, so this is the honest 503 fallback for a misconfigured host, not a crash.
|
||||
export function unavailable(ctx: RequestContext, what: string): RouteResult {
|
||||
return { data: { chrome: ctx.chrome, message: ctx.t("admin.unavailable.message", { what }), title: ctx.t("admin.unavailable.title") }, status: 503, view: "notice" };
|
||||
}
|
||||
|
||||
// The page a partial permission save reports on reads Keto again. If that read fails too, the report
|
||||
// stands alone on the notice page, so the admin still hears that part of the save landed.
|
||||
export async function partialSave(ctx: RequestContext, render: () => Promise<RouteResult>): Promise<RouteResult> {
|
||||
try {
|
||||
return await render();
|
||||
} catch {
|
||||
return { data: { chrome: ctx.chrome, message: ctx.t("admin.grants.partial"), title: ctx.t("admin.unavailable.title") }, status: 502, view: "notice" };
|
||||
}
|
||||
}
|
||||
|
||||
// Model for the shared destructive-confirm page (views/confirm.ejs). The view reads the shell fields
|
||||
// (brand/csrf/theme/user/nav) from ctx.chrome; this carries only the page body + title/breadcrumbs.
|
||||
export function buildConfirmModel(opts: {
|
||||
breadcrumbs: { href?: string; label: string }[];
|
||||
cancelHref: string;
|
||||
confirmAction: string;
|
||||
confirmLabel: string;
|
||||
message: string;
|
||||
title: string;
|
||||
}) {
|
||||
return {
|
||||
breadcrumbs: opts.breadcrumbs,
|
||||
cancelHref: opts.cancelHref,
|
||||
confirm: { action: opts.confirmAction, label: opts.confirmLabel },
|
||||
message: opts.message,
|
||||
title: opts.title,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// Users admin screen (example plugin): the pure view-model + Kratos-payload builders. The HTTP
|
||||
// routing/gate/CSRF + live Kratos calls are exercised over HTTP in src/http/app-admin.test.ts.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { Identity } from "@plainpages/plugin-api";
|
||||
import {
|
||||
buildUserFormModel,
|
||||
buildUsersListModel,
|
||||
createIdentityPayload,
|
||||
setStatePayload,
|
||||
toUserView,
|
||||
updateIdentityPayload,
|
||||
} from "./admin-users.ts";
|
||||
|
||||
const id = (n: number) => `01902d5e-7b6c-7e3a-9f21-3c8d1e0a4b${String(n).padStart(2, "0")}`;
|
||||
const identity = (n: number, over: Partial<Identity> = {}): Identity => ({
|
||||
id: id(n),
|
||||
schema_id: "default",
|
||||
state: "active",
|
||||
traits: { email: `user${n}@example.com`, name: { first: `First${n}`, last: `Last${n}` } },
|
||||
...over,
|
||||
});
|
||||
|
||||
test("toUserView maps traits → name/initials/email/state; falls back to the email local part", () => {
|
||||
const named = toUserView(identity(1));
|
||||
assert.equal(named.name, "First1 Last1");
|
||||
assert.equal(named.initials, "FL");
|
||||
assert.equal(named.email, "user1@example.com");
|
||||
assert.equal(named.state, "active");
|
||||
|
||||
// No name trait → derive from the email local part.
|
||||
const bare = toUserView({ id: id(2), state: "inactive", traits: { email: "ada.lovelace@example.com" } });
|
||||
assert.equal(bare.name, "ada.lovelace");
|
||||
assert.equal(bare.initials, "AD");
|
||||
assert.equal(bare.state, "inactive");
|
||||
});
|
||||
|
||||
test("buildUsersListModel filters by search + status, sorts, and paginates", () => {
|
||||
const people = Array.from({ length: 30 }, (_, i) => identity(i + 1, { state: i % 2 ? "inactive" : "active" }));
|
||||
|
||||
const all = buildUsersListModel({ identities: people, url: "http://x/auth-admin/users" });
|
||||
assert.equal(all.pagination.summary.total, 30);
|
||||
assert.equal(all.table.rows.length, 25); // default page size
|
||||
assert.equal(all.title, "Users");
|
||||
|
||||
// Search narrows to one and shows a pill.
|
||||
const one = buildUsersListModel({ identities: people, url: "http://x/auth-admin/users?q=user7%40example.com" });
|
||||
assert.equal(one.pagination.summary.total, 1);
|
||||
assert.deepEqual(one.filterBar.pills.map((p) => p.label), ["Search"]);
|
||||
|
||||
// Status filter keeps only inactive identities.
|
||||
const inactive = buildUsersListModel({ identities: people, url: "http://x/auth-admin/users?status=inactive" });
|
||||
assert.equal(inactive.pagination.summary.total, 15);
|
||||
assert.deepEqual(inactive.filterBar.pills.map((p) => p.label), ["Status"]);
|
||||
|
||||
// Sort by email descending reverses the order.
|
||||
const emailOf = (m: ReturnType<typeof buildUsersListModel>, i: number) => (m.table.rows[i]!.cells[1]) as string;
|
||||
const desc = buildUsersListModel({ identities: people, url: "http://x/auth-admin/users?sort=-email" });
|
||||
assert.ok(emailOf(desc, 0) > emailOf(desc, 1));
|
||||
|
||||
// Edit link points at the per-identity route.
|
||||
assert.match(all.table.rows[0]!.actions![0]!.href!, new RegExp(`/auth-admin/users/${people[0]!.id}$`));
|
||||
assert.deepEqual([all.table.rows[0]!.actions![0]!.icon, all.table.rows[0]!.actions![0]!.label], ["i-edit", "Edit"]);
|
||||
});
|
||||
|
||||
// The detail page of a `users:read` holder is read-only, so the row action must not promise an edit.
|
||||
test("buildUsersListModel: a read-only holder's row action says View, with the same target", () => {
|
||||
const people: Identity[] = [{ id: "u1", traits: { email: "a@x.io" } }];
|
||||
const action = buildUsersListModel({ canWrite: false, identities: people, url: "http://x/auth-admin/users" }).table.rows[0]!.actions![0]!;
|
||||
assert.deepEqual([action.icon, action.label, action.href], ["i-eye", "View", "/auth-admin/users/u1"]);
|
||||
});
|
||||
|
||||
test("buildUserFormModel: create mode has an editable email + password, no edit actions", () => {
|
||||
const m = buildUserFormModel({ csrfToken: "tok.sig" });
|
||||
assert.equal(m.title, "New user");
|
||||
assert.equal(m.form.action, "/auth-admin/users");
|
||||
assert.equal(m.form.submitLabel, "Create user");
|
||||
assert.equal(m.form.csrfToken, "tok.sig");
|
||||
const names = m.form.fields.map((f) => f.name);
|
||||
assert.deepEqual(names, ["email", "first", "last", "password"]);
|
||||
assert.equal(m.form.fields.find((f) => f.name === "email")!.readonly, undefined); // editable on create
|
||||
assert.equal(m.edit, undefined);
|
||||
});
|
||||
|
||||
test("buildUserFormModel: edit mode prefills, locks email, and exposes state/delete/recovery actions", () => {
|
||||
const m = buildUserFormModel({ identity: identity(3) });
|
||||
assert.equal(m.title, "Edit user");
|
||||
assert.equal(m.form.action, `/auth-admin/users/${id(3)}`);
|
||||
assert.equal(m.form.submitLabel, "Save changes");
|
||||
const email = m.form.fields.find((f) => f.name === "email")!;
|
||||
assert.equal(email.value, "user3@example.com");
|
||||
assert.equal(email.readonly, true);
|
||||
assert.ok(!m.form.fields.some((f) => f.name === "password")); // no password field when editing
|
||||
assert.equal(m.form.fields.find((f) => f.name === "first")!.value, "First3");
|
||||
assert.equal(m.edit!.nextLabel, "Deactivate"); // active → offers Deactivate
|
||||
assert.match(m.edit!.deleteAction, /\/delete$/);
|
||||
assert.match(m.edit!.recoveryAction, /\/recovery$/);
|
||||
|
||||
// An inactive identity offers Reactivate.
|
||||
assert.equal(buildUserFormModel({ identity: identity(4, { state: "inactive" }) }).edit!.nextLabel, "Reactivate");
|
||||
});
|
||||
|
||||
test("buildUserFormModel: the title and breadcrumb say New, Edit, or View for a users:read holder", () => {
|
||||
const cases: [Parameters<typeof buildUserFormModel>[0], string, string][] = [
|
||||
[{}, "New user", "New"],
|
||||
[{ identity: identity(3) }, "Edit user", "Edit"],
|
||||
[{ canWrite: false, identity: identity(3) }, "View user", "View"],
|
||||
];
|
||||
for (const [opts, title, crumb] of cases) {
|
||||
const m = buildUserFormModel(opts);
|
||||
assert.equal(m.title, title);
|
||||
assert.deepEqual(m.breadcrumbs, [{ href: "/auth-admin/users", label: "Users" }, { label: crumb }]);
|
||||
}
|
||||
});
|
||||
|
||||
test("createIdentityPayload: schema/state/traits, name only when given, password only when set", () => {
|
||||
assert.deepEqual(createIdentityPayload({ email: "a@b.c", first: "Ada", last: "Lovelace", password: "" }), {
|
||||
schema_id: "default",
|
||||
state: "active",
|
||||
traits: { email: "a@b.c", name: { first: "Ada", last: "Lovelace" } },
|
||||
});
|
||||
// No name parts → omit the name trait; a password → credentials.
|
||||
assert.deepEqual(createIdentityPayload({ email: "a@b.c", first: "", last: "", password: "s3cret" }), {
|
||||
credentials: { password: { config: { password: "s3cret" } } },
|
||||
schema_id: "default",
|
||||
state: "active",
|
||||
traits: { email: "a@b.c" },
|
||||
});
|
||||
});
|
||||
|
||||
test("updateIdentityPayload preserves email/schema/state and rewrites the name; setStatePayload flips state", () => {
|
||||
const existing = identity(5);
|
||||
assert.deepEqual(updateIdentityPayload(existing, { email: "ignored@x", first: "New", last: "Name", password: "" }), {
|
||||
schema_id: "default",
|
||||
state: "active",
|
||||
traits: { email: "user5@example.com", name: { first: "New", last: "Name" } }, // email kept, not the submitted one
|
||||
});
|
||||
// Clearing both name parts drops the name trait.
|
||||
assert.deepEqual(updateIdentityPayload(existing, { email: "", first: "", last: "", password: "" }).traits, { email: "user5@example.com" });
|
||||
|
||||
assert.deepEqual(setStatePayload(existing, "inactive"), {
|
||||
schema_id: "default",
|
||||
state: "inactive",
|
||||
traits: { email: "user5@example.com", name: { first: "First5", last: "Last5" } },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,446 @@
|
||||
// Users admin screen: list Kratos identities (filter/sort/paginate) +
|
||||
// create/edit/deactivate/delete/trigger-recovery. Pure builders turn identities + the request URL
|
||||
// into building-block view models; below them are thin per-route handlers keyed on ctx.params, over
|
||||
// a shared `withUser` gate.
|
||||
|
||||
import { buildPaginationModel, can, type Identity, type KetoClient, type KratosAdmin, KratosError, paginate, parseListQuery, type RecoveryCode, type RequestContext, type RouteHandler, type RouteResult, type Translate, type User } from "@plainpages/plugin-api";
|
||||
import { applyGrants, buildPermissionPicker, effectivePermissions, grantDiff, heldPermissions, isSavedNotice, isStale, type PermissionPicker, PERMISSIONS_FIELD, SAVED_NOTICE, userSubject } from "./admin-grants.ts";
|
||||
import { ADMIN_EN, type AdminAction, ADMIN_USERS_BASE, buildConfirmModel, guardedForm, notFound, partialSave, permissionName, requirePermission, unavailable } from "./admin-shared.ts";
|
||||
|
||||
const SCHEMA_ID = "default"; // matches kratos.yml identity.default_schema_id
|
||||
const DEFAULT_PAGE_SIZE = 25;
|
||||
const PAGE_SIZES = [25, 50, 100];
|
||||
// One Kratos page is fetched and filtered/sorted/paged in memory — the admin API offers no
|
||||
// full-text search or sort. Ample for an admin tool; raise if a deployment outgrows it.
|
||||
const LIST_FETCH_SIZE = 250;
|
||||
const STATE_TONE: Record<string, string> = { active: "pos", inactive: "warn" };
|
||||
|
||||
export interface UserView {
|
||||
email: string;
|
||||
id: string;
|
||||
initials: string;
|
||||
name: string;
|
||||
state: string; // Kratos identity state: "active" | "inactive"
|
||||
}
|
||||
|
||||
export interface UserInput {
|
||||
email: string;
|
||||
first: string;
|
||||
last: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
function nameParts(identity: Identity): { first: string; last: string } {
|
||||
const nm = ((identity.traits?.name ?? {}) as { first?: unknown; last?: unknown });
|
||||
return {
|
||||
first: typeof nm.first === "string" ? nm.first.trim() : "",
|
||||
last: typeof nm.last === "string" ? nm.last.trim() : "",
|
||||
};
|
||||
}
|
||||
|
||||
export function toUserView(identity: Identity): UserView {
|
||||
const email = typeof identity.traits?.email === "string" ? (identity.traits.email as string) : "";
|
||||
const { first, last } = nameParts(identity);
|
||||
const full = `${first} ${last}`.trim();
|
||||
const name = full || email.split("@")[0] || email;
|
||||
const initials = (first && last ? first[0]! + last[0]! : name.slice(0, 2) || "U").toUpperCase();
|
||||
return { email, id: identity.id, initials, name, state: identity.state ?? "active" };
|
||||
}
|
||||
|
||||
// ---- Kratos payloads ----
|
||||
|
||||
export function createIdentityPayload(input: UserInput): Record<string, unknown> {
|
||||
const traits: Record<string, unknown> = { email: input.email };
|
||||
if (input.first || input.last) traits.name = { first: input.first, last: input.last };
|
||||
const payload: Record<string, unknown> = { schema_id: SCHEMA_ID, state: "active", traits };
|
||||
if (input.password) payload.credentials = { password: { config: { password: input.password } } };
|
||||
return payload;
|
||||
}
|
||||
|
||||
// A full-identity PUT must carry schema/state/traits. Keep the existing email (the form's email is
|
||||
// read-only) and other traits; rewrite name from the input (cleared ⇒ drop it).
|
||||
export function updateIdentityPayload(identity: Identity, input: UserInput): Record<string, unknown> {
|
||||
const traits: Record<string, unknown> = { ...(identity.traits ?? {}) };
|
||||
if (input.first || input.last) traits.name = { first: input.first, last: input.last };
|
||||
else delete traits.name;
|
||||
return { schema_id: identity.schema_id ?? SCHEMA_ID, state: identity.state ?? "active", traits };
|
||||
}
|
||||
|
||||
export function setStatePayload(identity: Identity, state: "active" | "inactive"): Record<string, unknown> {
|
||||
return { schema_id: identity.schema_id ?? SCHEMA_ID, state, traits: { ...(identity.traits ?? {}) } };
|
||||
}
|
||||
|
||||
// ---- view models ----
|
||||
|
||||
interface ListState {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
q: string;
|
||||
sort: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
const SORT: Record<string, (u: UserView) => string> = {
|
||||
email: (u) => u.email,
|
||||
name: (u) => u.name,
|
||||
status: (u) => u.state,
|
||||
};
|
||||
const COLUMNS = [
|
||||
{ key: "name", label: "admin.users.column.name" },
|
||||
{ key: "email", label: "admin.users.column.email" },
|
||||
{ key: "status", label: "admin.users.column.status" },
|
||||
];
|
||||
|
||||
// Canonical list URL from the current state + per-link overrides; omits defaults so links stay tidy.
|
||||
function listHref(state: ListState, overrides: Partial<ListState> = {}): string {
|
||||
const s = { ...state, ...overrides };
|
||||
const p = new URLSearchParams();
|
||||
if (s.q) p.set("q", s.q);
|
||||
if (s.status && s.status !== "all") p.set("status", s.status);
|
||||
if (s.sort) p.set("sort", s.sort);
|
||||
if (s.page > 1) p.set("page", String(s.page));
|
||||
if (s.pageSize !== DEFAULT_PAGE_SIZE) p.set("pageSize", String(s.pageSize));
|
||||
const qs = p.toString();
|
||||
return qs ? `${ADMIN_USERS_BASE}?${qs}` : ADMIN_USERS_BASE;
|
||||
}
|
||||
|
||||
export function buildUsersListModel(opts: {
|
||||
canWrite?: boolean;
|
||||
csrfToken?: string;
|
||||
identities: Identity[];
|
||||
t?: Translate;
|
||||
url: URL | URLSearchParams | string;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const query = parseListQuery(opts.url, { defaultPageSize: DEFAULT_PAGE_SIZE });
|
||||
const status = query.filters.status?.[0] ?? "all";
|
||||
const sort = query.sort && SORT[query.sort.field] ? query.sort : null;
|
||||
const sortToken = sort ? (sort.dir === "desc" ? `-${sort.field}` : sort.field) : null;
|
||||
const needle = query.q.toLowerCase();
|
||||
|
||||
const all = opts.identities.map(toUserView);
|
||||
let list = all.filter((u) =>
|
||||
(!needle || u.name.toLowerCase().includes(needle) || u.email.toLowerCase().includes(needle)) &&
|
||||
(status === "all" || u.state === status));
|
||||
if (sort) {
|
||||
const get = SORT[sort.field] as (u: UserView) => string;
|
||||
const dir = sort.dir === "desc" ? -1 : 1;
|
||||
list = [...list].sort((a, b) => get(a).localeCompare(get(b)) * dir);
|
||||
}
|
||||
|
||||
const page = paginate(list.length, query.page, query.pageSize, { boundaries: 1, siblings: 1 });
|
||||
const start = (page.page - 1) * page.pageSize;
|
||||
const rows = list.slice(start, start + page.pageSize);
|
||||
const state: ListState = { page: page.page, pageSize: page.pageSize, q: query.q, sort: sortToken, status };
|
||||
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_USERS_BASE, label: t("admin.nav.section") }, { label: t("admin.users.title") }],
|
||||
canWrite: opts.canWrite !== false,
|
||||
filterBar: listFilterBar(state, all.length, t),
|
||||
pagination: buildPaginationModel(page, (n) => listHref(state, { page: n }), { label: t("admin.users.pagination"), pageSizes: PAGE_SIZES }),
|
||||
table: listTable(rows, state, sort, t, opts.canWrite !== false),
|
||||
title: t("admin.users.title"),
|
||||
};
|
||||
}
|
||||
|
||||
function listTable(rows: UserView[], state: ListState, sort: { dir: "asc" | "desc"; field: string } | null, t: Translate, canWrite: boolean) {
|
||||
return {
|
||||
actions: true,
|
||||
caption: t("admin.users.title"),
|
||||
columns: COLUMNS.map((c) => {
|
||||
const dir = sort && sort.field === c.key ? sort.dir : undefined;
|
||||
const next = dir === "asc" ? `-${c.key}` : c.key; // asc→desc, else→asc
|
||||
return { href: listHref(state, { page: 1, sort: next }), label: t(c.label), sort: dir, sortable: true };
|
||||
}),
|
||||
rows: rows.map((u) => ({
|
||||
actions: [{ href: `${ADMIN_USERS_BASE}/${encodeURIComponent(u.id)}`, icon: canWrite ? "i-edit" : "i-eye", label: t(canWrite ? "common.edit" : "admin.users.view") }],
|
||||
cells: [
|
||||
{ user: { initials: u.initials, name: u.name } },
|
||||
u.email,
|
||||
{ badge: { label: t(`admin.users.status.${u.state}`), tone: STATE_TONE[u.state] ?? "info" } },
|
||||
],
|
||||
name: u.name,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function listFilterBar(state: ListState, total: number, t: Translate) {
|
||||
const pills: { label: string; remove: string; value: string }[] = [];
|
||||
if (state.q) pills.push({ label: t("filter.search"), remove: listHref(state, { page: 1, q: "" }), value: state.q });
|
||||
if (state.status !== "all") pills.push({ label: t("admin.users.status.label"), remove: listHref(state, { page: 1, status: "all" }), value: t(`admin.users.status.${state.status}`) });
|
||||
return {
|
||||
applyLabel: t("filter.apply"), // an untranslated core key still resolves: the host catalog is the fallback
|
||||
clearHref: ADMIN_USERS_BASE,
|
||||
label: t("admin.users.filter"),
|
||||
pills,
|
||||
rows: [[
|
||||
{ label: t("admin.users.searchLabel"), name: "q", placeholder: t("admin.users.searchPlaceholder"), type: "search", value: state.q },
|
||||
{ legend: t("admin.users.status.label"), name: "status", options: [
|
||||
{ count: total, label: t("admin.users.status.all"), value: "all" },
|
||||
{ label: t("admin.users.status.active"), value: "active" },
|
||||
{ label: t("admin.users.status.inactive"), value: "inactive" },
|
||||
], type: "segmented", value: state.status },
|
||||
{ type: "spacer" },
|
||||
]],
|
||||
};
|
||||
}
|
||||
|
||||
export interface FieldConfig {
|
||||
autocomplete?: string;
|
||||
hint?: string;
|
||||
icon?: string;
|
||||
id: string;
|
||||
label: string;
|
||||
name: string;
|
||||
optional?: boolean;
|
||||
readonly?: boolean;
|
||||
required?: boolean;
|
||||
type?: string;
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export function buildUserFormModel(opts: {
|
||||
canWrite?: boolean; // false ⇒ a `users:read` holder: show the state, render no write affordance
|
||||
csrfToken?: string;
|
||||
error?: string;
|
||||
identity?: Identity | null;
|
||||
permissions?: PermissionPicker; // editing only — a user that doesn't exist yet can hold nothing
|
||||
recovery?: RecoveryCode;
|
||||
t?: Translate;
|
||||
values?: Partial<UserInput>;
|
||||
}) {
|
||||
const t = opts.t ?? ADMIN_EN;
|
||||
const editing = opts.identity != null;
|
||||
const view = editing ? toUserView(opts.identity!) : null;
|
||||
const np = editing ? nameParts(opts.identity!) : { first: opts.values?.first ?? "", last: opts.values?.last ?? "" };
|
||||
const email = editing ? view!.email : (opts.values?.email ?? "");
|
||||
const idPath = editing ? `${ADMIN_USERS_BASE}/${encodeURIComponent(view!.id)}` : ADMIN_USERS_BASE;
|
||||
|
||||
const fields: FieldConfig[] = [
|
||||
{ autocomplete: "email", icon: "i-mail", id: "email", label: t("admin.users.field.email"), name: "email", required: !editing, type: "email", value: email,
|
||||
...(editing ? { hint: t("admin.users.field.emailHint"), readonly: true } : {}) },
|
||||
{ id: "first", label: t("admin.users.field.first"), name: "first", optional: true, value: np.first },
|
||||
{ id: "last", label: t("admin.users.field.last"), name: "last", optional: true, value: np.last },
|
||||
];
|
||||
if (!editing) fields.push({ autocomplete: "new-password", hint: t("admin.users.field.passwordHint"), icon: "i-lock", id: "password", label: t("admin.users.field.password"), name: "password", optional: true, type: "password" });
|
||||
|
||||
const canWrite = opts.canWrite !== false;
|
||||
const mode = !editing ? "new" : canWrite ? "edit" : "view";
|
||||
return {
|
||||
breadcrumbs: [{ href: ADMIN_USERS_BASE, label: t("admin.users.title") }, { label: t({ edit: "common.edit", new: "common.new", view: "admin.users.view" }[mode]) }],
|
||||
canWrite, // the view drops every write affordance when false; the host already 403s the POSTs
|
||||
edit: editing ? {
|
||||
deleteAction: `${idPath}/delete`,
|
||||
id: view!.id,
|
||||
nextLabel: view!.state === "inactive" ? t("admin.users.reactivate") : t("admin.users.deactivate"),
|
||||
recoveryAction: `${idPath}/recovery`,
|
||||
state: view!.state,
|
||||
stateAction: `${idPath}/state`,
|
||||
} : undefined,
|
||||
error: opts.error,
|
||||
form: { action: idPath, cancelHref: ADMIN_USERS_BASE, csrfToken: opts.csrfToken ?? "", fields, submitLabel: editing ? t("admin.users.save") : t("admin.users.create") },
|
||||
permissions: editing ? opts.permissions : undefined,
|
||||
recovery: opts.recovery,
|
||||
title: t({ edit: "admin.users.edit", new: "admin.users.new", view: "admin.users.viewTitle" }[mode]),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- request handler (imperative shell) ----
|
||||
|
||||
function readUserInput(form: URLSearchParams): UserInput {
|
||||
return {
|
||||
email: (form.get("email") ?? "").trim(),
|
||||
first: (form.get("first") ?? "").trim(),
|
||||
last: (form.get("last") ?? "").trim(),
|
||||
password: form.get("password") ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
// Shared per-request deps for the Users screen, resolved by `withUser`: the gate (`users:read` on a
|
||||
// GET, `users:write` on a POST) and the Kratos capability (else a themed 503). Each route below is a
|
||||
// thin handler over these.
|
||||
// `keto` is optional the way every other capability here is: without it the page still lists and
|
||||
// edits users, it just can't show the permission picker.
|
||||
interface UsersDeps { ctx: RequestContext; keto: KetoClient | undefined; kratosAdmin: KratosAdmin; revoke: ((sub: string) => void) | undefined; user: User; }
|
||||
|
||||
// Resolve the shared deps, then run `inner`. The route's own `permission` already gated at the host;
|
||||
// `requirePermission` is defence-in-depth and yields the user. GuardError (auth/CSRF) → host maps it.
|
||||
function withUser(inner: (deps: UsersDeps) => Promise<RouteResult>, action?: AdminAction): RouteHandler {
|
||||
return async (ctx) => {
|
||||
const user = requirePermission(ctx, "users", action);
|
||||
const kratosAdmin = ctx.system?.kratosAdmin;
|
||||
if (!kratosAdmin) return unavailable(ctx, ctx.t("admin.capability.kratos"));
|
||||
return inner({ ctx, keto: ctx.system?.keto, kratosAdmin, revoke: ctx.system?.revoke, user });
|
||||
};
|
||||
}
|
||||
|
||||
// Same, plus the target identity from ctx.params.id (unknown id → themed 404). The router already
|
||||
// decoded the id and 404s malformed %-encoding, so no manual decode is needed here.
|
||||
function withTarget(inner: (deps: UsersDeps, identity: Identity, id: string) => Promise<RouteResult>, action?: AdminAction): RouteHandler {
|
||||
return withUser(async (deps) => {
|
||||
const id = deps.ctx.params["id"] ?? "";
|
||||
const identity = await deps.kratosAdmin.getIdentity(id);
|
||||
if (!identity) return notFound(deps.ctx);
|
||||
return inner(deps, identity, id);
|
||||
}, action);
|
||||
}
|
||||
|
||||
const formResult = (ctx: RequestContext, extra: Parameters<typeof buildUserFormModel>[0]): RouteResult =>
|
||||
({ data: { chrome: ctx.chrome, model: buildUserFormModel({ csrfToken: ctx.chrome.csrfToken, t: ctx.t, ...extra }) }, view: "user-form" });
|
||||
|
||||
// GET /auth-admin/users — the filtered/sorted/paged list.
|
||||
export const usersList = withUser(async ({ ctx, kratosAdmin }) => {
|
||||
const { identities } = await kratosAdmin.listIdentities({ pageSize: LIST_FETCH_SIZE });
|
||||
return { data: { chrome: ctx.chrome, model: buildUsersListModel({ canWrite: canWriteUsers(ctx), csrfToken: ctx.chrome.csrfToken, identities, t: ctx.t, url: ctx.url }) }, view: "users" };
|
||||
});
|
||||
|
||||
// POST /auth-admin/users — create; a Kratos 4xx re-renders the form (400), keeping the input.
|
||||
export const usersCreate = withUser(async ({ ctx, kratosAdmin, user }) => {
|
||||
const input = readUserInput((await guardedForm(ctx))!);
|
||||
try {
|
||||
await kratosAdmin.createIdentity(createIdentityPayload(input));
|
||||
} catch (err) {
|
||||
if (err instanceof KratosError) return { ...formResult(ctx, { error: createError(err, ctx.t), values: input }), status: 400 };
|
||||
throw err;
|
||||
}
|
||||
ctx.log.info("admin: user created", { actor: user.id, email: input.email });
|
||||
return { redirect: ADMIN_USERS_BASE };
|
||||
});
|
||||
|
||||
// GET /auth-admin/users/new — the empty create form.
|
||||
export const usersNewForm = withUser(({ ctx }) => Promise.resolve(formResult(ctx, {})), "write");
|
||||
|
||||
// GET /auth-admin/users/:id — the edit form, prefilled.
|
||||
export const usersEditForm = withTarget(async (deps, identity, id) => {
|
||||
const permissions = await userPermissionPicker(deps, id, undefined, isSavedNotice(deps.ctx.url) ? deps.ctx.t("admin.grants.saved") : undefined);
|
||||
return formResult(deps.ctx, { canWrite: canWriteUsers(deps.ctx), identity, ...(permissions ? { permissions } : {}) });
|
||||
});
|
||||
|
||||
const canWriteUsers = (ctx: RequestContext): boolean => can(ctx, permissionName("users", "write"));
|
||||
|
||||
// The checkbox list of declared permissions: ticked where this user holds one, and disabled where
|
||||
// the grant comes from a group (real, but removed on that group). Undefined when Keto isn't wired —
|
||||
// the rest of the edit page still works.
|
||||
async function userPermissionPicker(deps: UsersDeps, id: string, error?: string, notice?: string): Promise<PermissionPicker | undefined> {
|
||||
if (!deps.keto) return undefined;
|
||||
const subject = userSubject(id);
|
||||
const [direct, effective] = await Promise.all([
|
||||
heldPermissions(deps.keto, subject),
|
||||
effectivePermissions(deps.keto, subject, deps.ctx.declaredPermissions),
|
||||
]);
|
||||
return {
|
||||
...buildPermissionPicker({
|
||||
action: `${ADMIN_USERS_BASE}/${encodeURIComponent(id)}/permissions`,
|
||||
declared: deps.ctx.declaredPermissions,
|
||||
direct,
|
||||
effective,
|
||||
readOnly: !canWriteUsers(deps.ctx),
|
||||
t: deps.ctx.t,
|
||||
}),
|
||||
...(error ? { error } : {}),
|
||||
...(notice ? { notice } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// POST /auth-admin/users/:id/permissions — the submitted checkboxes are the desired set of *direct*
|
||||
// grants; grant what's newly ticked, revoke what's newly unticked. A change to a user's own grants
|
||||
// revokes their live tokens so it lands now rather than at the next re-mint.
|
||||
export const usersPermissions = withTarget(async (deps, identity, id) => {
|
||||
const { ctx, keto, revoke, user } = deps;
|
||||
const form = (await guardedForm(ctx))!;
|
||||
if (!keto) return unavailable(ctx, ctx.t("admin.capability.keto"));
|
||||
const subject = userSubject(id);
|
||||
const held = await heldPermissions(keto, subject);
|
||||
const refuse = async (error: string, status: number): Promise<RouteResult> => {
|
||||
const permissions = await userPermissionPicker(deps, id, error);
|
||||
return { ...formResult(ctx, { canWrite: canWriteUsers(ctx), identity, ...(permissions ? { permissions } : {}) }), status };
|
||||
};
|
||||
const diff = grantDiff(ctx.declaredPermissions, held, form.getAll(PERMISSIONS_FIELD));
|
||||
if (isStale(form, ctx.declaredPermissions, held, diff)) return refuse(ctx.t("admin.grants.stale"), 409);
|
||||
// Self-lockout guard, matching the self-deactivate/self-delete ones: revoking your own grants can
|
||||
// remove the last `users:write` on the deployment, and the instant-revoke hook lands it on the very
|
||||
// next request — leaving a `curl` against Keto as the only way back in.
|
||||
if (id === user.id && diff.revoke.length > 0) {
|
||||
ctx.log.warn("admin: refused a self-revoke of permissions", { actor: user.id, refused: diff.revoke.join(",") });
|
||||
return refuse(ctx.t("admin.grants.selfRevoke"), 400);
|
||||
}
|
||||
const { applied, error } = await applyGrants(keto, subject, diff);
|
||||
if (applied.grant.length > 0 || applied.revoke.length > 0) {
|
||||
revoke?.(id);
|
||||
ctx.log.info("admin: user permissions changed", { actor: user.id, granted: applied.grant.join(","), revoked: applied.revoke.join(","), target: id });
|
||||
}
|
||||
if (error) {
|
||||
ctx.log.error("admin: user permissions only partly saved", { actor: user.id, error: String(error), target: id });
|
||||
return partialSave(ctx, () => refuse(ctx.t("admin.grants.partial"), 502));
|
||||
}
|
||||
return { redirect: `${ADMIN_USERS_BASE}/${encodeURIComponent(id)}?info-msg=${SAVED_NOTICE}` };
|
||||
});
|
||||
|
||||
// POST /auth-admin/users/:id — save edits; a Kratos 4xx re-renders the form (400).
|
||||
export const usersUpdate = withTarget(async (deps, identity, id) => {
|
||||
const { ctx, kratosAdmin } = deps;
|
||||
const input = readUserInput((await guardedForm(ctx))!);
|
||||
try {
|
||||
await kratosAdmin.updateIdentity(id, updateIdentityPayload(identity, input));
|
||||
} catch (err) {
|
||||
// Re-render with the picker, or the permissions section vanishes off the page on a failed save.
|
||||
if (err instanceof KratosError) return { ...formResult(ctx, { canWrite: canWriteUsers(ctx), error: ctx.t("admin.users.error.save"), identity, ...(await pickerOrNothing(deps, id)) }), status: 400 };
|
||||
throw err;
|
||||
}
|
||||
return { redirect: `${ADMIN_USERS_BASE}/${encodeURIComponent(id)}` };
|
||||
});
|
||||
|
||||
// POST /auth-admin/users/:id/state — toggle active/inactive; a deactivation revokes the target's live
|
||||
// tokens now (not after the JWT TTL). Self-protection: an admin can't deactivate their own account.
|
||||
export const usersState = withTarget(async ({ ctx, kratosAdmin, revoke, user }, identity, id) => {
|
||||
await guardedForm(ctx); // CSRF-verify the POST (no fields read)
|
||||
if (id === user.id) return { ...formResult(ctx, { error: ctx.t("admin.users.error.selfDeactivate"), identity }), status: 400 };
|
||||
const nextState = identity.state === "inactive" ? "active" : "inactive";
|
||||
await kratosAdmin.updateIdentity(id, setStatePayload(identity, nextState));
|
||||
if (nextState === "inactive") revoke?.(id);
|
||||
ctx.log.info("admin: user state changed", { actor: user.id, state: nextState, target: id });
|
||||
return { redirect: `${ADMIN_USERS_BASE}/${encodeURIComponent(id)}` };
|
||||
});
|
||||
|
||||
// GET /auth-admin/users/:id/delete — the deliberate confirm step (zero-JS). Refuses self-delete.
|
||||
export const usersDeleteConfirm = withTarget((deps, identity, id) => {
|
||||
if (id === deps.user.id) return Promise.resolve({ ...formResult(deps.ctx, { error: deps.ctx.t("admin.users.error.selfDelete"), identity }), status: 400 });
|
||||
const back = `${ADMIN_USERS_BASE}/${encodeURIComponent(id)}`;
|
||||
const view = toUserView(identity);
|
||||
const tt = deps.ctx.t;
|
||||
return Promise.resolve({ data: { chrome: deps.ctx.chrome, model: buildConfirmModel({
|
||||
breadcrumbs: [{ href: ADMIN_USERS_BASE, label: tt("admin.users.title") }, { href: back, label: view.name }, { label: tt("common.delete") }],
|
||||
cancelHref: back, confirmAction: `${back}/delete`, confirmLabel: tt("admin.users.delete"),
|
||||
message: tt("admin.users.deleteMessage", { email: view.email }), title: tt("admin.users.delete"),
|
||||
}) }, view: "confirm" });
|
||||
}, "write");
|
||||
|
||||
// POST /auth-admin/users/:id/delete — perform it; revoke the gone account's live tokens. Refuses self-delete.
|
||||
export const usersDelete = withTarget(async ({ ctx, kratosAdmin, revoke, user }, identity, id) => {
|
||||
await guardedForm(ctx); // CSRF-verify the POST
|
||||
if (id === user.id) return { ...formResult(ctx, { error: ctx.t("admin.users.error.selfDelete"), identity }), status: 400 };
|
||||
await kratosAdmin.deleteIdentity(id);
|
||||
revoke?.(id);
|
||||
ctx.log.info("admin: user deleted", { actor: user.id, target: id });
|
||||
return { redirect: ADMIN_USERS_BASE };
|
||||
});
|
||||
|
||||
// POST /auth-admin/users/:id/recovery — mint a one-time recovery code, shown on the edit page.
|
||||
export const usersRecovery = withTarget(async (deps, identity, id) => {
|
||||
const { ctx, kratosAdmin } = deps;
|
||||
await guardedForm(ctx); // CSRF-verify the POST
|
||||
const recovery = await kratosAdmin.createRecoveryCode(id);
|
||||
return formResult(ctx, { canWrite: canWriteUsers(ctx), identity, recovery, ...(await pickerOrNothing(deps, id)) });
|
||||
});
|
||||
|
||||
// The picker as a spreadable fragment, so a re-render never silently drops the section.
|
||||
async function pickerOrNothing(deps: UsersDeps, id: string): Promise<{ permissions?: PermissionPicker }> {
|
||||
const permissions = await userPermissionPicker(deps, id);
|
||||
return permissions ? { permissions } : {};
|
||||
}
|
||||
|
||||
function createError(err: KratosError, t: Translate): string {
|
||||
return err.status === 409
|
||||
? t("admin.users.error.duplicate")
|
||||
: t("admin.users.error.create");
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// The admin plugin's own catalog — the baseline its other locales are written against. Its keys
|
||||
// are looked up before the host's, so this plugin owns its words without prefixing them.
|
||||
|
||||
const messages = {
|
||||
"admin.capability.hydra": "Hydra OAuth2 admin",
|
||||
"admin.capability.keto": "Keto and Kratos identity admin",
|
||||
"admin.capability.kratos": "Kratos identity admin",
|
||||
|
||||
"admin.clients.column.id": "Client ID",
|
||||
"admin.clients.column.name": "Name",
|
||||
"admin.clients.column.type": "Type",
|
||||
"admin.clients.confidential": "Confidential",
|
||||
"admin.clients.consent.firstParty": "First-party (auto-granted)",
|
||||
"admin.clients.consent.label": "Consent",
|
||||
"admin.clients.consent.screen": "Shows the consent screen",
|
||||
"admin.clients.created": "Client registered",
|
||||
"admin.clients.createdNotice": "Client registered.",
|
||||
"admin.clients.delete": "Delete client",
|
||||
"admin.clients.deleteMessage": "Delete client {{name}}? Apps using it can no longer sign in through Plainpages.",
|
||||
"admin.clients.error.rejected": "Hydra rejected the client — check the redirect URIs and scopes.",
|
||||
"admin.clients.field.name": "Name",
|
||||
"admin.clients.field.redirectUris": "Redirect URIs",
|
||||
"admin.clients.field.redirectUrisHint": "One per line — where the app is sent back after sign-in.",
|
||||
"admin.clients.field.scopes": "Scopes",
|
||||
"admin.clients.field.scopesHint": "Space-separated scopes the client may request.",
|
||||
"admin.clients.field.typeHint":
|
||||
"Browser and mobile apps can't keep a secret — choose Public. Server-side apps that can store one — leave it Confidential.",
|
||||
"admin.clients.filter": "Filter clients",
|
||||
"admin.clients.pagination": "Clients pagination",
|
||||
"admin.clients.public": "Public",
|
||||
"admin.clients.publicPkce": "Public (PKCE)",
|
||||
"admin.clients.register": "Register",
|
||||
"admin.clients.registerClient": "Register client",
|
||||
"admin.clients.registerTitle": "Register client",
|
||||
"admin.clients.rereg": "To change a client, delete and re-register — this issues a new client ID and secret. The secret is shown only once, at registration.",
|
||||
"admin.clients.searchLabel": "Search clients",
|
||||
"admin.clients.searchPlaceholder": "Search name or client ID…",
|
||||
"admin.clients.secret": "Client secret",
|
||||
"admin.clients.secretHint": "Copy these now — the secret can't be shown again. Store them where the app reads its credentials.",
|
||||
"admin.clients.title": "OAuth2 clients",
|
||||
"admin.clients.validation.name": "Enter a name for the client.",
|
||||
"admin.clients.validation.redirectUri": "\"{{uri}}\" is not a valid redirect URI — use an absolute URL like https://app.example.com/callback.",
|
||||
"admin.clients.validation.redirectUris": "Add at least one redirect URI.",
|
||||
|
||||
"admin.common.chooseMember": "Choose a user or group…",
|
||||
"admin.common.group": "Group",
|
||||
"admin.common.member": "Member",
|
||||
"admin.common.type": "Type",
|
||||
"admin.common.user": "User",
|
||||
|
||||
"admin.grants.hint": "Which permissions exist is set by the plugins installed on this system. Tick to grant, untick to revoke.",
|
||||
"admin.grants.hintReadOnly": "Which permissions exist is set by the plugins installed on this system. You can see these, but not change them.",
|
||||
"admin.grants.inherited": "Greyed-out permissions come from a group. Change them on that group.",
|
||||
"admin.grants.legend": "Permissions",
|
||||
"admin.grants.none": "No installed plugin declares a permission, so there is nothing to grant.",
|
||||
"admin.grants.partial": "Saving stopped part-way because the permission service failed, so only some changes were applied. Check the permissions and make any remaining changes again.",
|
||||
"admin.grants.pending": "Members get this at their next sign-in (up to 10 minutes).",
|
||||
"admin.grants.save": "Save permissions",
|
||||
"admin.grants.saved": "Permissions saved.",
|
||||
"admin.grants.selfRevoke": "You can't revoke your own permissions — ask another administrator, so you can't lock yourself out.",
|
||||
"admin.grants.stale": "These permissions changed while you had the page open, so nothing was saved. The list now shows the current state. Review it and save again.",
|
||||
|
||||
"admin.groups.actions": "Group actions",
|
||||
"admin.groups.addMember": "Add a member",
|
||||
"admin.groups.allMembers": "All users and groups are already members.",
|
||||
"admin.groups.column.members": "Members",
|
||||
"admin.groups.column.name": "Group",
|
||||
"admin.groups.create": "Create group",
|
||||
"admin.groups.delete": "Delete group",
|
||||
"admin.groups.deleteMessage": "Delete group {{name}}? This can't be undone.",
|
||||
"admin.groups.error.duplicate": "A group with that name already exists.",
|
||||
"admin.groups.error.selfLockout": "This change would lock you out of {{permissions}}, which you hold through this group. Ask another administrator to make it.",
|
||||
"admin.groups.field.name": "Group name",
|
||||
"admin.groups.field.nameHint": "Lowercase letters, digits, dashes and underscores.",
|
||||
"admin.groups.filter": "Filter groups",
|
||||
"admin.groups.firstMember": "First member",
|
||||
"admin.groups.firstMemberHint": "A group exists once it has a member; add more after creating it.",
|
||||
"admin.groups.members": "Members",
|
||||
"admin.groups.membersOf": "Members of {{name}}",
|
||||
"admin.groups.new": "New group",
|
||||
"admin.groups.noMembers": "No members yet.",
|
||||
"admin.groups.pagination": "Groups pagination",
|
||||
"admin.groups.searchLabel": "Search groups",
|
||||
"admin.groups.searchPlaceholder": "Search group name…",
|
||||
"admin.groups.title": "Groups",
|
||||
"admin.groups.validation.member": "Pick a member to add as the group's first member.",
|
||||
"admin.groups.validation.name": "Group names use lowercase letters, digits, dashes and underscores.",
|
||||
|
||||
"admin.nav.clients": "OAuth2 clients",
|
||||
"admin.nav.groups": "Groups",
|
||||
"admin.nav.pluginSettings": "Plugin settings",
|
||||
"admin.nav.section": "Admin",
|
||||
"admin.nav.users": "Users",
|
||||
|
||||
"admin.pluginSettings.caption": "Settings declared by {{plugin}}",
|
||||
"admin.pluginSettings.column.description": "Description",
|
||||
"admin.pluginSettings.column.key": "Key",
|
||||
"admin.pluginSettings.column.required": "Required",
|
||||
"admin.pluginSettings.column.source": "Source",
|
||||
"admin.pluginSettings.column.type": "Type",
|
||||
"admin.pluginSettings.column.value": "Value",
|
||||
"admin.pluginSettings.column.variable": "Variable",
|
||||
"admin.pluginSettings.no": "No",
|
||||
"admin.pluginSettings.none": "This plugin declares no settings.",
|
||||
"admin.pluginSettings.secretSet": "Secret — set",
|
||||
"admin.pluginSettings.secretUnset": "Secret — not set",
|
||||
"admin.pluginSettings.source.default": "Default",
|
||||
"admin.pluginSettings.source.env": "Environment",
|
||||
"admin.pluginSettings.source.unset": "Not set",
|
||||
"admin.pluginSettings.title": "Plugin settings",
|
||||
"admin.pluginSettings.unset": "—",
|
||||
"admin.pluginSettings.yes": "Yes",
|
||||
|
||||
"admin.notFound.message": "That item doesn't exist.",
|
||||
"admin.notFound.title": "Not found",
|
||||
|
||||
"admin.unavailable.message": "{{what}} is not configured on this deployment.",
|
||||
"admin.unavailable.title": "Admin unavailable",
|
||||
|
||||
"admin.users.actions": "Account actions",
|
||||
"admin.users.column.email": "Email",
|
||||
"admin.users.column.name": "Name",
|
||||
"admin.users.column.status": "Status",
|
||||
"admin.users.confirm": "Confirm action",
|
||||
"admin.users.create": "Create user",
|
||||
"admin.users.deactivate": "Deactivate",
|
||||
"admin.users.delete": "Delete user",
|
||||
"admin.users.deleteMessage": "Delete {{email}}? This permanently removes the account and can't be undone.",
|
||||
"admin.users.edit": "Edit user",
|
||||
"admin.users.error.create": "Could not create the user — check the email and try again.",
|
||||
"admin.users.error.duplicate": "A user with that email already exists.",
|
||||
"admin.users.error.save": "Could not save changes — check the fields and try again.",
|
||||
"admin.users.error.selfDeactivate": "You can't deactivate your own account.",
|
||||
"admin.users.error.selfDelete": "You can't delete your own account.",
|
||||
"admin.users.field.email": "Email",
|
||||
"admin.users.field.emailHint": "The sign-in identifier — can't be changed here.",
|
||||
"admin.users.field.first": "First name",
|
||||
"admin.users.field.last": "Last name",
|
||||
"admin.users.field.password": "Password",
|
||||
"admin.users.field.passwordHint": "Optional — leave blank to have the user set one via a recovery code.",
|
||||
"admin.users.filter": "Filter users",
|
||||
"admin.users.new": "New user",
|
||||
"admin.users.pagination": "Users pagination",
|
||||
"admin.users.reactivate": "Reactivate",
|
||||
"admin.users.recovery.body": "Send the user this link and code. They open the link and enter the code to set a new password (generate a fresh code if it has expired):",
|
||||
"admin.users.recovery.link": "password-reset link",
|
||||
"admin.users.recovery.generate": "Generate recovery code",
|
||||
"admin.users.recovery.title": "Recovery code generated",
|
||||
"admin.users.save": "Save changes",
|
||||
"admin.users.searchLabel": "Search users",
|
||||
"admin.users.searchPlaceholder": "Search name or email…",
|
||||
"admin.users.status.active": "Active",
|
||||
"admin.users.status.all": "All",
|
||||
"admin.users.status.inactive": "Inactive",
|
||||
"admin.users.status.label": "Status",
|
||||
"admin.users.title": "Users",
|
||||
"admin.users.view": "View",
|
||||
"admin.users.viewTitle": "View user",
|
||||
};
|
||||
|
||||
export type AdminMessages = typeof messages;
|
||||
|
||||
export default messages;
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { AdminMessages } from "./en-US.ts";
|
||||
|
||||
const messages: AdminMessages = {
|
||||
"admin.capability.hydra": "Hydra OAuth2-administration",
|
||||
"admin.capability.keto": "Keto- och Kratos-identitetsadministration",
|
||||
"admin.capability.kratos": "Kratos identitetsadministration",
|
||||
|
||||
"admin.clients.column.id": "Klient-ID",
|
||||
"admin.clients.column.name": "Namn",
|
||||
"admin.clients.column.type": "Typ",
|
||||
"admin.clients.confidential": "Konfidentiell",
|
||||
"admin.clients.consent.firstParty": "Förstapart (godkänns automatiskt)",
|
||||
"admin.clients.consent.label": "Godkännande",
|
||||
"admin.clients.consent.screen": "Visar godkännandesidan",
|
||||
"admin.clients.created": "Klienten är registrerad",
|
||||
"admin.clients.createdNotice": "Klienten är registrerad.",
|
||||
"admin.clients.delete": "Radera klient",
|
||||
"admin.clients.deleteMessage": "Ta bort klienten {{name}}? Appar som använder den kan inte längre logga in via Plainpages.",
|
||||
"admin.clients.error.rejected": "Hydra nekade klienten — kontrollera omdirigerings-URI:erna och scopen.",
|
||||
"admin.clients.field.name": "Namn",
|
||||
"admin.clients.field.redirectUris": "Omdirigerings-URI:er",
|
||||
"admin.clients.field.redirectUrisHint": "En per rad — dit appen skickas tillbaka efter inloggning.",
|
||||
"admin.clients.field.scopes": "Scope",
|
||||
"admin.clients.field.scopesHint": "Mellanslagsseparerade scope som klienten får begära.",
|
||||
"admin.clients.field.typeHint":
|
||||
"Webbläsar- och mobilappar kan inte hålla en hemlighet — välj Publik. Serverappar som kan lagra en — låt stå som Konfidentiell.",
|
||||
"admin.clients.filter": "Filtrera klienter",
|
||||
"admin.clients.pagination": "Sidnavigering för klienter",
|
||||
"admin.clients.public": "Publik",
|
||||
"admin.clients.publicPkce": "Publik (PKCE)",
|
||||
"admin.clients.register": "Registrera",
|
||||
"admin.clients.registerClient": "Registrera klient",
|
||||
"admin.clients.registerTitle": "Registrera klient",
|
||||
"admin.clients.rereg":
|
||||
"För att ändra en klient: ta bort den och registrera på nytt — det ger ett nytt klient-ID och en ny hemlighet. Hemligheten visas bara en gång, vid registreringen.",
|
||||
"admin.clients.searchLabel": "Sök klienter",
|
||||
"admin.clients.searchPlaceholder": "Sök på namn eller klient-ID…",
|
||||
"admin.clients.secret": "Klienthemlighet",
|
||||
"admin.clients.secretHint": "Kopiera nu — hemligheten kan inte visas igen. Spara uppgifterna där appen läser dem.",
|
||||
"admin.clients.title": "OAuth2-klienter",
|
||||
"admin.clients.validation.name": "Ange ett namn för klienten.",
|
||||
"admin.clients.validation.redirectUri": "\"{{uri}}\" är inte en giltig omdirigerings-URI — använd en absolut URL som https://app.example.com/callback.",
|
||||
"admin.clients.validation.redirectUris": "Lägg till minst en omdirigerings-URI.",
|
||||
|
||||
"admin.common.chooseMember": "Välj en användare eller grupp…",
|
||||
"admin.common.group": "Grupp",
|
||||
"admin.common.member": "Medlem",
|
||||
"admin.common.type": "Typ",
|
||||
"admin.common.user": "Användare",
|
||||
|
||||
"admin.grants.hint": "Vilka behörigheter som finns bestäms av de plugins som är installerade. Kryssa i för att tilldela, ur för att återkalla.",
|
||||
"admin.grants.hintReadOnly": "Vilka behörigheter som finns bestäms av de plugins som är installerade. Du kan se dem, men inte ändra dem.",
|
||||
"admin.grants.inherited": "Gråmarkerade behörigheter kommer från en grupp. Ändra dem på gruppen.",
|
||||
"admin.grants.legend": "Behörigheter",
|
||||
"admin.grants.none": "Ingen installerad plugin deklarerar någon behörighet, så det finns inget att tilldela.",
|
||||
"admin.grants.partial": "Sparandet avbröts halvvägs eftersom behörighetstjänsten gav fel, så bara en del av ändringarna genomfördes. Kontrollera behörigheterna och gör de återstående ändringarna igen.",
|
||||
"admin.grants.pending": "Medlemmar får detta vid nästa inloggning (upp till 10 minuter).",
|
||||
"admin.grants.save": "Spara behörigheter",
|
||||
"admin.grants.saved": "Behörigheterna är sparade.",
|
||||
"admin.grants.selfRevoke": "Du kan inte återkalla dina egna behörigheter — be en annan administratör, så att du inte låser ute dig själv.",
|
||||
"admin.grants.stale": "Behörigheterna ändrades medan du hade sidan öppen, så ingenting sparades. Listan visar nu aktuellt läge. Granska den och spara igen.",
|
||||
|
||||
"admin.groups.actions": "Gruppåtgärder",
|
||||
"admin.groups.addMember": "Lägg till en medlem",
|
||||
"admin.groups.allMembers": "Alla användare och grupper är redan medlemmar.",
|
||||
"admin.groups.column.members": "Medlemmar",
|
||||
"admin.groups.column.name": "Grupp",
|
||||
"admin.groups.create": "Skapa grupp",
|
||||
"admin.groups.delete": "Radera grupp",
|
||||
"admin.groups.deleteMessage": "Ta bort gruppen {{name}}? Det går inte att ångra.",
|
||||
"admin.groups.error.duplicate": "Det finns redan en grupp med det namnet.",
|
||||
"admin.groups.error.selfLockout": "Ändringen skulle låsa ute dig från {{permissions}}, som du har genom den här gruppen. Be en annan administratör att göra den.",
|
||||
"admin.groups.field.name": "Gruppnamn",
|
||||
"admin.groups.field.nameHint": "Små bokstäver, siffror, bindestreck och understreck.",
|
||||
"admin.groups.filter": "Filtrera grupper",
|
||||
"admin.groups.firstMember": "Första medlem",
|
||||
"admin.groups.firstMemberHint": "En grupp finns så snart den har en medlem; lägg till fler efteråt.",
|
||||
"admin.groups.members": "Medlemmar",
|
||||
"admin.groups.membersOf": "Medlemmar i {{name}}",
|
||||
"admin.groups.new": "Ny grupp",
|
||||
"admin.groups.noMembers": "Inga medlemmar ännu.",
|
||||
"admin.groups.pagination": "Sidnavigering för grupper",
|
||||
"admin.groups.searchLabel": "Sök grupper",
|
||||
"admin.groups.searchPlaceholder": "Sök på gruppnamn…",
|
||||
"admin.groups.title": "Grupper",
|
||||
"admin.groups.validation.member": "Välj en medlem som gruppens första medlem.",
|
||||
"admin.groups.validation.name": "Gruppnamn använder små bokstäver, siffror, bindestreck och understreck.",
|
||||
|
||||
"admin.nav.clients": "OAuth2-klienter",
|
||||
"admin.nav.groups": "Grupper",
|
||||
"admin.nav.pluginSettings": "Tilläggsinställningar",
|
||||
"admin.nav.section": "Administration",
|
||||
"admin.nav.users": "Användare",
|
||||
|
||||
"admin.pluginSettings.caption": "Inställningar som {{plugin}} deklarerar",
|
||||
"admin.pluginSettings.column.description": "Beskrivning",
|
||||
"admin.pluginSettings.column.key": "Nyckel",
|
||||
"admin.pluginSettings.column.required": "Obligatorisk",
|
||||
"admin.pluginSettings.column.source": "Källa",
|
||||
"admin.pluginSettings.column.type": "Typ",
|
||||
"admin.pluginSettings.column.value": "Värde",
|
||||
"admin.pluginSettings.column.variable": "Variabel",
|
||||
"admin.pluginSettings.no": "Nej",
|
||||
"admin.pluginSettings.none": "Det här tillägget deklarerar inga inställningar.",
|
||||
"admin.pluginSettings.secretSet": "Hemlighet — satt",
|
||||
"admin.pluginSettings.secretUnset": "Hemlighet — inte satt",
|
||||
"admin.pluginSettings.source.default": "Standardvärde",
|
||||
"admin.pluginSettings.source.env": "Miljövariabel",
|
||||
"admin.pluginSettings.source.unset": "Inte satt",
|
||||
"admin.pluginSettings.title": "Tilläggsinställningar",
|
||||
"admin.pluginSettings.unset": "—",
|
||||
"admin.pluginSettings.yes": "Ja",
|
||||
|
||||
"admin.notFound.message": "Objektet finns inte.",
|
||||
"admin.notFound.title": "Hittades inte",
|
||||
|
||||
"admin.unavailable.message": "{{what}} är inte konfigurerat i den här installationen.",
|
||||
"admin.unavailable.title": "Administrationen är otillgänglig",
|
||||
|
||||
"admin.users.actions": "Kontoåtgärder",
|
||||
"admin.users.column.email": "E-postadress",
|
||||
"admin.users.column.name": "Namn",
|
||||
"admin.users.column.status": "Status",
|
||||
"admin.users.confirm": "Bekräfta åtgärden",
|
||||
"admin.users.create": "Skapa användare",
|
||||
"admin.users.deactivate": "Inaktivera",
|
||||
"admin.users.delete": "Radera användare",
|
||||
"admin.users.deleteMessage": "Ta bort {{email}}? Kontot tas bort permanent och det går inte att ångra.",
|
||||
"admin.users.edit": "Redigera användare",
|
||||
"admin.users.error.create": "Användaren kunde inte skapas — kontrollera e-postadressen och försök igen.",
|
||||
"admin.users.error.duplicate": "Det finns redan en användare med den e-postadressen.",
|
||||
"admin.users.error.save": "Ändringarna kunde inte sparas — kontrollera fälten och försök igen.",
|
||||
"admin.users.error.selfDeactivate": "Du kan inte inaktivera ditt eget konto.",
|
||||
"admin.users.error.selfDelete": "Du kan inte ta bort ditt eget konto.",
|
||||
"admin.users.field.email": "E-postadress",
|
||||
"admin.users.field.emailHint": "Inloggningsidentiteten — den kan inte ändras här.",
|
||||
"admin.users.field.first": "Förnamn",
|
||||
"admin.users.field.last": "Efternamn",
|
||||
"admin.users.field.password": "Lösenord",
|
||||
"admin.users.field.passwordHint": "Frivilligt — lämna tomt så får användaren sätta det själv via en återställningskod.",
|
||||
"admin.users.filter": "Filtrera användare",
|
||||
"admin.users.new": "Ny användare",
|
||||
"admin.users.pagination": "Sidnavigering för användare",
|
||||
"admin.users.reactivate": "Aktivera igen",
|
||||
"admin.users.recovery.body": "Skicka länken och koden till användaren. Användaren öppnar länken och anger koden för att sätta ett nytt lösenord (skapa en ny kod om den hunnit gå ut):",
|
||||
"admin.users.recovery.link": "länk för lösenordsåterställning",
|
||||
"admin.users.recovery.generate": "Skapa återställningskod",
|
||||
"admin.users.recovery.title": "Återställningskod skapad",
|
||||
"admin.users.save": "Spara ändringar",
|
||||
"admin.users.searchLabel": "Sök användare",
|
||||
"admin.users.searchPlaceholder": "Sök på namn eller e-postadress…",
|
||||
"admin.users.status.active": "Aktiv",
|
||||
"admin.users.status.all": "Alla",
|
||||
"admin.users.status.inactive": "Inaktiv",
|
||||
"admin.users.status.label": "Status",
|
||||
"admin.users.title": "Användare",
|
||||
"admin.users.view": "Visa",
|
||||
"admin.users.viewTitle": "Visa användare",
|
||||
};
|
||||
|
||||
export default messages;
|
||||
@@ -0,0 +1,65 @@
|
||||
// The manifest's own invariants. A route gating on a permission the manifest doesn't declare is
|
||||
// silent: bootstrap seeds only declared names, so the demo admin would simply 403 on that screen
|
||||
// with nothing in the logs to explain it. Pin the two halves against each other here.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { isValidPermissionName } from "@plainpages/plugin-api";
|
||||
import manifest from "./plugin.ts";
|
||||
|
||||
const routes = manifest.routes ?? [];
|
||||
const declared = (manifest.permissions ?? []).map((p) => p.name);
|
||||
|
||||
test("every route is gated, and gates on a permission the manifest declares", () => {
|
||||
assert.ok(routes.length > 0);
|
||||
for (const route of routes) {
|
||||
assert.equal(route.public, undefined, `${route.method} ${route.path} must not be public`);
|
||||
assert.ok(route.permission, `${route.method} ${route.path} has no permission`);
|
||||
assert.ok(declared.includes(route.permission!), `${route.method} ${route.path} gates on undeclared ${route.permission}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the manifest declares no permission it never gates on", () => {
|
||||
const gated = new Set(routes.map((r) => r.permission));
|
||||
for (const name of declared) assert.ok(gated.has(name), `declared but unused: ${name}`);
|
||||
});
|
||||
|
||||
// A nav permission is a plain string the host matches against the JWT claim: a typo ("user:read")
|
||||
// passes discovery's shape check and silently hides that menu item forever. Same silent-failure
|
||||
// class the route checks above close, so close it on the nav side too.
|
||||
test("every nav permission is one the manifest declares", () => {
|
||||
const navPermissions: string[] = [];
|
||||
const walk = (nodes: typeof manifest.nav): void => {
|
||||
for (const node of nodes ?? []) {
|
||||
if (node.permission != null) navPermissions.push(node.permission);
|
||||
walk(node.children);
|
||||
}
|
||||
};
|
||||
walk(manifest.nav);
|
||||
assert.equal(navPermissions.length, 4);
|
||||
for (const name of navPermissions) assert.ok(declared.includes(name), `nav gates on undeclared ${name}`);
|
||||
});
|
||||
|
||||
test("every declared permission is <resource>:<action>, and reads and writes are split per resource", () => {
|
||||
for (const name of declared) assert.ok(isValidPermissionName(name), name); // the host's rule, not a copy of it
|
||||
// Three CRUD screens × read/write, plus read-only plugin settings — a screen that never writes
|
||||
// declares no `:write`, since a permission nothing gates on is one an operator can only mis-grant.
|
||||
// There is deliberately no `permissions:` pair either: permissions are declared in plugin code, so
|
||||
// holding one is edited on the user or group that holds it.
|
||||
assert.deepEqual([...declared].sort(), [
|
||||
"groups:read", "groups:write",
|
||||
"oauth2-clients:read", "oauth2-clients:write",
|
||||
"plugin-settings:read",
|
||||
"users:read", "users:write",
|
||||
]);
|
||||
});
|
||||
|
||||
test("GET routes gate on read and mutations on write, so a reader can open a screen but not change it", () => {
|
||||
// …except a write-intent GET — a create form or a delete-confirm page, which exists only to start a
|
||||
// write. Those gate on `:write` so a reader is refused there rather than at the submit.
|
||||
const writeIntent = (path: string): boolean => path.endsWith("/new") || path.endsWith("/delete");
|
||||
for (const route of routes) {
|
||||
const action = route.method === "GET" && !writeIntent(route.path) ? "read" : "write";
|
||||
assert.ok(route.permission?.endsWith(`:${action}`), `${route.method} ${route.path} → ${route.permission}`);
|
||||
}
|
||||
assert.equal(routes.filter((r) => r.method === "GET" && writeIntent(r.path)).length, 6); // 2 per CRUD screen; plugin settings has none
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
// Admin example plugin: the Users / Groups / OAuth2-clients screens for running the system. Copy
|
||||
// this folder to plugins/auth-admin (then restart) to enable it — see README → Quick start.
|
||||
//
|
||||
// It is a *system* plugin: its handlers reach the host's Ory admin clients and the instant-revoke
|
||||
// hook via ctx.system. Where a capability is absent the screen degrades to a themed 503.
|
||||
|
||||
import { definePlugin, type HttpMethod, type Route, type RouteHandler } from "@plainpages/plugin-api";
|
||||
import { clientsCreate, clientsDeleteConfirm, clientsDelete, clientsDetail, clientsList, clientsNewForm } from "./admin-clients.ts";
|
||||
import { groupsAddMember, groupsCreate, groupsDelete, groupsDeleteConfirm, groupsDetail, groupsList, groupsNewForm, groupsPermissions, groupsRemoveMember } from "./admin-groups.ts";
|
||||
import { pluginSettingsList } from "./admin-plugin-settings.ts";
|
||||
import { usersCreate, usersDeleteConfirm, usersDelete, usersEditForm, usersList, usersNewForm, usersPermissions, usersRecovery, usersState, usersUpdate } from "./admin-users.ts";
|
||||
import { ADMIN_NAV, actionForMethod, type AdminAction, type AdminResource, permissionName } from "./admin-shared.ts";
|
||||
|
||||
// One route factory per screen: a GET gates on `<resource>:read` and a POST on `<resource>:write`,
|
||||
// derived through the same two helpers the in-handler guard uses, so the table below cannot drift
|
||||
// from it. The host redirects an anonymous visitor to /login, gives a signed-in user missing the
|
||||
// permission the 403 page, and filters the nav the same way. Handlers are thin and keyed on
|
||||
// ctx.params (the host extracts :id / :name), the idiomatic per-route style.
|
||||
// `action` overrides the method's default for a *write-intent GET* — a create form or a
|
||||
// delete-confirm page, which exists only to start a write and so refuses a reader rather than
|
||||
// rendering a form whose submit would 403. The handler's own guard takes the same override.
|
||||
const on = (resource: AdminResource) => (method: HttpMethod, path: string, handler: RouteHandler, action?: AdminAction): Route =>
|
||||
({ handler, method, path, permission: permissionName(resource, action ?? actionForMethod(method)) });
|
||||
|
||||
const users = on("users");
|
||||
const groups = on("groups");
|
||||
const clients = on("oauth2-clients");
|
||||
const pluginSettings = on("plugin-settings");
|
||||
|
||||
export default definePlugin({
|
||||
apiVersion: "0.5.0", // the host contract this was built against — a literal, never HOST_API_VERSION
|
||||
|
||||
nav: [ADMIN_NAV],
|
||||
|
||||
permissions: [
|
||||
{ description: "View users and the permissions they hold", name: "users:read" },
|
||||
{ description: "Create, edit and delete users, and grant them permissions", name: "users:write" },
|
||||
{ description: "View groups, their members and the permissions they hold", name: "groups:read" },
|
||||
{ description: "Create and delete groups, and change their members and permissions", name: "groups:write" },
|
||||
{ description: "View OAuth2 clients", name: "oauth2-clients:read" },
|
||||
{ description: "Register and delete OAuth2 clients", name: "oauth2-clients:write" },
|
||||
{ description: "View the settings each installed plugin declares, and how they resolved", name: "plugin-settings:read" },
|
||||
],
|
||||
|
||||
routes: [
|
||||
// Users
|
||||
users("GET", "/users", usersList),
|
||||
users("POST", "/users", usersCreate),
|
||||
users("GET", "/users/new", usersNewForm, "write"),
|
||||
users("GET", "/users/:id", usersEditForm),
|
||||
users("POST", "/users/:id", usersUpdate),
|
||||
users("POST", "/users/:id/state", usersState),
|
||||
users("GET", "/users/:id/delete", usersDeleteConfirm, "write"),
|
||||
users("POST", "/users/:id/delete", usersDelete),
|
||||
users("POST", "/users/:id/recovery", usersRecovery),
|
||||
users("POST", "/users/:id/permissions", usersPermissions),
|
||||
// Groups
|
||||
groups("GET", "/groups", groupsList),
|
||||
groups("POST", "/groups", groupsCreate),
|
||||
groups("GET", "/groups/new", groupsNewForm, "write"),
|
||||
groups("GET", "/groups/:name", groupsDetail),
|
||||
groups("POST", "/groups/:name/members", groupsAddMember),
|
||||
groups("GET", "/groups/:name/delete", groupsDeleteConfirm, "write"),
|
||||
groups("POST", "/groups/:name/delete", groupsDelete),
|
||||
groups("POST", "/groups/:name/members/delete", groupsRemoveMember),
|
||||
groups("POST", "/groups/:name/permissions", groupsPermissions),
|
||||
// OAuth2 clients
|
||||
clients("GET", "/clients", clientsList),
|
||||
clients("POST", "/clients", clientsCreate),
|
||||
clients("GET", "/clients/new", clientsNewForm, "write"),
|
||||
clients("GET", "/clients/:id", clientsDetail),
|
||||
clients("GET", "/clients/:id/delete", clientsDeleteConfirm, "write"),
|
||||
clients("POST", "/clients/:id/delete", clientsDelete),
|
||||
// Plugin settings — read-only, so no :write route and no write-intent GET.
|
||||
pluginSettings("GET", "/plugin-settings", pluginSettingsList),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
<%#
|
||||
OAuth2 client detail page: the client-detail body (info · one-time secret · delete) in the
|
||||
shell. Doubles as the post-register page when `created`/`secret` are set.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/client-detail-body", { canWrite: model.canWrite, client: model.client, created: model.created, csrfToken: chrome.csrfToken, del: model.delete, secret: model.secret });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,16 @@
|
||||
<%#
|
||||
OAuth2 client register page: the client-form body captured into the app shell.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/client-form-body", { error: model.error, form: model.form });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,22 @@
|
||||
<%#
|
||||
OAuth2 clients admin list: apps that log in *through* us (Hydra). Same building blocks as
|
||||
the Groups screen, around the shell, backed by live Hydra OAuth2 clients (admin-clients.ts).
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const filters = include("partials/filter-bar", model.filterBar);
|
||||
const table = include("partials/data-table", model.table);
|
||||
const pager = include("partials/pagination", model.pagination);
|
||||
// Only offer "Register client" to an oauth2-clients:write holder — a :read one would get the 403 page.
|
||||
const actions = model.canWrite === false ? "" : '<a class="btn btn-primary" href="' + localeHref("/auth-admin/clients/new") + '"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-plus"/></svg>' + t("admin.clients.registerClient") + '</a>';
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
actions,
|
||||
body: filters + table + pager,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%#
|
||||
Admin destructive-action confirmation page: the confirm body in the app shell. Model
|
||||
from buildConfirmModel: { message, confirm:{action,label}, cancelHref, nav, shell }.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/confirm-body", { cancelHref: model.cancelHref, confirm: model.confirm, csrfToken: chrome.csrfToken, message: model.message });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,16 @@
|
||||
<%#
|
||||
Group admin detail / membership page: the group-detail body in the app shell.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/group-detail-body", { add: model.add, canWrite: model.canWrite, csrfToken: model.csrfToken, del: model.delete, error: model.error, group: model.group, members: model.members, permissions: model.permissions });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,16 @@
|
||||
<%#
|
||||
Group admin create page: the group-form body captured into the app shell.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/group-form-body", { error: model.error, form: model.form });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,22 @@
|
||||
<%#
|
||||
Groups admin list: the same building blocks as the Users screen, around the shell, but
|
||||
backed by live Keto subject sets (admin-groups.ts). Filter/sort/page round-trip the URL.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const filters = include("partials/filter-bar", model.filterBar);
|
||||
const table = include("partials/data-table", model.table);
|
||||
const pager = include("partials/pagination", model.pagination);
|
||||
// Only offer "New group" to a groups:write holder — a groups:read one would get the 403 page.
|
||||
const actions = model.canWrite === false ? "" : '<a class="btn btn-primary" href="' + localeHref("/auth-admin/groups/new") + '"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-plus"/></svg>' + t("admin.groups.new") + '</a>';
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
actions,
|
||||
body: filters + table + pager,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%#
|
||||
Admin notice page — a single message in the app shell, reused for not-found (404) and
|
||||
capability-unavailable (503). The shell renders `title` as the page <h1>; the body is one line.
|
||||
Data: chrome, title, message.
|
||||
%><%
|
||||
const navHtml = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/notice-body", { message });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav: navHtml,
|
||||
theme: chrome.theme,
|
||||
title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,40 @@
|
||||
<%#
|
||||
Admin OAuth2 client detail body, captured into the shell content slot. Config:
|
||||
client { firstParty, id, name, public, redirectUris[], scopes[] }
|
||||
created bool just registered → success banner
|
||||
secret? string one-time client secret (confidential clients), shown once right after create
|
||||
del { action } delete the client
|
||||
csrfToken
|
||||
%><%
|
||||
const c = locals.client;
|
||||
const del = locals.del;
|
||||
-%>
|
||||
<div class="form-page">
|
||||
<% if (locals.created) { -%>
|
||||
<%- include("partials/alert", { text: t("admin.clients.createdNotice"), tone: "pos" }) %>
|
||||
<% } -%>
|
||||
<% if (locals.secret) { -%>
|
||||
<section class="form-card" aria-labelledby="secret-h">
|
||||
<h2 class="card-title" id="secret-h"><%= t("admin.clients.secret") %></h2>
|
||||
<p class="field-hint"><%= t("admin.clients.secretHint") %></p>
|
||||
<div class="field"><label for="cid"><%= t("admin.clients.column.id") %></label><input class="input" id="cid" type="text" value="<%= c.id %>" readonly></div>
|
||||
<div class="field"><label for="csecret"><%= t("admin.clients.secret") %></label><input class="input" id="csecret" type="text" value="<%= locals.secret %>" readonly></div>
|
||||
</section>
|
||||
<% } -%>
|
||||
<section class="form-card" aria-labelledby="client-h">
|
||||
<h2 class="card-title" id="client-h"><%= c.name %></h2>
|
||||
<dl class="detail-list">
|
||||
<dt><%= t("admin.clients.column.id") %></dt><dd><%= c.id %></dd>
|
||||
<dt><%= t("admin.clients.column.type") %></dt><dd><%= c.public ? t("admin.clients.publicPkce") : t("admin.clients.confidential") %></dd>
|
||||
<dt><%= t("admin.clients.consent.label") %></dt><dd><%= c.firstParty ? t("admin.clients.consent.firstParty") : t("admin.clients.consent.screen") %></dd>
|
||||
<dt><%= t("admin.clients.field.scopes") %></dt><dd><%= c.scopes.length ? c.scopes.join(" ") : "—" %></dd>
|
||||
<dt><%= t("admin.clients.field.redirectUris") %></dt><dd><% if (c.redirectUris.length) { %><ul class="plain-list"><% c.redirectUris.forEach((u) => { %><li><%= u %></li><% }) %></ul><% } else { %>—<% } %></dd>
|
||||
</dl>
|
||||
</section>
|
||||
<% if (locals.canWrite !== false) { -%>
|
||||
<section class="form-card admin-actions" aria-label="<%= t("admin.clients.title") %>">
|
||||
<p class="field-hint"><%= t("admin.clients.rereg") %></p>
|
||||
<a class="btn btn-danger" href="<%= localeHref(del.action) %>"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-trash"/></svg><%= t("admin.clients.delete") %></a>
|
||||
</section>
|
||||
<% } -%>
|
||||
</div>
|
||||
@@ -0,0 +1,30 @@
|
||||
<%#
|
||||
Admin OAuth2 client register form body, captured into the shell content slot. Config:
|
||||
form { action, csrfToken, submitLabel, cancelHref, nameField, scopeField (field.ejs configs),
|
||||
redirectUris: string (newline-separated), public: bool, firstParty: bool }
|
||||
error? string shown when a write was rejected
|
||||
%><%
|
||||
const form = locals.form;
|
||||
-%>
|
||||
<div class="form-page">
|
||||
<% if (locals.error) { -%>
|
||||
<%- include("partials/alert", { text: locals.error, tone: "neg" }) %>
|
||||
<% } -%>
|
||||
<form class="form-card" method="post" action="<%= localeHref(form.action) %>">
|
||||
<input type="hidden" name="_csrf" value="<%= form.csrfToken %>">
|
||||
<%- include("partials/field", form.nameField) %>
|
||||
<div class="field">
|
||||
<label for="redirectUris"><%= t("admin.clients.field.redirectUris") %></label>
|
||||
<textarea class="input" id="redirectUris" name="redirectUris" rows="3" placeholder="https://app.example.com/callback"><%= form.redirectUris %></textarea>
|
||||
<span class="field-hint"><%= t("admin.clients.field.redirectUrisHint") %></span>
|
||||
</div>
|
||||
<%- include("partials/field", form.scopeField) %>
|
||||
<label class="check"><input type="checkbox" name="public"<% if (form.public) { %> checked<% } %>> Public client (SPA / native app, PKCE — no secret)</label>
|
||||
<span class="field-hint"><%= t("admin.clients.field.typeHint") %></span>
|
||||
<label class="check"><input type="checkbox" name="firstParty"<% if (form.firstParty) { %> checked<% } %>> First-party (auto-grant consent — skip the consent screen)</label>
|
||||
<div class="form-actions">
|
||||
<a class="btn" href="<%= localeHref(form.cancelHref) %>"><%= t("common.cancel") %></a>
|
||||
<button class="btn btn-primary" type="submit"><%= form.submitLabel %></button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%#
|
||||
Destructive-action confirm body, captured into the shell content slot. Zero-JS: the
|
||||
delete is a deliberate second step (a POST form), with a cancel link back. Config:
|
||||
message string
|
||||
confirm { action, label } the danger POST endpoint + button label
|
||||
cancelHref string
|
||||
csrfToken
|
||||
%>
|
||||
<div class="form-page">
|
||||
<section class="form-card admin-actions" aria-label="<%= t("admin.users.confirm") %>">
|
||||
<p><%= locals.message %></p>
|
||||
<div class="form-actions">
|
||||
<a class="btn" href="<%= localeHref(locals.cancelHref) %>"><%= t("common.cancel") %></a>
|
||||
<form method="post" action="<%= localeHref(locals.confirm.action) %>"><input type="hidden" name="_csrf" value="<%= locals.csrfToken %>"><button class="btn btn-danger" type="submit"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-trash"/></svg><%= locals.confirm.label %></button></form>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
<%#
|
||||
Admin group membership body, captured into the shell content slot. Config:
|
||||
group { name }
|
||||
members { action, rows: { kind:"group"|"identity", label, subject }[] } action = remove-member endpoint
|
||||
add { action, options: {label,value}[] } action = add-member endpoint
|
||||
del { action } delete the whole group
|
||||
csrfToken, error?
|
||||
%><%
|
||||
const group = locals.group;
|
||||
const members = locals.members;
|
||||
const add = locals.add;
|
||||
const del = locals.del;
|
||||
const csrf = locals.csrfToken;
|
||||
-%>
|
||||
<div class="form-page">
|
||||
<% if (locals.error) { -%>
|
||||
<%- include("partials/alert", { text: locals.error, tone: "neg" }) %>
|
||||
<% } -%>
|
||||
<section class="form-card" aria-labelledby="members-h">
|
||||
<h2 class="card-title" id="members-h"><%= t("admin.groups.members") %></h2>
|
||||
<% if (members.rows.length) { -%>
|
||||
<div class="table-wrap"><table class="table"><caption class="sr-only"><%= t("admin.groups.membersOf", { name: group.name }) %></caption><thead><tr><th scope="col"><%= t("admin.common.member") %></th><th scope="col"><%= t("admin.common.type") %></th><th class="col-actions" scope="col"><span class="sr-only"><%= t("table.actions") %></span></th></tr></thead><tbody>
|
||||
<% members.rows.forEach((m) => { -%>
|
||||
<tr><th scope="row"><span class="cell-strong"><%= m.label %></span></th><td><span class="badge info"><span class="dot"></span><%= m.kind === "group" ? t("admin.common.group") : t("admin.common.user") %></span></td><td class="col-actions"><% if (locals.canWrite !== false) { %><form method="post" action="<%= localeHref(members.action) %>"><input type="hidden" name="_csrf" value="<%= csrf %>"><input type="hidden" name="member" value="<%= m.subject %>"><button class="btn" type="submit"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-x"/></svg><%= t("common.remove") %></button></form><% } %></td></tr>
|
||||
<% }) -%>
|
||||
</tbody></table></div>
|
||||
<% } else { -%>
|
||||
<p class="cell-muted"><%= t("admin.groups.noMembers") %></p>
|
||||
<% } -%>
|
||||
</section>
|
||||
<% if (locals.canWrite !== false) { -%>
|
||||
<section class="form-card" aria-labelledby="add-h">
|
||||
<h2 class="card-title" id="add-h"><%= t("admin.groups.addMember") %></h2>
|
||||
<% if (add.options.length) { -%>
|
||||
<form class="inline-form" method="post" action="<%= localeHref(add.action) %>"><input type="hidden" name="_csrf" value="<%= csrf %>"><label class="sr-only" for="add-member"><%= t("admin.common.member") %></label><span class="select"><select id="add-member" name="member" required><option value="" disabled selected><%= t("admin.common.chooseMember") %></option><% add.options.forEach((o) => { %><option value="<%= o.value %>"><%= o.label %></option><% }) %></select></span><button class="btn btn-primary" type="submit"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-plus"/></svg><%= t("common.add") %></button></form>
|
||||
<% } else { -%>
|
||||
<p class="cell-muted"><%= t("admin.groups.allMembers") %></p>
|
||||
<% } -%>
|
||||
</section>
|
||||
<% } -%>
|
||||
<% if (locals.permissions) { -%>
|
||||
<%- include("partials/permission-picker", { csrfToken: csrf, permissions: locals.permissions }) %>
|
||||
<% } -%>
|
||||
<% if (locals.canWrite !== false) { -%>
|
||||
<section class="form-card admin-actions" aria-label="<%= t("admin.groups.actions") %>">
|
||||
<a class="btn btn-danger" href="<%= localeHref(del.action) %>"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-trash"/></svg><%= t("admin.groups.delete") %></a>
|
||||
</section>
|
||||
<% } -%>
|
||||
</div>
|
||||
@@ -0,0 +1,26 @@
|
||||
<%#
|
||||
Admin group create form body, captured into the shell content slot. Config:
|
||||
form { action, csrfToken, submitLabel, cancelHref, nameField: field.ejs config,
|
||||
memberOptions: {label,value}[], selectedMember }
|
||||
error? string shown when a write was rejected
|
||||
%><%
|
||||
const form = locals.form;
|
||||
-%>
|
||||
<div class="form-page">
|
||||
<% if (locals.error) { -%>
|
||||
<%- include("partials/alert", { text: locals.error, tone: "neg" }) %>
|
||||
<% } -%>
|
||||
<form class="form-card" method="post" action="<%= localeHref(form.action) %>">
|
||||
<input type="hidden" name="_csrf" value="<%= form.csrfToken %>">
|
||||
<%- include("partials/field", form.nameField) %>
|
||||
<div class="field">
|
||||
<label for="member"><%= t("admin.groups.firstMember") %></label>
|
||||
<span class="select"><select id="member" name="member" required><option value="" disabled<% if (!form.selectedMember) { %> selected<% } %>><%= t("admin.common.chooseMember") %></option><% form.memberOptions.forEach((o) => { %><option value="<%= o.value %>"<% if (form.selectedMember === o.value) { %> selected<% } %>><%= o.label %></option><% }) %></select></span>
|
||||
<span class="field-hint"><%= t("admin.groups.firstMemberHint") %></span>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<a class="btn" href="<%= localeHref(form.cancelHref) %>"><%= t("common.cancel") %></a>
|
||||
<button class="btn btn-primary" type="submit"><%= form.submitLabel %></button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,2 @@
|
||||
<%# One-line notice body (not-found / unavailable). Data: message. %>
|
||||
<section class="notice"><p><%= message %></p></section>
|
||||
@@ -0,0 +1,54 @@
|
||||
<%#
|
||||
The permission picker, shared by the user-edit and group-detail pages. A fieldset of checkboxes —
|
||||
one per permission the installed plugins declare — ticked where this user/group holds it. The whole
|
||||
set posts back, so what is submitted IS the desired set of *direct* grants (see admin-grants.ts).
|
||||
|
||||
Two rows never post, by design: an `inherited` one (the grant comes from a group, so it is changed
|
||||
there) and every row when `readOnly` (the viewer holds :read but not :write). Neither can be diffed
|
||||
into an accidental revoke, because grantDiff compares against the direct grants only.
|
||||
|
||||
Locals: csrfToken, permissions ({ action, baseline, choices, empty, error, field, hint, inheritedNote, legend, notice, pending, readOnly, submit }).
|
||||
%>
|
||||
<section class="form-card" aria-labelledby="permissions-h">
|
||||
<h2 class="card-title" id="permissions-h"><%= permissions.legend %></h2>
|
||||
<% if (permissions.error) { -%>
|
||||
<%- include("partials/alert", { text: permissions.error, tone: "neg" }) %>
|
||||
<% } -%>
|
||||
<% if (permissions.notice) { -%>
|
||||
<%- include("partials/alert", { text: permissions.notice, tone: "pos" }) %>
|
||||
<% } -%>
|
||||
<% if (permissions.empty) { -%>
|
||||
<p class="cell-muted"><%= permissions.empty %></p>
|
||||
<% } else { -%>
|
||||
<p class="cell-muted"><%= permissions.hint %></p>
|
||||
<% if (permissions.readOnly) { -%>
|
||||
<fieldset class="check-group">
|
||||
<legend class="sr-only"><%= permissions.legend %></legend>
|
||||
<% permissions.choices.forEach((c) => { -%>
|
||||
<label class="check"><input type="checkbox"<%= c.checked ? " checked" : "" %> disabled><span><%= c.description || c.name %></span><span class="cell-muted"><%= c.name %></span></label>
|
||||
<% }) -%>
|
||||
</fieldset>
|
||||
<% } else { -%>
|
||||
<%# The fragment brings the card, and the notice in it, into view on a long page. %>
|
||||
<form method="post" action="<%= localeHref(permissions.action + '#permissions-h') %>">
|
||||
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
|
||||
<input type="hidden" name="baseline" value="<%= permissions.baseline %>">
|
||||
<fieldset class="check-group">
|
||||
<legend class="sr-only"><%= permissions.legend %></legend>
|
||||
<% permissions.choices.forEach((c) => { -%>
|
||||
<label class="check"><input type="checkbox" name="<%= permissions.field %>" value="<%= c.name %>"<%= c.checked ? " checked" : "" %><%= c.inherited ? " disabled" : "" %>><span><%= c.description || c.name %></span><span class="cell-muted"><%= c.name %></span></label>
|
||||
<% }) -%>
|
||||
</fieldset>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-primary" type="submit"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-check-circle"/></svg><%= permissions.submit %></button>
|
||||
</div>
|
||||
</form>
|
||||
<% } -%>
|
||||
<% if (permissions.inheritedNote) { -%>
|
||||
<p class="cell-muted"><%= permissions.inheritedNote %></p>
|
||||
<% } -%>
|
||||
<% if (permissions.pending) { -%>
|
||||
<p class="cell-muted"><%= permissions.pending %></p>
|
||||
<% } -%>
|
||||
<% } -%>
|
||||
</section>
|
||||
@@ -0,0 +1,41 @@
|
||||
<%#
|
||||
Admin user create/edit form body, captured into the shell content slot. Config:
|
||||
form { action, csrfToken, submitLabel, cancelHref, fields: field.ejs config[] }
|
||||
edit? { nextLabel, stateAction, recoveryAction, deleteAction } (edit mode only)
|
||||
recovery? { code, link } shown after a recovery code is generated; link is the URL of the flow the code was minted on, the only flow that accepts the code
|
||||
error? string shown when a write was rejected
|
||||
%><%
|
||||
const form = locals.form;
|
||||
const edit = locals.edit;
|
||||
const recovery = locals.recovery;
|
||||
-%>
|
||||
<div class="form-page">
|
||||
<% if (locals.error) { -%>
|
||||
<%- include("partials/alert", { text: locals.error, tone: "neg" }) %>
|
||||
<% } -%>
|
||||
<% if (recovery) { -%>
|
||||
<div class="alert alert-pos" role="status"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-check-circle"/></svg><div class="alert-body"><strong><%= t("admin.users.recovery.title") %></strong><span><%= t("admin.users.recovery.body") %> <a href="<%= recovery.link %>"><%= t("admin.users.recovery.link") %></a></span><span class="recovery-code"><code><%= recovery.code %></code></span></div></div>
|
||||
<% } -%>
|
||||
<form class="form-card" method="post" action="<%= localeHref(form.action) %>">
|
||||
<input type="hidden" name="_csrf" value="<%= form.csrfToken %>">
|
||||
<% form.fields.forEach((field) => { -%>
|
||||
<%- include("partials/field", field) %>
|
||||
<% }) -%>
|
||||
<div class="form-actions">
|
||||
<a class="btn" href="<%= localeHref(form.cancelHref) %>"><%= t("common.cancel") %></a>
|
||||
<% if (locals.canWrite !== false) { -%>
|
||||
<button class="btn btn-primary" type="submit"><%= form.submitLabel %></button>
|
||||
<% } -%>
|
||||
</div>
|
||||
</form>
|
||||
<% if (edit && locals.permissions) { -%>
|
||||
<%- include("partials/permission-picker", { csrfToken: form.csrfToken, permissions: locals.permissions }) %>
|
||||
<% } -%>
|
||||
<% if (edit && locals.canWrite !== false) { -%>
|
||||
<section class="form-card admin-actions" aria-label="<%= t("admin.users.actions") %>">
|
||||
<form method="post" action="<%= localeHref(edit.recoveryAction) %>"><input type="hidden" name="_csrf" value="<%= form.csrfToken %>"><button class="btn" type="submit"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-mail"/></svg><%= t("admin.users.recovery.generate") %></button></form>
|
||||
<form method="post" action="<%= localeHref(edit.stateAction) %>"><input type="hidden" name="_csrf" value="<%= form.csrfToken %>"><button class="btn" type="submit"><%= edit.nextLabel %></button></form>
|
||||
<a class="btn btn-danger" href="<%= localeHref(edit.deleteAction) %>"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-trash"/></svg><%= t("admin.users.delete") %></a>
|
||||
</section>
|
||||
<% } -%>
|
||||
</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
<%#
|
||||
Plugin settings admin list: one section per installed plugin, each a table of what it declares
|
||||
and how each key resolved (admin-plugin-settings.ts). Read-only — no actions, no forms.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
let body = "";
|
||||
for (const group of model.groups) {
|
||||
// A plugin id is the folder name, which discovery constrains to [a-z0-9-] — no escaping needed.
|
||||
body += '<h2 class="h2">' + group.pluginId + "</h2>";
|
||||
body += group.table.rows.length === 0
|
||||
? '<p class="muted">' + group.emptyText + "</p>"
|
||||
: include("partials/data-table", group.table);
|
||||
}
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,16 @@
|
||||
<%#
|
||||
Users admin create/edit page: the user-form body captured into the app shell.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const body = include("partials/user-form-body", { canWrite: model.canWrite, edit: model.edit, error: model.error, form: model.form, permissions: model.permissions, recovery: model.recovery });
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
body,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
@@ -0,0 +1,22 @@
|
||||
<%#
|
||||
Users admin list: the same building blocks as the dashboard, around the shell, but
|
||||
backed by live Kratos identities (admin-users.ts). Filter/sort/page all round-trip the URL.
|
||||
%><%
|
||||
const nav = include("partials/nav-tree", { nodes: chrome.nav });
|
||||
const filters = include("partials/filter-bar", model.filterBar);
|
||||
const table = include("partials/data-table", model.table);
|
||||
const pager = include("partials/pagination", model.pagination);
|
||||
// Only offer "New user" to a users:write holder — a users:read one would get the 403 page.
|
||||
const actions = model.canWrite === false ? "" : '<a class="btn btn-primary" href="' + localeHref("/auth-admin/users/new") + '"><svg class="ico ico-sm" aria-hidden="true"><use href="#i-plus"/></svg>' + t("admin.users.new") + '</a>';
|
||||
-%>
|
||||
<%- include("partials/shell", {
|
||||
actions,
|
||||
body: filters + table + pager,
|
||||
brand: chrome.brand,
|
||||
breadcrumbs: model.breadcrumbs,
|
||||
csrfToken: chrome.csrfToken,
|
||||
nav,
|
||||
theme: chrome.theme,
|
||||
title: model.title,
|
||||
user: chrome.user,
|
||||
}) %>
|
||||
Reference in New Issue
Block a user