Commit Graph
252 Commits
Author SHA1 Message Date
Lucas Berger bd8283774d feat(03-07): VitePWA manifest + auth-safe SW denylist + iOS head/icons
- Add VitePWA plugin to vite.config.ts with registerType:autoUpdate
- navigateFallbackDenylist excludes /callback, /api/, /health (T-03-20 Gate 2)
- runtimeCaching: [] — no API response caching (T-03-21)
- Manifest: name/short_name FamilySync, display:standalone, scope:/, theme_color #4A90D9
- Icons: 192x192, 512x512, 512x512 maskable in manifest
- Generate icon-192.png (192x192), icon-512.png (512x512), apple-touch-icon.png (180x180)
- Add five iOS head entries: apple-touch-icon link, apple-mobile-web-app-capable/status-bar-style/title
- Build verified: dist/manifest.webmanifest emitted with correct fields; SW + workbox emitted
2026-06-05 18:02:56 -04:00
Lucas Berger 0a8222329e feat(03-03): implement write API surface — create/edit/delete + sync-status + writable-calendars
- POST /create: validates with zod, checks calendar ownership (D-03/T-03-06), enqueues pending outbox row, returns 202 with uid
- PATCH /:uid/edit: looks up event, checks ownership, enqueues update row; uses db.transaction for edit-as-move calendar pair (D-04)
- DELETE /:uid: looks up event, checks ownership, enqueues delete row with server-side etag (T-03-10)
- GET /sync-status: returns outbox status scoped to currentUser only (T-03-07/D-09)
- GET /writable-calendars: returns own personal + shared calendars, never other member's personal (D-03/T-03-11)
- Auth via dev-bypass (c.get('user')) + getAuth(c) fallback; 401 if neither
- No tsdav import — broker boundary enforced (D-12)
- All 69 events tests GREEN; tsc --noEmit clean
2026-06-05 17:58:01 -04:00
Lucas Berger e14c5dab69 test(03-03): extend events tests RED — write/sync-status/writable-calendars endpoints
- Add write endpoint tests: POST /create, PATCH /:uid/edit, DELETE /:uid
- Add GET /sync-status tests (D-09 outbox polling)
- Add GET /writable-calendars tests (D-03 writable set, access control)
- Wire db.insert and db.transaction into the vi.mock for db/client.js
- Mock devAuthBypass to inject dev user in write-endpoint tests
- All 9 new tests are RED (routes not yet registered)
2026-06-05 17:54:08 -04:00
Lucas Berger a1243c1b83 feat(03-02): implement tsdav write wrappers (Task 2 GREEN) + fix vevent.ts TS type
write.ts:
- createCalendarEvent: wraps client.createCalendarObject with ${uid}.ics filename
- updateCalendarEvent: wraps client.updateCalendarObject with etag → If-Match (D-08)
- deleteCalendarEvent: wraps client.deleteCalendarObject with etag → If-Match (D-08)
- null etag passed as '' (safe; no crash, no spurious If-Match header)
- Returns raw Response; status code interpretation deferred to outboxWorker (D-07)
- All 6 write.test.ts assertions GREEN

vevent.ts fix:
- ICAL.Time constructor requires 2 args per TS types; pass ICAL.Timezone.localTimezone
  as zone param for all-day DATE values (isDate:true suppresses TZID regardless)
- tsc --noEmit passes clean
2026-06-05 17:48:12 -04:00
Lucas Berger b23b9597df feat(03-02): implement buildVeventString VEVENT builder (Task 1 GREEN)
- buildVeventString(NewEventParams) → { uid, icsString } using ical.js ICAL.Component
- All-day events use ICAL.Time({ isDate: true }) → VALUE=DATE, no TZID, no time (D-13)
- Timed events use ICAL.Time.fromJSDate(date, true) → DTSTART:...Z, no TZID (D-13)
- RRULE serialized via ICAL.Recur.fromString + ICAL.Property (prevents char-split bug)
- Exports: buildVeventString, NewEventParams, RRULE_PRESETS (daily/weekly/monthly/yearly)
- Uses crypto.randomUUID() for UID generation; appends @familysync suffix
- All 7 vevent.test.ts assertions GREEN
2026-06-05 17:46:19 -04:00
Lucas Berger bbfccda756 test(03-01): add Wave 0 RED test scaffold for all Phase 3 behaviors
- vevent.test.ts: DTSTART UTC 'Z' for timed, DATE for all-day (D-13), RRULE (CAL-04/07)
- write.test.ts: createCalendarEvent uid.ics filename, updateCalendarEvent/deleteCalendarEvent
  etag/If-Match shapes (CAL-04/05/06, D-08)
- outboxWorker.test.ts: pending→done on 204, pending→failed on 412 (no retry), pending→backoff
  on 500, pending→dead at MAX_ATTEMPTS, edit-as-move create-before-delete ordering (D-04/D-07/D-08)
- events.test.ts (extended): POST /create 202+outbox row, PATCH /edit 202+etag, DELETE /:uid 202,
  GET /sync-status, GET /writable-calendars D-03 access control, 403 unauthorized calendar (V4)
- InstallPrompt.test.tsx: isIOSSafariNonStandalone UA detection, useAndroidInstallPrompt
  canInstall lifecycle (PWA-01/PWA-02)
All tests fail RED — implementation modules do not exist yet
2026-06-05 17:26:02 -04:00
Lucas Berger 0c0bcefeef feat(03-01): populate calendarEvents.objectUrl in sync.ts from obj.url
- Set objectUrl: obj.url ?? null in both .values() and .onDuplicateKeyUpdate({ set: {} })
  alongside existing etag assignment — stores CalDAV object URL for If-Match on
  update/delete (D-08)
- All existing broker/sync tests pass (47 total)
2026-06-05 17:23:06 -04:00
Lucas Berger 78f0deefac feat(03-01): extend schema with calendarOutbox table + calendarEvents.objectUrl; install vite-plugin-pwa
- Add mysqlEnum import to drizzle-orm/mysql-core import block
- Add objectUrl varchar(1024) to calendarEvents after etag column (D-08)
- Add calendarOutbox table with status machine columns, groupId for edit-as-move (D-04)
- Add indexes: idx_outbox_user_status, idx_outbox_next_attempt, idx_outbox_uid
- Install vite-plugin-pwa@1.3.0 (supply-chain gate T-03-SC cleared by Task 1)
2026-06-05 17:22:37 -04:00
Lucas Berger 504ce369b5 fix(02): display events in viewer's local timezone, not UTC
Schedule-X defaults its calendar timezone to 'UTC', so a 17:45-04:00 event rendered at
21:45 (9:45 PM). Set timezone to the viewer's resolved IANA zone so events convert to
local wall-clock; the popover already showed local time, so the two now agree.
2026-06-05 15:31:28 -04:00
Lucas Berger 05d9f70b45 fix(02): window occurrences in UTC, not server-local timezone
ICAL.Time.fromJSDate(window, false) interpreted the UTC-midnight window bounds in the
server's local TZ (America/New_York in dev), shifting the window by the server offset and
dropping evening occurrences near a day window's end (e.g. June 11 17:45-04:00 = 21:45Z was
excluded from the June-11 day view). Use UTC so the window is deterministic and correct.
2026-06-05 15:28:26 -04:00
Lucas Berger d07e8af88d fix(02): keep calendar mounted on empty windows so navigation survives
Navigation now lives in Schedule-X's built-in header; replacing the calendar with
EmptyState on a zero-event day removed the nav and stranded the user. Always render
the calendar (empty grid is self-explanatory).
2026-06-05 15:21:58 -04:00
Lucas Berger 92dbbfe110 fix(02): give React adapter wrapper height so week/day grid scrolls
.sx-react-calendar-wrapper (emitted by @schedule-x/react) had no height, collapsing the
height chain so .sx__view-container could not scroll. Set it to height:100%.
2026-06-05 15:19:05 -04:00
Lucas Berger 194f6a82a8 fix(02): show owner name / Family in event popover footer
Backend:
- expand.ts: add ownerName: string | null to CalendarOccurrence
  interface and expandOccurrences() signature; thread it onto every
  emitted occurrence.
- events.ts: SELECT users.displayName as ownerName in the join; pass
  it to expandOccurrences().

Frontend:
- client.ts: add ownerName: string | null to CalendarOccurrence.
- EventDetailPopover.tsx: render isShared ? 'Family' :
  (ownerName ?? calendarName) in the footer instead of calendarName.

Tests:
- expand.test.ts: pass ownerName to all expandOccurrences() calls;
  assert ownerName is carried onto occurrences in the DST test.
- events.test.ts: add ownerName to mock rows; assert ownerName present
  on occurrences; add ownerName assertion to timed-recurring test.
- EventDetailPopover.test.tsx: add ownerName to fixtures; split
  "calendar name in footer" into three targeted tests covering
  personal-with-owner, shared→Family, and null-owner fallback.
2026-06-05 15:14:43 -04:00
Lucas Berger fc758e8ea6 fix(02): fix week/day time-grid clip and hour-label contrast
- CalendarShell: remove overflow:hidden from calendar container; add
  height:100% so Schedule-X .sx__calendar-wrapper can fill the flex
  parent and .sx__view-container can scroll.
- index.css: add explicit .sx__calendar-wrapper { height: 100% } rule
  to propagate height through the React adapter's wrapper element.
- tokens.css: fix --sx-color-neutral override from near-white
  var(--color-surface-dim) to readable var(--color-text-secondary);
  fix --sx-color-neutral-variant to var(--color-border); add
  --sx-internal-color-text override for chevrons and UI borders.
  Both hour-axis labels (.sx__week-grid__hour-text) and weekday/day
  name headers (.sx__week-grid__day-name, .sx__week-grid__date-number)
  use --sx-color-neutral — all now readable.

Class and variable names confirmed from @schedule-x/theme-default@4.6.0
dist/index.css inspection.
2026-06-05 15:14:33 -04:00
Lucas Berger d240657059 fix(02): remove custom ViewToolbar; use Schedule-X built-in header
- Remove <ViewToolbar> render and its import from CalendarShell
- Remove createCalendarControlsPlugin import, useState instance, and plugin
  array entry (calendar-controls only served the custom toolbar)
- Delete ViewToolbar.tsx (no longer referenced anywhere)
- Remove calendar-controls mock from CalendarShell.test.tsx
- CSS audit confirmed no rules hide Schedule-X weekday-name row; no CSS changes needed
- All four views (day/week/month-grid/month-agenda) remain; Schedule-X's native
  header exposes them in its own view switcher
2026-06-05 14:54:40 -04:00
Lucas Berger 1f0b9546a8 fix(02): include all-day recurring masters in events route pre-filter
- Old filter: hasRrule=1 AND dtstartUtc < windowEnd
  All-day recurring masters have dtstartUtc=NULL so the comparison evaluates
  to NULL/false — 11 such rows in live cache were never returned
- New filter: hasRrule=1 AND (dtstartUtc < windowEnd OR dtstartDate < end)
  The OR covers all-day masters whose only date column is dtstartDate (DATE)
- expandOccurrences already does precise per-occurrence window checks, so
  over-selecting a master on the DATE path is safe
- Extend events.test.ts: assert timed recurring master (dtstart 2024) returns
  occurrences in 2026 window; assert all-day recurring master (dtstartDate 2024,
  dtstartUtc NULL) returns its 2026-06-15 occurrence
2026-06-05 14:50:27 -04:00
Lucas Berger f70496871a fix(02): populate hasRrule on every sync upsert so recurring masters are flagged
- Use ICAL.Event.isRecurring() (parity with expand.ts) to detect RRULE/RDATE
- Add hasRrule to .values() INSERT and .onDuplicateKeyUpdate() SET so the flag
  is set on first sync and self-heals on every subsequent re-sync
- Without this fix every event had has_rrule=0 (column default), causing the
  events route recurring-master pre-filter to return zero recurring occurrences
- Add sync.test.ts cases: hasRrule=true for timed+all-day recurring VEVENTs,
  hasRrule=false for non-recurring, and hasRrule in onDuplicateKeyUpdate.set
2026-06-05 14:50:18 -04:00
Lucas Berger 5d82f859fd fix(02): wire calendar-controls plugin and Zustand selectors
Bug A — navigation no-op: replace $app.calendarState private-API poking
with the official @schedule-x/calendar-controls plugin. CalendarShell
creates the plugin once via useState stable initialiser and passes it to
ViewToolbar as `controls`. ViewToolbar calls controls.setDate(PlainDate)
and controls.setView(id) for all navigation and view-switching. Step size
matches the active view: day→±1 day, week→±1 week, month-*→±1 month.

Bug B — popover-open calendar flash: replace the unselected
useCalendarStore() destructuring in CalendarShell and ViewToolbar with
per-field selectors. Neither component now subscribes to openEventId, so
popover open/close no longer triggers a re-render that rebuilds the
Schedule-X config.

- Add @schedule-x/calendar-controls@4.6.0 dependency
- Update CalendarShell.test.tsx: add vi.mock for calendar-controls
- typecheck, vitest (37/37), build all pass
2026-06-05 14:45:27 -04:00
Lucas Berger 1a24b00de9 fix(02): day-view 400, invalid date display, duplicate popover (BUG 2-4)
- BUG 2: onRangeUpdate sets exclusive end = range.end + 1 day so day view
  sends a 1-day window (start < end, no 400) and week/month include the last day
- BUG 3: formatDateTime strips IANA bracket '[Zone]' before new Date() to prevent
  'Invalid Date, Invalid Date – Invalid Date' in event popover; regression test added
- BUG 4: remove createEventModalPlugin + customComponents.eventModal — keep only
  the Zustand-driven standalone EventDetailPopover to prevent double-open fight
2026-06-05 14:34:36 -04:00
Lucas Berger ee2281fe81 fix(02): correct DURATION-only event end in expand.ts (BUG 1)
- Replace dtend ?? dtstart with event.endDate which handles DURATION-only VEVENTs
- Add positive-duration guard (PT30M / P1D) to both non-recurring and recurring branches
- Add single-duration.ics fixture and regression test asserting end > start for DURATION-only events
2026-06-05 14:33:00 -04:00
Lucas Berger bef4a83fe0 fix(02): CSS-safe occurrence ids + error boundary to surface render errors
Schedule-X rejects ids containing ':' '[' ']' (the old ${uid}::${iso} form) — mint ev-<uid>-<epochMs> instead. Add an ErrorBoundary so a render throw shows the error instead of a blank page.
2026-06-05 14:30:32 -04:00
Lucas Berger 93c368402c fix(02): update expand tests to assert IANA-annotated format + add cross-contract test
- Assert timed start/end strings include '[America/New_York]' bracket (not offset-only)
- Assert DST boundary offsets: -05:00[America/New_York] pre-transition, -04:00[America/New_York] post
- Add cross-contract regression test: feeds expandOccurrences output directly into
  Temporal.ZonedDateTime.from() to prove the expand→hydrate contract holds end-to-end
- Import 'temporal-polyfill/global' at top of test file for the Temporal global
- Rename describe block from 'RED stubs (Wave 0)' to reflect GREEN state
2026-06-05 14:04:00 -04:00
Lucas Berger 35f725d450 fix(02): emit IANA-annotated timed strings from serializeTime
Temporal.ZonedDateTime.from() rejects offset-only ISO strings such as
'2026-06-18T08:00:00-04:00'; it requires an IANA bracket, e.g.
'2026-06-18T08:00:00-04:00[America/New_York]'. serializeTime() was
emitting offset-only for named zones and bare 'Z' for UTC — both
unparseable by the frontend, blanking the calendar view.

Changes:
- Named IANA zone: emit '...±HH:MM[tzid]' using t.zone.tzid
- UTC zone: strip trailing 'Z' from toString(), emit '+00:00[UTC]'
- Floating zone (no registered VTIMEZONE): fall back to '+00:00[UTC]'
- Update CalendarOccurrence docstrings to reflect the IANA-annotated contract
- Add temporal-polyfill@0.3.2 as dev dep in api for cross-contract test
2026-06-05 14:02:36 -04:00
Lucas Berger df5d36308a fix(02): add regression tests for /api/me under dev-auth bypass
- Asserts GET /api/me returns 200 with DEV_USER (id=1, color=#4A90D9)
  when DEV_AUTH_BYPASS=true and NODE_ENV!=production
- Asserts oidcAuthMiddleware is NOT wired when bypass is active
- Asserts oidcAuthMiddleware IS wired when bypass is absent
- Asserts 401 from getAuth(null) fallback path with no OIDC session
2026-06-05 13:48:05 -04:00
Lucas Berger 4b34b16f02 fix(02): dev-auth bypass no longer blocked by oidcAuthMiddleware
- index.ts: compute devBypassActive at startup; skip app.use(oidcAuthMiddleware)
  entirely when active so the OIDC guard never runs in local dev
- routes/me.ts: read c.get('user') first; return dev identity directly when
  devAuthBypass injected it, bypassing getAuth() and the DB upsert
- auth/devBypass.ts: add ContextVariableMap augmentation for 'user' key;
  correct stale comment that claimed getAuth/401 path was still active
2026-06-05 13:48:00 -04:00
Lucas Berger 216ddcedf4 feat(02-05): ColorLegend, AppNav, ViewToolbar, SkeletonCalendar, EmptyState; retire EventProof
- ColorLegend: per-member color swatches (12px circle, label) + always-visible Family row
- AppNav: phone 48px top bar (avatar with aria-label/title) + tablet/desktop 240px sidebar with ColorLegend
- ViewToolbar: Today/prev/next + Day/Week/Month/Agenda view switcher; 44px min-height; active state uses surface tint not accent
- SkeletonCalendar: shimmer month (6x7 grid) and agenda (4 date-group blocks) variants; aria-busy=true
- EmptyState: CalendarDays icon + 'Nothing here' heading + body copy per UI-SPEC
- CalendarShell: full phone/desktop layout with AppNav + ViewToolbar + ColorLegend chrome
- CalendarShell: state branches — loading→SkeletonCalendar, empty→EmptyState, error→'Couldn't load events' + Retry button (refetchQueries)
- EventProof.tsx deleted; legacy types removed from client.ts
- CalendarShell.test.tsx: updated to waitFor ScheduleXCalendar after data loads
- All 36 tests pass, tsc clean, vite build clean (490kB)
2026-06-05 10:58:06 -04:00
Lucas Berger 3eebfbff42 feat(02-05): EventDetailPopover read-only popover, XSS-safe, wired into CalendarShell
- EventDetailPopover: reads openEventId from Zustand, resolves occurrence from TanStack Query cache
- Dual-mode: standalone (Zustand-driven) + customComponents.eventModal (Schedule-X)
- Plain-text JSX children for all event fields (T-02e-01 XSS guard)
- Focus trap, Escape to close, backdrop-click to close, aria-label=Close (44px target)
- Phone: bottom sheet layout; tablet/desktop: centered popover (max-width 360px)
- Phase-3 footer action area reserved with comment
- CalendarShell: passes customComponents.eventModal=EventDetailPopover to ScheduleXCalendar
- test-setup.ts: import @testing-library/jest-dom for toHaveTextContent matcher
- All 36 tests pass, tsc clean
2026-06-05 10:51:57 -04:00
Lucas Berger 433fb9f900 test(02-05): add failing tests for EventDetailPopover (TDD RED)
- renders title/location/description/calendar-name as plain text
- Escape key and backdrop click close the popover via setOpenEventId(null)
- close button aria-label=Close assertion
- XSS guard: HTML-looking title and description render as escaped text not DOM elements
- renders null when openEventId is null
2026-06-05 10:47:41 -04:00
Lucas Berger f0af43c4e6 test(02-04): CalendarShell CAL-03 render smoke — Temporal hydration + Pitfall 6 guard
- CalendarShell.test.tsx: 6 tests covering render-without-throw, ScheduleXCalendar mount,
  hydrateEvents called with both timed + all-day occurrences, Temporal.PlainDate guard
  (Pitfall 4/all-day date shift), Temporal.ZonedDateTime for timed (Pitfall 4)
- test-setup.ts: window.matchMedia polyfill for jsdom (calendarStore initialises at module load)
- vitest.config.ts: adds setupFiles pointing to test-setup.ts
2026-06-05 10:42:30 -04:00
Lucas Berger b79f649ac5 feat(02-04): mount Schedule-X CalendarShell wired to TanStack Query + Zustand + hydrateEvents
- CalendarShell.tsx: all four views (day/week/month-grid/month-agenda), eventsService + eventModal plugins
- calendarId routing: 'shared' | String(ownerUserId) via hydrateEvents, matching buildCalendarConfig keys
- SX_FIRST_DAY_OF_WEEK=7 (Sunday, Temporal convention); initial range from Zustand default (A4 guard)
- onRangeUpdate updates Zustand range, triggering TanStack Query refetch on navigation
- App.tsx: replaces EventProof landing with CalendarShell; tokens only (no hardcoded hex/px)
2026-06-05 10:40:07 -04:00
Lucas Berger 9ee26c07a7 feat(02-02): evolve /api/events to windowed endpoint with color/owner join
- zValidator enforces YYYY-MM-DD regex on start/end (T-02b-01)
- 90-day window cap prevents DoS (T-02b-02)
- innerJoin calendarEvents→calendars→users for color + isShared + ownerUserId
- SQL pre-filter includes hasRrule=true rows regardless of dtstartUtc range
- expandOccurrences() called per row; shared calendar uses #F25C7A rose color
- events.test.ts: added @hono/oidc-auth mock; 4/4 assertions green
2026-06-05 10:30:36 -04:00
Lucas Berger 6736194a4a feat(02-02): add expandOccurrences() with VTIMEZONE + allDay split + EXDATE
- ICAL.TimezoneService.register() runs before RecurExpansion (DST correctness)
- All-day events serialized as YYYY-MM-DD strings (no time shift)
- EXDATE exclusions handled internally by ICAL.RecurExpansion
- Malformed rawVevent returns [] without throwing
- expand.test.ts DST, all-day, EXDATE assertions green (3/3)
2026-06-05 10:30:22 -04:00
Lucas Berger f377d7c3f8 feat(02-03): hydrateEvents + calendarStore + windowed fetchEvents; RED stubs green
- Create hydrateEvents.ts: Temporal.PlainDate for allDay, ZonedDateTime for timed
  calendarId routes via isShared ? 'shared' : String(ownerUserId) — NOT String(calendarId)
  _familySync carries uid/color/isShared through to popover
- Update hydrateEvents.test.ts: add temporal-polyfill/global import; all 4 RED stubs now GREEN
- Create calendarStore.ts: Zustand store with selectedView (localStorage per breakpoint group),
  selectedDate, openEventId, calendarRange; D-05 view defaults; calendarRange ± buffer for
  initial TanStack Query key without depending on onRangeUpdate firing on mount
- Update client.ts: add CalendarOccurrence/OccurrencesResponse, windowed fetchEvents(start,end)
  with credentials:include; keep legacy CalendarEvent/EventsResponse + fetchEventsLegacy
  as deprecated for EventProof.tsx (removed in Plan 05)
- Update EventProof.tsx: switch to fetchEventsLegacy to keep build clean until Plan 05
- tsc --noEmit clean; all 18 PWA tests pass
2026-06-05 09:47:07 -04:00
Lucas Berger 43554f491b feat(02-03): colorUtils + calendarConfig; turn RED calendarConfig stubs green
- Create colorUtils.ts: hexToContainer (15% alpha over white), hexToOnContainer
  (darken 40%), deriveScheduleXColors() returning { main, container, onContainer }
- Create colorUtils.test.ts: hex blend math assertions for #4A90D9 and #F25C7A
- Create calendarConfig.ts: WEEK_START_DAY=0, SX_FIRST_DAY_OF_WEEK=7 (0→7 translation)
  buildCalendarConfig() keyed by String(userId) + 'shared'; returns { firstDayOfWeek, calendars }
- calendarConfig.test.ts (Plan 01 RED stubs) now GREEN: all 4 assertions pass
2026-06-05 09:44:19 -04:00
Lucas Berger 0911a2330a feat(02-03): install Schedule-X stack + CSS token layer + main.tsx imports
- Install @schedule-x/{calendar,react,theme-default,event-modal,events-service}@4.x
- Install temporal-polyfill@0.3.2 and lucide-react@1.17.0
- Create src/styles/tokens.css: all color/spacing/typography/breakpoint tokens
  plus --sx-color-* Schedule-X overrides mapped to project tokens
- Create src/styles/tokens.ts: TypeScript mirror of token values for inline styles
- Create src/styles/index.css: imports tokens.css + minimal global reset
- Update main.tsx: Temporal polyfill first, then SX theme CSS, then styles/index.css
2026-06-05 09:42:34 -04:00
Lucas Berger 8bd44b33c7 feat(02-01): dev-auth bypass middleware with production hard guard
- Create apps/api/src/auth/devBypass.ts: devAuthBypass() middleware with
  NODE_ENV=production hard guard as first conditional (T-02-01 mitigation)
- Exports DEV_USER const (id:1, color:COLOR_PALETTE[0]) for test reference
- Mount devAuthBypass() before oidcAuthMiddleware on /api/* in index.ts
- Add devBypass.test.ts: all three behavioral cases pass (production guard,
  unset-flag passthrough, active-injection)
- Add DEV_AUTH_BYPASS to .env.example with production warning comment
- Extend docs/deployment.md with dev-auth bypass section and production prohibition
2026-06-05 09:32:00 -04:00
Lucas Berger 75252eb08c feat(02-01): schema columns, PWA vitest harness, ICS fixtures, RED test stubs
- Add calendarEvents.hasRrule boolean + idx_calendar_events_has_rrule index (Phase 2 pre-filter)
- Add calendars.isShared boolean for shared-family calendar identification
- Create apps/pwa/vitest.config.ts with jsdom environment
- Add vitest, @testing-library/react, jsdom, @testing-library/jest-dom to PWA devDependencies
- Add "test": "vitest run" script to apps/pwa/package.json
- Create three ICS fixtures: weekly-dst.ics (DST spanning), allday-birthday.ics, exdate-series.ics
- Create RED test stub expand.test.ts with concrete DST wall-clock assertions (10:00 local both sides of March 2026 boundary)
- Create RED test stub events.test.ts with 400 validation and color/isShared field contracts
- Create RED test stub hydrateEvents.test.ts with Temporal type and calendarId routing contracts (shared→"shared", personal→String(ownerUserId))
- Create RED test stub calendarConfig.test.ts with firstDayOfWeek 0→7 translation contract
2026-06-05 09:29:45 -04:00
Lucas Berger 48f90ceca9 feat(01-04): wire broker + routes into bootstrap, add SSE endpoint, EventProof
- Mount /api/events, /api/sse in index.ts behind oidcAuthMiddleware; /callback + /health before guard
- Call startBrokerPoller() on boot (5-min ctag-poll background schedule)
- Add sseRouter with GET /heartbeat (streamSSE, 10s interval) for Pangolin SSE smoke test (D-08, T-04-01)
- Add CAL-08 spike script (broker/spike.ts): createFastmailClient → fetchCalendars → print calendar URLs
- Add fetchEvents() to pwa/api/client.ts with typed CalendarEvent/EventsResponse shapes
- Add EventProof.tsx: React Query ['events'], renders first event title+date or empty-state (CAL-01 broker proof)
- Update App.tsx to render MemberBadge + EventProof on landing page
- Add ical.js@2.2.1 to PWA dependencies for VEVENT summary parsing in EventProof
- All 24 API unit tests green; tsc --noEmit clean in both apps/api and apps/pwa
2026-06-04 11:16:10 -04:00
Lucas Berger 23b8e5326d feat(01-03): implement ctag poller with node-cron 5-min schedule
- startBrokerPoller schedules runPoll via node-cron */5 * * * *
- runPoll loads all member_credentials, decrypts each app password
- ctag/syncToken comparison skips syncCalendar when ctag unchanged
- errors per-credential caught and logged without crashing the poller
- runPoll exported for unit-testing with vi.mock injected dependencies
2026-06-04 11:08:46 -04:00
Lucas Berger 1b3ea4e99b test(01-03): add failing tests for broker poller ctag change detection
- 5 tests: skip on unchanged ctag, sync on changed ctag, first-sync (null ctag), decrypt failure handled, all credentials processed
- Mocks db.select, createFastmailClient, syncCalendar, decryptPassword at module level
- RED gate: all fail (src/broker/poller.ts does not exist yet)
2026-06-04 10:34:12 -04:00
Lucas Berger dd02207318 feat(01-03): implement broker client, syncCalendar, and events route (CAL-01)
- client.ts: createFastmailClient(email, appPassword) → tsdav DAVClient via Basic auth
- sync.ts: syncCalendar upserts calendar row, selects ID, fetches+parses VEVENTs with ical.js
  - all-day DATE → dtstartDate (Date obj at T00:00:00Z), dtstartUtc=null, allDay=true
  - timed → dtstartUtc (JS Date), dtstartDate=null, allDay=false (D-13/Pitfall #3)
  - onDuplicateKeyUpdate on calendarId+uid composite key (idempotent)
- routes/events.ts: GET /api/events reads cache only — no tsdav import (T-03-02)
- tsc --noEmit clean; all 6 sync tests pass
2026-06-04 10:33:28 -04:00
Lucas Berger 90b99296e8 test(01-03): refine sync RED tests with richer db mock (select + insert)
- Use separate mock functions for insert/select chain to enable per-test assertions
- Reset mock implementations in beforeEach after vi.clearAllMocks
- Mock returns {id:42} from select (calendar ID for event upsert)
2026-06-04 10:30:53 -04:00
Lucas Berger ae21541e97 test(01-03): add failing tests for syncCalendar (D-13 all-day DATE handling)
- 6 tests: all-day DATE vs timed TIMESTAMP, allDay flag, upsert on dup UID, rawVevent blob, ctag update
- Mocks db singleton at module level with vi.mock hoisting pattern
- Uses SAMPLE_VEVENT_TIMED/ALLDAY fixtures from tests/helpers/db.ts
- RED gate: all fail (src/broker/sync.ts does not exist yet)
2026-06-04 10:29:29 -04:00
Lucas Berger d6d91201b1 feat(01-03): implement AES-256-GCM app-password encryption (T-03-01)
- encryptPassword: randomBytes(12) IV, aes-256-gcm, returns JSON {iv,authTag,ciphertext}
- decryptPassword: verifies GCM auth tag; throws on tamper
- Key from APP_PASSWORD_ENCRYPTION_KEY env (64-char hex); validated on each call
- No logging of plaintext or key
2026-06-04 10:27:40 -04:00
Lucas Berger 04d7c23e94 test(01-03): add failing tests for AES-256-GCM crypto helpers
- 5 tests covering roundtrip, IV uniqueness, tamper detection, payload shape
- Dynamic import with env key set in beforeAll for module-level KEY eval
- RED gate: all fail (src/broker/crypto.ts does not exist yet)
2026-06-04 10:26:59 -04:00
Lucas Berger 668ed9be0d feat(01-02): wire OIDC middleware, /api/me route, and authenticated PWA shell
- src/auth/middleware.ts: re-exports oidcAuthMiddleware, processOAuthCallback,
  getAuth from @hono/oidc-auth; documents required env vars and AUTH-02
  refresh-token rotation (no iframe, D-12)
- src/routes/me.ts: GET / calls getAuth → upsertUser(iss, sub, email) →
  returns { user: { id, displayName, color } }; identity keyed on iss+sub
- src/index.ts: /callback registered before oidcAuthMiddleware; /api/*
  guarded; /health remains unauthenticated; /api/me mounted
- apps/pwa/src/api/client.ts: typed fetchMe() with credentials: 'include'
- apps/pwa/src/App.tsx: useQuery(['me'], fetchMe); renders member name and
  color swatch; retains /health stack indicator from Plan 01
- tsc --noEmit: clean; all tests pass
2026-06-04 10:22:46 -04:00
Lucas Berger baabfce9e2 feat(01-02): implement upsertUser with stable color assignment (AUTH-03)
- Export COLOR_PALETTE (6 accessible hex hues, round-robin assignment)
- upsertUser(oidcIss, oidcSub, displayName?) keyed on iss+sub never email
- First login: COUNT existing users → assign COLOR_PALETTE[count % len]
- Re-upsert: returns existing row unchanged (idempotent, no duplicate insert)
- Uses $returningId() + re-select pattern (mysql2 no RETURNING clause)
- All 6 tests pass (GREEN)
2026-06-04 10:21:04 -04:00
Lucas Berger 61c258c021 test(01-02): add failing tests for upsertUser color assignment + identity
- Replace it.todo stubs with real failing tests (RED gate)
- Tests cover palette[0] first user, palette[1] second user, idempotent
  re-upsert, iss+sub identity key, full row shape
- Tests fail: src/auth/user.ts does not exist yet
2026-06-04 10:20:27 -04:00
Lucas Berger 00efbab107 fix(01-01): build Docker image from repo-root pnpm workspace context
The walking-skeleton Dockerfile built from a ./apps/api context and could not
work in a pnpm workspace: the lockfile lives at the repo root, pnpm 11 refused
esbuild's build script without the root pnpm-workspace.yaml, the dev stage never
compiled src->dist, and the production stage had invalid COPY syntax referencing
a path outside its context.

Switch to the correct monorepo pattern: build from the repo-root context, copy
the workspace manifest + lockfile + both package.jsons, and install with
--frozen-lockfile --filter @familysync/api...  Reorder stages so production is
default; dev reuses builder output. Fix the dev volume mount path.

Surfaced while clearing the Task 3 checkpoint (stack bring-up): drizzle-kit push
applied the 4 tables and /health returned {ok:true,db:up} end-to-end.
2026-06-04 10:17:06 -04:00
Lucas Berger 96cda58509 feat(01-01): Drizzle schema + DB client + /health slice (GREEN)
- src/db/schema.ts: users, memberCredentials, calendars, calendarEvents tables
  - users: composite unique on oidc_iss+oidc_sub (D-10 identity)
  - calendar_events: separate dtstart_utc (TIMESTAMP) and dtstart_date (DATE) + allDay boolean (D-13)
- src/db/client.ts: drizzle(mysql2 pool) singleton export `db`
- drizzle.config.ts: dialect mysql, schema → migrations, dbCredentials from env
- src/routes/health.ts: GET / with real SELECT 1 DB round-trip, 200 or 503
- src/index.ts: Hono app with /health mounted before auth, serveStatic for PWA
- tests/health.test.ts: 2 tests pass (mocked DB); TDD GREEN gate
- apps/pwa/src/App.tsx: React shell fetching /health via TanStack Query
2026-06-04 09:52:36 -04:00