> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API keys

> Let external systems call your GatoJS API on behalf of an organization with scoped, hashed API keys and authenticateApiKey.

An external system (an integration, an AI agent, a customer's script) needs to call your app's API on behalf of an organization, without a person signing in. The `api-keys` module gives organization owners and admins an `/api-keys` page where they issue keys with scopes, such as `organization:read`. Your API routes call `authenticateApiKey(request, scope)`, which reads `Authorization: Bearer <key>`, resolves the organization and checks the scope.

The kit ships one example route, `GET /api/v1/organization`. You write routes for your own data.

A key belongs to the organization, not to a person: it keeps working after its creator's account is deleted. The database stores only an HMAC of the key, so the full key can't be read or shown twice.

## What it doesn't do

* **No session or `OrgContext`.** A key route doesn't go through `getOrgContext()`, role guards or service mode. It filters data by the organization from the key itself.
* **No rate limiting** and no per-request log. The only trace of use is the key's `lastUsedAt`.
* **No rotation and no OAuth.** You revoke a key and issue a new one by hand.
* **No audit events for API requests.** Only key management commands write audit events. Writing events with the `API` channel is up to your routes.
* **Not a replacement for user sign-in.** A key can't open app pages or call server actions; those read the session.

Skip the module if only signed-in users call your API, or if you can't keep a stable `API_KEY_PEPPER` secret in every environment.

## Requirements

| | `api-keys` |
| - | - |
| Required kit modules | None. With [`audit-logs`](https://docs.gatojs.com/modules/audit-logs) installed, key events are recorded. |
| Services | None. |
| Environment variables | `API_KEY_PEPPER`, required, at least 32 characters; in production it can't be the `.env.example` value. |
| npm dependencies | None. |
| Database | `api_keys` table, so a migration after adding the module. |

## Install and remove

> [tab] Existing project
>
> **1. Add the module**
>
> ```bash theme={null}
> npx gato add api-keys
> ```
>
> This copies the module files, adds `createdApiKeys ApiKey[]` to `User` and `apiKeys ApiKey[]` to `Organization`, adds `API_KEY_PEPPER` to the `wa:modules` region of `.env.example`, runs `gato generate` and `npm install`.
>
> **2. Set the pepper**
>
> `gato add` doesn't change `.env`. Add the variable yourself, or the server won't start:
>
> ```bash .env theme={null}
> API_KEY_PEPPER=dev-only-api-key-pepper-change-me-0123456789
> ```
>
> **3. Create the migration**
>
> ```bash theme={null}
> npx prisma migrate dev --name add-api-keys
> ```
>
> Commit it. After `--no-install`, also run `npm run db:generate`.

> [tab] New project
>
> ```bash theme={null}
> npm create gato-app@latest acme-app -- --modules api-keys
> ```
>
> `gato create` writes the example `API_KEY_PEPPER` to `.env`, which works locally and in tests. The first migration creates the `api_keys` table.

Integration tests get the pepper from `src/test/integration/setup-env.ts` and e2e servers from `e2e/env.ts`, so your CI doesn't need the secret.

### Configure `API_KEY_PEPPER`

Keys are stored as HMAC-SHA256 with `API_KEY_PEPPER` as the secret. A database leak alone isn't enough to verify keys without the pepper.

* **Production needs its own value.** The module's `env.ts` rejects a missing value, a value shorter than 32 characters and, with `NODE_ENV=production`, the example value from `.env.example`. Generate one with `openssl rand -base64 32` and set it before the first deployment. See [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md).
* **A bad pepper stops the whole app.** The module schema is part of the app-wide environment validation that runs at server start. With the example pepper in production, the server prints a report with `- API_KEY_PEPPER: w produkcji nie może być wartością z .env.example` ("can't be the .env.example value in production") and exits with code 1.
* **Changing the pepper invalidates every key.** The same key hashes to a different value, so no stored key matches and every request gets 401 `invalid`. Keys stay on the list as "Active" but don't work; organizations must issue new keys. Keep the pepper stable per environment and don't lose it. Different peppers on staging and production are fine, because keys don't move between environments.

### Removing the module

`npx gato remove api-keys` refuses when a project module lists `api-keys` in `requires`. After a successful removal:

| What | After `gato remove api-keys` |
| - | - |
| `api_keys` table with key hashes | Stays until you apply `npx prisma migrate dev --name remove-api-keys`. Keys stop working anyway, because the route and `authenticateApiKey` are gone. |
| `API_KEY_PEPPER` in `.env` and production | Stays; only `.env.example` loses it. Remove it yourself. |
| `GET /api/v1/organization`, `/api-keys` page, menu item | Removed. |
| Your routes that import `authenticateApiKey` or `ApiKeyContext` | Stop building with `TS2307`. `gato remove` doesn't look for such imports. |
| `apiScopes` declarations in your modules | Stay and do nothing. |
| `api_key.*` audit entries | Stay; `/audit-log` shows them as raw strings. |

## What the module adds

### Module definition

| Field | Value | Effect |
| - | - | - |
| `key` | `api-keys` | Key for `requireModuleAccess("api-keys")` and the translation namespace. |
| `nav` | `/api-keys`, label "API keys", icon `key-round`, `order: 85` | Menu item for roles with access. |
| `routePrefixes` | `["/api-keys"]` | Assigns the path to the module. |
| `roles` | `["owner", "admin"]` | Organization owners and admins have access; `member` doesn't. |
| `apiScopes` | `organization:read` ("Read organization data") | Scope of the example route. |
| `auditActions` | `api_key.created`, `api_key.revoked`, `api_key.deleted` | Labels for key events. |

### The `ApiKey` model

`prisma/schema/api-keys.prisma`, table `api_keys`:

| Field | Column and type | Meaning |
| - | - | - |
| `id` | `id`, `uuid` | Key ID; passed to routes as `apiKeyId`. |
| `organizationId` | `organization_id`, text, required | Organization the key acts for. |
| `createdById` | `created_by_id`, text, optional | Creator, for display only. |
| `name` | `name`, text | Name given at creation, 1–100 characters after trimming. |
| `displayPrefix` | `display_prefix`, text | Key prefix plus its first 6 random characters, to recognize the key in the list. |
| `hashedKey` | `hashed_key`, text, unique | HMAC-SHA256 of the key with `API_KEY_PEPPER`, hex (64 characters). |
| `scopes` | `scopes`, `text[]`, default `[]` | Scopes granted to the key. |
| `lastUsedAt` | `last_used_at`, `timestamptz`, optional | Last successful authentication. |
| `expiresAt` | `expires_at`, `timestamptz`, optional | Expiry; `null` means no expiry. |
| `revokedAt` | `revoked_at`, `timestamptz`, optional | When the key was revoked. |
| `createdAt`, `updatedAt` | `timestamptz` | Row timestamps. |

Deleting an organization deletes its keys (`onDelete: Cascade`). Deleting a user leaves their keys working with `createdById` set to `null`.

### Key lifecycle

The `/api-keys` page lists each key's name, `displayPrefix`, scope labels, last use, status and creator. Every action goes through `useServiceModeAction().run`, so a superadmin in service mode confirms it first.

**1. Create**

"New key" opens a form: name, scopes (a checkbox for every scope declared in the registry) and expiry: 30, 90 (default) or 365 days, or no expiry. `createApiKeyCommand` checks access and service mode, validates input, generates the key, then checks the limit and stores the row in one transaction.

**2. Show once**

The full key is returned only once, in a "Your new API key" dialog with a "Copy key" button. After the dialog closes the key is gone from the page. The database holds only `displayPrefix` and `hashedKey`; audit entries and the list never contain the key or its hash. A lost key must be replaced.

**3. Use**

The key format is `<project slug with _ instead of ->_live_<43 base64url characters>` (32 random bytes). For a project `acme-app`, keys start with `acme_app_live_`.

**4. Expire, revoke or delete**

A key whose `expiresAt` has passed gets 401 `expired` and can't be extended. "Revoke" sets `revokedAt` once; the key stays listed as "Revoked" and gets 401 `revoked`. "Delete" removes the row; the key then gets 401 `invalid`.

**Active key limit.** An organization can have at most 10 active keys (not revoked and not expired). At the limit, creation fails with "Osiągnięto limit 10 aktywnych kluczy" ("Active key limit of 10 reached"). The limit is a constant in code (`ACTIVE_KEY_LIMIT`). The check takes a Postgres advisory lock per organization, so two parallel requests can't both pass it.

### `GET /api/v1/organization`

```ts src/app/api/v1/organization/route.ts theme={null}
export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const NO_STORE = { "Cache-Control": "no-store" };

export async function GET(request: Request) {
  const auth = await authenticateApiKey(request, "organization:read");
  if (!auth.ok) {
    return Response.json(
      { error: auth.error },
      { status: auth.status, headers: NO_STORE },
    );
  }
  return Response.json(await readOrganizationForApiKey(auth.context), {
    headers: NO_STORE,
  });
}
```

A successful call returns 200 with `{ id, name, slug }` of the key's organization. Every response, including errors, has `Cache-Control: no-store`. An `x-organization-id` header or `?organizationId=` parameter changes nothing. Paths under `/api/` skip the locale middleware.

### Access by role

The page, the list query and the three commands are available to owners and admins of the active organization and to accounts with the global `admin` or `superadmin` role. A `member` gets a 404 on the page, and the commands call `notFound()` without writing anything. Roles don't apply to key routes: there, only the key's scopes decide. See [Auth and roles](https://docs.gatojs.com/concepts/auth-and-roles.md).

### Audit events

Key commands call `trackAudit` with `...auditActor(context)` after a successful write:

| Action | Data | When |
| - | - | - |
| `api_key.created` | `newData: { name, scopes, displayPrefix }` | After the key is stored. |
| `api_key.revoked` | `oldData: { name, displayPrefix }` | Only when the row changed; revoking again writes nothing. |
| `api_key.deleted` | `oldData: { name, displayPrefix }` | Only when a row was deleted. |

Events never contain the key or its hash and use the `WEB` channel. Without `audit-logs` they're recorded nowhere.

## The `authenticateApiKey` contract

```ts src/features/api-keys/services/authenticate-api-key.ts theme={null}
export interface ApiKeyContext {
  organizationId: string;
  apiKeyId: string;
  scopes: string[];
}

export type ApiKeyAuthResult =
  | { ok: true; context: ApiKeyContext }
  | {
      ok: false;
      status: 401 | 403;
      error: "missing" | "invalid" | "revoked" | "expired" | "scope";
    };

export async function authenticateApiKey(
  request: Request,
  requiredScope: string,
): Promise<ApiKeyAuthResult>;
```

The function doesn't throw on a bad header; it returns a result that your route turns into a response. Checks run in this order:

| Situation | `status` | `error` |
| - | - | - |
| No `Authorization` header, a scheme other than `Bearer ` (case-sensitive), or an empty token | 401 | `missing` |
| No key with this hash: wrong key, extra spaces inside the token, quoted key, deleted key, key from before a pepper change | 401 | `invalid` |
| Key has `revokedAt` | 401 | `revoked` |
| Key's `expiresAt` is at or before the request time | 401 | `expired` |
| Key lacks the required scope among scopes known to the registry | 403 | `scope` |
| Valid key with the scope | | `{ ok: true, context }` |

* **Lookup.** The function hashes the token and finds the row by the unique `hashedKey`, inside `withoutTenantScope("api key lookup by hash", …)` because the organization isn't known yet.
* **Scopes.** Key scopes are intersected with `knownApiScopes()`. A scope no module declares grants nothing. That includes the route's own scope: if no module declares it in `apiScopes`, the route always returns 403.
* **`lastUsedAt`.** After success the function updates `lastUsedAt` in the background without awaiting it. A failed update is only logged.
* **Organization.** `context.organizationId` comes from the key row. Headers and parameters can't change it.

> [!WARNING]
>
> Calling `authenticateApiKey` before touching data is a convention. No architecture test checks `route.ts` files. A route without the call is public.

### No `OrgContext`: filter by organization explicitly

A key is not a session. A key route doesn't call `getOrgContext()`, `requireModuleAccess()` or `assertServiceModeConfirmed`. There is no user, no organization role and no service mode; the only identity is `ApiKeyContext`. The core doesn't filter Prisma automatically, so **every query called from a key route must include `organizationId: context.organizationId`**: in `where` for reads, updates and deletes, and in `data` for creates. Never take the organization from the request body. See [Organizations](https://docs.gatojs.com/concepts/organizations.md).

Where to put code called from a key route:

* a service that takes `ApiKeyContext`, in the feature's `services/` folder, in a file **without** `"use server"`;
* not in `services/queries/`, because an architecture test requires a session guard before Prisma there;
* never in a `"use server"` file: every export there becomes a public server action that a client could call with its own `organizationId`.

### `apiScopes`

The `apiScopes?: { key: string; labelKey: string }[]` field in `defineModule` declares scopes a key can be granted.

* **Who declares.** The module or project feature whose route needs the scope, in its own `module.ts`, with the label in its own locale files. The label lives in the namespace of the declaring module, so `key` must match the folder name. The kit uses `resource:operation` names such as `organization:read`.
* **Who reads.** `knownApiScopes()` (server registry) for validation in the create command and filtering in `authenticateApiKey`; the `/api-keys` form (client registry) for checkboxes and labels.
* **When it applies.** A new `module.ts` enters the registry after `npx gato generate`; a new entry in an existing `apiScopes` array works without it.
* **Removing a declaration** (or the module that had it) silently removes that scope from every key that had it. The value stays in the `scopes` column and shows as a raw string.
* **Duplicates.** Don't declare another module's scope: the form would show two checkboxes for it.
* **Without `api-keys`** the field type-checks and does nothing.

## Use it from your code

The examples below come from a `deliveries` project module that lets an external system read and accept deliveries. Its `projectModules` entry in `.wa/kit.json` lists `"requires": ["api-keys"]`.

### Declare your own scopes

```ts src/features/deliveries/module.ts theme={null}
export default defineModule({
  key: "deliveries",
  nav: [],
  routePrefixes: [],
  apiScopes: [
    { key: "deliveries:read", labelKey: "scopes.deliveriesRead" },
    { key: "deliveries:write", labelKey: "scopes.deliveriesWrite" },
  ],
  auditActions: [
    { action: "delivery.accepted", labelKey: "action-delivery-accepted" },
  ],
});
```

Put the labels in `src/features/deliveries/i18n/en.json` (`"scopes": { "deliveriesRead": "Read deliveries", "deliveriesWrite": "Accept deliveries" }`) and every other locale. Run `npx gato generate` after adding `module.ts`. Separate read and write scopes let organizations issue read-only keys.

### Write a route with key authentication

```ts src/app/api/v1/deliveries/route.ts theme={null}
import { authenticateApiKey } from "@/features/api-keys/services/authenticate-api-key";
import {
  acceptDeliveryForApiKey,
  listDeliveriesForApiKey,
} from "@/features/deliveries/services/delivery-api";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const NO_STORE = { "Cache-Control": "no-store" };

export async function GET(request: Request) {
  const auth = await authenticateApiKey(request, "deliveries:read");
  if (!auth.ok) {
    return Response.json(
      { error: auth.error },
      { status: auth.status, headers: NO_STORE },
    );
  }
  return Response.json(await listDeliveriesForApiKey(auth.context), {
    headers: NO_STORE,
  });
}

export async function POST(request: Request) {
  const auth = await authenticateApiKey(request, "deliveries:write");
  if (!auth.ok) {
    return Response.json(
      { error: auth.error },
      { status: auth.status, headers: NO_STORE },
    );
  }
  const body: unknown = await request.json().catch(() => null);
  const result = await acceptDeliveryForApiKey(auth.context, body);
  if (!result.success) {
    return Response.json(
      { error: result.error },
      { status: 400, headers: NO_STORE },
    );
  }
  return Response.json(result.data, { status: 201, headers: NO_STORE });
}
```

The route authenticates first, passes `auth.context` to a service and sets `Cache-Control: no-store` on every response, errors included, so shared caches never keep organization data. `request.json().catch(() => null)` turns malformed JSON into a 400 validation error instead of a 500.

The service lives in `services/delivery-api.ts`, without `"use server"`, and filters by the key's organization:

```ts src/features/deliveries/services/delivery-api.ts theme={null}
import type { ApiKeyContext } from "@/features/api-keys/services/authenticate-api-key";

export async function listDeliveriesForApiKey(
  context: ApiKeyContext,
): Promise<DeliveryApiItem[]> {
  return prisma.delivery.findMany({
    where: { organizationId: context.organizationId },
    orderBy: { createdAt: "desc" },
    select: { id: true, supplier: true, packages: true, createdAt: true },
  });
}
```

### Record an audit event with the API channel

A key route has no `OrgContext`, so `auditActor` doesn't apply. Build the event from the key context:

```ts src/features/deliveries/services/delivery-api.ts theme={null}
export async function acceptDeliveryForApiKey(
  context: ApiKeyContext,
  input: unknown,
): Promise<OperationResult<{ id: string }>> {
  const parsed = acceptDeliverySchema.safeParse(input);
  if (!parsed.success) {
    return { success: false, error: "invalid_input" };
  }
  const delivery = await prisma.delivery.create({
    data: { organizationId: context.organizationId, ...parsed.data },
    select: { id: true },
  });
  await trackAudit({
    organizationId: context.organizationId,
    actorUserId: null,
    action: "delivery.accepted",
    entityType: "delivery",
    entityId: delivery.id,
    newData: parsed.data,
    channel: "API",
    credentialId: context.apiKeyId,
  });
  return { success: true, data: { id: delivery.id } };
}
```

The `/audit-log` page shows an "API" badge and "System" as the actor. `credential_id` has no foreign key, so the entry survives key deletion, but you can no longer look up the key's name. `trackAudit` also works without `audit-logs` and then records nothing. See [Audit logs](https://docs.gatojs.com/modules/audit-logs.md).

### Call the API from outside

An owner or admin creates a key with the right scope on `/api-keys`. The external system sends it in a header:

```bash theme={null}
curl -X POST https://your-app.example.com/api/v1/deliveries \
  -H "Authorization: Bearer acme_app_live_..." \
  -H "Content-Type: application/json" \
  -d '{"supplier":"North Wholesale","packages":3}'
```

Expected responses:

| Request | Response |
| - | - |
| No `Authorization` header | `401 {"error":"missing"}` |
| `POST` with a key that only has `deliveries:read` | `403 {"error":"scope"}` |
| `POST` with `deliveries:write` | `201 {"id":"…"}` |
| Malformed JSON | `400 {"error":"invalid_input"}` |
| `GET` with `deliveries:read` | `200` with the organization's deliveries |
| Same key on `GET /api/v1/organization` | `403 {"error":"scope"}`, because it lacks `organization:read` |

### Code that works without the module

An `apiScopes` declaration builds in a project without `api-keys` and starts working after `gato add api-keys`. A key route doesn't: it imports `authenticateApiKey`, so the project won't build without the module. Keep key routes in a feature that lists `api-keys` in `requires`. A service that takes plain `{ organizationId }` instead of `ApiKeyContext` imports nothing from the module and works everywhere.

## Security

* **Explicit organization filter** in every query called from a key route.
* **A route without `authenticateApiKey` is public.** Nothing checks this automatically.
* **No `"use server"` in key route services.**
* **Pepper required in production**; changing it invalidates every key, and a bad value stops the whole app.
* **The key is shown once.** The database stores only `displayPrefix` and an HMAC.
* **`Cache-Control: no-store`** on every key route response, including errors.
* **Scopes must be declared.** Removing a declaration silently removes access.
* **Deleting the creator doesn't disable the key.** When someone who knew a key leaves, revoke it.
* **No rate limiting or request log.** Abuse shows only in `lastUsedAt`.
* **Command isolation.** Revoking or deleting another organization's key returns "Nie znaleziono klucza" ("Key not found") and changes nothing.
* **Service mode** applies to key management commands, not to key routes.

## Testing

Test a key route against a real database by calling the exported `GET` or `POST` with a `Request` object, with no HTTP server and no mocks: `authenticateApiKey`, Prisma and `trackAudit` run for real. Seed keys yourself, computing the hash in the test from `process.env.API_KEY_PEPPER` rather than with `hashApiKey`, so a change in the hashing code shows up in the test.

```ts src/features/deliveries/services/__tests__/deliveries-route.integration.test.ts theme={null}
function hash(plaintext: string): string {
  return createHmac("sha256", process.env.API_KEY_PEPPER ?? "")
    .update(plaintext)
    .digest("hex");
}

async function seedKey(organizationId: string, plaintext: string, scopes: string[]) {
  return prisma.apiKey.create({
    data: {
      organizationId,
      name: `key ${plaintext.slice(-4)}`,
      displayPrefix: plaintext.slice(0, 20),
      hashedKey: hash(plaintext),
      scopes,
    },
    select: { id: true },
  });
}

describe("GET /api/v1/deliveries", () => {
  it("returns 401 missing with no-store without a key", async () => {
    const response = await GET(request("GET", null));

    expect(response.status).toBe(401);
    expect(response.headers.get("cache-control")).toBe("no-store");
    await expect(response.json()).resolves.toEqual({ error: "missing" });
  });

  it("does not show organization A's deliveries to a key of B", async () => {
    await seedKey(world.orgB.id, KEY_B, ["deliveries:read"]);

    const response = await GET(request("GET", `Bearer ${KEY_B}`));

    const items = (await response.json()) as { supplier: string }[];
    expect(items.map((item) => item.supplier)).toEqual(["Wholesale B"]);
  });
});
```

* Create two organizations and check that one key can't see or change the other's data.
* Cover the scope check (403 without the write scope, nothing stored), invalid input (400, nothing stored) and a `POST` with another organization's `organizationId` in the body (stored in the key's organization, audit entry with `channel: "API"`, `userId: null`).
* Use literal expected values. See [Testing](https://docs.gatojs.com/guides/testing.md).
* Integration tests read the pepper from `setup-env.ts`; you don't need it in `.env`.
* Tests of key management commands (session-based) mock the session with `vi.spyOn(auth.api, "getSession")`, framework I/O and `trackAudit`.

## Troubleshooting

| Symptom | Cause | Fix |
| - | - | - |
| Server won't start; the environment report lists `- API_KEY_PEPPER: …` and the process exits with code 1 | Pepper missing, shorter than 32 characters, or the `.env.example` value with `NODE_ENV=production`. | Set your own pepper and redeploy. |
| Every key gets 401 `invalid` though the list says "Active" | `API_KEY_PEPPER` changed, or the environment uses a different pepper than the one the keys were created with. | Restore the previous value, or issue new keys and delete the old ones. |
| 401 `missing` despite sending a key | The header doesn't start with exactly `Bearer ` (`bearer`, a tab, the bare key). | Send `Authorization: Bearer <key>`. |
| 401 `invalid` for a freshly copied key | Key copied partially, quoted, with two spaces after `Bearer` or a space inside; or the key was deleted. | Copy again; a lost key can't be recovered, so issue a new one. |
| 403 `scope` although the key has the scope | The route needs a different scope, or no module in the registry declares it. | Check `apiScopes` in `module.ts`; run `npx gato generate` after adding a new `module.ts`. |
| Your scope isn't in the `/api-keys` form | No `apiScopes` declaration or `module.ts` not in the registry. | Add the declaration; run the generator for a new file. |
| Key path instead of a scope label, `MISSING_MESSAGE` | Label key missing from a locale file, or module `key` differs from the folder name. | Add the key in every locale; make `key` match the folder. |
| Creation fails with the active key limit message | The organization has 10 active keys. | Revoke or delete an unused key. |
| `TS2307: Cannot find module '@/features/api-keys/…'` | A route imports a module file but the module isn't installed. | `npx gato add api-keys`, or remove the route. |
| `gato remove api-keys` refuses, naming a module | A project module lists `api-keys` in `requires`. | Remove its key routes and `requires` entry, or keep the module. |
| A route returns another organization's data | A service query lacks `organizationId: context.organizationId`. | Add the filter and an isolation test. |

> [!NOTE]
>
> Some server-side messages in the kit, such as environment validation lines and command errors, are currently in Polish. The tables above give their meaning.

## Reference

### Environment variables

| Variable | Required | Rule | Kit values |
| - | - | - | - |
| `API_KEY_PEPPER` | Yes, when the module is installed | At least 32 characters; with `NODE_ENV=production`, not `dev-only-api-key-pepper-change-me-0123456789` | Example value in `.env.example` and the generated `.env`; tests use `setup-env.ts` and `e2e/env.ts` |

### Routes

| Route | Scope | Responses |
| - | - | - |
| `GET /api/v1/organization` | `organization:read` | 200 `{ id, name, slug }`; 401 `{ error: "missing" \| "invalid" \| "revoked" \| "expired" }`; 403 `{ error: "scope" }`; always `Cache-Control: no-store`. |

### Scopes and audit actions

| String | Kind | English label |
| - | - | - |
| `organization:read` | scope | Read organization data |
| `api_key.created` | audit action | API key created |
| `api_key.revoked` | audit action | API key revoked |
| `api_key.deleted` | audit action | API key deleted |

### Files

| File | Export | Purpose |
| - | - | - |
| `components/api-keys-manager.tsx` | `ApiKeysManager` | `/api-keys` view: list, form, key dialog. |
| `services/commands/api-key-commands.ts` | `createApiKeyCommand`, `revokeApiKeyCommand`, `deleteApiKeyCommand` | Key management, signature `(input, confirmation?)`. |
| `services/queries/api-key-queries.ts` | `listApiKeysQuery` | Keys of the active organization, without `hashedKey`. |
| `services/authenticate-api-key.ts` | `authenticateApiKey`, `ApiKeyContext`, `ApiKeyAuthResult` | Route authentication. |
| `services/api-scopes.ts` | `knownApiScopes` | Scopes declared across the registry, deduplicated. |
| `services/api-key-secret.ts` | `apiKeyPrefix`, `generateApiKey`, `hashApiKey` | Prefix, key generation, HMAC-SHA256. |
| `services/organization-api.ts` | `readOrganizationForApiKey` | Data for the example route. |
| `env.ts` | `envSchema` | `API_KEY_PEPPER` validation. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.