@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.
- package/README.md +128 -7
- package/dist/blocks.d.ts +18 -1
- package/dist/blocks.js +1 -1
- package/dist/chunk-7SCMHKCR.js +33 -0
- package/dist/chunk-7SCMHKCR.js.map +1 -0
- package/dist/{chunk-ONBOLMXH.js → chunk-DYHH2G4A.js} +37 -3
- package/dist/chunk-DYHH2G4A.js.map +1 -0
- package/dist/chunk-XGAXPUFY.js +124 -0
- package/dist/chunk-XGAXPUFY.js.map +1 -0
- package/dist/{index-Ds0tO9WP.d.ts → index-D73YuwEY.d.ts} +4 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/jobs.d.ts +3 -1
- package/dist/jobs.js +48 -34
- package/dist/jobs.js.map +1 -1
- package/dist/native.d.ts +2 -2
- package/dist/runner.d.ts +179 -0
- package/dist/runner.js +3 -0
- package/dist/runner.js.map +1 -0
- package/dist/web-handoff-path-C_EEl_BC.d.ts +16 -0
- package/dist/web-handoff-server.d.ts +225 -0
- package/dist/web-handoff-server.js +262 -0
- package/dist/web-handoff-server.js.map +1 -0
- package/dist/web-handoff.d.ts +133 -0
- package/dist/web-handoff.js +104 -0
- package/dist/web-handoff.js.map +1 -0
- package/migrations/0009_genesis_owner_access.sql +89 -0
- package/migrations/0014_genesis_feature_registry_hardening.sql +124 -0
- package/migrations/0015_genesis_web_handoff.sql +270 -0
- package/migrations/tests/0009_genesis_owner_access.test.sql +70 -0
- package/migrations/tests/0014_genesis_feature_registry_hardening.test.sql +54 -0
- package/migrations/tests/0015_genesis_web_handoff.test.sql +203 -0
- package/package.json +88 -3
- package/dist/chunk-ONBOLMXH.js.map +0 -1
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
export { a as appRelativePath } from './web-handoff-path-C_EEl_BC.js';
|
|
2
|
+
|
|
3
|
+
/** A user as Supabase Auth returns one: the fields used here. */
|
|
4
|
+
interface HandoffUser {
|
|
5
|
+
id: string;
|
|
6
|
+
email?: string | null;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The parts of a service-role Supabase client the handoff uses. A `SupabaseClient` made with the
|
|
10
|
+
* secret key fits. Loose on purpose: a client typed by an app's Database narrows `rpc`.
|
|
11
|
+
*/
|
|
12
|
+
interface WebHandoffAdmin {
|
|
13
|
+
auth: {
|
|
14
|
+
getUser(jwt: string): PromiseLike<{
|
|
15
|
+
data: {
|
|
16
|
+
user: HandoffUser | null;
|
|
17
|
+
};
|
|
18
|
+
error: unknown;
|
|
19
|
+
}>;
|
|
20
|
+
admin: {
|
|
21
|
+
getUserById(id: string): PromiseLike<{
|
|
22
|
+
data: {
|
|
23
|
+
user: HandoffUser | null;
|
|
24
|
+
};
|
|
25
|
+
error: unknown;
|
|
26
|
+
}>;
|
|
27
|
+
generateLink(params: {
|
|
28
|
+
type: "magiclink";
|
|
29
|
+
email: string;
|
|
30
|
+
}): PromiseLike<{
|
|
31
|
+
data: {
|
|
32
|
+
properties?: {
|
|
33
|
+
hashed_token?: string | null;
|
|
34
|
+
} | null;
|
|
35
|
+
} | null;
|
|
36
|
+
error: unknown;
|
|
37
|
+
}>;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
rpc: (fn: any, ...rest: any[]) => PromiseLike<{
|
|
41
|
+
data: unknown;
|
|
42
|
+
error: {
|
|
43
|
+
message: string;
|
|
44
|
+
code?: string;
|
|
45
|
+
} | null;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
/** One line for the server log. Never carries a token, a nonce or an email. */
|
|
49
|
+
interface WebHandoffLogEvent {
|
|
50
|
+
event: "web_handoff.minted" | "web_handoff.refused" | "web_handoff.claimed" | "web_handoff.continued" | "web_handoff.discarded" | "web_handoff.signed_out";
|
|
51
|
+
userId?: string;
|
|
52
|
+
path?: string;
|
|
53
|
+
reason?: string;
|
|
54
|
+
count?: number;
|
|
55
|
+
at: string;
|
|
56
|
+
}
|
|
57
|
+
type Log = (event: WebHandoffLogEvent) => void;
|
|
58
|
+
/** @stability Beta */
|
|
59
|
+
interface WebHandoffOptions {
|
|
60
|
+
admin: WebHandoffAdmin;
|
|
61
|
+
/**
|
|
62
|
+
* The web app's origin (`https://app.example.com`), or a function of the request. Default: the
|
|
63
|
+
* mint request's own origin, so a preview deployment hands off to itself.
|
|
64
|
+
*/
|
|
65
|
+
webOrigin?: string | ((request: Request) => string);
|
|
66
|
+
/** The page that completes the handoff. Default `/auth/handoff`. */
|
|
67
|
+
pagePath?: string;
|
|
68
|
+
/** How long a link works, 10 to 300 seconds. Default 60. */
|
|
69
|
+
ttlSeconds?: number;
|
|
70
|
+
/** How long the page's Continue works after it opened the link, 5 to 120 seconds. Default 30. */
|
|
71
|
+
continueSeconds?: number;
|
|
72
|
+
/** Links one person may mint per window. Default 10 a minute. */
|
|
73
|
+
rateLimit?: {
|
|
74
|
+
max: number;
|
|
75
|
+
windowSeconds: number;
|
|
76
|
+
};
|
|
77
|
+
/** Where each step is logged (who, which path, when). Default `console.info` as JSON. */
|
|
78
|
+
log?: Log;
|
|
79
|
+
}
|
|
80
|
+
/** @stability Beta */
|
|
81
|
+
interface MintWebHandoffOptions extends Omit<WebHandoffOptions, "webOrigin" | "continueSeconds"> {
|
|
82
|
+
/** The person, already verified by the caller (a bearer token checked with `auth.getUser`). */
|
|
83
|
+
userId: string;
|
|
84
|
+
/** Where on the web app to land. Must pass {@link appRelativePath}. */
|
|
85
|
+
path: string;
|
|
86
|
+
webOrigin: string;
|
|
87
|
+
/** The app session asking (the bearer's `session_id`): signing it out later ends the web session. */
|
|
88
|
+
sourceSessionId?: string | null;
|
|
89
|
+
}
|
|
90
|
+
type MintWebHandoffResult = {
|
|
91
|
+
ok: true;
|
|
92
|
+
url: string;
|
|
93
|
+
expiresAt: string;
|
|
94
|
+
} | {
|
|
95
|
+
ok: false;
|
|
96
|
+
reason: "bad_path" | "no_user" | "no_email" | "rate_limited";
|
|
97
|
+
/** For no_email and rate_limited: the page, signed out, where the person can sign in and carry on. */
|
|
98
|
+
fallbackUrl?: string;
|
|
99
|
+
};
|
|
100
|
+
type ClaimWebHandoffResult =
|
|
101
|
+
/** The browser is already signed in as this person: go to `next`, nothing to exchange. */
|
|
102
|
+
{
|
|
103
|
+
status: "same_user";
|
|
104
|
+
next: string;
|
|
105
|
+
}
|
|
106
|
+
/** Ask "Continue as <email>?"; `continueNonce` works once, for `continueSeconds`. */
|
|
107
|
+
| {
|
|
108
|
+
status: "confirm";
|
|
109
|
+
next: string;
|
|
110
|
+
email: string;
|
|
111
|
+
continueNonce: string;
|
|
112
|
+
}
|
|
113
|
+
/** Unknown, already used or older than its lifetime. */
|
|
114
|
+
| {
|
|
115
|
+
status: "expired";
|
|
116
|
+
} | {
|
|
117
|
+
status: "unavailable";
|
|
118
|
+
};
|
|
119
|
+
type ContinueWebHandoffResult = {
|
|
120
|
+
status: "ok";
|
|
121
|
+
next: string;
|
|
122
|
+
userId: string;
|
|
123
|
+
tokenHash: string;
|
|
124
|
+
}
|
|
125
|
+
/** The nonce is unknown, used, cancelled or out of time. */
|
|
126
|
+
| {
|
|
127
|
+
status: "expired";
|
|
128
|
+
} | {
|
|
129
|
+
status: "unavailable";
|
|
130
|
+
};
|
|
131
|
+
/** The SHA-256 of a handoff token or nonce, hex: what the database keeps instead. */
|
|
132
|
+
declare function handoffDigest(token: string): Promise<string>;
|
|
133
|
+
/**
|
|
134
|
+
* The `session_id` claim of an access token Supabase Auth has already verified (`auth.getUser`),
|
|
135
|
+
* or null. It only reads the payload; never call it on a token nobody verified.
|
|
136
|
+
*/
|
|
137
|
+
declare function sessionIdOf(verifiedAccessToken: string): string | null;
|
|
138
|
+
/**
|
|
139
|
+
* Record a handoff for a person the caller has already verified and return the link that
|
|
140
|
+
* completes it. Refuses a path that could leave the app, a person without an email (Supabase
|
|
141
|
+
* signs in by email link; there is no phone equivalent), and more than `rateLimit` links a window.
|
|
142
|
+
*
|
|
143
|
+
* @stability Beta
|
|
144
|
+
*/
|
|
145
|
+
declare function mintWebHandoff(options: MintWebHandoffOptions): Promise<MintWebHandoffResult>;
|
|
146
|
+
/**
|
|
147
|
+
* The page opened a link: use it (once, within its lifetime) and say whose it is. Mints nothing.
|
|
148
|
+
* When the browser is already that person (`currentUserId`) the handoff is spent and the page
|
|
149
|
+
* simply goes on; otherwise it gets a continue nonce for {@link continueWebHandoff}.
|
|
150
|
+
*
|
|
151
|
+
* @stability Beta
|
|
152
|
+
*/
|
|
153
|
+
declare function claimWebHandoff(options: {
|
|
154
|
+
admin: WebHandoffAdmin;
|
|
155
|
+
token: string;
|
|
156
|
+
/** Who this browser is signed in as now, if anyone. Only ever skips the question; grants nothing. */
|
|
157
|
+
currentUserId?: string | null;
|
|
158
|
+
continueSeconds?: number;
|
|
159
|
+
log?: Log;
|
|
160
|
+
}): Promise<ClaimWebHandoffResult>;
|
|
161
|
+
/**
|
|
162
|
+
* The person chose Continue: spend the nonce (once, in time, not after Cancel) and only now ask
|
|
163
|
+
* Supabase Auth for a sign-in token for the handoff's own person.
|
|
164
|
+
*
|
|
165
|
+
* @stability Beta
|
|
166
|
+
*/
|
|
167
|
+
declare function continueWebHandoff(options: {
|
|
168
|
+
admin: WebHandoffAdmin;
|
|
169
|
+
nonce: string;
|
|
170
|
+
log?: Log;
|
|
171
|
+
}): Promise<ContinueWebHandoffResult>;
|
|
172
|
+
/** The person chose Cancel: burn the nonce, so Continue is refused from now on. @stability Beta */
|
|
173
|
+
declare function discardWebHandoff(options: {
|
|
174
|
+
admin: WebHandoffAdmin;
|
|
175
|
+
nonce: string;
|
|
176
|
+
log?: Log;
|
|
177
|
+
}): Promise<boolean>;
|
|
178
|
+
/**
|
|
179
|
+
* The page reports the session Continue made: its access token is verified with `auth.getUser`,
|
|
180
|
+
* and its `session_id` is kept on the handoff (for the same person, within two minutes of
|
|
181
|
+
* Continue), so {@link signOutWebHandoffs} can end it.
|
|
182
|
+
*
|
|
183
|
+
* @stability Beta
|
|
184
|
+
*/
|
|
185
|
+
declare function bindWebHandoffSession(options: {
|
|
186
|
+
admin: WebHandoffAdmin;
|
|
187
|
+
nonce: string;
|
|
188
|
+
accessToken: string;
|
|
189
|
+
}): Promise<boolean>;
|
|
190
|
+
/**
|
|
191
|
+
* The app is signing out: end the web sessions handed off from that app session (and only
|
|
192
|
+
* those; never the person's other devices). Call it before the app's own sign-out, with the
|
|
193
|
+
* app's still-valid access token. Supabase documents a session as signed out once its
|
|
194
|
+
* `auth.sessions` row is gone; that web session's access token works until it expires.
|
|
195
|
+
*
|
|
196
|
+
* @stability Beta
|
|
197
|
+
*/
|
|
198
|
+
declare function signOutWebHandoffs(options: {
|
|
199
|
+
admin: WebHandoffAdmin;
|
|
200
|
+
userId: string;
|
|
201
|
+
sourceSessionId: string | null;
|
|
202
|
+
log?: Log;
|
|
203
|
+
}): Promise<number>;
|
|
204
|
+
/**
|
|
205
|
+
* The web handoff's routes, each `(request) => Response`, POST only, no CORS headers:
|
|
206
|
+
*
|
|
207
|
+
* - `mint` (the app): `Authorization: Bearer <access token>` and `{ path }`. 200 `{ url, expiresAt }`;
|
|
208
|
+
* 401 without a valid session; 400 for a path that could leave the app; 409 `no_email` and
|
|
209
|
+
* 429 `rate_limited` with a `fallbackUrl` (the page, signed out) the app may open instead.
|
|
210
|
+
* - `redeem` (the page), JSON `{ action, … }`:
|
|
211
|
+
* `claim` `{ t, currentUserId? }` → {@link ClaimWebHandoffResult};
|
|
212
|
+
* `continue` `{ nonce }` → {@link ContinueWebHandoffResult};
|
|
213
|
+
* `discard` `{ nonce }` → `{ status: "discarded" }`;
|
|
214
|
+
* `bind` `{ nonce }` with `Authorization: Bearer <the new web session's access token>` → `{ status: "bound" | "not_bound" }`.
|
|
215
|
+
* - `signOut` (the app, before its own sign-out): Bearer → `{ status: "signed_out", count }`.
|
|
216
|
+
*
|
|
217
|
+
* @stability Beta
|
|
218
|
+
*/
|
|
219
|
+
declare function createWebHandoff(options: WebHandoffOptions): {
|
|
220
|
+
mint: (request: Request) => Promise<Response>;
|
|
221
|
+
redeem: (request: Request) => Promise<Response>;
|
|
222
|
+
signOut: (request: Request) => Promise<Response>;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
export { type ClaimWebHandoffResult, type ContinueWebHandoffResult, type MintWebHandoffOptions, type MintWebHandoffResult, type WebHandoffAdmin, type WebHandoffLogEvent, type WebHandoffOptions, bindWebHandoffSession, claimWebHandoff, continueWebHandoff, createWebHandoff, discardWebHandoff, handoffDigest, mintWebHandoff, sessionIdOf, signOutWebHandoffs };
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { appRelativePath } from './chunk-7SCMHKCR.js';
|
|
2
|
+
export { appRelativePath } from './chunk-7SCMHKCR.js';
|
|
3
|
+
|
|
4
|
+
// src/web-handoff-server.ts
|
|
5
|
+
var TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
|
6
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
7
|
+
var DEFAULT_PAGE = "/auth/handoff";
|
|
8
|
+
var defaultLog = (event) => console.info(JSON.stringify(event));
|
|
9
|
+
var now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
10
|
+
function base64url(bytes) {
|
|
11
|
+
let binary = "";
|
|
12
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
13
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
14
|
+
}
|
|
15
|
+
var randomToken = () => base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
16
|
+
async function handoffDigest(token) {
|
|
17
|
+
const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
18
|
+
return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
19
|
+
}
|
|
20
|
+
function sessionIdOf(verifiedAccessToken) {
|
|
21
|
+
const payload = verifiedAccessToken.split(".")[1];
|
|
22
|
+
if (!payload) return null;
|
|
23
|
+
try {
|
|
24
|
+
const json2 = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
|
|
25
|
+
return typeof json2.session_id === "string" && UUID.test(json2.session_id) ? json2.session_id : null;
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function handoffPage(origin, pagePath, fragment) {
|
|
31
|
+
const page = appRelativePath(pagePath) ?? DEFAULT_PAGE;
|
|
32
|
+
return `${origin.replace(/\/+$/, "")}${page}#${new URLSearchParams(fragment).toString()}`;
|
|
33
|
+
}
|
|
34
|
+
function firstRow(data) {
|
|
35
|
+
const row = Array.isArray(data) ? data[0] : data;
|
|
36
|
+
return row && typeof row === "object" ? row : null;
|
|
37
|
+
}
|
|
38
|
+
async function mintWebHandoff(options) {
|
|
39
|
+
const { admin, userId, webOrigin, pagePath = DEFAULT_PAGE, ttlSeconds = 60, log = defaultLog } = options;
|
|
40
|
+
const rateLimit = options.rateLimit ?? { max: 10, windowSeconds: 60 };
|
|
41
|
+
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 10 || ttlSeconds > 300) {
|
|
42
|
+
throw new RangeError("ttlSeconds must be a whole number from 10 to 300.");
|
|
43
|
+
}
|
|
44
|
+
const at = now();
|
|
45
|
+
const path = appRelativePath(options.path);
|
|
46
|
+
const refuse = (reason) => {
|
|
47
|
+
log({ event: "web_handoff.refused", userId, ...path ? { path } : {}, reason, at });
|
|
48
|
+
const fallbackUrl = path && (reason === "no_email" || reason === "rate_limited") ? handoffPage(webOrigin, pagePath, { next: path }) : void 0;
|
|
49
|
+
return { ok: false, reason, ...fallbackUrl ? { fallbackUrl } : {} };
|
|
50
|
+
};
|
|
51
|
+
if (!path) return refuse("bad_path");
|
|
52
|
+
if (!UUID.test(userId)) return refuse("no_user");
|
|
53
|
+
const { data, error } = await admin.auth.admin.getUserById(userId);
|
|
54
|
+
if (error || !data.user) return refuse("no_user");
|
|
55
|
+
if (!data.user.email) return refuse("no_email");
|
|
56
|
+
const token = randomToken();
|
|
57
|
+
const sourceSessionId = options.sourceSessionId && UUID.test(options.sourceSessionId) ? options.sourceSessionId : null;
|
|
58
|
+
const issued = await admin.rpc("genesis_web_handoff_issue", {
|
|
59
|
+
p_user_id: userId,
|
|
60
|
+
p_digest: await handoffDigest(token),
|
|
61
|
+
p_path: path,
|
|
62
|
+
p_ttl_seconds: ttlSeconds,
|
|
63
|
+
p_max: rateLimit.max,
|
|
64
|
+
p_window_seconds: rateLimit.windowSeconds,
|
|
65
|
+
p_source_session_id: sourceSessionId
|
|
66
|
+
});
|
|
67
|
+
if (issued.error) {
|
|
68
|
+
if (issued.error.code === "GS429") return refuse("rate_limited");
|
|
69
|
+
throw new Error(`genesis_web_handoff_issue: ${issued.error.message}`);
|
|
70
|
+
}
|
|
71
|
+
log({ event: "web_handoff.minted", userId, path, at });
|
|
72
|
+
return { ok: true, url: handoffPage(webOrigin, pagePath, { t: token, next: path }), expiresAt: String(issued.data) };
|
|
73
|
+
}
|
|
74
|
+
async function claimWebHandoff(options) {
|
|
75
|
+
const { admin, token, currentUserId, continueSeconds = 30, log = defaultLog } = options;
|
|
76
|
+
const at = now();
|
|
77
|
+
if (!TOKEN.test(token)) return { status: "expired" };
|
|
78
|
+
const nonce = randomToken();
|
|
79
|
+
const nonceDigest = await handoffDigest(nonce);
|
|
80
|
+
const { data, error } = await admin.rpc("genesis_web_handoff_claim", {
|
|
81
|
+
p_digest: await handoffDigest(token),
|
|
82
|
+
p_nonce_digest: nonceDigest,
|
|
83
|
+
p_nonce_ttl_seconds: continueSeconds
|
|
84
|
+
});
|
|
85
|
+
if (error) throw new Error(`genesis_web_handoff_claim: ${error.message}`);
|
|
86
|
+
const row = firstRow(data);
|
|
87
|
+
if (!row?.user_id) {
|
|
88
|
+
log({ event: "web_handoff.refused", reason: "expired", at });
|
|
89
|
+
return { status: "expired" };
|
|
90
|
+
}
|
|
91
|
+
const userId = row.user_id;
|
|
92
|
+
const next = appRelativePath(row.path) ?? "/";
|
|
93
|
+
if (currentUserId && currentUserId === userId) {
|
|
94
|
+
await admin.rpc("genesis_web_handoff_discard", { p_nonce_digest: nonceDigest });
|
|
95
|
+
log({ event: "web_handoff.claimed", userId, path: next, reason: "same_user", at });
|
|
96
|
+
return { status: "same_user", next };
|
|
97
|
+
}
|
|
98
|
+
const found = await admin.auth.admin.getUserById(userId);
|
|
99
|
+
const email = found.data.user?.email;
|
|
100
|
+
if (found.error || !email) {
|
|
101
|
+
await admin.rpc("genesis_web_handoff_discard", { p_nonce_digest: nonceDigest });
|
|
102
|
+
log({ event: "web_handoff.refused", userId, path: next, reason: "no_email", at });
|
|
103
|
+
return { status: "unavailable" };
|
|
104
|
+
}
|
|
105
|
+
log({ event: "web_handoff.claimed", userId, path: next, at });
|
|
106
|
+
return { status: "confirm", next, email, continueNonce: nonce };
|
|
107
|
+
}
|
|
108
|
+
async function continueWebHandoff(options) {
|
|
109
|
+
const { admin, nonce, log = defaultLog } = options;
|
|
110
|
+
const at = now();
|
|
111
|
+
if (!TOKEN.test(nonce)) return { status: "expired" };
|
|
112
|
+
const { data, error } = await admin.rpc("genesis_web_handoff_continue", { p_nonce_digest: await handoffDigest(nonce) });
|
|
113
|
+
if (error) throw new Error(`genesis_web_handoff_continue: ${error.message}`);
|
|
114
|
+
const row = firstRow(data);
|
|
115
|
+
if (!row?.user_id) {
|
|
116
|
+
log({ event: "web_handoff.refused", reason: "continue_expired", at });
|
|
117
|
+
return { status: "expired" };
|
|
118
|
+
}
|
|
119
|
+
const userId = row.user_id;
|
|
120
|
+
const next = appRelativePath(row.path) ?? "/";
|
|
121
|
+
const found = await admin.auth.admin.getUserById(userId);
|
|
122
|
+
const email = found.data.user?.email;
|
|
123
|
+
if (found.error || !email) {
|
|
124
|
+
log({ event: "web_handoff.refused", userId, path: next, reason: "no_email", at });
|
|
125
|
+
return { status: "unavailable" };
|
|
126
|
+
}
|
|
127
|
+
const link = await admin.auth.admin.generateLink({ type: "magiclink", email });
|
|
128
|
+
const tokenHash = link.data?.properties?.hashed_token;
|
|
129
|
+
if (link.error || !tokenHash) {
|
|
130
|
+
log({ event: "web_handoff.refused", userId, path: next, reason: "generate_link_failed", at });
|
|
131
|
+
return { status: "unavailable" };
|
|
132
|
+
}
|
|
133
|
+
log({ event: "web_handoff.continued", userId, path: next, at });
|
|
134
|
+
return { status: "ok", next, userId, tokenHash };
|
|
135
|
+
}
|
|
136
|
+
async function discardWebHandoff(options) {
|
|
137
|
+
const { admin, nonce, log = defaultLog } = options;
|
|
138
|
+
if (!TOKEN.test(nonce)) return false;
|
|
139
|
+
const { data, error } = await admin.rpc("genesis_web_handoff_discard", { p_nonce_digest: await handoffDigest(nonce) });
|
|
140
|
+
if (error) throw new Error(`genesis_web_handoff_discard: ${error.message}`);
|
|
141
|
+
if (data === true) log({ event: "web_handoff.discarded", at: now() });
|
|
142
|
+
return data === true;
|
|
143
|
+
}
|
|
144
|
+
async function bindWebHandoffSession(options) {
|
|
145
|
+
const { admin, nonce, accessToken } = options;
|
|
146
|
+
if (!TOKEN.test(nonce)) return false;
|
|
147
|
+
const { data, error } = await admin.auth.getUser(accessToken);
|
|
148
|
+
const sessionId = sessionIdOf(accessToken);
|
|
149
|
+
if (error || !data.user || !sessionId) return false;
|
|
150
|
+
const bound = await admin.rpc("genesis_web_handoff_bind_session", {
|
|
151
|
+
p_nonce_digest: await handoffDigest(nonce),
|
|
152
|
+
p_user_id: data.user.id,
|
|
153
|
+
p_session_id: sessionId
|
|
154
|
+
});
|
|
155
|
+
if (bound.error) throw new Error(`genesis_web_handoff_bind_session: ${bound.error.message}`);
|
|
156
|
+
return bound.data === true;
|
|
157
|
+
}
|
|
158
|
+
async function signOutWebHandoffs(options) {
|
|
159
|
+
const { admin, userId, sourceSessionId, log = defaultLog } = options;
|
|
160
|
+
if (!sourceSessionId) return 0;
|
|
161
|
+
const { data, error } = await admin.rpc("genesis_web_handoff_revoke_sessions", { p_user_id: userId, p_source_session_id: sourceSessionId });
|
|
162
|
+
if (error) throw new Error(`genesis_web_handoff_revoke_sessions: ${error.message}`);
|
|
163
|
+
const count = typeof data === "number" ? data : 0;
|
|
164
|
+
log({ event: "web_handoff.signed_out", userId, count, at: now() });
|
|
165
|
+
return count;
|
|
166
|
+
}
|
|
167
|
+
var NO_STORE = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
|
|
168
|
+
var json = (body, status = 200, headers = {}) => Response.json(body, { status, headers: { ...NO_STORE, ...headers } });
|
|
169
|
+
async function jsonBody(request) {
|
|
170
|
+
if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) return null;
|
|
171
|
+
const raw = await request.json().catch(() => null);
|
|
172
|
+
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
|
|
173
|
+
}
|
|
174
|
+
var bearerOf = (request) => /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1] ?? null;
|
|
175
|
+
var str = (value) => typeof value === "string" ? value : "";
|
|
176
|
+
var fail = (error) => {
|
|
177
|
+
console.error(`[web-handoff] ${error instanceof Error ? error.message : String(error)}`);
|
|
178
|
+
return json({ status: "unavailable" }, 500);
|
|
179
|
+
};
|
|
180
|
+
function createWebHandoff(options) {
|
|
181
|
+
const { admin, log = defaultLog, continueSeconds = 30 } = options;
|
|
182
|
+
const originOf = (request) => typeof options.webOrigin === "function" ? options.webOrigin(request) : options.webOrigin ?? new URL(request.url).origin;
|
|
183
|
+
const postOnly = (request) => request.method === "POST" ? null : json({ error: "Use POST." }, 405, { allow: "POST" });
|
|
184
|
+
const caller = async (request) => {
|
|
185
|
+
const bearer = bearerOf(request);
|
|
186
|
+
if (!bearer) return null;
|
|
187
|
+
const { data, error } = await admin.auth.getUser(bearer);
|
|
188
|
+
return error || !data.user ? null : { user: data.user, sessionId: sessionIdOf(bearer) };
|
|
189
|
+
};
|
|
190
|
+
const unauthorized = () => json({ error: "Sign in first." }, 401, { "www-authenticate": "Bearer" });
|
|
191
|
+
return {
|
|
192
|
+
async mint(request) {
|
|
193
|
+
const wrongMethod = postOnly(request);
|
|
194
|
+
if (wrongMethod) return wrongMethod;
|
|
195
|
+
const who = await caller(request);
|
|
196
|
+
if (!who) return unauthorized();
|
|
197
|
+
const body = await jsonBody(request);
|
|
198
|
+
if (!body) return json({ error: "Send JSON: { path }." }, 400);
|
|
199
|
+
let result;
|
|
200
|
+
try {
|
|
201
|
+
result = await mintWebHandoff({
|
|
202
|
+
...options,
|
|
203
|
+
admin,
|
|
204
|
+
log,
|
|
205
|
+
userId: who.user.id,
|
|
206
|
+
sourceSessionId: who.sessionId,
|
|
207
|
+
path: str(body["path"]),
|
|
208
|
+
webOrigin: originOf(request)
|
|
209
|
+
});
|
|
210
|
+
} catch (error) {
|
|
211
|
+
return fail(error);
|
|
212
|
+
}
|
|
213
|
+
if (result.ok) return json({ url: result.url, expiresAt: result.expiresAt });
|
|
214
|
+
const status = { bad_path: 400, no_user: 401, no_email: 409, rate_limited: 429 }[result.reason];
|
|
215
|
+
return json({ error: result.reason, ...result.fallbackUrl ? { fallbackUrl: result.fallbackUrl } : {} }, status);
|
|
216
|
+
},
|
|
217
|
+
async redeem(request) {
|
|
218
|
+
const wrongMethod = postOnly(request);
|
|
219
|
+
if (wrongMethod) return wrongMethod;
|
|
220
|
+
const body = await jsonBody(request);
|
|
221
|
+
if (!body) return json({ status: "expired" });
|
|
222
|
+
try {
|
|
223
|
+
switch (body["action"]) {
|
|
224
|
+
case "claim":
|
|
225
|
+
return json(
|
|
226
|
+
await claimWebHandoff({ admin, log, continueSeconds, token: str(body["t"]), currentUserId: str(body["currentUserId"]) || null })
|
|
227
|
+
);
|
|
228
|
+
case "continue":
|
|
229
|
+
return json(await continueWebHandoff({ admin, log, nonce: str(body["nonce"]) }));
|
|
230
|
+
case "discard":
|
|
231
|
+
await discardWebHandoff({ admin, log, nonce: str(body["nonce"]) });
|
|
232
|
+
return json({ status: "discarded" });
|
|
233
|
+
case "bind": {
|
|
234
|
+
const accessToken = bearerOf(request);
|
|
235
|
+
const bound = accessToken ? await bindWebHandoffSession({ admin, nonce: str(body["nonce"]), accessToken }) : false;
|
|
236
|
+
return json({ status: bound ? "bound" : "not_bound" });
|
|
237
|
+
}
|
|
238
|
+
default:
|
|
239
|
+
return json({ error: "Unknown action." }, 400);
|
|
240
|
+
}
|
|
241
|
+
} catch (error) {
|
|
242
|
+
return fail(error);
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
async signOut(request) {
|
|
246
|
+
const wrongMethod = postOnly(request);
|
|
247
|
+
if (wrongMethod) return wrongMethod;
|
|
248
|
+
const who = await caller(request);
|
|
249
|
+
if (!who) return unauthorized();
|
|
250
|
+
try {
|
|
251
|
+
const count = await signOutWebHandoffs({ admin, log, userId: who.user.id, sourceSessionId: who.sessionId });
|
|
252
|
+
return json({ status: "signed_out", count });
|
|
253
|
+
} catch (error) {
|
|
254
|
+
return fail(error);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export { bindWebHandoffSession, claimWebHandoff, continueWebHandoff, createWebHandoff, discardWebHandoff, handoffDigest, mintWebHandoff, sessionIdOf, signOutWebHandoffs };
|
|
261
|
+
//# sourceMappingURL=web-handoff-server.js.map
|
|
262
|
+
//# sourceMappingURL=web-handoff-server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/web-handoff-server.ts"],"names":["json"],"mappings":";;;;AAuIA,IAAM,KAAA,GAAQ,qBAAA;AACd,IAAM,IAAA,GAAO,iEAAA;AACb,IAAM,YAAA,GAAe,eAAA;AAErB,IAAM,UAAA,GAAkB,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAK,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AACrE,IAAM,GAAA,GAAM,MAAA,iBAAM,IAAI,IAAA,IAAO,WAAA,EAAY;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":"web-handoff-server.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/web-handoff/server`: continue on the web, already signed in.\n * The server half of `migrations/0015_genesis_web_handoff.sql`. Server only: it takes the\n * service-role client; never import it into browser or app code.\n *\n * A native app (or anything else that holds a person's verified session) asks for a link to a\n * page of the web app. The link opens that page signed in as the same person:\n *\n * 1. `mintWebHandoff` (for a person the caller already verified) records a handoff: who, which\n * path, good for 60 seconds, from which app session. Only a SHA-256 digest of its random\n * token is stored. It returns `<web origin>/auth/handoff#t=<token>&next=<path>`: the token is\n * in the fragment, which browsers never send to a server.\n * 2. The page claims it (`claimWebHandoff`): once, unexpired. It learns whose link it is and gets\n * a continue nonce that lives 30 seconds. Nothing that signs anyone in exists yet, so a page\n * left open, or cancelled, never holds a sign-in token.\n * 3. Continue (`continueWebHandoff`, the nonce, once, in time, not after Cancel) is the only step\n * that asks Supabase Auth for a sign-in token (`auth.admin.generateLink`, type `magiclink`,\n * which sends nothing), for the person's own email. The page exchanges it at once with\n * `auth.verifyOtp({ token_hash, type: \"email\" })`. Cancel (`discardWebHandoff`) burns the nonce.\n * 4. The page reports the session it made (`bindWebHandoffSession`), so signing out of the app\n * (`signOutWebHandoffs`) ends exactly the web sessions handed off from that app session.\n *\n * `createWebHandoff` wraps it all as three POST routes.\n *\n * ```ts\n * const handoff = createWebHandoff({ admin: supabaseAdmin });\n * // POST /api/auth/handoff (the app, Bearer) → handoff.mint(request)\n * // POST /api/auth/redeem-handoff (the page: claim, continue, discard, bind) → handoff.redeem(request)\n * // POST /api/auth/handoff-signout (the app, Bearer, before it signs out) → handoff.signOut(request)\n * ```\n *\n * @packageDocumentation\n */\nimport { appRelativePath } from \"./web-handoff-path\";\n\nexport { appRelativePath } from \"./web-handoff-path\";\n\n/** A user as Supabase Auth returns one: the fields used here. */\ninterface HandoffUser {\n id: string;\n email?: string | null;\n}\n\n/**\n * The parts of a service-role Supabase client the handoff uses. A `SupabaseClient` made with the\n * secret key fits. Loose on purpose: a client typed by an app's Database narrows `rpc`.\n */\nexport interface WebHandoffAdmin {\n auth: {\n getUser(jwt: string): PromiseLike<{ data: { user: HandoffUser | null }; error: unknown }>;\n admin: {\n getUserById(id: string): PromiseLike<{ data: { user: HandoffUser | null }; error: unknown }>;\n generateLink(params: { type: \"magiclink\"; email: string }): PromiseLike<{\n data: { properties?: { hashed_token?: string | null } | null } | null;\n error: unknown;\n }>;\n };\n };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: { message: string; code?: string } | null }>;\n}\n\n/** One line for the server log. Never carries a token, a nonce or an email. */\nexport interface WebHandoffLogEvent {\n event:\n | \"web_handoff.minted\"\n | \"web_handoff.refused\"\n | \"web_handoff.claimed\"\n | \"web_handoff.continued\"\n | \"web_handoff.discarded\"\n | \"web_handoff.signed_out\";\n userId?: string;\n path?: string;\n reason?: string;\n count?: number;\n at: string;\n}\n\ntype Log = (event: WebHandoffLogEvent) => void;\n\n/** @stability Beta */\nexport interface WebHandoffOptions {\n admin: WebHandoffAdmin;\n /**\n * The web app's origin (`https://app.example.com`), or a function of the request. Default: the\n * mint request's own origin, so a preview deployment hands off to itself.\n */\n webOrigin?: string | ((request: Request) => string);\n /** The page that completes the handoff. Default `/auth/handoff`. */\n pagePath?: string;\n /** How long a link works, 10 to 300 seconds. Default 60. */\n ttlSeconds?: number;\n /** How long the page's Continue works after it opened the link, 5 to 120 seconds. Default 30. */\n continueSeconds?: number;\n /** Links one person may mint per window. Default 10 a minute. */\n rateLimit?: { max: number; windowSeconds: number };\n /** Where each step is logged (who, which path, when). Default `console.info` as JSON. */\n log?: Log;\n}\n\n/** @stability Beta */\nexport interface MintWebHandoffOptions extends Omit<WebHandoffOptions, \"webOrigin\" | \"continueSeconds\"> {\n /** The person, already verified by the caller (a bearer token checked with `auth.getUser`). */\n userId: string;\n /** Where on the web app to land. Must pass {@link appRelativePath}. */\n path: string;\n webOrigin: string;\n /** The app session asking (the bearer's `session_id`): signing it out later ends the web session. */\n sourceSessionId?: string | null;\n}\n\nexport type MintWebHandoffResult =\n | { ok: true; url: string; expiresAt: string }\n | {\n ok: false;\n reason: \"bad_path\" | \"no_user\" | \"no_email\" | \"rate_limited\";\n /** For no_email and rate_limited: the page, signed out, where the person can sign in and carry on. */\n fallbackUrl?: string;\n };\n\nexport type ClaimWebHandoffResult =\n /** The browser is already signed in as this person: go to `next`, nothing to exchange. */\n | { status: \"same_user\"; next: string }\n /** Ask \"Continue as <email>?\"; `continueNonce` works once, for `continueSeconds`. */\n | { status: \"confirm\"; next: string; email: string; continueNonce: string }\n /** Unknown, already used or older than its lifetime. */\n | { status: \"expired\" }\n | { status: \"unavailable\" };\n\nexport type ContinueWebHandoffResult =\n | { status: \"ok\"; next: string; userId: string; tokenHash: string }\n /** The nonce is unknown, used, cancelled or out of time. */\n | { status: \"expired\" }\n | { status: \"unavailable\" };\n\nconst TOKEN = /^[A-Za-z0-9_-]{43}$/;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DEFAULT_PAGE = \"/auth/handoff\";\n\nconst defaultLog: Log = (event) => console.info(JSON.stringify(event));\nconst now = () => new Date().toISOString();\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nconst randomToken = () => base64url(crypto.getRandomValues(new Uint8Array(32)));\n\n/** The SHA-256 of a handoff token or nonce, hex: what the database keeps instead. */\nexport async function handoffDigest(token: string): Promise<string> {\n const hash = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token));\n return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * The `session_id` claim of an access token Supabase Auth has already verified (`auth.getUser`),\n * or null. It only reads the payload; never call it on a token nobody verified.\n */\nexport function sessionIdOf(verifiedAccessToken: string): string | null {\n const payload = verifiedAccessToken.split(\".\")[1];\n if (!payload) return null;\n try {\n const json = JSON.parse(atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"))) as { session_id?: unknown };\n return typeof json.session_id === \"string\" && UUID.test(json.session_id) ? json.session_id : null;\n } catch {\n return null;\n }\n}\n\nfunction handoffPage(origin: string, pagePath: string, fragment: Record<string, string>): string {\n const page = appRelativePath(pagePath) ?? DEFAULT_PAGE;\n return `${origin.replace(/\\/+$/, \"\")}${page}#${new URLSearchParams(fragment).toString()}`;\n}\n\nfunction firstRow(data: unknown): { user_id?: string; path?: string } | null {\n const row: unknown = Array.isArray(data) ? data[0] : data;\n return row && typeof row === \"object\" ? (row as { user_id?: string; path?: string }) : null;\n}\n\n/**\n * Record a handoff for a person the caller has already verified and return the link that\n * completes it. Refuses a path that could leave the app, a person without an email (Supabase\n * signs in by email link; there is no phone equivalent), and more than `rateLimit` links a window.\n *\n * @stability Beta\n */\nexport async function mintWebHandoff(options: MintWebHandoffOptions): Promise<MintWebHandoffResult> {\n const { admin, userId, webOrigin, pagePath = DEFAULT_PAGE, ttlSeconds = 60, log = defaultLog } = options;\n const rateLimit = options.rateLimit ?? { max: 10, windowSeconds: 60 };\n if (!Number.isInteger(ttlSeconds) || ttlSeconds < 10 || ttlSeconds > 300) {\n throw new RangeError(\"ttlSeconds must be a whole number from 10 to 300.\");\n }\n const at = now();\n const path = appRelativePath(options.path);\n const refuse = (reason: \"bad_path\" | \"no_user\" | \"no_email\" | \"rate_limited\"): MintWebHandoffResult => {\n log({ event: \"web_handoff.refused\", userId, ...(path ? { path } : {}), reason, at });\n const fallbackUrl =\n path && (reason === \"no_email\" || reason === \"rate_limited\") ? handoffPage(webOrigin, pagePath, { next: path }) : undefined;\n return { ok: false, reason, ...(fallbackUrl ? { fallbackUrl } : {}) };\n };\n if (!path) return refuse(\"bad_path\");\n if (!UUID.test(userId)) return refuse(\"no_user\");\n\n const { data, error } = await admin.auth.admin.getUserById(userId);\n if (error || !data.user) return refuse(\"no_user\");\n if (!data.user.email) return refuse(\"no_email\");\n\n const token = randomToken();\n const sourceSessionId = options.sourceSessionId && UUID.test(options.sourceSessionId) ? options.sourceSessionId : null;\n const issued = await admin.rpc(\"genesis_web_handoff_issue\", {\n p_user_id: userId,\n p_digest: await handoffDigest(token),\n p_path: path,\n p_ttl_seconds: ttlSeconds,\n p_max: rateLimit.max,\n p_window_seconds: rateLimit.windowSeconds,\n p_source_session_id: sourceSessionId,\n });\n if (issued.error) {\n if (issued.error.code === \"GS429\") return refuse(\"rate_limited\");\n throw new Error(`genesis_web_handoff_issue: ${issued.error.message}`);\n }\n log({ event: \"web_handoff.minted\", userId, path, at });\n return { ok: true, url: handoffPage(webOrigin, pagePath, { t: token, next: path }), expiresAt: String(issued.data) };\n}\n\n/**\n * The page opened a link: use it (once, within its lifetime) and say whose it is. Mints nothing.\n * When the browser is already that person (`currentUserId`) the handoff is spent and the page\n * simply goes on; otherwise it gets a continue nonce for {@link continueWebHandoff}.\n *\n * @stability Beta\n */\nexport async function claimWebHandoff(options: {\n admin: WebHandoffAdmin;\n token: string;\n /** Who this browser is signed in as now, if anyone. Only ever skips the question; grants nothing. */\n currentUserId?: string | null;\n continueSeconds?: number;\n log?: Log;\n}): Promise<ClaimWebHandoffResult> {\n const { admin, token, currentUserId, continueSeconds = 30, log = defaultLog } = options;\n const at = now();\n if (!TOKEN.test(token)) return { status: \"expired\" };\n const nonce = randomToken();\n const nonceDigest = await handoffDigest(nonce);\n const { data, error } = await admin.rpc(\"genesis_web_handoff_claim\", {\n p_digest: await handoffDigest(token),\n p_nonce_digest: nonceDigest,\n p_nonce_ttl_seconds: continueSeconds,\n });\n if (error) throw new Error(`genesis_web_handoff_claim: ${error.message}`);\n const row = firstRow(data);\n if (!row?.user_id) {\n log({ event: \"web_handoff.refused\", reason: \"expired\", at });\n return { status: \"expired\" };\n }\n const userId = row.user_id;\n const next = appRelativePath(row.path) ?? \"/\";\n if (currentUserId && currentUserId === userId) {\n await admin.rpc(\"genesis_web_handoff_discard\", { p_nonce_digest: nonceDigest });\n log({ event: \"web_handoff.claimed\", userId, path: next, reason: \"same_user\", at });\n return { status: \"same_user\", next };\n }\n const found = await admin.auth.admin.getUserById(userId);\n const email = found.data.user?.email;\n if (found.error || !email) {\n await admin.rpc(\"genesis_web_handoff_discard\", { p_nonce_digest: nonceDigest });\n log({ event: \"web_handoff.refused\", userId, path: next, reason: \"no_email\", at });\n return { status: \"unavailable\" };\n }\n log({ event: \"web_handoff.claimed\", userId, path: next, at });\n return { status: \"confirm\", next, email, continueNonce: nonce };\n}\n\n/**\n * The person chose Continue: spend the nonce (once, in time, not after Cancel) and only now ask\n * Supabase Auth for a sign-in token for the handoff's own person.\n *\n * @stability Beta\n */\nexport async function continueWebHandoff(options: { admin: WebHandoffAdmin; nonce: string; log?: Log }): Promise<ContinueWebHandoffResult> {\n const { admin, nonce, log = defaultLog } = options;\n const at = now();\n if (!TOKEN.test(nonce)) return { status: \"expired\" };\n const { data, error } = await admin.rpc(\"genesis_web_handoff_continue\", { p_nonce_digest: await handoffDigest(nonce) });\n if (error) throw new Error(`genesis_web_handoff_continue: ${error.message}`);\n const row = firstRow(data);\n if (!row?.user_id) {\n log({ event: \"web_handoff.refused\", reason: \"continue_expired\", at });\n return { status: \"expired\" };\n }\n const userId = row.user_id;\n const next = appRelativePath(row.path) ?? \"/\";\n const found = await admin.auth.admin.getUserById(userId);\n const email = found.data.user?.email;\n if (found.error || !email) {\n log({ event: \"web_handoff.refused\", userId, path: next, reason: \"no_email\", at });\n return { status: \"unavailable\" };\n }\n const link = await admin.auth.admin.generateLink({ type: \"magiclink\", email });\n const tokenHash = link.data?.properties?.hashed_token;\n if (link.error || !tokenHash) {\n log({ event: \"web_handoff.refused\", userId, path: next, reason: \"generate_link_failed\", at });\n return { status: \"unavailable\" };\n }\n log({ event: \"web_handoff.continued\", userId, path: next, at });\n return { status: \"ok\", next, userId, tokenHash };\n}\n\n/** The person chose Cancel: burn the nonce, so Continue is refused from now on. @stability Beta */\nexport async function discardWebHandoff(options: { admin: WebHandoffAdmin; nonce: string; log?: Log }): Promise<boolean> {\n const { admin, nonce, log = defaultLog } = options;\n if (!TOKEN.test(nonce)) return false;\n const { data, error } = await admin.rpc(\"genesis_web_handoff_discard\", { p_nonce_digest: await handoffDigest(nonce) });\n if (error) throw new Error(`genesis_web_handoff_discard: ${error.message}`);\n if (data === true) log({ event: \"web_handoff.discarded\", at: now() });\n return data === true;\n}\n\n/**\n * The page reports the session Continue made: its access token is verified with `auth.getUser`,\n * and its `session_id` is kept on the handoff (for the same person, within two minutes of\n * Continue), so {@link signOutWebHandoffs} can end it.\n *\n * @stability Beta\n */\nexport async function bindWebHandoffSession(options: { admin: WebHandoffAdmin; nonce: string; accessToken: string }): Promise<boolean> {\n const { admin, nonce, accessToken } = options;\n if (!TOKEN.test(nonce)) return false;\n const { data, error } = await admin.auth.getUser(accessToken);\n const sessionId = sessionIdOf(accessToken);\n if (error || !data.user || !sessionId) return false;\n const bound = await admin.rpc(\"genesis_web_handoff_bind_session\", {\n p_nonce_digest: await handoffDigest(nonce),\n p_user_id: data.user.id,\n p_session_id: sessionId,\n });\n if (bound.error) throw new Error(`genesis_web_handoff_bind_session: ${bound.error.message}`);\n return bound.data === true;\n}\n\n/**\n * The app is signing out: end the web sessions handed off from that app session (and only\n * those; never the person's other devices). Call it before the app's own sign-out, with the\n * app's still-valid access token. Supabase documents a session as signed out once its\n * `auth.sessions` row is gone; that web session's access token works until it expires.\n *\n * @stability Beta\n */\nexport async function signOutWebHandoffs(options: {\n admin: WebHandoffAdmin;\n userId: string;\n sourceSessionId: string | null;\n log?: Log;\n}): Promise<number> {\n const { admin, userId, sourceSessionId, log = defaultLog } = options;\n if (!sourceSessionId) return 0;\n const { data, error } = await admin.rpc(\"genesis_web_handoff_revoke_sessions\", { p_user_id: userId, p_source_session_id: sourceSessionId });\n if (error) throw new Error(`genesis_web_handoff_revoke_sessions: ${error.message}`);\n const count = typeof data === \"number\" ? data : 0;\n log({ event: \"web_handoff.signed_out\", userId, count, at: now() });\n return count;\n}\n\nconst NO_STORE = { \"cache-control\": \"no-store\", \"referrer-policy\": \"no-referrer\" };\nconst json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>\n Response.json(body, { status, headers: { ...NO_STORE, ...headers } });\n\nasync function jsonBody(request: Request): Promise<Record<string, unknown> | null> {\n if (!(request.headers.get(\"content-type\") ?? \"\").toLowerCase().startsWith(\"application/json\")) return null;\n const raw: unknown = await request.json().catch(() => null);\n return raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : null;\n}\n\nconst bearerOf = (request: Request) => /^Bearer\\s+(\\S+)$/i.exec(request.headers.get(\"authorization\") ?? \"\")?.[1] ?? null;\nconst str = (value: unknown) => (typeof value === \"string\" ? value : \"\");\nconst fail = (error: unknown) => {\n console.error(`[web-handoff] ${error instanceof Error ? error.message : String(error)}`);\n return json({ status: \"unavailable\" }, 500);\n};\n\n/**\n * The web handoff's routes, each `(request) => Response`, POST only, no CORS headers:\n *\n * - `mint` (the app): `Authorization: Bearer <access token>` and `{ path }`. 200 `{ url, expiresAt }`;\n * 401 without a valid session; 400 for a path that could leave the app; 409 `no_email` and\n * 429 `rate_limited` with a `fallbackUrl` (the page, signed out) the app may open instead.\n * - `redeem` (the page), JSON `{ action, … }`:\n * `claim` `{ t, currentUserId? }` → {@link ClaimWebHandoffResult};\n * `continue` `{ nonce }` → {@link ContinueWebHandoffResult};\n * `discard` `{ nonce }` → `{ status: \"discarded\" }`;\n * `bind` `{ nonce }` with `Authorization: Bearer <the new web session's access token>` → `{ status: \"bound\" | \"not_bound\" }`.\n * - `signOut` (the app, before its own sign-out): Bearer → `{ status: \"signed_out\", count }`.\n *\n * @stability Beta\n */\nexport function createWebHandoff(options: WebHandoffOptions): {\n mint: (request: Request) => Promise<Response>;\n redeem: (request: Request) => Promise<Response>;\n signOut: (request: Request) => Promise<Response>;\n} {\n const { admin, log = defaultLog, continueSeconds = 30 } = options;\n const originOf = (request: Request) =>\n typeof options.webOrigin === \"function\" ? options.webOrigin(request) : (options.webOrigin ?? new URL(request.url).origin);\n const postOnly = (request: Request) => (request.method === \"POST\" ? null : json({ error: \"Use POST.\" }, 405, { allow: \"POST\" }));\n const caller = async (request: Request) => {\n const bearer = bearerOf(request);\n if (!bearer) return null;\n const { data, error } = await admin.auth.getUser(bearer);\n return error || !data.user ? null : { user: data.user, sessionId: sessionIdOf(bearer) };\n };\n const unauthorized = () => json({ error: \"Sign in first.\" }, 401, { \"www-authenticate\": \"Bearer\" });\n\n return {\n async mint(request) {\n const wrongMethod = postOnly(request);\n if (wrongMethod) return wrongMethod;\n const who = await caller(request);\n if (!who) return unauthorized();\n const body = await jsonBody(request);\n if (!body) return json({ error: \"Send JSON: { path }.\" }, 400);\n let result: MintWebHandoffResult;\n try {\n result = await mintWebHandoff({\n ...options,\n admin,\n log,\n userId: who.user.id,\n sourceSessionId: who.sessionId,\n path: str(body[\"path\"]),\n webOrigin: originOf(request),\n });\n } catch (error) {\n return fail(error);\n }\n if (result.ok) return json({ url: result.url, expiresAt: result.expiresAt });\n const status = { bad_path: 400, no_user: 401, no_email: 409, rate_limited: 429 }[result.reason];\n return json({ error: result.reason, ...(result.fallbackUrl ? { fallbackUrl: result.fallbackUrl } : {}) }, status);\n },\n\n async redeem(request) {\n const wrongMethod = postOnly(request);\n if (wrongMethod) return wrongMethod;\n const body = await jsonBody(request);\n if (!body) return json({ status: \"expired\" });\n try {\n switch (body[\"action\"]) {\n case \"claim\":\n return json(\n await claimWebHandoff({ admin, log, continueSeconds, token: str(body[\"t\"]), currentUserId: str(body[\"currentUserId\"]) || null }),\n );\n case \"continue\":\n return json(await continueWebHandoff({ admin, log, nonce: str(body[\"nonce\"]) }));\n case \"discard\":\n await discardWebHandoff({ admin, log, nonce: str(body[\"nonce\"]) });\n return json({ status: \"discarded\" });\n case \"bind\": {\n const accessToken = bearerOf(request);\n const bound = accessToken ? await bindWebHandoffSession({ admin, nonce: str(body[\"nonce\"]), accessToken }) : false;\n return json({ status: bound ? \"bound\" : \"not_bound\" });\n }\n default:\n return json({ error: \"Unknown action.\" }, 400);\n }\n } catch (error) {\n return fail(error);\n }\n },\n\n async signOut(request) {\n const wrongMethod = postOnly(request);\n if (wrongMethod) return wrongMethod;\n const who = await caller(request);\n if (!who) return unauthorized();\n try {\n const count = await signOutWebHandoffs({ admin, log, userId: who.user.id, sourceSessionId: who.sessionId });\n return json({ status: \"signed_out\", count });\n } catch (error) {\n return fail(error);\n }\n },\n };\n}\n"]}
|