@marktiderman/genesis-supabase 0.7.0 → 0.9.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.
- package/README.md +123 -1
- package/dist/blocks.d.ts +9 -1
- package/dist/blocks.js +1 -1
- package/dist/{chunk-FWZIWKI4.js → chunk-4IVEBFZM.js} +26 -5
- package/dist/chunk-4IVEBFZM.js.map +1 -0
- package/dist/chunk-7SCMHKCR.js +33 -0
- package/dist/chunk-7SCMHKCR.js.map +1 -0
- package/dist/chunk-XGAXPUFY.js +124 -0
- package/dist/chunk-XGAXPUFY.js.map +1 -0
- package/dist/{index-D73YuwEY.d.ts → index-CaYX9z8D.d.ts} +16 -6
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/jobs.d.ts +3 -1
- package/dist/jobs.js +48 -34
- package/dist/jobs.js.map +1 -1
- package/dist/native.d.ts +2 -2
- package/dist/runner.d.ts +179 -0
- package/dist/runner.js +3 -0
- package/dist/runner.js.map +1 -0
- package/dist/web-handoff-path-C_EEl_BC.d.ts +16 -0
- package/dist/web-handoff-server.d.ts +225 -0
- package/dist/web-handoff-server.js +262 -0
- package/dist/web-handoff-server.js.map +1 -0
- package/dist/web-handoff.d.ts +133 -0
- package/dist/web-handoff.js +104 -0
- package/dist/web-handoff.js.map +1 -0
- package/migrations/0015_genesis_web_handoff.sql +270 -0
- package/migrations/0016_genesis_viewer_people.sql +70 -0
- package/migrations/0017_genesis_person_entitlements.sql +284 -0
- package/migrations/tests/0015_genesis_web_handoff.test.sql +203 -0
- package/migrations/tests/0016_genesis_viewer_people.test.sql +77 -0
- package/migrations/tests/0017_genesis_person_entitlements.test.sql +96 -0
- package/package.json +63 -5
- package/dist/chunk-FWZIWKI4.js.map +0 -1
package/README.md
CHANGED
|
@@ -604,6 +604,15 @@ way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
|
|
|
604
604
|
marked `in_registry = false`; its tenant values stay, and (0014) its platform value is cleared.
|
|
605
605
|
- **Paid access.** `feature_entitlements` (tenant, feature, source, `active`, optional `ends_at`). Your billing
|
|
606
606
|
webhook writes it with the service key.
|
|
607
|
+
- **Paid access for one person (0016, 0017).** `feature_person_entitlements` holds grants to the app's person
|
|
608
|
+
record, not a login: a membership, a class pack or a coaching package bought before sign-up counts once the
|
|
609
|
+
person signs in. Server code writes them with `grant_person_entitlement(tenant, person, feature, source,
|
|
610
|
+
source_ref, starts_at, ends_at)` (idempotent on `source_ref`, so a replayed webhook changes nothing) and
|
|
611
|
+
`revoke_person_entitlement(...)`. Which person records a login is comes from your
|
|
612
|
+
`private.genesis_viewer_people(viewer)` hook, read through the fail-closed `private.genesis_viewer_person_ids()`
|
|
613
|
+
(0016, shared with every block that gives something to a person record). `feature_on`,
|
|
614
|
+
`feature_entitled_tenants` and `feature_gate_state(tenant)` count the signed-in person's own grants; server
|
|
615
|
+
code gets the tenant's answer, or names a person with `feature_gate_state(tenant, person)`.
|
|
607
616
|
- **Flag values.** `tenant_flag_values` overrides a flag's default for one tenant (service key).
|
|
608
617
|
- **The gate in SQL.** `feature_on(tenant, feature)` is true for a shipped feature that, when paid, has an
|
|
609
618
|
active entitlement; a signed-in caller outside the tenant gets false. It runs once per row, so in policies
|
|
@@ -630,7 +639,8 @@ import registry from "../features.json";
|
|
|
630
639
|
// When a production deployment starts serving (never from a preview):
|
|
631
640
|
if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });
|
|
632
641
|
|
|
633
|
-
const state = await featureGateState(supabase, teamId); // per session
|
|
642
|
+
const state = await featureGateState(supabase, teamId); // per session; includes the person's own grants
|
|
643
|
+
// On the server, for one person: await featureGateState(admin, teamId, { personId })
|
|
634
644
|
const snapshot = gateSnapshot({ features, flags }, { platform: "web", ...state }, { version: BUILD_TIME });
|
|
635
645
|
```
|
|
636
646
|
|
|
@@ -677,6 +687,15 @@ const report = await runJobs(admin, {
|
|
|
677
687
|
- **Settle failures.** If recording an outcome fails, the job is counted as `unsettled` and comes
|
|
678
688
|
back when its lease runs out. The run carries on, and only a failed claim throws.
|
|
679
689
|
|
|
690
|
+
**One engine.** `runJobs` runs on `createRunner` from `@marktiderman/genesis-supabase/runner`, the
|
|
691
|
+
outbox engine genesis-notifications' push and email and genesis-forms' destinations also run on.
|
|
692
|
+
The engine claims a batch, sends it (in groups, `concurrency` at a time), turns each result into an
|
|
693
|
+
outcome (`sent`, `filtered`, `skipped`, `retry` with jittered backoff or a Retry-After deferral up
|
|
694
|
+
to `maxDeferrals`, `failed`, with `disable` on a 410) and records it, never throwing for one job.
|
|
695
|
+
It has no dependencies (no `@supabase/supabase-js`, no Node built-ins), so a package can bundle it,
|
|
696
|
+
and it knows nothing about recipients. For `runJobs` the queue keeps the attempts and the retry
|
|
697
|
+
times, as above. `@marktiderman/genesis-notifications/runner` still re-exports it, deprecated.
|
|
698
|
+
|
|
680
699
|
**One job route.** `createJobsHandler` runs the job the route names, but only if the request passes
|
|
681
700
|
one of two constant-time checks:
|
|
682
701
|
|
|
@@ -735,6 +754,109 @@ route instead: it sends GET with the bearer.
|
|
|
735
754
|
**Access.** The queue table has RLS on, no policies, and no grants to `anon` or `authenticated`.
|
|
736
755
|
Every function is granted by name to `service_role` only.
|
|
737
756
|
|
|
757
|
+
## Continue on the web, already signed in (the web-handoff block)
|
|
758
|
+
|
|
759
|
+
Some work a native app leaves to the web app (editing a form's questions, say). The web-handoff
|
|
760
|
+
block opens that web page signed in as the same person, with no sign-in screen:
|
|
761
|
+
|
|
762
|
+
1. **App:** `openOnWeb(path, …)` from `@marktiderman/genesis-native/web-handoff` posts `{ path }` to
|
|
763
|
+
the app's mint route with `Authorization: Bearer <access token>`.
|
|
764
|
+
2. **Mint** (`createWebHandoff(...).mint`, or `mintWebHandoff` for a person you verified another
|
|
765
|
+
way): verifies the bearer with `auth.getUser`, checks the path with `appRelativePath`, and
|
|
766
|
+
records a handoff (`genesis_web_handoff_issue`): the person, the path, the app session it came
|
|
767
|
+
from (the bearer's `session_id`), a 60-second expiry and a SHA-256 digest of a random 256-bit
|
|
768
|
+
token. It returns `<origin>/auth/handoff#t=<token>&next=<path>`; the fragment never reaches a
|
|
769
|
+
server. Ten links a person a minute, counted in the database.
|
|
770
|
+
3. **Page** (`/auth/handoff`): `takeWebHandoffFragment()` reads the fragment and removes it with
|
|
771
|
+
`history.replaceState` before analytics or error reporting load. `completeWebHandoff` checks
|
|
772
|
+
who is signed in here with `auth.getUser` (a session ended elsewhere counts as nobody and is
|
|
773
|
+
cleared), then **claims** the handoff (`genesis_web_handoff_claim`): once, unexpired. The claim
|
|
774
|
+
returns whose link it is and a **continue nonce** that works once, for 30 seconds. Nothing that
|
|
775
|
+
signs anyone in exists yet.
|
|
776
|
+
4. **Same person already signed in:** straight to `next`; nothing is ever minted.
|
|
777
|
+
**Otherwise:** "Continue as {email}?".
|
|
778
|
+
- **Continue** spends the nonce (`genesis_web_handoff_continue`: once, in time, not after
|
|
779
|
+
Cancel). Only now does the server ask Supabase Auth for a sign-in token for that person's own
|
|
780
|
+
email (`auth.admin.generateLink({ type: "magiclink" })`, which sends nothing). The page signs
|
|
781
|
+
any other person out locally, exchanges the token at once with
|
|
782
|
+
`auth.verifyOtp({ token_hash, type: "email" })`, checks the verified user is the link's, and
|
|
783
|
+
goes to `next`, checked again. It then reports the new session (`bind`, its access token as
|
|
784
|
+
the bearer), so the app's sign-out can end it.
|
|
785
|
+
- **Cancel** burns the nonce (`genesis_web_handoff_discard`) and signs out locally anyone else
|
|
786
|
+
who was signed in here, so the page never leaves someone in the app as another person. Show
|
|
787
|
+
"You can close this window".
|
|
788
|
+
- **A page left open** never gets a sign-in token: the nonce runs out.
|
|
789
|
+
5. **App sign-out:** `signOutOnWeb` (genesis-native) posts the app's bearer to the sign-out route
|
|
790
|
+
before the app signs out; `genesis_web_handoff_revoke_sessions` deletes the `auth.sessions` rows
|
|
791
|
+
of the web sessions handed off from that app session, and only those (never the person's other
|
|
792
|
+
devices; never a global sign-out).
|
|
793
|
+
|
|
794
|
+
```ts
|
|
795
|
+
// Server routes (the service-role client, server only)
|
|
796
|
+
import { createWebHandoff } from "@marktiderman/genesis-supabase/web-handoff/server";
|
|
797
|
+
const handoff = createWebHandoff({ admin: supabaseAdmin });
|
|
798
|
+
// POST /api/auth/handoff → handoff.mint(request)
|
|
799
|
+
// POST /api/auth/redeem-handoff → handoff.redeem(request) (claim, continue, discard, bind)
|
|
800
|
+
// POST /api/auth/handoff-signout → handoff.signOut(request)
|
|
801
|
+
|
|
802
|
+
// The page
|
|
803
|
+
import { completeWebHandoff, takeWebHandoffFragment } from "@marktiderman/genesis-supabase/web-handoff";
|
|
804
|
+
const step = await completeWebHandoff({ supabase, fragment: takeWebHandoffFragment() });
|
|
805
|
+
// "done" → go to step.next; "confirm" → ask, then step.continue() or step.cancel();
|
|
806
|
+
// "cancelled" → "You can close this window"; "failed" → step.reason, sign in keeping step.next
|
|
807
|
+
```
|
|
808
|
+
|
|
809
|
+
Install: copy `migrations/0015_genesis_web_handoff.sql` into `supabase/migrations/` under a new
|
|
810
|
+
timestamped name and its pgTAP test into `supabase/tests/database/`.
|
|
811
|
+
|
|
812
|
+
The page must send `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and
|
|
813
|
+
`Content-Security-Policy: frame-ancestors 'none'`, render without analytics, and call
|
|
814
|
+
`takeWebHandoffFragment` before any third-party script runs.
|
|
815
|
+
|
|
816
|
+
### Lifetimes
|
|
817
|
+
|
|
818
|
+
- **The handoff link:** 60 seconds and one claim (`ttlSeconds`, 10 to 300).
|
|
819
|
+
- **The continue nonce:** 30 seconds and one use (`continueSeconds`, 5 to 120); Cancel burns it.
|
|
820
|
+
- **Supabase's sign-in token:** minted only on Continue and exchanged by the page at once. It is
|
|
821
|
+
single use and would expire after the project's **Email OTP Expiration** (`mailer_otp_exp`;
|
|
822
|
+
default one hour; Authentication → Sign In / Providers → Email). The block doesn't rely on that
|
|
823
|
+
setting, which is project-wide. Minting one replaces any magic link or email code that person
|
|
824
|
+
has outstanding.
|
|
825
|
+
- **A web session the app's sign-out ended:** its `auth.sessions` row is gone, so it can't refresh
|
|
826
|
+
and `auth.getUser` refuses it; Supabase documents that its access token still verifies locally
|
|
827
|
+
until it expires (the project's JWT expiry, one hour by default).
|
|
828
|
+
|
|
829
|
+
### Choices, and why
|
|
830
|
+
|
|
831
|
+
- **Claim, then Continue.** Minting Supabase's token when the page opened would leave a working
|
|
832
|
+
sign-in token in a page someone cancelled or walked away from, for the whole OTP expiry. The
|
|
833
|
+
token exists only after the person chooses Continue, within 30 seconds of opening the link.
|
|
834
|
+
- **A record per handoff, not a signed timestamp.** A signed `iat` can't stop someone holding
|
|
835
|
+
Supabase's token hash from exchanging it directly; here there is no token hash to hold until
|
|
836
|
+
Continue.
|
|
837
|
+
- **Ask first unless it's the same person.** Anyone can mint a link for their own account and
|
|
838
|
+
send it to someone else (login CSRF); "Continue as {email}?" makes that visible. The in-app
|
|
839
|
+
browser keeps its storage, so the person taps Continue once and later handoffs go straight in.
|
|
840
|
+
- **Cancel signs the other person out.** Leaving the page (or opening Home) as whoever was signed
|
|
841
|
+
in before could put someone in the app as another person: an in-app browser keeps the previous
|
|
842
|
+
person's session after the app switched accounts. Signing out locally is the safe default; the
|
|
843
|
+
cost is that a person who cancels a link someone else sent them is signed out of this browser.
|
|
844
|
+
- **Ending the web session on app sign-out by deleting its `auth.sessions` row.** Supabase's docs:
|
|
845
|
+
"When a user signs out, the sessions affected by the sign-out are removed from the database";
|
|
846
|
+
a missing row means signed out. `auth.admin.signOut` needs that session's JWT, which the server
|
|
847
|
+
doesn't keep; `scope: "global"` would sign out every device. The session id comes from the
|
|
848
|
+
web session's verified access token (`session_id` claim), bound to the handoff once, within two
|
|
849
|
+
minutes of Continue, for the same person.
|
|
850
|
+
- **Magic link over passing the session.** Supabase has no first-party way to move a session to
|
|
851
|
+
another client. Sending the app's refresh token would share one session between app and
|
|
852
|
+
browser, and refresh-token rotation would sign one of them out. A magic-link token gives the
|
|
853
|
+
browser its own session.
|
|
854
|
+
- **`type: "email"` in `verifyOtp`.** Supabase marks `magiclink` deprecated for `verifyOtp` and
|
|
855
|
+
documents `generateLink({ type: "magiclink" })` then `verifyOtp({ token_hash, type: "email" })`.
|
|
856
|
+
The exchange is a POST from the page; it needs no PKCE code verifier, so a PKCE client works.
|
|
857
|
+
- **No email, no handoff.** Supabase's link sign-in is by email. A phone-only account gets a
|
|
858
|
+
409 `no_email` with a `fallbackUrl` (the page, signed out), and `openOnWeb` opens that instead.
|
|
859
|
+
|
|
738
860
|
## Testing your schema's data contract (genesis_testing)
|
|
739
861
|
|
|
740
862
|
`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,6 +30,14 @@ 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>;
|
|
33
41
|
/**
|
|
34
42
|
* The owner-access block: the contract every Genesis block with owned rows
|
|
35
43
|
* calls in its policies. Two fail-closed wrappers over the app's hooks
|
|
@@ -40,4 +48,4 @@ declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs",
|
|
|
40
48
|
*/
|
|
41
49
|
declare const ownerAccessBlock: _marktiderman_genesis_features_blocks.BlockDef<"owner-access", never>;
|
|
42
50
|
|
|
43
|
-
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock };
|
|
51
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock, webHandoffBlock };
|
package/dist/blocks.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './chunk-
|
|
1
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock, webHandoffBlock } from './chunk-4IVEBFZM.js';
|
|
2
2
|
//# sourceMappingURL=blocks.js.map
|
|
3
3
|
//# sourceMappingURL=blocks.js.map
|
|
@@ -78,11 +78,17 @@ var featureMirrorBlock = defineBlock({
|
|
|
78
78
|
package: PACKAGE,
|
|
79
79
|
file: "migrations/0014_genesis_feature_registry_hardening.sql",
|
|
80
80
|
test: "migrations/tests/0014_genesis_feature_registry_hardening.test.sql"
|
|
81
|
+
},
|
|
82
|
+
{ package: PACKAGE, file: "migrations/0016_genesis_viewer_people.sql", test: "migrations/tests/0016_genesis_viewer_people.test.sql" },
|
|
83
|
+
{
|
|
84
|
+
package: PACKAGE,
|
|
85
|
+
file: "migrations/0017_genesis_person_entitlements.sql",
|
|
86
|
+
test: "migrations/tests/0017_genesis_person_entitlements.test.sql"
|
|
81
87
|
}
|
|
82
88
|
],
|
|
83
89
|
privacy: {
|
|
84
90
|
notes: [
|
|
85
|
-
"Stores which tenants hold which paid features and flag values
|
|
91
|
+
"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values."
|
|
86
92
|
]
|
|
87
93
|
}
|
|
88
94
|
}
|
|
@@ -95,6 +101,20 @@ var jobsBlock = defineBlock({
|
|
|
95
101
|
privacy: { notes: ["Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days."] }
|
|
96
102
|
}
|
|
97
103
|
});
|
|
104
|
+
var webHandoffBlock = defineBlock({
|
|
105
|
+
id: "web-handoff",
|
|
106
|
+
platforms: ["web", "native"],
|
|
107
|
+
contributes: {
|
|
108
|
+
migrations: [
|
|
109
|
+
{ package: PACKAGE, file: "migrations/0015_genesis_web_handoff.sql", test: "migrations/tests/0015_genesis_web_handoff.test.sql" }
|
|
110
|
+
],
|
|
111
|
+
privacy: {
|
|
112
|
+
notes: [
|
|
113
|
+
"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."
|
|
114
|
+
]
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
});
|
|
98
118
|
var ownerAccessBlock = defineBlock({
|
|
99
119
|
id: "owner-access",
|
|
100
120
|
requires: ["tenant-features"],
|
|
@@ -105,12 +125,13 @@ var ownerAccessBlock = defineBlock({
|
|
|
105
125
|
package: PACKAGE,
|
|
106
126
|
file: "migrations/0009_genesis_owner_access.sql",
|
|
107
127
|
test: "migrations/tests/0009_genesis_owner_access.test.sql"
|
|
108
|
-
}
|
|
128
|
+
},
|
|
129
|
+
{ package: PACKAGE, file: "migrations/0016_genesis_viewer_people.sql", test: "migrations/tests/0016_genesis_viewer_people.test.sql" }
|
|
109
130
|
],
|
|
110
131
|
privacy: { notes: ["Stores nothing; it only asks the app's hooks who may read and write."] }
|
|
111
132
|
}
|
|
112
133
|
});
|
|
113
134
|
|
|
114
|
-
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock };
|
|
115
|
-
//# sourceMappingURL=chunk-
|
|
116
|
-
//# sourceMappingURL=chunk-
|
|
135
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock, webHandoffBlock };
|
|
136
|
+
//# sourceMappingURL=chunk-4IVEBFZM.js.map
|
|
137
|
+
//# sourceMappingURL=chunk-4IVEBFZM.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,E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AAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAUM,IAAM,mBAAmB,WAAA,CAAY;AAAA,EAC1C,EAAA,EAAI,cAAA;AAAA,EACJ,QAAA,EAAU,CAAC,iBAAiB,CAAA;AAAA,EAC5B,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,0CAAA;AAAA,QACN,IAAA,EAAM;AAAA,OACR;AAAA,MACA,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,2CAAA,EAA6C,MAAM,sDAAA;AAAuD,KACtI;AAAA,IACA,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,sEAAsE,CAAA;AAAE;AAE/F,CAAC","file":"chunk-4IVEBFZM.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 { package: PACKAGE, file: \"migrations/0016_genesis_viewer_people.sql\", test: \"migrations/tests/0016_genesis_viewer_people.test.sql\" },\n {\n package: PACKAGE,\n file: \"migrations/0017_genesis_person_entitlements.sql\",\n test: \"migrations/tests/0017_genesis_person_entitlements.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values.\",\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 { package: PACKAGE, file: \"migrations/0016_genesis_viewer_people.sql\", test: \"migrations/tests/0016_genesis_viewer_people.test.sql\" },\n ],\n privacy: { notes: [\"Stores nothing; it only asks the app's hooks who may read and write.\"] },\n },\n});\n"]}
|
|
@@ -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"]}
|
|
@@ -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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runner.ts"],"names":["seconds"],"mappings":";AA6JO,IAAM,oBAAA,GAAuB;AAC7B,IAAM,qBAAA,GAAwB;AAC9B,IAAM,kBAAA,GAAqB;AAO3B,SAAS,cAAA,CAAe,SAAiB,MAAA,EAA+B;AAC7E,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,GAAA,CAAI,EAAA,GAAK,IAAA,EAAM,GAAA,GAAM,CAAA,IAAK,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,OAAA,GAAU,CAAC,CAAC,CAAA;AAEvE,EAAA,MAAM,IAAI,OAAO,MAAA,KAAW,aAAa,MAAA,EAAO,GAAI,KAAK,MAAA,EAAO;AAChE,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,OAAA,IAAW,GAAA,GAAM,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA,CAAE,CAAA;AACvE;AAGO,SAAS,UAAA,CACd,MAAA,EACA,OAAA,EACA,OAAA,GAMI,EAAC,EACO;AACZ,EAAA,IAAI,OAAO,EAAA,EAAI;AACb,IAAA,IAAI,MAAA,CAAO,OAAA,EAAS,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,MAAA,EAAQ,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA,EAAE;AACrF,IAAA,OAAO,MAAA,CAAO,YAAA,GAAe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O,QAAA,EAAA;AAAA,iBAAA,IACtC,OAAA,CAAQ,MAAA,KAAW,SAAA,EAAW,MAAA,CAAO,OAAA,EAAA;AAAA,iBAAA,IACrC,OAAA,CAAQ,MAAA,KAAW,QAAA,EAAU,MAAA,CAAO,MAAA,EAAA;AAAA,iBAAA,IACpC,OAAA,CAAQ,SAAS,MAAA,CAAO,QAAA,EAAA;AAAA,iBAC5B,MAAA,CAAO,QAAA,EAAA;AAAA,UACd,CAAC;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"]}
|
|
@@ -212,20 +212,30 @@ type FlagStateValue = boolean | string | number | {
|
|
|
212
212
|
interface FeatureGateState {
|
|
213
213
|
/** Feature ids the tenant switched off. */
|
|
214
214
|
off: string[];
|
|
215
|
-
/** Feature ids the tenant
|
|
215
|
+
/** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */
|
|
216
216
|
entitlements: string[];
|
|
217
217
|
/** Flag values for the tenant (platform values applied), by flag name. */
|
|
218
218
|
flags: Record<string, FlagStateValue>;
|
|
219
219
|
}
|
|
220
|
+
/** @stability Beta */
|
|
221
|
+
interface FeatureGateStateOptions {
|
|
222
|
+
/**
|
|
223
|
+
* With the service key only: add this person's own entitlements (the app's person id, not a
|
|
224
|
+
* login), for a snapshot built on the server. A signed-in person's client gets their own
|
|
225
|
+
* without it, and is refused (`42501`) with it.
|
|
226
|
+
*/
|
|
227
|
+
personId?: string;
|
|
228
|
+
}
|
|
220
229
|
/**
|
|
221
230
|
* A tenant's switches, entitlements and flag values: `feature_gate_state`.
|
|
222
|
-
* Works with a signed-in person's client (for tenants they belong to
|
|
223
|
-
*
|
|
224
|
-
* refusal is never mistaken
|
|
231
|
+
* Works with a signed-in person's client (for tenants they belong to; their own
|
|
232
|
+
* person entitlements are included) or the service key. Throws a
|
|
233
|
+
* `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken
|
|
234
|
+
* for "nothing set".
|
|
225
235
|
*
|
|
226
236
|
* @stability Beta
|
|
227
237
|
*/
|
|
228
|
-
declare function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState>;
|
|
238
|
+
declare function featureGateState(client: FeatureRegistryClient, tenantId: string, options?: FeatureGateStateOptions): Promise<FeatureGateState>;
|
|
229
239
|
/** `features.json` as `genesis features build` writes it. @stability Beta */
|
|
230
240
|
interface FeatureRegistryDocument {
|
|
231
241
|
features: readonly ({
|
|
@@ -389,4 +399,4 @@ interface DeleteMyAccountOptions {
|
|
|
389
399
|
*/
|
|
390
400
|
declare function deleteMyAccount(client: DeleteAccountClient, options?: DeleteMyAccountOptions): Promise<void>;
|
|
391
401
|
|
|
392
|
-
export { APPLE_REVOKE_FUNCTION as A,
|
|
402
|
+
export { APPLE_REVOKE_FUNCTION as A, tenantFeatureHistory as B, tenantFeatureSettings as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, tenantFeatures as H, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type FeatureGateStateOptions as d, type FeatureRegistryClient as e, type FeatureRegistryDocument as f, type FlagStateValue as g, hasPkceCrypto as h, installWebCrypto as i, type FunctionsClient as j, type SetTenantFeatureInput as k, type StoreAppleTokenOptions as l, type StoreAppleTokenResult as m, SupabaseQueryError as n, type SyncFeatureRegistryOptions as o, type TenantFeatureSetting as p, type TenantFeatures as q, type TenantFeaturesClient as r, createGenesisSupabase as s, deleteMyAccount as t, featureGateState as u, must as v, requestAppleRevocation as w, setTenantFeature as x, storeAppleToken as y, syncFeatureRegistry as z };
|
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
|
|
2
|
+
export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureGateStateOptions, e as FeatureRegistryClient, f as FeatureRegistryDocument, g as FlagStateValue, j as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, k as SetTenantFeatureInput, l as StoreAppleTokenOptions, m as StoreAppleTokenResult, n as SupabaseQueryError, o as SyncFeatureRegistryOptions, T as TenantFeatureChange, p as TenantFeatureSetting, q as TenantFeatures, r as TenantFeaturesClient, s as createGenesisSupabase, t as deleteMyAccount, u as featureGateState, v as must, w as requestAppleRevocation, x as setTenantFeature, y as storeAppleToken, z as syncFeatureRegistry, B as tenantFeatureHistory, C as tenantFeatureSettings, H as tenantFeatures } from './index-CaYX9z8D.js';
|
|
3
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, ownerAccessBlock, tenantFeaturesBlock } from './chunk-
|
|
2
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './chunk-4IVEBFZM.js';
|
|
3
3
|
import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
|
|
4
4
|
|
|
5
5
|
// src/apple-tokens.ts
|
|
@@ -50,8 +50,9 @@ async function tenantFeatureHistory(client, tenantId, options = {}) {
|
|
|
50
50
|
|
|
51
51
|
// src/feature-registry.ts
|
|
52
52
|
var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
53
|
-
async function featureGateState(client, tenantId) {
|
|
54
|
-
const
|
|
53
|
+
async function featureGateState(client, tenantId, options = {}) {
|
|
54
|
+
const args = options.personId === void 0 ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };
|
|
55
|
+
const data = must(await client.rpc("feature_gate_state", args));
|
|
55
56
|
if (!data || typeof data !== "object" || Array.isArray(data)) throw new TypeError("feature_gate_state returned no state");
|
|
56
57
|
const { off, entitled, flags } = data;
|
|
57
58
|
if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== "object" || Array.isArray(flags)) {
|