[Worker auth]

API keys (pn_…), admin token, Bearer extraction, ALLOW_OPEN_KEYS, and KV validation.

Worker auth

Abstract

AXIS Worker auth is API-key based, not session cookies. Keys are created by admins (X-Admin-Token), validated via KV when bound, and used as Authorization: Bearer on script library and optionally on /api/run (usage metering).

Core helpers: frontend/worker/src/auth.ts. Key CRUD: frontend/worker/src/keys.ts.

Conceptual model

Interface surface

AuthContext

{ key: string; userId: string; tier: string }

userId is a truncated SHA-256 of the key (stable partition id).

extractBearer

  1. Authorization: Bearer <token>
  2. Else query ?key=

requireApiKey

Returns either { ok: true, ctx } or { ok: false, status, code, message }.

CodeHTTPWhen
NO_KEY401Empty
INVALID_KEY401Unknown in KV / malformed

Admin keys API (/api/keys)

ActionAuthBehavior
create (POST or ?action=create)X-Admin-Token === env.ADMIN_TOKENMint pn_ + 48 hex, store key:{key} in KV (1y TTL) with tier
validate (GET or ?action=validate)Bearer or ?key=Tier + created_at if known

Tiers: free | hobby | pro | team | enterprise.

Without ADMIN_TOKEN set, create always fails (isAdmin false).

Without KV on validate: accepts well-formed pn_[a-f0-9]{48} as hobby (dev).

ALLOW_OPEN_KEYS

wrangler.toml defaults local demos to "1":

accept any non-empty Bearer key for /api/scripts

Never leave open in production. Prefer bound API_KEYS + real admin-minted keys.

Internals

PathRole
src/auth.tsBearer, hash, requireApiKey
src/keys.tsAdmin create / validate
src/runtime.tsOptional usage increment by Bearer
src/scripts.tsrequireApiKey gate

Key format

'pn_' + 24 random bytes as hex  // 48 hex chars

Invariants & edge cases

  1. Admin token is a shared secret — rotate via wrangler secrets in production, not committed vars.
  2. KV record shape — JSON { key, tier, createdAt } under key:${apiKey}.
  3. No OAuth / cookies — PWA stores the key in plugin config (storage:cloud).
  4. Stream DO unauthenticated — public market data only.

Worked examples

Create a key (admin)

curl -sS -X POST 'http://127.0.0.1:8787/api/keys?action=create' \
  -H "X-Admin-Token: $ADMIN_TOKEN" \
  -H 'content-type: application/json' \
  -d '{"tier":"hobby"}'

Validate

curl -sS 'http://127.0.0.1:8787/api/keys?action=validate' \
  -H "Authorization: Bearer pn_…"

Failure modes

SymptomCause
403 createWrong/missing admin token
401 scriptsOpen keys off + no KV + bad shape
Cross-user leakage tests failPartition hash regression

See also