-
Notifications
You must be signed in to change notification settings - Fork 0
Tier-4 #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Tier-4 #5
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
760279f
Implement JWT authentication and API key management features
Hum2a 6e72b90
Implement rate limiting, session caching, and structured logging feat…
Hum2a 09c1b39
Update SCALE.md with KV deployment instructions and Cloudflare API to…
Hum2a f3e95c3
replaced placeholder id
Hum2a 892d7e2
converted to free features
Hum2a cbe5730
Enhance testing and deployment processes
Hum2a 3d199d5
Refactor session caching and validation logic
Hum2a e7b00df
Implement PWA features, i18n support, and scorecard export functionality
Hum2a b4b02f2
Enhance FileField component with custom file input button and tooltip…
Hum2a 796efd1
Merge pull request #2 from Hum2a:tier-7
Hum2a 3a9f531
Merge pull request #3 from Hum2a:tier-6
Hum2a 85c2198
Merge pull request #4 from Hum2a:tier-5
Hum2a File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| --- | ||
| description: JWT auth, API keys, owner switcher, RLS upgrade path | ||
| globs: "apps/{api,web}/src/**/*.{ts,tsx}" | ||
| --- | ||
| # Auth & multi-tenant (Tier 4) | ||
|
|
||
| ## Request principal | ||
|
|
||
| Resolve order in `resolvePrincipal()`: | ||
|
|
||
| 1. `Authorization: Bearer` JWT (or `?token=` for WebSocket) | ||
| 2. `x-oche-owner` / `?key=` API key (demo, env JSON, or `api_keys` table) | ||
|
|
||
| Every DB call still uses `withPrincipal(db, ownerId, fn)` until Neon JWT RLS is enabled — see docs/AUTH.md. | ||
|
|
||
| ## Secrets | ||
|
|
||
| - `OCHE_JWT_SECRET` — Wrangler secret per env; never in the SPA bundle. | ||
| - API keys stored **hashed** (SHA-256) in `api_keys`; plaintext returned once on create. | ||
| - Demo keys (`demo-key-a/b`) remain for RLS isolation demos. | ||
|
|
||
| ## SPA | ||
|
|
||
| - Use `AuthProvider` + `useAuth()`; never hardcode `demo-key-a` in `api.ts`. | ||
| - Owner switcher invalidates TanStack Query cache on venue change. | ||
| - API key UI at `/settings/keys`. | ||
|
|
||
| ## Adding auth to a new route | ||
|
|
||
| ```typescript | ||
| const ownerId = await resolvePrincipal(c, getDb(c.env)); | ||
| if (!ownerId) return c.json({ error: 'Unauthorised' }, 401); | ||
| ``` | ||
|
|
||
| ## Neon upgrade | ||
|
|
||
| Document only in take-home — do not drop GUC policies without migration plan. Reference: `docs/examples/neon-jwt-rls.sql`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| --- | ||
| description: Scale, caching, rate limits, observability | ||
| globs: "apps/api/**/*.ts" | ||
| --- | ||
| # Scale & reliability (Tier 5) | ||
|
|
||
| ## Rate limiting | ||
|
|
||
| - Use `RateLimiter` Durable Object (`RATE_LIMITER` binding) — one DO per IP. | ||
| - Do not reintroduce global in-memory Maps for production limits. | ||
| - Exempt `/health` and `/openapi.json` from rate limit. | ||
|
|
||
| ## Session list cache | ||
|
|
||
| - Cache only `GET /sessions` via `lib/session-cache.ts` + `CACHE` KV. | ||
| - TTL 60s in KV (Cloudflare minimum); HTTP `max-age=15`; invalidate with `bumpSessionListCache()` on `POST` / `PATCH`. | ||
| - Set `X-Cache: HIT|MISS` on list responses. | ||
|
|
||
| ## Logging | ||
|
|
||
| - Use `logInfo` / `logWarn` / `logError` from `lib/logger.ts` — JSON only, no raw `console.log` in routes. | ||
| - Every response gets `X-Trace-Id`; include `traceId` in 500 JSON body. | ||
|
|
||
| ## Health | ||
|
|
||
| - Shallow: `GET /health` (no DB). | ||
| - Readiness: `GET /health?deep=1` — `select 1`; return 503 if DB unreachable. | ||
|
|
||
| ## Docs | ||
|
|
||
| [docs/SCALE.md](../../docs/SCALE.md) · queue/transcode pipeline in [docs/MEDIA.md](../../docs/MEDIA.md) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| --- | ||
| description: Testing, contracts, visual regression, deploy DX | ||
| globs: "{apps/web,tests}/**/*.{ts,tsx}" | ||
| --- | ||
| # Quality & DX (Tier 6) | ||
|
|
||
| ## SPA component tests | ||
|
|
||
| - Use **Vitest + Testing Library** in `apps/web/src/**/*.test.tsx` (jsdom). | ||
| - Mock `@/lib/api` and hooks; wrap with `QueryClientProvider` (+ `MemoryRouter` when routing matters). | ||
| - Mock `@number-flow/react` in `apps/web/src/test/setup.ts`. | ||
|
|
||
| ## Contract tests | ||
|
|
||
| - `tests/contracts/` — OpenAPI paths must match homework + `@oche/shared` Zod schemas stay aligned. | ||
| - Run: `npm run test:contracts` | ||
|
|
||
| ## Visual regression | ||
|
|
||
| - Playwright `@visual` tests in `tests/e2e/visual.spec.ts`; snapshots under `tests/e2e/__snapshots__/`. | ||
| - Run: `npm run test:visual` · update baselines: `npx playwright test --grep @visual --update-snapshots` | ||
|
|
||
| ## Deploy | ||
|
|
||
| - **Staging full pipeline:** `npm run deploy:staging:full` (migrate → force-rls → rls check → seed → deploy). | ||
|
|
||
| ## Wrangler | ||
|
|
||
| - Project uses **Wrangler 4** (`apps/api`, `apps/web`). Run wrangler from `apps/api` for API/KV/DO commands. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| --- | ||
| description: PWA, i18n, scorecard export, analytics, API docs (Tier 7) | ||
| globs: "{apps/web,scripts}/**/*.{ts,tsx,mjs,html,json,svg}" | ||
| --- | ||
| # Nice extras (Tier 7) | ||
|
|
||
| ## PWA / offline read-only | ||
|
|
||
| - **vite-plugin-pwa** in `apps/web/vite.config.ts` — Workbox `NetworkFirst` for GET `/sessions*`. | ||
| - **React Query persistence** — `PersistQueryClientProvider` in `main.tsx`; keys `sessions` + `session` only. | ||
| - **Offline banner** — `OfflineBanner` in `App.tsx`; hide upload/mutations when offline. | ||
| - Mutations stay `networkMode: 'online'` — no offline score edits. | ||
|
|
||
| ## Scorecard export | ||
|
|
||
| - `apps/web/src/lib/export-scorecard.ts` — print-ready HTML → browser Save as PDF. | ||
| - Button on `SessionDetail` header only (history detail). | ||
|
|
||
| ## i18n | ||
|
|
||
| - **i18next** + single `en` locale: `apps/web/src/i18n/`. | ||
| - Nav + session detail + scorecard labels use `useTranslation()`. | ||
| - Game guides / field tooltips stay English in source files until a second locale ships. | ||
|
|
||
| ## Analytics | ||
|
|
||
| - Optional `VITE_PLAUSIBLE_DOMAIN` or `VITE_CF_WEB_ANALYTICS_TOKEN` — `initAnalytics()` in `main.tsx`. | ||
| - No custom events with session IDs or PII. | ||
|
|
||
| ## OpenAPI docs | ||
|
|
||
| - Source: `apps/api/src/openapi/spec.ts` → `npm run export:openapi` → `apps/web/public/openapi.json`. | ||
| - Static Redoc: `/docs/` (`apps/web/public/docs/index.html`). | ||
| - Live JSON also at `{API}/openapi.json`. | ||
|
|
||
| Human index: [docs/EXTRAS.md](../../docs/EXTRAS.md) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
| import { createApp } from '../app.js'; | ||
| import type { Env } from '../env.js'; | ||
|
|
||
| vi.mock('../lib/db.js', () => ({ | ||
| getDb: vi.fn(() => ({ | ||
| execute: vi.fn(async () => [{ ok: 1 }]), | ||
| })), | ||
| getConnectionString: vi.fn(), | ||
| })); | ||
|
|
||
| function mockEnv(): Env { | ||
| return { | ||
| DATABASE_URL: 'postgresql://test', | ||
| APP_ORIGIN: 'http://localhost:5173', | ||
| ENVIRONMENT: 'development', | ||
| SESSION_ROOM: { | ||
| idFromName: () => ({ fetch: vi.fn(async () => new Response('{}')) }), | ||
| } as unknown as Env['SESSION_ROOM'], | ||
| MEDIA: {} as Env['MEDIA'], | ||
| }; | ||
| } | ||
|
|
||
| describe('health', () => { | ||
| it('GET /health returns liveness', async () => { | ||
| const app = createApp(); | ||
| const res = await app.request('/health', {}, mockEnv()); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ ok: true, env: 'development' }); | ||
| expect(res.headers.get('X-Trace-Id')).toBeTruthy(); | ||
| }); | ||
|
|
||
| it('GET /health?deep=1 pings the database', async () => { | ||
| const app = createApp(); | ||
| const res = await app.request('/health?deep=1', {}, mockEnv()); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ ok: true, db: 'ok' }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { describe, expect, it } from 'vitest'; | ||
| import { signJwt, verifyJwt } from '../lib/jwt.js'; | ||
|
|
||
| describe('jwt', () => { | ||
| const secret = 'test-jwt-secret'; | ||
|
|
||
| it('signs and verifies a token', async () => { | ||
| const sub = '11111111-1111-1111-1111-111111111111'; | ||
| const token = await signJwt(sub, secret, 60); | ||
| const payload = await verifyJwt(token, secret); | ||
| expect(payload).toEqual({ sub }); | ||
| }); | ||
|
|
||
| it('rejects tampered tokens', async () => { | ||
| const token = await signJwt('11111111-1111-1111-1111-111111111111', secret, 60); | ||
| const bad = `${token}x`; | ||
| expect(await verifyJwt(bad, secret)).toBeNull(); | ||
| }); | ||
|
|
||
| it('rejects expired tokens', async () => { | ||
| const token = await signJwt('11111111-1111-1111-1111-111111111111', secret, -1); | ||
| expect(await verifyJwt(token, secret)).toBeNull(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import { describe, expect, it } from 'vitest'; | ||
| import { RateLimiter } from '../rate-limiter.js'; | ||
|
|
||
| describe('RateLimiter', () => { | ||
| it('allows requests within the bucket', async () => { | ||
| const storage = new Map<string, unknown>(); | ||
| const ctx = { | ||
| storage: { | ||
| get: async (k: string) => storage.get(k), | ||
| put: async (k: string, v: unknown) => storage.set(k, v), | ||
| }, | ||
| }; | ||
| const limiter = new RateLimiter(ctx as never, {} as never); | ||
|
|
||
| const res = await limiter.fetch( | ||
| new Request('https://rate-limiter/check', { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/json' }, | ||
| body: JSON.stringify({ limit: 2, windowMs: 60_000 }), | ||
| }), | ||
| ); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ allowed: true, remaining: 1 }); | ||
| }); | ||
|
|
||
| it('returns 429 when bucket is empty', async () => { | ||
| const storage = new Map<string, unknown>([['bucket', { tokens: 0, ts: Date.now() }]]); | ||
| const ctx = { | ||
| storage: { | ||
| get: async (k: string) => storage.get(k), | ||
| put: async (k: string, v: unknown) => storage.set(k, v), | ||
| }, | ||
| }; | ||
| const limiter = new RateLimiter(ctx as never, {} as never); | ||
|
|
||
| const res = await limiter.fetch( | ||
| new Request('https://rate-limiter/check', { | ||
| method: 'POST', | ||
| body: JSON.stringify({ limit: 60, windowMs: 60_000 }), | ||
| }), | ||
| ); | ||
| expect(res.status).toBe(429); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: This rule now documents that
RateLimitermust be SQLite-backed, but theglobsfield still only targetssession-room.ts. The rule won't activate when editingrate-limiter.ts, so future changes there can miss the SQLite constraint. Update the globs to include both files.Prompt for AI agents