@marktiderman/genesis-supabase 0.12.0 → 0.14.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 +52 -4
- package/dist/blocks.d.ts +9 -1
- package/dist/blocks.js +1 -1
- package/dist/{chunk-34OBTZJQ.js → chunk-XESMEWXI.js} +12 -3
- package/dist/chunk-XESMEWXI.js.map +1 -0
- package/dist/{index-UjHqJN2X.d.ts → index-CKloeGaz.d.ts} +42 -6
- package/dist/index.d.ts +2 -2
- package/dist/index.js +29 -11
- package/dist/index.js.map +1 -1
- package/dist/native.d.ts +2 -2
- package/migrations/0019_genesis_version_bump.sql +58 -0
- package/migrations/tests/0006_genesis_support.test.sql +15 -3
- package/migrations/tests/0019_genesis_version_bump.test.sql +66 -0
- package/package.json +31 -1
- package/dist/chunk-34OBTZJQ.js.map +0 -1
package/README.md
CHANGED
|
@@ -202,12 +202,30 @@ const client = createAuthFormClient(supabase, {
|
|
|
202
202
|
| `signInWithPassword` | `signInWithPassword` |
|
|
203
203
|
| `sendMagicLink`, `sendEmailCode` | `signInWithOtp` (`shouldCreateUser` follows the form's `allowSignUp`; without sign-up, an unknown email is answered as sent) |
|
|
204
204
|
| `verifyEmailCode` | `verifyOtp({ email, token, type: "email" })` |
|
|
205
|
-
| `signUp` | `signUp
|
|
205
|
+
| `signUp` | `signUp`, with the form's `signUpFields` as `options.data` (the user's metadata); `confirmEmail` when no session came back |
|
|
206
206
|
| `sendPasswordReset` | `resetPasswordForEmail` to `resetRedirectTo` |
|
|
207
207
|
| `updatePassword` | `updateUser({ password })`, on the session the reset link opened (`session_not_found` without one) |
|
|
208
|
-
| `signInWithProvider` | `signInWithOAuth` (leaves the page for the provider) |
|
|
208
|
+
| `signInWithProvider` | `signInWithOAuth` to `providerRedirectTo`, with `providerQueryParams` (leaves the page for the provider) |
|
|
209
|
+
| `sendPhoneCode`, `verifyPhoneCode` | `signInWithOtp({ phone })`, then `verifyOtp({ phone, token, type: "sms" })`: the form's `"phone-code"` method |
|
|
210
|
+
| `currentEmail` | `getSession()`: the signed-in email, which the new-password form gives the password manager (no request) |
|
|
209
211
|
| `providers` | `fetchAuthSettings`: `GET /auth/v1/settings`, the OAuth providers turned on (asked once per client) |
|
|
210
212
|
|
|
213
|
+
**Where each link comes back to.** `redirectTo` is the default for all of them. `emailRedirectTo`
|
|
214
|
+
overrides it for the emailed links (a magic link, the sign-up confirmation), `resetRedirectTo` for
|
|
215
|
+
the reset link (default `emailRedirectTo`), and `providerRedirectTo` for the providers: a string,
|
|
216
|
+
or a function of the provider's id that returns `undefined` for the default. `providerQueryParams`
|
|
217
|
+
adds parameters to the provider's authorize URL, for every provider or per provider:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const client = createAuthFormClient(supabase, {
|
|
221
|
+
redirectTo: `${location.origin}/auth/callback`,
|
|
222
|
+
providerRedirectTo: (provider) => (provider === "apple" ? `${location.origin}/auth/apple` : undefined),
|
|
223
|
+
providerQueryParams: (provider) => (provider === "google" ? { access_type: "offline", prompt: "consent" } : undefined),
|
|
224
|
+
});
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
There's no need to override `signInWithProvider` for either.
|
|
228
|
+
|
|
211
229
|
Every failure resolves as `{ error: { code, message } }` with Auth's code (`network` for a request
|
|
212
230
|
that got no answer, `session_not_found` for `AuthSessionMissingError`), also on a client made with
|
|
213
231
|
`throwOnError: true`. The form shows fixed copy for the code; Auth's `message` is never shown, only
|
|
@@ -215,7 +233,15 @@ sent to `reportError` when the form has no copy for the code.
|
|
|
215
233
|
|
|
216
234
|
- **Codes need the template.** Supabase sends the Magic Link email for a link and for a code alike,
|
|
217
235
|
and the default template has only the link: put `{{ .Token }}` in it to offer `"email-code"`.
|
|
218
|
-
|
|
236
|
+
With `offerCodeOnConfirm` the form also offers the code after sign-up, so put it in the Confirm
|
|
237
|
+
signup template too (`verifyOtp` with `type: "email"` confirms the account).
|
|
238
|
+
- **The code's length is the project's.** The form's `codeLength` (default 6) must match the
|
|
239
|
+
project's `otp_length` (Auth settings, "Email OTP length"). `/auth/v1/settings` doesn't report
|
|
240
|
+
it, so nothing can check it for you: with a mismatch no code can be entered whole, and code sign-in fails.
|
|
241
|
+
- **A texted code** (`"phone-code"`) needs a phone provider (Twilio, MessageBird…) turned on in
|
|
242
|
+
the project's Auth settings; its code length is the project's SMS OTP length, and the form's
|
|
243
|
+
`codeLength` must match it as for email.
|
|
244
|
+
- **The redirects** (`redirectTo`, `emailRedirectTo`, `resetRedirectTo`, `providerRedirectTo`) must be in the project's redirect allow list.
|
|
219
245
|
`createGenesisSupabase()` uses the PKCE flow (a plain `createClient` from supabase-js defaults to
|
|
220
246
|
the implicit flow), and its callback page needs nothing more on the web (`detectSessionInUrl`).
|
|
221
247
|
A PKCE link only works in the browser that asked for it, where the code verifier is stored: a
|
|
@@ -945,6 +971,28 @@ events.track("task.completed", { feature: "tasks", tenantId, properties: { count
|
|
|
945
971
|
- A vendor (PostHog, Amplitude) is a later sink fed from these events; Genesis flags stay the
|
|
946
972
|
source of truth.
|
|
947
973
|
|
|
974
|
+
## Versioned writes (the versioned-writes block)
|
|
975
|
+
|
|
976
|
+
`genesis_version_bump` advances a row's version on every update, so the data provider's `version`
|
|
977
|
+
rule can refuse an edit made on a stale copy as a `conflict` instead of overwriting someone
|
|
978
|
+
else's. `genesis add versioned-writes` copies `migrations/0019_genesis_version_bump.sql` and its
|
|
979
|
+
pgTAP test.
|
|
980
|
+
|
|
981
|
+
```sql
|
|
982
|
+
alter table public.tasks add column version bigint not null default 1;
|
|
983
|
+
create trigger tasks_version_bump before update on public.tasks
|
|
984
|
+
for each row execute function public.genesis_version_bump('version');
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
- The argument names the column (default `version`). On every update the trigger sets it to the
|
|
988
|
+
old value plus one, whatever the update wrote, so a client can't hold it back or jump it ahead.
|
|
989
|
+
- An update that changes nothing still advances it: a spare bump only makes a stale copy
|
|
990
|
+
conflict, which is the safe side.
|
|
991
|
+
- A table without the column fails the update (`42703`) rather than skipping the check silently.
|
|
992
|
+
- Then give the resource the rule: `createSupabaseProvider(supabase, { resources: { tasks: {
|
|
993
|
+
version: { field: "version", kind: "integer" } } } })`. See genesis-core's README, "Versioned
|
|
994
|
+
writes".
|
|
995
|
+
|
|
948
996
|
## Testing your schema's data contract (genesis_testing)
|
|
949
997
|
|
|
950
998
|
`sql/testing/genesis_testing.sql` is a pgTAP kit that checks your own tables and functions keep the
|
|
@@ -993,7 +1041,7 @@ ids are shared with `@marktiderman/genesis-core/testing`.
|
|
|
993
1041
|
|
|
994
1042
|
## Blocks
|
|
995
1043
|
|
|
996
|
-
`accountBlock`, `tenantFeaturesBlock` and `
|
|
1044
|
+
`accountBlock`, `tenantFeaturesBlock`, `jobsBlock` and `versionedWritesBlock` are `defineBlock` declarations
|
|
997
1045
|
(`@marktiderman/genesis-features/blocks`) of what this package's blocks need: their migrations
|
|
998
1046
|
(with their tests) and, for the account, what it means for the stores' privacy forms. The
|
|
999
1047
|
functions above don't change; the declarations are for `resolveBlocks` and the shell.
|
package/dist/blocks.d.ts
CHANGED
|
@@ -46,5 +46,13 @@ declare const webHandoffBlock: _marktiderman_genesis_features_blocks.BlockDef<"w
|
|
|
46
46
|
* @stability Beta
|
|
47
47
|
*/
|
|
48
48
|
declare const eventsBlock: _marktiderman_genesis_features_blocks.BlockDef<"events", never>;
|
|
49
|
+
/**
|
|
50
|
+
* The versioned-writes block: `genesis_version_bump`, the trigger that advances a row's version on
|
|
51
|
+
* every update, so the Supabase data provider's `version` rule can refuse an edit made on a stale
|
|
52
|
+
* copy as a `conflict`.
|
|
53
|
+
*
|
|
54
|
+
* @stability Beta
|
|
55
|
+
*/
|
|
56
|
+
declare const versionedWritesBlock: _marktiderman_genesis_features_blocks.BlockDef<"versioned-writes", never>;
|
|
49
57
|
|
|
50
|
-
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
|
|
58
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock, webHandoffBlock };
|
package/dist/blocks.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock } from './chunk-
|
|
1
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock, webHandoffBlock } from './chunk-XESMEWXI.js';
|
|
2
2
|
//# sourceMappingURL=blocks.js.map
|
|
3
3
|
//# sourceMappingURL=blocks.js.map
|
|
@@ -127,7 +127,16 @@ var eventsBlock = defineBlock({
|
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
129
|
});
|
|
130
|
+
var versionedWritesBlock = defineBlock({
|
|
131
|
+
id: "versioned-writes",
|
|
132
|
+
platforms: ["web", "native"],
|
|
133
|
+
contributes: {
|
|
134
|
+
migrations: [
|
|
135
|
+
{ package: PACKAGE, file: "migrations/0019_genesis_version_bump.sql", test: "migrations/tests/0019_genesis_version_bump.test.sql" }
|
|
136
|
+
]
|
|
137
|
+
}
|
|
138
|
+
});
|
|
130
139
|
|
|
131
|
-
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
|
|
132
|
-
//# sourceMappingURL=chunk-
|
|
133
|
-
//# sourceMappingURL=chunk-
|
|
140
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock, webHandoffBlock };
|
|
141
|
+
//# sourceMappingURL=chunk-XESMEWXI.js.map
|
|
142
|
+
//# sourceMappingURL=chunk-XESMEWXI.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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,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAUM,IAAM,cAAc,WAAA,CAAY;AAAA,EACrC,EAAA,EAAI,QAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,oCAAA,EAAsC,IAAA,EAAM,+CAAA,EAAiD,CAAA;AAAA,IACpI,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AASM,IAAM,uBAAuB,WAAA,CAAY;AAAA,EAC9C,EAAA,EAAI,kBAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,0CAAA,EAA4C,MAAM,qDAAA;AAAsD;AACpI;AAEJ,CAAC","file":"chunk-XESMEWXI.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/**\n * The product events block: the app's own events table and its tracking functions (ADR 0010).\n * The client is `createEventTracker` from `/events`; on native, `createEventsSink` plugs it into the\n * observability sinks.\n *\n * @stability Beta\n */\nexport const eventsBlock = defineBlock({\n id: \"events\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0018_genesis_events.sql\", test: \"migrations/tests/0018_genesis_events.test.sql\" }],\n privacy: {\n notes: [\n \"Stores product events: the login, the person record and tenant, the feature, an event name, small properties (labels and counts, never typed content or personal data), the flags that were on, the platform and the time. Only the service role reads them; delete old ones with genesis_prune_events (default 400 days).\",\n ],\n },\n },\n});\n\n/**\n * The versioned-writes block: `genesis_version_bump`, the trigger that advances a row's version on\n * every update, so the Supabase data provider's `version` rule can refuse an edit made on a stale\n * copy as a `conflict`.\n *\n * @stability Beta\n */\nexport const versionedWritesBlock = defineBlock({\n id: \"versioned-writes\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0019_genesis_version_bump.sql\", test: \"migrations/tests/0019_genesis_version_bump.test.sql\" },\n ],\n },\n});\n"]}
|
|
@@ -273,13 +273,16 @@ declare function syncFeatureRegistry(client: FeatureRegistryClient, document: Fe
|
|
|
273
273
|
/**
|
|
274
274
|
* Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each
|
|
275
275
|
* of its modes makes (password, magic link, emailed code, sign-up, reset, new
|
|
276
|
-
* password, providers) and the provider list read from the project's
|
|
276
|
+
* password, providers, a texted code) and the provider list read from the project's
|
|
277
277
|
* `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.
|
|
278
278
|
*/
|
|
279
279
|
|
|
280
|
-
/**
|
|
280
|
+
/**
|
|
281
|
+
* The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.
|
|
282
|
+
* `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).
|
|
283
|
+
*/
|
|
281
284
|
interface AuthFormSupabase {
|
|
282
|
-
auth: Pick<SupabaseClient["auth"], "signInWithPassword" | "signInWithOtp" | "verifyOtp" | "signUp" | "resetPasswordForEmail" | "updateUser" | "signInWithOAuth"
|
|
285
|
+
auth: Pick<SupabaseClient["auth"], "signInWithPassword" | "signInWithOtp" | "verifyOtp" | "signUp" | "resetPasswordForEmail" | "updateUser" | "signInWithOAuth"> & Partial<Pick<SupabaseClient["auth"], "getSession">>;
|
|
283
286
|
}
|
|
284
287
|
/**
|
|
285
288
|
* Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,
|
|
@@ -321,9 +324,11 @@ interface AuthFormSupabaseClient {
|
|
|
321
324
|
email: string;
|
|
322
325
|
code: string;
|
|
323
326
|
}): Promise<AuthCallResult>;
|
|
327
|
+
/** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */
|
|
324
328
|
signUp(input: {
|
|
325
329
|
email: string;
|
|
326
330
|
password: string;
|
|
331
|
+
data?: Record<string, unknown>;
|
|
327
332
|
}): Promise<AuthCallResult>;
|
|
328
333
|
sendPasswordReset(input: {
|
|
329
334
|
email: string;
|
|
@@ -332,6 +337,18 @@ interface AuthFormSupabaseClient {
|
|
|
332
337
|
password: string;
|
|
333
338
|
}): Promise<AuthCallResult>;
|
|
334
339
|
signInWithProvider(provider: string): Promise<AuthCallResult>;
|
|
340
|
+
/** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */
|
|
341
|
+
sendPhoneCode(input: {
|
|
342
|
+
phone: string;
|
|
343
|
+
createUser: boolean;
|
|
344
|
+
}): Promise<AuthCallResult>;
|
|
345
|
+
/** Checks a texted code (`verifyOtp({ phone, token, type: "sms" })`). */
|
|
346
|
+
verifyPhoneCode(input: {
|
|
347
|
+
phone: string;
|
|
348
|
+
code: string;
|
|
349
|
+
}): Promise<AuthCallResult>;
|
|
350
|
+
/** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */
|
|
351
|
+
currentEmail?(): Promise<string | null>;
|
|
335
352
|
/** Present when `url` and `publishableKey` were given. */
|
|
336
353
|
providers?(): Promise<string[]>;
|
|
337
354
|
}
|
|
@@ -347,8 +364,22 @@ interface CreateAuthFormClientOptions {
|
|
|
347
364
|
* project's redirect allow list. Left out: the project's Site URL.
|
|
348
365
|
*/
|
|
349
366
|
redirectTo?: string;
|
|
350
|
-
/** Where the
|
|
367
|
+
/** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */
|
|
368
|
+
emailRedirectTo?: string;
|
|
369
|
+
/** Where the password-reset link opens: the page that shows `mode="new-password"`. Default `emailRedirectTo`, then `redirectTo`. */
|
|
351
370
|
resetRedirectTo?: string;
|
|
371
|
+
/**
|
|
372
|
+
* Where a provider sends the person back to, for every provider or per provider (a function of
|
|
373
|
+
* its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the
|
|
374
|
+
* project's redirect allow list. Default `redirectTo`.
|
|
375
|
+
*/
|
|
376
|
+
providerRedirectTo?: string | ((provider: string) => string | undefined);
|
|
377
|
+
/**
|
|
378
|
+
* Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s
|
|
379
|
+
* `options.queryParams`): Google's `{ access_type: "offline", prompt: "consent" }`, say. One
|
|
380
|
+
* record for every provider, or a function of the provider's id. Default none.
|
|
381
|
+
*/
|
|
382
|
+
providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);
|
|
352
383
|
/** For the settings request. Default the global `fetch`. */
|
|
353
384
|
fetch?: typeof fetch;
|
|
354
385
|
}
|
|
@@ -357,7 +388,9 @@ interface CreateAuthFormClientOptions {
|
|
|
357
388
|
* link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),
|
|
358
389
|
* sign-up (`confirmEmail` when the project confirms emails), the reset email,
|
|
359
390
|
* the new password (`updateUser`, on the session the reset link opened), and
|
|
360
|
-
* OAuth providers (`signInWithOAuth`, which leaves the page
|
|
391
|
+
* OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and
|
|
392
|
+
* `providerQueryParams` shape where it goes), and a code by text message
|
|
393
|
+
* (`signInWithOtp({ phone })`, checked with `verifyOtp` type `"sms"`). Every failure is
|
|
361
394
|
* `{ error: { code, message } }`, never a throw, also on a client made with
|
|
362
395
|
* `throwOnError: true`.
|
|
363
396
|
*
|
|
@@ -375,7 +408,10 @@ interface CreateAuthFormClientOptions {
|
|
|
375
408
|
*
|
|
376
409
|
* One email template serves the link and the code: Supabase sends the Magic
|
|
377
410
|
* Link template for both, so a form offering `"email-code"` needs
|
|
378
|
-
* `{{ .Token }}` in it (the default template has only the link).
|
|
411
|
+
* `{{ .Token }}` in it (the default template has only the link). The form's
|
|
412
|
+
* `codeLength` must match the project's `otp_length`, which
|
|
413
|
+
* `/auth/v1/settings` doesn't report: with a mismatch no code can be entered
|
|
414
|
+
* whole, and code sign-in fails.
|
|
379
415
|
*
|
|
380
416
|
* ```ts
|
|
381
417
|
* const client = createAuthFormClient(supabase, {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import '@supabase/supabase-js';
|
|
2
|
-
export { A as APPLE_REVOKE_FUNCTION, c as AuthCallError, d as AuthCallResult, e as AuthFormSupabase, f as AuthFormSupabaseClient, g as AuthSettings, C as CreateAuthFormClientOptions, D as DeleteAccountClient, j as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, k as FeatureGateStateOptions, l as FeatureRegistryClient, m as FeatureRegistryDocument, n as FlagStateValue, o as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, p as SUPABASE_OAUTH_PROVIDERS, S as SessionStorage, q as SetTenantFeatureInput, r as StoreAppleTokenOptions, s as StoreAppleTokenResult, t as SupabaseQueryError, u as SyncFeatureRegistryOptions, T as TenantFeatureChange, v as TenantFeatureSetting, w as TenantFeatures, x as TenantFeaturesClient, y as createAuthFormClient, z as createGenesisSupabase, B as deleteMyAccount, H as featureGateState, I as fetchAuthSettings, J as must, K as requestAppleRevocation, L as setTenantFeature, M as storeAppleToken, N as syncFeatureRegistry, O as tenantFeatureHistory, Q as tenantFeatureSettings, R as tenantFeatures } from './index-
|
|
3
|
-
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
|
|
2
|
+
export { A as APPLE_REVOKE_FUNCTION, c as AuthCallError, d as AuthCallResult, e as AuthFormSupabase, f as AuthFormSupabaseClient, g as AuthSettings, C as CreateAuthFormClientOptions, D as DeleteAccountClient, j as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, k as FeatureGateStateOptions, l as FeatureRegistryClient, m as FeatureRegistryDocument, n as FlagStateValue, o as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, p as SUPABASE_OAUTH_PROVIDERS, S as SessionStorage, q as SetTenantFeatureInput, r as StoreAppleTokenOptions, s as StoreAppleTokenResult, t as SupabaseQueryError, u as SyncFeatureRegistryOptions, T as TenantFeatureChange, v as TenantFeatureSetting, w as TenantFeatures, x as TenantFeaturesClient, y as createAuthFormClient, z as createGenesisSupabase, B as deleteMyAccount, H as featureGateState, I as fetchAuthSettings, J as must, K as requestAppleRevocation, L as setTenantFeature, M as storeAppleToken, N as syncFeatureRegistry, O as tenantFeatureHistory, Q as tenantFeatureSettings, R as tenantFeatures } from './index-CKloeGaz.js';
|
|
3
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock } 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, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-
|
|
2
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock } from './chunk-XESMEWXI.js';
|
|
3
3
|
import { createClient, AuthInvalidJwtError, isAuthError } from '@supabase/supabase-js';
|
|
4
4
|
|
|
5
5
|
// src/apple-tokens.ts
|
|
@@ -123,20 +123,21 @@ async function call(run) {
|
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
function createAuthFormClient(supabase, options = {}) {
|
|
126
|
-
const { url, publishableKey, redirectTo,
|
|
126
|
+
const { url, publishableKey, redirectTo, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;
|
|
127
127
|
const auth = supabase.auth;
|
|
128
128
|
const otp = (email, createUser) => call(
|
|
129
|
-
() => auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...
|
|
129
|
+
() => auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...emailRedirectTo ? { emailRedirectTo } : {} } })
|
|
130
130
|
);
|
|
131
131
|
const client = {
|
|
132
132
|
signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),
|
|
133
133
|
sendMagicLink: ({ email, createUser }) => otp(email, createUser),
|
|
134
134
|
sendEmailCode: ({ email, createUser }) => otp(email, createUser),
|
|
135
135
|
verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: "email" })),
|
|
136
|
-
signUp: async ({ email, password }) => {
|
|
136
|
+
signUp: async ({ email, password, data }) => {
|
|
137
137
|
let confirmEmail = false;
|
|
138
|
+
const signUpOptions = { ...emailRedirectTo ? { emailRedirectTo } : {}, ...data ? { data } : {} };
|
|
138
139
|
const result = await call(async () => {
|
|
139
|
-
const r = await auth.signUp({ email, password, ...
|
|
140
|
+
const r = await auth.signUp({ email, password, ...Object.keys(signUpOptions).length ? { options: signUpOptions } : {} });
|
|
140
141
|
confirmEmail = !r.error && !r.data.session;
|
|
141
142
|
return r;
|
|
142
143
|
});
|
|
@@ -144,13 +145,30 @@ function createAuthFormClient(supabase, options = {}) {
|
|
|
144
145
|
},
|
|
145
146
|
sendPasswordReset: ({ email }) => call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : void 0)),
|
|
146
147
|
updatePassword: ({ password }) => call(() => auth.updateUser({ password })),
|
|
147
|
-
signInWithProvider: (provider) =>
|
|
148
|
-
()
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
148
|
+
signInWithProvider: (provider) => {
|
|
149
|
+
const back = (typeof providerRedirectTo === "function" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;
|
|
150
|
+
const queryParams = typeof providerQueryParams === "function" ? providerQueryParams(provider) : providerQueryParams;
|
|
151
|
+
const oauthOptions = { ...back ? { redirectTo: back } : {}, ...queryParams && Object.keys(queryParams).length ? { queryParams } : {} };
|
|
152
|
+
return call(
|
|
153
|
+
() => auth.signInWithOAuth({
|
|
154
|
+
provider,
|
|
155
|
+
...Object.keys(oauthOptions).length ? { options: oauthOptions } : {}
|
|
156
|
+
})
|
|
157
|
+
);
|
|
158
|
+
},
|
|
159
|
+
sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),
|
|
160
|
+
verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: "sms" }))
|
|
153
161
|
};
|
|
162
|
+
const getSession = auth.getSession?.bind(auth);
|
|
163
|
+
if (getSession) {
|
|
164
|
+
client.currentEmail = async () => {
|
|
165
|
+
try {
|
|
166
|
+
return (await getSession()).data.session?.user.email ?? null;
|
|
167
|
+
} catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
154
172
|
if (url && publishableKey) {
|
|
155
173
|
let providers;
|
|
156
174
|
client.providers = () => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/auth-form-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GAAI,QAAA,GAAW,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG,EAAG,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and the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each\n * of its modes makes (password, magic link, emailed code, sign-up, reset, new\n * password, providers) and the provider list read from the project's\n * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.\n */\nimport { isAuthError, type SupabaseClient } from \"@supabase/supabase-js\";\n\n/** The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits. */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n >;\n}\n\n/**\n * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,\n * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when\n * there is no session (`AuthSessionMissingError`), or `network` when the\n * request never got an answer. The shape genesis-ui's `AuthFormError` reads.\n * `message` is the server's text: the form never shows it (it is not marked\n * `displayable`), only reports it for a code it has no copy for.\n */\nexport interface AuthCallError {\n code?: string;\n message?: string;\n}\n\n/** What each call resolves with. Never throws. */\nexport interface AuthCallResult {\n error?: AuthCallError | null;\n /** From `signUp`: the account waits for its email to be confirmed. */\n confirmEmail?: boolean;\n}\n\n/**\n * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.\n *\n * @stability Beta\n */\nexport interface AuthFormSupabaseClient {\n signInWithPassword(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendMagicLink(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n sendEmailCode(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n verifyEmailCode(input: { email: string; code: string }): Promise<AuthCallResult>;\n signUp(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\n /** Present when `url` and `publishableKey` were given. */\n providers?(): Promise<string[]>;\n}\n\n/** @stability Beta */\nexport interface CreateAuthFormClientOptions {\n /** The project URL, with `publishableKey`: lets the form discover its providers. */\n url?: string;\n /** The publishable (anon) key. */\n publishableKey?: string;\n /**\n * Where a magic link, a sign-up confirmation and a provider come back to:\n * the app's callback route (`${origin}/auth/callback`). It must be in the\n * project's redirect allow list. Left out: the project's Site URL.\n */\n redirectTo?: string;\n /** Where the password-reset link opens: the page that shows `mode=\"new-password\"`. Default `redirectTo`. */\n resetRedirectTo?: string;\n /** For the settings request. Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ntype SupabaseAuthResult = { data?: unknown; error: { code?: string | undefined; message: string; name?: string; status?: number | undefined } | null };\n\ntype SupabaseAuthError = NonNullable<SupabaseAuthResult[\"error\"]>;\n\nfunction toResult(e: SupabaseAuthError | null): AuthCallResult {\n if (!e) return {};\n // supabase-js answers a request that never reached Auth with AuthRetryableFetchError, status 0.\n const network = e.name === \"AuthRetryableFetchError\" || e.status === 0;\n // updateUser with no session: AuthSessionMissingError, which has no code.\n const missingSession = e.name === \"AuthSessionMissingError\";\n const code = e.code ?? (missingSession ? \"session_not_found\" : network ? \"network\" : undefined);\n return { error: { ...(code ? { code } : {}), message: e.message } };\n}\n\nasync function call(run: () => Promise<SupabaseAuthResult>): Promise<AuthCallResult> {\n try {\n return toResult((await run()).error);\n } catch (e) {\n // A client made with `throwOnError: true` throws Auth's errors: read them like a returned one.\n if (isAuthError(e)) return toResult(e as SupabaseAuthError);\n return { error: { code: \"network\", message: e instanceof Error ? e.message : \"The request failed\" } };\n }\n}\n\n/**\n * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic\n * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),\n * sign-up (`confirmEmail` when the project confirms emails), the reset email,\n * the new password (`updateUser`, on the session the reset link opened), and\n * OAuth providers (`signInWithOAuth`, which leaves the page). Every failure is\n * `{ error: { code, message } }`, never a throw, also on a client made with\n * `throwOnError: true`.\n *\n * It takes the app's client (from `createGenesisSupabase()`) and makes no\n * client of its own.\n *\n * Without sign-up (`createUser: false`), an email with no account is answered\n * like one with an account: the link or code is \"sent\". Saying otherwise would\n * tell anyone which emails have accounts.\n *\n * The new-password page: show `mode=\"new-password\"` only after the client's\n * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the\n * session the reset link opened, `updatePassword` fails with\n * `session_not_found`.\n *\n * One email template serves the link and the code: Supabase sends the Magic\n * Link template for both, so a form offering `\"email-code\"` needs\n * `{{ .Token }}` in it (the default template has only the link).\n *\n * ```ts\n * const client = createAuthFormClient(supabase, {\n * url: import.meta.env.VITE_SUPABASE_URL,\n * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,\n * redirectTo: `${location.origin}/auth/callback`,\n * resetRedirectTo: `${location.origin}/auth/new-password`,\n * });\n * ```\n *\n * @stability Beta\n */\nexport function createAuthFormClient(supabase: AuthFormSupabase, options: CreateAuthFormClientOptions = {}): AuthFormSupabaseClient {\n const { url, publishableKey, redirectTo, resetRedirectTo = redirectTo } = options;\n const auth = supabase.auth;\n // Without sign-up, Auth refuses an unknown email with otp_disabled (\"Signups not allowed for otp\").\n // The client passes it on as it is; AuthForm answers it as sent, so it doesn't say which emails\n // have accounts (one place, for every client).\n const otp = (email: string, createUser: boolean): Promise<AuthCallResult> =>\n call(() =>\n auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...(redirectTo ? { emailRedirectTo: redirectTo } : {}) } }),\n );\n const client: AuthFormSupabaseClient = {\n signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),\n sendMagicLink: ({ email, createUser }) => otp(email, createUser),\n sendEmailCode: ({ email, createUser }) => otp(email, createUser),\n verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: \"email\" })),\n signUp: async ({ email, password }) => {\n let confirmEmail = false;\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(redirectTo ? { options: { emailRedirectTo: redirectTo } } : {}) });\n confirmEmail = !r.error && !r.data.session;\n return r;\n });\n return confirmEmail ? { ...result, confirmEmail } : result;\n },\n sendPasswordReset: ({ email }) =>\n call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : undefined)),\n updatePassword: ({ password }) => call(() => auth.updateUser({ password })),\n signInWithProvider: (provider) =>\n call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(redirectTo ? { options: { redirectTo } } : {}),\n }),\n ),\n };\n if (url && publishableKey) {\n // Asked once per client: the form may mount many times, the project's providers don't change.\n let providers: Promise<string[]> | undefined;\n client.providers = () => {\n providers ??= fetchAuthSettings({ url, publishableKey, ...(options.fetch ? { fetch: options.fetch } : {}) }).then(\n (settings) => settings.providers,\n (e: unknown) => {\n providers = undefined; // a failed lookup can be tried again\n throw e;\n },\n );\n return providers;\n };\n }\n return client;\n}\n\n/** What a project's Auth allows, from `/auth/v1/settings`. */\nexport interface AuthSettings {\n /** The OAuth providers turned on, as `signInWithOAuth` names them (`\"google\"`, `\"apple\"`…), sorted. */\n providers: string[];\n /** Email sign-in (password, link or code) is on. */\n email: boolean;\n /** Phone sign-in is on. */\n phone: boolean;\n /** New accounts are refused. */\n signUpDisabled: boolean;\n /** Emails are confirmed without a link. */\n autoConfirm: boolean;\n}\n\n/**\n * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`\n * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the\n * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.\n *\n * @stability Beta\n */\nexport const SUPABASE_OAUTH_PROVIDERS: readonly string[] = [\n \"apple\",\n \"azure\",\n \"bitbucket\",\n \"discord\",\n \"facebook\",\n \"figma\",\n \"github\",\n \"gitlab\",\n \"google\",\n \"kakao\",\n \"keycloak\",\n \"linkedin_oidc\",\n \"notion\",\n \"slack_oidc\",\n \"spotify\",\n \"twitch\",\n \"twitter\",\n \"workos\",\n \"zoom\",\n];\nconst OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);\n\n/** How long the settings request may take. */\nconst SETTINGS_TIMEOUT_MS = 5000;\n\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end--;\n return url.slice(0, end);\n}\n\n/**\n * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with\n * the publishable key): which OAuth providers are on, whether email and phone\n * sign-in are, and whether sign-up is closed. Throws when the request fails,\n * takes over 5 seconds or `signal` aborts it, and refuses a secret key\n * (`sb_secret_…`), which must never reach a browser.\n *\n * @stability Beta\n */\nexport async function fetchAuthSettings({\n url,\n publishableKey,\n fetch: fetcher = globalThis.fetch,\n signal,\n}: {\n url: string;\n publishableKey: string;\n fetch?: typeof fetch;\n /** Cancels the request (an unmounting form, say). */\n signal?: AbortSignal;\n}): Promise<AuthSettings> {\n if (publishableKey.startsWith(\"sb_secret_\")) {\n throw new Error(\"fetchAuthSettings takes the publishable key, not a secret key (sb_secret_…)\");\n }\n // A controller and a timer rather than AbortSignal.timeout/any, which older Safari and React\n // Native's Hermes lack.\n const controller = new AbortController();\n const timer = setTimeout(() => {\n const timedOut = new Error(\"Supabase Auth settings: timed out\");\n timedOut.name = \"TimeoutError\";\n controller.abort(timedOut);\n }, SETTINGS_TIMEOUT_MS);\n const onAbort = () => controller.abort(signal?.reason);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n let response: Response;\n try {\n response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {\n headers: { apikey: publishableKey },\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);\n const body = (await response.json()) as {\n external?: Record<string, unknown>;\n disable_signup?: unknown;\n mailer_autoconfirm?: unknown;\n };\n const external = body.external ?? {};\n return {\n providers: Object.keys(external)\n .filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key))\n .sort(),\n email: external.email === true,\n phone: external.phone === true,\n signUpDisabled: body.disable_signup === true,\n autoConfirm: body.mailer_autoconfirm === true,\n };\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\nexport {\n createAuthFormClient,\n fetchAuthSettings,\n SUPABASE_OAUTH_PROVIDERS,\n type AuthCallError,\n type AuthCallResult,\n type AuthFormSupabase,\n type AuthFormSupabaseClient,\n type AuthSettings,\n type CreateAuthFormClientOptions,\n} from \"./auth-form-client\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/auth-form-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GA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,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each\n * of its modes makes (password, magic link, emailed code, sign-up, reset, new\n * password, providers, a texted code) and the provider list read from the project's\n * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.\n */\nimport { isAuthError, type SupabaseClient } from \"@supabase/supabase-js\";\n\n/**\n * The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.\n * `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).\n */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n > &\n Partial<Pick<SupabaseClient[\"auth\"], \"getSession\">>;\n}\n\n/**\n * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,\n * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when\n * there is no session (`AuthSessionMissingError`), or `network` when the\n * request never got an answer. The shape genesis-ui's `AuthFormError` reads.\n * `message` is the server's text: the form never shows it (it is not marked\n * `displayable`), only reports it for a code it has no copy for.\n */\nexport interface AuthCallError {\n code?: string;\n message?: string;\n}\n\n/** What each call resolves with. Never throws. */\nexport interface AuthCallResult {\n error?: AuthCallError | null;\n /** From `signUp`: the account waits for its email to be confirmed. */\n confirmEmail?: boolean;\n}\n\n/**\n * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.\n *\n * @stability Beta\n */\nexport interface AuthFormSupabaseClient {\n signInWithPassword(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendMagicLink(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n sendEmailCode(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n verifyEmailCode(input: { email: string; code: string }): Promise<AuthCallResult>;\n /** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */\n signUp(input: { email: string; password: string; data?: Record<string, unknown> }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\n /** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */\n sendPhoneCode(input: { phone: string; createUser: boolean }): Promise<AuthCallResult>;\n /** Checks a texted code (`verifyOtp({ phone, token, type: \"sms\" })`). */\n verifyPhoneCode(input: { phone: string; code: string }): Promise<AuthCallResult>;\n /** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */\n currentEmail?(): Promise<string | null>;\n /** Present when `url` and `publishableKey` were given. */\n providers?(): Promise<string[]>;\n}\n\n/** @stability Beta */\nexport interface CreateAuthFormClientOptions {\n /** The project URL, with `publishableKey`: lets the form discover its providers. */\n url?: string;\n /** The publishable (anon) key. */\n publishableKey?: string;\n /**\n * Where a magic link, a sign-up confirmation and a provider come back to:\n * the app's callback route (`${origin}/auth/callback`). It must be in the\n * project's redirect allow list. Left out: the project's Site URL.\n */\n redirectTo?: string;\n /** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */\n emailRedirectTo?: string;\n /** Where the password-reset link opens: the page that shows `mode=\"new-password\"`. Default `emailRedirectTo`, then `redirectTo`. */\n resetRedirectTo?: string;\n /**\n * Where a provider sends the person back to, for every provider or per provider (a function of\n * its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the\n * project's redirect allow list. Default `redirectTo`.\n */\n providerRedirectTo?: string | ((provider: string) => string | undefined);\n /**\n * Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s\n * `options.queryParams`): Google's `{ access_type: \"offline\", prompt: \"consent\" }`, say. One\n * record for every provider, or a function of the provider's id. Default none.\n */\n providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);\n /** For the settings request. Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ntype SupabaseAuthResult = { data?: unknown; error: { code?: string | undefined; message: string; name?: string; status?: number | undefined } | null };\n\ntype SupabaseAuthError = NonNullable<SupabaseAuthResult[\"error\"]>;\n\nfunction toResult(e: SupabaseAuthError | null): AuthCallResult {\n if (!e) return {};\n // supabase-js answers a request that never reached Auth with AuthRetryableFetchError, status 0.\n const network = e.name === \"AuthRetryableFetchError\" || e.status === 0;\n // updateUser with no session: AuthSessionMissingError, which has no code.\n const missingSession = e.name === \"AuthSessionMissingError\";\n const code = e.code ?? (missingSession ? \"session_not_found\" : network ? \"network\" : undefined);\n return { error: { ...(code ? { code } : {}), message: e.message } };\n}\n\nasync function call(run: () => Promise<SupabaseAuthResult>): Promise<AuthCallResult> {\n try {\n return toResult((await run()).error);\n } catch (e) {\n // A client made with `throwOnError: true` throws Auth's errors: read them like a returned one.\n if (isAuthError(e)) return toResult(e as SupabaseAuthError);\n return { error: { code: \"network\", message: e instanceof Error ? e.message : \"The request failed\" } };\n }\n}\n\n/**\n * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic\n * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),\n * sign-up (`confirmEmail` when the project confirms emails), the reset email,\n * the new password (`updateUser`, on the session the reset link opened), and\n * OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and\n * `providerQueryParams` shape where it goes), and a code by text message\n * (`signInWithOtp({ phone })`, checked with `verifyOtp` type `\"sms\"`). Every failure is\n * `{ error: { code, message } }`, never a throw, also on a client made with\n * `throwOnError: true`.\n *\n * It takes the app's client (from `createGenesisSupabase()`) and makes no\n * client of its own.\n *\n * Without sign-up (`createUser: false`), an email with no account is answered\n * like one with an account: the link or code is \"sent\". Saying otherwise would\n * tell anyone which emails have accounts.\n *\n * The new-password page: show `mode=\"new-password\"` only after the client's\n * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the\n * session the reset link opened, `updatePassword` fails with\n * `session_not_found`.\n *\n * One email template serves the link and the code: Supabase sends the Magic\n * Link template for both, so a form offering `\"email-code\"` needs\n * `{{ .Token }}` in it (the default template has only the link). The form's\n * `codeLength` must match the project's `otp_length`, which\n * `/auth/v1/settings` doesn't report: with a mismatch no code can be entered\n * whole, and code sign-in fails.\n *\n * ```ts\n * const client = createAuthFormClient(supabase, {\n * url: import.meta.env.VITE_SUPABASE_URL,\n * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,\n * redirectTo: `${location.origin}/auth/callback`,\n * resetRedirectTo: `${location.origin}/auth/new-password`,\n * });\n * ```\n *\n * @stability Beta\n */\nexport function createAuthFormClient(supabase: AuthFormSupabase, options: CreateAuthFormClientOptions = {}): AuthFormSupabaseClient {\n const { url, publishableKey, redirectTo, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;\n const auth = supabase.auth;\n // Without sign-up, Auth refuses an unknown email with otp_disabled (\"Signups not allowed for otp\").\n // The client passes it on as it is; AuthForm answers it as sent, so it doesn't say which emails\n // have accounts (one place, for every client).\n const otp = (email: string, createUser: boolean): Promise<AuthCallResult> =>\n call(() =>\n auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...(emailRedirectTo ? { emailRedirectTo } : {}) } }),\n );\n const client: AuthFormSupabaseClient = {\n signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),\n sendMagicLink: ({ email, createUser }) => otp(email, createUser),\n sendEmailCode: ({ email, createUser }) => otp(email, createUser),\n verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: \"email\" })),\n signUp: async ({ email, password, data }) => {\n let confirmEmail = false;\n const signUpOptions = { ...(emailRedirectTo ? { emailRedirectTo } : {}), ...(data ? { data } : {}) };\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(Object.keys(signUpOptions).length ? { options: signUpOptions } : {}) });\n confirmEmail = !r.error && !r.data.session;\n return r;\n });\n return confirmEmail ? { ...result, confirmEmail } : result;\n },\n sendPasswordReset: ({ email }) =>\n call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : undefined)),\n updatePassword: ({ password }) => call(() => auth.updateUser({ password })),\n signInWithProvider: (provider) => {\n const back = (typeof providerRedirectTo === \"function\" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;\n const queryParams = typeof providerQueryParams === \"function\" ? providerQueryParams(provider) : providerQueryParams;\n const oauthOptions = { ...(back ? { redirectTo: back } : {}), ...(queryParams && Object.keys(queryParams).length ? { queryParams } : {}) };\n return call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(Object.keys(oauthOptions).length ? { options: oauthOptions } : {}),\n }),\n );\n },\n sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),\n verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: \"sms\" })),\n };\n const getSession = auth.getSession?.bind(auth);\n if (getSession) {\n client.currentEmail = async () => {\n try {\n return (await getSession()).data.session?.user.email ?? null;\n } catch {\n return null;\n }\n };\n }\n if (url && publishableKey) {\n // Asked once per client: the form may mount many times, the project's providers don't change.\n let providers: Promise<string[]> | undefined;\n client.providers = () => {\n providers ??= fetchAuthSettings({ url, publishableKey, ...(options.fetch ? { fetch: options.fetch } : {}) }).then(\n (settings) => settings.providers,\n (e: unknown) => {\n providers = undefined; // a failed lookup can be tried again\n throw e;\n },\n );\n return providers;\n };\n }\n return client;\n}\n\n/** What a project's Auth allows, from `/auth/v1/settings`. */\nexport interface AuthSettings {\n /** The OAuth providers turned on, as `signInWithOAuth` names them (`\"google\"`, `\"apple\"`…), sorted. */\n providers: string[];\n /** Email sign-in (password, link or code) is on. */\n email: boolean;\n /** Phone sign-in is on. */\n phone: boolean;\n /** New accounts are refused. */\n signUpDisabled: boolean;\n /** Emails are confirmed without a link. */\n autoConfirm: boolean;\n}\n\n/**\n * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`\n * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the\n * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.\n *\n * @stability Beta\n */\nexport const SUPABASE_OAUTH_PROVIDERS: readonly string[] = [\n \"apple\",\n \"azure\",\n \"bitbucket\",\n \"discord\",\n \"facebook\",\n \"figma\",\n \"github\",\n \"gitlab\",\n \"google\",\n \"kakao\",\n \"keycloak\",\n \"linkedin_oidc\",\n \"notion\",\n \"slack_oidc\",\n \"spotify\",\n \"twitch\",\n \"twitter\",\n \"workos\",\n \"zoom\",\n];\nconst OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);\n\n/** How long the settings request may take. */\nconst SETTINGS_TIMEOUT_MS = 5000;\n\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end--;\n return url.slice(0, end);\n}\n\n/**\n * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with\n * the publishable key): which OAuth providers are on, whether email and phone\n * sign-in are, and whether sign-up is closed. Throws when the request fails,\n * takes over 5 seconds or `signal` aborts it, and refuses a secret key\n * (`sb_secret_…`), which must never reach a browser.\n *\n * @stability Beta\n */\nexport async function fetchAuthSettings({\n url,\n publishableKey,\n fetch: fetcher = globalThis.fetch,\n signal,\n}: {\n url: string;\n publishableKey: string;\n fetch?: typeof fetch;\n /** Cancels the request (an unmounting form, say). */\n signal?: AbortSignal;\n}): Promise<AuthSettings> {\n if (publishableKey.startsWith(\"sb_secret_\")) {\n throw new Error(\"fetchAuthSettings takes the publishable key, not a secret key (sb_secret_…)\");\n }\n // A controller and a timer rather than AbortSignal.timeout/any, which older Safari and React\n // Native's Hermes lack.\n const controller = new AbortController();\n const timer = setTimeout(() => {\n const timedOut = new Error(\"Supabase Auth settings: timed out\");\n timedOut.name = \"TimeoutError\";\n controller.abort(timedOut);\n }, SETTINGS_TIMEOUT_MS);\n const onAbort = () => controller.abort(signal?.reason);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n let response: Response;\n try {\n response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {\n headers: { apikey: publishableKey },\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);\n const body = (await response.json()) as {\n external?: Record<string, unknown>;\n disable_signup?: unknown;\n mailer_autoconfirm?: unknown;\n };\n const external = body.external ?? {};\n return {\n providers: Object.keys(external)\n .filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key))\n .sort(),\n email: external.email === true,\n phone: external.phone === true,\n signUpDisabled: body.disable_signup === true,\n autoConfirm: body.mailer_autoconfirm === true,\n };\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock } from \"./blocks\";\nexport {\n createAuthFormClient,\n fetchAuthSettings,\n SUPABASE_OAUTH_PROVIDERS,\n type AuthCallError,\n type AuthCallResult,\n type AuthFormSupabase,\n type AuthFormSupabaseClient,\n type AuthSettings,\n type CreateAuthFormClientOptions,\n} from \"./auth-form-client\";\n"]}
|
package/dist/native.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as SessionStorage } from './index-
|
|
2
|
-
export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-
|
|
1
|
+
import { S as SessionStorage } from './index-CKloeGaz.js';
|
|
2
|
+
export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-CKloeGaz.js';
|
|
3
3
|
import { Session, SupabaseClient, User } from '@supabase/supabase-js';
|
|
4
4
|
import './blocks.js';
|
|
5
5
|
import '@marktiderman/genesis-features/blocks';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
-- Genesis version bump: a trigger that advances a row's version on every update
|
|
2
|
+
--
|
|
3
|
+
-- The Supabase data provider checks updates and deletes against the version the client read the
|
|
4
|
+
-- row at (a resource's `version: { field, kind: "integer" }` rule), so an edit made on a stale
|
|
5
|
+
-- copy is refused as a conflict instead of overwriting someone else's. That only works when the
|
|
6
|
+
-- database advances the version on every update, whoever makes it (the app, a function, the SQL
|
|
7
|
+
-- editor). This trigger does that:
|
|
8
|
+
--
|
|
9
|
+
-- alter table public.tasks add column version bigint not null default 1;
|
|
10
|
+
-- create trigger tasks_version_bump before update on public.tasks
|
|
11
|
+
-- for each row execute function public.genesis_version_bump('version');
|
|
12
|
+
--
|
|
13
|
+
-- The argument names the column (default `version`), an integer column (bigint, say); any other
|
|
14
|
+
-- type is an error (a `kind: "timestamp"` version uses a `moddatetime`-style trigger instead).
|
|
15
|
+
-- On every update it sets the column to the old value plus one, whatever the update wrote there,
|
|
16
|
+
-- so a client can neither hold the version back nor jump it ahead. An update that changes nothing still advances it: Postgres can't tell an
|
|
17
|
+
-- unchanged row from a changed one cheaply, and a spare bump only makes a stale copy conflict,
|
|
18
|
+
-- which is the safe side.
|
|
19
|
+
--
|
|
20
|
+
-- It is a plain trigger function (security invoker, search_path ''); it reads and writes only the
|
|
21
|
+
-- row being updated. Nobody calls it directly, so execute is revoked from everyone.
|
|
22
|
+
--
|
|
23
|
+
-- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
|
|
24
|
+
-- (`genesis migrate` does it). Never edit it once applied; change it with a new migration.
|
|
25
|
+
|
|
26
|
+
create or replace function public.genesis_version_bump()
|
|
27
|
+
returns trigger
|
|
28
|
+
language plpgsql
|
|
29
|
+
set search_path = ''
|
|
30
|
+
as $$
|
|
31
|
+
declare
|
|
32
|
+
col text := coalesce(nullif(tg_argv[0], ''), 'version');
|
|
33
|
+
previous bigint;
|
|
34
|
+
begin
|
|
35
|
+
if tg_op <> 'UPDATE' or tg_level <> 'ROW' or tg_when <> 'BEFORE' then
|
|
36
|
+
raise exception 'genesis_version_bump runs as a BEFORE UPDATE FOR EACH ROW trigger'
|
|
37
|
+
using errcode = '39P01';
|
|
38
|
+
end if;
|
|
39
|
+
if not (to_jsonb(old) ? col) then
|
|
40
|
+
raise exception 'genesis_version_bump: % has no column "%"', tg_table_name, col
|
|
41
|
+
using errcode = '42703';
|
|
42
|
+
end if;
|
|
43
|
+
-- The column's declared type, not its value: a null text or a numeric column is refused too.
|
|
44
|
+
if not exists (
|
|
45
|
+
select 1 from pg_catalog.pg_attribute a
|
|
46
|
+
where a.attrelid = tg_relid and a.attname = col and not a.attisdropped
|
|
47
|
+
and a.atttypid in ('pg_catalog.int2'::pg_catalog.regtype, 'pg_catalog.int4'::pg_catalog.regtype, 'pg_catalog.int8'::pg_catalog.regtype)
|
|
48
|
+
) then
|
|
49
|
+
raise exception 'genesis_version_bump: %.% is not an integer column', tg_table_name, col
|
|
50
|
+
using errcode = '42804';
|
|
51
|
+
end if;
|
|
52
|
+
previous := coalesce((to_jsonb(old) ->> col)::bigint, 0);
|
|
53
|
+
new := jsonb_populate_record(new, jsonb_build_object(col, previous + 1));
|
|
54
|
+
return new;
|
|
55
|
+
end;
|
|
56
|
+
$$;
|
|
57
|
+
|
|
58
|
+
revoke execute on function public.genesis_version_bump() from public, anon, authenticated;
|
|
@@ -9,6 +9,16 @@
|
|
|
9
9
|
-- request.jwt.claim.sub on older images), so pg_temp.sign_in sets both.
|
|
10
10
|
begin;
|
|
11
11
|
create extension if not exists pgtap with schema extensions;
|
|
12
|
+
-- Since support 0004 every ticket has a tenant: an app without the default-tenant hook gets one
|
|
13
|
+
-- here, inside this transaction only.
|
|
14
|
+
do $hook$ begin
|
|
15
|
+
if to_regprocedure('private.genesis_support_default_tenant()') is null
|
|
16
|
+
and to_regclass('public.ticket_agents') is not null then
|
|
17
|
+
execute $f$create function private.genesis_support_default_tenant() returns uuid language sql stable
|
|
18
|
+
set search_path = '' as 'select ''00000000-0000-4000-8000-00000000000f''::uuid'$f$;
|
|
19
|
+
revoke execute on function private.genesis_support_default_tenant() from public, anon, authenticated;
|
|
20
|
+
end if;
|
|
21
|
+
end $hook$;
|
|
12
22
|
select plan(119);
|
|
13
23
|
|
|
14
24
|
-- People: a1 reports, b2 is someone else, c3 is staff (once the hook exists),
|
|
@@ -50,15 +60,17 @@ grant execute on function pg_temp.person(text), pg_temp.sign_in(text), pg_temp.r
|
|
|
50
60
|
drop function if exists private.genesis_support_staff(uuid);
|
|
51
61
|
|
|
52
62
|
-- Shape -------------------------------------------------------------------------
|
|
53
|
-
|
|
54
|
-
select
|
|
63
|
+
-- Since support 0004 these are public.tickets and public.ticket_attachments, and the old names views.
|
|
64
|
+
select has_relation('public', 'support_reports', 'support_reports exists');
|
|
65
|
+
select has_relation('public', 'support_attachments', 'support_attachments exists');
|
|
55
66
|
select has_table('public', 'support_replies', 'support_replies exists');
|
|
56
67
|
select has_table('public', 'support_ideas', 'support_ideas exists');
|
|
57
68
|
select has_table('public', 'support_idea_votes', 'support_idea_votes exists');
|
|
58
69
|
select col_is_pk('public', 'support_idea_votes', array['idea_id', 'user_id'], 'one vote per person per idea');
|
|
59
70
|
select ok(
|
|
60
71
|
(select bool_and(relrowsecurity) from pg_class where oid in (
|
|
61
|
-
'public.
|
|
72
|
+
coalesce(to_regclass('public.tickets'), 'public.support_reports'::regclass),
|
|
73
|
+
coalesce(to_regclass('public.ticket_attachments'), 'public.support_attachments'::regclass), 'public.support_attachment_purges'::regclass,
|
|
62
74
|
'public.support_replies'::regclass, 'public.support_ideas'::regclass, 'public.support_idea_votes'::regclass)),
|
|
63
75
|
'RLS is on for every support table'
|
|
64
76
|
);
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
-- @feat:versioned-writes
|
|
2
|
+
-- pgTAP test for 0019_genesis_version_bump.sql.
|
|
3
|
+
-- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
|
|
4
|
+
-- It creates only its own temporary tables and rolls everything back.
|
|
5
|
+
begin;
|
|
6
|
+
create extension if not exists pgtap with schema extensions;
|
|
7
|
+
select plan(13);
|
|
8
|
+
|
|
9
|
+
select ok(not has_function_privilege('anon', 'public.genesis_version_bump()', 'execute'), 'anon cannot call it');
|
|
10
|
+
select ok(not has_function_privilege('authenticated', 'public.genesis_version_bump()', 'execute'), 'authenticated cannot call it');
|
|
11
|
+
|
|
12
|
+
create temp table vb_rows (id int primary key, title text, version bigint not null default 1);
|
|
13
|
+
create trigger vb_rows_bump before update on vb_rows
|
|
14
|
+
for each row execute function public.genesis_version_bump('version');
|
|
15
|
+
insert into vb_rows values (1, 'a', 1), (2, 'b', 7);
|
|
16
|
+
|
|
17
|
+
update vb_rows set title = 'a2' where id = 1;
|
|
18
|
+
select is((select version from vb_rows where id = 1), 2::bigint, 'an update advances the version by one');
|
|
19
|
+
|
|
20
|
+
update vb_rows set title = 'a3', version = 100 where id = 1;
|
|
21
|
+
select is((select version from vb_rows where id = 1), 3::bigint, 'a written version is ignored: it can''t jump ahead');
|
|
22
|
+
|
|
23
|
+
update vb_rows set version = 0 where id = 1;
|
|
24
|
+
select is((select version from vb_rows where id = 1), 4::bigint, 'and it can''t be held back');
|
|
25
|
+
|
|
26
|
+
update vb_rows set title = title where id = 1;
|
|
27
|
+
select is((select version from vb_rows where id = 1), 5::bigint, 'an update that changes nothing still advances it');
|
|
28
|
+
|
|
29
|
+
select is((select version from vb_rows where id = 2), 7::bigint, 'rows not updated keep their version');
|
|
30
|
+
|
|
31
|
+
update vb_rows set title = title || '!';
|
|
32
|
+
select results_eq('select id, version from vb_rows order by id', $$ values (1, 6::bigint), (2, 8::bigint) $$,
|
|
33
|
+
'a multi-row update advances each row from its own version');
|
|
34
|
+
|
|
35
|
+
-- A versioned update: what the data provider sends.
|
|
36
|
+
update vb_rows set title = 'stale' where id = 2 and version = 7;
|
|
37
|
+
select is((select title from vb_rows where id = 2), 'b!', 'an update at a stale version matches no row');
|
|
38
|
+
|
|
39
|
+
-- The column name is the argument; the default is `version`.
|
|
40
|
+
create temp table vb_named (id int primary key, rev bigint not null default 1);
|
|
41
|
+
create trigger vb_named_bump before update on vb_named
|
|
42
|
+
for each row execute function public.genesis_version_bump('rev');
|
|
43
|
+
insert into vb_named values (1, 1);
|
|
44
|
+
update vb_named set rev = rev where id = 1;
|
|
45
|
+
select is((select rev from vb_named where id = 1), 2::bigint, 'the column is named by the trigger argument');
|
|
46
|
+
|
|
47
|
+
create temp table vb_missing (id int primary key, title text);
|
|
48
|
+
create trigger vb_missing_bump before update on vb_missing
|
|
49
|
+
for each row execute function public.genesis_version_bump('version');
|
|
50
|
+
insert into vb_missing values (1, 'x');
|
|
51
|
+
select throws_ok($$ update vb_missing set title = 'y' $$, '42703', null, 'a missing column is an error, not a silent no-op');
|
|
52
|
+
|
|
53
|
+
create temp table vb_text (id int primary key, version timestamptz not null default now());
|
|
54
|
+
create trigger vb_text_bump before update on vb_text
|
|
55
|
+
for each row execute function public.genesis_version_bump('version');
|
|
56
|
+
insert into vb_text values (1);
|
|
57
|
+
select throws_ok($$ update vb_text set id = 1 $$, '42804', null, 'a column that isn''t an integer is an error');
|
|
58
|
+
|
|
59
|
+
create temp table vb_numeric (id int primary key, version numeric not null default 1);
|
|
60
|
+
create trigger vb_numeric_bump before update on vb_numeric
|
|
61
|
+
for each row execute function public.genesis_version_bump('version');
|
|
62
|
+
insert into vb_numeric values (1);
|
|
63
|
+
select throws_ok($$ update vb_numeric set id = 1 $$, '42804', null, 'a numeric column is refused by its type, not its value');
|
|
64
|
+
|
|
65
|
+
select * from finish();
|
|
66
|
+
rollback;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-supabase",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -302,6 +302,36 @@
|
|
|
302
302
|
"web",
|
|
303
303
|
"native"
|
|
304
304
|
]
|
|
305
|
+
},
|
|
306
|
+
"versioned-writes": {
|
|
307
|
+
"feature": {
|
|
308
|
+
"name": "Versioned writes",
|
|
309
|
+
"summary": "A trigger that advances a row's version on every update, so the Supabase data provider refuses an edit made on a stale copy as a conflict instead of overwriting someone else's.",
|
|
310
|
+
"keywords": [
|
|
311
|
+
"optimistic concurrency",
|
|
312
|
+
"version",
|
|
313
|
+
"conflict",
|
|
314
|
+
"lost update",
|
|
315
|
+
"offline"
|
|
316
|
+
],
|
|
317
|
+
"audience": [
|
|
318
|
+
"developer"
|
|
319
|
+
]
|
|
320
|
+
},
|
|
321
|
+
"platforms": [
|
|
322
|
+
"web",
|
|
323
|
+
"native"
|
|
324
|
+
],
|
|
325
|
+
"migrations": [
|
|
326
|
+
{
|
|
327
|
+
"file": "migrations/0019_genesis_version_bump.sql",
|
|
328
|
+
"test": "migrations/tests/0019_genesis_version_bump.test.sql"
|
|
329
|
+
}
|
|
330
|
+
],
|
|
331
|
+
"steps": [
|
|
332
|
+
"For each table to check: add `version bigint not null default 1` and `create trigger <table>_version_bump before update on <table> for each row execute function public.genesis_version_bump('version')`.",
|
|
333
|
+
"Give the resource a version rule in createSupabaseProvider: `resources: { tasks: { version: { field: \"version\", kind: \"integer\" } } }`. The Genesis write hooks then send the version they read, and a stale edit comes back as a conflict."
|
|
334
|
+
]
|
|
305
335
|
}
|
|
306
336
|
},
|
|
307
337
|
"doctor": {
|
|
@@ -1 +0,0 @@
|
|
|
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,QACT,IAAA,EAAM,oDAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,QAAA,EAAU;AAAA,QACR;AAAA,UACE,IAAA,EAAM,eAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,SAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,MAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA;AACZ,OACF;AAAA,MACA,KAAA,EAAO;AAAA,QACL,4GAAA;AAAA,QACA;AA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A,EAAS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC;AASM,IAAM,kBAAkB,WAAA,CAAY;AAAA,EACzC,EAAA,EAAI,aAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,yCAAA,EAA2C,MAAM,oDAAA;AAAqD,KAClI;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAUM,IAAM,cAAc,WAAA,CAAY;AAAA,EACrC,EAAA,EAAI,QAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,oCAAA,EAAsC,IAAA,EAAM,+CAAA,EAAiD,CAAA;AAAA,IACpI,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC","file":"chunk-34OBTZJQ.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/**\n * The product events block: the app's own events table and its tracking functions (ADR 0010).\n * The client is `createEventTracker` from `/events`; on native, `createEventsSink` plugs it into the\n * observability sinks.\n *\n * @stability Beta\n */\nexport const eventsBlock = defineBlock({\n id: \"events\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0018_genesis_events.sql\", test: \"migrations/tests/0018_genesis_events.test.sql\" }],\n privacy: {\n notes: [\n \"Stores product events: the login, the person record and tenant, the feature, an event name, small properties (labels and counts, never typed content or personal data), the flags that were on, the platform and the time. Only the service role reads them; delete old ones with genesis_prune_events (default 400 days).\",\n ],\n },\n },\n});\n"]}
|