@marktiderman/genesis-supabase 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/blocks.d.ts +1 -10
- package/dist/blocks.js +1 -1
- package/dist/{chunk-DYHH2G4A.js → chunk-FWQGZT4S.js} +10 -19
- package/dist/chunk-FWQGZT4S.js.map +1 -0
- package/dist/{index-D73YuwEY.d.ts → index-CaYX9z8D.d.ts} +16 -6
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/native.d.ts +2 -2
- package/migrations/0016_genesis_viewer_people.sql +70 -0
- package/migrations/0017_genesis_person_entitlements.sql +284 -0
- package/migrations/tests/0016_genesis_viewer_people.test.sql +77 -0
- package/migrations/tests/0017_genesis_person_entitlements.test.sql +96 -0
- package/package.json +10 -37
- package/dist/chunk-DYHH2G4A.js.map +0 -1
- package/migrations/0009_genesis_owner_access.sql +0 -89
- package/migrations/tests/0009_genesis_owner_access.test.sql +0 -70
package/README.md
CHANGED
|
@@ -604,6 +604,15 @@ way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
|
|
|
604
604
|
marked `in_registry = false`; its tenant values stay, and (0014) its platform value is cleared.
|
|
605
605
|
- **Paid access.** `feature_entitlements` (tenant, feature, source, `active`, optional `ends_at`). Your billing
|
|
606
606
|
webhook writes it with the service key.
|
|
607
|
+
- **Paid access for one person (0016, 0017).** `feature_person_entitlements` holds grants to the app's person
|
|
608
|
+
record, not a login: a membership, a class pack or a coaching package bought before sign-up counts once the
|
|
609
|
+
person signs in. Server code writes them with `grant_person_entitlement(tenant, person, feature, source,
|
|
610
|
+
source_ref, starts_at, ends_at)` (idempotent on `source_ref`, so a replayed webhook changes nothing) and
|
|
611
|
+
`revoke_person_entitlement(...)`. Which person records a login is comes from your
|
|
612
|
+
`private.genesis_viewer_people(viewer)` hook, read through the fail-closed `private.genesis_viewer_person_ids()`
|
|
613
|
+
(0016, shared with every block that gives something to a person record). `feature_on`,
|
|
614
|
+
`feature_entitled_tenants` and `feature_gate_state(tenant)` count the signed-in person's own grants; server
|
|
615
|
+
code gets the tenant's answer, or names a person with `feature_gate_state(tenant, person)`.
|
|
607
616
|
- **Flag values.** `tenant_flag_values` overrides a flag's default for one tenant (service key).
|
|
608
617
|
- **The gate in SQL.** `feature_on(tenant, feature)` is true for a shipped feature that, when paid, has an
|
|
609
618
|
active entitlement; a signed-in caller outside the tenant gets false. It runs once per row, so in policies
|
|
@@ -630,7 +639,8 @@ import registry from "../features.json";
|
|
|
630
639
|
// When a production deployment starts serving (never from a preview):
|
|
631
640
|
if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });
|
|
632
641
|
|
|
633
|
-
const state = await featureGateState(supabase, teamId); // per session
|
|
642
|
+
const state = await featureGateState(supabase, teamId); // per session; includes the person's own grants
|
|
643
|
+
// On the server, for one person: await featureGateState(admin, teamId, { personId })
|
|
634
644
|
const snapshot = gateSnapshot({ features, flags }, { platform: "web", ...state }, { version: BUILD_TIME });
|
|
635
645
|
```
|
|
636
646
|
|
package/dist/blocks.d.ts
CHANGED
|
@@ -38,14 +38,5 @@ declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs",
|
|
|
38
38
|
* @stability Beta
|
|
39
39
|
*/
|
|
40
40
|
declare const webHandoffBlock: _marktiderman_genesis_features_blocks.BlockDef<"web-handoff", never>;
|
|
41
|
-
/**
|
|
42
|
-
* The owner-access block: the contract every Genesis block with owned rows
|
|
43
|
-
* calls in its policies. Two fail-closed wrappers over the app's hooks
|
|
44
|
-
* (`genesis_owner_can`, `genesis_readable_owners`): a missing or broken hook
|
|
45
|
-
* means no.
|
|
46
|
-
*
|
|
47
|
-
* @stability Experimental
|
|
48
|
-
*/
|
|
49
|
-
declare const ownerAccessBlock: _marktiderman_genesis_features_blocks.BlockDef<"owner-access", never>;
|
|
50
41
|
|
|
51
|
-
export { accountBlock, featureMirrorBlock, jobsBlock,
|
|
42
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
|
package/dist/blocks.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { accountBlock, featureMirrorBlock, jobsBlock,
|
|
1
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock } from './chunk-FWQGZT4S.js';
|
|
2
2
|
//# sourceMappingURL=blocks.js.map
|
|
3
3
|
//# sourceMappingURL=blocks.js.map
|
|
@@ -78,11 +78,17 @@ var featureMirrorBlock = defineBlock({
|
|
|
78
78
|
package: PACKAGE,
|
|
79
79
|
file: "migrations/0014_genesis_feature_registry_hardening.sql",
|
|
80
80
|
test: "migrations/tests/0014_genesis_feature_registry_hardening.test.sql"
|
|
81
|
+
},
|
|
82
|
+
{ package: PACKAGE, file: "migrations/0016_genesis_viewer_people.sql", test: "migrations/tests/0016_genesis_viewer_people.test.sql" },
|
|
83
|
+
{
|
|
84
|
+
package: PACKAGE,
|
|
85
|
+
file: "migrations/0017_genesis_person_entitlements.sql",
|
|
86
|
+
test: "migrations/tests/0017_genesis_person_entitlements.test.sql"
|
|
81
87
|
}
|
|
82
88
|
],
|
|
83
89
|
privacy: {
|
|
84
90
|
notes: [
|
|
85
|
-
"Stores which tenants hold which paid features and flag values
|
|
91
|
+
"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values."
|
|
86
92
|
]
|
|
87
93
|
}
|
|
88
94
|
}
|
|
@@ -109,22 +115,7 @@ var webHandoffBlock = defineBlock({
|
|
|
109
115
|
}
|
|
110
116
|
}
|
|
111
117
|
});
|
|
112
|
-
var ownerAccessBlock = defineBlock({
|
|
113
|
-
id: "owner-access",
|
|
114
|
-
requires: ["tenant-features"],
|
|
115
|
-
platforms: ["web", "native"],
|
|
116
|
-
contributes: {
|
|
117
|
-
migrations: [
|
|
118
|
-
{
|
|
119
|
-
package: PACKAGE,
|
|
120
|
-
file: "migrations/0009_genesis_owner_access.sql",
|
|
121
|
-
test: "migrations/tests/0009_genesis_owner_access.test.sql"
|
|
122
|
-
}
|
|
123
|
-
],
|
|
124
|
-
privacy: { notes: ["Stores nothing; it only asks the app's hooks who may read and write."] }
|
|
125
|
-
}
|
|
126
|
-
});
|
|
127
118
|
|
|
128
|
-
export { accountBlock, featureMirrorBlock, jobsBlock,
|
|
129
|
-
//# sourceMappingURL=chunk-
|
|
130
|
-
//# sourceMappingURL=chunk-
|
|
119
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
|
|
120
|
+
//# sourceMappingURL=chunk-FWQGZT4S.js.map
|
|
121
|
+
//# sourceMappingURL=chunk-FWQGZT4S.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,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,SAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAA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ACL;AAAA;AACF;AACF;AAEJ,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;AASM,IAAM,kBAAkB,WAAA,CAAY;AAAA,EACzC,EAAA,EAAI,aAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,yCAAA,EAA2C,MAAM,oDAAA;AAAqD,KAClI;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC","file":"chunk-FWQGZT4S.js","sourcesContent":["/**\n * The blocks this package carries the server half of, as `defineBlock`\n * declarations: what each needs in the database, and what it means for the\n * stores' privacy forms. The functions themselves (`deleteMyAccount`,\n * `tenantFeatures`, …) don't change.\n */\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\n\nconst PACKAGE = \"@marktiderman/genesis-supabase\";\n\n/**\n * The account block: sign-in, profile and in-app account deletion. Its\n * screens are the app's (or genesis-ui-native's `AuthScreen`); this names its\n * migrations and its data.\n *\n * @stability Beta\n */\nexport const accountBlock = defineBlock({\n id: \"account\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0001_genesis_account_deletion.sql\",\n test: \"migrations/tests/0001_genesis_account_deletion.test.sql\",\n },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n {\n package: PACKAGE,\n file: \"migrations/0003_genesis_apple_token_revocation.sql\",\n test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\",\n },\n ],\n privacy: {\n collects: [\n {\n type: \"email address\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"user id\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"name\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n ],\n notes: [\n \"People delete their account from inside the app; their login and the rows that cascade from it go with it.\",\n \"With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted.\",\n ],\n },\n },\n});\n\n/**\n * The tenant features block: per-tenant on/off switches for shipped\n * features, set by the tenant's admins with a reason.\n *\n * @stability Beta\n */\nexport const tenantFeaturesBlock = defineBlock({\n id: \"tenant-features\",\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0004_genesis_tenant_features.sql\",\n test: \"migrations/tests/0004_genesis_tenant_features.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\",\n ],\n },\n },\n});\n\n/**\n * The feature registry block: the registry mirrored into the app's database\n * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,\n * for the feature gate. Needs the tenant features block.\n *\n * @stability Beta\n */\nexport const featureMirrorBlock = defineBlock({\n id: \"feature-mirror\",\n requires: [\"tenant-features\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0008_genesis_feature_registry.sql\",\n test: \"migrations/tests/0008_genesis_feature_registry.test.sql\",\n },\n {\n package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n { package: PACKAGE, file: \"migrations/0016_genesis_viewer_people.sql\", test: \"migrations/tests/0016_genesis_viewer_people.test.sql\" },\n {\n package: PACKAGE,\n file: \"migrations/0017_genesis_person_entitlements.sql\",\n test: \"migrations/tests/0017_genesis_person_entitlements.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n\n/**\n * The web handoff block: continue on the web, already signed in. The routes are\n * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native\n * app calls `openOnWeb` from genesis-native.\n *\n * @stability Beta\n */\nexport const webHandoffBlock = defineBlock({\n id: \"web-handoff\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0015_genesis_web_handoff.sql\", test: \"migrations/tests/0015_genesis_web_handoff.test.sql\" },\n ],\n privacy: {\n notes: [\n \"Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token.\",\n ],\n },\n },\n});\n\n"]}
|
|
@@ -212,20 +212,30 @@ type FlagStateValue = boolean | string | number | {
|
|
|
212
212
|
interface FeatureGateState {
|
|
213
213
|
/** Feature ids the tenant switched off. */
|
|
214
214
|
off: string[];
|
|
215
|
-
/** Feature ids the tenant
|
|
215
|
+
/** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */
|
|
216
216
|
entitlements: string[];
|
|
217
217
|
/** Flag values for the tenant (platform values applied), by flag name. */
|
|
218
218
|
flags: Record<string, FlagStateValue>;
|
|
219
219
|
}
|
|
220
|
+
/** @stability Beta */
|
|
221
|
+
interface FeatureGateStateOptions {
|
|
222
|
+
/**
|
|
223
|
+
* With the service key only: add this person's own entitlements (the app's person id, not a
|
|
224
|
+
* login), for a snapshot built on the server. A signed-in person's client gets their own
|
|
225
|
+
* without it, and is refused (`42501`) with it.
|
|
226
|
+
*/
|
|
227
|
+
personId?: string;
|
|
228
|
+
}
|
|
220
229
|
/**
|
|
221
230
|
* A tenant's switches, entitlements and flag values: `feature_gate_state`.
|
|
222
|
-
* Works with a signed-in person's client (for tenants they belong to
|
|
223
|
-
*
|
|
224
|
-
* refusal is never mistaken
|
|
231
|
+
* Works with a signed-in person's client (for tenants they belong to; their own
|
|
232
|
+
* person entitlements are included) or the service key. Throws a
|
|
233
|
+
* `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken
|
|
234
|
+
* for "nothing set".
|
|
225
235
|
*
|
|
226
236
|
* @stability Beta
|
|
227
237
|
*/
|
|
228
|
-
declare function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState>;
|
|
238
|
+
declare function featureGateState(client: FeatureRegistryClient, tenantId: string, options?: FeatureGateStateOptions): Promise<FeatureGateState>;
|
|
229
239
|
/** `features.json` as `genesis features build` writes it. @stability Beta */
|
|
230
240
|
interface FeatureRegistryDocument {
|
|
231
241
|
features: readonly ({
|
|
@@ -389,4 +399,4 @@ interface DeleteMyAccountOptions {
|
|
|
389
399
|
*/
|
|
390
400
|
declare function deleteMyAccount(client: DeleteAccountClient, options?: DeleteMyAccountOptions): Promise<void>;
|
|
391
401
|
|
|
392
|
-
export { APPLE_REVOKE_FUNCTION as A,
|
|
402
|
+
export { APPLE_REVOKE_FUNCTION as A, tenantFeatureHistory as B, tenantFeatureSettings as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, tenantFeatures as H, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type FeatureGateStateOptions as d, type FeatureRegistryClient as e, type FeatureRegistryDocument as f, type FlagStateValue as g, hasPkceCrypto as h, installWebCrypto as i, type FunctionsClient as j, type SetTenantFeatureInput as k, type StoreAppleTokenOptions as l, type StoreAppleTokenResult as m, SupabaseQueryError as n, type SyncFeatureRegistryOptions as o, type TenantFeatureSetting as p, type TenantFeatures as q, type TenantFeaturesClient as r, createGenesisSupabase as s, deleteMyAccount as t, featureGateState as u, must as v, requestAppleRevocation as w, setTenantFeature as x, storeAppleToken as y, syncFeatureRegistry as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import '@supabase/supabase-js';
|
|
2
|
-
export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as
|
|
3
|
-
export { accountBlock, featureMirrorBlock, jobsBlock,
|
|
2
|
+
export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureGateStateOptions, e as FeatureRegistryClient, f as FeatureRegistryDocument, g as FlagStateValue, j as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, k as SetTenantFeatureInput, l as StoreAppleTokenOptions, m as StoreAppleTokenResult, n as SupabaseQueryError, o as SyncFeatureRegistryOptions, T as TenantFeatureChange, p as TenantFeatureSetting, q as TenantFeatures, r as TenantFeaturesClient, s as createGenesisSupabase, t as deleteMyAccount, u as featureGateState, v as must, w as requestAppleRevocation, x as setTenantFeature, y as storeAppleToken, z as syncFeatureRegistry, B as tenantFeatureHistory, C as tenantFeatureSettings, H as tenantFeatures } from './index-CaYX9z8D.js';
|
|
3
|
+
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, featureMirrorBlock, jobsBlock,
|
|
2
|
+
export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-FWQGZT4S.js';
|
|
3
3
|
import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
|
|
4
4
|
|
|
5
5
|
// src/apple-tokens.ts
|
|
@@ -50,8 +50,9 @@ async function tenantFeatureHistory(client, tenantId, options = {}) {
|
|
|
50
50
|
|
|
51
51
|
// src/feature-registry.ts
|
|
52
52
|
var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
53
|
-
async function featureGateState(client, tenantId) {
|
|
54
|
-
const
|
|
53
|
+
async function featureGateState(client, tenantId, options = {}) {
|
|
54
|
+
const args = options.personId === void 0 ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };
|
|
55
|
+
const data = must(await client.rpc("feature_gate_state", args));
|
|
55
56
|
if (!data || typeof data !== "object" || Array.isArray(data)) throw new TypeError("feature_gate_state returned no state");
|
|
56
57
|
const { off, entitled, flags } = data;
|
|
57
58
|
if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== "object" || Array.isArray(flags)) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,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,S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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 * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
|
|
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,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AAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
|
package/dist/native.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as SessionStorage } from './index-
|
|
2
|
-
export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-
|
|
1
|
+
import { S as SessionStorage } from './index-CaYX9z8D.js';
|
|
2
|
+
export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-CaYX9z8D.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,70 @@
|
|
|
1
|
+
-- Genesis viewer people: private.genesis_viewer_person_ids()
|
|
2
|
+
--
|
|
3
|
+
-- The people records the signed-in person is, one per tenant. A person record is the app's, not a
|
|
4
|
+
-- login: a gym member who bought a pack, or a coaching client invited before they signed up, has
|
|
5
|
+
-- one before they have a login, and keeps it once they do. Genesis blocks that give something to a
|
|
6
|
+
-- person record (genesis-work's attendees, the feature registry's person entitlements in 0017) ask
|
|
7
|
+
-- through this one wrapper, so every block resolves "who is the viewer here" the same way.
|
|
8
|
+
--
|
|
9
|
+
-- Your app answers through one hook. Genesis never defines it:
|
|
10
|
+
--
|
|
11
|
+
-- private.genesis_viewer_people(viewer uuid) returns table (tenant_id uuid, person_id uuid)
|
|
12
|
+
-- Every person record the login is, across tenants: the personal record (whose tenant is its
|
|
13
|
+
-- own id, if your app has one) and one row per organization the login belongs to.
|
|
14
|
+
--
|
|
15
|
+
-- It runs with your migration's (the owner's) rights, so it reads your people tables whatever their
|
|
16
|
+
-- row security. For example:
|
|
17
|
+
--
|
|
18
|
+
-- create function private.genesis_viewer_people(viewer uuid)
|
|
19
|
+
-- returns table (tenant_id uuid, person_id uuid) language sql stable set search_path = '' as $$
|
|
20
|
+
-- select p.organization_id, p.id from public.people p where p.user_id = viewer
|
|
21
|
+
-- $$;
|
|
22
|
+
-- revoke execute on function private.genesis_viewer_people(uuid) from public, anon, authenticated;
|
|
23
|
+
--
|
|
24
|
+
-- This file ships the wrapper that blocks call in their policies and functions. It fails closed: a
|
|
25
|
+
-- missing hook, a hook that errors or returns the wrong type, or no signed-in person gives an empty
|
|
26
|
+
-- set. Duplicates and rows with a null id are dropped.
|
|
27
|
+
--
|
|
28
|
+
-- private.genesis_viewer_person_ids() returns table (tenant_id uuid, person_id uuid)
|
|
29
|
+
-- The signed-in person's records, from genesis_viewer_people(auth.uid()).
|
|
30
|
+
--
|
|
31
|
+
-- It is stable, security definer with search_path ''. In row security, compare against it in an
|
|
32
|
+
-- uncorrelated subquery, so Postgres calls it once per statement rather than once per row:
|
|
33
|
+
--
|
|
34
|
+
-- using ((tenant_id, person_id) in (select v.tenant_id, v.person_id from private.genesis_viewer_person_ids() v))
|
|
35
|
+
--
|
|
36
|
+
-- Row security runs as the caller, so authenticated may execute it; it only ever answers for
|
|
37
|
+
-- auth.uid(). anon and public may not.
|
|
38
|
+
--
|
|
39
|
+
-- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
|
|
40
|
+
-- (`genesis migrate` does it). Never edit it once applied; change it with a new migration.
|
|
41
|
+
--
|
|
42
|
+
-- Verify: the pgTAP test beside this file (`tests/0016_genesis_viewer_people.test.sql`).
|
|
43
|
+
|
|
44
|
+
create schema if not exists private;
|
|
45
|
+
|
|
46
|
+
create or replace function private.genesis_viewer_person_ids()
|
|
47
|
+
returns table (tenant_id uuid, person_id uuid)
|
|
48
|
+
language plpgsql
|
|
49
|
+
stable
|
|
50
|
+
security definer
|
|
51
|
+
set search_path = ''
|
|
52
|
+
as $$
|
|
53
|
+
begin
|
|
54
|
+
if auth.uid() is null or to_regprocedure('private.genesis_viewer_people(uuid)') is null then
|
|
55
|
+
return;
|
|
56
|
+
end if;
|
|
57
|
+
return query execute
|
|
58
|
+
'select distinct r.tenant_id::uuid, r.person_id::uuid from private.genesis_viewer_people($1) r
|
|
59
|
+
where r.tenant_id is not null and r.person_id is not null'
|
|
60
|
+
using auth.uid();
|
|
61
|
+
exception when others then
|
|
62
|
+
return;
|
|
63
|
+
end;
|
|
64
|
+
$$;
|
|
65
|
+
|
|
66
|
+
comment on function private.genesis_viewer_person_ids() is
|
|
67
|
+
'The signed-in person''s person records, one per tenant, from the app''s private.genesis_viewer_people(viewer) hook. Empty when there is no hook or nobody is signed in. Genesis viewer people.';
|
|
68
|
+
|
|
69
|
+
revoke execute on function private.genesis_viewer_person_ids() from public, anon, authenticated;
|
|
70
|
+
grant execute on function private.genesis_viewer_person_ids() to authenticated;
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
-- Genesis feature registry: entitlements held by one person (0008 and 0014, extended here).
|
|
2
|
+
--
|
|
3
|
+
-- 0008's feature_entitlements says which tenant may use a paid feature. A membership, a class pack,
|
|
4
|
+
-- a course or a coaching package is bought by one person, so the gate also needs grants that belong
|
|
5
|
+
-- to a person record. They live in their own table, beside the tenant's, and the gate reads both:
|
|
6
|
+
--
|
|
7
|
+
-- public.feature_person_entitlements
|
|
8
|
+
-- Which person may use which paid feature in a tenant, by source (a billing webhook, a manual
|
|
9
|
+
-- grant) and source_ref (the subscription item or purchase it came from, so a webhook can be
|
|
10
|
+
-- replayed), optionally from starts_at and until ends_at. person_id is the app's person record,
|
|
11
|
+
-- not a login, so a grant bought before sign-up counts once the person signs in. Written by
|
|
12
|
+
-- the service role only, through grant_person_entitlement and revoke_person_entitlement; a
|
|
13
|
+
-- signed-in person reads their own.
|
|
14
|
+
--
|
|
15
|
+
-- Who "their own" is comes from 0016's private.genesis_viewer_person_ids(), the app's answer to
|
|
16
|
+
-- which person records a login is.
|
|
17
|
+
--
|
|
18
|
+
-- What changes for the gate:
|
|
19
|
+
--
|
|
20
|
+
-- feature_on(tenant, feature)
|
|
21
|
+
-- A paid feature is on for a signed-in person when the tenant holds it or they do. Server code
|
|
22
|
+
-- still gets the tenant's answer.
|
|
23
|
+
-- feature_entitled_tenants(feature)
|
|
24
|
+
-- For a signed-in person, also the tenants where they hold it themselves, so a policy over many
|
|
25
|
+
-- rows answers "may this person use it here".
|
|
26
|
+
-- feature_gate_state(tenant)
|
|
27
|
+
-- `entitled` is the tenant's grants plus the signed-in person's own in that tenant.
|
|
28
|
+
-- feature_gate_state(tenant, person) (new, server code only)
|
|
29
|
+
-- The same for a person server code names, for a snapshot built on the server.
|
|
30
|
+
--
|
|
31
|
+
-- Credits, balances and which offer unlocks a feature are billing's, not the registry's: an
|
|
32
|
+
-- entitlement only says on or off.
|
|
33
|
+
--
|
|
34
|
+
-- Needs 0004, 0008, 0014 and 0016. Verify: tests/0017_genesis_person_entitlements.test.sql.
|
|
35
|
+
|
|
36
|
+
create table public.feature_person_entitlements (
|
|
37
|
+
tenant_id uuid not null,
|
|
38
|
+
person_id uuid not null,
|
|
39
|
+
-- No foreign key: a billing webhook may grant a feature before the deploy that adds it syncs.
|
|
40
|
+
feature_id text not null
|
|
41
|
+
constraint feature_person_entitlements_feature_id_format check (feature_id ~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' and char_length(feature_id) <= 100),
|
|
42
|
+
-- Where the grant comes from: 'stripe', 'manual', 'trial' …
|
|
43
|
+
source text not null
|
|
44
|
+
constraint feature_person_entitlements_source_format check (source ~ '^[a-z][a-z0-9_-]*$' and char_length(source) <= 40),
|
|
45
|
+
-- What in the source it comes from (a subscription item, a purchase); '' when there's only one.
|
|
46
|
+
source_ref text not null default ''
|
|
47
|
+
constraint feature_person_entitlements_source_ref_length check (char_length(source_ref) <= 200),
|
|
48
|
+
active boolean not null,
|
|
49
|
+
-- Optional start and end of the grant; outside them it doesn't count.
|
|
50
|
+
starts_at timestamptz,
|
|
51
|
+
ends_at timestamptz,
|
|
52
|
+
updated_at timestamptz not null default now(),
|
|
53
|
+
primary key (tenant_id, person_id, feature_id, source, source_ref),
|
|
54
|
+
constraint feature_person_entitlements_window check (starts_at is null or ends_at is null or starts_at < ends_at)
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
comment on table public.feature_person_entitlements is
|
|
58
|
+
'Which person may use which paid feature in a tenant, by source and source_ref, optionally from starts_at until ends_at. person_id is the app''s person record. Written by the service role; a person reads their own. Genesis feature registry.';
|
|
59
|
+
|
|
60
|
+
create index feature_person_entitlements_feature_active on public.feature_person_entitlements (feature_id) where active;
|
|
61
|
+
|
|
62
|
+
-- Writing grants (server code) -------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
-- Grant, or renew, one person's entitlement. Idempotent on (tenant, person, feature, source,
|
|
65
|
+
-- source_ref): a replayed webhook changes nothing but updated_at.
|
|
66
|
+
create or replace function public.grant_person_entitlement(
|
|
67
|
+
tenant uuid, person uuid, feature text, source text, source_ref text default '',
|
|
68
|
+
starts_at timestamptz default null, ends_at timestamptz default null)
|
|
69
|
+
returns void
|
|
70
|
+
language sql
|
|
71
|
+
set search_path = ''
|
|
72
|
+
as $$
|
|
73
|
+
insert into public.feature_person_entitlements as e
|
|
74
|
+
(tenant_id, person_id, feature_id, source, source_ref, active, starts_at, ends_at, updated_at)
|
|
75
|
+
values (tenant, person, feature, source, coalesce(source_ref, ''), true, starts_at, ends_at, now())
|
|
76
|
+
on conflict (tenant_id, person_id, feature_id, source, source_ref) do update
|
|
77
|
+
set active = true, starts_at = excluded.starts_at, ends_at = excluded.ends_at, updated_at = now()
|
|
78
|
+
$$;
|
|
79
|
+
|
|
80
|
+
comment on function public.grant_person_entitlement(uuid, uuid, text, text, text, timestamptz, timestamptz) is
|
|
81
|
+
'Grant or renew a person''s entitlement to a feature, idempotently. Service role only. Genesis feature registry.';
|
|
82
|
+
|
|
83
|
+
-- Revoke one person's entitlement. The row stays, inactive, as a record; false when there was none.
|
|
84
|
+
create or replace function public.revoke_person_entitlement(
|
|
85
|
+
tenant uuid, person uuid, feature text, source text, source_ref text default '')
|
|
86
|
+
returns boolean
|
|
87
|
+
language sql
|
|
88
|
+
set search_path = ''
|
|
89
|
+
as $$
|
|
90
|
+
with revoked as (
|
|
91
|
+
update public.feature_person_entitlements e
|
|
92
|
+
set active = false, updated_at = now()
|
|
93
|
+
where e.tenant_id = tenant and e.person_id = person and e.feature_id = feature
|
|
94
|
+
and e.source = revoke_person_entitlement.source and e.source_ref = coalesce(revoke_person_entitlement.source_ref, '')
|
|
95
|
+
returning 1
|
|
96
|
+
)
|
|
97
|
+
select exists (select 1 from revoked)
|
|
98
|
+
$$;
|
|
99
|
+
|
|
100
|
+
comment on function public.revoke_person_entitlement(uuid, uuid, text, text, text) is
|
|
101
|
+
'Revoke a person''s entitlement to a feature; the row stays inactive. Service role only. Genesis feature registry.';
|
|
102
|
+
|
|
103
|
+
-- Reading grants ---------------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
-- The features a person holds in a tenant right now.
|
|
106
|
+
create or replace function private.genesis_person_entitled(tenant uuid, person uuid)
|
|
107
|
+
returns setof text
|
|
108
|
+
language sql
|
|
109
|
+
stable
|
|
110
|
+
security definer
|
|
111
|
+
set search_path = ''
|
|
112
|
+
as $$
|
|
113
|
+
select distinct p.feature_id from public.feature_person_entitlements p
|
|
114
|
+
where p.tenant_id = tenant and p.person_id = person and p.active
|
|
115
|
+
and (p.starts_at is null or p.starts_at <= now()) and (p.ends_at is null or p.ends_at > now())
|
|
116
|
+
$$;
|
|
117
|
+
|
|
118
|
+
-- The features the signed-in person holds in a tenant, through any of their person records there.
|
|
119
|
+
create or replace function private.genesis_viewer_entitled(tenant uuid)
|
|
120
|
+
returns setof text
|
|
121
|
+
language sql
|
|
122
|
+
stable
|
|
123
|
+
security definer
|
|
124
|
+
set search_path = ''
|
|
125
|
+
as $$
|
|
126
|
+
select distinct p.feature_id from public.feature_person_entitlements p
|
|
127
|
+
join private.genesis_viewer_person_ids() v on v.tenant_id = p.tenant_id and v.person_id = p.person_id
|
|
128
|
+
where p.tenant_id = tenant and p.active
|
|
129
|
+
and (p.starts_at is null or p.starts_at <= now()) and (p.ends_at is null or p.ends_at > now())
|
|
130
|
+
$$;
|
|
131
|
+
|
|
132
|
+
create or replace function public.feature_on(tenant uuid, feature text)
|
|
133
|
+
returns boolean
|
|
134
|
+
language plpgsql
|
|
135
|
+
stable
|
|
136
|
+
security definer
|
|
137
|
+
set search_path = ''
|
|
138
|
+
as $$
|
|
139
|
+
begin
|
|
140
|
+
if tenant is null or feature is null then
|
|
141
|
+
return false;
|
|
142
|
+
end if;
|
|
143
|
+
if not private.genesis_feature_may_read(tenant) then
|
|
144
|
+
return false;
|
|
145
|
+
end if;
|
|
146
|
+
return exists (
|
|
147
|
+
select 1 from public.features f
|
|
148
|
+
where f.id = feature and f.in_registry and f.status in ('beta', 'live', 'deprecated')
|
|
149
|
+
and (f.access_plan is null
|
|
150
|
+
or exists (
|
|
151
|
+
select 1 from public.feature_entitlements e
|
|
152
|
+
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())
|
|
153
|
+
)
|
|
154
|
+
or f.id in (select private.genesis_viewer_entitled(tenant)))
|
|
155
|
+
);
|
|
156
|
+
end;
|
|
157
|
+
$$;
|
|
158
|
+
|
|
159
|
+
comment on function public.feature_on(uuid, text) is
|
|
160
|
+
'The gate in SQL: shipped (beta, live, deprecated) and, when paid, entitled to the tenant or to the signed-in person. For row security. A signed-in caller outside the tenant gets false. Genesis feature registry.';
|
|
161
|
+
|
|
162
|
+
create or replace function public.feature_entitled_tenants(feature text)
|
|
163
|
+
returns setof uuid
|
|
164
|
+
language plpgsql
|
|
165
|
+
stable
|
|
166
|
+
security definer
|
|
167
|
+
set search_path = ''
|
|
168
|
+
as $$
|
|
169
|
+
begin
|
|
170
|
+
return query
|
|
171
|
+
select e.tenant_id from public.feature_entitlements e
|
|
172
|
+
where e.feature_id = feature and e.active and (e.ends_at is null or e.ends_at > now())
|
|
173
|
+
and private.genesis_feature_may_read(e.tenant_id)
|
|
174
|
+
union
|
|
175
|
+
select p.tenant_id from public.feature_person_entitlements p
|
|
176
|
+
join private.genesis_viewer_person_ids() v on v.tenant_id = p.tenant_id and v.person_id = p.person_id
|
|
177
|
+
where p.feature_id = feature and p.active
|
|
178
|
+
and (p.starts_at is null or p.starts_at <= now()) and (p.ends_at is null or p.ends_at > now())
|
|
179
|
+
and private.genesis_feature_may_read(p.tenant_id);
|
|
180
|
+
end;
|
|
181
|
+
$$;
|
|
182
|
+
|
|
183
|
+
comment on function public.feature_entitled_tenants(text) is
|
|
184
|
+
'Tenants where a feature is entitled: every tenant holding it, for server code; for a signed-in person, their own tenants that hold it or where they hold it themselves. For row security, once per statement. Genesis feature registry.';
|
|
185
|
+
|
|
186
|
+
-- The snapshot's state, for the signed-in person (person grants are theirs) or for server code
|
|
187
|
+
-- naming a person (null: the tenant's alone).
|
|
188
|
+
create or replace function private.genesis_feature_gate_state(tenant uuid, person_entitled text[])
|
|
189
|
+
returns jsonb
|
|
190
|
+
language sql
|
|
191
|
+
stable
|
|
192
|
+
security definer
|
|
193
|
+
set search_path = ''
|
|
194
|
+
as $$
|
|
195
|
+
select jsonb_build_object(
|
|
196
|
+
'off', coalesce((
|
|
197
|
+
select jsonb_agg(t.feature_id order by t.feature_id) from public.tenant_features t
|
|
198
|
+
where t.tenant_id = tenant and not t.enabled
|
|
199
|
+
), '[]'::jsonb),
|
|
200
|
+
'entitled', coalesce((
|
|
201
|
+
select jsonb_agg(x.feature_id order by x.feature_id) from (
|
|
202
|
+
select e.feature_id from public.feature_entitlements e
|
|
203
|
+
where e.tenant_id = tenant and e.active and (e.ends_at is null or e.ends_at > now())
|
|
204
|
+
union
|
|
205
|
+
select unnest(person_entitled)
|
|
206
|
+
) x
|
|
207
|
+
), '[]'::jsonb),
|
|
208
|
+
-- The tenant's own values, then platform values on top: a platform value (a kill switch)
|
|
209
|
+
-- applies to every tenant, whatever the tenant's own value.
|
|
210
|
+
'flags', coalesce((
|
|
211
|
+
select jsonb_object_agg(v.flag_key, v.value) from public.tenant_flag_values v
|
|
212
|
+
join public.feature_flags fl on fl.key = v.flag_key and fl.in_registry
|
|
213
|
+
where v.tenant_id = tenant
|
|
214
|
+
), '{}'::jsonb) || coalesce((
|
|
215
|
+
select jsonb_object_agg(fl.key, fl.platform_value) from public.feature_flags fl
|
|
216
|
+
where fl.in_registry and fl.platform_value is not null
|
|
217
|
+
), '{}'::jsonb)
|
|
218
|
+
)
|
|
219
|
+
$$;
|
|
220
|
+
|
|
221
|
+
create or replace function public.feature_gate_state(tenant uuid)
|
|
222
|
+
returns jsonb
|
|
223
|
+
language plpgsql
|
|
224
|
+
stable
|
|
225
|
+
security definer
|
|
226
|
+
set search_path = ''
|
|
227
|
+
as $$
|
|
228
|
+
begin
|
|
229
|
+
if tenant is null then
|
|
230
|
+
raise exception 'feature_gate_state: tenant is required' using errcode = '22004';
|
|
231
|
+
end if;
|
|
232
|
+
if not private.genesis_feature_may_read(tenant) then
|
|
233
|
+
raise exception 'feature_gate_state: only the tenant''s members can read its features' using errcode = '42501';
|
|
234
|
+
end if;
|
|
235
|
+
return private.genesis_feature_gate_state(tenant, array(select private.genesis_viewer_entitled(tenant)));
|
|
236
|
+
end;
|
|
237
|
+
$$;
|
|
238
|
+
|
|
239
|
+
comment on function public.feature_gate_state(uuid) is
|
|
240
|
+
'A tenant''s switches off, entitlements held (the tenant''s and the signed-in person''s own) and flag values, for the gate''s snapshot. Its members and the service role. Genesis feature registry.';
|
|
241
|
+
|
|
242
|
+
create or replace function public.feature_gate_state(tenant uuid, person uuid)
|
|
243
|
+
returns jsonb
|
|
244
|
+
language plpgsql
|
|
245
|
+
stable
|
|
246
|
+
security definer
|
|
247
|
+
set search_path = ''
|
|
248
|
+
as $$
|
|
249
|
+
begin
|
|
250
|
+
if tenant is null then
|
|
251
|
+
raise exception 'feature_gate_state: tenant is required' using errcode = '22004';
|
|
252
|
+
end if;
|
|
253
|
+
if not private.genesis_feature_caller_is_server() then
|
|
254
|
+
raise exception 'feature_gate_state: only server code can name a person' using errcode = '42501';
|
|
255
|
+
end if;
|
|
256
|
+
return private.genesis_feature_gate_state(tenant,
|
|
257
|
+
case when person is null then '{}'::text[] else array(select private.genesis_person_entitled(tenant, person)) end);
|
|
258
|
+
end;
|
|
259
|
+
$$;
|
|
260
|
+
|
|
261
|
+
comment on function public.feature_gate_state(uuid, uuid) is
|
|
262
|
+
'A tenant''s gate state with one named person''s entitlements added. Server code only. Genesis feature registry.';
|
|
263
|
+
|
|
264
|
+
-- Access ---------------------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
alter table public.feature_person_entitlements enable row level security;
|
|
267
|
+
|
|
268
|
+
revoke all on table public.feature_person_entitlements from public, anon, authenticated, service_role;
|
|
269
|
+
grant select, insert, update, delete on table public.feature_person_entitlements to service_role;
|
|
270
|
+
grant select (tenant_id, person_id, feature_id, source, active, starts_at, ends_at) on table public.feature_person_entitlements to authenticated;
|
|
271
|
+
create policy "People read their own entitlements" on public.feature_person_entitlements for select to authenticated
|
|
272
|
+
using ((tenant_id, person_id) in (select v.tenant_id, v.person_id from private.genesis_viewer_person_ids() v));
|
|
273
|
+
|
|
274
|
+
revoke execute on function public.grant_person_entitlement(uuid, uuid, text, text, text, timestamptz, timestamptz) from public, anon, authenticated;
|
|
275
|
+
grant execute on function public.grant_person_entitlement(uuid, uuid, text, text, text, timestamptz, timestamptz) to service_role;
|
|
276
|
+
revoke execute on function public.revoke_person_entitlement(uuid, uuid, text, text, text) from public, anon, authenticated;
|
|
277
|
+
grant execute on function public.revoke_person_entitlement(uuid, uuid, text, text, text) to service_role;
|
|
278
|
+
|
|
279
|
+
revoke execute on function private.genesis_person_entitled(uuid, uuid) from public, anon, authenticated;
|
|
280
|
+
revoke execute on function private.genesis_viewer_entitled(uuid) from public, anon, authenticated;
|
|
281
|
+
revoke execute on function private.genesis_feature_gate_state(uuid, text[]) from public, anon, authenticated;
|
|
282
|
+
|
|
283
|
+
revoke execute on function public.feature_gate_state(uuid, uuid) from public, anon, authenticated;
|
|
284
|
+
grant execute on function public.feature_gate_state(uuid, uuid) to service_role;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
-- @feat:feature-mirror
|
|
2
|
+
-- pgTAP test for 0016_genesis_viewer_people.sql.
|
|
3
|
+
-- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
|
|
4
|
+
-- It writes only its own users and hook and rolls everything back. If your app already has the
|
|
5
|
+
-- hook, it is dropped and replaced inside this transaction only.
|
|
6
|
+
begin;
|
|
7
|
+
create extension if not exists pgtap with schema extensions;
|
|
8
|
+
select plan(9);
|
|
9
|
+
|
|
10
|
+
insert into auth.users (id, aud, role, email, instance_id)
|
|
11
|
+
select ('00000000-0000-4000-8000-0000000016' || n)::uuid, 'authenticated', 'authenticated', 'genesis-viewer-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
|
|
12
|
+
from unnest(array['a1', 'b2']) n;
|
|
13
|
+
|
|
14
|
+
create function pg_temp.login(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000016' || n)::uuid $$;
|
|
15
|
+
-- The wrapper is called as the owner with a person's claims, the way a policy calls it for that
|
|
16
|
+
-- person (signed-in callers can't name the private schema themselves).
|
|
17
|
+
create function pg_temp.claims(n text) returns void language plpgsql as $$
|
|
18
|
+
begin
|
|
19
|
+
perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.login(n), 'role', 'authenticated')::text, true);
|
|
20
|
+
perform set_config('request.jwt.claim.sub', pg_temp.login(n)::text, true);
|
|
21
|
+
end $$;
|
|
22
|
+
create function pg_temp.no_one() returns void language plpgsql as $$
|
|
23
|
+
begin
|
|
24
|
+
perform set_config('request.jwt.claims', '', true);
|
|
25
|
+
perform set_config('request.jwt.claim.sub', '', true);
|
|
26
|
+
end $$;
|
|
27
|
+
|
|
28
|
+
drop function if exists private.genesis_viewer_people(uuid);
|
|
29
|
+
|
|
30
|
+
select ok(not has_function_privilege('anon', 'private.genesis_viewer_person_ids()', 'execute'), 'anon can''t call genesis_viewer_person_ids');
|
|
31
|
+
select ok(has_function_privilege('authenticated', 'private.genesis_viewer_person_ids()', 'execute'), 'authenticated can, for row security');
|
|
32
|
+
|
|
33
|
+
-- No hook: fail closed, without an error.
|
|
34
|
+
select pg_temp.claims('a1');
|
|
35
|
+
select lives_ok($$select * from private.genesis_viewer_person_ids()$$, 'without the hook, no error');
|
|
36
|
+
select is((select count(*)::int from private.genesis_viewer_person_ids()), 0, '... and an empty set');
|
|
37
|
+
|
|
38
|
+
-- The app's hook: a1 has a personal record (its tenant is its own id) and records in two
|
|
39
|
+
-- organizations, one listed twice and one row with a null person; b2 has none.
|
|
40
|
+
create function private.genesis_viewer_people(viewer uuid)
|
|
41
|
+
returns table (tenant_id uuid, person_id uuid) language sql stable set search_path = '' as $$
|
|
42
|
+
select t, p from (values
|
|
43
|
+
('00000000-0000-4000-9000-0000000016c1'::uuid, '00000000-0000-4000-9000-0000000016c1'::uuid),
|
|
44
|
+
('00000000-0000-4000-9000-0000000016d1'::uuid, '00000000-0000-4000-a000-0000000016d1'::uuid),
|
|
45
|
+
('00000000-0000-4000-9000-0000000016d2'::uuid, '00000000-0000-4000-a000-0000000016d2'::uuid),
|
|
46
|
+
('00000000-0000-4000-9000-0000000016d2'::uuid, '00000000-0000-4000-a000-0000000016d2'::uuid),
|
|
47
|
+
('00000000-0000-4000-9000-0000000016d3'::uuid, null::uuid)
|
|
48
|
+
) r (t, p)
|
|
49
|
+
where viewer = '00000000-0000-4000-8000-0000000016a1'::uuid
|
|
50
|
+
$$;
|
|
51
|
+
|
|
52
|
+
select set_eq(
|
|
53
|
+
$$select tenant_id, person_id from private.genesis_viewer_person_ids()$$,
|
|
54
|
+
$$values ('00000000-0000-4000-9000-0000000016c1'::uuid, '00000000-0000-4000-9000-0000000016c1'::uuid),
|
|
55
|
+
('00000000-0000-4000-9000-0000000016d1'::uuid, '00000000-0000-4000-a000-0000000016d1'::uuid),
|
|
56
|
+
('00000000-0000-4000-9000-0000000016d2'::uuid, '00000000-0000-4000-a000-0000000016d2'::uuid)$$,
|
|
57
|
+
'a personal record and two organizations, without duplicates or null ids');
|
|
58
|
+
select is((select count(*)::int from private.genesis_viewer_person_ids()), 3, '... once each');
|
|
59
|
+
|
|
60
|
+
select pg_temp.claims('b2');
|
|
61
|
+
select is((select count(*)::int from private.genesis_viewer_person_ids()), 0, 'a login with no people gets an empty set');
|
|
62
|
+
|
|
63
|
+
select pg_temp.no_one();
|
|
64
|
+
select is((select count(*)::int from private.genesis_viewer_person_ids()), 0, 'nobody signed in gets an empty set');
|
|
65
|
+
|
|
66
|
+
-- A hook that errors fails closed.
|
|
67
|
+
drop function private.genesis_viewer_people(uuid);
|
|
68
|
+
create function private.genesis_viewer_people(viewer uuid)
|
|
69
|
+
returns table (tenant_id uuid, person_id uuid) language plpgsql stable set search_path = '' as $$
|
|
70
|
+
begin
|
|
71
|
+
raise exception 'broken hook';
|
|
72
|
+
end $$;
|
|
73
|
+
select pg_temp.claims('a1');
|
|
74
|
+
select is((select count(*)::int from private.genesis_viewer_person_ids()), 0, 'a hook that errors gives an empty set');
|
|
75
|
+
|
|
76
|
+
select * from finish();
|
|
77
|
+
rollback;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
-- @feat:feature-mirror
|
|
2
|
+
-- pgTAP test for 0017_genesis_person_entitlements.sql (needs 0004, 0008, 0014 and 0016).
|
|
3
|
+
-- Copy into your app's `supabase/tests/database/` and run `supabase test db`. Rolls back. If your
|
|
4
|
+
-- app already has the membership or viewer-people hooks, they are replaced inside this
|
|
5
|
+
-- transaction only.
|
|
6
|
+
begin;
|
|
7
|
+
create extension if not exists pgtap with schema extensions;
|
|
8
|
+
select plan(25);
|
|
9
|
+
|
|
10
|
+
-- Two logins, both members of tenant T. a1 is person P1 in T; b2 is person P2 in T.
|
|
11
|
+
insert into auth.users (id, aud, role, email, instance_id)
|
|
12
|
+
select ('00000000-0000-4000-8000-0000000017' || n)::uuid, 'authenticated', 'authenticated', 'person-ent-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
|
|
13
|
+
from unnest(array['a1', 'b2']) n;
|
|
14
|
+
|
|
15
|
+
create function pg_temp.t() returns uuid language sql immutable as $$ select '00000000-0000-4000-9000-0000000017c1'::uuid $$;
|
|
16
|
+
create function pg_temp.p(n int) returns uuid language sql immutable as $$ select ('00000000-0000-4000-a000-00000000170' || n)::uuid $$;
|
|
17
|
+
create function pg_temp.as_login(n text) returns void language plpgsql as $$
|
|
18
|
+
begin
|
|
19
|
+
perform set_config('request.jwt.claims', json_build_object('sub', '00000000-0000-4000-8000-0000000017' || n, 'role', 'authenticated')::text, true);
|
|
20
|
+
perform set_config('request.jwt.claim.sub', '00000000-0000-4000-8000-0000000017' || n, true);
|
|
21
|
+
end $$;
|
|
22
|
+
|
|
23
|
+
drop function if exists private.genesis_tenant_member(uuid, uuid);
|
|
24
|
+
create function private.genesis_tenant_member(tenant uuid, person uuid) returns boolean language sql stable set search_path = '' as $$
|
|
25
|
+
select tenant = '00000000-0000-4000-9000-0000000017c1'::uuid
|
|
26
|
+
and person in ('00000000-0000-4000-8000-0000000017a1'::uuid, '00000000-0000-4000-8000-0000000017b2'::uuid)
|
|
27
|
+
$$;
|
|
28
|
+
revoke execute on function private.genesis_tenant_member(uuid, uuid) from public, anon, authenticated;
|
|
29
|
+
|
|
30
|
+
drop function if exists private.genesis_viewer_people(uuid);
|
|
31
|
+
create function private.genesis_viewer_people(viewer uuid)
|
|
32
|
+
returns table (tenant_id uuid, person_id uuid) language sql stable set search_path = '' as $$
|
|
33
|
+
select '00000000-0000-4000-9000-0000000017c1'::uuid,
|
|
34
|
+
case viewer when '00000000-0000-4000-8000-0000000017a1'::uuid then '00000000-0000-4000-a000-000000001701'::uuid
|
|
35
|
+
when '00000000-0000-4000-8000-0000000017b2'::uuid then '00000000-0000-4000-a000-000000001702'::uuid end
|
|
36
|
+
$$;
|
|
37
|
+
revoke execute on function private.genesis_viewer_people(uuid) from public, anon, authenticated;
|
|
38
|
+
|
|
39
|
+
select public.sync_feature_registry(9300, 'person-1',
|
|
40
|
+
'[{"id": "classes", "name": "Classes", "status": "live", "access": {"plan": "member"}},
|
|
41
|
+
{"id": "coaching", "name": "Coaching", "status": "live", "access": {"plan": "coaching"}},
|
|
42
|
+
{"id": "free", "name": "Free", "status": "live"}]', '[]');
|
|
43
|
+
|
|
44
|
+
-- Privileges ---------------------------------------------------------------------------------
|
|
45
|
+
select ok(not has_function_privilege('authenticated', 'public.grant_person_entitlement(uuid,uuid,text,text,text,timestamptz,timestamptz)', 'execute'), 'a signed-in person can''t grant');
|
|
46
|
+
select ok(not has_function_privilege('authenticated', 'public.revoke_person_entitlement(uuid,uuid,text,text,text)', 'execute'), '... nor revoke');
|
|
47
|
+
select ok(not has_function_privilege('authenticated', 'public.feature_gate_state(uuid,uuid)', 'execute'), '... nor name a person for gate state');
|
|
48
|
+
select ok(not has_table_privilege('authenticated', 'public.feature_person_entitlements', 'insert'), '... nor write the table');
|
|
49
|
+
select ok(not has_function_privilege('anon', 'public.feature_gate_state(uuid)', 'execute'), 'anon still reads no gate state');
|
|
50
|
+
|
|
51
|
+
-- Granting -----------------------------------------------------------------------------------
|
|
52
|
+
set local role service_role;
|
|
53
|
+
select lives_ok($$select public.grant_person_entitlement(pg_temp.t(), pg_temp.p(1), 'classes', 'stripe', 'si_1')$$, 'server code grants P1 classes');
|
|
54
|
+
select lives_ok($$select public.grant_person_entitlement(pg_temp.t(), pg_temp.p(1), 'classes', 'stripe', 'si_1')$$, '... and a replayed webhook is fine');
|
|
55
|
+
select is((select count(*)::int from public.feature_person_entitlements where person_id = pg_temp.p(1)), 1, '... with one row');
|
|
56
|
+
select public.grant_person_entitlement(pg_temp.t(), pg_temp.p(1), 'coaching', 'stripe', 'pi_1', now() + interval '1 day', null);
|
|
57
|
+
select public.grant_person_entitlement(pg_temp.t(), pg_temp.p(2), 'coaching', 'manual', '', null, now() - interval '1 day');
|
|
58
|
+
select is(public.feature_gate_state(pg_temp.t(), pg_temp.p(1)) -> 'entitled', '["classes"]'::jsonb, 'server code reads a named person''s state; a grant not started yet doesn''t count');
|
|
59
|
+
select is(public.feature_gate_state(pg_temp.t(), pg_temp.p(2)) -> 'entitled', '[]'::jsonb, '... nor one that ended');
|
|
60
|
+
select is(public.feature_gate_state(pg_temp.t(), null) -> 'entitled', '[]'::jsonb, '... and no person means the tenant''s alone');
|
|
61
|
+
select is(public.feature_on(pg_temp.t(), 'classes'), false, 'server code''s feature_on stays the tenant''s answer');
|
|
62
|
+
reset role;
|
|
63
|
+
|
|
64
|
+
-- Reading, as each person ----------------------------------------------------------------------
|
|
65
|
+
set local role authenticated;
|
|
66
|
+
select pg_temp.as_login('a1');
|
|
67
|
+
select is(public.feature_on(pg_temp.t(), 'classes'), true, 'P1 may use classes');
|
|
68
|
+
select is(public.feature_on(pg_temp.t(), 'coaching'), false, '... but not coaching before it starts');
|
|
69
|
+
select is(public.feature_gate_state(pg_temp.t()) -> 'entitled', '["classes"]'::jsonb, 'P1''s gate state holds their own grant');
|
|
70
|
+
select ok(pg_temp.t() in (select public.feature_entitled_tenants('classes')), 'feature_entitled_tenants includes the tenant where P1 holds it');
|
|
71
|
+
select is((select count(*)::int from public.feature_person_entitlements), 2, 'P1 reads their own rows');
|
|
72
|
+
select throws_ok($$select public.feature_gate_state(pg_temp.t(), pg_temp.p(2))$$, '42501', null, 'P1 can''t name another person');
|
|
73
|
+
|
|
74
|
+
select pg_temp.as_login('b2');
|
|
75
|
+
select is(public.feature_on(pg_temp.t(), 'classes'), false, 'P2, in the same tenant, may not use P1''s classes');
|
|
76
|
+
select is((select count(*)::int from public.feature_person_entitlements), 1, 'P2 reads only their own row');
|
|
77
|
+
select is(public.feature_on(pg_temp.t(), 'free'), true, 'a free feature is on for everyone');
|
|
78
|
+
reset role;
|
|
79
|
+
select set_config('request.jwt.claims', '', true);
|
|
80
|
+
select set_config('request.jwt.claim.sub', '', true);
|
|
81
|
+
|
|
82
|
+
-- Revoking, and the tenant's own grants ---------------------------------------------------------
|
|
83
|
+
set local role service_role;
|
|
84
|
+
select is(public.revoke_person_entitlement(pg_temp.t(), pg_temp.p(1), 'classes', 'stripe', 'si_1'), true, 'revoking a grant');
|
|
85
|
+
select is(public.revoke_person_entitlement(pg_temp.t(), pg_temp.p(1), 'classes', 'stripe', 'si_nope'), false, '... and one that doesn''t exist is false');
|
|
86
|
+
insert into public.feature_entitlements (tenant_id, feature_id, source, active) values (pg_temp.t(), 'coaching', 'manual', true);
|
|
87
|
+
reset role;
|
|
88
|
+
|
|
89
|
+
set local role authenticated;
|
|
90
|
+
select pg_temp.as_login('a1');
|
|
91
|
+
select is(public.feature_on(pg_temp.t(), 'classes'), false, 'a revoked grant no longer counts');
|
|
92
|
+
select is(public.feature_on(pg_temp.t(), 'coaching'), true, 'a tenant grant still counts for every member');
|
|
93
|
+
reset role;
|
|
94
|
+
|
|
95
|
+
select * from finish();
|
|
96
|
+
rollback;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-supabase",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"README.md"
|
|
58
58
|
],
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@marktiderman/genesis-features": "^0.6.
|
|
60
|
+
"@marktiderman/genesis-features": "^0.6.1"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
63
|
"@supabase/supabase-js": "^2.118.0",
|
|
@@ -196,45 +196,18 @@
|
|
|
196
196
|
{
|
|
197
197
|
"file": "migrations/0014_genesis_feature_registry_hardening.sql",
|
|
198
198
|
"test": "migrations/tests/0014_genesis_feature_registry_hardening.test.sql"
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
},
|
|
205
|
-
"owner-access": {
|
|
206
|
-
"feature": {
|
|
207
|
-
"name": "Owner access",
|
|
208
|
-
"summary": "The owner-access contract: fail-closed wrappers (genesis_owner_readable, genesis_owner_allows) over the app's two hooks, for every Genesis block whose rows belong to a person, a team or the tenant.",
|
|
209
|
-
"keywords": [
|
|
210
|
-
"access",
|
|
211
|
-
"owners",
|
|
212
|
-
"row level security",
|
|
213
|
-
"tenants",
|
|
214
|
-
"teams"
|
|
215
|
-
],
|
|
216
|
-
"audience": [
|
|
217
|
-
"developer"
|
|
218
|
-
]
|
|
219
|
-
},
|
|
220
|
-
"platforms": [
|
|
221
|
-
"web",
|
|
222
|
-
"native"
|
|
223
|
-
],
|
|
224
|
-
"requires": [
|
|
225
|
-
"tenant-features"
|
|
226
|
-
],
|
|
227
|
-
"migrations": [
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
"file": "migrations/0016_genesis_viewer_people.sql",
|
|
202
|
+
"test": "migrations/tests/0016_genesis_viewer_people.test.sql"
|
|
203
|
+
},
|
|
228
204
|
{
|
|
229
|
-
"file": "migrations/
|
|
230
|
-
"test": "migrations/tests/
|
|
205
|
+
"file": "migrations/0017_genesis_person_entitlements.sql",
|
|
206
|
+
"test": "migrations/tests/0017_genesis_person_entitlements.test.sql"
|
|
231
207
|
}
|
|
232
208
|
],
|
|
233
|
-
"install": [
|
|
234
|
-
"@supabase/supabase-js@^2.118.0"
|
|
235
|
-
],
|
|
236
209
|
"steps": [
|
|
237
|
-
"
|
|
210
|
+
"Sync the registry on every deploy with the service key: syncFeatureRegistry(admin, features.json, { version: BUILD_TIME } (the build time, from a production deployment only)). Grant paid features by writing feature_entitlements from your billing webhook (a tenant's) or calling grant_person_entitlement (one person's). For person grants, define private.genesis_viewer_people(viewer) as 0016 shows."
|
|
238
211
|
]
|
|
239
212
|
},
|
|
240
213
|
"web-handoff": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/blocks.ts"],"names":[],"mappings":";;;AAQA,IAAM,OAAA,GAAU,gCAAA;AAST,IAAM,eAAe,WAAA,CAAY;AAAA,EACtC,EAAA,EAAI,SAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,8CAAA;AAAA,QACN,IAAA,EAAM;AAAA,OACR;AAAA;AAAA,MAEA;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,oDAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,QAAA,EAAU;AAAA,QACR;AAAA,UACE,IAAA,EAAM,eAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,SAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,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AS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC;AASM,IAAM,kBAAkB,WAAA,CAAY;AAAA,EACzC,EAAA,EAAI,aAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,yCAAA,EAA2C,MAAM,oDAAA;AAAqD,KAClI;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAUM,IAAM,mBAAmB,WAAA,CAAY;AAAA,EAC1C,EAAA,EAAI,cAAA;AAAA,EACJ,QAAA,EAAU,CAAC,iBAAiB,CAAA;AAAA,EAC5B,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,0CAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,sEAAsE,CAAA;AAAE;AAE/F,CAAC","file":"chunk-DYHH2G4A.js","sourcesContent":["/**\n * The blocks this package carries the server half of, as `defineBlock`\n * declarations: what each needs in the database, and what it means for the\n * stores' privacy forms. The functions themselves (`deleteMyAccount`,\n * `tenantFeatures`, …) don't change.\n */\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\n\nconst PACKAGE = \"@marktiderman/genesis-supabase\";\n\n/**\n * The account block: sign-in, profile and in-app account deletion. Its\n * screens are the app's (or genesis-ui-native's `AuthScreen`); this names its\n * migrations and its data.\n *\n * @stability Beta\n */\nexport const accountBlock = defineBlock({\n id: \"account\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0001_genesis_account_deletion.sql\",\n test: \"migrations/tests/0001_genesis_account_deletion.test.sql\",\n },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n {\n package: PACKAGE,\n file: \"migrations/0003_genesis_apple_token_revocation.sql\",\n test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\",\n },\n ],\n privacy: {\n collects: [\n {\n type: \"email address\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"user id\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"name\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n ],\n notes: [\n \"People delete their account from inside the app; their login and the rows that cascade from it go with it.\",\n \"With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted.\",\n ],\n },\n },\n});\n\n/**\n * The tenant features block: per-tenant on/off switches for shipped\n * features, set by the tenant's admins with a reason.\n *\n * @stability Beta\n */\nexport const tenantFeaturesBlock = defineBlock({\n id: \"tenant-features\",\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0004_genesis_tenant_features.sql\",\n test: \"migrations/tests/0004_genesis_tenant_features.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\",\n ],\n },\n },\n});\n\n/**\n * The feature registry block: the registry mirrored into the app's database\n * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,\n * for the feature gate. Needs the tenant features block.\n *\n * @stability Beta\n */\nexport const featureMirrorBlock = defineBlock({\n id: \"feature-mirror\",\n requires: [\"tenant-features\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0008_genesis_feature_registry.sql\",\n test: \"migrations/tests/0008_genesis_feature_registry.test.sql\",\n },\n {\n package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants hold which paid features and flag values; no personal data.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n\n/**\n * The web handoff block: continue on the web, already signed in. The routes are\n * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native\n * app calls `openOnWeb` from genesis-native.\n *\n * @stability Beta\n */\nexport const webHandoffBlock = defineBlock({\n id: \"web-handoff\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0015_genesis_web_handoff.sql\", test: \"migrations/tests/0015_genesis_web_handoff.test.sql\" },\n ],\n privacy: {\n notes: [\n \"Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token.\",\n ],\n },\n },\n});\n\n/**\n * The owner-access block: the contract every Genesis block with owned rows\n * calls in its policies. Two fail-closed wrappers over the app's hooks\n * (`genesis_owner_can`, `genesis_readable_owners`): a missing or broken hook\n * means no.\n *\n * @stability Experimental\n */\nexport const ownerAccessBlock = defineBlock({\n id: \"owner-access\",\n requires: [\"tenant-features\"],\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0009_genesis_owner_access.sql\",\n test: \"migrations/tests/0009_genesis_owner_access.test.sql\",\n },\n ],\n privacy: { notes: [\"Stores nothing; it only asks the app's hooks who may read and write.\"] },\n },\n});\n"]}
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
-- Genesis owner access: private.genesis_owner_readable() and private.genesis_owner_allows()
|
|
2
|
-
--
|
|
3
|
-
-- The owner-access contract, shared by every Genesis block whose rows have an owner (genesis-work's
|
|
4
|
-
-- goals, projects, tasks, issues, metrics, status updates and sessions). A row belongs to a tenant
|
|
5
|
-
-- and has exactly one owner: a person, a team or the tenant itself. Who may read and write it is
|
|
6
|
-
-- your app's answer, through two hooks. Genesis never defines them:
|
|
7
|
-
--
|
|
8
|
-
-- private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid,
|
|
9
|
-
-- organization_id uuid, action text) returns boolean
|
|
10
|
-
-- action is 'read' or 'write'.
|
|
11
|
-
-- private.genesis_readable_owners(viewer uuid) returns table (tenant_id uuid, owner_id uuid)
|
|
12
|
-
-- Every (tenant, owner) pair the viewer may read, across tenants, so a policy checks once per
|
|
13
|
-
-- statement instead of calling a function per row. owner_id is the row's person_id, team_id
|
|
14
|
-
-- or organization_id, whichever is set.
|
|
15
|
-
--
|
|
16
|
-
-- Both run with your migration's (the owner's) rights, so they read your membership tables
|
|
17
|
-
-- whatever their row security. For example:
|
|
18
|
-
--
|
|
19
|
-
-- create function private.genesis_readable_owners(viewer uuid)
|
|
20
|
-
-- returns table (tenant_id uuid, owner_id uuid) language sql stable set search_path = '' as $$
|
|
21
|
-
-- select m.team_id, m.user_id from public.memberships m where m.user_id = viewer -- my own rows
|
|
22
|
-
-- union all
|
|
23
|
-
-- select m.team_id, m.team_id from public.memberships m where m.user_id = viewer -- my team's rows
|
|
24
|
-
-- $$;
|
|
25
|
-
-- revoke execute on function private.genesis_readable_owners(uuid) from public, anon, authenticated;
|
|
26
|
-
--
|
|
27
|
-
-- This file ships the two wrappers that blocks call in their policies. They fail closed: a missing
|
|
28
|
-
-- hook, a hook that errors or returns the wrong type, no signed-in person, a null tenant, or an
|
|
29
|
-
-- action other than 'read' or 'write' gives false or an empty set.
|
|
30
|
-
--
|
|
31
|
-
-- private.genesis_owner_readable() returns table (tenant_id uuid, owner_id uuid)
|
|
32
|
-
-- The signed-in person's set, from genesis_readable_owners(auth.uid()).
|
|
33
|
-
-- private.genesis_owner_allows(tenant uuid, person_id uuid, team_id uuid, organization_id uuid,
|
|
34
|
-
-- action text) returns boolean
|
|
35
|
-
-- genesis_owner_can(tenant, auth.uid(), person_id, team_id, organization_id, action).
|
|
36
|
-
--
|
|
37
|
-
-- Both are security definer with search_path ''. Row security runs as the caller, so authenticated
|
|
38
|
-
-- may execute them; they only ever answer for auth.uid(). anon and public may not.
|
|
39
|
-
--
|
|
40
|
-
-- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
|
|
41
|
-
-- (`genesis migrate` does it). Never edit it once applied; change it with a new migration.
|
|
42
|
-
--
|
|
43
|
-
-- Verify: the pgTAP test beside this file (`tests/0009_genesis_owner_access.test.sql`).
|
|
44
|
-
|
|
45
|
-
create schema if not exists private;
|
|
46
|
-
|
|
47
|
-
create or replace function private.genesis_owner_readable()
|
|
48
|
-
returns table (tenant_id uuid, owner_id uuid)
|
|
49
|
-
language plpgsql
|
|
50
|
-
stable
|
|
51
|
-
security definer
|
|
52
|
-
set search_path = ''
|
|
53
|
-
as $$
|
|
54
|
-
begin
|
|
55
|
-
if auth.uid() is null or to_regprocedure('private.genesis_readable_owners(uuid)') is null then
|
|
56
|
-
return;
|
|
57
|
-
end if;
|
|
58
|
-
return query execute 'select r.tenant_id::uuid, r.owner_id::uuid from private.genesis_readable_owners($1) r' using auth.uid();
|
|
59
|
-
exception when others then
|
|
60
|
-
return;
|
|
61
|
-
end;
|
|
62
|
-
$$;
|
|
63
|
-
|
|
64
|
-
create or replace function private.genesis_owner_allows(tenant uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
|
|
65
|
-
returns boolean
|
|
66
|
-
language plpgsql
|
|
67
|
-
stable
|
|
68
|
-
security definer
|
|
69
|
-
set search_path = ''
|
|
70
|
-
as $$
|
|
71
|
-
declare
|
|
72
|
-
allowed boolean;
|
|
73
|
-
begin
|
|
74
|
-
if auth.uid() is null or tenant is null or action is null or action not in ('read', 'write')
|
|
75
|
-
or to_regprocedure('private.genesis_owner_can(uuid,uuid,uuid,uuid,uuid,text)') is null then
|
|
76
|
-
return false;
|
|
77
|
-
end if;
|
|
78
|
-
execute 'select (private.genesis_owner_can($1, $2, $3, $4, $5, $6))::boolean'
|
|
79
|
-
into allowed using tenant, auth.uid(), person_id, team_id, organization_id, action;
|
|
80
|
-
return coalesce(allowed, false);
|
|
81
|
-
exception when others then
|
|
82
|
-
return false;
|
|
83
|
-
end;
|
|
84
|
-
$$;
|
|
85
|
-
|
|
86
|
-
revoke execute on function private.genesis_owner_readable() from public, anon, authenticated;
|
|
87
|
-
revoke execute on function private.genesis_owner_allows(uuid, uuid, uuid, uuid, text) from public, anon, authenticated;
|
|
88
|
-
grant execute on function private.genesis_owner_readable() to authenticated;
|
|
89
|
-
grant execute on function private.genesis_owner_allows(uuid, uuid, uuid, uuid, text) to authenticated;
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
-- @feat:owner-access
|
|
2
|
-
-- pgTAP test for 0009_genesis_owner_access.sql.
|
|
3
|
-
-- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
|
|
4
|
-
-- It writes only its own users and hooks and rolls everything back. If your app already has the
|
|
5
|
-
-- hooks, they are dropped and replaced inside this transaction only.
|
|
6
|
-
begin;
|
|
7
|
-
create extension if not exists pgtap with schema extensions;
|
|
8
|
-
select plan(11);
|
|
9
|
-
|
|
10
|
-
insert into auth.users (id, aud, role, email, instance_id)
|
|
11
|
-
select ('00000000-0000-4000-8000-0000000000' || n)::uuid, 'authenticated', 'authenticated', 'genesis-owner-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
|
|
12
|
-
from unnest(array['a1', 'b2']) n;
|
|
13
|
-
|
|
14
|
-
create function pg_temp.person(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000000' || n)::uuid $$;
|
|
15
|
-
create function pg_temp.tenant(n int) returns uuid language sql immutable as $$ select ('00000000-0000-4000-9000-00000000000' || n)::uuid $$;
|
|
16
|
-
create function pg_temp.team(n int) returns uuid language sql immutable as $$ select ('00000000-0000-4000-a000-00000000000' || n)::uuid $$;
|
|
17
|
-
-- The wrappers are called as the owner with a person's claims, the way a policy calls them for
|
|
18
|
-
-- that person (signed-in callers can't name the private schema themselves).
|
|
19
|
-
create function pg_temp.claims(n text) returns void language plpgsql as $$
|
|
20
|
-
begin
|
|
21
|
-
perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.person(n), 'role', 'authenticated')::text, true);
|
|
22
|
-
perform set_config('request.jwt.claim.sub', pg_temp.person(n)::text, true);
|
|
23
|
-
end $$;
|
|
24
|
-
create function pg_temp.no_one() returns void language plpgsql as $$
|
|
25
|
-
begin
|
|
26
|
-
perform set_config('request.jwt.claims', '', true);
|
|
27
|
-
perform set_config('request.jwt.claim.sub', '', true);
|
|
28
|
-
end $$;
|
|
29
|
-
|
|
30
|
-
drop function if exists private.genesis_owner_can(uuid, uuid, uuid, uuid, uuid, text);
|
|
31
|
-
drop function if exists private.genesis_readable_owners(uuid);
|
|
32
|
-
|
|
33
|
-
-- Privileges ---------------------------------------------------------------------------------
|
|
34
|
-
select ok(not has_function_privilege('anon', 'private.genesis_owner_allows(uuid,uuid,uuid,uuid,text)', 'execute'), 'anon can''t call genesis_owner_allows');
|
|
35
|
-
select ok(not has_function_privilege('anon', 'private.genesis_owner_readable()', 'execute'), 'anon can''t call genesis_owner_readable');
|
|
36
|
-
|
|
37
|
-
-- No hooks: fail closed -----------------------------------------------------------------------
|
|
38
|
-
select pg_temp.claims('a1');
|
|
39
|
-
select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'write'), false, 'without the hook, no');
|
|
40
|
-
select is((select count(*)::int from private.genesis_owner_readable()), 0, 'without the hook, an empty set');
|
|
41
|
-
|
|
42
|
-
-- The app's hooks -----------------------------------------------------------------------------
|
|
43
|
-
create function private.genesis_readable_owners(viewer uuid)
|
|
44
|
-
returns table (tenant_id uuid, owner_id uuid) language sql stable set search_path = '' as $$
|
|
45
|
-
select '00000000-0000-4000-9000-000000000001'::uuid, '00000000-0000-4000-a000-000000000001'::uuid
|
|
46
|
-
where viewer = '00000000-0000-4000-8000-0000000000a1'::uuid
|
|
47
|
-
$$;
|
|
48
|
-
create function private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
|
|
49
|
-
returns boolean language sql stable set search_path = '' as $$
|
|
50
|
-
select viewer = '00000000-0000-4000-8000-0000000000a1'::uuid and team_id = '00000000-0000-4000-a000-000000000001'::uuid
|
|
51
|
-
$$;
|
|
52
|
-
|
|
53
|
-
select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'write'), true, 'the wrapper answers for the signed-in person');
|
|
54
|
-
select is((select count(*)::int from private.genesis_owner_readable()), 1, 'the readable set for the signed-in person');
|
|
55
|
-
select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'delete'), false, 'an action other than read or write is no');
|
|
56
|
-
select is(private.genesis_owner_allows(null, null, pg_temp.team(1), null, 'read'), false, 'a null tenant is no');
|
|
57
|
-
select pg_temp.claims('b2');
|
|
58
|
-
select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'read'), false, 'it answers only for the signed-in person');
|
|
59
|
-
select pg_temp.no_one();
|
|
60
|
-
select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'read'), false, 'nobody signed in is no');
|
|
61
|
-
|
|
62
|
-
-- A hook with the wrong return type fails closed -----------------------------------------------
|
|
63
|
-
drop function private.genesis_owner_can(uuid, uuid, uuid, uuid, uuid, text);
|
|
64
|
-
create function private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
|
|
65
|
-
returns text language sql stable set search_path = '' as $$ select 'maybe' $$;
|
|
66
|
-
select pg_temp.claims('a1');
|
|
67
|
-
select is(private.genesis_owner_allows(pg_temp.tenant(1), null, pg_temp.team(1), null, 'write'), false, 'a hook that errors means no');
|
|
68
|
-
|
|
69
|
-
select * from finish();
|
|
70
|
-
rollback;
|