Naalya Handbook

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

KindUsed fromMust also sendRate limit
secret (default)A school's own server or scriptNothing else60 a minute per key
publishableA browser, such as the school websiteAn 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

apps/server/src/app/enquiry/enquiry.controller.ts
@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):

RouteWhat it does
POST /enquiryReceives 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.

RouteOperation idNeedsWhat it does
POST /api-keyscreateApiKeycreateCreates a key and returns it. The response is the only time the raw key is shown
GET /api-keyslistApiKeyslistLists the school's keys, without the hash or the raw key
PATCH /api-keys/:id/revokerevokeApiKeyupdateStops the key working at once, and keeps the row and its history
DELETE /api-keys/:iddeleteApiKeydeleteSoft-deletes the key. Prefer revoke

createApiKey takes these body fields.

FieldRequiredDefaultWhat it holds
nameYesNoneA label people recognise, such as Main website. Up to 100 characters, not empty
kindNosecretsecret or publishable
allowedOriginsFor a publishable keyAn empty listThe 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.

ConditionResponse
A secret key is created with originsA secret key has no origins
A publishable key is created with no origins, more than 20, or a badly formed oneA publishable key needs 1 to 20 origins like https://www.school.ac.ug
revokeApiKey names an id that does not existA repository error, Entity not found, rather than a clean 404
deleteApiKey names an id that does not existNo 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 the sk_nly_ prefix. Without the prefix the hash differs and you get a 401.
  • Don't scope the lookup. verify runs 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

On this page