Skip to content

Latest commit

 

History

History
205 lines (167 loc) · 8.71 KB

api.md

File metadata and controls

205 lines (167 loc) · 8.71 KB

API

REST + JSON under /api/v1. The live OpenAPI document is at /api/docs (Swagger UI) and /api/docs/openapi.json when SWAGGER_ENABLED=true (default locally, disabled in production).

Conventions

  • Versioning: URI prefix /api/v1. Breaking changes would go to /api/v2.
  • Auth: HttpOnly cookies cst_access and cst_refresh, set by signup, login and refresh. API clients may send Authorization: Bearer <access token>. Endpoints marked "user" below need a valid access token, otherwise 401.
  • CSRF: a POST/PATCH/PUT/DELETE that carries a cookie must send an Origin (or Referer) from the allow-list (APP_URL, CORS_ORIGINS), otherwise 403. Browsers do this automatically.
  • Ownership: solve endpoints only ever see the caller's solves. Another user's solve answers 404, exactly like a missing one.
  • IDs: UUID v4. A malformed id in the path answers 400.
  • Validation: unknown body or query properties are rejected (400). Strings are trimmed and e-mails lower-cased. All validation messages are returned together.
  • Limits: JSON body 1 MB. Solve history pages hold 1 to 100 items (default 50). Trend returns 10 to 1000 points (default 200).
  • Rate limits (per client IP, per 60 s window by default): 120 requests overall (THROTTLE_LIMIT), and 10 on signup, login, verify-email, resend, forgot and reset (AUTH_THROTTLE_LIMIT). Exceeding either answers 429. Health endpoints are not limited.
  • Request id: every response carries X-Request-Id. A valid incoming id is propagated. Include it in bug reports.
  • Times are integer milliseconds. Dates are ISO 8601 UTC strings.

Error format

Every error, from validation to 500, has the same shape:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": ["timeMs must not be less than 1"],
  "path": "/api/v1/solves",
  "requestId": "4f0c2c1e-8d0e-4a35-9a51-0f3c1f8e2b7a",
  "timestamp": "2026-11-10T12:00:00.000Z"
}

message is a string, or an array of strings for validation errors. Database unique violations map to 409, check and foreign-key violations to 400, and anything unexpected to 500 with "Something went wrong" and no internals.

Types

type Puzzle = '222' | '333' | '444' | '555' | '666' | '777'
type Penalty = 'none' | 'plus2' | 'dnf'
type Stat = number | 'DNF' | null // null = not enough solves yet

interface User {
  id: string
  email: string
  username: string
  emailVerifiedAt: string | null
  createdAt: string
  updatedAt: string
}

interface Solve {
  id: string
  clientId: string
  puzzle: Puzzle
  timeMs: number // raw reading
  penalty: Penalty
  resultMs: number | null // after penalties; null for DNF
  scramble: string
  createdAt: string
  updatedAt: string
}

interface StatSet { single: Stat; mo3: Stat; ao5: Stat; ao12: Stat; ao50: Stat; ao100: Stat }

Auth

Method Path Auth Body Success Errors
POST /auth/signup – {email, username, password} 201 {user, accessTokenExpiresIn} + cookies; sends a verification e-mail 400, 409 e-mail registered, 429
POST /auth/login – {email, password} 200 {user, accessTokenExpiresIn} + cookies 401 "Email or password is incorrect", 429
POST /auth/refresh refresh cookie – 200 {user, accessTokenExpiresIn} + rotated cookies 401 (cookies cleared); reuse of a consumed token also revokes every session
POST /auth/logout refresh cookie (optional) – 204, session revoked, cookies cleared
POST /auth/logout-all user – 204, every session revoked, cookies cleared 401
POST /auth/verify-email – {token} 204 400 invalid or expired link, 429
POST /auth/verify-email/resend user – 204 401, 429
POST /auth/password/forgot – {email} 202 {message} whether or not the account exists 400, 429
POST /auth/password/reset – {token, password} 204, every session revoked 400 invalid or expired link, 429

Passwords: 8–128 characters with at least one letter and one digit. Usernames: 3–20 characters of letters, digits, ., -, _. Tokens: 20–128 characters. accessTokenExpiresIn is in seconds.

Users (current user only)

Method Path Auth Body Success Errors
GET /users/me user – 200 User 401
PATCH /users/me user {username} 200 User 400, 401
PUT /users/me/password user {currentPassword, newPassword} 204, other sessions revoked 400, 401 wrong current password
DELETE /users/me user {password} 204, account and all solves deleted, cookies cleared 401 wrong password

There is no admin surface and no endpoint that lists or reads other users.

Solves

All solve endpoints need a user. puzzle is required where listed.

Method Path Input Success Errors
GET /solves query puzzle, page (≥1, default 1), limit (1–100, default 50) 200 {items: Solve[], total, page, limit, totalPages}, newest first 400
POST /solves body {clientId, puzzle, timeMs, penalty?, scramble} 201 Solve created, or 200 Solve replay 400, 409
GET /solves/summary – 200 [{puzzle, count}] for all six puzzles
GET /solves/stats query puzzle 200 {count, dnfCount, mean, current: StatSet, best: StatSet} 400
GET /solves/trend query puzzle, limit (10–1000, default 200) 200 [{id, createdAt, resultMs, ao5, ao12}], oldest first 400
GET /solves/export query puzzle 200 text/csv attachment 400
PATCH /solves/:id body {penalty} 200 Solve 400, 404
DELETE /solves/:id – 204 400, 404
DELETE /solves query puzzle 200 {deleted} 400

Creating a solve (idempotent)

POST /api/v1/solves
Content-Type: application/json

{
  "clientId": "0b8f2f0e-4a0f-4e7a-9d65-1b2a3c4d5e6f",
  "puzzle": "333",
  "timeMs": 12345,
  "penalty": "none",
  "scramble": "R U R' U' F2 D L2 B' R2 U2"
}
  • clientId: UUID v4, generated by the client once per solve.
  • timeMs: integer, 1 to 86,400,000.
  • penalty: optional, default none.
  • scramble: up to 600 characters of space-separated WCA moves (R, Rw, 3Rw, each optionally followed by ' or 2).
Situation Response
New clientId 201 with the stored solve
Same clientId, same puzzle, time and scramble (a retry) 200 with the already stored solve; nothing is inserted
Same clientId, different puzzle, time or scramble 409 "clientId was already used for a different solve"

Retries are safe under concurrency: the unique (user_id, client_id) constraint decides. See ADR 0003.

Statistics

Rules (ADR 0007): +2 adds 2000 ms; DNF is worse than any time; mo3 is a plain mean and any DNF makes it DNF; aoN trims ceil(5% of N) results from each end (1 for ao5 and ao12, 3 for ao50, 5 for ao100), and more DNFs than that make it DNF. Averages are rounded to the nearest millisecond. mean is the mean of finished solves, or null.

Example shape (values illustrative):

{
  "count": 420,
  "dnfCount": 7,
  "mean": 21080,
  "current": { "single": 18410, "mo3": 15980, "ao5": 17450, "ao12": "DNF", "ao50": 16870, "ao100": 17390 },
  "best": { "single": 13260, "mo3": 15340, "ao5": 15550, "ao12": 16060, "ao50": 16730, "ao100": 17390 }
}

Trend points carry resultMs: null for a DNF. Rolling ao5 and ao12 are computed over the full history, so the first points of the returned window are not empty when older solves exist.

CSV export

GET /solves/export?puzzle=333 streams attachment; filename="cstimer-333-YYYY-MM-DD.csv" with Cache-Control: no-store. Rows are oldest first, read in batches of 1000, so memory stays flat for any history size.

no,puzzle,result_seconds,raw_seconds,penalty,scramble,solved_at
1,333,14.340,12.340,plus2,R U R' U',2026-09-11T08:00:00.000Z
2,333,DNF,17.260,dnf,F2 D L2,2026-09-11T08:01:00.000Z

Fields are quoted per RFC 4180. A value that starts with =, +, -, @, tab or carriage return is prefixed with ', so spreadsheet apps cannot execute it as a formula.

Health and metrics

Method Path Success
GET /health/live 200 {status: "ok", uptime} while the process serves HTTP
GET /health/ready 200 Terminus report when the database answers a ping within 1.5 s, else 503
GET /metrics (no /api prefix) Prometheus text format. Returns 404 when METRICS_ENABLED=false. nginx and Caddy return 404 for it publicly; scrape it on the private network.