Authentication
How registration, login and token checks work, and what they are built on.
The API authenticates with a JWT signed HS256. src/auth.ts implements signing, verification and password hashing on the Web Crypto API, with no crypto dependency.
Registration#
POST /api/v1/register takes name and password. The route hashes the password with PBKDF2-SHA256, 100 000 iterations, a 16-byte random salt, and stores it as pbkdf2$<iterations>$<salt>$<hash>. It also generates a public_id with crypto.randomUUID(). A duplicate name answers 409.
Login#
POST /api/v1/login reads HTTP Basic credentials. The route loads the user, re-derives the hash and compares it in constant time. On success it signs a token with SECRET_KEY:
{
"public_id": "1b671a64-40d5-491e-99b0-da01ff1f3341",
"iat": 1764000000,
"exp": 1764001800
}The token lives 30 minutes. Verification recomputes the HMAC over the signed parts, compares it in constant time, then checks exp.
The requireUser middleware#
src/index.ts applies requireUser to every route except register, login and healthz. The middleware:
- Reads
x-access-tokensfrom the request. Missing: 403{message: "a valid token is missing"}. - Verifies the signature and expiry. Invalid: 403
{message: "token is invalid"}. - Loads the user by
public_id. Deleted: 403. - Puts the user on the Hono context for the route handler.
Choosing the secret#
SECRET_KEY comes from the environment: .dev.vars under wrangler dev, wrangler secret in production. Anyone holding the key can mint tokens for any user, so treat it like a password and rotate it by deploying a new value, which invalidates every existing token.
Why PBKDF2#
The 2021 service used werkzeug hashes (scrypt on modern versions). Workers expose no scrypt or bcrypt, so the rewrite uses PBKDF2, the hash Web Crypto provides. The stored format records its iteration count, so raising PBKDF2_ITERATIONS later lets verifyPassword still check old hashes.