diff --git a/docs/data-sharing-webhooks.md b/docs/data-sharing-webhooks.md new file mode 100644 index 00000000..aa108149 --- /dev/null +++ b/docs/data-sharing-webhooks.md @@ -0,0 +1,206 @@ +# Data sharing webhooks + +Phoenix Portal can push a user's own training data to an HTTPS endpoint the +user controls. This page is for whoever builds the **receiver**, and for +operators. For the rules the code must keep, see `CLAUDE.md` → "Data sharing +(outbound webhooks)". + +- Available on **Flame and above**. Set up in the portal under + **Profile → Settings → Data Sharing**. +- Up to **3 endpoints** per account. Each endpoint chooses which kinds of + data it receives. +- Only the account owner can configure it, and an endpoint only ever receives + its owner's data. + +## Requirements for an endpoint + +| | | +|---|---| +| Scheme | `https` only, with a certificate a normal client would trust | +| Host | A public DNS name or public IP. Private, loopback, link-local and reserved addresses are refused, when the endpoint is saved and again before every delivery | +| Port | 443, or 1024–65535 | +| Credentials | Not in the URL. Use the signature, or the optional custom header | +| Redirects | Never followed. A `3xx` answer is a failed delivery | +| Timeout | 10 seconds | +| Success | Any `2xx` status. The response body is ignored and never stored | + +## The request + +Every delivery is a `POST` with a JSON body and these headers: + +| Header | Value | +|---|---| +| `content-type` | `application/json` | +| `user-agent` | `PhoenixPortal-Webhooks/1.0` | +| `webhook-id` | The delivery id. **The same on every retry** of that delivery: use it to deduplicate | +| `webhook-timestamp` | Unix seconds when this attempt was signed | +| `webhook-signature` | One or more space-separated `v1,` signatures | +| *(your custom header)* | Only if you configured one, e.g. `Authorization` | + +Body: + +```json +{ + "type": "workout.updated", + "timestamp": "2026-11-06T12:00:00.000Z", + "data": { + "apiVersion": "2026-11-01", + "endpointId": "…", + "entity": "workout", + "id": "…", + "loadConvention": "per_cable_kg", + "record": { "id": "…", "name": "…", "started_at": "…", "total_volume": 1200 }, + "children": { + "exercises": [{ "id": "…", "session_id": "…", "name": "Row", "cable_count": 2 }], + "sets": [{ "id": "…", "exercise_id": "…", "set_number": 1, "weight_kg": 40, "actual_reps": 8 }], + "rep_summaries": [{ "id": "…", "set_id": "…", "rep_number": 1 }] + } + } +} +``` + +A deletion carries the id and nothing else: + +```json +{ + "type": "routine.deleted", + "timestamp": "2026-11-06T12:05:00.000Z", + "data": { "apiVersion": "2026-11-01", "endpointId": "…", "entity": "routine", "id": "…" } +} +``` + +### Loads are per cable + +Every weight and volume is **per cable**, exactly as the phone shows it and as +it is stored. Nothing is doubled. `exercises.cable_count` is `1`, `2` or +`null`; `null` means the machine did not report it, so do not assume two. + +## Verifying a delivery + +Signatures follow the [Standard Webhooks](https://www.standardwebhooks.com) +format, so an existing library will verify them. With the reference Node +library: + +```js +import { Webhook } from "standardwebhooks"; + +const webhook = new Webhook(process.env.PHOENIX_SIGNING_SECRET); // "whsec_…" + +export async function handler(request) { + const body = await request.text(); // the raw body, before any JSON parsing + let event; + try { + event = webhook.verify(body, { + "webhook-id": request.headers.get("webhook-id"), + "webhook-timestamp": request.headers.get("webhook-timestamp"), + "webhook-signature": request.headers.get("webhook-signature"), + }); + } catch { + return new Response("invalid signature", { status: 401 }); + } + // event.type, event.data … + return new Response(null, { status: 204 }); +} +``` + +By hand: + +1. The signed content is `{webhook-id}.{webhook-timestamp}.{raw body}`. +2. The key is the **base64-decoded** bytes after the `whsec_` prefix (not the + text of the secret). +3. Compute HMAC-SHA256 and base64-encode it. Accept the delivery if it equals + the value after `v1,` in **any** entry of `webhook-signature`, compared in + constant time. +4. Reject a `webhook-timestamp` more than a few minutes from your clock, to + stop replays. + +Verify against the raw bytes you received. Re-serialising the JSON first +changes the bytes and the signature will not match. + +### The custom header + +For receivers that cannot verify a signature (some no-code tools), an endpoint +can carry one extra header, for example `Authorization: Bearer …`. It is sent +on every delivery and stored encrypted. It proves the caller knows the value; +unlike the signature it does not protect the body from being altered, so +prefer the signature where you can. + +### Replacing the secret + +"Replace secret" creates a new secret and shows it once. For the next +**24 hours** each delivery carries two signatures, new secret first, so a +receiver holding either secret keeps verifying. After that only the new one is +used. + +## Events + +`.updated` is sent when an item is created or changed and carries its +current state. `.deleted` is sent when it is removed. `ping` is the +test delivery from the portal's "Send test" button. + +| Scope (chosen per endpoint) | Entity | `record` is a row of | `children` | +|---|---|---|---| +| Workouts | `workout` | `workout_sessions` | `exercises`, `sets`, `rep_summaries` | +| Personal records | `personal_record` | `personal_records` | — | +| Routines | `routine` | `routines` | `routine_exercises` | +| Training cycles | `cycle` | `training_cycles` | `cycle_days` | +| Goals | `goal` | `user_goals` | — | +| Exercise progress | `exercise_progress` | `exercise_progress` | — | +| Achievements | `badge`, `gamification_stats`, `rpg_attributes` | `earned_badges`, `gamification_stats`, `rpg_attributes` | — | +| Imported activities | `external_activity` | `external_activities` (never Strava-sourced rows) | — | +| Profile | `profile`, `local_profile` | `profiles`, `local_profiles` | — | + +Field names are the database column names, the same ones the "Download All My +Data" export uses. The account's internal user id is not included. + +**Never sent this way:** raw force-curve telemetry, the Inferno biomechanics +tables, activities imported from Strava, community content, billing data, or +anything belonging to another user. + +## Delivery behaviour + +- **At least once.** A delivery can arrive more than once (a retry after your + `2xx` was lost, or "Resend all"). Deduplicate on `webhook-id`, or simply + upsert by `data.id`. +- **Current state, not a change log.** The payload is built when it is sent. + Several quick edits to one item arrive as one delivery with the final state; + an item edited and then deleted arrives as a deletion. +- **No ordering guarantee** between items. Because each delivery carries the + current state, applying them in any order converges. +- **Timing.** Changes are picked up within about a minute, after a 20-second + settle delay. +- **Retries.** Any answer other than `2xx`, a timeout or a connection failure + is retried after about 1 min, 5 min, 15 min, 1 h, 3 h, 6 h, 12 h and 24 h + (nine attempts over roughly two days). `429` and `503` honour `Retry-After` + up to one hour. +- **Switched off automatically.** If a delivery uses up all its attempts, or + the endpoint answers `410 Gone`, the endpoint is switched off and the portal + says why. Switching it back on sends one test delivery first and only + succeeds if that is accepted. +- **Paused with the plan.** If the account drops below Flame the endpoint is + paused and nothing is sent until the plan returns and the owner switches it + back on. +- **Size.** A payload over 1 MB is not sent and is shown as "too large" in the + delivery log. +- **Resend all** queues one delivery for every existing item in the endpoint's + selected data. Use it to load history into a new receiver. + +The portal keeps a 30-day delivery log per endpoint: status, attempt count, +HTTP status and a fixed reason code. It never records your endpoint's response +body. + +## Security notes for operators + +- The only code that fetches a user-chosen URL is + `supabase/functions/_shared/webhookTarget.ts`. Its header documents one + **residual risk that is not closed**: the runtime cannot pin a connection to + the address it validated, so DNS rebinding can still aim a request at an + internal address. It is bounded by https with certificate validation, by the + request carrying no Supabase credential, by redirects not being followed, and + by nothing of the response being kept beyond its status code. +- Signing secrets and custom header values are encrypted with + `OAUTH_TOKEN_ENCRYPTION_KEY` in `webhook_endpoint_secrets`, which no browser + role can read. Rotating that key without re-encrypting makes every endpoint + fail with `internal_error` until its secret is replaced. +- Operating steps (switching deliveries on and off, reading the queue) are in + `docs/runbooks/operations.md` → "Data Sharing Webhooks". diff --git a/docs/edge-functions-security-audit.md b/docs/edge-functions-security-audit.md index c29fe91c..e0048898 100644 --- a/docs/edge-functions-security-audit.md +++ b/docs/edge-functions-security-audit.md @@ -368,6 +368,29 @@ try { --- +## Addendum: functions added after this audit + +> **Added 2026-11-06. Not part of the 2026-03-28 audit.** The functions below +> did not exist when this report was written and were not reviewed by its +> auditor. This is a pointer to where their security model is stated, not a +> finding. + +#### `webhook-endpoints` and `deliver-webhooks` (data sharing) + +| Topic | Where it is decided | +| --- | --- | +| Authentication | `webhook-endpoints`: gateway JWT plus `auth.getUser()`; the user id comes only from the token. `deliver-webhooks`: `x-cron-secret` or service-role bearer, stated above its `verify_jwt = false` block in `supabase/config.toml` | +| User isolation | Every query carries the JWT user id (`webhook-endpoints/index.ts`). Payload reads use the claimed delivery's owner id (`_shared/webhookPayload.ts`). A composite foreign key ties each delivery to its endpoint's owner (`20261106120000`) | +| Tier | FLAME in `requireSubscription`, and again in SQL when deliveries are claimed | +| Secrets | Generated server-side, returned once, AES-GCM at rest in a table no browser role can read (`webhook_endpoint_secrets`) | +| Outbound requests (SSRF) | `_shared/webhookTarget.ts` is the only code that fetches a user-chosen URL. **Its header states a residual risk that is not closed:** DNS rebinding, bounded but not eliminated | +| Rate limiting | General key, plus a tighter key for the actions that contact a user-chosen host | + +Tests that fail if these break are named in `CLAUDE.md` under "Data sharing +(outbound webhooks)" and in `docs/data-sharing-webhooks.md`. + +--- + ## Recommendations Summary ### High Priority (Address Soon) diff --git a/docs/runbooks/operations.md b/docs/runbooks/operations.md index c4a3820a..76e0a11d 100644 --- a/docs/runbooks/operations.md +++ b/docs/runbooks/operations.md @@ -1737,6 +1737,89 @@ no reopen path, because auto-reopening would let a records edit un-achieve a goal. --- +## 15. Data Sharing Webhooks + +A Flame+ user's own data is pushed to endpoints they register (Profile > +Settings > Data Sharing). Receiver-facing behaviour is in +[`docs/data-sharing-webhooks.md`](../data-sharing-webhooks.md). + +### Switch deliveries on, and the kill switch + +The `deliver-webhooks` pg_cron job is **created inactive**. Activate it only +after the `deliver-webhooks` Edge Function is deployed: + +```sql +SELECT cron.alter_job( + (SELECT jobid FROM cron.job WHERE jobname = 'deliver-webhooks'), + active := true); +``` + +Setting `active := false` stops every delivery for every user. Changes keep +being captured (one waiting row per item, so the queue does not grow without +bound) and are sent when the job is switched back on. Nothing is lost by +pausing. + +It uses the same Vault secret (`edge_cron_secret`) and Edge secret +(`CRON_SECRET`) as the other cron-invoked functions; there is nothing extra to +set. + +### Is it working? + +```sql +-- The worker's own responses: 200 = a pass ran; 401 = the Vault secret and +-- CRON_SECRET differ; 404 = the function is not deployed. +SELECT id, status_code, timed_out, error_msg, created +FROM net._http_response ORDER BY created DESC LIMIT 20; + +-- Queue depth and what is failing. +SELECT status, last_error_code, count(*) +FROM public.webhook_deliveries +WHERE created_at > now() - interval '24 hours' +GROUP BY 1, 2 ORDER BY 3 DESC; + +-- Endpoints that are not active, and why. +SELECT status, disabled_reason, count(*) +FROM public.webhook_endpoints GROUP BY 1, 2; +``` + +| `last_error_code` | Meaning | +| --- | --- | +| `http_error`, `timeout`, `connection_failed`, `dns_failed`, `redirect_not_followed` | The receiver's side. Retried on the backoff schedule. | +| `target_not_allowed` | The stored URL now resolves to a private or reserved address, or is one of our own hosts. Not sent. | +| `internal_error` | Ours: the endpoint's secret could not be read or decrypted, or a payload read failed. Check `OAUTH_TOKEN_ENCRYPTION_KEY` and the function logs (`[DELIVER_WEBHOOKS]`). | +| `subscription_lapsed` | The owner dropped below Flame; the endpoint was paused. Expected. | +| `superseded`, `scope_removed`, `endpoint_inactive`, `not_shareable` | Closed without sending, by design. | + +A row stuck in `delivering` is a worker that died mid-send; it is reclaimed +after its 3-minute lease with no action needed. + +### A user reports an endpoint "switched itself off" + +`webhook_endpoints.disabled_reason` says why: `too_many_failures` (a delivery +used all nine attempts), `endpoint_gone` (the receiver answered 410), or +`subscription_lapsed`. The user switches it back on in the portal, which sends +one test delivery first. Do not set `status = 'active'` by hand: the table +requires `disabled_reason` to be cleared in the same statement, and skipping +the test delivery hides the fault that switched it off. + +### Stop one user's sharing immediately + +```sql +UPDATE public.webhook_endpoints +SET status = 'paused', disabled_reason = 'user_paused' +WHERE user_id = '' AND status = 'active'; +``` + +Account deletion removes endpoints, secrets and the delivery log by cascade. + +### What must never be logged or pasted into a ticket + +An endpoint's URL path or query (it may itself be a credential), a signing +secret, a custom header value, or a payload. The functions log ids, status +codes and fixed reason codes only. + +--- + ## Related Runbooks - [Billing Incident Response](billing-incident-response.md) -- manual fixes, diff --git a/e2e/data-sharing.spec.ts b/e2e/data-sharing.spec.ts new file mode 100644 index 00000000..ac81a427 --- /dev/null +++ b/e2e/data-sharing.spec.ts @@ -0,0 +1,100 @@ +import { expect, test } from "@playwright/test"; +import { mockAuthenticatedApp } from "./support/mockSupabase"; + +const USER_ID = "00000000-0000-4000-8000-000000000001"; + +function endpoint(overrides: Record = {}) { + return { + id: "endpoint-existing", + user_id: USER_ID, + label: "Home server", + url: "https://hooks.example.com/in", + scopes: ["workouts", "routines"], + status: "active", + disabled_reason: null, + custom_header_name: null, + signing_key_hint: "abcd", + consecutive_failures: 0, + last_success_at: null, + last_failure_at: null, + created_at: "2026-11-01T12:00:00.000Z", + updated_at: "2026-11-01T12:00:00.000Z", + ...overrides, + }; +} + +test.describe("Data sharing", () => { + test("a Flame user adds an endpoint, sees the secret once, tests it and deletes it", async ({ + page, + }) => { + await mockAuthenticatedApp(page, { tier: "FLAME" }); + await page.goto("/profile?tab=settings"); + + const section = page.getByTestId("data-sharing"); + await expect(section.getByText(/No endpoints yet/)).toBeVisible(); + + await section.getByRole("button", { name: "Add endpoint" }).click(); + const form = page.getByRole("dialog"); + await form.getByLabel("Name", { exact: true }).fill("Home server"); + await form.getByLabel("Endpoint URL").fill("https://hooks.example.com/in"); + await form.getByRole("switch", { name: "Workouts" }).click(); + await form.getByRole("button", { name: "Add endpoint" }).click(); + + // The secret is shown once, then cannot be found anywhere on the page. + const secret = page.getByTestId("signing-secret"); + await expect(secret).toContainText("whsec_"); + await page.getByRole("button", { name: "I have saved it" }).click(); + await expect(secret).toHaveCount(0); + await expect(page.getByText(/whsec_/)).toHaveCount(0); + + await expect(section.getByText("Home server")).toBeVisible(); + await expect(section.getByText("Active", { exact: true })).toBeVisible(); + + await section.getByRole("button", { name: "Send test" }).click(); + await expect( + section.getByText("The receiver accepted the test delivery (200)."), + ).toBeVisible(); + await section.getByRole("button", { name: "Recent deliveries" }).click(); + await expect(section.getByText("Delivered", { exact: true })).toBeVisible(); + + await section.getByRole("button", { name: "Delete", exact: true }).click(); + await page + .getByRole("alertdialog") + .getByRole("button", { name: "Delete endpoint" }) + .click(); + await expect(section.getByText(/No endpoints yet/)).toBeVisible(); + }); + + test("a user below Flame can pause and delete an endpoint but not add or edit one", async ({ + page, + }) => { + await mockAuthenticatedApp(page, { + tier: "EMBER", + webhookEndpoints: [endpoint()], + }); + await page.goto("/profile?tab=settings"); + + const section = page.getByTestId("data-sharing"); + await expect(section.getByText("Home server")).toBeVisible(); + await expect(section.getByTestId("data-sharing-upgrade")).toContainText( + "Data sharing is part of Flame.", + ); + await expect( + section.getByRole("button", { name: "Add endpoint" }), + ).toBeDisabled(); + await expect( + section.getByRole("button", { name: "Edit", exact: true }), + ).toBeDisabled(); + await expect( + section.getByRole("button", { name: "Send test" }), + ).toBeDisabled(); + + await section.getByRole("button", { name: "Pause", exact: true }).click(); + await expect(section.getByText("Paused", { exact: true })).toBeVisible(); + await expect(section.getByText("You paused this endpoint.")).toBeVisible(); + // Switching it back on needs the plan. + await expect( + section.getByRole("button", { name: "Switch on" }), + ).toBeDisabled(); + }); +}); diff --git a/e2e/support/mockSupabase.ts b/e2e/support/mockSupabase.ts index 944dc6f6..9c969c40 100644 --- a/e2e/support/mockSupabase.ts +++ b/e2e/support/mockSupabase.ts @@ -108,6 +108,8 @@ interface MockSupabaseOptions { personalRecords?: Record[]; phaseStatistics?: Record[]; exerciseProgress?: Record[]; + /** Data sharing endpoints the user already has (webhook_endpoints rows). */ + webhookEndpoints?: Record[]; } const MONTHLY_PRICE_IDS: Record = { @@ -168,6 +170,8 @@ export async function installMockSupabase( personalRecords: options.personalRecords ?? [], phaseStatistics: options.phaseStatistics ?? [], exerciseProgress: options.exerciseProgress ?? [], + webhookEndpoints: options.webhookEndpoints ?? [], + webhookDeliveries: [] as Record[], onboarding: { id: "onboarding-1", user_id: userId, @@ -624,6 +628,138 @@ export async function installMockSupabase( return; } + // Data sharing: the one write path for webhook endpoints. Mirrors the + // Edge Function's contract closely enough for the UI: the tier gate + // (402 below FLAME, except delete and a pause-only update), the + // one-time secret, and a test delivery written to the log. + if (functionName === "webhook-endpoints") { + const respond = (status: number, payload: unknown) => + route.fulfill({ + status, + contentType: "application/json", + body: JSON.stringify(payload), + }); + const pauseOnly = + body.action === "update" && + body.status === "paused" && + Object.keys(body).every((key) => + ["action", "endpointId", "status"].includes(key), + ); + const tier = state.subscription?.tier ?? "FREE"; + const flame = tier === "FLAME" || tier === "INFERNO"; + if (body.action !== "delete" && !pauseOnly && !flame) { + await respond(402, { + error: "subscription_required", + message: "This feature requires FLAME.", + requiredTier: "FLAME", + currentTier: tier, + }); + return; + } + const timestamp = new Date().toISOString(); + + if (body.action === "create") { + if (!String(body.url).startsWith("https://")) { + await respond(400, { + error: "url_not_https", + message: "The URL must start with https://.", + }); + return; + } + const created = { + id: nextId("endpoint"), + user_id: userId, + label: body.label, + url: body.url, + scopes: body.scopes, + status: "active", + disabled_reason: null, + custom_header_name: body.customHeader?.name ?? null, + signing_key_hint: "e2e1", + consecutive_failures: 0, + last_success_at: null, + last_failure_at: null, + created_at: timestamp, + updated_at: timestamp, + }; + state.webhookEndpoints.push(created); + await respond(201, { + endpoint: created, + signingSecret: "whsec_e2e-test-only-shown-once-1", + }); + return; + } + + const endpoint = state.webhookEndpoints.find( + (row) => row.id === body.endpointId, + ); + if (!endpoint) { + await respond(404, { + error: "endpoint_not_found", + message: "Endpoint not found.", + }); + return; + } + if (body.action === "delete") { + state.webhookEndpoints = state.webhookEndpoints.filter( + (row) => row.id !== body.endpointId, + ); + await respond(200, { deleted: true }); + return; + } + if (body.action === "update") { + if (body.label !== undefined) endpoint.label = body.label; + if (body.url !== undefined) endpoint.url = body.url; + if (body.scopes !== undefined) endpoint.scopes = body.scopes; + if (body.status === "paused" && endpoint.status === "active") { + endpoint.status = "paused"; + endpoint.disabled_reason = "user_paused"; + } + if (body.status === "active") { + endpoint.status = "active"; + endpoint.disabled_reason = null; + } + endpoint.updated_at = timestamp; + await respond(200, { endpoint }); + return; + } + if (body.action === "test") { + state.webhookDeliveries.unshift({ + id: nextId("delivery"), + endpoint_id: endpoint.id, + user_id: userId, + entity: "ping", + entity_id: "ping", + event_type: "ping", + status: "delivered", + attempt_count: 1, + next_attempt_at: timestamp, + last_status_code: 200, + last_error_code: null, + duration_ms: 42, + created_at: timestamp, + finished_at: timestamp, + }); + await respond(200, { + delivered: true, + statusCode: 200, + errorCode: null, + durationMs: 42, + }); + return; + } + if (body.action === "rotate_secret") { + endpoint.signing_key_hint = "e2e2"; + await respond(200, { + endpoint, + signingSecret: "whsec_e2e-test-only-shown-once-2", + }); + return; + } + await respond(200, { enqueued: 0 }); + return; + } + await route.fulfill({ status: 200, contentType: "application/json", @@ -904,6 +1040,29 @@ export async function installMockSupabase( }); return; } + case "webhook_endpoints": { + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(state.webhookEndpoints), + }); + return; + } + case "webhook_deliveries": { + const endpointId = url.searchParams + .get("endpoint_id") + ?.replace(/^eq\./, ""); + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify( + state.webhookDeliveries.filter( + (row) => !endpointId || row.endpoint_id === endpointId, + ), + ), + }); + return; + } default: { await route.fulfill({ status: 200, diff --git a/src/app/components/PrivacyPolicy.tsx b/src/app/components/PrivacyPolicy.tsx index cde8e7a1..27cb2bac 100644 --- a/src/app/components/PrivacyPolicy.tsx +++ b/src/app/components/PrivacyPolicy.tsx @@ -40,7 +40,7 @@ export function PrivacyPolicy() { Project Phoenix - Companion App

- Effective Date: February 20, 2026 + Effective Date: November 6, 2026

{/* Summary Box */} @@ -251,6 +251,18 @@ export function PrivacyPolicy() { integration at any time (Article 6(1)(a)) +
  • + • + + + Data sharing endpoints (optional): + {" "} + Consent — data is sent to an endpoint only after you add it + and choose what to share. You may withdraw consent by + pausing or deleting the endpoint at any time (Article + 6(1)(a)) + +
  • • @@ -470,6 +482,23 @@ export function PrivacyPolicy() { display name and workout statistics to other users. You can control this in your profile privacy settings.

    +

    + + Data sharing you set up yourself. + {" "} + If you add a data sharing endpoint in your profile settings, we + send the kinds of data you select (for example workouts, + personal records, routines and training cycles) to the web + address you provide, each time that data changes. This is off + unless you turn it on, only you can configure it for your + account, and each endpoint receives only your own data. We never + send raw force-curve telemetry, activities imported from Strava, + your payment details or other users' data this way. The + recipient is chosen by you and does not act on our behalf: once + data reaches your endpoint, how it is stored and used is between + you and whoever operates it. You can pause or delete an endpoint + at any time, and sharing stops immediately. +

    @@ -574,6 +603,18 @@ export function PrivacyPolicy() { Clauses for EEA/UK data transfers
  • +
  • + • + + + Data sharing endpoints: + {" "} + If you set one up, the data you select is sent to wherever + that endpoint is hosted, which may be outside your country + of residence. That transfer is made at your direction, to a + recipient you chose + +
  • Where your data is transferred outside the European Economic diff --git a/src/app/components/Profile.tsx b/src/app/components/Profile.tsx index 4c448ab3..b70770be 100644 --- a/src/app/components/Profile.tsx +++ b/src/app/components/Profile.tsx @@ -20,6 +20,7 @@ import { Link, useSearchParams } from "react-router"; import { toast } from "sonner"; import { PageShell } from "@/app/components/PageShell"; import { DangerZone } from "@/app/components/profile/DangerZone"; +import { DataSharingSection } from "@/app/components/profile/DataSharingSection"; import { ExportSection } from "@/app/components/profile/ExportSection"; import { ProfileAvatarImage } from "@/app/components/profile/ProfileAvatarImage"; import { TierBadge } from "@/app/components/TierBadge"; @@ -1163,6 +1164,10 @@ export function Profile() { {/* Data Export - available to all tiers (no SubscriptionGate) */} + {/* Data sharing: listed for every tier so a lapsed user can pause + or delete; adding and editing need Flame (server-enforced). */} + + {/* Account Deletion - available to all tiers (GDPR right to erasure) */} diff --git a/src/app/components/__tests__/DataSharingSection.test.tsx b/src/app/components/__tests__/DataSharingSection.test.tsx new file mode 100644 index 00000000..025b5dd4 --- /dev/null +++ b/src/app/components/__tests__/DataSharingSection.test.tsx @@ -0,0 +1,383 @@ +import { fireEvent, screen, waitFor, within } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "@/test/test-utils"; + +const state = vi.hoisted(() => ({ + endpoints: [] as Record[], + deliveries: [] as Record[], + subscription: { + tier: "FLAME", + isLoading: false, + isError: false, + refetch: () => Promise.resolve(), + }, + invoke: vi.fn(), + toast: { success: vi.fn(), error: vi.fn() }, +})); + +vi.mock("@/app/hooks/useAuth", () => ({ + useAuth: () => ({ user: { id: "test-user-id" } }), +})); + +vi.mock("@/hooks/useSubscription", () => ({ + useSubscription: () => state.subscription, +})); + +vi.mock("sonner", () => ({ + toast: { + success: (...args: unknown[]) => state.toast.success(...args), + error: (...args: unknown[]) => state.toast.error(...args), + info: vi.fn(), + }, +})); + +// A PostgREST builder double: every filter returns the builder, and awaiting +// it yields the rows of the table it was opened on. +vi.mock("@/lib/supabase", () => { + const builder = (rows: () => unknown[]) => { + const chain: Record = {}; + for (const method of ["select", "eq", "order", "limit"]) { + chain[method] = () => chain; + } + // biome-ignore lint/suspicious/noThenProperty: a PostgREST builder is awaited + chain.then = (resolve: (value: unknown) => unknown) => + Promise.resolve({ data: rows(), error: null }).then(resolve); + return chain; + }; + return { + supabase: { + from: (table: string) => + builder(() => + table === "webhook_endpoints" ? state.endpoints : state.deliveries, + ), + functions: { + invoke: (...args: unknown[]) => state.invoke(...args), + }, + }, + }; +}); + +import { DataSharingSection } from "@/app/components/profile/DataSharingSection"; + +// Obviously fake, and not shaped like a real secret: nothing here verifies it. +const SECRET = "whsec_test-only-not-a-real-secret"; + +function endpoint(overrides: Record = {}) { + return { + id: "e-1", + label: "Home server", + url: "https://hooks.example.com/in", + scopes: ["workouts", "routines"], + status: "active", + disabled_reason: null, + custom_header_name: null, + signing_key_hint: "LaSw", + consecutive_failures: 0, + last_success_at: null, + last_failure_at: null, + created_at: "2026-11-06T12:00:00.000Z", + updated_at: "2026-11-06T12:00:00.000Z", + ...overrides, + }; +} + +function button(name: RegExp | string) { + return screen.getByRole("button", { name }) as HTMLButtonElement; +} + +describe("DataSharingSection", () => { + beforeEach(() => { + vi.clearAllMocks(); + state.endpoints = []; + state.deliveries = []; + state.subscription = { + tier: "FLAME", + isLoading: false, + isError: false, + refetch: () => Promise.resolve(), + }; + }); + + it("shows a Flame user their endpoint and lets them manage it", async () => { + state.endpoints = [endpoint({ custom_header_name: "Authorization" })]; + + renderWithProviders(); + + expect(await screen.findByText("Home server")).toBeInTheDocument(); + expect( + screen.getByText("https://hooks.example.com/in"), + ).toBeInTheDocument(); + expect(screen.getByText("Active")).toBeInTheDocument(); + expect(screen.getByText("Workouts")).toBeInTheDocument(); + expect(screen.getByText("Routines")).toBeInTheDocument(); + expect(screen.getByText("LaSw")).toBeInTheDocument(); + expect(screen.getByText("Authorization")).toBeInTheDocument(); + for (const name of [ + /add endpoint/i, + /send test/i, + /^edit$/i, + /replace secret/i, + /resend all/i, + /^pause$/i, + /^delete$/i, + ]) { + expect(button(name).disabled, String(name)).toBe(false); + } + expect(screen.queryByTestId("data-sharing-upgrade")).toBeNull(); + }); + + it("lets a user below Flame pause and delete but nothing else", async () => { + state.subscription = { ...state.subscription, tier: "EMBER" }; + state.endpoints = [endpoint()]; + + renderWithProviders(); + + await screen.findByText("Home server"); + expect(screen.getByTestId("data-sharing-upgrade")).toHaveTextContent( + /part of Flame/, + ); + expect(screen.getByTestId("data-sharing-upgrade")).toHaveTextContent( + /pause or delete/, + ); + expect(button(/^pause$/i).disabled).toBe(false); + expect(button(/^delete$/i).disabled).toBe(false); + for (const name of [ + /add endpoint/i, + /send test/i, + /^edit$/i, + /replace secret/i, + /resend all/i, + ]) { + expect(button(name).disabled, String(name)).toBe(true); + } + }); + + it("does not tell a paying user to upgrade when billing is unavailable", async () => { + state.subscription = { ...state.subscription, tier: "FREE", isError: true }; + state.endpoints = [endpoint()]; + + renderWithProviders(); + + await screen.findByText("Home server"); + expect(screen.queryByTestId("data-sharing-upgrade")).toBeNull(); + expect( + screen.getByText(/billing status is unavailable/i), + ).toBeInTheDocument(); + expect(button(/add endpoint/i).disabled).toBe(true); + expect(button(/^pause$/i).disabled).toBe(false); + }); + + it("says why an endpoint was switched off and offers to switch it back on", async () => { + state.endpoints = [ + endpoint({ + status: "disabled", + disabled_reason: "too_many_failures", + consecutive_failures: 9, + }), + ]; + + renderWithProviders(); + + expect(await screen.findByText("Switched off")).toBeInTheDocument(); + expect( + screen.getByText(/switched off after repeated failed deliveries/i), + ).toBeInTheDocument(); + expect(button(/switch on/i).disabled).toBe(false); + // Nothing to resend to while it is off. + expect(button(/resend all/i).disabled).toBe(true); + }); + + it("stops offering a new endpoint at the limit", async () => { + state.endpoints = [ + endpoint({ id: "e-1" }), + endpoint({ id: "e-2", label: "Second" }), + endpoint({ id: "e-3", label: "Third" }), + ]; + + renderWithProviders(); + + await screen.findByText("Third"); + expect(button(/add endpoint/i).disabled).toBe(true); + expect(screen.getByText(/maximum of 3 endpoints/i)).toBeInTheDocument(); + }); + + it("creates an endpoint from the form and shows the secret once", async () => { + state.invoke.mockResolvedValue({ + data: { endpoint: endpoint(), signingSecret: SECRET }, + error: null, + }); + renderWithProviders(); + await screen.findByText(/no endpoints yet/i); + + // Act: fill in the form and submit. + fireEvent.click(button(/add endpoint/i)); + const dialog = await screen.findByRole("dialog"); + fireEvent.change(within(dialog).getByLabelText("Name"), { + target: { value: "Home server" }, + }); + fireEvent.change(within(dialog).getByLabelText("Endpoint URL"), { + target: { value: "https://hooks.example.com/in" }, + }); + fireEvent.click(within(dialog).getByRole("switch", { name: "Workouts" })); + fireEvent.click( + within(dialog).getByRole("button", { name: "Add endpoint" }), + ); + + // Assert: one create call, with no user id for the server to trust. + await waitFor(() => expect(state.invoke).toHaveBeenCalledTimes(1)); + expect(state.invoke).toHaveBeenCalledWith("webhook-endpoints", { + body: { + action: "create", + label: "Home server", + url: "https://hooks.example.com/in", + scopes: ["workouts"], + }, + }); + // The secret is shown... + expect(await screen.findByTestId("signing-secret")).toHaveTextContent( + SECRET, + ); + // ...and gone for good once the dialog is closed. + fireEvent.click(button(/i have saved it/i)); + await waitFor(() => + expect(screen.queryByTestId("signing-secret")).toBeNull(), + ); + expect(document.body.textContent).not.toContain(SECRET); + }); + + it("does not call the server while the form is invalid", async () => { + renderWithProviders(); + await screen.findByText(/no endpoints yet/i); + + fireEvent.click(button(/add endpoint/i)); + const dialog = await screen.findByRole("dialog"); + fireEvent.change(within(dialog).getByLabelText("Name"), { + target: { value: "Home server" }, + }); + fireEvent.change(within(dialog).getByLabelText("Endpoint URL"), { + target: { value: "http://hooks.example.com/in" }, + }); + fireEvent.click( + within(dialog).getByRole("button", { name: "Add endpoint" }), + ); + + expect( + await within(dialog).findByText("The URL must start with https://."), + ).toBeInTheDocument(); + expect( + within(dialog).getByText("Choose at least one kind of data to share."), + ).toBeInTheDocument(); + expect(state.invoke).not.toHaveBeenCalled(); + }); + + it("pauses an endpoint with a pause-only request", async () => { + state.endpoints = [endpoint()]; + state.invoke.mockResolvedValue({ + data: { + endpoint: endpoint({ + status: "paused", + disabled_reason: "user_paused", + }), + }, + error: null, + }); + renderWithProviders(); + await screen.findByText("Home server"); + + fireEvent.click(button(/^pause$/i)); + + // Exactly these keys: the server lets a pause through without Flame + // only when nothing else rides along. + await waitFor(() => + expect(state.invoke).toHaveBeenCalledWith("webhook-endpoints", { + body: { action: "update", endpointId: "e-1", status: "paused" }, + }), + ); + }); + + it("shows the result of a test delivery", async () => { + state.endpoints = [endpoint()]; + state.invoke.mockResolvedValue({ + data: { + delivered: false, + statusCode: 503, + errorCode: "http_error", + durationMs: 120, + }, + error: null, + }); + renderWithProviders(); + await screen.findByText("Home server"); + + fireEvent.click(button(/send test/i)); + + expect( + await screen.findByText( + "The receiver answered with an error status (503).", + ), + ).toBeInTheDocument(); + expect(state.invoke).toHaveBeenCalledWith("webhook-endpoints", { + body: { action: "test", endpointId: "e-1" }, + }); + }); + + it("asks before deleting and only then calls the server", async () => { + state.endpoints = [endpoint()]; + state.invoke.mockResolvedValue({ data: { deleted: true }, error: null }); + renderWithProviders(); + await screen.findByText("Home server"); + + fireEvent.click(button(/^delete$/i)); + const confirm = await screen.findByRole("alertdialog"); + expect(state.invoke).not.toHaveBeenCalled(); + fireEvent.click( + within(confirm).getByRole("button", { name: "Delete endpoint" }), + ); + + await waitFor(() => + expect(state.invoke).toHaveBeenCalledWith("webhook-endpoints", { + body: { action: "delete", endpointId: "e-1" }, + }), + ); + }); + + it("surfaces the server's reason when a save is refused", async () => { + const { FunctionsHttpError } = await import("@supabase/supabase-js"); + state.invoke.mockResolvedValue({ + data: null, + error: new FunctionsHttpError( + new Response( + JSON.stringify({ + error: "url_resolves_to_private_address", + message: "That host resolves to a private or reserved address.", + }), + { status: 400 }, + ), + ), + }); + renderWithProviders(); + await screen.findByText(/no endpoints yet/i); + + fireEvent.click(button(/add endpoint/i)); + const dialog = await screen.findByRole("dialog"); + fireEvent.change(within(dialog).getByLabelText("Name"), { + target: { value: "Internal" }, + }); + fireEvent.change(within(dialog).getByLabelText("Endpoint URL"), { + target: { value: "https://internal.example.com/in" }, + }); + fireEvent.click(within(dialog).getByRole("switch", { name: "Workouts" })); + fireEvent.click( + within(dialog).getByRole("button", { name: "Add endpoint" }), + ); + + await waitFor(() => + expect(state.toast.error).toHaveBeenCalledWith( + "That host resolves to a private or reserved address.", + ), + ); + // The form stays open so the URL can be corrected. + expect(screen.getByRole("dialog")).toBeInTheDocument(); + expect(screen.queryByTestId("signing-secret")).toBeNull(); + }); +}); diff --git a/src/app/components/profile/DataSharingSection.tsx b/src/app/components/profile/DataSharingSection.tsx new file mode 100644 index 00000000..19148028 --- /dev/null +++ b/src/app/components/profile/DataSharingSection.tsx @@ -0,0 +1,229 @@ +import { useQuery } from "@tanstack/react-query"; +import { Plus, Share2 } from "lucide-react"; +import { useState } from "react"; +import { Link } from "react-router"; +import { toast } from "sonner"; +import { EndpointCard } from "@/app/components/profile/data-sharing/EndpointCard"; +import { + EndpointFormDialog, + type EndpointFormSubmission, +} from "@/app/components/profile/data-sharing/EndpointFormDialog"; +import { + type RevealedSecret, + SecretRevealDialog, +} from "@/app/components/profile/data-sharing/SecretRevealDialog"; +import { Button } from "@/app/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/app/components/ui/card"; +import { Skeleton } from "@/app/components/ui/skeleton"; +import { useAuth } from "@/app/hooks/useAuth"; +import { useSubscription } from "@/hooks/useSubscription"; +import { MAX_WEBHOOK_ENDPOINTS, type WebhookEndpoint } from "@/lib/dataSharing"; +import { TIER_LEVEL } from "@/lib/subscription-entitlement"; +import { FEATURE_MIN_TIER } from "@/lib/tierMatrix"; +import { + useCreateWebhookEndpoint, + useUpdateWebhookEndpoint, +} from "@/mutations/dataSharing"; +import { webhookEndpointsOptions } from "@/queries/dataSharing"; + +type FormState = { endpoint: WebhookEndpoint | null } | null; + +/** + * Profile > Settings > Data Sharing. Lives on a route with no tier gate on + * purpose: someone whose plan lapsed must still be able to see where their + * data was going and pause or delete it. Adding, editing and switching an + * endpoint on need Flame, here for the buttons and on the server for real. + */ +export function DataSharingSection() { + const { user } = useAuth(); + const userId = user?.id ?? ""; + const subscription = useSubscription(); + const { + data: endpoints, + isLoading, + isError, + refetch, + } = useQuery(webhookEndpointsOptions(userId)); + + const [form, setForm] = useState(null); + const [revealed, setRevealed] = useState(null); + const create = useCreateWebhookEndpoint(userId); + const update = useUpdateWebhookEndpoint(userId); + + // A billing outage is not "no plan": it disables changes without telling a + // paying user to upgrade. + const billingUnavailable = subscription.isError; + const tierKnown = !subscription.isLoading && !billingUnavailable; + const canManage = + tierKnown && + TIER_LEVEL[subscription.tier] >= TIER_LEVEL[FEATURE_MIN_TIER.dataSharing]; + const needsUpgrade = tierKnown && !canManage; + const count = endpoints?.length ?? 0; + const atLimit = count >= MAX_WEBHOOK_ENDPOINTS; + + const handleSubmit = (values: EndpointFormSubmission) => { + const editing = form?.endpoint ?? null; + if (!editing) { + create.mutate( + { + label: values.label, + url: values.url, + scopes: values.scopes, + ...(values.customHeader ? { customHeader: values.customHeader } : {}), + }, + { + onSuccess: (result) => { + setForm(null); + setRevealed({ + endpointLabel: result.endpoint.label, + signingSecret: result.signingSecret, + rotated: false, + }); + }, + }, + ); + return; + } + update.mutate( + { + endpointId: editing.id, + label: values.label, + scopes: values.scopes, + // Only when it changed: a new URL is re-validated and resolved. + ...(values.url !== editing.url ? { url: values.url } : {}), + ...(values.customHeader !== undefined + ? { customHeader: values.customHeader } + : {}), + }, + { + onSuccess: () => { + setForm(null); + toast.success("Endpoint updated"); + }, + }, + ); + }; + + return ( + + + + + Data Sharing + + + Send your own training data to an HTTPS endpoint you control, as + signed webhook events. Only you can set this up, and each endpoint + receives only your data. + + + + {needsUpgrade && ( +

    + Data sharing is part of Flame.{" "} + + See plans + + {count > 0 + ? " Your endpoints are listed below so you can pause or delete them; nothing is sent while your plan does not include data sharing." + : ""} +
    + )} + {billingUnavailable && ( +
    + Billing status is unavailable, so changes are switched off for the + moment. You can still pause or delete an endpoint.{" "} + +
    + )} + + {isLoading ? ( + + ) : isError ? ( +
    +

    + Couldn't load your endpoints. +

    + +
    + ) : count === 0 ? ( +

    + No endpoints yet. Add one to start receiving your workouts, records, + routines and more as they change. +

    + ) : ( +
    + {endpoints?.map((endpoint) => ( + setForm({ endpoint: target })} + onSecret={(target, signingSecret) => + setRevealed({ + endpointLabel: target.label, + signingSecret, + rotated: true, + }) + } + /> + ))} +
    + )} + +
    + +

    + {atLimit + ? `You have the maximum of ${MAX_WEBHOOK_ENDPOINTS} endpoints.` + : `Up to ${MAX_WEBHOOK_ENDPOINTS} endpoints.`} +

    +
    + +

    + Loads are sent per cable, as on the phone. Raw force-curve telemetry, + advanced biomechanics data and activities imported from Strava are + never shared this way. The complete download above is unaffected. +

    + + + setForm(null)} + /> + setRevealed(null)} /> + + ); +} diff --git a/src/app/components/profile/data-sharing/DeliveryLog.tsx b/src/app/components/profile/data-sharing/DeliveryLog.tsx new file mode 100644 index 00000000..2172c129 --- /dev/null +++ b/src/app/components/profile/data-sharing/DeliveryLog.tsx @@ -0,0 +1,119 @@ +import { useQuery } from "@tanstack/react-query"; +import { formatRelative } from "@/app/components/integrations/formatRelative"; +import { Badge } from "@/app/components/ui/badge"; +import { Skeleton } from "@/app/components/ui/skeleton"; +import { describeDeliveryError } from "@/lib/dataSharing"; +import { + WEBHOOK_DELIVERY_LOG_LIMIT, + type WebhookDelivery, + webhookDeliveriesOptions, +} from "@/queries/dataSharing"; + +const STATUS_LABEL: Record = { + pending: "Waiting", + delivering: "Sending", + delivered: "Delivered", + dead: "Failed", + skipped: "Not sent", +}; + +const STATUS_CLASS: Record = { + pending: "bg-secondary/40 text-foreground", + delivering: "bg-secondary/40 text-foreground", + delivered: "bg-success/20 text-success", + dead: "bg-destructive/20 text-destructive", + skipped: "bg-muted/30 text-muted-foreground", +}; + +/** What a delivery was about: the resolved event, or the item while it waits. */ +function deliverySubject(delivery: WebhookDelivery): string { + return delivery.event_type ?? delivery.entity.replaceAll("_", " "); +} + +function deliveryDetail(delivery: WebhookDelivery): string | null { + if (delivery.status === "pending" && delivery.attempt_count > 0) { + // A retry is scheduled: say what went wrong last time and when it retries. + const reason = describeDeliveryError( + delivery.last_error_code, + delivery.last_status_code, + ); + const when = new Date(delivery.next_attempt_at).toLocaleString(); + return `${reason ?? "Last attempt failed"}. Retrying at ${when}.`; + } + if (delivery.status === "delivered") { + return delivery.duration_ms === null + ? null + : `${delivery.last_status_code ?? ""} in ${delivery.duration_ms} ms`.trim(); + } + return describeDeliveryError( + delivery.last_error_code, + delivery.last_status_code, + ); +} + +interface DeliveryLogProps { + userId: string; + endpointId: string; +} + +/** The endpoint's latest deliveries, read directly under owner RLS. */ +export function DeliveryLog({ userId, endpointId }: DeliveryLogProps) { + const { data, isLoading, isError } = useQuery( + webhookDeliveriesOptions(userId, endpointId), + ); + + if (isLoading) return ; + if (isError) { + return ( +

    + Couldn't load the delivery log. Try again in a moment. +

    + ); + } + if (!data?.length) { + return ( +

    + No deliveries yet. They appear here within a minute or two of a change. +

    + ); + } + + return ( +
    +
      + {data.map((delivery) => { + const detail = deliveryDetail(delivery); + return ( +
    • + + {STATUS_LABEL[delivery.status]} + + + {deliverySubject(delivery)} + + + {formatRelative(delivery.created_at)} + {delivery.attempt_count > 1 + ? ` · attempt ${delivery.attempt_count}` + : ""} + + {detail && ( + + {detail} + + )} +
    • + ); + })} +
    +

    + Showing the latest {WEBHOOK_DELIVERY_LOG_LIMIT}. The log keeps 30 days. +

    +
    + ); +} diff --git a/src/app/components/profile/data-sharing/EndpointCard.tsx b/src/app/components/profile/data-sharing/EndpointCard.tsx new file mode 100644 index 00000000..15c55fc1 --- /dev/null +++ b/src/app/components/profile/data-sharing/EndpointCard.tsx @@ -0,0 +1,397 @@ +import { ChevronDown, ChevronUp, Send } from "lucide-react"; +import { useState } from "react"; +import { toast } from "sonner"; +import { formatRelative } from "@/app/components/integrations/formatRelative"; +import { DeliveryLog } from "@/app/components/profile/data-sharing/DeliveryLog"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/app/components/ui/alert-dialog"; +import { Badge } from "@/app/components/ui/badge"; +import { Button } from "@/app/components/ui/button"; +import { + DATA_SHARING_SCOPE_INFO, + DataSharingError, + describeDisabledReason, + describeTestResult, + type WebhookEndpoint, + type WebhookTestResult, +} from "@/lib/dataSharing"; +import { + useDeleteWebhookEndpoint, + useResendWebhookData, + useRotateWebhookSecret, + useTestWebhookEndpoint, + useUpdateWebhookEndpoint, +} from "@/mutations/dataSharing"; + +const STATUS_LABEL: Record = { + active: "Active", + paused: "Paused", + disabled: "Switched off", +}; + +const STATUS_CLASS: Record = { + active: "bg-success/20 text-success", + paused: "bg-warning/20 text-warning", + disabled: "bg-destructive/20 text-destructive", +}; + +const SCOPE_LABEL: Record = Object.fromEntries( + DATA_SHARING_SCOPE_INFO.map((info) => [info.scope, info.label]), +); + +type Confirm = "rotate" | "resend" | "delete"; + +const CONFIRM_COPY: Record< + Confirm, + { title: string; body: string; action: string; pending: string } +> = { + rotate: { + title: "Replace the signing secret?", + body: "A new secret is created and shown once. Deliveries are signed with both secrets for 24 hours, then only the new one, so update your receiver within a day.", + action: "Replace secret", + pending: "Replacing...", + }, + resend: { + title: "Resend everything?", + body: "Every existing item in this endpoint's selected data is queued and sent again, one delivery each. A long history can take a while and your receiver will see items it already has.", + action: "Resend all", + pending: "Queuing...", + }, + delete: { + title: "Delete this endpoint?", + body: "Nothing more is sent to it. Its signing secret and delivery log are deleted and cannot be recovered.", + action: "Delete endpoint", + pending: "Deleting...", + }, +}; + +interface EndpointCardProps { + userId: string; + endpoint: WebhookEndpoint; + /** FLAME or above. Pausing and deleting stay available without it. */ + canManage: boolean; + onEdit: (endpoint: WebhookEndpoint) => void; + onSecret: (endpoint: WebhookEndpoint, signingSecret: string) => void; +} + +export function EndpointCard({ + userId, + endpoint, + canManage, + onEdit, + onSecret, +}: EndpointCardProps) { + const [confirm, setConfirm] = useState(null); + const [showLog, setShowLog] = useState(false); + const [testResult, setTestResult] = useState(null); + + const update = useUpdateWebhookEndpoint(userId); + const rotate = useRotateWebhookSecret(userId); + const test = useTestWebhookEndpoint(userId); + const resend = useResendWebhookData(userId); + const remove = useDeleteWebhookEndpoint(userId); + + const busy = + update.isPending || + rotate.isPending || + test.isPending || + resend.isPending || + remove.isPending; + const reason = describeDisabledReason(endpoint.disabled_reason); + const isActive = endpoint.status === "active"; + + const handleTest = () => { + setTestResult(null); + test.mutate(endpoint.id, { onSuccess: setTestResult }); + }; + + const handlePause = () => { + update.mutate( + { endpointId: endpoint.id, status: "paused" }, + { onSuccess: () => toast.success(`Paused ${endpoint.label}`) }, + ); + }; + + const handleResume = () => { + setTestResult(null); + update.mutate( + { endpointId: endpoint.id, status: "active" }, + { + onSuccess: () => toast.success(`${endpoint.label} is switched on`), + onError: (error) => { + // The server sends one test delivery first; show what it got. + if ( + error instanceof DataSharingError && + error.code === "test_delivery_failed" + ) { + setTestResult({ + delivered: false, + statusCode: + typeof error.details.statusCode === "number" + ? error.details.statusCode + : null, + errorCode: + typeof error.details.errorCode === "string" + ? error.details.errorCode + : null, + durationMs: null, + }); + } + }, + }, + ); + }; + + const runConfirmed = () => { + if (confirm === "rotate") { + rotate.mutate(endpoint.id, { + onSuccess: (result) => { + setConfirm(null); + onSecret(result.endpoint, result.signingSecret); + }, + onError: () => setConfirm(null), + }); + } else if (confirm === "resend") { + resend.mutate(endpoint.id, { + onSuccess: (result) => { + setConfirm(null); + toast.success( + result.enqueued === 0 + ? "Nothing new to resend" + : `Queued ${result.enqueued} deliveries`, + ); + }, + onError: () => setConfirm(null), + }); + } else if (confirm === "delete") { + remove.mutate(endpoint.id, { + onSuccess: () => { + setConfirm(null); + toast.success(`Deleted ${endpoint.label}`); + }, + onError: () => setConfirm(null), + }); + } + }; + + const confirmPending = + rotate.isPending || resend.isPending || remove.isPending; + + return ( +
    +
    +
    +

    {endpoint.label}

    +

    + {endpoint.url} +

    +
    + + {STATUS_LABEL[endpoint.status]} + +
    + + {reason && ( +

    + {reason} +

    + )} + +
    + {endpoint.scopes.map((scope) => ( + + {SCOPE_LABEL[scope] ?? scope} + + ))} +
    + +
    +
    +
    Signing secret ends in
    +
    + {endpoint.signing_key_hint} +
    +
    +
    +
    Custom header:
    +
    + {endpoint.custom_header_name ?? "none"} +
    +
    +
    +
    Last delivered:
    +
    + {formatRelative(endpoint.last_success_at)} +
    +
    + {endpoint.consecutive_failures > 0 && ( +
    +
    Failed attempts in a row:
    +
    + {endpoint.consecutive_failures} +
    +
    + )} +
    + + {testResult && ( +

    + {describeTestResult(testResult)} +

    + )} + +
    + {isActive ? ( + + ) : ( + + )} + + + + + +
    + +
    + + {showLog && ( +
    + +
    + )} +
    + + { + if (!open && !confirmPending) setConfirm(null); + }} + > + + + + {confirm ? CONFIRM_COPY[confirm].title : ""} + + + {confirm ? CONFIRM_COPY[confirm].body : ""} + + + + + Cancel + + { + // Keep the dialog open while the request runs and stop a + // double click from sending it twice. + event.preventDefault(); + if (confirmPending) return; + runConfirmed(); + }} + > + {confirm + ? confirmPending + ? CONFIRM_COPY[confirm].pending + : CONFIRM_COPY[confirm].action + : ""} + + + + +
    + ); +} diff --git a/src/app/components/profile/data-sharing/EndpointFormDialog.tsx b/src/app/components/profile/data-sharing/EndpointFormDialog.tsx new file mode 100644 index 00000000..41b29623 --- /dev/null +++ b/src/app/components/profile/data-sharing/EndpointFormDialog.tsx @@ -0,0 +1,315 @@ +import { useEffect, useId, useState } from "react"; +import { Button } from "@/app/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/app/components/ui/dialog"; +import { Input } from "@/app/components/ui/input"; +import { Label } from "@/app/components/ui/label"; +import { Switch } from "@/app/components/ui/switch"; +import { + DATA_SHARING_SCOPE_INFO, + type DataSharingScope, + isDataSharingScope, + type WebhookCustomHeaderInput, + type WebhookEndpoint, +} from "@/lib/dataSharing"; +import { + WEBHOOK_HEADER_VALUE_MAX, + WEBHOOK_LABEL_MAX, + WEBHOOK_URL_MAX, + webhookEndpointFormSchema, + webhookFormErrors, +} from "@/schemas/dataSharing"; + +export interface EndpointFormSubmission { + label: string; + url: string; + scopes: DataSharingScope[]; + /** undefined: leave as is. null: remove. Otherwise set. */ + customHeader: WebhookCustomHeaderInput | null | undefined; +} + +interface EndpointFormDialogProps { + open: boolean; + /** The endpoint being edited, or null to create one. */ + endpoint: WebhookEndpoint | null; + isSaving: boolean; + onSubmit: (values: EndpointFormSubmission) => void; + onClose: () => void; +} + +type FieldErrors = ReturnType; + +export function EndpointFormDialog({ + open, + endpoint, + isSaving, + onSubmit, + onClose, +}: EndpointFormDialogProps) { + const formId = useId(); + const [label, setLabel] = useState(""); + const [url, setUrl] = useState(""); + const [scopes, setScopes] = useState([]); + const [headerName, setHeaderName] = useState(""); + const [headerValue, setHeaderValue] = useState(""); + const [removeHeader, setRemoveHeader] = useState(false); + const [errors, setErrors] = useState({}); + + // Reset to the endpoint being edited (or to empty) each time it opens. The + // stored header value is never sent to the browser, so its field starts + // empty and "leave empty to keep" is the edit default. + useEffect(() => { + if (!open) return; + setLabel(endpoint?.label ?? ""); + setUrl(endpoint?.url ?? ""); + setScopes((endpoint?.scopes ?? []).filter(isDataSharingScope)); + setHeaderName(""); + setHeaderValue(""); + setRemoveHeader(false); + setErrors({}); + }, [open, endpoint]); + + const existingHeader = endpoint?.custom_header_name ?? null; + + const toggleScope = (scope: DataSharingScope, checked: boolean) => { + setScopes((current) => + checked + ? [...current.filter((entry) => entry !== scope), scope] + : current.filter((entry) => entry !== scope), + ); + }; + + const handleSubmit = (event: React.FormEvent) => { + event.preventDefault(); + const parsed = webhookEndpointFormSchema.safeParse({ + label, + url: url.trim(), + scopes, + headerName: removeHeader ? "" : headerName, + headerValue: removeHeader ? "" : headerValue, + }); + if (!parsed.success) { + setErrors(webhookFormErrors(parsed.error)); + return; + } + setErrors({}); + const values = parsed.data; + let customHeader: EndpointFormSubmission["customHeader"]; + if (removeHeader) customHeader = null; + else if (values.headerName !== "") { + customHeader = { name: values.headerName, value: values.headerValue }; + } + onSubmit({ + label: values.label, + url: values.url, + scopes: values.scopes, + customHeader, + }); + }; + + return ( + { + if (!next && !isSaving) onClose(); + }} + > + + + + {endpoint ? "Edit endpoint" : "Add a data sharing endpoint"} + + + Phoenix Portal sends the data you choose to this address as signed + JSON, within a minute or two of each change. Only use an endpoint + you control. + + + +
    +
    + + setLabel(event.target.value)} + /> + {errors.label && ( +

    + {errors.label} +

    + )} +
    + +
    + + setUrl(event.target.value)} + /> + {errors.url ? ( +

    + {errors.url} +

    + ) : ( +

    + Must be https and reachable from the internet. Redirects are not + followed. +

    + )} +
    + +
    + + Data to share + + {DATA_SHARING_SCOPE_INFO.map((info) => { + const switchId = `${formId}-scope-${info.scope}`; + return ( +
    +
    + +

    + {info.description} +

    +
    + + toggleScope(info.scope, checked) + } + /> +
    + ); + })} + {errors.scopes && ( +

    {errors.scopes}

    + )} +
    + +
    + + Custom header (optional) + +

    + For receivers that need a key or token on each request and cannot + check the signature. Sent with every delivery, stored encrypted, + and never shown again. +

    + {existingHeader && ( +
    +

    + A {existingHeader} header + is set. Leave the fields below empty to keep it. +

    +
    + + +
    +
    + )} + {!removeHeader && ( +
    +
    + + setHeaderName(event.target.value)} + /> + {errors.headerName && ( +

    + {errors.headerName} +

    + )} +
    +
    + + setHeaderValue(event.target.value)} + /> + {errors.headerValue && ( +

    + {errors.headerValue} +

    + )} +
    +
    + )} +
    +
    + + + + + +
    +
    + ); +} diff --git a/src/app/components/profile/data-sharing/SecretRevealDialog.tsx b/src/app/components/profile/data-sharing/SecretRevealDialog.tsx new file mode 100644 index 00000000..02554b2b --- /dev/null +++ b/src/app/components/profile/data-sharing/SecretRevealDialog.tsx @@ -0,0 +1,113 @@ +import { Check, Copy, KeyRound } from "lucide-react"; +import { useState } from "react"; +import { toast } from "sonner"; +import { Button } from "@/app/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/app/components/ui/dialog"; + +export interface RevealedSecret { + endpointLabel: string; + signingSecret: string; + /** True after a rotation: the previous secret stays valid for a while. */ + rotated: boolean; +} + +interface SecretRevealDialogProps { + secret: RevealedSecret | null; + onClose: () => void; +} + +/** + * Shows a signing secret the one time the server returns it. The secret is + * held only in the parent's state and dropped when this closes; it is never + * written to storage, a query cache or a log. + */ +export function SecretRevealDialog({ + secret, + onClose, +}: SecretRevealDialogProps) { + const [copied, setCopied] = useState(false); + + const handleCopy = async () => { + if (!secret) return; + try { + await navigator.clipboard.writeText(secret.signingSecret); + setCopied(true); + } catch { + toast.error("Could not copy. Select the secret and copy it manually."); + } + }; + + return ( + { + if (!open) { + setCopied(false); + onClose(); + } + }} + > + event.preventDefault()} + > + + + + Signing secret for {secret?.endpointLabel} + + + Copy this secret into your receiver now. It is shown only once: we + store it encrypted and cannot show it again. + + + +
    + + {secret?.signingSecret} + + +

    + Your receiver uses it to check the{" "} + webhook-signature header on every + delivery (Standard Webhooks format), which proves the delivery came + from Phoenix Portal and was not altered. +

    + {secret?.rotated && ( +

    + Deliveries are signed with both the new and the previous secret + for the next 24 hours, so you can switch your receiver over + without missing any. +

    + )} +
    + + + + +
    +
    + ); +} diff --git a/src/lib/__tests__/dataSharing.test.ts b/src/lib/__tests__/dataSharing.test.ts new file mode 100644 index 00000000..d641084c --- /dev/null +++ b/src/lib/__tests__/dataSharing.test.ts @@ -0,0 +1,213 @@ +import { FunctionsFetchError, FunctionsHttpError } from "@supabase/supabase-js"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// Hoisted with the mock below, which is evaluated before this module's body. +const invoke = vi.hoisted(() => vi.fn()); + +vi.mock("@/lib/supabase", () => ({ + supabase: { functions: { invoke } }, +})); + +import { + DataSharingError, + describeDeliveryError, + describeDisabledReason, + describeTestResult, + invokeWebhookEndpoints, +} from "@/lib/dataSharing"; +import { isTierDenied } from "@/lib/tierErrors"; + +function httpError( + status: number, + body: unknown, + headers: Record = {}, +) { + return new FunctionsHttpError( + new Response(typeof body === "string" ? body : JSON.stringify(body), { + status, + headers, + }), + ); +} + +async function failure(): Promise { + try { + await invokeWebhookEndpoints({ action: "test", endpointId: "e-1" }); + } catch (error) { + return error as DataSharingError; + } + throw new Error("expected invokeWebhookEndpoints to reject"); +} + +describe("invokeWebhookEndpoints", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("posts the action to webhook-endpoints and returns the body", async () => { + invoke.mockResolvedValue({ data: { enqueued: 3 }, error: null }); + + const result = await invokeWebhookEndpoints<{ enqueued: number }>({ + action: "resend_all", + endpointId: "e-1", + }); + + expect(result).toEqual({ enqueued: 3 }); + expect(invoke).toHaveBeenCalledWith("webhook-endpoints", { + body: { action: "resend_all", endpointId: "e-1" }, + }); + }); + + it("turns a refusal into a DataSharingError carrying the server's code and message", async () => { + invoke.mockResolvedValue({ + data: null, + error: httpError(400, { + error: "url_resolves_to_private_address", + message: "That host resolves to a private or reserved address.", + }), + }); + + const error = await failure(); + + expect(error).toBeInstanceOf(DataSharingError); + expect(error.code).toBe("url_resolves_to_private_address"); + expect(error.status).toBe(400); + expect(error.message).toBe( + "That host resolves to a private or reserved address.", + ); + }); + + it("keeps the test-delivery details of a refused resume", async () => { + invoke.mockResolvedValue({ + data: null, + error: httpError(409, { + error: "test_delivery_failed", + message: + "The endpoint did not accept a test delivery, so it was not switched on.", + statusCode: 503, + errorCode: "http_error", + }), + }); + + const error = await failure(); + + expect(error.code).toBe("test_delivery_failed"); + expect(error.details.statusCode).toBe(503); + expect(error.details.errorCode).toBe("http_error"); + }); + + it("is recognised as a tier denial when the server answers 402", async () => { + invoke.mockResolvedValue({ + data: null, + error: httpError(402, { + error: "subscription_required", + message: "This feature requires FLAME.", + requiredTier: "FLAME", + }), + }); + + const error = await failure(); + + expect(error.status).toBe(402); + expect(isTierDenied(error)).toBe(true); + }); + + it("explains a rate limit and reads the wait from the response", async () => { + invoke.mockResolvedValue({ + data: null, + error: httpError( + 429, + { error: "rate_limit_exceeded", retryAfterSeconds: 240 }, + { "Retry-After": "240" }, + ), + }); + + const error = await failure(); + + expect(error.code).toBe("rate_limit_exceeded"); + expect(error.retryAfterSeconds).toBe(240); + expect(error.message).toMatch(/too many requests/i); + }); + + it("falls back to a generic message when the body is not JSON", async () => { + invoke.mockResolvedValue({ + data: null, + error: httpError(500, "gateway"), + }); + + const error = await failure(); + + expect(error.code).toBe("unknown"); + expect(error.status).toBe(500); + expect(error.message).not.toContain("html"); + }); + + it("reports a network failure without leaking the underlying error text", async () => { + invoke.mockResolvedValue({ + data: null, + error: new FunctionsFetchError(new Error("ECONNRESET 10.0.0.5")), + }); + + const error = await failure(); + + expect(error.code).toBe("network_error"); + expect(error.message).not.toContain("10.0.0.5"); + }); + + it("reports a thrown invoke the same way", async () => { + invoke.mockRejectedValue(new TypeError("Failed to fetch")); + + const error = await failure(); + + expect(error.code).toBe("network_error"); + }); +}); + +describe("data sharing copy", () => { + it("explains why an endpoint is not active", () => { + expect(describeDisabledReason(null)).toBeNull(); + expect(describeDisabledReason("subscription_lapsed")).toMatch( + /plan no longer includes data sharing/, + ); + expect(describeDisabledReason("too_many_failures")).toMatch( + /repeated failed deliveries/, + ); + expect(describeDisabledReason("endpoint_gone")).toMatch(/410 Gone/); + // A code this build does not know still says something true. + expect(describeDisabledReason("future_reason")).toBe( + "This endpoint is switched off.", + ); + }); + + it("describes a delivery outcome with its status code when there is one", () => { + expect(describeDeliveryError(null, 200)).toBeNull(); + expect(describeDeliveryError("http_error", 503)).toBe( + "The receiver answered with an error status (503)", + ); + expect(describeDeliveryError("connection_failed", null)).toBe( + "Could not connect to the receiver", + ); + expect(describeDeliveryError("future_code", null)).toBe("Delivery failed"); + }); + + it("describes a test result as one sentence", () => { + expect( + describeTestResult({ + delivered: true, + statusCode: 204, + errorCode: null, + durationMs: 80, + }), + ).toBe("The receiver accepted the test delivery (204)."); + expect( + describeTestResult({ + delivered: false, + statusCode: 301, + errorCode: "redirect_not_followed", + durationMs: 40, + }), + ).toBe( + "The receiver answered with a redirect, which is not followed (301).", + ); + }); +}); diff --git a/src/lib/dataSharing.ts b/src/lib/dataSharing.ts new file mode 100644 index 00000000..2d37d1a3 --- /dev/null +++ b/src/lib/dataSharing.ts @@ -0,0 +1,218 @@ +/** + * Data sharing (outbound webhooks): the browser's side of the + * `webhook-endpoints` Edge Function. + * + * Every write goes through that function. The browser cannot write the + * tables, never sees a stored secret, and never calls the user's endpoint + * itself (the SPA's CSP `connect-src` forbids it, and a test delivery has to + * come from where real deliveries come from). + */ +import { FunctionsHttpError } from "@supabase/supabase-js"; +import { supabase } from "@/lib/supabase"; +import type { DataSharingScope } from "../../supabase/functions/_shared/dataSharingScopes.ts"; + +export { + DATA_SHARING_SCOPE_INFO, + DATA_SHARING_SCOPES, + type DataSharingScope, + isDataSharingScope, + MAX_WEBHOOK_ENDPOINTS, +} from "../../supabase/functions/_shared/dataSharingScopes.ts"; + +export type WebhookEndpointStatus = "active" | "paused" | "disabled"; + +/** An endpoint as the server returns it. There is no secret in it, ever. */ +export interface WebhookEndpoint { + id: string; + label: string; + url: string; + scopes: string[]; + status: WebhookEndpointStatus; + disabled_reason: string | null; + custom_header_name: string | null; + signing_key_hint: string; + consecutive_failures: number; + last_success_at: string | null; + last_failure_at: string | null; + created_at: string; + updated_at: string; +} + +export interface WebhookTestResult { + delivered: boolean; + statusCode: number | null; + errorCode: string | null; + durationMs: number | null; +} + +export interface WebhookCustomHeaderInput { + name: string; + value: string; +} + +export type WebhookEndpointsRequest = + | { + action: "create"; + label: string; + url: string; + scopes: DataSharingScope[]; + customHeader?: WebhookCustomHeaderInput; + } + | { + action: "update"; + endpointId: string; + label?: string; + url?: string; + scopes?: DataSharingScope[]; + /** `null` clears the header; omitted leaves it as it is. */ + customHeader?: WebhookCustomHeaderInput | null; + status?: "active" | "paused"; + } + | { action: "rotate_secret"; endpointId: string } + | { action: "test"; endpointId: string } + | { action: "resend_all"; endpointId: string } + | { action: "delete"; endpointId: string }; + +/** + * A refusal from `webhook-endpoints`. `code` is the server's fixed code + * (`url_not_https`, `endpoint_limit`, `test_delivery_failed`, ...) and + * `message` is its user-facing sentence. `status` 402 is a tier denial, so + * `isTierDenied` recognises this error too. + */ +export class DataSharingError extends Error { + readonly code: string; + readonly status: number; + readonly retryAfterSeconds: number | null; + readonly details: Record; + + constructor( + message: string, + options: { + code: string; + status: number; + retryAfterSeconds?: number | null; + details?: Record; + }, + ) { + super(message); + this.name = "DataSharingError"; + this.code = options.code; + this.status = options.status; + this.retryAfterSeconds = options.retryAfterSeconds ?? null; + this.details = options.details ?? {}; + } +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +const GENERIC_FAILURE = + "Data sharing could not be updated. Please try again in a moment."; + +async function toDataSharingError(error: unknown): Promise { + if (error instanceof FunctionsHttpError) { + const response = error.context as Response; + let body: unknown = null; + try { + body = await response.clone().json(); + } catch { + // Not JSON: fall through to the status-only message. + } + const details = isPlainObject(body) ? body : {}; + const code = typeof details.error === "string" ? details.error : "unknown"; + const retryHeader = Number(response.headers.get("Retry-After")); + const retryAfterSeconds = + typeof details.retryAfterSeconds === "number" + ? details.retryAfterSeconds + : Number.isFinite(retryHeader) && retryHeader > 0 + ? retryHeader + : null; + let message = + typeof details.message === "string" ? details.message : GENERIC_FAILURE; + if (response.status === 429) { + message = + "Too many requests. Wait a few minutes before trying that again."; + } + return new DataSharingError(message, { + // requireSubscription's 402 body uses `subscription_required`. + code, + status: response.status, + retryAfterSeconds, + details, + }); + } + // FunctionsFetchError / FunctionsRelayError: network or gateway. + return new DataSharingError( + "Could not reach the server. Check your connection and try again.", + { code: "network_error", status: 0 }, + ); +} + +/** Calls `webhook-endpoints` and returns its JSON body, or throws DataSharingError. */ +export async function invokeWebhookEndpoints( + request: WebhookEndpointsRequest, +): Promise { + let result: { data: unknown; error: unknown }; + try { + result = await supabase.functions.invoke("webhook-endpoints", { + body: request, + }); + } catch (error) { + throw await toDataSharingError(error); + } + if (result.error) throw await toDataSharingError(result.error); + return result.data as T; +} + +const DISABLED_REASON_TEXT: Record = { + user_paused: "You paused this endpoint.", + subscription_lapsed: + "Paused because your plan no longer includes data sharing. Nothing is sent while it is paused.", + too_many_failures: + "Switched off after repeated failed deliveries. Fix the receiver, then switch it back on.", + endpoint_gone: + "Switched off because the receiver answered 410 Gone. Check the URL, then switch it back on.", +}; + +/** Why an endpoint is not active, in words. */ +export function describeDisabledReason(reason: string | null): string | null { + if (!reason) return null; + return DISABLED_REASON_TEXT[reason] ?? "This endpoint is switched off."; +} + +const DELIVERY_ERROR_TEXT: Record = { + http_error: "The receiver answered with an error status", + redirect_not_followed: + "The receiver answered with a redirect, which is not followed", + timeout: "The receiver did not answer within 10 seconds", + connection_failed: "Could not connect to the receiver", + dns_failed: "The host name could not be resolved", + target_not_allowed: "The URL is no longer an allowed target", + payload_too_large: "The data was too large to send", + subscription_lapsed: "Not sent: your plan no longer includes data sharing", + superseded: "Replaced by a newer delivery for the same item", + scope_removed: "Not sent: this kind of data is no longer selected", + endpoint_inactive: "Not sent: the endpoint was switched off", + not_shareable: "Not sent: this item is not shared", + unknown_entity: "Not sent: this item is not shared", + internal_error: "A problem on our side; it will be retried", +}; + +/** One line for a delivery's outcome, e.g. "The receiver answered with an error status (503)". */ +export function describeDeliveryError( + errorCode: string | null, + statusCode: number | null, +): string | null { + if (!errorCode) return null; + const text = DELIVERY_ERROR_TEXT[errorCode] ?? "Delivery failed"; + return statusCode ? `${text} (${statusCode})` : text; +} + +/** The result of a test delivery, as one sentence. */ +export function describeTestResult(result: WebhookTestResult): string { + if (result.delivered) { + return `The receiver accepted the test delivery (${result.statusCode}).`; + } + return `${describeDeliveryError(result.errorCode, result.statusCode) ?? "The test delivery failed"}.`; +} diff --git a/src/lib/pricing.ts b/src/lib/pricing.ts index c4fe8d54..280a068a 100644 --- a/src/lib/pricing.ts +++ b/src/lib/pricing.ts @@ -48,6 +48,7 @@ export const TIER_PRICING: TierPricing[] = [ "Community hub, routines & cycles", "Analytics, leaderboards, challenges & compare", "Integrations (Strava, Hevy, Liftosaur) & session replay (rep-by-rep)", + "Data sharing: send your own data to an endpoint you choose (webhooks)", ], }, { diff --git a/src/lib/tierMatrix.ts b/src/lib/tierMatrix.ts index 15f32c94..58ac7461 100644 --- a/src/lib/tierMatrix.ts +++ b/src/lib/tierMatrix.ts @@ -18,6 +18,10 @@ type PaidTier = Exclude; * 20260920000900_flame_write_policies.sql), the import RPCs, OAuth start * (initiate-oauth) and the integration sync / rankings Edge Functions. * Routines and cycles pushed from mobile stay EMBER (service-role push). + * Data sharing (outbound webhooks) is FLAME in the `webhook-endpoints` + * Edge Function and again in SQL when deliveries are claimed; it has no + * route of its own (Profile > Settings), and pausing or deleting an + * endpoint is deliberately allowed below FLAME. * - INFERNO: the force-curve and biomechanics DATA — rep_telemetry (and the * telemetry_points view), vbt_assessments, session_phase_statistics and * exercise_signatures — is SELECT-gated in RLS @@ -42,6 +46,7 @@ export const FEATURE_MIN_TIER = { cycles: "FLAME", compare: "FLAME", integrations: "FLAME", + dataSharing: "FLAME", sessionReplay: "FLAME", biomechanics: "INFERNO", } as const satisfies Record; diff --git a/src/mutations/dataSharing.ts b/src/mutations/dataSharing.ts new file mode 100644 index 00000000..93c14f8c --- /dev/null +++ b/src/mutations/dataSharing.ts @@ -0,0 +1,110 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { + DataSharingError, + invokeWebhookEndpoints, + type WebhookEndpoint, + type WebhookEndpointsRequest, + type WebhookTestResult, +} from "@/lib/dataSharing"; +import { isTierDenied, TIER_DENIED_MESSAGE } from "@/lib/tierErrors"; +import { queryKeys } from "@/queries/keys"; + +/** + * Data sharing writes. Each one is a single `webhook-endpoints` action; the + * server derives the user from the session, so nothing here sends a user id + * for it to trust. `userId` is only used to invalidate the right cache keys. + */ + +type CreateInput = Omit< + Extract, + "action" +>; +type UpdateInput = Omit< + Extract, + "action" +>; + +export interface EndpointWithSecret { + endpoint: WebhookEndpoint; + /** Shown once. The server never returns it again. */ + signingSecret: string; +} + +/** The message to show for a failed data sharing action. */ +export function dataSharingErrorMessage(error: unknown): string { + if (isTierDenied(error)) return TIER_DENIED_MESSAGE; + if (error instanceof DataSharingError) return error.message; + return "Data sharing could not be updated. Please try again in a moment."; +} + +function useDataSharingMutation( + userId: string, + mutationFn: (input: TInput) => Promise, +) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn, + // Settled, not only success: a refused resume has still written a test + // delivery to the log, and a failed edit may have applied in part. + onSettled: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.dataSharing.endpoints(userId), + }); + }, + onError: (error) => { + toast.error(dataSharingErrorMessage(error)); + if (isTierDenied(error)) { + // The plan changed under an open page: let the gate catch up. + void queryClient.invalidateQueries({ + queryKey: queryKeys.subscription.all, + }); + } + }, + }); +} + +export function useCreateWebhookEndpoint(userId: string) { + return useDataSharingMutation(userId, (input: CreateInput) => + invokeWebhookEndpoints({ action: "create", ...input }), + ); +} + +export function useUpdateWebhookEndpoint(userId: string) { + return useDataSharingMutation(userId, (input: UpdateInput) => + invokeWebhookEndpoints<{ endpoint: WebhookEndpoint }>({ + action: "update", + ...input, + }), + ); +} + +export function useRotateWebhookSecret(userId: string) { + return useDataSharingMutation(userId, (endpointId: string) => + invokeWebhookEndpoints({ + action: "rotate_secret", + endpointId, + }), + ); +} + +export function useTestWebhookEndpoint(userId: string) { + return useDataSharingMutation(userId, (endpointId: string) => + invokeWebhookEndpoints({ action: "test", endpointId }), + ); +} + +export function useResendWebhookData(userId: string) { + return useDataSharingMutation(userId, (endpointId: string) => + invokeWebhookEndpoints<{ enqueued: number }>({ + action: "resend_all", + endpointId, + }), + ); +} + +export function useDeleteWebhookEndpoint(userId: string) { + return useDataSharingMutation(userId, (endpointId: string) => + invokeWebhookEndpoints<{ deleted: true }>({ action: "delete", endpointId }), + ); +} diff --git a/src/queries/dataSharing.ts b/src/queries/dataSharing.ts new file mode 100644 index 00000000..fb370336 --- /dev/null +++ b/src/queries/dataSharing.ts @@ -0,0 +1,70 @@ +import { queryOptions } from "@tanstack/react-query"; +import type { WebhookEndpoint } from "@/lib/dataSharing"; +import { supabase } from "@/lib/supabase"; +import { queryKeys } from "@/queries/keys"; + +/** + * Data sharing reads. Both tables are read directly under owner RLS (the + * owner may SELECT their own rows and nothing else); every write goes through + * the `webhook-endpoints` Edge Function. `webhook_endpoint_secrets` is not + * readable by any browser role, so there is no query for it. + */ + +const ENDPOINT_COLUMNS = + "id, label, url, scopes, status, disabled_reason, custom_header_name, signing_key_hint, consecutive_failures, last_success_at, last_failure_at, created_at, updated_at"; + +const DELIVERY_COLUMNS = + "id, endpoint_id, entity, entity_id, event_type, status, attempt_count, next_attempt_at, last_status_code, last_error_code, duration_ms, created_at, finished_at"; + +export const WEBHOOK_DELIVERY_LOG_LIMIT = 20; + +export interface WebhookDelivery { + id: string; + endpoint_id: string; + entity: string; + entity_id: string; + event_type: string | null; + status: "pending" | "delivering" | "delivered" | "dead" | "skipped"; + attempt_count: number; + next_attempt_at: string; + last_status_code: number | null; + last_error_code: string | null; + duration_ms: number | null; + created_at: string; + finished_at: string | null; +} + +export function webhookEndpointsOptions(userId: string) { + return queryOptions({ + queryKey: queryKeys.dataSharing.endpoints(userId), + queryFn: async (): Promise => { + const { data, error } = await supabase + .from("webhook_endpoints") + .select(ENDPOINT_COLUMNS) + .eq("user_id", userId) + .order("created_at", { ascending: true }); + if (error) throw error; + return (data ?? []) as WebhookEndpoint[]; + }, + enabled: !!userId, + }); +} + +/** The latest deliveries for one endpoint, newest first. */ +export function webhookDeliveriesOptions(userId: string, endpointId: string) { + return queryOptions({ + queryKey: queryKeys.dataSharing.deliveries(userId, endpointId), + queryFn: async (): Promise => { + const { data, error } = await supabase + .from("webhook_deliveries") + .select(DELIVERY_COLUMNS) + .eq("user_id", userId) + .eq("endpoint_id", endpointId) + .order("created_at", { ascending: false }) + .limit(WEBHOOK_DELIVERY_LOG_LIMIT); + if (error) throw error; + return (data ?? []) as WebhookDelivery[]; + }, + enabled: !!userId && !!endpointId, + }); +} diff --git a/src/queries/keys.ts b/src/queries/keys.ts index 62b70401..42ff2073 100644 --- a/src/queries/keys.ts +++ b/src/queries/keys.ts @@ -153,6 +153,19 @@ export const queryKeys = { syncQueueActive: (userId: string) => [...queryKeys.integrations.syncQueue(userId), "active"] as const, }, + dataSharing: { + all: ["data-sharing"] as const, + endpoints: (userId: string) => + [...queryKeys.dataSharing.all, "endpoints", userId] as const, + // Nested under `endpoints` so one invalidation after any write refreshes + // the endpoint list and every open delivery log. + deliveries: (userId: string, endpointId: string) => + [ + ...queryKeys.dataSharing.endpoints(userId), + "deliveries", + endpointId, + ] as const, + }, comments: { all: ["comments"] as const, byItem: (itemId: string) => [...queryKeys.comments.all, itemId] as const, diff --git a/src/schemas/__tests__/dataSharing.test.ts b/src/schemas/__tests__/dataSharing.test.ts new file mode 100644 index 00000000..74727351 --- /dev/null +++ b/src/schemas/__tests__/dataSharing.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "vitest"; +import { + WEBHOOK_HEADER_VALUE_MAX, + WEBHOOK_LABEL_MAX, + webhookEndpointFormSchema, + webhookFormErrors, +} from "@/schemas/dataSharing"; + +const VALID = { + label: "Home server", + url: "https://hooks.example.com/phoenix", + scopes: ["workouts", "personal_records"], + headerName: "", + headerValue: "", +}; + +function errorsFor(patch: Partial) { + const parsed = webhookEndpointFormSchema.safeParse({ ...VALID, ...patch }); + return parsed.success ? {} : webhookFormErrors(parsed.error); +} + +describe("webhookEndpointFormSchema", () => { + it("accepts a named https endpoint with at least one scope and trims the name", () => { + const parsed = webhookEndpointFormSchema.safeParse({ + ...VALID, + label: " Home server ", + }); + + expect(parsed.success).toBe(true); + expect(parsed.success && parsed.data.label).toBe("Home server"); + }); + + it("requires a name within the length limit", () => { + expect(errorsFor({ label: " " }).label).toBe("Give the endpoint a name."); + expect( + errorsFor({ label: "x".repeat(WEBHOOK_LABEL_MAX + 1) }).label, + ).toMatch(/at most 80/); + }); + + it("refuses URLs that are not https, are malformed or carry credentials", () => { + expect(errorsFor({ url: "" }).url).toBe( + "Enter the URL to send your data to.", + ); + expect(errorsFor({ url: "http://hooks.example.com/in" }).url).toBe( + "The URL must start with https://.", + ); + expect(errorsFor({ url: "hooks.example.com/in" }).url).toBe( + "Enter a valid URL.", + ); + expect(errorsFor({ url: "https://hooks.example.com/a b" }).url).toBe( + "Enter a valid URL.", + ); + expect( + errorsFor({ url: "https://user:pw@hooks.example.com/" }).url, + ).toMatch(/username or password/); + }); + + it("does not second-guess hosts the server decides on", () => { + // Private addresses and own hosts are refused by the server, which can + // resolve the name. The form only checks what it can know. + expect(errorsFor({ url: "https://10.0.0.1/in" })).toEqual({}); + expect(errorsFor({ url: "https://hooks.example.com:8443/in" })).toEqual({}); + }); + + it("requires at least one known scope", () => { + expect(errorsFor({ scopes: [] }).scopes).toBe( + "Choose at least one kind of data to share.", + ); + expect(errorsFor({ scopes: ["telemetry"] }).scopes).toBeDefined(); + }); + + it("treats the custom header as optional, but a name and a value go together", () => { + expect(errorsFor({ headerName: "", headerValue: "" })).toEqual({}); + expect( + errorsFor({ headerName: "Authorization", headerValue: "Bearer abc" }), + ).toEqual({}); + expect( + errorsFor({ headerName: "Authorization", headerValue: "" }).headerValue, + ).toBeDefined(); + expect( + errorsFor({ headerName: "", headerValue: "Bearer abc" }).headerName, + ).toBeDefined(); + }); + + it("refuses header names and values that could not be sent safely", () => { + expect( + errorsFor({ headerName: "bad name", headerValue: "v" }).headerName, + ).toBeDefined(); + expect( + errorsFor({ headerName: "X-Key", headerValue: "a\r\nX-Injected: 1" }) + .headerValue, + ).toBeDefined(); + expect( + errorsFor({ + headerName: "X-Key", + headerValue: "a".repeat(WEBHOOK_HEADER_VALUE_MAX + 1), + }).headerValue, + ).toBeDefined(); + }); +}); diff --git a/src/schemas/dataSharing.ts b/src/schemas/dataSharing.ts new file mode 100644 index 00000000..64aac45d --- /dev/null +++ b/src/schemas/dataSharing.ts @@ -0,0 +1,94 @@ +import { z } from "zod"; +import { DATA_SHARING_SCOPES } from "@/lib/dataSharing"; + +/** + * The data sharing endpoint form. These checks are for instant feedback only: + * `webhook-endpoints` validates again and is the authority. In particular the + * server also resolves the host and refuses private or reserved addresses, + * which the browser cannot check. Keep the rules here no stricter than + * `supabase/functions/_shared/webhookTarget.ts`, or the form would reject a + * URL the server accepts. + */ + +export const WEBHOOK_LABEL_MAX = 80; +export const WEBHOOK_URL_MAX = 2048; +export const WEBHOOK_HEADER_VALUE_MAX = 512; + +const HEADER_NAME = /^[A-Za-z][A-Za-z0-9-]{0,63}$/; +const HEADER_VALUE = /^[\x20-\x7E]+$/; + +function checkUrl(value: string): string | null { + if (/\s/.test(value)) return "Enter a valid URL."; + let url: URL; + try { + url = new URL(value); + } catch { + return "Enter a valid URL."; + } + if (url.protocol !== "https:") return "The URL must start with https://."; + if (url.username !== "" || url.password !== "") { + return "The URL must not contain a username or password. Use the custom header instead."; + } + return null; +} + +export const webhookEndpointFormSchema = z + .object({ + label: z + .string() + .trim() + .min(1, "Give the endpoint a name.") + .max(WEBHOOK_LABEL_MAX, `Use at most ${WEBHOOK_LABEL_MAX} characters.`), + url: z + .string() + .min(1, "Enter the URL to send your data to.") + .max(WEBHOOK_URL_MAX, `Use at most ${WEBHOOK_URL_MAX} characters.`), + scopes: z + .array(z.enum(DATA_SHARING_SCOPES)) + .min(1, "Choose at least one kind of data to share."), + headerName: z.string().trim(), + headerValue: z.string(), + }) + .superRefine((form, ctx) => { + const urlProblem = form.url ? checkUrl(form.url) : null; + if (urlProblem) { + ctx.addIssue({ code: "custom", path: ["url"], message: urlProblem }); + } + // The header is optional, but a name and a value go together. + if (form.headerName === "" && form.headerValue === "") return; + if (!HEADER_NAME.test(form.headerName)) { + ctx.addIssue({ + code: "custom", + path: ["headerName"], + message: + "Use letters, digits and hyphens, starting with a letter (for example Authorization).", + }); + } + if ( + form.headerValue.length === 0 || + form.headerValue.length > WEBHOOK_HEADER_VALUE_MAX || + !HEADER_VALUE.test(form.headerValue) + ) { + ctx.addIssue({ + code: "custom", + path: ["headerValue"], + message: `Enter 1 to ${WEBHOOK_HEADER_VALUE_MAX} printable characters.`, + }); + } + }); + +export type WebhookEndpointFormValues = z.infer< + typeof webhookEndpointFormSchema +>; + +/** The first message per field, for showing beside each input. */ +export function webhookFormErrors( + error: z.ZodError, +): Partial> { + const messages: Partial> = {}; + for (const issue of error.issues) { + const field = issue.path[0] as keyof WebhookEndpointFormValues | undefined; + if (field && !(field in messages)) messages[field] = issue.message; + } + return messages; +} diff --git a/tests/security/edge-function-security.test.ts b/tests/security/edge-function-security.test.ts index 5580bec0..6def2d54 100644 --- a/tests/security/edge-function-security.test.ts +++ b/tests/security/edge-function-security.test.ts @@ -838,6 +838,14 @@ describe("SPA -> Edge _shared import boundary", () => { // re-open the door; it passes every predicate the test below checks. "userDataManifest.ts", "workoutModes.ts", + // Reviewed 2026-11-06 for data sharing: `src/lib/dataSharing.ts` + // re-exports the scope list and its user-facing copy so the settings + // form offers exactly the scopes the server and the table constraint + // accept (parity: tests/security/data-sharing-scopes.test.ts). Pure + // data and two lookup helpers with ZERO import statements; it names + // table names only, no credential and no client. Checked against every + // predicate in the test below. + "dataSharingScopes.ts", ]; function readShared(file: string) {