@marktiderman/genesis-supabase 0.6.2 → 0.8.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.
Files changed (35) hide show
  1. package/README.md +128 -7
  2. package/dist/blocks.d.ts +18 -1
  3. package/dist/blocks.js +1 -1
  4. package/dist/chunk-7SCMHKCR.js +33 -0
  5. package/dist/chunk-7SCMHKCR.js.map +1 -0
  6. package/dist/{chunk-ONBOLMXH.js → chunk-DYHH2G4A.js} +37 -3
  7. package/dist/chunk-DYHH2G4A.js.map +1 -0
  8. package/dist/chunk-XGAXPUFY.js +124 -0
  9. package/dist/chunk-XGAXPUFY.js.map +1 -0
  10. package/dist/{index-Ds0tO9WP.d.ts → index-D73YuwEY.d.ts} +4 -4
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/jobs.d.ts +3 -1
  15. package/dist/jobs.js +48 -34
  16. package/dist/jobs.js.map +1 -1
  17. package/dist/native.d.ts +2 -2
  18. package/dist/runner.d.ts +179 -0
  19. package/dist/runner.js +3 -0
  20. package/dist/runner.js.map +1 -0
  21. package/dist/web-handoff-path-C_EEl_BC.d.ts +16 -0
  22. package/dist/web-handoff-server.d.ts +225 -0
  23. package/dist/web-handoff-server.js +262 -0
  24. package/dist/web-handoff-server.js.map +1 -0
  25. package/dist/web-handoff.d.ts +133 -0
  26. package/dist/web-handoff.js +104 -0
  27. package/dist/web-handoff.js.map +1 -0
  28. package/migrations/0009_genesis_owner_access.sql +89 -0
  29. package/migrations/0014_genesis_feature_registry_hardening.sql +124 -0
  30. package/migrations/0015_genesis_web_handoff.sql +270 -0
  31. package/migrations/tests/0009_genesis_owner_access.test.sql +70 -0
  32. package/migrations/tests/0014_genesis_feature_registry_hardening.test.sql +54 -0
  33. package/migrations/tests/0015_genesis_web_handoff.test.sql +203 -0
  34. package/package.json +88 -3
  35. package/dist/chunk-ONBOLMXH.js.map +0 -1
@@ -0,0 +1,133 @@
1
+ export { a as appRelativePath } from './web-handoff-path-C_EEl_BC.js';
2
+
3
+ /** What the handoff link carried in its fragment. */
4
+ interface WebHandoffFragment {
5
+ /** The single-use handoff token, or null when the link had none. */
6
+ token: string | null;
7
+ /** Where to land, already checked with {@link appRelativePath}; `/` when missing or unsafe. */
8
+ next: string;
9
+ }
10
+ interface LocationLike {
11
+ hash: string;
12
+ pathname: string;
13
+ search: string;
14
+ }
15
+ interface HistoryLike {
16
+ state: unknown;
17
+ replaceState(data: unknown, unused: string, url?: string | null): void;
18
+ }
19
+ /**
20
+ * Read the handoff link's fragment (`#t=<token>&next=<path>`) and remove it from the address bar
21
+ * and history at once (`history.replaceState`), so the token isn't left in history, a bookmark,
22
+ * a screenshot of the address bar, or the URL an analytics or error script records. Call it
23
+ * before those scripts load. Later calls return what the first call read.
24
+ *
25
+ * @stability Beta
26
+ */
27
+ declare function takeWebHandoffFragment(win?: {
28
+ location: LocationLike;
29
+ history: HistoryLike;
30
+ }): WebHandoffFragment | null;
31
+ /** Forget a fragment {@link takeWebHandoffFragment} read (tests, or after the handoff finished). */
32
+ declare function forgetWebHandoffFragment(): void;
33
+ /** The parts of a browser Supabase client the handoff uses. */
34
+ interface WebHandoffAuthClient {
35
+ auth: {
36
+ getSession(): PromiseLike<{
37
+ data: {
38
+ session: {
39
+ access_token?: string;
40
+ user: {
41
+ id: string;
42
+ email?: string | null;
43
+ };
44
+ } | null;
45
+ };
46
+ }>;
47
+ getUser(): PromiseLike<{
48
+ data: {
49
+ user: {
50
+ id: string;
51
+ email?: string | null;
52
+ } | null;
53
+ };
54
+ error: unknown;
55
+ }>;
56
+ signOut(options: {
57
+ scope: "local";
58
+ }): PromiseLike<{
59
+ error: unknown;
60
+ }>;
61
+ verifyOtp(params: {
62
+ token_hash: string;
63
+ type: "email";
64
+ }): PromiseLike<{
65
+ data: {
66
+ user: {
67
+ id: string;
68
+ } | null;
69
+ session?: {
70
+ access_token: string;
71
+ } | null;
72
+ } | null;
73
+ error: {
74
+ message: string;
75
+ } | null;
76
+ }>;
77
+ };
78
+ }
79
+ type WebHandoffFailure = "missing" | "expired" | "unavailable" | "verify_failed" | "wrong_user";
80
+ type WebHandoffStep =
81
+ /** Signed in as the right person: go to `next`. */
82
+ {
83
+ kind: "done";
84
+ next: string;
85
+ }
86
+ /**
87
+ * Ask before signing in: "Continue as {email}?". Shown whenever the browser isn't already
88
+ * signed in as this person (nobody, or someone else), so a link someone else minted for their
89
+ * own account can't sign you in to it unnoticed. Nothing that signs anyone in exists until
90
+ * `continue()`: it spends the continue nonce (30 seconds, once), and only then does the server
91
+ * mint Supabase's token, which is exchanged at once. `cancel()` burns the nonce.
92
+ */
93
+ | {
94
+ kind: "confirm";
95
+ email: string;
96
+ next: string;
97
+ signedInAs: string | null;
98
+ continue(): Promise<WebHandoffStep>;
99
+ cancel(): Promise<WebHandoffStep>;
100
+ }
101
+ /**
102
+ * The person chose Cancel. Whoever else was signed in here has been signed out locally, so the
103
+ * page never leaves someone in the app as another person: show "You can close this window".
104
+ */
105
+ | {
106
+ kind: "cancelled";
107
+ next: string;
108
+ signedOut: boolean;
109
+ } | {
110
+ kind: "failed";
111
+ reason: WebHandoffFailure;
112
+ next: string;
113
+ };
114
+ /** @stability Beta */
115
+ interface CompleteWebHandoffOptions {
116
+ supabase: WebHandoffAuthClient;
117
+ /** From {@link takeWebHandoffFragment}. */
118
+ fragment: WebHandoffFragment | null;
119
+ /** The redeem route. Default `/api/auth/redeem-handoff`. */
120
+ redeemEndpoint?: string;
121
+ fetch?: typeof fetch;
122
+ }
123
+ /**
124
+ * Claim the handoff and say what the page shows next. Never signs anyone in or out by itself:
125
+ * a `confirm` step does that only when the person chooses `continue()` or `cancel()`. A fragment
126
+ * is claimed once: calling again with the same fragment (React's development double effects)
127
+ * returns the same promise.
128
+ *
129
+ * @stability Beta
130
+ */
131
+ declare function completeWebHandoff(options: CompleteWebHandoffOptions): Promise<WebHandoffStep>;
132
+
133
+ export { type CompleteWebHandoffOptions, type WebHandoffAuthClient, type WebHandoffFailure, type WebHandoffFragment, type WebHandoffStep, completeWebHandoff, forgetWebHandoffFragment, takeWebHandoffFragment };
@@ -0,0 +1,104 @@
1
+ import { appRelativePath } from './chunk-7SCMHKCR.js';
2
+ export { appRelativePath } from './chunk-7SCMHKCR.js';
3
+
4
+ // src/web-handoff.ts
5
+ var taken = null;
6
+ function takeWebHandoffFragment(win = globalThis) {
7
+ const hash = win.location.hash;
8
+ if (hash.length > 1) {
9
+ const params = new URLSearchParams(hash.slice(1));
10
+ taken = { token: params.get("t"), next: appRelativePath(params.get("next")) ?? "/" };
11
+ win.history.replaceState(win.history.state, "", win.location.pathname + win.location.search);
12
+ }
13
+ return taken;
14
+ }
15
+ function forgetWebHandoffFragment() {
16
+ taken = null;
17
+ }
18
+ var redeeming = /* @__PURE__ */ new WeakMap();
19
+ function completeWebHandoff(options) {
20
+ const { fragment } = options;
21
+ if (!fragment) return claim(options);
22
+ let pending = redeeming.get(fragment);
23
+ if (!pending) {
24
+ pending = claim(options);
25
+ redeeming.set(fragment, pending);
26
+ }
27
+ return pending;
28
+ }
29
+ async function claim(options) {
30
+ const { supabase, fragment, redeemEndpoint = "/api/auth/redeem-handoff" } = options;
31
+ const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
32
+ const fallback = fragment?.next ?? "/";
33
+ if (!fragment?.token) return { kind: "failed", reason: "missing", next: fallback };
34
+ const post = async (body, bearer) => {
35
+ const response = await doFetch(redeemEndpoint, {
36
+ method: "POST",
37
+ headers: { "content-type": "application/json", ...bearer ? { authorization: `Bearer ${bearer}` } : {} },
38
+ body: JSON.stringify(body),
39
+ credentials: "omit",
40
+ referrerPolicy: "no-referrer",
41
+ cache: "no-store"
42
+ });
43
+ return await response.json();
44
+ };
45
+ const { data } = await supabase.auth.getSession();
46
+ let current = data.session?.user ?? null;
47
+ if (current) {
48
+ const checked = await supabase.auth.getUser();
49
+ if (checked.error || !checked.data.user || checked.data.user.id !== current.id) {
50
+ await supabase.auth.signOut({ scope: "local" });
51
+ current = null;
52
+ }
53
+ }
54
+ let outcome;
55
+ try {
56
+ outcome = await post({ action: "claim", t: fragment.token, currentUserId: current?.id ?? null });
57
+ } catch {
58
+ return { kind: "failed", reason: "unavailable", next: fallback };
59
+ }
60
+ const next = appRelativePath(outcome.next) ?? fallback;
61
+ if (outcome.status === "same_user") return { kind: "done", next };
62
+ if (outcome.status === "expired") return { kind: "failed", reason: "expired", next: fallback };
63
+ if (outcome.status !== "confirm" || !outcome.continueNonce || !outcome.email) {
64
+ return { kind: "failed", reason: "unavailable", next: fallback };
65
+ }
66
+ const { continueNonce: nonce, email } = outcome;
67
+ let running = null;
68
+ const once = (step) => running ??= step();
69
+ return {
70
+ kind: "confirm",
71
+ email,
72
+ next,
73
+ signedInAs: current?.email ?? (current ? current.id : null),
74
+ continue: () => once(async () => {
75
+ let minted;
76
+ try {
77
+ minted = await post({ action: "continue", nonce });
78
+ } catch {
79
+ return { kind: "failed", reason: "unavailable", next };
80
+ }
81
+ if (minted.status === "expired") return { kind: "failed", reason: "expired", next };
82
+ if (minted.status !== "ok" || !minted.tokenHash || !minted.userId) return { kind: "failed", reason: "unavailable", next };
83
+ if (current) await supabase.auth.signOut({ scope: "local" });
84
+ const verified = await supabase.auth.verifyOtp({ token_hash: minted.tokenHash, type: "email" });
85
+ if (verified.error || !verified.data?.user) return { kind: "failed", reason: "verify_failed", next };
86
+ if (verified.data.user.id !== minted.userId) {
87
+ await supabase.auth.signOut({ scope: "local" });
88
+ return { kind: "failed", reason: "wrong_user", next };
89
+ }
90
+ const accessToken = verified.data.session?.access_token ?? (await supabase.auth.getSession()).data.session?.access_token;
91
+ if (accessToken) await post({ action: "bind", nonce }, accessToken).catch(() => void 0);
92
+ return { kind: "done", next: appRelativePath(minted.next) ?? next };
93
+ }),
94
+ cancel: () => once(async () => {
95
+ await post({ action: "discard", nonce }).catch(() => void 0);
96
+ if (current) await supabase.auth.signOut({ scope: "local" });
97
+ return { kind: "cancelled", next, signedOut: current !== null };
98
+ })
99
+ };
100
+ }
101
+
102
+ export { completeWebHandoff, forgetWebHandoffFragment, takeWebHandoffFragment };
103
+ //# sourceMappingURL=web-handoff.js.map
104
+ //# sourceMappingURL=web-handoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web-handoff.ts"],"names":[],"mappings":";;;;AAqCA,IAAI,KAAA,GAAmC,IAAA;AAUhC,SAAS,sBAAA,CACd,MAAwD,UAAA,EAC7B;AAC3B,EAAA,MAAM,IAAA,GAAO,IAAI,QAAA,CAAS,IAAA;AAC1B,EAAA,IAAI,IAAA,CAAK,SAAS,CAAA,EAAG;AACnB,IAAA,MAAM,SAAS,IAAI,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAChD,IAAA,KAAA,GAAQ,EAAE,KAAA,EAAO,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG,IAAA,EAAM,eAAA,CAAgB,MAAA,CAAO,GAAA,CAAI,MAAM,CAAC,KAAK,GAAA,EAAI;AACnF,IAAA,GAAA,CAAI,OAAA,CAAQ,YAAA,CAAa,GAAA,CAAI,OAAA,CAAQ,KAAA,EAAO,EAAA,EAAI,GAAA,CAAI,QAAA,CAAS,QAAA,GAAW,GAAA,CAAI,QAAA,CAAS,MAAM,CAAA;AAAA,EAC7F;AACA,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,wBAAA,GAAiC;AAC/C,EAAA,KAAA,GAAQ,IAAA;AACV;AAsDA,IAAM,SAAA,uBAAgB,OAAA,EAAqD;AAUpE,SAAS,mBAAmB,OAAA,EAA6D;AAC9F,EAAA,MAAM,EAAE,UAAS,GAAI,OAAA;AACrB,EAAA,IAAI,CAAC,QAAA,EAAU,OAAO,KAAA,CAAM,OAAO,CAAA;AACnC,EAAA,IAAI,OAAA,GAAU,SAAA,CAAU,GAAA,CAAI,QAAQ,CAAA;AACpC,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA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already signed in\" (the server half is `/web-handoff/server`). Browser code, no React.\n *\n * ```ts\n * // As early as the page's code runs, before analytics or error reporting load:\n * const fragment = takeWebHandoffFragment();\n * // In the page:\n * const step = await completeWebHandoff({ supabase, fragment });\n * if (step.kind === \"confirm\") showChoice(`Continue as ${step.email}?`, () => step.continue());\n * if (step.kind === \"done\") navigate(step.next);\n * ```\n *\n * @packageDocumentation\n */\nimport { appRelativePath } from \"./web-handoff-path\";\n\nexport { appRelativePath } from \"./web-handoff-path\";\n\n/** What the handoff link carried in its fragment. */\nexport interface WebHandoffFragment {\n /** The single-use handoff token, or null when the link had none. */\n token: string | null;\n /** Where to land, already checked with {@link appRelativePath}; `/` when missing or unsafe. */\n next: string;\n}\n\ninterface LocationLike {\n hash: string;\n pathname: string;\n search: string;\n}\ninterface HistoryLike {\n state: unknown;\n replaceState(data: unknown, unused: string, url?: string | null): void;\n}\n\nlet taken: WebHandoffFragment | null = null;\n\n/**\n * Read the handoff link's fragment (`#t=<token>&next=<path>`) and remove it from the address bar\n * and history at once (`history.replaceState`), so the token isn't left in history, a bookmark,\n * a screenshot of the address bar, or the URL an analytics or error script records. Call it\n * before those scripts load. Later calls return what the first call read.\n *\n * @stability Beta\n */\nexport function takeWebHandoffFragment(\n win: { location: LocationLike; history: HistoryLike } = globalThis as unknown as { location: LocationLike; history: HistoryLike },\n): WebHandoffFragment | null {\n const hash = win.location.hash;\n if (hash.length > 1) {\n const params = new URLSearchParams(hash.slice(1));\n taken = { token: params.get(\"t\"), next: appRelativePath(params.get(\"next\")) ?? \"/\" };\n win.history.replaceState(win.history.state, \"\", win.location.pathname + win.location.search);\n }\n return taken;\n}\n\n/** Forget a fragment {@link takeWebHandoffFragment} read (tests, or after the handoff finished). */\nexport function forgetWebHandoffFragment(): void {\n taken = null;\n}\n\n/** The parts of a browser Supabase client the handoff uses. */\nexport interface WebHandoffAuthClient {\n auth: {\n getSession(): PromiseLike<{\n data: { session: { access_token?: string; user: { id: string; email?: string | null } } | null };\n }>;\n getUser(): PromiseLike<{ data: { user: { id: string; email?: string | null } | null }; error: unknown }>;\n signOut(options: { scope: \"local\" }): PromiseLike<{ error: unknown }>;\n verifyOtp(params: { token_hash: string; type: \"email\" }): PromiseLike<{\n data: { user: { id: string } | null; session?: { access_token: string } | null } | null;\n error: { message: string } | null;\n }>;\n };\n}\n\nexport type WebHandoffFailure = \"missing\" | \"expired\" | \"unavailable\" | \"verify_failed\" | \"wrong_user\";\n\nexport type WebHandoffStep =\n /** Signed in as the right person: go to `next`. */\n | { kind: \"done\"; next: string }\n /**\n * Ask before signing in: \"Continue as {email}?\". Shown whenever the browser isn't already\n * signed in as this person (nobody, or someone else), so a link someone else minted for their\n * own account can't sign you in to it unnoticed. Nothing that signs anyone in exists until\n * `continue()`: it spends the continue nonce (30 seconds, once), and only then does the server\n * mint Supabase's token, which is exchanged at once. `cancel()` burns the nonce.\n */\n | {\n kind: \"confirm\";\n email: string;\n next: string;\n signedInAs: string | null;\n continue(): Promise<WebHandoffStep>;\n cancel(): Promise<WebHandoffStep>;\n }\n /**\n * The person chose Cancel. Whoever else was signed in here has been signed out locally, so the\n * page never leaves someone in the app as another person: show \"You can close this window\".\n */\n | { kind: \"cancelled\"; next: string; signedOut: boolean }\n | { kind: \"failed\"; reason: WebHandoffFailure; next: string };\n\n/** @stability Beta */\nexport interface CompleteWebHandoffOptions {\n supabase: WebHandoffAuthClient;\n /** From {@link takeWebHandoffFragment}. */\n fragment: WebHandoffFragment | null;\n /** The redeem route. Default `/api/auth/redeem-handoff`. */\n redeemEndpoint?: string;\n fetch?: typeof fetch;\n}\n\nconst redeeming = new WeakMap<WebHandoffFragment, Promise<WebHandoffStep>>();\n\n/**\n * Claim the handoff and say what the page shows next. Never signs anyone in or out by itself:\n * a `confirm` step does that only when the person chooses `continue()` or `cancel()`. A fragment\n * is claimed once: calling again with the same fragment (React's development double effects)\n * returns the same promise.\n *\n * @stability Beta\n */\nexport function completeWebHandoff(options: CompleteWebHandoffOptions): Promise<WebHandoffStep> {\n const { fragment } = options;\n if (!fragment) return claim(options);\n let pending = redeeming.get(fragment);\n if (!pending) {\n pending = claim(options);\n redeeming.set(fragment, pending);\n }\n return pending;\n}\n\ntype Outcome = { status?: string; next?: string; email?: string; userId?: string; tokenHash?: string; continueNonce?: string };\n\nasync function claim(options: CompleteWebHandoffOptions): Promise<WebHandoffStep> {\n const { supabase, fragment, redeemEndpoint = \"/api/auth/redeem-handoff\" } = options;\n const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n const fallback = fragment?.next ?? \"/\";\n if (!fragment?.token) return { kind: \"failed\", reason: \"missing\", next: fallback };\n\n const post = async (body: Record<string, unknown>, bearer?: string): Promise<Outcome> => {\n const response = await doFetch(redeemEndpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },\n body: JSON.stringify(body),\n credentials: \"omit\",\n referrerPolicy: \"no-referrer\",\n cache: \"no-store\",\n });\n return (await response.json()) as Outcome;\n };\n\n // Who is signed in here, checked with Supabase Auth (getUser), not just read from storage: a\n // session ended elsewhere (the app signed out) still has a stored token until it expires.\n // Such a stale session is cleared here, so it is never mistaken for, or left behind as, a person.\n const { data } = await supabase.auth.getSession();\n let current = data.session?.user ?? null;\n if (current) {\n const checked = await supabase.auth.getUser();\n if (checked.error || !checked.data.user || checked.data.user.id !== current.id) {\n await supabase.auth.signOut({ scope: \"local\" });\n current = null;\n }\n }\n\n let outcome: Outcome;\n try {\n outcome = await post({ action: \"claim\", t: fragment.token, currentUserId: current?.id ?? null });\n } catch {\n return { kind: \"failed\", reason: \"unavailable\", next: fallback };\n }\n const next = appRelativePath(outcome.next) ?? fallback;\n if (outcome.status === \"same_user\") return { kind: \"done\", next };\n if (outcome.status === \"expired\") return { kind: \"failed\", reason: \"expired\", next: fallback };\n if (outcome.status !== \"confirm\" || !outcome.continueNonce || !outcome.email) {\n return { kind: \"failed\", reason: \"unavailable\", next: fallback };\n }\n\n const { continueNonce: nonce, email } = outcome;\n let running: Promise<WebHandoffStep> | null = null;\n const once = (step: () => Promise<WebHandoffStep>) => (running ??= step());\n\n return {\n kind: \"confirm\",\n email,\n next,\n signedInAs: current?.email ?? (current ? current.id : null),\n continue: () =>\n once(async () => {\n let minted: Outcome;\n try {\n minted = await post({ action: \"continue\", nonce });\n } catch {\n return { kind: \"failed\", reason: \"unavailable\", next };\n }\n if (minted.status === \"expired\") return { kind: \"failed\", reason: \"expired\", next };\n if (minted.status !== \"ok\" || !minted.tokenHash || !minted.userId) return { kind: \"failed\", reason: \"unavailable\", next };\n // Signed out first, so a failed exchange leaves nobody signed in rather than a mix.\n if (current) await supabase.auth.signOut({ scope: \"local\" });\n const verified = await supabase.auth.verifyOtp({ token_hash: minted.tokenHash, type: \"email\" });\n if (verified.error || !verified.data?.user) return { kind: \"failed\", reason: \"verify_failed\", next };\n if (verified.data.user.id !== minted.userId) {\n await supabase.auth.signOut({ scope: \"local\" });\n return { kind: \"failed\", reason: \"wrong_user\", next };\n }\n // Tell the server which session this is, so signing out of the app ends it. Best effort.\n const accessToken = verified.data.session?.access_token ?? (await supabase.auth.getSession()).data.session?.access_token;\n if (accessToken) await post({ action: \"bind\", nonce }, accessToken).catch(() => undefined);\n return { kind: \"done\", next: appRelativePath(minted.next) ?? next };\n }),\n cancel: () =>\n once(async () => {\n await post({ action: \"discard\", nonce }).catch(() => undefined);\n // Never leave the page signed in as someone other than the link's person.\n if (current) await supabase.auth.signOut({ scope: \"local\" });\n return { kind: \"cancelled\", next, signedOut: current !== null };\n }),\n };\n}\n"]}
@@ -0,0 +1,89 @@
1
+ -- Genesis owner access: private.genesis_owner_readable() and private.genesis_owner_allows()
2
+ --
3
+ -- The owner-access contract, shared by every Genesis block whose rows have an owner (genesis-work's
4
+ -- goals, projects, tasks, issues, metrics, status updates and sessions). A row belongs to a tenant
5
+ -- and has exactly one owner: a person, a team or the tenant itself. Who may read and write it is
6
+ -- your app's answer, through two hooks. Genesis never defines them:
7
+ --
8
+ -- private.genesis_owner_can(tenant uuid, viewer uuid, person_id uuid, team_id uuid,
9
+ -- organization_id uuid, action text) returns boolean
10
+ -- action is 'read' or 'write'.
11
+ -- private.genesis_readable_owners(viewer uuid) returns table (tenant_id uuid, owner_id uuid)
12
+ -- Every (tenant, owner) pair the viewer may read, across tenants, so a policy checks once per
13
+ -- statement instead of calling a function per row. owner_id is the row's person_id, team_id
14
+ -- or organization_id, whichever is set.
15
+ --
16
+ -- Both run with your migration's (the owner's) rights, so they read your membership tables
17
+ -- whatever their row security. For example:
18
+ --
19
+ -- create function private.genesis_readable_owners(viewer uuid)
20
+ -- returns table (tenant_id uuid, owner_id uuid) language sql stable set search_path = '' as $$
21
+ -- select m.team_id, m.user_id from public.memberships m where m.user_id = viewer -- my own rows
22
+ -- union all
23
+ -- select m.team_id, m.team_id from public.memberships m where m.user_id = viewer -- my team's rows
24
+ -- $$;
25
+ -- revoke execute on function private.genesis_readable_owners(uuid) from public, anon, authenticated;
26
+ --
27
+ -- This file ships the two wrappers that blocks call in their policies. They fail closed: a missing
28
+ -- hook, a hook that errors or returns the wrong type, no signed-in person, a null tenant, or an
29
+ -- action other than 'read' or 'write' gives false or an empty set.
30
+ --
31
+ -- private.genesis_owner_readable() returns table (tenant_id uuid, owner_id uuid)
32
+ -- The signed-in person's set, from genesis_readable_owners(auth.uid()).
33
+ -- private.genesis_owner_allows(tenant uuid, person_id uuid, team_id uuid, organization_id uuid,
34
+ -- action text) returns boolean
35
+ -- genesis_owner_can(tenant, auth.uid(), person_id, team_id, organization_id, action).
36
+ --
37
+ -- Both are security definer with search_path ''. Row security runs as the caller, so authenticated
38
+ -- may execute them; they only ever answer for auth.uid(). anon and public may not.
39
+ --
40
+ -- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
41
+ -- (`genesis migrate` does it). Never edit it once applied; change it with a new migration.
42
+ --
43
+ -- Verify: the pgTAP test beside this file (`tests/0009_genesis_owner_access.test.sql`).
44
+
45
+ create schema if not exists private;
46
+
47
+ create or replace function private.genesis_owner_readable()
48
+ returns table (tenant_id uuid, owner_id uuid)
49
+ language plpgsql
50
+ stable
51
+ security definer
52
+ set search_path = ''
53
+ as $$
54
+ begin
55
+ if auth.uid() is null or to_regprocedure('private.genesis_readable_owners(uuid)') is null then
56
+ return;
57
+ end if;
58
+ return query execute 'select r.tenant_id::uuid, r.owner_id::uuid from private.genesis_readable_owners($1) r' using auth.uid();
59
+ exception when others then
60
+ return;
61
+ end;
62
+ $$;
63
+
64
+ create or replace function private.genesis_owner_allows(tenant uuid, person_id uuid, team_id uuid, organization_id uuid, action text)
65
+ returns boolean
66
+ language plpgsql
67
+ stable
68
+ security definer
69
+ set search_path = ''
70
+ as $$
71
+ declare
72
+ allowed boolean;
73
+ begin
74
+ if auth.uid() is null or tenant is null or action is null or action not in ('read', 'write')
75
+ or to_regprocedure('private.genesis_owner_can(uuid,uuid,uuid,uuid,uuid,text)') is null then
76
+ return false;
77
+ end if;
78
+ execute 'select (private.genesis_owner_can($1, $2, $3, $4, $5, $6))::boolean'
79
+ into allowed using tenant, auth.uid(), person_id, team_id, organization_id, action;
80
+ return coalesce(allowed, false);
81
+ exception when others then
82
+ return false;
83
+ end;
84
+ $$;
85
+
86
+ revoke execute on function private.genesis_owner_readable() from public, anon, authenticated;
87
+ revoke execute on function private.genesis_owner_allows(uuid, uuid, uuid, uuid, text) from public, anon, authenticated;
88
+ grant execute on function private.genesis_owner_readable() to authenticated;
89
+ grant execute on function private.genesis_owner_allows(uuid, uuid, uuid, uuid, text) to authenticated;
@@ -0,0 +1,124 @@
1
+ -- Genesis feature registry, hardened (0008, shipped in genesis-supabase 0.6.0, changed here).
2
+ --
3
+ -- 1. Who is asking. Server code is now told apart from a person by the request's role
4
+ -- (`current_setting('role')`, which PostgREST sets per request with SET LOCAL ROLE), not by
5
+ -- request.jwt.claims, which a session can set for itself. A role that bypasses row security
6
+ -- (service_role, postgres) is server code, and so is a connection that never switched role
7
+ -- (`none`, as in migrations). Anything else, `authenticated` included, must be a member of the
8
+ -- tenant. Before, a session that switched to
9
+ -- `authenticated` without setting claims was treated as server code.
10
+ -- 2. feature_shipped(feature) answers a signed-in person only for customer-facing features
11
+ -- (visibility customer or public): an internal feature's id can no longer be confirmed by
12
+ -- guessing it. Server code still gets every feature.
13
+ -- 3. A flag that leaves the registry loses its platform_value, so a forgotten kill switch can't
14
+ -- come back with the flag. Its tenant values stay, as before.
15
+ -- 4. feature_entitlements gets an index on (feature_id) for active rows, for
16
+ -- feature_entitled_tenants and feature_on.
17
+ --
18
+ -- Needs 0004 and 0008. Verify: tests/0014_genesis_feature_registry_hardening.test.sql.
19
+
20
+ create index if not exists feature_entitlements_feature_active on public.feature_entitlements (feature_id) where active;
21
+
22
+ create or replace function private.genesis_feature_caller_is_server()
23
+ returns boolean
24
+ language plpgsql
25
+ stable
26
+ security definer
27
+ set search_path = ''
28
+ as $$
29
+ declare
30
+ request_role text := coalesce(nullif(current_setting('role', true), ''), 'none');
31
+ begin
32
+ -- No role switch (a direct connection, a migration), or a role that bypasses row security
33
+ -- (service_role, postgres): server code. authenticated and anon never bypass it.
34
+ return request_role = 'none'
35
+ or coalesce((select r.rolbypassrls from pg_catalog.pg_roles r where r.rolname = request_role), false);
36
+ end;
37
+ $$;
38
+
39
+ revoke execute on function private.genesis_feature_caller_is_server() from public, anon, authenticated;
40
+
41
+ create or replace function public.feature_shipped(feature text)
42
+ returns boolean
43
+ language sql
44
+ stable
45
+ security definer
46
+ set search_path = ''
47
+ as $$
48
+ select exists (
49
+ select 1 from public.features f
50
+ where f.id = feature and f.in_registry and f.status in ('beta', 'live', 'deprecated')
51
+ and (f.visibility in ('customer', 'public') or private.genesis_feature_caller_is_server())
52
+ )
53
+ $$;
54
+
55
+ create or replace function public.sync_feature_registry(version bigint, hash text, features jsonb, flags jsonb, allow_shrink boolean default false)
56
+ returns boolean
57
+ language plpgsql
58
+ security definer
59
+ set search_path = ''
60
+ as $$
61
+ declare
62
+ current_count int;
63
+ gone_count int;
64
+ begin
65
+ if version is null or hash is null
66
+ or jsonb_typeof(features) is distinct from 'array' or jsonb_typeof(flags) is distinct from 'array' then
67
+ raise exception 'sync_feature_registry: needs a version, a hash and two arrays' using errcode = '22023';
68
+ end if;
69
+ if exists (select 1 from jsonb_array_elements(features) r where coalesce(r ->> 'id', '') = '')
70
+ or jsonb_array_length(features) <> (select count(distinct r ->> 'id') from jsonb_array_elements(features) r) then
71
+ raise exception 'sync_feature_registry: every feature needs a unique id' using errcode = '22023';
72
+ end if;
73
+ if exists (select 1 from jsonb_array_elements(flags) r where coalesce(r ->> 'key', '') = '')
74
+ or jsonb_array_length(flags) <> (select count(distinct r ->> 'key') from jsonb_array_elements(flags) r) then
75
+ raise exception 'sync_feature_registry: every flag needs a unique key' using errcode = '22023';
76
+ end if;
77
+ -- One sync at a time: a second deploy waits, then finds itself already current.
78
+ perform pg_advisory_xact_lock(hashtext('public.sync_feature_registry'));
79
+ -- Never backwards, and nothing to do for the same registry.
80
+ if exists (select 1 from private.feature_registry_state s where s.version > sync_feature_registry.version or s.hash = sync_feature_registry.hash) then
81
+ return false;
82
+ end if;
83
+ -- A broken or foreign registry must not switch everything off.
84
+ select count(*) into current_count from public.features f where f.in_registry;
85
+ select count(*) into gone_count from public.features f
86
+ where f.in_registry and not exists (select 1 from jsonb_array_elements(features) r where r ->> 'id' = f.id);
87
+ if not coalesce(allow_shrink, false) and (jsonb_array_length(features) = 0 or (gone_count >= 3 and gone_count * 5 > current_count)) then
88
+ raise exception 'sync_feature_registry: this registry drops % of % features', gone_count, current_count
89
+ using errcode = '22023', hint = 'Check features.json; if the removal is intended, call again with allow_shrink => true.';
90
+ end if;
91
+
92
+ insert into public.features as f (id, name, status, visibility, access_plan, platforms, record, in_registry, synced_at)
93
+ select r ->> 'id', r ->> 'name', r ->> 'status', coalesce(r ->> 'visibility', 'customer'),
94
+ case when jsonb_typeof(r -> 'access') = 'object' then nullif(btrim(r -> 'access' ->> 'plan'), '') end,
95
+ case when jsonb_typeof(r -> 'platforms') = 'object' then r -> 'platforms' end,
96
+ r, true, now()
97
+ from jsonb_array_elements(features) r
98
+ on conflict (id) do update set
99
+ name = excluded.name, status = excluded.status, visibility = excluded.visibility, access_plan = excluded.access_plan,
100
+ platforms = excluded.platforms, record = excluded.record, in_registry = true, synced_at = excluded.synced_at;
101
+
102
+ -- Ids are permanent: a feature the registry no longer lists stays, marked as gone.
103
+ update public.features f set in_registry = false, synced_at = now()
104
+ where f.in_registry and not exists (select 1 from jsonb_array_elements(features) r where r ->> 'id' = f.id);
105
+
106
+ update public.feature_flags fl set in_registry = false, platform_value = null, synced_at = now()
107
+ where fl.in_registry and not exists (select 1 from jsonb_array_elements(flags) r where r ->> 'key' = fl.key);
108
+ insert into public.feature_flags as fl (key, feature_id, kind, default_value, scopes, expires, record, in_registry, synced_at)
109
+ select r ->> 'key', r ->> 'feature', r ->> 'kind', coalesce(r -> 'default', 'false'::jsonb),
110
+ coalesce(array(select jsonb_array_elements_text(r -> 'scopes')), '{}'),
111
+ (r ->> 'expires')::date, r, true, now()
112
+ from jsonb_array_elements(flags) r
113
+ on conflict (key) do update set
114
+ feature_id = excluded.feature_id, kind = excluded.kind, default_value = excluded.default_value,
115
+ scopes = excluded.scopes, expires = excluded.expires, record = excluded.record, in_registry = true,
116
+ synced_at = excluded.synced_at;
117
+
118
+ insert into private.feature_registry_state (id, version, hash, synced_at)
119
+ values (true, sync_feature_registry.version, sync_feature_registry.hash, now())
120
+ on conflict (id) do update set version = excluded.version, hash = excluded.hash, synced_at = excluded.synced_at;
121
+ return true;
122
+ end;
123
+ $$;
124
+