@marktiderman/genesis-supabase 0.5.0 → 0.6.1

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
@@ -589,6 +589,42 @@ A delete that cascades into `tenant_features` (from your tenant table, or a pers
589
589
  goes with them) isn't recorded, so it never refuses the tenant's or the person's deletion; saving
590
590
  the same switch and reason again changes nothing, not even who and when.
591
591
 
592
+ ## The feature registry in the database (the feature-mirror block)
593
+
594
+ Migration `0008_genesis_feature_registry.sql` (needs 0004) gives the feature gate its rows. Why it works this
595
+ way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
596
+
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.
603
+ - **Paid access.** `feature_entitlements` (tenant, feature, source, `active`, optional `ends_at`). Your billing
604
+ webhook writes it with the service key.
605
+ - **Flag values.** `tenant_flag_values` overrides a flag's default for one tenant (service key).
606
+ - **The gate in SQL.** `feature_on(tenant, feature)` is true for a shipped feature that, when paid, has an
607
+ active entitlement; a signed-in caller outside the tenant gets false. It runs once per row, so in policies
608
+ over many rows use the once-per-statement pair instead:
609
+ `using ((select feature_shipped('exports')) and team_id = any (array(select feature_entitled_tenants('exports'))))`
610
+ (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
612
+ only `id, name, status, visibility, access_plan, platforms, in_registry`; the full record stays server side.
613
+ - **The snapshot's input.** `feature_gate_state(tenant)` returns the tenant's switches off, entitlements and
614
+ flag values, to its members (with their own JWT, so browsers and extensions can call it) and the service role.
615
+
616
+ ```ts
617
+ import { featureGateState, syncFeatureRegistry } from "@marktiderman/genesis-supabase";
618
+ import { gateSnapshot } from "@marktiderman/genesis-features/gate";
619
+ import registry from "../features.json";
620
+
621
+ // When a production deployment starts serving (never from a preview):
622
+ if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
623
+
624
+ const state = await featureGateState(supabase, teamId); // per session
625
+ const snapshot = gateSnapshot({ features, flags }, { platform: "web", ...state }, { version: BUILD_TIME });
626
+ ```
627
+
592
628
  ## Background jobs (the jobs block)
593
629
 
594
630
  `migrations/0007_genesis_jobs.sql` is one queue for background work and one way to schedule it, so
package/dist/blocks.d.ts CHANGED
@@ -15,6 +15,14 @@ declare const accountBlock: _marktiderman_genesis_features_blocks.BlockDef<"acco
15
15
  * @stability Beta
16
16
  */
17
17
  declare const tenantFeaturesBlock: _marktiderman_genesis_features_blocks.BlockDef<"tenant-features", never>;
18
+ /**
19
+ * The feature registry block: the registry mirrored into the app's database
20
+ * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,
21
+ * for the feature gate. Needs the tenant features block.
22
+ *
23
+ * @stability Beta
24
+ */
25
+ declare const featureMirrorBlock: _marktiderman_genesis_features_blocks.BlockDef<"feature-mirror", never>;
18
26
  /**
19
27
  * The jobs block: a background-job queue and named schedules that call the
20
28
  * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.
@@ -23,4 +31,4 @@ declare const tenantFeaturesBlock: _marktiderman_genesis_features_blocks.BlockDe
23
31
  */
24
32
  declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs", never>;
25
33
 
26
- export { accountBlock, jobsBlock, tenantFeaturesBlock };
34
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
package/dist/blocks.js CHANGED
@@ -1,3 +1,3 @@
1
- export { accountBlock, jobsBlock, tenantFeaturesBlock } from './chunk-A3H5CTYT.js';
1
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
2
2
  //# sourceMappingURL=blocks.js.map
3
3
  //# sourceMappingURL=blocks.js.map
@@ -0,0 +1,96 @@
1
+ import { defineBlock } from '@marktiderman/genesis-features/blocks';
2
+
3
+ // src/blocks.ts
4
+ var PACKAGE = "@marktiderman/genesis-supabase";
5
+ var accountBlock = defineBlock({
6
+ id: "account",
7
+ platforms: ["web", "native"],
8
+ contributes: {
9
+ migrations: [
10
+ {
11
+ package: PACKAGE,
12
+ file: "migrations/0001_genesis_account_deletion.sql",
13
+ test: "migrations/tests/0001_genesis_account_deletion.test.sql"
14
+ },
15
+ // With Sign in with Apple, with the genesis-apple-revoke function beside it.
16
+ {
17
+ package: PACKAGE,
18
+ file: "migrations/0003_genesis_apple_token_revocation.sql",
19
+ test: "migrations/tests/0003_genesis_apple_token_revocation.test.sql"
20
+ }
21
+ ],
22
+ privacy: {
23
+ collects: [
24
+ {
25
+ type: "email address",
26
+ purposes: ["app functionality"],
27
+ linked: true,
28
+ tracking: false
29
+ },
30
+ {
31
+ type: "user id",
32
+ purposes: ["app functionality"],
33
+ linked: true,
34
+ tracking: false
35
+ },
36
+ {
37
+ type: "name",
38
+ purposes: ["app functionality"],
39
+ linked: true,
40
+ tracking: false
41
+ }
42
+ ],
43
+ notes: [
44
+ "People delete their account from inside the app; their login and the rows that cascade from it go with it.",
45
+ "With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted."
46
+ ]
47
+ }
48
+ }
49
+ });
50
+ var tenantFeaturesBlock = defineBlock({
51
+ id: "tenant-features",
52
+ contributes: {
53
+ migrations: [
54
+ {
55
+ package: PACKAGE,
56
+ file: "migrations/0004_genesis_tenant_features.sql",
57
+ test: "migrations/tests/0004_genesis_tenant_features.test.sql"
58
+ }
59
+ ],
60
+ privacy: {
61
+ notes: [
62
+ "Keeps who changed a tenant's switches; a deleted person's changes stay, without the person."
63
+ ]
64
+ }
65
+ }
66
+ });
67
+ var featureMirrorBlock = defineBlock({
68
+ id: "feature-mirror",
69
+ requires: ["tenant-features"],
70
+ contributes: {
71
+ migrations: [
72
+ {
73
+ package: PACKAGE,
74
+ file: "migrations/0008_genesis_feature_registry.sql",
75
+ test: "migrations/tests/0008_genesis_feature_registry.test.sql"
76
+ }
77
+ ],
78
+ privacy: {
79
+ notes: [
80
+ "Stores which tenants hold which paid features and flag values; no personal data."
81
+ ]
82
+ }
83
+ }
84
+ });
85
+ var jobsBlock = defineBlock({
86
+ id: "jobs",
87
+ platforms: ["web"],
88
+ contributes: {
89
+ migrations: [{ package: PACKAGE, file: "migrations/0007_genesis_jobs.sql", test: "migrations/tests/0007_genesis_jobs.test.sql" }],
90
+ privacy: { notes: ["Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days."] }
91
+ }
92
+ });
93
+
94
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
95
+ //# sourceMappingURL=chunk-ONBOLMXH.js.map
96
+ //# sourceMappingURL=chunk-ONBOLMXH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/blocks.ts"],"names":[],"mappings":";;;AAQA,IAAM,OAAA,GAAU,gCAAA;AAST,IAAM,eAAe,WAAA,CAAY;AAAA,EACtC,EAAA,EAAI,SAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,8CAAA;AAAA,QACN,IAAA,EAAM;AAAA,OACR;AAAA;AAAA,MAEA;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,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,EA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AAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,kCAAA,EAAoC,IAAA,EAAM,6CAAA,EAA+C,CAAA;AAAA,IAChI,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC","file":"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"]}
@@ -185,6 +185,81 @@ declare function tenantFeatureHistory(client: TenantFeaturesClient, tenantId: st
185
185
  maxRows?: number;
186
186
  }): Promise<TenantFeatureChange[]>;
187
187
 
188
+ /**
189
+ * The feature registry in the database: the client half of
190
+ * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code
191
+ * registry on deploy; anyone building the gate's snapshot reads a tenant's
192
+ * runtime state in one call.
193
+ */
194
+
195
+ /** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */
196
+ interface FeatureRegistryClient {
197
+ rpc: (fn: any, ...rest: any[]) => PromiseLike<{
198
+ data: unknown;
199
+ error: PostgrestErrorLike | null;
200
+ }>;
201
+ }
202
+ /** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */
203
+ type FlagStateValue = boolean | string | number | {
204
+ readonly [key: string]: unknown;
205
+ };
206
+ /**
207
+ * A tenant's runtime state for the gate, shaped to spread into a
208
+ * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.
209
+ *
210
+ * @stability Beta
211
+ */
212
+ interface FeatureGateState {
213
+ /** Feature ids the tenant switched off. */
214
+ off: string[];
215
+ /** Feature ids the tenant holds an active entitlement for. */
216
+ entitlements: string[];
217
+ /** Flag values for the tenant (platform values applied), by flag name. */
218
+ flags: Record<string, FlagStateValue>;
219
+ }
220
+ /**
221
+ * A tenant's switches, entitlements and flag values: `feature_gate_state`.
222
+ * Works with a signed-in person's client (for tenants they belong to) or the
223
+ * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a
224
+ * refusal is never mistaken for "nothing set".
225
+ *
226
+ * @stability Beta
227
+ */
228
+ declare function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState>;
229
+ /** `features.json` as `genesis features build` writes it. @stability Beta */
230
+ interface FeatureRegistryDocument {
231
+ features: readonly ({
232
+ id: string;
233
+ } & Record<string, unknown>)[];
234
+ flags?: Readonly<Record<string, Record<string, unknown>>>;
235
+ }
236
+ /** @stability Beta */
237
+ interface SyncFeatureRegistryOptions {
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.
242
+ */
243
+ version: number;
244
+ /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */
245
+ allowShrink?: boolean;
246
+ }
247
+ /**
248
+ * Copy the registry into the database: `sync_feature_registry`. Call it with
249
+ * the service key when a production deployment starts serving, never from a
250
+ * preview. Returns false when the database already has this registry or a
251
+ * newer one; throws (`22023`) for an empty registry or one that drops most
252
+ * features, unless `allowShrink`.
253
+ *
254
+ * ```ts
255
+ * import registry from "../features.json";
256
+ * if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
257
+ * ```
258
+ *
259
+ * @stability Beta
260
+ */
261
+ declare function syncFeatureRegistry(client: FeatureRegistryClient, document: FeatureRegistryDocument, options: SyncFeatureRegistryOptions): Promise<boolean>;
262
+
188
263
  /**
189
264
  * Supabase for Genesis apps. Platform-neutral: web, React Native and the
190
265
  * server import it. Native-only helpers (Keychain storage, foreground
@@ -314,4 +389,4 @@ interface DeleteMyAccountOptions {
314
389
  */
315
390
  declare function deleteMyAccount(client: DeleteAccountClient, options?: DeleteMyAccountOptions): Promise<void>;
316
391
 
317
- export { APPLE_REVOKE_FUNCTION as A, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FunctionsClient as F, type GenesisSupabaseOptions as G, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type SetTenantFeatureInput as d, type StoreAppleTokenOptions as e, type StoreAppleTokenResult as f, SupabaseQueryError as g, hasPkceCrypto as h, installWebCrypto as i, type TenantFeatureSetting as j, type TenantFeatures as k, type TenantFeaturesClient as l, createGenesisSupabase as m, deleteMyAccount as n, must as o, storeAppleToken as p, tenantFeatureSettings as q, requestAppleRevocation as r, setTenantFeature as s, tenantFeatureHistory as t, tenantFeatures as u };
392
+ export { APPLE_REVOKE_FUNCTION as A, tenantFeatureSettings as B, tenantFeatures as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type FeatureRegistryClient as d, type FeatureRegistryDocument as e, type FlagStateValue as f, type FunctionsClient as g, hasPkceCrypto as h, installWebCrypto as i, type SetTenantFeatureInput as j, type StoreAppleTokenOptions as k, type StoreAppleTokenResult as l, SupabaseQueryError as m, type SyncFeatureRegistryOptions as n, type TenantFeatureSetting as o, type TenantFeatures as p, type TenantFeaturesClient as q, createGenesisSupabase as r, deleteMyAccount as s, featureGateState as t, must as u, requestAppleRevocation as v, setTenantFeature as w, storeAppleToken as x, syncFeatureRegistry as y, tenantFeatureHistory as z };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@supabase/supabase-js';
2
- export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, d as SetTenantFeatureInput, e as StoreAppleTokenOptions, f as StoreAppleTokenResult, g as SupabaseQueryError, T as TenantFeatureChange, j as TenantFeatureSetting, k as TenantFeatures, l as TenantFeaturesClient, m as createGenesisSupabase, n as deleteMyAccount, o as must, r as requestAppleRevocation, s as setTenantFeature, p as storeAppleToken, t as tenantFeatureHistory, q as tenantFeatureSettings, u as tenantFeatures } from './index-BSGz3RGk.js';
3
- export { accountBlock, 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-Ds0tO9WP.js';
3
+ export { accountBlock, featureMirrorBlock, jobsBlock, 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, jobsBlock, tenantFeaturesBlock } from './chunk-A3H5CTYT.js';
2
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
3
3
  import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
4
4
 
5
5
  // src/apple-tokens.ts
@@ -48,6 +48,65 @@ async function tenantFeatureHistory(client, tenantId, options = {}) {
48
48
  return must(await client.rpc("tenant_feature_history", args)) ?? [];
49
49
  }
50
50
 
51
+ // src/feature-registry.ts
52
+ var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
53
+ async function featureGateState(client, tenantId) {
54
+ const data = must(await client.rpc("feature_gate_state", { tenant: tenantId }));
55
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new TypeError("feature_gate_state returned no state");
56
+ const { off, entitled, flags } = data;
57
+ if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== "object" || Array.isArray(flags)) {
58
+ throw new TypeError("feature_gate_state returned an unexpected shape");
59
+ }
60
+ const values = {};
61
+ for (const [key, value] of Object.entries(flags)) {
62
+ if (typeof value === "boolean" || typeof value === "string" || typeof value === "number") values[key] = value;
63
+ else if (value && typeof value === "object" && !Array.isArray(value)) values[key] = value;
64
+ }
65
+ return { off: strings(off), entitlements: strings(entitled), flags: values };
66
+ }
67
+ function canonical(value) {
68
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
69
+ if (value && typeof value === "object") {
70
+ const entries = Object.entries(value).filter(
71
+ ([, v]) => v !== void 0
72
+ );
73
+ return `{${entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
74
+ }
75
+ return JSON.stringify(value) ?? "null";
76
+ }
77
+ async function sha256(text) {
78
+ const digest = await globalThis.crypto.subtle.digest(
79
+ "SHA-256",
80
+ new TextEncoder().encode(text)
81
+ );
82
+ return Array.from(
83
+ new Uint8Array(digest),
84
+ (b) => b.toString(16).padStart(2, "0")
85
+ ).join("");
86
+ }
87
+ async function syncFeatureRegistry(client, document, options) {
88
+ if (!Number.isSafeInteger(options.version) || options.version < 0) {
89
+ throw new TypeError(
90
+ "syncFeatureRegistry: version must be a non-negative integer"
91
+ );
92
+ }
93
+ const features = [...document.features];
94
+ const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({
95
+ key,
96
+ ...flag
97
+ }));
98
+ const hash = await sha256(canonical({ features, flags }));
99
+ return must(
100
+ await client.rpc("sync_feature_registry", {
101
+ version: options.version,
102
+ hash,
103
+ features,
104
+ flags,
105
+ allow_shrink: options.allowShrink ?? false
106
+ })
107
+ ) === true;
108
+ }
109
+
51
110
  // src/index.ts
52
111
  function createGenesisSupabase({
53
112
  url,
@@ -100,6 +159,6 @@ async function deleteMyAccount(client, options = {}) {
100
159
  await client.auth.signOut({ scope: "local" });
101
160
  }
102
161
 
103
- export { APPLE_REVOKE_FUNCTION, SupabaseQueryError, createGenesisSupabase, deleteMyAccount, must, requestAppleRevocation, setTenantFeature, storeAppleToken, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
162
+ export { APPLE_REVOKE_FUNCTION, SupabaseQueryError, createGenesisSupabase, deleteMyAccount, featureGateState, must, requestAppleRevocation, setTenantFeature, storeAppleToken, syncFeatureRegistry, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
104
163
  //# sourceMappingURL=index.js.map
105
164
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,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,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAClB,IAAA,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACrB,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAAA,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,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 * 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 { accountBlock, 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,MAAM,MAAA,CAAQ,KAAA,CAAgC,OAAA,IAAW,KAAK,CAAC,CAAA,EAAE;AAC5I,IAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AAAA,EACpB,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA,EAAE;AAAA,EACvF;AACF;AAQA,eAAsB,sBAAA,CAAuB,MAAA,EAAy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YAAY,KAAA,EAA2B;AACrC,IAAA,KAAA,CAAM,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAO,CAAA;AACrC,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAClB,IAAA,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACrB,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAAA,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,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"]}
package/dist/native.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SessionStorage } from './index-BSGz3RGk.js';
2
- export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-BSGz3RGk.js';
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';
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,412 @@
1
+ -- Genesis feature registry in the database: the mirror, entitlements, flag values and the gate.
2
+ --
3
+ -- Feature and flag definitions live in code (`features.ts`, `flags.json`). This file gives the
4
+ -- app's database the rows the gate needs (ADR 0001, "One feature gate"):
5
+ --
6
+ -- public.features, public.feature_flags
7
+ -- A mirror of the registry, written only by public.sync_feature_registry with the service
8
+ -- key, by production deploys only (a preview must never sync production). Each sync carries a
9
+ -- version: the time the deployment started serving, not its build time, so an instant
10
+ -- rollback to an older build syncs as the newest. An older version than the last one synced is
11
+ -- refused (two instances racing), and the same hash again changes nothing. An empty registry,
12
+ -- or one that drops more than a fifth of the features (at least 3), is refused unless the call
13
+ -- says allow_shrink: a broken features.json must not switch everything off. Nothing is ever
14
+ -- deleted: a feature or flag gone from the registry is marked in_registry = false, and a
15
+ -- flag's per-tenant values stay until it comes back or you delete them.
16
+ --
17
+ -- public.feature_entitlements
18
+ -- Which tenant may use which paid feature (`access: { plan }`), by source (a billing webhook,
19
+ -- a manual grant), optionally until a time. Written by the service role only.
20
+ --
21
+ -- public.tenant_flag_values, feature_flags.platform_value
22
+ -- A flag's value for one tenant, overriding its default; and a value for every tenant at once
23
+ -- (a kill switch), overriding tenant values. Written by the service role only.
24
+ --
25
+ -- public.feature_on(tenant, feature)
26
+ -- The gate in SQL, for row security and functions: shipped (beta, live or deprecated) and,
27
+ -- when paid, entitled. Nothing else: platform, tenant switches and flags are exposure, which
28
+ -- server code enforces with the TypeScript gate (`requireFeature`).
29
+ --
30
+ -- public.feature_gate_state(tenant)
31
+ -- A tenant's runtime state in one call (switches off, entitlements held, flag values), for the
32
+ -- server to build the gate's snapshot. For the tenant's members, and the service role.
33
+ --
34
+ -- Tenants and membership: as in 0004_genesis_tenant_features, a tenant is any uuid your app
35
+ -- groups people by, and private.genesis_tenant_member / private.genesis_tenant_admin (your
36
+ -- hooks) decide who belongs. This file needs 0004 (it reads tenant_features and its hooks).
37
+ -- Add your tenant foreign keys yourself in a later migration:
38
+ --
39
+ -- alter table public.feature_entitlements add foreign key (tenant_id) references public.teams (id) on delete cascade;
40
+ -- alter table public.tenant_flag_values add foreign key (tenant_id) references public.teams (id) on delete cascade;
41
+ --
42
+ -- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
43
+ -- (`genesis migrate` does it). Never edit it once applied; change it with a new migration.
44
+ --
45
+ -- Verify: the pgTAP test beside this file (`tests/0008_genesis_feature_registry.test.sql`).
46
+
47
+ create schema if not exists private;
48
+
49
+ -- The mirror -----------------------------------------------------------------------------------
50
+
51
+ create table public.features (
52
+ id text primary key
53
+ constraint features_id_format check (id ~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' and char_length(id) <= 100),
54
+ name text not null,
55
+ status text not null
56
+ constraint features_status check (status in ('idea', 'planned', 'building', 'beta', 'live', 'deprecated', 'retired')),
57
+ visibility text not null default 'customer',
58
+ -- The plan a paid feature needs (`access: { plan }`); null when everyone gets it.
59
+ access_plan text,
60
+ -- The status per platform (`platforms`), when the registry gives one.
61
+ platforms jsonb,
62
+ -- The whole registry entry, as code defines it.
63
+ record jsonb not null,
64
+ in_registry boolean not null default true,
65
+ synced_at timestamptz not null default now()
66
+ );
67
+
68
+ comment on table public.features is
69
+ 'Mirror of features.ts, written only by sync_feature_registry. Ids are permanent: rows are never deleted. Genesis feature registry.';
70
+
71
+ create table public.feature_flags (
72
+ key text primary key,
73
+ feature_id text not null references public.features (id),
74
+ kind text not null,
75
+ default_value jsonb not null,
76
+ scopes text[] not null default '{}',
77
+ expires date,
78
+ record jsonb not null,
79
+ in_registry boolean not null default true,
80
+ -- A value for every tenant, set by the service role: a kill switch or a global rollout. It
81
+ -- overrides tenant values, and sync never touches it.
82
+ platform_value jsonb,
83
+ synced_at timestamptz not null default now()
84
+ );
85
+
86
+ create index feature_flags_feature on public.feature_flags (feature_id);
87
+
88
+ comment on table public.feature_flags is
89
+ 'Mirror of flags.json, written only by sync_feature_registry. A flag gone from the registry is kept, marked in_registry = false. Genesis feature registry.';
90
+
91
+ create table private.feature_registry_state (
92
+ id boolean primary key default true constraint feature_registry_state_one_row check (id),
93
+ version bigint not null,
94
+ hash text not null,
95
+ synced_at timestamptz not null default now()
96
+ );
97
+
98
+ create or replace function public.sync_feature_registry(version bigint, hash text, features jsonb, flags jsonb, allow_shrink boolean default false)
99
+ returns boolean
100
+ language plpgsql
101
+ security definer
102
+ set search_path = ''
103
+ as $$
104
+ declare
105
+ current_count int;
106
+ gone_count int;
107
+ begin
108
+ if version is null or hash is null
109
+ or jsonb_typeof(features) is distinct from 'array' or jsonb_typeof(flags) is distinct from 'array' then
110
+ raise exception 'sync_feature_registry: needs a version, a hash and two arrays' using errcode = '22023';
111
+ end if;
112
+ if exists (select 1 from jsonb_array_elements(features) r where coalesce(r ->> 'id', '') = '')
113
+ or jsonb_array_length(features) <> (select count(distinct r ->> 'id') from jsonb_array_elements(features) r) then
114
+ raise exception 'sync_feature_registry: every feature needs a unique id' using errcode = '22023';
115
+ end if;
116
+ if exists (select 1 from jsonb_array_elements(flags) r where coalesce(r ->> 'key', '') = '')
117
+ or jsonb_array_length(flags) <> (select count(distinct r ->> 'key') from jsonb_array_elements(flags) r) then
118
+ raise exception 'sync_feature_registry: every flag needs a unique key' using errcode = '22023';
119
+ end if;
120
+ -- One sync at a time: a second deploy waits, then finds itself already current.
121
+ perform pg_advisory_xact_lock(hashtext('public.sync_feature_registry'));
122
+ -- Never backwards, and nothing to do for the same registry.
123
+ 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
124
+ return false;
125
+ end if;
126
+ -- A broken or foreign registry must not switch everything off.
127
+ select count(*) into current_count from public.features f where f.in_registry;
128
+ select count(*) into gone_count from public.features f
129
+ where f.in_registry and not exists (select 1 from jsonb_array_elements(features) r where r ->> 'id' = f.id);
130
+ if not coalesce(allow_shrink, false) and (jsonb_array_length(features) = 0 or (gone_count >= 3 and gone_count * 5 > current_count)) then
131
+ raise exception 'sync_feature_registry: this registry drops % of % features', gone_count, current_count
132
+ using errcode = '22023', hint = 'Check features.json; if the removal is intended, call again with allow_shrink => true.';
133
+ end if;
134
+
135
+ insert into public.features as f (id, name, status, visibility, access_plan, platforms, record, in_registry, synced_at)
136
+ select r ->> 'id', r ->> 'name', r ->> 'status', coalesce(r ->> 'visibility', 'customer'),
137
+ case when jsonb_typeof(r -> 'access') = 'object' then nullif(btrim(r -> 'access' ->> 'plan'), '') end,
138
+ case when jsonb_typeof(r -> 'platforms') = 'object' then r -> 'platforms' end,
139
+ r, true, now()
140
+ from jsonb_array_elements(features) r
141
+ on conflict (id) do update set
142
+ name = excluded.name, status = excluded.status, visibility = excluded.visibility, access_plan = excluded.access_plan,
143
+ platforms = excluded.platforms, record = excluded.record, in_registry = true, synced_at = excluded.synced_at;
144
+
145
+ -- Ids are permanent: a feature the registry no longer lists stays, marked as gone.
146
+ update public.features f set in_registry = false, synced_at = now()
147
+ where f.in_registry and not exists (select 1 from jsonb_array_elements(features) r where r ->> 'id' = f.id);
148
+
149
+ update public.feature_flags fl set in_registry = false, synced_at = now()
150
+ where fl.in_registry and not exists (select 1 from jsonb_array_elements(flags) r where r ->> 'key' = fl.key);
151
+ insert into public.feature_flags as fl (key, feature_id, kind, default_value, scopes, expires, record, in_registry, synced_at)
152
+ select r ->> 'key', r ->> 'feature', r ->> 'kind', coalesce(r -> 'default', 'false'::jsonb),
153
+ coalesce(array(select jsonb_array_elements_text(r -> 'scopes')), '{}'),
154
+ (r ->> 'expires')::date, r, true, now()
155
+ from jsonb_array_elements(flags) r
156
+ on conflict (key) do update set
157
+ feature_id = excluded.feature_id, kind = excluded.kind, default_value = excluded.default_value,
158
+ scopes = excluded.scopes, expires = excluded.expires, record = excluded.record, in_registry = true,
159
+ synced_at = excluded.synced_at;
160
+
161
+ insert into private.feature_registry_state (id, version, hash, synced_at)
162
+ values (true, sync_feature_registry.version, sync_feature_registry.hash, now())
163
+ on conflict (id) do update set version = excluded.version, hash = excluded.hash, synced_at = excluded.synced_at;
164
+ return true;
165
+ end;
166
+ $$;
167
+
168
+ comment on function public.sync_feature_registry(bigint, text, jsonb, jsonb, boolean) is
169
+ 'Mirrors features.ts and flags.json into features and feature_flags. Service role, production deploys only. Refuses an older version, an empty registry or a sharp shrink (unless allow_shrink); the same hash is a no-op; nothing is deleted. Genesis feature registry.';
170
+
171
+ create or replace function public.feature_registry_synced()
172
+ returns table (version bigint, hash text, synced_at timestamptz)
173
+ language sql
174
+ stable
175
+ security definer
176
+ set search_path = ''
177
+ as $$
178
+ select s.version, s.hash, s.synced_at from private.feature_registry_state s
179
+ $$;
180
+
181
+ comment on function public.feature_registry_synced() is
182
+ 'The version, hash and time of the last registry sync. Service role only. Genesis feature registry.';
183
+
184
+ -- Paid access and flag values ------------------------------------------------------------------
185
+
186
+ create table public.feature_entitlements (
187
+ tenant_id uuid not null,
188
+ -- No foreign key: a billing webhook may grant a feature before the deploy that adds it syncs.
189
+ feature_id text not null
190
+ constraint feature_entitlements_feature_id_format check (feature_id ~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' and char_length(feature_id) <= 100),
191
+ -- Where the grant comes from: 'stripe', 'manual', 'trial' … One row per source.
192
+ source text not null
193
+ constraint feature_entitlements_source_format check (source ~ '^[a-z][a-z0-9_-]*$' and char_length(source) <= 40),
194
+ active boolean not null,
195
+ -- Optional end of the grant; past it the entitlement no longer counts.
196
+ ends_at timestamptz,
197
+ updated_at timestamptz not null default now(),
198
+ primary key (tenant_id, feature_id, source)
199
+ );
200
+
201
+ comment on table public.feature_entitlements is
202
+ 'Which tenant may use which paid feature, by source, optionally until ends_at. The feature id doubles as the billing lookup key. Service role only. Genesis feature registry.';
203
+
204
+ create table public.tenant_flag_values (
205
+ tenant_id uuid not null,
206
+ flag_key text not null references public.feature_flags (key),
207
+ value jsonb not null,
208
+ updated_at timestamptz not null default now(),
209
+ primary key (tenant_id, flag_key)
210
+ );
211
+
212
+ comment on table public.tenant_flag_values is
213
+ 'A flag''s value for one tenant, overriding its default. Kept while its flag is out of the registry. Service role only. Genesis feature registry.';
214
+
215
+ -- The gate -------------------------------------------------------------------------------------
216
+
217
+ -- Who is asking: server code (the service role, or a direct database connection with no request
218
+ -- claims) answers for any tenant; everyone else must be a member. Decided on the request's role,
219
+ -- never on a missing person: an authenticated request without `sub` is refused, not trusted.
220
+ create or replace function private.genesis_feature_caller_is_server()
221
+ returns boolean
222
+ language plpgsql
223
+ stable
224
+ security definer
225
+ set search_path = ''
226
+ as $$
227
+ declare
228
+ claims jsonb := coalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb, '{}'::jsonb);
229
+ request_role text := coalesce(nullif(claims ->> 'role', ''), nullif(current_setting('request.jwt.claim.role', true), ''));
230
+ begin
231
+ return request_role is null or request_role = 'service_role';
232
+ end;
233
+ $$;
234
+
235
+ create or replace function private.genesis_feature_may_read(tenant uuid)
236
+ returns boolean
237
+ language plpgsql
238
+ stable
239
+ security definer
240
+ set search_path = ''
241
+ as $$
242
+ begin
243
+ return private.genesis_feature_caller_is_server() or private.genesis_is_tenant_member(tenant);
244
+ end;
245
+ $$;
246
+
247
+ -- Shipped and, when paid, entitled: the part of the gate that row security enforces. A signed-in
248
+ -- caller gets an answer only for a tenant they belong to (false otherwise), so a policy can't be
249
+ -- used to probe another tenant's plan. Server code (the service role, no signed-in person) gets
250
+ -- an answer for any tenant.
251
+ create or replace function public.feature_on(tenant uuid, feature text)
252
+ returns boolean
253
+ language plpgsql
254
+ stable
255
+ security definer
256
+ set search_path = ''
257
+ as $$
258
+ begin
259
+ if tenant is null or feature is null then
260
+ return false;
261
+ end if;
262
+ if not private.genesis_feature_may_read(tenant) then
263
+ return false;
264
+ end if;
265
+ return exists (
266
+ select 1 from public.features f
267
+ where f.id = feature and f.in_registry and f.status in ('beta', 'live', 'deprecated')
268
+ and (f.access_plan is null or exists (
269
+ select 1 from public.feature_entitlements e
270
+ where e.tenant_id = tenant and e.feature_id = f.id and e.active and (e.ends_at is null or e.ends_at > now())
271
+ ))
272
+ );
273
+ end;
274
+ $$;
275
+
276
+ comment on function public.feature_on(uuid, text) is
277
+ 'The gate in SQL: shipped (beta, live, deprecated) and entitled when paid. For row security. A signed-in caller outside the tenant gets false. Genesis feature registry.';
278
+
279
+ -- For row security over many rows, two answers Postgres computes once per statement instead of
280
+ -- once per row (wrap them in a subquery):
281
+ -- free feature: using ((select public.feature_shipped('notes')) and <your row rule>)
282
+ -- paid feature: using ((select public.feature_shipped('exports'))
283
+ -- and tenant_id = any (array(select public.feature_entitled_tenants('exports'))) and <your row rule>)
284
+ create or replace function public.feature_shipped(feature text)
285
+ returns boolean
286
+ language sql
287
+ stable
288
+ security definer
289
+ set search_path = ''
290
+ as $$
291
+ select exists (
292
+ select 1 from public.features f
293
+ where f.id = feature and f.in_registry and f.status in ('beta', 'live', 'deprecated')
294
+ )
295
+ $$;
296
+
297
+ comment on function public.feature_shipped(text) is
298
+ 'Whether a feature has shipped (beta, live, deprecated), whatever the tenant. For row security, once per statement. Genesis feature registry.';
299
+
300
+ -- The tenants with an active entitlement to a feature: every one for server code, only the
301
+ -- caller's own for a signed-in person.
302
+ create or replace function public.feature_entitled_tenants(feature text)
303
+ returns setof uuid
304
+ language plpgsql
305
+ stable
306
+ security definer
307
+ set search_path = ''
308
+ as $$
309
+ begin
310
+ return query
311
+ select distinct e.tenant_id from public.feature_entitlements e
312
+ where e.feature_id = feature and e.active and (e.ends_at is null or e.ends_at > now())
313
+ and private.genesis_feature_may_read(e.tenant_id);
314
+ end;
315
+ $$;
316
+
317
+ comment on function public.feature_entitled_tenants(text) is
318
+ 'Tenants holding an active entitlement to a feature (the caller''s own when signed in). For row security, once per statement. Genesis feature registry.';
319
+
320
+ -- A tenant's runtime state for the gate's snapshot: { off: [ids], entitled: [ids], flags: { key: value } }.
321
+ create or replace function public.feature_gate_state(tenant uuid)
322
+ returns jsonb
323
+ language plpgsql
324
+ stable
325
+ security definer
326
+ set search_path = ''
327
+ as $$
328
+ begin
329
+ if tenant is null then
330
+ raise exception 'feature_gate_state: tenant is required' using errcode = '22004';
331
+ end if;
332
+ if not private.genesis_feature_may_read(tenant) then
333
+ raise exception 'feature_gate_state: only the tenant''s members can read its features' using errcode = '42501';
334
+ end if;
335
+ return jsonb_build_object(
336
+ 'off', coalesce((
337
+ select jsonb_agg(t.feature_id order by t.feature_id) from public.tenant_features t
338
+ where t.tenant_id = tenant and not t.enabled
339
+ ), '[]'::jsonb),
340
+ 'entitled', coalesce((
341
+ select jsonb_agg(distinct e.feature_id) from public.feature_entitlements e
342
+ where e.tenant_id = tenant and e.active and (e.ends_at is null or e.ends_at > now())
343
+ ), '[]'::jsonb),
344
+ -- The tenant's own values, then platform values on top: a platform value (a kill switch)
345
+ -- applies to every tenant, whatever the tenant's own value.
346
+ 'flags', coalesce((
347
+ select jsonb_object_agg(v.flag_key, v.value) from public.tenant_flag_values v
348
+ join public.feature_flags fl on fl.key = v.flag_key and fl.in_registry
349
+ where v.tenant_id = tenant
350
+ ), '{}'::jsonb) || coalesce((
351
+ select jsonb_object_agg(fl.key, fl.platform_value) from public.feature_flags fl
352
+ where fl.in_registry and fl.platform_value is not null
353
+ ), '{}'::jsonb)
354
+ );
355
+ end;
356
+ $$;
357
+
358
+ comment on function public.feature_gate_state(uuid) is
359
+ 'A tenant''s switches off, entitlements held and flag values, for the gate''s snapshot. Its members and the service role. Genesis feature registry.';
360
+
361
+ -- Access ---------------------------------------------------------------------------------------
362
+
363
+ alter table public.features enable row level security;
364
+ alter table public.feature_flags enable row level security;
365
+ alter table public.feature_entitlements enable row level security;
366
+ alter table public.tenant_flag_values enable row level security;
367
+ alter table private.feature_registry_state enable row level security;
368
+
369
+ -- Signed-in people (not anonymous sign-ins) read shipped, customer-facing features, and only the
370
+ -- columns a screen needs: the full record (owners, plans, acceptance, links) stays server side.
371
+ -- Flags, entitlements and flag values are read through feature_gate_state.
372
+ revoke all on table public.features from public, anon, authenticated, service_role;
373
+ grant select on table public.features to service_role;
374
+ grant select (id, name, status, visibility, access_plan, platforms, in_registry) on table public.features to authenticated;
375
+ create policy "Signed-in people read shipped features" on public.features for select to authenticated
376
+ using (
377
+ in_registry and status in ('beta', 'live', 'deprecated') and visibility in ('customer', 'public')
378
+ and not coalesce((select (auth.jwt() ->> 'is_anonymous')::boolean), false)
379
+ );
380
+
381
+ revoke all on table public.feature_flags from public, anon, authenticated, service_role;
382
+ grant select on table public.feature_flags to service_role;
383
+ -- The service role sets platform values; everything else in the row belongs to the sync.
384
+ grant update (platform_value) on table public.feature_flags to service_role;
385
+
386
+ revoke all on table public.feature_entitlements from public, anon, authenticated, service_role;
387
+ grant select, insert, update, delete on table public.feature_entitlements to service_role;
388
+
389
+ revoke all on table public.tenant_flag_values from public, anon, authenticated, service_role;
390
+ grant select, insert, update, delete on table public.tenant_flag_values to service_role;
391
+
392
+ revoke all on table private.feature_registry_state from public, anon, authenticated, service_role;
393
+ revoke execute on function private.genesis_feature_caller_is_server() from public, anon, authenticated;
394
+ revoke execute on function private.genesis_feature_may_read(uuid) from public, anon, authenticated;
395
+
396
+ revoke execute on function public.sync_feature_registry(bigint, text, jsonb, jsonb, boolean) from public, anon, authenticated;
397
+ grant execute on function public.sync_feature_registry(bigint, text, jsonb, jsonb, boolean) to service_role;
398
+ revoke execute on function public.feature_registry_synced() from public, anon, authenticated;
399
+ grant execute on function public.feature_registry_synced() to service_role;
400
+ revoke execute on function public.feature_gate_state(uuid) from public, anon;
401
+ grant execute on function public.feature_gate_state(uuid) to authenticated, service_role;
402
+
403
+ -- For one row or a function: `public.feature_on(tenant_id, 'my-feature')`; over many rows prefer
404
+ -- feature_shipped and feature_entitled_tenants (above). Policies run as the
405
+ -- querying role, so authenticated needs execute. Anon gets nothing: without a signed-in person
406
+ -- the function answers for any tenant, which is for server code only.
407
+ revoke execute on function public.feature_on(uuid, text) from public, anon;
408
+ grant execute on function public.feature_on(uuid, text) to authenticated, service_role;
409
+ revoke execute on function public.feature_shipped(text) from public, anon;
410
+ grant execute on function public.feature_shipped(text) to authenticated, service_role;
411
+ revoke execute on function public.feature_entitled_tenants(text) from public, anon;
412
+ grant execute on function public.feature_entitled_tenants(text) to authenticated, service_role;
@@ -0,0 +1,180 @@
1
+ -- @feat:feature-mirror
2
+ -- pgTAP test for 0008_genesis_feature_registry.sql (needs 0004_genesis_tenant_features.sql).
3
+ -- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
4
+ -- It writes only its own users, tenants, hooks and registry rows and rolls everything back.
5
+ -- If your app already has the hooks, they are replaced inside this transaction only.
6
+ begin;
7
+ create extension if not exists pgtap with schema extensions;
8
+ select plan(62);
9
+
10
+ -- People: a1 admin of tenant 1, b2 member of tenant 1, c3 admin of tenant 2.
11
+ insert into auth.users (id, aud, role, email, instance_id)
12
+ select ('00000000-0000-4000-8000-0000000000' || n)::uuid, 'authenticated', 'authenticated', 'genesis-registry-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
13
+ from unnest(array['a1', 'b2', 'c3']) n;
14
+
15
+ create function pg_temp.person(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000000' || n)::uuid $$;
16
+ create function pg_temp.tenant(n int) returns uuid language sql immutable as $$ select ('00000000-0000-4000-9000-00000000000' || n)::uuid $$;
17
+ create function pg_temp.sign_in(n text) returns void language plpgsql as $$
18
+ begin
19
+ perform set_config('role', 'authenticated', true);
20
+ perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.person(n), 'role', 'authenticated')::text, true);
21
+ perform set_config('request.jwt.claim.sub', pg_temp.person(n)::text, true);
22
+ end $$;
23
+ create function pg_temp.as_service() returns void language plpgsql as $$
24
+ begin
25
+ perform set_config('role', 'service_role', true);
26
+ perform set_config('request.jwt.claims', json_build_object('role', 'service_role')::text, true);
27
+ perform set_config('request.jwt.claim.sub', '', true);
28
+ end $$;
29
+ create function pg_temp.as_owner() returns void language plpgsql as $$
30
+ begin
31
+ perform set_config('role', 'postgres', true);
32
+ perform set_config('request.jwt.claims', '', true);
33
+ perform set_config('request.jwt.claim.sub', '', true);
34
+ end $$;
35
+ grant execute on function pg_temp.person(text), pg_temp.tenant(int), pg_temp.sign_in(text), pg_temp.as_service(), pg_temp.as_owner()
36
+ to anon, authenticated, service_role;
37
+
38
+ drop function if exists private.genesis_tenant_admin(uuid, uuid);
39
+ drop function if exists private.genesis_tenant_member(uuid, uuid);
40
+ create table private.genesis_test_members (tenant uuid, person uuid, admin boolean);
41
+ insert into private.genesis_test_members values
42
+ (pg_temp.tenant(1), pg_temp.person('a1'), true),
43
+ (pg_temp.tenant(1), pg_temp.person('b2'), false),
44
+ (pg_temp.tenant(2), pg_temp.person('c3'), true);
45
+ create function private.genesis_tenant_admin(tenant uuid, person uuid) returns boolean language sql stable set search_path = '' as $$
46
+ select exists (select 1 from private.genesis_test_members m where m.tenant = genesis_tenant_admin.tenant and m.person = genesis_tenant_admin.person and m.admin)
47
+ $$;
48
+ create function private.genesis_tenant_member(tenant uuid, person uuid) returns boolean language sql stable set search_path = '' as $$
49
+ select exists (select 1 from private.genesis_test_members m where m.tenant = genesis_tenant_member.tenant and m.person = genesis_tenant_member.person)
50
+ $$;
51
+ revoke execute on function private.genesis_tenant_admin(uuid, uuid), private.genesis_tenant_member(uuid, uuid) from public, anon, authenticated;
52
+
53
+ -- The registry: live, paid, beta behind a flag, planned. The same shapes as features.json.
54
+ create table pg_temp.registry (features jsonb, flags jsonb);
55
+ insert into pg_temp.registry values (
56
+ '[{"id": "forms", "name": "Forms", "status": "live", "apps": ["web"]},
57
+ {"id": "webhooks", "name": "Webhooks", "status": "live", "apps": ["web"], "access": {"plan": "pro"}},
58
+ {"id": "sms", "name": "Text a link", "status": "beta", "apps": ["web"], "platforms": {"web": "beta"}},
59
+ {"id": "courses", "name": "Courses", "status": "planned", "apps": ["web"]}]',
60
+ '[{"key": "sms.release", "feature": "sms", "kind": "release", "default": false, "scopes": ["platform", "tenant"], "expires": "2027-01-31"}]');
61
+ grant select on pg_temp.registry to service_role, authenticated;
62
+
63
+ -- Shape and access ------------------------------------------------------------------------------
64
+ select has_table('public', 'features', 'features exists');
65
+ select has_table('public', 'feature_flags', 'feature_flags exists');
66
+ select has_table('public', 'feature_entitlements', 'feature_entitlements exists');
67
+ select has_table('public', 'tenant_flag_values', 'tenant_flag_values exists');
68
+ select ok(
69
+ (select bool_and(relrowsecurity) from pg_class where oid in ('public.features'::regclass, 'public.feature_flags'::regclass,
70
+ 'public.feature_entitlements'::regclass, 'public.tenant_flag_values'::regclass, 'private.feature_registry_state'::regclass)),
71
+ 'RLS is on for every table');
72
+ select ok(not has_table_privilege('authenticated', 'public.feature_flags', 'select'), 'signed-in people can''t read flag rows');
73
+ select ok(not has_table_privilege('authenticated', 'public.feature_entitlements', 'select,insert,update,delete'), '... nor entitlements');
74
+ select ok(not has_table_privilege('authenticated', 'public.tenant_flag_values', 'select,insert,update,delete'), '... nor flag values');
75
+ select ok(not has_table_privilege('authenticated', 'public.features', 'insert,update,delete'), 'nobody signed in writes features');
76
+ select ok(not has_function_privilege('authenticated', 'public.sync_feature_registry(bigint, text, jsonb, jsonb, boolean)', 'execute'), 'only the service role syncs');
77
+ select ok(not has_function_privilege('anon', 'public.feature_on(uuid, text)', 'execute'), 'anon can''t ask the gate');
78
+ select ok(not has_function_privilege('anon', 'public.feature_gate_state(uuid)', 'execute'), '... nor read gate state');
79
+
80
+ -- Syncing ---------------------------------------------------------------------------------------
81
+ select pg_temp.as_service();
82
+ select is(public.sync_feature_registry(100, 'h1', (select features from pg_temp.registry), (select flags from pg_temp.registry)), true, 'the service role syncs');
83
+ select is(public.sync_feature_registry(100, 'h1', (select features from pg_temp.registry), (select flags from pg_temp.registry)), false, 'the same hash is a no-op');
84
+ select is(public.sync_feature_registry(50, 'old', (select features from pg_temp.registry), '[]'), false, 'an older version is refused');
85
+ select is((select count(*)::int from public.feature_flags), 1, '... and leaves the newer flags');
86
+ select is((select access_plan from public.features where id = 'webhooks'), 'pro', 'a paid feature keeps its plan');
87
+ select is((select platforms ->> 'web' from public.features where id = 'sms'), 'beta', 'platform statuses are kept');
88
+ select throws_ok($$select public.sync_feature_registry(null, 'x', '[]', '[]')$$, '22023', null, 'a sync needs a version');
89
+
90
+ -- The gate in SQL --------------------------------------------------------------------------------
91
+ select is(public.feature_on(pg_temp.tenant(1), 'forms'), true, 'a live feature is on');
92
+ select is(public.feature_on(pg_temp.tenant(1), 'webhooks'), false, 'a paid feature is off without an entitlement');
93
+ insert into public.feature_entitlements (tenant_id, feature_id, source, active) values (pg_temp.tenant(1), 'webhooks', 'manual', true);
94
+ select is(public.feature_on(pg_temp.tenant(1), 'webhooks'), true, '... and on with one');
95
+ insert into public.feature_entitlements (tenant_id, feature_id, source, active, ends_at) values (pg_temp.tenant(2), 'webhooks', 'trial', true, now() - interval '1 day');
96
+ select is(public.feature_on(pg_temp.tenant(2), 'webhooks'), false, 'an ended entitlement doesn''t count');
97
+ insert into public.feature_entitlements (tenant_id, feature_id, source, active) values (pg_temp.tenant(2), 'webhooks', 'manual', false);
98
+ select is(public.feature_on(pg_temp.tenant(2), 'webhooks'), false, '... nor an inactive one');
99
+ insert into public.feature_entitlements (tenant_id, feature_id, source, active) values (pg_temp.tenant(2), 'not-synced-yet', 'stripe', true);
100
+ select pass('billing can grant a feature before the deploy that adds it syncs');
101
+ select is(public.feature_on(pg_temp.tenant(1), 'courses') or public.feature_on(pg_temp.tenant(1), 'nope'), false, 'planned and unknown features are off');
102
+ select is(public.feature_on(pg_temp.tenant(1), 'sms'), true, 'flags are not the database''s business');
103
+
104
+ -- Runtime state for the snapshot -------------------------------------------------------------------
105
+ insert into public.tenant_flag_values (tenant_id, flag_key, value) values (pg_temp.tenant(1), 'sms.release', 'true');
106
+ select pg_temp.as_owner();
107
+ insert into public.tenant_features (tenant_id, feature_id, enabled, reason) values (pg_temp.tenant(1), 'forms', false, 'Not yet');
108
+ select is(public.feature_on(pg_temp.tenant(1), 'forms'), true, 'a tenant switch hides, it doesn''t block rows');
109
+
110
+ select pg_temp.sign_in('b2');
111
+ select is(public.feature_gate_state(pg_temp.tenant(1)),
112
+ '{"off": ["forms"], "entitled": ["webhooks"], "flags": {"sms.release": true}}'::jsonb,
113
+ 'a member reads the tenant''s switches, entitlements and flag values');
114
+ select is(public.feature_on(pg_temp.tenant(1), 'webhooks'), true, 'a member asks the gate for their tenant');
115
+ select is(public.feature_on(pg_temp.tenant(2), 'forms'), false, 'and gets false for another tenant');
116
+ select throws_ok($$select public.feature_gate_state(pg_temp.tenant(2))$$, '42501', null, 'another tenant''s state is refused');
117
+ select is((select array_agg(id order by id) from public.features), array['forms', 'sms', 'webhooks'], 'signed-in people read shipped features only');
118
+ select throws_ok($$select record from public.features$$, '42501', null, '... and not the full registry record');
119
+ select is(array(select public.feature_entitled_tenants('webhooks')), array[pg_temp.tenant(1)], 'a member sees their own tenant''s entitlement');
120
+ select is((select public.feature_shipped('forms')) and not (select public.feature_shipped('courses')), true, 'feature_shipped answers once per statement');
121
+ select throws_ok($$select * from public.feature_entitlements$$, '42501', null, 'but not the entitlements table');
122
+
123
+ select pg_temp.sign_in('c3');
124
+ select is(public.feature_gate_state(pg_temp.tenant(2)), '{"off": [], "entitled": ["not-synced-yet"], "flags": {}}'::jsonb, 'another tenant sees only its own state');
125
+ select is(array(select public.feature_entitled_tenants('webhooks')), '{}'::uuid[], 'and none of another tenant''s entitlements');
126
+ select set_config('request.jwt.claims', json_build_object('sub', pg_temp.person('c3'), 'role', 'authenticated', 'is_anonymous', true)::text, true);
127
+ select is((select count(*)::int from public.features), 0, 'an anonymous sign-in reads no features');
128
+
129
+ -- An authenticated request without a person is refused, never mistaken for server code.
130
+ select set_config('request.jwt.claims', '{"role": "authenticated"}', true);
131
+ select set_config('request.jwt.claim.sub', '', true);
132
+ select throws_ok($$select public.feature_gate_state(pg_temp.tenant(1))$$, '42501', null, 'no sub: gate state is refused');
133
+ select is(public.feature_on(pg_temp.tenant(1), 'forms'), false, 'no sub: the gate says no');
134
+ select is(array(select public.feature_entitled_tenants('webhooks')), '{}'::uuid[], 'no sub: no entitled tenants');
135
+
136
+ -- A platform value is a kill switch for every tenant, over the tenant's own value.
137
+ select pg_temp.as_service();
138
+ update public.feature_flags set platform_value = 'false' where key = 'sms.release';
139
+ select pg_temp.sign_in('b2');
140
+ select is(public.feature_gate_state(pg_temp.tenant(1)) -> 'flags', '{"sms.release": false}'::jsonb, 'a platform value overrides the tenant''s');
141
+ select pg_temp.as_service();
142
+ update public.feature_flags set platform_value = null where key = 'sms.release';
143
+ select is(public.feature_gate_state(pg_temp.tenant(1)) -> 'flags', '{"sms.release": true}'::jsonb, 'without it the tenant value applies (server code reads any tenant)');
144
+
145
+ -- A registry without courses and without the flag --------------------------------------------------
146
+ select pg_temp.as_service();
147
+ select is(public.sync_feature_registry(200, 'h2',
148
+ (select jsonb_agg(f) from pg_temp.registry, jsonb_array_elements(features) f where f ->> 'id' <> 'courses'), '[]'), true, 'a changed registry syncs');
149
+ select is((select in_registry from public.features where id = 'courses'), false, 'a feature gone from the registry stays, marked gone');
150
+ select is((select in_registry from public.feature_flags where key = 'sms.release'), false, 'a flag gone from the registry stays, marked gone');
151
+ select is((select count(*)::int from public.tenant_flag_values), 1, '... and keeps its tenant values');
152
+ select pg_temp.sign_in('b2');
153
+ select is(public.feature_gate_state(pg_temp.tenant(1)) -> 'flags', '{}'::jsonb, 'but a gone flag''s value is not handed out');
154
+ select pg_temp.as_service();
155
+ select is((select version from public.feature_registry_synced()), 200::bigint, 'the last sync is recorded');
156
+
157
+ -- Retired: off even with an entitlement.
158
+ select is(public.sync_feature_registry(300, 'h3',
159
+ '[{"id": "webhooks", "name": "Webhooks", "status": "retired", "apps": ["web"], "access": {"plan": "pro"}},
160
+ {"id": "legacy", "name": "Old export", "status": "deprecated", "apps": ["web"]},
161
+ {"id": "drafts", "name": "Drafts", "status": "building", "apps": ["web"]},
162
+ {"id": "free", "name": "Free", "status": "live", "apps": ["web"], "access": {"plan": " "}}]', '[]'), true, 'webhooks retires');
163
+ select is(public.feature_on(pg_temp.tenant(1), 'webhooks'), false, 'a retired feature is off whatever the entitlement');
164
+ select is(public.feature_on(pg_temp.tenant(1), 'forms'), false, 'a feature missing from the registry is off');
165
+ select is(public.feature_on(pg_temp.tenant(1), 'legacy'), true, 'a deprecated feature still works');
166
+ select is(public.feature_on(pg_temp.tenant(1), 'drafts'), false, 'a building feature is not shipped');
167
+ select is(public.feature_on(pg_temp.tenant(1), 'free'), true, 'a blank plan is no plan');
168
+
169
+ -- Guards against a broken registry -----------------------------------------------------------------
170
+ select throws_ok($$select public.sync_feature_registry(400, 'empty', '[]', '[]')$$, '22023', null, 'an empty registry is refused');
171
+ select throws_ok($$select public.sync_feature_registry(400, 'dup', '[{"id": "a", "name": "A", "status": "live"}, {"id": "a", "name": "A", "status": "live"}]', '[]')$$,
172
+ '22023', null, 'duplicate ids are refused');
173
+ select throws_ok($$select public.sync_feature_registry(400, 'shrink', '[{"id": "legacy", "name": "Old export", "status": "deprecated"}]', '[]')$$,
174
+ '22023', null, 'a registry that drops most features is refused');
175
+ select is((select count(*)::int from public.features where in_registry), 4, '... and changes nothing');
176
+ select is(public.sync_feature_registry(400, 'shrink', '[{"id": "legacy", "name": "Old export", "status": "deprecated"}]', '[]', true), true,
177
+ 'unless the call allows the shrink');
178
+
179
+ select * from finish();
180
+ rollback;
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-supabase",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
- "description": "Supabase for Genesis apps on web and React Native: a client with PKCE and safe defaults, Keychain session storage that survives interrupted writes, refresh only while the app is in front, native Sign in with Apple and Google, OAuth redirects, in-app account deletion, per-tenant feature switches (tenant_features), a background-job queue with schedules (genesis_jobs), and a result helper. Part of the Genesis framework.",
7
+ "description": "Supabase for Genesis apps on web and React Native: a client with PKCE and safe defaults, Keychain session storage that survives interrupted writes, refresh only while the app is in front, native Sign in with Apple and Google, OAuth redirects, in-app account deletion, per-tenant feature switches (tenant_features), a background-job queue with schedules (genesis_jobs), the feature registry in the database for the feature gate (features, entitlements, flag values, feature_on), and a result helper. Part of the Genesis framework.",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/marktiderman/genesis.git",
@@ -45,7 +45,7 @@
45
45
  "README.md"
46
46
  ],
47
47
  "dependencies": {
48
- "@marktiderman/genesis-features": "^0.4.0"
48
+ "@marktiderman/genesis-features": "^0.5.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@supabase/supabase-js": "^2.118.0",
@@ -158,6 +158,33 @@
158
158
  "Add one job route with createJobsHandler from @marktiderman/genesis-supabase/jobs, and set GENESIS_JOBS_SECRET on the server.",
159
159
  "For schedules: enable pg_cron and pg_net, add the Vault secrets genesis_jobs_url (the route's base URL) and genesis_jobs_secret (the same secret), then call genesis_schedule_job(name, cron, job) in a migration."
160
160
  ]
161
+ },
162
+ "feature-mirror": {
163
+ "feature": {
164
+ "name": "Registry in the app's database",
165
+ "summary": "The feature registry mirrored into the database on deploy, entitlements, per-tenant flag values and SQL feature_on(), for the feature gate.",
166
+ "keywords": [
167
+ "feature gate",
168
+ "entitlements",
169
+ "flags",
170
+ "feature_on"
171
+ ],
172
+ "audience": [
173
+ "developer"
174
+ ]
175
+ },
176
+ "requires": [
177
+ "tenant-features"
178
+ ],
179
+ "migrations": [
180
+ {
181
+ "file": "migrations/0008_genesis_feature_registry.sql",
182
+ "test": "migrations/tests/0008_genesis_feature_registry.test.sql"
183
+ }
184
+ ],
185
+ "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."
187
+ ]
161
188
  }
162
189
  }
163
190
  },
@@ -1,45 +0,0 @@
1
- import { defineBlock } from '@marktiderman/genesis-features/blocks';
2
-
3
- // src/blocks.ts
4
- var PACKAGE = "@marktiderman/genesis-supabase";
5
- var accountBlock = defineBlock({
6
- id: "account",
7
- platforms: ["web", "native"],
8
- contributes: {
9
- migrations: [
10
- { package: PACKAGE, file: "migrations/0001_genesis_account_deletion.sql", test: "migrations/tests/0001_genesis_account_deletion.test.sql" },
11
- // With Sign in with Apple, with the genesis-apple-revoke function beside it.
12
- { package: PACKAGE, file: "migrations/0003_genesis_apple_token_revocation.sql", test: "migrations/tests/0003_genesis_apple_token_revocation.test.sql" }
13
- ],
14
- privacy: {
15
- collects: [
16
- { type: "email address", purposes: ["app functionality"], linked: true, tracking: false },
17
- { type: "user id", purposes: ["app functionality"], linked: true, tracking: false },
18
- { type: "name", purposes: ["app functionality"], linked: true, tracking: false }
19
- ],
20
- notes: [
21
- "People delete their account from inside the app; their login and the rows that cascade from it go with it.",
22
- "With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted."
23
- ]
24
- }
25
- }
26
- });
27
- var tenantFeaturesBlock = defineBlock({
28
- id: "tenant-features",
29
- contributes: {
30
- migrations: [{ package: PACKAGE, file: "migrations/0004_genesis_tenant_features.sql", test: "migrations/tests/0004_genesis_tenant_features.test.sql" }],
31
- privacy: { notes: ["Keeps who changed a tenant's switches; a deleted person's changes stay, without the person."] }
32
- }
33
- });
34
- var jobsBlock = defineBlock({
35
- id: "jobs",
36
- platforms: ["web"],
37
- contributes: {
38
- migrations: [{ package: PACKAGE, file: "migrations/0007_genesis_jobs.sql", test: "migrations/tests/0007_genesis_jobs.test.sql" }],
39
- privacy: { notes: ["Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days."] }
40
- }
41
- });
42
-
43
- export { accountBlock, jobsBlock, tenantFeaturesBlock };
44
- //# sourceMappingURL=chunk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IACtJ,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,6FAA6F,CAAA;AAAE;AAEtH,CAAC;AAQM,IAAM,YAAY,WAAA,CAAY;AAAA,EACnC,EAAA,EAAI,MAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAK,CAAA;AAAA,EACjB,WAAA,EAAa;AAAA,IACX,UAAA,EAAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,kCAAA,EAAoC,IAAA,EAAM,6CAAA,EAA+C,CAAA;AAAA,IAChI,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC","file":"chunk-A3H5CTYT.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 { package: PACKAGE, file: \"migrations/0001_genesis_account_deletion.sql\", test: \"migrations/tests/0001_genesis_account_deletion.test.sql\" },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n { package: PACKAGE, file: \"migrations/0003_genesis_apple_token_revocation.sql\", test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\" },\n ],\n privacy: {\n collects: [\n { type: \"email address\", purposes: [\"app functionality\"], linked: true, tracking: false },\n { type: \"user id\", purposes: [\"app functionality\"], linked: true, tracking: false },\n { type: \"name\", purposes: [\"app functionality\"], linked: true, tracking: false },\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: [{ package: PACKAGE, file: \"migrations/0004_genesis_tenant_features.sql\", test: \"migrations/tests/0004_genesis_tenant_features.test.sql\" }],\n privacy: { notes: [\"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\"] },\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"]}