diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5a4f415 --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +# Optional: local simulation and builds work without these values. +# Copy to .env.local, replace both placeholders, then restart Vite. +# Everything prefixed VITE_ is PUBLIC in the browser bundle. +VITE_SUPABASE_URL=https://YOUR_PROJECT.supabase.co +VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY + +# For an older project, use its public anon JWT only if a publishable key is unavailable. +# VITE_SUPABASE_ANON_KEY=YOUR_PUBLIC_ANON_KEY +# NEVER put a service_role JWT, sb_secret_ key, database password, or access token here. diff --git a/.gitignore b/.gitignore index d0582c4..245c3eb 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ dist/ playwright-report/ test-results/ .DS_Store + +.vite/ diff --git a/.prettierignore b/.prettierignore index 6cc8e56..e5ed4c3 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,3 +3,5 @@ dist package-lock.json test-results playwright-report + +.vite/ diff --git a/README.md b/README.md index 116c0c4..eb368f9 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,109 @@ # MSD Impact Monitor -A working React + TypeScript prototype for monitoring vehicle motion and threshold events. The **Live simulation** and **Event-only preview** modes are explicitly separated. Continuous GPS and IMU values are simulated; locally injected threshold packets are labeled test events. No physical hardware, phone gateway, account, API key, or cloud database is connected or required. +A React + TypeScript observer dashboard for vehicle GPS and threshold events. Stage 2 adds authenticated Supabase storage, shared real-time observation, three-IMU threshold configuration, and persistent cloud session history. The local demonstrations still run without Supabase configuration. -![MSD Impact Monitor dashboard with simulated GPS, acceleration, and impact history](docs/dashboard.png) +![MSD cloud observer with simulated cloud test records](docs/cloud-preview.png) + +The cloud preview uses simulated test records. Configure your own Supabase project using the steps below to connect a hosted database. ## Run locally -Use **Node.js 22.12+** (Node 24 recommended) and npm. +Use **Node.js 22.12+** (Node 24 recommended) and npm: ```sh npm ci npm run dev ``` -Open `http://localhost:5173` in your browser. To preview the production bundle: +Open the address Vite prints, normally `http://localhost:5173`. To preview the production bundle: ```sh npm run build npm run preview ``` -Vite prints the preview address (normally `http://localhost:4173`). The development and preview servers bind to all interfaces for use in a development container; they are development tools, not a production deployment. +The preview address is normally `http://localhost:4173`. Vite's development and preview servers bind to all interfaces for development-container use; they are not a production deployment. + +## Choose a telemetry source + +Use **Telemetry source** to switch between: + +| Source | What it displays | Persistence | +| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | +| **Live simulation** | Moving demo vehicle, signed X/Y/Z acceleration axes, automatic/injected impacts, adjustable local thresholds | In memory; resets on refresh | +| **Event-only preview** | Sparse local test events; no device connection or fabricated continuous values | In memory; resets on refresh | +| **Supabase cloud** | Authenticated cloud sessions, live geographic GPS route, event locations, connection freshness, and threshold-event history for IMUs 1–3 | Database; survives visits and is shared with authorized observers | + +Cloud mode never falls back to demo values while claiming to show a real device. Sessions carry immutable **simulated** or **device** provenance. The optional cloud test drive uploads simulated GPS/events through the normal authenticated database path only into simulated sessions. No phone application, ESP32-S3 firmware, or physical sensor connection is included. + +## Enable Supabase cloud + +Follow the complete [Supabase setup guide](docs/SUPABASE_SETUP.md). The required steps are: + +1. Create a Supabase project and apply [`supabase/migrations/20261021000100_msd_cloud.sql`](supabase/migrations/20261021000100_msd_cloud.sql) in its SQL Editor, or use an initialized/linked Supabase CLI and `supabase db push`. +2. Enable email/password Auth, configure the frontend Site URL and allowed redirect URLs, and confirm user emails. +3. Copy `.env.example` to `.env.local`, set `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY` to your project's **public** values, then restart Vite. A legacy public anon key is also supported. +4. Select **Supabase cloud**, sign in, create a simulated cloud session, and start its cloud test drive. Observe from a second browser, or share the session with another registered, email-confirmed user's email. + +No credentials are needed to build or run the tests. All `VITE_` values are public in browser bundles. **Never put a Supabase service-role/secret key, database password, or administrative access token in frontend configuration.** The public key plus the signed-in user's JWT and database RLS determine access. -## Choose a telemetry mode +Owners control session creation, uploads, threshold settings, completion, and sharing. Explicitly shared observers can only read. Unrelated and anonymous users cannot access session data. Realtime reconnect refreshes and periodic reconciliation recover missed changes and recheck access. -Use the **Telemetry source** selector at the top of the dashboard: +## Availability and impact semantics -- **Live simulation** retains the moving-vehicle demonstration, three continuously updated acceleration axes, and automatic/injected impact pulses. Every continuous value is labeled simulated. -- **Event-only preview** prepares the UI for the ESP32-S3’s threshold-event protocol. No device is connected. Continuous acceleration, live GPS, route, speed, and distance are unavailable; the dashboard does not fill them with simulated values or zeros. **Inject test event** delivers a local sparse threshold packet through the event adapter. Its provenance remains **Test event**, never **Device event**. +For known resultant acceleration `A = sqrt(x² + y² + z²)`, the rule is **green A < T1; yellow T1 ≤ A ≤ T2; red A > T2**. Both exact thresholds are yellow. Thresholds satisfy `0 < T1 < T2 ≤ 10 g`; default values are 0.8 g and 1.8 g. They are demonstration defaults, not calibrated safety limits. -Event-only packets may omit peak magnitude and GPS. The event table displays **Not supplied** instead of generating either value. Session distance is **Not available** when no continuous position stream exists. The two modes keep separate in-memory histories, so simulation records cannot appear as real-device records after changing modes. +**Gray means unavailable, stale, or unknown.** In event-only/cloud mode, a threshold event describes a past impact, not continuous current acceleration. No events, fresh GPS, or a healthy gateway heartbeat do not establish a green IMU state. Cloud IMU cards show the latest reported event separately from unknown current motion, and never invent continuous X/Y/Z readings. Complete raw IMU data is intended to stay on the ESP32-S3. -![Event-only preview showing unknown current motion and a sparse test event](docs/event-only.png) +Cloud GPS freshness uses its source `recorded_at` time with a five-second limit; an old packet uploaded now is still historical. Gateway heartbeat freshness has a fifteen-second limit. The live map shows observed route coordinates and supplied event locations; stale GPS does not claim a live vehicle. Optional peak magnitude/GPS values remain `null` and display as **Not supplied**. Connection status to Supabase is separate from gateway status. -## Try the dashboard +Cloud GPS/events are immutable and use stable packet UUIDs and sequence numbers. Duplicate/conflicting identities are first-write wins. Delayed/out-of-order points are sorted by source time without moving the live marker backward; packets recorded within a finished session's original time bounds can still arrive later. See [Telemetry protocol](docs/TELEMETRY_PROTOCOL.md) for fields, RPC examples, clock bounds, retry rules, and future phone-gateway responsibilities. -- **Live GPS (simulation only):** a demo vehicle travels a closed San Francisco route at 32 km/h. The map follows it; drag to explore, use +/− to zoom, and use the target button to resume following. Impact markers include event timestamps and coordinates when those values are supplied. -- **IMU indicators (simulation only):** view signed X (longitudinal), Y (lateral), and Z (vertical) acceleration in g, with the latest 24 seconds plotted. Values represent linear acceleration with gravity removed. These are not ESP32-S3 readings. -- **Traffic light:** for fresh simulated resultant acceleration `A = sqrt(x² + y² + z²)`, green means **A < T1**, yellow means **T1 ≤ A ≤ T2**, and red means **A > T2**. Both exact threshold values are yellow. Gray means current motion is unknown or data is unavailable/stale. -- **Demo thresholds:** open the threshold settings dialog. The prototype supports `0 < T1 < T2 ≤ 10 g`, defaulting to T1 = 0.8 g and T2 = 1.8 g. Changes apply only to the local live demonstration. They are not sent to a device and do not reclassify recorded events. These values are not calibrated safety limits. -- **Impact simulation:** select **Simulate impact** in live simulation to inject a short pulse. Automatic warning and critical pulses also occur at alternating 30-second intervals. One continuous excursion produces one event; its peak magnitude, timestamp, GPS location, and highest observed severity update as the pulse evolves. -- **Freshness:** availability, connection state, last-received time, and age are separate from impact severity. Live samples older than **5 seconds** are stale; their acceleration and GPS are hidden and the current traffic light becomes gray. Use **Pause updates** to exercise connected-but-stale behavior. Turning **Data feed** off disconnects immediately; reconnecting waits for a new sample instead of restoring an old green status. -- **Event-only silence:** no threshold events does **not** mean the vehicle is below T1, healthy, or currently safe. A threshold packet describes a historical impact, not continuous motion. Event-only current status remains **unknown/gray**; the latest event is shown separately with its timestamp and provenance. A locally injected test event never establishes device connectivity. Event age is recency information, not a device heartbeat. -- **Session history:** select **New session** to save the current session and begin another. Simulated drives retain measured distance, duration, impact count, and maximum magnitude. Event-only sessions retain event activity without inventing missing distance or acceleration. -- **Impact history:** open **Impact events** and filter by severity. Event packets retain their reported severity; changing local demo thresholds does not reclassify them. An empty log or zero impacts is not a confirmed green state. -- **Export:** **Export data** downloads a JSON snapshot containing the active mode, provenance, thresholds, sessions, and timestamped impact records. Unknown peak/GPS/distance values remain `null`. +## Try the local demonstrations -Live simulation starts with three explicitly simulated historical sessions and three impact events. Event-only preview starts empty. Active data, settings, and newly recorded history are held **in memory** and reset on refresh. Export JSON before refreshing to retain a copy. Times use the browser’s local timezone; exported timestamps are Unix milliseconds and export time is ISO 8601. +- **Live GPS and axes:** the local vehicle follows a San Francisco route at 32 km/h. Its three displayed axes are simulated linear acceleration with gravity removed, not ESP32-S3 telemetry. +- **Impact controls:** select **Simulate impact** to inject a pulse. Automatic warning/critical pulses also alternate at thirty-second intervals. One continuous excursion becomes one peak event. +- **Threshold settings:** local demo settings affect only the live demonstration. Cloud per-IMU settings persist separately and do not reclassify recorded events or prove firmware delivery. +- **Freshness controls:** **Pause updates** demonstrates a connected but stale local stream; **Data feed** disconnects immediately. Missing/stale current readings and GPS are hidden and the status becomes gray. Reconnect waits for new samples. +- **Event-only preview:** **Inject test event** creates a labeled sparse local packet. It never establishes a real device connection or infers green from silence. +- **History/export:** local mode histories stay separate and reset on refresh. Export JSON before refreshing to retain them. Cloud sessions and events reload from Supabase between visits. -## Map and offline behavior +![MSD Impact Monitor local simulation](docs/dashboard.png) -The map uses Leaflet and public OpenStreetMap raster tiles, with visible attribution. Tile access is the only external browser request; fonts and application assets are bundled locally. In live simulation, if tile loading fails or the browser is offline, an **illustrated offline basemap** keeps GPS coordinates, the route, vehicle movement, and event markers usable. Event-only preview does not show a simulated live map. The illustration is approximate and is not a navigation map. OpenStreetMap tiles are subject to their [usage policy](https://operations.osmfoundation.org/policies/tiles/); choose an appropriate tile service before a production deployment. +![Local event-only preview with unknown motion and a sparse test event](docs/event-only.png) + +## Map behavior + +Leaflet uses public OpenStreetMap raster tiles with attribution. Fonts and application assets are bundled locally. When tiles are blocked or unavailable, an illustrated offline basemap still supports geographically placed route/vehicle/event data; it is approximate and is not a navigation map. Local event-only preview does not invent a live route. OpenStreetMap's [tile usage policy](https://operations.osmfoundation.org/policies/tiles/) applies; choose a suitable tile provider before production deployment. ## Validate ```sh npm run build # TypeScript checks and optimized Vite build -npm test # Domain and telemetry unit tests -npm run test:e2e # Browser interaction and mobile checks +npm test # Domain, adapters, repository, and actual SQL/RLS migration tests +npm run test:e2e # Local and cloud browser workflows with controlled fixtures npm run format:check ``` -Browser tests use `/usr/bin/chromium` when available. Otherwise install Playwright’s browser once: - -```sh -npx playwright install chromium -npm run test:e2e -``` +Browser tests use `/usr/bin/chromium` when available. Otherwise install Playwright's browser once with `npx playwright install chromium`; on Linux, `npx playwright install --with-deps chromium` can also install required libraries. The browser runner starts its own isolated server and blocks external map tiles to exercise the fallback. GitHub Actions runs build, unit/database, and browser checks. -On Linux, `npx playwright install --with-deps chromium` can also install required system libraries. Browser tests start the app automatically on port 5173 and deliberately block external map tiles to exercise the offline fallback. GitHub Actions runs build, unit, and browser checks on pull requests and main-branch pushes. +SQL tests execute the real migration in PostgreSQL via PGlite with **test-only** auth fixtures and roles. Cloud service/browser tests simulate Supabase HTTP and Realtime. They need no hosted-project credentials and do not claim to validate your project's email delivery, deployment, or network configuration. After configuring your own project, complete the [two-observer acceptance checklist](docs/SUPABASE_SETUP.md#4-test-two-observers-with-simulated-cloud-telemetry). ## Project structure ```text src/ - components/ Map, acceleration chart, statistics, event/session tables, settings - data/demo.ts Explicitly seeded demonstration history - domain/ - types.ts Normalized telemetry, event, threshold, and session models - monitoring.ts Pure magnitude, classification, validation, and GPS distance logic - freshness.ts Explicit waiting/fresh/stale/disconnected classification - *.test.ts Domain and freshness tests - hooks/useMonitor.ts Live state, event aggregation, sessions, and JSON export - lib/format.ts Time and duration presentation - services/telemetry.ts - Deterministic simulator and sparse event-only adapter - services/*.test.ts Event-only packet/provenance and adapter cleanup tests - App.tsx Dashboard layout and navigation - styles.css Responsive theme - tests/ Browser-level behavior and mobile layout checks + components/ Local/cloud dashboards, geographic map, auth, event/session views + domain/ Shared records, classification, freshness, deduplication, SQL tests + hooks/ Local monitor, cloud auth, scoped/reconnecting cloud session state + services/ + telemetry.ts Local continuous simulator and sparse event-only adapter + supabase.ts Public environment validation and lazy authenticated client + cloudRepository.ts Paginated reads, authenticated RPCs, and Realtime subscriptions + cloudSimulator.ts Owner-controlled simulated cloud GPS/events/heartbeat publisher +supabase/migrations/ Versioned schema, constraints, RPCs, RLS, and Realtime publication + tests/ Browser behavior, including credential-free cloud fixtures + docs/ Supabase setup and future telemetry protocol ``` -## Later integration - -No cloud integration is started in this change. The existing boundaries are ready for later work: - -1. **ESP32-S3 → driver phone gateway:** use the event-first `TelemetryMessage` union to distinguish threshold-event packets from connection notifications. The ESP32-S3 will transmit threshold events, not continuous acceleration. A packet’s reported warning/critical severity is retained; optional peak magnitude and GPS stay `null` when absent. Continuous `sample` messages are typed as simulation data only. Implement a separate gateway adapter when hardware work begins, without making the simulator an implicit fallback. -2. **Connection and freshness:** keep transport connectivity independent of event arrival. Sparse events do not establish a heartbeat, and event silence cannot confirm current normal acceleration. A future gateway must report connection state and any explicit heartbeat/freshness contract separately. A recent historical event must not be represented as a current sensor reading. -3. **Persistence (later):** keep any future database calls in a service layer around the shared session and event models. Authentication, schema migrations, and row-level security are separate future work. No Supabase client, configuration, or database connection is added now. -4. **Configuration:** no environment variables are needed today. Introduce documented public configuration only when an integration is added. - -No hardware connection, cloud database, real GPS collection, or authentication is implemented in this prototype. +The cloud observer integration is implemented here; driver phone software, microcontroller firmware, raw-IMU cloud streaming, and production deployment are future work. diff --git a/docs/SUPABASE_SETUP.md b/docs/SUPABASE_SETUP.md new file mode 100644 index 0000000..2f5b024 --- /dev/null +++ b/docs/SUPABASE_SETUP.md @@ -0,0 +1,140 @@ +# Supabase setup + +The dashboard builds and runs its local demonstration without a Supabase account or credentials. To enable **Supabase cloud**, configure your own project using the steps below. No hosted project is created or modified by this repository, and no privileged key is needed in the frontend. + +## 1. Create a project and install the database migration + +Create a Supabase project and wait until its database is available. In the project's **SQL Editor**, open a new query and run the complete contents of: + +[`supabase/migrations/20261021000100_msd_cloud.sql`](../supabase/migrations/20261021000100_msd_cloud.sql) + +Apply this migration once to a fresh project. It uses the standard Supabase `auth.users`, `auth.uid()`, `anon`, and `authenticated` objects. Do not run the test-only auth fixtures against your project. Keep this migration in version control and use new migrations for later schema changes. + +If you already use an installed and initialized Supabase CLI for this checkout, you can apply the same migration through its normal workflow instead: + +```sh +supabase login +supabase link --project-ref YOUR_PROJECT_REF +supabase db push +``` + +CLI login credentials belong to the CLI's secure setup, never to a `VITE_` variable or a tracked file. A local Docker/Supabase stack is optional; the credential-free SQL tests use PGlite and do not require one. + +The migration creates these six tables: + +| Table | Purpose | +| ------------------- | --------------------------------------------------------------------------------------- | +| `driving_sessions` | Owner, immutable simulated/device provenance, label, start/end time | +| `session_observers` | Explicit read-only access grants for registered users | +| `gps_points` | Append-only GPS route points, normally uploaded about once per second | +| `threshold_events` | Append-only events for IMUs 1, 2, and 3, with threshold snapshots and optional GPS/peak | +| `connection_status` | Append-only gateway connection/heartbeat history | +| `imu_thresholds` | Configured T1/T2 values for all three IMUs in a session | + +All six tables have row-level security. Owners and explicitly shared observers can read authorized session data. Observers cannot upload telemetry, change thresholds, finish sessions, or manage sharing. Owners write through narrowly scoped authenticated RPCs; direct browser table writes and changes to session ownership or provenance are denied. Anonymous users have no access to session records. + +The migration adds five tables to the `supabase_realtime` publication: `driving_sessions`, `gps_points`, `threshold_events`, `connection_status`, and `imu_thresholds`. Membership in `session_observers` is deliberately not published: Realtime DELETE notifications must not disclose observer identities. Sharing, revocation, and session discovery are rechecked with authorized queries on reconnect and during the ten-second reconciliation cycle. In your project's database replication/publication settings, verify the five published tables are present. This read-only SQL check is another way to inspect the publication: + +```sql +select schemaname, tablename +from pg_publication_tables +where pubname = 'supabase_realtime' + and schemaname = 'public' +order by tablename; +``` + +Keep RLS enabled. Do not add broad anonymous read/write policies to make Realtime work. + +## 2. Configure authentication + +In **Authentication → Providers**, enable email/password sign-in. Keep email confirmation enabled for normal use; configure an SMTP provider and email delivery settings appropriate to your deployment. + +In the authentication URL configuration: + +- Set **Site URL** to the frontend origin you use, for example `http://localhost:5173` during local development. +- Add the exact development, preview, and deployed callback origins/URLs you will use to the allowed redirect list. The usual local preview origin is `http://localhost:4173`; Vite prints its actual address when starting. Use the actual HTTPS application URL for a deployed frontend. +- Do not use a public wildcard redirect in production. + +Create accounts through **Supabase cloud → Create an account** in the dashboard. Confirm the email before signing in. PKCE email confirmation works best in the same browser where account creation began. If the confirmation link returns to local simulation, choose **Supabase cloud** to finish loading the cloud account state. + +Sharing requires the observer to have registered and confirmed their email in the same Supabase project. It does not create accounts or send invitations automatically. + +## 3. Set the public frontend configuration + +Find your project's URL and its **publishable** key in Supabase's project connection/API-key settings. From the repository root: + +```sh +cp .env.example .env.local +``` + +Replace the two placeholders in `.env.local`: + +```dotenv +VITE_SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.co +VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_PROJECT_PUBLISHABLE_KEY +``` + +A legacy public `anon` JWT is supported as `VITE_SUPABASE_ANON_KEY` when a publishable key is unavailable. Remove or comment out `VITE_SUPABASE_PUBLISHABLE_KEY` before using that alternative; leaving its placeholder set will keep configuration unavailable. If both key variables are set, the publishable-key variable takes precedence. + +These values are public application configuration. All `VITE_` variables are included in the browser build. **Never put a `service_role` JWT, an `sb_secret_` key, a database password, or an administrative access token in frontend environment variables or source code.** Build-time and runtime checks reject known privileged-key formats in the supported key variables, and the runtime client references only the three documented public configuration fields. These guards do not make it safe to put secrets in frontend variables or source files. RLS and the signed-in user's session enforce access with the public project key. + +`.env.local` is ignored by Git. Do not commit real configuration values. Restart Vite after changing environment variables, or rebuild and redeploy when using a production bundle: + +```sh +npm ci +npm run dev +``` + +For a production preview: + +```sh +npm run build +npm run preview +``` + +If your execution environment restricts network destinations, allow your specific project hostname (for example `YOUR_PROJECT_REF.supabase.co`) for HTTPS and secure WebSocket traffic in that environment's network settings. Map tiles are optional and use `tile.openstreetmap.org`; the bundled offline map still shows route coordinates and markers when tiles are blocked. Do not disable TLS verification or use a privileged key to work around a network error. + +## 4. Test two observers with simulated cloud telemetry + +1. Start the frontend and choose **Supabase cloud** in **Telemetry source**. Missing configuration is shown as setup guidance; it never falls back to local simulated readings while claiming to be cloud-connected. +2. Create an owner account, confirm its email, and sign in. Create a new cloud session with **simulated** provenance and a descriptive label. Session creation also installs default T1 = 0.8 g / T2 = 1.8 g settings for IMUs 1, 2, and 3. +3. Select that session and start its **cloud test drive**. Only the owner can start it, and only for an active session labeled simulated. It uploads GPS about once per second, connection heartbeats about every five seconds, and a sparse threshold event about every ten seconds, cycling through all three IMUs. It never uploads continuous raw IMU samples. +4. In a second browser or private window, either sign in to the same owner account for a quick observation test, or create a separate observer account and confirm its email. For the separate account, use the owner's sharing control to grant that email access, then sign in as the observer. The observer should see the same route and new events without receiving write controls. +5. Keep the test drive running in only one browser. Check the route and marker in the second browser, then reload it: the session, route, and recorded events should reload from the database. The Realtime subscription receives changes, and the dashboard refetches on reconnect and periodically reconciles state. +6. Verify each IMU's configured T1/T2 values. Owner changes are persisted, but are **configuration records**, not proof that a future ESP32 received them. Saving thresholds stops the test drive. Start it again to use the new threshold snapshot. Recorded events retain their original threshold snapshots and severity. +7. Stop the cloud test drive. The latest GPS becomes stale after five seconds and the gateway heartbeat after fifteen seconds. A historical route remains viewable, but an old packet does not claim a live vehicle or green IMU status. Stopping does not fabricate a device-disconnected packet; the heartbeat expires naturally. +8. Finish the session and confirm it remains in history after refresh or signing out and back in. Try signing in as an unrelated account: the session must not appear. Revoke a shared observer and verify a subsequent refresh/reconciliation removes their access. + +A browser may retain data it already downloaded; revocation prevents subsequent authorized reads and the UI clears inaccessible session data when it detects the change. It cannot erase screenshots or previously exported files. + +The test uploader is a development tool with a bounded, in-memory retry queue. It serializes requests, preserves packet identities during retries, and surfaces failures. On stop it drops unsent queued packets and permits an already-started request to finish. It is not a phone application's durable offline outbox. + +## 5. Verify availability and safety semantics + +Cloud GPS availability, gateway connection status, Realtime subscription status, and IMU impact history are separate signals: + +- The current GPS position is chosen using source `recorded_at` time, not arrival time. A just-uploaded old point stays historical. GPS older than five seconds is stale. +- Gateway status comes from its latest sequence-numbered connection packet. A heartbeat older than fifteen seconds does not establish current connectivity. +- A connected observer WebSocket is a connection to Supabase, not evidence that the phone, vehicle, or IMUs are currently transmitting. +- Event-only IMU cards remain **unknown/gray** for current motion. A recent warning/critical event is a historical report. No events, fresh GPS, and a healthy heartbeat do not confirm a current green acceleration state. +- Where acceleration is actually known, the rule remains **green A < T1; yellow T1 ≤ A ≤ T2; red A > T2**. Both exact thresholds are yellow. + +The driver phone application and ESP32-S3 firmware are not implemented here. The ESP32-S3 will retain complete raw IMU data locally; a later authenticated phone gateway will upload GPS and threshold packets using the protocol in [TELEMETRY_PROTOCOL.md](TELEMETRY_PROTOCOL.md). + +## Troubleshooting + +| Symptom | Check | +| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| Cloud setup guidance appears | Replace both placeholders in `.env.local` and restart Vite; verify a public publishable/anon key is used | +| Email sign-in fails | Confirm the account's email, project, password, and enabled email provider | +| Confirmation returns to a wrong URL | Update Auth Site URL/redirect settings and use the same browser for the PKCE confirmation flow | +| Session list is empty | Create an owned session, or ask its owner to share it with your confirmed account's email | +| RPC/table is missing | Apply the full migration to the same project used by the frontend | +| Data loads but live changes do not | Verify the `supabase_realtime` publication, project Realtime status, WebSocket network access, and authenticated SELECT policies | +| New uploads fail after finishing | Only packets recorded within the session's original start/end window can be accepted; new post-session telemetry is rejected | +| A retry does not alter a row | Expected: immutable duplicate UUIDs/sequences are first-write wins; upload a new packet rather than editing history | +| Old data appears gray | Expected for stale source timestamps; a new `received_at` time does not make old telemetry live | + +## What has and has not been validated + +The repository includes tests that execute the actual migration in PostgreSQL via PGlite with test-only auth roles/users; service/domain tests use controlled inputs; browser tests use simulated Supabase HTTP and Realtime fixtures. They run without project credentials. These checks validate the implementation, SQL constraints/RLS, and client behavior but do **not** establish that your hosted project, email delivery, or network policy is configured correctly. Complete the two-observer checklist above against your own project before relying on hosted operation. diff --git a/docs/TELEMETRY_PROTOCOL.md b/docs/TELEMETRY_PROTOCOL.md new file mode 100644 index 0000000..91b3459 --- /dev/null +++ b/docs/TELEMETRY_PROTOCOL.md @@ -0,0 +1,142 @@ +# Stage 2 telemetry and storage protocol + +This contract prepares the observer dashboard for a later phone gateway. It does not implement the driver phone application or ESP32-S3 firmware. Complete raw IMU data remains on the ESP32-S3. Cloud storage contains continuous GPS, sparse threshold events, explicit connection/heartbeat packets, session metadata, and per-IMU threshold configuration. + +## Trust and ownership + +Every cloud request uses the signed-in user's Supabase session with the public publishable/anon project key. The database assigns session ownership from `auth.uid()`; clients cannot supply or change the owner. Only an owner can upload to, finish, configure, or share a session. Shared observers have read-only access enforced by RLS. Anonymous clients and unrelated authenticated users cannot read its records. + +The frontend must never receive a service-role/secret key. A future phone uploader must authenticate as the session owner, or use a separately designed narrowly scoped ingestion service. No such privileged ingestion service is included in Stage 2. + +`data_source` is `simulated` or `device` and is fixed when the session is created. A cloud test drive can publish only into an active `simulated` session. It cannot label generated telemetry as a real-device session. Local simulation, local test events, and cloud session records are never an implicit fallback for one another. + +## Shared identity, time, and retry rules + +- Generate a stable UUID for each GPS point and each threshold event before enqueueing it. +- Allocate an increasing, JavaScript-safe nonnegative integer `sequence` for each stream within the session. GPS, threshold-event, and connection streams have separate sequence spaces. Threshold-event sequence is shared across **all three IMUs**, not restarted for each IMU. +- Preserve the UUID, sequence, source timestamp, and payload when retrying. A future phone's durable outbox must preserve sequence allocation across restarts; the browser test uploader is an in-memory development tool only. +- Use ISO 8601 UTC timestamps. `recorded_at` is when the source recorded the GPS/event/status. `received_at` is assigned by PostgreSQL and cannot be supplied by an uploader. +- A packet must be recorded on/after session start and, for a finished session, on/before its end. Delayed uploads of packets within that window are accepted even after the session has finished. Source time may be at most 60 seconds ahead of database time; larger clock errors are rejected. +- GPS and event UUIDs are primary keys and `(session_id, sequence)` is unique. Connection identity is `(session_id, sequence)`. Duplicate/conflicting keys are **first-write wins**: accepted history is not overwritten by a retry or a conflicting replay. +- A GPS/event batch contains 1–100 records and is atomic. Invalid fields or timestamps reject the call; split larger backlogs into batches and handle errors explicitly. Constraints still apply to retry payloads: retry the original valid payload rather than using a duplicate key to submit invalid values. +- Finishing a session is serialized with ingestion. Its end time includes any already accepted source timestamps within the allowed clock tolerance, so accepted history remains inside the closed session window. New telemetry after that end is rejected. +- Upload/arrival order is not display order. GPS and events are deduplicated and ordered by `recorded_at`, with sequence as a stable tie-breaker. The live marker uses the newest source point; a delayed older point extends the historical route without moving the live vehicle backward. Latest connection status is chosen by highest sequence. +- Current freshness uses source time, never `received_at`. Future-dated or stale source data must not claim fresh current readings. Realtime notifications from the five published session/telemetry tables trigger database refreshes; reconnect refresh and ten-second reconciliation recover missed changes. Observer membership is not published, so authorized reconciliation also discovers sharing and revocation without exposing membership DELETE notifications. + +These rules assume one coordinated uploader for each session. Multiple independent publishers must not allocate the same session/stream sequence space. + +## RPCs + +The following are authenticated Supabase RPCs in `public`: + +| RPC | Parameters | Result/purpose | +| ------------------------- | ----------------------------------------- | ------------------------------------------------------------------------- | +| `create_driving_session` | `p_label`, `p_data_source` | Returns the new UUID and atomically creates default settings for IMUs 1–3 | +| `finish_driving_session` | `p_session_id` | Sets end time once; does not erase history | +| `ingest_gps` | `p_session_id`, `p_points` JSON array | Append GPS points; duplicates do not overwrite | +| `ingest_threshold_events` | `p_session_id`, `p_events` JSON array | Append sparse IMU events with threshold snapshots | +| `ingest_connection` | `p_session_id`, `p_status` JSON object | Append a connection/heartbeat packet | +| `set_imu_thresholds` | `p_session_id`, `p_thresholds` JSON array | Atomically set all three IMUs' T1/T2 configuration for an active session | +| `share_session` | `p_session_id`, `p_email` | Grant read access to an already registered, email-confirmed account | +| `revoke_session_observer` | `p_session_id`, `p_user_id` | Revoke that observer's future reads | + +Use the repository methods in `src/services/cloudRepository.ts` from the frontend. The examples below show the underlying wire contract for the future uploader. They require an authenticated owner and an active session; the public key alone cannot upload. + +## GPS, approximately 1 Hz + +```ts +const point = { + id: crypto.randomUUID(), + sequence: 1, // Allocate once and retain through retry. + recorded_at: new Date().toISOString(), + latitude: 37.7793, + longitude: -122.4193, + speed_kph: 32, // null when unavailable + heading: 140, // degrees clockwise from north; null when unavailable +}; + +const { error } = await supabase.rpc("ingest_gps", { + p_session_id: sessionId, + p_points: [point], +}); +if (error) throw error; +``` + +Latitude must be within −90…90 and longitude within −180…180. Optional speed is finite and nonnegative; optional heading is at least 0 and less than 360. GPS source samples should target roughly one per second. Cellular delivery can be delayed or batched; that does not change the original timestamps or packet identities. + +The dashboard fetches paginated history rather than relying on Supabase's default 1,000-row response limit. It shows the observed route and event markers. An illustrated offline basemap remains available when public map tiles cannot load; the underlying GPS coordinates remain geographic data. + +## Threshold events for three IMUs + +```ts +const event = { + id: crypto.randomUUID(), + sequence: 1, // One event sequence space across IMUs 1, 2, and 3. + imu_id: 2, + recorded_at: new Date().toISOString(), + severity: "warning", + magnitude: 1.8, // optional peak resultant acceleration in g; null if omitted + latitude: null, + longitude: null, // both coordinates supplied together or both null + t1: 0.8, + t2: 1.8, +}; + +const { error } = await supabase.rpc("ingest_threshold_events", { + p_session_id: sessionId, + p_events: [event], +}); +if (error) throw error; +``` + +`imu_id` is exactly 1, 2, or 3. An event snapshots the T1/T2 values that applied when it occurred. They must satisfy `0 < T1 < T2 ≤ 10 g`. The rule is: + +| Known acceleration A | Classification | +| -------------------- | -------------- | +| A < T1 | Green/normal | +| T1 ≤ A ≤ T2 | Yellow/warning | +| A > T2 | Red/critical | + +Threshold events contain warning or critical reports; absence of an event is not a normal/green report. If a peak magnitude is supplied, it must agree with the event's snapshot classification. Both exact boundaries are warning. When the magnitude is absent, the reported severity is retained without inventing a peak. Optional event GPS is `null` when no event location was supplied; the dashboard does not silently substitute a current or simulated location. + +No continuous X/Y/Z acceleration samples are stored or synthesized for cloud mode. A latest-event badge is a historical observation, not the IMU's current state. All three cloud IMU current-state indicators remain unknown/gray when only threshold events are available, regardless of GPS freshness or time since the last event. + +## Connection status and heartbeat + +```ts +const { error } = await supabase.rpc("ingest_connection", { + p_session_id: sessionId, + p_status: { + sequence: 1, + recorded_at: new Date().toISOString(), + connected: true, + }, +}); +if (error) throw error; +``` + +Connection packets are append-only. The newest sequence determines the most recent known gateway status; late delivery of an older sequence cannot replace it. For the cloud simulator, a connected heartbeat is sent about every five seconds. A latest status older than fifteen seconds is stale. A fresh observer-to-Supabase WebSocket does not prove a fresh phone-to-vehicle connection. + +The simulator's stop control stops its timer and drops unsent queued packets; an in-flight RPC can still finish. It does not create a fake disconnected packet on behalf of a device. Its last heartbeat naturally ages out. A future phone gateway may upload an explicit `connected: false` observation when it actually detects a disconnection. + +## Per-IMU threshold configuration + +```ts +const { error } = await supabase.rpc("set_imu_thresholds", { + p_session_id: sessionId, + p_thresholds: [ + { imu_id: 1, t1: 0.8, t2: 1.8 }, + { imu_id: 2, t1: 0.8, t2: 1.8 }, + { imu_id: 3, t1: 0.8, t2: 1.8 }, + ], +}); +if (error) throw error; +``` + +Supply exactly the three unique IMU IDs in one call. Configuration is persisted and available to all authorized observers. Historical event snapshots are unchanged. Stage 2 does not send configuration to ESP32-S3 firmware or acknowledge its application; that phone/firmware synchronization is future work. Saving cloud thresholds stops the browser test drive; start it again to use the updated snapshot. + +## Simulated cloud publishing + +The development publisher uses the same authenticated repository/RPC path as later uploads, but only into a session whose immutable `data_source` is `simulated`. It enqueues GPS immediately and about every second, a heartbeat every five ticks, and one sparse threshold event every ten ticks, cycling IMUs so all three are exercised over about thirty seconds. + +Requests are serialized and transient failures retain packet identity for retry. The queue is bounded at 60 pending packets; overflow skips new GPS rather than growing without limit and surfaces an error. Stop/reload is not durable recovery: the queue is in memory and unsent items are discarded. A real phone will need a durable outbox, coordinated sequence allocation, clock handling, and explicit synchronization, none of which is implemented here. diff --git a/docs/cloud-preview.png b/docs/cloud-preview.png new file mode 100644 index 0000000..b4656cb Binary files /dev/null and b/docs/cloud-preview.png differ diff --git a/package-lock.json b/package-lock.json index f61e352..e74cc1a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,18 +10,22 @@ "dependencies": { "@fontsource-variable/dm-sans": "^5.3.0", "@fontsource-variable/manrope": "^5.3.0", + "@supabase/supabase-js": "^2.118.0", "leaflet": "^1.9.4", "lucide-react": "^0.468.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { + "@electric-sql/pglite": "^0.5.11", "@playwright/test": "^1.56.1", + "@testing-library/react": "^16.3.3", "@types/leaflet": "^1.9.21", "@types/node": "^24.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.0", + "jsdom": "^30.1.3", "prettier": "^3.9.10", "typescript": "~5.9.3", "vite": "^7.1.12", @@ -31,6 +35,59 @@ "node": ">=22.12.0" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.7.tgz", + "integrity": "sha512-Q7ioeear07HwixdIitIn9KS1LZi97CEDFCSjPNm9v+y8KNbsu9q4Lrd4zUQW4faED+E7qxvfeVnbNRW46wFKuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.4.3", + "@csstools/css-color-parser": "^4.2.6", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.4.tgz", + "integrity": "sha512-A6f1nKy99I6tyoK82U6kBHvQQZmdHmTmPzJYPY/0eaOW0r8/qPmEOwjGHs+hL/vCgOwQTupu4LT1XtXNUuDruA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -265,6 +322,16 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -313,6 +380,166 @@ "node": ">=6.9.0" } }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz", + "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz", + "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@electric-sql/pglite": { + "version": "0.5.11", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.11.tgz", + "integrity": "sha512-SWuqsTjA4DDWqgZ05PC1RJaq8e00p5KACxbqaikDFQ8dIGA0SLRzuPniky7IW+q/c5RDNMdEXwv7mFBWIx9Hxw==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -755,6 +982,24 @@ "node": ">=18" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@fontsource-variable/dm-sans": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/@fontsource-variable/dm-sans/-/dm-sans-5.3.0.tgz", @@ -1213,6 +1458,155 @@ "win32" ] }, + "node_modules/@supabase/auth-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.118.0.tgz", + "integrity": "sha512-xWfPXyhS2KDSfAneMtI6p/tBnbdiz/5vaRKXEqUfzfC9WCniKr2Ds5o5G7RIGig0bom4z6wUY9zaV07WDVTfnQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.118.0.tgz", + "integrity": "sha512-4ofletPa/noKAU6KHeqsd3FztGzRPUEJRey1MKY0o+PIHaVePqRPShIXtl37gcVyIWaFM+zNg6r9zh0uUSFOSA==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/phoenix": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.5.tgz", + "integrity": "sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==", + "license": "MIT" + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.118.0.tgz", + "integrity": "sha512-JXy+37KPApHsyotaQACovv/Jy9E22rfiWLRuT+2UjoEAcAIelDFIrsF/FY47Dy19mO7lI0Tq+zDCX8oJ2Ozfiw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.118.0.tgz", + "integrity": "sha512-pzCIEWjqD5/xqEZQerpt+q9rsgYkcrkgCJgf0W2ULqC4fYUeB/p9CFa3t9vn+IVh6dMN9r4ZCE262lZvUC+Bfw==", + "license": "MIT", + "dependencies": { + "@supabase/phoenix": "0.4.5", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.118.0.tgz", + "integrity": "sha512-5MNkKt2Moy7Jud/sPX7/28BwdDxZMCVHGJT00b8op3KRa9LKSjOAYU5IcfGWIstaasAqY8GkbA6oI3IRDgB1YQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.118.0.tgz", + "integrity": "sha512-FxI8UXMVC2UG7IkeiI8fuQZqq2oI3JeSuN8MPIC2RLVaoEAxKS0nqE6kii9Ewpq8f9gNPM6git1Y8f0vN/QLFw==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.118.0", + "@supabase/functions-js": "2.118.0", + "@supabase/postgrest-js": "2.118.0", + "@supabase/realtime-js": "2.118.0", + "@supabase/storage-js": "2.118.0" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + } + } + }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1466,6 +1860,42 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "dequal": "^2.0.3" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1489,6 +1919,16 @@ "node": ">=6.0.0" } }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/browserslist": { "version": "4.29.4", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.4.tgz", @@ -1588,6 +2028,20 @@ "dev": true, "license": "MIT" }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -1595,6 +2049,20 @@ "dev": true, "license": "MIT" }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1613,6 +2081,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/deep-eql": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", @@ -1623,6 +2098,25 @@ "node": ">=6" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/electron-to-chromium": { "version": "1.5.463", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.463.tgz", @@ -1630,6 +2124,19 @@ "dev": true, "license": "ISC" }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -1752,6 +2259,35 @@ "node": ">=6.9.0" } }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1759,6 +2295,56 @@ "dev": true, "license": "MIT" }, + "node_modules/jsdom": { + "version": "30.1.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", + "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^10.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.1", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "canvas": "^3.2.3" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -1817,6 +2403,17 @@ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" } }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1827,6 +2424,13 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -1863,6 +2467,19 @@ "node": ">=18" } }, + "node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -1974,6 +2591,32 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -1995,6 +2638,14 @@ "react": "^19.3.1" } }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/react-refresh": { "version": "0.18.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", @@ -2005,6 +2656,16 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/rollup": { "version": "4.64.12", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.12.tgz", @@ -2051,6 +2712,19 @@ "fsevents": "~2.3.2" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", @@ -2179,6 +2853,58 @@ "node": ">=14.0.0" } }, + "node_modules/tldts": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", + "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.19.tgz", + "integrity": "sha512-goNXV6Ho9TIOfpJZanTd6CKG5DyYgYAL+k+22T0SLh8l6+KHIfBUPFuePuSZv05UttIaaLmI9tb7TmGIdK5AkQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -2193,6 +2919,16 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", + "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/undici-types": { "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", @@ -2402,6 +3138,54 @@ } } }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -2419,6 +3203,23 @@ "node": ">=8" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/package.json b/package.json index 4b65add..27f8123 100644 --- a/package.json +++ b/package.json @@ -19,18 +19,22 @@ "dependencies": { "@fontsource-variable/dm-sans": "^5.3.0", "@fontsource-variable/manrope": "^5.3.0", + "@supabase/supabase-js": "^2.118.0", "leaflet": "^1.9.4", "lucide-react": "^0.468.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { + "@electric-sql/pglite": "^0.5.11", "@playwright/test": "^1.56.1", + "@testing-library/react": "^16.3.3", "@types/leaflet": "^1.9.21", "@types/node": "^24.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.0", + "jsdom": "^30.1.3", "prettier": "^3.9.10", "typescript": "~5.9.3", "vite": "^7.1.12", diff --git a/playwright.config.ts b/playwright.config.ts index a788f50..814aa5d 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -9,7 +9,7 @@ export default defineConfig({ workers: 2, reporter: "list", use: { - baseURL: "http://127.0.0.1:5173", + baseURL: "http://127.0.0.1:5175", viewport: { width: 1440, height: 1000 }, trace: "retain-on-failure", screenshot: "only-on-failure", @@ -18,9 +18,14 @@ export default defineConfig({ : {}, }, webServer: { - command: "npm run dev -- --port 5173", - url: "http://127.0.0.1:5173", - reuseExistingServer: true, + command: "npm run dev -- --port 5175 --strictPort", + url: "http://127.0.0.1:5175", + reuseExistingServer: !process.env.CI, + env: { + // Public, nonfunctional fixtures are intercepted by cloud browser tests only. + VITE_SUPABASE_URL: "https://msd-test.supabase.co", + VITE_SUPABASE_PUBLISHABLE_KEY: "sb_publishable_msd_browser_test_fixture", + }, timeout: 30_000, }, }); diff --git a/src/App.tsx b/src/App.tsx index ad80194..dde4396 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,866 +1,29 @@ -import { useState } from "react"; -import { - Activity, - ArrowDownToLine, - ArrowRight, - Bell, - Check, - ChevronDown, - ChevronRight, - CircleHelp, - Clock3, - Gauge, - LayoutDashboard, - MapPin, - MoreHorizontal, - Navigation, - Play, - Plus, - Route, - Settings2, - ShieldCheck, - SlidersHorizontal, - Sparkles, - TriangleAlert, - Wifi, - WifiOff, - X, - Zap, -} from "lucide-react"; -import { Stat } from "./components/StatCard"; -import { Sparkline } from "./components/Sparkline"; -import { EventTable } from "./components/EventTable"; -import { SessionTable } from "./components/SessionTable"; -import { ThresholdDialog } from "./components/ThresholdDialog"; -import { time, date, duration } from "./lib/format"; -import { VehicleMap } from "./components/VehicleMap"; -import { ROUTE_COORDINATES } from "./services/telemetry"; -import { TelemetryAvailability } from "./components/TelemetryAvailability"; -import { useMonitor } from "./hooks/useMonitor"; +import { lazy, Suspense, useState } from "react"; +import LocalDashboard from "./LocalDashboard"; +import type { TelemetryMode } from "./domain/types"; -type Page = "overview" | "events" | "sessions"; -const pageNames: Record = { - overview: "Vehicle overview", - events: "Impact events", - sessions: "Driving sessions", -}; +const CloudDashboard = lazy(() => + import("./components/CloudDashboard").then((module) => ({ + default: module.CloudDashboard, + })), +); export default function App() { - const monitor = useMonitor(); - const [page, setPage] = useState("overview"); - const [settingsOpen, setSettingsOpen] = useState(false); - const [eventFilter, setEventFilter] = useState("all"); - const [helpOpen, setHelpOpen] = useState(false); - const { - available, - mode, - connected, - freshness, - sample, - severity, - thresholds, - session, - events, - sessions, - now, - history, - } = monitor; - const isDemo = mode === "simulation"; - const magnitude = sample - ? Math.hypot( - sample.acceleration.x, - sample.acceleration.y, - sample.acceleration.z, - ) - : null; - const labels = { - normal: "All systems normal", - warning: "Moderate impact detected", - critical: "High impact detected", - unavailable: "Waiting for data", - }; - const statusDescriptions = { - normal: "Simulated acceleration is below T1. This is not a device reading.", - warning: - "Acceleration reached your warning threshold. An event has been logged.", - critical: - "Simulated acceleration is greater than T2. An event has been logged.", - unavailable: - "Current motion is unconfirmed. Fresh data is required before a green assessment.", - }; - const currentEvents = events.filter((e) => e.sessionId === session.id); - const filteredEvents = events.filter( - (e) => eventFilter === "all" || e.severity === eventFilter, - ); - - return ( -
- -
-
-
- Workspace - - {pageNames[page]} -
-
- - - {isDemo ? "Live simulation" : "Event-only preview"} - - - - DM -
-
-
-
-
- - VEHICLE INTELLIGENCE -
-
-
-

- {page === "overview" - ? "Every journey, in focus." - : pageNames[page]} -

-

- {page === "overview" - ? isDemo - ? "Real-time motion. Meaningful insights. A safer road ahead." - : "Threshold events with clear availability and source context." - : page === "events" - ? "A closer look at the moments that matter on the road." - : "Your driving activity, all in one place."} -

-
- -
-
- -
- - - - -
- {page === "overview" && ( - <> -
-
-
-
-

- - {isDemo ? "Live location" : "Event locations"} -

-

- {isDemo - ? "San Francisco, California · Simulated GPS" - : "Locations from individual event packets only"} -

-
- - - {!isDemo - ? "NO LIVE GPS" - : available - ? "SIMULATED GPS" - : "NO GPS DATA"} - -
- {isDemo ? ( - event.position !== null) - .map((event) => ({ - ...event, - position: event.position!, - }))} - route={ROUTE_COORDINATES} - available={available} - /> - ) : ( -
- -

Event locations only

-

- No live vehicle position is available. GPS appears only - when a threshold event supplies a location. -

-
    - {currentEvents.length === 0 ? ( -
  • No event locations received
  • - ) : ( - currentEvents.slice(0, 4).map((event) => ( -
  • - {time(event.timestamp)} ·{" "} - {event.position - ? `${event.position.latitude.toFixed(5)}, ${event.position.longitude.toFixed(5)}` - : "GPS not supplied"} -
  • - )) - )} -
-
- )} -
- - - - {isDemo ? "Demo vehicle" : "Event-only preview"} - - · - {isDemo ? "MSD-001" : "No device"} - - - - - {available && sample - ? Math.round(sample.speedKph) - : "—"} - {" "} - km/h - -
-
-
-
-
-

- - Impact status -

-

- {isDemo - ? "Simulated assessment · Fresh samples only" - : "Current motion cannot be inferred from events"} -

-
- -
-
-
- - - - - - - - - -
- - {!isDemo - ? "CURRENT STATE UNKNOWN" - : severity === "unavailable" - ? "SIGNAL UNAVAILABLE" - : severity === "normal" - ? "YOU’RE IN THE GREEN" - : "THRESHOLD EXCEEDED"} - -
-

- {!isDemo - ? "Current motion unknown" - : freshness === "stale" - ? "Telemetry is stale" - : labels[severity]} -

-
-

- {isDemo - ? statusDescriptions[severity] - : "Threshold events report past impacts, not ongoing safe motion. Event silence never confirms green."} -

-
- Resultant acceleration - - {available && magnitude !== null - ? magnitude.toFixed(2) - : "—"} - g - -
-
- {!isDemo && monitor.latestEvent && ( -
- - Last{" "} - {monitor.latestEvent.source === "test-event" - ? "test" - : "device"}{" "} - event ·{" "} - {monitor.latestEvent.severity === "critical" - ? "High impact" - : "Moderate"} - - - {time(monitor.latestEvent.timestamp)} · Historical - report, not current motion - - - Last{" "} - {monitor.latestEvent.source === "device" - ? "device" - : "test"}{" "} - event received{" "} - {monitor.lastEventReceivedAt === null - ? "never" - : `${Math.max(0, Math.floor((now - monitor.lastEventReceivedAt) / 1000))}s ago`} - {monitor.lastEventReceivedAt !== null && - now - monitor.lastEventReceivedAt > 5000 - ? " · Stale event record" - : " · Recent event record"} - -
- )} - {isDemo ? ( - - ) : ( -
- Demo settings do not configure device thresholds. -
- )} -
-
-
-
-
-

- - Motion at a glance -

-

- {isDemo - ? "Simulated axes · Gravity removed · Not device telemetry" - : "Not provided by event-only telemetry"} -

-
- - {isDemo ? ( - <> - LAST 24 SECONDS · g - - ) : ( - "NO CONTINUOUS DATA" - )} - -
-
- {(["x", "y", "z"] as const).map((axis, i) => ( -
-
- {axis.toUpperCase()} - - {["Longitudinal", "Lateral", "Vertical"][i]} - - -
-
- {available && sample - ? `${sample.acceleration[axis] >= 0 ? "+" : ""}${sample.acceleration[axis].toFixed(2)}` - : "—"} - g -
- {isDemo && available && ( - s.acceleration[axis]) - : [] - } - axis={axis} - /> - )} - {isDemo && !available && ( -
- No fresh samples -
- )} -
- {isDemo ? "24s ago" : "Not supplied"} - {isDemo ? "Now" : ""} -
-
- ))} -
-
-
-
-
-
-

- - Recent impacts - {events.length} -

-

Timestamped moments, with location context

-
- -
- -
-
-
-
-

- - Session history -

-

Recent driving activity

-
- -
-
- {sessions.slice(0, 3).map((s) => ( - - ))} -
- -
-
- - )} - {page === "events" && ( -
-
-
-

- - Impact event log - {filteredEvents.length} -

-

- Events retain the severity recorded at the time of impact. -

-
- -
- -
- )} - {page === "sessions" && ( -
-
-
-

- - Driving session history -

-

- Start a new session to save the current drive. History is - kept for this browser visit. -

-
- - {sessions.length + 1} SESSIONS - -
- -
- )} -
-
- - - -
- - {isDemo ? "Your virtual test drive" : "Sparse event preview"} - - - {isDemo - ? "Continuous simulated data · No device connection" - : "Local test packets only · No continuous samples"} - -
-
-
- {isDemo ? ( - <> - - - - - ) : ( - <> - - - - )} -
-
-
- - - Simulation and test events only. No hardware or cloud connection. - - - MSD Impact Monitor / Prototype - 0.1 - -
+ const [source, setSource] = useState("simulation"); + return source === "cloud" ? ( + +

Loading cloud dashboard…

-
- {settingsOpen && ( - setSettingsOpen(false)} - /> - )}{" "} - {monitor.notice && ( -
- - {monitor.notice} -
- )} - {helpOpen && ( -
- - BUILT FOR THE ROAD AHEAD -

Meet your impact monitor.

-

- This prototype simulates a vehicle driving around San Francisco. - Acceleration is measured in g, with gravity removed. Warning and - critical thresholds determine the traffic light and impact log. -

-

- Use the data feed switch to test missing data, or inject an impact - to see an alert. Sessions and changes are in memory and reset on - refresh; export JSON to keep a copy. -

-

- Continuous readings are simulation-only. Event-only mode displays - sparse local test packets and never confirms current safe motion. - GPS coordinates do not represent a real driver. -

-
- )} -
+ } + > + + + ) : ( + setSource("cloud")} + /> ); } diff --git a/src/LocalDashboard.tsx b/src/LocalDashboard.tsx new file mode 100644 index 0000000..2dbe0c7 --- /dev/null +++ b/src/LocalDashboard.tsx @@ -0,0 +1,875 @@ +import { useState } from "react"; +import { + Activity, + ArrowDownToLine, + ArrowRight, + Bell, + Check, + ChevronDown, + ChevronRight, + CircleHelp, + Clock3, + Gauge, + LayoutDashboard, + MapPin, + MoreHorizontal, + Navigation, + Play, + Plus, + Route, + Settings2, + ShieldCheck, + SlidersHorizontal, + Sparkles, + TriangleAlert, + Wifi, + WifiOff, + X, + Zap, +} from "lucide-react"; +import { Stat } from "./components/StatCard"; +import { Sparkline } from "./components/Sparkline"; +import { EventTable } from "./components/EventTable"; +import { SessionTable } from "./components/SessionTable"; +import { ThresholdDialog } from "./components/ThresholdDialog"; +import { time, date, duration } from "./lib/format"; +import { VehicleMap } from "./components/VehicleMap"; +import { ROUTE_COORDINATES } from "./services/telemetry"; +import { TelemetryAvailability } from "./components/TelemetryAvailability"; +import type { TelemetryMode } from "./domain/types"; +import { useMonitor } from "./hooks/useMonitor"; + +type Page = "overview" | "events" | "sessions"; +const pageNames: Record = { + overview: "Vehicle overview", + events: "Impact events", + sessions: "Driving sessions", +}; + +export default function LocalDashboard({ + initialMode, + onCloudMode, +}: { + initialMode: TelemetryMode; + onCloudMode: () => void; +}) { + const monitor = useMonitor(initialMode); + const [page, setPage] = useState("overview"); + const [settingsOpen, setSettingsOpen] = useState(false); + const [eventFilter, setEventFilter] = useState("all"); + const [helpOpen, setHelpOpen] = useState(false); + const { + available, + mode, + connected, + freshness, + sample, + severity, + thresholds, + session, + events, + sessions, + now, + history, + } = monitor; + const isDemo = mode === "simulation"; + const magnitude = sample + ? Math.hypot( + sample.acceleration.x, + sample.acceleration.y, + sample.acceleration.z, + ) + : null; + const labels = { + normal: "All systems normal", + warning: "Moderate impact detected", + critical: "High impact detected", + unavailable: "Waiting for data", + }; + const statusDescriptions = { + normal: "Simulated acceleration is below T1. This is not a device reading.", + warning: + "Acceleration reached your warning threshold. An event has been logged.", + critical: + "Simulated acceleration is greater than T2. An event has been logged.", + unavailable: + "Current motion is unconfirmed. Fresh data is required before a green assessment.", + }; + const currentEvents = events.filter((e) => e.sessionId === session.id); + const filteredEvents = events.filter( + (e) => eventFilter === "all" || e.severity === eventFilter, + ); + + return ( +
+ +
+
+
+ Workspace + + {pageNames[page]} +
+
+ + + {isDemo ? "Live simulation" : "Event-only preview"} + + + + DM +
+
+
+
+
+ + VEHICLE INTELLIGENCE +
+
+
+

+ {page === "overview" + ? "Every journey, in focus." + : pageNames[page]} +

+

+ {page === "overview" + ? isDemo + ? "Real-time motion. Meaningful insights. A safer road ahead." + : "Threshold events with clear availability and source context." + : page === "events" + ? "A closer look at the moments that matter on the road." + : "Your driving activity, all in one place."} +

+
+ +
+
+ + next === "cloud" ? onCloudMode() : monitor.setMode(next) + } + connected={connected} + freshness={freshness} + lastReceivedAt={monitor.lastReceivedAt} + lastEventReceivedAt={monitor.lastEventReceivedAt} + lastEventSource={monitor.latestEvent?.source} + now={now} + /> +
+ + + + +
+ {page === "overview" && ( + <> +
+
+
+
+

+ + {isDemo ? "Live location" : "Event locations"} +

+

+ {isDemo + ? "San Francisco, California · Simulated GPS" + : "Locations from individual event packets only"} +

+
+ + + {!isDemo + ? "NO LIVE GPS" + : available + ? "SIMULATED GPS" + : "NO GPS DATA"} + +
+ {isDemo ? ( + event.position !== null) + .map((event) => ({ + ...event, + position: event.position!, + }))} + route={ROUTE_COORDINATES} + available={available} + /> + ) : ( +
+ +

Event locations only

+

+ No live vehicle position is available. GPS appears only + when a threshold event supplies a location. +

+
    + {currentEvents.length === 0 ? ( +
  • No event locations received
  • + ) : ( + currentEvents.slice(0, 4).map((event) => ( +
  • + {time(event.timestamp)} ·{" "} + {event.position + ? `${event.position.latitude.toFixed(5)}, ${event.position.longitude.toFixed(5)}` + : "GPS not supplied"} +
  • + )) + )} +
+
+ )} +
+ + + + {isDemo ? "Demo vehicle" : "Event-only preview"} + + · + {isDemo ? "MSD-001" : "No device"} + + + + + {available && sample + ? Math.round(sample.speedKph) + : "—"} + {" "} + km/h + +
+
+
+
+
+

+ + Impact status +

+

+ {isDemo + ? "Simulated assessment · Fresh samples only" + : "Current motion cannot be inferred from events"} +

+
+ +
+
+
+ + + + + + + + + +
+ + {!isDemo + ? "CURRENT STATE UNKNOWN" + : severity === "unavailable" + ? "SIGNAL UNAVAILABLE" + : severity === "normal" + ? "YOU’RE IN THE GREEN" + : "THRESHOLD EXCEEDED"} + +
+

+ {!isDemo + ? "Current motion unknown" + : freshness === "stale" + ? "Telemetry is stale" + : labels[severity]} +

+
+

+ {isDemo + ? statusDescriptions[severity] + : "Threshold events report past impacts, not ongoing safe motion. Event silence never confirms green."} +

+
+ Resultant acceleration + + {available && magnitude !== null + ? magnitude.toFixed(2) + : "—"} + g + +
+
+ {!isDemo && monitor.latestEvent && ( +
+ + Last{" "} + {monitor.latestEvent.source === "test-event" + ? "test" + : "device"}{" "} + event ·{" "} + {monitor.latestEvent.severity === "critical" + ? "High impact" + : "Moderate"} + + + {time(monitor.latestEvent.timestamp)} · Historical + report, not current motion + + + Last{" "} + {monitor.latestEvent.source === "device" + ? "device" + : "test"}{" "} + event received{" "} + {monitor.lastEventReceivedAt === null + ? "never" + : `${Math.max(0, Math.floor((now - monitor.lastEventReceivedAt) / 1000))}s ago`} + {monitor.lastEventReceivedAt !== null && + now - monitor.lastEventReceivedAt > 5000 + ? " · Stale event record" + : " · Recent event record"} + +
+ )} + {isDemo ? ( + + ) : ( +
+ Demo settings do not configure device thresholds. +
+ )} +
+
+
+
+
+

+ + Motion at a glance +

+

+ {isDemo + ? "Simulated axes · Gravity removed · Not device telemetry" + : "Not provided by event-only telemetry"} +

+
+ + {isDemo ? ( + <> + LAST 24 SECONDS · g + + ) : ( + "NO CONTINUOUS DATA" + )} + +
+
+ {(["x", "y", "z"] as const).map((axis, i) => ( +
+
+ {axis.toUpperCase()} + + {["Longitudinal", "Lateral", "Vertical"][i]} + + +
+
+ {available && sample + ? `${sample.acceleration[axis] >= 0 ? "+" : ""}${sample.acceleration[axis].toFixed(2)}` + : "—"} + g +
+ {isDemo && available && ( + s.acceleration[axis]) + : [] + } + axis={axis} + /> + )} + {isDemo && !available && ( +
+ No fresh samples +
+ )} +
+ {isDemo ? "24s ago" : "Not supplied"} + {isDemo ? "Now" : ""} +
+
+ ))} +
+
+
+
+
+
+

+ + Recent impacts + {events.length} +

+

Timestamped moments, with location context

+
+ +
+ +
+
+
+
+

+ + Session history +

+

Recent driving activity

+
+ +
+
+ {sessions.slice(0, 3).map((s) => ( + + ))} +
+ +
+
+ + )} + {page === "events" && ( +
+
+
+

+ + Impact event log + {filteredEvents.length} +

+

+ Events retain the severity recorded at the time of impact. +

+
+ +
+ +
+ )} + {page === "sessions" && ( +
+
+
+

+ + Driving session history +

+

+ Start a new session to save the current drive. History is + kept for this browser visit. +

+
+ + {sessions.length + 1} SESSIONS + +
+ +
+ )} +
+
+ + + +
+ + {isDemo ? "Your virtual test drive" : "Sparse event preview"} + + + {isDemo + ? "Continuous simulated data · No device connection" + : "Local test packets only · No continuous samples"} + +
+
+
+ {isDemo ? ( + <> + + + + + ) : ( + <> + + + + )} +
+
+
+ + + Simulation and test events only. No hardware or cloud connection. + + + MSD Impact Monitor / Prototype + 0.1 + +
+
+
+ {settingsOpen && ( + setSettingsOpen(false)} + /> + )}{" "} + {monitor.notice && ( +
+ + {monitor.notice} +
+ )} + {helpOpen && ( +
+ + BUILT FOR THE ROAD AHEAD +

Meet your impact monitor.

+

+ This prototype simulates a vehicle driving around San Francisco. + Acceleration is measured in g, with gravity removed. Warning and + critical thresholds determine the traffic light and impact log. +

+

+ Use the data feed switch to test missing data, or inject an impact + to see an alert. Sessions and changes are in memory and reset on + refresh; export JSON to keep a copy. +

+

+ Continuous readings are simulation-only. Event-only mode displays + sparse local test packets and never confirms current safe motion. + GPS coordinates do not represent a real driver. +

+
+ )} +
+ ); +} diff --git a/src/components/CloudAuth.css b/src/components/CloudAuth.css new file mode 100644 index 0000000..81ce900 --- /dev/null +++ b/src/components/CloudAuth.css @@ -0,0 +1,180 @@ +.cloud-auth { + display: grid; + grid-template-columns: 1.1fr 1fr; + max-width: 900px; + margin: 28px auto; + background: #fffefa; +} +.cloud-auth-intro { + display: flex; + align-items: flex-start; + flex-direction: column; + padding: 40px; + background: linear-gradient(140deg, #f0f5e9, #f9faf5); +} +.cloud-auth-icon { + display: grid; + place-items: center; + width: 52px; + height: 52px; + border: 1px solid #dbe6d0; + border-radius: 14px; + background: #e6efdc; + color: #557c43; + margin-bottom: 25px; +} +.cloud-auth-intro .heading-eyebrow { + font-size: 8px; + color: #8c9f77; +} +.cloud-auth h2 { + font-family: var(--heading); + font-size: 27px; + font-weight: 600; + line-height: 1.4; + letter-spacing: -0.9px; + margin: 14px 0; + color: #3b5830; +} +.cloud-auth-intro > p { + font-size: 12px; + line-height: 1.9; + color: #7d906b; + margin: 0; +} +.cloud-auth-privacy { + display: flex; + align-items: flex-start; + gap: 9px; + border-top: 1px solid #e1e8d8; + padding-top: 20px; + margin-top: auto; + color: #8a9b78; + font-size: 10px; + line-height: 1.8; +} +.cloud-auth-privacy svg { + flex-shrink: 0; + margin-top: 2px; +} +.cloud-auth-form { + padding: 36px; + display: flex; + flex-direction: column; + gap: 18px; +} +.cloud-auth-form h3 { + font-family: var(--heading); + font-size: 18px; + font-weight: 600; + letter-spacing: -0.4px; + color: #4c663e; + margin: 0 0 5px; +} +.cloud-auth-form > label { + display: flex; + flex-direction: column; + gap: 8px; + font-size: 11px; + color: #738964; +} +.cloud-auth-form > label > span { + display: flex; + align-items: center; + gap: 7px; +} +.cloud-auth-form input { + width: 100%; + padding: 11px 12px; + border: 1px solid #dde6d1; + border-radius: 6px; + background: #fbfcf8; + font-size: 12px; + color: #4b643d; +} +.cloud-auth-form input::placeholder { + color: #b1bba5; +} +.cloud-auth-form .button { + font-size: 11px; + min-height: 39px; +} +.cloud-auth-switch { + padding: 5px 0; + font-size: 10px; + color: #7d9864; + background: none; + border: 0; + text-align: center; +} +.cloud-auth-switch:hover { + color: #3e6730; +} +.cloud-auth-hint { + font-size: 9px; + line-height: 1.8; + color: #9baa88; + margin: 0; +} +.cloud-auth-error { + font-size: 11px; + color: #ae6651; + background: #fcf3ec; + border: 1px solid #f0dfd0; + border-radius: 6px; + padding: 10px 12px; + margin: 0; + line-height: 1.7; +} +.cloud-auth-notice { + font-size: 11px; + color: #597e43; + background: #f0f6e9; + border: 1px solid #dfebd2; + border-radius: 6px; + padding: 10px 12px; + margin: 0; + line-height: 1.7; +} +@media (max-width: 750px) { + .cloud-auth { + grid-template-columns: 1fr; + } + .cloud-auth-intro { + padding: 25px; + } + .cloud-auth h2 { + font-size: 23px; + } + .cloud-auth-privacy { + margin-top: 20px; + padding-top: 15px; + } + .cloud-auth-form { + padding: 25px; + gap: 16px; + } + .cloud-auth-icon { + margin-bottom: 18px; + width: 44px; + height: 44px; + } + .cloud-auth-intro > p { + font-size: 11px; + } +} +@media (max-width: 480px) { + .cloud-auth-intro, + .cloud-auth-form { + padding: 21px; + } + .cloud-auth h2 { + font-size: 22px; + } + .cloud-auth-form h3 { + font-size: 17px; + } + .cloud-auth-privacy { + font-size: 9px; + } +} diff --git a/src/components/CloudAuth.tsx b/src/components/CloudAuth.tsx new file mode 100644 index 0000000..439fa45 --- /dev/null +++ b/src/components/CloudAuth.tsx @@ -0,0 +1,154 @@ +import { useState } from "react"; +import { ArrowRight, LockKeyhole, Mail, ShieldCheck } from "lucide-react"; +import type { useCloudAuth } from "../hooks/useCloudAuth"; +import "./CloudAuth.css"; + +export function CloudAuth({ auth }: { auth: ReturnType }) { + const [creating, setCreating] = useState(false); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [confirmation, setConfirmation] = useState(""); + const mismatch = + creating && confirmation.length > 0 && confirmation !== password; + async function submit(event: React.FormEvent) { + event.preventDefault(); + if (creating && password !== confirmation) return; + const success = await (creating + ? auth.signUp(email, password) + : auth.signIn(email, password)); + if (success) { + setPassword(""); + setConfirmation(""); + setEmail(""); + } + } + return ( +
+
+ + + + PRIVATE BY DEFAULT +

+ {creating + ? "Create your cloud account." + : "Your journeys, securely connected."} +

+

+ Sign in to view sessions you own or that another owner has shared with + you. Cloud records persist between visits and synchronize with other + authorized observers. +

+
+ + + Session access is enforced by database row-level security. Local + simulation remains available without signing in. + +
+
+
void submit(event)} + > +

{creating ? "Create an account" : "Sign in to Supabase"}

+ + + {creating && ( + + )} + {mismatch && ( + + )} + {auth.error && ( +

+ {auth.error} +

+ )} + {auth.notice && ( +

+ {auth.notice} +

+ )} + + +

+ {creating + ? "Use at least 8 characters. If email confirmation is enabled, confirm the email before signing in." + : "Use the email and password for this Supabase project."} +

+
+
+ ); +} diff --git a/src/components/CloudDashboard.css b/src/components/CloudDashboard.css new file mode 100644 index 0000000..e1b4e95 --- /dev/null +++ b/src/components/CloudDashboard.css @@ -0,0 +1,909 @@ +.cloud-shell { + min-height: 100vh; + background: #f6f7f4; +} +.cloud-topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + min-height: 82px; + background: #fffefa; + border-bottom: 1px solid var(--border); + padding: 18px max(28px, calc((100vw - 1390px) / 2)); +} +.cloud-brand { + display: flex; + align-items: center; + gap: 11px; +} +.cloud-brand > strong { + font-family: var(--heading); + font-size: 29px; + letter-spacing: -1.5px; + color: #2b4937; +} +.cloud-brand > strong > span { + color: #7b9e67; +} +.cloud-brand-label { + font-size: 8px; + letter-spacing: 1.5px; + color: #8d9b7d; + margin-left: 6px; +} +.cloud-top-actions { + display: flex; + align-items: center; + gap: 15px; +} +.cloud-source-label { + display: flex; + align-items: center; + gap: 10px; + font-size: 10px; + color: #829174; +} +.cloud-source-label select, +.cloud-session-choice select, +.cloud-create select, +.cloud-create input, +.cloud-sharing input { + background: #f8faf3; + border: 1px solid #dfe6d7; + border-radius: 6px; + padding: 9px 11px; + font-size: 11px; + color: #526a40; + max-width: 100%; +} +.cloud-main { + max-width: 1430px; + margin: 0 auto; + padding: 33px 32px 25px; +} +.cloud-page-heading { + display: flex; + justify-content: space-between; + align-items: center; + gap: 20px; + margin-bottom: 26px; +} +.cloud-page-heading h1 { + margin: 12px 0 5px; + font-size: 30px; +} +.cloud-page-heading p { + font-size: 12px; + color: #829372; + margin: 0; + line-height: 1.8; +} +.cloud-user { + display: flex; + align-items: center; + gap: 7px; + font-size: 10px; + color: #8b9b79; + overflow-wrap: anywhere; +} +.cloud-setup, +.cloud-empty { + padding: 45px; + display: flex; + align-items: flex-start; + flex-direction: column; + gap: 15px; + color: #8d9d79; +} +.cloud-setup h2, +.cloud-empty h2 { + font: 600 23px var(--heading); + letter-spacing: -0.6px; + color: #4d6840; + margin: 0; +} +.cloud-setup p, +.cloud-empty p { + font-size: 12px; + line-height: 1.9; + max-width: 850px; + margin: 0; + color: #7f906d; +} +.cloud-setup ol { + font-size: 12px; + line-height: 2.3; + margin: 0; + padding-left: 18px; + color: #7b8e67; +} +.cloud-setup code { + font-size: 11px; + background: #f0f4e7; + padding: 2px 5px; + border-radius: 4px; +} +.cloud-session-toolbar { + display: flex; + align-items: end; + gap: 15px; + padding: 18px 20px; + flex-wrap: wrap; + margin-bottom: 17px; +} +.cloud-session-choice { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 230px; + flex: 1; +} +.cloud-session-choice label { + font-size: 10px; + font-weight: 550; + color: #7b8f66; +} +.cloud-session-choice select { + width: 100%; +} +.cloud-create { + display: flex; + gap: 8px; + align-items: center; + flex-wrap: wrap; + margin-left: auto; +} +.cloud-create input { + min-width: 160px; + flex: 1; +} +.cloud-message { + display: flex; + align-items: center; + gap: 9px; + color: #64874c; + border: 1px solid #dce8ce; + background: #f1f6e8; + font-size: 11px; + line-height: 1.8; + border-radius: 7px; + padding: 11px 15px; + margin-bottom: 15px; + overflow-wrap: anywhere; +} +.cloud-message svg { + flex-shrink: 0; +} +.cloud-error { + background: #fcf4ed; + color: #b27b5c; + border-color: #f0dfd0; +} +.cloud-tabs { + display: flex; + gap: 7px; + align-items: center; + flex-wrap: wrap; + border-bottom: 1px solid #e3e8da; + margin: 10px 0 24px; + padding: 0 0 11px; +} +.cloud-tabs > button { + border: 0; + background: none; + color: #8d9d7c; + font-size: 11px; + padding: 8px 13px; + border-radius: 6px; + text-transform: capitalize; +} +.cloud-tabs > button.active { + color: #5e8049; + background: #eaf1e1; + font-weight: 600; +} +.cloud-tabs > button:hover { + background: #f0f4e9; +} +.cloud-sync { + margin-left: auto; + font-size: 9px; + color: #a0a98f; + display: flex; + align-items: center; + gap: 6px; +} +.cloud-sync i { + width: 5px; + height: 5px; + border-radius: 50%; + background: #a9b09d; +} +.cloud-sync-subscribed { + color: #839c6c; +} +.cloud-sync-subscribed i { + background: #8ea973; +} +.cloud-session-caption { + display: flex; + justify-content: space-between; + align-items: center; + gap: 15px; + margin-bottom: 20px; +} +.cloud-session-caption > div { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} +.cloud-session-caption h2 { + font: 600 20px var(--heading); + letter-spacing: -0.5px; + color: #49613d; + margin: 0; +} +.cloud-session-caption > div > span { + font-size: 10px; + color: #8a9a77; +} +.cloud-source-chip { + font-size: 7px !important; + letter-spacing: 0.7px; + border: 1px solid #e2e9d8; + padding: 5px 8px; + border-radius: 5px; + background: #f1f5e9; + color: #8b9f70 !important; +} +.cloud-source-chip.device { + background: #edf2f0; + color: #7c9789 !important; + border-color: #dfe8e1; +} +.cloud-stats .stat-value { + font-size: 25px; +} +.cloud-stats .stat-detail { + line-height: 1.7; +} +.cloud-live-grid { + display: grid; + grid-template-columns: minmax(0, 1.7fr) minmax(290px, 1fr); + gap: 21px; + margin-bottom: 22px; + align-items: start; +} +.cloud-map-card .vehicle-map { + border-radius: 0; + height: 360px; +} +.cloud-gps-times { + font-size: 9px; + color: #9aa68b; + line-height: 1.8; + padding: 0 20px 15px; + margin: 0; +} +.cloud-imu-grid { + display: flex; + flex-direction: column; + gap: 13px; +} +.cloud-imu-card { + padding: 17px 19px; +} +.cloud-imu-title { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.cloud-imu-number { + display: grid; + place-items: center; + width: 25px; + height: 25px; + font-size: 10px; + color: #8b9c78; + background: #f0f4e8; + border: 1px solid #e8eedf; + border-radius: 7px; +} +.cloud-imu-title h2 { + font-size: 13px; + color: #677e54; + margin: 0; + font-weight: 600; +} +.cloud-unknown { + display: flex; + align-items: center; + gap: 5px; + font-size: 9px; + color: #9da491; + margin-left: auto; + white-space: nowrap; +} +.cloud-unknown i { + width: 6px; + height: 6px; + border-radius: 50%; + background: #aeb4a6; + box-shadow: 0 0 0 3px #f1f2ed; +} +.cloud-imu-card > p { + font-size: 9px; + color: #9da88c; + line-height: 1.8; + margin: 9px 0 11px; +} +.cloud-last-event { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + color: #98a584; + font-size: 8px; + min-height: 22px; +} +.cloud-last-event .severity-badge { + font-size: 8px; +} +.cloud-imu-card footer { + border-top: 1px dashed #e7ecdc; + margin-top: 12px; + padding-top: 10px; + font-size: 9px; + color: #9da98d; +} +.cloud-imu-card footer span { + margin: 0 8px; + color: #b3bca7; +} +.cloud-recent { + margin-bottom: 22px; +} +.cloud-events-table { + font-size: 11px; +} +.cloud-events-table td { + padding: 15px; + font-size: 10px; + color: #7f926a; +} +.cloud-events-table th { + padding: 12px 15px; + font-size: 8px; +} +.cloud-events-table strong, +.cloud-history-table strong { + font-size: 11px; + font-weight: 500; + color: #738a5d; + font-variant-numeric: tabular-nums; +} +.cloud-events-table small, +.cloud-history-table small { + display: block; + font-size: 8px; + color: #a1ae8e; + margin-top: 5px; + line-height: 1.6; +} +.cloud-events-table .severity-badge { + font-size: 9px; +} +.cloud-history-table td { + font-size: 11px; + padding: 17px 15px; + color: #8b9c76; +} +.cloud-settings-grid { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(300px, 1fr); + gap: 21px; + margin-bottom: 22px; +} +.cloud-threshold-settings form { + padding: 0 20px 20px; +} +.cloud-threshold-rows { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 13px; +} +.cloud-threshold-rows > div { + display: flex; + flex-direction: column; + gap: 9px; + border: 1px solid #e7ecde; + background: #fafbf6; + padding: 13px; + border-radius: 7px; +} +.cloud-threshold-rows strong { + font-size: 11px; + font-weight: 550; + color: #7b9067; + margin-bottom: 2px; +} +.cloud-threshold-rows label { + display: flex; + align-items: center; + gap: 6px; + font-size: 10px; + color: #97a584; +} +.cloud-threshold-rows input { + width: 100%; + min-width: 0; + border: 1px solid #e0e7d5; + background: #fffefa; + color: #79935f; + font-size: 11px; + padding: 7px; + border-radius: 5px; + font-variant-numeric: tabular-nums; +} +.cloud-threshold-rows input:disabled { + background: #f1f3ec; + color: #9aa58b; +} +.cloud-settings-note { + font-size: 10px; + color: #98a789; + line-height: 1.9; + margin: 14px 0; +} +.cloud-form-error { + font-size: 10px; + color: #b78262; + line-height: 1.7; +} +.cloud-sharing form { + padding: 0 20px; +} +.cloud-sharing form > label { + font-size: 10px; + color: #82986c; + display: block; + margin-bottom: 8px; +} +.cloud-sharing form > div { + display: flex; + align-items: center; + gap: 8px; +} +.cloud-sharing input { + min-width: 0; + flex: 1; +} +.cloud-sharing > .cloud-settings-note { + padding: 0 20px 5px; + font-size: 9px; +} +.cloud-observer-list { + padding: 0 20px; + list-style: none; + margin: 14px 0; +} +.cloud-observer-list li { + display: flex; + align-items: center; + gap: 8px; + border-bottom: 1px solid #edf0e5; + padding: 9px 0; +} +.cloud-observer-list li > span { + font-size: 8px; + overflow-wrap: anywhere; + color: #98a886; + flex: 1; +} +.cloud-observer-list button { + font-size: 8px; + white-space: nowrap; +} +.cloud-readonly { + display: flex; + align-items: center; + flex-direction: column; + justify-content: center; + gap: 11px; + padding: 15px 30px 30px; + text-align: center; + color: #94a57f; +} +.cloud-readonly strong { + font-size: 13px; + font-weight: 550; + color: #7c9167; +} +.cloud-readonly p { + font-size: 11px; + line-height: 1.9; + margin: 0; + color: #99a98b; +} +.cloud-test-controls { + margin-top: 0; +} +.cloud-test-controls .demo-controls-title div > span { + font-size: 10px; +} +.cloud-footer { + display: flex; + justify-content: space-between; + gap: 15px; + font-size: 9px; + color: #a4ae95; + line-height: 1.8; + padding: 23px 0 0; +} +.cloud-footer > span:first-child { + display: flex; + align-items: center; + gap: 6px; +} +@media (max-width: 1100px) { + .cloud-main { + padding: 28px 23px; + } + .cloud-topbar { + padding: 18px 24px; + } + .cloud-create { + width: 100%; + margin-left: 0; + } + .cloud-session-choice { + flex: 1; + } + .cloud-brand-label { + display: none; + } + .cloud-stats .stat-value { + font-size: 21px; + } + .cloud-live-grid { + grid-template-columns: minmax(0, 1.4fr) minmax(270px, 1fr); + gap: 17px; + } + .cloud-settings-grid { + gap: 17px; + grid-template-columns: minmax(0, 1.2fr) minmax(280px, 1fr); + } + .cloud-threshold-rows { + gap: 8px; + } + .cloud-threshold-rows > div { + padding: 10px; + } + .cloud-unknown { + font-size: 8px; + } + .cloud-imu-card { + padding: 15px; + } +} +@media (max-width: 760px) { + .cloud-topbar { + padding: 15px 20px; + min-height: 75px; + } + .cloud-brand > strong { + font-size: 24px; + } + .cloud-brand .brand-mark { + width: 34px; + height: 37px; + } + .cloud-source-label { + font-size: 0; + gap: 0; + } + .cloud-source-label select { + font-size: 10px; + padding: 8px; + max-width: 145px; + } + .cloud-top-actions { + gap: 9px; + } + .cloud-top-actions .button { + font-size: 9px; + padding: 8px; + min-height: 30px; + } + .cloud-main { + padding: 25px 18px; + } + .cloud-page-heading { + align-items: flex-start; + flex-direction: column; + gap: 12px; + } + .cloud-page-heading h1 { + font-size: 27px; + } + .cloud-page-heading p { + font-size: 11px; + } + .cloud-user { + font-size: 9px; + } + .cloud-session-toolbar { + padding: 16px; + gap: 13px; + } + .cloud-session-choice { + min-width: 180px; + } + .cloud-create { + gap: 9px; + } + .cloud-create input { + width: 100%; + min-width: 0; + flex: auto; + } + .cloud-create select { + flex: 1; + } + .cloud-create .button { + font-size: 9px; + } + .cloud-sync { + width: 100%; + margin-left: 7px; + margin-top: 6px; + } + .cloud-tabs { + margin-bottom: 20px; + } + .cloud-tabs > button { + font-size: 10px; + padding: 7px 10px; + } + .cloud-stats { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .cloud-live-grid, + .cloud-settings-grid { + grid-template-columns: 1fr; + } + .cloud-imu-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; + } + .cloud-imu-card { + padding: 13px 10px; + } + .cloud-imu-title { + gap: 5px; + } + .cloud-imu-title h2 { + font-size: 11px; + } + .cloud-imu-number { + width: 20px; + height: 20px; + font-size: 8px; + } + .cloud-unknown { + margin-left: 0; + width: 100%; + margin-top: 7px; + font-size: 8px; + } + .cloud-imu-card > p { + font-size: 8px; + } + .cloud-last-event { + font-size: 7px; + } + .cloud-imu-card footer { + font-size: 8px; + } + .cloud-imu-card footer span { + margin: 0 3px; + } + .cloud-map-card .vehicle-map { + height: 325px; + } + .cloud-session-caption { + align-items: flex-start; + } + .cloud-session-caption h2 { + font-size: 18px; + } + .cloud-session-caption > div { + gap: 8px; + } + .cloud-session-caption > div > span { + font-size: 8px; + } + .cloud-session-caption > .button { + font-size: 9px; + padding: 7px 9px; + } + .cloud-gps-times { + font-size: 8px; + padding-left: 15px; + padding-right: 15px; + } + .cloud-settings-note { + font-size: 9px; + } + .cloud-settings-grid { + gap: 18px; + } + .cloud-footer { + flex-direction: column; + font-size: 8px; + } + .cloud-footer > span:first-child { + align-items: flex-start; + } + .cloud-footer svg { + flex-shrink: 0; + } + .cloud-setup, + .cloud-empty { + padding: 25px; + gap: 15px; + } + .cloud-setup h2, + .cloud-empty h2 { + font-size: 21px; + } + .cloud-setup p, + .cloud-empty p, + .cloud-setup ol { + font-size: 11px; + } + .cloud-setup code { + overflow-wrap: anywhere; + font-size: 10px; + } + .cloud-message { + font-size: 10px; + } +} +@media (max-width: 430px) { + .cloud-topbar { + padding: 13px; + gap: 10px; + } + .cloud-brand { + gap: 7px; + } + .cloud-top-actions { + gap: 7px; + } + .cloud-source-label select { + max-width: 122px; + font-size: 9px; + } + .cloud-top-actions .button { + font-size: 0; + padding: 7px; + } + .cloud-top-actions .button svg { + height: 14px; + width: 14px; + } + .cloud-main { + padding: 22px 13px; + } + .cloud-page-heading h1 { + font-size: 25px; + } + .cloud-page-heading p { + font-size: 10px; + } + .cloud-session-toolbar { + padding: 14px; + } + .cloud-session-toolbar > .button { + font-size: 9px; + padding: 8px; + } + .cloud-create select { + font-size: 10px; + min-width: 0; + } + .cloud-create .button { + font-size: 8px; + padding: 8px; + } + .cloud-session-caption { + flex-wrap: wrap; + } + .cloud-stats .stat-value { + font-size: 22px; + } + .cloud-stats .stat-detail { + font-size: 8px; + } + .cloud-imu-grid { + grid-template-columns: 1fr; + } + .cloud-imu-card { + padding: 15px 16px; + } + .cloud-imu-title h2 { + font-size: 13px; + } + .cloud-unknown { + margin-left: auto; + width: auto; + margin-top: 0; + font-size: 9px; + } + .cloud-imu-card > p { + font-size: 9px; + } + .cloud-last-event { + font-size: 9px; + } + .cloud-imu-card footer { + font-size: 9px; + } + .cloud-threshold-rows { + gap: 7px; + } + .cloud-threshold-rows > div { + padding: 9px 7px; + } + .cloud-threshold-rows label { + font-size: 9px; + gap: 4px; + } + .cloud-threshold-rows input { + padding: 6px 3px; + font-size: 10px; + } + .cloud-threshold-settings form { + padding: 0 13px 17px; + } + .cloud-sharing form { + padding: 0 13px; + } + .cloud-sharing form > div { + flex-wrap: wrap; + } + .cloud-sharing input { + min-width: 155px; + } + .cloud-sharing .button { + font-size: 9px; + } + .cloud-test-controls .demo-controls-title div > span { + font-size: 9px; + line-height: 1.7; + } + .cloud-test-controls .demo-controls-title { + align-items: flex-start; + } + .cloud-test-controls .demo-actions { + gap: 9px; + } + .cloud-test-controls .demo-actions .button { + font-size: 9px; + padding: 8px; + } + .cloud-events-table td { + font-size: 9px; + } + .cloud-history-table td { + font-size: 10px; + } + .cloud-map-card .vehicle-map { + height: 290px; + } +} diff --git a/src/components/CloudDashboard.tsx b/src/components/CloudDashboard.tsx new file mode 100644 index 0000000..e43b182 --- /dev/null +++ b/src/components/CloudDashboard.tsx @@ -0,0 +1,1099 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { + Activity, + ArrowDownToLine, + Check, + Cloud, + Clock3, + Database, + LogOut, + MapPin, + Play, + Plus, + Radio, + RefreshCw, + Route, + Settings2, + ShieldCheck, + Square, + Users, + WifiOff, + Zap, +} from "lucide-react"; +import type { CloudThresholdEvent, ImuId } from "../domain/cloud"; +import type { TelemetryMode } from "../domain/types"; +import { + connectionFreshness, + gpsFreshness, + latestGps, + normalizeEvents, + normalizeGps, + routeDistanceKm, +} from "../domain/cloudRecords"; +import { getSupabaseClient, getSupabaseConfig } from "../services/supabase"; +import { CloudRepository } from "../services/cloudRepository"; +import { startCloudSimulation } from "../services/cloudSimulator"; +import { useCloudAuth } from "../hooks/useCloudAuth"; +import { useCloudSession } from "../hooks/useCloudSession"; +import { CloudAuth } from "./CloudAuth"; +import { Stat } from "./StatCard"; +import { VehicleMap } from "./VehicleMap"; +import { date, duration, time } from "../lib/format"; +import "./CloudDashboard.css"; + +type Props = { onModeChange: (mode: TelemetryMode | "cloud") => void }; +const age = (value: string | undefined, now: number) => + value + ? `${Math.max(0, Math.floor((now - Date.parse(value)) / 1000))}s ago` + : "Never received"; +const imuIds: ImuId[] = [1, 2, 3]; +const message = (error: unknown) => + error instanceof Error + ? error.message + : "Cloud operation failed. Please retry."; + +function CloudEvents({ + events, + compact = false, +}: { + events: CloudThresholdEvent[]; + compact?: boolean; +}) { + const sorted = [...events].reverse(); + return ( +
+ + + + + + + + + + + + {(compact ? sorted.slice(0, 5) : sorted).map((event) => ( + + + + + + + + ))} + +
EVENT TIME / IMUREPORTED STATUSPEAK AEVENT LOCATIONTHRESHOLD SNAPSHOT
+ {time(Date.parse(event.recorded_at))} + + {date(Date.parse(event.recorded_at))} · IMU {event.imu_id} + + + + + {event.severity === "critical" ? "High impact" : "Moderate"} + + Historical event + + {event.magnitude === null + ? "Not supplied" + : `${event.magnitude.toFixed(2)} g`} + + {event.latitude === null || event.longitude === null + ? "Not supplied" + : `${event.latitude.toFixed(5)}, ${event.longitude.toFixed(5)}`} + + T1 {event.t1.toFixed(2)} g · T2 {event.t2.toFixed(2)} g +
+ {events.length === 0 && ( +
+ + No threshold events recorded +

Event silence does not confirm safe motion.

+
+ )} +
+ ); +} + +export function CloudDashboard({ onModeChange }: Props) { + const [config] = useState(getSupabaseConfig); + const [client] = useState(getSupabaseClient); + const repository = useMemo( + () => (client ? new CloudRepository(client) : null), + [client], + ); + const auth = useCloudAuth(client); + const cloud = useCloudSession(repository, auth.user?.id ?? null); + const { snapshot, sessions, selectedId } = cloud; + const [tab, setTab] = useState<"overview" | "history" | "events">("overview"); + const [now, setNow] = useState(Date.now()); + const [label, setLabel] = useState(""); + const [dataSource, setDataSource] = useState<"simulated" | "device">( + "simulated", + ); + const [sharingEmail, setSharingEmail] = useState(""); + const [busy, setBusy] = useState(false); + const [actionError, setActionError] = useState(""); + const [notice, setNotice] = useState(""); + const [feeding, setFeeding] = useState(false); + const feedStop = useRef<(() => void) | null>(null); + const [draftThresholds, setDraftThresholds] = useState( + imuIds.map((imu_id) => ({ imu_id, t1: "0.8", t2: "1.8" })), + ); + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), 500); + return () => window.clearInterval(timer); + }, []); + useEffect(() => { + setFeeding(false); + return () => { + feedStop.current?.(); + feedStop.current = null; + }; + }, [selectedId, auth.user?.id]); + const thresholdVersion = JSON.stringify(snapshot?.thresholds ?? []); + useEffect(() => { + if (snapshot) + setDraftThresholds( + imuIds.map((imu_id) => { + const row = snapshot.thresholds.find( + (item) => item.imu_id === imu_id, + ); + return { + imu_id, + t1: String(row?.t1 ?? 0.8), + t2: String(row?.t2 ?? 1.8), + }; + }), + ); + }, [selectedId, thresholdVersion]); + const gps = useMemo(() => normalizeGps(snapshot?.gps ?? []), [snapshot?.gps]); + const events = useMemo( + () => normalizeEvents(snapshot?.events ?? []), + [snapshot?.events], + ); + const fix = useMemo(() => latestGps(gps), [gps]); + const gpsState = gpsFreshness(fix, now); + const gatewayState = connectionFreshness(snapshot?.connection ?? null, now); + const owner = Boolean( + snapshot && auth.user?.id === snapshot.session.owner_id, + ); + const active = Boolean(snapshot && !snapshot.session.ended_at); + const gpsLive = gpsState === "fresh" && active && !cloud.error; + const route = useMemo( + () => + gps.map((point) => ({ + latitude: point.latitude, + longitude: point.longitude, + })), + [gps], + ); + const eventMarkers = useMemo( + () => + events.flatMap((event) => + event.latitude !== null && event.longitude !== null + ? [ + { + id: event.id, + timestamp: Date.parse(event.recorded_at), + severity: event.severity, + position: { + latitude: event.latitude, + longitude: event.longitude, + }, + }, + ] + : [], + ), + [events], + ); + const validThresholds = draftThresholds.every( + (row) => + row.t1.trim() !== "" && + row.t2.trim() !== "" && + Number.isFinite(Number(row.t1)) && + Number.isFinite(Number(row.t2)) && + Number(row.t1) > 0 && + Number(row.t2) > Number(row.t1) && + Number(row.t2) <= 10, + ); + async function act(work: () => Promise, success: string) { + setBusy(true); + setActionError(""); + setNotice(""); + try { + await work(); + setNotice(success); + } catch (error) { + setActionError(message(error)); + } finally { + setBusy(false); + } + } + function stopDrive() { + feedStop.current?.(); + feedStop.current = null; + setFeeding(false); + } + function startDrive() { + if ( + !repository || + !snapshot || + !owner || + snapshot.session.data_source !== "simulated" || + !active + ) + return; + setActionError(""); + try { + feedStop.current = startCloudSimulation( + repository, + snapshot.session, + snapshot.thresholds, + (error) => setActionError(error), + ); + setFeeding(true); + setNotice( + "Uploading simulated GPS at approximately 1 Hz. Other authorized observers can watch this session.", + ); + } catch (error) { + setActionError(message(error)); + } + } + function exportSession() { + if (!snapshot) return; + const blob = new Blob( + [ + JSON.stringify( + { + schemaVersion: 3, + transport: "supabase", + exportedAt: new Date().toISOString(), + ...snapshot, + }, + null, + 2, + ), + ], + { type: "application/json" }, + ); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = `msd-cloud-${snapshot.session.id}.json`; + link.click(); + URL.revokeObjectURL(url); + } + + return ( +
+
+ { + event.preventDefault(); + onModeChange("simulation"); + }} + > + + + + + MSD. + + IMPACT MONITOR + +
+ + {auth.user && ( + + )} +
+
+
+
+
+ + + STAGE 2 · CLOUD OBSERVATION + +

Cloud session monitor

+

+ Live GPS. Historical threshold events. Shared, persistent session + records. +

+
+ {auth.user && ( + + + {auth.user.email} + + )} +
+ {!config.ready ? ( +
+ +

Connect your Supabase project

+

{config.message}

+
    +
  1. + Apply the migration in supabase/migrations to your + project. +
  2. +
  3. + Set VITE_SUPABASE_URL and{" "} + VITE_SUPABASE_PUBLISHABLE_KEY in{" "} + .env.local. +
  4. +
  5. + Restart the development server, then create an account and a + simulated cloud session. +
  6. +
+

+ Use only a publishable or legacy anon key. Privileged keys never + belong in frontend code. Full instructions are in{" "} + docs/SUPABASE_SETUP.md. +

+ +
+ ) : !auth.user ? ( + + ) : ( + <> +
+
+ + +
+ +
{ + event.preventDefault(); + if (!repository) return; + void act(async () => { + const id = await repository.createSession( + label.trim(), + dataSource, + ); + await cloud.refreshSessions(); + cloud.setSelectedId(id); + setLabel(""); + setTab("overview"); + }, "Cloud session created with three IMU threshold configurations."); + }} + > + setLabel(event.target.value)} + maxLength={100} + required + /> + + +
+
+ {(cloud.error || actionError || auth.error) && ( +
+ + {actionError || cloud.error || auth.error} +
+ )} + {notice && ( +
+ + {notice} +
+ )} + + {tab === "history" ? ( +
+
+
+

+ + Persistent session history +

+

+ Owned and shared sessions, loaded from Supabase after + every visit. +

+
+
+
+ + + + + + + + + + + + {sessions.map((session) => ( + + + + + + + + + ))} + +
SESSION / SOURCESTARTEDDURATIONACCESSSTATE +
+ {session.label} + + {session.data_source === "simulated" + ? "Simulated cloud telemetry" + : "Device telemetry"} + + + {date(Date.parse(session.started_at))} ·{" "} + {time(Date.parse(session.started_at))} + + {duration( + Date.parse( + session.ended_at ?? new Date(now).toISOString(), + ) - Date.parse(session.started_at), + )} + + {session.owner_id === auth.user!.id + ? "Owner" + : "Observer · read only"} + {session.ended_at ? "Completed" : "Active"} + +
+
+
+ ) : !snapshot ? ( +
+ +

+ {cloud.loading + ? "Loading authorized session records…" + : "Choose or create a cloud session"} +

+

+ Sessions are private until the owner shares access. Local demo + records are never used as a cloud fallback. +

+
+ ) : ( + <> +
+
+

{snapshot.session.label}

+ + {snapshot.session.data_source === "simulated" + ? "SIMULATED CLOUD DATA" + : "DEVICE TELEMETRY"} + + {owner ? "Owner" : "Observer · read only"} + + {active + ? "Active session" + : "Completed session · Historical records"} + +
+ +
+
+ + + + +
+ {tab === "events" ? ( +
+
+
+

+ + Cloud threshold event records +

+

+ All three IMUs · Immutable event-time thresholds and + optional GPS locations +

+
+
+ +
+ ) : ( + <> +
+
+
+
+

+ + Live GPS route +

+

+ {gpsLive + ? "Recent source GPS · Not inferred from event arrival" + : "Current GPS unavailable or stale · Recorded route remains visible"} +

+
+ + + {gpsLive ? "RECENT GPS" : "NO CURRENT GPS"} + +
+ +
+ + + {gps.length} GPS fixes · {eventMarkers.length} event + locations + + + {gpsLive && + fix?.speed_kph !== null && + fix?.speed_kph !== undefined + ? Math.round(fix.speed_kph) + : "—"}{" "} + km/h + +
+

+ Source fix:{" "} + {fix + ? new Date(fix.recorded_at).toLocaleString() + : "Not received"}{" "} + · Cloud receipt:{" "} + {fix + ? new Date(fix.received_at).toLocaleString() + : "Not received"} +

+
+
+ {imuIds.map((imu_id) => { + const event = events + .filter((item) => item.imu_id === imu_id) + .at(-1); + const threshold = snapshot.thresholds.find( + (item) => item.imu_id === imu_id, + ); + return ( +
+
+ + {imu_id} + +

IMU {imu_id}

+ + + Current: Unknown + +
+

+ Event-only telemetry · Continuous acceleration + not transmitted +

+
+ {event ? ( + <> + + + {event.severity === "critical" + ? "High impact" + : "Moderate"} + + + {time(Date.parse(event.recorded_at))} · + Historical event + + + ) : ( + + No event received · Silence does not confirm + green + + )} +
+
+ T1 {threshold?.t1.toFixed(2) ?? "—"} g{" "} + · T2{" "} + {threshold?.t2.toFixed(2) ?? "—"} g +
+
+ ); + })} +
+
+
+
+
+

+ + Recent cloud events +

+

+ {snapshot.session.data_source === "simulated" + ? "Simulated cloud records" + : "Device reports"}{" "} + · Event time and GPS retained between visits +

+
+ +
+ +
+
+
+
+
+

+ + Three-IMU cloud thresholds +

+

+ Green A < T1 · Yellow T1 ≤ A ≤ T2 · Red A > + T2 +

+
+ + {owner ? "OWNER SETTINGS" : "READ ONLY"} + +
+
{ + event.preventDefault(); + if (!repository || !validThresholds || !owner) + return; + stopDrive(); + void act(async () => { + await repository.setThresholds( + snapshot.session.id, + draftThresholds.map((row) => ({ + imu_id: row.imu_id, + t1: Number(row.t1), + t2: Number(row.t2), + })), + ); + await cloud.refreshSnapshot(); + }, "Threshold configurations saved. Restart the cloud test drive to use them. Future hardware must explicitly apply these settings."); + }} + > +
+ {draftThresholds.map((row, index) => ( +
+ IMU {row.imu_id} + {(["t1", "t2"] as const).map((key) => ( + + ))} +
+ ))} +
+ {!validThresholds && ( +

+ Each IMU requires 0 < T1 < T2 ≤ 10 g. +

+ )} +

+ These settings do not reclassify historical events + or confirm current acceleration. Device + configuration delivery belongs to the future phone + gateway. +

+ {owner && ( + + )} +
+
+
+
+
+

+ + Session observers +

+

Only the owner can grant read-only access.

+
+
+ {owner ? ( + <> +
{ + event.preventDefault(); + if (!repository) return; + void act(async () => { + await repository.shareSession( + snapshot.session.id, + sharingEmail.trim(), + ); + setSharingEmail(""); + await cloud.refreshSnapshot(); + }, "Observer access granted. The observer must sign in to this same Supabase project."); + }} + > + +
+ + setSharingEmail(event.target.value) + } + required + placeholder="observer@example.com" + /> + +
+
+
    + {snapshot.observers.map((observer) => ( +
  • + {observer.user_id} + +
  • + ))} +
+

+ Access is enforced by row-level security. + Membership changes are reconciled within 10 + seconds; unauthorized reads are denied + immediately. +

+ + ) : ( +
+ + Read-only observer +

+ You can view this session’s route, events, + history, and thresholds. Upload and sharing + controls belong to its owner. +

+
+ )} +
+
+ {owner && ( +
+
+ + + +
+ + {snapshot.session.data_source === "simulated" + ? "Test cloud delivery with simulated telemetry" + : "Awaiting a future phone gateway"} + + + {snapshot.session.data_source === "simulated" + ? "GPS ~1 Hz · Three IMUs send threshold events only · No raw IMU uploads" + : "Device sessions never fall back to generated telemetry."} + +
+
+
+ {snapshot.session.data_source === "simulated" && + active && ( + + )} + {active && ( + + )} +
+
+ )} + + )} + + )} + + )} +
+ + + Raw IMU data stays on the ESP32-S3. Cloud events never imply current + safe motion. + + MSD · Supabase integration prototype +
+
+
+ ); +} diff --git a/src/components/TelemetryAvailability.tsx b/src/components/TelemetryAvailability.tsx index 169c876..1776e48 100644 --- a/src/components/TelemetryAvailability.tsx +++ b/src/components/TelemetryAvailability.tsx @@ -16,7 +16,7 @@ export function TelemetryAvailability({ now, }: { mode: TelemetryMode; - onModeChange: (mode: TelemetryMode) => void; + onModeChange: (mode: TelemetryMode | "cloud") => void; connected: boolean; freshness: TelemetryFreshness; lastReceivedAt: number | null; @@ -38,11 +38,12 @@ export function TelemetryAvailability({ id="telemetry-source" value={mode} onChange={(event) => - onModeChange(event.target.value as TelemetryMode) + onModeChange(event.target.value as TelemetryMode | "cloud") } > +
diff --git a/src/components/VehicleMap.tsx b/src/components/VehicleMap.tsx index f38642e..bc44d6f 100644 --- a/src/components/VehicleMap.tsx +++ b/src/components/VehicleMap.tsx @@ -16,6 +16,10 @@ export type VehicleMapProps = { }>; route: Coordinates[]; available: boolean; + sourceLabel?: string; + mapLabel?: string; + gpsStatusLabel?: string; + fitRoute?: boolean; }; const MAP_BOUNDS: L.LatLngBoundsExpression = [ @@ -74,6 +78,10 @@ export function VehicleMap({ events, route, available, + sourceLabel = "MSD-001 · simulated vehicle", + mapLabel = "Live GPS map of the simulated vehicle in San Francisco", + gpsStatusLabel = "GPS connected", + fitRoute = false, }: VehicleMapProps) { const container = useRef(null); const map = useRef(null); @@ -81,6 +89,7 @@ export function VehicleMap({ const routeLayers = useRef(null); const eventLayers = useRef(null); const following = useRef(true); + const hasFitRoute = useRef(false); const currentPosition = useRef(position); const [offline, setOffline] = useState(true); const [isFollowing, setIsFollowing] = useState(true); @@ -97,6 +106,7 @@ export function VehicleMap({ attributionControl: true, }); map.current = instance; + hasFitRoute.current = false; L.imageOverlay(offlineMapImage(), MAP_BOUNDS, { opacity: 1, interactive: false, @@ -119,7 +129,7 @@ export function VehicleMap({ zIndexOffset: 1000, keyboard: false, }).addTo(instance); - vehicle.current.bindTooltip("MSD-001 · simulated vehicle", { + vehicle.current.bindTooltip(sourceLabel, { direction: "top", offset: [0, -25], }); @@ -222,6 +232,21 @@ export function VehicleMap({ }); }, [events]); + useEffect(() => { + if (!fitRoute || hasFitRoute.current || !map.current || route.length === 0) + return; + const coordinates: L.LatLngExpression[] = route.map((point) => [ + point.latitude, + point.longitude, + ]); + map.current.fitBounds(L.latLngBounds(coordinates), { + padding: [35, 35], + maxZoom: 16, + animate: false, + }); + hasFitRoute.current = true; + }, [route, fitRoute]); + const recenter = () => { following.current = true; setIsFollowing(true); @@ -242,13 +267,13 @@ export function VehicleMap({ ref={container} className="vehicle-map__canvas" role="region" - aria-label="Live GPS map of the simulated vehicle in San Francisco" + aria-label={mapLabel} />
- {available ? "GPS connected" : "GPS unavailable"} + {available ? gpsStatusLabel : "GPS unavailable"}
diff --git a/src/domain/cloud.ts b/src/domain/cloud.ts new file mode 100644 index 0000000..8a22d57 --- /dev/null +++ b/src/domain/cloud.ts @@ -0,0 +1,73 @@ +/** Cloud records never contain continuous raw IMU samples. Times are ISO 8601 UTC. */ +export type ImuId = 1 | 2 | 3; +export type CloudDataSource = "simulated" | "device"; +export interface CloudSession { + id: string; + owner_id: string; + label: string; + started_at: string; + ended_at: string | null; + data_source: CloudDataSource; + created_at: string; +} +export interface GpsPoint { + id: string; + session_id: string; + sequence: number; + recorded_at: string; + received_at: string; + latitude: number; + longitude: number; + speed_kph: number | null; + heading: number | null; +} +export interface CloudThresholdEvent { + id: string; + session_id: string; + sequence: number; + imu_id: ImuId; + recorded_at: string; + received_at: string; + severity: "warning" | "critical"; + magnitude: number | null; + latitude: number | null; + longitude: number | null; + t1: number; + t2: number; +} +export interface CloudConnection { + session_id: string; + sequence: number; + recorded_at: string; + received_at: string; + connected: boolean; +} +export interface ImuThreshold { + session_id: string; + imu_id: ImuId; + t1: number; + t2: number; + updated_at: string; +} +export interface SessionObserver { + session_id: string; + user_id: string; + created_at: string; +} +export interface CloudSnapshot { + session: CloudSession; + gps: GpsPoint[]; + events: CloudThresholdEvent[]; + connection: CloudConnection | null; + thresholds: ImuThreshold[]; + observers: SessionObserver[]; +} +export type GpsUpload = Omit; +export type EventUpload = Omit< + CloudThresholdEvent, + "session_id" | "received_at" +>; +export type ConnectionUpload = Omit< + CloudConnection, + "session_id" | "received_at" +>; diff --git a/src/domain/cloudRecords.test.ts b/src/domain/cloudRecords.test.ts new file mode 100644 index 0000000..994f0ff --- /dev/null +++ b/src/domain/cloudRecords.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from "vitest"; +import type { CloudConnection, CloudThresholdEvent, GpsPoint } from "./cloud"; +import { + connectionFreshness, + gpsFreshness, + latestGps, + normalizeEvents, + normalizeGps, + routeDistanceKm, +} from "./cloudRecords"; +const base = 1_700_000_000_000; +const point = (sequence: number, age = sequence * 1000): GpsPoint => ({ + id: `gps-${sequence}`, + session_id: "session-a", + sequence, + recorded_at: new Date(base + age).toISOString(), + received_at: new Date(base + age + 100).toISOString(), + latitude: 37.77 + sequence * 0.001, + longitude: -122.42, + speed_kph: 30, + heading: 0, +}); + +describe("cloud source-time records", () => { + it("deduplicates repeated deliveries and sorts delayed positions by source time without mutating inputs", () => { + const rows = [point(3), point(1), point(2), point(1)]; + expect(normalizeGps(rows).map((p) => p.sequence)).toEqual([1, 2, 3]); + expect(rows.map((p) => p.sequence)).toEqual([3, 1, 2, 1]); + expect(latestGps(rows)?.sequence).toBe(3); + expect(routeDistanceKm(rows)).toBeCloseTo( + routeDistanceKm([point(1), point(2), point(3)]), + 8, + ); + }); + it("retains first received payload on conflicting duplicate IDs or session sequence numbers", () => { + const original = point(1); + const conflicting = { + ...original, + latitude: 0, + received_at: new Date(base + 9000).toISOString(), + }; + const conflictingSequence = { ...conflicting, id: "another-id" }; + expect(normalizeGps([conflictingSequence, conflicting, original])).toEqual([ + original, + ]); + }); + it("keeps distinct sessions sequences separate and resolves equal source times by sequence", () => { + const rows = [ + point(2, 1000), + point(1, 1000), + { ...point(1), id: "session-b-gps", session_id: "session-b" }, + ]; + expect(normalizeGps(rows)).toHaveLength(3); + expect( + normalizeGps([point(2, 1000), point(1, 1000)]).map((p) => p.sequence), + ).toEqual([1, 2]); + }); + it("never treats freshly received delayed GPS as a live position", () => { + const delayed = { + ...point(1), + received_at: new Date(base + 60_000).toISOString(), + }; + expect(gpsFreshness(delayed, base + 60_000)).toBe("stale"); + expect(gpsFreshness(point(1), base + 6000)).toBe("fresh"); + expect(gpsFreshness(point(1), base + 6001)).toBe("stale"); + expect(gpsFreshness(point(1), base)).toBe("waiting"); + expect(gpsFreshness(null, base)).toBe("waiting"); + }); + it("retains event reported severity and nullable GPS/magnitude under replay", () => { + const event: CloudThresholdEvent = { + ...point(1), + imu_id: 3, + severity: "critical", + magnitude: null, + latitude: null, + longitude: null, + t1: 0.8, + t2: 1.8, + }; + expect(normalizeEvents([event, event])).toEqual([event]); + }); + it("connection freshness uses source heartbeat time and never implies normal acceleration", () => { + const heartbeat: CloudConnection = { + session_id: "a", + sequence: 2, + recorded_at: new Date(base).toISOString(), + received_at: new Date(base + 60_000).toISOString(), + connected: true, + }; + expect(connectionFreshness(heartbeat, base + 15_000)).toBe("fresh"); + expect(connectionFreshness(heartbeat, base + 15_001)).toBe("stale"); + expect(connectionFreshness({ ...heartbeat, connected: false }, base)).toBe( + "disconnected", + ); + expect(connectionFreshness(null, base)).toBe("waiting"); + }); +}); diff --git a/src/domain/cloudRecords.ts b/src/domain/cloudRecords.ts new file mode 100644 index 0000000..77e92df --- /dev/null +++ b/src/domain/cloudRecords.ts @@ -0,0 +1,83 @@ +import type { CloudConnection, CloudThresholdEvent, GpsPoint } from "./cloud"; +import type { TelemetryFreshness } from "./types"; +import { haversineDistanceKm } from "./monitoring"; + +/** The database is append-only. If a duplicate delivery conflicts, retain the first received row. */ +function normalize< + T extends { + id: string; + session_id: string; + sequence: number; + recorded_at: string; + received_at: string; + }, +>(rows: readonly T[]): T[] { + const byId = new Set(); + const bySequence = new Set(); + return [...rows] + .sort( + (a, b) => + Date.parse(a.received_at) - Date.parse(b.received_at) || + a.id.localeCompare(b.id), + ) + .filter((row) => { + const sequence = `${row.session_id}:${row.sequence}`; + if (byId.has(row.id) || bySequence.has(sequence)) return false; + byId.add(row.id); + bySequence.add(sequence); + return true; + }) + .sort( + (a, b) => + Date.parse(a.recorded_at) - Date.parse(b.recorded_at) || + a.sequence - b.sequence || + a.id.localeCompare(b.id), + ); +} +export function normalizeGps(rows: readonly GpsPoint[]): GpsPoint[] { + return normalize(rows); +} +export function normalizeEvents( + rows: readonly CloudThresholdEvent[], +): CloudThresholdEvent[] { + return normalize(rows); +} +export function latestGps(rows: readonly GpsPoint[]): GpsPoint | null { + return normalizeGps(rows).at(-1) ?? null; +} + +/** Source time is essential: a delayed backlog received now is not a live GPS fix. */ +export function gpsFreshness( + point: GpsPoint | null, + now: number, + staleAfterMs = 5000, +): TelemetryFreshness { + if (!point) return "waiting"; + const timestamp = Date.parse(point.recorded_at); + if (!Number.isFinite(timestamp) || !Number.isFinite(now) || timestamp > now) + return "waiting"; + return now - timestamp <= staleAfterMs ? "fresh" : "stale"; +} +export function connectionFreshness( + connection: CloudConnection | null, + now: number, + staleAfterMs = 15000, +): TelemetryFreshness { + if (!connection) return "waiting"; + if (!connection.connected) return "disconnected"; + const timestamp = Date.parse(connection.recorded_at); + if (!Number.isFinite(timestamp) || !Number.isFinite(now) || timestamp > now) + return "waiting"; + return now - timestamp <= staleAfterMs ? "fresh" : "stale"; +} +/** Recalculate from source-time ordering rather than arrival-order deltas. */ +export function routeDistanceKm(rows: readonly GpsPoint[]): number { + const points = normalizeGps(rows); + return points + .slice(1) + .reduce( + (distance, point, index) => + distance + haversineDistanceKm(points[index], point), + 0, + ); +} diff --git a/src/domain/database.test.ts b/src/domain/database.test.ts new file mode 100644 index 0000000..4ca6096 --- /dev/null +++ b/src/domain/database.test.ts @@ -0,0 +1,548 @@ +import { readFileSync } from "node:fs"; +import { PGlite } from "@electric-sql/pglite"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; + +const owner = "11111111-1111-4111-8111-111111111111"; +const observer = "22222222-2222-4222-8222-222222222222"; +const outsider = "33333333-3333-4333-8333-333333333333"; +const unconfirmed = "44444444-4444-4444-8444-444444444444"; +let db: PGlite; + +async function asUser( + user: string | null, + operation: () => Promise, +): Promise { + await db.exec(`set role ${user ? "authenticated" : "anon"}`); + await db.query("select set_config('request.jwt.claim.sub', $1, false)", [ + user ?? "", + ]); + try { + return await operation(); + } finally { + await db.exec("reset role"); + } +} +async function createSession(user = owner, source = "simulated") { + const result = await asUser(user, () => + db.query<{ id: string }>( + "select public.create_driving_session($1, $2) as id", + ["Cloud test drive", source], + ), + ); + const id = result.rows[0].id; + // Historical source times allow deterministic delayed/reordered packet assertions. + await db.query( + "update public.driving_sessions set started_at = now() - interval '5 minutes' where id = $1", + [id], + ); + const row = await db.query<{ started_at: Date }>( + "select started_at from public.driving_sessions where id=$1", + [id], + ); + return { id, start: new Date(row.rows[0].started_at).getTime() }; +} +const at = (session: { start: number }, seconds: number) => + new Date(session.start + seconds * 1000).toISOString(); +const gps = (session: { start: number }, sequence: number, extra = {}) => ({ + id: crypto.randomUUID(), + sequence, + recorded_at: at(session, sequence), + latitude: 37.77, + longitude: -122.41, + speed_kph: 32, + heading: 90, + ...extra, +}); +const event = (session: { start: number }, sequence: number, extra = {}) => ({ + id: crypto.randomUUID(), + sequence, + imu_id: 1, + recorded_at: at(session, sequence), + severity: "warning", + magnitude: 1.8, + latitude: null, + longitude: null, + t1: 0.8, + t2: 1.8, + ...extra, +}); +async function ingestGps(sessionId: string, points: unknown[], user = owner) { + return asUser(user, () => + db.query("select public.ingest_gps($1,$2::jsonb)", [ + sessionId, + JSON.stringify(points), + ]), + ); +} +async function ingestEvents( + sessionId: string, + events: unknown[], + user = owner, +) { + return asUser(user, () => + db.query("select public.ingest_threshold_events($1,$2::jsonb)", [ + sessionId, + JSON.stringify(events), + ]), + ); +} +async function count(table: string, user: string) { + const result = await asUser(user, () => + db.query<{ count: number }>( + `select count(*)::int as count from public.${table}`, + ), + ); + return result.rows[0].count; +} + +beforeAll(async () => { + db = new PGlite(); + await db.exec(` + create schema auth; + create role anon; + create role authenticated; + create table auth.users(id uuid primary key,email text unique,email_confirmed_at timestamptz); + create function auth.uid() returns uuid language sql stable as $$ select nullif(current_setting('request.jwt.claim.sub',true),'')::uuid $$; + grant usage on schema public,auth to anon,authenticated; + grant execute on function auth.uid() to anon,authenticated; + `); + await db.exec( + readFileSync( + new URL( + "../../supabase/migrations/20261021000100_msd_cloud.sql", + import.meta.url, + ), + "utf8", + ), + ); +}, 30_000); +afterAll(async () => { + await db?.close(); +}); +beforeEach(async () => { + await db.exec( + "reset role; truncate public.driving_sessions,auth.users cascade;", + ); + await db.query( + "insert into auth.users(id,email,email_confirmed_at) values ($1,'owner@example.com',now()),($2,'observer@example.com',now()),($3,'outsider@example.com',now()),($4,'unconfirmed@example.com',null)", + [owner, observer, outsider, unconfirmed], + ); +}); + +describe("Supabase migration and RPC security in PostgreSQL", () => { + it("creates an owned session with exactly three IMUs and immutable provenance", async () => { + const session = await createSession(); + const result = await asUser(owner, () => + db.query<{ owner_id: string; data_source: string }>( + "select owner_id,data_source from public.driving_sessions", + ), + ); + expect(result.rows).toEqual([ + { owner_id: owner, data_source: "simulated" }, + ]); + const thresholds = await asUser(owner, () => + db.query<{ imu_id: number; t1: number; t2: number }>( + "select imu_id,t1,t2 from public.imu_thresholds where session_id=$1 order by imu_id", + [session.id], + ), + ); + expect(thresholds.rows).toEqual( + [1, 2, 3].map((imu_id) => ({ imu_id, t1: 0.8, t2: 1.8 })), + ); + await expect( + asUser(owner, () => + db.query( + "update public.driving_sessions set owner_id=$1,data_source='device' where id=$2", + [outsider, session.id], + ), + ), + ).rejects.toThrow(/permission denied/i); + await expect( + asUser(owner, () => + db.query("delete from public.driving_sessions where id=$1", [ + session.id, + ]), + ), + ).rejects.toThrow(/permission denied/i); + }); + + it("denies anonymous reads and RPCs and isolates other authenticated owners", async () => { + const session = await createSession(); + await ingestGps(session.id, [gps(session, 1)]); + for (const table of [ + "driving_sessions", + "session_observers", + "gps_points", + "threshold_events", + "connection_status", + "imu_thresholds", + ]) { + await expect( + asUser(null, () => db.query(`select * from public.${table}`)), + ).rejects.toThrow(/permission denied/i); + expect(await count(table, outsider)).toBe(0); + } + await expect( + asUser(null, () => + db.query("select public.create_driving_session('Anonymous','device')"), + ), + ).rejects.toThrow(/permission denied/i); + await expect( + ingestGps(session.id, [gps(session, 2)], outsider), + ).rejects.toThrow(/not owned/i); + await expect( + asUser(outsider, () => + db.query("select public.finish_driving_session($1)", [session.id]), + ), + ).rejects.toThrow(/not owned/i); + await expect( + asUser(owner, () => + db.query("select public.require_owned_session($1)", [session.id]), + ), + ).rejects.toThrow(/permission denied/i); + }); + + it("shares a session read-only with a confirmed account and revokes access", async () => { + const session = await createSession(); + await ingestGps(session.id, [gps(session, 1)]); + await ingestEvents(session.id, [event(session, 1)]); + await asUser(owner, () => + db.query("select public.share_session($1,'OBSERVER@example.com')", [ + session.id, + ]), + ); + expect(await count("driving_sessions", observer)).toBe(1); + expect(await count("gps_points", observer)).toBe(1); + expect(await count("threshold_events", observer)).toBe(1); + expect(await count("imu_thresholds", observer)).toBe(3); + await expect( + ingestGps(session.id, [gps(session, 2)], observer), + ).rejects.toThrow(/not owned/i); + await expect( + asUser(observer, () => + db.query("select public.share_session($1,'outsider@example.com')", [ + session.id, + ]), + ), + ).rejects.toThrow(/not owned/i); + await expect( + asUser(owner, () => + db.query("select public.share_session($1,'unconfirmed@example.com')", [ + session.id, + ]), + ), + ).rejects.toThrow(/confirm/i); + await asUser(owner, () => + db.query("select public.revoke_session_observer($1,$2)", [ + session.id, + observer, + ]), + ); + expect(await count("driving_sessions", observer)).toBe(0); + expect(await count("gps_points", observer)).toBe(0); + expect(await count("threshold_events", observer)).toBe(0); + }); + + it("preserves first-write-wins GPS history for duplicate and out-of-order packets", async () => { + const session = await createSession(); + const first = gps(session, 1); + const third = gps(session, 3); + const second = gps(session, 2); + await ingestGps(session.id, [third, first, second]); + await ingestGps(session.id, [ + first, + { ...first, id: crypto.randomUUID(), latitude: 1 }, + ]); + const result = await asUser(owner, () => + db.query<{ + sequence: number; + latitude: number; + received_at: Date; + recorded_at: Date; + }>( + "select sequence::int,latitude,received_at,recorded_at from public.gps_points where session_id=$1 order by recorded_at,sequence", + [session.id], + ), + ); + expect(result.rows.map((row) => row.sequence)).toEqual([1, 2, 3]); + expect(result.rows.every((row) => row.latitude === 37.77)).toBe(true); + expect( + result.rows.every( + (row) => + new Date(row.received_at).getTime() > + new Date(row.recorded_at).getTime(), + ), + ).toBe(true); + await expect( + asUser(owner, () => + db.query( + "update public.gps_points set latitude=0 where session_id=$1", + [session.id], + ), + ), + ).rejects.toThrow(/permission denied/i); + await expect( + asUser(owner, () => + db.query("delete from public.gps_points where session_id=$1", [ + session.id, + ]), + ), + ).rejects.toThrow(/permission denied/i); + await expect( + asUser(owner, () => + db.query( + "insert into public.gps_points(id,session_id,sequence,recorded_at,latitude,longitude) values(gen_random_uuid(),$1,4,now(),0,0)", + [session.id], + ), + ), + ).rejects.toThrow(/permission denied/i); + }); + + it("records all three IMUs, handles sparse events and preserves exact threshold snapshots", async () => { + const session = await createSession(); + const packets = [ + event(session, 1, { imu_id: 1, magnitude: 0.8 }), + event(session, 2, { imu_id: 2, magnitude: 1.8 }), + event(session, 3, { imu_id: 3, magnitude: 1.801, severity: "critical" }), + event(session, 4, { imu_id: 3, magnitude: null, severity: "critical" }), + ]; + await ingestEvents(session.id, [ + packets[2], + packets[0], + packets[3], + packets[1], + ]); + await ingestEvents(session.id, [ + packets[0], + { ...packets[0], id: crypto.randomUUID(), magnitude: 1.2 }, + ]); + const result = await asUser(owner, () => + db.query<{ + imu_id: number; + magnitude: number | null; + t1: number; + t2: number; + severity: string; + }>( + "select imu_id,magnitude,t1,t2,severity from public.threshold_events where session_id=$1 order by sequence", + [session.id], + ), + ); + expect(result.rows).toEqual([ + { imu_id: 1, magnitude: 0.8, t1: 0.8, t2: 1.8, severity: "warning" }, + { imu_id: 2, magnitude: 1.8, t1: 0.8, t2: 1.8, severity: "warning" }, + { imu_id: 3, magnitude: 1.801, t1: 0.8, t2: 1.8, severity: "critical" }, + { imu_id: 3, magnitude: null, t1: 0.8, t2: 1.8, severity: "critical" }, + ]); + await asUser(owner, () => + db.query("select public.set_imu_thresholds($1,$2::jsonb)", [ + session.id, + JSON.stringify([1, 2, 3].map((imu_id) => ({ imu_id, t1: 2, t2: 3 }))), + ]), + ); + const unchanged = await asUser(owner, () => + db.query<{ t1: number; t2: number }>( + "select t1,t2 from public.threshold_events where session_id=$1", + [session.id], + ), + ); + expect( + unchanged.rows.every((row) => row.t1 === 0.8 && row.t2 === 1.8), + ).toBe(true); + await expect( + ingestEvents(session.id, [ + event(session, 5, { magnitude: 1.8, severity: "critical" }), + ]), + ).rejects.toThrow(/check constraint/i); + await expect( + ingestEvents(session.id, [event(session, 6, { imu_id: 4 })]), + ).rejects.toThrow(/check constraint/i); + await expect( + ingestEvents(session.id, [ + event(session, 7, { latitude: 37.7, longitude: null }), + ]), + ).rejects.toThrow(/check constraint/i); + }); + + it("updates exactly three thresholds atomically and denies observer configuration writes", async () => { + const session = await createSession(); + const valid = [1, 2, 3].map((imu_id) => ({ imu_id, t1: 1, t2: 2 })); + await asUser(owner, () => + db.query("select public.set_imu_thresholds($1,$2::jsonb)", [ + session.id, + JSON.stringify(valid), + ]), + ); + for (const invalid of [ + valid.slice(0, 2), + [valid[0], valid[0], valid[2]], + [valid[0], { ...valid[0], imu_id: "01" }, valid[2]], + [valid[0], { imu_id: 2, t1: 5, t2: 2 }, valid[2]], + ]) { + await expect( + asUser(owner, () => + db.query("select public.set_imu_thresholds($1,$2::jsonb)", [ + session.id, + JSON.stringify(invalid), + ]), + ), + ).rejects.toThrow(); + } + const saved = await asUser(owner, () => + db.query<{ t1: number; t2: number }>( + "select t1,t2 from public.imu_thresholds where session_id=$1", + [session.id], + ), + ); + expect(saved.rows).toEqual([ + { t1: 1, t2: 2 }, + { t1: 1, t2: 2 }, + { t1: 1, t2: 2 }, + ]); + await expect( + asUser(outsider, () => + db.query("select public.set_imu_thresholds($1,$2::jsonb)", [ + session.id, + JSON.stringify(valid), + ]), + ), + ).rejects.toThrow(/not owned/i); + }); + + it("keeps reordered connection status history and selects current state by highest sequence", async () => { + const session = await createSession(); + for (const [sequence, connected] of [ + [3, false], + [1, true], + [2, true], + [3, true], + ] as const) { + await asUser(owner, () => + db.query("select public.ingest_connection($1,$2::jsonb)", [ + session.id, + JSON.stringify({ + sequence, + connected, + recorded_at: at(session, sequence), + }), + ]), + ); + } + const result = await asUser(owner, () => + db.query<{ sequence: number; connected: boolean }>( + "select sequence::int,connected from public.connection_status where session_id=$1 order by sequence desc", + [session.id], + ), + ); + expect(result.rows).toEqual([ + { sequence: 3, connected: false }, + { sequence: 2, connected: true }, + { sequence: 1, connected: true }, + ]); + await expect( + asUser(owner, () => + db.query( + "update public.connection_status set connected=true where session_id=$1", + [session.id], + ), + ), + ).rejects.toThrow(/permission denied/i); + }); + + it("accepts delayed telemetry recorded before session end and rejects packets outside its bounds", async () => { + const session = await createSession(); + await asUser(owner, () => + db.query("select public.finish_driving_session($1)", [session.id]), + ); + await ingestGps(session.id, [gps(session, 10)]); + await ingestEvents(session.id, [event(session, 10)]); + await expect( + ingestGps(session.id, [ + gps(session, 11, { recorded_at: at(session, -1) }), + ]), + ).rejects.toThrow(/bounds/i); + await expect( + ingestGps(session.id, [ + gps(session, 12, { + recorded_at: new Date(Date.now() + 30_000).toISOString(), + }), + ]), + ).rejects.toThrow(/bounds/i); + const before = await db.query<{ ended_at: Date }>( + "select ended_at from public.driving_sessions where id=$1", + [session.id], + ); + await asUser(owner, () => + db.query("select public.finish_driving_session($1)", [session.id]), + ); + const after = await db.query<{ ended_at: Date }>( + "select ended_at from public.driving_sessions where id=$1", + [session.id], + ); + expect(after.rows[0].ended_at).toEqual(before.rows[0].ended_at); + }); + + it("keeps accepted clock-tolerant records inside the final session bounds", async () => { + const session = await createSession(); + const recordedAt = new Date(Date.now() + 30_000).toISOString(); + await ingestGps(session.id, [gps(session, 1, { recorded_at: recordedAt })]); + await asUser(owner, () => + db.query("select public.finish_driving_session($1)", [session.id]), + ); + const result = await asUser(owner, () => + db.query<{ ended_at: Date }>( + "select ended_at from public.driving_sessions where id=$1", + [session.id], + ), + ); + expect(new Date(result.rows[0].ended_at).getTime()).toBeGreaterThanOrEqual( + Date.parse(recordedAt), + ); + }); + + it("rejects bad batches, invalid GPS and future source times without partial writes", async () => { + const session = await createSession(); + await expect(ingestGps(session.id, [])).rejects.toThrow(/1 to 100/i); + await expect( + ingestGps( + session.id, + Array.from({ length: 101 }, (_, i) => gps(session, i)), + ), + ).rejects.toThrow(/1 to 100/i); + await expect( + ingestGps(session.id, [ + gps(session, 1), + gps(session, 2, { latitude: 100 }), + ]), + ).rejects.toThrow(/check constraint/i); + expect(await count("gps_points", owner)).toBe(0); + await expect( + ingestGps(session.id, [ + gps(session, 1, { + recorded_at: new Date(Date.now() + 120_000).toISOString(), + }), + ]), + ).rejects.toThrow(/bounds/i); + await expect( + ingestGps(session.id, [gps(session, 1, { sequence: 9007199254740992 })]), + ).rejects.toThrow(/check constraint/i); + await expect( + ingestGps(session.id, [gps(session, 1, { speed_kph: "NaN" })]), + ).rejects.toThrow(/check constraint/i); + }); + + it("enables RLS on all tables and excludes sensitive membership DELETE keys from Realtime", async () => { + const rls = await db.query<{ relname: string; relrowsecurity: boolean }>( + "select relname,relrowsecurity from pg_class where relnamespace='public'::regnamespace and relkind='r' order by relname", + ); + expect(rls.rows).toHaveLength(6); + expect(rls.rows.every((row) => row.relrowsecurity)).toBe(true); + const publication = await db.query( + "select tablename from pg_publication_tables where pubname='supabase_realtime'", + ); + expect(publication.rows).toHaveLength(5); + expect(publication.rows).not.toContainEqual({ + tablename: "session_observers", + }); + }); +}); diff --git a/src/hooks/useCloudAuth.test.tsx b/src/hooks/useCloudAuth.test.tsx new file mode 100644 index 0000000..4d5faa3 --- /dev/null +++ b/src/hooks/useCloudAuth.test.tsx @@ -0,0 +1,148 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { + AuthChangeEvent, + Session, + SupabaseClient, + User, +} from "@supabase/supabase-js"; +import { useCloudAuth } from "./useCloudAuth"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} +const user = { id: "owner-a", email: "owner@example.com" } as User; +function authFixture( + initial = Promise.resolve({ + data: { session: null as Session | null }, + error: null, + }), +) { + let callback: ( + event: AuthChangeEvent, + session: Session | null, + ) => void = () => {}; + const unsubscribe = vi.fn(); + const auth = { + getSession: vi.fn(() => initial), + onAuthStateChange: vi.fn((listener: typeof callback) => { + callback = listener; + return { data: { subscription: { unsubscribe } } }; + }), + signInWithPassword: vi + .fn() + .mockResolvedValue({ data: { user }, error: null }), + signUp: vi + .fn() + .mockResolvedValue({ data: { user, session: null }, error: null }), + signOut: vi.fn().mockResolvedValue({ error: null }), + }; + return { + client: { auth } as unknown as SupabaseClient, + auth, + unsubscribe, + emit: (event: AuthChangeEvent, current: User | null) => + callback(event, current ? ({ user: current } as Session) : null), + }; +} +afterEach(() => cleanup()); + +describe("cloud authentication lifetime", () => { + it("does not restore an old user when a late getSession resolves after a sign-out notification", async () => { + const initial = deferred<{ + data: { session: Session | null }; + error: null; + }>(); + const fixture = authFixture(initial.promise); + const { result } = renderHook(() => useCloudAuth(fixture.client)); + act(() => fixture.emit("SIGNED_OUT", null)); + await act(async () => + initial.resolve({ data: { session: { user } as Session }, error: null }), + ); + expect(result.current.user).toBeNull(); + expect(result.current.loading).toBe(false); + }); + + it("does not restore an old user after explicit signOut even if no auth notification arrives", async () => { + const initial = deferred<{ + data: { session: Session | null }; + error: null; + }>(); + const fixture = authFixture(initial.promise); + const { result } = renderHook(() => useCloudAuth(fixture.client)); + await act(async () => { + expect(await result.current.signOut()).toBe(true); + }); + await act(async () => + initial.resolve({ data: { session: { user } as Session }, error: null }), + ); + expect(result.current.user).toBeNull(); + expect(result.current.loading).toBe(false); + }); + + it("ignores a previous client's auth response after configuration changes", async () => { + const initial = deferred<{ + data: { session: Session | null }; + error: null; + }>(); + const first = authFixture(initial.promise); + const second = authFixture(); + const { result, rerender } = renderHook( + ({ client }) => useCloudAuth(client), + { initialProps: { client: first.client } }, + ); + rerender({ client: second.client }); + await waitFor(() => expect(result.current.loading).toBe(false)); + await act(async () => + initial.resolve({ data: { session: { user } as Session }, error: null }), + ); + expect(result.current.user).toBeNull(); + expect(first.unsubscribe).toHaveBeenCalledTimes(1); + }); + + it("surfaces confirmation requirements and authenticates only when there is a session", async () => { + const fixture = authFixture(); + const { result } = renderHook(() => useCloudAuth(fixture.client)); + await waitFor(() => expect(result.current.loading).toBe(false)); + await act(async () => { + expect( + await result.current.signUp(" owner@example.com ", "test-password"), + ).toBe(true); + }); + expect(result.current.user).toBeNull(); + expect(result.current.notice).toMatch(/confirm your account/i); + expect(fixture.auth.signUp).toHaveBeenCalledWith( + expect.objectContaining({ email: "owner@example.com" }), + ); + await act(async () => { + expect( + await result.current.signIn(" owner@example.com ", "test-password"), + ).toBe(true); + }); + expect(result.current.user?.id).toBe("owner-a"); + }); + + it("surfaces auth errors without creating a user and cleans up on unmount", async () => { + const fixture = authFixture(); + fixture.auth.signInWithPassword.mockResolvedValue({ + data: { user: null }, + error: new Error("Invalid credentials"), + }); + const { result, unmount } = renderHook(() => useCloudAuth(fixture.client)); + await waitFor(() => expect(result.current.loading).toBe(false)); + await act(async () => { + expect( + await result.current.signIn("owner@example.com", "invalid-password"), + ).toBe(false); + }); + expect(result.current.user).toBeNull(); + expect(result.current.error).toBe("Invalid credentials"); + unmount(); + expect(fixture.unsubscribe).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/hooks/useCloudAuth.ts b/src/hooks/useCloudAuth.ts new file mode 100644 index 0000000..c621ec2 --- /dev/null +++ b/src/hooks/useCloudAuth.ts @@ -0,0 +1,207 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import type { SupabaseClient, User } from "@supabase/supabase-js"; + +type AuthState = { + client: SupabaseClient | null; + user: User | null; + initializing: boolean; + busy: boolean; + error: string | null; + notice: string | null; +}; + +/** Only the Supabase auth session establishes an authenticated cloud identity. */ +export function useCloudAuth(client: SupabaseClient | null) { + const epoch = useRef(0); + const authRevision = useRef(0); + const [state, setState] = useState({ + client, + user: null, + initializing: client !== null, + busy: false, + error: null, + notice: null, + }); + + useEffect(() => { + const generation = ++epoch.current; + authRevision.current += 1; + setState({ + client, + user: null, + initializing: client !== null, + busy: false, + error: null, + notice: null, + }); + if (!client) return; + const { + data: { subscription }, + } = client.auth.onAuthStateChange((_event, session) => { + if (epoch.current !== generation) return; + authRevision.current += 1; + setState((old) => ({ + ...old, + client, + user: session?.user ?? null, + initializing: false, + error: null, + })); + }); + const initialRevision = authRevision.current; + void client.auth + .getSession() + .then(({ data, error }) => { + if ( + epoch.current !== generation || + authRevision.current !== initialRevision + ) + return; + setState((old) => ({ + ...old, + client, + user: data.session?.user ?? null, + initializing: false, + error: error?.message ?? null, + })); + }) + .catch((error: unknown) => { + if ( + epoch.current !== generation || + authRevision.current !== initialRevision + ) + return; + setState((old) => ({ + ...old, + initializing: false, + error: + error instanceof Error + ? error.message + : "Could not restore the cloud sign-in session.", + })); + }); + return () => { + epoch.current += 1; + subscription.unsubscribe(); + }; + }, [client]); + + const signIn = useCallback( + async (email: string, password: string): Promise => { + if (!client) return false; + const generation = epoch.current; + setState((old) => ({ ...old, busy: true, error: null, notice: null })); + try { + const { data, error } = await client.auth.signInWithPassword({ + email: email.trim(), + password, + }); + if (epoch.current !== generation) return false; + if (error) throw error; + authRevision.current += 1; + setState((old) => ({ + ...old, + client, + user: data.user, + initializing: false, + busy: false, + })); + return true; + } catch (error) { + if (epoch.current === generation) + setState((old) => ({ + ...old, + busy: false, + error: + error instanceof Error + ? error.message + : "Could not sign in. Please try again.", + })); + return false; + } + }, + [client], + ); + + const signUp = useCallback( + async (email: string, password: string): Promise => { + if (!client) return false; + const generation = epoch.current; + setState((old) => ({ ...old, busy: true, error: null, notice: null })); + try { + const { data, error } = await client.auth.signUp({ + email: email.trim(), + password, + options: { emailRedirectTo: window.location.origin }, + }); + if (epoch.current !== generation) return false; + if (error) throw error; + authRevision.current += 1; + setState((old) => ({ + ...old, + client, + user: data.session?.user ?? null, + initializing: false, + busy: false, + notice: data.session + ? "Account created. You are signed in." + : "Check your email to confirm your account, then return here to sign in.", + })); + return true; + } catch (error) { + if (epoch.current === generation) + setState((old) => ({ + ...old, + busy: false, + error: + error instanceof Error + ? error.message + : "Could not create an account. Please try again.", + })); + return false; + } + }, + [client], + ); + + const signOut = useCallback(async (): Promise => { + if (!client) return false; + const generation = epoch.current; + setState((old) => ({ ...old, busy: true, error: null, notice: null })); + try { + const { error } = await client.auth.signOut(); + if (epoch.current !== generation) return false; + if (error) throw error; + authRevision.current += 1; + setState((old) => ({ + ...old, + user: null, + initializing: false, + busy: false, + })); + return true; + } catch (error) { + if (epoch.current === generation) + setState((old) => ({ + ...old, + busy: false, + error: + error instanceof Error + ? error.message + : "Could not sign out. Please try again.", + })); + return false; + } + }, [client]); + + const current = state.client === client; + return { + user: current ? state.user : null, + loading: current ? state.initializing || state.busy : client !== null, + error: current ? state.error : null, + notice: current ? state.notice : null, + signIn, + signUp, + signOut, + }; +} diff --git a/src/hooks/useCloudSession.test.tsx b/src/hooks/useCloudSession.test.tsx new file mode 100644 index 0000000..980eb05 --- /dev/null +++ b/src/hooks/useCloudSession.test.tsx @@ -0,0 +1,243 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { CloudSession, CloudSnapshot } from "../domain/cloud"; +import type { + CloudRepository, + RealtimeState, +} from "../services/cloudRepository"; +import { useCloudSession } from "./useCloudSession"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} +function session(id: string, owner = "owner-a"): CloudSession { + return { + id, + owner_id: owner, + label: id, + started_at: "2026-10-21T12:00:00Z", + ended_at: null, + data_source: "simulated", + created_at: "2026-10-21T12:00:00Z", + }; +} +function snapshot(id: string, sequence?: number): CloudSnapshot { + return { + session: session(id), + gps: + sequence === undefined + ? [] + : [ + { + id: `gps-${sequence}`, + session_id: id, + sequence, + recorded_at: "2026-10-21T12:00:01Z", + received_at: "2026-10-21T12:00:01Z", + latitude: 37, + longitude: -122, + speed_kph: 30, + heading: 0, + }, + ], + events: [], + connection: null, + thresholds: [], + observers: [], + }; +} +function repositoryFixture( + rows = [session("session-a"), session("session-b")], +) { + const order: string[] = []; + const subscriptions: Array<{ + id: string; + change: () => void; + status: (state: RealtimeState) => void; + unsubscribe: ReturnType; + }> = []; + const methods = { + listSessions: vi.fn(async () => rows), + loadSnapshot: vi.fn(async (id: string) => { + order.push(`load:${id}`); + return snapshot(id); + }), + watchSession: vi.fn( + ( + id: string, + change: () => void, + status: (state: RealtimeState) => void, + ) => { + order.push(`watch:${id}`); + const subscription = { id, change, status, unsubscribe: vi.fn() }; + subscriptions.push(subscription); + status("connecting"); + return subscription.unsubscribe; + }, + ), + }; + return { + repository: methods as unknown as CloudRepository, + methods, + order, + subscriptions, + }; +} +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("cloud observer synchronization", () => { + it("registers realtime before loading and reconciles a change received during the initial snapshot", async () => { + const fixture = repositoryFixture(); + const first = deferred(); + fixture.methods.loadSnapshot + .mockImplementationOnce(async (id) => { + fixture.order.push(`load:${id}`); + return first.promise; + }) + .mockImplementationOnce(async (id) => snapshot(id, 2)); + const { result } = renderHook(() => + useCloudSession(fixture.repository, "owner-a"), + ); + await waitFor(() => + expect(fixture.methods.loadSnapshot).toHaveBeenCalledTimes(1), + ); + expect(fixture.order.slice(0, 2)).toEqual([ + "watch:session-a", + "load:session-a", + ]); + act(() => fixture.subscriptions[0].change()); + await act(async () => first.resolve(snapshot("session-a", 1))); + await waitFor(() => + expect(result.current.snapshot?.gps[0]?.sequence).toBe(2), + ); + expect(fixture.methods.loadSnapshot).toHaveBeenCalledTimes(2); + }); + + it("never replaces the selected session with a slow response from an old selection", async () => { + const fixture = repositoryFixture(); + const first = deferred(); + fixture.methods.loadSnapshot.mockImplementationOnce( + async () => first.promise, + ); + const { result } = renderHook(() => + useCloudSession(fixture.repository, "owner-a"), + ); + await waitFor(() => + expect(fixture.methods.loadSnapshot).toHaveBeenCalledWith("session-a"), + ); + act(() => result.current.setSelectedId("session-b")); + await waitFor(() => + expect(result.current.snapshot?.session.id).toBe("session-b"), + ); + await act(async () => first.resolve(snapshot("session-a", 9))); + expect(result.current.snapshot?.session.id).toBe("session-b"); + expect(fixture.subscriptions[0].unsubscribe).toHaveBeenCalledTimes(1); + }); + + it("clears records on sign-out and ignores an earlier user's in-flight response", async () => { + const fixture = repositoryFixture(); + const first = deferred(); + fixture.methods.loadSnapshot.mockImplementationOnce( + async () => first.promise, + ); + const { result, rerender } = renderHook( + ({ userId }: { userId: string | null }) => + useCloudSession(fixture.repository, userId), + { initialProps: { userId: "owner-a" as string | null } }, + ); + await waitFor(() => + expect(fixture.methods.loadSnapshot).toHaveBeenCalledTimes(1), + ); + rerender({ userId: null }); + expect(result.current.snapshot).toBeNull(); + expect(result.current.sessions).toEqual([]); + expect(result.current.selectedId).toBeNull(); + await act(async () => first.resolve(snapshot("session-a", 9))); + expect(result.current.snapshot).toBeNull(); + expect(result.current.sessions).toEqual([]); + expect(result.current.realtimeStatus).toBe("closed"); + expect(fixture.subscriptions[0].unsubscribe).toHaveBeenCalledTimes(1); + }); + + it("does not expose one user's session when switching directly to another user", async () => { + const fixture = repositoryFixture([session("session-a")]); + const { result, rerender } = renderHook( + ({ userId }) => useCloudSession(fixture.repository, userId), + { initialProps: { userId: "owner-a" } }, + ); + await waitFor(() => + expect(result.current.snapshot?.session.id).toBe("session-a"), + ); + fixture.methods.listSessions.mockResolvedValue([ + session("session-b", "owner-b"), + ]); + rerender({ userId: "owner-b" }); + expect(result.current.snapshot?.session.id).not.toBe("session-a"); + await waitFor(() => + expect(result.current.snapshot?.session.id).toBe("session-b"), + ); + }); + + it("clears a previously loaded route when access or a snapshot refresh fails", async () => { + const fixture = repositoryFixture(); + const { result } = renderHook(() => + useCloudSession(fixture.repository, "owner-a"), + ); + await waitFor(() => + expect(result.current.snapshot?.session.id).toBe("session-a"), + ); + fixture.methods.loadSnapshot.mockRejectedValueOnce( + new Error("Session access revoked"), + ); + await act(async () => result.current.refreshSnapshot()); + expect(result.current.snapshot).toBeNull(); + expect(result.current.error).toBe("Session access revoked"); + expect(result.current.loading).toBe(false); + }); + + it("reloads after realtime reconnect to recover events missed during an outage", async () => { + const fixture = repositoryFixture(); + const { result } = renderHook(() => + useCloudSession(fixture.repository, "owner-a"), + ); + await waitFor(() => + expect(result.current.snapshot?.session.id).toBe("session-a"), + ); + act(() => fixture.subscriptions[0].status("error")); + expect(result.current.realtimeStatus).toBe("error"); + fixture.methods.loadSnapshot.mockResolvedValueOnce( + snapshot("session-a", 3), + ); + act(() => fixture.subscriptions[0].status("subscribed")); + await waitFor(() => + expect(result.current.snapshot?.gps[0]?.sequence).toBe(3), + ); + expect(result.current.realtimeStatus).toBe("subscribed"); + }); + + it("cleans up the realtime channel and reconciliation interval, rejecting late callbacks", async () => { + const clearInterval = vi.spyOn(window, "clearInterval"); + const fixture = repositoryFixture(); + const { result, unmount } = renderHook(() => + useCloudSession(fixture.repository, "owner-a"), + ); + await waitFor(() => + expect(result.current.snapshot?.session.id).toBe("session-a"), + ); + const calls = fixture.methods.loadSnapshot.mock.calls.length; + unmount(); + expect(fixture.subscriptions[0].unsubscribe).toHaveBeenCalledTimes(1); + expect(clearInterval).toHaveBeenCalled(); + fixture.subscriptions[0].change(); + fixture.subscriptions[0].status("subscribed"); + expect(fixture.methods.loadSnapshot).toHaveBeenCalledTimes(calls); + }); +}); diff --git a/src/hooks/useCloudSession.ts b/src/hooks/useCloudSession.ts new file mode 100644 index 0000000..550f529 --- /dev/null +++ b/src/hooks/useCloudSession.ts @@ -0,0 +1,296 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import type { CloudSession, CloudSnapshot } from "../domain/cloud"; +import type { CloudRepository } from "../services/cloudRepository"; + +type RealtimeStatus = "connecting" | "subscribed" | "error" | "closed"; +type CloudState = { + repository: CloudRepository | null; + userId: string | null; + sessions: CloudSession[]; + selectedId: string | null; + snapshot: CloudSnapshot | null; + listLoading: boolean; + snapshotLoading: boolean; + listError: string | null; + snapshotError: string | null; + realtimeStatus: RealtimeStatus; +}; +const errorMessage = (error: unknown) => + error instanceof Error + ? error.message + : "Could not load cloud records. Please retry."; + +/** + * Owns the observer subscription, bounded reconciliation polling, and snapshot + * lifetime. Auth/selection changes invalidate pending work before it can be shown. + */ +export function useCloudSession( + repository: CloudRepository | null, + userId: string | null, +) { + const contextEpoch = useRef(0); + const selectionEpoch = useRef(0); + const listRequest = useRef(0); + const selectedRef = useRef(null); + const snapshotController = useRef<{ + context: number; + selection: number; + id: string; + reload: () => Promise; + } | null>(null); + const [state, setState] = useState({ + repository, + userId, + sessions: [], + selectedId: null, + snapshot: null, + listLoading: Boolean(repository && userId), + snapshotLoading: false, + listError: null, + snapshotError: null, + realtimeStatus: "closed", + }); + + const refreshSessions = useCallback(async (): Promise => { + if (!repository || !userId) return; + const context = contextEpoch.current; + const request = ++listRequest.current; + try { + const sessions = await repository.listSessions(); + if (contextEpoch.current !== context || listRequest.current !== request) + return; + const previous = selectedRef.current; + const next = sessions.some((session) => session.id === previous) + ? previous + : (sessions[0]?.id ?? null); + if (next !== previous) { + selectedRef.current = next; + selectionEpoch.current += 1; + } + setState((old) => + contextEpoch.current !== context || + old.repository !== repository || + old.userId !== userId + ? old + : { + ...old, + sessions, + selectedId: next, + listLoading: false, + listError: null, + snapshot: next === previous ? old.snapshot : null, + snapshotLoading: + next !== null && (next !== previous || old.snapshotLoading), + snapshotError: next === previous ? old.snapshotError : null, + }, + ); + } catch (error) { + if (contextEpoch.current !== context || listRequest.current !== request) + return; + // Never continue displaying a cached route as current after a failed access check. + setState((old) => + old.repository !== repository || old.userId !== userId + ? old + : { + ...old, + listLoading: false, + snapshotLoading: false, + listError: errorMessage(error), + snapshot: null, + }, + ); + } + }, [repository, userId]); + + const setSelectedId = useCallback( + (id: string | null) => { + if (!repository || !userId || id === selectedRef.current) return; + selectedRef.current = id; + selectionEpoch.current += 1; + setState((old) => + old.repository !== repository || old.userId !== userId + ? old + : { + ...old, + selectedId: id, + snapshot: null, + snapshotLoading: id !== null, + snapshotError: null, + realtimeStatus: id ? "connecting" : "closed", + }, + ); + }, + [repository, userId], + ); + + const refreshSnapshot = useCallback(async (): Promise => { + const controller = snapshotController.current; + if ( + controller && + controller.context === contextEpoch.current && + controller.selection === selectionEpoch.current && + controller.id === selectedRef.current + ) + await controller.reload(); + }, []); + + useEffect(() => { + const context = ++contextEpoch.current; + selectionEpoch.current += 1; + listRequest.current += 1; + selectedRef.current = null; + snapshotController.current = null; + setState({ + repository, + userId, + sessions: [], + selectedId: null, + snapshot: null, + listLoading: Boolean(repository && userId), + snapshotLoading: false, + listError: null, + snapshotError: null, + realtimeStatus: "closed", + }); + if (!repository || !userId) return; + void refreshSessions(); + const poll = window.setInterval(() => { + void refreshSessions(); + void refreshSnapshot(); + }, 10_000); + return () => { + if (contextEpoch.current === context) contextEpoch.current += 1; + selectionEpoch.current += 1; + listRequest.current += 1; + window.clearInterval(poll); + }; + }, [repository, userId, refreshSessions, refreshSnapshot]); + + const currentContext = + state.repository === repository && state.userId === userId; + const selectedId = currentContext ? state.selectedId : null; + + useEffect(() => { + if (!repository || !userId || !selectedId) return; + const context = contextEpoch.current; + const selection = selectionEpoch.current; + let disposed = false; + let pending = false; + let running: Promise | null = null; + const active = () => + !disposed && + contextEpoch.current === context && + selectionEpoch.current === selection && + selectedRef.current === selectedId; + const commit = (update: (old: CloudState) => CloudState) => { + if (!active()) return; + setState((old) => + active() && + old.repository === repository && + old.userId === userId && + old.selectedId === selectedId + ? update(old) + : old, + ); + }; + const reload = (): Promise => { + if (!active()) return Promise.resolve(); + pending = true; + if (running) return running; + running = (async () => { + while (pending && active()) { + pending = false; + commit((old) => ({ ...old, snapshotLoading: old.snapshot === null })); + try { + const snapshot = await repository.loadSnapshot(selectedId); + if (!active()) return; + if (snapshot.session.id !== selectedId) + throw new Error( + "Received records for a different driving session.", + ); + commit((old) => ({ + ...old, + snapshot, + snapshotLoading: false, + snapshotError: null, + })); + } catch (error) { + if (!active()) return; + commit((old) => ({ + ...old, + snapshot: null, + snapshotLoading: false, + snapshotError: errorMessage(error), + })); + // A network failure must not spin on already queued invalidations. + pending = false; + } + } + })().finally(() => { + running = null; + }); + return running; + }; + snapshotController.current = { context, selection, id: selectedId, reload }; + commit((old) => ({ + ...old, + snapshot: null, + snapshotLoading: true, + snapshotError: null, + realtimeStatus: "connecting", + })); + // Register before requesting the snapshot. A change during that request queues + // a second read; subscription/reconnect acknowledgments also reconcile gaps. + let unsubscribe = () => {}; + try { + unsubscribe = repository.watchSession( + selectedId, + () => { + void reload(); + }, + (status) => { + commit((old) => ({ ...old, realtimeStatus: status })); + if (status === "subscribed") void reload(); + }, + ); + void reload(); + } catch (error) { + commit((old) => ({ + ...old, + snapshotLoading: false, + snapshot: null, + snapshotError: errorMessage(error), + realtimeStatus: "error", + })); + } + return () => { + disposed = true; + pending = false; + unsubscribe(); + if ( + snapshotController.current?.context === context && + snapshotController.current.selection === selection + ) + snapshotController.current = null; + }; + }, [repository, userId, selectedId]); + + return { + sessions: currentContext ? state.sessions : [], + selectedId, + setSelectedId, + snapshot: + currentContext && state.snapshot?.session.id === selectedId + ? state.snapshot + : null, + loading: currentContext + ? state.listLoading || state.snapshotLoading + : Boolean(repository && userId), + error: currentContext ? (state.listError ?? state.snapshotError) : null, + realtimeStatus: currentContext + ? state.realtimeStatus + : ("closed" as RealtimeStatus), + refreshSessions, + refreshSnapshot, + }; +} diff --git a/src/hooks/useMonitor.ts b/src/hooks/useMonitor.ts index 4da5dd3..d8340b4 100644 --- a/src/hooks/useMonitor.ts +++ b/src/hooks/useMonitor.ts @@ -36,8 +36,8 @@ function createSession(source: TelemetryMode): DrivingSession { }; } -export function useMonitor() { - const [mode, updateMode] = useState("simulation"); +export function useMonitor(initialMode: TelemetryMode = "simulation") { + const [mode, updateMode] = useState(initialMode); const [connected, updateConnected] = useState(true); const [deviceConnected, setDeviceConnected] = useState(false); const [paused, setPaused] = useState(false); diff --git a/src/services/cloudRepository.test.ts b/src/services/cloudRepository.test.ts new file mode 100644 index 0000000..8677b4f --- /dev/null +++ b/src/services/cloudRepository.test.ts @@ -0,0 +1,303 @@ +import { describe, expect, it, vi } from "vitest"; +import type { SupabaseClient } from "@supabase/supabase-js"; +import { CloudRepository } from "./cloudRepository"; +import { assertPublicSupabaseKeys, getSupabaseConfig } from "./supabase"; +import type { CloudSession, GpsPoint } from "../domain/cloud"; + +type Query = { + table: string; + operations: Array<{ name: string; args: unknown[] }>; +}; +function mockClient( + resolve: (query: Query) => { + data: unknown; + error: { message: string } | null; + }, +) { + const queries: Query[] = []; + const rpc = vi.fn(async () => ({ data: null, error: null })); + const client = { + rpc, + from(table: string) { + const query: Query = { table, operations: [] }; + queries.push(query); + const builder = { + then( + onFulfilled: (value: unknown) => unknown, + onRejected?: (reason: unknown) => unknown, + ) { + return Promise.resolve(resolve(query)).then(onFulfilled, onRejected); + }, + } as Record; + for (const name of [ + "select", + "eq", + "order", + "range", + "single", + "maybeSingle", + "limit", + ]) + builder[name] = (...args: unknown[]) => { + query.operations.push({ name, args }); + return builder; + }; + return builder; + }, + }; + return { client: client as unknown as SupabaseClient, queries, rpc }; +} +const session: CloudSession = { + id: "a", + owner_id: "owner", + label: "Drive", + started_at: "2026-10-21T00:00:00Z", + ended_at: null, + data_source: "simulated", + created_at: "2026-10-21T00:00:00Z", +}; +const gps = (sequence: number): GpsPoint => ({ + id: `gps-${sequence}`, + session_id: "a", + sequence, + recorded_at: new Date(1700000000000 + sequence * 1000).toISOString(), + received_at: new Date(1700000000000 + sequence * 1000 + 1).toISOString(), + latitude: 37, + longitude: -122, + speed_kph: 30, + heading: 0, +}); + +describe("public Supabase configuration", () => { + const publicKey = "sb_publishable_public_key_for_tests"; + const config = ( + key = publicKey, + url = "https://example-project.supabase.co", + ) => + getSupabaseConfig({ + VITE_SUPABASE_URL: url, + VITE_SUPABASE_PUBLISHABLE_KEY: key, + }); + it("keeps cloud mode inert until real public configuration is supplied", () => { + expect(getSupabaseConfig({}).ready).toBe(false); + expect(config(publicKey, "https://your-project.supabase.co").ready).toBe( + false, + ); + expect(config().ready).toBe(true); + expect(config(publicKey, "http://127.0.0.1:54321").ready).toBe(true); + expect(config(publicKey, "http://example-project.supabase.co").ready).toBe( + false, + ); + expect( + config(publicKey, "https://user:password@example-project.supabase.co") + .ready, + ).toBe(false); + }); + it("blocks privileged keys at build time even if configuration is otherwise missing or another public key takes precedence", () => { + expect(() => + assertPublicSupabaseKeys({ + VITE_SUPABASE_PUBLISHABLE_KEY: "sb_secret_do_not_log", + }), + ).toThrow("frontend build"); + const secretJwt = `header.${btoa(JSON.stringify({ role: "service_role" }))}.signature`; + expect(() => + assertPublicSupabaseKeys({ + VITE_SUPABASE_PUBLISHABLE_KEY: publicKey, + VITE_SUPABASE_ANON_KEY: secretJwt, + }), + ).toThrow("frontend build"); + expect(() => assertPublicSupabaseKeys({})).not.toThrow(); + }); + it("rejects secret/service-role keys and accepts only legacy anon JWTs", () => { + const jwt = (role: string) => + `header.${btoa(JSON.stringify({ role })).replace(/=/g, "")}.signature`; + expect(config("sb_secret_not_for_browser").ready).toBe(false); + expect(config(jwt("service_role")).ready).toBe(false); + expect(config(jwt("authenticated")).ready).toBe(false); + expect(config(jwt("anon")).ready).toBe(true); + expect(config("malformed-token").ready).toBe(false); + expect( + getSupabaseConfig({ + VITE_SUPABASE_URL: "https://example-project.supabase.co", + VITE_SUPABASE_ANON_KEY: jwt("anon"), + }).ready, + ).toBe(true); + }); +}); + +describe("authenticated cloud repository", () => { + it("loads more than a PostgREST default page and scopes every telemetry table to the session", async () => { + const points = Array.from({ length: 1002 }, (_, i) => gps(i)); + const mock = mockClient((query) => { + if (query.table === "driving_sessions") + return { data: session, error: null }; + if (query.table === "connection_status") + return { data: null, error: null }; + const range = query.operations.find((op) => op.name === "range") + ?.args as number[]; + return { + data: + query.table === "gps_points" + ? points.slice(range[0], range[1] + 1) + : [], + error: null, + }; + }); + const snapshot = await new CloudRepository(mock.client).loadSnapshot("a"); + expect(snapshot.gps).toHaveLength(1002); + expect(snapshot.gps.at(-1)?.sequence).toBe(1001); + expect(snapshot.connection).toBeNull(); + for (const query of mock.queries.filter( + (q) => q.table !== "driving_sessions", + )) + expect(query.operations).toContainEqual({ + name: "eq", + args: ["session_id", "a"], + }); + expect(mock.queries.filter((q) => q.table === "gps_points")).toHaveLength( + 2, + ); + expect( + mock.queries.find((q) => q.table === "connection_status")?.operations, + ).toContainEqual({ + name: "order", + args: ["sequence", { ascending: false }], + }); + }); + it("preserves source-time route order under repeated/out-of-order deliveries", async () => { + const mock = mockClient((query) => ({ + data: + query.table === "driving_sessions" + ? session + : query.table === "connection_status" + ? null + : query.table === "gps_points" + ? [gps(3), gps(1), gps(2), gps(2)] + : [], + error: null, + })); + expect( + (await new CloudRepository(mock.client).loadSnapshot("a")).gps.map( + (p) => p.sequence, + ), + ).toEqual([1, 2, 3]); + }); + it("surfaces permission failures instead of returning an empty successful history", async () => { + const mock = mockClient(() => ({ + data: null, + error: { message: "permission denied" }, + })); + await expect( + new CloudRepository(mock.client).listSessions(), + ).rejects.toThrow("permission denied"); + await expect( + new CloudRepository(mock.client).loadSnapshot("a"), + ).rejects.toThrow("permission denied"); + }); + it("paginates the session list as well as telemetry records", async () => { + const sessions = Array.from({ length: 1001 }, (_, i) => ({ + ...session, + id: String(i), + })); + const mock = mockClient((query) => { + const range = query.operations.find((op) => op.name === "range")! + .args as number[]; + return { data: sessions.slice(range[0], range[1] + 1), error: null }; + }); + expect(await new CloudRepository(mock.client).listSessions()).toHaveLength( + 1001, + ); + }); + it("writes only through authenticated ingestion/sharing/threshold RPCs with session scope", async () => { + const mock = mockClient(() => ({ data: [], error: null })); + mock.rpc.mockResolvedValue({ data: "new-session" as never, error: null }); + const repository = new CloudRepository(mock.client); + expect(await repository.createSession("Test drive", "simulated")).toBe( + "new-session", + ); + await repository.ingestGps("a", [ + { + id: "gps", + sequence: 1, + recorded_at: session.started_at, + latitude: 37, + longitude: -122, + speed_kph: null, + heading: null, + }, + ]); + await repository.ingestEvents("a", []); + await repository.ingestConnection("a", { + sequence: 1, + recorded_at: session.started_at, + connected: true, + }); + await repository.setThresholds("a", [{ imu_id: 1, t1: 0.8, t2: 1.8 }]); + await repository.shareSession("a", "observer@example.com"); + await repository.revokeObserver("a", "observer"); + await repository.finishSession("a"); + expect(mock.rpc.mock.calls.map((call) => (call as unknown[])[0])).toEqual([ + "create_driving_session", + "ingest_gps", + "ingest_threshold_events", + "ingest_connection", + "set_imu_thresholds", + "share_session", + "revoke_session_observer", + "finish_driving_session", + ]); + expect(mock.rpc).toHaveBeenCalledWith("share_session", { + p_session_id: "a", + p_email: "observer@example.com", + }); + expect(mock.queries).toEqual([]); + }); + it("reloads on subscribed/reconnected notifications and removes listeners on cleanup", () => { + const handlers: Array<{ + filter: Record; + callback: () => void; + }> = []; + let statusCallback: (status: string) => void = () => {}; + const channel = { + on: vi.fn( + ( + _event: string, + filter: Record, + callback: () => void, + ) => { + handlers.push({ filter, callback }); + return channel; + }, + ), + subscribe: vi.fn((callback: (status: string) => void) => { + statusCallback = callback; + return channel; + }), + }; + const client = { + channel: vi.fn(() => channel), + removeChannel: vi.fn(async () => "ok"), + } as unknown as SupabaseClient; + const changed = vi.fn(); + const status = vi.fn(); + const stop = new CloudRepository(client).watchSession("a", changed, status); + expect(status).toHaveBeenCalledWith("connecting"); + expect(handlers).toHaveLength(5); + expect( + handlers + .filter((h) => h.filter.table !== "driving_sessions") + .every((h) => h.filter.filter === "session_id=eq.a"), + ).toBe(true); + statusCallback("SUBSCRIBED"); + handlers[0].callback(); + expect(changed).toHaveBeenCalledTimes(2); + statusCallback("CHANNEL_ERROR"); + expect(status).toHaveBeenLastCalledWith("error"); + stop(); + stop(); + handlers[0].callback(); + statusCallback("SUBSCRIBED"); + expect(changed).toHaveBeenCalledTimes(2); + expect(client.removeChannel).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/services/cloudRepository.ts b/src/services/cloudRepository.ts new file mode 100644 index 0000000..e150dc5 --- /dev/null +++ b/src/services/cloudRepository.ts @@ -0,0 +1,229 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; +import type { + CloudDataSource, + CloudSession, + CloudSnapshot, + ConnectionUpload, + EventUpload, + GpsUpload, + ImuThreshold, + SessionObserver, + GpsPoint, + CloudThresholdEvent, + CloudConnection, +} from "../domain/cloud"; +import { normalizeEvents, normalizeGps } from "../domain/cloudRecords"; + +export type RealtimeState = "connecting" | "subscribed" | "error" | "closed"; +const PAGE_SIZE = 1000; +function failure(error: { message: string } | null, operation: string): void { + if (error) throw new Error(`${operation}: ${error.message}`); +} + +/** Every request is made with the current authenticated user's JWT; RLS is authoritative. */ +export class CloudRepository { + constructor(readonly client: SupabaseClient) {} + + async listSessions(): Promise { + const rows: CloudSession[] = []; + for (let start = 0; ; start += PAGE_SIZE) { + const { data, error } = await this.client + .from("driving_sessions") + .select("*") + .order("started_at", { ascending: false }) + .order("id") + .range(start, start + PAGE_SIZE - 1); + failure(error, "Load sessions"); + rows.push(...((data ?? []) as CloudSession[])); + if ((data?.length ?? 0) < PAGE_SIZE) return rows; + } + } + private async sessionRows( + table: string, + sessionId: string, + order: string, + ): Promise { + const rows: T[] = []; + for (let start = 0; ; start += PAGE_SIZE) { + let query = this.client + .from(table) + .select("*") + .eq("session_id", sessionId) + .order(order); + if (order === "recorded_at") query = query.order("sequence"); + const { data, error } = await query.range(start, start + PAGE_SIZE - 1); + failure(error, `Load ${table}`); + rows.push(...((data ?? []) as T[])); + if ((data?.length ?? 0) < PAGE_SIZE) return rows; + } + } + async createSession(label: string, source: CloudDataSource): Promise { + const { data, error } = await this.client.rpc("create_driving_session", { + p_label: label, + p_data_source: source, + }); + failure(error, "Create session"); + if (typeof data !== "string") + throw new Error( + "Create session returned no session ID. Check the installed database migration.", + ); + return data; + } + async finishSession(sessionId: string): Promise { + const { error } = await this.client.rpc("finish_driving_session", { + p_session_id: sessionId, + }); + failure(error, "Finish session"); + } + async loadSnapshot(sessionId: string): Promise { + const [ + sessionResult, + gps, + events, + connectionResult, + thresholds, + observers, + ] = await Promise.all([ + this.client + .from("driving_sessions") + .select("*") + .eq("id", sessionId) + .single(), + this.sessionRows("gps_points", sessionId, "recorded_at"), + this.sessionRows( + "threshold_events", + sessionId, + "recorded_at", + ), + this.client + .from("connection_status") + .select("*") + .eq("session_id", sessionId) + .order("sequence", { ascending: false }) + .limit(1) + .maybeSingle(), + this.sessionRows("imu_thresholds", sessionId, "imu_id"), + this.sessionRows( + "session_observers", + sessionId, + "user_id", + ), + ]); + failure(sessionResult.error, "Load driving session"); + failure(connectionResult.error, "Load connection status"); + if (!sessionResult.data) + throw new Error("Session not found or access is no longer available."); + return { + session: sessionResult.data as CloudSession, + gps: normalizeGps(gps), + events: normalizeEvents(events), + connection: connectionResult.data as CloudConnection | null, + thresholds, + observers, + }; + } + /** Realtime notifications invalidate persisted state; reconnecting must reload the snapshot. */ + watchSession( + sessionId: string, + onChange: () => void, + onStatus: (state: RealtimeState) => void, + ): () => void { + let closed = false; + onStatus("connecting"); + const channel = this.client.channel( + `session:${sessionId}:${crypto.randomUUID()}`, + ); + const changed = () => { + if (!closed) onChange(); + }; + for (const table of [ + "gps_points", + "threshold_events", + "connection_status", + "imu_thresholds", + ]) { + channel.on( + "postgres_changes", + { + event: "*", + schema: "public", + table, + filter: `session_id=eq.${sessionId}`, + }, + changed, + ); + } + channel.on( + "postgres_changes", + { + event: "*", + schema: "public", + table: "driving_sessions", + filter: `id=eq.${sessionId}`, + }, + changed, + ); + channel.subscribe((status) => { + if (closed) return; + if (status === "SUBSCRIBED") { + onStatus("subscribed"); + onChange(); + } else if (status === "CHANNEL_ERROR" || status === "TIMED_OUT") + onStatus("error"); + else if (status === "CLOSED") onStatus("closed"); + }); + return () => { + if (closed) return; + closed = true; + void this.client.removeChannel(channel); + }; + } + async setThresholds( + sessionId: string, + thresholds: Array>, + ): Promise { + const { error } = await this.client.rpc("set_imu_thresholds", { + p_session_id: sessionId, + p_thresholds: thresholds, + }); + failure(error, "Save IMU thresholds"); + } + async shareSession(sessionId: string, email: string): Promise { + const { error } = await this.client.rpc("share_session", { + p_session_id: sessionId, + p_email: email, + }); + failure(error, "Share session"); + } + async revokeObserver(sessionId: string, userId: string): Promise { + const { error } = await this.client.rpc("revoke_session_observer", { + p_session_id: sessionId, + p_user_id: userId, + }); + failure(error, "Revoke observer"); + } + async ingestGps(sessionId: string, points: GpsUpload[]): Promise { + const { error } = await this.client.rpc("ingest_gps", { + p_session_id: sessionId, + p_points: points, + }); + failure(error, "Upload GPS"); + } + async ingestEvents(sessionId: string, events: EventUpload[]): Promise { + const { error } = await this.client.rpc("ingest_threshold_events", { + p_session_id: sessionId, + p_events: events, + }); + failure(error, "Upload threshold events"); + } + async ingestConnection( + sessionId: string, + status: ConnectionUpload, + ): Promise { + const { error } = await this.client.rpc("ingest_connection", { + p_session_id: sessionId, + p_status: status, + }); + failure(error, "Upload connection status"); + } +} diff --git a/src/services/cloudSimulator.test.ts b/src/services/cloudSimulator.test.ts new file mode 100644 index 0000000..4061e28 --- /dev/null +++ b/src/services/cloudSimulator.test.ts @@ -0,0 +1,150 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { CloudSession, ImuThreshold } from "../domain/cloud"; +import { startCloudSimulation } from "./cloudSimulator"; +const base = 1_700_000_000_000; +const session: CloudSession = { + id: "a", + owner_id: "owner", + label: "Test", + started_at: new Date(base).toISOString(), + ended_at: null, + data_source: "simulated", + created_at: new Date(base).toISOString(), +}; +const thresholds: ImuThreshold[] = ([1, 2, 3] as const).map((imu_id) => ({ + session_id: "a", + imu_id, + t1: 0.8, + t2: 1.8, + updated_at: session.started_at, +})); +const repository = () => ({ + ingestGps: vi.fn(async () => {}), + ingestEvents: vi.fn(async () => {}), + ingestConnection: vi.fn(async () => {}), +}); + +describe("cloud simulated test-drive uploader", () => { + afterEach(() => vi.useRealTimers()); + it("stores GPS at approximately one-second cadence and only sparse threshold events for all three IMUs", async () => { + vi.useFakeTimers(); + vi.setSystemTime(base); + const repo = repository(); + const failed = vi.fn(); + const stop = startCloudSimulation(repo, session, thresholds, failed); + await vi.advanceTimersByTimeAsync(30_000); + expect(repo.ingestGps).toHaveBeenCalledTimes(31); + expect(repo.ingestEvents).toHaveBeenCalledTimes(3); + expect(repo.ingestConnection).toHaveBeenCalledTimes(7); + const events = repo.ingestEvents.mock.calls.map( + (call) => (call as unknown as [string, Array<{ imu_id: number }>])[1][0], + ); + expect(new Set(events.map((event) => event.imu_id))).toEqual( + new Set([1, 2, 3]), + ); + const points = repo.ingestGps.mock.calls.map( + (call) => + ( + call as unknown as [ + string, + Array<{ sequence: number; recorded_at: string }>, + ] + )[1][0], + ); + expect( + Date.parse(points[1].recorded_at) - Date.parse(points[0].recorded_at), + ).toBe(1000); + expect(points[1].sequence).toBeGreaterThan(points[0].sequence); + expect(points.every((point) => !("acceleration" in point))).toBe(true); + expect(failed).not.toHaveBeenCalled(); + stop(); + await vi.advanceTimersByTimeAsync(5000); + expect(repo.ingestGps).toHaveBeenCalledTimes(31); + }); + it("refuses to turn an actual device session into simulated hardware data", () => { + expect(() => + startCloudSimulation( + repository(), + { ...session, data_source: "device" }, + thresholds, + vi.fn(), + ), + ).toThrow("simulated"); + expect(() => + startCloudSimulation( + repository(), + { ...session, ended_at: session.started_at }, + thresholds, + vi.fn(), + ), + ).toThrow("active"); + expect(() => + startCloudSimulation( + repository(), + session, + thresholds.slice(0, 2), + vi.fn(), + ), + ).toThrow("three IMUs"); + }); + it("retries the exact same immutable GPS packet after a transient upload error", async () => { + vi.useFakeTimers(); + vi.setSystemTime(base); + const repo = repository(); + const failed = vi.fn(); + repo.ingestGps.mockRejectedValueOnce(new Error("offline")); + const stop = startCloudSimulation(repo, session, thresholds, failed); + await vi.advanceTimersByTimeAsync(1000); + expect(failed).toHaveBeenCalledTimes(1); + expect(repo.ingestGps).toHaveBeenCalledTimes(3); + expect(repo.ingestGps.mock.calls[0]).toEqual(repo.ingestGps.mock.calls[1]); + expect(repo.ingestConnection).toHaveBeenCalledTimes(1); + stop(); + }); + it("bounds the retry queue and reports skipped new samples during a prolonged outage", async () => { + vi.useFakeTimers(); + vi.setSystemTime(base); + let online = false; + const uploaded: unknown[] = []; + const repo = repository(); + repo.ingestGps.mockImplementation(async (...args: unknown[]) => { + if (!online) throw new Error("offline"); + uploaded.push((args[1] as unknown[])[0]); + }); + const failed = vi.fn(); + const stop = startCloudSimulation(repo, session, thresholds, failed); + await vi.advanceTimersByTimeAsync(70_000); + expect( + failed.mock.calls.some(([message]) => + String(message).includes("queue is full"), + ), + ).toBe(true); + online = true; + await vi.advanceTimersByTimeAsync(1000); + expect(uploaded).toHaveLength(60); + expect( + new Set(uploaded.map((point) => (point as { id: string }).id)).size, + ).toBe(60); + stop(); + }); + it("does not overlap uploads or start remaining writes after stopping an in-flight request", async () => { + vi.useFakeTimers(); + vi.setSystemTime(base); + let resolve: () => void = () => {}; + const repo = repository(); + repo.ingestGps.mockImplementationOnce( + () => + new Promise((done) => { + resolve = done; + }), + ); + const stop = startCloudSimulation(repo, session, thresholds, vi.fn()); + await vi.advanceTimersByTimeAsync(6000); + expect(repo.ingestGps).toHaveBeenCalledTimes(1); + stop(); + resolve(); + await vi.advanceTimersByTimeAsync(1000); + expect(repo.ingestGps).toHaveBeenCalledTimes(1); + expect(repo.ingestConnection).not.toHaveBeenCalled(); + }); +}); diff --git a/src/services/cloudSimulator.ts b/src/services/cloudSimulator.ts new file mode 100644 index 0000000..c45db2d --- /dev/null +++ b/src/services/cloudSimulator.ts @@ -0,0 +1,148 @@ +import type { + CloudSession, + ImuThreshold, + GpsUpload, + EventUpload, + ConnectionUpload, + ImuId, +} from "../domain/cloud"; +import type { CloudRepository } from "./cloudRepository"; +import { getSimulatedSample } from "./telemetry"; + +type UploadRepository = Pick< + CloudRepository, + "ingestGps" | "ingestEvents" | "ingestConnection" +>; +type Pending = { + gps: GpsUpload; + event: EventUpload | null; + connection: ConnectionUpload | null; +}; + +/** + * A labeled cloud test-drive uploader, not the driver phone application. + * Immutable packet IDs/sequences survive retries; writes are serialized and bounded. + */ +export function startCloudSimulation( + repository: UploadRepository, + session: CloudSession, + thresholds: ImuThreshold[], + onError: (message: string) => void, +): () => void { + if (session.data_source !== "simulated" || session.ended_at !== null) + throw new Error( + "Cloud test drives require an active session labeled simulated.", + ); + if ( + thresholds.length !== 3 || + new Set(thresholds.map((t) => t.imu_id)).size !== 3 || + thresholds.some( + (t) => + t.session_id !== session.id || + ![1, 2, 3].includes(t.imu_id) || + !Number.isFinite(t.t1) || + !Number.isFinite(t.t2) || + t.t1 <= 0 || + t.t2 <= t.t1 || + t.t2 > 10, + ) + ) + throw new Error( + "Configure valid thresholds for all three IMUs before starting the cloud test drive.", + ); + const startedAt = Date.now(); + const baseSequence = startedAt; + const queue: Pending[] = []; + let tick = 0; + let stopped = false; + let writing = false; + let overflowReported = false; + async function flush() { + if (writing || stopped) return; + writing = true; + try { + while (!stopped && queue.length) { + const packet = queue[0]; + await repository.ingestGps(session.id, [packet.gps]); + if (stopped) break; + if (packet.event) + await repository.ingestEvents(session.id, [packet.event]); + if (stopped) break; + if (packet.connection) + await repository.ingestConnection(session.id, packet.connection); + if (stopped) break; + queue.shift(); + } + } catch { + // Never print request details or configuration. Keep the head packet for an idempotent retry. + if (!stopped) + onError( + "Cloud test-drive upload failed. Pending packets will retry while the test drive is running.", + ); + } finally { + writing = false; + } + } + function enqueue() { + if (stopped) return; + if (queue.length >= 60) { + if (!overflowReported) + onError( + "The cloud test-drive queue is full. New GPS samples are being skipped until uploads recover; no continuous IMU data is buffered.", + ); + overflowReported = true; + void flush(); + return; + } + overflowReported = false; + const now = Date.now(); + const sample = getSimulatedSample(now - startedAt, startedAt); + const sequence = baseSequence + tick; + const recorded_at = new Date(now).toISOString(); + const imu = ((Math.floor(tick / 10) % 3) + 1) as ImuId; + const threshold = thresholds.find((t) => t.imu_id === imu)!; + const severity = Math.floor(tick / 10) % 2 === 0 ? "warning" : "critical"; + queue.push({ + gps: { + id: crypto.randomUUID(), + sequence, + recorded_at, + ...sample.position, + speed_kph: sample.speedKph, + heading: sample.heading, + }, + event: + tick > 0 && tick % 10 === 0 + ? { + id: crypto.randomUUID(), + sequence, + recorded_at, + imu_id: imu, + severity, + magnitude: + severity === "warning" + ? (threshold.t1 + threshold.t2) / 2 + : threshold.t2 + 0.25, + latitude: sample.position.latitude, + longitude: sample.position.longitude, + t1: threshold.t1, + t2: threshold.t2, + } + : null, + connection: + tick % 5 === 0 ? { sequence, recorded_at, connected: true } : null, + }); + tick += 1; + void flush(); + } + enqueue(); + const timer = setInterval(enqueue, 1000); + return () => { + if (stopped) return; + stopped = true; + clearInterval(timer); + queue.length = 0; + // Do not fabricate a gateway disconnection on stop: an already-started request + // may finish, but no further writes are initiated. Its heartbeat ages to stale. + }; +} diff --git a/src/services/supabase.ts b/src/services/supabase.ts new file mode 100644 index 0000000..dfe8abd --- /dev/null +++ b/src/services/supabase.ts @@ -0,0 +1,42 @@ +import { createClient, type SupabaseClient } from "@supabase/supabase-js"; +import { + getSupabaseConfig as parseSupabaseConfig, + type BuildEnvironment, +} from "./supabaseConfig"; +export { + assertPublicSupabaseEnvironment, + assertPublicSupabaseEnvironment as assertPublicSupabaseKeys, +} from "./supabaseConfig"; +export type { SupabaseConfig } from "./supabaseConfig"; + +/** Explicit property references prevent Vite from inlining unrelated VITE_* values. */ +export function getSupabaseConfig(env?: BuildEnvironment) { + return parseSupabaseConfig( + env ?? { + VITE_SUPABASE_URL: (import.meta as ImportMeta & { env: BuildEnvironment }) + .env.VITE_SUPABASE_URL, + VITE_SUPABASE_PUBLISHABLE_KEY: ( + import.meta as ImportMeta & { env: BuildEnvironment } + ).env.VITE_SUPABASE_PUBLISHABLE_KEY, + VITE_SUPABASE_ANON_KEY: ( + import.meta as ImportMeta & { env: BuildEnvironment } + ).env.VITE_SUPABASE_ANON_KEY, + }, + ); +} + +let client: SupabaseClient | null = null; +/** Deliberately lazy: selecting local simulation never creates a cloud connection. */ +export function getSupabaseClient(): SupabaseClient | null { + const config = getSupabaseConfig(); + if (!config.ready) return null; + client ??= createClient(config.url, config.key, { + auth: { + persistSession: true, + autoRefreshToken: true, + detectSessionInUrl: true, + flowType: "pkce", + }, + }); + return client; +} diff --git a/src/services/supabaseConfig.ts b/src/services/supabaseConfig.ts new file mode 100644 index 0000000..fcf5a48 --- /dev/null +++ b/src/services/supabaseConfig.ts @@ -0,0 +1,106 @@ +export type BuildEnvironment = Record; +export type SupabaseConfig = + { ready: true; url: string; key: string } | { ready: false; message: string }; + +/** Build-time and runtime guard. The error never contains a key value. */ +export function assertPublicSupabaseEnvironment(env: BuildEnvironment): void { + for (const name of [ + "VITE_SUPABASE_PUBLISHABLE_KEY", + "VITE_SUPABASE_ANON_KEY", + ]) { + const key = env[name]?.trim(); + if (!key) continue; + if (key.startsWith("sb_secret_")) + throw new Error( + "Privileged Supabase keys cannot be included in a frontend build. Use a publishable or anon key.", + ); + if (key.split(".").length === 3) { + let role: unknown; + try { + role = JSON.parse( + atob(key.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")), + ).role; + } catch { + /* Normal validation reports malformed public configuration. */ + } + if (role !== undefined && role !== "anon") + throw new Error( + "Privileged or user-specific Supabase JWTs cannot be included in a frontend build. Use a publishable or anon key.", + ); + } + } +} + +/** Public project configuration only. A service-role/secret key must never enter a browser build. */ +export function getSupabaseConfig(env: BuildEnvironment): SupabaseConfig { + try { + assertPublicSupabaseEnvironment(env); + } catch { + return { + ready: false, + message: + "Privileged Supabase keys are forbidden in frontend configuration. Use the project publishable key.", + }; + } + const url = env.VITE_SUPABASE_URL?.trim(); + const key = ( + env.VITE_SUPABASE_PUBLISHABLE_KEY || env.VITE_SUPABASE_ANON_KEY + )?.trim(); + if ( + !url || + !key || + /your[-_ ]|placeholder|replace[-_ ]|[<>]/i.test(`${url} ${key}`) + ) { + return { + ready: false, + message: + "Cloud mode needs VITE_SUPABASE_URL and VITE_SUPABASE_PUBLISHABLE_KEY in .env.local. Local simulation is available without them.", + }; + } + try { + const parsed = new URL(url); + const local = ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname); + if ( + (parsed.protocol !== "https:" && + !(local && parsed.protocol === "http:")) || + parsed.username || + parsed.password || + parsed.search || + parsed.hash || + (parsed.pathname !== "/" && parsed.pathname !== "") + ) + throw new Error(); + } catch { + return { + ready: false, + message: + "Use a valid HTTPS Supabase project URL (HTTP is supported only for local development).", + }; + } + if (key.startsWith("sb_secret_")) + return { + ready: false, + message: + "Privileged Supabase keys are forbidden in frontend configuration. Use the project publishable key.", + }; + if (!key.startsWith("sb_publishable_")) { + try { + const payload = JSON.parse( + atob(key.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")), + ) as { role?: string }; + if (payload.role !== "anon") + return { + ready: false, + message: + "Use a publishable key or the legacy anon key. Service-role keys must never be exposed in frontend code.", + }; + } catch { + return { + ready: false, + message: + "The configured key must be a Supabase publishable key or a legacy anon JWT.", + }; + } + } + return { ready: true, url: url.replace(/\/$/, ""), key }; +} diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/supabase/README.md b/supabase/README.md new file mode 100644 index 0000000..6abfb9a --- /dev/null +++ b/supabase/README.md @@ -0,0 +1,17 @@ +# Database contract + +Apply `migrations/20261021000100_msd_cloud.sql` once in a Supabase project's SQL editor, or with `supabase db push` after linking the CLI. The project must have its standard `auth.users`, `auth.uid()`, `anon`, and `authenticated` objects. No seed creates real accounts or bypasses authentication. + +All six tables enable row-level security. Authenticated owners and explicitly shared observers can read a session's records. Observers cannot mutate data. Owners write through narrow, authenticated RPCs; direct table INSERT/UPDATE/DELETE is denied, including changing session ownership or provenance. Sharing requires an already registered, email-confirmed observer. Only the owner can grant or revoke access. + +The authenticated RPC routes are `create_driving_session`, `finish_driving_session`, `ingest_gps`, `ingest_threshold_events`, `ingest_connection`, `set_imu_thresholds`, `share_session`, and `revoke_session_observer`. Helpers used internally are not exposed to authenticated callers except the boolean read-policy helper. + +Each GPS/event packet supplies a client UUID, session-scoped monotonic `sequence`, source `recorded_at`, and its sensor fields. Connection packets are append-only with session/sequence identity. Retries and conflicting duplicate IDs/sequences use **first-write wins** and cannot replace a previously accepted row. Sequence allocation must survive uploader retries/restarts within a session. Upload batches are atomic and limited to 100 GPS/event records. Query historical GPS by source time, with sequence as a stable tie-breaker; query latest connection by highest sequence. Delivery order and `received_at` must never determine the live vehicle position. + +A source timestamp must be finite, on/after session start, at most 60 seconds into the future, and on/before a closed session's end. Delayed upload after closing is allowed for packets recorded during that session. Owner session-row locks serialize ingestion, configuration, and closing. Closing preserves the latest already accepted source timestamp if it was within the permitted +60s clock tolerance. All receipt times are assigned by PostgreSQL. Current freshness must be judged using source time (plus explicit connection state), so a newly received old packet does not look live. + +Exactly three IMUs (IDs 1, 2, 3) have configurable `0 < T1 < T2 ≤ 10 g` thresholds. Every threshold event snapshots T1/T2. An optional peak must agree with `T1 ≤ A ≤ T2` for warning or `A > T2` for critical. GPS and peak values may remain null. Threshold settings do not retroactively reclassify events and are cloud configuration, not proof of firmware configuration delivery. No raw continuous IMU table exists. + +The migration registers the five session/telemetry/configuration tables in `supabase_realtime`. Membership is deliberately not published because Supabase DELETE notifications cannot enforce row policies and could expose its `(session_id, user_id)` key. Realtime uses the authenticated user's SELECT policies. In addition to change subscriptions, observers must refetch on reconnect and periodically recheck access. In particular, revoking membership cannot remove data that a browser already downloaded, but subsequent authorized queries must return no session data. + +`src/domain/database.test.ts` executes this exact migration with PostgreSQL in PGlite. Its auth schema/user fixtures and role impersonation exist only in the test and are never deployed. diff --git a/supabase/migrations/20261021000100_msd_cloud.sql b/supabase/migrations/20261021000100_msd_cloud.sql new file mode 100644 index 0000000..7a003e1 --- /dev/null +++ b/supabase/migrations/20261021000100_msd_cloud.sql @@ -0,0 +1,272 @@ +-- MSD Stage 2: authenticated, owner-controlled ingestion and shared read-only observation. +-- No raw continuous IMU samples are stored here; the ESP32 retains those locally. + +create table public.driving_sessions ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references auth.users(id), + label text not null check (char_length(trim(label)) between 1 and 120), + started_at timestamptz not null default now(), + ended_at timestamptz, + data_source text not null check (data_source in ('simulated', 'device')), + created_at timestamptz not null default now(), + check (isfinite(started_at) and (ended_at is null or (isfinite(ended_at) and ended_at >= started_at))) +); + +create table public.session_observers ( + session_id uuid not null references public.driving_sessions(id) on delete cascade, + user_id uuid not null references auth.users(id) on delete cascade, + created_at timestamptz not null default now(), + primary key (session_id, user_id) +); + +create table public.gps_points ( + id uuid primary key, + session_id uuid not null references public.driving_sessions(id) on delete cascade, + sequence bigint not null check (sequence between 0 and 9007199254740991), + recorded_at timestamptz not null check (isfinite(recorded_at)), + received_at timestamptz not null default now(), + latitude double precision not null check (latitude between -90 and 90), + longitude double precision not null check (longitude between -180 and 180), + speed_kph double precision check (speed_kph >= 0 and speed_kph < 'Infinity'::double precision), + heading double precision check (heading >= 0 and heading < 360), + unique (session_id, sequence) +); + +create table public.threshold_events ( + id uuid primary key, + session_id uuid not null references public.driving_sessions(id) on delete cascade, + sequence bigint not null check (sequence between 0 and 9007199254740991), + imu_id smallint not null check (imu_id between 1 and 3), + recorded_at timestamptz not null check (isfinite(recorded_at)), + received_at timestamptz not null default now(), + severity text not null check (severity in ('warning', 'critical')), + magnitude double precision check (magnitude >= 0 and magnitude < 'Infinity'::double precision), + latitude double precision check (latitude between -90 and 90), + longitude double precision check (longitude between -180 and 180), + t1 double precision not null check (t1 > 0), + t2 double precision not null check (t2 > t1 and t2 <= 10), + check ((latitude is null) = (longitude is null)), + -- Snapshot thresholds are part of the event, never reclassified on a later settings edit. + check (magnitude is null or + (severity = 'warning' and magnitude >= t1 and magnitude <= t2) or + (severity = 'critical' and magnitude > t2)), + unique (session_id, sequence) +); + +create table public.connection_status ( + session_id uuid not null references public.driving_sessions(id) on delete cascade, + sequence bigint not null check (sequence between 0 and 9007199254740991), + recorded_at timestamptz not null check (isfinite(recorded_at)), + received_at timestamptz not null default now(), + connected boolean not null, + primary key (session_id, sequence) +); + +create table public.imu_thresholds ( + session_id uuid not null references public.driving_sessions(id) on delete cascade, + imu_id smallint not null check (imu_id between 1 and 3), + t1 double precision not null check (t1 > 0), + t2 double precision not null check (t2 > t1 and t2 <= 10), + updated_at timestamptz not null default now(), + primary key (session_id, imu_id) +); + +create index driving_sessions_owner_time on public.driving_sessions(owner_id, started_at desc); +create index session_observers_user on public.session_observers(user_id, session_id); +create index gps_points_session_time on public.gps_points(session_id, recorded_at, sequence); +create index threshold_events_session_time on public.threshold_events(session_id, recorded_at, sequence); +create index connection_status_session_sequence on public.connection_status(session_id, sequence desc); + +-- These narrow helpers run under their fixed owner with an empty search path to avoid +-- recursive membership policies and malicious schema/function substitution. +create function public.can_read_session(p_session_id uuid) +returns boolean language sql stable security definer set search_path = '' as $$ + select auth.uid() is not null and ( + exists(select 1 from public.driving_sessions s where s.id = p_session_id and s.owner_id = auth.uid()) + or exists(select 1 from public.session_observers o where o.session_id = p_session_id and o.user_id = auth.uid()) + ); +$$; + +create function public.require_owned_session(p_session_id uuid) +returns public.driving_sessions language plpgsql security definer set search_path = '' as $$ +declare v_session public.driving_sessions; +begin + select * into v_session from public.driving_sessions where id = p_session_id and owner_id = auth.uid() for update; + if not found then raise exception 'Session not owned by authenticated user' using errcode = '42501'; end if; + return v_session; +end; +$$; + +create function public.validate_telemetry_time(p_session public.driving_sessions, p_recorded_at timestamptz) +returns void language plpgsql stable security definer set search_path = '' as $$ +begin + if p_recorded_at is null or not isfinite(p_recorded_at) + or p_recorded_at < p_session.started_at + or p_recorded_at > now() + interval '60 seconds' + or (p_session.ended_at is not null and p_recorded_at > p_session.ended_at) then + raise exception 'Telemetry timestamp is outside the session bounds' using errcode = '22023'; + end if; +end; +$$; + +alter table public.driving_sessions enable row level security; +alter table public.session_observers enable row level security; +alter table public.gps_points enable row level security; +alter table public.threshold_events enable row level security; +alter table public.connection_status enable row level security; +alter table public.imu_thresholds enable row level security; + +create policy session_read on public.driving_sessions for select to authenticated using (public.can_read_session(id)); +create policy observer_read on public.session_observers for select to authenticated using (public.can_read_session(session_id)); +create policy gps_read on public.gps_points for select to authenticated using (public.can_read_session(session_id)); +create policy event_read on public.threshold_events for select to authenticated using (public.can_read_session(session_id)); +create policy connection_read on public.connection_status for select to authenticated using (public.can_read_session(session_id)); +create policy thresholds_read on public.imu_thresholds for select to authenticated using (public.can_read_session(session_id)); + +revoke all on public.driving_sessions, public.session_observers, public.gps_points, public.threshold_events, public.connection_status, public.imu_thresholds from anon, authenticated; +grant select on public.driving_sessions, public.session_observers, public.gps_points, public.threshold_events, public.connection_status, public.imu_thresholds to authenticated; + +create function public.create_driving_session(p_label text, p_data_source text) +returns uuid language plpgsql security definer set search_path = '' as $$ +declare v_id uuid; +begin + if auth.uid() is null then raise exception 'Authentication required' using errcode = '42501'; end if; + insert into public.driving_sessions(owner_id, label, data_source) + values (auth.uid(), trim(p_label), p_data_source) returning id into v_id; + insert into public.imu_thresholds(session_id, imu_id, t1, t2) + select v_id, n, 0.8, 1.8 from generate_series(1, 3) n; + return v_id; +end; +$$; + +create function public.finish_driving_session(p_session_id uuid) +returns void language plpgsql security definer set search_path = '' as $$ +begin + perform public.require_owned_session(p_session_id); + -- The owner-row lock serializes finishing with ingestion. Preserve already accepted + -- source records even when the phone clock was within the allowed +60s tolerance. + update public.driving_sessions set ended_at = greatest(now(), + (select max(recorded_at) from public.gps_points where session_id = p_session_id), + (select max(recorded_at) from public.threshold_events where session_id = p_session_id), + (select max(recorded_at) from public.connection_status where session_id = p_session_id)) + where id = p_session_id and ended_at is null; +end; +$$; + +create function public.ingest_gps(p_session_id uuid, p_points jsonb) +returns void language plpgsql security definer set search_path = '' as $$ +declare v_session public.driving_sessions; v_point jsonb; v_time timestamptz; +begin + v_session := public.require_owned_session(p_session_id); + if jsonb_typeof(p_points) is distinct from 'array' or jsonb_array_length(p_points) not between 1 and 100 then + raise exception 'GPS batch must contain 1 to 100 points' using errcode = '22023'; + end if; + for v_point in select value from jsonb_array_elements(p_points) loop + v_time := (v_point->>'recorded_at')::timestamptz; + perform public.validate_telemetry_time(v_session, v_time); + insert into public.gps_points(id, session_id, sequence, recorded_at, latitude, longitude, speed_kph, heading) + values ((v_point->>'id')::uuid, p_session_id, (v_point->>'sequence')::bigint, v_time, + (v_point->>'latitude')::double precision, (v_point->>'longitude')::double precision, + (v_point->>'speed_kph')::double precision, (v_point->>'heading')::double precision) + on conflict do nothing; + end loop; +end; +$$; + +create function public.ingest_threshold_events(p_session_id uuid, p_events jsonb) +returns void language plpgsql security definer set search_path = '' as $$ +declare v_session public.driving_sessions; v_event jsonb; v_time timestamptz; +begin + v_session := public.require_owned_session(p_session_id); + if jsonb_typeof(p_events) is distinct from 'array' or jsonb_array_length(p_events) not between 1 and 100 then + raise exception 'Event batch must contain 1 to 100 events' using errcode = '22023'; + end if; + for v_event in select value from jsonb_array_elements(p_events) loop + v_time := (v_event->>'recorded_at')::timestamptz; + perform public.validate_telemetry_time(v_session, v_time); + insert into public.threshold_events(id, session_id, sequence, imu_id, recorded_at, severity, magnitude, latitude, longitude, t1, t2) + values ((v_event->>'id')::uuid, p_session_id, (v_event->>'sequence')::bigint, (v_event->>'imu_id')::smallint, + v_time, v_event->>'severity', (v_event->>'magnitude')::double precision, + (v_event->>'latitude')::double precision, (v_event->>'longitude')::double precision, + (v_event->>'t1')::double precision, (v_event->>'t2')::double precision) + on conflict do nothing; + end loop; +end; +$$; + +create function public.ingest_connection(p_session_id uuid, p_status jsonb) +returns void language plpgsql security definer set search_path = '' as $$ +declare v_session public.driving_sessions; v_time timestamptz; +begin + v_session := public.require_owned_session(p_session_id); + if jsonb_typeof(p_status) is distinct from 'object' then + raise exception 'Connection packet must be an object' using errcode = '22023'; + end if; + v_time := (p_status->>'recorded_at')::timestamptz; + perform public.validate_telemetry_time(v_session, v_time); + insert into public.connection_status(session_id, sequence, recorded_at, connected) + values (p_session_id, (p_status->>'sequence')::bigint, v_time, (p_status->>'connected')::boolean) + on conflict do nothing; +end; +$$; + +create function public.set_imu_thresholds(p_session_id uuid, p_thresholds jsonb) +returns void language plpgsql security definer set search_path = '' as $$ +declare v_session public.driving_sessions; v_threshold jsonb; +begin + v_session := public.require_owned_session(p_session_id); + if v_session.ended_at is not null then raise exception 'Session is already finished' using errcode = '22023'; end if; + if jsonb_typeof(p_thresholds) is distinct from 'array' or jsonb_array_length(p_thresholds) <> 3 then + raise exception 'Exactly three IMU thresholds are required' using errcode = '22023'; + end if; + if (select count(distinct (value->>'imu_id')::smallint) from jsonb_array_elements(p_thresholds)) <> 3 then + raise exception 'IMU identifiers must be unique' using errcode = '22023'; + end if; + for v_threshold in select value from jsonb_array_elements(p_thresholds) loop + insert into public.imu_thresholds(session_id, imu_id, t1, t2) + values(p_session_id, (v_threshold->>'imu_id')::smallint, (v_threshold->>'t1')::double precision, (v_threshold->>'t2')::double precision) + on conflict(session_id, imu_id) do update set t1 = excluded.t1, t2 = excluded.t2, updated_at = now(); + end loop; +end; +$$; + +create function public.share_session(p_session_id uuid, p_email text) +returns void language plpgsql security definer set search_path = '' as $$ +declare v_user uuid; +begin + perform public.require_owned_session(p_session_id); + select id into v_user from auth.users where lower(email) = lower(trim(p_email)) and email_confirmed_at is not null; + if v_user is null then raise exception 'Observer must first register and confirm their email' using errcode = '22023'; end if; + insert into public.session_observers(session_id, user_id) values (p_session_id, v_user) on conflict do nothing; +end; +$$; + +create function public.revoke_session_observer(p_session_id uuid, p_user_id uuid) +returns void language plpgsql security definer set search_path = '' as $$ +begin + perform public.require_owned_session(p_session_id); + delete from public.session_observers where session_id = p_session_id and user_id = p_user_id; +end; +$$; + +-- Supabase exposes SQL functions as RPC routes: PUBLIC must not retain default execute. +revoke all on function public.can_read_session(uuid), public.require_owned_session(uuid), public.validate_telemetry_time(public.driving_sessions,timestamptz), public.create_driving_session(text,text), public.finish_driving_session(uuid), public.ingest_gps(uuid,jsonb), public.ingest_threshold_events(uuid,jsonb), public.ingest_connection(uuid,jsonb), public.set_imu_thresholds(uuid,jsonb), public.share_session(uuid,text), public.revoke_session_observer(uuid,uuid) from public, anon, authenticated; +grant execute on function public.can_read_session(uuid), public.create_driving_session(text,text), public.finish_driving_session(uuid), public.ingest_gps(uuid,jsonb), public.ingest_threshold_events(uuid,jsonb), public.ingest_connection(uuid,jsonb), public.set_imu_thresholds(uuid,jsonb), public.share_session(uuid,text), public.revoke_session_observer(uuid,uuid) to authenticated; + +-- Realtime INSERT/UPDATE delivery uses the authenticated observer SELECT policies. +-- Membership is intentionally not published: Supabase DELETE notifications cannot +-- apply row-level checks and would expose its composite (session,user) primary key. +-- Shared-data clients recheck membership on reconnect and periodic authorized fetches. +do $$ +declare v_table text; +begin + if not exists (select 1 from pg_publication where pubname = 'supabase_realtime') then + create publication supabase_realtime; + end if; + foreach v_table in array array['driving_sessions','gps_points','threshold_events','connection_status','imu_thresholds'] loop + if not exists (select 1 from pg_publication_tables where pubname = 'supabase_realtime' and schemaname = 'public' and tablename = v_table) then + execute format('alter publication supabase_realtime add table public.%I', v_table); + end if; + end loop; +end; +$$; diff --git a/tests/cloud.spec.ts b/tests/cloud.spec.ts new file mode 100644 index 0000000..1bf81a8 --- /dev/null +++ b/tests/cloud.spec.ts @@ -0,0 +1,402 @@ +import { expect, test, type Page } from "@playwright/test"; +import { CloudFixture, SESSION_ID } from "./helpers/cloudFixture"; + +async function signIn( + page: Page, + email = "owner@example.test", + password = "fixture-password", +) { + await page.goto("/"); + await page + .getByRole("combobox", { name: "Telemetry source" }) + .selectOption("cloud"); + await expect( + page.getByRole("heading", { name: "Cloud session monitor" }), + ).toBeVisible(); + await page.getByLabel("Email address", { exact: true }).fill(email); + await page.getByLabel("Password", { exact: true }).fill(password); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); +} + +async function expectSession(page: Page) { + await expect( + page.getByRole("combobox", { name: "Cloud driving session" }), + ).toHaveValue(SESSION_ID); + await expect( + page.getByRole("heading", { name: "Live GPS route", exact: true }), + ).toBeVisible(); +} + +test("cloud sign-in loads persisted route, event locations, and three unknown IMUs without fabricating samples", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + await signIn(page); + await expectSession(page); + await expect(page.locator(".vehicle-map__coordinates")).toContainText( + "37.77910", + ); + for (const imu of [1, 2, 3]) { + const card = page.getByLabel(`IMU ${imu} event status`, { exact: true }); + await expect(card).toBeVisible(); + await expect(card).toContainText(/unknown|unavailable/i); + } + await expect(page.locator(".axis-reading")).toHaveCount(0); + await expect(page.locator(".sparkline")).toHaveCount(0); + await expect(page.locator(".traffic-light .green.lit")).toHaveCount(0); + await page.getByRole("button", { name: "Cloud events", exact: true }).click(); + const table = page.getByRole("table"); + await expect(table).toContainText("IMU 2"); + await expect(table).toContainText(/high impact|critical/i); + await expect(table).toContainText("37.7791"); + await expect( + page.getByText("SIMULATED CLOUD DATA", { exact: true }), + ).toBeVisible(); + expect(errors).toEqual([]); +}); + +test("failed credentials expose an error and sign-out clears the cloud session", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + await signIn(page, "owner@example.test", "wrong-password"); + await expect(page.getByRole("alert")).toContainText(/invalid login/i); + await expect( + page.getByRole("combobox", { name: "Cloud driving session" }), + ).toHaveCount(0); + await page.getByLabel("Password", { exact: true }).fill("fixture-password"); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + await expectSession(page); + await page.getByRole("button", { name: "Sign out", exact: true }).click(); + await expect(page.getByLabel("Email address", { exact: true })).toBeVisible(); + await expect( + page.getByRole("combobox", { name: "Cloud driving session" }), + ).toHaveCount(0); + await expect(page.locator(".vehicle-map")).toHaveCount(0); + await expect( + page.getByText("Shared test drive", { exact: true }), + ).toHaveCount(0); +}); + +test("realtime updates reach two authorized observers and source-time ordering survives duplicates and delayed uploads", async ({ + page, + context, + browser, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + await signIn(page); + await expectSession(page); + const observerContext = await browser.newContext({ + baseURL: "http://127.0.0.1:5175", + }); + await backend.install(observerContext); + const observer = await observerContext.newPage(); + try { + await signIn(observer, "observer@example.test"); + await expectSession(observer); + await expect.poll(() => backend.socketCount).toBeGreaterThanOrEqual(2); + const newest = backend.point(3, 37.7788, -122.4186); + backend.addGps(newest); + for (const target of [page, observer]) + await expect(target.locator(".vehicle-map__coordinates")).toContainText( + "37.77880", + ); + backend.addGps({ + ...backend.point( + 4, + 37.78, + -122.42, + new Date(Date.now() - 30_000).toISOString(), + ), + received_at: new Date().toISOString(), + }); + backend.addGps({ ...newest }); + const event = { + ...backend.events[0], + id: "40000000-0000-4000-8000-000000000002", + sequence: 2, + imu_id: 3 as const, + recorded_at: new Date().toISOString(), + received_at: new Date().toISOString(), + magnitude: 1.8, + severity: "warning" as const, + }; + backend.addEvent(event); + backend.addEvent({ ...event }); + for (const target of [page, observer]) { + await expect(target.locator(".vehicle-map__coordinates")).toContainText( + "37.77880", + ); + await target + .getByRole("button", { name: "Cloud events", exact: true }) + .click(); + const rows = target.getByRole("table").getByRole("row"); + await expect(rows).toHaveCount(3); // Header + two unique events. + await expect(target.getByRole("table")).toContainText("IMU 3"); + } + // A new page load rehydrates the persisted API state rather than generating demo history. + await page.reload(); + await page + .getByRole("combobox", { name: "Telemetry source" }) + .selectOption("cloud"); + await expectSession(page); + await page + .getByRole("button", { name: "Cloud events", exact: true }) + .click(); + await expect(page.getByRole("table").getByRole("row")).toHaveCount(3); + } finally { + await observerContext.close(); + } +}); + +test("read-only observers cannot start uploads or save session configuration", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + await signIn(page, "observer@example.test"); + await expectSession(page); + for (const label of [ + "Start cloud test drive", + "Save cloud thresholds", + "Share session", + ]) { + const button = page.getByRole("button", { name: label, exact: true }); + if (await button.count()) await expect(button).toBeDisabled(); + } + await expect(page.getByText(/read.only observer/i).first()).toBeVisible(); + expect( + backend.requests.filter( + (request) => request.path.includes("/rpc/") && request.method === "POST", + ), + ).toHaveLength(0); +}); + +test("the cloud test drive uploads one-second GPS fixtures only to a simulated session", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + await signIn(page); + await expectSession(page); + await page + .getByRole("button", { name: "Start cloud test drive", exact: true }) + .click(); + await expect + .poll( + () => + backend.requests.filter((request) => + request.path.endsWith("/rpc/ingest_gps"), + ).length, + { timeout: 10_000 }, + ) + .toBeGreaterThanOrEqual(3); + await page + .getByRole("button", { name: "Stop cloud test drive", exact: true }) + .click(); + const uploaded = backend.requests.filter((request) => + request.path.endsWith("/rpc/ingest_gps"), + ); + const points = uploaded.flatMap( + (request) => + (request.body as { p_points: Array<{ recorded_at: string }> }).p_points, + ); + expect(points.length).toBeGreaterThanOrEqual(3); + const interval = + Date.parse(points[1].recorded_at) - Date.parse(points[0].recorded_at); + expect(interval).toBeGreaterThanOrEqual(800); + expect(interval).toBeLessThan(2500); + expect( + backend.requests.some((request) => + request.path.endsWith("/rpc/ingest_connection"), + ), + ).toBe(true); + const countAtStop = uploaded.length; + await page.waitForTimeout(1300); + expect( + backend.requests.filter((request) => + request.path.endsWith("/rpc/ingest_gps"), + ), + ).toHaveLength(countAtStop); + await expect( + page.getByRole("button", { name: "Start cloud test drive", exact: true }), + ).toBeVisible(); +}); + +test("local and cloud modes remain separate and cloud layout fits a phone", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + await signIn(page); + await expectSession(page); + await page.setViewportSize({ width: 390, height: 844 }); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + ).toBe(true); + const source = page.getByRole("combobox", { name: "Telemetry source" }); + await source.selectOption("simulation"); + await expect( + page.getByRole("heading", { name: "All systems normal" }), + ).toBeVisible(); + await expect(page.locator(".axis-reading")).toHaveCount(3); + await source.selectOption("cloud"); + await expectSession(page); + await expect(page.locator(".axis-reading")).toHaveCount(0); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + ).toBe(true); +}); + +test("owners configure all three IMUs and grant observer access without rewriting historical thresholds", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + await backend.install(context); + await signIn(page); + await expectSession(page); + for (const imu of [1, 2, 3]) { + await page + .getByLabel(`IMU ${imu} T1`, { exact: true }) + .fill(String(imu / 10 + 0.5)); + await page + .getByLabel(`IMU ${imu} T2`, { exact: true }) + .fill(String(imu / 10 + 2)); + } + await page + .getByRole("button", { name: "Save cloud thresholds", exact: true }) + .click(); + await expect + .poll( + () => + backend.requests.filter((request) => + request.path.endsWith("/rpc/set_imu_thresholds"), + ).length, + ) + .toBe(1); + expect( + backend.thresholds.map(({ imu_id, t1, t2 }) => ({ imu_id, t1, t2 })), + ).toEqual([ + { imu_id: 1, t1: 0.6, t2: 2.1 }, + { imu_id: 2, t1: 0.7, t2: 2.2 }, + { imu_id: 3, t1: 0.8, t2: 2.3 }, + ]); + expect(backend.events[0]).toMatchObject({ + t1: 0.8, + t2: 1.8, + severity: "critical", + }); + await page + .getByLabel("Existing account email", { exact: true }) + .fill("observer@example.test"); + await page + .getByRole("button", { name: "Share session", exact: true }) + .click(); + await expect + .poll( + () => + backend.requests.filter((request) => + request.path.endsWith("/rpc/share_session"), + ).length, + ) + .toBe(1); + expect( + backend.requests.find((request) => + request.path.endsWith("/rpc/share_session"), + )?.body, + ).toMatchObject({ + p_session_id: SESSION_ID, + p_email: "observer@example.test", + }); +}); + +test("device sessions never offer generated cloud uploads, and failed reads do not fall back to local telemetry", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + backend.sessions[0].data_source = "device"; + await backend.install(context); + await signIn(page); + await expectSession(page); + await expect( + page.getByText("DEVICE TELEMETRY", { exact: true }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "Start cloud test drive", exact: true }), + ).toHaveCount(0); + await expect(page.locator(".axis-reading")).toHaveCount(0); + backend.failSnapshots = true; + await page + .getByRole("button", { name: "Refresh records", exact: true }) + .click(); + await expect(page.getByRole("alert")).toContainText(/unavailable/i); + await expect(page.locator(".vehicle-map")).toHaveCount(0); + await expect( + page.getByRole("heading", { name: "Cloud session monitor" }), + ).toBeVisible(); + await expect(page.locator(".axis-reading")).toHaveCount(0); + await expect(page.locator(".traffic-light .green.lit")).toHaveCount(0); +}); + +test("recent cloud delivery of old GPS and heartbeat records stays historical and never confirms current IMU motion", async ({ + page, + context, +}) => { + const backend = new CloudFixture(); + const oldSourceTime = new Date(Date.now() - 30_000).toISOString(); + for (const point of backend.gps) { + point.recorded_at = oldSourceTime; + point.received_at = new Date().toISOString(); + } + backend.connections[0].recorded_at = oldSourceTime; + backend.connections[0].received_at = new Date().toISOString(); + await backend.install(context); + await signIn(page); + await expectSession(page); + await expect(page.locator(".cloud-sync")).toHaveText("Realtime connected"); + const gpsStatus = page.getByRole("article").filter({ + has: page.getByText("GPS availability", { exact: true }), + }); + await expect(gpsStatus.locator(".stat-value")).toHaveText("Historical"); + const gatewayStatus = page.getByRole("article").filter({ + has: page.getByText("Gateway availability", { exact: true }), + }); + await expect(gatewayStatus.locator(".stat-value")).toHaveText("Stale"); + await expect(page.locator(".vehicle-map__coordinates")).toHaveText( + "Awaiting GPS data", + ); + const marker = page.locator(".msd-vehicle-icon"); + await expect + .poll(() => + marker.evaluateAll((markers) => + markers.every((element) => getComputedStyle(element).opacity === "0"), + ), + ) + .toBe(true); + await expect( + page.getByText("2 GPS fixes · 1 event locations", { exact: true }), + ).toBeVisible(); + for (const imu of [1, 2, 3]) { + await expect( + page.getByLabel(`IMU ${imu} event status`, { exact: true }), + ).toContainText("Current: Unknown"); + } + await expect(page.locator(".axis-reading")).toHaveCount(0); + await expect(page.locator(".traffic-light .green.lit")).toHaveCount(0); +}); diff --git a/tests/helpers/cloudFixture.ts b/tests/helpers/cloudFixture.ts new file mode 100644 index 0000000..9facd2f --- /dev/null +++ b/tests/helpers/cloudFixture.ts @@ -0,0 +1,536 @@ +import type { BrowserContext, WebSocketRoute } from "@playwright/test"; +import type { + CloudConnection, + CloudSession, + CloudThresholdEvent, + GpsPoint, + ImuThreshold, + SessionObserver, +} from "../../src/domain/cloud"; + +// An in-process test double for the public Supabase API. No test credential is +// trusted by a real project, and this module is never imported by the app. +export const OWNER_ID = "10000000-0000-4000-8000-000000000001"; +export const OBSERVER_ID = "10000000-0000-4000-8000-000000000002"; +export const SESSION_ID = "20000000-0000-4000-8000-000000000001"; +const now = () => new Date().toISOString(); +function token(id: string) { + const encode = (value: object) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + return `${encode({ alg: "HS256", typ: "JWT" })}.${encode({ sub: id, role: "authenticated", exp: Math.floor(Date.now() / 1000) + 3600 })}.browser-test-signature`; +} +function user(id: string) { + return { + id, + aud: "authenticated", + role: "authenticated", + email: id === OBSERVER_ID ? "observer@example.test" : "owner@example.test", + email_confirmed_at: now(), + created_at: now(), + app_metadata: { provider: "email", providers: ["email"] }, + user_metadata: {}, + identities: [], + }; +} +function userFromAuthorization(header: string | undefined) { + try { + return JSON.parse( + Buffer.from( + (header ?? "").replace(/^Bearer /, "").split(".")[1], + "base64url", + ).toString(), + ).sub as string; + } catch { + return null; + } +} +type Binding = { + id: number; + event: string; + schema: string; + table: string; + filter?: string; +}; +type Socket = { + route: WebSocketRoute; + topic: string; + joinRef: string | null; + bindings: Binding[]; +}; +export class CloudFixture { + readonly sessions: CloudSession[]; + readonly gps: GpsPoint[]; + readonly events: CloudThresholdEvent[]; + readonly connections: CloudConnection[]; + readonly thresholds: ImuThreshold[]; + readonly observers: SessionObserver[]; + readonly requests: Array<{ + path: string; + method: string; + body: unknown; + userId: string | null; + }> = []; + private sockets = new Set(); + failSnapshots = false; + + constructor() { + const timestamp = now(); + this.sessions = [ + { + id: SESSION_ID, + owner_id: OWNER_ID, + label: "Shared test drive", + started_at: new Date(Date.now() - 60_000).toISOString(), + ended_at: null, + data_source: "simulated", + created_at: timestamp, + }, + ]; + this.gps = [ + this.point(1, 37.7793, -122.4193), + this.point(2, 37.7791, -122.419), + ]; + this.events = [ + { + id: "40000000-0000-4000-8000-000000000001", + session_id: SESSION_ID, + sequence: 1, + imu_id: 2, + recorded_at: timestamp, + received_at: timestamp, + severity: "critical", + magnitude: 2.14, + latitude: 37.7791, + longitude: -122.419, + t1: 0.8, + t2: 1.8, + }, + ]; + this.connections = [ + { + session_id: SESSION_ID, + sequence: 1, + recorded_at: timestamp, + received_at: timestamp, + connected: true, + }, + ]; + this.thresholds = ([1, 2, 3] as const).map((imu_id) => ({ + session_id: SESSION_ID, + imu_id, + t1: 0.8, + t2: 1.8, + updated_at: timestamp, + })); + this.observers = [ + { session_id: SESSION_ID, user_id: OBSERVER_ID, created_at: timestamp }, + ]; + } + point( + sequence: number, + latitude: number, + longitude: number, + recordedAt = now(), + ): GpsPoint { + return { + id: `30000000-0000-4000-8000-${String(sequence).padStart(12, "0")}`, + session_id: SESSION_ID, + sequence, + recorded_at: recordedAt, + received_at: now(), + latitude, + longitude, + speed_kph: 32, + heading: 130, + }; + } + canRead(id: string | null, sessionId: string) { + return ( + !!id && + (this.sessions.some( + (session) => session.id === sessionId && session.owner_id === id, + ) || + this.observers.some( + (observer) => + observer.session_id === sessionId && observer.user_id === id, + )) + ); + } + emit(table: string, record: Record) { + for (const socket of this.sockets) { + const ids = socket.bindings + .filter( + (binding) => + binding.table === table && + (!binding.filter || + binding.filter.endsWith(`.${record.session_id ?? record.id}`)), + ) + .map((binding) => binding.id); + if (!ids.length) continue; + try { + socket.route.send( + JSON.stringify([ + socket.joinRef, + null, + socket.topic, + "postgres_changes", + { + ids, + data: { + schema: "public", + table, + type: "INSERT", + commit_timestamp: now(), + columns: [], + record, + old_record: {}, + errors: null, + }, + }, + ]), + ); + } catch { + this.sockets.delete(socket); + } + } + } + addGps(point: GpsPoint) { + this.gps.push(point); + this.emit("gps_points", point as unknown as Record); + } + addEvent(event: CloudThresholdEvent) { + this.events.push(event); + this.emit("threshold_events", event as unknown as Record); + } + get socketCount() { + return this.sockets.size; + } + + async install(context: BrowserContext) { + await context.route("https://msd-test.supabase.co/**", async (route) => { + const request = route.request(); + const url = new URL(request.url()); + const id = userFromAuthorization(request.headers().authorization); + let body: Record = {}; + try { + body = request.postDataJSON() ?? {}; + } catch { + /* GET and empty POST */ + } + this.requests.push({ + path: url.pathname, + method: request.method(), + body, + userId: id, + }); + const respond = (payload: unknown, status = 200) => + route.fulfill({ + status, + contentType: "application/json", + headers: { + "access-control-allow-origin": "*", + "access-control-allow-headers": "*", + "access-control-expose-headers": "content-range", + "content-range": "0-0/*", + }, + body: JSON.stringify(payload), + }); + if (request.method() === "OPTIONS") return respond(null, 200); + if (url.pathname === "/auth/v1/token") { + if (String(body.password).startsWith("wrong")) + return respond( + { + error: "invalid_grant", + error_description: "Invalid login credentials", + msg: "Invalid login credentials", + }, + 400, + ); + const actor = + body.email === "observer@example.test" ? OBSERVER_ID : OWNER_ID; + return respond({ + access_token: token(actor), + token_type: "bearer", + expires_in: 3600, + expires_at: Math.floor(Date.now() / 1000) + 3600, + refresh_token: `fixture-refresh-${actor}`, + user: user(actor), + }); + } + if (url.pathname === "/auth/v1/user") + return id + ? respond(user(id)) + : respond({ msg: "Not authenticated" }, 401); + if (url.pathname === "/auth/v1/signup") + return respond({ user: user(OWNER_ID), session: null }); + if (url.pathname === "/auth/v1/logout") return respond(null); + if (!id) + return respond( + { message: "Authentication required", code: "42501" }, + 401, + ); + if (url.pathname.startsWith("/rest/v1/rpc/")) { + const rpc = url.pathname.split("/").at(-1); + if (rpc === "create_driving_session") { + const sessionId = crypto.randomUUID(); + const timestamp = now(); + this.sessions.push({ + id: sessionId, + owner_id: id, + label: String(body.p_label), + started_at: timestamp, + ended_at: null, + data_source: + body.p_data_source === "device" ? "device" : "simulated", + created_at: timestamp, + }); + for (const imu_id of [1, 2, 3] as const) + this.thresholds.push({ + session_id: sessionId, + imu_id, + t1: 0.8, + t2: 1.8, + updated_at: timestamp, + }); + return respond(sessionId); + } + const sessionId = String(body.p_session_id); + const session = this.sessions.find((item) => item.id === sessionId); + if (session?.owner_id !== id) + return respond( + { message: "Only the session owner may write", code: "42501" }, + 403, + ); + if (rpc === "finish_driving_session") { + session.ended_at ??= now(); + this.emit( + "driving_sessions", + session as unknown as Record, + ); + } + if (rpc === "ingest_gps") + for (const point of body.p_points as Omit< + GpsPoint, + "session_id" | "received_at" + >[]) { + if ( + this.gps.some( + (old) => + old.id === point.id || + (old.session_id === sessionId && + old.sequence === point.sequence), + ) + ) + continue; + this.addGps({ + ...point, + session_id: sessionId, + received_at: now(), + }); + } + if (rpc === "ingest_threshold_events") + for (const event of body.p_events as Omit< + CloudThresholdEvent, + "session_id" | "received_at" + >[]) { + if ( + this.events.some( + (old) => + old.id === event.id || + (old.session_id === sessionId && + old.sequence === event.sequence), + ) + ) + continue; + this.addEvent({ + ...event, + session_id: sessionId, + received_at: now(), + }); + } + if (rpc === "ingest_connection") { + const status = { + ...(body.p_status as Omit< + CloudConnection, + "session_id" | "received_at" + >), + session_id: sessionId, + received_at: now(), + }; + this.connections.push(status); + this.emit("connection_status", status); + } + if (rpc === "set_imu_thresholds") + for (const value of body.p_thresholds as Array<{ + imu_id: number; + t1: number; + t2: number; + }>) { + const threshold = this.thresholds.find( + (old) => + old.session_id === sessionId && old.imu_id === value.imu_id, + ); + if (threshold) { + Object.assign(threshold, value, { updated_at: now() }); + this.emit( + "imu_thresholds", + threshold as unknown as Record, + ); + } + } + if (rpc === "share_session") { + if ( + !this.observers.some( + (observer) => + observer.session_id === sessionId && + observer.user_id === OBSERVER_ID, + ) + ) + this.observers.push({ + session_id: sessionId, + user_id: OBSERVER_ID, + created_at: now(), + }); + } + if (rpc === "revoke_session_observer") { + const index = this.observers.findIndex( + (observer) => + observer.session_id === sessionId && + observer.user_id === body.p_user_id, + ); + if (index >= 0) this.observers.splice(index, 1); + } + return respond(null); + } + // Use a terminal access failure here: PostgREST intentionally retries 503, + // which would test SDK backoff rather than the dashboard's failed-read path. + if (this.failSnapshots) + return respond({ message: "Fixture session access unavailable" }, 403); + const table = url.pathname.split("/").at(-1); + const sessionFilter = url.searchParams + .get("session_id") + ?.replace(/^eq\./, ""); + const idFilter = url.searchParams.get("id")?.replace(/^eq\./, ""); + let rows: unknown[] = []; + if (table === "driving_sessions") + rows = this.sessions.filter( + (row) => + this.canRead(id, row.id) && (!idFilter || row.id === idFilter), + ); + if (table === "gps_points") + rows = this.gps.filter( + (row) => + this.canRead(id, row.session_id) && + (!sessionFilter || row.session_id === sessionFilter), + ); + if (table === "threshold_events") + rows = this.events.filter( + (row) => + this.canRead(id, row.session_id) && + (!sessionFilter || row.session_id === sessionFilter), + ); + if (table === "connection_status") + rows = this.connections + .filter( + (row) => + this.canRead(id, row.session_id) && + (!sessionFilter || row.session_id === sessionFilter), + ) + .sort((a, b) => b.sequence - a.sequence); + if (table === "imu_thresholds") + rows = this.thresholds.filter( + (row) => + this.canRead(id, row.session_id) && + (!sessionFilter || row.session_id === sessionFilter), + ); + if (table === "session_observers") + rows = this.observers.filter( + (row) => + this.canRead(id, row.session_id) && + (!sessionFilter || row.session_id === sessionFilter), + ); + const offset = Number(url.searchParams.get("offset") ?? "0"); + const limit = Number(url.searchParams.get("limit") ?? rows.length); + rows = rows.slice(offset, offset + limit); + if ( + request.headers().accept?.includes("application/vnd.pgrst.object+json") + ) + return rows.length === 1 + ? respond(rows[0]) + : respond({ message: "No rows found", code: "PGRST116" }, 406); + return respond(rows); + }); + await context.routeWebSocket( + "wss://msd-test.supabase.co/realtime/v1/**", + (route) => { + const socket: Socket = { + route, + topic: "", + joinRef: null, + bindings: [], + }; + route.onMessage((raw) => { + const parsed = JSON.parse(String(raw)); + const arrayProtocol = Array.isArray(parsed); + const [joinRef, ref, topic, event, payload] = arrayProtocol + ? parsed + : [ + parsed.join_ref, + parsed.ref, + parsed.topic, + parsed.event, + parsed.payload, + ]; + if (event === "phx_join") { + socket.topic = topic; + socket.joinRef = joinRef; + socket.bindings = (payload.config?.postgres_changes ?? []).map( + (binding: Binding, index: number) => ({ + ...binding, + id: index + 1, + }), + ); + this.sockets.add(socket); + const reply = { + status: "ok", + response: { postgres_changes: socket.bindings }, + }; + route.send( + JSON.stringify( + arrayProtocol + ? [joinRef, ref, topic, "phx_reply", reply] + : { + join_ref: joinRef, + ref, + topic, + event: "phx_reply", + payload: reply, + }, + ), + ); + } else if (event === "heartbeat" || event === "phx_leave") { + const reply = { status: "ok", response: {} }; + route.send( + JSON.stringify( + arrayProtocol + ? [joinRef, ref, topic, "phx_reply", reply] + : { + join_ref: joinRef, + ref, + topic, + event: "phx_reply", + payload: reply, + }, + ), + ); + if (event === "phx_leave") this.sockets.delete(socket); + } + }); + route.onClose(() => this.sockets.delete(socket)); + }, + ); + await context.route(/https:\/\/tile\.openstreetmap\.org\//, (route) => + route.abort(), + ); + } +} diff --git a/vite.config.ts b/vite.config.ts index bd72786..b949bb2 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,7 +1,12 @@ import { defineConfig } from "vitest/config"; +import { loadEnv } from "vite"; +import { assertPublicSupabaseEnvironment } from "./src/services/supabaseConfig"; import react from "@vitejs/plugin-react"; -export default defineConfig({ - plugins: [react()], - test: { include: ["src/**/*.test.ts"] }, +export default defineConfig(({ mode }) => { + assertPublicSupabaseEnvironment(loadEnv(mode, process.cwd(), "VITE_")); + return { + plugins: [react()], + test: { include: ["src/**/*.test.{ts,tsx}"] }, + }; });