API tokens
How a school's API key lets a website or script call the API as that school. The two kinds of key, the guard, the decorator, rate limits, and managing keys.
Most routes expect a signed-in person with a JWT. Some callers are machines: the school website posting an enquiry, or the public chat on that website. They send an API key instead.
A key is a school, not a person
A key proves only "I belong to this school". It carries no permissions and no user. A route that accepts keys has to do its own authorization, and the audit log names the key, not a person.
The two kinds
| Kind | Used from | Must also send | Rate limit |
|---|---|---|---|
secret (default) | A school's own server or script | Nothing else | 60 a minute per key |
publishable | A browser, such as the school website | An Origin on the key's allow-list (1 to 20 https://host entries) | 60 a minute per key, and 10 per visitor IP |
A key is sk_nly_ plus 32 random bytes. Only its SHA-256 hash and a hint like sk_nly_...a4f9 are stored, so a database leak doesn't leak working keys. A fast hash is right here: the key is already 256 bits of randomness.
What happens on a request
Read the key from the X-API-Key header, with its sk_nly_ prefix. Missing: 401 API key required.
Find it by hash among keys that aren't revoked. This lookup is deliberately unscoped: no school is known yet, because the key is what tells us. Not found: 401 Invalid API key.
Check the kind. The route says which kinds it accepts (secret only by default): 403 This key kind is not accepted here. A publishable key must come from an allowed origin: 403 Origin not allowed for this key.
Pin the school in the tenant context, exactly as the JWT guard does, so every query in the handler is scoped to it. Attach { id, name, kind } as request.apiKey for the audit log, and stamp lastUsedAt.
Rate limit, where the route adds ApiKeyRateLimitGuard. Windows live in Redis, so every API copy shares them. Over the limit: 429 Too many requests.
Opening a route to keys
@Post()
// Guards run bottom-up: the limiter needs the key the guard below verified.
@UseGuards(ApiKeyRateLimitGuard)
@ApiKeyAuth('secret', 'publishable')
@Audit({
action: ActionAuditAction.CREATE,
resource: AuditResourceType.ENQUIRY,
context: (ctx) => {
const req = ctx.switchToHttp().getRequest<Request>();
const apiKey = (req as Request & { apiKey?: ApiKeyRequestContext }).apiKey;
return apiKey ? { apiKeyId: apiKey.id, apiKeyName: apiKey.name } : {};
},
})
submit(@Body() body: CreateEnquiryDto) {
return this.enquiryService.create(body);
}@ApiKeyAuth(...kinds) does three things: marks the route @Public() (so the global JWT and permission guards stand down), binds ApiKeyGuard, and documents the X-API-Key header. With no kinds it accepts secret keys only.
Routes that accept keys today (both kinds, rate limited):
| Route | What it does |
|---|---|
POST /enquiry | Receives the website's enquiry and contact forms |
POST /public-ai/chat (publicAiChat) | Answers a message in the website's chat |
GET /public-ai/config (publicAiConfig) | Returns the chat's settings |
The clinic app has its own key system under apps/ehr.
Public means no permission checks
A valid key gets in; nothing checks whether that key may do this particular thing. Keep key routes narrow: validate the body tightly, return as little as possible, add the rate limiter, and put the key in the audit context as above so the log shows which integration acted.
Managing keys
Key management is an ordinary JWT route with permissions on api_key. The Hub screen is /staff-hub/school/api-keys.
| Route | Operation id | Needs | What it does |
|---|---|---|---|
POST /api-keys | createApiKey | create | Creates a key and returns it. The response is the only time the raw key is shown |
GET /api-keys | listApiKeys | list | Lists the school's keys, without the hash or the raw key |
PATCH /api-keys/:id/revoke | revokeApiKey | update | Stops the key working at once, and keeps the row and its history |
DELETE /api-keys/:id | deleteApiKey | delete | Soft-deletes the key. Prefer revoke |
createApiKey takes these body fields.
| Field | Required | Default | What it holds |
|---|---|---|---|
name | Yes | None | A label people recognise, such as Main website. Up to 100 characters, not empty |
kind | No | secret | secret or publishable |
allowedOrigins | For a publishable key | An empty list | The exact origins a publishable key works from, 1 to 20 entries. Lowercased when stored. Must be empty for a secret key |
The key routes return these errors.
| Condition | Response |
|---|---|
| A secret key is created with origins | A secret key has no origins |
| A publishable key is created with no origins, more than 20, or a badly formed one | A publishable key needs 1 to 20 origins like https://www.school.ac.ug |
revokeApiKey names an id that does not exist | A repository error, Entity not found, rather than a clean 404 |
deleteApiKey names an id that does not exist | No error. The answer is still "API key deleted" |
Gotchas
- The key is shown once. Only the hash is stored, so there's no "show again". Lost keys are revoked and replaced.
- Header, not bearer.
X-API-Key, with thesk_nly_prefix. Without the prefix the hash differs and you get a 401. - Don't scope the lookup.
verifyruns unscoped on purpose; scoping it would break every key. - Guard order matters. Put
@UseGuards(ApiKeyRateLimitGuard)above@ApiKeyAuth(...), so the key is verified before it's counted.
Where to go next
User lifecycle
The transaction that creates a user and its profile together, plus suspend, soft-delete cascade, seeding, and the sharp edges to watch for.
Secrets and credentials
How the API handles secrets, the key names that matter, the Zod fail-fast boundary, and the one rule that keeps real values out of git.