@marktiderman/genesis-supabase 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +128 -7
  2. package/dist/blocks.d.ts +18 -1
  3. package/dist/blocks.js +1 -1
  4. package/dist/chunk-7SCMHKCR.js +33 -0
  5. package/dist/chunk-7SCMHKCR.js.map +1 -0
  6. package/dist/{chunk-ONBOLMXH.js → chunk-DYHH2G4A.js} +37 -3
  7. package/dist/chunk-DYHH2G4A.js.map +1 -0
  8. package/dist/chunk-XGAXPUFY.js +124 -0
  9. package/dist/chunk-XGAXPUFY.js.map +1 -0
  10. package/dist/{index-Ds0tO9WP.d.ts → index-D73YuwEY.d.ts} +4 -4
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/jobs.d.ts +3 -1
  15. package/dist/jobs.js +48 -34
  16. package/dist/jobs.js.map +1 -1
  17. package/dist/native.d.ts +2 -2
  18. package/dist/runner.d.ts +179 -0
  19. package/dist/runner.js +3 -0
  20. package/dist/runner.js.map +1 -0
  21. package/dist/web-handoff-path-C_EEl_BC.d.ts +16 -0
  22. package/dist/web-handoff-server.d.ts +225 -0
  23. package/dist/web-handoff-server.js +262 -0
  24. package/dist/web-handoff-server.js.map +1 -0
  25. package/dist/web-handoff.d.ts +133 -0
  26. package/dist/web-handoff.js +104 -0
  27. package/dist/web-handoff.js.map +1 -0
  28. package/migrations/0009_genesis_owner_access.sql +89 -0
  29. package/migrations/0014_genesis_feature_registry_hardening.sql +124 -0
  30. package/migrations/0015_genesis_web_handoff.sql +270 -0
  31. package/migrations/tests/0009_genesis_owner_access.test.sql +70 -0
  32. package/migrations/tests/0014_genesis_feature_registry_hardening.test.sql +54 -0
  33. package/migrations/tests/0015_genesis_web_handoff.test.sql +203 -0
  34. package/package.json +88 -3
  35. package/dist/chunk-ONBOLMXH.js.map +0 -1
package/README.md CHANGED
@@ -595,11 +595,13 @@ Migration `0008_genesis_feature_registry.sql` (needs 0004) gives the feature gat
595
595
  way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
596
596
 
597
597
  - **The mirror.** `features` and `feature_flags` copy `features.json`, written only by `sync_feature_registry`
598
- with the service key. Run it from **production deployments only**, when one starts serving, with
599
- `Date.now()` as the version (not the build time), so an instant rollback syncs as the newest. The same
600
- registry again changes nothing; an empty registry, or one dropping more than a fifth of the features, is
601
- refused unless `allowShrink`. Nothing is deleted: a removed feature or flag is marked `in_registry = false`,
602
- and a flag's tenant values stay.
598
+ with the service key. Run it from **production deployments only**, with the **build time** as the version.
599
+ Vercel sets `VERCEL_ENV=production` on every production deployment, old ones included, so an instance-start
600
+ time would let a cold start of an old URL sync a stale registry; a build time can't. After an instant
601
+ rollback the database keeps the newer registry until the next deploy (only SQL's status and entitlement
602
+ checks read it). The same registry again changes nothing; an empty registry, or one dropping more than a
603
+ fifth of the features, is refused unless `allowShrink`. Nothing is deleted: a removed feature or flag is
604
+ marked `in_registry = false`; its tenant values stay, and (0014) its platform value is cleared.
603
605
  - **Paid access.** `feature_entitlements` (tenant, feature, source, `active`, optional `ends_at`). Your billing
604
606
  webhook writes it with the service key.
605
607
  - **Flag values.** `tenant_flag_values` overrides a flag's default for one tenant (service key).
@@ -608,7 +610,14 @@ way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
608
610
  over many rows use the once-per-statement pair instead:
609
611
  `using ((select feature_shipped('exports')) and team_id = any (array(select feature_entitled_tenants('exports'))))`
610
612
  (drop the second half for a free feature). Switches and flags are not checked here: server code enforces them.
611
- - **Reading features.** Signed-in people (not anonymous sign-ins) read shipped, customer-facing features, and
613
+ - **Who is asking (0014).** Server code is told apart from a person by the request's role
614
+ (`current_setting('role')`, set per request by PostgREST), never by `request.jwt.claims`: a role that bypasses
615
+ row security, or a connection that never switched role, is server code; everyone else must be a member. So any database login that
616
+ connects directly, without switching role, is trusted as server code: give people API access only, never a
617
+ direct database login. The
618
+ functions use `auth.jwt()` and `auth.uid()`, so they need Supabase's `auth` schema (not bare Postgres).
619
+ - **Reading features.** Signed-in people (not anonymous sign-ins) read shipped, customer-facing features (and
620
+ `feature_shipped` answers them only for those), and
612
621
  only `id, name, status, visibility, access_plan, platforms, in_registry`; the full record stays server side.
613
622
  - **The snapshot's input.** `feature_gate_state(tenant)` returns the tenant's switches off, entitlements and
614
623
  flag values, to its members (with their own JWT, so browsers and extensions can call it) and the service role.
@@ -619,7 +628,7 @@ import { gateSnapshot } from "@marktiderman/genesis-features/gate";
619
628
  import registry from "../features.json";
620
629
 
621
630
  // When a production deployment starts serving (never from a preview):
622
- if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
631
+ if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });
623
632
 
624
633
  const state = await featureGateState(supabase, teamId); // per session
625
634
  const snapshot = gateSnapshot({ features, flags }, { platform: "web", ...state }, { version: BUILD_TIME });
@@ -668,6 +677,15 @@ const report = await runJobs(admin, {
668
677
  - **Settle failures.** If recording an outcome fails, the job is counted as `unsettled` and comes
669
678
  back when its lease runs out. The run carries on, and only a failed claim throws.
670
679
 
680
+ **One engine.** `runJobs` runs on `createRunner` from `@marktiderman/genesis-supabase/runner`, the
681
+ outbox engine genesis-notifications' push and email and genesis-forms' destinations also run on.
682
+ The engine claims a batch, sends it (in groups, `concurrency` at a time), turns each result into an
683
+ outcome (`sent`, `filtered`, `skipped`, `retry` with jittered backoff or a Retry-After deferral up
684
+ to `maxDeferrals`, `failed`, with `disable` on a 410) and records it, never throwing for one job.
685
+ It has no dependencies (no `@supabase/supabase-js`, no Node built-ins), so a package can bundle it,
686
+ and it knows nothing about recipients. For `runJobs` the queue keeps the attempts and the retry
687
+ times, as above. `@marktiderman/genesis-notifications/runner` still re-exports it, deprecated.
688
+
671
689
  **One job route.** `createJobsHandler` runs the job the route names, but only if the request passes
672
690
  one of two constant-time checks:
673
691
 
@@ -726,6 +744,109 @@ route instead: it sends GET with the bearer.
726
744
  **Access.** The queue table has RLS on, no policies, and no grants to `anon` or `authenticated`.
727
745
  Every function is granted by name to `service_role` only.
728
746
 
747
+ ## Continue on the web, already signed in (the web-handoff block)
748
+
749
+ Some work a native app leaves to the web app (editing a form's questions, say). The web-handoff
750
+ block opens that web page signed in as the same person, with no sign-in screen:
751
+
752
+ 1. **App:** `openOnWeb(path, …)` from `@marktiderman/genesis-native/web-handoff` posts `{ path }` to
753
+ the app's mint route with `Authorization: Bearer <access token>`.
754
+ 2. **Mint** (`createWebHandoff(...).mint`, or `mintWebHandoff` for a person you verified another
755
+ way): verifies the bearer with `auth.getUser`, checks the path with `appRelativePath`, and
756
+ records a handoff (`genesis_web_handoff_issue`): the person, the path, the app session it came
757
+ from (the bearer's `session_id`), a 60-second expiry and a SHA-256 digest of a random 256-bit
758
+ token. It returns `<origin>/auth/handoff#t=<token>&next=<path>`; the fragment never reaches a
759
+ server. Ten links a person a minute, counted in the database.
760
+ 3. **Page** (`/auth/handoff`): `takeWebHandoffFragment()` reads the fragment and removes it with
761
+ `history.replaceState` before analytics or error reporting load. `completeWebHandoff` checks
762
+ who is signed in here with `auth.getUser` (a session ended elsewhere counts as nobody and is
763
+ cleared), then **claims** the handoff (`genesis_web_handoff_claim`): once, unexpired. The claim
764
+ returns whose link it is and a **continue nonce** that works once, for 30 seconds. Nothing that
765
+ signs anyone in exists yet.
766
+ 4. **Same person already signed in:** straight to `next`; nothing is ever minted.
767
+ **Otherwise:** "Continue as {email}?".
768
+ - **Continue** spends the nonce (`genesis_web_handoff_continue`: once, in time, not after
769
+ Cancel). Only now does the server ask Supabase Auth for a sign-in token for that person's own
770
+ email (`auth.admin.generateLink({ type: "magiclink" })`, which sends nothing). The page signs
771
+ any other person out locally, exchanges the token at once with
772
+ `auth.verifyOtp({ token_hash, type: "email" })`, checks the verified user is the link's, and
773
+ goes to `next`, checked again. It then reports the new session (`bind`, its access token as
774
+ the bearer), so the app's sign-out can end it.
775
+ - **Cancel** burns the nonce (`genesis_web_handoff_discard`) and signs out locally anyone else
776
+ who was signed in here, so the page never leaves someone in the app as another person. Show
777
+ "You can close this window".
778
+ - **A page left open** never gets a sign-in token: the nonce runs out.
779
+ 5. **App sign-out:** `signOutOnWeb` (genesis-native) posts the app's bearer to the sign-out route
780
+ before the app signs out; `genesis_web_handoff_revoke_sessions` deletes the `auth.sessions` rows
781
+ of the web sessions handed off from that app session, and only those (never the person's other
782
+ devices; never a global sign-out).
783
+
784
+ ```ts
785
+ // Server routes (the service-role client, server only)
786
+ import { createWebHandoff } from "@marktiderman/genesis-supabase/web-handoff/server";
787
+ const handoff = createWebHandoff({ admin: supabaseAdmin });
788
+ // POST /api/auth/handoff → handoff.mint(request)
789
+ // POST /api/auth/redeem-handoff → handoff.redeem(request) (claim, continue, discard, bind)
790
+ // POST /api/auth/handoff-signout → handoff.signOut(request)
791
+
792
+ // The page
793
+ import { completeWebHandoff, takeWebHandoffFragment } from "@marktiderman/genesis-supabase/web-handoff";
794
+ const step = await completeWebHandoff({ supabase, fragment: takeWebHandoffFragment() });
795
+ // "done" → go to step.next; "confirm" → ask, then step.continue() or step.cancel();
796
+ // "cancelled" → "You can close this window"; "failed" → step.reason, sign in keeping step.next
797
+ ```
798
+
799
+ Install: copy `migrations/0015_genesis_web_handoff.sql` into `supabase/migrations/` under a new
800
+ timestamped name and its pgTAP test into `supabase/tests/database/`.
801
+
802
+ The page must send `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and
803
+ `Content-Security-Policy: frame-ancestors 'none'`, render without analytics, and call
804
+ `takeWebHandoffFragment` before any third-party script runs.
805
+
806
+ ### Lifetimes
807
+
808
+ - **The handoff link:** 60 seconds and one claim (`ttlSeconds`, 10 to 300).
809
+ - **The continue nonce:** 30 seconds and one use (`continueSeconds`, 5 to 120); Cancel burns it.
810
+ - **Supabase's sign-in token:** minted only on Continue and exchanged by the page at once. It is
811
+ single use and would expire after the project's **Email OTP Expiration** (`mailer_otp_exp`;
812
+ default one hour; Authentication → Sign In / Providers → Email). The block doesn't rely on that
813
+ setting, which is project-wide. Minting one replaces any magic link or email code that person
814
+ has outstanding.
815
+ - **A web session the app's sign-out ended:** its `auth.sessions` row is gone, so it can't refresh
816
+ and `auth.getUser` refuses it; Supabase documents that its access token still verifies locally
817
+ until it expires (the project's JWT expiry, one hour by default).
818
+
819
+ ### Choices, and why
820
+
821
+ - **Claim, then Continue.** Minting Supabase's token when the page opened would leave a working
822
+ sign-in token in a page someone cancelled or walked away from, for the whole OTP expiry. The
823
+ token exists only after the person chooses Continue, within 30 seconds of opening the link.
824
+ - **A record per handoff, not a signed timestamp.** A signed `iat` can't stop someone holding
825
+ Supabase's token hash from exchanging it directly; here there is no token hash to hold until
826
+ Continue.
827
+ - **Ask first unless it's the same person.** Anyone can mint a link for their own account and
828
+ send it to someone else (login CSRF); "Continue as {email}?" makes that visible. The in-app
829
+ browser keeps its storage, so the person taps Continue once and later handoffs go straight in.
830
+ - **Cancel signs the other person out.** Leaving the page (or opening Home) as whoever was signed
831
+ in before could put someone in the app as another person: an in-app browser keeps the previous
832
+ person's session after the app switched accounts. Signing out locally is the safe default; the
833
+ cost is that a person who cancels a link someone else sent them is signed out of this browser.
834
+ - **Ending the web session on app sign-out by deleting its `auth.sessions` row.** Supabase's docs:
835
+ "When a user signs out, the sessions affected by the sign-out are removed from the database";
836
+ a missing row means signed out. `auth.admin.signOut` needs that session's JWT, which the server
837
+ doesn't keep; `scope: "global"` would sign out every device. The session id comes from the
838
+ web session's verified access token (`session_id` claim), bound to the handoff once, within two
839
+ minutes of Continue, for the same person.
840
+ - **Magic link over passing the session.** Supabase has no first-party way to move a session to
841
+ another client. Sending the app's refresh token would share one session between app and
842
+ browser, and refresh-token rotation would sign one of them out. A magic-link token gives the
843
+ browser its own session.
844
+ - **`type: "email"` in `verifyOtp`.** Supabase marks `magiclink` deprecated for `verifyOtp` and
845
+ documents `generateLink({ type: "magiclink" })` then `verifyOtp({ token_hash, type: "email" })`.
846
+ The exchange is a POST from the page; it needs no PKCE code verifier, so a PKCE client works.
847
+ - **No email, no handoff.** Supabase's link sign-in is by email. A phone-only account gets a
848
+ 409 `no_email` with a `fallbackUrl` (the page, signed out), and `openOnWeb` opens that instead.
849
+
729
850
  ## Testing your schema's data contract (genesis_testing)
730
851
 
731
852
  `sql/testing/genesis_testing.sql` is a pgTAP kit that checks your own tables and functions keep the
package/dist/blocks.d.ts CHANGED
@@ -30,5 +30,22 @@ declare const featureMirrorBlock: _marktiderman_genesis_features_blocks.BlockDef
30
30
  * @stability Beta
31
31
  */
32
32
  declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs", never>;
33
+ /**
34
+ * The web handoff block: continue on the web, already signed in. The routes are
35
+ * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native
36
+ * app calls `openOnWeb` from genesis-native.
37
+ *
38
+ * @stability Beta
39
+ */
40
+ declare const webHandoffBlock: _marktiderman_genesis_features_blocks.BlockDef<"web-handoff", never>;
41
+ /**
42
+ * The owner-access block: the contract every Genesis block with owned rows
43
+ * calls in its policies. Two fail-closed wrappers over the app's hooks
44
+ * (`genesis_owner_can`, `genesis_readable_owners`): a missing or broken hook
45
+ * means no.
46
+ *
47
+ * @stability Experimental
48
+ */
49
+ declare const ownerAccessBlock: _marktiderman_genesis_features_blocks.BlockDef<"owner-access", never>;
33
50
 
34
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
51
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock, webHandoffBlock };
package/dist/blocks.js CHANGED
@@ -1,3 +1,3 @@
1
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
1
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock, webHandoffBlock } from './chunk-DYHH2G4A.js';
2
2
  //# sourceMappingURL=blocks.js.map
3
3
  //# sourceMappingURL=blocks.js.map
@@ -0,0 +1,33 @@
1
+ // src/web-handoff-path.ts
2
+ var BASE = "https://handoff.invalid";
3
+ var UNSAFE = /[\\\u0000-\u0020\u007f-\u009f]/;
4
+ var UNSAFE_DECODED = /[\\\u0000-\u001f\u007f-\u009f]/;
5
+ function appRelativePath(value) {
6
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return null;
7
+ if (value[0] !== "/" || value[1] === "/" || UNSAFE.test(value)) return null;
8
+ let decoded = value;
9
+ for (let layer = 0; layer < 3; layer++) {
10
+ let next;
11
+ try {
12
+ next = decodeURIComponent(decoded);
13
+ } catch {
14
+ return null;
15
+ }
16
+ if (next === decoded) break;
17
+ decoded = next;
18
+ if (decoded[0] !== "/" || decoded[1] === "/" || UNSAFE_DECODED.test(decoded)) return null;
19
+ }
20
+ let url;
21
+ try {
22
+ url = new URL(value, BASE);
23
+ } catch {
24
+ return null;
25
+ }
26
+ if (url.origin !== BASE) return null;
27
+ const path = url.pathname + url.search + url.hash;
28
+ return path.startsWith("//") ? null : path;
29
+ }
30
+
31
+ export { appRelativePath };
32
+ //# sourceMappingURL=chunk-7SCMHKCR.js.map
33
+ //# sourceMappingURL=chunk-7SCMHKCR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web-handoff-path.ts"],"names":[],"mappings":";AAMA,IAAM,IAAA,GAAO,yBAAA;AAIb,IAAM,MAAA,GAAS,gCAAA;AAGf,IAAM,cAAA,GAAiB,gCAAA;AAUhB,SAAS,gBAAgB,KAAA,EAA+B;AAC7D,EAAA,IAAI,OAAO,UAAU,QAAA,IAAY,KAAA,CAAM,WAAW,CAAA,IAAK,KAAA,CAAM,MAAA,GAAS,IAAA,EAAM,OAAO,IAAA;AACnF,EAAA,IAAI,KAAA,CAAM,CAAC,CAAA,KAAM,GAAA,IAAO,KAAA,CAAM,CAAC,CAAA,KAAM,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,IAAA;AACvE,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,KAAA,IAAS,KAAA,GAAQ,CAAA,EAAG,KAAA,GAAQ,CAAA,EAAG,KAAA,EAAA,EAAS;AACtC,IAAA,IAAI,IAAA;AACJ,IAAA,IAAI;AACF,MAAA,IAAA,GAAO,mBAAmB,OAAO,CAAA;AAAA,IACnC,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,IAAI,SAAS,OAAA,EAAS;AACtB,IAAA,OAAA,GAAU,IAAA;AACV,IAAA,IAAI,OAAA,CAAQ,CAAC,CAAA,KAAM,GAAA,IAAO,OAAA,CAAQ,CAAC,CAAA,KAAM,GAAA,IAAO,cAAA,CAAe,IAAA,CAAK,OAAO,CAAA,EAAG,OAAO,IAAA;AAAA,EACvF;AACA,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAI,GAAA,CAAI,KAAA,EAAO,IAAI,CAAA;AAAA,EAC3B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,IAAA,EAAM,OAAO,IAAA;AAChC,EAAA,MAAM,IAAA,GAAO,GAAA,CAAI,QAAA,GAAW,GAAA,CAAI,SAAS,GAAA,CAAI,IAAA;AAC7C,EAAA,OAAO,IAAA,CAAK,UAAA,CAAW,IAAI,CAAA,GAAI,IAAA,GAAO,IAAA;AACxC","file":"chunk-7SCMHKCR.js","sourcesContent":["/**\n * The one check for a web handoff's destination, used before a link is minted\n * and again after the person is signed in: the path must stay on the app's\n * own origin. Shared by `/web-handoff` (the page) and `/web-handoff/server`.\n */\n\nconst BASE = \"https://handoff.invalid\";\n// A backslash (browsers read `/\\host` as `//host`), whitespace and control characters (browsers\n// drop tabs and newlines from URLs, so `/\\t/host` becomes `//host`).\n// eslint-disable-next-line no-control-regex -- matching control characters is the point.\nconst UNSAFE = /[\\\\\\u0000-\\u0020\\u007f-\\u009f]/;\n// After decoding, a space is ordinary text; the rest still is not.\n// eslint-disable-next-line no-control-regex -- as above.\nconst UNSAFE_DECODED = /[\\\\\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * `value` as a path on this app (`/clients/1/forms?tab=questions`), normalized, or `null` when it\n * could leave the origin or isn't a path: anything without a single leading `/`, `//host`,\n * `/\\host`, a scheme (`javascript:`, `https:`), whitespace or control characters, and the same\n * tricks percent-encoded (`/%2F%2Fhost`, `/%5Chost`, `/%09/host`, up to three layers).\n *\n * @stability Beta\n */\nexport function appRelativePath(value: unknown): string | null {\n if (typeof value !== \"string\" || value.length === 0 || value.length > 2048) return null;\n if (value[0] !== \"/\" || value[1] === \"/\" || UNSAFE.test(value)) return null;\n let decoded = value;\n for (let layer = 0; layer < 3; layer++) {\n let next: string;\n try {\n next = decodeURIComponent(decoded);\n } catch {\n return null;\n }\n if (next === decoded) break;\n decoded = next;\n if (decoded[0] !== \"/\" || decoded[1] === \"/\" || UNSAFE_DECODED.test(decoded)) return null;\n }\n let url: URL;\n try {\n url = new URL(value, BASE);\n } catch {\n return null;\n }\n if (url.origin !== BASE) return null;\n const path = url.pathname + url.search + url.hash;\n return path.startsWith(\"//\") ? null : path;\n}\n"]}
@@ -73,6 +73,11 @@ var featureMirrorBlock = defineBlock({
73
73
  package: PACKAGE,
74
74
  file: "migrations/0008_genesis_feature_registry.sql",
75
75
  test: "migrations/tests/0008_genesis_feature_registry.test.sql"
76
+ },
77
+ {
78
+ package: PACKAGE,
79
+ file: "migrations/0014_genesis_feature_registry_hardening.sql",
80
+ test: "migrations/tests/0014_genesis_feature_registry_hardening.test.sql"
76
81
  }
77
82
  ],
78
83
  privacy: {
@@ -90,7 +95,36 @@ var jobsBlock = defineBlock({
90
95
  privacy: { notes: ["Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days."] }
91
96
  }
92
97
  });
98
+ var webHandoffBlock = defineBlock({
99
+ id: "web-handoff",
100
+ platforms: ["web", "native"],
101
+ contributes: {
102
+ migrations: [
103
+ { package: PACKAGE, file: "migrations/0015_genesis_web_handoff.sql", test: "migrations/tests/0015_genesis_web_handoff.test.sql" }
104
+ ],
105
+ privacy: {
106
+ notes: [
107
+ "Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token."
108
+ ]
109
+ }
110
+ }
111
+ });
112
+ var ownerAccessBlock = defineBlock({
113
+ id: "owner-access",
114
+ requires: ["tenant-features"],
115
+ platforms: ["web", "native"],
116
+ contributes: {
117
+ migrations: [
118
+ {
119
+ package: PACKAGE,
120
+ file: "migrations/0009_genesis_owner_access.sql",
121
+ test: "migrations/tests/0009_genesis_owner_access.test.sql"
122
+ }
123
+ ],
124
+ privacy: { notes: ["Stores nothing; it only asks the app's hooks who may read and write."] }
125
+ }
126
+ });
93
127
 
94
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
95
- //# sourceMappingURL=chunk-ONBOLMXH.js.map
96
- //# sourceMappingURL=chunk-ONBOLMXH.js.map
128
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock, webHandoffBlock };
129
+ //# sourceMappingURL=chunk-DYHH2G4A.js.map
130
+ //# sourceMappingURL=chunk-DYHH2G4A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/blocks.ts"],"names":[],"mappings":";;;AAQA,IAAM,OAAA,GAAU,gCAAA;AAST,IAAM,eAAe,WAAA,CAAY;AAAA,EACtC,EAAA,EAAI,SAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,8CAAA;AAAA,QACN,IAAA,EAAM;AAAA,OACR;AAAA;AAAA,MAEA;AAAA,QACE,OAAA,EAAS,OAAA;AAAA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,CAAC","file":"chunk-DYHH2G4A.js","sourcesContent":["/**\n * The blocks this package carries the server half of, as `defineBlock`\n * declarations: what each needs in the database, and what it means for the\n * stores' privacy forms. The functions themselves (`deleteMyAccount`,\n * `tenantFeatures`, …) don't change.\n */\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\n\nconst PACKAGE = \"@marktiderman/genesis-supabase\";\n\n/**\n * The account block: sign-in, profile and in-app account deletion. Its\n * screens are the app's (or genesis-ui-native's `AuthScreen`); this names its\n * migrations and its data.\n *\n * @stability Beta\n */\nexport const accountBlock = defineBlock({\n id: \"account\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0001_genesis_account_deletion.sql\",\n test: \"migrations/tests/0001_genesis_account_deletion.test.sql\",\n },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n {\n package: PACKAGE,\n file: \"migrations/0003_genesis_apple_token_revocation.sql\",\n test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\",\n },\n ],\n privacy: {\n collects: [\n {\n type: \"email address\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"user id\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"name\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n ],\n notes: [\n \"People delete their account from inside the app; their login and the rows that cascade from it go with it.\",\n \"With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted.\",\n ],\n },\n },\n});\n\n/**\n * The tenant features block: per-tenant on/off switches for shipped\n * features, set by the tenant's admins with a reason.\n *\n * @stability Beta\n */\nexport const tenantFeaturesBlock = defineBlock({\n id: \"tenant-features\",\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0004_genesis_tenant_features.sql\",\n test: \"migrations/tests/0004_genesis_tenant_features.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\",\n ],\n },\n },\n});\n\n/**\n * The feature registry block: the registry mirrored into the app's database\n * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,\n * for the feature gate. Needs the tenant features block.\n *\n * @stability Beta\n */\nexport const featureMirrorBlock = defineBlock({\n id: \"feature-mirror\",\n requires: [\"tenant-features\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0008_genesis_feature_registry.sql\",\n test: \"migrations/tests/0008_genesis_feature_registry.test.sql\",\n },\n {\n package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants hold which paid features and flag values; no personal data.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n\n/**\n * The web handoff block: continue on the web, already signed in. The routes are\n * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native\n * app calls `openOnWeb` from genesis-native.\n *\n * @stability Beta\n */\nexport const webHandoffBlock = defineBlock({\n id: \"web-handoff\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0015_genesis_web_handoff.sql\", test: \"migrations/tests/0015_genesis_web_handoff.test.sql\" },\n ],\n privacy: {\n notes: [\n \"Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token.\",\n ],\n },\n },\n});\n\n/**\n * The owner-access block: the contract every Genesis block with owned rows\n * calls in its policies. Two fail-closed wrappers over the app's hooks\n * (`genesis_owner_can`, `genesis_readable_owners`): a missing or broken hook\n * means no.\n *\n * @stability Experimental\n */\nexport const ownerAccessBlock = defineBlock({\n id: \"owner-access\",\n requires: [\"tenant-features\"],\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0009_genesis_owner_access.sql\",\n test: \"migrations/tests/0009_genesis_owner_access.test.sql\",\n },\n ],\n privacy: { notes: [\"Stores nothing; it only asks the app's hooks who may read and write.\"] },\n },\n});\n"]}
@@ -0,0 +1,124 @@
1
+ // src/runner.ts
2
+ var DEFAULT_MAX_ATTEMPTS = 8;
3
+ var DEFAULT_MAX_DEFERRALS = 24;
4
+ var DEFAULT_BATCH_SIZE = 25;
5
+ function defaultBackoff(attempt, random) {
6
+ const nominal = Math.min(24 * 3600, 300 * 4 ** Math.max(0, attempt - 1));
7
+ const r = typeof random === "function" ? random() : Math.random();
8
+ return Math.round(nominal * (0.8 + 0.4 * Math.min(1, Math.max(0, r))));
9
+ }
10
+ function jobOutcome(result, attempt, options = {}) {
11
+ if (result.ok) {
12
+ if (result.notSent) return { status: "skipped", reason: result.notSent.slice(0, 500) };
13
+ return result.alreadyThere ? { status: "sent", alreadyThere: true } : { status: "sent" };
14
+ }
15
+ const http = result.status !== void 0 ? { httpStatus: result.status } : {};
16
+ if (result.disable) return { status: "failed", error: result.error, ...http, disable: true };
17
+ if (!result.retryable) return { status: "failed", error: result.error, ...http };
18
+ const now = options.now ?? Date.now();
19
+ if (result.retryAfterSeconds !== void 0 && (options.deferrals ?? 0) < (options.maxDeferrals ?? DEFAULT_MAX_DEFERRALS)) {
20
+ const seconds2 = Math.max(1, Math.ceil(result.retryAfterSeconds));
21
+ return { status: "retry", error: result.error, retryAt: new Date(now + seconds2 * 1e3), retryAfterSeconds: seconds2, counted: false, ...http };
22
+ }
23
+ const max = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
24
+ if (attempt >= max) return { status: "failed", error: `${result.error} (gave up after ${attempt} attempts)`.slice(0, 500), ...http };
25
+ const seconds = Math.max(1, Math.ceil((options.backoff ?? defaultBackoff)(attempt)));
26
+ return { status: "retry", error: result.error, retryAt: new Date(now + seconds * 1e3), retryAfterSeconds: seconds, counted: true, ...http };
27
+ }
28
+ function failureOf(error) {
29
+ const e = error;
30
+ if (e && typeof e === "object" && typeof e.retryable === "boolean" && typeof e.message === "string") {
31
+ return {
32
+ ok: false,
33
+ retryable: e.disable === true ? false : e.retryable,
34
+ error: e.message.slice(0, 500),
35
+ ...typeof e.retryAfterSeconds === "number" ? { retryAfterSeconds: e.retryAfterSeconds } : {},
36
+ ...typeof e.status === "number" ? { status: e.status } : {},
37
+ ...e.disable === true ? { disable: true } : {}
38
+ };
39
+ }
40
+ const timeout = e && typeof e === "object" && (e.name === "TimeoutError" || e.name === "AbortError");
41
+ return { ok: false, retryable: true, error: timeout ? "Timed out" : "Unexpected error" };
42
+ }
43
+ function createRunner(options) {
44
+ const log = (message) => {
45
+ try {
46
+ options.log?.(message);
47
+ } catch {
48
+ }
49
+ };
50
+ const label = (job) => options.label?.(job) ?? `Job ${job.id}`;
51
+ const recordLabel = (job) => options.recordLabel?.(job) ?? `job ${job.id}`;
52
+ const now = () => options.now?.() ?? Date.now();
53
+ return {
54
+ async run(runOptions = {}) {
55
+ const report = { claimed: 0, sent: 0, filtered: 0, skipped: 0, retrying: 0, deferred: 0, failed: 0, stale: 0, unrecorded: 0 };
56
+ const limit = runOptions.limit ?? options.batchSize ?? DEFAULT_BATCH_SIZE;
57
+ const claimed = await options.claim({ limit, filter: runOptions.filter });
58
+ report.claimed = claimed.length;
59
+ const groups = /* @__PURE__ */ new Map();
60
+ claimed.forEach((job, i) => {
61
+ const key = options.group ? options.group(job) : `\0${i}`;
62
+ const list = groups.get(key) ?? [];
63
+ list.push(job);
64
+ groups.set(key, list);
65
+ });
66
+ const runGroup = async (group) => {
67
+ let results;
68
+ try {
69
+ results = await options.send(group, { signal: runOptions.signal });
70
+ if (results.length !== group.length) throw new Error("send answered the wrong number of results");
71
+ } catch (error) {
72
+ const failure = failureOf(error);
73
+ results = group.map(() => failure);
74
+ }
75
+ const at = now();
76
+ await Promise.all(
77
+ group.map(async (job, i) => {
78
+ const result = results[i];
79
+ const outcome = result === "filtered" ? { status: "filtered" } : jobOutcome(result, job.attempt, {
80
+ now: at,
81
+ maxAttempts: options.maxAttempts,
82
+ backoff: options.backoff,
83
+ deferrals: job.deferrals,
84
+ maxDeferrals: options.maxDeferrals
85
+ });
86
+ if (outcome.status === "failed" || outcome.status === "retry") {
87
+ log(`${label(job)} ${outcome.status === "failed" ? "failed" : "will be retried"}: ${outcome.error}`);
88
+ } else if (outcome.status === "skipped") {
89
+ log(`${label(job)} skipped: ${outcome.reason}`);
90
+ }
91
+ let recorded;
92
+ try {
93
+ recorded = await options.record(job, outcome);
94
+ } catch {
95
+ report.unrecorded++;
96
+ log(`Recording ${recordLabel(job)} failed`);
97
+ return;
98
+ }
99
+ if (recorded === false) report.stale++;
100
+ else if (outcome.status === "sent") report.sent++;
101
+ else if (outcome.status === "filtered") report.filtered++;
102
+ else if (outcome.status === "skipped") report.skipped++;
103
+ else if (outcome.status === "failed") report.failed++;
104
+ else if (outcome.counted) report.retrying++;
105
+ else report.deferred++;
106
+ })
107
+ );
108
+ };
109
+ const queue = [...groups.values()];
110
+ const wanted = options.concurrency ?? queue.length;
111
+ const width = Math.max(1, Math.min(Number.isFinite(wanted) ? Math.floor(wanted) : queue.length, queue.length));
112
+ await Promise.all(
113
+ Array.from({ length: width }, async () => {
114
+ for (let group = queue.shift(); group; group = queue.shift()) await runGroup(group);
115
+ })
116
+ );
117
+ return report;
118
+ }
119
+ };
120
+ }
121
+
122
+ export { DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, createRunner, defaultBackoff, failureOf, jobOutcome };
123
+ //# sourceMappingURL=chunk-XGAXPUFY.js.map
124
+ //# sourceMappingURL=chunk-XGAXPUFY.js.map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;AAAA,SACH;AAAA,MACF,CAAA;AAEA,MAAA,MAAM,KAAA,GAAQ,CAAC,GAAG,MAAA,CAAO,QAAQ,CAAA;AACjC,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,WAAA,IAAe,KAAA,CAAM,MAAA;AAC5C,MAAA,MAAM,QAAQ,IAAA,CAAK,GAAA,CAAI,GAAG,IAAA,CAAK,GAAA,CAAI,OAAO,QAAA,CAAS,MAAM,CAAA,GAAI,IAAA,CAAK,MAAM,MAAM,CAAA,GAAI,MAAM,MAAA,EAAQ,KAAA,CAAM,MAAM,CAAC,CAAA;AAC7G,MAAA,MAAM,OAAA,CAAQ,GAAA;AAAA,QACZ,MAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAA,IAAS,YAAY;AACxC,UAAA,KAAA,IAAS,KAAA,GAAQ,KAAA,CAAM,KAAA,EAAM,EAAG,KAAA,EAAO,KAAA,GAAQ,KAAA,CAAM,KAAA,EAAM,EAAG,MAAM,QAAA,CAAS,KAAK,CAAA;AAAA,QACpF,CAAC;AAAA,OACH;AACA,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,GACF;AACF","file":"chunk-XGAXPUFY.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/runner`: the one outbox engine. Claim a\n * batch of due jobs, send them (grouped, so a destination that takes many at\n * once gets one request), and record what happened. No dependencies: no\n * `@supabase/supabase-js` and no Node built-ins, so a package can bundle it.\n *\n * The store is the caller's (a SQL outbox claimed with SKIP LOCKED, a\n * queue): `claim` hands over leased jobs and `record` takes back outcomes.\n * The engine owns the rest: turning each send result into an outcome with a\n * retry time, jittered backoff, the deferral cap, and never throwing for one\n * job's failure. It runs the background-job queue (`runJobs` in `/jobs`),\n * genesis-notifications' push and email channels, and genesis-forms'\n * destinations (Sheets, webhooks), each with its own claim. It knows nothing\n * about recipients: preferences, windows and caps are the notifier's.\n *\n * Outcomes:\n * - `sent`: delivered (or already there, on a redelivery: `alreadyThere`).\n * - `filtered`: the sender decided it doesn't apply; nothing sent, nothing to retry.\n * - `skipped`: deliberately not sent (`notSent`: a reason safe to store); never retried.\n * - `retry`: a retryable failure. With the service's own Retry-After it is\n * deferred without counting an attempt (`counted: false`), until\n * `maxDeferrals`; otherwise it backs off by attempt (`counted: true`), until\n * `maxAttempts`.\n * - `failed`: permanent, or out of attempts. With `disable: true` the receiver\n * asked to be switched off (a 410 Gone): stop sending to it.\n *\n * It never logs content, addresses or secrets: only what `label` gives and\n * the senders' safe error messages.\n *\n * @packageDocumentation\n */\n\n/** One claimed job. Extend it with what your sender needs. */\nexport interface RunnerJob {\n /** Stable across retries (an idempotency key is made from it). */\n id: string;\n /** This attempt's number, from 1. */\n attempt: number;\n /** Deferrals so far (outcomes with `counted: false`); pass it back so `maxDeferrals` holds. Default 0. */\n deferrals?: number | undefined;\n /** An earlier attempt may have gone through (its lease ran out): senders that can look first do. */\n redelivery?: boolean | undefined;\n}\n\n/** What a sender says about one job. */\nexport type JobResult =\n | {\n ok: true;\n /** Deliberately sent nothing; the reason, safe to store. Recorded as `skipped`. */\n notSent?: string | undefined;\n /** It was already there (a redelivery), so nothing was sent this time. */\n alreadyThere?: boolean | undefined;\n }\n | JobFailure;\n\nexport interface JobFailure {\n ok: false;\n /** The same request may succeed later (rate limited, the service down, a timeout). */\n retryable: boolean;\n /** The service said when to come back: retry after this many seconds, without counting an attempt. */\n retryAfterSeconds?: number | undefined;\n status?: number | undefined;\n /** The receiver asked to be switched off. Always with `retryable: false`. */\n disable?: true | undefined;\n /** Safe to store and log: never secrets, content or addresses. */\n error: string;\n}\n\nexport type JobOutcome =\n | { status: \"sent\"; alreadyThere?: boolean }\n | { status: \"filtered\" }\n | { status: \"skipped\"; reason: string }\n | {\n status: \"retry\";\n error: string;\n retryAt: Date;\n retryAfterSeconds: number;\n /** Whether this attempt counts toward `maxAttempts`. False when the service said when to come back. */\n counted: boolean;\n httpStatus?: number;\n }\n | { status: \"failed\"; error: string; httpStatus?: number; disable?: true };\n\nexport interface RunReport {\n claimed: number;\n sent: number;\n filtered: number;\n skipped: number;\n /** Retryable failures, backed off by attempt. */\n retrying: number;\n /** Retryable failures the service said when to retry; no attempt used. */\n deferred: number;\n failed: number;\n /** Recorded after the claim was lost (`record` resolved false). */\n stale: number;\n /** `record` threw. */\n unrecorded: number;\n}\n\nexport interface ClaimRequest<Filter> {\n limit: number;\n filter?: Filter | undefined;\n}\n\nexport interface SendContext {\n signal?: AbortSignal | undefined;\n}\n\nexport interface RunnerOptions<J extends RunnerJob, Filter = undefined> {\n /** Claims up to `limit` due jobs, each leased so no other runner sends it meanwhile. */\n claim(request: ClaimRequest<Filter>): Promise<readonly J[]>;\n /**\n * Sends one group of jobs (those with the same `group` key) and resolves one\n * result per job, in order, or `\"filtered\"`. A throw fails the whole group\n * with a retryable error.\n */\n send(group: readonly J[], context: SendContext): Promise<readonly (JobResult | \"filtered\")[]>;\n /** Jobs with the same key are sent together. Default: each job alone. */\n group?: ((job: J) => string) | undefined;\n /**\n * Records an outcome. Resolve `false` when the claim was no longer held: it\n * is counted as stale. A rejection is counted as unrecorded; the lease runs\n * out and the job comes back on its own.\n */\n record(job: J, outcome: JobOutcome): Promise<void | boolean>;\n now?: (() => number) | undefined;\n /** Safe lines (ids, kinds, short reasons). Default: nothing is logged. */\n log?: ((message: string) => void) | undefined;\n /** How a job is named in a log line, capitalised (\"Delivery d1 (email)\"). Default `Job <id>`. */\n label?: ((job: J) => string) | undefined;\n /** How a job is named when recording it failed (\"delivery d1\"). Default `job <id>`. */\n recordLabel?: ((job: J) => string) | undefined;\n /** Jobs claimed per run. Default 25. */\n batchSize?: number | undefined;\n /** Groups sent (and their outcomes recorded) at once. Default: every group at once. */\n concurrency?: number | undefined;\n /** Counted attempts before a retryable failure is given up. Default 8. */\n maxAttempts?: number | undefined;\n /** Deferrals allowed before a further one counts as an attempt. Default 24. */\n maxDeferrals?: number | undefined;\n /** Seconds to wait after a counted failed attempt. Default `defaultBackoff`. */\n backoff?: ((attempt: number) => number) | undefined;\n}\n\nexport interface RunOptions<Filter> {\n filter?: Filter | undefined;\n /** Overrides `batchSize` for this run. */\n limit?: number | undefined;\n /** Aborts the sends in flight. */\n signal?: AbortSignal | undefined;\n}\n\nexport interface Runner<Filter = undefined> {\n /** One claim, its sends and their records. Never rejects for a job's failure; a failing `claim` rejects. */\n run(options?: RunOptions<Filter>): Promise<RunReport>;\n}\n\nexport const DEFAULT_MAX_ATTEMPTS = 8;\nexport const DEFAULT_MAX_DEFERRALS = 24;\nexport const DEFAULT_BATCH_SIZE = 25;\n\n/**\n * 5 minutes, quadrupling each attempt, at most 24 hours: 5m, 20m, 80m, 5h20m,\n * 21h20m, then 24h; about 3 days across 8 attempts. Each wait is jittered by\n * up to ±20%, so jobs that failed together don't all come back at once.\n */\nexport function defaultBackoff(attempt: number, random?: () => number): number {\n const nominal = Math.min(24 * 3600, 300 * 4 ** Math.max(0, attempt - 1));\n // A function only: `[1, 2].map(defaultBackoff)` passes an index here.\n const r = typeof random === \"function\" ? random() : Math.random();\n return Math.round(nominal * (0.8 + 0.4 * Math.min(1, Math.max(0, r))));\n}\n\n/** Turns a send result into an outcome for a job on its `attempt`. */\nexport function jobOutcome(\n result: JobResult,\n attempt: number,\n options: {\n now?: number | undefined;\n maxAttempts?: number | undefined;\n backoff?: ((attempt: number) => number) | undefined;\n deferrals?: number | undefined;\n maxDeferrals?: number | undefined;\n } = {},\n): JobOutcome {\n if (result.ok) {\n if (result.notSent) return { status: \"skipped\", reason: result.notSent.slice(0, 500) };\n return result.alreadyThere ? { status: \"sent\", alreadyThere: true } : { status: \"sent\" };\n }\n const http = result.status !== undefined ? { httpStatus: result.status } : {};\n if (result.disable) return { status: \"failed\", error: result.error, ...http, disable: true };\n if (!result.retryable) return { status: \"failed\", error: result.error, ...http };\n const now = options.now ?? Date.now();\n if (result.retryAfterSeconds !== undefined && (options.deferrals ?? 0) < (options.maxDeferrals ?? DEFAULT_MAX_DEFERRALS)) {\n const seconds = Math.max(1, Math.ceil(result.retryAfterSeconds));\n return { status: \"retry\", error: result.error, retryAt: new Date(now + seconds * 1000), retryAfterSeconds: seconds, counted: false, ...http };\n }\n const max = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n if (attempt >= max) return { status: \"failed\", error: `${result.error} (gave up after ${attempt} attempts)`.slice(0, 500), ...http };\n const seconds = Math.max(1, Math.ceil((options.backoff ?? defaultBackoff)(attempt)));\n return { status: \"retry\", error: result.error, retryAt: new Date(now + seconds * 1000), retryAfterSeconds: seconds, counted: true, ...http };\n}\n\n/** A thrown error as a retryable failure with a safe message. */\nexport function failureOf(error: unknown): JobFailure {\n const e = error as { name?: unknown; message?: unknown; retryable?: unknown; retryAfterSeconds?: unknown; status?: unknown; disable?: unknown } | null;\n if (e && typeof e === \"object\" && typeof e.retryable === \"boolean\" && typeof e.message === \"string\") {\n return {\n ok: false,\n retryable: e.disable === true ? false : e.retryable,\n error: e.message.slice(0, 500),\n ...(typeof e.retryAfterSeconds === \"number\" ? { retryAfterSeconds: e.retryAfterSeconds } : {}),\n ...(typeof e.status === \"number\" ? { status: e.status } : {}),\n ...(e.disable === true ? { disable: true as const } : {}),\n };\n }\n const timeout = e && typeof e === \"object\" && (e.name === \"TimeoutError\" || e.name === \"AbortError\");\n return { ok: false, retryable: true, error: timeout ? \"Timed out\" : \"Unexpected error\" };\n}\n\n/**\n * The runner.\n *\n * @stability Beta\n */\nexport function createRunner<J extends RunnerJob, Filter = undefined>(options: RunnerOptions<J, Filter>): Runner<Filter> {\n const log = (message: string): void => {\n try {\n options.log?.(message);\n } catch {\n // A logger that throws never stops an outcome being recorded.\n }\n };\n const label = (job: J) => options.label?.(job) ?? `Job ${job.id}`;\n const recordLabel = (job: J) => options.recordLabel?.(job) ?? `job ${job.id}`;\n const now = () => options.now?.() ?? Date.now();\n\n return {\n async run(runOptions: RunOptions<Filter> = {}): Promise<RunReport> {\n const report: RunReport = { claimed: 0, sent: 0, filtered: 0, skipped: 0, retrying: 0, deferred: 0, failed: 0, stale: 0, unrecorded: 0 };\n const limit = runOptions.limit ?? options.batchSize ?? DEFAULT_BATCH_SIZE;\n const claimed = await options.claim({ limit, filter: runOptions.filter });\n report.claimed = claimed.length;\n\n const groups = new Map<string, J[]>();\n claimed.forEach((job, i) => {\n const key = options.group ? options.group(job) : `\\u0000${i}`;\n const list = groups.get(key) ?? [];\n list.push(job);\n groups.set(key, list);\n });\n\n const runGroup = async (group: J[]): Promise<void> => {\n let results: readonly (JobResult | \"filtered\")[];\n try {\n results = await options.send(group, { signal: runOptions.signal });\n if (results.length !== group.length) throw new Error(\"send answered the wrong number of results\");\n } catch (error) {\n const failure = failureOf(error);\n results = group.map(() => failure);\n }\n const at = now();\n await Promise.all(\n group.map(async (job, i) => {\n const result = results[i]!;\n const outcome: JobOutcome =\n result === \"filtered\"\n ? { status: \"filtered\" }\n : jobOutcome(result, job.attempt, {\n now: at,\n maxAttempts: options.maxAttempts,\n backoff: options.backoff,\n deferrals: job.deferrals,\n maxDeferrals: options.maxDeferrals,\n });\n if (outcome.status === \"failed\" || outcome.status === \"retry\") {\n log(`${label(job)} ${outcome.status === \"failed\" ? \"failed\" : \"will be retried\"}: ${outcome.error}`);\n } else if (outcome.status === \"skipped\") {\n log(`${label(job)} skipped: ${outcome.reason}`);\n }\n let recorded: void | boolean;\n try {\n recorded = await options.record(job, outcome);\n } catch {\n report.unrecorded++;\n log(`Recording ${recordLabel(job)} failed`);\n return;\n }\n if (recorded === false) report.stale++;\n else if (outcome.status === \"sent\") report.sent++;\n else if (outcome.status === \"filtered\") report.filtered++;\n else if (outcome.status === \"skipped\") report.skipped++;\n else if (outcome.status === \"failed\") report.failed++;\n else if (outcome.counted) report.retrying++;\n else report.deferred++;\n }),\n );\n };\n\n const queue = [...groups.values()];\n const wanted = options.concurrency ?? queue.length;\n const width = Math.max(1, Math.min(Number.isFinite(wanted) ? Math.floor(wanted) : queue.length, queue.length));\n await Promise.all(\n Array.from({ length: width }, async () => {\n for (let group = queue.shift(); group; group = queue.shift()) await runGroup(group);\n }),\n );\n return report;\n },\n };\n}\n"]}
@@ -236,9 +236,9 @@ interface FeatureRegistryDocument {
236
236
  /** @stability Beta */
237
237
  interface SyncFeatureRegistryOptions {
238
238
  /**
239
- * When this deployment started serving, in milliseconds (`Date.now()` at server start), not its
240
- * build time: an instant rollback to an older build then syncs as the newest. Older versions
241
- * than the last sync are refused.
239
+ * This build's version: an increasing number such as the build time in milliseconds, so an old
240
+ * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer
241
+ * one. Older versions than the last sync are refused.
242
242
  */
243
243
  version: number;
244
244
  /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */
@@ -253,7 +253,7 @@ interface SyncFeatureRegistryOptions {
253
253
  *
254
254
  * ```ts
255
255
  * import registry from "../features.json";
256
- * if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
256
+ * if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });
257
257
  * ```
258
258
  *
259
259
  * @stability Beta
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@supabase/supabase-js';
2
- export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureRegistryClient, e as FeatureRegistryDocument, f as FlagStateValue, g as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, j as SetTenantFeatureInput, k as StoreAppleTokenOptions, l as StoreAppleTokenResult, m as SupabaseQueryError, n as SyncFeatureRegistryOptions, T as TenantFeatureChange, o as TenantFeatureSetting, p as TenantFeatures, q as TenantFeaturesClient, r as createGenesisSupabase, s as deleteMyAccount, t as featureGateState, u as must, v as requestAppleRevocation, w as setTenantFeature, x as storeAppleToken, y as syncFeatureRegistry, z as tenantFeatureHistory, B as tenantFeatureSettings, C as tenantFeatures } from './index-Ds0tO9WP.js';
3
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
2
+ export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureRegistryClient, e as FeatureRegistryDocument, f as FlagStateValue, g as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, j as SetTenantFeatureInput, k as StoreAppleTokenOptions, l as StoreAppleTokenResult, m as SupabaseQueryError, n as SyncFeatureRegistryOptions, T as TenantFeatureChange, o as TenantFeatureSetting, p as TenantFeatures, q as TenantFeaturesClient, r as createGenesisSupabase, s as deleteMyAccount, t as featureGateState, u as must, v as requestAppleRevocation, w as setTenantFeature, x as storeAppleToken, y as syncFeatureRegistry, z as tenantFeatureHistory, B as tenantFeatureSettings, C as tenantFeatures } from './index-D73YuwEY.js';
3
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './blocks.js';
4
4
  import '@marktiderman/genesis-features/blocks';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { installWebCrypto, assertPkceCrypto, isDigestOnlyPolyfill, claimsViaServer } from './chunk-FAA2FTF4.js';
2
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
2
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './chunk-DYHH2G4A.js';
3
3
  import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
4
4
 
5
5
  // src/apple-tokens.ts