@marktiderman/genesis-supabase 0.7.0 → 0.9.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.
@@ -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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IAAA,EAAK;AAAA,IAChE,CAAC;AAAA,GACL;AACF","file":"web-handoff.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/web-handoff`: the web page half of \"continue on the web,\n * 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,270 @@
1
+ -- Genesis web handoff: continue on the web, already signed in
2
+ --
3
+ -- The database half of `@marktiderman/genesis-supabase/web-handoff/server`. A native app asks
4
+ -- the server for a link to a web page; the link opens that page signed in as the same person.
5
+ -- Each link is a row in private.genesis_web_handoffs, which keeps SHA-256 digests only, never a
6
+ -- token, so a copy of the table signs nobody in. A row moves through:
7
+ --
8
+ -- issued the app asked (genesis_web_handoff_issue): person, path, a 60-second expiry, the
9
+ -- app session it came from. At most `max` a person per window (SQLSTATE GS429),
10
+ -- counted under a per-person lock.
11
+ -- claimed the page opened it (genesis_web_handoff_claim), once and unexpired, and got a
12
+ -- continue nonce that lives 30 seconds. Nothing that signs anyone in exists yet.
13
+ -- continued the person chose Continue (genesis_web_handoff_continue), once, within the
14
+ -- nonce's life; only now does the server ask Supabase Auth for a sign-in token.
15
+ -- discarded the person chose Cancel (genesis_web_handoff_discard): the nonce is burnt.
16
+ -- bound the page reported the session it made (genesis_web_handoff_bind_session), so
17
+ -- signing out of the app can end exactly that web session
18
+ -- (genesis_web_handoff_revoke_sessions, which deletes those auth.sessions rows:
19
+ -- Supabase documents a session as signed out when its row is gone; its access
20
+ -- token still works until it expires).
21
+ --
22
+ -- Rows are also the log of handoffs (who, which path, when), kept 30 days, or longer while the
23
+ -- web session they made still exists.
24
+ --
25
+ -- Access: only service_role, through the functions below, granted by name. anon and
26
+ -- authenticated reach nothing: the table is in `private`, has row level security with no
27
+ -- policies, and every function also refuses any role but service_role
28
+ -- (`current_setting('role')`, which is what PostgREST set, not a JWT claim).
29
+ --
30
+ -- Account deletion: a person's handoffs go with their login (on delete cascade).
31
+ --
32
+ -- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name.
33
+ -- Never edit it once applied; change it with a new migration. It stands alone.
34
+ --
35
+ -- Verify: the pgTAP test beside this file (`tests/0015_genesis_web_handoff.test.sql`).
36
+
37
+ create schema if not exists private;
38
+
39
+ create table private.genesis_web_handoffs (
40
+ id uuid primary key default gen_random_uuid(),
41
+ user_id uuid not null references auth.users (id) on delete cascade,
42
+ token_digest text not null unique check (token_digest ~ '^[0-9a-f]{64}$'),
43
+ path text not null check (char_length(path) between 1 and 2048 and left(path, 1) = '/' and left(path, 2) <> '//'),
44
+ created_at timestamptz not null default now(),
45
+ expires_at timestamptz not null,
46
+ used_at timestamptz,
47
+ source_session_id uuid,
48
+ nonce_digest text unique check (nonce_digest ~ '^[0-9a-f]{64}$'),
49
+ nonce_expires_at timestamptz,
50
+ continued_at timestamptz,
51
+ discarded_at timestamptz,
52
+ web_session_id uuid,
53
+ check (expires_at > created_at)
54
+ );
55
+
56
+ comment on table private.genesis_web_handoffs is
57
+ 'Native-to-web sign-in handoffs (genesis-supabase web-handoff): digests, never tokens. Service role only.';
58
+
59
+ create index genesis_web_handoffs_user_recent on private.genesis_web_handoffs (user_id, created_at desc);
60
+ create index genesis_web_handoffs_created on private.genesis_web_handoffs (created_at);
61
+ create index genesis_web_handoffs_source on private.genesis_web_handoffs (user_id, source_session_id) where web_session_id is not null;
62
+
63
+ alter table private.genesis_web_handoffs enable row level security;
64
+ revoke all on table private.genesis_web_handoffs from public, anon, authenticated;
65
+
66
+ -- Issue ------------------------------------------------------------------------------
67
+
68
+ create or replace function public.genesis_web_handoff_issue(
69
+ p_user_id uuid,
70
+ p_digest text,
71
+ p_path text,
72
+ p_ttl_seconds integer default 60,
73
+ p_max integer default 10,
74
+ p_window_seconds integer default 60,
75
+ p_source_session_id uuid default null
76
+ )
77
+ returns timestamptz
78
+ language plpgsql
79
+ volatile
80
+ security definer
81
+ set search_path = ''
82
+ as $$
83
+ declare
84
+ recent integer;
85
+ expires timestamptz;
86
+ begin
87
+ if coalesce(nullif(current_setting('role', true), ''), 'none') <> 'service_role' then
88
+ raise exception 'genesis_web_handoff_issue is for the server only' using errcode = '42501';
89
+ end if;
90
+ if p_ttl_seconds is null or p_ttl_seconds not between 10 and 300 then
91
+ raise exception 'p_ttl_seconds must be from 10 to 300' using errcode = '22023';
92
+ end if;
93
+ if p_max is null or p_max < 1 or p_window_seconds is null or p_window_seconds < 1 then
94
+ raise exception 'p_max and p_window_seconds must be positive' using errcode = '22023';
95
+ end if;
96
+
97
+ -- One person's issues one at a time, so the count below can't be raced.
98
+ perform pg_advisory_xact_lock(hashtextextended('genesis_web_handoff:' || p_user_id::text, 0));
99
+
100
+ select count(*) into recent
101
+ from private.genesis_web_handoffs h
102
+ where h.user_id = p_user_id and h.created_at > now() - make_interval(secs => p_window_seconds);
103
+ if recent >= p_max then
104
+ raise exception 'too many web handoffs; try again in a minute' using errcode = 'GS429';
105
+ end if;
106
+
107
+ expires := now() + make_interval(secs => p_ttl_seconds);
108
+ insert into private.genesis_web_handoffs (user_id, token_digest, path, expires_at, source_session_id)
109
+ values (p_user_id, p_digest, p_path, expires, p_source_session_id);
110
+
111
+ -- The log keeps 30 days, and a row whose web session still exists until that session goes.
112
+ delete from private.genesis_web_handoffs h
113
+ where h.created_at < now() - interval '30 days'
114
+ and (h.web_session_id is null or not exists (select 1 from auth.sessions s where s.id = h.web_session_id));
115
+ return expires;
116
+ end;
117
+ $$;
118
+
119
+ revoke execute on function public.genesis_web_handoff_issue(uuid, text, text, integer, integer, integer, uuid) from public, anon, authenticated;
120
+ grant execute on function public.genesis_web_handoff_issue(uuid, text, text, integer, integer, integer, uuid) to service_role;
121
+
122
+ -- Claim: the page opened the link. Once, unexpired; hands out a short-lived continue nonce.
123
+
124
+ create or replace function public.genesis_web_handoff_claim(
125
+ p_digest text,
126
+ p_nonce_digest text,
127
+ p_nonce_ttl_seconds integer default 30
128
+ )
129
+ returns table (user_id uuid, path text)
130
+ language plpgsql
131
+ volatile
132
+ security definer
133
+ set search_path = ''
134
+ as $$
135
+ begin
136
+ if coalesce(nullif(current_setting('role', true), ''), 'none') <> 'service_role' then
137
+ raise exception 'genesis_web_handoff_claim is for the server only' using errcode = '42501';
138
+ end if;
139
+ if p_nonce_ttl_seconds is null or p_nonce_ttl_seconds not between 5 and 120 then
140
+ raise exception 'p_nonce_ttl_seconds must be from 5 to 120' using errcode = '22023';
141
+ end if;
142
+ return query
143
+ update private.genesis_web_handoffs h
144
+ set used_at = now(), nonce_digest = p_nonce_digest, nonce_expires_at = now() + make_interval(secs => p_nonce_ttl_seconds)
145
+ where h.token_digest = p_digest and h.used_at is null and h.expires_at > now()
146
+ returning h.user_id, h.path;
147
+ end;
148
+ $$;
149
+
150
+ revoke execute on function public.genesis_web_handoff_claim(text, text, integer) from public, anon, authenticated;
151
+ grant execute on function public.genesis_web_handoff_claim(text, text, integer) to service_role;
152
+
153
+ -- Continue: the person chose Continue. Once, within the nonce's life, not after Cancel.
154
+
155
+ create or replace function public.genesis_web_handoff_continue(p_nonce_digest text)
156
+ returns table (user_id uuid, path text)
157
+ language plpgsql
158
+ volatile
159
+ security definer
160
+ set search_path = ''
161
+ as $$
162
+ begin
163
+ if coalesce(nullif(current_setting('role', true), ''), 'none') <> 'service_role' then
164
+ raise exception 'genesis_web_handoff_continue is for the server only' using errcode = '42501';
165
+ end if;
166
+ return query
167
+ update private.genesis_web_handoffs h
168
+ set continued_at = now()
169
+ where h.nonce_digest = p_nonce_digest and h.continued_at is null and h.discarded_at is null
170
+ and h.nonce_expires_at > now()
171
+ returning h.user_id, h.path;
172
+ end;
173
+ $$;
174
+
175
+ revoke execute on function public.genesis_web_handoff_continue(text) from public, anon, authenticated;
176
+ grant execute on function public.genesis_web_handoff_continue(text) to service_role;
177
+
178
+ -- Discard: the person chose Cancel. Burns the nonce, so Continue is refused afterwards.
179
+
180
+ create or replace function public.genesis_web_handoff_discard(p_nonce_digest text)
181
+ returns boolean
182
+ language plpgsql
183
+ volatile
184
+ security definer
185
+ set search_path = ''
186
+ as $$
187
+ begin
188
+ if coalesce(nullif(current_setting('role', true), ''), 'none') <> 'service_role' then
189
+ raise exception 'genesis_web_handoff_discard is for the server only' using errcode = '42501';
190
+ end if;
191
+ update private.genesis_web_handoffs h
192
+ set discarded_at = now()
193
+ where h.nonce_digest = p_nonce_digest and h.continued_at is null and h.discarded_at is null;
194
+ return found;
195
+ end;
196
+ $$;
197
+
198
+ revoke execute on function public.genesis_web_handoff_discard(text) from public, anon, authenticated;
199
+ grant execute on function public.genesis_web_handoff_discard(text) to service_role;
200
+
201
+ -- Bind: the page reports the session Continue made (its id from the verified access token),
202
+ -- once, within two minutes of Continue, for the handoff's own person.
203
+
204
+ create or replace function public.genesis_web_handoff_bind_session(p_nonce_digest text, p_user_id uuid, p_session_id uuid)
205
+ returns boolean
206
+ language plpgsql
207
+ volatile
208
+ security definer
209
+ set search_path = ''
210
+ as $$
211
+ begin
212
+ if coalesce(nullif(current_setting('role', true), ''), 'none') <> 'service_role' then
213
+ raise exception 'genesis_web_handoff_bind_session is for the server only' using errcode = '42501';
214
+ end if;
215
+ update private.genesis_web_handoffs h
216
+ set web_session_id = p_session_id
217
+ where h.nonce_digest = p_nonce_digest and h.user_id = p_user_id and h.web_session_id is null
218
+ and h.continued_at > now() - interval '2 minutes'
219
+ and h.source_session_id is distinct from p_session_id;
220
+ return found;
221
+ end;
222
+ $$;
223
+
224
+ revoke execute on function public.genesis_web_handoff_bind_session(text, uuid, uuid) from public, anon, authenticated;
225
+ grant execute on function public.genesis_web_handoff_bind_session(text, uuid, uuid) to service_role;
226
+
227
+ -- Revoke: the app signs out. Ends exactly the web sessions handed off from that app session
228
+ -- (never the person's other devices), by deleting their auth.sessions rows.
229
+
230
+ create or replace function public.genesis_web_handoff_revoke_sessions(p_user_id uuid, p_source_session_id uuid)
231
+ returns integer
232
+ language plpgsql
233
+ volatile
234
+ security definer
235
+ set search_path = ''
236
+ as $$
237
+ declare
238
+ ended integer;
239
+ begin
240
+ if coalesce(nullif(current_setting('role', true), ''), 'none') <> 'service_role' then
241
+ raise exception 'genesis_web_handoff_revoke_sessions is for the server only' using errcode = '42501';
242
+ end if;
243
+ if p_user_id is null or p_source_session_id is null then
244
+ return 0;
245
+ end if;
246
+ with targets as (
247
+ select h.id, h.web_session_id
248
+ from private.genesis_web_handoffs h
249
+ where h.user_id = p_user_id and h.source_session_id = p_source_session_id
250
+ and h.web_session_id is not null and h.web_session_id <> p_source_session_id
251
+ for update
252
+ ), gone as (
253
+ delete from auth.sessions s
254
+ using targets t
255
+ where s.id = t.web_session_id and s.user_id = p_user_id
256
+ returning s.id
257
+ ), cleared as (
258
+ update private.genesis_web_handoffs h
259
+ set web_session_id = null
260
+ from targets t
261
+ where h.id = t.id
262
+ returning h.id
263
+ )
264
+ select count(*) into ended from gone;
265
+ return ended;
266
+ end;
267
+ $$;
268
+
269
+ revoke execute on function public.genesis_web_handoff_revoke_sessions(uuid, uuid) from public, anon, authenticated;
270
+ grant execute on function public.genesis_web_handoff_revoke_sessions(uuid, uuid) to service_role;
@@ -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;