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 throughgetOrgContext(), 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
APIchannel 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.
API_KEY_PEPPER secret in every environment.
Requirements
Install and remove
- Existing project
- New project
1
Add the module
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
--no-install, also run npm run db:generate.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.tsrejects a missing value, a value shorter than 32 characters and, withNODE_ENV=production, the example value from.env.example. Generate one withopenssl rand -base64 32and 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). 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
{ 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 globaladmin 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 calltrackAudit 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
- Lookup. The function hashes the token and finds the row by the unique
hashedKey, insidewithoutTenantScope("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 inapiScopes, the route always returns 403. lastUsedAt. After success the function updateslastUsedAtin the background without awaiting it. A failed update is only logged.- Organization.
context.organizationIdcomes from the key row. Headers and parameters can’t change it.
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’sservices/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 ownorganizationId.
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, sokeymust match the folder name. The kit usesresource:operationnames such asorganization:read. - Who reads.
knownApiScopes()(server registry) for validation in the create command and filtering inauthenticateApiKey; the/api-keysform (client registry) for checkboxes and labels. - When it applies. A new
module.tsenters the registry afternpx gato generate; a new entry in an existingapiScopesarray 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
scopescolumn and shows as a raw string. - Duplicates. Don’t declare another module’s scope: the form would show two checkboxes for it.
- Without
api-keysthe field type-checks and does nothing.
Use it from your code
The examples below come from adeliveries 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
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
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 noOrgContext, so auditActor doesn’t apply. Build the event from the key context:
src/features/deliveries/services/delivery-api.ts
/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:
Code that works without the module
AnapiScopes 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
authenticateApiKeyis 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
displayPrefixand an HMAC. Cache-Control: no-storeon 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 exportedGET 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
POSTwith another organization’sorganizationIdin the body (stored in the key’s organization, audit entry withchannel: "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 andtrackAudit.
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.