direct-auth 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +486 -2
- package/dist/accounts.d.ts +118 -0
- package/dist/accounts.js +314 -0
- package/dist/apps.d.ts +85 -0
- package/dist/apps.js +449 -0
- package/dist/auth.d.ts +396 -0
- package/dist/auth.js +699 -0
- package/dist/base64.d.ts +20 -0
- package/dist/base64.js +45 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +463 -0
- package/dist/client.d.ts +170 -0
- package/dist/client.js +438 -0
- package/dist/codes.d.ts +81 -0
- package/dist/codes.js +91 -0
- package/dist/crypto.d.ts +11 -0
- package/dist/crypto.js +37 -0
- package/dist/d1.d.ts +2 -0
- package/dist/d1.js +2 -0
- package/dist/db/limits.d.ts +16 -0
- package/dist/db/limits.js +23 -0
- package/dist/db/schema.d.ts +25 -0
- package/dist/db/schema.js +136 -0
- package/dist/db/sql.d.ts +52 -0
- package/dist/db/sql.js +121 -0
- package/dist/dns.d.ts +48 -0
- package/dist/dns.js +133 -0
- package/dist/env.d.ts +39 -0
- package/dist/env.js +169 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +14 -0
- package/dist/init.d.ts +134 -0
- package/dist/init.js +912 -0
- package/dist/jwks.d.ts +18 -0
- package/dist/jwks.js +63 -0
- package/dist/jwt.d.ts +90 -0
- package/dist/jwt.js +99 -0
- package/dist/keys.d.ts +33 -0
- package/dist/keys.js +54 -0
- package/dist/messages.d.ts +26 -0
- package/dist/messages.js +57 -0
- package/dist/migrate-cli.d.ts +82 -0
- package/dist/migrate-cli.js +564 -0
- package/dist/migrate.d.ts +99 -0
- package/dist/migrate.js +396 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.js +63 -0
- package/dist/passkeys.d.ts +126 -0
- package/dist/passkeys.js +383 -0
- package/dist/passwords.d.ts +53 -0
- package/dist/passwords.js +326 -0
- package/dist/pgwire.d.ts +86 -0
- package/dist/pgwire.js +445 -0
- package/dist/phone.d.ts +11 -0
- package/dist/phone.js +18 -0
- package/dist/postgres.d.ts +2 -0
- package/dist/postgres.js +2 -0
- package/dist/providers/apple-revoke.d.ts +55 -0
- package/dist/providers/apple-revoke.js +113 -0
- package/dist/providers/apple.d.ts +28 -0
- package/dist/providers/apple.js +51 -0
- package/dist/providers/github.d.ts +28 -0
- package/dist/providers/github.js +67 -0
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +47 -0
- package/dist/providers/identity.d.ts +24 -0
- package/dist/providers/identity.js +3 -0
- package/dist/proxy.d.ts +19 -0
- package/dist/proxy.js +43 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +264 -0
- package/dist/scrypt.d.ts +26 -0
- package/dist/scrypt.js +179 -0
- package/dist/senders/aws.d.ts +13 -0
- package/dist/senders/aws.js +47 -0
- package/dist/senders/dev.d.ts +6 -0
- package/dist/senders/dev.js +13 -0
- package/dist/senders/index.d.ts +5 -0
- package/dist/senders/index.js +4 -0
- package/dist/senders/mail.d.ts +26 -0
- package/dist/senders/mail.js +66 -0
- package/dist/senders/sms.d.ts +34 -0
- package/dist/senders/sms.js +69 -0
- package/dist/senders/smtp.d.ts +32 -0
- package/dist/senders/smtp.js +145 -0
- package/dist/senders/types.d.ts +31 -0
- package/dist/senders/types.js +25 -0
- package/dist/server.d.ts +67 -0
- package/dist/server.js +494 -0
- package/dist/sessions.d.ts +74 -0
- package/dist/sessions.js +146 -0
- package/dist/skill.d.ts +25 -0
- package/dist/skill.js +66 -0
- package/dist/sources.d.ts +138 -0
- package/dist/sources.js +931 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +2 -0
- package/dist/stores/d1.d.ts +22 -0
- package/dist/stores/d1.js +23 -0
- package/dist/stores/postgres.d.ts +33 -0
- package/dist/stores/postgres.js +71 -0
- package/dist/stores/sqlite.d.ts +27 -0
- package/dist/stores/sqlite.js +55 -0
- package/dist/supabase.d.ts +71 -0
- package/dist/supabase.js +283 -0
- package/dist/tui.d.ts +178 -0
- package/dist/tui.js +537 -0
- package/package.json +90 -4
- package/skills/direct-auth/SKILL.md +101 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP API (docs/API.md) as one `fetch(request) → response`, for anything that speaks Request and Response:
|
|
3
|
+
* Supabase's Edge Functions, Deno, Bun, Cloudflare Workers, Vercel and Netlify functions; on Node, `serve()` from
|
|
4
|
+
* `direct-auth/node`.
|
|
5
|
+
*
|
|
6
|
+
* const server = await createAuthServer({ sql, issuer, keys, app: "Example", apple: { … }, email: { … } });
|
|
7
|
+
* Deno.serve(server.fetch);
|
|
8
|
+
*/
|
|
9
|
+
import { createAuth } from "./auth.js";
|
|
10
|
+
import { hit } from "./db/limits.js";
|
|
11
|
+
import { same } from "./crypto.js";
|
|
12
|
+
const STATUS = {
|
|
13
|
+
bad_request: 400,
|
|
14
|
+
invalid_email: 400,
|
|
15
|
+
invalid_phone: 400,
|
|
16
|
+
unauthorized: 401,
|
|
17
|
+
invalid_code: 401,
|
|
18
|
+
invalid_credentials: 401,
|
|
19
|
+
password_too_short: 400,
|
|
20
|
+
password_too_long: 400,
|
|
21
|
+
email_needed: 400,
|
|
22
|
+
expired: 401,
|
|
23
|
+
too_many_attempts: 401,
|
|
24
|
+
invalid_token: 401,
|
|
25
|
+
session_ended: 401,
|
|
26
|
+
token_reused: 401,
|
|
27
|
+
reauth_needed: 401,
|
|
28
|
+
country_not_allowed: 403,
|
|
29
|
+
human_check_failed: 403,
|
|
30
|
+
too_large: 413,
|
|
31
|
+
google_domain: 403,
|
|
32
|
+
not_found: 404,
|
|
33
|
+
apple_code_needed: 409,
|
|
34
|
+
identity_in_use: 409,
|
|
35
|
+
nonce_needed: 400,
|
|
36
|
+
last_way_in: 409,
|
|
37
|
+
rate_limited: 429,
|
|
38
|
+
too_soon: 429,
|
|
39
|
+
send_failed: 502,
|
|
40
|
+
apple_keys_unavailable: 503,
|
|
41
|
+
migration_pending: 503,
|
|
42
|
+
google_keys_unavailable: 503,
|
|
43
|
+
github_unavailable: 503,
|
|
44
|
+
};
|
|
45
|
+
function statusOf(reason) {
|
|
46
|
+
if (STATUS[reason])
|
|
47
|
+
return STATUS[reason];
|
|
48
|
+
if (reason.endsWith("_not_configured"))
|
|
49
|
+
return 404;
|
|
50
|
+
if (/^(apple|google|github|passkey)_/.test(reason))
|
|
51
|
+
return 401;
|
|
52
|
+
return 400;
|
|
53
|
+
}
|
|
54
|
+
const onWorkers = () => globalThis.navigator?.userAgent === "Cloudflare-Workers";
|
|
55
|
+
/** Supabase's Edge Functions (its edge runtime has an `EdgeRuntime` object, and Deno). */
|
|
56
|
+
const onSupabaseEdge = () => {
|
|
57
|
+
const g = globalThis;
|
|
58
|
+
return typeof g.EdgeRuntime === "object" && g.EdgeRuntime !== null && typeof g.Deno === "object";
|
|
59
|
+
};
|
|
60
|
+
const lastForwarded = (req) => {
|
|
61
|
+
const forwarded = req.headers.get("x-forwarded-for")?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
62
|
+
return forwarded?.length ? forwarded[forwarded.length - 1] : undefined;
|
|
63
|
+
};
|
|
64
|
+
/** The connection's address as the runtime gives it: Deno's `info.remoteAddr`, Bun's `server.requestIP(req)`. */
|
|
65
|
+
const connectionIp = (req, info) => {
|
|
66
|
+
if (!info || typeof info !== "object")
|
|
67
|
+
return undefined;
|
|
68
|
+
const deno = info.remoteAddr;
|
|
69
|
+
if (deno && typeof deno.hostname === "string")
|
|
70
|
+
return deno.hostname;
|
|
71
|
+
const bun = info;
|
|
72
|
+
if (typeof bun.requestIP === "function") {
|
|
73
|
+
try {
|
|
74
|
+
const a = bun.requestIP(req);
|
|
75
|
+
return a && typeof a.address === "string" ? a.address : undefined;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
};
|
|
83
|
+
const defaultIp = (req, info, trustProxy) => {
|
|
84
|
+
if (onWorkers())
|
|
85
|
+
return req.headers.get("cf-connecting-ip");
|
|
86
|
+
if (trustProxy)
|
|
87
|
+
return lastForwarded(req) ?? req.headers.get("x-real-ip");
|
|
88
|
+
// Supabase's gateway appends the caller's address to x-forwarded-for, so its last entry is the one a client can't set.
|
|
89
|
+
if (onSupabaseEdge())
|
|
90
|
+
return lastForwarded(req);
|
|
91
|
+
return connectionIp(req, info);
|
|
92
|
+
};
|
|
93
|
+
/** An IP as a limit's key: IPv6 by its /64 (one host holds a whole one), an IPv4 one written as IPv6 as itself. */
|
|
94
|
+
export function ipKey(ip) {
|
|
95
|
+
let v = ip?.trim();
|
|
96
|
+
if (!v)
|
|
97
|
+
return undefined;
|
|
98
|
+
// A port, as some proxies write it: [IPv6]:port, IPv4:port.
|
|
99
|
+
v = /^\[([^\]]*)\](?::\d*)?$/.exec(v)?.[1] ?? /^(\d{1,3}(?:\.\d{1,3}){3}):\d*$/.exec(v)?.[1] ?? v;
|
|
100
|
+
v = v.replace(/%.*$/, "");
|
|
101
|
+
if (!v)
|
|
102
|
+
return undefined;
|
|
103
|
+
// IPv4-mapped (::ffff:203.0.113.7, ::ffff:cb00:7107): a dual-stack socket's way of saying an IPv4 caller.
|
|
104
|
+
const mapped = /^(?:0{0,4}:){0,4}:?(?:0{0,4}:)?ffff:(.+)$/i.exec(v);
|
|
105
|
+
if (mapped) {
|
|
106
|
+
const rest = mapped[1];
|
|
107
|
+
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(rest))
|
|
108
|
+
v = rest;
|
|
109
|
+
else {
|
|
110
|
+
const hex = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(rest);
|
|
111
|
+
if (hex) {
|
|
112
|
+
const a = parseInt(hex[1], 16);
|
|
113
|
+
const b = parseInt(hex[2], 16);
|
|
114
|
+
v = `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (!v.includes(":"))
|
|
119
|
+
return v.slice(0, 45);
|
|
120
|
+
const [head = "", tail = ""] = v.split("::");
|
|
121
|
+
const h = head ? head.split(":") : [];
|
|
122
|
+
const t = tail ? tail.split(":") : [];
|
|
123
|
+
const groups = v.includes("::") ? [...h, ...Array(Math.max(0, 8 - h.length - t.length)).fill("0"), ...t] : h;
|
|
124
|
+
return `${groups.slice(0, 4).map((g) => g.toLowerCase().replace(/^0+(?=.)/, "")).join(":")}::/64`.slice(0, 45);
|
|
125
|
+
}
|
|
126
|
+
const MAX_BODY = 64 * 1024;
|
|
127
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
128
|
+
export async function createAuthServer(o) {
|
|
129
|
+
const auth = await createAuth(o);
|
|
130
|
+
const base = `/${(o.basePath ?? "/auth").replace(/^\/+|\/+$/g, "")}`.replace(/^\/$/, "");
|
|
131
|
+
// `__Host-`: the browser takes it only from this host, over HTTPS, on Path=/, so a sibling subdomain can't plant
|
|
132
|
+
// a session of its own in it.
|
|
133
|
+
const cookieName = o.cookieName ?? "__Host-direct_auth_refresh";
|
|
134
|
+
const origins = new Set(o.origins ?? []);
|
|
135
|
+
const proxied = (req) => {
|
|
136
|
+
const said = req.headers.get("x-direct-auth-proxy");
|
|
137
|
+
return !!o.proxySecret && !!said && same(said, o.proxySecret) ? req.headers.get("x-direct-auth-ip") : undefined;
|
|
138
|
+
};
|
|
139
|
+
const ipOf = (req, info) => ipKey(proxied(req) || (o.ip ? o.ip(req) : defaultIp(req, info, o.trustProxy ?? false)));
|
|
140
|
+
const fresh = (o.freshMinutes ?? 10) * 60_000;
|
|
141
|
+
const cors = (req) => {
|
|
142
|
+
const origin = req.headers.get("origin");
|
|
143
|
+
if (!origin || !origins.has(origin))
|
|
144
|
+
return {};
|
|
145
|
+
return {
|
|
146
|
+
"access-control-allow-origin": origin,
|
|
147
|
+
"access-control-allow-credentials": "true",
|
|
148
|
+
"access-control-allow-headers": "authorization, content-type, x-direct-auth-cookie",
|
|
149
|
+
"access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
|
|
150
|
+
"access-control-max-age": "600",
|
|
151
|
+
vary: "origin",
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
const json = (req, status, body, headers = {}) => new Response(status === 204 ? null : JSON.stringify(body), {
|
|
155
|
+
status,
|
|
156
|
+
headers: { "content-type": "application/json", "cache-control": "no-store", ...cors(req), ...headers },
|
|
157
|
+
});
|
|
158
|
+
const fail = (req, route, reason, detail) => {
|
|
159
|
+
o.observe?.({ route, reason, detail });
|
|
160
|
+
const headers = reason === "rate_limited" || reason === "too_soon" ? { "retry-after": reason === "too_soon" ? "30" : "600" } : {};
|
|
161
|
+
return json(req, statusOf(reason), { error: reason }, headers);
|
|
162
|
+
};
|
|
163
|
+
const cookieMode = (req) => req.headers.get("x-direct-auth-cookie") === "1";
|
|
164
|
+
const cookie = (value, maxAge) => `${cookieName}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
|
|
165
|
+
const readCookie = (req) => (req.headers.get("cookie") ?? "")
|
|
166
|
+
.split(/;\s*/)
|
|
167
|
+
.find((c) => c.startsWith(`${cookieName}=`))
|
|
168
|
+
?.slice(cookieName.length + 1);
|
|
169
|
+
const userJson = (user) => ({
|
|
170
|
+
id: user.id,
|
|
171
|
+
email: user.email,
|
|
172
|
+
phone: user.phone,
|
|
173
|
+
name: user.name,
|
|
174
|
+
picture: user.picture,
|
|
175
|
+
createdAt: user.createdAt,
|
|
176
|
+
isGuest: user.isGuest,
|
|
177
|
+
hasPassword: user.hasPassword,
|
|
178
|
+
});
|
|
179
|
+
const session = (req, route, r) => {
|
|
180
|
+
if (!r.ok)
|
|
181
|
+
return fail(req, route, r.reason);
|
|
182
|
+
const { user, tokens, created } = r;
|
|
183
|
+
const body = {
|
|
184
|
+
user: userJson(user),
|
|
185
|
+
accessToken: tokens.accessToken,
|
|
186
|
+
refreshToken: tokens.refreshToken,
|
|
187
|
+
expiresIn: tokens.expiresIn,
|
|
188
|
+
tokenType: tokens.tokenType,
|
|
189
|
+
sessionId: tokens.sessionId,
|
|
190
|
+
created,
|
|
191
|
+
};
|
|
192
|
+
if (!cookieMode(req))
|
|
193
|
+
return json(req, 200, body);
|
|
194
|
+
delete body.refreshToken;
|
|
195
|
+
return json(req, 200, body, { "set-cookie": cookie(tokens.refreshToken, (o.maxDays ?? 365) * 86_400) });
|
|
196
|
+
};
|
|
197
|
+
const account = (req, route, r) => r.ok ? json(req, 200, { user: userJson(r.user), accessToken: r.accessToken, expiresIn: r.expiresIn, tokenType: "Bearer" }) : fail(req, route, r.reason);
|
|
198
|
+
const signedIn = async (req) => {
|
|
199
|
+
const token = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
|
|
200
|
+
return token ? auth.signedIn(token) : null;
|
|
201
|
+
};
|
|
202
|
+
const body = async (req) => {
|
|
203
|
+
if (req.method === "GET" || req.method === "HEAD")
|
|
204
|
+
return {};
|
|
205
|
+
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY)
|
|
206
|
+
return "too_large";
|
|
207
|
+
const text = await req.text();
|
|
208
|
+
if (text.length > MAX_BODY)
|
|
209
|
+
return "too_large";
|
|
210
|
+
if (!text.trim())
|
|
211
|
+
return {};
|
|
212
|
+
const type = req.headers.get("content-type") ?? "";
|
|
213
|
+
if (type.includes("application/x-www-form-urlencoded"))
|
|
214
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
215
|
+
try {
|
|
216
|
+
const v = JSON.parse(text);
|
|
217
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
async function handle(req, info) {
|
|
224
|
+
const url = new URL(req.url);
|
|
225
|
+
if (base && url.pathname !== base && !url.pathname.startsWith(`${base}/`))
|
|
226
|
+
return json(req, 404, { error: "not_found" });
|
|
227
|
+
const path = url.pathname.slice(base.length).replace(/\/+$/, "") || "/";
|
|
228
|
+
const route = `${req.method} ${path}`;
|
|
229
|
+
if (req.method === "OPTIONS")
|
|
230
|
+
return new Response(null, { status: 204, headers: cors(req) });
|
|
231
|
+
if (req.method === "GET" && path === "/.well-known/openid-configuration") {
|
|
232
|
+
return json(req, 200, auth.discovery(), { "cache-control": "public, max-age=3600" });
|
|
233
|
+
}
|
|
234
|
+
if (req.method === "GET" && path === "/.well-known/jwks.json") {
|
|
235
|
+
return json(req, 200, auth.jwks(), { "cache-control": "public, max-age=600" });
|
|
236
|
+
}
|
|
237
|
+
const b = await body(req);
|
|
238
|
+
if (b === "too_large")
|
|
239
|
+
return fail(req, route, "too_large");
|
|
240
|
+
if (!b)
|
|
241
|
+
return fail(req, route, "bad_request");
|
|
242
|
+
const c = { ip: ipOf(req, info), userAgent: req.headers.get("user-agent") ?? undefined };
|
|
243
|
+
switch (route) {
|
|
244
|
+
case "POST /apple": {
|
|
245
|
+
const idToken = str(b.idToken);
|
|
246
|
+
if (!idToken)
|
|
247
|
+
return fail(req, route, "bad_request");
|
|
248
|
+
return session(req, route, await auth.signInWithApple({ idToken, nonce: str(b.nonce), name: str(b.name), authorizationCode: str(b.authorizationCode), redirectUri: str(b.redirectUri) }, c));
|
|
249
|
+
}
|
|
250
|
+
case "POST /apple/notifications": {
|
|
251
|
+
const payload = str(b.payload);
|
|
252
|
+
if (!payload)
|
|
253
|
+
return fail(req, route, "bad_request");
|
|
254
|
+
const r = await auth.appleNotification(payload, c);
|
|
255
|
+
return r.ok ? json(req, 200, { ok: true }) : fail(req, route, r.reason);
|
|
256
|
+
}
|
|
257
|
+
case "POST /google": {
|
|
258
|
+
const idToken = str(b.idToken);
|
|
259
|
+
if (!idToken)
|
|
260
|
+
return fail(req, route, "bad_request");
|
|
261
|
+
return session(req, route, await auth.signInWithGoogle({ idToken, nonce: str(b.nonce) }, c));
|
|
262
|
+
}
|
|
263
|
+
case "POST /github": {
|
|
264
|
+
const code = str(b.code);
|
|
265
|
+
if (!code)
|
|
266
|
+
return fail(req, route, "bad_request");
|
|
267
|
+
return session(req, route, await auth.signInWithGitHub({ code, redirectUri: str(b.redirectUri), codeVerifier: str(b.codeVerifier) }, c));
|
|
268
|
+
}
|
|
269
|
+
case "POST /email/start":
|
|
270
|
+
case "POST /sms/start": {
|
|
271
|
+
const sms = path === "/sms/start";
|
|
272
|
+
const target = str(sms ? b.phone : b.email);
|
|
273
|
+
if (!target)
|
|
274
|
+
return fail(req, route, "bad_request");
|
|
275
|
+
if (o.humanCheck && !(await o.humanCheck(req, b, sms ? "sms" : "email")))
|
|
276
|
+
return fail(req, route, "human_check_failed");
|
|
277
|
+
const r = sms ? await auth.startSms({ phone: target, locale: str(b.locale) }, c) : await auth.startEmail({ email: target, locale: str(b.locale) }, c);
|
|
278
|
+
if (r.ok)
|
|
279
|
+
return json(req, 200, { ok: true });
|
|
280
|
+
return fail(req, route, r.reason, "detail" in r ? String(r.detail) : undefined);
|
|
281
|
+
}
|
|
282
|
+
case "POST /email/verify": {
|
|
283
|
+
const email = str(b.email);
|
|
284
|
+
const code = str(b.code);
|
|
285
|
+
if (!email || !code)
|
|
286
|
+
return fail(req, route, "bad_request");
|
|
287
|
+
return session(req, route, await auth.verifyEmail({ email, code }, c));
|
|
288
|
+
}
|
|
289
|
+
case "POST /sms/verify": {
|
|
290
|
+
const phone = str(b.phone);
|
|
291
|
+
const code = str(b.code);
|
|
292
|
+
if (!phone || !code)
|
|
293
|
+
return fail(req, route, "bad_request");
|
|
294
|
+
return session(req, route, await auth.verifySms({ phone, code }, c));
|
|
295
|
+
}
|
|
296
|
+
case "POST /refresh": {
|
|
297
|
+
const fromCookie = cookieMode(req);
|
|
298
|
+
const token = fromCookie ? readCookie(req) : str(b.refreshToken);
|
|
299
|
+
if (!token)
|
|
300
|
+
return fail(req, route, fromCookie ? "invalid_token" : "bad_request");
|
|
301
|
+
const r = await auth.refresh(token, c);
|
|
302
|
+
if (!r.ok) {
|
|
303
|
+
const res = fail(req, route, r.reason);
|
|
304
|
+
if (fromCookie)
|
|
305
|
+
res.headers.append("set-cookie", cookie("", 0));
|
|
306
|
+
return res;
|
|
307
|
+
}
|
|
308
|
+
const user = await auth.getUser(decodeSub(r.tokens.accessToken));
|
|
309
|
+
if (!user)
|
|
310
|
+
return fail(req, route, "session_ended");
|
|
311
|
+
return session(req, route, { ok: true, user, tokens: r.tokens, created: false });
|
|
312
|
+
}
|
|
313
|
+
case "POST /passkey/signin/start": {
|
|
314
|
+
if (c.ip && !(await hit(auth.sql, `passkey-ip:${c.ip}`, { max: 60, window: 3_600_000 })))
|
|
315
|
+
return fail(req, route, "rate_limited");
|
|
316
|
+
const r = await auth.passkeys.signInOptions(c);
|
|
317
|
+
return r.ok ? json(req, 200, { challengeId: r.challengeId, options: r.options }) : fail(req, route, r.reason);
|
|
318
|
+
}
|
|
319
|
+
case "POST /passkey/signin/finish":
|
|
320
|
+
return session(req, route, await auth.passkeys.signIn({ challengeId: b.challengeId, credential: b.credential }, c));
|
|
321
|
+
case "POST /guest": {
|
|
322
|
+
if (o.humanCheck && !(await o.humanCheck(req, b, "guest")))
|
|
323
|
+
return fail(req, route, "human_check_failed");
|
|
324
|
+
return session(req, route, await auth.signInAsGuest({ name: str(b.name) }, c));
|
|
325
|
+
}
|
|
326
|
+
case "POST /guest/claim":
|
|
327
|
+
return session(req, route, await auth.claimGuest({ supabaseRefreshToken: str(b.supabaseRefreshToken) ?? "" }, c));
|
|
328
|
+
case "POST /password/signin": {
|
|
329
|
+
const email = str(b.email);
|
|
330
|
+
const password = str(b.password);
|
|
331
|
+
if (!email || password === undefined)
|
|
332
|
+
return fail(req, route, "bad_request");
|
|
333
|
+
return session(req, route, await auth.signInWithPassword({ email, password }, c));
|
|
334
|
+
}
|
|
335
|
+
case "POST /password/signup":
|
|
336
|
+
case "POST /password/reset": {
|
|
337
|
+
const email = str(b.email);
|
|
338
|
+
const code = str(b.code);
|
|
339
|
+
const password = str(b.password);
|
|
340
|
+
if (!email || !code || password === undefined)
|
|
341
|
+
return fail(req, route, "bad_request");
|
|
342
|
+
return session(req, route, await auth.setPasswordWithCode({ email, code, password }, c));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
// A web app in cookie mode signs out with its cookie: no access token needed (it may have none left).
|
|
346
|
+
if (route === "POST /signout" && cookieMode(req) && !req.headers.get("authorization")) {
|
|
347
|
+
const token = readCookie(req);
|
|
348
|
+
if (token)
|
|
349
|
+
await auth.signOutWithRefresh(token, b.everywhere === true, c);
|
|
350
|
+
return json(req, 200, { ok: true }, { "set-cookie": cookie("", 0) });
|
|
351
|
+
}
|
|
352
|
+
// Signed in from here.
|
|
353
|
+
const who = await signedIn(req);
|
|
354
|
+
const known = [
|
|
355
|
+
"GET /user",
|
|
356
|
+
"POST /signout",
|
|
357
|
+
"DELETE /user",
|
|
358
|
+
"POST /passkey/register/start",
|
|
359
|
+
"POST /passkey/register/finish",
|
|
360
|
+
"POST /password",
|
|
361
|
+
"DELETE /password",
|
|
362
|
+
"POST /link/apple",
|
|
363
|
+
"POST /link/google",
|
|
364
|
+
"POST /link/github",
|
|
365
|
+
"POST /link/email",
|
|
366
|
+
"POST /email/change",
|
|
367
|
+
];
|
|
368
|
+
let passkeyDelete = null;
|
|
369
|
+
let identityDelete = null;
|
|
370
|
+
try {
|
|
371
|
+
if (req.method === "DELETE" && path.startsWith("/passkey/"))
|
|
372
|
+
passkeyDelete = decodeURIComponent(path.slice("/passkey/".length));
|
|
373
|
+
if (req.method === "DELETE" && path.startsWith("/identity/"))
|
|
374
|
+
identityDelete = decodeURIComponent(path.slice("/identity/".length));
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
return fail(req, route, "bad_request");
|
|
378
|
+
}
|
|
379
|
+
if (!known.includes(route) && !passkeyDelete && !identityDelete)
|
|
380
|
+
return json(req, 404, { error: "not_found" });
|
|
381
|
+
if (!who)
|
|
382
|
+
return fail(req, route, "unauthorized");
|
|
383
|
+
const me = await auth.getUser(who.userId);
|
|
384
|
+
if (!me)
|
|
385
|
+
return fail(req, route, "unauthorized");
|
|
386
|
+
// Changing how the account is reached asks for a recent sign-in, so a token taken from a device can't leave a
|
|
387
|
+
// way back in behind it (or lock the owner out). A guest has nothing to sign in again with, and isn't asked.
|
|
388
|
+
// Deleting the account asks for one too: a token taken from a device can't end it (or start Apple's revocation).
|
|
389
|
+
const changesAccess = route !== "GET /user" && route !== "POST /signout" && route !== "POST /passkey/register/finish";
|
|
390
|
+
if (changesAccess && !me.isGuest && Date.now() - who.sessionCreatedAt > fresh)
|
|
391
|
+
return fail(req, route, "reauth_needed");
|
|
392
|
+
switch (route) {
|
|
393
|
+
case "GET /user": {
|
|
394
|
+
const [identities, passkeys] = await Promise.all([auth.identities(who.userId), auth.passkeys.list(who.userId)]);
|
|
395
|
+
return json(req, 200, {
|
|
396
|
+
user: userJson(me),
|
|
397
|
+
identities: identities.map((i) => ({ id: i.id, provider: i.provider, email: i.email, createdAt: i.createdAt, lastUsedAt: i.lastUsedAt })),
|
|
398
|
+
passkeys,
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
case "POST /signout": {
|
|
402
|
+
if (b.everywhere === true)
|
|
403
|
+
await auth.signOutEverywhere(who.userId);
|
|
404
|
+
else if (who.sessionId)
|
|
405
|
+
await auth.signOut(who.sessionId);
|
|
406
|
+
return json(req, 200, { ok: true }, cookieMode(req) ? { "set-cookie": cookie("", 0) } : {});
|
|
407
|
+
}
|
|
408
|
+
case "DELETE /user": {
|
|
409
|
+
const r = await auth.deleteUser(who.userId, { appleAuthorizationCode: str(b.appleAuthorizationCode), redirectUri: str(b.redirectUri) });
|
|
410
|
+
if (!r.ok)
|
|
411
|
+
return fail(req, route, r.reason);
|
|
412
|
+
if (r.appleRevoked === false)
|
|
413
|
+
o.observe?.({ route, reason: "apple_revoke_failed" });
|
|
414
|
+
return json(req, 200, { ok: true }, cookieMode(req) ? { "set-cookie": cookie("", 0) } : {});
|
|
415
|
+
}
|
|
416
|
+
case "POST /passkey/register/start": {
|
|
417
|
+
const r = await auth.passkeys.registrationOptions(who.userId, c);
|
|
418
|
+
return r.ok ? json(req, 200, { challengeId: r.challengeId, options: r.options }) : fail(req, route, r.reason);
|
|
419
|
+
}
|
|
420
|
+
case "POST /passkey/register/finish": {
|
|
421
|
+
const r = await auth.passkeys.register(who.userId, { challengeId: b.challengeId, credential: b.credential, name: b.name }, c);
|
|
422
|
+
return r.ok ? json(req, 200, { passkey: r.passkey }) : fail(req, route, r.reason);
|
|
423
|
+
}
|
|
424
|
+
case "POST /password": {
|
|
425
|
+
const password = str(b.password);
|
|
426
|
+
if (password === undefined)
|
|
427
|
+
return fail(req, route, "bad_request");
|
|
428
|
+
return account(req, route, await auth.setPassword(who.userId, who.sessionId, password, c));
|
|
429
|
+
}
|
|
430
|
+
case "DELETE /password":
|
|
431
|
+
return account(req, route, await auth.removePassword(who.userId, who.sessionId, c));
|
|
432
|
+
case "POST /link/apple": {
|
|
433
|
+
const idToken = str(b.idToken);
|
|
434
|
+
if (!idToken)
|
|
435
|
+
return fail(req, route, "bad_request");
|
|
436
|
+
return account(req, route, await auth.linkApple(who.userId, who.sessionId, {
|
|
437
|
+
idToken,
|
|
438
|
+
nonce: str(b.nonce),
|
|
439
|
+
name: str(b.name),
|
|
440
|
+
authorizationCode: str(b.authorizationCode),
|
|
441
|
+
redirectUri: str(b.redirectUri),
|
|
442
|
+
}, c));
|
|
443
|
+
}
|
|
444
|
+
case "POST /link/google": {
|
|
445
|
+
const idToken = str(b.idToken);
|
|
446
|
+
if (!idToken)
|
|
447
|
+
return fail(req, route, "bad_request");
|
|
448
|
+
return account(req, route, await auth.linkGoogle(who.userId, who.sessionId, { idToken, nonce: str(b.nonce) }, c));
|
|
449
|
+
}
|
|
450
|
+
case "POST /link/github": {
|
|
451
|
+
const code = str(b.code);
|
|
452
|
+
if (!code)
|
|
453
|
+
return fail(req, route, "bad_request");
|
|
454
|
+
return account(req, route, await auth.linkGitHub(who.userId, who.sessionId, { code, redirectUri: str(b.redirectUri), codeVerifier: str(b.codeVerifier) }, c));
|
|
455
|
+
}
|
|
456
|
+
case "POST /link/email":
|
|
457
|
+
case "POST /email/change": {
|
|
458
|
+
const email = str(b.email);
|
|
459
|
+
const code = str(b.code);
|
|
460
|
+
if (!email || !code)
|
|
461
|
+
return fail(req, route, "bad_request");
|
|
462
|
+
const r = route === "POST /link/email"
|
|
463
|
+
? await auth.linkEmail(who.userId, who.sessionId, { email, code }, c)
|
|
464
|
+
: await auth.changeEmail(who.userId, who.sessionId, { email, code }, c);
|
|
465
|
+
return account(req, route, r);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (passkeyDelete) {
|
|
469
|
+
const r = await auth.passkeys.remove(who.userId, passkeyDelete);
|
|
470
|
+
return r.ok ? json(req, 200, { ok: true }) : fail(req, route, r.reason);
|
|
471
|
+
}
|
|
472
|
+
if (identityDelete)
|
|
473
|
+
return account(req, route, await auth.unlink(who.userId, who.sessionId, identityDelete, c));
|
|
474
|
+
return json(req, 404, { error: "not_found" });
|
|
475
|
+
}
|
|
476
|
+
return {
|
|
477
|
+
auth,
|
|
478
|
+
async fetch(req, info) {
|
|
479
|
+
try {
|
|
480
|
+
return await handle(req, info);
|
|
481
|
+
}
|
|
482
|
+
catch (e) {
|
|
483
|
+
o.observe?.({ route: `${req.method} ${new URL(req.url).pathname}`, reason: "internal", detail: e?.message });
|
|
484
|
+
return json(req, 500, { error: "internal" });
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/** The `sub` of an access token this server just signed (read, not checked: it was made a line before). */
|
|
490
|
+
function decodeSub(token) {
|
|
491
|
+
const part = token.split(".")[1] ?? "";
|
|
492
|
+
const claims = JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
|
|
493
|
+
return String(claims.sub);
|
|
494
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sessions: a short access token anyone can check with the published keys (an ES256 JWT, an hour), and a refresh
|
|
3
|
+
* token only this server can use, kept hashed, replaced at each use. A refresh token used again later (copied off a
|
|
4
|
+
* device and used by someone else, or the device's own old copy) ends the whole session. Within a few seconds of its
|
|
5
|
+
* first use it answers the same new token again: two tabs, or a browser restoring several, racing to refresh with one
|
|
6
|
+
* token all end up with the one session.
|
|
7
|
+
*
|
|
8
|
+
* The access token is what Supabase (as a third-party issuer), Hasura, PostgREST or any API reads: `sub` is the
|
|
9
|
+
* user's id, `role` is `authenticated`, `aud` is the audience given (`authenticated` by default, as Supabase expects).
|
|
10
|
+
*/
|
|
11
|
+
import { type Sql } from "./db/sql.ts";
|
|
12
|
+
import type { SigningKeys } from "./keys.ts";
|
|
13
|
+
import type { User } from "./accounts.ts";
|
|
14
|
+
export interface SessionOptions {
|
|
15
|
+
/** The issuer's URL, the tokens' `iss`: where `/.well-known/openid-configuration` is served. */
|
|
16
|
+
issuer: string;
|
|
17
|
+
/** The tokens' `aud` (`authenticated`). */
|
|
18
|
+
audience?: string;
|
|
19
|
+
/** Seconds an access token lasts (3600). */
|
|
20
|
+
accessTtl?: number;
|
|
21
|
+
/** Days a session lives without being used (60). */
|
|
22
|
+
idleDays?: number;
|
|
23
|
+
/** Days a session lives at most, used or not (365). */
|
|
24
|
+
maxDays?: number;
|
|
25
|
+
/** Seconds a used refresh token still works, for racing requests (10). */
|
|
26
|
+
reuseGrace?: number;
|
|
27
|
+
/** More claims for the access token (an app's own), from the user. Never anything secret: anyone can read them. */
|
|
28
|
+
claims?: (user: User) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
29
|
+
}
|
|
30
|
+
export interface Tokens {
|
|
31
|
+
accessToken: string;
|
|
32
|
+
refreshToken: string;
|
|
33
|
+
/** Seconds until the access token expires. */
|
|
34
|
+
expiresIn: number;
|
|
35
|
+
tokenType: "Bearer";
|
|
36
|
+
sessionId: string;
|
|
37
|
+
}
|
|
38
|
+
export declare function accessToken(keys: SigningKeys, o: SessionOptions, user: User, sessionId: string, now?: number): Promise<{
|
|
39
|
+
token: string;
|
|
40
|
+
expiresIn: number;
|
|
41
|
+
}>;
|
|
42
|
+
export declare function createSession(sql: Sql, keys: SigningKeys, o: SessionOptions, user: User, userAgent?: string, now?: number): Promise<Tokens>;
|
|
43
|
+
export type RefreshFailure = "invalid_token" | "session_ended" | "token_reused";
|
|
44
|
+
export declare function refreshSession(sql: Sql, keys: SigningKeys, o: SessionOptions, refreshToken: string, getUser: (id: string) => Promise<User | null>, now?: number): Promise<{
|
|
45
|
+
ok: true;
|
|
46
|
+
tokens: Tokens;
|
|
47
|
+
} | {
|
|
48
|
+
ok: false;
|
|
49
|
+
reason: RefreshFailure;
|
|
50
|
+
}>;
|
|
51
|
+
/** The live session a refresh token belongs to, and whether that token is its current one (not used yet). */
|
|
52
|
+
export declare function sessionOfRefresh(sql: Sql, refreshToken: string, now?: number): Promise<{
|
|
53
|
+
sessionId: string;
|
|
54
|
+
userId: string;
|
|
55
|
+
current: boolean;
|
|
56
|
+
} | null>;
|
|
57
|
+
export declare function revokeSession(sql: Sql, sessionId: string, now?: number): Promise<void>;
|
|
58
|
+
export declare function revokeUserSessions(sql: Sql, userId: string, now?: number): Promise<void>;
|
|
59
|
+
/** Ends every session of the user but `keep` (a new password signs the other devices out). */
|
|
60
|
+
export declare function revokeOtherSessions(sql: Sql, userId: string, keep: string | null, now?: number): Promise<void>;
|
|
61
|
+
/** Checks an access token this server signed: for an API that runs beside it. Others check it with the JWKS. */
|
|
62
|
+
export declare function checkAccessToken(keys: SigningKeys, o: SessionOptions, token: string, now?: number): Promise<import("./jwt.ts").JwtResult>;
|
|
63
|
+
export interface SessionInfo {
|
|
64
|
+
id: string;
|
|
65
|
+
createdAt: number;
|
|
66
|
+
refreshedAt: number;
|
|
67
|
+
userAgent: string | null;
|
|
68
|
+
}
|
|
69
|
+
export declare function listSessions(sql: Sql, userId: string, now?: number): Promise<SessionInfo[]>;
|
|
70
|
+
/** A session that is still on: not signed out, not past its end, its user still there. Null otherwise. */
|
|
71
|
+
export declare function liveSession(sql: Sql, sessionId: string, now?: number): Promise<{
|
|
72
|
+
userId: string;
|
|
73
|
+
createdAt: number;
|
|
74
|
+
} | null>;
|