Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Add API keys for the public API

Clauded2030959fd85
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ea04e9..b29149c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,18 @@ release says when it does.
## [Unreleased]
+### API
+
+- API keys: an administrator can make keys under Settings, Organization, API
+ keys, for another app to use the SignuDoc API. A key is shown once, only
+ its hash is stored, and it acts as the administrator who made it. Keys can
+ be read-only, can expire, and stop working when revoked or when their
+ administrator stops being one. `GET /api/v1/me` checks a key works. See
+ [docs/api.md](docs/api.md).
+
+This changes the database: the new `api_keys` table is added by the
+migration that runs on deploy.
+
## [0.3.0] - 2026-11-16
Sign-in security and audit features for organizations that need them, and
diff --git a/db/migrations/20261118090000_api_keys.sql b/db/migrations/20261118090000_api_keys.sql
new file mode 100644
index 0000000..471ecd0
--- /dev/null
+++ b/db/migrations/20261118090000_api_keys.sql
@@ -0,0 +1,28 @@
+-- API keys for the public API (/api/v1).
+--
+-- An administrator creates a key in Settings and sees it once. Only a
+-- SHA-256 hash of the key is kept, the same way signing links are, so a
+-- copy of the database cannot be used to call the API. A key acts as the
+-- administrator who created it: envelopes it creates are theirs, and a
+-- key stops working when that account stops being an administrator.
+--
+-- * prefix: the start of the key, shown so people can tell keys apart.
+-- * scope: 'read' may only look; 'write' may also create, send and void.
+-- * last_used_at: written at most once a minute, in seconds.
+-- * expires_at, revoked_at: null until set. A revoked key never works again.
+
+create table if not exists public.api_keys (
+ id text primary key,
+ user_id text not null references public."user"(id) on delete cascade,
+ name text not null check (length(name) between 1 and 80),
+ prefix text not null,
+ key_hash text not null unique check (length(key_hash) = 64),
+ scope text not null check (scope in ('read', 'write')),
+ created_at bigint not null,
+ last_used_at bigint,
+ expires_at bigint,
+ revoked_at bigint
+);
+
+create index if not exists api_keys_user_id_idx
+ on public.api_keys (user_id);
diff --git a/docs/api.md b/docs/api.md
new file mode 100644
index 0000000..a993416
--- /dev/null
+++ b/docs/api.md
@@ -0,0 +1,98 @@
+# The SignuDoc API
+
+Another app can use SignuDoc through its API: check a key works now, and
+create, send and track envelopes as the next releases add those endpoints.
+Everything here runs inside your own install; nothing goes through a
+service of ours.
+
+The API is version 1 and lives under `/api/v1` on your install, for example
+`https://sign.example.com/api/v1`. Within version 1, endpoints, fields and
+error codes are only ever added, never changed or removed.
+
+## Keys
+
+An administrator makes a key under **Settings, Organization, API keys**:
+
+1. Give it a name that says which app uses it, such as "Billing app".
+2. Choose **Read and write** (create, send and void envelopes, and read
+ them) or **Read only**.
+3. Choose when it expires: in 30 days, 90 days, a year, or never.
+4. Copy the key. It starts with `sdk_` and is shown only this once; SignuDoc
+ keeps only a hash of it.
+
+Send the key in the `Authorization` header of every request:
+
+```sh
+curl https://sign.example.com/api/v1/me \
+ -H "Authorization: Bearer sdk_…"
+```
+
+```json
+{
+ "key": { "id": "…", "name": "Billing app", "scope": "write" },
+ "user": { "email": "[email protected]", "id": "…", "name": "Ops" }
+}
+```
+
+What to know about keys:
+
+- **A key acts as the administrator who made it.** Envelopes it creates are
+ theirs and show in their documents, sent in their name. An app that should
+ send in its own name gets its own administrator account (for example
+ "Billing app", with a shared mailbox) and its key from there.
+- **A key stops working** the moment it is revoked, when it expires, when
+ its administrator stops being an administrator, or when their account is
+ being closed. A key that stopped because its administrator lost the role
+ stays revoked if they get it back; make a new one.
+- **Keys skip two-step sign-in.** They are for servers, so keep them in your
+ app's secret settings (for example a Vercel environment variable), never
+ in a browser or a mobile app, and revoke a key as soon as it may have
+ leaked. The `sdk_` prefix lets secret scanners such as GitHub's spot one.
+- Each administrator can have up to 25 keys that have not been revoked or
+ expired.
+- Making and revoking keys is recorded in the site audit trail (Settings,
+ Organization, Sign-in security), and each key shows when it was last used.
+
+## Errors
+
+Every error has the same shape, and the code is meant for your program:
+
+```json
+{
+ "error": {
+ "code": "unauthorized",
+ "message": "Send a valid API key as \"Authorization: Bearer sdk_…\"."
+ }
+}
+```
+
+| Status | Code | Meaning |
+| ------ | ------------------------ | ---------------------------------------------------------------------------------------- |
+| 400 | `invalid_request` | The request is missing something or has a value that is not allowed. |
+| 401 | `unauthorized` | No key, or one that is unknown, revoked or expired. All of these look the same. |
+| 403 | `forbidden` | The key may not do this, such as a read-only key asked to send. |
+| 404 | `not_found` | There is no such thing, or the key's administrator cannot see it. |
+| 409 | `wrong_state` | Not possible in the envelope's current state, such as sending one that was sent already. |
+| 413 | `payload_too_large` | The file is too big. |
+| 422 | `idempotency_key_reused` | An `Idempotency-Key` was used before with a different request. |
+| 429 | `rate_limited` | Too many requests. Wait the number of seconds in `Retry-After`. |
+| 500 | `internal_error` | Something went wrong on the install. Try again later. |
+
+## Rate limits
+
+Each key may make 600 requests in 10 minutes. Every response says where it
+stands:
+
+- `RateLimit-Limit`: requests allowed in the window.
+- `RateLimit-Remaining`: requests left in it.
+- `RateLimit-Reset`: seconds until the window starts again.
+
+The limits the web app has on creating and sending envelopes apply to keys
+too. An address that sends 30 bad keys in 10 minutes is turned away until
+the 10 minutes are up.
+
+## Endpoints
+
+| Method and path | Access | What it does |
+| ---------------- | ------ | -------------------------------------- |
+| `GET /api/v1/me` | read | Which key this is and whom it acts as. |
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 1aef0cf..b37b1da 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -176,6 +176,10 @@ These cover the people with an account (senders and administrators). Signers who
- **Wrong passwords.** Ten wrong passwords for one email address within 15 minutes stop sign-in for that address until the 15 minutes are up. This happens whether or not the address has an account, so it says nothing about which ones do. Ten wrong codes at the second step lock that step for 15 minutes in the same way.
- **The site audit trail** (Settings, Organization, Sign-in security) records each sign-in and failed sign-in with the address it came from, lockouts, sign-outs, password changes and resets, two-step sign-in being turned on, off or reset, new backup codes, and changes to settings, roles, the logo, the email domain, identity confirmations and signing locks. The rows form one hash chain, so a changed or removed row shows, and the trail downloads as CSV.
+### API keys
+
+Another app can create and send envelopes through the [SignuDoc API](api.md). An administrator makes a key for it under Settings, Organization, API keys. The key is shown once and only its hash is stored. It acts as the administrator who made it, skips two-step sign-in (it is for servers, not people), and stops working when it is revoked, expires, or its administrator stops being one. Making and revoking keys is in the site audit trail.
+
### Send the audit trail to your SIEM
Every row added to the site audit trail or to a document's audit trail is also written to the function logs, once it is saved, as one line of JSON. So are refused requests and failures worth a look. A Vercel log drain (team Settings, Drains, or an observability integration from the Vercel Marketplace such as Datadog, Axiom or Better Stack) then delivers them to your SIEM as fields it can search and alert on. Log drains are a paid Vercel feature; see Vercel's pricing page for which plans have them.
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index cb2b550..885fbea 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -1216,6 +1216,91 @@ test("a signer signs with a qualified signature in their own name, through the s
});
});
+test("an administrator makes an API key, the API accepts it, and revoking it stops it", async ({
+ baseURL,
+ page,
+ playwright,
+}) => {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ adminEmail =
+ (
+ await database.query<{ email: string }>(
+ `select email from public."user" where role = 'admin' order by "createdAt" limit 1`,
+ )
+ ).rows[0]?.email ?? "";
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ // A separate client, with no session cookie: only the key gets it in.
+ const api = await playwright.request.newContext({ baseURL });
+ let key = "";
+
+ await test.step("the key is made in Settings and shown once", async () => {
+ await page.goto("/login");
+ await page.getByLabel("Email").fill(adminEmail);
+ await page.getByLabel("Password").fill(PASSWORD);
+ await page.getByRole("button", { name: "Log in" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+ await page.goto("/settings");
+ await page.getByPlaceholder("For example: Billing app").fill("Billing app");
+ await page.getByRole("button", { name: "Create key" }).click();
+
+ key =
+ (await page.getByTestId("new-api-key").locator("code").textContent()) ??
+ "";
+ expect(key).toMatch(/^sdk_[A-Za-z0-9_-]{43}$/);
+ await page.getByRole("button", { name: "Done" }).click();
+ await expect(page.getByTestId("new-api-key")).toHaveCount(0);
+ await expect(
+ page.getByRole("list", { name: "API keys" }).getByText(key.slice(0, 12)),
+ ).toBeVisible();
+ });
+
+ await test.step("the API answers to the key and to nothing else", async () => {
+ const me = await api.get("/api/v1/me", {
+ headers: { authorization: `Bearer ${key}` },
+ });
+
+ expect(me.status()).toBe(200);
+ expect(me.headers()["ratelimit-limit"]).toBe("600");
+ expect(await me.json()).toMatchObject({
+ key: { name: "Billing app", scope: "write" },
+ user: { email: adminEmail },
+ });
+
+ const anonymous = await api.get("/api/v1/me");
+
+ expect(anonymous.status()).toBe(401);
+ expect(await anonymous.json()).toMatchObject({
+ error: { code: "unauthorized" },
+ });
+ });
+
+ await test.step("a revoked key is refused at once", async () => {
+ await page.getByRole("button", { name: "Revoke Billing app" }).click();
+ await page.getByRole("button", { name: "Revoke", exact: true }).click();
+ await expect(
+ page.getByRole("list", { name: "API keys" }).getByText("Revoked"),
+ ).toBeVisible();
+
+ const refused = await api.get("/api/v1/me", {
+ headers: { authorization: `Bearer ${key}` },
+ });
+
+ expect(refused.status()).toBe(401);
+ });
+
+ await api.dispose();
+});
+
test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({
browser,
page,
diff --git a/src/app/api/admin/api-keys/[id]/route.ts b/src/app/api/admin/api-keys/[id]/route.ts
new file mode 100644
index 0000000..2d41fa0
--- /dev/null
+++ b/src/app/api/admin/api-keys/[id]/route.ts
@@ -0,0 +1,63 @@
+import { NextResponse } from "next/server";
+
+import { ApiKeyError, revokeApiKey } from "@/lib/api-keys";
+import { requireAdminSession } from "@/lib/auth/admin";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+
+const noStore = { "cache-control": "private, no-store" };
+
+type ApiKeyRouteContext = {
+ params: Promise<{ id: string }>;
+};
+
+// Revokes an API key. It stops working at once and cannot be turned back
+// on. Administrators only.
+export async function DELETE(request: Request, context: ApiKeyRouteContext) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const { id } = await context.params;
+
+ try {
+ const key = await revokeApiKey(
+ {
+ email: session.user.email,
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ userId: session.user.id,
+ },
+ id,
+ );
+
+ return NextResponse.json({ key }, { headers: noStore });
+ } catch (error) {
+ if (error instanceof ApiKeyError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "api_key_revoke_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while revoking an API key.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The key could not be revoked." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/admin/api-keys/route.ts b/src/app/api/admin/api-keys/route.ts
new file mode 100644
index 0000000..6e2d584
--- /dev/null
+++ b/src/app/api/admin/api-keys/route.ts
@@ -0,0 +1,119 @@
+import { NextResponse } from "next/server";
+
+import {
+ ApiKeyError,
+ createApiKey,
+ listApiKeys,
+ parseApiKeyExpiry,
+ parseApiKeyName,
+ parseApiKeyScope,
+} from "@/lib/api-keys";
+import { requireAdminSession } from "@/lib/auth/admin";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import { getSettings } from "@/lib/settings";
+
+const noStore = { "cache-control": "private, no-store" };
+
+// API keys for the public API. Administrators only. The key itself is in
+// the response to the request that creates it, and nowhere else, ever.
+
+export async function GET(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ return NextResponse.json({ keys: await listApiKeys() }, { headers: noStore });
+}
+
+export async function POST(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const rateLimitResponse = await applyRateLimit({
+ category: "api_key_create",
+ key: buildRateLimitKey(["api-key-create", session.user.id]),
+ limit: 10,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ if ((await getSettings()).hosted) {
+ return NextResponse.json(
+ { error: "API keys are for self-hosted installs." },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ const parsed: unknown = await request.json().catch(() => null);
+ const body =
+ typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as { expiresInDays?: unknown; name?: unknown; scope?: unknown })
+ : {};
+ const name = parseApiKeyName(body.name);
+ const scope = parseApiKeyScope(body.scope);
+ const expiresInDays = parseApiKeyExpiry(body.expiresInDays);
+
+ if (!name || !scope || expiresInDays === undefined) {
+ return NextResponse.json(
+ {
+ error:
+ "Give the key a name of up to 80 characters, read or write access, and an expiry of 30, 90 or 365 days or none.",
+ },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ try {
+ const created = await createApiKey(
+ {
+ email: session.user.email,
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ userId: session.user.id,
+ },
+ { expiresInDays, name, scope },
+ );
+
+ return NextResponse.json(created, { headers: noStore, status: 201 });
+ } catch (error) {
+ if (error instanceof ApiKeyError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "api_key_create_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while creating an API key.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The key could not be created." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/v1/me/route.ts b/src/app/api/v1/me/route.ts
new file mode 100644
index 0000000..887973a
--- /dev/null
+++ b/src/app/api/v1/me/route.ts
@@ -0,0 +1,28 @@
+import { apiJson } from "@/lib/api/http";
+import { requireApiKey, withRateLimitHeaders } from "@/lib/auth/api-key";
+
+// Which key this is and whom it acts as. The simplest way to check that a
+// key works.
+export async function GET(request: Request) {
+ const principal = await requireApiKey(request, "read");
+
+ if (principal instanceof Response) {
+ return principal;
+ }
+
+ return withRateLimitHeaders(
+ apiJson({
+ key: {
+ id: principal.apiKey.id,
+ name: principal.apiKey.name,
+ scope: principal.apiKey.scope,
+ },
+ user: {
+ email: principal.user.email,
+ id: principal.user.id,
+ name: principal.user.name,
+ },
+ }),
+ principal.rateLimit,
+ );
+}
diff --git a/src/components/settings/api-keys-panel.tsx b/src/components/settings/api-keys-panel.tsx
new file mode 100644
index 0000000..07fedf7
--- /dev/null
+++ b/src/components/settings/api-keys-panel.tsx
@@ -0,0 +1,366 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import type { ApiKeySummary } from "@/lib/api-keys";
+
+// API keys for the public API (/api/v1). Administrators only. A new key is
+// shown once, right after it is made, and never again.
+
+const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";
+const API_DOCS_URL =
+ "https://github.com/NYLLON-SOFTWARE/SignuDoc/blob/main/docs/api.md";
+
+const dateFormatter = new Intl.DateTimeFormat("en-US", {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+});
+
+function formatDate(seconds: number | null) {
+ return seconds === null
+ ? null
+ : dateFormatter.format(new Date(seconds * 1000));
+}
+
+function keyState(key: ApiKeySummary, now: number) {
+ if (key.revokedAt !== null) {
+ return { label: "Revoked", tone: "pill-neutral" };
+ }
+
+ if (key.expiresAt !== null && key.expiresAt <= now) {
+ return { label: "Expired", tone: "pill-warning" };
+ }
+
+ return { label: "Active", tone: "pill-success" };
+}
+
+export function ApiKeysPanel() {
+ const [keys, setKeys] = useState<ApiKeySummary[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [name, setName] = useState("");
+ const [scope, setScope] = useState<"read" | "write">("write");
+ const [expiry, setExpiry] = useState("365");
+ const [isCreating, setIsCreating] = useState(false);
+ const [newKey, setNewKey] = useState<{ key: string; name: string } | null>(
+ null,
+ );
+ const [copied, setCopied] = useState(false);
+ const [revokingId, setRevokingId] = useState<string | null>(null);
+ const [pendingId, setPendingId] = useState<string | null>(null);
+ const [revision, setRevision] = useState(0);
+ // When the list was last read, for telling which keys have expired.
+ const [now, setNow] = useState(0);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ void (async () => {
+ try {
+ const response = await fetch("/api/admin/api-keys", {
+ cache: "no-store",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ keys?: ApiKeySummary[];
+ } | null;
+
+ if (cancelled) {
+ return;
+ }
+
+ if (!response.ok || !payload?.keys) {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ setNow(Math.floor(Date.now() / 1000));
+ setKeys(payload.keys);
+ } catch {
+ if (!cancelled) {
+ setError(GENERIC_ERROR_MESSAGE);
+ }
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [revision]);
+
+ async function createKey() {
+ setIsCreating(true);
+ setError(null);
+ setNewKey(null);
+ setCopied(false);
+
+ try {
+ const response = await fetch("/api/admin/api-keys", {
+ body: JSON.stringify({
+ expiresInDays: expiry === "never" ? null : Number(expiry),
+ name,
+ scope,
+ }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ key?: string;
+ summary?: ApiKeySummary;
+ } | null;
+
+ if (!response.ok || !payload?.key || !payload.summary) {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ setNewKey({ key: payload.key, name: payload.summary.name });
+ setName("");
+ setRevision((value) => value + 1);
+ } catch {
+ setError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setIsCreating(false);
+ }
+ }
+
+ async function revokeKey(key: ApiKeySummary) {
+ setPendingId(key.id);
+ setError(null);
+
+ try {
+ const response = await fetch(
+ `/api/admin/api-keys/${encodeURIComponent(key.id)}`,
+ { method: "DELETE" },
+ );
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+
+ if (!response.ok) {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ setRevokingId(null);
+ setRevision((value) => value + 1);
+ } catch {
+ setError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setPendingId(null);
+ }
+ }
+
+ async function copyKey() {
+ if (!newKey) {
+ return;
+ }
+
+ try {
+ await navigator.clipboard.writeText(newKey.key);
+ setCopied(true);
+ } catch {
+ setCopied(false);
+ }
+ }
+
+ const trimmedName = name.trim();
+
+ return (
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
+ API keys
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ Let another app create and send envelopes through the{" "}
+ <a
+ className="font-semibold text-(--accent) underline-offset-4 hover:underline"
+ href={API_DOCS_URL}
+ rel="noreferrer"
+ target="_blank"
+ >
+ SignuDoc API
+ </a>
+ . A key acts as the administrator who made it: what it sends shows in
+ their documents. Keys skip two-step sign-in, so keep them in the
+ app&apos;s secret settings, never in a browser, and revoke one as soon
+ as it may have leaked.
+ </p>
+ </div>
+
+ <div className="grid max-w-xl gap-4 sm:grid-cols-3">
+ <label className="grid gap-1.5 sm:col-span-3">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Name
+ </span>
+ <input
+ autoComplete="off"
+ className="field-input"
+ disabled={isCreating}
+ maxLength={80}
+ name="api-key-name"
+ onChange={(event) => setName(event.target.value)}
+ placeholder="For example: Billing app"
+ value={name}
+ />
+ </label>
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Access
+ </span>
+ <select
+ className="field-input"
+ disabled={isCreating}
+ name="api-key-scope"
+ onChange={(event) =>
+ setScope(event.target.value === "read" ? "read" : "write")
+ }
+ value={scope}
+ >
+ <option value="write">Read and write</option>
+ <option value="read">Read only</option>
+ </select>
+ </label>
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Expires
+ </span>
+ <select
+ className="field-input"
+ disabled={isCreating}
+ name="api-key-expiry"
+ onChange={(event) => setExpiry(event.target.value)}
+ value={expiry}
+ >
+ <option value="30">In 30 days</option>
+ <option value="90">In 90 days</option>
+ <option value="365">In a year</option>
+ <option value="never">Never</option>
+ </select>
+ </label>
+ <div className="flex items-end">
+ <button
+ className="btn-quiet min-h-12 w-full px-5 text-sm"
+ disabled={isCreating || trimmedName.length === 0}
+ onClick={() => void createKey()}
+ type="button"
+ >
+ {isCreating ? "Creating..." : "Create key"}
+ </button>
+ </div>
+ </div>
+
+ {newKey ? (
+ <div
+ className="well grid max-w-2xl gap-3 p-4"
+ data-testid="new-api-key"
+ role="status"
+ >
+ <p className="text-sm font-semibold text-(--fg)">
+ Copy the key for {newKey.name} now. It is not shown again.
+ </p>
+ <code className="block overflow-x-auto rounded-lg border border-(--border) bg-(--paper) px-3 py-2 font-mono text-sm break-all text-(--fg)">
+ {newKey.key}
+ </code>
+ <div className="flex flex-wrap gap-2">
+ <button
+ className="btn-quiet"
+ onClick={() => void copyKey()}
+ type="button"
+ >
+ {copied ? "Copied" : "Copy"}
+ </button>
+ <button
+ className="btn-quiet"
+ onClick={() => setNewKey(null)}
+ type="button"
+ >
+ Done
+ </button>
+ </div>
+ </div>
+ ) : null}
+
+ {error ? (
+ <p className="notice notice-danger max-w-2xl" role="alert">
+ {error}
+ </p>
+ ) : null}
+
+ {keys === null ? null : keys.length === 0 ? (
+ <p className="text-sm text-(--secondary)">No keys yet.</p>
+ ) : (
+ <ul aria-label="API keys" className="grid max-w-2xl gap-3">
+ {keys.map((key) => {
+ const state = keyState(key, now);
+ const lastUsed = formatDate(key.lastUsedAt);
+ const expires = formatDate(key.expiresAt);
+
+ return (
+ <li className="well grid gap-2 p-4" key={key.id}>
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="text-[0.9375rem] font-bold text-(--fg)">
+ {key.name}
+ </p>
+ <span className={`pill ${state.tone}`}>{state.label}</span>
+ <span className="pill pill-neutral">
+ {key.scope === "write" ? "Read and write" : "Read only"}
+ </span>
+ </div>
+ <p className="font-mono text-sm text-(--secondary)">
+ {key.prefix}…
+ </p>
+ <p className="text-sm text-(--secondary)">
+ Made by {key.ownerName} on {formatDate(key.createdAt)}.{" "}
+ {lastUsed ? `Last used ${lastUsed}.` : "Not used yet."}
+ {key.revokedAt === null && expires
+ ? ` Expires ${expires}.`
+ : ""}
+ </p>
+ {state.label === "Active" ? (
+ <div className="flex flex-wrap items-center gap-2">
+ {revokingId === key.id ? (
+ <>
+ <span className="text-sm text-(--secondary)">
+ Revoke this key? Apps using it stop working at once.
+ </span>
+ <button
+ className="btn-quiet btn-quiet-danger"
+ disabled={pendingId !== null}
+ onClick={() => void revokeKey(key)}
+ type="button"
+ >
+ {pendingId === key.id ? "Revoking..." : "Revoke"}
+ </button>
+ <button
+ className="btn-quiet"
+ disabled={pendingId !== null}
+ onClick={() => setRevokingId(null)}
+ type="button"
+ >
+ Cancel
+ </button>
+ </>
+ ) : (
+ <button
+ aria-label={`Revoke ${key.name}`}
+ className="btn-quiet btn-quiet-danger"
+ disabled={pendingId !== null}
+ onClick={() => setRevokingId(key.id)}
+ type="button"
+ >
+ Revoke
+ </button>
+ )}
+ </div>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index 61f3fcd..63f61d2 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+import { ApiKeysPanel } from "@/components/settings/api-keys-panel";
import { BrandingPanel } from "@/components/settings/branding-panel";
import { Part11Panel } from "@/components/settings/part11-panel";
import { PeoplePanel } from "@/components/settings/people-panel";
@@ -413,6 +414,8 @@ export function OrganizationSettings({
<Part11Panel initialEnabled={values.part11Mode} />
) : null}
+ {!values.hosted ? <ApiKeysPanel /> : null}
+
<SignerDataPanel />
</div>
</section>
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index eee9784..3e73080 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -23,6 +23,8 @@ type AuditResponse = {
const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
account_closure_requested: "Account closure requested",
account_deleted: "Account deleted",
+ api_key_created: "API key created",
+ api_key_revoked: "API key revoked",
email_domain_changed: "Email domain changed",
identity_verification_revoked: "Identity confirmation taken back",
identity_verified: "Identity confirmed",
@@ -94,6 +96,17 @@ function describeEvent(event: SystemAuditEvent): string {
return metadata.action === "removed" ? "Removed" : "Replaced";
case "email_domain_changed":
return typeof metadata.domain === "string" ? metadata.domain : "";
+ case "api_key_created":
+ case "api_key_revoked":
+ return [
+ typeof metadata.name === "string" ? metadata.name : null,
+ typeof metadata.prefix === "string" ? `${metadata.prefix}…` : null,
+ metadata.reason === "role_removed"
+ ? "owner is no longer an administrator"
+ : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
default:
return target ?? "";
}
diff --git a/src/lib/api-keys.dbtest.ts b/src/lib/api-keys.dbtest.ts
new file mode 100644
index 0000000..3cc841b
--- /dev/null
+++ b/src/lib/api-keys.dbtest.ts
@@ -0,0 +1,217 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import {
+ ApiKeyError,
+ authenticateApiKey,
+ createApiKey,
+ listApiKeys,
+ MAX_API_KEYS_PER_USER,
+ revokeApiKey,
+} from "./api-keys.ts";
+import { openTestDatabase } from "./db/test-database.ts";
+import { setPersonRole } from "./people.ts";
+
+// API keys against a real Postgres. Run with `npm run test:db`.
+
+let database: pg.Pool;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+});
+
+async function createUser(role: "admin" | "user" = "admin") {
+ const id = randomUUID();
+
+ createdUsers.push(id);
+ await database.query(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ values ($1, $2, $3, $4, true)
+ `,
+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`, role],
+ );
+
+ return { email: `${id}@example.test`, userId: id };
+}
+
+async function systemEventsFor(apiKeyId: string) {
+ const result = await database.query<{ event: string; reason: string | null }>(
+ `
+ select event, metadata->>'reason' as reason
+ from system_audit_events
+ where metadata->>'apiKeyId' = $1
+ order by sequence
+ `,
+ [apiKeyId],
+ );
+
+ return result.rows;
+}
+
+test("a new key works, acts as its creator, and only its hash is kept", async () => {
+ const admin = await createUser();
+ const { key, summary } = await createApiKey(
+ admin,
+ { expiresInDays: null, name: "Billing app", scope: "write" },
+ database,
+ );
+
+ const principal = await authenticateApiKey(key, database);
+
+ assert.equal(principal?.user.id, admin.userId);
+ assert.equal(principal?.apiKey.scope, "write");
+ assert.equal(summary.prefix, key.slice(0, 12));
+
+ const stored = await database.query(`select * from api_keys where id = $1`, [
+ summary.id,
+ ]);
+
+ assert.ok(!JSON.stringify(stored.rows[0]).includes(key));
+ assert.deepEqual(
+ (await systemEventsFor(summary.id)).map((row) => row.event),
+ ["api_key_created"],
+ );
+ assert.ok((await listApiKeys(database)).some((row) => row.id === summary.id));
+});
+
+test("an unknown key and a key of the wrong shape are both refused", async () => {
+ assert.equal(
+ await authenticateApiKey(`sdk_${"A".repeat(43)}`, database),
+ null,
+ );
+ assert.equal(await authenticateApiKey("not-a-key", database), null);
+});
+
+test("a revoked key stops working at once and stays revoked", async () => {
+ const admin = await createUser();
+ const { key, summary } = await createApiKey(
+ admin,
+ { expiresInDays: 30, name: "Old app", scope: "read" },
+ database,
+ );
+
+ await revokeApiKey(admin, summary.id, database);
+ // A second revoke changes nothing and records nothing.
+ await revokeApiKey(admin, summary.id, database);
+
+ assert.equal(await authenticateApiKey(key, database), null);
+ assert.deepEqual(
+ (await systemEventsFor(summary.id)).map((row) => row.event),
+ ["api_key_created", "api_key_revoked"],
+ );
+});
+
+test("an expired key is refused", async () => {
+ const admin = await createUser();
+ const { key } = await createApiKey(
+ admin,
+ { expiresInDays: 30, name: "Short-lived", scope: "write" },
+ database,
+ );
+ const later = Math.floor(Date.now() / 1000) + 31 * 24 * 60 * 60;
+
+ assert.ok(await authenticateApiKey(key, database));
+ assert.equal(await authenticateApiKey(key, database, later), null);
+});
+
+test("an administrator who loses the role loses their keys for good", async () => {
+ const stays = await createUser();
+ const leaves = await createUser();
+ const { key, summary } = await createApiKey(
+ leaves,
+ { expiresInDays: null, name: "Leaver's app", scope: "write" },
+ database,
+ );
+
+ await setPersonRole(stays.userId, leaves.userId, "user", database);
+
+ assert.equal(await authenticateApiKey(key, database), null);
+
+ await setPersonRole(stays.userId, leaves.userId, "admin", database);
+
+ assert.equal(await authenticateApiKey(key, database), null);
+ assert.deepEqual(await systemEventsFor(summary.id), [
+ { event: "api_key_created", reason: null },
+ { event: "api_key_revoked", reason: "role_removed" },
+ ]);
+});
+
+test("a key stops working while its owner's account is being closed", async () => {
+ const admin = await createUser();
+ const { key } = await createApiKey(
+ admin,
+ { expiresInDays: null, name: "Closing", scope: "write" },
+ database,
+ );
+ const now = Math.floor(Date.now() / 1000);
+
+ await database.query(
+ `
+ insert into account_closure_requests (
+ user_id, requested_at, export_expires_at, purge_after_at, updated_at
+ ) values ($1, $2, $2, $2, $2)
+ `,
+ [admin.userId, now],
+ );
+
+ assert.equal(await authenticateApiKey(key, database), null);
+});
+
+test("only an administrator can create or revoke keys", async () => {
+ const member = await createUser("user");
+ const admin = await createUser();
+ const { summary } = await createApiKey(
+ admin,
+ { expiresInDays: null, name: "Theirs", scope: "write" },
+ database,
+ );
+
+ await assert.rejects(
+ createApiKey(
+ member,
+ { expiresInDays: null, name: "Mine", scope: "write" },
+ database,
+ ),
+ (error: unknown) =>
+ error instanceof ApiKeyError && error.statusCode === 403,
+ );
+ await assert.rejects(
+ revokeApiKey(member, summary.id, database),
+ (error: unknown) =>
+ error instanceof ApiKeyError && error.statusCode === 403,
+ );
+});
+
+test("an administrator can have only so many keys at once", async () => {
+ const admin = await createUser();
+
+ for (let index = 0; index < MAX_API_KEYS_PER_USER; index += 1) {
+ await createApiKey(
+ admin,
+ { expiresInDays: null, name: `Key ${String(index)}`, scope: "read" },
+ database,
+ );
+ }
+
+ await assert.rejects(
+ createApiKey(
+ admin,
+ { expiresInDays: null, name: "One too many", scope: "read" },
+ database,
+ ),
+ (error: unknown) =>
+ error instanceof ApiKeyError && error.statusCode === 409,
+ );
+});
diff --git a/src/lib/api-keys.test.ts b/src/lib/api-keys.test.ts
new file mode 100644
index 0000000..21a7c2d
--- /dev/null
+++ b/src/lib/api-keys.test.ts
@@ -0,0 +1,72 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ generateApiKey,
+ hashApiKey,
+ looksLikeApiKey,
+ parseApiKeyExpiry,
+ parseApiKeyName,
+ parseApiKeyScope,
+ readBearerToken,
+ scopeAllows,
+} from "./api-keys.ts";
+
+test("a new key has the fixed prefix and 256 bits of randomness", () => {
+ const key = generateApiKey();
+
+ assert.match(key, /^sdk_[A-Za-z0-9_-]{43}$/);
+ assert.ok(looksLikeApiKey(key));
+ assert.notEqual(generateApiKey(), key);
+});
+
+test("only the shape of our keys is looked up", () => {
+ assert.equal(looksLikeApiKey("sdk_short"), false);
+ assert.equal(looksLikeApiKey(`sk_${"a".repeat(43)}`), false);
+ assert.equal(looksLikeApiKey(`sdk_${"a".repeat(43)}!`), false);
+});
+
+test("the hash is SHA-256 in hex", () => {
+ assert.equal(
+ hashApiKey("abc"),
+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
+ );
+});
+
+test("the bearer token is read whatever the scheme's case", () => {
+ const key = generateApiKey();
+
+ assert.equal(
+ readBearerToken(new Headers({ authorization: `Bearer ${key}` })),
+ key,
+ );
+ assert.equal(
+ readBearerToken(new Headers({ authorization: `bearer ${key} ` })),
+ key,
+ );
+ assert.equal(
+ readBearerToken(new Headers({ authorization: `Basic ${key}` })),
+ null,
+ );
+ assert.equal(readBearerToken(new Headers()), null);
+});
+
+test("write access includes read, read does not include write", () => {
+ assert.equal(scopeAllows("write", "read"), true);
+ assert.equal(scopeAllows("write", "write"), true);
+ assert.equal(scopeAllows("read", "read"), true);
+ assert.equal(scopeAllows("read", "write"), false);
+});
+
+test("names, scopes and expiries are checked", () => {
+ assert.equal(parseApiKeyName(" Billing app "), "Billing app");
+ assert.equal(parseApiKeyName(""), null);
+ assert.equal(parseApiKeyName("x".repeat(81)), null);
+ assert.equal(parseApiKeyScope("read"), "read");
+ assert.equal(parseApiKeyScope("admin"), null);
+ assert.equal(parseApiKeyExpiry(90), 90);
+ assert.equal(parseApiKeyExpiry("365"), 365);
+ assert.equal(parseApiKeyExpiry(null), null);
+ assert.equal(parseApiKeyExpiry("never"), null);
+ assert.equal(parseApiKeyExpiry(7), undefined);
+});
diff --git a/src/lib/api-keys.ts b/src/lib/api-keys.ts
new file mode 100644
index 0000000..c3f67d8
--- /dev/null
+++ b/src/lib/api-keys.ts
@@ -0,0 +1,501 @@
+import {
+ createHash,
+ randomBytes,
+ randomUUID,
+ timingSafeEqual,
+} from "node:crypto";
+
+import {
+ getDb,
+ queryMany,
+ queryOne,
+ withTransaction,
+ type DbExecutor,
+ type DbPool,
+} from "./db/connection.ts";
+import { recordSystemAuditEvent } from "./services/system-audit.ts";
+
+// API keys for the public API. An administrator creates one in Settings,
+// sees it once, and from then on it acts as that administrator. Only a
+// hash of the key is stored. See db/migrations/20261118090000_api_keys.sql.
+
+export const API_KEY_PREFIX = "sdk_";
+export const MAX_API_KEYS_PER_USER = 25;
+export const API_KEY_SCOPES = ["read", "write"] as const;
+export const API_KEY_EXPIRY_DAYS = [30, 90, 365] as const;
+
+/** How much of a key is kept in the clear to tell keys apart. */
+const DISPLAY_PREFIX_LENGTH = 12;
+/** last_used_at is written at most this often. */
+const LAST_USED_WRITE_INTERVAL_SECONDS = 60;
+const DAY_IN_SECONDS = 24 * 60 * 60;
+
+export type ApiKeyScope = (typeof API_KEY_SCOPES)[number];
+
+export class ApiKeyError extends Error {
+ readonly statusCode: number;
+
+ constructor(message: string, statusCode: number) {
+ super(message);
+ this.name = "ApiKeyError";
+ this.statusCode = statusCode;
+ }
+}
+
+export type ApiKeySummary = {
+ createdAt: number;
+ expiresAt: number | null;
+ id: string;
+ lastUsedAt: number | null;
+ name: string;
+ ownerEmail: string;
+ ownerName: string;
+ prefix: string;
+ revokedAt: number | null;
+ scope: ApiKeyScope;
+ userId: string;
+};
+
+export type ApiKeyPrincipal = {
+ apiKey: {
+ id: string;
+ name: string;
+ scope: ApiKeyScope;
+ };
+ user: {
+ email: string;
+ id: string;
+ name: string;
+ };
+};
+
+type Actor = {
+ email: string;
+ ipAddress?: string | null;
+ userAgent?: string | null;
+ userId: string;
+};
+
+const SUMMARY_COLUMNS = `
+ k.id,
+ k.user_id AS "userId",
+ k.name,
+ k.prefix,
+ k.scope,
+ k.created_at AS "createdAt",
+ k.last_used_at AS "lastUsedAt",
+ k.expires_at AS "expiresAt",
+ k.revoked_at AS "revokedAt",
+ u.email AS "ownerEmail",
+ u.name AS "ownerName"
+`;
+
+function nowInSeconds() {
+ return Math.floor(Date.now() / 1000);
+}
+
+export function hashApiKey(key: string): string {
+ return createHash("sha256").update(key).digest("hex");
+}
+
+/** A new key: the fixed prefix, then 32 random bytes. */
+export function generateApiKey(): string {
+ return `${API_KEY_PREFIX}${randomBytes(32).toString("base64url")}`;
+}
+
+/**
+ * Whether a string has the shape of one of our keys. Checked before the
+ * database is asked, so stray headers cost nothing.
+ */
+export function looksLikeApiKey(value: string): boolean {
+ return /^sdk_[A-Za-z0-9_-]{43}$/.test(value);
+}
+
+/**
+ * The key from an `Authorization: Bearer …` header, or null. The scheme is
+ * matched without regard to case, as HTTP asks.
+ */
+export function readBearerToken(headers: Headers): string | null {
+ const header = headers.get("authorization");
+
+ if (!header) {
+ return null;
+ }
+
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(header);
+
+ return match?.[1] ?? null;
+}
+
+export function parseApiKeyScope(value: unknown): ApiKeyScope | null {
+ return value === "read" || value === "write" ? value : null;
+}
+
+export function scopeAllows(granted: ApiKeyScope, needed: ApiKeyScope) {
+ return granted === "write" || needed === "read";
+}
+
+export function parseApiKeyName(value: unknown): string | null {
+ if (typeof value !== "string") {
+ return null;
+ }
+
+ const name = value.trim().replace(/\s+/g, " ");
+
+ return name.length >= 1 && name.length <= 80 ? name : null;
+}
+
+/** 30, 90 or 365 days, or null for a key that does not expire. */
+export function parseApiKeyExpiry(value: unknown): number | null | undefined {
+ if (value === null || value === undefined || value === "never") {
+ return null;
+ }
+
+ const days = typeof value === "string" ? Number(value) : value;
+
+ return (API_KEY_EXPIRY_DAYS as readonly unknown[]).includes(days)
+ ? (days as number)
+ : undefined;
+}
+
+function isAdminRow(row: { role: string } | null): boolean {
+ return row?.role === "admin";
+}
+
+/**
+ * Creates a key for the administrator `actor`. Returns the key itself, which
+ * is never stored and cannot be shown again, and its summary.
+ */
+export async function createApiKey(
+ actor: Actor,
+ input: { expiresInDays: number | null; name: string; scope: ApiKeyScope },
+ database: DbPool = getDb(),
+): Promise<{ key: string; summary: ApiKeySummary }> {
+ const key = generateApiKey();
+ const createdAt = nowInSeconds();
+ const id = randomUUID();
+ const expiresAt =
+ input.expiresInDays === null
+ ? null
+ : createdAt + input.expiresInDays * DAY_IN_SECONDS;
+
+ await withTransaction(async (tx) => {
+ // Held while counting, so two requests at once cannot both slip under
+ // the limit, and while the role is checked, so a removal that lands at
+ // the same moment is seen.
+ const owner = await queryOne<{ role: string }>(
+ tx,
+ `SELECT role FROM "user" WHERE id = $1 FOR UPDATE`,
+ [actor.userId],
+ );
+
+ if (!isAdminRow(owner)) {
+ throw new ApiKeyError("Only an administrator can do this.", 403);
+ }
+
+ const active = await queryOne<{ count: number }>(
+ tx,
+ `
+ SELECT count(*)::int AS count
+ FROM api_keys
+ WHERE user_id = $1
+ AND revoked_at IS NULL
+ AND (expires_at IS NULL OR expires_at > $2)
+ `,
+ [actor.userId, createdAt],
+ );
+
+ if ((active?.count ?? 0) >= MAX_API_KEYS_PER_USER) {
+ throw new ApiKeyError(
+ `You can have up to ${String(MAX_API_KEYS_PER_USER)} keys. Revoke one you no longer use first.`,
+ 409,
+ );
+ }
+
+ await tx.query(
+ `
+ INSERT INTO api_keys (
+ id, user_id, name, prefix, key_hash, scope, created_at, expires_at
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `,
+ [
+ id,
+ actor.userId,
+ input.name,
+ key.slice(0, DISPLAY_PREFIX_LENGTH),
+ hashApiKey(key),
+ input.scope,
+ createdAt,
+ expiresAt,
+ ],
+ );
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ createdAt,
+ event: "api_key_created",
+ ipAddress: actor.ipAddress ?? null,
+ metadata: {
+ apiKeyId: id,
+ expiresAt,
+ name: input.name,
+ prefix: key.slice(0, DISPLAY_PREFIX_LENGTH),
+ scope: input.scope,
+ },
+ userAgent: actor.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+
+ const summary = await getApiKeySummary(id, database);
+
+ if (!summary) {
+ throw new Error("A key that was just created could not be read back.");
+ }
+
+ return { key, summary };
+}
+
+async function getApiKeySummary(
+ id: string,
+ database: DbExecutor,
+): Promise<ApiKeySummary | null> {
+ return queryOne<ApiKeySummary>(
+ database,
+ `
+ SELECT ${SUMMARY_COLUMNS}
+ FROM api_keys k
+ JOIN "user" u ON u.id = k.user_id
+ WHERE k.id = $1
+ `,
+ [id],
+ );
+}
+
+/**
+ * Every key on the install, newest first. Administrators manage each
+ * other's keys, since a key acts for the organization.
+ */
+export async function listApiKeys(
+ database: DbExecutor = getDb(),
+): Promise<ApiKeySummary[]> {
+ return queryMany<ApiKeySummary>(
+ database,
+ `
+ SELECT ${SUMMARY_COLUMNS}
+ FROM api_keys k
+ JOIN "user" u ON u.id = k.user_id
+ ORDER BY k.revoked_at IS NOT NULL, k.created_at DESC
+ LIMIT 200
+ `,
+ );
+}
+
+/** Revokes a key for the administrator `actor`. Revoking twice is fine. */
+export async function revokeApiKey(
+ actor: Actor,
+ keyId: string,
+ database: DbPool = getDb(),
+): Promise<ApiKeySummary> {
+ const revokedAt = nowInSeconds();
+
+ await withTransaction(async (tx) => {
+ const owner = await queryOne<{ role: string }>(
+ tx,
+ `SELECT role FROM "user" WHERE id = $1`,
+ [actor.userId],
+ );
+
+ if (!isAdminRow(owner)) {
+ throw new ApiKeyError("Only an administrator can do this.", 403);
+ }
+
+ const key = await queryOne<{
+ name: string;
+ prefix: string;
+ revokedAt: number | null;
+ userId: string;
+ }>(
+ tx,
+ `
+ SELECT name, prefix, user_id AS "userId", revoked_at AS "revokedAt"
+ FROM api_keys
+ WHERE id = $1
+ FOR UPDATE
+ `,
+ [keyId],
+ );
+
+ if (!key) {
+ throw new ApiKeyError("That key no longer exists.", 404);
+ }
+
+ if (key.revokedAt !== null) {
+ return;
+ }
+
+ await tx.query(`UPDATE api_keys SET revoked_at = $1 WHERE id = $2`, [
+ revokedAt,
+ keyId,
+ ]);
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ createdAt: revokedAt,
+ event: "api_key_revoked",
+ ipAddress: actor.ipAddress ?? null,
+ metadata: {
+ apiKeyId: keyId,
+ name: key.name,
+ prefix: key.prefix,
+ reason: "revoked",
+ },
+ targetUserId: key.userId,
+ userAgent: actor.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+
+ const summary = await getApiKeySummary(keyId, database);
+
+ if (!summary) {
+ throw new ApiKeyError("That key no longer exists.", 404);
+ }
+
+ return summary;
+}
+
+/**
+ * Revokes every key an account still has, inside the caller's transaction.
+ * Called when the account stops being an administrator, so that making it
+ * one again later does not quietly bring old keys back.
+ */
+export async function revokeApiKeysForUser(
+ userId: string,
+ reason: string,
+ tx: DbExecutor,
+ actor: { email: string | null; userId: string | null } = {
+ email: null,
+ userId: null,
+ },
+): Promise<number> {
+ const revokedAt = nowInSeconds();
+ const revoked = await tx.query<{ id: string; name: string; prefix: string }>(
+ `
+ UPDATE api_keys
+ SET revoked_at = $1
+ WHERE user_id = $2 AND revoked_at IS NULL
+ RETURNING id, name, prefix
+ `,
+ [revokedAt, userId],
+ );
+
+ for (const key of revoked.rows) {
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ createdAt: revokedAt,
+ event: "api_key_revoked",
+ metadata: {
+ apiKeyId: key.id,
+ name: key.name,
+ prefix: key.prefix,
+ reason,
+ },
+ targetUserId: userId,
+ },
+ tx,
+ );
+ }
+
+ return revoked.rowCount ?? 0;
+}
+
+/**
+ * The account a presented key acts as, or null if the key is unknown,
+ * revoked, expired, or belongs to someone who is no longer an
+ * administrator or is closing their account. Every one of those looks the
+ * same to the caller.
+ */
+export async function authenticateApiKey(
+ presented: string,
+ database: DbExecutor = getDb(),
+ now: number = nowInSeconds(),
+): Promise<ApiKeyPrincipal | null> {
+ if (!looksLikeApiKey(presented)) {
+ return null;
+ }
+
+ const presentedHash = hashApiKey(presented);
+ const row = await queryOne<{
+ email: string;
+ emailVerified: boolean;
+ id: string;
+ keyHash: string;
+ lastUsedAt: number | null;
+ name: string;
+ role: string;
+ scope: ApiKeyScope;
+ userId: string;
+ userName: string;
+ }>(
+ database,
+ `
+ SELECT
+ k.id,
+ k.name,
+ k.scope,
+ k.key_hash AS "keyHash",
+ k.last_used_at AS "lastUsedAt",
+ u.id AS "userId",
+ u.email,
+ u.name AS "userName",
+ u.role,
+ u."emailVerified" AS "emailVerified"
+ FROM api_keys k
+ JOIN "user" u ON u.id = k.user_id
+ WHERE k.key_hash = $1
+ AND k.revoked_at IS NULL
+ AND (k.expires_at IS NULL OR k.expires_at > $2)
+ AND NOT EXISTS (
+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id
+ )
+ `,
+ [presentedHash, now],
+ );
+
+ if (
+ !row ||
+ row.role !== "admin" ||
+ row.emailVerified !== true ||
+ // The lookup was by hash already; this only guards against a database
+ // that compares text loosely.
+ !timingSafeEqual(Buffer.from(row.keyHash), Buffer.from(presentedHash))
+ ) {
+ return null;
+ }
+
+ if (
+ row.lastUsedAt === null ||
+ now - row.lastUsedAt >= LAST_USED_WRITE_INTERVAL_SECONDS
+ ) {
+ await database
+ .query(`UPDATE api_keys SET last_used_at = $1 WHERE id = $2`, [
+ now,
+ row.id,
+ ])
+ .catch((error: unknown) => {
+ console.error("Recording when an API key was used failed:", error);
+ });
+ }
+
+ return {
+ apiKey: { id: row.id, name: row.name, scope: row.scope },
+ user: { email: row.email, id: row.userId, name: row.userName },
+ };
+}
diff --git a/src/lib/api/http.ts b/src/lib/api/http.ts
new file mode 100644
index 0000000..b9b512d
--- /dev/null
+++ b/src/lib/api/http.ts
@@ -0,0 +1,62 @@
+import { NextResponse } from "next/server";
+
+// Responses for the public API (/api/v1). Every error has the same shape,
+// {"error": {"code": "…", "message": "…"}}, and the codes do not change
+// within a version. See docs/api.md.
+
+export type ApiErrorCode =
+ | "forbidden"
+ | "idempotency_key_reused"
+ | "internal_error"
+ | "invalid_request"
+ | "not_found"
+ | "payload_too_large"
+ | "rate_limited"
+ | "unauthorized"
+ | "wrong_state";
+
+const NO_STORE = "private, no-store";
+
+export function apiJson(
+ body: unknown,
+ init: { headers?: Record<string, string>; status?: number } = {},
+) {
+ const response = NextResponse.json(body, {
+ headers: init.headers,
+ status: init.status ?? 200,
+ });
+
+ response.headers.set("cache-control", NO_STORE);
+ return response;
+}
+
+export function apiError(
+ status: number,
+ code: ApiErrorCode,
+ message: string,
+ headers: Record<string, string> = {},
+) {
+ return apiJson({ error: { code, message } }, { headers, status });
+}
+
+/** The code that fits an HTTP status the app's own errors carry. */
+export function codeForStatus(status: number): ApiErrorCode {
+ switch (status) {
+ case 400:
+ return "invalid_request";
+ case 401:
+ return "unauthorized";
+ case 403:
+ return "forbidden";
+ case 404:
+ return "not_found";
+ case 409:
+ return "wrong_state";
+ case 413:
+ return "payload_too_large";
+ case 429:
+ return "rate_limited";
+ default:
+ return status >= 500 ? "internal_error" : "invalid_request";
+ }
+}
diff --git a/src/lib/auth/api-key.ts b/src/lib/auth/api-key.ts
new file mode 100644
index 0000000..bffe646
--- /dev/null
+++ b/src/lib/auth/api-key.ts
@@ -0,0 +1,140 @@
+import {
+ authenticateApiKey,
+ readBearerToken,
+ scopeAllows,
+ type ApiKeyPrincipal,
+ type ApiKeyScope,
+} from "../api-keys.ts";
+import { apiError } from "../api/http.ts";
+import { logSecurityEvent } from "../security/logging.ts";
+import { consumeRateLimit, peekRateLimit } from "../security/rate-limit.ts";
+import { getClientIpAddress, getRequestPathname } from "../security/request.ts";
+
+/** Requests one key may make in a window, across every endpoint. */
+export const API_KEY_RATE_LIMIT = 600;
+export const API_KEY_RATE_WINDOW_MS = 10 * 60 * 1000;
+/** Failed attempts one address may make before it is turned away. */
+const FAILED_ATTEMPT_LIMIT = 30;
+const FAILED_ATTEMPT_WINDOW_MS = 10 * 60 * 1000;
+
+const UNAUTHORIZED_MESSAGE =
+ 'Send a valid API key as "Authorization: Bearer sdk_…".';
+
+/**
+ * For /api/v1 routes: the key's principal, or the response to send. Every
+ * kind of bad key gets the same 401, so a caller cannot tell an unknown key
+ * from a revoked one. Rate limit headers are set on the response by
+ * `withRateLimitHeaders`.
+ */
+export async function requireApiKey(
+ request: Request,
+ scope: ApiKeyScope,
+): Promise<(ApiKeyPrincipal & { rateLimit: RateLimitState }) | Response> {
+ const ipAddress = getClientIpAddress(request.headers);
+ const presented = readBearerToken(request.headers);
+
+ if (!presented) {
+ return apiError(401, "unauthorized", UNAUTHORIZED_MESSAGE, {
+ "www-authenticate": 'Bearer realm="signudoc"',
+ });
+ }
+
+ const failureKey = `api-key-failures:${ipAddress ?? "unknown"}`;
+ const failures = await peekRateLimit({
+ key: failureKey,
+ limit: FAILED_ATTEMPT_LIMIT,
+ });
+
+ // An address that keeps sending bad keys is turned away before the
+ // database is asked about another one.
+ if (!failures.allowed) {
+ return apiError(
+ 429,
+ "rate_limited",
+ "Too many requests with a bad key. Try again later.",
+ { "retry-after": String(failures.retryAfterSeconds) },
+ );
+ }
+
+ const principal = await authenticateApiKey(presented);
+
+ if (!principal) {
+ await consumeRateLimit({
+ key: failureKey,
+ limit: FAILED_ATTEMPT_LIMIT,
+ windowMs: FAILED_ATTEMPT_WINDOW_MS,
+ });
+ logSecurityEvent("warn", {
+ category: "api_key_rejected",
+ ipAddress,
+ message:
+ "Refused an API request with an unknown, revoked or expired key.",
+ path: getRequestPathname(request),
+ });
+
+ return apiError(401, "unauthorized", UNAUTHORIZED_MESSAGE, {
+ "www-authenticate": 'Bearer realm="signudoc", error="invalid_token"',
+ });
+ }
+
+ const decision = await consumeRateLimit({
+ key: `api-key:${principal.apiKey.id}`,
+ limit: API_KEY_RATE_LIMIT,
+ windowMs: API_KEY_RATE_WINDOW_MS,
+ });
+ const rateLimit: RateLimitState = {
+ limit: API_KEY_RATE_LIMIT,
+ remaining: Math.max(0, API_KEY_RATE_LIMIT - decision.count),
+ resetSeconds: decision.retryAfterSeconds,
+ };
+
+ if (!decision.allowed) {
+ logSecurityEvent("warn", {
+ category: "api_key_rate_limited",
+ ipAddress,
+ message: "Rate limit exceeded for an API key.",
+ metadata: { apiKeyId: principal.apiKey.id },
+ path: getRequestPathname(request),
+ userId: principal.user.id,
+ });
+
+ return withRateLimitHeaders(
+ apiError(
+ 429,
+ "rate_limited",
+ "This key has made too many requests. Wait and try again.",
+ { "retry-after": String(decision.retryAfterSeconds) },
+ ),
+ rateLimit,
+ );
+ }
+
+ if (!scopeAllows(principal.apiKey.scope, scope)) {
+ return withRateLimitHeaders(
+ apiError(
+ 403,
+ "forbidden",
+ "This key is read-only. Use a key with write access.",
+ ),
+ rateLimit,
+ );
+ }
+
+ return { ...principal, rateLimit };
+}
+
+export type RateLimitState = {
+ limit: number;
+ remaining: number;
+ resetSeconds: number;
+};
+
+export function withRateLimitHeaders<T extends Response>(
+ response: T,
+ state: RateLimitState,
+): T {
+ response.headers.set("ratelimit-limit", String(state.limit));
+ response.headers.set("ratelimit-remaining", String(state.remaining));
+ response.headers.set("ratelimit-reset", String(state.resetSeconds));
+ return response;
+}
diff --git a/src/lib/people.ts b/src/lib/people.ts
index 36d4708..04dd9f2 100644
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@ -6,6 +6,7 @@ import {
queryOne,
withTransaction,
} from "./db/connection.ts";
+import { revokeApiKeysForUser } from "./api-keys.ts";
import { recordSystemAuditEvent } from "./services/system-audit.ts";
// The accounts on this install and who among them is an administrator.
@@ -298,6 +299,16 @@ export async function setPersonRole(
tx,
);
+ if (role === "user") {
+ // A key acts as its administrator. One who is no longer one loses
+ // their keys for good, so making them one again later does not
+ // quietly bring old keys back.
+ await revokeApiKeysForUser(targetUserId, "role_removed", tx, {
+ email: actor.email,
+ userId: actingUserId,
+ });
+ }
+
if (keeperId) {
// The account's row has been held since it was read above. A closed
// account's envelopes are handed over only while holding the
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
index b68cbfa..18ed1d3 100644
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@ -42,6 +42,8 @@ export const systemAuditEventTypes = [
"two_factor_requirement_changed",
"logo_changed",
"email_domain_changed",
+ "api_key_created",
+ "api_key_revoked",
] as const;
export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];