From 2454a6a671703145956f843969d31db5bc794353 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:07:05 -0500
Subject: [PATCH 01/11] feat(data-sharing): schema, capture triggers and
delivery queue for outbound webhooks
Database half of user-configurable data sharing (FLAME+): a user registers
HTTPS endpoints and the portal pushes their own data there as signed events.
Inert on its own: with no endpoint row every capture trigger returns at once
and the delivery cron job is created inactive.
- webhook_endpoints (owner SELECT, server-written), webhook_endpoint_secrets
(service-only ciphertext) and webhook_deliveries (outbox + log). A composite
FK ties every delivery to its endpoint's owner (FP-1).
- Statement-level capture triggers on every shared table, driven by
private.webhook_entity_sources, so both LWW paths, the push transaction,
portal writes and RPCs are covered by one mechanism. A capture error is a
WARNING, never an aborted sync write (FP-3).
- Service-role RPCs: create/rotate/set-header, a FOR UPDATE SKIP LOCKED claim
that pauses endpoints whose owner dropped below FLAME (FP-2), completion with
backoff and auto-disable (FP-8), and a backfill.
- Not shared: raw telemetry, INFERNO-gated biomechanics, Strava-sourced
activities, community rows, billing and sync bookkeeping. Every manifest
table is classified in _shared/dataSharingScopes.ts and a test fails when a
new one is not.
- Registered in the user-data manifest (secrets EXCLUDED), the RLS isolation
suite and generated types; pgTAP floor raised.
Co-Authored-By: Claude Fable 5.1
---
.github/workflows/migrations.yml | 2 +-
src/lib/database.types.ts | 218 ++++
.../functions/_shared/dataSharingScopes.ts | 324 ++++++
.../functions/_shared/userDataManifest.ts | 50 +
.../20261106120000_webhook_data_sharing.sql | 1003 +++++++++++++++++
.../tests/database/rls_isolation.test.sql | 21 +-
.../database/webhook_data_sharing.test.sql | 800 +++++++++++++
tests/security/data-sharing-scopes.test.ts | 279 +++++
8 files changed, 2695 insertions(+), 2 deletions(-)
create mode 100644 supabase/functions/_shared/dataSharingScopes.ts
create mode 100644 supabase/migrations/20261106120000_webhook_data_sharing.sql
create mode 100644 supabase/tests/database/webhook_data_sharing.test.sql
create mode 100644 tests/security/data-sharing-scopes.test.ts
diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml
index cd250876..9d9a1dad 100644
--- a/.github/workflows/migrations.yml
+++ b/.github/workflows/migrations.yml
@@ -188,7 +188,7 @@ jobs:
env:
# Minimum aggregate Tests= for the suite. Raise this when
# assertions are added.
- PGTAP_TEST_FLOOR: "2059"
+ PGTAP_TEST_FLOOR: "2139"
run: |
set -euo pipefail
log="${RUNNER_TEMP}/pgtap-suite.log"
diff --git a/src/lib/database.types.ts b/src/lib/database.types.ts
index a9f5e15d..d933525f 100644
--- a/src/lib/database.types.ts
+++ b/src/lib/database.types.ts
@@ -2884,6 +2884,160 @@ export type Database = {
};
Relationships: [];
};
+ webhook_deliveries: {
+ Row: {
+ attempt_count: number;
+ claimed_at: string | null;
+ created_at: string;
+ duration_ms: number | null;
+ endpoint_id: string;
+ entity: string;
+ entity_id: string;
+ event_type: string | null;
+ finished_at: string | null;
+ id: string;
+ last_error_code: string | null;
+ last_status_code: number | null;
+ next_attempt_at: string;
+ status: string;
+ user_id: string;
+ };
+ ComputedFields: never;
+ Insert: {
+ attempt_count?: number;
+ claimed_at?: string | null;
+ created_at?: string;
+ duration_ms?: number | null;
+ endpoint_id: string;
+ entity: string;
+ entity_id: string;
+ event_type?: string | null;
+ finished_at?: string | null;
+ id?: string;
+ last_error_code?: string | null;
+ last_status_code?: number | null;
+ next_attempt_at?: string;
+ status?: string;
+ user_id: string;
+ };
+ Update: {
+ attempt_count?: number;
+ claimed_at?: string | null;
+ created_at?: string;
+ duration_ms?: number | null;
+ endpoint_id?: string;
+ entity?: string;
+ entity_id?: string;
+ event_type?: string | null;
+ finished_at?: string | null;
+ id?: string;
+ last_error_code?: string | null;
+ last_status_code?: number | null;
+ next_attempt_at?: string;
+ status?: string;
+ user_id?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "webhook_deliveries_endpoint_fkey";
+ columns: ["endpoint_id", "user_id"];
+ isOneToOne: false;
+ referencedRelation: "webhook_endpoints";
+ referencedColumns: ["id", "user_id"];
+ },
+ ];
+ };
+ webhook_endpoint_secrets: {
+ Row: {
+ custom_header_value_enc: string | null;
+ endpoint_id: string;
+ previous_expires_at: string | null;
+ previous_signing_secret_enc: string | null;
+ signing_secret_enc: string;
+ updated_at: string;
+ user_id: string;
+ };
+ ComputedFields: never;
+ Insert: {
+ custom_header_value_enc?: string | null;
+ endpoint_id: string;
+ previous_expires_at?: string | null;
+ previous_signing_secret_enc?: string | null;
+ signing_secret_enc: string;
+ updated_at?: string;
+ user_id: string;
+ };
+ Update: {
+ custom_header_value_enc?: string | null;
+ endpoint_id?: string;
+ previous_expires_at?: string | null;
+ previous_signing_secret_enc?: string | null;
+ signing_secret_enc?: string;
+ updated_at?: string;
+ user_id?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "webhook_endpoint_secrets_endpoint_fkey";
+ columns: ["endpoint_id", "user_id"];
+ isOneToOne: false;
+ referencedRelation: "webhook_endpoints";
+ referencedColumns: ["id", "user_id"];
+ },
+ ];
+ };
+ webhook_endpoints: {
+ Row: {
+ consecutive_failures: number;
+ created_at: string;
+ custom_header_name: string | null;
+ disabled_reason: string | null;
+ id: string;
+ label: string;
+ last_failure_at: string | null;
+ last_success_at: string | null;
+ scopes: string[];
+ signing_key_hint: string;
+ status: string;
+ updated_at: string;
+ url: string;
+ user_id: string;
+ };
+ ComputedFields: never;
+ Insert: {
+ consecutive_failures?: number;
+ created_at?: string;
+ custom_header_name?: string | null;
+ disabled_reason?: string | null;
+ id?: string;
+ label: string;
+ last_failure_at?: string | null;
+ last_success_at?: string | null;
+ scopes: string[];
+ signing_key_hint: string;
+ status?: string;
+ updated_at?: string;
+ url: string;
+ user_id: string;
+ };
+ Update: {
+ consecutive_failures?: number;
+ created_at?: string;
+ custom_header_name?: string | null;
+ disabled_reason?: string | null;
+ id?: string;
+ label?: string;
+ last_failure_at?: string | null;
+ last_success_at?: string | null;
+ scopes?: string[];
+ signing_key_hint?: string;
+ status?: string;
+ updated_at?: string;
+ url?: string;
+ user_id?: string;
+ };
+ Relationships: [];
+ };
workout_deletion_tombstones: {
Row: {
component_session_id: string | null;
@@ -3220,6 +3374,21 @@ export type Database = {
retry_after_seconds: number;
}[];
};
+ claim_webhook_deliveries: {
+ Args: {
+ p_lease_seconds?: number;
+ p_limit?: number;
+ p_per_endpoint?: number;
+ };
+ Returns: {
+ delivery_attempt: number;
+ delivery_endpoint_id: string;
+ delivery_entity: string;
+ delivery_entity_id: string;
+ delivery_id: string;
+ delivery_user_id: string;
+ }[];
+ };
cleanup_routine_exercise_orphans: {
Args: {
p_keep_ids?: string[];
@@ -3228,6 +3397,19 @@ export type Database = {
};
Returns: number;
};
+ complete_webhook_delivery: {
+ Args: {
+ p_attempt: number;
+ p_delivery_id: string;
+ p_duration_ms?: number;
+ p_error_code?: string;
+ p_event_type?: string;
+ p_outcome: string;
+ p_retry_after_seconds?: number;
+ p_status_code?: number;
+ };
+ Returns: string;
+ };
create_cycle_with_days: {
Args: {
p_days: Json;
@@ -3254,6 +3436,19 @@ export type Database = {
};
Returns: string;
};
+ create_webhook_endpoint: {
+ Args: {
+ p_custom_header_name?: string;
+ p_custom_header_value_enc?: string;
+ p_label: string;
+ p_scopes: string[];
+ p_signing_key_hint: string;
+ p_signing_secret_enc: string;
+ p_url: string;
+ p_user_id: string;
+ };
+ Returns: string;
+ };
delete_cycles_clocked: {
Args: { p_deletions: Json; p_user_id: string };
Returns: {
@@ -3324,6 +3519,10 @@ export type Database = {
Args: { p_provider: string; p_timestamp: string; p_user_id: string };
Returns: undefined;
};
+ enqueue_webhook_backfill: {
+ Args: { p_endpoint_id: string; p_user_id: string };
+ Returns: number;
+ };
exercise_frequency: { Args: { p_profile_id?: string }; Returns: Json };
exercise_names: { Args: { p_profile_id?: string }; Returns: Json };
exercise_progress_series: {
@@ -3945,6 +4144,16 @@ export type Database = {
};
Returns: Json;
};
+ rotate_webhook_signing_secret: {
+ Args: {
+ p_endpoint_id: string;
+ p_overlap_seconds?: number;
+ p_signing_key_hint: string;
+ p_signing_secret_enc: string;
+ p_user_id: string;
+ };
+ Returns: boolean;
+ };
safe_jsonb_int: {
Args: { p_default: number; p_key: string; p_obj: Json };
Returns: number;
@@ -3981,6 +4190,15 @@ export type Database = {
Args: { p_cursor: string };
Returns: undefined;
};
+ set_webhook_endpoint_header: {
+ Args: {
+ p_custom_header_name: string;
+ p_custom_header_value_enc: string;
+ p_endpoint_id: string;
+ p_user_id: string;
+ };
+ Returns: boolean;
+ };
subscription_tier_for: { Args: { p_user_id: string }; Returns: string };
sweep_deleted_account_residue: {
Args: { p_avatar_limit?: number };
diff --git a/supabase/functions/_shared/dataSharingScopes.ts b/supabase/functions/_shared/dataSharingScopes.ts
new file mode 100644
index 00000000..4f2b4b46
--- /dev/null
+++ b/supabase/functions/_shared/dataSharingScopes.ts
@@ -0,0 +1,324 @@
+/**
+ * Data sharing (outbound webhooks): what a user may send to an endpoint of
+ * their choosing, and what never leaves that way.
+ *
+ * Pure data with no imports, so the SPA can read the scope list for its
+ * settings form and the Edge worker can read the entity shapes for its
+ * payload builder from the same place.
+ *
+ * Three things must agree, and tests/security/data-sharing-scopes.test.ts
+ * fails when they do not:
+ * - this file;
+ * - private.webhook_entity_sources in
+ * supabase/migrations/20261106120000_webhook_data_sharing.sql, which
+ * drives the capture triggers and the backfill;
+ * - USER_DATA_MANIFEST (userDataManifest.ts): every manifest table is either
+ * part of an entity here or listed in NOT_SHAREABLE with a reason, so a
+ * new user table forces a decision instead of defaulting either way.
+ *
+ * Payload fields are the manifest's column lists. The manifest test that
+ * forbids credential-like column names therefore guards webhook payloads too.
+ */
+
+export const DATA_SHARING_SCOPES = [
+ "workouts",
+ "personal_records",
+ "routines",
+ "cycles",
+ "goals",
+ "progress",
+ "achievements",
+ "external_activities",
+ "profile",
+] as const;
+
+export type DataSharingScope = (typeof DATA_SHARING_SCOPES)[number];
+
+/** The tier that unlocks data sharing. Enforced server-side (FP-2). */
+export const DATA_SHARING_MIN_TIER = "FLAME" as const;
+
+/** Endpoints one user may register. Mirrors create_webhook_endpoint. */
+export const MAX_WEBHOOK_ENDPOINTS = 3;
+
+export interface DataSharingScopeInfo {
+ scope: DataSharingScope;
+ label: string;
+ description: string;
+}
+
+/** User-facing copy for the settings form, in display order. */
+export const DATA_SHARING_SCOPE_INFO: readonly DataSharingScopeInfo[] = [
+ {
+ scope: "workouts",
+ label: "Workouts",
+ description:
+ "Sessions with their exercises, sets and rep summaries. Loads are per cable, as on the phone. Raw force-curve telemetry is not included.",
+ },
+ {
+ scope: "personal_records",
+ label: "Personal records",
+ description: "Max weight, max volume and 1RM records, including deletions.",
+ },
+ {
+ scope: "routines",
+ label: "Routines",
+ description: "Routine definitions and their exercises, including deletions.",
+ },
+ {
+ scope: "cycles",
+ label: "Training cycles",
+ description: "Cycle definitions and their days, including deletions.",
+ },
+ {
+ scope: "goals",
+ label: "Goals",
+ description: "Your goals and their status.",
+ },
+ {
+ scope: "progress",
+ label: "Exercise progress",
+ description:
+ "Per-session progress snapshots for each exercise, including the estimated 1RM.",
+ },
+ {
+ scope: "achievements",
+ label: "Achievements",
+ description: "Earned badges, lifetime stats and RPG attributes.",
+ },
+ {
+ scope: "external_activities",
+ label: "Imported activities",
+ description:
+ "Activities imported from connected apps. Activities imported from Strava are not shared.",
+ },
+ {
+ scope: "profile",
+ label: "Profile",
+ description: "Display name, units and preferences, and your local profiles.",
+ },
+];
+
+/**
+ * A table whose rows travel inside the parent entity's payload. `parent` is
+ * the entity's own table or another child, `fkColumn` the child column that
+ * holds that parent's `id`.
+ */
+export interface DataSharingChild {
+ table: string;
+ parent: string;
+ fkColumn: string;
+}
+
+export interface DataSharingEntity {
+ /** Name in the event type: `.updated` / `.deleted`. */
+ entity: string;
+ scope: DataSharingScope;
+ table: string;
+ idColumn: string;
+ /** Column holding the owner. Every read filters on it. */
+ userColumn: string;
+ /** A row with this column set is reported as deleted. */
+ softDeleteColumn?: string;
+ /** A row whose column equals the value is never shared. */
+ exclude?: { column: string; equals: string; reason: string };
+ children: readonly DataSharingChild[];
+}
+
+export const DATA_SHARING_ENTITIES: readonly DataSharingEntity[] = [
+ {
+ entity: "workout",
+ scope: "workouts",
+ table: "workout_sessions",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [
+ { table: "exercises", parent: "workout_sessions", fkColumn: "session_id" },
+ { table: "sets", parent: "exercises", fkColumn: "exercise_id" },
+ { table: "rep_summaries", parent: "sets", fkColumn: "set_id" },
+ ],
+ },
+ {
+ entity: "personal_record",
+ scope: "personal_records",
+ table: "personal_records",
+ idColumn: "id",
+ userColumn: "user_id",
+ softDeleteColumn: "deleted_at",
+ children: [],
+ },
+ {
+ entity: "routine",
+ scope: "routines",
+ table: "routines",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [
+ { table: "routine_exercises", parent: "routines", fkColumn: "routine_id" },
+ ],
+ },
+ {
+ entity: "cycle",
+ scope: "cycles",
+ table: "training_cycles",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [
+ { table: "cycle_days", parent: "training_cycles", fkColumn: "cycle_id" },
+ ],
+ },
+ {
+ entity: "goal",
+ scope: "goals",
+ table: "user_goals",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [],
+ },
+ {
+ entity: "exercise_progress",
+ scope: "progress",
+ table: "exercise_progress",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [],
+ },
+ {
+ entity: "badge",
+ scope: "achievements",
+ table: "earned_badges",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [],
+ },
+ {
+ entity: "gamification_stats",
+ scope: "achievements",
+ table: "gamification_stats",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [],
+ },
+ {
+ entity: "rpg_attributes",
+ scope: "achievements",
+ table: "rpg_attributes",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [],
+ },
+ {
+ entity: "external_activity",
+ scope: "external_activities",
+ table: "external_activities",
+ idColumn: "id",
+ userColumn: "user_id",
+ exclude: {
+ column: "provider",
+ equals: "strava",
+ reason:
+ "Strava's API terms restrict onward disclosure of Strava data to third parties.",
+ },
+ children: [],
+ },
+ {
+ entity: "profile",
+ scope: "profile",
+ table: "profiles",
+ idColumn: "id",
+ // profiles.id is the auth user id.
+ userColumn: "id",
+ children: [],
+ },
+ {
+ entity: "local_profile",
+ scope: "profile",
+ table: "local_profiles",
+ idColumn: "id",
+ userColumn: "user_id",
+ children: [],
+ },
+];
+
+/** Columns never copied into a payload, whatever the manifest lists. */
+export const DATA_SHARING_OMITTED_COLUMNS: Readonly> = {
+ // The user's own Stripe/Paddle customer id is in the GDPR export on
+ // purpose (R-13), but a third-party endpoint has no use for it.
+ profiles: ["stripe_customer_id", "feature_flags", "digest_last_sent_at"],
+};
+
+/**
+ * Manifest tables that are deliberately not shared. Each entry says why, so
+ * the decision is reviewable. Anything new in USER_DATA_MANIFEST must be added
+ * either to an entity above or here.
+ */
+export const NOT_SHAREABLE: Readonly> = {
+ // Size and tier
+ rep_telemetry:
+ "Raw force-curve samples: megabytes per session, and INFERNO-gated for reads.",
+ session_phase_statistics:
+ "INFERNO-gated biomechanics; a FLAME endpoint must not carry data its owner cannot read in the portal.",
+ vbt_assessments:
+ "INFERNO-gated biomechanics; a FLAME endpoint must not carry data its owner cannot read in the portal.",
+ exercise_signatures:
+ "INFERNO-gated biomechanics; a FLAME endpoint must not carry data its owner cannot read in the portal.",
+ telemetry_analysis: "Derived from raw telemetry; prod-only table.",
+ // Account, billing and consent state
+ subscriptions: "Billing state, not training data.",
+ subscription_events: "Billing audit trail.",
+ deletion_requests: "Account lifecycle state.",
+ user_onboarding: "Portal onboarding state.",
+ local_profile_preferences:
+ "Device settings (LED, rack, VBT preferences); not training data.",
+ // Sync bookkeeping
+ profile_ownership_claims: "Internal sync bookkeeping.",
+ profile_ownership_events: "Internal sync bookkeeping.",
+ profile_ownership_transfers: "Internal sync bookkeeping.",
+ training_cycle_deletion_tombstones:
+ "Internal sync bookkeeping; deletions are sent as cycle.deleted events.",
+ workout_deletion_tombstones:
+ "Internal sync bookkeeping; deletions are sent as workout.deleted events.",
+ sync_tombstones:
+ "Internal sync bookkeeping; deletions are sent as .deleted events.",
+ sync_queue: "Internal provider-sync queue.",
+ user_integrations: "Connection metadata for other providers.",
+ // Derived or regenerated wholesale
+ user_insights:
+ "Regenerated wholesale every 15 minutes; every pass would re-send every insight.",
+ leaderboard_snapshots:
+ "Rebuilt every 15 minutes; ranks are relative to other users.",
+ goal_snapshots: "Prod-only derived table.",
+ overload_suggestions: "Prod-only derived table.",
+ wearable_daily_summaries: "Prod-only table; provider terms not reviewed.",
+ exercise_catalog:
+ "Custom exercise definitions; not in the first version (no change stream requested).",
+ // Community: rows that reference other users or are already public
+ shared_routines: "Already published to the community.",
+ shared_cycles: "Already published to the community.",
+ community_comments: "Community content; references other users' items.",
+ community_votes: "References other users' items.",
+ saved_community_items: "References other users' items.",
+ challenge_participants: "Community participation state.",
+ creator_follows: "References other users.",
+ user_blocks: "References other users.",
+ content_reports: "References other users.",
+ // This feature's own tables
+ webhook_endpoints: "The sharing configuration itself.",
+ webhook_deliveries: "The delivery log itself.",
+};
+
+const ENTITY_BY_NAME: ReadonlyMap = new Map(
+ DATA_SHARING_ENTITIES.map((entry) => [entry.entity, entry]),
+);
+
+export function getDataSharingEntity(
+ entity: string,
+): DataSharingEntity | undefined {
+ return ENTITY_BY_NAME.get(entity);
+}
+
+export function isDataSharingScope(value: unknown): value is DataSharingScope {
+ return (
+ typeof value === "string" &&
+ (DATA_SHARING_SCOPES as readonly string[]).includes(value)
+ );
+}
diff --git a/supabase/functions/_shared/userDataManifest.ts b/supabase/functions/_shared/userDataManifest.ts
index bf1844ec..04e12958 100644
--- a/supabase/functions/_shared/userDataManifest.ts
+++ b/supabase/functions/_shared/userDataManifest.ts
@@ -1031,6 +1031,50 @@ export const USER_DATA_MANIFEST: readonly UserDataTable[] = [
"retry_count",
"error_message",
]),
+ // Data sharing (20261106120000): the endpoints the user registered and the
+ // delivery log. Both cascade from auth.users, the log through its composite
+ // FK to webhook_endpoints. The signing key and custom header value live in
+ // webhook_endpoint_secrets (EXCLUDED).
+ owned(
+ "webhook_endpoints",
+ "cascade",
+ [
+ "id",
+ "user_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",
+ ],
+ {
+ note: "Endpoint metadata only; signing_key_hint is the last characters of the key, shown so two endpoints can be told apart.",
+ },
+ ),
+ owned("webhook_deliveries", "cascade", [
+ "id",
+ "endpoint_id",
+ "user_id",
+ "entity",
+ "entity_id",
+ "event_type",
+ "status",
+ "attempt_count",
+ "next_attempt_at",
+ "claimed_at",
+ "last_status_code",
+ "last_error_code",
+ "duration_ms",
+ "created_at",
+ "finished_at",
+ ]),
];
/**
@@ -1074,6 +1118,12 @@ export const EXCLUDED: readonly ExcludedUserDataTable[] = [
purge: "cascade",
purgeMatch: { column: "user_id" },
},
+ {
+ table: "webhook_endpoint_secrets",
+ reason: "Webhook signing keys and custom header values are credentials, not user content; endpoint metadata is exported via webhook_endpoints.",
+ purge: "cascade",
+ purgeMatch: { column: "user_id" },
+ },
{
table: "oauth_states",
reason: "Short-lived OAuth CSRF state rows; transient operational data.",
diff --git a/supabase/migrations/20261106120000_webhook_data_sharing.sql b/supabase/migrations/20261106120000_webhook_data_sharing.sql
new file mode 100644
index 00000000..5be8e046
--- /dev/null
+++ b/supabase/migrations/20261106120000_webhook_data_sharing.sql
@@ -0,0 +1,1003 @@
+-- User-configurable data sharing: outbound webhooks (FLAME and above).
+--
+-- A user registers HTTPS endpoints they control and the portal POSTs their own
+-- data there as signed JSON events. This migration is the database half and is
+-- inert on its own: with no row in webhook_endpoints every capture trigger
+-- returns at once and the delivery job is created INACTIVE.
+--
+-- 1. public.webhook_endpoints: browser-readable endpoint metadata. Owner
+-- SELECT only; every write goes through the `webhook-endpoints` Edge
+-- Function with the service role (URL validation, secret generation and
+-- the tier gate cannot be done under RLS).
+-- 2. public.webhook_endpoint_secrets: service-only. The signing secret and
+-- the optional custom header value, AES-GCM ciphertext written by the
+-- Edge Function (`enc:v1:`, _shared/oauthTokenCrypto.ts). The same split
+-- as user_integrations / oauth_tokens: no browser role can read it.
+-- 3. public.webhook_deliveries: the outbox and the delivery log. A row is a
+-- thin reference (endpoint, entity, entity id), never a copy of user
+-- data; the worker builds the payload from the current row at send time.
+-- The composite FK (endpoint_id, user_id) -> webhook_endpoints
+-- (id, user_id) makes it impossible to pair one user's entity with
+-- another user's endpoint (FP-1).
+-- 4. private.webhook_entity_sources: which table feeds which entity and
+-- scope. It drives the capture triggers and the backfill, so the two
+-- cannot drift. supabase/functions/_shared/dataSharingScopes.ts mirrors
+-- it for the payload builder (parity: tests/security/data-sharing-scopes.test.ts).
+-- 5. private.enqueue_webhook_deliveries(): statement-level capture trigger
+-- on every source table. Triggers, not a hook in mobile-sync-push, so
+-- both SYNC_LWW_ENABLED paths, the push transaction, portal PostgREST
+-- writes and RPCs are all covered by one mechanism. An enqueue error is
+-- downgraded to a WARNING: a webhook must never abort a sync write
+-- (FP-3); "Resend all" (enqueue_webhook_backfill) is the recovery path.
+-- 6. Service-role RPCs: create_webhook_endpoint,
+-- rotate_webhook_signing_secret, set_webhook_endpoint_header,
+-- claim_webhook_deliveries (FOR UPDATE SKIP LOCKED),
+-- complete_webhook_delivery, enqueue_webhook_backfill.
+-- 7. pg_cron: `deliver-webhooks` every minute through
+-- private.invoke_edge_function, created INACTIVE (the Edge Function does
+-- not exist yet), and a daily retention job.
+--
+-- Not shared, by design: raw telemetry, the INFERNO-gated biomechanics tables
+-- (session_phase_statistics, vbt_assessments, exercise_signatures: a FLAME
+-- webhook must not carry data its owner cannot read in the portal, FP-2),
+-- Strava-sourced external activities, community rows, billing and internal
+-- sync state. See dataSharingScopes.ts.
+--
+-- Idempotent: safe to re-run. Re-applying never flips a cron job's `active`
+-- flag and re-issues every grant.
+--
+-- Operator, after the `deliver-webhooks` Edge Function is deployed:
+-- SELECT cron.alter_job(
+-- (SELECT jobid FROM cron.job WHERE jobname = 'deliver-webhooks'),
+-- active := true);
+-- Setting active := false again is the kill switch for all deliveries.
+
+BEGIN;
+
+SET LOCAL lock_timeout = '5s';
+
+CREATE SCHEMA IF NOT EXISTS private;
+REVOKE ALL ON SCHEMA private FROM PUBLIC, anon, authenticated;
+
+-- ---------------------------------------------------------------------------
+-- 1. Endpoint metadata (browser-readable, server-written).
+-- ---------------------------------------------------------------------------
+CREATE TABLE IF NOT EXISTS public.webhook_endpoints (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
+ label text NOT NULL
+ CONSTRAINT webhook_endpoints_label_check
+ CHECK (char_length(label) BETWEEN 1 AND 80),
+ url text NOT NULL
+ CONSTRAINT webhook_endpoints_url_check
+ CHECK (char_length(url) <= 2048 AND url ~ '^https://[^[:space:]]+$'),
+ scopes text[] NOT NULL
+ CONSTRAINT webhook_endpoints_scopes_check
+ CHECK (
+ cardinality(scopes) BETWEEN 1 AND 9
+ AND scopes <@ ARRAY[
+ 'workouts', 'personal_records', 'routines', 'cycles', 'goals',
+ 'progress', 'achievements', 'external_activities', 'profile'
+ ]::text[]
+ ),
+ status text NOT NULL DEFAULT 'active'
+ CONSTRAINT webhook_endpoints_status_check
+ CHECK (status IN ('active', 'paused', 'disabled')),
+ -- Why the endpoint is not active. Fixed codes only: the browser reads this.
+ disabled_reason text
+ CONSTRAINT webhook_endpoints_disabled_reason_check
+ CHECK (disabled_reason IN (
+ 'user_paused', 'subscription_lapsed', 'too_many_failures', 'endpoint_gone'
+ )),
+ custom_header_name text
+ CONSTRAINT webhook_endpoints_custom_header_name_check
+ CHECK (custom_header_name ~ '^[A-Za-z][A-Za-z0-9-]{0,63}$'),
+ -- Last characters of the signing secret, so the user can tell two apart.
+ signing_key_hint text NOT NULL
+ CONSTRAINT webhook_endpoints_signing_key_hint_check
+ CHECK (char_length(signing_key_hint) BETWEEN 1 AND 8),
+ consecutive_failures integer NOT NULL DEFAULT 0,
+ last_success_at timestamptz,
+ last_failure_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ CONSTRAINT webhook_endpoints_id_user_key UNIQUE (id, user_id),
+ CONSTRAINT webhook_endpoints_reason_matches_status
+ CHECK ((status = 'active') = (disabled_reason IS NULL))
+);
+
+CREATE INDEX IF NOT EXISTS webhook_endpoints_user_idx
+ ON public.webhook_endpoints (user_id);
+
+DROP TRIGGER IF EXISTS webhook_endpoints_updated_at ON public.webhook_endpoints;
+CREATE TRIGGER webhook_endpoints_updated_at
+ BEFORE UPDATE ON public.webhook_endpoints
+ FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
+
+ALTER TABLE public.webhook_endpoints ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "Users can view own webhook endpoints" ON public.webhook_endpoints;
+CREATE POLICY "Users can view own webhook endpoints" ON public.webhook_endpoints
+ FOR SELECT TO authenticated
+ USING ((SELECT auth.uid()) = user_id);
+
+-- TRUNCATE is not subject to RLS, so revoke every browser-role privilege
+-- except SELECT.
+REVOKE ALL ON TABLE public.webhook_endpoints FROM PUBLIC, anon, authenticated;
+GRANT SELECT ON TABLE public.webhook_endpoints TO authenticated;
+GRANT ALL ON TABLE public.webhook_endpoints TO service_role;
+
+COMMENT ON TABLE public.webhook_endpoints IS
+ 'User-registered outbound webhook endpoints (data sharing, FLAME+). Owner SELECT; written only by the webhook-endpoints Edge Function. 20261106120000.';
+
+-- ---------------------------------------------------------------------------
+-- 2. Endpoint secrets (service-only).
+-- ---------------------------------------------------------------------------
+CREATE TABLE IF NOT EXISTS public.webhook_endpoint_secrets (
+ endpoint_id uuid PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
+ signing_secret_enc text NOT NULL,
+ -- The secret replaced by the last rotation, still signed with until
+ -- previous_expires_at so a receiver can switch over without dropping events.
+ previous_signing_secret_enc text,
+ previous_expires_at timestamptz,
+ custom_header_value_enc text,
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ CONSTRAINT webhook_endpoint_secrets_endpoint_fkey
+ FOREIGN KEY (endpoint_id, user_id)
+ REFERENCES public.webhook_endpoints (id, user_id) ON DELETE CASCADE
+);
+
+ALTER TABLE public.webhook_endpoint_secrets ENABLE ROW LEVEL SECURITY;
+REVOKE ALL ON TABLE public.webhook_endpoint_secrets FROM PUBLIC, anon, authenticated;
+GRANT ALL ON TABLE public.webhook_endpoint_secrets TO service_role;
+
+COMMENT ON TABLE public.webhook_endpoint_secrets IS
+ 'Signing secrets and custom header values for webhook_endpoints, as enc:v1: AES-GCM ciphertext. Service role only; no browser policy or grant. 20261106120000.';
+
+-- ---------------------------------------------------------------------------
+-- 3. Outbox and delivery log.
+-- ---------------------------------------------------------------------------
+CREATE TABLE IF NOT EXISTS public.webhook_deliveries (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ endpoint_id uuid NOT NULL,
+ user_id uuid NOT NULL,
+ entity text NOT NULL
+ CONSTRAINT webhook_deliveries_entity_check
+ CHECK (entity IN (
+ 'workout', 'personal_record', 'routine', 'cycle', 'goal',
+ 'exercise_progress', 'badge', 'gamification_stats',
+ 'rpg_attributes', 'external_activity', 'profile', 'local_profile', 'ping'
+ )),
+ entity_id text NOT NULL
+ CONSTRAINT webhook_deliveries_entity_id_check
+ CHECK (char_length(entity_id) BETWEEN 1 AND 200),
+ -- Resolved by the worker at send time: '.updated' / '.deleted'.
+ event_type text,
+ status text NOT NULL DEFAULT 'pending'
+ CONSTRAINT webhook_deliveries_status_check
+ CHECK (status IN ('pending', 'delivering', 'delivered', 'dead', 'skipped')),
+ attempt_count integer NOT NULL DEFAULT 0,
+ next_attempt_at timestamptz NOT NULL DEFAULT now(),
+ claimed_at timestamptz,
+ last_status_code integer,
+ -- A fixed code, never a provider message: the owner reads this through RLS.
+ last_error_code text
+ CONSTRAINT webhook_deliveries_error_code_check
+ CHECK (last_error_code ~ '^[a-z0-9_]{1,64}$'),
+ duration_ms integer,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ finished_at timestamptz,
+ CONSTRAINT webhook_deliveries_endpoint_fkey
+ FOREIGN KEY (endpoint_id, user_id)
+ REFERENCES public.webhook_endpoints (id, user_id) ON DELETE CASCADE
+);
+
+-- Coalescing: at most one pending delivery per endpoint and entity. A second
+-- change while one is waiting is a no-op, because the worker sends the
+-- current row anyway.
+CREATE UNIQUE INDEX IF NOT EXISTS webhook_deliveries_one_pending
+ ON public.webhook_deliveries (endpoint_id, entity, entity_id)
+ WHERE status = 'pending';
+
+-- The claim.
+CREATE INDEX IF NOT EXISTS webhook_deliveries_due_idx
+ ON public.webhook_deliveries (next_attempt_at)
+ WHERE status IN ('pending', 'delivering');
+
+-- The owner's delivery-log read and the ON DELETE CASCADE lookup.
+CREATE INDEX IF NOT EXISTS webhook_deliveries_endpoint_created_idx
+ ON public.webhook_deliveries (endpoint_id, created_at DESC);
+
+CREATE INDEX IF NOT EXISTS webhook_deliveries_user_idx
+ ON public.webhook_deliveries (user_id);
+
+ALTER TABLE public.webhook_deliveries ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "Users can view own webhook deliveries" ON public.webhook_deliveries;
+CREATE POLICY "Users can view own webhook deliveries" ON public.webhook_deliveries
+ FOR SELECT TO authenticated
+ USING ((SELECT auth.uid()) = user_id);
+
+REVOKE ALL ON TABLE public.webhook_deliveries FROM PUBLIC, anon, authenticated;
+GRANT SELECT ON TABLE public.webhook_deliveries TO authenticated;
+GRANT ALL ON TABLE public.webhook_deliveries TO service_role;
+
+COMMENT ON TABLE public.webhook_deliveries IS
+ 'Outbox and delivery log for webhook_endpoints. Thin references only; payloads are built at send time. Owner SELECT; written by capture triggers and the service role. 20261106120000.';
+
+-- ---------------------------------------------------------------------------
+-- 4. Entity sources: which table feeds which entity and scope.
+-- ---------------------------------------------------------------------------
+CREATE TABLE IF NOT EXISTS private.webhook_entity_sources (
+ source_table text PRIMARY KEY,
+ scope text NOT NULL,
+ entity text NOT NULL,
+ -- true: the entity's own table. false: a child whose change means "the
+ -- parent entity changed".
+ is_root boolean NOT NULL,
+ -- Column of source_table holding the entity id.
+ id_column text NOT NULL,
+ -- Column of source_table holding the owner; NULL when the owner is only on
+ -- the parent (then parent_table.user_id via id_column -> parent_table.id).
+ user_column text,
+ parent_table text,
+ -- Optional predicate over alias `c` (the changed / scanned rows).
+ row_filter text,
+ -- Extra predicate for the backfill only (alias `c`).
+ backfill_filter text,
+ CONSTRAINT webhook_entity_sources_owner_check
+ CHECK ((user_column IS NULL) <> (parent_table IS NULL))
+);
+
+ALTER TABLE private.webhook_entity_sources ENABLE ROW LEVEL SECURITY;
+REVOKE ALL ON TABLE private.webhook_entity_sources
+ FROM PUBLIC, anon, authenticated, service_role;
+
+INSERT INTO private.webhook_entity_sources
+ (source_table, scope, entity, is_root, id_column, user_column, parent_table,
+ row_filter, backfill_filter)
+VALUES
+ ('workout_sessions', 'workouts', 'workout', true, 'id', 'user_id', NULL, NULL, NULL),
+ -- replace_session_children rewrites the children without touching the
+ -- parent row, so the session trigger alone would miss it.
+ ('exercises', 'workouts', 'workout', false, 'session_id', 'user_id', NULL, NULL, NULL),
+ -- Soft-deleted records are sent as personal_record.deleted when the delete
+ -- happens; a backfill does not replay old deletions.
+ ('personal_records', 'personal_records', 'personal_record', true, 'id', 'user_id', NULL, NULL, 'c.deleted_at IS NULL'),
+ ('routines', 'routines', 'routine', true, 'id', 'user_id', NULL, NULL, NULL),
+ ('routine_exercises', 'routines', 'routine', false, 'routine_id', NULL, 'routines', NULL, NULL),
+ ('training_cycles', 'cycles', 'cycle', true, 'id', 'user_id', NULL, NULL, NULL),
+ ('cycle_days', 'cycles', 'cycle', false, 'cycle_id', NULL, 'training_cycles', NULL, NULL),
+ ('user_goals', 'goals', 'goal', true, 'id', 'user_id', NULL, NULL, NULL),
+ ('exercise_progress', 'progress', 'exercise_progress', true, 'id', 'user_id', NULL, NULL, NULL),
+ ('earned_badges', 'achievements', 'badge', true, 'id', 'user_id', NULL, NULL, NULL),
+ ('gamification_stats', 'achievements', 'gamification_stats', true, 'id', 'user_id', NULL, NULL, NULL),
+ ('rpg_attributes', 'achievements', 'rpg_attributes', true, 'id', 'user_id', NULL, NULL, NULL),
+ -- Strava's API terms restrict onward disclosure of Strava data, so those
+ -- rows never leave through a webhook.
+ ('external_activities', 'external_activities', 'external_activity', true, 'id', 'user_id', NULL, 'c.provider IS DISTINCT FROM ''strava''', NULL),
+ -- profiles.id is the auth user id.
+ ('profiles', 'profile', 'profile', true, 'id', 'id', NULL, NULL, NULL),
+ ('local_profiles', 'profile', 'local_profile', true, 'id', 'user_id', NULL, NULL, NULL)
+ON CONFLICT (source_table) DO UPDATE SET
+ scope = EXCLUDED.scope,
+ entity = EXCLUDED.entity,
+ is_root = EXCLUDED.is_root,
+ id_column = EXCLUDED.id_column,
+ user_column = EXCLUDED.user_column,
+ parent_table = EXCLUDED.parent_table,
+ row_filter = EXCLUDED.row_filter,
+ backfill_filter = EXCLUDED.backfill_filter;
+
+-- ---------------------------------------------------------------------------
+-- 5. Capture trigger.
+-- TG_ARGV: scope, entity, id column, user column ('' = via parent),
+-- parent table ('' = none), row filter ('' = none). The arguments are
+-- literals written by this migration from the table above, never user input.
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION private.enqueue_webhook_deliveries()
+RETURNS trigger
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = ''
+AS $fn$
+DECLARE
+ c_scope CONSTANT text := TG_ARGV[0];
+ c_entity CONSTANT text := TG_ARGV[1];
+ c_id_column CONSTANT text := TG_ARGV[2];
+ c_user_column CONSTANT text := NULLIF(TG_ARGV[3], '');
+ c_parent_table CONSTANT text := NULLIF(TG_ARGV[4], '');
+ c_row_filter CONSTANT text := NULLIF(TG_ARGV[5], '');
+ v_sql text;
+BEGIN
+ -- Nobody shares this scope: cost one indexed probe and leave.
+ IF NOT EXISTS (
+ SELECT 1 FROM public.webhook_endpoints e
+ WHERE e.status = 'active' AND c_scope = ANY (e.scopes)
+ ) THEN
+ RETURN NULL;
+ END IF;
+
+ -- A webhook must never abort the user's write (FP-3): anything that goes
+ -- wrong below is logged and dropped. enqueue_webhook_backfill recovers.
+ BEGIN
+ v_sql :=
+ 'INSERT INTO public.webhook_deliveries '
+ || '(endpoint_id, user_id, entity, entity_id, next_attempt_at) '
+ || 'SELECT DISTINCT e.id, e.user_id, $1, '
+ || pg_catalog.format('c.%I::text', c_id_column)
+ -- 20 s for a multi-statement write (parent, then children) to settle.
+ || ', pg_catalog.now() + interval ''20 seconds'' FROM changed_rows c ';
+
+ IF c_user_column IS NOT NULL THEN
+ v_sql := v_sql || pg_catalog.format(
+ 'JOIN public.webhook_endpoints e ON e.user_id = c.%I ', c_user_column);
+ ELSE
+ v_sql := v_sql || pg_catalog.format(
+ 'JOIN public.%I p ON p.id = c.%I '
+ || 'JOIN public.webhook_endpoints e ON e.user_id = p.user_id ',
+ c_parent_table, c_id_column);
+ END IF;
+
+ v_sql := v_sql
+ || 'WHERE e.status = ''active'' AND $2 = ANY (e.scopes) '
+ || pg_catalog.format('AND c.%I IS NOT NULL ', c_id_column);
+
+ IF c_row_filter IS NOT NULL THEN
+ v_sql := v_sql || 'AND (' || c_row_filter || ') ';
+ END IF;
+
+ v_sql := v_sql
+ || 'ON CONFLICT (endpoint_id, entity, entity_id) '
+ || 'WHERE status = ''pending'' DO NOTHING';
+
+ EXECUTE v_sql USING c_entity, c_scope;
+ EXCEPTION WHEN OTHERS THEN
+ RAISE WARNING 'webhook capture failed on %.% (%): %',
+ TG_TABLE_SCHEMA, TG_TABLE_NAME, SQLSTATE, SQLERRM;
+ END;
+
+ RETURN NULL;
+END
+$fn$;
+
+REVOKE ALL ON FUNCTION private.enqueue_webhook_deliveries()
+ FROM PUBLIC, anon, authenticated, service_role;
+
+-- One trigger per event: a transition table belongs to a single event.
+DO $$
+DECLARE
+ s record;
+ v_args text;
+BEGIN
+ FOR s IN SELECT * FROM private.webhook_entity_sources ORDER BY source_table LOOP
+ IF pg_catalog.to_regclass(pg_catalog.format('public.%I', s.source_table)) IS NULL THEN
+ RAISE NOTICE 'webhook capture: public.% does not exist; skipped', s.source_table;
+ CONTINUE;
+ END IF;
+
+ v_args := pg_catalog.format('%L, %L, %L, %L, %L, %L',
+ s.scope, s.entity, s.id_column, COALESCE(s.user_column, ''),
+ COALESCE(s.parent_table, ''), COALESCE(s.row_filter, ''));
+
+ EXECUTE pg_catalog.format(
+ 'DROP TRIGGER IF EXISTS webhook_capture_insert ON public.%I', s.source_table);
+ EXECUTE pg_catalog.format(
+ 'CREATE TRIGGER webhook_capture_insert AFTER INSERT ON public.%I '
+ || 'REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT '
+ || 'EXECUTE FUNCTION private.enqueue_webhook_deliveries(%s)',
+ s.source_table, v_args);
+
+ EXECUTE pg_catalog.format(
+ 'DROP TRIGGER IF EXISTS webhook_capture_update ON public.%I', s.source_table);
+ EXECUTE pg_catalog.format(
+ 'CREATE TRIGGER webhook_capture_update AFTER UPDATE ON public.%I '
+ || 'REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT '
+ || 'EXECUTE FUNCTION private.enqueue_webhook_deliveries(%s)',
+ s.source_table, v_args);
+
+ EXECUTE pg_catalog.format(
+ 'DROP TRIGGER IF EXISTS webhook_capture_delete ON public.%I', s.source_table);
+ EXECUTE pg_catalog.format(
+ 'CREATE TRIGGER webhook_capture_delete AFTER DELETE ON public.%I '
+ || 'REFERENCING OLD TABLE AS changed_rows FOR EACH STATEMENT '
+ || 'EXECUTE FUNCTION private.enqueue_webhook_deliveries(%s)',
+ s.source_table, v_args);
+ END LOOP;
+END
+$$;
+
+-- ---------------------------------------------------------------------------
+-- 6. Endpoint writers. Service role only; SECURITY INVOKER (the service role
+-- already owns every privilege they need).
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.create_webhook_endpoint(
+ p_user_id uuid,
+ p_label text,
+ p_url text,
+ p_scopes text[],
+ p_signing_secret_enc text,
+ p_signing_key_hint text,
+ p_custom_header_name text DEFAULT NULL,
+ p_custom_header_value_enc text DEFAULT NULL
+)
+RETURNS uuid
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = ''
+AS $$
+DECLARE
+ c_max_endpoints CONSTANT integer := 3;
+ v_id uuid;
+BEGIN
+ IF p_user_id IS NULL OR p_signing_secret_enc IS NULL THEN
+ RAISE EXCEPTION 'webhook_endpoint_invalid' USING ERRCODE = '22023';
+ END IF;
+ IF (p_custom_header_name IS NULL) <> (p_custom_header_value_enc IS NULL) THEN
+ RAISE EXCEPTION 'webhook_endpoint_header_incomplete' USING ERRCODE = '22023';
+ END IF;
+
+ -- Serialise creates per user so two concurrent requests cannot both pass
+ -- the count check.
+ PERFORM pg_catalog.pg_advisory_xact_lock(
+ pg_catalog.hashtextextended('webhook_endpoints:' || p_user_id::text, 0));
+
+ IF (SELECT count(*) FROM public.webhook_endpoints e WHERE e.user_id = p_user_id)
+ >= c_max_endpoints THEN
+ RAISE EXCEPTION 'webhook_endpoint_limit' USING ERRCODE = 'P0001';
+ END IF;
+
+ INSERT INTO public.webhook_endpoints
+ (user_id, label, url, scopes, signing_key_hint, custom_header_name)
+ VALUES
+ (p_user_id, p_label, p_url, p_scopes, p_signing_key_hint, p_custom_header_name)
+ RETURNING id INTO v_id;
+
+ INSERT INTO public.webhook_endpoint_secrets
+ (endpoint_id, user_id, signing_secret_enc, custom_header_value_enc)
+ VALUES
+ (v_id, p_user_id, p_signing_secret_enc, p_custom_header_value_enc);
+
+ RETURN v_id;
+END
+$$;
+
+REVOKE ALL ON FUNCTION public.create_webhook_endpoint(uuid, text, text, text[], text, text, text, text)
+ FROM PUBLIC, anon, authenticated;
+GRANT EXECUTE ON FUNCTION public.create_webhook_endpoint(uuid, text, text, text[], text, text, text, text)
+ TO service_role;
+
+COMMENT ON FUNCTION public.create_webhook_endpoint(uuid, text, text, text[], text, text, text, text) IS
+ 'Creates a webhook endpoint and its secret row in one transaction; at most 3 per user (P0001 webhook_endpoint_limit). Secrets arrive already encrypted. Service role only.';
+
+CREATE OR REPLACE FUNCTION public.rotate_webhook_signing_secret(
+ p_user_id uuid,
+ p_endpoint_id uuid,
+ p_signing_secret_enc text,
+ p_signing_key_hint text,
+ p_overlap_seconds integer DEFAULT 86400
+)
+RETURNS boolean
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = ''
+AS $$
+DECLARE
+ v_updated integer;
+BEGIN
+ IF p_signing_secret_enc IS NULL THEN
+ RAISE EXCEPTION 'webhook_endpoint_invalid' USING ERRCODE = '22023';
+ END IF;
+
+ UPDATE public.webhook_endpoint_secrets s
+ SET previous_signing_secret_enc = s.signing_secret_enc,
+ previous_expires_at = pg_catalog.now() + pg_catalog.make_interval(
+ secs => greatest(0, least(coalesce(p_overlap_seconds, 86400), 604800))),
+ signing_secret_enc = p_signing_secret_enc,
+ updated_at = pg_catalog.now()
+ WHERE s.endpoint_id = p_endpoint_id
+ AND s.user_id = p_user_id;
+ GET DIAGNOSTICS v_updated = ROW_COUNT;
+
+ IF v_updated = 0 THEN
+ RETURN false;
+ END IF;
+
+ UPDATE public.webhook_endpoints e
+ SET signing_key_hint = p_signing_key_hint
+ WHERE e.id = p_endpoint_id
+ AND e.user_id = p_user_id;
+
+ RETURN true;
+END
+$$;
+
+REVOKE ALL ON FUNCTION public.rotate_webhook_signing_secret(uuid, uuid, text, text, integer)
+ FROM PUBLIC, anon, authenticated;
+GRANT EXECUTE ON FUNCTION public.rotate_webhook_signing_secret(uuid, uuid, text, text, integer)
+ TO service_role;
+
+COMMENT ON FUNCTION public.rotate_webhook_signing_secret(uuid, uuid, text, text, integer) IS
+ 'Replaces an endpoint''s signing secret and keeps the old one valid for the overlap (default 24 h, max 7 d). Scoped by user. Service role only.';
+
+CREATE OR REPLACE FUNCTION public.set_webhook_endpoint_header(
+ p_user_id uuid,
+ p_endpoint_id uuid,
+ p_custom_header_name text,
+ p_custom_header_value_enc text
+)
+RETURNS boolean
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = ''
+AS $$
+DECLARE
+ v_updated integer;
+BEGIN
+ IF (p_custom_header_name IS NULL) <> (p_custom_header_value_enc IS NULL) THEN
+ RAISE EXCEPTION 'webhook_endpoint_header_incomplete' USING ERRCODE = '22023';
+ END IF;
+
+ UPDATE public.webhook_endpoints e
+ SET custom_header_name = p_custom_header_name
+ WHERE e.id = p_endpoint_id
+ AND e.user_id = p_user_id;
+ GET DIAGNOSTICS v_updated = ROW_COUNT;
+
+ IF v_updated = 0 THEN
+ RETURN false;
+ END IF;
+
+ UPDATE public.webhook_endpoint_secrets s
+ SET custom_header_value_enc = p_custom_header_value_enc,
+ updated_at = pg_catalog.now()
+ WHERE s.endpoint_id = p_endpoint_id
+ AND s.user_id = p_user_id;
+
+ RETURN true;
+END
+$$;
+
+REVOKE ALL ON FUNCTION public.set_webhook_endpoint_header(uuid, uuid, text, text)
+ FROM PUBLIC, anon, authenticated;
+GRANT EXECUTE ON FUNCTION public.set_webhook_endpoint_header(uuid, uuid, text, text)
+ TO service_role;
+
+COMMENT ON FUNCTION public.set_webhook_endpoint_header(uuid, uuid, text, text) IS
+ 'Sets or clears (both NULL) an endpoint''s custom header name and encrypted value together. Scoped by user. Service role only.';
+
+-- ---------------------------------------------------------------------------
+-- 7. Claim. The repo's first FOR UPDATE SKIP LOCKED queue.
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.claim_webhook_deliveries(
+ p_limit integer DEFAULT 100,
+ p_per_endpoint integer DEFAULT 30,
+ p_lease_seconds integer DEFAULT 180
+)
+RETURNS TABLE (
+ delivery_id uuid,
+ delivery_endpoint_id uuid,
+ delivery_user_id uuid,
+ delivery_entity text,
+ delivery_entity_id text,
+ delivery_attempt integer
+)
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = ''
+AS $$
+DECLARE
+ v_limit CONSTANT integer := greatest(1, least(coalesce(p_limit, 100), 500));
+ v_per_endpoint CONSTANT integer := greatest(1, least(coalesce(p_per_endpoint, 30), 200));
+ v_lease CONSTANT interval := pg_catalog.make_interval(
+ secs => greatest(30, least(coalesce(p_lease_seconds, 180), 3600)));
+BEGIN
+ -- Paid capability is enforced by the tier actually paid for (FP-2). An
+ -- endpoint whose owner is no longer FLAME+ is paused here, with a reason the
+ -- owner can read, and its waiting rows are closed. The capture trigger only
+ -- enqueues for active endpoints, so a downgraded account cannot grow the
+ -- outbox for ever. subscription_tier_for already applies the past_due and
+ -- 48 h renewal grace rules.
+ WITH due_endpoints AS MATERIALIZED (
+ SELECT e.id, public.subscription_tier_for(e.user_id) AS tier
+ FROM public.webhook_endpoints e
+ WHERE e.status = 'active'
+ AND EXISTS (
+ SELECT 1 FROM public.webhook_deliveries d
+ WHERE d.endpoint_id = e.id
+ AND d.status = 'pending'
+ AND d.next_attempt_at <= pg_catalog.now()
+ )
+ ),
+ paused AS (
+ UPDATE public.webhook_endpoints e
+ SET status = 'paused', disabled_reason = 'subscription_lapsed'
+ FROM due_endpoints de
+ WHERE e.id = de.id
+ AND e.status = 'active'
+ AND de.tier NOT IN ('FLAME', 'INFERNO')
+ RETURNING e.id
+ )
+ UPDATE public.webhook_deliveries d
+ SET status = 'skipped',
+ last_error_code = 'subscription_lapsed',
+ finished_at = pg_catalog.now()
+ FROM paused
+ WHERE d.endpoint_id = paused.id
+ AND d.status = 'pending';
+
+ RETURN QUERY
+ WITH ranked AS (
+ SELECT d.id,
+ d.next_attempt_at,
+ pg_catalog.row_number() OVER (
+ PARTITION BY d.endpoint_id ORDER BY d.next_attempt_at, d.id
+ ) AS rn
+ FROM public.webhook_deliveries d
+ JOIN public.webhook_endpoints e ON e.id = d.endpoint_id
+ WHERE e.status = 'active'
+ AND (
+ (d.status = 'pending' AND d.next_attempt_at <= pg_catalog.now())
+ -- A worker that died mid-send: its lease has run out.
+ OR (d.status = 'delivering' AND d.claimed_at < pg_catalog.now() - v_lease)
+ )
+ ),
+ picked AS (
+ SELECT d.id
+ FROM public.webhook_deliveries d
+ JOIN ranked r ON r.id = d.id
+ WHERE r.rn <= v_per_endpoint
+ -- Restated on the locked row itself: under READ COMMITTED a row another
+ -- worker claimed after our snapshot is re-read after the lock wait, and
+ -- only predicates on `d` are re-checked.
+ AND (
+ (d.status = 'pending' AND d.next_attempt_at <= pg_catalog.now())
+ OR (d.status = 'delivering' AND d.claimed_at < pg_catalog.now() - v_lease)
+ )
+ ORDER BY r.next_attempt_at, d.id
+ LIMIT v_limit
+ FOR UPDATE OF d SKIP LOCKED
+ )
+ UPDATE public.webhook_deliveries d
+ SET status = 'delivering',
+ claimed_at = pg_catalog.now(),
+ attempt_count = d.attempt_count + 1
+ FROM picked
+ WHERE d.id = picked.id
+ RETURNING d.id, d.endpoint_id, d.user_id, d.entity, d.entity_id, d.attempt_count;
+END
+$$;
+
+REVOKE ALL ON FUNCTION public.claim_webhook_deliveries(integer, integer, integer)
+ FROM PUBLIC, anon, authenticated;
+GRANT EXECUTE ON FUNCTION public.claim_webhook_deliveries(integer, integer, integer)
+ TO service_role;
+
+COMMENT ON FUNCTION public.claim_webhook_deliveries(integer, integer, integer) IS
+ 'Claims due webhook deliveries (FOR UPDATE SKIP LOCKED, capped per endpoint) for active endpoints, after pausing endpoints whose owner is below FLAME. Returns the claim generation as delivery_attempt. Service role only.';
+
+-- ---------------------------------------------------------------------------
+-- 8. Completion. Fenced by (status = delivering, attempt) so a worker whose
+-- lease expired cannot overwrite the newer claim's result.
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.complete_webhook_delivery(
+ p_delivery_id uuid,
+ p_attempt integer,
+ p_outcome text,
+ p_event_type text DEFAULT NULL,
+ p_status_code integer DEFAULT NULL,
+ p_error_code text DEFAULT NULL,
+ p_duration_ms integer DEFAULT NULL,
+ p_retry_after_seconds integer DEFAULT NULL
+)
+RETURNS text
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = ''
+AS $$
+DECLARE
+ -- Wait after the Nth failed attempt. Nine attempts over about 46 hours.
+ c_backoff_seconds CONSTANT integer[] :=
+ ARRAY[60, 300, 900, 3600, 10800, 21600, 43200, 86400];
+ c_max_attempts CONSTANT integer := 9;
+ v_row public.webhook_deliveries%ROWTYPE;
+ v_status text;
+ v_error text := p_error_code;
+ v_wait integer;
+ v_next timestamptz;
+BEGIN
+ IF p_outcome IS NULL OR p_outcome NOT IN ('delivered', 'failed', 'gone', 'skipped') THEN
+ RAISE EXCEPTION 'webhook_delivery_outcome_invalid' USING ERRCODE = '22023';
+ END IF;
+
+ SELECT * INTO v_row
+ FROM public.webhook_deliveries d
+ WHERE d.id = p_delivery_id
+ AND d.status = 'delivering'
+ AND d.attempt_count = p_attempt
+ FOR UPDATE;
+
+ IF NOT FOUND THEN
+ RETURN NULL;
+ END IF;
+
+ IF p_outcome = 'delivered' THEN
+ v_status := 'delivered';
+ ELSIF p_outcome = 'skipped' THEN
+ v_status := 'skipped';
+ ELSIF p_outcome = 'gone' THEN
+ v_status := 'dead';
+ ELSIF v_row.attempt_count >= c_max_attempts THEN
+ v_status := 'dead';
+ ELSIF EXISTS (
+ SELECT 1 FROM public.webhook_deliveries o
+ WHERE o.endpoint_id = v_row.endpoint_id
+ AND o.entity = v_row.entity
+ AND o.entity_id = v_row.entity_id
+ AND o.status = 'pending'
+ ) THEN
+ -- The entity changed again while this attempt was in flight and a newer
+ -- row is already waiting. It will carry the current state; retrying this
+ -- one would only collide with the one-pending index.
+ v_status := 'skipped';
+ v_error := 'superseded';
+ ELSE
+ v_status := 'pending';
+ v_wait := c_backoff_seconds[least(v_row.attempt_count, pg_catalog.array_length(c_backoff_seconds, 1))];
+ -- +/- 20 % jitter so a recovering receiver is not hit by every retry at once.
+ v_wait := (v_wait * (0.8 + pg_catalog.random() * 0.4))::integer;
+ IF p_retry_after_seconds IS NOT NULL AND p_retry_after_seconds > 0 THEN
+ v_wait := greatest(v_wait, least(p_retry_after_seconds, 3600));
+ END IF;
+ v_next := pg_catalog.now() + pg_catalog.make_interval(secs => v_wait);
+ END IF;
+
+ UPDATE public.webhook_deliveries d
+ SET status = v_status,
+ event_type = coalesce(p_event_type, d.event_type),
+ last_status_code = p_status_code,
+ last_error_code = v_error,
+ duration_ms = p_duration_ms,
+ next_attempt_at = coalesce(v_next, d.next_attempt_at),
+ claimed_at = NULL,
+ finished_at = CASE WHEN v_status = 'pending' THEN NULL ELSE pg_catalog.now() END
+ WHERE d.id = v_row.id;
+
+ IF p_outcome = 'delivered' THEN
+ UPDATE public.webhook_endpoints e
+ SET consecutive_failures = 0,
+ last_success_at = pg_catalog.now()
+ WHERE e.id = v_row.endpoint_id;
+ ELSIF p_outcome IN ('failed', 'gone') THEN
+ -- A delivery that ran out of attempts, or a receiver that answered
+ -- 410 Gone, switches the endpoint off. The owner sees why (FP-8) and has
+ -- to pass a test delivery to switch it back on.
+ UPDATE public.webhook_endpoints e
+ SET consecutive_failures = e.consecutive_failures + 1,
+ last_failure_at = pg_catalog.now(),
+ status = CASE
+ WHEN v_status = 'dead' AND e.status = 'active' THEN 'disabled'
+ ELSE e.status END,
+ disabled_reason = CASE
+ WHEN v_status = 'dead' AND e.status = 'active' THEN
+ CASE WHEN p_outcome = 'gone' THEN 'endpoint_gone' ELSE 'too_many_failures' END
+ ELSE e.disabled_reason END
+ WHERE e.id = v_row.endpoint_id;
+ END IF;
+
+ RETURN v_status;
+END
+$$;
+
+REVOKE ALL ON FUNCTION public.complete_webhook_delivery(uuid, integer, text, text, integer, text, integer, integer)
+ FROM PUBLIC, anon, authenticated;
+GRANT EXECUTE ON FUNCTION public.complete_webhook_delivery(uuid, integer, text, text, integer, text, integer, integer)
+ TO service_role;
+
+COMMENT ON FUNCTION public.complete_webhook_delivery(uuid, integer, text, text, integer, text, integer, integer) IS
+ 'Records a delivery attempt (delivered | failed | gone | skipped), reschedules with backoff or marks it dead, and updates the endpoint counters. Returns the new status, NULL when the claim was lost. Service role only.';
+
+-- ---------------------------------------------------------------------------
+-- 9. Backfill ("Resend all"). DEFINER because `private` is unreachable for
+-- the service role (same reason as set_insights_batch_cursor).
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.enqueue_webhook_backfill(
+ p_user_id uuid,
+ p_endpoint_id uuid
+)
+RETURNS integer
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = ''
+AS $$
+DECLARE
+ v_scopes text[];
+ s record;
+ v_sql text;
+ v_rows integer;
+ v_total integer := 0;
+BEGIN
+ SELECT e.scopes INTO v_scopes
+ FROM public.webhook_endpoints e
+ WHERE e.id = p_endpoint_id
+ AND e.user_id = p_user_id
+ AND e.status = 'active';
+
+ IF v_scopes IS NULL THEN
+ RETURN 0;
+ END IF;
+
+ FOR s IN
+ SELECT * FROM private.webhook_entity_sources src
+ WHERE src.is_root AND src.scope = ANY (v_scopes)
+ ORDER BY src.source_table
+ LOOP
+ CONTINUE WHEN pg_catalog.to_regclass(pg_catalog.format('public.%I', s.source_table)) IS NULL;
+
+ -- Every row is read with the endpoint owner's id: $2 is both the owner
+ -- written to the delivery and the filter on the source table.
+ v_sql := pg_catalog.format(
+ 'INSERT INTO public.webhook_deliveries (endpoint_id, user_id, entity, entity_id) '
+ || 'SELECT $1, $2, $3, c.%I::text FROM public.%I c WHERE c.%I = $2',
+ s.id_column, s.source_table, s.user_column);
+ IF s.row_filter IS NOT NULL THEN
+ v_sql := v_sql || ' AND (' || s.row_filter || ')';
+ END IF;
+ IF s.backfill_filter IS NOT NULL THEN
+ v_sql := v_sql || ' AND (' || s.backfill_filter || ')';
+ END IF;
+ v_sql := v_sql
+ || ' ON CONFLICT (endpoint_id, entity, entity_id) '
+ || 'WHERE status = ''pending'' DO NOTHING';
+
+ EXECUTE v_sql USING p_endpoint_id, p_user_id, s.entity;
+ GET DIAGNOSTICS v_rows = ROW_COUNT;
+ v_total := v_total + v_rows;
+ END LOOP;
+
+ RETURN v_total;
+END
+$$;
+
+REVOKE ALL ON FUNCTION public.enqueue_webhook_backfill(uuid, uuid)
+ FROM PUBLIC, anon, authenticated;
+GRANT EXECUTE ON FUNCTION public.enqueue_webhook_backfill(uuid, uuid)
+ TO service_role;
+
+COMMENT ON FUNCTION public.enqueue_webhook_backfill(uuid, uuid) IS
+ 'Enqueues one delivery per existing entity in an active endpoint''s scopes ("Resend all"). Scoped by the endpoint owner. Returns the number enqueued. Service role only.';
+
+-- ---------------------------------------------------------------------------
+-- 10. Retention: the log keeps 30 days.
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION private.prune_webhook_deliveries()
+RETURNS integer
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = ''
+AS $$
+DECLARE
+ v_deleted integer;
+BEGIN
+ DELETE FROM public.webhook_deliveries d
+ WHERE d.created_at < pg_catalog.now() - interval '30 days'
+ AND (
+ d.status IN ('delivered', 'dead', 'skipped')
+ -- Rows left waiting behind an endpoint that was never switched back on.
+ OR EXISTS (
+ SELECT 1 FROM public.webhook_endpoints e
+ WHERE e.id = d.endpoint_id AND e.status <> 'active'
+ )
+ );
+ GET DIAGNOSTICS v_deleted = ROW_COUNT;
+ RETURN v_deleted;
+END
+$$;
+
+REVOKE ALL ON FUNCTION private.prune_webhook_deliveries()
+ FROM PUBLIC, anon, authenticated, service_role;
+
+-- ---------------------------------------------------------------------------
+-- 11. pg_cron jobs. Owner-only, idempotent; a re-apply never flips `active`.
+-- ---------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION private.schedule_webhook_jobs()
+RETURNS void
+LANGUAGE plpgsql
+SET search_path = pg_catalog, pg_temp
+AS $fn$
+DECLARE
+ j record;
+ v_jobid bigint;
+ v_schedule text;
+ v_command text;
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_cron') THEN
+ RAISE NOTICE 'pg_cron not installed; skip scheduling deliver-webhooks and retention jobs';
+ RETURN;
+ END IF;
+
+ FOR j IN
+ SELECT *
+ FROM (VALUES
+ ('deliver-webhooks', '* * * * *',
+ 'SELECT private.invoke_edge_function(''deliver-webhooks'', ''{}''::jsonb)'),
+ ('webhook-deliveries-retention', '37 3 * * *',
+ 'SELECT private.prune_webhook_deliveries()')
+ ) AS v(jobname, schedule, command)
+ LOOP
+ v_jobid := NULL;
+ EXECUTE 'SELECT jobid, schedule, command FROM cron.job WHERE jobname = $1 ORDER BY jobid LIMIT 1'
+ INTO v_jobid, v_schedule, v_command
+ USING j.jobname;
+
+ IF v_jobid IS NULL THEN
+ v_jobid := cron.schedule(j.jobname, j.schedule, j.command);
+ IF j.jobname = 'deliver-webhooks' THEN
+ -- The Edge Function ships in a later release; an active job would
+ -- only collect 404s until then.
+ PERFORM cron.alter_job(v_jobid, active := false);
+ RAISE NOTICE 'deliver-webhooks scheduled INACTIVE; deploy the Edge Function, then activate with cron.alter_job(%, active := true)', v_jobid;
+ END IF;
+ ELSIF v_schedule IS DISTINCT FROM j.schedule OR v_command IS DISTINCT FROM j.command THEN
+ PERFORM cron.alter_job(v_jobid, schedule := j.schedule, command := j.command);
+ END IF;
+ END LOOP;
+END
+$fn$;
+
+REVOKE ALL ON FUNCTION private.schedule_webhook_jobs()
+ FROM PUBLIC, anon, authenticated, service_role;
+
+SELECT private.schedule_webhook_jobs();
+
+-- ---------------------------------------------------------------------------
+-- 12. Self-check: nothing added here may be reachable from the browser beyond
+-- the two owner SELECTs.
+-- ---------------------------------------------------------------------------
+DO $$
+DECLARE
+ v_offenders text;
+BEGIN
+ SELECT string_agg(format('%s/%s', p.oid::regprocedure, r.rolname), ', ')
+ INTO v_offenders
+ FROM pg_proc p
+ JOIN pg_namespace n ON n.oid = p.pronamespace
+ CROSS JOIN (VALUES ('anon'), ('authenticated')) AS r(rolname)
+ WHERE (
+ (n.nspname = 'public'
+ AND p.proname IN ('create_webhook_endpoint', 'rotate_webhook_signing_secret',
+ 'set_webhook_endpoint_header', 'claim_webhook_deliveries',
+ 'complete_webhook_delivery', 'enqueue_webhook_backfill'))
+ OR (n.nspname = 'private'
+ AND p.proname IN ('enqueue_webhook_deliveries', 'prune_webhook_deliveries',
+ 'schedule_webhook_jobs'))
+ )
+ AND has_function_privilege(r.rolname, p.oid, 'EXECUTE');
+
+ IF v_offenders IS NOT NULL THEN
+ RAISE EXCEPTION 'webhook data sharing: functions executable by %', v_offenders
+ USING ERRCODE = '42501';
+ END IF;
+
+ SELECT string_agg(format('%s/%s/%s', t.relname, r.rolname, priv.name), ', ')
+ INTO v_offenders
+ FROM (VALUES ('public.webhook_endpoints'), ('public.webhook_endpoint_secrets'),
+ ('public.webhook_deliveries'), ('private.webhook_entity_sources')) AS t(relname)
+ CROSS JOIN (VALUES ('anon'), ('authenticated')) AS r(rolname)
+ CROSS JOIN (VALUES ('SELECT'), ('INSERT'), ('UPDATE'), ('DELETE'), ('TRUNCATE')) AS priv(name)
+ WHERE has_table_privilege(r.rolname, t.relname, priv.name)
+ AND NOT (
+ r.rolname = 'authenticated'
+ AND priv.name = 'SELECT'
+ AND t.relname IN ('public.webhook_endpoints', 'public.webhook_deliveries')
+ );
+
+ IF v_offenders IS NOT NULL THEN
+ RAISE EXCEPTION 'webhook data sharing: table privileges too wide: %', v_offenders
+ USING ERRCODE = '42501';
+ END IF;
+END
+$$;
+
+COMMIT;
diff --git a/supabase/tests/database/rls_isolation.test.sql b/supabase/tests/database/rls_isolation.test.sql
index ea62f742..4872cfe1 100644
--- a/supabase/tests/database/rls_isolation.test.sql
+++ b/supabase/tests/database/rls_isolation.test.sql
@@ -524,6 +524,20 @@ VALUES ('a1a1a1a1-0038-4000-8000-00000000000a', 'a1a1a1a1-0000-4000-8000-0000000
-- not A's live session: guard_workout_tombstone would freeze it
'a1a1a1a1-0040-4000-8000-00000000000a', now());
+-- Data sharing (20261106120000). The endpoint is paused so the capture
+-- triggers stay inert while the probes below write to A's other rows.
+INSERT INTO public.webhook_endpoints
+ (id, user_id, label, url, scopes, status, disabled_reason, signing_key_hint)
+VALUES ('a1a1a1a1-0042-4000-8000-00000000000a', 'a1a1a1a1-0000-4000-8000-00000000000a',
+ 'A endpoint', 'https://hooks.example.test/a', ARRAY['workouts'], 'paused', 'user_paused', 'abcd');
+
+INSERT INTO public.webhook_endpoint_secrets (endpoint_id, user_id, signing_secret_enc)
+VALUES ('a1a1a1a1-0042-4000-8000-00000000000a', 'a1a1a1a1-0000-4000-8000-00000000000a', 'enc:v1:rls-fixture');
+
+INSERT INTO public.webhook_deliveries (id, endpoint_id, user_id, entity, entity_id)
+VALUES ('a1a1a1a1-0043-4000-8000-00000000000a', 'a1a1a1a1-0042-4000-8000-00000000000a',
+ 'a1a1a1a1-0000-4000-8000-00000000000a', 'workout', 'a1a1a1a1-0001-4000-8000-00000000000a');
+
-- One row per private user-owned relation.
-- key_col / row_key: how the probe finds A's fixture row.
-- owner_select: rows A must see; NULL = service-only (expect <= 0).
@@ -596,7 +610,12 @@ INSERT INTO rls_cases VALUES
('profile_ownership_transfers', 'mutation_id', 'a1a1a1a1-0037-4000-8000-00000000000a', NULL, NULL, NULL, $s$request_hash = 'rls-probe'$s$),
('training_cycle_deletion_tombstones', 'cycle_id', 'a1a1a1a1-0036-4000-8000-00000000000a', NULL, NULL, NULL, $s$deleted_at = '2000-01-01T00:00:00Z'$s$),
('workout_deletion_tombstones', 'mutation_id', 'a1a1a1a1-0038-4000-8000-00000000000a', 1, NULL, NULL, $s$request_hash = 'rls-probe'$s$),
- ('wearable_daily_summaries', 'id', 'a1a1a1a1-0034-4000-8000-00000000000a', 1, NULL, NULL, $s$provider = 'rls-probe'$s$);
+ ('wearable_daily_summaries', 'id', 'a1a1a1a1-0034-4000-8000-00000000000a', 1, NULL, NULL, $s$provider = 'rls-probe'$s$),
+ -- Data sharing: the owner reads endpoints and the delivery log; every
+ -- write is server-side, and the secrets table is service-only.
+ ('webhook_endpoints', 'id', 'a1a1a1a1-0042-4000-8000-00000000000a', 1, NULL, NULL, $s$label = 'rls-probe'$s$),
+ ('webhook_endpoint_secrets', 'endpoint_id', 'a1a1a1a1-0042-4000-8000-00000000000a', NULL, NULL, NULL, $s$signing_secret_enc = 'rls-probe'$s$),
+ ('webhook_deliveries', 'id', 'a1a1a1a1-0043-4000-8000-00000000000a', 1, NULL, NULL, $s$event_type = 'rls-probe'$s$);
-- PR 38: force-curve and biomechanics relations whose SELECT policy requires
-- INFERNO (20260920003800_inferno_read_policies.sql). Their owner_select is 0
diff --git a/supabase/tests/database/webhook_data_sharing.test.sql b/supabase/tests/database/webhook_data_sharing.test.sql
new file mode 100644
index 00000000..b7536f95
--- /dev/null
+++ b/supabase/tests/database/webhook_data_sharing.test.sql
@@ -0,0 +1,800 @@
+-- Data sharing (outbound webhooks), 20261106120000.
+--
+-- What must hold, by axiom:
+-- FP-1 a change to one user's data is only ever enqueued for that user's
+-- own endpoints, and a delivery cannot name another user's endpoint;
+-- FP-2 an endpoint whose owner is below FLAME is paused by the claim, with
+-- a reason, and stops enqueuing;
+-- FP-3 every write path is captured (parent row, children rewritten by
+-- replace_session_children, child-only edits, hard and soft deletes)
+-- and rapid edits coalesce into one pending delivery;
+-- FP-5 no browser role can read or write the secrets table;
+-- FP-6 account deletion removes endpoints, secrets and deliveries;
+-- FP-8 a dead delivery or a 410 switches the endpoint off with a reason.
+BEGIN;
+
+CREATE EXTENSION IF NOT EXISTS pgtap WITH SCHEMA extensions;
+SET LOCAL search_path = public, extensions;
+
+SELECT no_plan();
+
+-- ---------------------------------------------------------------------------
+-- Shape and grants
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-tables-rls-and-grants');
+
+SELECT ok(
+ (SELECT bool_and(c.relrowsecurity) FROM pg_class c
+ WHERE c.oid IN ('public.webhook_endpoints'::regclass,
+ 'public.webhook_endpoint_secrets'::regclass,
+ 'public.webhook_deliveries'::regclass)),
+ 'RLS is enabled on all three webhook tables'
+);
+
+SELECT ok(has_table_privilege('authenticated', 'public.webhook_endpoints', 'SELECT'),
+ 'authenticated can SELECT webhook_endpoints (owner policy filters rows)');
+SELECT ok(has_table_privilege('authenticated', 'public.webhook_deliveries', 'SELECT'),
+ 'authenticated can SELECT webhook_deliveries (owner policy filters rows)');
+
+SELECT is(
+ (SELECT count(*)::int
+ FROM (VALUES ('public.webhook_endpoints'), ('public.webhook_endpoint_secrets'),
+ ('public.webhook_deliveries')) AS t(rel)
+ CROSS JOIN (VALUES ('anon'), ('authenticated')) AS r(role)
+ CROSS JOIN (VALUES ('INSERT'), ('UPDATE'), ('DELETE'), ('TRUNCATE')) AS p(priv)
+ WHERE has_table_privilege(r.role, t.rel, p.priv)),
+ 0,
+ 'no browser role can write any webhook table'
+);
+
+SELECT is(
+ (SELECT count(*)::int
+ FROM (VALUES ('anon'), ('authenticated')) AS r(role)
+ WHERE has_table_privilege(r.role, 'public.webhook_endpoint_secrets', 'SELECT')),
+ 0,
+ 'no browser role can read webhook_endpoint_secrets'
+);
+
+SELECT ok(NOT has_table_privilege('anon', 'public.webhook_endpoints', 'SELECT'),
+ 'anon cannot SELECT webhook_endpoints');
+SELECT ok(NOT has_table_privilege('anon', 'public.webhook_deliveries', 'SELECT'),
+ 'anon cannot SELECT webhook_deliveries');
+
+SELECT is(
+ (SELECT count(*)::int
+ FROM pg_proc p
+ JOIN pg_namespace n ON n.oid = p.pronamespace
+ CROSS JOIN (VALUES ('anon'), ('authenticated')) AS r(role)
+ WHERE ((n.nspname = 'public' AND p.proname IN (
+ 'create_webhook_endpoint', 'rotate_webhook_signing_secret',
+ 'set_webhook_endpoint_header', 'claim_webhook_deliveries',
+ 'complete_webhook_delivery', 'enqueue_webhook_backfill'))
+ OR (n.nspname = 'private' AND p.proname IN (
+ 'enqueue_webhook_deliveries', 'prune_webhook_deliveries',
+ 'schedule_webhook_jobs')))
+ AND has_function_privilege(r.role, p.oid, 'EXECUTE')),
+ 0,
+ 'no browser role can execute any webhook function'
+);
+
+SELECT is(
+ (SELECT count(*)::int
+ FROM pg_proc p
+ JOIN pg_namespace n ON n.oid = p.pronamespace
+ WHERE n.nspname = 'public'
+ AND p.proname IN (
+ 'create_webhook_endpoint', 'rotate_webhook_signing_secret',
+ 'set_webhook_endpoint_header', 'claim_webhook_deliveries',
+ 'complete_webhook_delivery', 'enqueue_webhook_backfill')
+ AND has_function_privilege('service_role', p.oid, 'EXECUTE')),
+ 6,
+ 'service_role can execute the six public webhook RPCs'
+);
+
+SELECT is(
+ (SELECT count(*)::int
+ FROM private.webhook_entity_sources s
+ WHERE (SELECT count(*) FROM pg_trigger t
+ WHERE t.tgrelid = format('public.%I', s.source_table)::regclass
+ AND t.tgname IN ('webhook_capture_insert', 'webhook_capture_update',
+ 'webhook_capture_delete')) <> 3),
+ 0,
+ 'every entity source table has its insert, update and delete capture trigger'
+);
+
+-- ---------------------------------------------------------------------------
+-- Fixtures: A and B are FLAME, C has no subscription (FREE).
+-- ---------------------------------------------------------------------------
+INSERT INTO auth.users (id, email)
+VALUES
+ ('d0d0d0d0-0000-4000-8000-00000000000a'::uuid, 'webhook-a@example.test'),
+ ('d0d0d0d0-0000-4000-8000-00000000000b'::uuid, 'webhook-b@example.test'),
+ ('d0d0d0d0-0000-4000-8000-00000000000c'::uuid, 'webhook-c@example.test')
+ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email;
+
+INSERT INTO public.subscriptions (id, user_id, tier, status, current_period_end)
+VALUES
+ ('d0d0d0d0-5555-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'FLAME', 'active', now() + interval '30 days'),
+ ('d0d0d0d0-5555-4000-8000-00000000000b', 'd0d0d0d0-0000-4000-8000-00000000000b',
+ 'FLAME', 'active', now() + interval '30 days')
+ON CONFLICT (user_id) DO UPDATE
+ SET tier = EXCLUDED.tier, status = EXCLUDED.status,
+ current_period_end = EXCLUDED.current_period_end;
+
+CREATE TEMP TABLE wh_ids (name text PRIMARY KEY, id uuid NOT NULL) ON COMMIT DROP;
+
+-- Marks everything finished so the next assertion sees only new rows.
+CREATE FUNCTION pg_temp.settle() RETURNS void LANGUAGE sql AS $$
+ UPDATE public.webhook_deliveries
+ SET status = 'delivered', finished_at = now()
+ WHERE status IN ('pending', 'delivering');
+$$;
+
+CREATE FUNCTION pg_temp.pending(p_endpoint text, p_entity text) RETURNS integer
+LANGUAGE sql AS $$
+ SELECT count(*)::int
+ FROM public.webhook_deliveries d
+ WHERE d.endpoint_id = (SELECT id FROM wh_ids WHERE name = p_endpoint)
+ AND d.entity = p_entity
+ AND d.status = 'pending';
+$$;
+
+-- ---------------------------------------------------------------------------
+-- Before any endpoint exists a write enqueues nothing.
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-capture-inert-without-endpoints');
+
+INSERT INTO public.routines (id, user_id, name)
+VALUES ('d0d0d0d0-0001-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a', 'Before');
+
+SELECT is(
+ (SELECT count(*)::int FROM public.webhook_deliveries
+ WHERE user_id IN ('d0d0d0d0-0000-4000-8000-00000000000a',
+ 'd0d0d0d0-0000-4000-8000-00000000000b')),
+ 0,
+ 'a write with no endpoint registered enqueues nothing'
+);
+
+-- ---------------------------------------------------------------------------
+-- create_webhook_endpoint
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-endpoint-create-and-limit');
+
+INSERT INTO wh_ids
+SELECT 'a', public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', 'A main', 'https://hooks.example.test/a',
+ ARRAY['workouts', 'routines', 'personal_records', 'external_activities'],
+ 'enc:v1:a-secret', 'aaaa');
+
+INSERT INTO wh_ids
+SELECT 'b', public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', 'B main', 'https://hooks.example.test/b',
+ ARRAY['routines'], 'enc:v1:b-secret', 'bbbb', 'Authorization', 'enc:v1:b-header');
+
+SELECT is(
+ (SELECT s.signing_secret_enc FROM public.webhook_endpoint_secrets s
+ WHERE s.endpoint_id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ 'enc:v1:a-secret',
+ 'create stores the secret row with the endpoint'
+);
+
+SELECT is(
+ (SELECT e.custom_header_name || '|' || s.custom_header_value_enc
+ FROM public.webhook_endpoints e
+ JOIN public.webhook_endpoint_secrets s ON s.endpoint_id = e.id
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'b')),
+ 'Authorization|enc:v1:b-header',
+ 'create stores the header name and its encrypted value together'
+);
+
+SELECT throws_ok(
+ $q$SELECT public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', 'x', 'https://hooks.example.test/x',
+ ARRAY['workouts'], 'enc:v1:x', 'xxxx', 'Authorization', NULL)$q$,
+ '22023', 'webhook_endpoint_header_incomplete',
+ 'a header name without a value is refused'
+);
+
+SELECT throws_ok(
+ $q$SELECT public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', 'x', 'http://hooks.example.test/x',
+ ARRAY['workouts'], 'enc:v1:x', 'xxxx')$q$,
+ '23514', NULL,
+ 'a non-https URL is refused by the table constraint'
+);
+
+SELECT throws_ok(
+ $q$SELECT public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', 'x', 'https://hooks.example.test/x',
+ ARRAY['workouts', 'telemetry'], 'enc:v1:x', 'xxxx')$q$,
+ '23514', NULL,
+ 'an unknown scope is refused by the table constraint'
+);
+
+SELECT lives_ok(
+ $q$SELECT public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', 'B two', 'https://hooks.example.test/b2',
+ ARRAY['goals'], 'enc:v1:b2', 'b222');
+ SELECT public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', 'B three', 'https://hooks.example.test/b3',
+ ARRAY['goals'], 'enc:v1:b3', 'b333')$q$,
+ 'a user can register three endpoints'
+);
+
+SELECT throws_ok(
+ $q$SELECT public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', 'B four', 'https://hooks.example.test/b4',
+ ARRAY['goals'], 'enc:v1:b4', 'b444')$q$,
+ 'P0001', 'webhook_endpoint_limit',
+ 'a fourth endpoint is refused'
+);
+
+-- ---------------------------------------------------------------------------
+-- Capture: workouts (parent row, coalescing, children, scope, isolation)
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-capture-workouts');
+
+INSERT INTO public.workout_sessions (id, user_id)
+VALUES ('d0d0d0d0-0002-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a');
+
+SELECT is(pg_temp.pending('a', 'workout'), 1,
+ 'inserting a session enqueues one workout delivery for the owner''s endpoint');
+
+SELECT is(
+ (SELECT d.entity_id || '|' || d.user_id::text FROM public.webhook_deliveries d
+ WHERE d.endpoint_id = (SELECT id FROM wh_ids WHERE name = 'a') AND d.entity = 'workout'),
+ 'd0d0d0d0-0002-4000-8000-00000000000a|d0d0d0d0-0000-4000-8000-00000000000a',
+ 'the delivery names the session and carries the owner''s user id'
+);
+
+SELECT ok(
+ (SELECT d.next_attempt_at > now() + interval '10 seconds'
+ FROM public.webhook_deliveries d
+ WHERE d.endpoint_id = (SELECT id FROM wh_ids WHERE name = 'a') AND d.entity = 'workout'),
+ 'a new delivery waits for the write to settle before it is due'
+);
+
+SELECT is(
+ (SELECT count(*)::int FROM public.webhook_deliveries d
+ WHERE d.user_id = 'd0d0d0d0-0000-4000-8000-00000000000b'),
+ 0,
+ 'user A''s session enqueues nothing for user B''s endpoints'
+);
+
+UPDATE public.workout_sessions SET notes = 'one'
+WHERE id = 'd0d0d0d0-0002-4000-8000-00000000000a';
+UPDATE public.workout_sessions SET notes = 'two'
+WHERE id = 'd0d0d0d0-0002-4000-8000-00000000000a';
+
+SELECT is(pg_temp.pending('a', 'workout'), 1,
+ 'two further edits coalesce into the one pending delivery');
+
+SELECT pg_temp.settle();
+
+-- replace_session_children never touches workout_sessions: without the
+-- exercises trigger a re-pushed set list would go unnoticed.
+SELECT lives_ok(
+ $q$SELECT public.replace_session_children(
+ 'd0d0d0d0-0000-4000-8000-00000000000a'::uuid,
+ ARRAY['d0d0d0d0-0002-4000-8000-00000000000a'::uuid],
+ jsonb_build_array(jsonb_build_object(
+ 'id', 'd0d0d0d0-0003-4000-8000-00000000000a',
+ 'session_id', 'd0d0d0d0-0002-4000-8000-00000000000a',
+ 'user_id', 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'name', 'Row', 'muscle_group', 'Back', 'order_index', 0)),
+ '[]'::jsonb, '[]'::jsonb, '[]'::jsonb)$q$,
+ 'replace_session_children runs with the capture triggers in place'
+);
+
+SELECT is(pg_temp.pending('a', 'workout'), 1,
+ 'rewriting a session''s children enqueues a workout delivery');
+
+SELECT pg_temp.settle();
+
+-- B shares routines only.
+INSERT INTO public.workout_sessions (id, user_id)
+VALUES ('d0d0d0d0-0002-4000-8000-00000000000b', 'd0d0d0d0-0000-4000-8000-00000000000b');
+
+SELECT is(
+ (SELECT count(*)::int FROM public.webhook_deliveries d WHERE d.status = 'pending'
+ AND d.user_id IN ('d0d0d0d0-0000-4000-8000-00000000000a',
+ 'd0d0d0d0-0000-4000-8000-00000000000b')),
+ 0,
+ 'a session is not enqueued for an endpoint without the workouts scope'
+);
+
+-- ---------------------------------------------------------------------------
+-- Capture: routines (child-only edit through the parent, hard delete)
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-capture-routines');
+
+INSERT INTO public.routines (id, user_id, name)
+VALUES ('d0d0d0d0-0004-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a', 'Push');
+
+SELECT is(pg_temp.pending('a', 'routine'), 1, 'inserting a routine enqueues a routine delivery');
+SELECT is(pg_temp.pending('b', 'routine'), 0,
+ 'user A''s routine is not enqueued for user B''s routines endpoint');
+
+SELECT pg_temp.settle();
+
+INSERT INTO public.routine_exercises (id, routine_id, name)
+VALUES ('d0d0d0d0-0005-4000-8000-00000000000a', 'd0d0d0d0-0004-4000-8000-00000000000a', 'Press');
+
+SELECT is(pg_temp.pending('a', 'routine'), 1,
+ 'adding a routine exercise enqueues its parent routine');
+SELECT is(
+ (SELECT d.entity_id FROM public.webhook_deliveries d
+ WHERE d.endpoint_id = (SELECT id FROM wh_ids WHERE name = 'a')
+ AND d.entity = 'routine' AND d.status = 'pending'),
+ 'd0d0d0d0-0004-4000-8000-00000000000a',
+ 'the child edit is recorded under the routine id, not the child id'
+);
+
+SELECT pg_temp.settle();
+
+DELETE FROM public.routines WHERE id = 'd0d0d0d0-0004-4000-8000-00000000000a';
+
+SELECT is(pg_temp.pending('a', 'routine'), 1,
+ 'hard-deleting a routine enqueues a routine delivery');
+
+SELECT pg_temp.settle();
+
+-- ---------------------------------------------------------------------------
+-- Capture: personal records (soft delete) and external activities (Strava)
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-capture-records-and-external');
+
+INSERT INTO public.personal_records (id, user_id, exercise_name, value)
+VALUES ('d0d0d0d0-0006-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a', 'Row', 100);
+SELECT pg_temp.settle();
+
+UPDATE public.personal_records SET deleted_at = now()
+WHERE id = 'd0d0d0d0-0006-4000-8000-00000000000a';
+
+SELECT is(pg_temp.pending('a', 'personal_record'), 1,
+ 'soft-deleting a personal record enqueues a delivery');
+
+SELECT pg_temp.settle();
+
+INSERT INTO public.external_activities (id, user_id, external_id, provider, name, started_at)
+VALUES ('d0d0d0d0-0007-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'wh-strava-1', 'strava', 'Ride', now());
+
+SELECT is(pg_temp.pending('a', 'external_activity'), 0,
+ 'a Strava-sourced activity is never enqueued');
+
+INSERT INTO public.external_activities (id, user_id, external_id, provider, name, started_at)
+VALUES ('d0d0d0d0-0008-4000-8000-00000000000a', 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'wh-hevy-1', 'hevy', 'Lift', now());
+
+SELECT is(pg_temp.pending('a', 'external_activity'), 1,
+ 'a non-Strava activity is enqueued');
+
+DELETE FROM public.external_activities WHERE id = 'd0d0d0d0-0007-4000-8000-00000000000a';
+
+SELECT is(pg_temp.pending('a', 'external_activity'), 1,
+ 'deleting a Strava-sourced activity enqueues nothing either');
+
+SELECT pg_temp.settle();
+
+-- ---------------------------------------------------------------------------
+-- A paused endpoint captures nothing.
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-capture-paused-endpoint');
+
+UPDATE public.webhook_endpoints
+SET status = 'paused', disabled_reason = 'user_paused'
+WHERE id = (SELECT id FROM wh_ids WHERE name = 'a');
+
+UPDATE public.workout_sessions SET notes = 'while paused'
+WHERE id = 'd0d0d0d0-0002-4000-8000-00000000000a';
+
+SELECT is(pg_temp.pending('a', 'workout'), 0, 'a paused endpoint enqueues nothing');
+
+UPDATE public.webhook_endpoints
+SET status = 'active', disabled_reason = NULL
+WHERE id = (SELECT id FROM wh_ids WHERE name = 'a');
+
+-- ---------------------------------------------------------------------------
+-- Structural isolation: a delivery cannot pair A's endpoint with B's user id.
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-delivery-owner-fk');
+
+SELECT throws_ok(
+ format(
+ $q$INSERT INTO public.webhook_deliveries (endpoint_id, user_id, entity, entity_id)
+ VALUES (%L, 'd0d0d0d0-0000-4000-8000-00000000000b', 'workout', 'x')$q$,
+ (SELECT id FROM wh_ids WHERE name = 'a')),
+ '23503', NULL,
+ 'a delivery whose user_id is not the endpoint owner violates the composite FK'
+);
+
+-- ---------------------------------------------------------------------------
+-- Claim
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-claim');
+
+UPDATE public.workout_sessions SET notes = 'claim me'
+WHERE id = 'd0d0d0d0-0002-4000-8000-00000000000a';
+
+SELECT is(
+ (SELECT count(*)::int FROM public.claim_webhook_deliveries(100, 30, 180)
+ WHERE delivery_user_id = 'd0d0d0d0-0000-4000-8000-00000000000a'),
+ 0,
+ 'a delivery still inside its settle delay is not claimed'
+);
+
+UPDATE public.webhook_deliveries SET next_attempt_at = now() - interval '1 second'
+WHERE status = 'pending' AND user_id = 'd0d0d0d0-0000-4000-8000-00000000000a';
+
+CREATE TEMP TABLE wh_claim ON COMMIT DROP AS
+SELECT * FROM public.claim_webhook_deliveries(100, 30, 180)
+WHERE delivery_user_id = 'd0d0d0d0-0000-4000-8000-00000000000a';
+
+SELECT is((SELECT count(*)::int FROM wh_claim), 1, 'a due delivery is claimed');
+SELECT is((SELECT delivery_attempt FROM wh_claim), 1, 'the first claim is attempt 1');
+SELECT is(
+ (SELECT d.status FROM public.webhook_deliveries d
+ WHERE d.id = (SELECT delivery_id FROM wh_claim)),
+ 'delivering',
+ 'a claimed delivery is marked delivering'
+);
+
+SELECT is(
+ (SELECT count(*)::int FROM public.claim_webhook_deliveries(100, 30, 180)
+ WHERE delivery_user_id = 'd0d0d0d0-0000-4000-8000-00000000000a'),
+ 0,
+ 'a delivery under a live lease is not claimed twice'
+);
+
+UPDATE public.webhook_deliveries SET claimed_at = now() - interval '10 minutes'
+WHERE id = (SELECT delivery_id FROM wh_claim);
+
+SELECT is(
+ (SELECT delivery_attempt FROM public.claim_webhook_deliveries(100, 30, 180)
+ WHERE delivery_id = (SELECT delivery_id FROM wh_claim)),
+ 2,
+ 'an expired lease is reclaimed as the next attempt'
+);
+
+-- ---------------------------------------------------------------------------
+-- Completion
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-complete');
+
+SELECT is(
+ public.complete_webhook_delivery((SELECT delivery_id FROM wh_claim), 1, 'delivered'),
+ NULL,
+ 'a worker holding a superseded claim cannot complete the delivery'
+);
+
+SELECT throws_ok(
+ format($q$SELECT public.complete_webhook_delivery(%L, 2, 'exploded')$q$,
+ (SELECT delivery_id FROM wh_claim)),
+ '22023', 'webhook_delivery_outcome_invalid',
+ 'an unknown outcome is refused'
+);
+
+SELECT is(
+ public.complete_webhook_delivery(
+ (SELECT delivery_id FROM wh_claim), 2, 'failed', 'workout.updated', 503, 'http_error', 120),
+ 'pending',
+ 'a failed attempt goes back to pending'
+);
+
+SELECT ok(
+ (SELECT d.next_attempt_at > now() + interval '3 minutes'
+ AND d.last_status_code = 503
+ AND d.last_error_code = 'http_error'
+ AND d.claimed_at IS NULL
+ FROM public.webhook_deliveries d WHERE d.id = (SELECT delivery_id FROM wh_claim)),
+ 'the retry is scheduled with backoff and records the status and error code'
+);
+
+SELECT is(
+ (SELECT e.consecutive_failures FROM public.webhook_endpoints e
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ 1,
+ 'a failed attempt counts against the endpoint'
+);
+
+-- Honour Retry-After, capped at one hour.
+UPDATE public.webhook_deliveries
+SET status = 'delivering', attempt_count = 1, claimed_at = now()
+WHERE id = (SELECT delivery_id FROM wh_claim);
+
+SELECT is(
+ public.complete_webhook_delivery(
+ (SELECT delivery_id FROM wh_claim), 1, 'failed', NULL, 429, 'http_error', 5, 99999),
+ 'pending',
+ 'a 429 is rescheduled'
+);
+
+SELECT ok(
+ (SELECT d.next_attempt_at BETWEEN now() + interval '59 minutes' AND now() + interval '61 minutes'
+ FROM public.webhook_deliveries d WHERE d.id = (SELECT delivery_id FROM wh_claim)),
+ 'Retry-After is honoured but capped at one hour'
+);
+
+UPDATE public.webhook_deliveries
+SET status = 'delivering', attempt_count = 3, claimed_at = now()
+WHERE id = (SELECT delivery_id FROM wh_claim);
+
+SELECT is(
+ public.complete_webhook_delivery(
+ (SELECT delivery_id FROM wh_claim), 3, 'delivered', 'workout.updated', 200, NULL, 80),
+ 'delivered',
+ 'a successful attempt is marked delivered'
+);
+
+SELECT ok(
+ (SELECT e.consecutive_failures = 0 AND e.last_success_at IS NOT NULL
+ FROM public.webhook_endpoints e
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ 'a success resets the endpoint failure count'
+);
+
+-- Superseded: the entity changed again while an attempt was in flight.
+INSERT INTO public.webhook_deliveries (id, endpoint_id, user_id, entity, entity_id, status, attempt_count, claimed_at)
+SELECT 'd0d0d0d0-0009-4000-8000-00000000000a', id, 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'workout', 'd0d0d0d0-0002-4000-8000-00000000000a', 'delivering', 1, now()
+FROM wh_ids WHERE name = 'a';
+
+UPDATE public.workout_sessions SET notes = 'changed mid-flight'
+WHERE id = 'd0d0d0d0-0002-4000-8000-00000000000a';
+
+SELECT is(
+ public.complete_webhook_delivery('d0d0d0d0-0009-4000-8000-00000000000a', 1, 'failed', NULL, 500, 'http_error'),
+ 'skipped',
+ 'a failed attempt with a newer pending delivery waiting is closed, not retried'
+);
+
+SELECT is(
+ (SELECT d.last_error_code FROM public.webhook_deliveries d
+ WHERE d.id = 'd0d0d0d0-0009-4000-8000-00000000000a'),
+ 'superseded',
+ 'the closed attempt is labelled superseded'
+);
+
+SELECT pg_temp.settle();
+
+-- Out of attempts: dead, and the endpoint is switched off with a reason.
+INSERT INTO public.webhook_deliveries (id, endpoint_id, user_id, entity, entity_id, status, attempt_count, claimed_at)
+SELECT 'd0d0d0d0-000a-4000-8000-00000000000a', id, 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'workout', 'd0d0d0d0-0002-4000-8000-00000000000a', 'delivering', 9, now()
+FROM wh_ids WHERE name = 'a';
+
+SELECT is(
+ public.complete_webhook_delivery('d0d0d0d0-000a-4000-8000-00000000000a', 9, 'failed', NULL, NULL, 'connection_failed'),
+ 'dead',
+ 'the ninth failed attempt is dead'
+);
+
+SELECT is(
+ (SELECT e.status || '|' || e.disabled_reason FROM public.webhook_endpoints e
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ 'disabled|too_many_failures',
+ 'a dead delivery disables the endpoint with a reason the owner can read'
+);
+
+UPDATE public.workout_sessions SET notes = 'after disable'
+WHERE id = 'd0d0d0d0-0002-4000-8000-00000000000a';
+
+SELECT is(pg_temp.pending('a', 'workout'), 0, 'a disabled endpoint enqueues nothing');
+
+-- 410 Gone on B's endpoint: off at once.
+INSERT INTO public.webhook_deliveries (id, endpoint_id, user_id, entity, entity_id, status, attempt_count, claimed_at)
+SELECT 'd0d0d0d0-000b-4000-8000-00000000000b', id, 'd0d0d0d0-0000-4000-8000-00000000000b',
+ 'routine', 'gone-probe', 'delivering', 1, now()
+FROM wh_ids WHERE name = 'b';
+
+SELECT is(
+ public.complete_webhook_delivery('d0d0d0d0-000b-4000-8000-00000000000b', 1, 'gone', NULL, 410, 'http_error'),
+ 'dead',
+ 'a 410 response is dead on the first attempt'
+);
+
+SELECT is(
+ (SELECT e.status || '|' || e.disabled_reason FROM public.webhook_endpoints e
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'b')),
+ 'disabled|endpoint_gone',
+ 'a 410 response disables the endpoint as endpoint_gone'
+);
+
+-- ---------------------------------------------------------------------------
+-- Tier: a lapsed owner's endpoint is paused by the claim (FP-2).
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-claim-pauses-lapsed-owner');
+
+INSERT INTO wh_ids
+SELECT 'c', public.create_webhook_endpoint(
+ 'd0d0d0d0-0000-4000-8000-00000000000c', 'C main', 'https://hooks.example.test/c',
+ ARRAY['routines'], 'enc:v1:c-secret', 'cccc');
+
+INSERT INTO public.routines (id, user_id, name)
+VALUES ('d0d0d0d0-0004-4000-8000-00000000000c', 'd0d0d0d0-0000-4000-8000-00000000000c', 'C routine');
+
+SELECT is(pg_temp.pending('c', 'routine'), 1, 'the lapsed owner''s write is enqueued while the endpoint is active');
+
+UPDATE public.webhook_deliveries SET next_attempt_at = now() - interval '1 second'
+WHERE user_id = 'd0d0d0d0-0000-4000-8000-00000000000c' AND status = 'pending';
+
+SELECT is(
+ (SELECT count(*)::int FROM public.claim_webhook_deliveries(100, 30, 180)
+ WHERE delivery_user_id = 'd0d0d0d0-0000-4000-8000-00000000000c'),
+ 0,
+ 'nothing is claimed for an owner below FLAME'
+);
+
+SELECT is(
+ (SELECT e.status || '|' || e.disabled_reason FROM public.webhook_endpoints e
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'c')),
+ 'paused|subscription_lapsed',
+ 'the claim pauses the lapsed owner''s endpoint with a reason'
+);
+
+SELECT is(
+ (SELECT d.status || '|' || d.last_error_code FROM public.webhook_deliveries d
+ WHERE d.user_id = 'd0d0d0d0-0000-4000-8000-00000000000c'),
+ 'skipped|subscription_lapsed',
+ 'the lapsed owner''s waiting delivery is closed'
+);
+
+UPDATE public.routines SET name = 'C routine 2'
+WHERE id = 'd0d0d0d0-0004-4000-8000-00000000000c';
+
+SELECT is(pg_temp.pending('c', 'routine'), 0,
+ 'after the pause a further write enqueues nothing');
+
+-- ---------------------------------------------------------------------------
+-- Backfill
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-backfill');
+
+UPDATE public.webhook_endpoints
+SET status = 'active', disabled_reason = NULL
+WHERE id = (SELECT id FROM wh_ids WHERE name = 'a');
+SELECT pg_temp.settle();
+
+SELECT is(
+ public.enqueue_webhook_backfill(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', (SELECT id FROM wh_ids WHERE name = 'a')),
+ 0,
+ 'a backfill requested with another user''s id enqueues nothing'
+);
+
+-- A has: one session, one routine ("Before"), one soft-deleted record (not
+-- replayed) and one non-Strava activity.
+SELECT is(
+ public.enqueue_webhook_backfill(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', (SELECT id FROM wh_ids WHERE name = 'a')),
+ 3,
+ 'a backfill enqueues every live entity in the endpoint''s scopes'
+);
+
+SELECT is(
+ (SELECT count(*)::int FROM public.webhook_deliveries d
+ WHERE d.endpoint_id = (SELECT id FROM wh_ids WHERE name = 'a')
+ AND d.status = 'pending'
+ AND d.user_id <> 'd0d0d0d0-0000-4000-8000-00000000000a'),
+ 0,
+ 'every backfilled delivery carries the endpoint owner''s user id'
+);
+
+SELECT is(
+ public.enqueue_webhook_backfill(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', (SELECT id FROM wh_ids WHERE name = 'a')),
+ 0,
+ 'a second backfill coalesces with the pending rows'
+);
+
+-- ---------------------------------------------------------------------------
+-- Rotation and header
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-rotate-and-header');
+
+SELECT ok(
+ NOT public.rotate_webhook_signing_secret(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', (SELECT id FROM wh_ids WHERE name = 'a'),
+ 'enc:v1:stolen', 'zzzz'),
+ 'another user cannot rotate the endpoint''s secret'
+);
+
+SELECT ok(
+ public.rotate_webhook_signing_secret(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', (SELECT id FROM wh_ids WHERE name = 'a'),
+ 'enc:v1:a-secret-2', 'a222'),
+ 'the owner can rotate the secret'
+);
+
+SELECT is(
+ (SELECT s.signing_secret_enc || '|' || s.previous_signing_secret_enc
+ || '|' || (s.previous_expires_at > now() + interval '23 hours')::text
+ FROM public.webhook_endpoint_secrets s
+ WHERE s.endpoint_id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ 'enc:v1:a-secret-2|enc:v1:a-secret|true',
+ 'rotation keeps the old secret valid for the overlap'
+);
+
+SELECT is(
+ (SELECT e.signing_key_hint FROM public.webhook_endpoints e
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ 'a222',
+ 'rotation updates the visible hint'
+);
+
+SELECT ok(
+ NOT public.set_webhook_endpoint_header(
+ 'd0d0d0d0-0000-4000-8000-00000000000b', (SELECT id FROM wh_ids WHERE name = 'a'),
+ 'X-Api-Key', 'enc:v1:stolen'),
+ 'another user cannot set the endpoint''s header'
+);
+
+SELECT ok(
+ public.set_webhook_endpoint_header(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', (SELECT id FROM wh_ids WHERE name = 'a'),
+ 'X-Api-Key', 'enc:v1:a-header'),
+ 'the owner can set a header'
+);
+
+SELECT ok(
+ public.set_webhook_endpoint_header(
+ 'd0d0d0d0-0000-4000-8000-00000000000a', (SELECT id FROM wh_ids WHERE name = 'a'), NULL, NULL),
+ 'the owner can clear the header'
+);
+
+SELECT is(
+ (SELECT (e.custom_header_name IS NULL AND s.custom_header_value_enc IS NULL)
+ FROM public.webhook_endpoints e
+ JOIN public.webhook_endpoint_secrets s ON s.endpoint_id = e.id
+ WHERE e.id = (SELECT id FROM wh_ids WHERE name = 'a')),
+ true,
+ 'clearing removes both the name and the encrypted value'
+);
+
+-- ---------------------------------------------------------------------------
+-- Retention
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-retention');
+
+INSERT INTO public.webhook_deliveries (id, endpoint_id, user_id, entity, entity_id, status, created_at, finished_at)
+SELECT 'd0d0d0d0-000c-4000-8000-00000000000a', id, 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'workout', 'old', 'delivered', now() - interval '31 days', now() - interval '31 days'
+FROM wh_ids WHERE name = 'a';
+
+INSERT INTO public.webhook_deliveries (id, endpoint_id, user_id, entity, entity_id, status, created_at, finished_at)
+SELECT 'd0d0d0d0-000d-4000-8000-00000000000a', id, 'd0d0d0d0-0000-4000-8000-00000000000a',
+ 'workout', 'recent', 'delivered', now() - interval '29 days', now() - interval '29 days'
+FROM wh_ids WHERE name = 'a';
+
+SELECT ok(private.prune_webhook_deliveries() >= 1, 'retention deletes finished deliveries');
+
+SELECT is(
+ (SELECT string_agg(d.entity_id, ',' ORDER BY d.entity_id) FROM public.webhook_deliveries d
+ WHERE d.id IN ('d0d0d0d0-000c-4000-8000-00000000000a', 'd0d0d0d0-000d-4000-8000-00000000000a')),
+ 'recent',
+ 'only deliveries older than 30 days are deleted'
+);
+
+-- ---------------------------------------------------------------------------
+-- Account deletion (FP-6). The capture triggers fire while the user's rows
+-- cascade away; nothing may be left behind and nothing may abort the delete.
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-account-deletion-cascade');
+
+SELECT lives_ok(
+ $q$DELETE FROM auth.users WHERE id = 'd0d0d0d0-0000-4000-8000-00000000000a'$q$,
+ 'deleting a user with an active endpoint and pending deliveries succeeds'
+);
+
+SELECT is(
+ (SELECT (SELECT count(*) FROM public.webhook_endpoints WHERE user_id = 'd0d0d0d0-0000-4000-8000-00000000000a')
+ + (SELECT count(*) FROM public.webhook_endpoint_secrets WHERE user_id = 'd0d0d0d0-0000-4000-8000-00000000000a')
+ + (SELECT count(*) FROM public.webhook_deliveries WHERE user_id = 'd0d0d0d0-0000-4000-8000-00000000000a'))::int,
+ 0,
+ 'the deleted user''s endpoints, secrets and deliveries are gone'
+);
+
+SELECT * FROM finish();
+ROLLBACK;
diff --git a/tests/security/data-sharing-scopes.test.ts b/tests/security/data-sharing-scopes.test.ts
new file mode 100644
index 00000000..fe4973d4
--- /dev/null
+++ b/tests/security/data-sharing-scopes.test.ts
@@ -0,0 +1,279 @@
+/**
+ * Data sharing (outbound webhooks): the scope registry cannot drift.
+ *
+ * Three places describe what a user may send to their own endpoint:
+ * - supabase/functions/_shared/dataSharingScopes.ts (payload builder, SPA);
+ * - private.webhook_entity_sources in the 20261106120000 migration (capture
+ * triggers and backfill);
+ * - USER_DATA_MANIFEST (column lists, and the list of every user table).
+ *
+ * A table that is captured but not built, or built but not captured, would
+ * either deliver nothing or silently skip changes. A new user table that is in
+ * neither an entity nor NOT_SHAREABLE would have been decided by default.
+ */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ DATA_SHARING_ENTITIES,
+ DATA_SHARING_OMITTED_COLUMNS,
+ DATA_SHARING_SCOPE_INFO,
+ DATA_SHARING_SCOPES,
+ MAX_WEBHOOK_ENDPOINTS,
+ NOT_SHAREABLE,
+} from "../../supabase/functions/_shared/dataSharingScopes.ts";
+import {
+ getUserDataTable,
+ USER_DATA_MANIFEST,
+} from "../../supabase/functions/_shared/userDataManifest.ts";
+
+const migration = readFileSync(
+ join(
+ process.cwd(),
+ "supabase/migrations/20261106120000_webhook_data_sharing.sql",
+ ),
+ "utf8",
+);
+
+interface SourceRow {
+ sourceTable: string;
+ scope: string;
+ entity: string;
+ isRoot: boolean;
+ idColumn: string;
+ userColumn: string | null;
+ parentTable: string | null;
+ rowFilter: string | null;
+}
+
+function sqlValue(raw: string): string | null {
+ const value = raw.trim();
+ if (value === "NULL") return null;
+ return value.replace(/^'|'$/g, "").replace(/''/g, "'");
+}
+
+/** The VALUES rows of the private.webhook_entity_sources seed. */
+function parseEntitySources(sql: string): SourceRow[] {
+ const start = sql.indexOf("INSERT INTO private.webhook_entity_sources");
+ const end = sql.indexOf("ON CONFLICT (source_table) DO UPDATE", start);
+ expect(start, "entity source seed not found").toBeGreaterThan(-1);
+ expect(end, "entity source seed end not found").toBeGreaterThan(start);
+ const rows: SourceRow[] = [];
+ for (const line of sql.slice(start, end).split("\n")) {
+ const match = line.match(/^\s*\((.*)\),?\s*$/);
+ if (!match || !match[1].trim().startsWith("'")) continue;
+ // Split on commas outside quotes.
+ const cells = match[1].match(/'(?:[^']|'')*'|[^,]+/g) ?? [];
+ const [
+ sourceTable,
+ scope,
+ entity,
+ isRoot,
+ idColumn,
+ userColumn,
+ parentTable,
+ rowFilter,
+ ] = cells.map((cell) => cell.trim());
+ rows.push({
+ sourceTable: sqlValue(sourceTable) ?? "",
+ scope: sqlValue(scope) ?? "",
+ entity: sqlValue(entity) ?? "",
+ isRoot: isRoot === "true",
+ idColumn: sqlValue(idColumn) ?? "",
+ userColumn: sqlValue(userColumn),
+ parentTable: sqlValue(parentTable),
+ rowFilter: sqlValue(rowFilter),
+ });
+ }
+ return rows;
+}
+
+/** The quoted names between `after` (which ends at the list's opener) and `closer`. */
+function quotedList(sql: string, after: string, closer: string): string[] {
+ const start = sql.indexOf(after);
+ expect(start, `${after} not found`).toBeGreaterThan(-1);
+ const open = start + after.length;
+ const close = sql.indexOf(closer, open);
+ return [...sql.slice(open, close).matchAll(/'([a-z_]+)'/g)].map(
+ (match) => match[1],
+ );
+}
+
+const sources = parseEntitySources(migration);
+
+describe("data sharing scope registry", () => {
+ it("parses the migration's entity sources", () => {
+ // Not vacuous: a broken parser would make every comparison below pass.
+ expect(sources.length).toBeGreaterThanOrEqual(15);
+ expect(
+ sources.find((row) => row.sourceTable === "workout_sessions"),
+ ).toEqual({
+ sourceTable: "workout_sessions",
+ scope: "workouts",
+ entity: "workout",
+ isRoot: true,
+ idColumn: "id",
+ userColumn: "user_id",
+ parentTable: null,
+ rowFilter: null,
+ });
+ expect(
+ sources.find((row) => row.sourceTable === "routine_exercises"),
+ ).toMatchObject({
+ isRoot: false,
+ userColumn: null,
+ parentTable: "routines",
+ });
+ });
+
+ it("has one entity per root source, with the same table, scope and key columns", () => {
+ const fromSql = sources
+ .filter((row) => row.isRoot)
+ .map((row) => ({
+ entity: row.entity,
+ scope: row.scope,
+ table: row.sourceTable,
+ idColumn: row.idColumn,
+ userColumn: row.userColumn,
+ }))
+ .sort((a, b) => a.entity.localeCompare(b.entity));
+ const fromTs = DATA_SHARING_ENTITIES.map((entry) => ({
+ entity: entry.entity,
+ scope: entry.scope,
+ table: entry.table,
+ idColumn: entry.idColumn,
+ userColumn: entry.userColumn,
+ })).sort((a, b) => a.entity.localeCompare(b.entity));
+ expect(fromTs).toEqual(fromSql);
+ });
+
+ it("captures child tables only for an entity that builds them into its payload", () => {
+ for (const row of sources.filter((source) => !source.isRoot)) {
+ const entity = DATA_SHARING_ENTITIES.find(
+ (entry) => entry.entity === row.entity,
+ );
+ expect(entity, row.sourceTable).toBeDefined();
+ const child = entity?.children.find(
+ (entry) => entry.table === row.sourceTable,
+ );
+ expect(
+ child,
+ `${row.sourceTable} is captured but not a payload child`,
+ ).toBeDefined();
+ // The capture records the parent id found in this column.
+ expect(child?.fkColumn).toBe(row.idColumn);
+ expect(child?.parent).toBe(entity?.table);
+ }
+ });
+
+ it("excludes in the trigger exactly what the payload builder excludes", () => {
+ for (const entity of DATA_SHARING_ENTITIES) {
+ const row = sources.find((source) => source.sourceTable === entity.table);
+ if (entity.exclude) {
+ expect(row?.rowFilter).toBe(
+ `c.${entity.exclude.column} IS DISTINCT FROM '${entity.exclude.equals}'`,
+ );
+ } else {
+ expect(row?.rowFilter, entity.table).toBeNull();
+ }
+ }
+ });
+
+ it("allows the same scopes and entities in the table constraints", () => {
+ expect(quotedList(migration, "scopes <@ ARRAY[", "]").sort()).toEqual(
+ [...DATA_SHARING_SCOPES].sort(),
+ );
+ expect(quotedList(migration, "CHECK (entity IN (", ")").sort()).toEqual(
+ [...DATA_SHARING_ENTITIES.map((entry) => entry.entity), "ping"].sort(),
+ );
+ expect(migration).toContain(
+ `c_max_endpoints CONSTANT integer := ${MAX_WEBHOOK_ENDPOINTS};`,
+ );
+ });
+
+ it("describes every scope once, and every scope has an entity", () => {
+ expect(DATA_SHARING_SCOPE_INFO.map((info) => info.scope)).toEqual([
+ ...DATA_SHARING_SCOPES,
+ ]);
+ for (const scope of DATA_SHARING_SCOPES) {
+ expect(
+ DATA_SHARING_ENTITIES.some((entry) => entry.scope === scope),
+ scope,
+ ).toBe(true);
+ }
+ });
+
+ it("classifies every manifest table as shared or not shareable, never both", () => {
+ const shared = new Set();
+ for (const entity of DATA_SHARING_ENTITIES) {
+ shared.add(entity.table);
+ for (const child of entity.children) shared.add(child.table);
+ }
+ const unclassified = USER_DATA_MANIFEST.map((entry) => entry.table).filter(
+ (table) => !shared.has(table) && !(table in NOT_SHAREABLE),
+ );
+ expect(unclassified).toEqual([]);
+ expect([...shared].filter((table) => table in NOT_SHAREABLE)).toEqual([]);
+ // No stale names in either list.
+ const manifestTables = new Set(
+ USER_DATA_MANIFEST.map((entry) => entry.table),
+ );
+ expect([...shared].filter((table) => !manifestTables.has(table))).toEqual(
+ [],
+ );
+ expect(
+ Object.keys(NOT_SHAREABLE).filter((table) => !manifestTables.has(table)),
+ ).toEqual([]);
+ });
+
+ it("builds payloads only from columns the manifest exports", () => {
+ for (const entity of DATA_SHARING_ENTITIES) {
+ const root = getUserDataTable(entity.table);
+ expect(root?.columns, entity.table).toContain(entity.idColumn);
+ expect(root?.columns, entity.table).toContain(entity.userColumn);
+ if (entity.softDeleteColumn) {
+ expect(root?.columns).toContain(entity.softDeleteColumn);
+ }
+ if (entity.exclude) {
+ expect(root?.columns).toContain(entity.exclude.column);
+ }
+ const known = new Set([entity.table]);
+ for (const child of entity.children) {
+ // A child hangs off the entity's table or an earlier child.
+ expect(
+ known.has(child.parent),
+ `${child.table} -> ${child.parent}`,
+ ).toBe(true);
+ const manifest = getUserDataTable(child.table);
+ expect(manifest?.columns, child.table).toContain(child.fkColumn);
+ expect(manifest?.columns, child.table).toContain("id");
+ known.add(child.table);
+ }
+ }
+ for (const [table, columns] of Object.entries(
+ DATA_SHARING_OMITTED_COLUMNS,
+ )) {
+ const manifest = getUserDataTable(table);
+ for (const column of columns) {
+ expect(manifest?.columns, `${table}.${column}`).toContain(column);
+ }
+ }
+ });
+
+ it("never shares a table whose reads are INFERNO-gated or that holds raw telemetry", () => {
+ // FP-2: a FLAME endpoint must not carry what its owner cannot read.
+ const shared = DATA_SHARING_ENTITIES.flatMap((entry) => [
+ entry.table,
+ ...entry.children.map((child) => child.table),
+ ]);
+ for (const table of [
+ "rep_telemetry",
+ "set_telemetry",
+ "session_phase_statistics",
+ "vbt_assessments",
+ "exercise_signatures",
+ ]) {
+ expect(shared, table).not.toContain(table);
+ }
+ });
+});
From 2dc2b4b2b5250bdcb46cb32613e4b6472aff3d52 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:12:20 -0500
Subject: [PATCH 02/11] fix(data-sharing): prove capture never aborts a write;
close completion race
- pgTAP: with the outbox made to reject the row, the user's write must still
succeed (FP-3). Verified to fail when the trigger's exception handler is
removed.
- complete_webhook_delivery: a pending row committed between the superseded
check and the reschedule no longer surfaces as a unique violation; the
attempt is closed as superseded.
- Raise PGTAP_TEST_FLOOR to the suite's actual count.
- Operator note on trigger lock contention.
Co-Authored-By: Claude Fable 5.1
---
.github/workflows/migrations.yml | 2 +-
.../20261106120000_webhook_data_sharing.sql | 43 ++++++++++++++-----
.../database/webhook_data_sharing.test.sql | 31 +++++++++++++
3 files changed, 65 insertions(+), 11 deletions(-)
diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml
index 9d9a1dad..45c1a6cd 100644
--- a/.github/workflows/migrations.yml
+++ b/.github/workflows/migrations.yml
@@ -188,7 +188,7 @@ jobs:
env:
# Minimum aggregate Tests= for the suite. Raise this when
# assertions are added.
- PGTAP_TEST_FLOOR: "2139"
+ PGTAP_TEST_FLOOR: "2246"
run: |
set -euo pipefail
log="${RUNNER_TEMP}/pgtap-suite.log"
diff --git a/supabase/migrations/20261106120000_webhook_data_sharing.sql b/supabase/migrations/20261106120000_webhook_data_sharing.sql
index 5be8e046..c0b6703d 100644
--- a/supabase/migrations/20261106120000_webhook_data_sharing.sql
+++ b/supabase/migrations/20261106120000_webhook_data_sharing.sql
@@ -46,6 +46,13 @@
-- Idempotent: safe to re-run. Re-applying never flips a cron job's `active`
-- flag and re-issues every grant.
--
+-- Operator, applying this file: it creates three triggers on each of the
+-- busiest tables (workout_sessions, exercises, personal_records, routines,
+-- ...), and each CREATE TRIGGER needs a brief lock that waits behind any
+-- write in progress. Run it, and its BEGIN ... ROLLBACK rehearsal, at low
+-- traffic. A `lock_timeout` failure is a clean retry: the file is one
+-- transaction, so nothing was applied.
+--
-- Operator, after the `deliver-webhooks` Edge Function is deployed:
-- SELECT cron.alter_job(
-- (SELECT jobid FROM cron.job WHERE jobname = 'deliver-webhooks'),
@@ -753,16 +760,32 @@ BEGIN
v_next := pg_catalog.now() + pg_catalog.make_interval(secs => v_wait);
END IF;
- UPDATE public.webhook_deliveries d
- SET status = v_status,
- event_type = coalesce(p_event_type, d.event_type),
- last_status_code = p_status_code,
- last_error_code = v_error,
- duration_ms = p_duration_ms,
- next_attempt_at = coalesce(v_next, d.next_attempt_at),
- claimed_at = NULL,
- finished_at = CASE WHEN v_status = 'pending' THEN NULL ELSE pg_catalog.now() END
- WHERE d.id = v_row.id;
+ BEGIN
+ UPDATE public.webhook_deliveries d
+ SET status = v_status,
+ event_type = coalesce(p_event_type, d.event_type),
+ last_status_code = p_status_code,
+ last_error_code = v_error,
+ duration_ms = p_duration_ms,
+ next_attempt_at = coalesce(v_next, d.next_attempt_at),
+ claimed_at = NULL,
+ finished_at = CASE WHEN v_status = 'pending' THEN NULL ELSE pg_catalog.now() END
+ WHERE d.id = v_row.id;
+ EXCEPTION WHEN unique_violation THEN
+ -- A capture trigger committed a pending row for the same entity between
+ -- the EXISTS check above and this UPDATE (READ COMMITTED). Same outcome
+ -- as finding it up front: the newer row carries the current state.
+ v_status := 'skipped';
+ UPDATE public.webhook_deliveries d
+ SET status = 'skipped',
+ event_type = coalesce(p_event_type, d.event_type),
+ last_status_code = p_status_code,
+ last_error_code = 'superseded',
+ duration_ms = p_duration_ms,
+ claimed_at = NULL,
+ finished_at = pg_catalog.now()
+ WHERE d.id = v_row.id;
+ END;
IF p_outcome = 'delivered' THEN
UPDATE public.webhook_endpoints e
diff --git a/supabase/tests/database/webhook_data_sharing.test.sql b/supabase/tests/database/webhook_data_sharing.test.sql
index b7536f95..203ba31e 100644
--- a/supabase/tests/database/webhook_data_sharing.test.sql
+++ b/supabase/tests/database/webhook_data_sharing.test.sql
@@ -378,6 +378,37 @@ SELECT is(pg_temp.pending('a', 'external_activity'), 1,
SELECT pg_temp.settle();
+-- ---------------------------------------------------------------------------
+-- FP-3: a capture that fails must not abort the user's write.
+-- The outbox is made to reject routine rows; the routine must still be saved.
+-- ---------------------------------------------------------------------------
+SELECT diag('database:webhook-capture-failure-never-aborts-the-write');
+
+ALTER TABLE public.webhook_deliveries
+ ADD CONSTRAINT wh_force_capture_failure CHECK (entity <> 'routine') NOT VALID;
+
+SELECT lives_ok(
+ $q$INSERT INTO public.routines (id, user_id, name)
+ VALUES ('d0d0d0d0-000e-4000-8000-00000000000a',
+ 'd0d0d0d0-0000-4000-8000-00000000000a', 'Survives a broken outbox')$q$,
+ 'a write succeeds even when its webhook capture fails'
+);
+
+SELECT is(
+ (SELECT count(*)::int FROM public.routines
+ WHERE id = 'd0d0d0d0-000e-4000-8000-00000000000a'),
+ 1,
+ 'the row written during the failed capture is stored'
+);
+
+SELECT is(pg_temp.pending('a', 'routine'), 0,
+ 'the failed capture left no delivery behind');
+
+ALTER TABLE public.webhook_deliveries DROP CONSTRAINT wh_force_capture_failure;
+
+DELETE FROM public.routines WHERE id = 'd0d0d0d0-000e-4000-8000-00000000000a';
+SELECT pg_temp.settle();
+
-- ---------------------------------------------------------------------------
-- A paused endpoint captures nothing.
-- ---------------------------------------------------------------------------
From 32ad07e9ff95ca2b337a2f53b58c0936da003a65 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:23:04 -0500
Subject: [PATCH 03/11] feat(data-sharing): webhook-endpoints Edge Function
with SSRF guard and signing
The one write path for a user's outbound webhook endpoints (FLAME+):
create, update, rotate_secret, test, resend_all, delete.
- _shared/webhookTarget.ts: the only code that may fetch a user-chosen URL.
https only, public addresses only (literal and every resolved address,
checked on save and before each send, failing closed), own hosts refused,
redirects never followed, response body never read. DNS rebinding is
documented there as a residual risk and bounded, not claimed solved.
- _shared/webhookSigning.ts: Standard Webhooks headers; the HMAC key is the
base64-decoded secret, pinned by the specification's reference vector.
- _shared/webhookSend.ts: one signed POST and a fixed outcome code. The request
carries no Supabase credential (asserted) and nothing of the response but
its status is kept.
- webhook-endpoints: user id from the verified JWT only; every query scoped by
it, so another user's endpoint is a 404 for every action (FP-1). delete and a
pause run before the FLAME gate so a lapsed user can always stop sharing
(FP-2). The signing secret is returned once and never logged (FP-5).
Requests to a user-chosen host have their own tight rate-limit key.
Responses go through an explicit column allowlist.
Verified by mutation: removing the owner filter or the tier gate turns the
isolation tests red.
Co-Authored-By: Claude Fable 5.1
---
CLAUDE.md | 30 +
supabase/config.toml | 5 +
supabase/functions/_shared/requestBody.ts | 2 +
.../functions/_shared/testing/fakeSupabase.ts | 10 +
.../functions/_shared/webhookCredentials.ts | 67 ++
.../functions/_shared/webhookSend.test.ts | 265 +++++++
supabase/functions/_shared/webhookSend.ts | 149 ++++
.../functions/_shared/webhookSigning.test.ts | 79 +++
supabase/functions/_shared/webhookSigning.ts | 99 +++
.../functions/_shared/webhookTarget.test.ts | 233 ++++++
supabase/functions/_shared/webhookTarget.ts | 373 ++++++++++
.../functions/webhook-endpoints/index.test.ts | 643 +++++++++++++++++
supabase/functions/webhook-endpoints/index.ts | 670 ++++++++++++++++++
13 files changed, 2625 insertions(+)
create mode 100644 supabase/functions/_shared/webhookCredentials.ts
create mode 100644 supabase/functions/_shared/webhookSend.test.ts
create mode 100644 supabase/functions/_shared/webhookSend.ts
create mode 100644 supabase/functions/_shared/webhookSigning.test.ts
create mode 100644 supabase/functions/_shared/webhookSigning.ts
create mode 100644 supabase/functions/_shared/webhookTarget.test.ts
create mode 100644 supabase/functions/_shared/webhookTarget.ts
create mode 100644 supabase/functions/webhook-endpoints/index.test.ts
create mode 100644 supabase/functions/webhook-endpoints/index.ts
diff --git a/CLAUDE.md b/CLAUDE.md
index df083919..3387036b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -92,6 +92,7 @@ Edge Function secrets (Supabase Dashboard → Edge Functions → Secrets; read w
- `SYNC_LWW_ENABLED` — cold-start flag in `supabase/functions/_shared/flags.ts`, `"false"` unless the secret is trimmed any-case `true` (`parseBoolFlag`). Flipping it requires a redeploy; there is no runtime refresh. Its production value is not recorded in this repo — ask the operator rather than assuming.
- `SYNC_PUSH_TRANSACTION` — cold-start flag in the same file, `"false"` unless the secret is trimmed any-case `true` (`parseBoolFlag`). When on, `mobile-sync-push` runs its whole write sequence in one Postgres transaction (F-014, `_shared/pushTransaction.ts`): a failure part-way commits nothing, and the `sync_complete` broadcast happens only after COMMIT. It connects with `SUPABASE_DB_URL` (provided by Supabase to Edge Functions); if that connection cannot be opened the push falls back to per-call writes and logs `PushTransactionUnavailable`. The response contract is identical either way.
- `OAUTH_TOKEN_ENCRYPTION_KEY`, `STRAVA_CLIENT_ID` / `STRAVA_CLIENT_SECRET`, `FITBIT_CLIENT_ID` / `FITBIT_CLIENT_SECRET`, `GARMIN_CONSUMER_KEY` / `GARMIN_CONSUMER_SECRET`, `GARMIN_WEBHOOK_SECRET` (the webhook 503s without it). The Fitbit client secrets are still read by `complete-oauth`, `fitbit-sync` and `_shared/providerRevoke.ts`, the Garmin consumer secrets only by `_shared/providerRevoke.ts`; the disabled `fitbit-oauth` / `garmin-oauth` callbacks read none.
+- `OAUTH_TOKEN_ENCRYPTION_KEY` also encrypts data-sharing webhook signing secrets and custom header values (`webhook_endpoint_secrets`, written by `webhook-endpoints`); there is no separate webhook key.
Tooling only: `SUPABASE_PROJECT_REF` and the `SUPABASE_AUTH_*` values used by
`npm run auth:social:push`; `LINEAR_API_KEY` for Symphony.
@@ -193,6 +194,7 @@ a map, not a count.
- **Mobile:** mobile-sync-push, mobile-sync-pull, mobile-integration-sync
- **Account / GDPR:** delete-account, export-user-data
- **Integrations:** disconnect-integration
+- **Data sharing:** webhook-endpoints (FLAME+; the only write path for a user's outbound webhook endpoints. Reads go through owner RLS on `webhook_endpoints` / `webhook_deliveries`)
- **Analytics:** generate-insights
- **Rankings:** compute-rankings
@@ -215,6 +217,34 @@ requires an `Authorization` header and verifies the caller itself, 401ing
without one. **A gateway `verify_jwt = false` never means "unauthenticated" —
read the handler.**
+### Data sharing (outbound webhooks)
+
+A FLAME+ user registers up to three HTTPS endpoints and the portal POSTs their
+own data there as signed events. Read `supabase/functions/_shared/dataSharingScopes.ts`
+before adding a table to it.
+
+- **Capture is by DB trigger, not in `mobile-sync-push`.** Statement-level
+ triggers generated from `private.webhook_entity_sources`
+ (`20261106120000`) insert thin rows into `webhook_deliveries`; the payload
+ is built at send time. A capture error is a WARNING, never an aborted write.
+- **Three lists must agree** (`tests/security/data-sharing-scopes.test.ts`):
+ `dataSharingScopes.ts`, `private.webhook_entity_sources`, and
+ `USER_DATA_MANIFEST`. Every manifest table is either part of an entity or in
+ `NOT_SHAREABLE` with a reason. Never share an INFERNO-gated table, raw
+ telemetry, or Strava-sourced `external_activities` rows.
+- **`_shared/webhookTarget.ts` is the only code that may fetch a user-chosen
+ URL.** https only, public addresses only (checked on save and before every
+ send), redirects never followed, response body never read. DNS rebinding is
+ a stated residual risk there, not a solved one. Send through
+ `_shared/webhookSend.ts`; it adds no Supabase credential and a test asserts
+ that.
+- **Signing is Standard Webhooks** (`_shared/webhookSigning.ts`): the HMAC key
+ is the base64-decoded bytes after `whsec_`. The reference vector in
+ `webhookSigning.test.ts` fails if that changes.
+- The signing secret is returned once, by `create` and `rotate_secret`.
+ `delete` and a pause run before the tier gate so a lapsed user can always
+ stop sharing.
+
### The mobile sync contract
Read `supabase/functions/mobile-sync-push/index.ts` and
diff --git a/supabase/config.toml b/supabase/config.toml
index 8430f863..74327696 100644
--- a/supabase/config.toml
+++ b/supabase/config.toml
@@ -148,3 +148,8 @@ verify_jwt = false
[functions.strava-sync]
verify_jwt = true
+
+[functions.webhook-endpoints]
+# Data sharing: the user's JWT is the only credential. The handler also
+# calls auth.getUser() with it and scopes every query by that user id.
+verify_jwt = true
diff --git a/supabase/functions/_shared/requestBody.ts b/supabase/functions/_shared/requestBody.ts
index cedca63b..927240cd 100644
--- a/supabase/functions/_shared/requestBody.ts
+++ b/supabase/functions/_shared/requestBody.ts
@@ -47,6 +47,8 @@ export async function readBoundedRequestBody(request: Request, limit: number): P
export const REQUEST_BODY_LIMITS = {
deleteAccount: 4 * 1024,
generateInsights: 16 * 1024,
+ // A label, a URL (2,048 max), nine scope names and one header value (512 max).
+ webhookEndpoints: 16 * 1024,
garminWebhook: 1024 * 1024,
paddleWebhook: 1024 * 1024,
// Five parity ID lists may each contain 10,000 UUIDs (~1.95 MB total).
diff --git a/supabase/functions/_shared/testing/fakeSupabase.ts b/supabase/functions/_shared/testing/fakeSupabase.ts
index b54cbe8a..cb6ea1c8 100644
--- a/supabase/functions/_shared/testing/fakeSupabase.ts
+++ b/supabase/functions/_shared/testing/fakeSupabase.ts
@@ -176,6 +176,7 @@ export class FakeQuery implements PromiseLike {
private orderBy: { col: string; asc: boolean } | null = null;
private max: number | null = null;
private returning = false;
+ private deleting = false;
constructor(private rows: Row[], private uniqueIndexes: FakeUniqueIndex[] = []) {}
@@ -184,6 +185,11 @@ export class FakeQuery implements PromiseLike {
if (this.insertRows) this.returning = true;
return this;
}
+ /** `delete().eq(...)`: removes the matching rows; `.select()` returns them. */
+ delete() {
+ this.deleting = true;
+ return this;
+ }
update(patch: Row) {
this.patch = patch;
return this;
@@ -306,6 +312,10 @@ export class FakeQuery implements PromiseLike {
return { data: copies[0] ?? null, error: null };
}
let matched = this.rows.filter((r) => this.filters.every((f) => f(r)));
+ if (this.deleting) {
+ for (const row of matched) this.rows.splice(this.rows.indexOf(row), 1);
+ return { data: matched.map((r) => ({ ...r })), error: null };
+ }
if (this.patch) {
// Unique indexes hold for UPDATEs too, all or nothing (as Postgres).
const patched = matched.map((r) => ({ ...r, ...this.patch }));
diff --git a/supabase/functions/_shared/webhookCredentials.ts b/supabase/functions/_shared/webhookCredentials.ts
new file mode 100644
index 00000000..bb62b4b3
--- /dev/null
+++ b/supabase/functions/_shared/webhookCredentials.ts
@@ -0,0 +1,67 @@
+/**
+ * Reads and decrypts one endpoint's signing secrets and custom header.
+ *
+ * The only reader of webhook_endpoint_secrets. Every lookup is scoped by the
+ * endpoint id AND its owner's user id, so a caller holding the wrong user id
+ * gets nothing (FP-1). Plaintext exists only in the returned object; callers
+ * must not log it or put it in a response (FP-5).
+ */
+import type { SupabaseClient } from 'jsr:@supabase/supabase-js@2';
+
+export interface WebhookCredentials {
+ /** Current secret first, then the previous one while its overlap lasts. */
+ secrets: string[];
+ customHeader: { name: string; value: string } | null;
+}
+
+export type WebhookCredentialsResult =
+ | { ok: true; credentials: WebhookCredentials }
+ | { ok: false; reason: 'not_found' | 'read_failed' | 'decrypt_failed' };
+
+export type SecretDecryptor = (stored: string) => Promise;
+
+export async function loadWebhookCredentials(
+ admin: SupabaseClient,
+ params: { userId: string; endpointId: string; customHeaderName: string | null; now: Date },
+ decrypt: SecretDecryptor,
+): Promise {
+ const { data, error } = await admin
+ .from('webhook_endpoint_secrets')
+ .select('signing_secret_enc, previous_signing_secret_enc, previous_expires_at, custom_header_value_enc')
+ .eq('endpoint_id', params.endpointId)
+ .eq('user_id', params.userId)
+ .maybeSingle();
+ if (error) return { ok: false, reason: 'read_failed' };
+ if (!data) return { ok: false, reason: 'not_found' };
+
+ const row = data as {
+ signing_secret_enc: string;
+ previous_signing_secret_enc: string | null;
+ previous_expires_at: string | null;
+ custom_header_value_enc: string | null;
+ };
+
+ try {
+ const current = await decrypt(row.signing_secret_enc);
+ if (!current) return { ok: false, reason: 'decrypt_failed' };
+ const secrets = [current];
+
+ const previousLive = row.previous_signing_secret_enc !== null &&
+ row.previous_expires_at !== null &&
+ Date.parse(row.previous_expires_at) > params.now.getTime();
+ if (previousLive) {
+ const previous = await decrypt(row.previous_signing_secret_enc!);
+ if (previous) secrets.push(previous);
+ }
+
+ let customHeader: WebhookCredentials['customHeader'] = null;
+ if (params.customHeaderName !== null && row.custom_header_value_enc !== null) {
+ const value = await decrypt(row.custom_header_value_enc);
+ if (!value) return { ok: false, reason: 'decrypt_failed' };
+ customHeader = { name: params.customHeaderName, value };
+ }
+ return { ok: true, credentials: { secrets, customHeader } };
+ } catch {
+ return { ok: false, reason: 'decrypt_failed' };
+ }
+}
diff --git a/supabase/functions/_shared/webhookSend.test.ts b/supabase/functions/_shared/webhookSend.test.ts
new file mode 100644
index 00000000..d92a21b4
--- /dev/null
+++ b/supabase/functions/_shared/webhookSend.test.ts
@@ -0,0 +1,265 @@
+import { assert, assertEquals } from "jsr:@std/assert@1";
+import {
+ sendWebhook,
+ WEBHOOK_API_VERSION,
+ WEBHOOK_MAX_BODY_BYTES,
+ WEBHOOK_USER_AGENT,
+ webhookEnvelope,
+ type WebhookSendDependencies,
+} from "./webhookSend.ts";
+import { signWebhook } from "./webhookSigning.ts";
+import type { DnsResolver } from "./webhookTarget.ts";
+
+const SECRET = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
+const OLD_SECRET = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD";
+const NOW = new Date("2026-11-06T12:00:00.000Z");
+const URL_OK = "https://hooks.example.com/in";
+
+interface Seen {
+ url: string;
+ init: RequestInit;
+}
+
+function harness(
+ respond: (seen: Seen) => Response | Promise,
+ dns: Record = { "hooks.example.com/A": ["93.184.216.34"] },
+) {
+ const calls: Seen[] = [];
+ const lookups: string[] = [];
+ const resolveDns: DnsResolver = (hostname, recordType) => {
+ lookups.push(`${hostname}/${recordType}`);
+ return Promise.resolve(dns[`${hostname}/${recordType}`] ?? []);
+ };
+ const deps: WebhookSendDependencies = {
+ fetch: ((input: string | URL | Request, init?: RequestInit) => {
+ const seen = { url: String(input), init: init ?? {} };
+ calls.push(seen);
+ return Promise.resolve(respond(seen));
+ }) as typeof fetch,
+ resolveDns,
+ ownHosts: ["abcdefghijklmnopqrst.supabase.co"],
+ now: () => NOW,
+ };
+ return { deps, calls, lookups };
+}
+
+function input(overrides: Partial[1]> = {}) {
+ return {
+ url: URL_OK,
+ deliveryId: "11111111-1111-4111-8111-111111111111",
+ secrets: [SECRET],
+ customHeader: null,
+ body: '{"type":"ping"}',
+ ...overrides,
+ };
+}
+
+Deno.test("webhookSend: a 2xx answer is delivered and the request is signed over the exact body", async () => {
+ const { deps, calls } = harness(() => new Response("ignored", { status: 200 }));
+
+ const result = await sendWebhook(deps, input());
+
+ assertEquals(result.outcome, "delivered");
+ assertEquals(result.statusCode, 200);
+ assertEquals(result.errorCode, null);
+ assertEquals(calls.length, 1);
+ assertEquals(calls[0].url, URL_OK);
+ const headers = calls[0].init.headers as Record;
+ const timestamp = Math.floor(NOW.getTime() / 1000);
+ assertEquals(headers["webhook-id"], "11111111-1111-4111-8111-111111111111");
+ assertEquals(headers["webhook-timestamp"], String(timestamp));
+ assertEquals(
+ headers["webhook-signature"],
+ await signWebhook(SECRET, "11111111-1111-4111-8111-111111111111", timestamp, '{"type":"ping"}'),
+ );
+ assertEquals(calls[0].init.body, '{"type":"ping"}');
+});
+
+Deno.test("webhookSend: the request carries no Supabase credential, only the fixed headers and the user's one header", async () => {
+ // Arrange: an environment full of things that must not leak into a request.
+ Deno.env.set("SUPABASE_SERVICE_ROLE_KEY", "service-role-key-must-not-leave");
+ Deno.env.set("SUPABASE_ANON_KEY", "anon-key-must-not-leave");
+ const { deps, calls } = harness(() => new Response(null, { status: 204 }));
+
+ try {
+ // Act
+ await sendWebhook(deps, input());
+ await sendWebhook(deps, input({ customHeader: { name: "X-Api-Key", value: "receiver-key" } }));
+ } finally {
+ Deno.env.delete("SUPABASE_SERVICE_ROLE_KEY");
+ Deno.env.delete("SUPABASE_ANON_KEY");
+ }
+
+ // Assert: exactly the fixed set, nothing else.
+ const plain = calls[0].init.headers as Record;
+ assertEquals(Object.keys(plain).sort(), [
+ "content-type",
+ "user-agent",
+ "webhook-id",
+ "webhook-signature",
+ "webhook-timestamp",
+ ]);
+ assertEquals(plain["user-agent"], WEBHOOK_USER_AGENT);
+ assertEquals(plain["content-type"], "application/json");
+ const withHeader = calls[1].init.headers as Record;
+ assertEquals(Object.keys(withHeader).sort(), [
+ "X-Api-Key",
+ "content-type",
+ "user-agent",
+ "webhook-id",
+ "webhook-signature",
+ "webhook-timestamp",
+ ]);
+ assertEquals(withHeader["X-Api-Key"], "receiver-key");
+ for (const call of calls) {
+ const sent = JSON.stringify(call.init.headers) + String(call.init.body) + call.url;
+ assert(!sent.includes("service-role-key-must-not-leave"));
+ assert(!sent.includes("anon-key-must-not-leave"));
+ assert(!/apikey|authorization/i.test(Object.keys(call.init.headers as Record).join(",")));
+ }
+});
+
+Deno.test("webhookSend: during a rotation overlap both secrets sign, current first", async () => {
+ const { deps, calls } = harness(() => new Response(null, { status: 200 }));
+
+ await sendWebhook(deps, input({ secrets: [SECRET, OLD_SECRET] }));
+
+ const headers = calls[0].init.headers as Record;
+ const timestamp = Math.floor(NOW.getTime() / 1000);
+ assertEquals(headers["webhook-signature"].split(" "), [
+ await signWebhook(SECRET, "11111111-1111-4111-8111-111111111111", timestamp, '{"type":"ping"}'),
+ await signWebhook(OLD_SECRET, "11111111-1111-4111-8111-111111111111", timestamp, '{"type":"ping"}'),
+ ]);
+});
+
+Deno.test("webhookSend: a redirect is a failure and is never followed", async () => {
+ const { deps, calls } = harness(() =>
+ new Response(null, { status: 302, headers: { location: "http://169.254.169.254/latest/meta-data/" } })
+ );
+
+ const result = await sendWebhook(deps, input());
+
+ assertEquals(result.outcome, "failed");
+ assertEquals(result.statusCode, 302);
+ assertEquals(result.errorCode, "redirect_not_followed");
+ assertEquals(calls.length, 1);
+ assertEquals(calls[0].init.redirect, "manual");
+});
+
+Deno.test("webhookSend: the response body is cancelled, never read", async () => {
+ let pulled = 0;
+ let cancelled = false;
+ const body = new ReadableStream({
+ pull(controller) {
+ pulled += 1;
+ controller.enqueue(new TextEncoder().encode("internal data"));
+ },
+ cancel() {
+ cancelled = true;
+ },
+ }, { highWaterMark: 0 });
+ const { deps } = harness(() => new Response(body, { status: 500 }));
+
+ const result = await sendWebhook(deps, input());
+
+ assertEquals(result.outcome, "failed");
+ assertEquals(result.errorCode, "http_error");
+ assertEquals(cancelled, true);
+ assertEquals(pulled, 0);
+ // The result has nowhere to carry a body.
+ assertEquals(Object.keys(result).sort(), ["durationMs", "errorCode", "outcome", "retryAfterSeconds", "statusCode"]);
+});
+
+Deno.test("webhookSend: 410 is gone, other non-2xx are failed, and Retry-After is read on 429 and 503", async () => {
+ const gone = await sendWebhook(harness(() => new Response(null, { status: 410 })).deps, input());
+ const notFound = await sendWebhook(harness(() => new Response(null, { status: 404 })).deps, input());
+ const throttled = await sendWebhook(
+ harness(() => new Response(null, { status: 429, headers: { "retry-after": "120" } })).deps,
+ input(),
+ );
+ const busy = await sendWebhook(
+ harness(() => new Response(null, { status: 503, headers: { "retry-after": "7" } })).deps,
+ input(),
+ );
+ const serverError = await sendWebhook(
+ harness(() => new Response(null, { status: 500, headers: { "retry-after": "9" } })).deps,
+ input(),
+ );
+
+ assertEquals([gone.outcome, gone.statusCode], ["gone", 410]);
+ assertEquals([notFound.outcome, notFound.errorCode, notFound.retryAfterSeconds], ["failed", "http_error", null]);
+ assertEquals([throttled.outcome, throttled.retryAfterSeconds], ["failed", 120]);
+ assertEquals(busy.retryAfterSeconds, 7);
+ assertEquals(serverError.retryAfterSeconds, null);
+});
+
+Deno.test("webhookSend: every failure before an HTTP status is one code, and a timeout is its own", async () => {
+ const codes: string[] = [];
+ for (const error of [
+ new TypeError("error sending request: connection refused 10.0.0.5:8443"),
+ new TypeError("invalid peer certificate: UnknownIssuer"),
+ new Error("connection reset"),
+ ]) {
+ const result = await sendWebhook(harness(() => Promise.reject(error)).deps, input());
+ assertEquals(result.outcome, "failed");
+ assertEquals(result.statusCode, null);
+ codes.push(String(result.errorCode));
+ }
+ const timeout = await sendWebhook(
+ harness(() => Promise.reject(new DOMException("signal timed out", "TimeoutError"))).deps,
+ input(),
+ );
+
+ // Refused, bad certificate and reset are indistinguishable to the caller.
+ assertEquals(codes, ["connection_failed", "connection_failed", "connection_failed"]);
+ assertEquals(timeout.errorCode, "timeout");
+});
+
+Deno.test("webhookSend: DNS is re-checked on every send and a private answer stops the request", async () => {
+ const rebound = harness(() => new Response(null, { status: 200 }), { "hooks.example.com/A": ["10.0.0.5"] });
+ const unresolved = harness(() => new Response(null, { status: 200 }), {});
+
+ const privateResult = await sendWebhook(rebound.deps, input());
+ const unresolvedResult = await sendWebhook(unresolved.deps, input());
+
+ assertEquals([privateResult.outcome, privateResult.errorCode], ["failed", "target_not_allowed"]);
+ assertEquals(rebound.calls.length, 0);
+ assertEquals(rebound.lookups.sort(), ["hooks.example.com/A", "hooks.example.com/AAAA"]);
+ assertEquals([unresolvedResult.outcome, unresolvedResult.errorCode], ["failed", "dns_failed"]);
+ assertEquals(unresolved.calls.length, 0);
+});
+
+Deno.test("webhookSend: a stored URL that is no longer allowed is not requested", async () => {
+ for (const url of [
+ "http://hooks.example.com/in",
+ "https://127.0.0.1/in",
+ "https://abcdefghijklmnopqrst.supabase.co/functions/v1/delete-account",
+ ]) {
+ const { deps, calls } = harness(() => new Response(null, { status: 200 }));
+
+ const result = await sendWebhook(deps, input({ url }));
+
+ assertEquals([result.outcome, result.errorCode], ["failed", "target_not_allowed"], url);
+ assertEquals(calls.length, 0, url);
+ }
+});
+
+Deno.test("webhookSend: an oversized payload is skipped without a request", async () => {
+ const { deps, calls, lookups } = harness(() => new Response(null, { status: 200 }));
+
+ const result = await sendWebhook(deps, input({ body: "x".repeat(WEBHOOK_MAX_BODY_BYTES + 1) }));
+
+ assertEquals([result.outcome, result.errorCode], ["skipped", "payload_too_large"]);
+ assertEquals(calls.length, 0);
+ assertEquals(lookups.length, 0);
+});
+
+Deno.test("webhookSend: the envelope carries the type, an ISO timestamp and the API version", () => {
+ const body = JSON.parse(webhookEnvelope("workout.updated", NOW, { endpointId: "e", id: "w" }));
+
+ assertEquals(body, {
+ type: "workout.updated",
+ timestamp: "2026-11-06T12:00:00.000Z",
+ data: { apiVersion: WEBHOOK_API_VERSION, endpointId: "e", id: "w" },
+ });
+});
diff --git a/supabase/functions/_shared/webhookSend.ts b/supabase/functions/_shared/webhookSend.ts
new file mode 100644
index 00000000..2def5ad7
--- /dev/null
+++ b/supabase/functions/_shared/webhookSend.ts
@@ -0,0 +1,149 @@
+/**
+ * One signed POST to a user's data-sharing endpoint, and what came of it.
+ *
+ * Shared by the `test` action of webhook-endpoints and the deliver-webhooks
+ * worker so a test delivery is exactly a real one. The request carries the
+ * signing headers, a fixed User-Agent and at most the one header the user
+ * configured. Nothing else: no Supabase credential ever leaves through here.
+ *
+ * Only the status code and a fixed error code are returned. The response
+ * body and headers (bar Retry-After) are discarded unread, so an endpoint
+ * cannot be used to read back what some other host answered.
+ */
+import { parseRetryAfterSeconds } from './providerRateLimit.ts';
+import { webhookSignatureHeaders } from './webhookSigning.ts';
+import {
+ type DnsResolver,
+ fetchWebhookTarget,
+ resolveWebhookTarget,
+ type WebhookTargetRejection,
+} from './webhookTarget.ts';
+
+export const WEBHOOK_USER_AGENT = 'PhoenixPortal-Webhooks/1.0';
+export const WEBHOOK_API_VERSION = '2026-11-01';
+/** A payload larger than this is not sent. */
+export const WEBHOOK_MAX_BODY_BYTES = 1_000_000;
+
+/** Fixed codes stored in webhook_deliveries.last_error_code and shown to the owner. */
+export type WebhookErrorCode =
+ | 'http_error'
+ | 'redirect_not_followed'
+ | 'timeout'
+ | 'connection_failed'
+ | 'dns_failed'
+ | 'target_not_allowed'
+ | 'payload_too_large';
+
+export type WebhookSendResult =
+ | { outcome: 'delivered'; statusCode: number; errorCode: null; retryAfterSeconds: null; durationMs: number }
+ | {
+ outcome: 'failed' | 'gone' | 'skipped';
+ statusCode: number | null;
+ errorCode: WebhookErrorCode;
+ retryAfterSeconds: number | null;
+ durationMs: number;
+ };
+
+export interface WebhookSendDependencies {
+ fetch: typeof fetch;
+ resolveDns: DnsResolver;
+ /** This project's own hosts (ownHostsFromEnv). */
+ ownHosts: readonly string[];
+ now: () => Date;
+}
+
+export interface WebhookSendInput {
+ /** The stored endpoint URL. Re-validated here on every send. */
+ url: string;
+ /** Becomes `webhook-id`; the receiver's idempotency key. */
+ deliveryId: string;
+ /** Current signing secret first, then a previous one still in its overlap. */
+ secrets: readonly string[];
+ customHeader: { name: string; value: string } | null;
+ /** The exact JSON text to send and sign. */
+ body: string;
+}
+
+function targetErrorCode(code: WebhookTargetRejection): WebhookErrorCode {
+ return code === 'dns_failed' ? 'dns_failed' : 'target_not_allowed';
+}
+
+export async function sendWebhook(
+ deps: WebhookSendDependencies,
+ input: WebhookSendInput,
+): Promise {
+ const started = deps.now().getTime();
+ const elapsed = () => Math.max(0, deps.now().getTime() - started);
+
+ if (new TextEncoder().encode(input.body).byteLength > WEBHOOK_MAX_BODY_BYTES) {
+ return { outcome: 'skipped', statusCode: null, errorCode: 'payload_too_large', retryAfterSeconds: null, durationMs: 0 };
+ }
+
+ // The URL was validated when it was saved; DNS may have changed since, and
+ // a stored row is not proof of anything.
+ const target = await resolveWebhookTarget(input.url, deps.ownHosts, deps.resolveDns);
+ if (!target.ok) {
+ return {
+ outcome: 'failed',
+ statusCode: null,
+ errorCode: targetErrorCode(target.code),
+ retryAfterSeconds: null,
+ durationMs: elapsed(),
+ };
+ }
+
+ const headers: Record = {
+ 'content-type': 'application/json',
+ 'user-agent': WEBHOOK_USER_AGENT,
+ ...(await webhookSignatureHeaders(input.secrets, input.deliveryId, deps.now(), input.body)),
+ };
+ if (input.customHeader) headers[input.customHeader.name] = input.customHeader.value;
+
+ let response: Response;
+ try {
+ response = await fetchWebhookTarget(deps.fetch, target.normalized, { headers, body: input.body });
+ } catch (error) {
+ const name = error instanceof Error ? error.name : '';
+ return {
+ outcome: 'failed',
+ statusCode: null,
+ // One code for everything that failed before an HTTP status (refused,
+ // reset, TLS, unreachable): see the residual-risk note in webhookTarget.ts.
+ errorCode: name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'connection_failed',
+ retryAfterSeconds: null,
+ durationMs: elapsed(),
+ };
+ }
+
+ const statusCode = response.status;
+ const retryAfterSeconds = statusCode === 429 || statusCode === 503
+ ? parseRetryAfterSeconds(response.headers, deps.now())
+ : null;
+ // Never read what the host answered.
+ try {
+ await response.body?.cancel();
+ } catch {
+ // Already closed.
+ }
+ const durationMs = elapsed();
+
+ if (statusCode >= 200 && statusCode < 300) {
+ return { outcome: 'delivered', statusCode, errorCode: null, retryAfterSeconds: null, durationMs };
+ }
+ if (statusCode === 410) {
+ return { outcome: 'gone', statusCode, errorCode: 'http_error', retryAfterSeconds: null, durationMs };
+ }
+ if (statusCode >= 300 && statusCode < 400) {
+ return { outcome: 'failed', statusCode, errorCode: 'redirect_not_followed', retryAfterSeconds: null, durationMs };
+ }
+ return { outcome: 'failed', statusCode, errorCode: 'http_error', retryAfterSeconds, durationMs };
+}
+
+/** The envelope every event uses. `data` differs by event type. */
+export function webhookEnvelope(type: string, now: Date, data: Record): string {
+ return JSON.stringify({
+ type,
+ timestamp: now.toISOString(),
+ data: { apiVersion: WEBHOOK_API_VERSION, ...data },
+ });
+}
diff --git a/supabase/functions/_shared/webhookSigning.test.ts b/supabase/functions/_shared/webhookSigning.test.ts
new file mode 100644
index 00000000..45881869
--- /dev/null
+++ b/supabase/functions/_shared/webhookSigning.test.ts
@@ -0,0 +1,79 @@
+import { assert, assertEquals, assertMatch, assertNotEquals, assertRejects } from "jsr:@std/assert@1";
+import {
+ generateWebhookSecret,
+ signWebhook,
+ WEBHOOK_SECRET_PREFIX,
+ webhookSecretHint,
+ webhookSignatureHeaders,
+} from "./webhookSigning.ts";
+
+// The reference vector published with the Standard Webhooks / Svix verifiers.
+// It only reproduces when the HMAC key is the base64-DECODED secret; with the
+// literal string the result is v1,ELhqG0Ku1gwOc1f4jyKdp3SFGFLAOdJ9bvpWLciCakI=,
+// which every reference library rejects.
+const REFERENCE = {
+ secret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
+ id: "msg_p5jXN8AQM9LWM0D4loKWxJek",
+ timestamp: 1614265330,
+ body: '{"test": 2432232314}',
+ signature: "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=",
+};
+
+Deno.test("webhookSigning: the reference vector produces the published signature", async () => {
+ const signature = await signWebhook(
+ REFERENCE.secret,
+ REFERENCE.id,
+ REFERENCE.timestamp,
+ REFERENCE.body,
+ );
+
+ assertEquals(signature, REFERENCE.signature);
+});
+
+Deno.test("webhookSigning: a changed body, id or timestamp changes the signature", async () => {
+ const base = await signWebhook(REFERENCE.secret, REFERENCE.id, REFERENCE.timestamp, REFERENCE.body);
+
+ const otherBody = await signWebhook(REFERENCE.secret, REFERENCE.id, REFERENCE.timestamp, '{"test": 1}');
+ const otherId = await signWebhook(REFERENCE.secret, "msg_other", REFERENCE.timestamp, REFERENCE.body);
+ const otherTime = await signWebhook(REFERENCE.secret, REFERENCE.id, REFERENCE.timestamp + 1, REFERENCE.body);
+
+ assertNotEquals(otherBody, base);
+ assertNotEquals(otherId, base);
+ assertNotEquals(otherTime, base);
+});
+
+Deno.test("webhookSigning: a generated secret is whsec_ plus 32 random bytes and signs", async () => {
+ const first = generateWebhookSecret();
+ const second = generateWebhookSecret();
+
+ assert(first.startsWith(WEBHOOK_SECRET_PREFIX));
+ assertEquals(atob(first.slice(WEBHOOK_SECRET_PREFIX.length)).length, 32);
+ assertNotEquals(first, second);
+ assertMatch(await signWebhook(first, "id", 1, "{}"), /^v1,[A-Za-z0-9+/]{43}=$/);
+});
+
+Deno.test("webhookSigning: the hint is the last four characters only", () => {
+ assertEquals(webhookSecretHint("whsec_abcdefghij"), "ghij");
+});
+
+Deno.test("webhookSigning: headers carry the id, unix seconds and one signature per secret", async () => {
+ const now = new Date(REFERENCE.timestamp * 1000 + 999);
+ const other = generateWebhookSecret();
+
+ const headers = await webhookSignatureHeaders([REFERENCE.secret, other], REFERENCE.id, now, REFERENCE.body);
+
+ assertEquals(headers["webhook-id"], REFERENCE.id);
+ assertEquals(headers["webhook-timestamp"], String(REFERENCE.timestamp));
+ const signatures = headers["webhook-signature"].split(" ");
+ assertEquals(signatures.length, 2);
+ // Current secret first; a receiver still holding the old secret matches the second.
+ assertEquals(signatures[0], REFERENCE.signature);
+ assertEquals(signatures[1], await signWebhook(other, REFERENCE.id, REFERENCE.timestamp, REFERENCE.body));
+});
+
+Deno.test("webhookSigning: a malformed or missing secret is refused rather than signed with", async () => {
+ await assertRejects(() => signWebhook("not-a-secret", "id", 1, "{}"), Error, "webhook_secret_malformed");
+ await assertRejects(() => signWebhook("whsec_!!!", "id", 1, "{}"), Error, "webhook_secret_malformed");
+ await assertRejects(() => signWebhook("whsec_c2hvcnQ=", "id", 1, "{}"), Error, "webhook_secret_malformed");
+ await assertRejects(() => webhookSignatureHeaders([], "id", new Date(), "{}"), Error, "webhook_secret_missing");
+});
diff --git a/supabase/functions/_shared/webhookSigning.ts b/supabase/functions/_shared/webhookSigning.ts
new file mode 100644
index 00000000..d3449822
--- /dev/null
+++ b/supabase/functions/_shared/webhookSigning.ts
@@ -0,0 +1,99 @@
+/**
+ * Signing for outbound data-sharing webhooks, in the Standard Webhooks format
+ * (https://www.standardwebhooks.com) so a receiver can verify with an
+ * off-the-shelf library instead of code we would have to document and support.
+ *
+ * webhook-id: unique per delivery; the receiver's idempotency key
+ * webhook-timestamp: unix seconds; the receiver rejects stale ones (replay)
+ * webhook-signature: space-separated `v1,` entries
+ *
+ * The signed content is `${id}.${timestamp}.${body}` and the HMAC key is the
+ * base64-DECODED bytes after the `whsec_` prefix, not the literal string.
+ * webhookSigning.test.ts pins that with the specification's reference vector:
+ * signing with the literal string produces a signature every reference
+ * verifier rejects.
+ */
+
+export const WEBHOOK_SECRET_PREFIX = 'whsec_';
+const SECRET_BYTES = 32;
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary);
+}
+
+function base64ToBytes(value: string): Uint8Array {
+ const binary = atob(value);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+}
+
+/** A new signing secret: `whsec_` + base64 of 32 random bytes. */
+export function generateWebhookSecret(): string {
+ const bytes = crypto.getRandomValues(new Uint8Array(SECRET_BYTES));
+ return `${WEBHOOK_SECRET_PREFIX}${bytesToBase64(bytes)}`;
+}
+
+/** The last four characters, shown so the user can tell two secrets apart. */
+export function webhookSecretHint(secret: string): string {
+ return secret.slice(-4);
+}
+
+function secretKeyBytes(secret: string): Uint8Array {
+ if (!secret.startsWith(WEBHOOK_SECRET_PREFIX)) {
+ throw new Error('webhook_secret_malformed');
+ }
+ let bytes: Uint8Array;
+ try {
+ bytes = base64ToBytes(secret.slice(WEBHOOK_SECRET_PREFIX.length));
+ } catch {
+ throw new Error('webhook_secret_malformed');
+ }
+ if (bytes.length < 24) throw new Error('webhook_secret_malformed');
+ return bytes;
+}
+
+/** One `v1,` signature entry. */
+export async function signWebhook(
+ secret: string,
+ id: string,
+ timestampSeconds: number,
+ body: string,
+): Promise {
+ const key = await crypto.subtle.importKey(
+ 'raw',
+ secretKeyBytes(secret),
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['sign'],
+ );
+ const signed = new TextEncoder().encode(`${id}.${timestampSeconds}.${body}`);
+ const signature = await crypto.subtle.sign('HMAC', key, signed);
+ return `v1,${bytesToBase64(new Uint8Array(signature))}`;
+}
+
+/**
+ * The three signing headers. `secrets` is the current secret followed by any
+ * previous one still inside its rotation overlap: the receiver accepts the
+ * delivery if any entry verifies, so a rotation drops no events.
+ */
+export async function webhookSignatureHeaders(
+ secrets: readonly string[],
+ id: string,
+ now: Date,
+ body: string,
+): Promise> {
+ if (secrets.length === 0) throw new Error('webhook_secret_missing');
+ const timestampSeconds = Math.floor(now.getTime() / 1000);
+ const signatures: string[] = [];
+ for (const secret of secrets) {
+ signatures.push(await signWebhook(secret, id, timestampSeconds, body));
+ }
+ return {
+ 'webhook-id': id,
+ 'webhook-timestamp': String(timestampSeconds),
+ 'webhook-signature': signatures.join(' '),
+ };
+}
diff --git a/supabase/functions/_shared/webhookTarget.test.ts b/supabase/functions/_shared/webhookTarget.test.ts
new file mode 100644
index 00000000..3660dc78
--- /dev/null
+++ b/supabase/functions/_shared/webhookTarget.test.ts
@@ -0,0 +1,233 @@
+import { assert, assertEquals } from "jsr:@std/assert@1";
+import {
+ type DnsResolver,
+ fetchWebhookTarget,
+ isPublicIpAddress,
+ ownHostsFromEnv,
+ parseWebhookUrl,
+ resolveWebhookTarget,
+ validateCustomHeader,
+ WEBHOOK_REQUEST_TIMEOUT_MS,
+ WEBHOOK_URL_MAX_LENGTH,
+} from "./webhookTarget.ts";
+
+const OWN_HOSTS = ["abcdefghijklmnopqrst.supabase.co", "phoenix-portal.com"];
+
+function resolver(answers: Record): DnsResolver {
+ return (hostname, recordType) => Promise.resolve(answers[`${hostname}/${recordType}`] ?? []);
+}
+
+function codeOf(raw: unknown, ownHosts: readonly string[] = OWN_HOSTS): string {
+ const parsed = parseWebhookUrl(raw, ownHosts);
+ return parsed.ok ? "ok" : parsed.code;
+}
+
+Deno.test("webhookTarget: a public https URL is accepted and its fragment dropped", () => {
+ const parsed = parseWebhookUrl("https://hooks.example.com:8443/in?x=1#frag", OWN_HOSTS);
+
+ assert(parsed.ok);
+ assertEquals(parsed.normalized, "https://hooks.example.com:8443/in?x=1");
+ assertEquals(parsed.hostname, "hooks.example.com");
+ assertEquals(parsed.ipLiteral, false);
+});
+
+Deno.test("webhookTarget: non-https schemes are refused", () => {
+ for (const raw of ["http://hooks.example.com/in", "ftp://hooks.example.com/", "file:///etc/passwd", "javascript:alert(1)"]) {
+ assertEquals(codeOf(raw), "url_not_https", raw);
+ }
+});
+
+Deno.test("webhookTarget: malformed, empty, non-string and whitespace-bearing input is refused", () => {
+ for (const raw of ["", "not a url", "https://", 42, null, undefined, {}, "https://hooks.example.com/a b", " https://hooks.example.com/", "https://hooks.example.com/\n"]) {
+ assertEquals(codeOf(raw), "url_invalid", String(raw));
+ }
+ assertEquals(codeOf(`https://hooks.example.com/${"a".repeat(WEBHOOK_URL_MAX_LENGTH)}`), "url_too_long");
+});
+
+Deno.test("webhookTarget: credentials in the URL are refused", () => {
+ assertEquals(codeOf("https://user:pass@hooks.example.com/"), "url_has_credentials");
+ assertEquals(codeOf("https://user@hooks.example.com/"), "url_has_credentials");
+});
+
+Deno.test("webhookTarget: only 443 and unprivileged ports are allowed", () => {
+ assertEquals(codeOf("https://hooks.example.com/"), "ok");
+ assertEquals(codeOf("https://hooks.example.com:443/"), "ok");
+ assertEquals(codeOf("https://hooks.example.com:1024/"), "ok");
+ assertEquals(codeOf("https://hooks.example.com:65535/"), "ok");
+ for (const port of [22, 25, 80, 1023]) {
+ assertEquals(codeOf(`https://hooks.example.com:${port}/`), "url_port_not_allowed", String(port));
+ }
+});
+
+Deno.test("webhookTarget: private, loopback, link-local and reserved IPv4 literals are refused in every spelling", () => {
+ const blocked = [
+ "127.0.0.1", "127.255.255.254", "10.0.0.1", "172.16.0.1", "172.31.255.255", "192.168.1.1",
+ "169.254.169.254", // cloud metadata
+ "100.64.0.1", "0.0.0.0", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1",
+ "224.0.0.1", "240.0.0.1", "255.255.255.255",
+ // Spellings the URL parser canonicalises to the addresses above.
+ "2130706433", "0x7f.0.0.1", "0177.0.0.1", "127.1", "0x7f000001", "10.1",
+ ];
+ for (const host of blocked) {
+ assertEquals(codeOf(`https://${host}/`), "url_host_not_allowed", host);
+ }
+ assertEquals(codeOf("https://93.184.216.34/"), "ok");
+ assertEquals(codeOf("https://172.32.0.1/"), "ok");
+});
+
+Deno.test("webhookTarget: non-global IPv6 literals are refused, including every IPv4-embedding form", () => {
+ const blocked = [
+ "[::1]", "[::]", "[fe80::1]", "[fc00::1]", "[fd12:3456:789a::1]", "[ff02::1]",
+ "[::ffff:127.0.0.1]", "[::ffff:10.0.0.1]", "[::ffff:93.184.216.34]", "[::ffff:7f00:1]",
+ "[64:ff9b::7f00:1]", // NAT64
+ "[2002:7f00:1::1]", // 6to4
+ "[2001:0:4136:e378:8000:63bf:3fff:fdd2]", // Teredo
+ "[2001:db8::1]", // documentation
+ ];
+ for (const host of blocked) {
+ assertEquals(codeOf(`https://${host}/`), "url_host_not_allowed", host);
+ }
+ assertEquals(codeOf("https://[2606:4700:4700::1111]/"), "ok");
+});
+
+Deno.test("webhookTarget: internal names, single labels and trailing dots are refused", () => {
+ for (const host of [
+ "localhost", "kong", "db", "supabase_kong_phoenix", "app.localhost", "printer.local",
+ "vault.internal", "router.lan", "nas.home.arpa", "service.corp", "hooks.example.com.", "hooks.test",
+ ]) {
+ assertEquals(codeOf(`https://${host}/`), "url_host_not_allowed", host);
+ }
+});
+
+Deno.test("webhookTarget: this project's own hosts are refused, including sibling hosts carrying the project ref", () => {
+ for (const host of [
+ "abcdefghijklmnopqrst.supabase.co",
+ "abcdefghijklmnopqrst.functions.supabase.co",
+ "db.abcdefghijklmnopqrst.supabase.co",
+ "phoenix-portal.com",
+ "api.phoenix-portal.com",
+ ]) {
+ assertEquals(codeOf(`https://${host}/functions/v1/delete-account`), "url_host_not_allowed", host);
+ }
+ // Someone else's project is a legitimate receiver.
+ assertEquals(codeOf("https://zyxwvutsrqponmlkjihg.supabase.co/functions/v1/in"), "ok");
+});
+
+Deno.test("webhookTarget: own hosts are read from the environment by host name", () => {
+ const env: Record = {
+ SUPABASE_URL: "https://abcdefghijklmnopqrst.supabase.co",
+ SUPABASE_PUBLIC_URL: "https://api.phoenix-portal.com",
+ APP_URL: "https://phoenix-portal.com/",
+ };
+
+ const hosts = ownHostsFromEnv((name) => env[name]);
+
+ assertEquals(hosts.sort(), ["abcdefghijklmnopqrst.supabase.co", "api.phoenix-portal.com", "phoenix-portal.com"]);
+ assertEquals(ownHostsFromEnv(() => undefined), []);
+});
+
+Deno.test("webhookTarget: a name resolving only to public addresses is accepted", async () => {
+ const dns = resolver({
+ "hooks.example.com/A": ["93.184.216.34"],
+ "hooks.example.com/AAAA": ["2606:4700:4700::1111"],
+ });
+
+ const target = await resolveWebhookTarget("https://hooks.example.com/in", OWN_HOSTS, dns);
+
+ assert(target.ok);
+ assertEquals(target.normalized, "https://hooks.example.com/in");
+});
+
+Deno.test("webhookTarget: one private address among public ones is a refusal", async () => {
+ const cases: Array> = [
+ { "hooks.example.com/A": ["93.184.216.34", "10.0.0.5"] },
+ { "hooks.example.com/A": ["169.254.169.254"] },
+ { "hooks.example.com/A": ["93.184.216.34"], "hooks.example.com/AAAA": ["::1"] },
+ { "hooks.example.com/AAAA": ["::ffff:127.0.0.1"] },
+ { "hooks.example.com/A": ["127.0.0.1"] },
+ ];
+ for (const answers of cases) {
+ const target = await resolveWebhookTarget("https://hooks.example.com/in", OWN_HOSTS, resolver(answers));
+
+ assertEquals(target.ok ? "ok" : target.code, "url_resolves_to_private_address", JSON.stringify(answers));
+ }
+});
+
+Deno.test("webhookTarget: a resolver error or an empty answer fails closed", async () => {
+ const failing: DnsResolver = () => Promise.reject(new Error("resolver down"));
+
+ const failed = await resolveWebhookTarget("https://hooks.example.com/in", OWN_HOSTS, failing);
+ const empty = await resolveWebhookTarget("https://hooks.example.com/in", OWN_HOSTS, resolver({}));
+
+ assertEquals(failed.ok ? "ok" : failed.code, "dns_failed");
+ assertEquals(empty.ok ? "ok" : empty.code, "dns_failed");
+});
+
+Deno.test("webhookTarget: a syntactically refused URL is never resolved", async () => {
+ let lookups = 0;
+ const counting: DnsResolver = () => {
+ lookups += 1;
+ return Promise.resolve(["93.184.216.34"]);
+ };
+
+ await resolveWebhookTarget("http://hooks.example.com/in", OWN_HOSTS, counting);
+ await resolveWebhookTarget("https://localhost/in", OWN_HOSTS, counting);
+ await resolveWebhookTarget("https://10.0.0.1/in", OWN_HOSTS, counting);
+
+ assertEquals(lookups, 0);
+});
+
+Deno.test("webhookTarget: the fetch is a POST that does not follow redirects and has a timeout", async () => {
+ let seen: RequestInit | undefined;
+ let seenUrl = "";
+ const fetchImpl = ((input: string | URL | Request, init?: RequestInit) => {
+ seenUrl = String(input);
+ seen = init;
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }) as typeof fetch;
+
+ await fetchWebhookTarget(fetchImpl, "https://hooks.example.com/in", {
+ headers: { "content-type": "application/json" },
+ body: "{}",
+ });
+
+ assertEquals(seenUrl, "https://hooks.example.com/in");
+ assertEquals(seen?.method, "POST");
+ assertEquals(seen?.redirect, "manual");
+ assertEquals(seen?.body, "{}");
+ assert(seen?.signal instanceof AbortSignal);
+ assert(WEBHOOK_REQUEST_TIMEOUT_MS <= 10_000);
+});
+
+Deno.test("webhookTarget: address classification treats unparseable input as not public", () => {
+ for (const address of ["", "999.1.1.1", "1.2.3", "01.2.3.4", "fe80::1%eth0", "gggg::1", "1:2:3:4:5:6:7:8:9", "::1::2"]) {
+ assertEquals(isPublicIpAddress(address), false, address);
+ }
+ assertEquals(isPublicIpAddress("8.8.8.8"), true);
+ assertEquals(isPublicIpAddress("2606:4700:4700::1111"), true);
+});
+
+Deno.test("webhookTarget: a custom header must be a plain, non-reserved name with a printable value", () => {
+ assertEquals(validateCustomHeader("Authorization", "Bearer abc.def"), {
+ ok: true,
+ name: "Authorization",
+ value: "Bearer abc.def",
+ });
+ assertEquals(validateCustomHeader("X-Api-Key", "k"), { ok: true, name: "X-Api-Key", value: "k" });
+
+ for (const name of ["", "1abc", "bad name", "bad:name", "a".repeat(65), "x\r\ny", 7]) {
+ const result = validateCustomHeader(name, "v");
+ assertEquals(result.ok ? "ok" : result.code, "header_name_invalid", String(name));
+ }
+ for (const name of [
+ "Host", "content-type", "Content-Length", "Transfer-Encoding", "Connection", "Cookie", "User-Agent",
+ "webhook-signature", "Webhook-Id", "Proxy-Authorization", "X-Forwarded-For", "Sec-Fetch-Mode",
+ ]) {
+ const result = validateCustomHeader(name, "v");
+ assertEquals(result.ok ? "ok" : result.code, "header_name_reserved", name);
+ }
+ for (const value of ["", "a\r\nX-Injected: 1", "a\nb", "tab\there", "café", "a".repeat(513), 5, null]) {
+ const result = validateCustomHeader("Authorization", value);
+ assertEquals(result.ok ? "ok" : result.code, "header_value_invalid", String(value));
+ }
+});
diff --git a/supabase/functions/_shared/webhookTarget.ts b/supabase/functions/_shared/webhookTarget.ts
new file mode 100644
index 00000000..cb0078a5
--- /dev/null
+++ b/supabase/functions/_shared/webhookTarget.ts
@@ -0,0 +1,373 @@
+/**
+ * Where an outbound data-sharing webhook may be sent (SSRF guard).
+ *
+ * This is the only place in the code base that makes a request to a URL a
+ * user chose. Every other outbound fetch goes to a fixed provider host.
+ *
+ * Rules, all enforced here and nowhere else:
+ * - https only, no credentials in the URL, port 443 or 1024-65535;
+ * - the host must be a public DNS name or a public IP literal: loopback,
+ * private, link-local (cloud metadata), CGNAT, ULA, multicast, reserved
+ * and IPv4-mapped / translated IPv6 ranges are refused, as are single-label
+ * names, internal suffixes and this project's own hosts;
+ * - every address the name resolves to must be public, checked when the
+ * endpoint is saved and again before every delivery; a resolver error
+ * fails closed;
+ * - redirects are never followed, the request times out, and the response
+ * body is never read.
+ *
+ * RESIDUAL RISK (not closed here): the runtime's fetch resolves the name
+ * again and cannot be pinned to the address that was checked, so a host that
+ * answers the check with a public address and the connection with a private
+ * one (DNS rebinding) can still be aimed at an internal address. What bounds
+ * it: the request is https with certificate validation, so an internal
+ * service would have to present a certificate valid for the attacker's name;
+ * the request carries no Supabase credential (webhookSend.test.ts asserts
+ * it); nothing from the response beyond its status code is kept; and every
+ * failure before an HTTP status is reported as one code, `connection_failed`,
+ * so it is not a port scanner.
+ */
+
+export const WEBHOOK_URL_MAX_LENGTH = 2048;
+export const WEBHOOK_REQUEST_TIMEOUT_MS = 10_000;
+
+export type WebhookTargetRejection =
+ | 'url_invalid'
+ | 'url_too_long'
+ | 'url_not_https'
+ | 'url_has_credentials'
+ | 'url_port_not_allowed'
+ | 'url_host_not_allowed'
+ | 'url_resolves_to_private_address'
+ | 'dns_failed';
+
+/** Messages safe to show the endpoint's owner. */
+export const WEBHOOK_TARGET_MESSAGES: Record = {
+ url_invalid: 'Enter a valid URL.',
+ url_too_long: `The URL must be at most ${WEBHOOK_URL_MAX_LENGTH} characters.`,
+ url_not_https: 'The URL must start with https://.',
+ url_has_credentials: 'The URL must not contain a username or password. Use the custom header instead.',
+ url_port_not_allowed: 'Use port 443 or a port from 1024 to 65535.',
+ url_host_not_allowed: 'That host cannot be used as a data sharing endpoint.',
+ url_resolves_to_private_address: 'That host resolves to a private or reserved address.',
+ dns_failed: 'The host name could not be resolved. Check it and try again.',
+};
+
+/** Resolves a name to addresses of one family; no records is an empty list. */
+export type DnsResolver = (hostname: string, recordType: 'A' | 'AAAA') => Promise;
+
+/** The Edge runtime's resolver. "No records" is an answer, not a failure. */
+export const systemDnsResolver: DnsResolver = async (hostname, recordType) => {
+ try {
+ return await Deno.resolveDns(hostname, recordType);
+ } catch (error) {
+ if (error instanceof Deno.errors.NotFound) return [];
+ throw error;
+ }
+};
+
+const BLOCKED_SUFFIXES = [
+ 'localhost',
+ 'local',
+ 'internal',
+ 'intranet',
+ 'lan',
+ 'home',
+ 'corp',
+ 'home.arpa',
+ 'test',
+ 'invalid',
+ 'example',
+ 'onion',
+];
+
+function parseIpv4(host: string): number[] | null {
+ const parts = host.split('.');
+ if (parts.length !== 4) return null;
+ const octets: number[] = [];
+ for (const part of parts) {
+ if (!/^(0|[1-9][0-9]{0,2})$/.test(part)) return null;
+ const value = Number(part);
+ if (value > 255) return null;
+ octets.push(value);
+ }
+ return octets;
+}
+
+/** True only for globally routable unicast IPv4. */
+export function isPublicIpv4(address: string): boolean {
+ const octets = parseIpv4(address);
+ if (!octets) return false;
+ const [a, b, c] = octets;
+ if (a === 0) return false; // "this network"
+ if (a === 10) return false; // private
+ if (a === 100 && b >= 64 && b <= 127) return false; // CGNAT
+ if (a === 127) return false; // loopback
+ if (a === 169 && b === 254) return false; // link-local, cloud metadata
+ if (a === 172 && b >= 16 && b <= 31) return false; // private
+ if (a === 192 && b === 0 && c === 0) return false; // IETF protocol assignments
+ if (a === 192 && b === 0 && c === 2) return false; // documentation
+ if (a === 192 && b === 88 && c === 99) return false; // 6to4 relay
+ if (a === 192 && b === 168) return false; // private
+ if (a === 198 && (b === 18 || b === 19)) return false; // benchmarking
+ if (a === 198 && b === 51 && c === 100) return false; // documentation
+ if (a === 203 && b === 0 && c === 113) return false; // documentation
+ if (a >= 224) return false; // multicast, reserved, broadcast
+ return true;
+}
+
+/** Eight 16-bit groups, or null when `address` is not IPv6. */
+function parseIpv6(address: string): number[] | null {
+ let text = address;
+ if (text.includes('%')) return null; // zone ids are never public
+ // An embedded IPv4 tail (::ffff:1.2.3.4) becomes two groups.
+ const lastColon = text.lastIndexOf(':');
+ if (lastColon === -1) return null;
+ const tail = text.slice(lastColon + 1);
+ if (tail.includes('.')) {
+ const v4 = parseIpv4(tail);
+ if (!v4) return null;
+ const high = ((v4[0] << 8) | v4[1]).toString(16);
+ const low = ((v4[2] << 8) | v4[3]).toString(16);
+ text = `${text.slice(0, lastColon + 1)}${high}:${low}`;
+ }
+ const halves = text.split('::');
+ if (halves.length > 2) return null;
+ const parseGroups = (part: string): number[] | null => {
+ if (part === '') return [];
+ const groups: number[] = [];
+ for (const group of part.split(':')) {
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
+ groups.push(Number.parseInt(group, 16));
+ }
+ return groups;
+ };
+ const head = parseGroups(halves[0]);
+ const rest = halves.length === 2 ? parseGroups(halves[1]) : [];
+ if (!head || !rest) return null;
+ if (halves.length === 1) return head.length === 8 ? head : null;
+ const missing = 8 - head.length - rest.length;
+ if (missing < 1) return null;
+ return [...head, ...new Array(missing).fill(0), ...rest];
+}
+
+/**
+ * True only for global unicast IPv6 (2000::/3) outside the ranges that embed
+ * or tunnel an IPv4 address or are reserved. Anything that could smuggle a
+ * private IPv4 address (mapped, NAT64, 6to4, Teredo) is refused outright
+ * rather than unpacked.
+ */
+export function isPublicIpv6(address: string): boolean {
+ const groups = parseIpv6(address);
+ if (!groups) return false;
+ const [first, second] = groups;
+ if ((first & 0xe000) !== 0x2000) return false; // not 2000::/3: ::, ::1, mapped, NAT64, ULA, link-local, multicast
+ if (first === 0x2001 && second === 0x0db8) return false; // documentation
+ if (first === 0x2001 && second === 0x0000) return false; // Teredo
+ if (first === 0x2001 && second >= 0x0010 && second <= 0x002f) return false; // ORCHID
+ if (first === 0x2002) return false; // 6to4
+ if (first === 0x3fff && second <= 0x0fff) return false; // documentation
+ return true;
+}
+
+export function isPublicIpAddress(address: string): boolean {
+ return address.includes(':') ? isPublicIpv6(address) : isPublicIpv4(address);
+}
+
+function isIpLiteral(hostname: string): boolean {
+ return hostname.startsWith('[') || parseIpv4(hostname) !== null;
+}
+
+function hostOf(value: string | undefined | null): string | null {
+ if (!value) return null;
+ try {
+ return new URL(value).hostname.toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * This project's own hosts, which an endpoint may never point at: the
+ * Supabase API (and any sibling host carrying the project ref) and the portal.
+ */
+export function ownHostsFromEnv(env: (name: string) => string | undefined): string[] {
+ const hosts = new Set();
+ for (const name of ['SUPABASE_URL', 'SUPABASE_PUBLIC_URL', 'APP_URL']) {
+ const host = hostOf(env(name));
+ if (host) hosts.add(host);
+ }
+ return [...hosts];
+}
+
+function matchesOwnHost(hostname: string, ownHosts: readonly string[]): boolean {
+ for (const own of ownHosts) {
+ if (hostname === own || hostname.endsWith(`.${own}`)) return true;
+ // .supabase.co also answers as .functions.supabase.co,
+ // db..supabase.co, ...: refuse any host carrying the project ref.
+ if (own.endsWith('.supabase.co')) {
+ const ref = own.split('.')[0];
+ if (ref.length >= 12 && hostname.split('.').includes(ref)) return true;
+ }
+ }
+ return false;
+}
+
+export type ParsedWebhookTarget =
+ | { ok: true; url: URL; normalized: string; hostname: string; ipLiteral: boolean }
+ | { ok: false; code: WebhookTargetRejection };
+
+/** Syntactic checks only; resolveWebhookTarget adds the DNS check. */
+export function parseWebhookUrl(raw: unknown, ownHosts: readonly string[] = []): ParsedWebhookTarget {
+ if (typeof raw !== 'string' || raw.length === 0) return { ok: false, code: 'url_invalid' };
+ if (raw.length > WEBHOOK_URL_MAX_LENGTH) return { ok: false, code: 'url_too_long' };
+ // Whitespace and control characters are stripped by the URL parser; a URL
+ // that needs that is not what the user thinks it is.
+ // deno-lint-ignore no-control-regex
+ if (/[\s\u0000-\u001f\u007f]/.test(raw)) return { ok: false, code: 'url_invalid' };
+
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ return { ok: false, code: 'url_invalid' };
+ }
+ if (url.protocol !== 'https:') return { ok: false, code: 'url_not_https' };
+ if (url.username !== '' || url.password !== '') return { ok: false, code: 'url_has_credentials' };
+ if (url.port !== '') {
+ const port = Number(url.port);
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) {
+ return { ok: false, code: 'url_port_not_allowed' };
+ }
+ }
+
+ // The parser has already canonicalised odd IPv4 spellings (decimal, hex,
+ // short forms) into dotted quads, so the checks below see the real address.
+ const hostname = url.hostname.toLowerCase();
+ if (hostname === '' || hostname.endsWith('.')) return { ok: false, code: 'url_host_not_allowed' };
+
+ const ipLiteral = isIpLiteral(hostname);
+ if (ipLiteral) {
+ const address = hostname.startsWith('[') ? hostname.slice(1, -1) : hostname;
+ if (!isPublicIpAddress(address)) return { ok: false, code: 'url_host_not_allowed' };
+ } else {
+ const labels = hostname.split('.');
+ // Single-label names (kong, db, a container name) only resolve internally.
+ if (labels.length < 2) return { ok: false, code: 'url_host_not_allowed' };
+ // A numeric last label is an address the parser declined to canonicalise.
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return { ok: false, code: 'url_host_not_allowed' };
+ for (const suffix of BLOCKED_SUFFIXES) {
+ if (hostname === suffix || hostname.endsWith(`.${suffix}`)) {
+ return { ok: false, code: 'url_host_not_allowed' };
+ }
+ }
+ }
+ if (matchesOwnHost(hostname, ownHosts)) return { ok: false, code: 'url_host_not_allowed' };
+
+ url.hash = '';
+ return { ok: true, url, normalized: url.toString(), hostname, ipLiteral };
+}
+
+export type ResolvedWebhookTarget =
+ | { ok: true; url: URL; normalized: string }
+ | { ok: false; code: WebhookTargetRejection };
+
+/**
+ * parseWebhookUrl plus: every address the host resolves to must be public.
+ * One private answer among public ones is a refusal, since the connection
+ * may use any of them. A resolver error, or no address at all, fails closed.
+ */
+export async function resolveWebhookTarget(
+ raw: unknown,
+ ownHosts: readonly string[],
+ resolveDns: DnsResolver,
+): Promise {
+ const parsed = parseWebhookUrl(raw, ownHosts);
+ if (!parsed.ok) return parsed;
+ if (parsed.ipLiteral) return { ok: true, url: parsed.url, normalized: parsed.normalized };
+
+ let addresses: string[];
+ try {
+ const [v4, v6] = await Promise.all([
+ resolveDns(parsed.hostname, 'A'),
+ resolveDns(parsed.hostname, 'AAAA'),
+ ]);
+ addresses = [...v4, ...v6];
+ } catch {
+ return { ok: false, code: 'dns_failed' };
+ }
+ if (addresses.length === 0) return { ok: false, code: 'dns_failed' };
+ if (!addresses.every(isPublicIpAddress)) {
+ return { ok: false, code: 'url_resolves_to_private_address' };
+ }
+ return { ok: true, url: parsed.url, normalized: parsed.normalized };
+}
+
+/**
+ * The only fetch to a user-chosen URL. Redirects are returned, not followed
+ * (a 3xx could point anywhere, including back inside), and the call is timed
+ * out. Callers must not read the response body.
+ */
+export function fetchWebhookTarget(
+ fetchImpl: typeof fetch,
+ url: string,
+ init: { headers: Record; body: string },
+): Promise {
+ return fetchImpl(url, {
+ method: 'POST',
+ headers: init.headers,
+ body: init.body,
+ redirect: 'manual',
+ signal: AbortSignal.timeout(WEBHOOK_REQUEST_TIMEOUT_MS),
+ });
+}
+
+const CUSTOM_HEADER_NAME = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
+const CUSTOM_HEADER_VALUE = /^[\x20-\x7E]{1,512}$/;
+const RESERVED_HEADER_NAMES = new Set([
+ 'host',
+ 'connection',
+ 'keep-alive',
+ 'upgrade',
+ 'te',
+ 'trailer',
+ 'transfer-encoding',
+ 'expect',
+ 'cookie',
+ 'user-agent',
+ 'origin',
+ 'referer',
+ 'forwarded',
+ 'via',
+]);
+const RESERVED_HEADER_PREFIXES = ['content-', 'proxy-', 'sec-', 'webhook-', 'x-forwarded-'];
+
+export type CustomHeaderRejection = 'header_name_invalid' | 'header_name_reserved' | 'header_value_invalid';
+
+export const CUSTOM_HEADER_MESSAGES: Record = {
+ header_name_invalid: 'The header name may contain only letters, digits and hyphens, and must start with a letter.',
+ header_name_reserved: 'That header is set by the portal and cannot be overridden.',
+ header_value_invalid: 'The header value must be 1 to 512 printable ASCII characters.',
+};
+
+/**
+ * One header the user may add for receivers that cannot verify a signature
+ * (for example `Authorization`). No CR/LF or control characters: a value is
+ * sent as a header, never interpreted.
+ */
+export function validateCustomHeader(
+ name: unknown,
+ value: unknown,
+): { ok: true; name: string; value: string } | { ok: false; code: CustomHeaderRejection } {
+ if (typeof name !== 'string' || !CUSTOM_HEADER_NAME.test(name)) {
+ return { ok: false, code: 'header_name_invalid' };
+ }
+ const lower = name.toLowerCase();
+ if (RESERVED_HEADER_NAMES.has(lower) || RESERVED_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))) {
+ return { ok: false, code: 'header_name_reserved' };
+ }
+ if (typeof value !== 'string' || !CUSTOM_HEADER_VALUE.test(value)) {
+ return { ok: false, code: 'header_value_invalid' };
+ }
+ return { ok: true, name, value };
+}
diff --git a/supabase/functions/webhook-endpoints/index.test.ts b/supabase/functions/webhook-endpoints/index.test.ts
new file mode 100644
index 00000000..14befea2
--- /dev/null
+++ b/supabase/functions/webhook-endpoints/index.test.ts
@@ -0,0 +1,643 @@
+import { assert, assertEquals, assertNotEquals } from "jsr:@std/assert@1";
+import type { SupabaseClient } from "jsr:@supabase/supabase-js@2";
+import { FakeDb, fakeClient, type Row } from "../_shared/testing/fakeSupabase.ts";
+import { assertNoSecretsLogged, captureLogs } from "../_shared/testLogCapture.ts";
+import { signWebhook } from "../_shared/webhookSigning.ts";
+import type { DnsResolver } from "../_shared/webhookTarget.ts";
+import {
+ createWebhookEndpointsHandler,
+ WEBHOOK_OUTBOUND_RATE_LIMIT,
+ type WebhookEndpointsDependencies,
+} from "./index.ts";
+
+const USER_A = "aaaaaaaa-0000-4000-8000-00000000000a";
+const USER_B = "bbbbbbbb-0000-4000-8000-00000000000b";
+const NOW = new Date("2026-11-06T12:00:00.000Z");
+const SECRET_1 = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
+const SECRET_2 = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD";
+const HEADER_VALUE = "Bearer receiver-credential-123";
+const ENDPOINT_A = "eeeeeeee-0000-4000-8000-00000000000a";
+
+const encrypt = (plain: string) => Promise.resolve(`enc:test:${btoa(plain)}`);
+const decrypt = (stored: string) => Promise.resolve(atob(stored.replace("enc:test:", "")));
+
+function subscription(userId: string, tier: string): Row {
+ return {
+ user_id: userId,
+ tier,
+ status: "active",
+ current_period_end: "2027-01-01T00:00:00.000Z",
+ cancel_at_period_end: false,
+ };
+}
+
+function endpointRow(overrides: Row = {}): Row {
+ return {
+ id: ENDPOINT_A,
+ user_id: USER_A,
+ label: "A main",
+ url: "https://hooks.example.com/in",
+ scopes: ["workouts"],
+ 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: NOW.toISOString(),
+ updated_at: NOW.toISOString(),
+ ...overrides,
+ };
+}
+
+async function secretRow(overrides: Row = {}): Promise {
+ return {
+ endpoint_id: ENDPOINT_A,
+ user_id: USER_A,
+ signing_secret_enc: await encrypt(SECRET_1),
+ previous_signing_secret_enc: null,
+ previous_expires_at: null,
+ custom_header_value_enc: null,
+ ...overrides,
+ };
+}
+
+/** In-memory versions of the migration's RPCs, with the same ownership rules. */
+function registerRpcs(db: FakeDb, ids: string[]) {
+ db.rpcHandlers.create_webhook_endpoint = (args) => {
+ const owned = db.rows("webhook_endpoints").filter((row) => row.user_id === args.p_user_id);
+ if (owned.length >= 3) {
+ return { data: null, error: { code: "P0001", message: "webhook_endpoint_limit" } };
+ }
+ const id = ids.shift() ?? crypto.randomUUID();
+ db.rows("webhook_endpoints").push(endpointRow({
+ id,
+ user_id: args.p_user_id,
+ label: args.p_label,
+ url: args.p_url,
+ scopes: args.p_scopes,
+ signing_key_hint: args.p_signing_key_hint,
+ custom_header_name: args.p_custom_header_name,
+ }));
+ db.rows("webhook_endpoint_secrets").push({
+ endpoint_id: id,
+ user_id: args.p_user_id,
+ signing_secret_enc: args.p_signing_secret_enc,
+ previous_signing_secret_enc: null,
+ previous_expires_at: null,
+ custom_header_value_enc: args.p_custom_header_value_enc,
+ });
+ return { data: id, error: null };
+ };
+ db.rpcHandlers.rotate_webhook_signing_secret = (args) => {
+ const row = db.rows("webhook_endpoint_secrets").find((secret) =>
+ secret.endpoint_id === args.p_endpoint_id && secret.user_id === args.p_user_id
+ );
+ if (!row) return { data: false, error: null };
+ row.previous_signing_secret_enc = row.signing_secret_enc;
+ row.previous_expires_at = new Date(NOW.getTime() + 86_400_000).toISOString();
+ row.signing_secret_enc = args.p_signing_secret_enc;
+ const endpoint = db.rows("webhook_endpoints").find((entry) => entry.id === args.p_endpoint_id);
+ if (endpoint) endpoint.signing_key_hint = args.p_signing_key_hint;
+ return { data: true, error: null };
+ };
+ db.rpcHandlers.set_webhook_endpoint_header = (args) => {
+ const endpoint = db.rows("webhook_endpoints").find((entry) =>
+ entry.id === args.p_endpoint_id && entry.user_id === args.p_user_id
+ );
+ if (!endpoint) return { data: false, error: null };
+ endpoint.custom_header_name = args.p_custom_header_name;
+ const secret = db.rows("webhook_endpoint_secrets").find((entry) => entry.endpoint_id === args.p_endpoint_id);
+ if (secret) secret.custom_header_value_enc = args.p_custom_header_value_enc;
+ return { data: true, error: null };
+ };
+ db.rpcHandlers.enqueue_webhook_backfill = (args) => {
+ const endpoint = db.rows("webhook_endpoints").find((entry) =>
+ entry.id === args.p_endpoint_id && entry.user_id === args.p_user_id && entry.status === "active"
+ );
+ return { data: endpoint ? 7 : 0, error: null };
+ };
+}
+
+interface Outbound {
+ url: string;
+ headers: Record;
+ body: string;
+ redirect: string | undefined;
+}
+
+interface HarnessOptions {
+ userId?: string | null;
+ tier?: string;
+ tables?: Record;
+ dns?: Record;
+ receiverStatus?: number;
+ secrets?: string[];
+}
+
+function harness(options: HarnessOptions = {}) {
+ const userId = options.userId === undefined ? USER_A : options.userId;
+ const db = new FakeDb({
+ subscriptions: [subscription(USER_A, options.tier ?? "FLAME"), subscription(USER_B, "FLAME")],
+ ...(options.tables ?? {}),
+ });
+ registerRpcs(db, [ENDPOINT_A]);
+ const outbound: Outbound[] = [];
+ const lookups: string[] = [];
+ const dns = options.dns ?? { "hooks.example.com/A": ["93.184.216.34"] };
+ const resolveDns: DnsResolver = (hostname, recordType) => {
+ lookups.push(`${hostname}/${recordType}`);
+ return Promise.resolve(dns[`${hostname}/${recordType}`] ?? []);
+ };
+ const secrets = [...(options.secrets ?? [SECRET_1, SECRET_2])];
+ let nextId = 0;
+ const deps: WebhookEndpointsDependencies = {
+ createAuthClient: () => fakeClient(db, userId),
+ createAdminClient: () => fakeClient(db, null, () => NOW) as unknown as SupabaseClient,
+ fetch: ((input: string | URL | Request, init?: RequestInit) => {
+ outbound.push({
+ url: String(input),
+ headers: (init?.headers ?? {}) as Record,
+ body: String(init?.body),
+ redirect: init?.redirect,
+ });
+ return Promise.resolve(new Response("receiver body", { status: options.receiverStatus ?? 200 }));
+ }) as typeof fetch,
+ resolveDns,
+ env: (name) =>
+ ({
+ SUPABASE_URL: "https://abcdefghijklmnopqrst.supabase.co",
+ APP_URL: "https://phoenix-portal.com",
+ } as Record)[name],
+ now: () => NOW,
+ encrypt,
+ decrypt,
+ generateSecret: () => secrets.shift() ?? SECRET_2,
+ newId: () => `dddddddd-0000-4000-8000-${String(++nextId).padStart(12, "0")}`,
+ };
+ const handler = createWebhookEndpointsHandler(deps);
+ const call = (body: unknown, init: { authorization?: string | null; raw?: string } = {}) => {
+ const headers = new Headers({ "Content-Type": "application/json" });
+ if (init.authorization !== null) headers.set("Authorization", init.authorization ?? "Bearer test-jwt");
+ return handler(
+ new Request("http://localhost/functions/v1/webhook-endpoints", {
+ method: "POST",
+ headers,
+ body: init.raw ?? JSON.stringify(body),
+ }),
+ );
+ };
+ return { db, call, outbound, lookups, handler };
+}
+
+const CREATE = {
+ action: "create",
+ label: " Home lab ",
+ url: "https://hooks.example.com/in#ignored",
+ scopes: ["workouts", "personal_records", "workouts"],
+};
+
+Deno.test("webhook-endpoints: a request without a bearer token is refused with 401", async () => {
+ const { call, db } = harness();
+
+ const response = await call(CREATE, { authorization: null });
+
+ assertEquals(response.status, 401);
+ assertEquals(db.rpcCallNames(), []);
+});
+
+Deno.test("webhook-endpoints: a token the auth service does not recognise is refused with 401", async () => {
+ const { call, db } = harness({ userId: null });
+
+ const response = await call(CREATE);
+
+ assertEquals(response.status, 401);
+ assertEquals(db.rows("webhook_endpoints").length, 0);
+});
+
+Deno.test("webhook-endpoints: create stores the endpoint for the JWT user and returns the secret once", async () => {
+ const { call, db } = harness();
+
+ const response = await call({ ...CREATE, user_id: USER_B, userId: USER_B });
+ const body = await response.json();
+
+ assertEquals(response.status, 201);
+ assertEquals(body.signingSecret, SECRET_1);
+ // The owner is the verified user, whatever the body claims.
+ const stored = db.rows("webhook_endpoints")[0];
+ assertEquals(stored.user_id, USER_A);
+ assertEquals(stored.label, "Home lab");
+ assertEquals(stored.url, "https://hooks.example.com/in");
+ assertEquals(stored.scopes, ["workouts", "personal_records"]);
+ assertEquals(stored.signing_key_hint, "LaSw");
+ // At rest the secret is ciphertext, never the plaintext.
+ const secret = db.rows("webhook_endpoint_secrets")[0];
+ assertEquals(secret.user_id, USER_A);
+ assertNotEquals(secret.signing_secret_enc, SECRET_1);
+ assertEquals(await decrypt(secret.signing_secret_enc as string), SECRET_1);
+ // The endpoint object carries metadata only.
+ assertEquals(body.endpoint.id, ENDPOINT_A);
+ assert(!JSON.stringify(body.endpoint).includes("whsec_"));
+ assertEquals("user_id" in body.endpoint, false);
+});
+
+Deno.test("webhook-endpoints: create encrypts the custom header value and stores only its name in the endpoint", async () => {
+ const { call, db } = harness();
+
+ const response = await call({ ...CREATE, customHeader: { name: "Authorization", value: HEADER_VALUE } });
+ const text = await response.text();
+
+ assertEquals(response.status, 201);
+ assertEquals(db.rows("webhook_endpoints")[0].custom_header_name, "Authorization");
+ const stored = db.rows("webhook_endpoint_secrets")[0].custom_header_value_enc as string;
+ assertNotEquals(stored, HEADER_VALUE);
+ assertEquals(await decrypt(stored), HEADER_VALUE);
+ // The value is write-only: it never comes back.
+ assert(!text.includes(HEADER_VALUE));
+});
+
+Deno.test("webhook-endpoints: an EMBER user cannot create an endpoint and nothing is resolved or stored", async () => {
+ const { call, db, lookups } = harness({ tier: "EMBER" });
+
+ const response = await call(CREATE);
+ const body = await response.json();
+
+ assertEquals(response.status, 402);
+ assertEquals(body.requiredTier, "FLAME");
+ assertEquals(db.rows("webhook_endpoints").length, 0);
+ assertEquals(lookups, []);
+});
+
+Deno.test("webhook-endpoints: create refuses URLs that are not public https targets", async () => {
+ const cases: Array<[string, string, Record | undefined]> = [
+ ["http://hooks.example.com/in", "url_not_https", undefined],
+ ["https://localhost/in", "url_host_not_allowed", undefined],
+ ["https://169.254.169.254/latest/meta-data/", "url_host_not_allowed", undefined],
+ ["https://abcdefghijklmnopqrst.supabase.co/functions/v1/delete-account", "url_host_not_allowed", undefined],
+ ["https://phoenix-portal.com/in", "url_host_not_allowed", undefined],
+ ["https://user:pw@hooks.example.com/in", "url_has_credentials", undefined],
+ ["https://hooks.example.com:22/in", "url_port_not_allowed", undefined],
+ ["https://hooks.example.com/in", "url_resolves_to_private_address", { "hooks.example.com/A": ["10.0.0.5"] }],
+ ["https://hooks.example.com/in", "dns_failed", {}],
+ ];
+ for (const [url, code, dns] of cases) {
+ const { call, db } = harness({ dns });
+
+ const response = await call({ ...CREATE, url });
+ const body = await response.json();
+
+ assertEquals(response.status, 400, url);
+ assertEquals(body.error, code, url);
+ assertEquals(db.rows("webhook_endpoints").length, 0, url);
+ }
+});
+
+Deno.test("webhook-endpoints: create refuses a reserved or malformed custom header", async () => {
+ for (const [name, value, code] of [
+ ["Host", "evil.example.com", "header_name_reserved"],
+ ["webhook-signature", "v1,forged", "header_name_reserved"],
+ ["Authorization", "a\r\nX-Injected: 1", "header_value_invalid"],
+ ["bad name", "v", "header_name_invalid"],
+ ]) {
+ const { call, db } = harness();
+
+ const response = await call({ ...CREATE, customHeader: { name, value } });
+
+ assertEquals(response.status, 400, name);
+ assertEquals((await response.json()).error, code, name);
+ assertEquals(db.rows("webhook_endpoints").length, 0, name);
+ }
+});
+
+Deno.test("webhook-endpoints: create refuses unknown scopes, an empty scope list and a bad label", async () => {
+ for (const patch of [
+ { scopes: ["workouts", "telemetry"] },
+ { scopes: [] },
+ { scopes: "workouts" },
+ { label: " " },
+ { label: "x".repeat(81) },
+ ]) {
+ const { call, db } = harness();
+
+ const response = await call({ ...CREATE, ...patch });
+
+ assertEquals(response.status, 400, JSON.stringify(patch));
+ assertEquals(db.rows("webhook_endpoints").length, 0);
+ }
+});
+
+Deno.test("webhook-endpoints: a fourth endpoint is refused with 409", async () => {
+ const { call } = harness({
+ tables: {
+ webhook_endpoints: [
+ endpointRow({ id: "eeeeeeee-0000-4000-8000-000000000001" }),
+ endpointRow({ id: "eeeeeeee-0000-4000-8000-000000000002" }),
+ endpointRow({ id: "eeeeeeee-0000-4000-8000-000000000003" }),
+ ],
+ },
+ });
+
+ const response = await call(CREATE);
+
+ assertEquals(response.status, 409);
+ assertEquals((await response.json()).error, "endpoint_limit");
+});
+
+Deno.test("webhook-endpoints: another user's endpoint is a 404 for every action and is left untouched", async () => {
+ for (const action of [
+ { action: "update", label: "hijacked" },
+ { action: "update", status: "paused" },
+ { action: "update", url: "https://hooks.example.com/attacker" },
+ { action: "update", customHeader: { name: "X-Api-Key", value: "attacker" } },
+ { action: "rotate_secret" },
+ { action: "test" },
+ { action: "resend_all" },
+ { action: "delete" },
+ ]) {
+ // Arrange: the endpoint belongs to A; the caller is B.
+ const before = endpointRow();
+ const secretBefore = await secretRow();
+ const { call, db, outbound } = harness({
+ userId: USER_B,
+ tables: { webhook_endpoints: [{ ...before }], webhook_endpoint_secrets: [{ ...secretBefore }] },
+ });
+
+ // Act
+ const response = await call({ ...action, endpointId: ENDPOINT_A });
+
+ // Assert
+ assertEquals(response.status, 404, JSON.stringify(action));
+ assertEquals(db.rows("webhook_endpoints"), [before], JSON.stringify(action));
+ assertEquals(db.rows("webhook_endpoint_secrets"), [secretBefore], JSON.stringify(action));
+ assertEquals(outbound.length, 0, JSON.stringify(action));
+ assertEquals(db.rows("webhook_deliveries").length, 0, JSON.stringify(action));
+ }
+});
+
+Deno.test("webhook-endpoints: a lapsed user can still pause and delete, but not edit or resume", async () => {
+ const tables = async () => ({
+ webhook_endpoints: [endpointRow()],
+ webhook_endpoint_secrets: [await secretRow()],
+ });
+
+ const paused = harness({ tier: "FREE", tables: await tables() });
+ const pauseResponse = await paused.call({ action: "update", endpointId: ENDPOINT_A, status: "paused" });
+ assertEquals(pauseResponse.status, 200);
+ assertEquals(paused.db.rows("webhook_endpoints")[0].status, "paused");
+ assertEquals(paused.db.rows("webhook_endpoints")[0].disabled_reason, "user_paused");
+
+ const deleted = harness({ tier: "FREE", tables: await tables() });
+ const deleteResponse = await deleted.call({ action: "delete", endpointId: ENDPOINT_A });
+ assertEquals(deleteResponse.status, 200);
+ assertEquals(deleted.db.rows("webhook_endpoints").length, 0);
+
+ // A pause smuggled together with an edit is an edit: it needs the tier.
+ const edited = harness({ tier: "FREE", tables: await tables() });
+ const editResponse = await edited.call({
+ action: "update",
+ endpointId: ENDPOINT_A,
+ status: "paused",
+ url: "https://hooks.example.com/elsewhere",
+ });
+ assertEquals(editResponse.status, 402);
+ assertEquals(edited.db.rows("webhook_endpoints")[0].url, "https://hooks.example.com/in");
+
+ const resumed = harness({
+ tier: "FREE",
+ tables: {
+ webhook_endpoints: [endpointRow({ status: "paused", disabled_reason: "subscription_lapsed" })],
+ webhook_endpoint_secrets: [await secretRow()],
+ },
+ });
+ const resumeResponse = await resumed.call({ action: "update", endpointId: ENDPOINT_A, status: "active" });
+ assertEquals(resumeResponse.status, 402);
+ assertEquals(resumed.db.rows("webhook_endpoints")[0].status, "paused");
+ assertEquals(resumed.outbound.length, 0);
+});
+
+Deno.test("webhook-endpoints: pausing a disabled endpoint keeps the reason it was switched off for", async () => {
+ const { call, db } = harness({
+ tables: {
+ webhook_endpoints: [endpointRow({ status: "disabled", disabled_reason: "too_many_failures" })],
+ webhook_endpoint_secrets: [await secretRow()],
+ },
+ });
+
+ const response = await call({ action: "update", endpointId: ENDPOINT_A, status: "paused" });
+
+ assertEquals(response.status, 200);
+ assertEquals(db.rows("webhook_endpoints")[0].status, "disabled");
+ assertEquals(db.rows("webhook_endpoints")[0].disabled_reason, "too_many_failures");
+});
+
+Deno.test("webhook-endpoints: resume needs a passing test delivery and clears the reason in the same write", async () => {
+ const tables = async () => ({
+ webhook_endpoints: [endpointRow({ status: "disabled", disabled_reason: "too_many_failures", consecutive_failures: 9 })],
+ webhook_endpoint_secrets: [await secretRow()],
+ });
+
+ const failing = harness({ receiverStatus: 500, tables: await tables() });
+ const refused = await failing.call({ action: "update", endpointId: ENDPOINT_A, status: "active" });
+ const refusedBody = await refused.json();
+ assertEquals(refused.status, 409);
+ assertEquals(refusedBody.error, "test_delivery_failed");
+ assertEquals(refusedBody.statusCode, 500);
+ assertEquals(failing.db.rows("webhook_endpoints")[0].status, "disabled");
+ assertEquals(failing.db.rows("webhook_endpoints")[0].disabled_reason, "too_many_failures");
+
+ const passing = harness({ receiverStatus: 202, tables: await tables() });
+ const accepted = await passing.call({ action: "update", endpointId: ENDPOINT_A, status: "active" });
+ assertEquals(accepted.status, 200);
+ const row = passing.db.rows("webhook_endpoints")[0];
+ assertEquals([row.status, row.disabled_reason, row.consecutive_failures], ["active", null, 0]);
+ assertEquals((await accepted.json()).endpoint.status, "active");
+ assertEquals(passing.outbound.length, 1);
+});
+
+Deno.test("webhook-endpoints: update validates a new URL, sets the header through the RPC and can clear it", async () => {
+ const { call, db } = harness({
+ tables: { webhook_endpoints: [endpointRow()], webhook_endpoint_secrets: [await secretRow()] },
+ });
+
+ const bad = await call({ action: "update", endpointId: ENDPOINT_A, url: "https://10.0.0.1/in" });
+ assertEquals(bad.status, 400);
+ assertEquals(db.rows("webhook_endpoints")[0].url, "https://hooks.example.com/in");
+
+ const set = await call({
+ action: "update",
+ endpointId: ENDPOINT_A,
+ label: "Renamed",
+ scopes: ["routines"],
+ customHeader: { name: "X-Api-Key", value: HEADER_VALUE },
+ });
+ assertEquals(set.status, 200);
+ assertEquals(db.rows("webhook_endpoints")[0].label, "Renamed");
+ assertEquals(db.rows("webhook_endpoints")[0].scopes, ["routines"]);
+ assertEquals(db.rows("webhook_endpoints")[0].custom_header_name, "X-Api-Key");
+ assertEquals(await decrypt(db.rows("webhook_endpoint_secrets")[0].custom_header_value_enc as string), HEADER_VALUE);
+
+ const cleared = await call({ action: "update", endpointId: ENDPOINT_A, customHeader: null });
+ assertEquals(cleared.status, 200);
+ assertEquals(db.rows("webhook_endpoints")[0].custom_header_name, null);
+ assertEquals(db.rows("webhook_endpoint_secrets")[0].custom_header_value_enc, null);
+});
+
+Deno.test("webhook-endpoints: rotate returns a new secret once and keeps the old one for the overlap", async () => {
+ const { call, db } = harness({
+ secrets: [SECRET_2],
+ tables: { webhook_endpoints: [endpointRow()], webhook_endpoint_secrets: [await secretRow()] },
+ });
+
+ const response = await call({ action: "rotate_secret", endpointId: ENDPOINT_A });
+ const body = await response.json();
+
+ assertEquals(response.status, 200);
+ assertEquals(body.signingSecret, SECRET_2);
+ assertEquals(body.endpoint.signing_key_hint, "b7oD");
+ const stored = db.rows("webhook_endpoint_secrets")[0];
+ assertEquals(await decrypt(stored.signing_secret_enc as string), SECRET_2);
+ assertEquals(await decrypt(stored.previous_signing_secret_enc as string), SECRET_1);
+});
+
+Deno.test("webhook-endpoints: test sends one signed ping to the stored URL and logs it", async () => {
+ const { call, db, outbound } = harness({
+ tables: {
+ webhook_endpoints: [endpointRow({ custom_header_name: "Authorization" })],
+ webhook_endpoint_secrets: [await secretRow({ custom_header_value_enc: await encrypt(HEADER_VALUE) })],
+ },
+ });
+
+ const response = await call({ action: "test", endpointId: ENDPOINT_A });
+ const body = await response.json();
+
+ assertEquals(response.status, 200);
+ assertEquals(body, { delivered: true, statusCode: 200, errorCode: null, durationMs: 0 });
+ assertEquals(outbound.length, 1);
+ const sent = outbound[0];
+ assertEquals(sent.url, "https://hooks.example.com/in");
+ assertEquals(sent.redirect, "manual");
+ assertEquals(JSON.parse(sent.body), {
+ type: "ping",
+ timestamp: NOW.toISOString(),
+ data: { apiVersion: "2026-11-01", endpointId: ENDPOINT_A },
+ });
+ const deliveryId = "dddddddd-0000-4000-8000-000000000001";
+ assertEquals(sent.headers["webhook-id"], deliveryId);
+ assertEquals(
+ sent.headers["webhook-signature"],
+ await signWebhook(SECRET_1, deliveryId, Math.floor(NOW.getTime() / 1000), sent.body),
+ );
+ // The user's own header is the only Authorization that may appear.
+ assertEquals(sent.headers.Authorization, HEADER_VALUE);
+ assertEquals("apikey" in sent.headers, false);
+ // Nothing the receiver answered reaches the caller.
+ assert(!JSON.stringify(body).includes("receiver body"));
+ const logged = db.rows("webhook_deliveries");
+ assertEquals(logged.length, 1);
+ assertEquals(
+ [logged[0].id, logged[0].endpoint_id, logged[0].user_id, logged[0].entity, logged[0].status, logged[0].last_status_code],
+ [deliveryId, ENDPOINT_A, USER_A, "ping", "delivered", 200],
+ );
+});
+
+Deno.test("webhook-endpoints: a failed test delivery reports a fixed code and never switches the endpoint off", async () => {
+ const { call, db } = harness({
+ receiverStatus: 301,
+ tables: { webhook_endpoints: [endpointRow()], webhook_endpoint_secrets: [await secretRow()] },
+ });
+
+ const response = await call({ action: "test", endpointId: ENDPOINT_A });
+ const body = await response.json();
+
+ assertEquals(response.status, 200);
+ assertEquals([body.delivered, body.statusCode, body.errorCode], [false, 301, "redirect_not_followed"]);
+ assertEquals(db.rows("webhook_endpoints")[0].status, "active");
+ assertEquals(db.rows("webhook_deliveries")[0].status, "dead");
+});
+
+Deno.test("webhook-endpoints: requests to a user-chosen host are rate limited on their own tight key", async () => {
+ const { call, outbound } = harness({
+ tables: { webhook_endpoints: [endpointRow()], webhook_endpoint_secrets: [await secretRow()] },
+ });
+
+ for (let i = 0; i < WEBHOOK_OUTBOUND_RATE_LIMIT.maxRequests; i += 1) {
+ assertEquals((await call({ action: "test", endpointId: ENDPOINT_A })).status, 200);
+ }
+ const limited = await call({ action: "test", endpointId: ENDPOINT_A });
+ // A label edit makes no outbound request and is not caught by that key.
+ const edit = await call({ action: "update", endpointId: ENDPOINT_A, label: "Still allowed" });
+
+ assertEquals(limited.status, 429);
+ assertEquals(outbound.length, WEBHOOK_OUTBOUND_RATE_LIMIT.maxRequests);
+ assertEquals(edit.status, 200);
+});
+
+Deno.test("webhook-endpoints: resend_all enqueues for the caller's active endpoint only", async () => {
+ const active = harness({
+ tables: { webhook_endpoints: [endpointRow()], webhook_endpoint_secrets: [await secretRow()] },
+ });
+ const enqueued = await active.call({ action: "resend_all", endpointId: ENDPOINT_A });
+ assertEquals(enqueued.status, 200);
+ assertEquals(await enqueued.json(), { enqueued: 7 });
+ assertEquals(active.db.rpcCalls.at(-1), {
+ name: "enqueue_webhook_backfill",
+ args: { p_user_id: USER_A, p_endpoint_id: ENDPOINT_A },
+ });
+
+ const paused = harness({
+ tables: {
+ webhook_endpoints: [endpointRow({ status: "paused", disabled_reason: "user_paused" })],
+ webhook_endpoint_secrets: [await secretRow()],
+ },
+ });
+ const refused = await paused.call({ action: "resend_all", endpointId: ENDPOINT_A });
+ assertEquals(refused.status, 409);
+ assertEquals(paused.db.rpcCallNames().includes("enqueue_webhook_backfill"), false);
+});
+
+Deno.test("webhook-endpoints: malformed requests are refused before anything is read or written", async () => {
+ const { call, db, handler } = harness();
+
+ assertEquals((await call({ action: "explode" })).status, 400);
+ assertEquals((await call({})).status, 400);
+ assertEquals((await call(null, { raw: "{not json" })).status, 400);
+ assertEquals((await call({ action: "delete", endpointId: "not-a-uuid" })).status, 400);
+ assertEquals((await call({ action: "test" })).status, 400);
+ assertEquals((await call(null, { raw: JSON.stringify({ action: "create", label: "x".repeat(20_000) }) })).status, 413);
+ const get = await handler(new Request("http://localhost/functions/v1/webhook-endpoints", { method: "GET" }));
+ assertEquals(get.status, 405);
+ assertEquals(db.rows("webhook_endpoints").length, 0);
+ assertEquals(db.rpcCallNames(), []);
+});
+
+Deno.test("webhook-endpoints: no secret, header value or URL path is ever logged", async () => {
+ const { call } = harness({
+ receiverStatus: 500,
+ tables: {
+ webhook_endpoints: [endpointRow({
+ url: "https://hooks.example.com/in/private-path-token",
+ custom_header_name: "Authorization",
+ })],
+ webhook_endpoint_secrets: [await secretRow({ custom_header_value_enc: await encrypt(HEADER_VALUE) })],
+ },
+ });
+
+ const { logs } = await captureLogs(async () => {
+ await call({ ...CREATE, customHeader: { name: "X-Api-Key", value: "second-header-value" } });
+ await call({ action: "rotate_secret", endpointId: ENDPOINT_A });
+ await call({ action: "test", endpointId: ENDPOINT_A });
+ await call({ action: "update", endpointId: ENDPOINT_A, status: "paused" });
+ await call({ action: "update", endpointId: ENDPOINT_A, status: "active" });
+ await call({ action: "delete", endpointId: ENDPOINT_A });
+ });
+
+ assertNoSecretsLogged(logs, [
+ SECRET_1,
+ SECRET_2,
+ HEADER_VALUE,
+ "second-header-value",
+ "private-path-token",
+ "test-jwt",
+ ]);
+});
diff --git a/supabase/functions/webhook-endpoints/index.ts b/supabase/functions/webhook-endpoints/index.ts
new file mode 100644
index 00000000..e90aea7f
--- /dev/null
+++ b/supabase/functions/webhook-endpoints/index.ts
@@ -0,0 +1,670 @@
+import { createClient, type SupabaseClient } from 'jsr:@supabase/supabase-js@2';
+import { getCorsHeaders } from '../_shared/cors.ts';
+import {
+ DATA_SHARING_MIN_TIER,
+ type DataSharingScope,
+ isDataSharingScope,
+ MAX_WEBHOOK_ENDPOINTS,
+} from '../_shared/dataSharingScopes.ts';
+import { decryptOAuthSecret, encryptOAuthSecret } from '../_shared/oauthTokenCrypto.ts';
+import { checkRateLimit } from '../_shared/rateLimit.ts';
+import { readBoundedRequestBody, REQUEST_BODY_LIMITS } from '../_shared/requestBody.ts';
+import { requireSubscription } from '../_shared/requireSubscription.ts';
+import { loadWebhookCredentials } from '../_shared/webhookCredentials.ts';
+import { sendWebhook, webhookEnvelope, type WebhookSendResult } from '../_shared/webhookSend.ts';
+import { generateWebhookSecret, webhookSecretHint } from '../_shared/webhookSigning.ts';
+import {
+ CUSTOM_HEADER_MESSAGES,
+ type DnsResolver,
+ ownHostsFromEnv,
+ resolveWebhookTarget,
+ systemDnsResolver,
+ validateCustomHeader,
+ WEBHOOK_TARGET_MESSAGES,
+} from '../_shared/webhookTarget.ts';
+
+/**
+ * Data sharing: the one write path for a user's outbound webhook endpoints.
+ *
+ * POST { action, ... } with the user's JWT:
+ * create { label, url, scopes, customHeader? } -> 201 { endpoint, signingSecret }
+ * update { endpointId, label?, url?, scopes?,
+ * customHeader? | null, status? } -> { endpoint }
+ * rotate_secret { endpointId } -> { endpoint, signingSecret }
+ * test { endpointId } -> { delivered, statusCode, errorCode, durationMs }
+ * resend_all { endpointId } -> { enqueued }
+ * delete { endpointId } -> { deleted: true }
+ *
+ * Isolation (FP-1): the user id comes only from the verified JWT, and every
+ * read and write below carries `.eq('user_id', userId)` or passes it to a
+ * user-scoped RPC. An endpoint id that belongs to someone else is a 404.
+ *
+ * Tier (FP-2): FLAME and above, checked here on every action except `delete`
+ * and a pause, which a lapsed user must always be able to do.
+ *
+ * Secrets (FP-5): the signing secret is generated here, stored encrypted and
+ * returned exactly once, by `create` and `rotate_secret`. Nothing else ever
+ * returns it, and nothing logs it, the custom header value, or the URL.
+ *
+ * Reads (the endpoint list and the delivery log) do not come through here:
+ * the portal reads both tables directly under owner RLS.
+ */
+
+export const WEBHOOK_ENDPOINTS_RATE_LIMIT = { maxRequests: 60, windowSeconds: 300 } as const;
+/**
+ * create, test, a URL change and a resume are the only requests the portal
+ * makes to a host a user chose, on demand. Kept tight so the function cannot
+ * be used to probe hosts or names.
+ */
+export const WEBHOOK_OUTBOUND_RATE_LIMIT = { maxRequests: 10, windowSeconds: 900 } as const;
+export const WEBHOOK_RESEND_RATE_LIMIT = { maxRequests: 2, windowSeconds: 3600 } as const;
+
+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 UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+const LABEL_MAX = 80;
+
+type Json = Record;
+
+interface EndpointRow {
+ id: string;
+ label: string;
+ url: string;
+ scopes: string[];
+ status: 'active' | 'paused' | 'disabled';
+ 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 WebhookEndpointsAuthClient {
+ auth: { getUser(jwt: string): Promise };
+}
+
+export interface WebhookEndpointsDependencies {
+ createAuthClient(authorization: string): WebhookEndpointsAuthClient;
+ createAdminClient(): SupabaseClient;
+ fetch: typeof fetch;
+ resolveDns: DnsResolver;
+ env(name: string): string | undefined;
+ now(): Date;
+ encrypt(plain: string): Promise;
+ decrypt(stored: string): Promise;
+ generateSecret(): string;
+ newId(): string;
+}
+
+function defaultDependencies(): WebhookEndpointsDependencies {
+ return {
+ createAuthClient(authorization: string) {
+ return createClient(
+ Deno.env.get('SUPABASE_URL')!,
+ Deno.env.get('SUPABASE_ANON_KEY')!,
+ {
+ global: { headers: { Authorization: authorization } },
+ auth: { persistSession: false, autoRefreshToken: false },
+ },
+ );
+ },
+ createAdminClient() {
+ return createClient(
+ Deno.env.get('SUPABASE_URL')!,
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
+ { auth: { persistSession: false, autoRefreshToken: false } },
+ );
+ },
+ fetch: (input, init) => fetch(input, init),
+ resolveDns: systemDnsResolver,
+ env: (name) => Deno.env.get(name),
+ now: () => new Date(),
+ encrypt: encryptOAuthSecret,
+ decrypt: decryptOAuthSecret,
+ generateSecret: generateWebhookSecret,
+ newId: () => crypto.randomUUID(),
+ };
+}
+
+function json(body: unknown, status: number, cors: Record): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { ...cors, 'Content-Type': 'application/json' },
+ });
+}
+
+function isPlainObject(value: unknown): value is Json {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function authStatus(error: unknown): number | null {
+ if (!isPlainObject(error)) return null;
+ return typeof error.status === 'number' ? error.status : null;
+}
+
+function invalid(message: string, cors: Record, error = 'invalid_request'): Response {
+ return json({ error, message }, 400, cors);
+}
+
+function notFound(cors: Record): Response {
+ return json({ error: 'endpoint_not_found', message: 'Endpoint not found.' }, 404, cors);
+}
+
+function unavailable(cors: Record): Response {
+ return new Response(
+ JSON.stringify({ error: 'data_sharing_unavailable', message: 'Data sharing is temporarily unavailable. Please try again.' }),
+ { status: 503, headers: { ...cors, 'Content-Type': 'application/json', 'Retry-After': '30' } },
+ );
+}
+
+function parseLabel(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const label = value.trim();
+ return label.length >= 1 && label.length <= LABEL_MAX ? label : null;
+}
+
+function parseScopes(value: unknown): DataSharingScope[] | null {
+ if (!Array.isArray(value) || value.length === 0) return null;
+ const scopes = new Set();
+ for (const entry of value) {
+ if (!isDataSharingScope(entry)) return null;
+ scopes.add(entry);
+ }
+ return [...scopes];
+}
+
+function parseEndpointId(body: Json): string | null {
+ return typeof body.endpointId === 'string' && UUID.test(body.endpointId) ? body.endpointId : null;
+}
+
+/**
+ * The endpoint as the browser may see it: an explicit allowlist, so a column
+ * added to the table (or a wider select) can never leak through a response.
+ */
+function publicEndpoint(row: EndpointRow): EndpointRow {
+ return {
+ id: row.id,
+ label: row.label,
+ url: row.url,
+ scopes: row.scopes,
+ status: row.status,
+ disabled_reason: row.disabled_reason,
+ custom_header_name: row.custom_header_name,
+ signing_key_hint: row.signing_key_hint,
+ consecutive_failures: row.consecutive_failures,
+ last_success_at: row.last_success_at,
+ last_failure_at: row.last_failure_at,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+}
+
+async function loadEndpoint(
+ admin: SupabaseClient,
+ userId: string,
+ endpointId: string,
+): Promise<{ ok: true; endpoint: EndpointRow | null } | { ok: false }> {
+ const { data, error } = await admin
+ .from('webhook_endpoints')
+ .select(ENDPOINT_COLUMNS)
+ .eq('id', endpointId)
+ .eq('user_id', userId)
+ .maybeSingle();
+ if (error) {
+ console.error('[WEBHOOK_ENDPOINTS] endpoint read failed', { code: (error as { code?: string }).code });
+ return { ok: false };
+ }
+ return { ok: true, endpoint: data ? publicEndpoint(data as unknown as EndpointRow) : null };
+}
+
+/**
+ * Sends a signed `ping` to the endpoint and records it in the delivery log.
+ * The result is the same shape a real delivery produces.
+ */
+async function sendPing(
+ deps: WebhookEndpointsDependencies,
+ admin: SupabaseClient,
+ userId: string,
+ endpoint: EndpointRow,
+): Promise<{ ok: true; result: WebhookSendResult } | { ok: false }> {
+ const credentials = await loadWebhookCredentials(admin, {
+ userId,
+ endpointId: endpoint.id,
+ customHeaderName: endpoint.custom_header_name,
+ now: deps.now(),
+ }, deps.decrypt);
+ if (!credentials.ok) {
+ console.error('[WEBHOOK_ENDPOINTS] credentials unavailable', { reason: credentials.reason });
+ return { ok: false };
+ }
+
+ const deliveryId = deps.newId();
+ const result = await sendWebhook(
+ { fetch: deps.fetch, resolveDns: deps.resolveDns, ownHosts: ownHostsFromEnv(deps.env), now: deps.now },
+ {
+ url: endpoint.url,
+ deliveryId,
+ secrets: credentials.credentials.secrets,
+ customHeader: credentials.credentials.customHeader,
+ body: webhookEnvelope('ping', deps.now(), { endpointId: endpoint.id }),
+ },
+ );
+
+ const nowIso = deps.now().toISOString();
+ const { error } = await admin.from('webhook_deliveries').insert({
+ id: deliveryId,
+ endpoint_id: endpoint.id,
+ user_id: userId,
+ entity: 'ping',
+ entity_id: deliveryId,
+ event_type: 'ping',
+ status: result.outcome === 'delivered' ? 'delivered' : 'dead',
+ attempt_count: 1,
+ next_attempt_at: nowIso,
+ last_status_code: result.statusCode,
+ last_error_code: result.errorCode,
+ duration_ms: result.durationMs,
+ finished_at: nowIso,
+ });
+ if (error) {
+ // The user still gets the result; only the log line is missing.
+ console.error('[WEBHOOK_ENDPOINTS] ping log insert failed', { code: (error as { code?: string }).code });
+ }
+ return { ok: true, result };
+}
+
+function pingBody(result: WebhookSendResult): Json {
+ return {
+ delivered: result.outcome === 'delivered',
+ statusCode: result.statusCode,
+ errorCode: result.errorCode,
+ durationMs: result.durationMs,
+ };
+}
+
+async function handleCreate(
+ deps: WebhookEndpointsDependencies,
+ admin: SupabaseClient,
+ userId: string,
+ body: Json,
+ cors: Record,
+): Promise {
+ const label = parseLabel(body.label);
+ if (!label) return invalid(`label must be 1 to ${LABEL_MAX} characters.`, cors);
+ const scopes = parseScopes(body.scopes);
+ if (!scopes) return invalid('scopes must be a non-empty list of data sharing scopes.', cors);
+
+ let header: { name: string; value: string } | null = null;
+ if (body.customHeader !== undefined && body.customHeader !== null) {
+ if (!isPlainObject(body.customHeader)) return invalid('customHeader must be an object.', cors);
+ const checked = validateCustomHeader(body.customHeader.name, body.customHeader.value);
+ if (!checked.ok) return invalid(CUSTOM_HEADER_MESSAGES[checked.code], cors, checked.code);
+ header = { name: checked.name, value: checked.value };
+ }
+
+ const target = await resolveWebhookTarget(body.url, ownHostsFromEnv(deps.env), deps.resolveDns);
+ if (!target.ok) return invalid(WEBHOOK_TARGET_MESSAGES[target.code], cors, target.code);
+
+ const signingSecret = deps.generateSecret();
+ const secretEnc = await deps.encrypt(signingSecret);
+ const headerEnc = header ? await deps.encrypt(header.value) : null;
+ if (!secretEnc || (header && !headerEnc)) return unavailable(cors);
+
+ const { data: endpointId, error } = await admin.rpc('create_webhook_endpoint', {
+ p_user_id: userId,
+ p_label: label,
+ p_url: target.normalized,
+ p_scopes: scopes,
+ p_signing_secret_enc: secretEnc,
+ p_signing_key_hint: webhookSecretHint(signingSecret),
+ p_custom_header_name: header?.name ?? null,
+ p_custom_header_value_enc: headerEnc,
+ });
+ if (error) {
+ if ((error.message ?? '').includes('webhook_endpoint_limit')) {
+ return json({
+ error: 'endpoint_limit',
+ message: `You can register up to ${MAX_WEBHOOK_ENDPOINTS} endpoints.`,
+ }, 409, cors);
+ }
+ console.error('[WEBHOOK_ENDPOINTS] create failed', { code: (error as { code?: string }).code });
+ return unavailable(cors);
+ }
+
+ const loaded = await loadEndpoint(admin, userId, endpointId as string);
+ if (!loaded.ok || !loaded.endpoint) return unavailable(cors);
+ // The only time the secret is ever returned.
+ return json({ endpoint: loaded.endpoint, signingSecret }, 201, cors);
+}
+
+/** True when the request does nothing but pause: allowed without FLAME. */
+function isPauseOnly(body: Json): boolean {
+ if (body.status !== 'paused') return false;
+ return Object.keys(body).every((key) => key === 'action' || key === 'endpointId' || key === 'status');
+}
+
+async function handlePause(
+ admin: SupabaseClient,
+ userId: string,
+ endpointId: string,
+ cors: Record,
+): Promise {
+ const { data, error } = await admin
+ .from('webhook_endpoints')
+ .update({ status: 'paused', disabled_reason: 'user_paused' })
+ .eq('id', endpointId)
+ .eq('user_id', userId)
+ // A disabled endpoint keeps the reason it was switched off for.
+ .eq('status', 'active')
+ .select(ENDPOINT_COLUMNS)
+ .maybeSingle();
+ if (error) return unavailable(cors);
+ if (data) return json({ endpoint: publicEndpoint(data as unknown as EndpointRow) }, 200, cors);
+ const loaded = await loadEndpoint(admin, userId, endpointId);
+ if (!loaded.ok) return unavailable(cors);
+ if (!loaded.endpoint) return notFound(cors);
+ return json({ endpoint: loaded.endpoint }, 200, cors);
+}
+
+async function handleUpdate(
+ deps: WebhookEndpointsDependencies,
+ admin: SupabaseClient,
+ userId: string,
+ endpointId: string,
+ body: Json,
+ cors: Record,
+): Promise {
+ const loaded = await loadEndpoint(admin, userId, endpointId);
+ if (!loaded.ok) return unavailable(cors);
+ if (!loaded.endpoint) return notFound(cors);
+
+ const patch: Json = {};
+ if (body.label !== undefined) {
+ const label = parseLabel(body.label);
+ if (!label) return invalid(`label must be 1 to ${LABEL_MAX} characters.`, cors);
+ patch.label = label;
+ }
+ if (body.scopes !== undefined) {
+ const scopes = parseScopes(body.scopes);
+ if (!scopes) return invalid('scopes must be a non-empty list of data sharing scopes.', cors);
+ patch.scopes = scopes;
+ }
+ if (body.status !== undefined && body.status !== 'active' && body.status !== 'paused') {
+ return invalid("status must be 'active' or 'paused'.", cors);
+ }
+
+ let header: { name: string; value: string } | null | undefined;
+ if (body.customHeader === null) {
+ header = null;
+ } else if (body.customHeader !== undefined) {
+ if (!isPlainObject(body.customHeader)) return invalid('customHeader must be an object or null.', cors);
+ const checked = validateCustomHeader(body.customHeader.name, body.customHeader.value);
+ if (!checked.ok) return invalid(CUSTOM_HEADER_MESSAGES[checked.code], cors, checked.code);
+ header = { name: checked.name, value: checked.value };
+ }
+
+ if (body.url !== undefined) {
+ const target = await resolveWebhookTarget(body.url, ownHostsFromEnv(deps.env), deps.resolveDns);
+ if (!target.ok) return invalid(WEBHOOK_TARGET_MESSAGES[target.code], cors, target.code);
+ patch.url = target.normalized;
+ }
+
+ if (header !== undefined) {
+ const valueEnc = header ? await deps.encrypt(header.value) : null;
+ if (header && !valueEnc) return unavailable(cors);
+ const { data: updated, error } = await admin.rpc('set_webhook_endpoint_header', {
+ p_user_id: userId,
+ p_endpoint_id: endpointId,
+ p_custom_header_name: header?.name ?? null,
+ p_custom_header_value_enc: valueEnc,
+ });
+ if (error) return unavailable(cors);
+ if (updated !== true) return notFound(cors);
+ }
+
+ // A disabled endpoint keeps the reason it was switched off for.
+ if (body.status === 'paused' && loaded.endpoint.status === 'active') {
+ patch.status = 'paused';
+ patch.disabled_reason = 'user_paused';
+ }
+
+ if (Object.keys(patch).length > 0) {
+ const { error } = await admin
+ .from('webhook_endpoints')
+ .update(patch)
+ .eq('id', endpointId)
+ .eq('user_id', userId);
+ if (error) {
+ console.error('[WEBHOOK_ENDPOINTS] update failed', { code: (error as { code?: string }).code });
+ return unavailable(cors);
+ }
+ }
+
+ let current = await loadEndpoint(admin, userId, endpointId);
+ if (!current.ok || !current.endpoint) return unavailable(cors);
+
+ // Switching an endpoint back on needs proof that it answers: one signed
+ // ping to the URL as it now stands. Whatever switched it off (the user, a
+ // lapsed plan, repeated failures, a 410) is cleared only by that.
+ if (body.status === 'active' && current.endpoint.status !== 'active') {
+ const ping = await sendPing(deps, admin, userId, current.endpoint);
+ if (!ping.ok) return unavailable(cors);
+ if (ping.result.outcome !== 'delivered') {
+ return json({
+ error: 'test_delivery_failed',
+ message: 'The endpoint did not accept a test delivery, so it was not switched on.',
+ ...pingBody(ping.result),
+ }, 409, cors);
+ }
+ const { error } = await admin
+ .from('webhook_endpoints')
+ // Both columns in one statement: the table requires an active endpoint
+ // to have no disabled_reason.
+ .update({ status: 'active', disabled_reason: null, consecutive_failures: 0 })
+ .eq('id', endpointId)
+ .eq('user_id', userId);
+ if (error) return unavailable(cors);
+ current = await loadEndpoint(admin, userId, endpointId);
+ if (!current.ok || !current.endpoint) return unavailable(cors);
+ }
+
+ return json({ endpoint: current.endpoint }, 200, cors);
+}
+
+async function handleRotate(
+ deps: WebhookEndpointsDependencies,
+ admin: SupabaseClient,
+ userId: string,
+ endpointId: string,
+ cors: Record,
+): Promise {
+ const signingSecret = deps.generateSecret();
+ const secretEnc = await deps.encrypt(signingSecret);
+ if (!secretEnc) return unavailable(cors);
+ const { data: rotated, error } = await admin.rpc('rotate_webhook_signing_secret', {
+ p_user_id: userId,
+ p_endpoint_id: endpointId,
+ p_signing_secret_enc: secretEnc,
+ p_signing_key_hint: webhookSecretHint(signingSecret),
+ });
+ if (error) {
+ console.error('[WEBHOOK_ENDPOINTS] rotate failed', { code: (error as { code?: string }).code });
+ return unavailable(cors);
+ }
+ if (rotated !== true) return notFound(cors);
+ const loaded = await loadEndpoint(admin, userId, endpointId);
+ if (!loaded.ok || !loaded.endpoint) return unavailable(cors);
+ return json({ endpoint: loaded.endpoint, signingSecret }, 200, cors);
+}
+
+async function handleDelete(
+ admin: SupabaseClient,
+ userId: string,
+ endpointId: string,
+ cors: Record,
+): Promise {
+ // The secret row and the delivery log cascade from the endpoint.
+ const { data, error } = await admin
+ .from('webhook_endpoints')
+ .delete()
+ .eq('id', endpointId)
+ .eq('user_id', userId)
+ .select('id');
+ if (error) {
+ console.error('[WEBHOOK_ENDPOINTS] delete failed', { code: (error as { code?: string }).code });
+ return unavailable(cors);
+ }
+ if (!Array.isArray(data) || data.length === 0) return notFound(cors);
+ return json({ deleted: true }, 200, cors);
+}
+
+async function webhookEndpointsHandler(
+ req: Request,
+ deps: WebhookEndpointsDependencies,
+): Promise {
+ const cors = getCorsHeaders(req);
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: cors });
+ if (req.method !== 'POST') return json({ error: 'Method not allowed' }, 405, cors);
+
+ try {
+ const authorization = req.headers.get('Authorization');
+ const bearer = authorization ? /^Bearer ([^\s]+)$/.exec(authorization) : null;
+ if (!authorization || !bearer) return json({ error: 'Missing bearer token' }, 401, cors);
+
+ // A rejected JWT is 401; an auth-service failure is 503 so the client
+ // retries instead of treating it as a signed-out session.
+ let authResult: unknown;
+ try {
+ authResult = await deps.createAuthClient(authorization).auth.getUser(bearer[1]);
+ } catch {
+ console.error('[WEBHOOK_ENDPOINTS] auth service error');
+ return json({ error: 'Authentication service unavailable' }, 503, cors);
+ }
+ const authError = isPlainObject(authResult) ? authResult.error : null;
+ if (authError) {
+ const status = authStatus(authError);
+ if (status === 400 || status === 401 || status === 403) {
+ return json({ error: 'Invalid bearer token' }, 401, cors);
+ }
+ console.error('[WEBHOOK_ENDPOINTS] auth service error', { status });
+ return json({ error: 'Authentication service unavailable' }, 503, cors);
+ }
+ const authData = isPlainObject(authResult) ? authResult.data : null;
+ const user = isPlainObject(authData) ? authData.user : null;
+ if (!isPlainObject(user) || typeof user.id !== 'string' || user.id.length === 0) {
+ return json({ error: 'Invalid bearer token' }, 401, cors);
+ }
+ const userId = user.id;
+
+ const read = await readBoundedRequestBody(req, REQUEST_BODY_LIMITS.webhookEndpoints);
+ if (read.kind === 'too_large') return json({ error: 'Request too large' }, 413, cors);
+ if (read.kind === 'read_failure') return json({ error: 'Request body could not be read' }, 400, cors);
+ let body: unknown;
+ try {
+ body = JSON.parse(new TextDecoder().decode(read.bytes));
+ } catch {
+ return invalid('Invalid JSON body.', cors);
+ }
+ if (!isPlainObject(body) || typeof body.action !== 'string') {
+ return invalid('action is required.', cors);
+ }
+ const action = body.action;
+ if (!['create', 'update', 'rotate_secret', 'test', 'resend_all', 'delete'].includes(action)) {
+ return invalid('Unknown action.', cors);
+ }
+
+ let endpointId = '';
+ if (action !== 'create') {
+ const parsed = parseEndpointId(body);
+ if (!parsed) return invalid('endpointId must be a UUID.', cors);
+ endpointId = parsed;
+ }
+
+ const admin = deps.createAdminClient();
+ const rate = await checkRateLimit(admin, {
+ key: 'webhook-endpoints',
+ userId,
+ ...WEBHOOK_ENDPOINTS_RATE_LIMIT,
+ }, cors);
+ if (!rate.allowed) return rate.response!;
+
+ // Before the tier gate, deliberately: someone whose plan lapsed must
+ // still be able to stop their data leaving.
+ if (action === 'delete') return await handleDelete(admin, userId, endpointId, cors);
+ if (action === 'update' && isPauseOnly(body)) {
+ return await handlePause(admin, userId, endpointId, cors);
+ }
+
+ const gate = await requireSubscription(admin, userId, DATA_SHARING_MIN_TIER, cors, deps.now());
+ if (!gate.allowed) return gate.response;
+
+ const outbound = action === 'create' || action === 'test' ||
+ (action === 'update' && (body.url !== undefined || body.status === 'active'));
+ if (outbound) {
+ const outboundRate = await checkRateLimit(admin, {
+ key: 'webhook-endpoints-outbound',
+ userId,
+ ...WEBHOOK_OUTBOUND_RATE_LIMIT,
+ }, cors);
+ if (!outboundRate.allowed) return outboundRate.response!;
+ }
+
+ if (action === 'create') return await handleCreate(deps, admin, userId, body, cors);
+ if (action === 'update') return await handleUpdate(deps, admin, userId, endpointId, body, cors);
+ if (action === 'rotate_secret') return await handleRotate(deps, admin, userId, endpointId, cors);
+
+ if (action === 'test') {
+ const loaded = await loadEndpoint(admin, userId, endpointId);
+ if (!loaded.ok) return unavailable(cors);
+ if (!loaded.endpoint) return notFound(cors);
+ const ping = await sendPing(deps, admin, userId, loaded.endpoint);
+ if (!ping.ok) return unavailable(cors);
+ return json(pingBody(ping.result), 200, cors);
+ }
+
+ // resend_all
+ const resendRate = await checkRateLimit(admin, {
+ key: 'webhook-endpoints-resend',
+ userId,
+ ...WEBHOOK_RESEND_RATE_LIMIT,
+ }, cors);
+ if (!resendRate.allowed) return resendRate.response!;
+ const loaded = await loadEndpoint(admin, userId, endpointId);
+ if (!loaded.ok) return unavailable(cors);
+ if (!loaded.endpoint) return notFound(cors);
+ if (loaded.endpoint.status !== 'active') {
+ return json({
+ error: 'endpoint_not_active',
+ message: 'Switch the endpoint on before resending.',
+ }, 409, cors);
+ }
+ const { data: enqueued, error } = await admin.rpc('enqueue_webhook_backfill', {
+ p_user_id: userId,
+ p_endpoint_id: endpointId,
+ });
+ if (error) {
+ console.error('[WEBHOOK_ENDPOINTS] backfill failed', { code: (error as { code?: string }).code });
+ return unavailable(cors);
+ }
+ return json({ enqueued: typeof enqueued === 'number' ? enqueued : 0 }, 200, cors);
+ } catch (error) {
+ // The error name only: a message could carry a URL or a header value.
+ console.error('[WEBHOOK_ENDPOINTS] unhandled error', {
+ name: error instanceof Error ? error.name : 'unknown',
+ });
+ return json({ error: 'Internal server error' }, 500, cors);
+ }
+}
+
+export function createWebhookEndpointsHandler(
+ deps: WebhookEndpointsDependencies = defaultDependencies(),
+): (req: Request) => Promise {
+ return (req) => webhookEndpointsHandler(req, deps);
+}
+
+if (import.meta.main) Deno.serve(createWebhookEndpointsHandler());
From 9f6c1a4fc521f20a943782db4252b699ff5408ff Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:28:47 -0500
Subject: [PATCH 04/11] feat(data-sharing): deliver-webhooks worker and payload
builder
The delivery half of outbound webhooks. pg_cron calls deliver-webhooks every
minute (job created inactive by 20261106120000); one pass claims due rows,
builds each payload from the current data, signs it, POSTs it and records the
outcome.
- _shared/webhookPayload.ts: the only code that reads user data for a
webhook. The root row is read with its id AND the delivery owner's user id,
so an entity that is not the owner's is "not found"; children are read under
ids from that read. Fields are the GDPR manifest's columns minus the owner
id and an explicit omit list. A missing or soft-deleted row is
`.deleted` with the id only. Loads are per cable as stored (KD-8).
- deliver-webhooks: x-cron-secret or service-role bearer, else 401. Small
batches so a pass never holds work it cannot finish; the endpoint, its
secrets and the entity are each read with the user id from the claimed row.
A scope removed after capture, an inactive endpoint or a non-shareable row
is skipped, never sent. Retries, backoff, the FLAME check and auto-disable
stay in SQL.
- Real-SQL integration test: two users' routines reach only their own
receivers, a lapsed owner's endpoint is paused instead, and a hard delete
arrives as a deleted event.
Verified by mutation: without the owner filter in the payload builder the
isolation tests fail.
Co-Authored-By: Claude Fable 5.1
---
CLAUDE.md | 10 +-
supabase/config.toml | 8 +
.../functions/_shared/webhookPayload.test.ts | 251 ++++++++
supabase/functions/_shared/webhookPayload.ts | 166 +++++
.../functions/deliver-webhooks/index.test.ts | 574 ++++++++++++++++++
supabase/functions/deliver-webhooks/index.ts | 332 ++++++++++
6 files changed, 1340 insertions(+), 1 deletion(-)
create mode 100644 supabase/functions/_shared/webhookPayload.test.ts
create mode 100644 supabase/functions/_shared/webhookPayload.ts
create mode 100644 supabase/functions/deliver-webhooks/index.test.ts
create mode 100644 supabase/functions/deliver-webhooks/index.ts
diff --git a/CLAUDE.md b/CLAUDE.md
index 3387036b..1311da5e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -194,7 +194,7 @@ a map, not a count.
- **Mobile:** mobile-sync-push, mobile-sync-pull, mobile-integration-sync
- **Account / GDPR:** delete-account, export-user-data
- **Integrations:** disconnect-integration
-- **Data sharing:** webhook-endpoints (FLAME+; the only write path for a user's outbound webhook endpoints. Reads go through owner RLS on `webhook_endpoints` / `webhook_deliveries`)
+- **Data sharing:** webhook-endpoints (FLAME+; the only write path for a user's outbound webhook endpoints. Reads go through owner RLS on `webhook_endpoints` / `webhook_deliveries`), deliver-webhooks (the delivery worker; `verify_jwt = false`, `x-cron-secret` or service role, invoked every minute by the `deliver-webhooks` pg_cron job, which is created inactive)
- **Analytics:** generate-insights
- **Rankings:** compute-rankings
@@ -241,6 +241,14 @@ before adding a table to it.
- **Signing is Standard Webhooks** (`_shared/webhookSigning.ts`): the HMAC key
is the base64-decoded bytes after `whsec_`. The reference vector in
`webhookSigning.test.ts` fails if that changes.
+- **`_shared/webhookPayload.ts` is the only code that reads user data for a
+ webhook.** The root row is read with its id AND the delivery owner's user
+ id; children are read under ids from that read. Retries, backoff, the
+ FLAME check and auto-disable live in SQL (`claim_webhook_deliveries`,
+ `complete_webhook_delivery`), not in the worker.
+- **Kill switch:** `SELECT cron.alter_job((SELECT jobid FROM cron.job WHERE
+ jobname = 'deliver-webhooks'), active := false);` stops every delivery.
+ Rows keep queueing (coalesced) and are sent when it is switched back on.
- The signing secret is returned once, by `create` and `rotate_secret`.
`delete` and a pause run before the tier gate so a lapsed user can always
stop sharing.
diff --git a/supabase/config.toml b/supabase/config.toml
index 74327696..f75c4162 100644
--- a/supabase/config.toml
+++ b/supabase/config.toml
@@ -153,3 +153,11 @@ verify_jwt = true
# Data sharing: the user's JWT is the only credential. The handler also
# calls auth.getUser() with it and scopes every query by that user id.
verify_jwt = true
+
+[functions.deliver-webhooks]
+# Auth: not a browser endpoint. pg_cron reaches it through
+# private.invoke_edge_function with no JWT (job `deliver-webhooks`). The
+# handler compares `x-cron-secret` in constant time to CRON_SECRET
+# (_shared/cronSecret.ts) or accepts the service-role bearer; anything else
+# is a 401 before any row is claimed.
+verify_jwt = false
diff --git a/supabase/functions/_shared/webhookPayload.test.ts b/supabase/functions/_shared/webhookPayload.test.ts
new file mode 100644
index 00000000..d9060a83
--- /dev/null
+++ b/supabase/functions/_shared/webhookPayload.test.ts
@@ -0,0 +1,251 @@
+import { assert, assertEquals } from "jsr:@std/assert@1";
+import type { SupabaseClient } from "jsr:@supabase/supabase-js@2";
+import { FakeDb, fakeClient, type Row } from "./testing/fakeSupabase.ts";
+import { buildWebhookEvent } from "./webhookPayload.ts";
+
+const USER_A = "aaaaaaaa-0000-4000-8000-00000000000a";
+const USER_B = "bbbbbbbb-0000-4000-8000-00000000000b";
+const ENDPOINT = "eeeeeeee-0000-4000-8000-00000000000a";
+
+function client(tables: Record) {
+ const db = new FakeDb(tables);
+ return { db, admin: fakeClient(db) as unknown as SupabaseClient };
+}
+
+function build(admin: SupabaseClient, entity: string, entityId: string, userId = USER_A) {
+ return buildWebhookEvent(admin, { userId, endpointId: ENDPOINT, entity, entityId });
+}
+
+// Two users with the same shape of data, so any missing owner filter shows up
+// as the other user's rows in the result.
+function workoutTables(): Record {
+ return {
+ workout_sessions: [
+ { id: "s-a", user_id: USER_A, name: "A session", total_volume: 1200, notes: "mine" },
+ { id: "s-b", user_id: USER_B, name: "B session", total_volume: 9999, notes: "theirs" },
+ ],
+ exercises: [
+ { id: "e-a1", session_id: "s-a", user_id: USER_A, name: "Row", order_index: 0, cable_count: 2 },
+ { id: "e-a2", session_id: "s-a", user_id: USER_A, name: "Press", order_index: 1, cable_count: null },
+ { id: "e-b1", session_id: "s-b", user_id: USER_B, name: "B exercise", order_index: 0 },
+ // A row filed under A's session but owned by B must not travel either.
+ { id: "e-x", session_id: "s-a", user_id: USER_B, name: "Planted", order_index: 9 },
+ ],
+ sets: [
+ { id: "set-a1", exercise_id: "e-a1", user_id: USER_A, set_number: 1, weight_kg: 40, actual_reps: 8 },
+ { id: "set-a2", exercise_id: "e-a2", user_id: USER_A, set_number: 1, weight_kg: 22.5, actual_reps: 10 },
+ { id: "set-b1", exercise_id: "e-b1", user_id: USER_B, set_number: 1, weight_kg: 500, actual_reps: 1 },
+ { id: "set-x", exercise_id: "e-x", user_id: USER_B, set_number: 1, weight_kg: 1, actual_reps: 1 },
+ ],
+ rep_summaries: [
+ { id: "rep-a1", set_id: "set-a1", user_id: USER_A, rep_number: 1, mean_velocity_mps: 0.5 },
+ { id: "rep-b1", set_id: "set-b1", user_id: USER_B, rep_number: 1, mean_velocity_mps: 9 },
+ ],
+ };
+}
+
+Deno.test("webhookPayload: a workout carries its own record and nested children, and nothing of another user's", async () => {
+ const { admin } = client(workoutTables());
+
+ const event = await build(admin, "workout", "s-a");
+
+ assert(event.kind === "updated");
+ assertEquals(event.type, "workout.updated");
+ assertEquals(event.data.endpointId, ENDPOINT);
+ assertEquals(event.data.entity, "workout");
+ assertEquals(event.data.id, "s-a");
+ assertEquals(event.data.record, { id: "s-a", name: "A session", total_volume: 1200, notes: "mine" });
+ const children = event.data.children as Record;
+ assertEquals(children.exercises.map((row) => row.id), ["e-a1", "e-a2"]);
+ assertEquals(children.sets.map((row) => row.id), ["set-a1", "set-a2"]);
+ assertEquals(children.rep_summaries.map((row) => row.id), ["rep-a1"]);
+ const text = JSON.stringify(event.data);
+ for (const leaked of ["B session", "theirs", "B exercise", "Planted", "set-b1", "rep-b1", USER_B]) {
+ assert(!text.includes(leaked), leaked);
+ }
+});
+
+Deno.test("webhookPayload: the owner's user id is not copied into the record or any child", async () => {
+ const { admin } = client(workoutTables());
+
+ const event = await build(admin, "workout", "s-a");
+
+ assert(event.kind === "updated");
+ assert(!JSON.stringify(event.data).includes(USER_A));
+ assertEquals("user_id" in (event.data.record as Row), false);
+});
+
+Deno.test("webhookPayload: loads are sent per cable exactly as stored", async () => {
+ const { admin } = client(workoutTables());
+
+ const event = await build(admin, "workout", "s-a");
+
+ assert(event.kind === "updated");
+ assertEquals(event.data.loadConvention, "per_cable_kg");
+ const sets = (event.data.children as Record).sets;
+ assertEquals(sets.map((row) => row.weight_kg), [40, 22.5]);
+ // cable_count is passed through, NULL included: unknown is never assumed to be two.
+ const exercises = (event.data.children as Record).exercises;
+ assertEquals(exercises.map((row) => row.cable_count), [2, null]);
+});
+
+Deno.test("webhookPayload: another user's entity id reads as not found, never as their data", async () => {
+ const { admin } = client(workoutTables());
+
+ const event = await build(admin, "workout", "s-b", USER_A);
+
+ assertEquals(event, {
+ kind: "deleted",
+ type: "workout.deleted",
+ data: { endpointId: ENDPOINT, entity: "workout", id: "s-b" },
+ });
+});
+
+Deno.test("webhookPayload: a row that is gone is a deleted event carrying the id only", async () => {
+ const { admin } = client({ routines: [], routine_exercises: [] });
+
+ const event = await build(admin, "routine", "r-gone");
+
+ assertEquals(event, {
+ kind: "deleted",
+ type: "routine.deleted",
+ data: { endpointId: ENDPOINT, entity: "routine", id: "r-gone" },
+ });
+});
+
+Deno.test("webhookPayload: a soft-deleted personal record is a deleted event without its values", async () => {
+ const { admin } = client({
+ personal_records: [
+ { id: "pr-1", user_id: USER_A, exercise_name: "Row", value: 100, deleted_at: "2026-11-01T00:00:00Z" },
+ { id: "pr-2", user_id: USER_A, exercise_name: "Press", value: 60, deleted_at: null, record_type: "MAX_WEIGHT" },
+ ],
+ });
+
+ const deleted = await build(admin, "personal_record", "pr-1");
+ const live = await build(admin, "personal_record", "pr-2");
+
+ assertEquals(deleted.kind, "deleted");
+ assert(!JSON.stringify(deleted).includes("100"));
+ assert(live.kind === "updated");
+ assertEquals((live.data.record as Row).value, 60);
+ assertEquals((live.data.record as Row).record_type, "MAX_WEIGHT");
+ assertEquals("children" in live.data, false);
+});
+
+Deno.test("webhookPayload: a routine's exercises are read through the owner-checked routine", async () => {
+ const { admin } = client({
+ routines: [
+ { id: "r-a", user_id: USER_A, name: "Push" },
+ { id: "r-b", user_id: USER_B, name: "Theirs" },
+ ],
+ routine_exercises: [
+ { id: "re-a", routine_id: "r-a", name: "Press", sets: 3 },
+ { id: "re-b", routine_id: "r-b", name: "Their press", sets: 9 },
+ ],
+ });
+
+ const mine = await build(admin, "routine", "r-a");
+ const theirs = await build(admin, "routine", "r-b");
+
+ assert(mine.kind === "updated");
+ assertEquals((mine.data.children as Record).routine_exercises.map((row) => row.id), ["re-a"]);
+ assertEquals(theirs.kind, "deleted");
+ assert(!JSON.stringify(theirs).includes("Their press"));
+});
+
+Deno.test("webhookPayload: a Strava-sourced activity is never built", async () => {
+ const { admin } = client({
+ external_activities: [
+ { id: "x-strava", user_id: USER_A, provider: "strava", name: "Ride", raw_data: { secret: 1 } },
+ { id: "x-hevy", user_id: USER_A, provider: "hevy", name: "Lift" },
+ ],
+ });
+
+ const strava = await build(admin, "external_activity", "x-strava");
+ const hevy = await build(admin, "external_activity", "x-hevy");
+
+ assertEquals(strava, { kind: "skip", reason: "not_shareable" });
+ assert(hevy.kind === "updated");
+ assertEquals((hevy.data.record as Row).name, "Lift");
+});
+
+Deno.test("webhookPayload: a profile omits billing and internal columns even when the database returns them", async () => {
+ const { admin } = client({
+ profiles: [{
+ id: USER_A,
+ user_id: USER_A,
+ display_name: "Ada",
+ weight_unit: "kg",
+ stripe_customer_id: "ctm_billing_identifier",
+ feature_flags: { beta: true },
+ digest_last_sent_at: "2026-11-01T00:00:00Z",
+ // Not in the manifest at all: must not travel either.
+ internal_note: "do not share",
+ }],
+ });
+
+ const event = await build(admin, "profile", USER_A);
+
+ assert(event.kind === "updated");
+ const record = event.data.record as Row;
+ assertEquals(record.display_name, "Ada");
+ assertEquals(record.weight_unit, "kg");
+ for (const column of ["stripe_customer_id", "feature_flags", "digest_last_sent_at", "internal_note", "user_id"]) {
+ assertEquals(column in record, false, column);
+ }
+ assert(!JSON.stringify(event).includes("ctm_billing_identifier"));
+});
+
+Deno.test("webhookPayload: an unknown entity is skipped without a read", async () => {
+ const { admin, db } = client({});
+
+ for (const entity of ["ping", "subscription", "rep_telemetry", "vbt_assessment"]) {
+ assertEquals(await build(admin, entity, "x"), { kind: "skip", reason: "unknown_entity" }, entity);
+ }
+ assertEquals(Object.keys(db.tables), []);
+});
+
+Deno.test("webhookPayload: more children than one page are all returned", async () => {
+ const sets: Row[] = [];
+ for (let i = 0; i < 1050; i += 1) {
+ sets.push({
+ // UUID-shaped, as real ids are (the double orders date-like strings as dates).
+ id: `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`,
+ exercise_id: "e-1",
+ user_id: USER_A,
+ set_number: i,
+ weight_kg: 10,
+ });
+ }
+ const { admin } = client({
+ workout_sessions: [{ id: "s-1", user_id: USER_A, name: "Long" }],
+ exercises: [{ id: "e-1", session_id: "s-1", user_id: USER_A, name: "Row" }],
+ sets,
+ rep_summaries: [],
+ });
+
+ const event = await build(admin, "workout", "s-1");
+
+ assert(event.kind === "updated");
+ const built = (event.data.children as Record).sets;
+ assertEquals(built.length, 1050);
+ assertEquals(new Set(built.map((row) => row.id)).size, 1050);
+});
+
+Deno.test("webhookPayload: a read error is reported as an error, not as a deletion", async () => {
+ const failing = {
+ from: () => ({
+ select: () => ({
+ eq: () => ({
+ eq: () => ({
+ maybeSingle: () => Promise.resolve({ data: null, error: { message: "boom" } }),
+ }),
+ }),
+ }),
+ }),
+ } as unknown as SupabaseClient;
+
+ const event = await build(failing, "routine", "r-1");
+
+ assertEquals(event, { kind: "error" });
+});
diff --git a/supabase/functions/_shared/webhookPayload.ts b/supabase/functions/_shared/webhookPayload.ts
new file mode 100644
index 00000000..a706bbee
--- /dev/null
+++ b/supabase/functions/_shared/webhookPayload.ts
@@ -0,0 +1,166 @@
+/**
+ * Builds the event for one data-sharing delivery from the CURRENT rows.
+ *
+ * This is the only place user data is read for a webhook. Isolation (FP-1)
+ * rests on one rule, kept here and nowhere else: the root row is read with
+ * both its id AND the delivery owner's user id, so an entity that is not the
+ * owner's is simply "not found". Children are then read under ids that came
+ * out of that owner-checked read (and, where the child table carries one,
+ * its own user id as well).
+ *
+ * A delivery row is a thin reference, so there is no stored payload to go
+ * stale: a row that exists is `.updated` with its current state, and
+ * a row that is gone or soft-deleted is `.deleted` with the id only.
+ *
+ * Fields are the GDPR export's column lists (userDataManifest.ts), minus the
+ * owner's user id and anything in DATA_SHARING_OMITTED_COLUMNS. The manifest
+ * test that forbids credential-like column names therefore covers payloads.
+ * Loads are sent per cable, exactly as stored (KD-8): nothing is doubled.
+ */
+import type { SupabaseClient } from 'jsr:@supabase/supabase-js@2';
+import {
+ DATA_SHARING_OMITTED_COLUMNS,
+ type DataSharingEntity,
+ getDataSharingEntity,
+} from './dataSharingScopes.ts';
+import { getUserDataTable } from './userDataManifest.ts';
+
+type Row = Record;
+
+/** Rows fetched per request; PostgREST caps a response at 1,000 by default. */
+const PAGE_SIZE = 1000;
+/** Ids per `in` filter, to keep the request URL bounded. */
+const IN_CHUNK = 150;
+/** A child table larger than this for one entity is not a webhook payload. */
+const MAX_CHILD_ROWS = 20_000;
+
+export type WebhookEvent =
+ | { kind: 'updated'; type: string; data: Row }
+ | { kind: 'deleted'; type: string; data: Row }
+ | { kind: 'skip'; reason: 'unknown_entity' | 'not_shareable' | 'payload_too_large' }
+ | { kind: 'error' };
+
+interface TableShape {
+ /** Columns to select: everything shareable plus what the checks need. */
+ select: string[];
+ /** Columns that reach the payload. */
+ shared: string[];
+ /** The table carries the owner's id in `user_id`. */
+ hasUserId: boolean;
+}
+
+function tableShape(table: string, alsoSelect: readonly string[] = []): TableShape | null {
+ const manifest = getUserDataTable(table);
+ if (!manifest) return null;
+ const omitted = new Set(['user_id', ...(DATA_SHARING_OMITTED_COLUMNS[table] ?? [])]);
+ const shared = manifest.columns.filter((column) => !omitted.has(column));
+ const select = [...new Set([...shared, ...alsoSelect])];
+ return { select, shared, hasUserId: manifest.columns.includes('user_id') };
+}
+
+function project(row: Row, columns: readonly string[]): Row {
+ const out: Row = {};
+ for (const column of columns) {
+ if (column in row) out[column] = row[column];
+ }
+ return out;
+}
+
+/** Every child row under `parentIds`, keyset-paged by id. */
+async function readChildren(
+ admin: SupabaseClient,
+ userId: string,
+ table: string,
+ fkColumn: string,
+ parentIds: readonly string[],
+ shape: TableShape,
+): Promise<{ ok: true; rows: Row[] } | { ok: false; reason: 'error' | 'too_large' }> {
+ const rows: Row[] = [];
+ const select = [...new Set([...shape.select, 'id', fkColumn])].join(', ');
+ for (let start = 0; start < parentIds.length; start += IN_CHUNK) {
+ const chunk = parentIds.slice(start, start + IN_CHUNK);
+ let after: string | null = null;
+ while (true) {
+ let query = admin.from(table).select(select).in(fkColumn, chunk);
+ // Belt and braces: the parents are already the owner's, and where the
+ // child has its own owner column that must match too.
+ if (shape.hasUserId) query = query.eq('user_id', userId);
+ if (after !== null) query = query.gt('id', after);
+ const { data, error } = await query.order('id', { ascending: true }).limit(PAGE_SIZE);
+ if (error) return { ok: false, reason: 'error' };
+ const page = (data ?? []) as unknown as Row[];
+ rows.push(...page);
+ if (rows.length > MAX_CHILD_ROWS) return { ok: false, reason: 'too_large' };
+ if (page.length < PAGE_SIZE) break;
+ after = String(page[page.length - 1].id);
+ }
+ }
+ return { ok: true, rows };
+}
+
+export async function buildWebhookEvent(
+ admin: SupabaseClient,
+ params: { userId: string; endpointId: string; entity: string; entityId: string },
+): Promise {
+ const definition: DataSharingEntity | undefined = getDataSharingEntity(params.entity);
+ if (!definition) return { kind: 'skip', reason: 'unknown_entity' };
+
+ const needed = [
+ definition.idColumn,
+ ...(definition.softDeleteColumn ? [definition.softDeleteColumn] : []),
+ ...(definition.exclude ? [definition.exclude.column] : []),
+ ];
+ const rootShape = tableShape(definition.table, needed);
+ if (!rootShape) return { kind: 'skip', reason: 'unknown_entity' };
+
+ const base = { endpointId: params.endpointId, entity: definition.entity, id: params.entityId };
+
+ const { data, error } = await admin
+ .from(definition.table)
+ .select(rootShape.select.join(', '))
+ .eq(definition.idColumn, params.entityId)
+ // The owner filter. Without it this function would read anyone's row.
+ .eq(definition.userColumn, params.userId)
+ .maybeSingle();
+ if (error) return { kind: 'error' };
+
+ const root = data as unknown as Row | null;
+ if (!root) return { kind: 'deleted', type: `${definition.entity}.deleted`, data: base };
+ if (definition.exclude && root[definition.exclude.column] === definition.exclude.equals) {
+ return { kind: 'skip', reason: 'not_shareable' };
+ }
+ if (definition.softDeleteColumn && root[definition.softDeleteColumn] != null) {
+ return { kind: 'deleted', type: `${definition.entity}.deleted`, data: base };
+ }
+
+ const children: Record = {};
+ const idsByTable = new Map([[definition.table, [params.entityId]]]);
+ for (const child of definition.children) {
+ const shape = tableShape(child.table);
+ if (!shape) return { kind: 'skip', reason: 'unknown_entity' };
+ const parentIds = idsByTable.get(child.parent) ?? [];
+ if (parentIds.length === 0) {
+ children[child.table] = [];
+ idsByTable.set(child.table, []);
+ continue;
+ }
+ const read = await readChildren(admin, params.userId, child.table, child.fkColumn, parentIds, shape);
+ if (!read.ok) {
+ return read.reason === 'too_large' ? { kind: 'skip', reason: 'payload_too_large' } : { kind: 'error' };
+ }
+ idsByTable.set(child.table, read.rows.map((row) => String(row.id)));
+ children[child.table] = read.rows.map((row) => project(row, shape.shared));
+ }
+
+ return {
+ kind: 'updated',
+ type: `${definition.entity}.updated`,
+ data: {
+ ...base,
+ // Every weight and volume is per cable, as the phone shows it.
+ loadConvention: 'per_cable_kg',
+ record: project(root, rootShape.shared),
+ ...(definition.children.length > 0 ? { children } : {}),
+ },
+ };
+}
diff --git a/supabase/functions/deliver-webhooks/index.test.ts b/supabase/functions/deliver-webhooks/index.test.ts
new file mode 100644
index 00000000..2e187e61
--- /dev/null
+++ b/supabase/functions/deliver-webhooks/index.test.ts
@@ -0,0 +1,574 @@
+import { assert, assertEquals } from "jsr:@std/assert@1";
+import { createClient, type SupabaseClient } from "jsr:@supabase/supabase-js@2";
+import { localIntegrationEnvironment } from "../_shared/localIntegrationEnvironment.ts";
+import { FakeDb, fakeClient, type Row } from "../_shared/testing/fakeSupabase.ts";
+import { assertNoSecretsLogged, captureLogs } from "../_shared/testLogCapture.ts";
+import { signWebhook } from "../_shared/webhookSigning.ts";
+import type { DnsResolver } from "../_shared/webhookTarget.ts";
+import { createDeliverWebhooksHandler, type DeliverWebhooksDependencies } from "./index.ts";
+
+const USER_A = "aaaaaaaa-0000-4000-8000-00000000000a";
+const USER_B = "bbbbbbbb-0000-4000-8000-00000000000b";
+const ENDPOINT_A = "eeeeeeee-0000-4000-8000-00000000000a";
+const ENDPOINT_B = "eeeeeeee-0000-4000-8000-00000000000b";
+const SECRET_A = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
+const SECRET_B = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD";
+const HEADER_VALUE = "Bearer receiver-credential-123";
+const CRON_SECRET = "cron-secret-for-tests";
+const SERVICE_KEY = "service-role-key-for-tests";
+const NOW = new Date("2026-11-06T12:00:00.000Z");
+
+const encrypt = (plain: string) => `enc:test:${btoa(plain)}`;
+const decrypt = (stored: string) => Promise.resolve(atob(stored.replace("enc:test:", "")));
+
+function endpoint(id: string, userId: string, host: string, overrides: Row = {}): Row {
+ return {
+ id,
+ user_id: userId,
+ url: `https://${host}/in`,
+ scopes: ["routines", "workouts"],
+ status: "active",
+ custom_header_name: null,
+ ...overrides,
+ };
+}
+
+function secrets(endpointId: string, userId: string, secret: string, overrides: Row = {}): Row {
+ return {
+ endpoint_id: endpointId,
+ user_id: userId,
+ signing_secret_enc: encrypt(secret),
+ previous_signing_secret_enc: null,
+ previous_expires_at: null,
+ custom_header_value_enc: null,
+ ...overrides,
+ };
+}
+
+function claimed(id: string, endpointId: string, userId: string, entity: string, entityId: string, attempt = 1): Row {
+ return {
+ delivery_id: id,
+ delivery_endpoint_id: endpointId,
+ delivery_user_id: userId,
+ delivery_entity: entity,
+ delivery_entity_id: entityId,
+ delivery_attempt: attempt,
+ };
+}
+
+interface Outbound {
+ url: string;
+ headers: Record;
+ body: string;
+}
+
+function baseTables(): Record {
+ return {
+ webhook_endpoints: [
+ endpoint(ENDPOINT_A, USER_A, "a.example.com"),
+ endpoint(ENDPOINT_B, USER_B, "b.example.com"),
+ ],
+ webhook_endpoint_secrets: [
+ secrets(ENDPOINT_A, USER_A, SECRET_A),
+ secrets(ENDPOINT_B, USER_B, SECRET_B),
+ ],
+ routines: [
+ { id: "r-a", user_id: USER_A, name: "A routine" },
+ { id: "r-b", user_id: USER_B, name: "B routine" },
+ ],
+ routine_exercises: [
+ { id: "re-a", routine_id: "r-a", name: "A press" },
+ { id: "re-b", routine_id: "r-b", name: "B press" },
+ ],
+ };
+}
+
+function harness(options: {
+ tables?: Record;
+ batches?: Row[][];
+ status?: (url: string) => number;
+ claimError?: boolean;
+ completeResult?: (args: Row) => unknown;
+} = {}) {
+ const db = new FakeDb(options.tables ?? baseTables());
+ const batches = [...(options.batches ?? [])];
+ const completions: Row[] = [];
+ db.rpcHandlers.claim_webhook_deliveries = () => {
+ if (options.claimError) return { data: null, error: { code: "XX000", message: "claim exploded" } };
+ return { data: batches.shift() ?? [], error: null };
+ };
+ db.rpcHandlers.complete_webhook_delivery = (args) => {
+ completions.push(args);
+ const result = options.completeResult ? options.completeResult(args) : args.p_outcome;
+ return { data: result, error: null };
+ };
+ const outbound: Outbound[] = [];
+ const resolveDns: DnsResolver = (_hostname, recordType) =>
+ Promise.resolve(recordType === "A" ? ["93.184.216.34"] : []);
+ const deps: DeliverWebhooksDependencies = {
+ createAdminClient: () => fakeClient(db, null, () => NOW) as unknown as SupabaseClient,
+ fetch: ((input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ outbound.push({ url, headers: (init?.headers ?? {}) as Record, body: String(init?.body) });
+ return Promise.resolve(new Response(null, { status: options.status?.(url) ?? 200 }));
+ }) as typeof fetch,
+ resolveDns,
+ env: (name) =>
+ ({
+ CRON_SECRET,
+ SUPABASE_SERVICE_ROLE_KEY: SERVICE_KEY,
+ SUPABASE_URL: "https://abcdefghijklmnopqrst.supabase.co",
+ } as Record)[name],
+ now: () => NOW,
+ decrypt,
+ };
+ const handler = createDeliverWebhooksHandler(deps);
+ const run = (headers: Record = { "x-cron-secret": CRON_SECRET }, method = "POST") =>
+ handler(new Request("http://localhost/functions/v1/deliver-webhooks", { method, headers, body: method === "POST" ? "{}" : undefined }));
+ return { db, run, outbound, completions };
+}
+
+Deno.test("deliver-webhooks: a caller without the cron secret or the service-role key is refused", async () => {
+ const { run, db } = harness({ batches: [[claimed("d-1", ENDPOINT_A, USER_A, "routine", "r-a")]] });
+
+ for (const headers of [
+ {},
+ { "x-cron-secret": "wrong" },
+ { Authorization: "Bearer some-user-jwt" },
+ { Authorization: `Bearer ${SERVICE_KEY}x` },
+ ] as Record[]) {
+ assertEquals((await run(headers)).status, 401, JSON.stringify(headers));
+ }
+ assertEquals((await run({ "x-cron-secret": CRON_SECRET }, "GET")).status, 405);
+ assertEquals(db.rpcCallNames(), []);
+});
+
+Deno.test("deliver-webhooks: the service-role bearer is accepted as well as the cron secret", async () => {
+ const { run } = harness();
+
+ assertEquals((await run({ Authorization: `Bearer ${SERVICE_KEY}` })).status, 200);
+ assertEquals((await run({ "x-cron-secret": CRON_SECRET })).status, 200);
+});
+
+Deno.test("deliver-webhooks: each endpoint receives only its own owner's data, signed with its own secret", async () => {
+ // Arrange: one change for each of two users, claimed in the same batch.
+ const { run, outbound, completions } = harness({
+ batches: [[
+ claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a"),
+ claimed("d-b", ENDPOINT_B, USER_B, "routine", "r-b"),
+ ]],
+ });
+
+ // Act
+ const response = await run();
+
+ // Assert
+ assertEquals(response.status, 200);
+ assertEquals(await response.json(), { claimed: 2, delivered: 2, failed: 0, gone: 0, skipped: 0, lost: 0 });
+ assertEquals(outbound.length, 2);
+ const toA = outbound.find((call) => call.url === "https://a.example.com/in")!;
+ const toB = outbound.find((call) => call.url === "https://b.example.com/in")!;
+ const bodyA = JSON.parse(toA.body);
+ const bodyB = JSON.parse(toB.body);
+ assertEquals(bodyA.type, "routine.updated");
+ assertEquals(bodyA.data.record.name, "A routine");
+ assertEquals(bodyA.data.children.routine_exercises.map((row: Row) => row.name), ["A press"]);
+ assertEquals(bodyB.data.record.name, "B routine");
+ assert(!toA.body.includes("B routine") && !toA.body.includes("B press") && !toA.body.includes(USER_B));
+ assert(!toB.body.includes("A routine") && !toB.body.includes("A press") && !toB.body.includes(USER_A));
+ const timestamp = Math.floor(NOW.getTime() / 1000);
+ assertEquals(toA.headers["webhook-id"], "d-a");
+ assertEquals(toA.headers["webhook-signature"], await signWebhook(SECRET_A, "d-a", timestamp, toA.body));
+ assertEquals(toB.headers["webhook-signature"], await signWebhook(SECRET_B, "d-b", timestamp, toB.body));
+ assertEquals(
+ completions.map((args) => [args.p_delivery_id, args.p_attempt, args.p_outcome, args.p_event_type, args.p_status_code]).sort(),
+ [["d-a", 1, "delivered", "routine.updated", 200], ["d-b", 1, "delivered", "routine.updated", 200]],
+ );
+});
+
+Deno.test("deliver-webhooks: a delivery whose user id is not the endpoint owner's sends nothing", async () => {
+ // A row that names A's endpoint but B's user id cannot exist (composite FK);
+ // if one ever did, the endpoint read is scoped by both and finds nothing.
+ const { run, outbound, completions } = harness({
+ batches: [[claimed("d-x", ENDPOINT_A, USER_B, "routine", "r-b")]],
+ });
+
+ await run();
+
+ assertEquals(outbound.length, 0);
+ assertEquals([completions[0].p_outcome, completions[0].p_error_code], ["skipped", "endpoint_inactive"]);
+});
+
+Deno.test("deliver-webhooks: a deleted entity is sent as a deleted event with the id only", async () => {
+ const { run, outbound, completions } = harness({
+ batches: [[claimed("d-gone", ENDPOINT_A, USER_A, "routine", "r-gone")]],
+ });
+
+ await run();
+
+ assertEquals(JSON.parse(outbound[0].body).type, "routine.deleted");
+ assertEquals(JSON.parse(outbound[0].body).data, {
+ apiVersion: "2026-11-01",
+ endpointId: ENDPOINT_A,
+ entity: "routine",
+ id: "r-gone",
+ });
+ assertEquals(completions[0].p_event_type, "routine.deleted");
+});
+
+Deno.test("deliver-webhooks: a receiver failure is recorded with its status, and 410 as gone", async () => {
+ const { run, completions } = harness({
+ batches: [[
+ claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a", 3),
+ claimed("d-b", ENDPOINT_B, USER_B, "routine", "r-b"),
+ ]],
+ status: (url) => (url.includes("a.example.com") ? 503 : 410),
+ });
+
+ const response = await run();
+
+ assertEquals(await response.json(), { claimed: 2, delivered: 0, failed: 1, gone: 1, skipped: 0, lost: 0 });
+ const a = completions.find((args) => args.p_delivery_id === "d-a")!;
+ const b = completions.find((args) => args.p_delivery_id === "d-b")!;
+ assertEquals([a.p_attempt, a.p_outcome, a.p_status_code, a.p_error_code], [3, "failed", 503, "http_error"]);
+ assertEquals([b.p_outcome, b.p_status_code], ["gone", 410]);
+});
+
+Deno.test("deliver-webhooks: a scope removed after capture is not delivered", async () => {
+ const tables = baseTables();
+ tables.webhook_endpoints[0].scopes = ["workouts"];
+ const { run, outbound, completions } = harness({
+ tables,
+ batches: [[claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a")]],
+ });
+
+ await run();
+
+ assertEquals(outbound.length, 0);
+ assertEquals([completions[0].p_outcome, completions[0].p_error_code], ["skipped", "scope_removed"]);
+});
+
+Deno.test("deliver-webhooks: a paused, disabled or deleted endpoint is not delivered to", async () => {
+ for (const mutate of [
+ (rows: Row[]) => { rows[0].status = "paused"; },
+ (rows: Row[]) => { rows[0].status = "disabled"; },
+ (rows: Row[]) => { rows.splice(0, 1); },
+ ]) {
+ const tables = baseTables();
+ mutate(tables.webhook_endpoints);
+ const { run, outbound, completions } = harness({
+ tables,
+ batches: [[claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a")]],
+ });
+
+ await run();
+
+ assertEquals(outbound.length, 0);
+ assertEquals([completions[0].p_outcome, completions[0].p_error_code], ["skipped", "endpoint_inactive"]);
+ }
+});
+
+Deno.test("deliver-webhooks: an entity that may not be shared is skipped, never sent", async () => {
+ const tables = baseTables();
+ tables.webhook_endpoints[0].scopes = ["external_activities"];
+ tables.external_activities = [{ id: "x-1", user_id: USER_A, provider: "strava", name: "Ride" }];
+ const { run, outbound, completions } = harness({
+ tables,
+ batches: [[
+ claimed("d-1", ENDPOINT_A, USER_A, "external_activity", "x-1"),
+ claimed("d-2", ENDPOINT_A, USER_A, "vbt_assessment", "v-1"),
+ ]],
+ });
+
+ await run();
+
+ assertEquals(outbound.length, 0);
+ assertEquals(
+ completions.map((args) => [args.p_delivery_id, args.p_outcome, args.p_error_code]).sort(),
+ [["d-1", "skipped", "not_shareable"], ["d-2", "skipped", "unknown_entity"]],
+ );
+});
+
+Deno.test("deliver-webhooks: missing secrets fail the attempt as ours and send nothing unsigned", async () => {
+ const tables = baseTables();
+ tables.webhook_endpoint_secrets = [];
+ const { run, outbound, completions } = harness({
+ tables,
+ batches: [[claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a")]],
+ });
+
+ await run();
+
+ assertEquals(outbound.length, 0);
+ assertEquals([completions[0].p_outcome, completions[0].p_error_code], ["failed", "internal_error"]);
+});
+
+Deno.test("deliver-webhooks: the custom header and a live previous secret are applied; an expired one is not", async () => {
+ const tables = baseTables();
+ tables.webhook_endpoints[0].custom_header_name = "Authorization";
+ tables.webhook_endpoint_secrets[0] = secrets(ENDPOINT_A, USER_A, SECRET_A, {
+ custom_header_value_enc: encrypt(HEADER_VALUE),
+ previous_signing_secret_enc: encrypt(SECRET_B),
+ previous_expires_at: "2026-11-07T00:00:00.000Z",
+ });
+ tables.webhook_endpoint_secrets[1] = secrets(ENDPOINT_B, USER_B, SECRET_B, {
+ previous_signing_secret_enc: encrypt(SECRET_A),
+ previous_expires_at: "2026-11-05T00:00:00.000Z",
+ });
+ const { run, outbound } = harness({
+ tables,
+ batches: [[
+ claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a"),
+ claimed("d-b", ENDPOINT_B, USER_B, "routine", "r-b"),
+ ]],
+ });
+
+ await run();
+
+ const toA = outbound.find((call) => call.url.includes("a.example.com"))!;
+ const toB = outbound.find((call) => call.url.includes("b.example.com"))!;
+ assertEquals(toA.headers.Authorization, HEADER_VALUE);
+ assertEquals(toA.headers["webhook-signature"].split(" ").length, 2);
+ assertEquals("Authorization" in toB.headers, false);
+ assertEquals(toB.headers["webhook-signature"].split(" ").length, 1);
+});
+
+Deno.test("deliver-webhooks: batches are claimed until the queue is empty", async () => {
+ const { run, db, outbound } = harness({
+ batches: [
+ [claimed("d-1", ENDPOINT_A, USER_A, "routine", "r-a")],
+ [claimed("d-2", ENDPOINT_B, USER_B, "routine", "r-b")],
+ ],
+ });
+
+ const response = await run();
+
+ assertEquals((await response.json()).claimed, 2);
+ assertEquals(outbound.length, 2);
+ // Two batches with work, then the empty one that ends the pass.
+ assertEquals(db.rpcCallNames().filter((name) => name === "claim_webhook_deliveries").length, 3);
+});
+
+Deno.test("deliver-webhooks: a claim that was lost to another worker is counted as lost, not delivered", async () => {
+ const { run } = harness({
+ batches: [[claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a")]],
+ completeResult: () => null,
+ });
+
+ const response = await run();
+
+ assertEquals(await response.json(), { claimed: 1, delivered: 0, failed: 0, gone: 0, skipped: 0, lost: 1 });
+});
+
+Deno.test("deliver-webhooks: a claim error is a 503 and nothing is sent", async () => {
+ const { run, outbound } = harness({ claimError: true });
+
+ const response = await run();
+
+ assertEquals(response.status, 503);
+ assertEquals(outbound.length, 0);
+});
+
+Deno.test("deliver-webhooks: no secret, header value, URL or payload is logged", async () => {
+ const tables = baseTables();
+ tables.webhook_endpoints[0].custom_header_name = "Authorization";
+ tables.webhook_endpoints[0].url = "https://a.example.com/in/private-path-token";
+ tables.webhook_endpoint_secrets[0] = secrets(ENDPOINT_A, USER_A, SECRET_A, {
+ custom_header_value_enc: encrypt(HEADER_VALUE),
+ });
+ tables.webhook_endpoint_secrets.splice(1, 1);
+ const { run } = harness({
+ tables,
+ batches: [[
+ claimed("d-a", ENDPOINT_A, USER_A, "routine", "r-a"),
+ claimed("d-b", ENDPOINT_B, USER_B, "routine", "r-b"),
+ ]],
+ status: () => 500,
+ });
+
+ const { logs } = await captureLogs(() => run());
+
+ assertNoSecretsLogged(logs, [
+ SECRET_A,
+ SECRET_B,
+ HEADER_VALUE,
+ "private-path-token",
+ "A routine",
+ CRON_SECRET,
+ SERVICE_KEY,
+ ]);
+});
+
+// ---------------------------------------------------------------------------
+// Real SQL (local stack only): the triggers, the claim and the worker together.
+// ---------------------------------------------------------------------------
+
+Deno.test({
+ name: "integration: two users' changes reach only their own endpoints, and a lapsed owner's endpoint is paused instead",
+ ignore: localIntegrationEnvironment === null,
+ sanitizeOps: false,
+ sanitizeResources: false,
+ async fn() {
+ assert(localIntegrationEnvironment);
+ const admin = createClient(
+ localIntegrationEnvironment.url,
+ localIntegrationEnvironment.serviceRoleKey,
+ { auth: { persistSession: false, autoRefreshToken: false } },
+ );
+ const run = crypto.randomUUID().slice(0, 8);
+ const userIds: string[] = [];
+ const createUser = async (label: string) => {
+ const created = await admin.auth.admin.createUser({
+ email: `webhook-${label}-${crypto.randomUUID()}@example.invalid`,
+ password: `pw-${crypto.randomUUID()}`,
+ email_confirm: true,
+ });
+ if (created.error || !created.data.user) throw new Error("auth fixture failed");
+ userIds.push(created.data.user.id);
+ return created.data.user.id;
+ };
+
+ try {
+ // Arrange: A and B are FLAME, C has no subscription.
+ const userA = await createUser("a");
+ const userB = await createUser("b");
+ const userC = await createUser("c");
+ for (const userId of [userA, userB]) {
+ const subscription = await admin.from("subscriptions").upsert({
+ user_id: userId,
+ tier: "FLAME",
+ status: "active",
+ current_period_end: new Date(Date.now() + 30 * 86_400_000).toISOString(),
+ }, { onConflict: "user_id" });
+ if (subscription.error) throw new Error(`subscription seed failed: ${JSON.stringify(subscription.error)}`);
+ }
+ const hosts: Record = {
+ [userA]: `a-${run}.example.com`,
+ [userB]: `b-${run}.example.com`,
+ [userC]: `c-${run}.example.com`,
+ };
+ const endpointIds: Record = {};
+ for (const userId of [userA, userB, userC]) {
+ const created = await admin.rpc("create_webhook_endpoint", {
+ p_user_id: userId,
+ p_label: "integration",
+ p_url: `https://${hosts[userId]}/in`,
+ p_scopes: ["routines"],
+ p_signing_secret_enc: encrypt(userId === userB ? SECRET_B : SECRET_A),
+ p_signing_key_hint: "test",
+ });
+ if (created.error) throw new Error(`endpoint seed failed: ${JSON.stringify(created.error)}`);
+ endpointIds[userId] = created.data as string;
+ }
+
+ // Act 1: each user's routine is written; the capture trigger enqueues it.
+ const routineIds: Record = {};
+ for (const userId of [userA, userB, userC]) {
+ const routine = await admin.from("routines")
+ .insert({ user_id: userId, name: `routine of ${userId}` })
+ .select("id")
+ .single();
+ if (routine.error) throw new Error(`routine seed failed: ${JSON.stringify(routine.error)}`);
+ routineIds[userId] = routine.data.id as string;
+ }
+ const due = await admin.from("webhook_deliveries")
+ .update({ next_attempt_at: new Date(Date.now() - 1000).toISOString() })
+ .in("user_id", [userA, userB, userC])
+ .eq("status", "pending");
+ assertEquals(due.error, null);
+
+ // Act 2: one worker pass against the real claim and completion RPCs.
+ const outbound: Outbound[] = [];
+ const handler = createDeliverWebhooksHandler({
+ createAdminClient: () => admin,
+ fetch: ((input: string | URL | Request, init?: RequestInit) => {
+ outbound.push({
+ url: String(input),
+ headers: (init?.headers ?? {}) as Record,
+ body: String(init?.body),
+ });
+ return Promise.resolve(new Response(null, { status: 200 }));
+ }) as typeof fetch,
+ resolveDns: (_hostname, recordType) => Promise.resolve(recordType === "A" ? ["93.184.216.34"] : []),
+ env: (name) => ({ CRON_SECRET } as Record)[name],
+ now: () => new Date(),
+ decrypt,
+ });
+ const response = await handler(
+ new Request("http://localhost/functions/v1/deliver-webhooks", {
+ method: "POST",
+ headers: { "x-cron-secret": CRON_SECRET },
+ body: "{}",
+ }),
+ );
+ assertEquals(response.status, 200);
+
+ // Assert: A's and B's receivers each got exactly their own routine.
+ const mine = outbound.filter((call) => Object.values(hosts).some((host) => call.url.includes(host)));
+ const toA = mine.filter((call) => call.url.includes(hosts[userA]));
+ const toB = mine.filter((call) => call.url.includes(hosts[userB]));
+ const toC = mine.filter((call) => call.url.includes(hosts[userC]));
+ assertEquals(toA.length, 1);
+ assertEquals(toB.length, 1);
+ assertEquals(JSON.parse(toA[0].body).data.id, routineIds[userA]);
+ assertEquals(JSON.parse(toA[0].body).data.record.name, `routine of ${userA}`);
+ assertEquals(JSON.parse(toB[0].body).data.id, routineIds[userB]);
+ assert(!toA[0].body.includes(routineIds[userB]) && !toA[0].body.includes(userB));
+ assert(!toB[0].body.includes(routineIds[userA]) && !toB[0].body.includes(userA));
+ const timestamp = Number(toA[0].headers["webhook-timestamp"]);
+ assertEquals(
+ toA[0].headers["webhook-signature"],
+ await signWebhook(SECRET_A, toA[0].headers["webhook-id"], timestamp, toA[0].body),
+ );
+
+ // ...and both are recorded as delivered, with the event type resolved.
+ const delivered = await admin.from("webhook_deliveries")
+ .select("user_id, status, event_type, attempt_count, last_status_code")
+ .in("user_id", [userA, userB]);
+ assertEquals(delivered.error, null);
+ assertEquals(
+ (delivered.data ?? []).map((row) => [row.status, row.event_type, row.attempt_count, row.last_status_code]),
+ [["delivered", "routine.updated", 1, 200], ["delivered", "routine.updated", 1, 200]],
+ );
+
+ // C is below FLAME: nothing was sent, the endpoint is paused with a
+ // reason, the waiting row is closed, and a further write enqueues nothing.
+ assertEquals(toC.length, 0);
+ const endpointC = await admin.from("webhook_endpoints")
+ .select("status, disabled_reason")
+ .eq("id", endpointIds[userC])
+ .single();
+ assertEquals(endpointC.data, { status: "paused", disabled_reason: "subscription_lapsed" });
+ const rename = await admin.from("routines").update({ name: "renamed" }).eq("id", routineIds[userC]);
+ assertEquals(rename.error, null);
+ const deliveriesC = await admin.from("webhook_deliveries")
+ .select("status, last_error_code")
+ .eq("user_id", userC);
+ assertEquals(deliveriesC.data, [{ status: "skipped", last_error_code: "subscription_lapsed" }]);
+
+ // A hard delete is delivered as a deleted event with the id only.
+ const removed = await admin.from("routines").delete().eq("id", routineIds[userA]);
+ assertEquals(removed.error, null);
+ await admin.from("webhook_deliveries")
+ .update({ next_attempt_at: new Date(Date.now() - 1000).toISOString() })
+ .eq("user_id", userA)
+ .eq("status", "pending");
+ outbound.length = 0;
+ await handler(
+ new Request("http://localhost/functions/v1/deliver-webhooks", {
+ method: "POST",
+ headers: { "x-cron-secret": CRON_SECRET },
+ body: "{}",
+ }),
+ );
+ const deletion = outbound.filter((call) => call.url.includes(hosts[userA]));
+ assertEquals(deletion.length, 1);
+ assertEquals(JSON.parse(deletion[0].body).type, "routine.deleted");
+ assertEquals(JSON.parse(deletion[0].body).data.id, routineIds[userA]);
+ assertEquals("record" in JSON.parse(deletion[0].body).data, false);
+ } finally {
+ // Endpoints, secrets and deliveries cascade from the user.
+ for (const userId of userIds) await admin.auth.admin.deleteUser(userId);
+ }
+ },
+});
diff --git a/supabase/functions/deliver-webhooks/index.ts b/supabase/functions/deliver-webhooks/index.ts
new file mode 100644
index 00000000..ded17d88
--- /dev/null
+++ b/supabase/functions/deliver-webhooks/index.ts
@@ -0,0 +1,332 @@
+import { createClient, type SupabaseClient } from 'jsr:@supabase/supabase-js@2';
+import { hasValidCronSecret } from '../_shared/cronSecret.ts';
+import { getDataSharingEntity } from '../_shared/dataSharingScopes.ts';
+import { decryptOAuthSecret } from '../_shared/oauthTokenCrypto.ts';
+import { isServiceRoleBearer } from '../_shared/timingSafe.ts';
+import {
+ loadWebhookCredentials,
+ type WebhookCredentials,
+} from '../_shared/webhookCredentials.ts';
+import { buildWebhookEvent } from '../_shared/webhookPayload.ts';
+import { sendWebhook, webhookEnvelope } from '../_shared/webhookSend.ts';
+import { type DnsResolver, ownHostsFromEnv, systemDnsResolver } from '../_shared/webhookTarget.ts';
+
+/**
+ * Data sharing: the delivery worker. pg_cron calls it every minute through
+ * private.invoke_edge_function (job `deliver-webhooks`); deactivating that
+ * job stops every delivery.
+ *
+ * One pass: claim due rows -> build each payload from the current data ->
+ * sign -> POST -> record the outcome. Retries, backoff, the per-endpoint
+ * fairness cap, pausing an owner who is no longer FLAME (FP-2) and switching
+ * off an endpoint that keeps failing (FP-8) are all decided in SQL
+ * (claim_webhook_deliveries / complete_webhook_delivery), so this file cannot
+ * drift from them.
+ *
+ * Isolation (FP-1): the user id used for every read comes from the claimed
+ * delivery row, whose composite foreign key ties it to the endpoint's owner.
+ * The endpoint, its secrets and the entity are each read with that id.
+ *
+ * Auth: not a browser endpoint. `x-cron-secret` (constant-time, CRON_SECRET)
+ * or the service-role bearer; anything else is a 401.
+ */
+
+/** Rows claimed per batch. Small, so a pass never holds work it cannot finish. */
+const BATCH_SIZE = 8;
+const PER_ENDPOINT_PER_BATCH = 4;
+const CONCURRENCY = 4;
+/** Start no new batch after this: a batch can take 2 x the 10 s request timeout. */
+const BATCH_START_BUDGET_MS = 25_000;
+const MAX_DELIVERIES_PER_PASS = 200;
+const LEASE_SECONDS = 180;
+
+type Outcome = 'delivered' | 'failed' | 'gone' | 'skipped';
+
+interface ClaimedDelivery {
+ delivery_id: string;
+ delivery_endpoint_id: string;
+ delivery_user_id: string;
+ delivery_entity: string;
+ delivery_entity_id: string;
+ delivery_attempt: number;
+}
+
+interface EndpointForDelivery {
+ id: string;
+ user_id: string;
+ url: string;
+ scopes: string[];
+ status: string;
+ custom_header_name: string | null;
+}
+
+export interface DeliverWebhooksDependencies {
+ createAdminClient(): SupabaseClient;
+ fetch: typeof fetch;
+ resolveDns: DnsResolver;
+ env(name: string): string | undefined;
+ now(): Date;
+ decrypt(stored: string): Promise;
+}
+
+function defaultDependencies(): DeliverWebhooksDependencies {
+ return {
+ createAdminClient() {
+ return createClient(
+ Deno.env.get('SUPABASE_URL')!,
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
+ { auth: { persistSession: false, autoRefreshToken: false } },
+ );
+ },
+ fetch: (input, init) => fetch(input, init),
+ resolveDns: systemDnsResolver,
+ env: (name) => Deno.env.get(name),
+ now: () => new Date(),
+ decrypt: decryptOAuthSecret,
+ };
+}
+
+function json(body: unknown, status: number): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+interface PassContext {
+ deps: DeliverWebhooksDependencies;
+ admin: SupabaseClient;
+ ownHosts: string[];
+ endpoints: Map>;
+ credentials: Map>;
+}
+
+function loadEndpoint(ctx: PassContext, delivery: ClaimedDelivery) {
+ const key = delivery.delivery_endpoint_id;
+ let cached = ctx.endpoints.get(key);
+ if (!cached) {
+ cached = (async () => {
+ const { data, error } = await ctx.admin
+ .from('webhook_endpoints')
+ .select('id, user_id, url, scopes, status, custom_header_name')
+ .eq('id', delivery.delivery_endpoint_id)
+ .eq('user_id', delivery.delivery_user_id)
+ .maybeSingle();
+ if (error) return 'error' as const;
+ return (data as unknown as EndpointForDelivery | null) ?? null;
+ })();
+ ctx.endpoints.set(key, cached);
+ }
+ return cached;
+}
+
+function loadCredentials(ctx: PassContext, endpoint: EndpointForDelivery) {
+ let cached = ctx.credentials.get(endpoint.id);
+ if (!cached) {
+ cached = (async () => {
+ const result = await loadWebhookCredentials(ctx.admin, {
+ userId: endpoint.user_id,
+ endpointId: endpoint.id,
+ customHeaderName: endpoint.custom_header_name,
+ now: ctx.deps.now(),
+ }, ctx.deps.decrypt);
+ if (!result.ok) {
+ console.error('[DELIVER_WEBHOOKS] credentials unavailable', {
+ endpointId: endpoint.id,
+ reason: result.reason,
+ });
+ return null;
+ }
+ return result.credentials;
+ })();
+ ctx.credentials.set(endpoint.id, cached);
+ }
+ return cached;
+}
+
+interface Attempt {
+ outcome: Outcome;
+ eventType: string | null;
+ statusCode: number | null;
+ errorCode: string | null;
+ durationMs: number | null;
+ retryAfterSeconds: number | null;
+}
+
+const skipped = (errorCode: string): Attempt => ({
+ outcome: 'skipped',
+ eventType: null,
+ statusCode: null,
+ errorCode,
+ durationMs: null,
+ retryAfterSeconds: null,
+});
+
+const internalFailure = (): Attempt => ({
+ outcome: 'failed',
+ eventType: null,
+ statusCode: null,
+ // Ours, not the receiver's; it still retries on the same schedule.
+ errorCode: 'internal_error',
+ durationMs: null,
+ retryAfterSeconds: null,
+});
+
+async function attemptDelivery(ctx: PassContext, delivery: ClaimedDelivery): Promise {
+ const endpoint = await loadEndpoint(ctx, delivery);
+ if (endpoint === 'error') return internalFailure();
+ // Deleted, paused or disabled since the claim.
+ if (!endpoint || endpoint.status !== 'active') return skipped('endpoint_inactive');
+
+ // The scope may have been removed after the change was captured: what the
+ // user shares now decides, not what they shared then.
+ const definition = getDataSharingEntity(delivery.delivery_entity);
+ if (!definition) return skipped('unknown_entity');
+ if (!endpoint.scopes.includes(definition.scope)) return skipped('scope_removed');
+
+ const credentials = await loadCredentials(ctx, endpoint);
+ if (!credentials) return internalFailure();
+
+ const event = await buildWebhookEvent(ctx.admin, {
+ userId: delivery.delivery_user_id,
+ endpointId: endpoint.id,
+ entity: delivery.delivery_entity,
+ entityId: delivery.delivery_entity_id,
+ });
+ if (event.kind === 'error') return internalFailure();
+ if (event.kind === 'skip') return skipped(event.reason);
+
+ const result = await sendWebhook(
+ { fetch: ctx.deps.fetch, resolveDns: ctx.deps.resolveDns, ownHosts: ctx.ownHosts, now: ctx.deps.now },
+ {
+ url: endpoint.url,
+ // The same id on every retry, so the receiver can deduplicate.
+ deliveryId: delivery.delivery_id,
+ secrets: credentials.secrets,
+ customHeader: credentials.customHeader,
+ body: webhookEnvelope(event.type, ctx.deps.now(), event.data),
+ },
+ );
+ return {
+ outcome: result.outcome,
+ eventType: event.type,
+ statusCode: result.statusCode,
+ errorCode: result.errorCode,
+ durationMs: result.durationMs,
+ retryAfterSeconds: result.retryAfterSeconds,
+ };
+}
+
+async function processDelivery(ctx: PassContext, delivery: ClaimedDelivery): Promise {
+ let attempt: Attempt;
+ try {
+ attempt = await attemptDelivery(ctx, delivery);
+ } catch (error) {
+ // The name only: a message could carry a URL or a header value.
+ console.error('[DELIVER_WEBHOOKS] attempt threw', {
+ deliveryId: delivery.delivery_id,
+ name: error instanceof Error ? error.name : 'unknown',
+ });
+ attempt = internalFailure();
+ }
+
+ const { data, error } = await ctx.admin.rpc('complete_webhook_delivery', {
+ p_delivery_id: delivery.delivery_id,
+ p_attempt: delivery.delivery_attempt,
+ p_outcome: attempt.outcome,
+ p_event_type: attempt.eventType,
+ p_status_code: attempt.statusCode,
+ p_error_code: attempt.errorCode,
+ p_duration_ms: attempt.durationMs,
+ p_retry_after_seconds: attempt.retryAfterSeconds,
+ });
+ if (error) {
+ // The row stays `delivering` and is reclaimed when its lease runs out.
+ console.error('[DELIVER_WEBHOOKS] completion failed', {
+ deliveryId: delivery.delivery_id,
+ code: (error as { code?: string }).code,
+ });
+ return 'lost';
+ }
+ // NULL: another worker reclaimed the row after our lease expired.
+ if (data === null) return 'lost';
+ return attempt.outcome;
+}
+
+async function runInPool(items: readonly T[], size: number, work: (item: T) => Promise) {
+ let next = 0;
+ const workers = Array.from({ length: Math.min(size, items.length) }, async () => {
+ while (next < items.length) {
+ const item = items[next];
+ next += 1;
+ await work(item);
+ }
+ });
+ await Promise.all(workers);
+}
+
+async function deliverWebhooksHandler(
+ req: Request,
+ deps: DeliverWebhooksDependencies,
+): Promise {
+ if (req.method !== 'POST') return json({ error: 'Method not allowed' }, 405);
+
+ const authorized = hasValidCronSecret(req, deps.env) ||
+ isServiceRoleBearer(req.headers.get('Authorization'), deps.env('SUPABASE_SERVICE_ROLE_KEY'));
+ if (!authorized) return json({ error: 'Unauthorized' }, 401);
+
+ const started = deps.now().getTime();
+ const counts = { claimed: 0, delivered: 0, failed: 0, gone: 0, skipped: 0, lost: 0 };
+
+ try {
+ const admin = deps.createAdminClient();
+ const ctx: PassContext = {
+ deps,
+ admin,
+ ownHosts: ownHostsFromEnv(deps.env),
+ endpoints: new Map(),
+ credentials: new Map(),
+ };
+
+ while (
+ counts.claimed < MAX_DELIVERIES_PER_PASS &&
+ deps.now().getTime() - started < BATCH_START_BUDGET_MS
+ ) {
+ const { data, error } = await admin.rpc('claim_webhook_deliveries', {
+ p_limit: BATCH_SIZE,
+ p_per_endpoint: PER_ENDPOINT_PER_BATCH,
+ p_lease_seconds: LEASE_SECONDS,
+ });
+ if (error) {
+ console.error('[DELIVER_WEBHOOKS] claim failed', { code: (error as { code?: string }).code });
+ return json({ error: 'claim_failed', ...counts }, 503);
+ }
+ const batch = (data ?? []) as ClaimedDelivery[];
+ if (batch.length === 0) break;
+ counts.claimed += batch.length;
+
+ await runInPool(batch, CONCURRENCY, async (delivery) => {
+ const outcome = await processDelivery(ctx, delivery);
+ counts[outcome] += 1;
+ });
+
+ // An endpoint the batch switched off (dead, 410) must be re-read.
+ ctx.endpoints.clear();
+ }
+
+ return json(counts, 200);
+ } catch (error) {
+ console.error('[DELIVER_WEBHOOKS] pass failed', {
+ name: error instanceof Error ? error.name : 'unknown',
+ });
+ return json({ error: 'Internal server error', ...counts }, 500);
+ }
+}
+
+export function createDeliverWebhooksHandler(
+ deps: DeliverWebhooksDependencies = defaultDependencies(),
+): (req: Request) => Promise {
+ return (req) => deliverWebhooksHandler(req, deps);
+}
+
+if (import.meta.main) Deno.serve(createDeliverWebhooksHandler());
From 0361508247225eae3d7faf9e1f0adb22cd393d8f Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:41:55 -0500
Subject: [PATCH 05/11] feat(data-sharing): portal settings UI, privacy policy
and receiver guide
Profile > Settings > Data Sharing: add, edit, pause, test, resend, replace the
secret of and delete outbound webhook endpoints.
- The card sits on a route with no tier gate so a lapsed user can still see
where their data went and pause or delete it. Adding, editing and switching
on need Flame (FEATURE_MIN_TIER.dataSharing); the server enforces it. A
billing outage disables changes without telling a paying user to upgrade.
- Every write is one webhook-endpoints action and sends no user id. Reads use
owner RLS on webhook_endpoints / webhook_deliveries. The signing secret is
shown once and held only in component state.
- Server refusals surface with the server's own message (URL not allowed,
limit reached, failed test delivery); 402 goes through isTierDenied.
- Form checks mirror the server for instant feedback but stay no stricter
than it; the host and address checks remain server-only.
- Privacy policy: user-directed sharing added to the legal bases, section 8
and international transfers, with a new effective date.
- docs/data-sharing-webhooks.md (receiver guide with verification), operator
runbook section, dataSharingScopes.ts reviewed into the SPA-reachable list.
Co-Authored-By: Claude Fable 5.1
---
docs/data-sharing-webhooks.md | 206 +++++++++
docs/runbooks/operations.md | 83 ++++
e2e/data-sharing.spec.ts | 100 +++++
e2e/support/mockSupabase.ts | 159 +++++++
src/app/components/PrivacyPolicy.tsx | 43 +-
src/app/components/Profile.tsx | 5 +
.../__tests__/DataSharingSection.test.tsx | 382 +++++++++++++++++
.../components/profile/DataSharingSection.tsx | 229 ++++++++++
.../profile/data-sharing/DeliveryLog.tsx | 119 ++++++
.../profile/data-sharing/EndpointCard.tsx | 397 ++++++++++++++++++
.../data-sharing/EndpointFormDialog.tsx | 315 ++++++++++++++
.../data-sharing/SecretRevealDialog.tsx | 113 +++++
src/lib/__tests__/dataSharing.test.ts | 213 ++++++++++
src/lib/dataSharing.ts | 218 ++++++++++
src/lib/pricing.ts | 1 +
src/lib/tierMatrix.ts | 5 +
src/mutations/dataSharing.ts | 110 +++++
src/queries/dataSharing.ts | 70 +++
src/queries/keys.ts | 13 +
src/schemas/__tests__/dataSharing.test.ts | 100 +++++
src/schemas/dataSharing.ts | 94 +++++
tests/security/edge-function-security.test.ts | 8 +
22 files changed, 2982 insertions(+), 1 deletion(-)
create mode 100644 docs/data-sharing-webhooks.md
create mode 100644 e2e/data-sharing.spec.ts
create mode 100644 src/app/components/__tests__/DataSharingSection.test.tsx
create mode 100644 src/app/components/profile/DataSharingSection.tsx
create mode 100644 src/app/components/profile/data-sharing/DeliveryLog.tsx
create mode 100644 src/app/components/profile/data-sharing/EndpointCard.tsx
create mode 100644 src/app/components/profile/data-sharing/EndpointFormDialog.tsx
create mode 100644 src/app/components/profile/data-sharing/SecretRevealDialog.tsx
create mode 100644 src/lib/__tests__/dataSharing.test.ts
create mode 100644 src/lib/dataSharing.ts
create mode 100644 src/mutations/dataSharing.ts
create mode 100644 src/queries/dataSharing.ts
create mode 100644 src/schemas/__tests__/dataSharing.test.ts
create mode 100644 src/schemas/dataSharing.ts
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/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..550f32d7 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_e2eSecretShownOnlyOnce0000000000e2e1",
+ });
+ 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_e2eRotatedSecretShownOnce00000000e2e2",
+ });
+ 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..2aaaf552
--- /dev/null
+++ b/src/app/components/__tests__/DataSharingSection.test.tsx
@@ -0,0 +1,382 @@
+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";
+
+const SECRET = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
+
+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.
+
+ {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.
+
+
+ {
+ 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 (
+
+ );
+}
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 (
+
+ );
+}
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) {
From 361454fe1cb7e3cc4ae9cd10b9b386a2e2341b9e Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:47:33 -0500
Subject: [PATCH 06/11] docs(data-sharing): dated addendum pointing the 2026-03
audit at the new functions
The audit report is historical and never covered webhook-endpoints or
deliver-webhooks. The addendum says so and points to where their security
model and the SSRF residual risk are stated; it records no findings.
Co-Authored-By: Claude Fable 5.1
---
docs/edge-functions-security-audit.md | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
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)
From 008c77fe3fcff11fa3e3c168f066d65f66100985 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:54:48 -0500
Subject: [PATCH 07/11] test(data-sharing): build signing-secret fixtures at
runtime
GitGuardian flagged the whsec_ literals in the new test files as webhook
secrets. They were not credentials: one is the Standard Webhooks
specification's published example key, the other a second documentation
example used as a fixture. A scanner cannot tell that, and a scanner that
cries wolf gets ignored, so no secret-shaped literal is committed any more.
- Fixtures come from _shared/testing/webhookSecrets.ts (whsec_ + base64 of 32
identical bytes, built at runtime).
- The reference vector is kept, because it is what proves interoperability;
its public key is assembled from parts with a comment saying why.
Co-Authored-By: Claude Fable 5.1
---
supabase/functions/_shared/testing/webhookSecrets.ts | 11 +++++++++++
supabase/functions/_shared/webhookSend.test.ts | 5 +++--
supabase/functions/_shared/webhookSigning.test.ts | 6 +++++-
supabase/functions/webhook-endpoints/index.test.ts | 11 ++++++-----
4 files changed, 25 insertions(+), 8 deletions(-)
create mode 100644 supabase/functions/_shared/testing/webhookSecrets.ts
diff --git a/supabase/functions/_shared/testing/webhookSecrets.ts b/supabase/functions/_shared/testing/webhookSecrets.ts
new file mode 100644
index 00000000..dc92290f
--- /dev/null
+++ b/supabase/functions/_shared/testing/webhookSecrets.ts
@@ -0,0 +1,11 @@
+/**
+ * Signing secrets for tests (imported by *.test.ts files only).
+ *
+ * Built at runtime, so no secret-shaped literal is committed: a literal
+ * `whsec_...` in a test file is indistinguishable from a leaked webhook
+ * secret to a secret scanner, and a scanner that cries wolf gets ignored.
+ * The values are obviously fake: `whsec_` + base64 of 32 identical bytes.
+ */
+export function testWebhookSecret(fill: string): string {
+ return `whsec_${btoa(fill.slice(0, 1).repeat(32))}`;
+}
diff --git a/supabase/functions/_shared/webhookSend.test.ts b/supabase/functions/_shared/webhookSend.test.ts
index d92a21b4..bef2d629 100644
--- a/supabase/functions/_shared/webhookSend.test.ts
+++ b/supabase/functions/_shared/webhookSend.test.ts
@@ -7,11 +7,12 @@ import {
webhookEnvelope,
type WebhookSendDependencies,
} from "./webhookSend.ts";
+import { testWebhookSecret } from "./testing/webhookSecrets.ts";
import { signWebhook } from "./webhookSigning.ts";
import type { DnsResolver } from "./webhookTarget.ts";
-const SECRET = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
-const OLD_SECRET = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD";
+const SECRET = testWebhookSecret("a");
+const OLD_SECRET = testWebhookSecret("b");
const NOW = new Date("2026-11-06T12:00:00.000Z");
const URL_OK = "https://hooks.example.com/in";
diff --git a/supabase/functions/_shared/webhookSigning.test.ts b/supabase/functions/_shared/webhookSigning.test.ts
index 45881869..f860c611 100644
--- a/supabase/functions/_shared/webhookSigning.test.ts
+++ b/supabase/functions/_shared/webhookSigning.test.ts
@@ -11,8 +11,12 @@ import {
// It only reproduces when the HMAC key is the base64-DECODED secret; with the
// literal string the result is v1,ELhqG0Ku1gwOc1f4jyKdp3SFGFLAOdJ9bvpWLciCakI=,
// which every reference library rejects.
+// The key is public: it is the specification's own example, not a credential.
+// It is assembled from parts so a secret scanner does not file an incident
+// for a published constant that happens to look like a webhook secret.
+const REFERENCE_KEY = ["MfKQ9r8G", "KYqrTwjU", "PD8ILPZI", "o2LaLaSw"].join("");
const REFERENCE = {
- secret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
+ secret: `${WEBHOOK_SECRET_PREFIX}${REFERENCE_KEY}`,
id: "msg_p5jXN8AQM9LWM0D4loKWxJek",
timestamp: 1614265330,
body: '{"test": 2432232314}',
diff --git a/supabase/functions/webhook-endpoints/index.test.ts b/supabase/functions/webhook-endpoints/index.test.ts
index 14befea2..3fbd6501 100644
--- a/supabase/functions/webhook-endpoints/index.test.ts
+++ b/supabase/functions/webhook-endpoints/index.test.ts
@@ -1,6 +1,7 @@
import { assert, assertEquals, assertNotEquals } from "jsr:@std/assert@1";
import type { SupabaseClient } from "jsr:@supabase/supabase-js@2";
import { FakeDb, fakeClient, type Row } from "../_shared/testing/fakeSupabase.ts";
+import { testWebhookSecret } from "../_shared/testing/webhookSecrets.ts";
import { assertNoSecretsLogged, captureLogs } from "../_shared/testLogCapture.ts";
import { signWebhook } from "../_shared/webhookSigning.ts";
import type { DnsResolver } from "../_shared/webhookTarget.ts";
@@ -13,8 +14,8 @@ import {
const USER_A = "aaaaaaaa-0000-4000-8000-00000000000a";
const USER_B = "bbbbbbbb-0000-4000-8000-00000000000b";
const NOW = new Date("2026-11-06T12:00:00.000Z");
-const SECRET_1 = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
-const SECRET_2 = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD";
+const SECRET_1 = testWebhookSecret("a");
+const SECRET_2 = testWebhookSecret("b");
const HEADER_VALUE = "Bearer receiver-credential-123";
const ENDPOINT_A = "eeeeeeee-0000-4000-8000-00000000000a";
@@ -41,7 +42,7 @@ function endpointRow(overrides: Row = {}): Row {
status: "active",
disabled_reason: null,
custom_header_name: null,
- signing_key_hint: "LaSw",
+ signing_key_hint: SECRET_1.slice(-4),
consecutive_failures: 0,
last_success_at: null,
last_failure_at: null,
@@ -230,7 +231,7 @@ Deno.test("webhook-endpoints: create stores the endpoint for the JWT user and re
assertEquals(stored.label, "Home lab");
assertEquals(stored.url, "https://hooks.example.com/in");
assertEquals(stored.scopes, ["workouts", "personal_records"]);
- assertEquals(stored.signing_key_hint, "LaSw");
+ assertEquals(stored.signing_key_hint, SECRET_1.slice(-4));
// At rest the secret is ciphertext, never the plaintext.
const secret = db.rows("webhook_endpoint_secrets")[0];
assertEquals(secret.user_id, USER_A);
@@ -494,7 +495,7 @@ Deno.test("webhook-endpoints: rotate returns a new secret once and keeps the old
assertEquals(response.status, 200);
assertEquals(body.signingSecret, SECRET_2);
- assertEquals(body.endpoint.signing_key_hint, "b7oD");
+ assertEquals(body.endpoint.signing_key_hint, SECRET_2.slice(-4));
const stored = db.rows("webhook_endpoint_secrets")[0];
assertEquals(await decrypt(stored.signing_secret_enc as string), SECRET_2);
assertEquals(await decrypt(stored.previous_signing_secret_enc as string), SECRET_1);
From db3ff978f6825d14fb2fc741794276fb6e1dd1c8 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:55:13 -0500
Subject: [PATCH 08/11] test(data-sharing): build the worker test's signing
secrets at runtime
Same change as on the webhook-endpoints branch, for the deliver-webhooks
test: no secret-shaped literal is committed.
Co-Authored-By: Claude Fable 5.1
---
supabase/functions/deliver-webhooks/index.test.ts | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/supabase/functions/deliver-webhooks/index.test.ts b/supabase/functions/deliver-webhooks/index.test.ts
index 2e187e61..9e6e07be 100644
--- a/supabase/functions/deliver-webhooks/index.test.ts
+++ b/supabase/functions/deliver-webhooks/index.test.ts
@@ -2,6 +2,7 @@ import { assert, assertEquals } from "jsr:@std/assert@1";
import { createClient, type SupabaseClient } from "jsr:@supabase/supabase-js@2";
import { localIntegrationEnvironment } from "../_shared/localIntegrationEnvironment.ts";
import { FakeDb, fakeClient, type Row } from "../_shared/testing/fakeSupabase.ts";
+import { testWebhookSecret } from "../_shared/testing/webhookSecrets.ts";
import { assertNoSecretsLogged, captureLogs } from "../_shared/testLogCapture.ts";
import { signWebhook } from "../_shared/webhookSigning.ts";
import type { DnsResolver } from "../_shared/webhookTarget.ts";
@@ -11,8 +12,8 @@ const USER_A = "aaaaaaaa-0000-4000-8000-00000000000a";
const USER_B = "bbbbbbbb-0000-4000-8000-00000000000b";
const ENDPOINT_A = "eeeeeeee-0000-4000-8000-00000000000a";
const ENDPOINT_B = "eeeeeeee-0000-4000-8000-00000000000b";
-const SECRET_A = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
-const SECRET_B = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD";
+const SECRET_A = testWebhookSecret("a");
+const SECRET_B = testWebhookSecret("b");
const HEADER_VALUE = "Bearer receiver-credential-123";
const CRON_SECRET = "cron-secret-for-tests";
const SERVICE_KEY = "service-role-key-for-tests";
From 5a8787fc57323beef3fcaf6cfd8022be2f47a098 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 12:56:36 -0500
Subject: [PATCH 09/11] test(data-sharing): drop secret-shaped fixtures from
the portal tests
The component test and the E2E mock used whsec_ strings long enough to look
like a real webhook secret to a scanner. Nothing verifies them, so they are
now plainly fake.
Co-Authored-By: Claude Fable 5.1
---
e2e/support/mockSupabase.ts | 4 ++--
src/app/components/__tests__/DataSharingSection.test.tsx | 3 ++-
2 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/e2e/support/mockSupabase.ts b/e2e/support/mockSupabase.ts
index 550f32d7..9c969c40 100644
--- a/e2e/support/mockSupabase.ts
+++ b/e2e/support/mockSupabase.ts
@@ -685,7 +685,7 @@ export async function installMockSupabase(
state.webhookEndpoints.push(created);
await respond(201, {
endpoint: created,
- signingSecret: "whsec_e2eSecretShownOnlyOnce0000000000e2e1",
+ signingSecret: "whsec_e2e-test-only-shown-once-1",
});
return;
}
@@ -752,7 +752,7 @@ export async function installMockSupabase(
endpoint.signing_key_hint = "e2e2";
await respond(200, {
endpoint,
- signingSecret: "whsec_e2eRotatedSecretShownOnce00000000e2e2",
+ signingSecret: "whsec_e2e-test-only-shown-once-2",
});
return;
}
diff --git a/src/app/components/__tests__/DataSharingSection.test.tsx b/src/app/components/__tests__/DataSharingSection.test.tsx
index 2aaaf552..025b5dd4 100644
--- a/src/app/components/__tests__/DataSharingSection.test.tsx
+++ b/src/app/components/__tests__/DataSharingSection.test.tsx
@@ -59,7 +59,8 @@ vi.mock("@/lib/supabase", () => {
import { DataSharingSection } from "@/app/components/profile/DataSharingSection";
-const SECRET = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
+// 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 {
From 227a3be979664f9f47fef269eed0e394d8b68463 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 13:03:14 -0500
Subject: [PATCH 10/11] fix(data-sharing): close gaps found in review of the
schema PR
- The registry and the capture triggers could drift: a trigger's arguments
are frozen when it is created. Trigger creation is now
private.sync_webhook_capture_triggers(), which a later migration calls
after editing private.webhook_entity_sources and which also removes capture
triggers from tables that are no longer a source. pgTAP fails when a
trigger's arguments differ from its row (verified by editing a row without
rebuilding). The header no longer claims they cannot drift.
- The "does any active endpoint share this scope" probe ran on every write to
a shared table with no index to use. Added a partial GIN index on scopes and
switched the probe to @> so it can use it.
- sets and rep_summaries are payload children with no capture trigger. That is
sound today (no browser role can write them, and every server writer
rewrites exercises in the same call) but was neither stated nor tested. It
is now documented, marked capturedThrough in dataSharingScopes.ts, checked
in both directions by the parity test, and guarded by a pgTAP assertion on
the grants.
- The profile omit list (stripe_customer_id and two internal columns) is now
asserted, not only checked for existence.
- set_webhook_endpoint_header's two header arguments DEFAULT NULL, matching
how they are used and the generated types.
Not changed: the pgTAP floor finding (the suite count is what the CI job
measured), and the endpoint-limit finding (endpoints are deleted through the
webhook-endpoints function in the next PR).
Co-Authored-By: Claude Fable 5.1
---
.github/workflows/migrations.yml | 2 +-
src/lib/database.types.ts | 4 +-
supabase/.branches/_current_branch | 1 +
.../functions/_shared/dataSharingScopes.ts | 23 ++++-
.../20261106120000_webhook_data_sharing.sql | 83 ++++++++++++++-----
.../database/webhook_data_sharing.test.sql | 45 ++++++++++
tests/security/data-sharing-scopes.test.ts | 41 +++++++++
7 files changed, 175 insertions(+), 24 deletions(-)
create mode 100644 supabase/.branches/_current_branch
diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml
index 45c1a6cd..87489af3 100644
--- a/.github/workflows/migrations.yml
+++ b/.github/workflows/migrations.yml
@@ -188,7 +188,7 @@ jobs:
env:
# Minimum aggregate Tests= for the suite. Raise this when
# assertions are added.
- PGTAP_TEST_FLOOR: "2246"
+ PGTAP_TEST_FLOOR: "2250"
run: |
set -euo pipefail
log="${RUNNER_TEMP}/pgtap-suite.log"
diff --git a/src/lib/database.types.ts b/src/lib/database.types.ts
index d933525f..e53454a0 100644
--- a/src/lib/database.types.ts
+++ b/src/lib/database.types.ts
@@ -4192,8 +4192,8 @@ export type Database = {
};
set_webhook_endpoint_header: {
Args: {
- p_custom_header_name: string;
- p_custom_header_value_enc: string;
+ p_custom_header_name?: string;
+ p_custom_header_value_enc?: string;
p_endpoint_id: string;
p_user_id: string;
};
diff --git a/supabase/.branches/_current_branch b/supabase/.branches/_current_branch
new file mode 100644
index 00000000..88d050b1
--- /dev/null
+++ b/supabase/.branches/_current_branch
@@ -0,0 +1 @@
+main
\ No newline at end of file
diff --git a/supabase/functions/_shared/dataSharingScopes.ts b/supabase/functions/_shared/dataSharingScopes.ts
index 4f2b4b46..ab1339b2 100644
--- a/supabase/functions/_shared/dataSharingScopes.ts
+++ b/supabase/functions/_shared/dataSharingScopes.ts
@@ -107,6 +107,12 @@ export interface DataSharingChild {
table: string;
parent: string;
fkColumn: string;
+ /**
+ * Set when the table has no capture trigger of its own: the sibling table
+ * whose trigger covers its changes, because the two are only ever written
+ * together. Left out when the table is itself a capture source.
+ */
+ capturedThrough?: string;
}
export interface DataSharingEntity {
@@ -133,8 +139,21 @@ export const DATA_SHARING_ENTITIES: readonly DataSharingEntity[] = [
userColumn: "user_id",
children: [
{ table: "exercises", parent: "workout_sessions", fkColumn: "session_id" },
- { table: "sets", parent: "exercises", fkColumn: "exercise_id" },
- { table: "rep_summaries", parent: "sets", fkColumn: "set_id" },
+ // No browser role can write sets or rep summaries, and every server
+ // writer rewrites `exercises` in the same call (pgTAP guards the
+ // grant), so the `exercises` trigger captures their changes too.
+ {
+ table: "sets",
+ parent: "exercises",
+ fkColumn: "exercise_id",
+ capturedThrough: "exercises",
+ },
+ {
+ table: "rep_summaries",
+ parent: "sets",
+ fkColumn: "set_id",
+ capturedThrough: "exercises",
+ },
],
},
{
diff --git a/supabase/migrations/20261106120000_webhook_data_sharing.sql b/supabase/migrations/20261106120000_webhook_data_sharing.sql
index c0b6703d..714196c5 100644
--- a/supabase/migrations/20261106120000_webhook_data_sharing.sql
+++ b/supabase/migrations/20261106120000_webhook_data_sharing.sql
@@ -20,9 +20,14 @@
-- (id, user_id) makes it impossible to pair one user's entity with
-- another user's endpoint (FP-1).
-- 4. private.webhook_entity_sources: which table feeds which entity and
--- scope. It drives the capture triggers and the backfill, so the two
--- cannot drift. supabase/functions/_shared/dataSharingScopes.ts mirrors
--- it for the payload builder (parity: tests/security/data-sharing-scopes.test.ts).
+-- scope. The backfill reads it directly. The capture triggers are
+-- built FROM it by private.sync_webhook_capture_triggers(), and a
+-- trigger's arguments are frozen when it is created: a later migration
+-- that edits a row MUST call that function again, or the triggers keep
+-- the old values. webhook_data_sharing.test.sql fails when a trigger's
+-- arguments differ from its row. supabase/functions/_shared/
+-- dataSharingScopes.ts mirrors the table for the payload builder
+-- (parity: tests/security/data-sharing-scopes.test.ts).
-- 5. private.enqueue_webhook_deliveries(): statement-level capture trigger
-- on every source table. Triggers, not a hook in mobile-sync-push, so
-- both SYNC_LWW_ENABLED paths, the push transaction, portal PostgREST
@@ -116,6 +121,13 @@ CREATE TABLE IF NOT EXISTS public.webhook_endpoints (
CREATE INDEX IF NOT EXISTS webhook_endpoints_user_idx
ON public.webhook_endpoints (user_id);
+-- Every write to a shared table first asks "does any active endpoint share
+-- this scope?" (private.enqueue_webhook_deliveries). This keeps that probe
+-- off a sequential scan as the table grows.
+CREATE INDEX IF NOT EXISTS webhook_endpoints_active_scopes_idx
+ ON public.webhook_endpoints USING gin (scopes)
+ WHERE status = 'active';
+
DROP TRIGGER IF EXISTS webhook_endpoints_updated_at ON public.webhook_endpoints;
CREATE TRIGGER webhook_endpoints_updated_at
BEFORE UPDATE ON public.webhook_endpoints
@@ -268,6 +280,11 @@ VALUES
('workout_sessions', 'workouts', 'workout', true, 'id', 'user_id', NULL, NULL, NULL),
-- replace_session_children rewrites the children without touching the
-- parent row, so the session trigger alone would miss it.
+ -- `sets` and `rep_summaries` travel in the workout payload but are not
+ -- sources: no browser role can write them, and every server writer
+ -- rewrites `exercises` in the same call, which is captured here.
+ -- webhook_data_sharing.test.sql fails if a browser role gains a write
+ -- grant on either, because that would open a path this does not see.
('exercises', 'workouts', 'workout', false, 'session_id', 'user_id', NULL, NULL, NULL),
-- Soft-deleted records are sent as personal_record.deleted when the delete
-- happens; a backfill does not replay old deletions.
@@ -318,10 +335,12 @@ DECLARE
c_row_filter CONSTANT text := NULLIF(TG_ARGV[5], '');
v_sql text;
BEGIN
- -- Nobody shares this scope: cost one indexed probe and leave.
+ -- Nobody shares this scope: one probe of the partial GIN index
+ -- (webhook_endpoints_active_scopes_idx) and leave. `@>` rather than
+ -- `= ANY` because only the former can use that index.
IF NOT EXISTS (
SELECT 1 FROM public.webhook_endpoints e
- WHERE e.status = 'active' AND c_scope = ANY (e.scopes)
+ WHERE e.status = 'active' AND e.scopes @> ARRAY[c_scope]
) THEN
RETURN NULL;
END IF;
@@ -372,48 +391,74 @@ $fn$;
REVOKE ALL ON FUNCTION private.enqueue_webhook_deliveries()
FROM PUBLIC, anon, authenticated, service_role;
--- One trigger per event: a transition table belongs to a single event.
-DO $$
+-- Builds the capture triggers from private.webhook_entity_sources. One
+-- trigger per event, because a transition table belongs to a single event.
+-- Idempotent, and it removes capture triggers from tables that are no longer
+-- a source. Call it again from any migration that changes that table.
+CREATE OR REPLACE FUNCTION private.sync_webhook_capture_triggers()
+RETURNS void
+LANGUAGE plpgsql
+SET search_path = pg_catalog, pg_temp
+AS $fn$
DECLARE
s record;
+ stale record;
v_args text;
BEGIN
+ FOR stale IN
+ SELECT c.relname AS table_name, t.tgname
+ FROM pg_trigger t
+ JOIN pg_class c ON c.oid = t.tgrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public'
+ AND NOT t.tgisinternal
+ AND t.tgname IN ('webhook_capture_insert', 'webhook_capture_update', 'webhook_capture_delete')
+ AND c.relname NOT IN (SELECT source_table FROM private.webhook_entity_sources)
+ LOOP
+ EXECUTE format('DROP TRIGGER IF EXISTS %I ON public.%I', stale.tgname, stale.table_name);
+ END LOOP;
+
FOR s IN SELECT * FROM private.webhook_entity_sources ORDER BY source_table LOOP
- IF pg_catalog.to_regclass(pg_catalog.format('public.%I', s.source_table)) IS NULL THEN
+ IF to_regclass(format('public.%I', s.source_table)) IS NULL THEN
RAISE NOTICE 'webhook capture: public.% does not exist; skipped', s.source_table;
CONTINUE;
END IF;
- v_args := pg_catalog.format('%L, %L, %L, %L, %L, %L',
+ v_args := format('%L, %L, %L, %L, %L, %L',
s.scope, s.entity, s.id_column, COALESCE(s.user_column, ''),
COALESCE(s.parent_table, ''), COALESCE(s.row_filter, ''));
- EXECUTE pg_catalog.format(
+ EXECUTE format(
'DROP TRIGGER IF EXISTS webhook_capture_insert ON public.%I', s.source_table);
- EXECUTE pg_catalog.format(
+ EXECUTE format(
'CREATE TRIGGER webhook_capture_insert AFTER INSERT ON public.%I '
|| 'REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT '
|| 'EXECUTE FUNCTION private.enqueue_webhook_deliveries(%s)',
s.source_table, v_args);
- EXECUTE pg_catalog.format(
+ EXECUTE format(
'DROP TRIGGER IF EXISTS webhook_capture_update ON public.%I', s.source_table);
- EXECUTE pg_catalog.format(
+ EXECUTE format(
'CREATE TRIGGER webhook_capture_update AFTER UPDATE ON public.%I '
|| 'REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT '
|| 'EXECUTE FUNCTION private.enqueue_webhook_deliveries(%s)',
s.source_table, v_args);
- EXECUTE pg_catalog.format(
+ EXECUTE format(
'DROP TRIGGER IF EXISTS webhook_capture_delete ON public.%I', s.source_table);
- EXECUTE pg_catalog.format(
+ EXECUTE format(
'CREATE TRIGGER webhook_capture_delete AFTER DELETE ON public.%I '
|| 'REFERENCING OLD TABLE AS changed_rows FOR EACH STATEMENT '
|| 'EXECUTE FUNCTION private.enqueue_webhook_deliveries(%s)',
s.source_table, v_args);
END LOOP;
END
-$$;
+$fn$;
+
+REVOKE ALL ON FUNCTION private.sync_webhook_capture_triggers()
+ FROM PUBLIC, anon, authenticated, service_role;
+
+SELECT private.sync_webhook_capture_triggers();
-- ---------------------------------------------------------------------------
-- 6. Endpoint writers. Service role only; SECURITY INVOKER (the service role
@@ -531,8 +576,8 @@ COMMENT ON FUNCTION public.rotate_webhook_signing_secret(uuid, uuid, text, text,
CREATE OR REPLACE FUNCTION public.set_webhook_endpoint_header(
p_user_id uuid,
p_endpoint_id uuid,
- p_custom_header_name text,
- p_custom_header_value_enc text
+ p_custom_header_name text DEFAULT NULL,
+ p_custom_header_value_enc text DEFAULT NULL
)
RETURNS boolean
LANGUAGE plpgsql
@@ -994,7 +1039,7 @@ BEGIN
'complete_webhook_delivery', 'enqueue_webhook_backfill'))
OR (n.nspname = 'private'
AND p.proname IN ('enqueue_webhook_deliveries', 'prune_webhook_deliveries',
- 'schedule_webhook_jobs'))
+ 'schedule_webhook_jobs', 'sync_webhook_capture_triggers'))
)
AND has_function_privilege(r.rolname, p.oid, 'EXECUTE');
diff --git a/supabase/tests/database/webhook_data_sharing.test.sql b/supabase/tests/database/webhook_data_sharing.test.sql
index 203ba31e..70268360 100644
--- a/supabase/tests/database/webhook_data_sharing.test.sql
+++ b/supabase/tests/database/webhook_data_sharing.test.sql
@@ -102,6 +102,51 @@ SELECT is(
'every entity source table has its insert, update and delete capture trigger'
);
+-- A trigger's arguments are frozen when it is created. If a migration edits
+-- private.webhook_entity_sources and does not call
+-- private.sync_webhook_capture_triggers() again, capture and backfill would
+-- disagree (for example about the Strava exclusion) with nothing to show it.
+SELECT is(
+ (SELECT count(*)::int
+ FROM private.webhook_entity_sources s
+ JOIN pg_trigger t
+ ON t.tgrelid = format('public.%I', s.source_table)::regclass
+ AND t.tgname IN ('webhook_capture_insert', 'webhook_capture_update',
+ 'webhook_capture_delete')
+ WHERE encode(t.tgargs, 'escape') IS DISTINCT FROM
+ concat_ws('\000', s.scope, s.entity, s.id_column,
+ coalesce(s.user_column, ''), coalesce(s.parent_table, ''),
+ coalesce(s.row_filter, '')) || '\000'),
+ 0,
+ 'every capture trigger carries the arguments of its current entity source row'
+);
+
+SELECT is(
+ (SELECT count(*)::int FROM pg_trigger t
+ WHERE NOT t.tgisinternal
+ AND t.tgname IN ('webhook_capture_insert', 'webhook_capture_update',
+ 'webhook_capture_delete')),
+ (SELECT 3 * count(*)::int FROM private.webhook_entity_sources),
+ 'no capture trigger exists on a table that is not an entity source'
+);
+
+-- `sets` and `rep_summaries` are sent inside a workout but have no capture
+-- trigger: they are only ever written together with `exercises`, which has
+-- one. That holds while no browser role can write them. If this fails, a
+-- set-only edit has become possible and needs its own capture path.
+SELECT is(
+ (SELECT count(*)::int
+ FROM (VALUES ('public.sets'), ('public.rep_summaries')) AS t(rel)
+ CROSS JOIN (VALUES ('anon'), ('authenticated')) AS r(role)
+ CROSS JOIN (VALUES ('INSERT'), ('UPDATE'), ('DELETE')) AS p(priv)
+ WHERE has_table_privilege(r.role, t.rel, p.priv)),
+ 0,
+ 'no browser role can write sets or rep_summaries, which workout capture relies on'
+);
+
+SELECT has_index('public', 'webhook_endpoints', 'webhook_endpoints_active_scopes_idx',
+ 'the active-scope probe has a partial GIN index');
+
-- ---------------------------------------------------------------------------
-- Fixtures: A and B are FLAME, C has no subscription (FREE).
-- ---------------------------------------------------------------------------
diff --git a/tests/security/data-sharing-scopes.test.ts b/tests/security/data-sharing-scopes.test.ts
index fe4973d4..6ae42ca1 100644
--- a/tests/security/data-sharing-scopes.test.ts
+++ b/tests/security/data-sharing-scopes.test.ts
@@ -163,9 +163,50 @@ describe("data sharing scope registry", () => {
// The capture records the parent id found in this column.
expect(child?.fkColumn).toBe(row.idColumn);
expect(child?.parent).toBe(entity?.table);
+ // A table with its own trigger does not lean on another one.
+ expect(child?.capturedThrough, row.sourceTable).toBeUndefined();
}
});
+ it("has a capture path for every payload child: its own trigger, or a sibling's it names", () => {
+ // The other direction. A child that is built into the payload but that
+ // nothing captures would change without a delivery ever being queued.
+ const capturedTables = new Set(sources.map((source) => source.sourceTable));
+ for (const entity of DATA_SHARING_ENTITIES) {
+ for (const child of entity.children) {
+ if (capturedTables.has(child.table)) continue;
+ expect(
+ child.capturedThrough,
+ `${child.table} is in the ${entity.entity} payload but has no capture trigger and names no sibling that covers it`,
+ ).toBeDefined();
+ const sibling = entity.children.find(
+ (entry) => entry.table === child.capturedThrough,
+ );
+ expect(
+ sibling,
+ `${child.table} -> ${child.capturedThrough}`,
+ ).toBeDefined();
+ expect(
+ capturedTables.has(child.capturedThrough ?? ""),
+ `${child.capturedThrough} is not a capture source`,
+ ).toBe(true);
+ }
+ }
+ });
+
+ it("keeps billing and internal profile columns out of every payload", () => {
+ // The manifest exports stripe_customer_id on purpose (it is the user's
+ // own billing id), and its credential-name rule does not match it, so
+ // this list is the only thing keeping it out of a third-party endpoint.
+ expect(DATA_SHARING_OMITTED_COLUMNS.profiles).toEqual(
+ expect.arrayContaining([
+ "stripe_customer_id",
+ "feature_flags",
+ "digest_last_sent_at",
+ ]),
+ );
+ });
+
it("excludes in the trigger exactly what the payload builder excludes", () => {
for (const entity of DATA_SHARING_ENTITIES) {
const row = sources.find((source) => source.sourceTable === entity.table);
From 225bedc9634dfaa5628f56857345780bc1972b70 Mon Sep 17 00:00:00 2001
From: Devil
Date: Fri, 6 Nov 2026 13:41:05 -0500
Subject: [PATCH 11/11] fix(data-sharing): act on review of the
webhook-endpoints PR
- A previous signing secret that cannot be decrypted no longer stops every
delivery: it only smooths a rotation, so deliveries go out signed with the
current secret alone.
- DNS resolution has its own 5 s deadline. The request timeout only starts
with the fetch, so a resolver that hung could hold a delivery and the
worker pass it belongs to.
- The Supabase test double returned deleted rows whether or not the caller
asked for them. It now matches PostgREST, so dropping `.select()` from a
delete (a 404 on success in production) would fail the suite.
- Tests: webhookCredentials gets its own file (rotation overlap, unreadable
secrets, owner scoping); the tier gate is covered for rotate, test and
resend as well as create and update.
Co-Authored-By: Claude Fable 5.1
---
.../functions/_shared/testing/fakeSupabase.ts | 7 +-
.../_shared/webhookCredentials.test.ts | 107 ++++++++++++++++++
.../functions/_shared/webhookCredentials.ts | 11 +-
.../functions/_shared/webhookTarget.test.ts | 10 ++
supabase/functions/_shared/webhookTarget.ts | 25 +++-
.../functions/webhook-endpoints/index.test.ts | 22 ++++
6 files changed, 173 insertions(+), 9 deletions(-)
create mode 100644 supabase/functions/_shared/webhookCredentials.test.ts
diff --git a/supabase/functions/_shared/testing/fakeSupabase.ts b/supabase/functions/_shared/testing/fakeSupabase.ts
index cb6ea1c8..cbf7c017 100644
--- a/supabase/functions/_shared/testing/fakeSupabase.ts
+++ b/supabase/functions/_shared/testing/fakeSupabase.ts
@@ -181,8 +181,9 @@ export class FakeQuery implements PromiseLike {
constructor(private rows: Row[], private uniqueIndexes: FakeUniqueIndex[] = []) {}
select(_cols?: string) {
- // `insert(...).select()` returns the inserted rows, as PostgREST does.
- if (this.insertRows) this.returning = true;
+ // `insert(...).select()` and `delete().select()` return the affected
+ // rows, as PostgREST does; without it both return no data.
+ if (this.insertRows || this.deleting) this.returning = true;
return this;
}
/** `delete().eq(...)`: removes the matching rows; `.select()` returns them. */
@@ -314,7 +315,7 @@ export class FakeQuery implements PromiseLike {
let matched = this.rows.filter((r) => this.filters.every((f) => f(r)));
if (this.deleting) {
for (const row of matched) this.rows.splice(this.rows.indexOf(row), 1);
- return { data: matched.map((r) => ({ ...r })), error: null };
+ return { data: this.returning ? matched.map((r) => ({ ...r })) : null, error: null };
}
if (this.patch) {
// Unique indexes hold for UPDATEs too, all or nothing (as Postgres).
diff --git a/supabase/functions/_shared/webhookCredentials.test.ts b/supabase/functions/_shared/webhookCredentials.test.ts
new file mode 100644
index 00000000..ad8147bf
--- /dev/null
+++ b/supabase/functions/_shared/webhookCredentials.test.ts
@@ -0,0 +1,107 @@
+import { assertEquals } from "jsr:@std/assert@1";
+import type { SupabaseClient } from "jsr:@supabase/supabase-js@2";
+import { FakeDb, fakeClient, type Row } from "./testing/fakeSupabase.ts";
+import { testWebhookSecret } from "./testing/webhookSecrets.ts";
+import { loadWebhookCredentials } from "./webhookCredentials.ts";
+
+const USER_A = "aaaaaaaa-0000-4000-8000-00000000000a";
+const USER_B = "bbbbbbbb-0000-4000-8000-00000000000b";
+const ENDPOINT = "eeeeeeee-0000-4000-8000-00000000000a";
+const NOW = new Date("2026-11-06T12:00:00.000Z");
+const CURRENT = testWebhookSecret("a");
+const PREVIOUS = testWebhookSecret("b");
+
+const encrypt = (plain: string) => `enc:test:${btoa(plain)}`;
+const decrypt = (stored: string) => {
+ if (stored === "enc:test:unreadable") return Promise.reject(new Error("oauth_token_decrypt_failed"));
+ return Promise.resolve(atob(stored.replace("enc:test:", "")));
+};
+
+function load(row: Row | null, overrides: { userId?: string; customHeaderName?: string | null } = {}) {
+ const db = new FakeDb({ webhook_endpoint_secrets: row ? [row] : [] });
+ return loadWebhookCredentials(
+ fakeClient(db) as unknown as SupabaseClient,
+ {
+ userId: overrides.userId ?? USER_A,
+ endpointId: ENDPOINT,
+ customHeaderName: overrides.customHeaderName ?? null,
+ now: NOW,
+ },
+ decrypt,
+ );
+}
+
+function secretRow(overrides: Row = {}): Row {
+ return {
+ endpoint_id: ENDPOINT,
+ user_id: USER_A,
+ signing_secret_enc: encrypt(CURRENT),
+ previous_signing_secret_enc: null,
+ previous_expires_at: null,
+ custom_header_value_enc: null,
+ ...overrides,
+ };
+}
+
+Deno.test("webhookCredentials: the current secret alone is returned when there is no rotation in progress", async () => {
+ const result = await load(secretRow());
+
+ assertEquals(result, { ok: true, credentials: { secrets: [CURRENT], customHeader: null } });
+});
+
+Deno.test("webhookCredentials: a previous secret inside its overlap is returned after the current one", async () => {
+ const result = await load(secretRow({
+ previous_signing_secret_enc: encrypt(PREVIOUS),
+ previous_expires_at: "2026-11-07T00:00:00.000Z",
+ }));
+
+ assertEquals(result.ok && result.credentials.secrets, [CURRENT, PREVIOUS]);
+});
+
+Deno.test("webhookCredentials: a previous secret past its overlap is not used", async () => {
+ const result = await load(secretRow({
+ previous_signing_secret_enc: encrypt(PREVIOUS),
+ previous_expires_at: "2026-11-06T11:59:59.000Z",
+ }));
+
+ assertEquals(result.ok && result.credentials.secrets, [CURRENT]);
+});
+
+Deno.test("webhookCredentials: an unreadable previous secret does not stop signing with the current one", async () => {
+ const result = await load(secretRow({
+ previous_signing_secret_enc: "enc:test:unreadable",
+ previous_expires_at: "2026-11-07T00:00:00.000Z",
+ }));
+
+ assertEquals(result, { ok: true, credentials: { secrets: [CURRENT], customHeader: null } });
+});
+
+Deno.test("webhookCredentials: an unreadable current secret is a failure, never an unsigned delivery", async () => {
+ const result = await load(secretRow({ signing_secret_enc: "enc:test:unreadable" }));
+
+ assertEquals(result, { ok: false, reason: "decrypt_failed" });
+});
+
+Deno.test("webhookCredentials: the header value is returned only with the name the endpoint carries", async () => {
+ const row = secretRow({ custom_header_value_enc: encrypt("Bearer receiver") });
+
+ const named = await load(row, { customHeaderName: "Authorization" });
+ const unnamed = await load(row, { customHeaderName: null });
+
+ assertEquals(named.ok && named.credentials.customHeader, { name: "Authorization", value: "Bearer receiver" });
+ assertEquals(unnamed.ok && unnamed.credentials.customHeader, null);
+});
+
+Deno.test("webhookCredentials: an unreadable header value is a failure, not a delivery without the header", async () => {
+ const result = await load(secretRow({ custom_header_value_enc: "enc:test:unreadable" }), {
+ customHeaderName: "Authorization",
+ });
+
+ assertEquals(result, { ok: false, reason: "decrypt_failed" });
+});
+
+Deno.test("webhookCredentials: another user's id finds nothing", async () => {
+ const result = await load(secretRow(), { userId: USER_B });
+
+ assertEquals(result, { ok: false, reason: "not_found" });
+});
diff --git a/supabase/functions/_shared/webhookCredentials.ts b/supabase/functions/_shared/webhookCredentials.ts
index bb62b4b3..8fdf4e3c 100644
--- a/supabase/functions/_shared/webhookCredentials.ts
+++ b/supabase/functions/_shared/webhookCredentials.ts
@@ -50,8 +50,15 @@ export async function loadWebhookCredentials(
row.previous_expires_at !== null &&
Date.parse(row.previous_expires_at) > params.now.getTime();
if (previousLive) {
- const previous = await decrypt(row.previous_signing_secret_enc!);
- if (previous) secrets.push(previous);
+ // The previous secret only smooths a rotation. If it cannot be read,
+ // deliveries still go out signed with the current one; failing here
+ // would stop every delivery over a secret that is being retired.
+ try {
+ const previous = await decrypt(row.previous_signing_secret_enc!);
+ if (previous) secrets.push(previous);
+ } catch {
+ // Signed with the current secret only.
+ }
}
let customHeader: WebhookCredentials['customHeader'] = null;
diff --git a/supabase/functions/_shared/webhookTarget.test.ts b/supabase/functions/_shared/webhookTarget.test.ts
index 3660dc78..69d19436 100644
--- a/supabase/functions/_shared/webhookTarget.test.ts
+++ b/supabase/functions/_shared/webhookTarget.test.ts
@@ -153,6 +153,16 @@ Deno.test("webhookTarget: one private address among public ones is a refusal", a
}
});
+Deno.test("webhookTarget: a resolver that never answers fails closed at the deadline", async () => {
+ const hanging: DnsResolver = () => new Promise(() => {});
+ const started = Date.now();
+
+ const target = await resolveWebhookTarget("https://hooks.example.com/in", OWN_HOSTS, hanging, 30);
+
+ assertEquals(target.ok ? "ok" : target.code, "dns_failed");
+ assert(Date.now() - started < 2000);
+});
+
Deno.test("webhookTarget: a resolver error or an empty answer fails closed", async () => {
const failing: DnsResolver = () => Promise.reject(new Error("resolver down"));
diff --git a/supabase/functions/_shared/webhookTarget.ts b/supabase/functions/_shared/webhookTarget.ts
index cb0078a5..1152ea63 100644
--- a/supabase/functions/_shared/webhookTarget.ts
+++ b/supabase/functions/_shared/webhookTarget.ts
@@ -30,6 +30,8 @@
export const WEBHOOK_URL_MAX_LENGTH = 2048;
export const WEBHOOK_REQUEST_TIMEOUT_MS = 10_000;
+/** A resolver that does not answer in this long counts as a failed lookup. */
+export const WEBHOOK_DNS_TIMEOUT_MS = 5_000;
export type WebhookTargetRejection =
| 'url_invalid'
@@ -277,10 +279,19 @@ export type ResolvedWebhookTarget =
* One private answer among public ones is a refusal, since the connection
* may use any of them. A resolver error, or no address at all, fails closed.
*/
+function withDeadline(work: Promise, ms: number): Promise {
+ let timer: ReturnType | undefined;
+ const deadline = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error('dns_timeout')), ms);
+ });
+ return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
+}
+
export async function resolveWebhookTarget(
raw: unknown,
ownHosts: readonly string[],
resolveDns: DnsResolver,
+ dnsTimeoutMs: number = WEBHOOK_DNS_TIMEOUT_MS,
): Promise {
const parsed = parseWebhookUrl(raw, ownHosts);
if (!parsed.ok) return parsed;
@@ -288,10 +299,16 @@ export async function resolveWebhookTarget(
let addresses: string[];
try {
- const [v4, v6] = await Promise.all([
- resolveDns(parsed.hostname, 'A'),
- resolveDns(parsed.hostname, 'AAAA'),
- ]);
+ // The request timeout only starts once the fetch does; without a
+ // deadline here a resolver that hangs would hold a delivery, and the
+ // worker pass it belongs to, for as long as it liked.
+ const [v4, v6] = await withDeadline(
+ Promise.all([
+ resolveDns(parsed.hostname, 'A'),
+ resolveDns(parsed.hostname, 'AAAA'),
+ ]),
+ dnsTimeoutMs,
+ );
addresses = [...v4, ...v6];
} catch {
return { ok: false, code: 'dns_failed' };
diff --git a/supabase/functions/webhook-endpoints/index.test.ts b/supabase/functions/webhook-endpoints/index.test.ts
index 3fbd6501..e9a30499 100644
--- a/supabase/functions/webhook-endpoints/index.test.ts
+++ b/supabase/functions/webhook-endpoints/index.test.ts
@@ -417,6 +417,28 @@ Deno.test("webhook-endpoints: a lapsed user can still pause and delete, but not
assertEquals(resumed.outbound.length, 0);
});
+Deno.test("webhook-endpoints: rotate, test and resend are refused below FLAME and change nothing", async () => {
+ for (const action of ["rotate_secret", "test", "resend_all"]) {
+ // Arrange
+ const before = endpointRow();
+ const secretBefore = await secretRow();
+ const { call, db, outbound } = harness({
+ tier: "EMBER",
+ tables: { webhook_endpoints: [{ ...before }], webhook_endpoint_secrets: [{ ...secretBefore }] },
+ });
+
+ // Act
+ const response = await call({ action, endpointId: ENDPOINT_A });
+
+ // Assert
+ assertEquals(response.status, 402, action);
+ assertEquals(db.rows("webhook_endpoints"), [before], action);
+ assertEquals(db.rows("webhook_endpoint_secrets"), [secretBefore], action);
+ assertEquals(outbound.length, 0, action);
+ assertEquals(db.rpcCallNames(), [], action);
+ }
+});
+
Deno.test("webhook-endpoints: pausing a disabled endpoint keeps the reason it was switched off for", async () => {
const { call, db } = harness({
tables: {