@marktiderman/genesis-supabase 0.6.2 → 0.7.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 CHANGED
@@ -595,11 +595,13 @@ Migration `0008_genesis_feature_registry.sql` (needs 0004) gives the feature gat
595
595
  way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
596
596
 
597
597
  - **The mirror.** `features` and `feature_flags` copy `features.json`, written only by `sync_feature_registry`
598
- with the service key. Run it from **production deployments only**, when one starts serving, with
599
- `Date.now()` as the version (not the build time), so an instant rollback syncs as the newest. The same
600
- registry again changes nothing; an empty registry, or one dropping more than a fifth of the features, is
601
- refused unless `allowShrink`. Nothing is deleted: a removed feature or flag is marked `in_registry = false`,
602
- and a flag's tenant values stay.
598
+ with the service key. Run it from **production deployments only**, with the **build time** as the version.
599
+ Vercel sets `VERCEL_ENV=production` on every production deployment, old ones included, so an instance-start
600
+ time would let a cold start of an old URL sync a stale registry; a build time can't. After an instant
601
+ rollback the database keeps the newer registry until the next deploy (only SQL's status and entitlement
602
+ checks read it). The same registry again changes nothing; an empty registry, or one dropping more than a
603
+ fifth of the features, is refused unless `allowShrink`. Nothing is deleted: a removed feature or flag is
604
+ marked `in_registry = false`; its tenant values stay, and (0014) its platform value is cleared.
603
605
  - **Paid access.** `feature_entitlements` (tenant, feature, source, `active`, optional `ends_at`). Your billing
604
606
  webhook writes it with the service key.
605
607
  - **Flag values.** `tenant_flag_values` overrides a flag's default for one tenant (service key).
@@ -608,7 +610,14 @@ way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
608
610
  over many rows use the once-per-statement pair instead:
609
611
  `using ((select feature_shipped('exports')) and team_id = any (array(select feature_entitled_tenants('exports'))))`
610
612
  (drop the second half for a free feature). Switches and flags are not checked here: server code enforces them.
611
- - **Reading features.** Signed-in people (not anonymous sign-ins) read shipped, customer-facing features, and
613
+ - **Who is asking (0014).** Server code is told apart from a person by the request's role
614
+ (`current_setting('role')`, set per request by PostgREST), never by `request.jwt.claims`: a role that bypasses
615
+ row security, or a connection that never switched role, is server code; everyone else must be a member. So any database login that
616
+ connects directly, without switching role, is trusted as server code: give people API access only, never a
617
+ direct database login. The
618
+ functions use `auth.jwt()` and `auth.uid()`, so they need Supabase's `auth` schema (not bare Postgres).
619
+ - **Reading features.** Signed-in people (not anonymous sign-ins) read shipped, customer-facing features (and
620
+ `feature_shipped` answers them only for those), and
612
621
  only `id, name, status, visibility, access_plan, platforms, in_registry`; the full record stays server side.
613
622
  - **The snapshot's input.** `feature_gate_state(tenant)` returns the tenant's switches off, entitlements and
614
623
  flag values, to its members (with their own JWT, so browsers and extensions can call it) and the service role.
@@ -619,7 +628,7 @@ import { gateSnapshot } from "@marktiderman/genesis-features/gate";
619
628
  import registry from "../features.json";
620
629
 
621
630
  // When a production deployment starts serving (never from a preview):
622
- if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
631
+ if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });
623
632
 
624
633
  const state = await featureGateState(supabase, teamId); // per session
625
634
  const snapshot = gateSnapshot({ features, flags }, { platform: "web", ...state }, { version: BUILD_TIME });
package/dist/blocks.d.ts CHANGED
@@ -30,5 +30,14 @@ declare const featureMirrorBlock: _marktiderman_genesis_features_blocks.BlockDef
30
30
  * @stability Beta
31
31
  */
32
32
  declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs", never>;
33
+ /**
34
+ * The owner-access block: the contract every Genesis block with owned rows
35
+ * calls in its policies. Two fail-closed wrappers over the app's hooks
36
+ * (`genesis_owner_can`, `genesis_readable_owners`): a missing or broken hook
37
+ * means no.
38
+ *
39
+ * @stability Experimental
40
+ */
41
+ declare const ownerAccessBlock: _marktiderman_genesis_features_blocks.BlockDef<"owner-access", never>;
33
42
 
34
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
43
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock };
package/dist/blocks.js CHANGED
@@ -1,3 +1,3 @@
1
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
1
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './chunk-FWZIWKI4.js';
2
2
  //# sourceMappingURL=blocks.js.map
3
3
  //# sourceMappingURL=blocks.js.map
@@ -73,6 +73,11 @@ var featureMirrorBlock = defineBlock({
73
73
  package: PACKAGE,
74
74
  file: "migrations/0008_genesis_feature_registry.sql",
75
75
  test: "migrations/tests/0008_genesis_feature_registry.test.sql"
76
+ },
77
+ {
78
+ package: PACKAGE,
79
+ file: "migrations/0014_genesis_feature_registry_hardening.sql",
80
+ test: "migrations/tests/0014_genesis_feature_registry_hardening.test.sql"
76
81
  }
77
82
  ],
78
83
  privacy: {
@@ -90,7 +95,22 @@ var jobsBlock = defineBlock({
90
95
  privacy: { notes: ["Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days."] }
91
96
  }
92
97
  });
98
+ var ownerAccessBlock = defineBlock({
99
+ id: "owner-access",
100
+ requires: ["tenant-features"],
101
+ platforms: ["web", "native"],
102
+ contributes: {
103
+ migrations: [
104
+ {
105
+ package: PACKAGE,
106
+ file: "migrations/0009_genesis_owner_access.sql",
107
+ test: "migrations/tests/0009_genesis_owner_access.test.sql"
108
+ }
109
+ ],
110
+ privacy: { notes: ["Stores nothing; it only asks the app's hooks who may read and write."] }
111
+ }
112
+ });
93
113
 
94
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
95
- //# sourceMappingURL=chunk-ONBOLMXH.js.map
96
- //# sourceMappingURL=chunk-ONBOLMXH.js.map
114
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock };
115
+ //# sourceMappingURL=chunk-FWZIWKI4.js.map
116
+ //# sourceMappingURL=chunk-FWZIWKI4.js.map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A,IACA,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,sEAAsE,CAAA;AAAE;AAE/F,CAAC","file":"chunk-FWZIWKI4.js","sourcesContent":["/**\n * The blocks this package carries the server half of, as `defineBlock`\n * declarations: what each needs in the database, and what it means for the\n * stores' privacy forms. The functions themselves (`deleteMyAccount`,\n * `tenantFeatures`, …) don't change.\n */\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\n\nconst PACKAGE = \"@marktiderman/genesis-supabase\";\n\n/**\n * The account block: sign-in, profile and in-app account deletion. Its\n * screens are the app's (or genesis-ui-native's `AuthScreen`); this names its\n * migrations and its data.\n *\n * @stability Beta\n */\nexport const accountBlock = defineBlock({\n id: \"account\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0001_genesis_account_deletion.sql\",\n test: \"migrations/tests/0001_genesis_account_deletion.test.sql\",\n },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n {\n package: PACKAGE,\n file: \"migrations/0003_genesis_apple_token_revocation.sql\",\n test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\",\n },\n ],\n privacy: {\n collects: [\n {\n type: \"email address\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"user id\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"name\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n ],\n notes: [\n \"People delete their account from inside the app; their login and the rows that cascade from it go with it.\",\n \"With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted.\",\n ],\n },\n },\n});\n\n/**\n * The tenant features block: per-tenant on/off switches for shipped\n * features, set by the tenant's admins with a reason.\n *\n * @stability Beta\n */\nexport const tenantFeaturesBlock = defineBlock({\n id: \"tenant-features\",\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0004_genesis_tenant_features.sql\",\n test: \"migrations/tests/0004_genesis_tenant_features.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\",\n ],\n },\n },\n});\n\n/**\n * The feature registry block: the registry mirrored into the app's database\n * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,\n * for the feature gate. Needs the tenant features block.\n *\n * @stability Beta\n */\nexport const featureMirrorBlock = defineBlock({\n id: \"feature-mirror\",\n requires: [\"tenant-features\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0008_genesis_feature_registry.sql\",\n test: \"migrations/tests/0008_genesis_feature_registry.test.sql\",\n },\n {\n package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants hold which paid features and flag values; no personal data.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n\n/**\n * The owner-access block: the contract every Genesis block with owned rows\n * calls in its policies. Two fail-closed wrappers over the app's hooks\n * (`genesis_owner_can`, `genesis_readable_owners`): a missing or broken hook\n * means no.\n *\n * @stability Experimental\n */\nexport const ownerAccessBlock = defineBlock({\n id: \"owner-access\",\n requires: [\"tenant-features\"],\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0009_genesis_owner_access.sql\",\n test: \"migrations/tests/0009_genesis_owner_access.test.sql\",\n },\n ],\n privacy: { notes: [\"Stores nothing; it only asks the app's hooks who may read and write.\"] },\n },\n});\n"]}
@@ -236,9 +236,9 @@ interface FeatureRegistryDocument {
236
236
  /** @stability Beta */
237
237
  interface SyncFeatureRegistryOptions {
238
238
  /**
239
- * When this deployment started serving, in milliseconds (`Date.now()` at server start), not its
240
- * build time: an instant rollback to an older build then syncs as the newest. Older versions
241
- * than the last sync are refused.
239
+ * This build's version: an increasing number such as the build time in milliseconds, so an old
240
+ * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer
241
+ * one. Older versions than the last sync are refused.
242
242
  */
243
243
  version: number;
244
244
  /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */
@@ -253,7 +253,7 @@ interface SyncFeatureRegistryOptions {
253
253
  *
254
254
  * ```ts
255
255
  * import registry from "../features.json";
256
- * if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
256
+ * if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });
257
257
  * ```
258
258
  *
259
259
  * @stability Beta
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@supabase/supabase-js';
2
- export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureRegistryClient, e as FeatureRegistryDocument, f as FlagStateValue, g as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, j as SetTenantFeatureInput, k as StoreAppleTokenOptions, l as StoreAppleTokenResult, m as SupabaseQueryError, n as SyncFeatureRegistryOptions, T as TenantFeatureChange, o as TenantFeatureSetting, p as TenantFeatures, q as TenantFeaturesClient, r as createGenesisSupabase, s as deleteMyAccount, t as featureGateState, u as must, v as requestAppleRevocation, w as setTenantFeature, x as storeAppleToken, y as syncFeatureRegistry, z as tenantFeatureHistory, B as tenantFeatureSettings, C as tenantFeatures } from './index-Ds0tO9WP.js';
3
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
2
+ export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureRegistryClient, e as FeatureRegistryDocument, f as FlagStateValue, g as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, j as SetTenantFeatureInput, k as StoreAppleTokenOptions, l as StoreAppleTokenResult, m as SupabaseQueryError, n as SyncFeatureRegistryOptions, T as TenantFeatureChange, o as TenantFeatureSetting, p as TenantFeatures, q as TenantFeaturesClient, r as createGenesisSupabase, s as deleteMyAccount, t as featureGateState, u as must, v as requestAppleRevocation, w as setTenantFeature, x as storeAppleToken, y as syncFeatureRegistry, z as tenantFeatureHistory, B as tenantFeatureSettings, C as tenantFeatures } from './index-D73YuwEY.js';
3
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './blocks.js';
4
4
  import '@marktiderman/genesis-features/blocks';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { installWebCrypto, assertPkceCrypto, isDigestOnlyPolyfill, claimsViaServer } from './chunk-FAA2FTF4.js';
2
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
2
+ export { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from './chunk-FWZIWKI4.js';
3
3
  import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
4
4
 
5
5
  // src/apple-tokens.ts
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/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,uB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,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,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 the tenant holds an active entitlement for. */\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/**\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) or the\n * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a\n * refusal is never mistaken for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState> {\n const data = must((await client.rpc(\"feature_gate_state\", { tenant: tenantId })) 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 * When this deployment started serving, in milliseconds (`Date.now()` at server start), not its\n * build time: an instant rollback to an older build then syncs as the newest. Older versions\n * 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: Date.now() });\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 * 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 FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
1
+ {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.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,OAAA,EAAS,gBAAA,EAAkB,CAAA;AAClL,IAAA,IAAI,OAAO,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,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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 the tenant holds an active entitlement for. */\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/**\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) or the\n * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a\n * refusal is never mistaken for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState> {\n const data = must((await client.rpc(\"feature_gate_state\", { tenant: tenantId })) 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 * 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 FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
package/dist/native.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SessionStorage } from './index-Ds0tO9WP.js';
2
- export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-Ds0tO9WP.js';
1
+ import { S as SessionStorage } from './index-D73YuwEY.js';
2
+ export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-D73YuwEY.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,89 @@
1
+ -- Genesis owner access: private.genesis_owner_readable() and private.genesis_owner_allows()
2
+ --
3
+ -- The owner-access contract, shared by every Genesis block whose rows have an owner (genesis-work's
4
+ -- goals, projects, tasks, issues, metrics, status updates and sessions). A row belongs to a tenant
5
+ -- and has exactly one owner: a person, a team or the tenant itself. Who may read and write it is
6
+ -- your app's answer, through two hooks. Genesis never defines them:
7
+ --
8
+ -- private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid,
9
+ -- organization_id uuid, action text) returns boolean
10
+ -- action is 'read' or 'write'.
11
+ -- private.genesis_readable_owners(viewer uuid) returns table (tenant_id uuid, owner_id uuid)
12
+ -- Every (tenant, owner) pair the viewer may read, across tenants, so a policy checks once per
13
+ -- statement instead of calling a function per row. owner_id is the row's person_id, team_id
14
+ -- or organization_id, whichever is set.
15
+ --
16
+ -- Both run with your migration's (the owner's) rights, so they read your membership tables
17
+ -- whatever their row security. For example:
18
+ --
19
+ -- create function private.genesis_readable_owners(viewer uuid)
20
+ -- returns table (tenant_id uuid, owner_id uuid) language sql stable set search_path = '' as $$
21
+ -- select m.team_id, m.user_id from public.memberships m where m.user_id = viewer -- my own rows
22
+ -- union all
23
+ -- select m.team_id, m.team_id from public.memberships m where m.user_id = viewer -- my team's rows
24
+ -- $$;
25
+ -- revoke execute on function private.genesis_readable_owners(uuid) from public, anon, authenticated;
26
+ --
27
+ -- This file ships the two wrappers that blocks call in their policies. They fail closed: a missing
28
+ -- hook, a hook that errors or returns the wrong type, no signed-in person, a null tenant, or an
29
+ -- action other than 'read' or 'write' gives false or an empty set.
30
+ --
31
+ -- private.genesis_owner_readable() returns table (tenant_id uuid, owner_id uuid)
32
+ -- The signed-in person's set, from genesis_readable_owners(auth.uid()).
33
+ -- private.genesis_owner_allows(tenant uuid, person_id uuid, team_id uuid, organization_id uuid,
34
+ -- action text) returns boolean
35
+ -- genesis_owner_can(tenant, auth.uid(), person_id, team_id, organization_id, action).
36
+ --
37
+ -- Both are security definer with search_path ''. Row security runs as the caller, so authenticated
38
+ -- may execute them; they only ever answer for auth.uid(). anon and public may not.
39
+ --
40
+ -- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
41
+ -- (`genesis migrate` does it). Never edit it once applied; change it with a new migration.
42
+ --
43
+ -- Verify: the pgTAP test beside this file (`tests/0009_genesis_owner_access.test.sql`).
44
+
45
+ create schema if not exists private;
46
+
47
+ create or replace function private.genesis_owner_readable()
48
+ returns table (tenant_id uuid, owner_id uuid)
49
+ language plpgsql
50
+ stable
51
+ security definer
52
+ set search_path = ''
53
+ as $$
54
+ begin
55
+ if auth.uid() is null or to_regprocedure('private.genesis_readable_owners(uuid)') is null then
56
+ return;
57
+ end if;
58
+ return query execute 'select r.tenant_id::uuid, r.owner_id::uuid from private.genesis_readable_owners($1) r' using auth.uid();
59
+ exception when others then
60
+ return;
61
+ end;
62
+ $$;
63
+
64
+ create or replace function private.genesis_owner_allows(tenant uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
65
+ returns boolean
66
+ language plpgsql
67
+ stable
68
+ security definer
69
+ set search_path = ''
70
+ as $$
71
+ declare
72
+ allowed boolean;
73
+ begin
74
+ if auth.uid() is null or tenant is null or action is null or action not in ('read', 'write')
75
+ or to_regprocedure('private.genesis_owner_can(uuid,uuid,uuid,uuid,uuid,text)') is null then
76
+ return false;
77
+ end if;
78
+ execute 'select (private.genesis_owner_can($1, $2, $3, $4, $5, $6))::boolean'
79
+ into allowed using tenant, auth.uid(), person_id, team_id, organization_id, action;
80
+ return coalesce(allowed, false);
81
+ exception when others then
82
+ return false;
83
+ end;
84
+ $$;
85
+
86
+ revoke execute on function private.genesis_owner_readable() from public, anon, authenticated;
87
+ revoke execute on function private.genesis_owner_allows(uuid, uuid, uuid, uuid, text) from public, anon, authenticated;
88
+ grant execute on function private.genesis_owner_readable() to authenticated;
89
+ grant execute on function private.genesis_owner_allows(uuid, uuid, uuid, uuid, text) to authenticated;
@@ -0,0 +1,124 @@
1
+ -- Genesis feature registry, hardened (0008, shipped in genesis-supabase 0.6.0, changed here).
2
+ --
3
+ -- 1. Who is asking. Server code is now told apart from a person by the request's role
4
+ -- (`current_setting('role')`, which PostgREST sets per request with SET LOCAL ROLE), not by
5
+ -- request.jwt.claims, which a session can set for itself. A role that bypasses row security
6
+ -- (service_role, postgres) is server code, and so is a connection that never switched role
7
+ -- (`none`, as in migrations). Anything else, `authenticated` included, must be a member of the
8
+ -- tenant. Before, a session that switched to
9
+ -- `authenticated` without setting claims was treated as server code.
10
+ -- 2. feature_shipped(feature) answers a signed-in person only for customer-facing features
11
+ -- (visibility customer or public): an internal feature's id can no longer be confirmed by
12
+ -- guessing it. Server code still gets every feature.
13
+ -- 3. A flag that leaves the registry loses its platform_value, so a forgotten kill switch can't
14
+ -- come back with the flag. Its tenant values stay, as before.
15
+ -- 4. feature_entitlements gets an index on (feature_id) for active rows, for
16
+ -- feature_entitled_tenants and feature_on.
17
+ --
18
+ -- Needs 0004 and 0008. Verify: tests/0014_genesis_feature_registry_hardening.test.sql.
19
+
20
+ create index if not exists feature_entitlements_feature_active on public.feature_entitlements (feature_id) where active;
21
+
22
+ create or replace function private.genesis_feature_caller_is_server()
23
+ returns boolean
24
+ language plpgsql
25
+ stable
26
+ security definer
27
+ set search_path = ''
28
+ as $$
29
+ declare
30
+ request_role text := coalesce(nullif(current_setting('role', true), ''), 'none');
31
+ begin
32
+ -- No role switch (a direct connection, a migration), or a role that bypasses row security
33
+ -- (service_role, postgres): server code. authenticated and anon never bypass it.
34
+ return request_role = 'none'
35
+ or coalesce((select r.rolbypassrls from pg_catalog.pg_roles r where r.rolname = request_role), false);
36
+ end;
37
+ $$;
38
+
39
+ revoke execute on function private.genesis_feature_caller_is_server() from public, anon, authenticated;
40
+
41
+ create or replace function public.feature_shipped(feature text)
42
+ returns boolean
43
+ language sql
44
+ stable
45
+ security definer
46
+ set search_path = ''
47
+ as $$
48
+ select exists (
49
+ select 1 from public.features f
50
+ where f.id = feature and f.in_registry and f.status in ('beta', 'live', 'deprecated')
51
+ and (f.visibility in ('customer', 'public') or private.genesis_feature_caller_is_server())
52
+ )
53
+ $$;
54
+
55
+ create or replace function public.sync_feature_registry(version bigint, hash text, features jsonb, flags jsonb, allow_shrink boolean default false)
56
+ returns boolean
57
+ language plpgsql
58
+ security definer
59
+ set search_path = ''
60
+ as $$
61
+ declare
62
+ current_count int;
63
+ gone_count int;
64
+ begin
65
+ if version is null or hash is null
66
+ or jsonb_typeof(features) is distinct from 'array' or jsonb_typeof(flags) is distinct from 'array' then
67
+ raise exception 'sync_feature_registry: needs a version, a hash and two arrays' using errcode = '22023';
68
+ end if;
69
+ if exists (select 1 from jsonb_array_elements(features) r where coalesce(r ->> 'id', '') = '')
70
+ or jsonb_array_length(features) <> (select count(distinct r ->> 'id') from jsonb_array_elements(features) r) then
71
+ raise exception 'sync_feature_registry: every feature needs a unique id' using errcode = '22023';
72
+ end if;
73
+ if exists (select 1 from jsonb_array_elements(flags) r where coalesce(r ->> 'key', '') = '')
74
+ or jsonb_array_length(flags) <> (select count(distinct r ->> 'key') from jsonb_array_elements(flags) r) then
75
+ raise exception 'sync_feature_registry: every flag needs a unique key' using errcode = '22023';
76
+ end if;
77
+ -- One sync at a time: a second deploy waits, then finds itself already current.
78
+ perform pg_advisory_xact_lock(hashtext('public.sync_feature_registry'));
79
+ -- Never backwards, and nothing to do for the same registry.
80
+ if exists (select 1 from private.feature_registry_state s where s.version > sync_feature_registry.version or s.hash = sync_feature_registry.hash) then
81
+ return false;
82
+ end if;
83
+ -- A broken or foreign registry must not switch everything off.
84
+ select count(*) into current_count from public.features f where f.in_registry;
85
+ select count(*) into gone_count from public.features f
86
+ where f.in_registry and not exists (select 1 from jsonb_array_elements(features) r where r ->> 'id' = f.id);
87
+ if not coalesce(allow_shrink, false) and (jsonb_array_length(features) = 0 or (gone_count >= 3 and gone_count * 5 > current_count)) then
88
+ raise exception 'sync_feature_registry: this registry drops % of % features', gone_count, current_count
89
+ using errcode = '22023', hint = 'Check features.json; if the removal is intended, call again with allow_shrink => true.';
90
+ end if;
91
+
92
+ insert into public.features as f (id, name, status, visibility, access_plan, platforms, record, in_registry, synced_at)
93
+ select r ->> 'id', r ->> 'name', r ->> 'status', coalesce(r ->> 'visibility', 'customer'),
94
+ case when jsonb_typeof(r -> 'access') = 'object' then nullif(btrim(r -> 'access' ->> 'plan'), '') end,
95
+ case when jsonb_typeof(r -> 'platforms') = 'object' then r -> 'platforms' end,
96
+ r, true, now()
97
+ from jsonb_array_elements(features) r
98
+ on conflict (id) do update set
99
+ name = excluded.name, status = excluded.status, visibility = excluded.visibility, access_plan = excluded.access_plan,
100
+ platforms = excluded.platforms, record = excluded.record, in_registry = true, synced_at = excluded.synced_at;
101
+
102
+ -- Ids are permanent: a feature the registry no longer lists stays, marked as gone.
103
+ update public.features f set in_registry = false, synced_at = now()
104
+ where f.in_registry and not exists (select 1 from jsonb_array_elements(features) r where r ->> 'id' = f.id);
105
+
106
+ update public.feature_flags fl set in_registry = false, platform_value = null, synced_at = now()
107
+ where fl.in_registry and not exists (select 1 from jsonb_array_elements(flags) r where r ->> 'key' = fl.key);
108
+ insert into public.feature_flags as fl (key, feature_id, kind, default_value, scopes, expires, record, in_registry, synced_at)
109
+ select r ->> 'key', r ->> 'feature', r ->> 'kind', coalesce(r -> 'default', 'false'::jsonb),
110
+ coalesce(array(select jsonb_array_elements_text(r -> 'scopes')), '{}'),
111
+ (r ->> 'expires')::date, r, true, now()
112
+ from jsonb_array_elements(flags) r
113
+ on conflict (key) do update set
114
+ feature_id = excluded.feature_id, kind = excluded.kind, default_value = excluded.default_value,
115
+ scopes = excluded.scopes, expires = excluded.expires, record = excluded.record, in_registry = true,
116
+ synced_at = excluded.synced_at;
117
+
118
+ insert into private.feature_registry_state (id, version, hash, synced_at)
119
+ values (true, sync_feature_registry.version, sync_feature_registry.hash, now())
120
+ on conflict (id) do update set version = excluded.version, hash = excluded.hash, synced_at = excluded.synced_at;
121
+ return true;
122
+ end;
123
+ $$;
124
+
@@ -0,0 +1,70 @@
1
+ -- @feat:owner-access
2
+ -- pgTAP test for 0009_genesis_owner_access.sql.
3
+ -- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
4
+ -- It writes only its own users and hooks and rolls everything back. If your app already has the
5
+ -- hooks, they are dropped and replaced inside this transaction only.
6
+ begin;
7
+ create extension if not exists pgtap with schema extensions;
8
+ select plan(11);
9
+
10
+ insert into auth.users (id, aud, role, email, instance_id)
11
+ select ('00000000-0000-4000-8000-0000000000' || n)::uuid, 'authenticated', 'authenticated', 'genesis-owner-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
12
+ from unnest(array['a1', 'b2']) n;
13
+
14
+ create function pg_temp.person(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000000' || n)::uuid $$;
15
+ create function pg_temp.tenant(n int) returns uuid language sql immutable as $$ select ('00000000-0000-4000-9000-00000000000' || n)::uuid $$;
16
+ create function pg_temp.team(n int) returns uuid language sql immutable as $$ select ('00000000-0000-4000-a000-00000000000' || n)::uuid $$;
17
+ -- The wrappers are called as the owner with a person's claims, the way a policy calls them for
18
+ -- that person (signed-in callers can't name the private schema themselves).
19
+ create function pg_temp.claims(n text) returns void language plpgsql as $$
20
+ begin
21
+ perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.person(n), 'role', 'authenticated')::text, true);
22
+ perform set_config('request.jwt.claim.sub', pg_temp.person(n)::text, true);
23
+ end $$;
24
+ create function pg_temp.no_one() returns void language plpgsql as $$
25
+ begin
26
+ perform set_config('request.jwt.claims', '', true);
27
+ perform set_config('request.jwt.claim.sub', '', true);
28
+ end $$;
29
+
30
+ drop function if exists private.genesis_owner_can(uuid, uuid, uuid, uuid, uuid, text);
31
+ drop function if exists private.genesis_readable_owners(uuid);
32
+
33
+ -- Privileges ---------------------------------------------------------------------------------
34
+ select ok(not has_function_privilege('anon', 'private.genesis_owner_allows(uuid,uuid,uuid,uuid,text)', 'execute'), 'anon can''t call genesis_owner_allows');
35
+ select ok(not has_function_privilege('anon', 'private.genesis_owner_readable()', 'execute'), 'anon can''t call genesis_owner_readable');
36
+
37
+ -- No hooks: fail closed -----------------------------------------------------------------------
38
+ select pg_temp.claims('a1');
39
+ select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'write'), false, 'without the hook, no');
40
+ select is((select count(*)::int from private.genesis_owner_readable()), 0, 'without the hook, an empty set');
41
+
42
+ -- The app's hooks -----------------------------------------------------------------------------
43
+ create function private.genesis_readable_owners(viewer uuid)
44
+ returns table (tenant_id uuid, owner_id uuid) language sql stable set search_path = '' as $$
45
+ select '00000000-0000-4000-9000-000000000001'::uuid, '00000000-0000-4000-a000-000000000001'::uuid
46
+ where viewer = '00000000-0000-4000-8000-0000000000a1'::uuid
47
+ $$;
48
+ create function private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
49
+ returns boolean language sql stable set search_path = '' as $$
50
+ select viewer = '00000000-0000-4000-8000-0000000000a1'::uuid and team_id = '00000000-0000-4000-a000-000000000001'::uuid
51
+ $$;
52
+
53
+ select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'write'), true, 'the wrapper answers for the signed-in person');
54
+ select is((select count(*)::int from private.genesis_owner_readable()), 1, 'the readable set for the signed-in person');
55
+ select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'delete'), false, 'an action other than read or write is no');
56
+ select is(private.genesis_owner_allows(null, null, pg_temp.team(1), null, 'read'), false, 'a null tenant is no');
57
+ select pg_temp.claims('b2');
58
+ select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'read'), false, 'it answers only for the signed-in person');
59
+ select pg_temp.no_one();
60
+ select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'read'), false, 'nobody signed in is no');
61
+
62
+ -- A hook with the wrong return type fails closed -----------------------------------------------
63
+ drop function private.genesis_owner_can(uuid, uuid, uuid, uuid, uuid, text);
64
+ create function private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
65
+ returns text language sql stable set search_path = '' as $$ select 'maybe' $$;
66
+ select pg_temp.claims('a1');
67
+ select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'write'), false, 'a hook that errors means no');
68
+
69
+ select * from finish();
70
+ rollback;
@@ -0,0 +1,54 @@
1
+ -- @feat:feature-mirror
2
+ -- pgTAP test for 0014_genesis_feature_registry_hardening.sql (needs 0004 and 0008).
3
+ -- Copy into your app's `supabase/tests/database/` and run `supabase test db`. Rolls back.
4
+ begin;
5
+ create extension if not exists pgtap with schema extensions;
6
+ select plan(11);
7
+
8
+ insert into auth.users (id, aud, role, email, instance_id)
9
+ values ('00000000-0000-4000-8000-0000000014a1', 'authenticated', 'authenticated', 'hardening-a1@example.test', '00000000-0000-0000-0000-000000000000');
10
+ drop function if exists private.genesis_tenant_member(uuid, uuid);
11
+ create function private.genesis_tenant_member(tenant uuid, person uuid) returns boolean language sql stable set search_path = '' as $$
12
+ select tenant = '00000000-0000-4000-9000-000000001401'::uuid and person = '00000000-0000-4000-8000-0000000014a1'::uuid
13
+ $$;
14
+ revoke execute on function private.genesis_tenant_member(uuid, uuid) from public, anon, authenticated;
15
+
16
+ select public.sync_feature_registry(9100, 'hard-1',
17
+ '[{"id": "open", "name": "Open", "status": "live"},
18
+ {"id": "secret", "name": "Secret", "status": "live", "visibility": "internal"},
19
+ {"id": "a", "name": "A", "status": "live"}, {"id": "b", "name": "B", "status": "live"}]',
20
+ '[{"key": "open.release", "feature": "open", "kind": "release", "default": false}]');
21
+
22
+ select ok(exists (select 1 from pg_indexes where indexname = 'feature_entitlements_feature_active'), 'entitlements are indexed by feature');
23
+
24
+ -- A session that switched to authenticated without claims is a person with no tenant, not the server.
25
+ set local role authenticated;
26
+ select set_config('request.jwt.claims', '', true);
27
+ select is(public.feature_on('00000000-0000-4000-9000-000000001401', 'open'), false, 'SET ROLE authenticated with no claims gets no answer');
28
+ select throws_ok($$select public.feature_gate_state('00000000-0000-4000-9000-000000001401')$$, '42501', null, '... and no gate state');
29
+ select is(public.feature_shipped('secret'), false, 'a person can''t confirm an internal feature');
30
+ select is(public.feature_shipped('open'), true, '... but sees customer-facing ones');
31
+ -- Claims that say service_role don't make a person server code: the role decides.
32
+ select set_config('request.jwt.claims', '{"role": "service_role"}', true);
33
+ select is(public.feature_on('00000000-0000-4000-9000-000000001401', 'open'), false, 'claims claiming service_role are refused');
34
+ select is(public.feature_shipped('secret'), false, '... and see no internal feature');
35
+ -- A member with claims is still answered.
36
+ select set_config('request.jwt.claims', '{"sub": "00000000-0000-4000-8000-0000000014a1", "role": "authenticated"}', true);
37
+ select is(public.feature_on('00000000-0000-4000-9000-000000001401', 'open'), true, 'a member is answered');
38
+ reset role;
39
+ select set_config('request.jwt.claims', '', true);
40
+
41
+ set local role service_role;
42
+ select is(public.feature_shipped('secret'), true, 'server code sees internal features');
43
+ reset role;
44
+
45
+ -- A flag that leaves the registry loses its kill switch.
46
+ update public.feature_flags set platform_value = 'false' where key = 'open.release';
47
+ select public.sync_feature_registry(9200, 'hard-2',
48
+ '[{"id": "open", "name": "Open", "status": "live"}, {"id": "secret", "name": "Secret", "status": "live", "visibility": "internal"},
49
+ {"id": "a", "name": "A", "status": "live"}, {"id": "b", "name": "B", "status": "live"}]', '[]');
50
+ select is((select platform_value from public.feature_flags where key = 'open.release'), null, 'a flag leaving the registry drops its platform value');
51
+ select is((select in_registry from public.feature_flags where key = 'open.release'), false, '... and is marked gone');
52
+
53
+ select * from finish();
54
+ rollback;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-supabase",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -180,10 +180,49 @@
180
180
  {
181
181
  "file": "migrations/0008_genesis_feature_registry.sql",
182
182
  "test": "migrations/tests/0008_genesis_feature_registry.test.sql"
183
+ },
184
+ {
185
+ "file": "migrations/0014_genesis_feature_registry_hardening.sql",
186
+ "test": "migrations/tests/0014_genesis_feature_registry_hardening.test.sql"
187
+ }
188
+ ],
189
+ "steps": [
190
+ "Sync the registry on every deploy with the service key: syncFeatureRegistry(admin, features.json, { version: BUILD_TIME } (the build time, from a production deployment only)). Grant paid features by writing feature_entitlements from your billing webhook."
191
+ ]
192
+ },
193
+ "owner-access": {
194
+ "feature": {
195
+ "name": "Owner access",
196
+ "summary": "The owner-access contract: fail-closed wrappers (genesis_owner_readable, genesis_owner_allows) over the app's two hooks, for every Genesis block whose rows belong to a person, a team or the tenant.",
197
+ "keywords": [
198
+ "access",
199
+ "owners",
200
+ "row level security",
201
+ "tenants",
202
+ "teams"
203
+ ],
204
+ "audience": [
205
+ "developer"
206
+ ]
207
+ },
208
+ "platforms": [
209
+ "web",
210
+ "native"
211
+ ],
212
+ "requires": [
213
+ "tenant-features"
214
+ ],
215
+ "migrations": [
216
+ {
217
+ "file": "migrations/0009_genesis_owner_access.sql",
218
+ "test": "migrations/tests/0009_genesis_owner_access.test.sql"
183
219
  }
184
220
  ],
221
+ "install": [
222
+ "@supabase/supabase-js@^2.118.0"
223
+ ],
185
224
  "steps": [
186
- "Sync the registry on every deploy with the service key: syncFeatureRegistry(admin, features.json, { version: BUILD_TIME }). Grant paid features by writing feature_entitlements from your billing webhook."
225
+ "Define private.genesis_owner_can(tenant, viewer, person_id, team_id, organization_id, action) and private.genesis_readable_owners(viewer) in your own migration, as the header of 0009 shows. Without them the wrappers answer no."
187
226
  ]
188
227
  }
189
228
  }
@@ -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,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"chunk-ONBOLMXH.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 privacy: {\n notes: [\n \"Stores which tenants hold which paid features and flag values; no personal data.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n"]}