Skip to main content
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

Install and remove

1

Add the module

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:
.env
3

Create the migration

Commit it. After --no-install, also run npm run db:generate.
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.
  • 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 the module adds

Module definition

The ApiKey model

prisma/schema/api-keys.prisma, table api_keys: 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

src/app/api/v1/organization/route.ts
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.

Audit events

Key commands call trackAudit with ...auditActor(context) after a successful write: Events never contain the key or its hash and use the WEB channel. Without audit-logs they’re recorded nowhere.

The authenticateApiKey contract

src/features/api-keys/services/authenticate-api-key.ts
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:
  • 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.
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. 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

src/features/deliveries/module.ts
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

src/app/api/v1/deliveries/route.ts
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:
src/features/deliveries/services/delivery-api.ts

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:
src/features/deliveries/services/delivery-api.ts
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.

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:
Expected responses:

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.
src/features/deliveries/services/__tests__/deliveries-route.integration.test.ts
  • 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.
  • 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

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

Routes

Scopes and audit actions

Files