Commit Graph
62 Commits
Author SHA1 Message Date
Lucas Berger 9b62887f0f feat(20-03): unify member editor + declutter admin members panel
- playwright-cli verified: Members tab shows tappable rows, no retired buttons
- Row tap opens 'Edit member' sheet; per-section saves keep sheet open
- 'Add member' trigger opens 'Add member' sheet in create mode
- Profile save fires 'Profile saved.' toast; sheet stays open (D-05)
- eslint + prettier + typecheck + vitest (275 tests) all pass
- Fix pre-existing prettier drift in docs/*, CLAUDE.md, README.md, api/admin.ts
2026-06-18 17:39:00 -04:00
Lucas Berger bc48632756 feat(20-01): add PATCH /members/:id member-profile update with last-admin guard
- Add isAdmin field to GET /members select and mapped member object (D-02)
- Add updateMemberSchema (displayName optional string, isAdmin optional boolean)
- Register adminRouter.patch('/members/:id') with noEchoHook and requireAdmin (inherited)
- Handler: parsePositiveIntParam id validation (400), existence check (404),
  D-03 last-admin guard via COUNT(*) query (409), partial set() update (200)
- Fix Test D: switch to adminId2 for GET after self-demotion (adminId1 no longer admin)
- All 44 tests green including 7 new PATCH/isAdmin tests
2026-06-18 17:19:43 -04:00
Lucas Berger a0a82ac9b6 test(20-01): add failing tests for member-profile update + last-admin guard + isAdmin read
- Test A: PATCH displayName happy path → 200, GET reflects change
- Test B: PATCH isAdmin promote → 200, GET shows isAdmin true
- Test C: last-admin guard → 409 when only admin demotes self
- Test D: self-demotion → 200 when second admin exists
- Test E: non-admin PATCH → 403 (requireAdmin boundary)
- Test F: wrong-type body → 400 { error: "Invalid request" }; malformed :id → 400
- Test G: non-existent member id → 404
- Test H: GET /members includes boolean isAdmin per member
All 7 new tests fail RED for the right reasons (route 404 / isAdmin missing)
2026-06-18 17:18:14 -04:00
Lucas BergerandClaude Opus 4.8 b6490feff4 fix(19): satisfy CI fast-checks + secret scan
CI / changes (pull_request) Successful in 9s
CI / api (pull_request) Successful in 3m2s
CI / fast-checks (pull_request) Successful in 4m20s
CI / security (pull_request) Successful in 1m14s
CI / harness (pull_request) Successful in 6m56s
CI / gate (pull_request) Successful in 2s
Lint (eslint --max-warnings 0):
- index.ts: disable no-unsafe-argument on the type-only Context mismatch when
  delegating to the OIDC handler inside the local-session skip wrapper
- localAuth.ts: handleLogout is sync (no await) — drop async (require-await)
- devBypass.ts: disable detect-possible-timing-attacks on the public well-known
  dev-placeholder string compare (not a secret comparison)
- remove dead code / unused bindings flagged by no-unused-vars: makeTestApp
  (localSession.test), makeUnauthContext + BrowserContext import (login.spec),
  unused memberId (admin.test), unused txSelectCount counter (me.test)
- localAuthMiddleware.test / me.test: fix unused + reflow-detached
  eslint-disable directives

Format: prettier --write across the 20 Phase-19 files that were never formatted.

Secret scan (gitleaks): allowlist two false positives — the synthetic >=32-char
TEST_SECRET in localSession.test.ts, and .planning/ design prose (a generic-api-key
regex hit on "credential atomically, 409-equivalent"). Neither is a real secret.

Verified locally: format:check, lint, typecheck, md:lint, gitleaks (no leaks),
PWA 266/266, API 452/452.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 23:05:15 -04:00
Lucas Berger 4bd6b2c057 fix(19): WR-05 add no-echo tests for admin create-member and me password hook sites 2026-06-17 20:33:46 -04:00
Lucas Berger 32bdd1e92d fix(19): WR-07 reject route ids with trailing garbage via strict integer parse 2026-06-17 20:32:26 -04:00
Lucas Berger 30ad25c026 fix(19): WR-03 make scrypt hashing async (threadpool) to avoid event-loop starvation DoS 2026-06-17 20:30:28 -04:00
Lucas Berger b083cb7193 fix(19): CR-04 scope login lockout to username, add TTL auto-expiry + admin-reset unlock 2026-06-17 20:20:43 -04:00
Lucas Berger 6ef8e03f8c fix(19): CR-03 return 403 for wrong current password so change-password does not log user out 2026-06-17 20:17:32 -04:00
Lucas Berger 1f94dc5eb7 feat(19-05): global-setup local_credentials seed + login.spec.ts + CI harness env
- global-setup.ts: TRUNCATE local_credentials + seed devuser/devpass (PHC scrypt inline)
- Create login.spec.ts: real-login-form e2e (gate redirect, wrong-password error, correct login)
- ci.yml: add LOCAL_SESSION_SECRET dev value + local_credentials seed step in harness job
- Fix all test mocks: add devSessionCookieMiddleware no-op to vi.mock(devBypass.js) blocks
  in admin/setup/push/lists/localAuth/authMode/requireAdmin tests (Rule 1 - Bug: missing export)
- Full API suite: 446/446 tests pass; pnpm typecheck: exit 0
2026-06-17 17:21:05 -04:00
Lucas Berger db66295920 test(19-03): add failing tests for POST /api/auth/local/login + logout
- RED: 8 tests for login success, wrong-password 401, unknown-username 401 (no enumeration), rate-limit 429, lockout 423, logout cookie clear, no-echo 400
2026-06-17 16:49:51 -04:00
Lucas Berger ac32bd405f test(19-03): add failing tests for localAuthMiddleware and GET /api/auth/mode
- RED: 8 tests failing (modules not yet created)
- localAuthMiddleware: 4 tests for cookie→user shape, no-cookie passthrough, missing user row, devAuthBypass coexistence
- authMode: 3 tests for mode response with no oidc, env oidc, app_config oidc
2026-06-17 16:48:07 -04:00
Lucas Berger 8ced2d0a20 test(19-02): add failing tests for linkOidcToUser and POST /api/me/link-oidc
RED phase for Task 3:
- Test 1: linkOidcToUser updates users.oidc_iss/sub and deletes local_credentials
- Test 2: linkOidcToUser throws OidcLinkConflictError on conflict, no local_cred deletion
- Test 3: POST /api/me/link-oidc returns initiation payload (state / authorizationUrl)
2026-06-17 16:35:19 -04:00
Lucas Berger 80b5906bb8 test(19-02): add failing tests for self-change password and hasLocalCredential on /api/me
RED phase for Task 2:
- Test 1: POST /api/me/password correct current → 200, new hash verifies newPassword
- Test 2: wrong currentPassword → 401, UPDATE not called (hash unchanged)
- Test 3: no local_credentials row → 404
- Test 4 (GET /api/me): hasLocalCredential:true/false based on local_credentials existence
2026-06-17 16:32:48 -04:00
Lucas Berger b2c7902e9e test(19-02): add failing tests for admin create-member, reset-password, hasLocalCredential
RED phase for Task 1:
- Test 1: POST /api/admin/members creates users row + local_credentials, hash verifies
- Test 2: duplicate username returns 409, transaction rolled back (no orphaned user row)
- Test 3: admin reset password updates hash, old password no longer verifies
- Test 4: non-admin gets 403 on both POST /members and POST /members/:id/password
- Test 5: GET /api/admin/members returns hasLocalCredential:true/false per local cred existence
2026-06-17 16:29:43 -04:00
Lucas BergerandClaude Opus 4.8 a193bc8236 fix(12): satisfy CI fast-checks — lint unused vars, typed contract-test body, prettier
CI / changes (pull_request) Successful in 3s
CI / fast-checks (pull_request) Successful in 2m16s
CI / api (pull_request) Failing after 1m37s
CI / harness (pull_request) Failing after 1h3m45s
CI / security (pull_request) Failing after 11s
CI / gate (pull_request) Failing after 1s
- Remove unused 'res'/'container' assignments (no-unused-vars)
- setupClient.contract.test.ts: typed parseSentBody helper + non-async json mock
  (no-unsafe-*/require-await)
- Prettier format 7 setup files

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:53:14 -04:00
Lucas Berger fbd3b77bde feat(12-06): expose non-secret DB name via GET /api/setup/status (gap 3)
- status returns { setupComplete, dbName } from process.env.DB_NAME (null fallback)
- only the DB name; never DB_HOST/DB_USER/DB_PASSWORD
- SetupStatusResponse carries dbName?: string | null for the PWA read-only field
2026-06-15 21:13:47 -04:00
Lucas Berger e9d07b38fb test(12-06): add failing tests for vapid public-key equality assertion (gap 2)
- mismatched submitted key (BH123) → 400, no VAPID_PRIVATE_KEY leak
- absent app_config.vapid_public_key row → 400
- happy path seeds matching app_config row
2026-06-15 21:11:41 -04:00
Lucas BergerandClaude Sonnet 4.6 687f9dc9fa fix(12): WR-01 narrow TOCTOU guard and set claimed=true for OIDC inserts
- apps/api/src/auth/user.ts: upsertUser step-5 insert now sets claimed=true
  for all OIDC-created users. An identity-bound OIDC user is never a pending
  wizard bootstrap user; explicit claimed=true prevents ambiguity with the
  (oidcIss IS NULL AND claimed=false) sentinel used by the TOCTOU guard and
  isSetupLocked. First-login-claims path is unaffected (it updates a
  pre-existing oidcIss=null row; this change only touches the fresh insert).

- apps/api/src/routes/setup.ts: TOCTOU guard in POST /credential now queries
  WHERE oidc_iss IS NULL AND claimed = false FOR UPDATE, matching the exact
  definition of a pending wizard bootstrap user. This provides defense-in-depth
  against any future path that could produce claimed=false OIDC rows.

- apps/api/tests/auth/user.test.ts: new WR-01 test asserts that the fresh
  OIDC insert sets claimed=true in the values passed to db.insert().

- apps/api/tests/routes/setup.test.ts: new WR-01 integration test seeds an
  OIDC user with claimed=false (oidcIss NOT NULL) and verifies POST /credential
  still succeeds (guard ignores the OIDC row, only counts local wizard rows).

All 402 API tests, 253 PWA tests, and typecheck pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 16:46:41 -04:00
Lucas BergerandClaude Sonnet 4.6 61a869ca7d fix(12): CR-01 guard effective-config branch during wizard in-progress
isSetupLocked() now checks for an unclaimed local wizard user
(oidcIss IS NULL, claimed=false) before firing the effective-config
branch. During the credential→complete window, this sentinel prevents
a production container with VAPID env set from blocking POST /complete
with 423. The explicit setup_complete flag (Check 1) still locks
unconditionally once written. Adds regression test that sets VAPID env
explicitly (no beforeEach clearing) to reproduce the production scenario.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 16:36:52 -04:00
Lucas BergerandClaude Sonnet 4.6 3babbfa20e fix(12): IN-02 guard /setup/complete against skipping the credential step
Without a prerequisite check, an operator could call POST /api/setup/complete
directly, setting setup_complete=true with no admin user or credential row,
leaving no recovery path without manual DB surgery.

Add an inner join check for an unclaimed user with an associated credential;
return 422 if absent. Update /complete tests to seed the prerequisite for
the success path and add an explicit 422 regression test.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 16:20:55 -04:00
Lucas Berger 67a9d29dc1 feat(12-02): OIDC boot env-OR-app_config fallback + pre-auth mount verification
- A2 CONFIRMED: @hono/oidc-auth reads OIDC_ISSUER/OIDC_CLIENT_ID/OIDC_AUTH_EXTERNAL_URL
  at per-request call time (env(c) → process.env), NOT at import time — fresh instance
  boots cleanly without OIDC env vars
- Implement oidcConfigFallbackMiddleware in auth/middleware.ts: reads OIDC_ISSUER,
  OIDC_CLIENT_ID, OIDC_AUTH_EXTERNAL_URL from app_config when process.env is absent,
  injects into process.env before oidcAuthMiddleware() reads it (D-02/D-03/Recommendation a)
- Mount oidcConfigFallbackMiddleware before oidcAuthMiddleware() in index.ts so
  wizard-configured instances work before a container restart
- Verify /api/setup mount order: line 49 < devAuthBypass line 54 (T-12-09/Pitfall 1)
- Fix push.test.ts vi.doMock for middleware.js: add oidcConfigFallbackMiddleware stub
- 394 tests pass | 5 todo (D-08 RED scaffolds); typecheck clean
2026-06-15 14:03:15 -04:00
Lucas Berger 4748d578e7 test(12-02): isSetupLocked() real impl + RED-first setup route tests
- Implement real isSetupLocked() in setupGuard.ts: reads app_config.setup_complete
  (returns true if value==='true'); else checks member_credentials row + VAPID env
  for effective-config branch (D-10)
- Re-queries DB fresh every call — no module-level cache (D-10/Pitfall 8)
- Convert Wave-0 it.todo() scaffolds into real integration tests (17 tests RED)
- RED-first 423 guard test: POST /complete twice → first 200, second 423 (Pitfall 8)
- D-10 effective-config tests: 423 when credRow AND VAPID env; NOT 423 otherwise
- 2 'does NOT return 423' tests pass (404 ≠ 423); all others RED pending Task 2 router
2026-06-15 13:53:53 -04:00
Lucas Berger e098be3929 test(12-01): Wave-0 test scaffolds — setup.test.ts + user.test.ts (RED)
- Add apps/api/tests/routes/setup.test.ts with it.todo() scaffolds for:
  SETUP-01 (GET /api/setup/status), SETUP-02 (validate/vapid + validate/oidc),
  SETUP-01 (POST /api/setup/credential), SETUP-04 (POST /api/setup/complete
  × 2 → first 200, second 423), D-10 effective-config 423 guard.
  All 15 cases RED (it.todo) so Plan 02 implements against real failing tests.
- Extend apps/api/tests/auth/user.test.ts with D-08 first-login-claims describe
  block (5 it.todo() cases): unclaimed user bind, is_admin preservation,
  setup_complete=false fallthrough, no unclaimed fallthrough, no email lookup (D-10)
- Suite collects clean: 375 passed | 20 todo — no import errors
2026-06-15 13:43:47 -04:00
Lucas BergerandClaude Opus 4.8 93217b58fe fix(18): WR-02 derive seed flag from DB write, not a stale pre-flight SELECT
The seed handler computed seeded from a pre-flight SELECT then returned
seeded:!alreadySet. Under a genuine concurrent race both requests can
SELECT the empty table, both enter the insert branch, and both return
seeded:true though only one row was actually written. Replace the
SELECT + conditional onDuplicateKeyUpdate with a single INSERT IGNORE
and derive seeded from affectedRows (1 = inserted, 0 = ignored/existing
row preserved, D-03). On MariaDB onDuplicateKeyUpdate(value=value)
reports affectedRows 1 for both insert and no-op, so it cannot
distinguish them; INSERT IGNORE can. timezone is bound via a
parameterized sql template and is already IANA-validated by zod. Adds a
test asserting seeded:false for a directly-pre-inserted row.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 07:41:52 -04:00
Lucas Berger bda31a33bd fix(18): make timezone seed idempotent under concurrent race (WR-02)
- Import sql from drizzle-orm in admin.ts
- Add onDuplicateKeyUpdate({ set: { value: sql\`value\` } }) to the
  conditional INSERT in POST /config/timezone/seed so a concurrent seed
  (or seed racing a PUT) cannot 500 on the app_config.key PK constraint
- Existing value is preserved per D-03 no-overwrite (no-op ODKU)
- seeded flag still reflects the pre-flight SELECT (winner: true, loser: false)
- Add tests: 403 access control, seeded:true on first seed, seeded:false
  on second seed without throw (WR-02 idempotent race)
2026-06-14 22:56:18 -04:00
Lucas Berger f109b3cf38 test(18-02): add failing integration tests for admin timezone endpoints
- describe('admin timezone config') covers 8 cases:
  - GET and PUT 403 for non-admin authenticated user (T-18-03)
  - GET with no stored row returns 200 with isExplicitlySet: false
  - PUT America/Chicago then GET round-trip with isExplicitlySet: true
  - PUT UTC returns 200 (Pitfall 2)
  - PUT Not/AZone returns 400 and does not write to app_config (T-18-04)
  - POST seed when unset stores the value (D-02)
  - POST seed when already set does NOT overwrite (D-03)
- appConfig imported from db/schema for per-test cleanup
- afterEach removes household_timezone row to prevent test bleed
- 6 new cases FAIL (404 — endpoints not yet implemented); 19 existing pass
2026-06-14 22:11:05 -04:00
Lucas Berger 30b8c9643a test(11-05): RED — WR-02 reminderLeadMinutes max(10080) in both Zod schemas
- outboxPayloadSchema: 10081 must hard-fail the row (currently dispatches)
- eventFieldsSchema: POST /create with 10081 must 400 (currently 202)
- boundary 10080 and null pass (already correct, no test fails expected)
2026-06-14 08:21:44 -04:00
Lucas Berger 2f347cbd98 fix(10): guard shared-calendar designation against non-existent target (CR-01)
PUT /api/admin/calendars/:id/shared cleared the current shared calendar then
set the target in two non-transactional UPDATEs without checking the target
exists — a bad/stale id wiped the family shared lane and still returned ok.
Verify the target inside a transaction; return 404 when absent. Adds a
regression test (RED→GREEN).
2026-06-13 15:38:35 -04:00
Lucas Berger 79fe3e0e04 fix(10-04): prettier format + remove unnecessary type assertions
- Run prettier on all new/modified PWA files (CredentialSheet, SetupBanner, AdminPage, admin.spec.ts)
- Remove unnecessary 'as React.RefObject<HTMLElement | null>' casts flagged by @typescript-eslint/no-unnecessary-type-assertion
- Format pre-existing API files from Plans 02/03 (me.ts, user.test.ts, requireAdmin.test.ts, me.test.ts)
- All 270 API tests + 191 PWA vitest tests pass; lint/typecheck/build clean
2026-06-13 15:22:50 -04:00
Lucas Berger 037a7ed4c1 test(10-03): add RED tests for adminRouter guard, credential no-echo, shared-calendar, self-service
RED phase: all admin.test.ts tests fail (404 — routes/mounts not yet created).
Tests cover:
- T-10-08 Pitfall 9: 403 for non-admin on every /api/admin/* route
- T-10-09 Pitfall 7: 400 with no echoed password for all credential failure modes
  (PROPFIND/auth failure, createFastmailClient throw, network error, schema mismatch)
- T-10-11: valid credential stores encrypted (AES-256-GCM), not plaintext
- ADMIN-02: PUT /api/admin/calendars/:id/shared — exclusive is_shared=1
- T-10-12 Pitfall 6: POST /api/me/credential ignores body userId, writes to session user
- D-07: non-admin member can POST /api/me/credential (no requireAdmin on self-service)
2026-06-13 14:49:35 -04:00
Lucas Berger e5889df03e test(10-02): add failing /api/me isAdmin+needsProviderSetup tests (RED)
- dev-bypass path: isAdmin from DB (not hardcoded), needsProviderSetup from member_credentials
- needsProviderSetup=true when no member_credentials row exists
- needsProviderSetup=false when member_credentials row exists
2026-06-13 14:36:45 -04:00
Lucas Berger 982438dc10 style(13-03): apply Prettier formatting across repo
Mechanical reformat — no logic changes. 398 files changed, 19125
insertions(+), 16457 deletions(-). Prettier 3.8.4 with .prettierrc
(singleQuote:true, semi:true, tabWidth:2, trailingComma:all,
printWidth:100). Isolated per D-13-08 for reviewability.
2026-06-11 20:35:18 -04:00
Lucas Berger 03e953158a fix(13-02): eliminate all ESLint violations — pnpm lint exits 0
- eslint.config.js: disable React Compiler rules (v7 flat.recommended enables
  them; codebase does not use the Compiler); add e2e/ to disableTypeChecked
  block; promote exhaustive-deps to error
- API broker: remove redundant as-casts (outboxWorker, poller, reminderScheduler,
  expand, sync, vevent, spike); add targeted ical.js no-unsafe-assignment/argument
  disables with justifying comments inside try blocks
- API routes/sse.ts: fix no-misused-promises on async writeSSE callback with
  void+IIFE+catch pattern
- API routes/lists.ts: let → const for updateValues
- API tests: remove unused imports (beforeEach, eq, vi); rename unused vars
  with _ prefix; remove unused lastActiveId assignment
- PWA components: void navigate() and void queryClient.invalidateQueries() on
  all fire-and-forget call sites; fix CalendarShell explicit-type-casts;
  Couldn't → HTML entity
- PWA test files: as unknown as Response for partial mock objects; string | null
  type annotation on mockLastSyncedUid; remove async from test callbacks without
  await; act(() => {}) not await act(async () => {}) for sync ops
- sw.ts: restructure Notification.data?.url access as let+if so disable
  comments land on the exact violation lines; void self.skipWaiting()
2026-06-11 20:23:38 -04:00
Lucas Berger d2ce4e08c7 feat(05-05): hook notifyListChange into list/item mutations (reorder excluded)
- POST /:id/items (item added) → notifyListChange
- PATCH /list-items/:itemId checked/text → notifyListChange; position-only → silent (D-01)
- DELETE /list-items/:itemId → notifyListChange
- PATCH /:id (list rename/share toggle) → notifyListChange
- DELETE /:id (list delete) → notifyListChange
- POST / (list create) → no notification (empty list, D-01 spirit)
- lists.test.ts: 2 new tests prove reorder-silent (position) and check-notifies (NOTIF-02)
- All 59 lists.test.ts assertions GREEN
2026-06-09 21:26:29 -04:00
Lucas Berger f6f1374904 feat(05-04): push subscription API + VAPID startup wiring
- Create apps/api/src/routes/push.ts: GET /vapid-public-key, POST /subscription (upsert), DELETE /subscription (user-scoped)
- Wire pushRouter at /api/push in index.ts
- Call webpush.setVapidDetails() in isMainModule() guard before serve()
- Fix broken vi.getMockImplementation scaffold bug in push.test.ts (Rule 1)
- push.test.ts: all 4 tests GREEN
2026-06-09 21:04:16 -04:00
Lucas Berger ef558b65be test(05-01): add Wave-0 RED scaffolds + VAPID fixture + setup truncation
- tests/fixtures/vapid.ts: static TEST_VAPID keypair for offline unit tests
- tests/lib/pushDispatcher.test.ts: RED — 410/404 prune + 201/5xx no-delete
- tests/lib/pushCoalescer.test.ts: RED — burst coalesce fires once with count=N; excludeUserId
- tests/broker/reminderScheduler.test.ts: RED — shared+timed filter; dedup by (uid,minuteBucket)
- tests/lib/eventChangeDispatcher.test.ts: RED — create/meaningful-update fires; description-only silent; actor excluded
- tests/routes/push.test.ts: RED — POST 201/401; DELETE removes rows; GET vapid-public-key
- test/setup.ts: import pushSubscriptions + add db.delete(pushSubscriptions) in afterEach
- all 5 RED files fail on missing-module (correct; implementations in Plans 05-02..05-06)
2026-06-09 20:50:35 -04:00
Lucas Berger 931f767922 test(04-07): add failing sharee-403 tests for T-04-08 owner-only isShared guard
- T-04-08 test 1: sharee PATCH { isShared: false } must get 403 and
  list_shares row unchanged (currently 200 + shares wiped — bug)
- T-04-08 test 2: sharee PATCH { isShared: true } must get 403 and
  no new shares inserted (currently 200 + shares fan-out — bug)
- Both tests fail now; GREEN once owner-only guard added to lists.ts
2026-06-09 14:22:21 -04:00
Lucas Berger ece663d1df test(04-07): add failing collation regression test (LIST-03)
- Seed items with ranks 'a0' and 'a1', drag second to top via rank 'Zz'
- Assert 'Zz' < 'a0' is true in JS (documents uppercase-before-lowercase intent)
- GET /api/lists/:id/items must return Zz-ranked item at index 0
- Fails now because MariaDB utf8mb4_uca1400_ai_ci sorts 'Zz' after 'a0'
- Will pass once rank column gets COLLATE utf8mb4_bin via migration
2026-06-09 14:19:27 -04:00
Lucas Berger 5a8d1efe1c test(04-06): add failing RED tests for LIST-04 SSE fan-out + bounded backoff
- API: 5 failing fan-out spy tests (subscribeListEvents receives 0 events since publishListEvent seams commented out in lists.ts)
- API: 4 D-04 scoped subscription tests (green — listAccess primitives from 04-02 already proven)
- PWA: useListSSE.test.ts — all 7 tests fail (module-not-found; hook not yet created)
- Covers: item:added/updated/deleted, list:updated/deleted fan-out + D-11 bounded backoff exhaustion + D-10 reconnect invalidation
2026-06-09 13:25:39 -04:00
Lucas Berger ef4b1157b3 test(04-05): server-side reorder ordering + rank precision tests (LIST-03, D-13)
- rank.test.ts: 100-iteration zipper mid-point insert precision test (Pitfall 2);
  rank-between-neighbors contract test; total 10 tests (was 8)
- lists.test.ts: 5 new LIST-03 ordering tests — PATCH position updates only rank
  and GET returns new ASC order; one-row write asserts other items unchanged;
  LWW (D-15): second PATCH overwrites first; T-04-07 two-field position PATCH → 400
- Note: tests use a0–a5 rank range (avoids uppercase ranks that sort differently
  under MariaDB utf8mb4_unicode_ci vs JS lexicographic order)
2026-06-09 13:17:35 -04:00
Lucas Berger b1dc9b8048 test(04-04): add failing tests for item CRUD endpoints + rank helpers
- Add rank.test.ts: unit tests for rankForAppend/rankBetween (RED - no impl yet)
- Extend lists.test.ts with item route tests: POST /:id/items, GET /:id/items,
  PATCH /list-items/:id (per-field LWW D-08), DELETE /list-items/:id (D-09)
- Import listItems from schema; add seedItem helper
- Tests cover: fractional rank assignment (D-13), exact-one-field refine (T-04-07),
  uncheck rank recompute, access gating T-04-05, delete-wins no resurrection D-09
2026-06-09 12:52:34 -04:00
Lucas Berger 9546b747d2 feat(04-03): implement listsRouter POST/GET/PATCH/DELETE /api/lists (LIST-01)
- GET /: scoped access (owner + list_shares); activeCount/doneCount per list
- POST /: auto-populates list_shares for all other members when isShared=true (D-01/D-02)
- PATCH /🆔 rename + isShared toggle; reconciles list_shares on visibility change
- DELETE /🆔 owner-only; cascade handles items/shares via FK onDelete cascade
- resolveUserId helper copied verbatim from events.ts per project convention
- zod createListSchema (name 1..255, isShared default true) + patchListSchema
- T-04-02 / T-04-05 / T-04-07 / T-04-08 mitigations applied
- listsRouter mounted at /api/lists in index.ts (after sseRouter)
- Plan 06 SSE seam comments left at every mutation handler
- [Rule 1 - Fix] zValidator returns 400 (not 422); tests corrected to match convention
- All 23 tests green; full API suite 140 passed no regressions
2026-06-09 12:38:05 -04:00
Lucas Berger 2b3d7896f1 test(04-03): add failing integration tests for lists router (LIST-01, D-01/D-02/D-04/D-06)
- GET /api/lists scoped access tests (empty, owned, shared, D-04 negative)
- GET /api/lists item count (activeCount/doneCount) assertion
- POST /api/lists shared/private create + auto list_shares + zod validation
- DELETE /api/lists/:id owner/403/404/cascade tests
- PATCH /api/lists/:id rename/share toggle/403/zod tests
- All fail 404 (router not yet mounted) — RED gate confirmed
2026-06-09 12:34:49 -04:00
Lucas Berger 60745b3281 refactor(04-01): move API list test stubs into tests/ mirror dir to match convention
The two Wave-0 RED stubs (lists.test.ts, listEmitter.test.ts) were co-located in
src/ but all existing API tests live in apps/api/tests/. Move them to tests/routes/
and tests/lib/, add explicit vitest imports to match the tests/ convention, and
update path references in downstream plans 04-02..04-06. PWA tests keep co-location
(that IS the PWA convention).
2026-06-09 12:10:31 -04:00
Lucas Berger fd13852eb9 fix(03): WR-04 rank failed/dead outbox row above done in sync-status 2026-06-09 11:04:00 -04:00
Lucas Berger 5168920eb1 fix(03): CR-01 preserve RRULE on edit-as-move (forward source rule to create row) 2026-06-09 10:59:19 -04:00
Lucas Berger 7a48659cae fix(03): update event lookup test mocks for CR-01/CR-02 query-chain changes
The CR-01 fix appended .orderBy().limit(1) to the edit/delete event lookups
and CR-02 added .innerJoin(calendars).limit(1) to the freshest-etag re-read.
The existing test doubles terminated the mock chain at .where(), so the new
chain calls hit undefined methods → handlers caught the throw and returned 503
(events.test.ts) and the worker skipped the PUT (outboxWorker.test.ts).

Extend the mocks to match the corrected production chains. Behaviour-preserving:
mockWhereCalEvents stays the awaited terminal so etag override assertions still drive.

8 failing tests now green; full suite: api 103, pwa 141.
2026-06-09 10:51:10 -04:00
Lucas Berger a99ef1daae refactor(260607-l6l): extract shared deriveDisplayName helper (BUG 2 DRY)
The displayName claim-preference logic (name → preferred_username → email →
sub fallback) was duplicated verbatim in me.ts and events.ts resolveUserId.
Extract it to auth/user.ts as deriveDisplayName and use it in both call sites,
so the rule has one definition. Update the events.test.ts user.js mock to keep
the real helper (spread importActual) while stubbing only upsertUser.
2026-06-07 15:37:18 -04:00
Lucas Berger 509f4b26e0 test(260607-l6l): make BUG 1 join regression test couple to the handler
The original toSQL() regression test hand-built the joined query inside the
test body and asserted the SQL contained a join — tautological: it never
exercised the handler, so removing .innerJoin from events.ts left it green.

Replace it with two tests that issue real PATCH/DELETE requests against the
mocked select-chain (from → innerJoin → where) and assert the handler returns
202 (not 503) AND invokes the innerJoin spy. Verified RED: removing the
edit+delete joins fails both tests; GREEN with the joins present.
2026-06-07 15:34:39 -04:00