@midsummer-ai/sdk 0.1.0-staging.3650 → 0.1.0-staging.3656
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/THIRD-PARTY-NOTICES +1279 -0
- package/auth/client.d.mts +222 -18
- package/auth/client.mjs +321 -40
- package/auth/contract.d.mts +10 -1
- package/auth/contract.mjs +347 -30
- package/auth/files.d.mts +2 -28
- package/auth/files.mjs +2 -231
- package/auth/impersonate.d.mts +33 -0
- package/auth/impersonate.mjs +42 -0
- package/auth/import.d.mts +71 -0
- package/auth/import.mjs +195 -0
- package/auth/index.d.mts +5 -198
- package/auth/index.mjs +3 -2
- package/auth/mail.d.mts +23 -5
- package/auth/mail.mjs +93 -39
- package/auth/password.d.mts +10 -2
- package/auth/password.mjs +14 -2
- package/auth/react.d.mts +86 -0
- package/auth/react.mjs +865 -0
- package/auth/stand-in.d.mts +14 -3
- package/auth/stand-in.mjs +162 -29
- package/auth-CND9RW17.mjs +1819 -0
- package/authorize-BzDrbYtI-0gOzDrp2.mjs +18783 -0
- package/{client-C7QtAX5u.mjs → connection-C_JSWUrt.mjs} +3 -668
- package/database/client.mjs +665 -1
- package/dist-DXtY-DJA.mjs +343 -0
- package/engine-BhA0XgI7.mjs +48423 -0
- package/esm-E3EvzsGX.mjs +1518 -0
- package/factory-9jfDGyc1.mjs +1138 -0
- package/files-C-FvBxT4.d.mts +75 -0
- package/files-DAFOuID_.mjs +692 -0
- package/get-id-field-vhOArqXN.mjs +1455 -0
- package/index-CsgQ_ouh.d.mts +246 -0
- package/package.json +24 -7
- package/qr-C1mfuCT9.mjs +1163 -0
- package/request-state-BaLB2Hrt.mjs +85 -0
- package/rolldown-runtime-CL6CfywC.mjs +36 -0
- package/schemas-DTJTcCdK.mjs +6046 -0
- package/settings-si8iBtwc.d.mts +47 -0
- package/store-CeIGY-xT.d.mts +16 -0
- package/{store-dsVD9VnM.mjs → store-CsBhnabU.mjs} +1 -1
- package/{tabs-C85sXTwS.mjs → tabs-gHJHkhm2.mjs} +1 -1
- package/auth-BM6vB3XD.mjs +0 -754
- package/store-gCz6XVaG.d.mts +0 -15
|
@@ -0,0 +1,1819 @@
|
|
|
1
|
+
import { r as processEnv, t as here } from "./here-1plIxb0D.mjs";
|
|
2
|
+
import { connect } from "./database/client.mjs";
|
|
3
|
+
import { sendSignInMail } from "./auth/mail.mjs";
|
|
4
|
+
import "./files-DAFOuID_.mjs";
|
|
5
|
+
import { standIn } from "./auth/stand-in.mjs";
|
|
6
|
+
import { a as ourWords, c as agentOfToken, d as credentialOf, f as remembering, l as challenge, n as REFUSALS, p as resourceOf, r as buildEngine, s as agentOfKey, t as JoinRefused, u as consentPage } from "./engine-BhA0XgI7.mjs";
|
|
7
|
+
import { a as WORDS, c as setupKeyOf, i as CAPTCHA_WIDGETS, n as qrSvg, o as ago, r as AUTH_CSS, s as deviceOf } from "./qr-C1mfuCT9.mjs";
|
|
8
|
+
//#region src/auth/store.ts
|
|
9
|
+
const KIND = {
|
|
10
|
+
create: "mutation",
|
|
11
|
+
findOne: "query",
|
|
12
|
+
findMany: "query",
|
|
13
|
+
count: "query",
|
|
14
|
+
update: "mutation",
|
|
15
|
+
updateMany: "mutation",
|
|
16
|
+
deleteMany: "mutation",
|
|
17
|
+
consume: "mutation",
|
|
18
|
+
increment: "mutation",
|
|
19
|
+
page: "query"
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* The app's database as sign-in's store: each call one of `db/auth.ts`'s functions. `database` gives the
|
|
23
|
+
* connection a call goes over; it is asked for one each call, so it can hand out the request's own. A function
|
|
24
|
+
* that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`.
|
|
25
|
+
*/
|
|
26
|
+
function databaseStore(database) {
|
|
27
|
+
return { async call(fn, args) {
|
|
28
|
+
const db = await database();
|
|
29
|
+
try {
|
|
30
|
+
return KIND[fn] === "query" ? await db.query({
|
|
31
|
+
name: `auth.${fn}`,
|
|
32
|
+
kind: "query"
|
|
33
|
+
}, args) : await db.mutation({
|
|
34
|
+
name: `auth.${fn}`,
|
|
35
|
+
kind: "mutation"
|
|
36
|
+
}, args);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (/no function|not found|unknown function/i.test(String(error?.message))) throw new Error(`The database has no auth.${fn}: add sign-in's tables and functions with midsummer auth init, then deploy db/.`);
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
} };
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/auth/settings.ts
|
|
45
|
+
/** How long a read of the settings is used before it is read again, in ms. */
|
|
46
|
+
const SETTINGS_TTL_MS = 5e3;
|
|
47
|
+
/** What the settings are when the app has set none. */
|
|
48
|
+
const DEFAULT_SETTINGS = {
|
|
49
|
+
methods: {
|
|
50
|
+
password: true,
|
|
51
|
+
code: true,
|
|
52
|
+
link: true,
|
|
53
|
+
passkey: true,
|
|
54
|
+
google: true,
|
|
55
|
+
github: true
|
|
56
|
+
},
|
|
57
|
+
signUp: {
|
|
58
|
+
policy: "open",
|
|
59
|
+
domains: []
|
|
60
|
+
},
|
|
61
|
+
branding: {
|
|
62
|
+
name: null,
|
|
63
|
+
logo: null,
|
|
64
|
+
color: null
|
|
65
|
+
},
|
|
66
|
+
sender: { from: null },
|
|
67
|
+
captcha: null
|
|
68
|
+
};
|
|
69
|
+
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
70
|
+
const flag = (value, fallback) => typeof value === "boolean" ? value : fallback;
|
|
71
|
+
const line = (value, most) => typeof value === "string" && value.trim() && value.length <= most && !/[\r\n]/.test(value) ? value.trim() : null;
|
|
72
|
+
const DOMAIN = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
|
|
73
|
+
const COLOR = /^#[0-9a-f]{6}$/i;
|
|
74
|
+
const ADDRESS = /^[^\s@<>()",;:]+@[a-z0-9.-]+\.[a-z]{2,}$/i;
|
|
75
|
+
/** The settings a row holds, each field checked on its own: one of the wrong shape is its default. */
|
|
76
|
+
function settingsOf(row) {
|
|
77
|
+
const given = object(row);
|
|
78
|
+
const methods = object(given.methods), signUp = object(given.signUp), branding = object(given.branding), sender = object(given.sender), captcha = object(given.captcha);
|
|
79
|
+
const policy = [
|
|
80
|
+
"open",
|
|
81
|
+
"invite",
|
|
82
|
+
"domains",
|
|
83
|
+
"waitlist"
|
|
84
|
+
].find((one) => one === signUp.policy) ?? "open";
|
|
85
|
+
const logo = line(branding.logo, 2048);
|
|
86
|
+
const provider = [
|
|
87
|
+
"turnstile",
|
|
88
|
+
"hcaptcha",
|
|
89
|
+
"recaptcha"
|
|
90
|
+
].find((one) => one === captcha.provider);
|
|
91
|
+
const siteKey = line(captcha.siteKey, 200), secretName = line(captcha.secretName, 100);
|
|
92
|
+
const d = DEFAULT_SETTINGS.methods;
|
|
93
|
+
return {
|
|
94
|
+
methods: {
|
|
95
|
+
password: flag(methods.password, d.password),
|
|
96
|
+
code: flag(methods.code, d.code),
|
|
97
|
+
link: flag(methods.link, d.link),
|
|
98
|
+
passkey: flag(methods.passkey, d.passkey),
|
|
99
|
+
google: flag(methods.google, d.google),
|
|
100
|
+
github: flag(methods.github, d.github)
|
|
101
|
+
},
|
|
102
|
+
signUp: {
|
|
103
|
+
policy,
|
|
104
|
+
domains: Array.isArray(signUp.domains) ? signUp.domains.filter((one) => typeof one === "string").map((one) => one.trim().toLowerCase()).filter((one) => DOMAIN.test(one)).slice(0, 50) : []
|
|
105
|
+
},
|
|
106
|
+
branding: {
|
|
107
|
+
name: line(branding.name, 80),
|
|
108
|
+
logo: logo && URL.parse(logo)?.protocol === "https:" ? logo : null,
|
|
109
|
+
color: typeof branding.color === "string" && COLOR.test(branding.color) ? branding.color.toLowerCase() : null
|
|
110
|
+
},
|
|
111
|
+
sender: { from: typeof sender.from === "string" && ADDRESS.test(sender.from.trim()) ? sender.from.trim() : null },
|
|
112
|
+
captcha: provider && siteKey && secretName && /^[A-Z_][A-Z0-9_]*$/.test(secretName) ? {
|
|
113
|
+
provider,
|
|
114
|
+
siteKey,
|
|
115
|
+
secretName
|
|
116
|
+
} : null
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** The settings a browser reads (`GET /api/auth/settings`), with the app's name filled in. */
|
|
120
|
+
function publicSettings(settings, appName) {
|
|
121
|
+
return {
|
|
122
|
+
methods: settings.methods,
|
|
123
|
+
signUp: { policy: settings.signUp.policy },
|
|
124
|
+
branding: {
|
|
125
|
+
...settings.branding,
|
|
126
|
+
name: settings.branding.name ?? appName
|
|
127
|
+
},
|
|
128
|
+
captcha: settings.captcha ? {
|
|
129
|
+
provider: settings.captcha.provider,
|
|
130
|
+
siteKey: settings.captcha.siteKey
|
|
131
|
+
} : null
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The app's settings from `store`, read again once `SETTINGS_TTL_MS` has passed since the last read. Reads asked
|
|
136
|
+
* for while one is on its way share it.
|
|
137
|
+
*/
|
|
138
|
+
function settingsReader(store, clock = Date.now) {
|
|
139
|
+
let kept;
|
|
140
|
+
return () => {
|
|
141
|
+
if (kept && kept.until > clock()) return kept.value;
|
|
142
|
+
const value = store.call("findOne", {
|
|
143
|
+
model: "authSettings",
|
|
144
|
+
where: [{
|
|
145
|
+
field: "key",
|
|
146
|
+
value: "settings"
|
|
147
|
+
}]
|
|
148
|
+
}).then(settingsOf);
|
|
149
|
+
kept = {
|
|
150
|
+
until: clock() + SETTINGS_TTL_MS,
|
|
151
|
+
value
|
|
152
|
+
};
|
|
153
|
+
value.catch(() => {
|
|
154
|
+
kept = void 0;
|
|
155
|
+
});
|
|
156
|
+
return value;
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The sign-up policy's decision for `email`, given whether it was invited (an approved waitlist entry or a pending
|
|
161
|
+
* invitation to an organization) and its waitlist entry. `wait` asks the caller to add a waiting entry.
|
|
162
|
+
*/
|
|
163
|
+
function mayJoin(settings, email, seen) {
|
|
164
|
+
const domain = email.slice(email.lastIndexOf("@") + 1).toLowerCase();
|
|
165
|
+
switch (settings.signUp.policy) {
|
|
166
|
+
case "open": return { allowed: true };
|
|
167
|
+
case "domains": return settings.signUp.domains.includes(domain) || seen.invited ? { allowed: true } : {
|
|
168
|
+
allowed: false,
|
|
169
|
+
code: "SIGN_UP_DOMAIN",
|
|
170
|
+
message: `Sign-up is open to some email domains only, and ${domain} isn't one of them.`
|
|
171
|
+
};
|
|
172
|
+
case "invite": return seen.invited ? { allowed: true } : {
|
|
173
|
+
allowed: false,
|
|
174
|
+
code: "SIGN_UP_INVITE_ONLY",
|
|
175
|
+
message: "You need an invitation to sign up. Ask the people who run this app for one."
|
|
176
|
+
};
|
|
177
|
+
case "waitlist":
|
|
178
|
+
if (seen.invited) return { allowed: true };
|
|
179
|
+
if (seen.entry === "declined") return {
|
|
180
|
+
allowed: false,
|
|
181
|
+
code: "SIGN_UP_DECLINED",
|
|
182
|
+
message: "Sign-up isn't open to this email."
|
|
183
|
+
};
|
|
184
|
+
return {
|
|
185
|
+
allowed: false,
|
|
186
|
+
code: "SIGN_UP_WAITLIST",
|
|
187
|
+
message: "You're on the waitlist. We'll let you know when you can sign up.",
|
|
188
|
+
wait: seen.entry === null
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
//#endregion
|
|
193
|
+
//#region src/auth/guard.ts
|
|
194
|
+
/** What a path costs one address: its group's tries in a minute. */
|
|
195
|
+
const LIMITS = {
|
|
196
|
+
"sign-in": 10,
|
|
197
|
+
"sign-up": 5,
|
|
198
|
+
mail: 5
|
|
199
|
+
};
|
|
200
|
+
const LIMIT_WINDOW_MS = 6e4;
|
|
201
|
+
const PATHS = {
|
|
202
|
+
"/sign-in/email": {
|
|
203
|
+
method: "password",
|
|
204
|
+
limit: "sign-in",
|
|
205
|
+
captcha: true
|
|
206
|
+
},
|
|
207
|
+
"/sign-up/email": {
|
|
208
|
+
method: "password",
|
|
209
|
+
limit: "sign-up",
|
|
210
|
+
captcha: true,
|
|
211
|
+
password: "password"
|
|
212
|
+
},
|
|
213
|
+
"/request-password-reset": {
|
|
214
|
+
method: "password",
|
|
215
|
+
limit: "mail",
|
|
216
|
+
captcha: true
|
|
217
|
+
},
|
|
218
|
+
"/reset-password": {
|
|
219
|
+
method: "password",
|
|
220
|
+
password: "newPassword"
|
|
221
|
+
},
|
|
222
|
+
"/change-password": {
|
|
223
|
+
limit: "sign-in",
|
|
224
|
+
password: "newPassword"
|
|
225
|
+
},
|
|
226
|
+
"/email-otp/send-verification-otp": {
|
|
227
|
+
method: "code",
|
|
228
|
+
limit: "mail",
|
|
229
|
+
captcha: true
|
|
230
|
+
},
|
|
231
|
+
"/sign-in/email-otp": {
|
|
232
|
+
method: "code",
|
|
233
|
+
limit: "sign-in"
|
|
234
|
+
},
|
|
235
|
+
"/sign-in/magic-link": {
|
|
236
|
+
method: "link",
|
|
237
|
+
limit: "mail",
|
|
238
|
+
captcha: true
|
|
239
|
+
},
|
|
240
|
+
"/magic-link/verify": { method: "link" },
|
|
241
|
+
"/two-factor/verify-totp": { limit: "sign-in" },
|
|
242
|
+
"/two-factor/verify-otp": { limit: "sign-in" },
|
|
243
|
+
"/two-factor/verify-backup-code": { limit: "sign-in" },
|
|
244
|
+
"/two-factor/send-otp": { limit: "mail" },
|
|
245
|
+
"/organization/invite-member": { limit: "mail" },
|
|
246
|
+
"/callback/google": { method: "google" },
|
|
247
|
+
"/callback/github": { method: "github" }
|
|
248
|
+
};
|
|
249
|
+
/** Paths no one reaches: signing in as someone is the platform's alone (`/impersonate`). */
|
|
250
|
+
const CLOSED = /* @__PURE__ */ new Set(["/admin/impersonate-user", "/admin/stop-impersonating"]);
|
|
251
|
+
/** A refusal as the engine's are: JSON `{ code, message }`. */
|
|
252
|
+
const refusal = (status, code, message, headers = {}) => Response.json({
|
|
253
|
+
code,
|
|
254
|
+
message
|
|
255
|
+
}, {
|
|
256
|
+
status,
|
|
257
|
+
headers: {
|
|
258
|
+
"Cache-Control": "no-store",
|
|
259
|
+
...headers
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
const PROVIDERS = /* @__PURE__ */ new Set(["google", "github"]);
|
|
263
|
+
/** The refusal `request` gets before the engine sees it, or null to let it through. `path` is under `/api/auth`. */
|
|
264
|
+
async function guard(request, path, deps) {
|
|
265
|
+
if (CLOSED.has(path)) return refusal(404, "NOT_FOUND", "There's nothing here.");
|
|
266
|
+
const methods = deps.settings.methods;
|
|
267
|
+
if (path.startsWith("/passkey/") && !methods.passkey) return refusal(403, "METHOD_OFF", "Passkeys are turned off for this app.");
|
|
268
|
+
const rule = PATHS[path];
|
|
269
|
+
const body = request.method === "POST" && (rule?.password || path === "/sign-in/social") ? await request.clone().json().catch(() => null) : null;
|
|
270
|
+
const method = path === "/sign-in/social" && typeof body?.provider === "string" && PROVIDERS.has(body.provider) ? body.provider : rule?.method;
|
|
271
|
+
if (method && !methods[method]) return refusal(403, "METHOD_OFF", `${{
|
|
272
|
+
password: "Signing in with a password",
|
|
273
|
+
code: "Signing in with a code",
|
|
274
|
+
link: "Signing in with a link",
|
|
275
|
+
passkey: "Passkeys",
|
|
276
|
+
google: "Signing in with Google",
|
|
277
|
+
github: "Signing in with GitHub"
|
|
278
|
+
}[method]} is turned off for this app.`);
|
|
279
|
+
if (!rule || request.method !== "POST") return null;
|
|
280
|
+
if (rule.limit && deps.ip && !await deps.allow(rule.limit, deps.ip)) return refusal(429, "TOO_MANY_REQUESTS", "Too many tries from here. Wait a minute and try again.", { "Retry-After": String(LIMIT_WINDOW_MS / 1e3) });
|
|
281
|
+
const captcha = deps.settings.captcha;
|
|
282
|
+
if (rule.captcha && captcha) {
|
|
283
|
+
const token = request.headers.get("x-captcha-response") ?? "";
|
|
284
|
+
const secret = deps.env[captcha.secretName];
|
|
285
|
+
if (!secret) return refusal(503, "CAPTCHA_UNAVAILABLE", `The bot check has no secret here: set ${captcha.secretName} in this environment.`);
|
|
286
|
+
if (!token) return refusal(400, "CAPTCHA_REQUIRED", "Show you're not a bot first.");
|
|
287
|
+
let passed;
|
|
288
|
+
try {
|
|
289
|
+
passed = await deps.human(captcha.provider, secret, token, deps.ip);
|
|
290
|
+
} catch {
|
|
291
|
+
return refusal(503, "CAPTCHA_UNAVAILABLE", "We couldn't check that you're not a bot. Try again.");
|
|
292
|
+
}
|
|
293
|
+
if (!passed) return refusal(400, "CAPTCHA_FAILED", "The bot check didn't pass. Try again.");
|
|
294
|
+
}
|
|
295
|
+
const password = rule.password ? body?.[rule.password] : void 0;
|
|
296
|
+
if (typeof password === "string" && password && await deps.leaked(password)) return refusal(400, "PASSWORD_COMPROMISED", "This password has appeared in a data leak, so it isn't safe. Choose another.");
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* How often one address tries each group, kept in the app's own database (`authRateLimits`): one row per address
|
|
301
|
+
* and group, its count since its window began. Only the paths in `PATHS` with a limit count, so reading a session
|
|
302
|
+
* writes nothing.
|
|
303
|
+
*/
|
|
304
|
+
function rateLimiter(store, clock = Date.now) {
|
|
305
|
+
return async (group, ip) => {
|
|
306
|
+
const key = `${group}:${ip}`, now = clock(), since = now - LIMIT_WINDOW_MS;
|
|
307
|
+
const where = [
|
|
308
|
+
{
|
|
309
|
+
field: "key",
|
|
310
|
+
value: key
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
field: "windowStart",
|
|
314
|
+
operator: "gt",
|
|
315
|
+
value: since
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
field: "count",
|
|
319
|
+
operator: "lt",
|
|
320
|
+
value: LIMITS[group]
|
|
321
|
+
}
|
|
322
|
+
];
|
|
323
|
+
if (await store.call("increment", {
|
|
324
|
+
model: "authRateLimits",
|
|
325
|
+
where,
|
|
326
|
+
increment: { count: 1 }
|
|
327
|
+
})) return true;
|
|
328
|
+
const row = await store.call("findOne", {
|
|
329
|
+
model: "authRateLimits",
|
|
330
|
+
where: [{
|
|
331
|
+
field: "key",
|
|
332
|
+
value: key
|
|
333
|
+
}]
|
|
334
|
+
});
|
|
335
|
+
if (row && row.windowStart > since) return false;
|
|
336
|
+
if (row) {
|
|
337
|
+
await store.call("update", {
|
|
338
|
+
model: "authRateLimits",
|
|
339
|
+
where: [{
|
|
340
|
+
field: "key",
|
|
341
|
+
value: key
|
|
342
|
+
}],
|
|
343
|
+
update: {
|
|
344
|
+
count: 1,
|
|
345
|
+
windowStart: now
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
return true;
|
|
349
|
+
}
|
|
350
|
+
await store.call("deleteMany", {
|
|
351
|
+
model: "authRateLimits",
|
|
352
|
+
where: [{
|
|
353
|
+
field: "windowStart",
|
|
354
|
+
operator: "lt",
|
|
355
|
+
value: now - 864e5
|
|
356
|
+
}]
|
|
357
|
+
});
|
|
358
|
+
await store.call("create", {
|
|
359
|
+
model: "authRateLimits",
|
|
360
|
+
data: {
|
|
361
|
+
key,
|
|
362
|
+
count: 1,
|
|
363
|
+
windowStart: now
|
|
364
|
+
}
|
|
365
|
+
}).catch(async (error) => {
|
|
366
|
+
if (!await store.call("findOne", {
|
|
367
|
+
model: "authRateLimits",
|
|
368
|
+
where: [{
|
|
369
|
+
field: "key",
|
|
370
|
+
value: key
|
|
371
|
+
}]
|
|
372
|
+
})) throw error;
|
|
373
|
+
});
|
|
374
|
+
return true;
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
/** Where each bot check's provider confirms a token: the provider the app's owner chose and connected with their own key. */
|
|
378
|
+
const VERIFY = {
|
|
379
|
+
turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify",
|
|
380
|
+
hcaptcha: "https://api.hcaptcha.com/siteverify",
|
|
381
|
+
recaptcha: "https://www.google.com/recaptcha/api/siteverify"
|
|
382
|
+
};
|
|
383
|
+
/** Asks the app's bot-check provider whether `token` passes. Throws when the provider can't be reached. */
|
|
384
|
+
async function verifyHuman(provider, secret, token, ip, fetcher = fetch) {
|
|
385
|
+
const response = await fetcher(VERIFY[provider], {
|
|
386
|
+
method: "POST",
|
|
387
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
388
|
+
body: new URLSearchParams({
|
|
389
|
+
secret,
|
|
390
|
+
response: token,
|
|
391
|
+
...ip ? { remoteip: ip } : {}
|
|
392
|
+
})
|
|
393
|
+
});
|
|
394
|
+
if (!response.ok) throw new Error(`The bot check returned ${response.status}.`);
|
|
395
|
+
return (await response.json()).success === true;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Whether a password is in the public list of leaked passwords: only the first five characters of its SHA-1 leave
|
|
399
|
+
* the server (k-anonymity), and the list's answer is compared here. When the list can't be reached the password is
|
|
400
|
+
* taken, since a sign-up should not fail on someone else's outage.
|
|
401
|
+
*/
|
|
402
|
+
async function leakedPassword(password, fetcher = fetch) {
|
|
403
|
+
const hex = [...new Uint8Array(await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password)))].map((byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();
|
|
404
|
+
const response = await fetcher(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, { headers: { "Add-Padding": "true" } }).catch(() => null);
|
|
405
|
+
if (!response?.ok) return false;
|
|
406
|
+
const suffix = hex.slice(5);
|
|
407
|
+
return (await response.text()).split("\n").some((line) => {
|
|
408
|
+
const [rest, count] = line.trim().split(":");
|
|
409
|
+
return rest === suffix && Number(count) > 0;
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
const WAITS_MS = [500, 2e3];
|
|
413
|
+
const text = (value) => typeof value === "string" ? value : null;
|
|
414
|
+
const time = (value) => typeof value === "number" ? value : value instanceof Date ? value.getTime() : void 0;
|
|
415
|
+
function scopesOf(permissions) {
|
|
416
|
+
try {
|
|
417
|
+
const parsed = typeof permissions === "string" ? JSON.parse(permissions) : permissions;
|
|
418
|
+
return Array.isArray(parsed?.scope) ? parsed.scope.filter((one) => typeof one === "string") : [];
|
|
419
|
+
} catch {
|
|
420
|
+
return [];
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const userOf = (row) => ({
|
|
424
|
+
id: String(row.id),
|
|
425
|
+
email: String(row.email ?? ""),
|
|
426
|
+
name: String(row.name ?? ""),
|
|
427
|
+
emailVerified: row.emailVerified === true,
|
|
428
|
+
image: text(row.image),
|
|
429
|
+
banned: row.banned === true,
|
|
430
|
+
...time(row.createdAt) !== void 0 ? { createdAt: time(row.createdAt) } : {},
|
|
431
|
+
...row.publicMetadata !== void 0 ? { publicMetadata: row.publicMetadata } : {},
|
|
432
|
+
...row.privateMetadata !== void 0 ? { privateMetadata: row.privateMetadata } : {}
|
|
433
|
+
});
|
|
434
|
+
/** The events one change makes, at `at`. */
|
|
435
|
+
function eventsOf(change, at) {
|
|
436
|
+
const once = (type, row, data) => ({
|
|
437
|
+
id: `${type}:${String(row.id)}`,
|
|
438
|
+
type,
|
|
439
|
+
at,
|
|
440
|
+
data
|
|
441
|
+
});
|
|
442
|
+
const each = (type, row, data) => ({
|
|
443
|
+
id: `${type}:${String(row.id)}:${at}`,
|
|
444
|
+
type,
|
|
445
|
+
at,
|
|
446
|
+
data
|
|
447
|
+
});
|
|
448
|
+
return change.rows.flatMap((row) => {
|
|
449
|
+
switch (change.table) {
|
|
450
|
+
case "users":
|
|
451
|
+
if (change.op === "create") return [once("user.created", row, { user: userOf(row) })];
|
|
452
|
+
if (change.op === "delete") return [once("user.deleted", row, { user: {
|
|
453
|
+
id: String(row.id),
|
|
454
|
+
email: String(row.email ?? "")
|
|
455
|
+
} })];
|
|
456
|
+
return [each(change.update?.banned === true ? "user.banned" : "user.updated", row, { user: userOf(row) })];
|
|
457
|
+
case "authSessions": {
|
|
458
|
+
const session = {
|
|
459
|
+
id: String(row.id),
|
|
460
|
+
userId: String(row.userId),
|
|
461
|
+
ipAddress: text(row.ipAddress),
|
|
462
|
+
userAgent: text(row.userAgent),
|
|
463
|
+
impersonatedBy: text(row.impersonatedBy)
|
|
464
|
+
};
|
|
465
|
+
if (change.op === "delete") return [once("session.revoked", row, { session: {
|
|
466
|
+
id: session.id,
|
|
467
|
+
userId: session.userId
|
|
468
|
+
} })];
|
|
469
|
+
if (change.op !== "create") return [];
|
|
470
|
+
return session.impersonatedBy ? [once("user.impersonated", row, {
|
|
471
|
+
user: { id: session.userId },
|
|
472
|
+
session,
|
|
473
|
+
by: session.impersonatedBy
|
|
474
|
+
})] : [once("user.signed_in", row, {
|
|
475
|
+
user: { id: session.userId },
|
|
476
|
+
session
|
|
477
|
+
})];
|
|
478
|
+
}
|
|
479
|
+
case "organizations": return change.op === "create" ? [once("organization.created", row, { organization: {
|
|
480
|
+
id: String(row.id),
|
|
481
|
+
name: String(row.name ?? ""),
|
|
482
|
+
slug: String(row.slug ?? "")
|
|
483
|
+
} })] : [];
|
|
484
|
+
case "authMembers": {
|
|
485
|
+
const member = {
|
|
486
|
+
id: String(row.id),
|
|
487
|
+
userId: String(row.userId),
|
|
488
|
+
organizationId: String(row.organizationId),
|
|
489
|
+
role: String(row.role ?? "")
|
|
490
|
+
};
|
|
491
|
+
return change.op === "create" ? [once("organization.member.added", row, { member })] : change.op === "delete" ? [once("organization.member.removed", row, { member })] : [];
|
|
492
|
+
}
|
|
493
|
+
case "authKeys": {
|
|
494
|
+
const key = {
|
|
495
|
+
id: String(row.id),
|
|
496
|
+
userId: String(row.referenceId),
|
|
497
|
+
name: text(row.name),
|
|
498
|
+
scopes: scopesOf(row.permissions)
|
|
499
|
+
};
|
|
500
|
+
return change.op === "create" ? [once("key.created", row, { key })] : change.op === "delete" ? [once("key.revoked", row, { key })] : [];
|
|
501
|
+
}
|
|
502
|
+
case "authGrants": {
|
|
503
|
+
const grant = {
|
|
504
|
+
id: String(row.id),
|
|
505
|
+
userId: text(row.userId),
|
|
506
|
+
clientId: String(row.clientId),
|
|
507
|
+
scopes: Array.isArray(row.scopes) ? row.scopes : []
|
|
508
|
+
};
|
|
509
|
+
return change.op === "create" ? [once("grant.created", row, { grant })] : change.op === "delete" ? [once("grant.revoked", row, { grant })] : [];
|
|
510
|
+
}
|
|
511
|
+
default: return [];
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
/** A queue of events that sends itself, one batch at a time. */
|
|
516
|
+
function reporter(deps) {
|
|
517
|
+
const wait = deps.wait ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
518
|
+
const queue = [];
|
|
519
|
+
let dropped = 0;
|
|
520
|
+
let sending = null;
|
|
521
|
+
async function drain(send) {
|
|
522
|
+
await wait(0);
|
|
523
|
+
while (queue.length) {
|
|
524
|
+
const events = queue.splice(0, 100);
|
|
525
|
+
const batch = dropped ? {
|
|
526
|
+
events,
|
|
527
|
+
dropped
|
|
528
|
+
} : { events };
|
|
529
|
+
let outcome = "retry";
|
|
530
|
+
for (let attempt = 0; attempt < 3 && outcome === "retry"; attempt++) {
|
|
531
|
+
if (attempt) await wait(WAITS_MS[attempt - 1]);
|
|
532
|
+
outcome = await send(batch).catch(() => "retry");
|
|
533
|
+
}
|
|
534
|
+
if (outcome === "sent") dropped = 0;
|
|
535
|
+
else dropped += events.length;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return {
|
|
539
|
+
/** Queues events; they are sent after the request that made them. */
|
|
540
|
+
report(events) {
|
|
541
|
+
const send = deps.send();
|
|
542
|
+
if (!send || !events.length) return;
|
|
543
|
+
queue.push(...events);
|
|
544
|
+
if (queue.length > 500) dropped += queue.splice(0, queue.length - 500).length;
|
|
545
|
+
if (sending) return;
|
|
546
|
+
const work = drain(send).finally(() => {
|
|
547
|
+
sending = null;
|
|
548
|
+
});
|
|
549
|
+
sending = work;
|
|
550
|
+
deps.keep?.(work);
|
|
551
|
+
},
|
|
552
|
+
/** Waits for what is queued to be sent or dropped. */
|
|
553
|
+
async flush() {
|
|
554
|
+
while (sending) await sending;
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Sends batches over HTTP to the platform's events Action: with a database key, or a run's workload token and the
|
|
560
|
+
* binding, as `db.token.create` takes them.
|
|
561
|
+
*/
|
|
562
|
+
function httpSend(url, proof, fetcher = fetch) {
|
|
563
|
+
return async (batch) => {
|
|
564
|
+
const response = await fetcher(url, {
|
|
565
|
+
method: "POST",
|
|
566
|
+
headers: { "content-type": "application/json" },
|
|
567
|
+
body: JSON.stringify({
|
|
568
|
+
...proof,
|
|
569
|
+
...batch
|
|
570
|
+
})
|
|
571
|
+
});
|
|
572
|
+
if (response.ok) return "sent";
|
|
573
|
+
return response.status === 429 || response.status >= 500 ? "retry" : "drop";
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
//#endregion
|
|
577
|
+
//#region src/auth/ui.ts
|
|
578
|
+
const UI = "/api/auth/ui";
|
|
579
|
+
const escape = (text) => String(text ?? "").replace(/[&<>"']/g, (c) => ({
|
|
580
|
+
"&": "&",
|
|
581
|
+
"<": "<",
|
|
582
|
+
">": ">",
|
|
583
|
+
"\"": """,
|
|
584
|
+
"'": "'"
|
|
585
|
+
})[c]);
|
|
586
|
+
/** A path on the app's own address to go to after signing in: anything else goes to `/`. */
|
|
587
|
+
function redirectOf(url) {
|
|
588
|
+
const asked = url.searchParams.get("redirect") ?? "/";
|
|
589
|
+
return asked.startsWith("/") && !asked.startsWith("//") && !asked.startsWith("/\\") ? asked : "/";
|
|
590
|
+
}
|
|
591
|
+
/** One hosted page, by its path under `/api/auth/ui`. */
|
|
592
|
+
async function hostedPage(request, path, deps) {
|
|
593
|
+
const url = new URL(request.url), origin = url.origin;
|
|
594
|
+
const settings = deps.settings, app = settings.branding.name;
|
|
595
|
+
const cookie = request.headers.get("cookie") ?? "";
|
|
596
|
+
const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
|
|
597
|
+
const cookies = [];
|
|
598
|
+
const form = request.method === "POST" ? Object.fromEntries([...(await request.formData().catch(() => new FormData())).entries()].map(([key, value]) => [key, String(value)])) : {};
|
|
599
|
+
if (request.method === "POST" && request.headers.get("origin") !== origin) return new Response(WORDS.errors.otherSite, { status: 403 });
|
|
600
|
+
/** Calls sign-in as the person's browser would, keeping the cookies it sets for the page's response. */
|
|
601
|
+
async function call(to, body, captcha) {
|
|
602
|
+
const headers = {
|
|
603
|
+
origin,
|
|
604
|
+
cookie: [cookie, ...cookies.map((line) => line.split(";")[0])].filter(Boolean).join("; "),
|
|
605
|
+
"user-agent": request.headers.get("user-agent") ?? ""
|
|
606
|
+
};
|
|
607
|
+
const forwarded = request.headers.get("x-forwarded-for");
|
|
608
|
+
if (forwarded) headers["x-forwarded-for"] = forwarded;
|
|
609
|
+
if (captcha) headers["x-captcha-response"] = captcha;
|
|
610
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
611
|
+
const response = await deps.auth.handler(new Request(`${origin}/api/auth${to}`, {
|
|
612
|
+
method: body === void 0 ? "GET" : "POST",
|
|
613
|
+
headers,
|
|
614
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
615
|
+
}));
|
|
616
|
+
cookies.push(...response.headers.getSetCookie());
|
|
617
|
+
const text = await response.text();
|
|
618
|
+
let json = null;
|
|
619
|
+
try {
|
|
620
|
+
json = text ? JSON.parse(text) : null;
|
|
621
|
+
} catch {
|
|
622
|
+
json = null;
|
|
623
|
+
}
|
|
624
|
+
return {
|
|
625
|
+
ok: response.ok,
|
|
626
|
+
status: response.status,
|
|
627
|
+
json,
|
|
628
|
+
message: typeof json?.message === "string" ? json.message : response.ok ? "" : WORDS.errors.generic
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
const respond = (html, status = 200) => {
|
|
632
|
+
const headers = new Headers({
|
|
633
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
634
|
+
"Cache-Control": "no-store",
|
|
635
|
+
"X-Frame-Options": "DENY",
|
|
636
|
+
"Referrer-Policy": "same-origin",
|
|
637
|
+
"Content-Security-Policy": csp(nonce, settings)
|
|
638
|
+
});
|
|
639
|
+
for (const line of cookies) headers.append("Set-Cookie", line);
|
|
640
|
+
return new Response(html, {
|
|
641
|
+
status,
|
|
642
|
+
headers
|
|
643
|
+
});
|
|
644
|
+
};
|
|
645
|
+
const away = (to) => {
|
|
646
|
+
const headers = new Headers({
|
|
647
|
+
Location: to,
|
|
648
|
+
"Cache-Control": "no-store"
|
|
649
|
+
});
|
|
650
|
+
for (const line of cookies) headers.append("Set-Cookie", line);
|
|
651
|
+
return new Response(null, {
|
|
652
|
+
status: 303,
|
|
653
|
+
headers
|
|
654
|
+
});
|
|
655
|
+
};
|
|
656
|
+
const shell = (title, body, options = {}) => page({
|
|
657
|
+
title,
|
|
658
|
+
body,
|
|
659
|
+
nonce,
|
|
660
|
+
settings,
|
|
661
|
+
...options
|
|
662
|
+
});
|
|
663
|
+
const redirect = redirectOf(url);
|
|
664
|
+
const oauthQuery = url.searchParams.has("sig") ? url.search.slice(1) : void 0;
|
|
665
|
+
const withOauth = (body) => oauthQuery ? {
|
|
666
|
+
...body,
|
|
667
|
+
oauth_query: oauthQuery
|
|
668
|
+
} : body;
|
|
669
|
+
/** Where a sign-in goes on to: the MCP client's page that asks, when it came from one, else `redirect`. */
|
|
670
|
+
const onward = (answer) => answer?.redirect === true && typeof answer.url === "string" ? answer.url : redirect;
|
|
671
|
+
const captchaToken = () => settings.captcha ? form[CAPTCHA_WIDGETS[settings.captcha.provider].field] : void 0;
|
|
672
|
+
switch (path.replace(/\/+$/, "")) {
|
|
673
|
+
case "/sign-in": {
|
|
674
|
+
let problem = "", notice = "";
|
|
675
|
+
if (request.method === "POST") {
|
|
676
|
+
const email = (form.email ?? "").trim();
|
|
677
|
+
if (form.action === "password") {
|
|
678
|
+
const signed = await call("/sign-in/email", withOauth({
|
|
679
|
+
email,
|
|
680
|
+
password: form.password ?? ""
|
|
681
|
+
}), captchaToken());
|
|
682
|
+
if (signed.ok && signed.json?.twoFactorRedirect) return away(`${UI}/two-factor${url.search}`);
|
|
683
|
+
if (signed.ok) return away(onward(signed.json));
|
|
684
|
+
problem = signed.message;
|
|
685
|
+
} else if (form.action === "code") {
|
|
686
|
+
const sent = await call("/email-otp/send-verification-otp", {
|
|
687
|
+
email,
|
|
688
|
+
type: "sign-in"
|
|
689
|
+
}, captchaToken());
|
|
690
|
+
if (sent.ok) return respond(shell(WORDS.signIn.title(app), codeForm(email, ""), { lead: WORDS.code.sent(email) }));
|
|
691
|
+
problem = sent.message;
|
|
692
|
+
} else if (form.action === "verify") {
|
|
693
|
+
const signed = await call("/sign-in/email-otp", withOauth({
|
|
694
|
+
email,
|
|
695
|
+
otp: (form.code ?? "").trim()
|
|
696
|
+
}));
|
|
697
|
+
if (signed.ok) return away(onward(signed.json));
|
|
698
|
+
return respond(shell(WORDS.signIn.title(app), codeForm(email, signed.message), { lead: WORDS.code.sent(email) }), signed.status);
|
|
699
|
+
} else if (form.action === "link") {
|
|
700
|
+
const sent = await call("/sign-in/magic-link", {
|
|
701
|
+
email,
|
|
702
|
+
callbackURL: redirect
|
|
703
|
+
}, captchaToken());
|
|
704
|
+
if (sent.ok) notice = WORDS.link.sent(email);
|
|
705
|
+
else problem = sent.message;
|
|
706
|
+
} else if (form.action === "google" || form.action === "github") {
|
|
707
|
+
const started = await call("/sign-in/social", {
|
|
708
|
+
provider: form.action,
|
|
709
|
+
callbackURL: redirect
|
|
710
|
+
});
|
|
711
|
+
if (started.ok && typeof started.json?.url === "string") return away(started.json.url);
|
|
712
|
+
problem = started.message;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return respond(shell(WORDS.signIn.title(app), notice ? `<p class="msa-note" role="status">${escape(notice)}</p>` : signInForm(settings, problem, url.search), { script: settings.methods.passkey ? passkeyScript("sign-in", redirect) : "" }), problem ? 400 : 200);
|
|
716
|
+
}
|
|
717
|
+
case "/two-factor": {
|
|
718
|
+
let problem = "";
|
|
719
|
+
if (request.method === "POST") {
|
|
720
|
+
const to = form.action === "backup" ? "/two-factor/verify-backup-code" : form.action === "mail-code" ? "/two-factor/verify-otp" : "/two-factor/verify-totp";
|
|
721
|
+
if (form.action === "send") {
|
|
722
|
+
const sent = await call("/two-factor/send-otp", {});
|
|
723
|
+
problem = sent.ok ? "" : sent.message;
|
|
724
|
+
} else {
|
|
725
|
+
const checked = await call(to, withOauth({ code: (form.code ?? "").trim() }));
|
|
726
|
+
if (checked.ok) return away(onward(checked.json));
|
|
727
|
+
problem = checked.message;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
const mailed = form.action === "send" || form.action === "mail-code";
|
|
731
|
+
return respond(shell(WORDS.twoFactor.title, twoFactorForm(problem, mailed), { lead: mailed ? WORDS.twoFactor.mailed : WORDS.twoFactor.lead }), problem ? 400 : 200);
|
|
732
|
+
}
|
|
733
|
+
case "/sign-up": {
|
|
734
|
+
let problem = "", notice = "";
|
|
735
|
+
if (request.method === "POST") {
|
|
736
|
+
const made = await call("/sign-up/email", withOauth({
|
|
737
|
+
name: (form.name ?? "").trim(),
|
|
738
|
+
email: (form.email ?? "").trim(),
|
|
739
|
+
password: form.password ?? ""
|
|
740
|
+
}), captchaToken());
|
|
741
|
+
if (made.ok) return away(onward(made.json));
|
|
742
|
+
if (made.json?.code === "SIGN_UP_WAITLIST") notice = made.message;
|
|
743
|
+
else problem = made.message;
|
|
744
|
+
}
|
|
745
|
+
return respond(shell(WORDS.signUp.title(app), notice ? `<p class="msa-note" role="status">${escape(notice)}</p>` : signUpForm(settings, problem, url.search), settings.signUp.policy === "invite" ? { lead: WORDS.signUp.invite } : {}), problem ? 400 : 200);
|
|
746
|
+
}
|
|
747
|
+
case "/reset-password": {
|
|
748
|
+
const token = url.searchParams.get("token");
|
|
749
|
+
if (token) {
|
|
750
|
+
if (request.method === "POST") {
|
|
751
|
+
const reset = await call("/reset-password", {
|
|
752
|
+
token,
|
|
753
|
+
newPassword: form.password ?? ""
|
|
754
|
+
});
|
|
755
|
+
if (reset.ok) return respond(shell(WORDS.reset.title, `<p class="msa-note" role="status">${escape(WORDS.reset.done)}</p><p class="msa-foot"><a href="${UI}/sign-in">${escape(WORDS.signIn.submit)}</a></p>`));
|
|
756
|
+
return respond(shell(WORDS.reset.choose, newPasswordForm(reset.message)), 400);
|
|
757
|
+
}
|
|
758
|
+
return respond(shell(WORDS.reset.choose, newPasswordForm("")));
|
|
759
|
+
}
|
|
760
|
+
if (request.method === "POST") {
|
|
761
|
+
const email = (form.email ?? "").trim();
|
|
762
|
+
const asked = await call("/request-password-reset", {
|
|
763
|
+
email,
|
|
764
|
+
redirectTo: `${UI}/reset-password`
|
|
765
|
+
}, captchaToken());
|
|
766
|
+
if (asked.ok) return respond(shell(WORDS.reset.title, `<p class="msa-note" role="status">${escape(WORDS.reset.sent(email))}</p>`));
|
|
767
|
+
return respond(shell(WORDS.reset.title, resetForm(settings, asked.message), { lead: WORDS.reset.lead }), 400);
|
|
768
|
+
}
|
|
769
|
+
return respond(shell(WORDS.reset.title, resetForm(settings, ""), { lead: WORDS.reset.lead }));
|
|
770
|
+
}
|
|
771
|
+
case "/account": {
|
|
772
|
+
const signedIn = (await call("/get-session")).json;
|
|
773
|
+
if (!signedIn) return away(`${UI}/sign-in?redirect=${encodeURIComponent(`${UI}/account`)}`);
|
|
774
|
+
let problem = "", notice = "", shown = "";
|
|
775
|
+
if (request.method === "POST") {
|
|
776
|
+
const done = async (work, said = WORDS.account.saved) => {
|
|
777
|
+
const result = await work;
|
|
778
|
+
if (result.ok) notice = said;
|
|
779
|
+
else problem = result.message;
|
|
780
|
+
return result;
|
|
781
|
+
};
|
|
782
|
+
switch (form.action) {
|
|
783
|
+
case "profile":
|
|
784
|
+
await done(call("/update-user", { name: (form.name ?? "").trim() }));
|
|
785
|
+
break;
|
|
786
|
+
case "password":
|
|
787
|
+
await done(call("/change-password", {
|
|
788
|
+
currentPassword: form.current ?? "",
|
|
789
|
+
newPassword: form.next ?? "",
|
|
790
|
+
revokeOtherSessions: true
|
|
791
|
+
}), WORDS.account.passwordChanged);
|
|
792
|
+
break;
|
|
793
|
+
case "two-factor-on": {
|
|
794
|
+
const enabled = await call("/two-factor/enable", { password: form.password ?? "" });
|
|
795
|
+
if (enabled.ok) shown = twoFactorSetup(String(enabled.json?.totpURI ?? ""), enabled.json?.backupCodes ?? []);
|
|
796
|
+
else problem = enabled.message;
|
|
797
|
+
break;
|
|
798
|
+
}
|
|
799
|
+
case "two-factor-verify":
|
|
800
|
+
await done(call("/two-factor/verify-totp", { code: (form.code ?? "").trim() }));
|
|
801
|
+
break;
|
|
802
|
+
case "two-factor-off":
|
|
803
|
+
await done(call("/two-factor/disable", { password: form.password ?? "" }));
|
|
804
|
+
break;
|
|
805
|
+
case "session-revoke":
|
|
806
|
+
await done(call("/revoke-session", { token: form.token ?? "" }));
|
|
807
|
+
break;
|
|
808
|
+
case "sign-out":
|
|
809
|
+
await call("/sign-out", {});
|
|
810
|
+
return away("/");
|
|
811
|
+
case "passkey-remove":
|
|
812
|
+
await done(call("/passkey/delete-passkey", { id: form.id ?? "" }));
|
|
813
|
+
break;
|
|
814
|
+
case "key-create": {
|
|
815
|
+
const made = await call("/account/keys", {
|
|
816
|
+
name: (form.name ?? "").trim(),
|
|
817
|
+
scopes: Object.keys(form).filter((key) => key.startsWith("scope:")).map((key) => key.slice(6))
|
|
818
|
+
});
|
|
819
|
+
if (made.ok) shown = `<div class="msa-stack"><p class="msa-note" role="status">${escape(WORDS.account.keyShown)}</p>${secret(WORDS.account.keys, String(made.json?.key ?? ""))}</div>`;
|
|
820
|
+
else problem = made.message;
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
case "key-revoke":
|
|
824
|
+
await done(call("/account/keys/revoke", { id: form.id ?? "" }));
|
|
825
|
+
break;
|
|
826
|
+
case "grant-revoke": await done(call("/account/grants/revoke", { id: form.id ?? "" }));
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const [session, sessions, passkeys, keys, grants] = await Promise.all([
|
|
830
|
+
call("/get-session").then((one) => one.json ?? signedIn),
|
|
831
|
+
call("/account/sessions").then((one) => Array.isArray(one.json) ? one.json : []),
|
|
832
|
+
settings.methods.passkey ? call("/passkey/list-user-passkeys").then((one) => Array.isArray(one.json) ? one.json : []) : Promise.resolve([]),
|
|
833
|
+
Object.keys(deps.scopes).length ? call("/account/keys").then((one) => Array.isArray(one.json) ? one.json : []) : Promise.resolve([]),
|
|
834
|
+
call("/account/grants").then((one) => Array.isArray(one.json) ? one.json : [])
|
|
835
|
+
]);
|
|
836
|
+
const failed = problem ? SECTION_OF[form.action ?? ""] ?? "profile" : "";
|
|
837
|
+
return respond(shell(WORDS.account.title, back(app, redirect) + accountBody({
|
|
838
|
+
settings,
|
|
839
|
+
scopes: deps.scopes,
|
|
840
|
+
signedIn: session,
|
|
841
|
+
sessions,
|
|
842
|
+
passkeys,
|
|
843
|
+
keys,
|
|
844
|
+
grants,
|
|
845
|
+
problem,
|
|
846
|
+
failed,
|
|
847
|
+
notice,
|
|
848
|
+
shown,
|
|
849
|
+
made: form.action ?? ""
|
|
850
|
+
}), {
|
|
851
|
+
lead: String(session.user.email),
|
|
852
|
+
wide: true,
|
|
853
|
+
script: [copyScript(), settings.methods.passkey ? passkeyScript("add", `${UI}/account`) : ""].join(";")
|
|
854
|
+
}), problem ? 400 : 200);
|
|
855
|
+
}
|
|
856
|
+
case "/organization": {
|
|
857
|
+
const signedIn = (await call("/get-session")).json;
|
|
858
|
+
if (!signedIn) return away(`${UI}/sign-in?redirect=${encodeURIComponent(`${UI}/organization`)}`);
|
|
859
|
+
let problem = "";
|
|
860
|
+
let id = url.searchParams.get("id") ?? (typeof signedIn.session.activeOrganizationId === "string" ? signedIn.session.activeOrganizationId : "");
|
|
861
|
+
if (request.method === "POST") {
|
|
862
|
+
const result = await (async () => {
|
|
863
|
+
switch (form.action) {
|
|
864
|
+
case "create": {
|
|
865
|
+
const name = (form.name ?? "").trim();
|
|
866
|
+
const made = await call("/organization/create", {
|
|
867
|
+
name,
|
|
868
|
+
slug: name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48)
|
|
869
|
+
});
|
|
870
|
+
if (made.ok) id = String(made.json?.id ?? "");
|
|
871
|
+
return made;
|
|
872
|
+
}
|
|
873
|
+
case "switch":
|
|
874
|
+
id = form.id ?? "";
|
|
875
|
+
return call("/organization/set-active", { organizationId: id || null });
|
|
876
|
+
case "rename": return call("/organization/update", {
|
|
877
|
+
organizationId: id,
|
|
878
|
+
data: { name: (form.name ?? "").trim() }
|
|
879
|
+
});
|
|
880
|
+
case "invite": return call("/organization/invite-member", {
|
|
881
|
+
organizationId: id,
|
|
882
|
+
email: (form.email ?? "").trim(),
|
|
883
|
+
role: form.role ?? "member"
|
|
884
|
+
});
|
|
885
|
+
case "cancel": return call("/organization/cancel-invitation", { invitationId: form.invitation ?? "" });
|
|
886
|
+
case "role": return call("/organization/update-member-role", {
|
|
887
|
+
organizationId: id,
|
|
888
|
+
memberId: form.member ?? "",
|
|
889
|
+
role: form.role ?? "member"
|
|
890
|
+
});
|
|
891
|
+
case "remove": return call("/organization/remove-member", {
|
|
892
|
+
organizationId: id,
|
|
893
|
+
memberIdOrEmail: form.member ?? ""
|
|
894
|
+
});
|
|
895
|
+
case "leave": {
|
|
896
|
+
const left = await call("/organization/leave", { organizationId: id });
|
|
897
|
+
if (left.ok) id = "";
|
|
898
|
+
return left;
|
|
899
|
+
}
|
|
900
|
+
default: return {
|
|
901
|
+
ok: true,
|
|
902
|
+
message: ""
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
})();
|
|
906
|
+
if (!result.ok) problem = result.message;
|
|
907
|
+
else return away(id ? `${UI}/organization?id=${encodeURIComponent(id)}` : `${UI}/organization`);
|
|
908
|
+
}
|
|
909
|
+
const organizations = (await call("/organization/list")).json ?? [];
|
|
910
|
+
const full = id ? (await call(`/organization/get-full-organization?organizationId=${encodeURIComponent(id)}`)).json : null;
|
|
911
|
+
return respond(shell(full ? String(full.name) : WORDS.organizations.switch, back(app, redirect) + organizationBody({
|
|
912
|
+
organizations,
|
|
913
|
+
full,
|
|
914
|
+
userId: String(signedIn.user.id),
|
|
915
|
+
activeId: id,
|
|
916
|
+
problem
|
|
917
|
+
}), { wide: true }), problem ? 400 : 200);
|
|
918
|
+
}
|
|
919
|
+
default: {
|
|
920
|
+
const invitation = /^\/invitation\/([A-Za-z0-9_-]{1,100})$/.exec(path)?.[1];
|
|
921
|
+
if (!invitation) return respond(shell(WORDS.errors.notFound, `<p class="msa-note">${escape(WORDS.errors.nothingHere)}</p><p class="msa-foot"><a href="${UI}/sign-in">${escape(WORDS.signIn.submit)}</a></p>`), 404);
|
|
922
|
+
if (!(await call("/get-session")).json) return respond(shell(WORDS.invitation.title(app), `<p class="msa-note">${escape(WORDS.invitation.signInFirst)}</p><div class="msa-stack"><a href="${UI}/sign-in?redirect=${encodeURIComponent(path === "" ? "/" : `${UI}${path}`)}">${escape(WORDS.signIn.submit)}</a><a href="${UI}/sign-up?redirect=${encodeURIComponent(`${UI}${path}`)}">${escape(WORDS.signIn.signUp)}</a></div>`));
|
|
923
|
+
if (request.method === "POST") {
|
|
924
|
+
const answered = await call(form.action === "reject" ? "/organization/reject-invitation" : "/organization/accept-invitation", { invitationId: invitation });
|
|
925
|
+
if (answered.ok) return away(form.action === "reject" ? "/" : `${UI}/organization`);
|
|
926
|
+
return respond(shell(WORDS.invitation.title(app), `<p class="msa-error" role="alert">${escape(answered.message)}</p>`), 400);
|
|
927
|
+
}
|
|
928
|
+
const found = await call(`/organization/get-invitation?id=${encodeURIComponent(invitation)}`);
|
|
929
|
+
if (!found.ok || !found.json) return respond(shell(WORDS.invitation.title(app), `<p class="msa-note">${escape(WORDS.invitation.gone)}</p>`), 404);
|
|
930
|
+
const name = String(found.json.organizationName ?? app);
|
|
931
|
+
return respond(shell(WORDS.invitation.title(name), `<form method="post"><button class="msa-primary" name="action" value="accept">${escape(WORDS.invitation.accept)}</button><button class="msa-quiet" name="action" value="reject">${escape(WORDS.invitation.reject)}</button></form>`, { lead: WORDS.invitation.lead(typeof found.json.inviterEmail === "string" ? found.json.inviterEmail : void 0, name, app) }));
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
function codeForm(email, problem) {
|
|
935
|
+
return `<form method="post"><input type="hidden" name="email" value="${escape(email)}"><label>${escape(WORDS.fields.code)}<input name="code" required autocomplete="one-time-code" inputmode="numeric" autofocus></label><p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary" name="action" value="verify">${escape(WORDS.code.submit)}</button></form>`;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
/** What a hosted page may load: its own styles, the person's own address for forms, and the bot check when set. */
|
|
939
|
+
function csp(nonce, settings) {
|
|
940
|
+
const captcha = settings.captcha ? new URL(CAPTCHA_WIDGETS[settings.captcha.provider].script).origin : "";
|
|
941
|
+
return [
|
|
942
|
+
`default-src 'none'`,
|
|
943
|
+
`style-src 'unsafe-inline'`,
|
|
944
|
+
`img-src https: data:`,
|
|
945
|
+
`script-src 'nonce-${nonce}'${captcha ? ` ${captcha}` : ""}`,
|
|
946
|
+
`frame-src ${captcha || "'none'"}`,
|
|
947
|
+
`connect-src 'self'${captcha ? ` ${captcha}` : ""}`,
|
|
948
|
+
`form-action 'self' https:`,
|
|
949
|
+
`frame-ancestors 'none'`,
|
|
950
|
+
`base-uri 'none'`
|
|
951
|
+
].join("; ");
|
|
952
|
+
}
|
|
953
|
+
function page(input) {
|
|
954
|
+
const { settings } = input;
|
|
955
|
+
const captcha = settings.captcha ? `<script src="${escape(CAPTCHA_WIDGETS[settings.captcha.provider].script)}" async defer><\/script>` : "";
|
|
956
|
+
const brand = settings.branding.color ? ` style="--msa-brand:${escape(settings.branding.color)}"` : "";
|
|
957
|
+
return `<!doctype html>
|
|
958
|
+
<html lang="en">
|
|
959
|
+
<head>
|
|
960
|
+
<meta charset="utf-8">
|
|
961
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
962
|
+
<meta name="robots" content="noindex">
|
|
963
|
+
<title>${escape(input.title)} · ${escape(settings.branding.name)}</title>
|
|
964
|
+
<style>body{margin:0;min-height:100vh;display:grid;place-items:center;padding:24px 16px;background:#fafafa;font-family:system-ui,-apple-system,sans-serif}@media (prefers-color-scheme:dark){body{background:#09090b}}${AUTH_CSS}</style>
|
|
965
|
+
${captcha}
|
|
966
|
+
</head>
|
|
967
|
+
<body>
|
|
968
|
+
<main class="msa"${brand}>
|
|
969
|
+
<div class="msa-card${input.wide ? " msa-wide" : ""}">
|
|
970
|
+
${settings.branding.logo ? `<img class="msa-logo" src="${escape(settings.branding.logo)}" alt="${escape(settings.branding.name)}">` : ""}
|
|
971
|
+
<h1>${escape(input.title)}</h1>
|
|
972
|
+
${input.lead ? `<p class="msa-lead">${escape(input.lead)}</p>` : ""}
|
|
973
|
+
${input.body}
|
|
974
|
+
</div>
|
|
975
|
+
</main>
|
|
976
|
+
${input.script ? `<script nonce="${input.nonce}">${input.script}<\/script>` : ""}
|
|
977
|
+
</body>
|
|
978
|
+
</html>
|
|
979
|
+
`;
|
|
980
|
+
}
|
|
981
|
+
/** The way back to the app from a page a person was sent to. */
|
|
982
|
+
const back = (app, to) => `<a class="msa-back" href="${escape(to)}">${escape(WORDS.account.back(app))}</a>`;
|
|
983
|
+
function captchaWidget(settings) {
|
|
984
|
+
return settings.captcha ? `<div class="${CAPTCHA_WIDGETS[settings.captcha.provider].className}" data-sitekey="${escape(settings.captcha.siteKey)}"></div>` : "";
|
|
985
|
+
}
|
|
986
|
+
function signInForm(settings, problem, search) {
|
|
987
|
+
const { methods } = settings;
|
|
988
|
+
const social = ["google", "github"].filter((one) => methods[one]);
|
|
989
|
+
const quick = social.length || methods.passkey ? `<div class="msa-stack">${social.map((one) => `<form method="post"><button name="action" value="${one}">${escape(WORDS.ways[one])}</button></form>`).join("")}${methods.passkey ? `<button type="button" id="msa-passkey">${escape(WORDS.ways.passkey)}</button>` : ""}</div><div class="msa-or">${escape(WORDS.ways.or)}</div>` : "";
|
|
990
|
+
const password = methods.password ? `<label>${escape(WORDS.fields.password)}<input type="password" name="password" autocomplete="current-password"></label>` : "";
|
|
991
|
+
const others = [methods.code ? `<button class="msa-quiet" name="action" value="code" formnovalidate>${escape(WORDS.ways.code)}</button>` : "", methods.link ? `<button class="msa-quiet" name="action" value="link" formnovalidate>${escape(WORDS.ways.link)}</button>` : ""].join("");
|
|
992
|
+
const main = methods.password ? `<button class="msa-primary" name="action" value="password">${escape(WORDS.signIn.submit)}</button>` : methods.code ? `<button class="msa-primary" name="action" value="code">${escape(WORDS.ways.code)}</button>` : methods.link ? `<button class="msa-primary" name="action" value="link">${escape(WORDS.ways.link)}</button>` : "";
|
|
993
|
+
const foot = [methods.password ? `<a href="${UI}/reset-password">${escape(WORDS.signIn.forgot)}</a>` : "", settings.signUp.policy === "invite" ? "" : `${escape(WORDS.signIn.noAccount)} <a href="${UI}/sign-up${escape(search)}">${escape(WORDS.signIn.signUp)}</a>`].filter(Boolean).join(" · ");
|
|
994
|
+
return `${quick}<form method="post"><label>${escape(WORDS.fields.email)}<input type="email" name="email" required autocomplete="email"></label>${password}${captchaWidget(settings)}<p class="msa-error" role="alert">${escape(problem)}</p>${main}${methods.password && others ? `<div class="msa-stack">${others}</div>` : ""}</form><p class="msa-foot">${foot}</p>`;
|
|
995
|
+
}
|
|
996
|
+
function signUpForm(settings, problem, search) {
|
|
997
|
+
return `<form method="post"><label>${escape(WORDS.fields.name)}<input name="name" required autocomplete="name"></label><label>${escape(WORDS.fields.email)}<input type="email" name="email" required autocomplete="email"></label><label>${escape(WORDS.fields.password)}<input type="password" name="password" required autocomplete="new-password" minlength="8"></label>${captchaWidget(settings)}<p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary">${escape(settings.signUp.policy === "waitlist" ? WORDS.signUp.waitlist : WORDS.signUp.submit)}</button></form><p class="msa-foot">${escape(WORDS.signUp.haveAccount)} <a href="${UI}/sign-in${escape(search)}">${escape(WORDS.signUp.signIn)}</a></p>`;
|
|
998
|
+
}
|
|
999
|
+
function twoFactorForm(problem, mailed) {
|
|
1000
|
+
return `<form method="post"><label>${escape(WORDS.fields.code)}<input name="code" required autocomplete="one-time-code" inputmode="numeric" autofocus></label><p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary" name="action" value="${mailed ? "mail-code" : "totp"}">${escape(WORDS.twoFactor.submit)}</button></form><form method="post" class="msa-stack" style="margin-top:12px"><button class="msa-quiet" name="action" value="send">${escape(WORDS.twoFactor.byMail)}</button></form><form method="post" style="margin-top:12px"><label>${escape(WORDS.twoFactor.backupField)}<input name="code" required autocomplete="off"></label><button name="action" value="backup">${escape(WORDS.twoFactor.backup)}</button></form>`;
|
|
1001
|
+
}
|
|
1002
|
+
function resetForm(settings, problem) {
|
|
1003
|
+
return `<form method="post"><label>${escape(WORDS.fields.email)}<input type="email" name="email" required autocomplete="email"></label>${captchaWidget(settings)}<p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary">${escape(WORDS.reset.submit)}</button></form>`;
|
|
1004
|
+
}
|
|
1005
|
+
function newPasswordForm(problem) {
|
|
1006
|
+
return `<form method="post"><label>${escape(WORDS.fields.newPassword)}<input type="password" name="password" required autocomplete="new-password" minlength="8"></label><p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary">${escape(WORDS.reset.save)}</button></form>`;
|
|
1007
|
+
}
|
|
1008
|
+
/** A value shown once, on one line, with a Copy button that says when it copied (`copyScript`). */
|
|
1009
|
+
const secret = (label, value) => `<div class="msa-secret"><code aria-label="${escape(label)}">${escape(value)}</code><button type="button" data-copy="${escape(value)}">${escape(WORDS.account.copy)}</button></div>`;
|
|
1010
|
+
function twoFactorSetup(uri, codes) {
|
|
1011
|
+
return `<div class="msa-stack"><p class="msa-note">${escape(WORDS.account.twoFactorSetup)}</p>${qrSvg(uri, WORDS.account.qr)}${secret(WORDS.account.setupKey, setupKeyOf(uri))}<a href="${escape(uri)}">${escape(WORDS.account.openInApp)}</a><p class="msa-note">${escape(WORDS.account.backupCodes)}</p><ul class="msa-codes">${codes.map((one) => `<li><code>${escape(one)}</code></li>`).join("")}</ul><div><button type="button" data-copy="${escape(codes.join("\n"))}">${escape(WORDS.account.copyCodes)}</button></div><form method="post"><label>${escape(WORDS.fields.code)}<input name="code" required autocomplete="one-time-code" inputmode="numeric"></label><button name="action" value="two-factor-verify">${escape(WORDS.twoFactor.submit)}</button></form></div>`;
|
|
1012
|
+
}
|
|
1013
|
+
const row = (title, detail, action = "") => `<div class="msa-row"><div><strong>${escape(title)}</strong><span>${escape(detail)}</span></div>${action}</div>`;
|
|
1014
|
+
/** A row's action; one that removes something asks first, by opening to its button for good. */
|
|
1015
|
+
const rowButton = (action, words, fields = {}, confirm) => {
|
|
1016
|
+
const hidden = Object.entries(fields).map(([name, value]) => `<input type="hidden" name="${escape(name)}" value="${escape(value)}">`).join("");
|
|
1017
|
+
if (!confirm) return `<form method="post">${hidden}<button class="msa-quiet" name="action" value="${escape(action)}">${escape(words)}</button></form>`;
|
|
1018
|
+
return `<details><summary class="msa-danger">${escape(words)}</summary><form method="post">${hidden}<button class="msa-danger" name="action" value="${escape(action)}">${escape(confirm)}</button></form></details>`;
|
|
1019
|
+
};
|
|
1020
|
+
/** The account page's section each of its forms belongs to, where a refusal of it is said. */
|
|
1021
|
+
const SECTION_OF = {
|
|
1022
|
+
profile: "profile",
|
|
1023
|
+
password: "security",
|
|
1024
|
+
"two-factor-on": "security",
|
|
1025
|
+
"two-factor-verify": "security",
|
|
1026
|
+
"two-factor-off": "security",
|
|
1027
|
+
"passkey-remove": "passkeys",
|
|
1028
|
+
"session-revoke": "sessions",
|
|
1029
|
+
"key-create": "agents",
|
|
1030
|
+
"key-revoke": "agents",
|
|
1031
|
+
"grant-revoke": "agents"
|
|
1032
|
+
};
|
|
1033
|
+
/** The few lines a Copy button needs: the value to the clipboard, and the button saying it copied. */
|
|
1034
|
+
function copyScript() {
|
|
1035
|
+
return `document.querySelectorAll("[data-copy]").forEach((b)=>b.addEventListener("click",()=>{if(navigator.clipboard)navigator.clipboard.writeText(b.getAttribute("data-copy")||"").then(()=>{b.textContent=${JSON.stringify(WORDS.account.copied)}},()=>{})}))`;
|
|
1036
|
+
}
|
|
1037
|
+
function accountBody(input) {
|
|
1038
|
+
const { user, session } = input.signedIn;
|
|
1039
|
+
/** Where a section says a refusal of one of its forms. */
|
|
1040
|
+
const problemIn = (section) => `<p class="msa-error" role="alert" data-for="${section}">${input.failed === section ? escape(input.problem) : ""}</p>`;
|
|
1041
|
+
/** What a form of a section made, such as a new key, shown under it. */
|
|
1042
|
+
const shownIn = (section) => input.shown && SECTION_OF[input.made] === section ? input.shown : "";
|
|
1043
|
+
const words = WORDS.account;
|
|
1044
|
+
const twoFactor = user.twoFactorEnabled === true;
|
|
1045
|
+
const profile = `<section><h2>${escape(words.profile)}</h2>${problemIn("profile")}<form method="post"><label>${escape(WORDS.fields.name)}<input name="name" value="${escape(user.name)}" required autocomplete="name"></label><div><button name="action" value="profile">${escape(words.save)}</button></div></form></section>`;
|
|
1046
|
+
const password = input.settings.methods.password ? `<form method="post"><label>${escape(WORDS.fields.currentPassword)}<input type="password" name="current" required autocomplete="current-password"></label><label>${escape(WORDS.fields.newPassword)}<input type="password" name="next" required autocomplete="new-password" minlength="8"></label><div><button name="action" value="password">${escape(words.changePassword)}</button></div></form>` : "";
|
|
1047
|
+
const twoFactorRow = `<div class="msa-row" style="margin-top:12px"><div><strong>${escape(twoFactor ? words.twoFactorOn : words.twoFactorOff)}</strong></div><form method="post" style="display:flex;gap:8px;align-items:end"><label>${escape(words.yourPassword)}<input type="password" name="password" required autocomplete="current-password"></label><button name="action" value="${twoFactor ? "two-factor-off" : "two-factor-on"}">${escape(twoFactor ? words.turnOff : words.turnOn)}</button></form></div>`;
|
|
1048
|
+
const passkeys = input.settings.methods.passkey ? `<section><h2>${escape(words.passkeys)}</h2>${problemIn("passkeys")}${input.passkeys.length ? input.passkeys.map((one) => row(String(one.name || words.passkey), ago(one.createdAt), rowButton("passkey-remove", words.remove, { id: String(one.id) }, words.removeForGood))).join("") : `<p class="msa-note">${escape(words.noPasskeys)}</p>`}<div style="margin-top:12px"><button type="button" id="msa-passkey">${escape(words.addPasskey)}</button></div></section>` : "";
|
|
1049
|
+
const sessions = `<section><h2>${escape(words.sessions)}</h2>${problemIn("sessions")}${input.sessions.map((one) => row(one.id === session.id ? words.thisDevice : deviceOf(one.userAgent) ?? words.unknownDevice, [
|
|
1050
|
+
typeof one.impersonatedBy === "string" && one.impersonatedBy ? words.signedInBy(one.impersonatedBy) : "",
|
|
1051
|
+
ago(one.createdAt),
|
|
1052
|
+
typeof one.ipAddress === "string" ? one.ipAddress : ""
|
|
1053
|
+
].filter(Boolean).join(" · "), one.id === session.id ? "" : rowButton("session-revoke", words.signOut, { token: String(one.token) }))).join("")}<form method="post" style="margin-top:12px"><button name="action" value="sign-out">${escape(WORDS.user.signOut)}</button></form></section>`;
|
|
1054
|
+
const scopes = Object.entries(input.scopes);
|
|
1055
|
+
const keys = scopes.length ? `${input.keys.length ? input.keys.map((one) => row(String(one.name ?? one.start ?? one.id), [(one.scopes ?? []).map((scope) => input.scopes[scope] ?? scope).join(", "), one.lastUsedAt ? words.lastUsed(ago(one.lastUsedAt)) : words.neverUsed].join(" · "), rowButton("key-revoke", words.revoke, { id: String(one.id) }, words.revokeForGood))).join("") : `<p class="msa-note">${escape(words.noKeys)}</p>`}<form method="post" style="margin-top:12px"><label>${escape(WORDS.fields.keyName)}<input name="name" required maxlength="32"></label><fieldset style="border:0;padding:0;margin:0;display:grid;gap:6px"><legend style="font-weight:500;font-size:14px;margin-bottom:6px">${escape(words.scopes)}</legend>${scopes.map(([scope, what]) => `<label style="display:flex;gap:8px;align-items:center;font-weight:400"><input type="checkbox" name="scope:${escape(scope)}" style="width:auto;min-height:0">${escape(what)}</label>`).join("")}</fieldset><div><button name="action" value="key-create">${escape(words.createKey)}</button></div></form>` : "";
|
|
1056
|
+
const grants = `<h2 style="margin-top:20px">${escape(words.apps)}</h2>${input.grants.length ? input.grants.map((one) => row(String(one.client ?? one.clientId), (one.scopes ?? []).map((scope) => input.scopes[scope] ?? scope).join(", "), rowButton("grant-revoke", words.removeAccess, { id: String(one.id) }, words.removeAccessForGood))).join("") : `<p class="msa-note">${escape(words.noApps)}</p>`}`;
|
|
1057
|
+
const agents = scopes.length || input.grants.length ? `<section><h2>${escape(words.agents)}</h2>${problemIn("agents")}${shownIn("agents")}${keys}${grants}</section>` : "";
|
|
1058
|
+
return `${input.notice ? `<p class="msa-note" role="status">${escape(input.notice)}</p>` : ""}${profile}<section><h2>${escape(words.security)}</h2>${problemIn("security")}${password}${twoFactorRow}${shownIn("security")}</section>${passkeys}${sessions}${agents}`;
|
|
1059
|
+
}
|
|
1060
|
+
function organizationBody(input) {
|
|
1061
|
+
const words = WORDS.organizations, roles = words.roles;
|
|
1062
|
+
const roleOptions = (chosen) => Object.keys(roles).map((one) => `<option value="${one}"${one === chosen ? " selected" : ""}>${escape(roles[one])}</option>`).join("");
|
|
1063
|
+
const switcher = `<section><form method="post" style="display:flex;gap:8px;align-items:end"><label style="flex:1">${escape(words.switch)}<select name="id"><option value="">${escape(words.personal)}</option>${input.organizations.map((one) => `<option value="${escape(one.id)}"${one.id === input.activeId ? " selected" : ""}>${escape(one.name)}</option>`).join("")}</select></label><button name="action" value="switch">${escape(words.switchTo)}</button></form><form method="post" style="display:flex;gap:8px;align-items:end;margin-top:12px"><label style="flex:1">${escape(WORDS.fields.organization)}<input name="name" required></label><button name="action" value="create">${escape(words.create)}</button></form></section>`;
|
|
1064
|
+
const full = input.full;
|
|
1065
|
+
if (!full) return `<p class="msa-error" role="alert">${escape(input.problem)}</p>${switcher}`;
|
|
1066
|
+
const members = full.members ?? [];
|
|
1067
|
+
const me = members.find((member) => member.userId === input.userId);
|
|
1068
|
+
const manages = me?.role === "owner" || me?.role === "admin";
|
|
1069
|
+
const memberRows = members.map((member) => {
|
|
1070
|
+
const user = member.user ?? {};
|
|
1071
|
+
const action = manages && member.userId !== input.userId ? `<div style="display:flex;gap:8px"><form method="post" style="display:flex;gap:8px"><input type="hidden" name="member" value="${escape(member.id)}"><select name="role" aria-label="${escape(WORDS.fields.role)}, ${escape(user.email)}" style="width:auto">${roleOptions(String(member.role))}</select><button class="msa-quiet" name="action" value="role">${escape(words.save)}</button></form>${rowButton("remove", words.remove, { member: String(member.id) }, words.removeForGood)}</div>` : `<span>${escape(roles[member.role] ?? member.role)}</span>`;
|
|
1072
|
+
return row(String(user.name || user.email), String(user.email ?? ""), action);
|
|
1073
|
+
}).join("");
|
|
1074
|
+
const pending = (full.invitations ?? []).filter((one) => one.status === "pending");
|
|
1075
|
+
const invitations = manages ? `<section><h2>${escape(words.invitations)}</h2>${pending.length ? pending.map((one) => row(String(one.email), roles[one.role ?? "member"] ?? String(one.role), rowButton("cancel", words.cancel, { invitation: String(one.id) }, words.cancel))).join("") : `<p class="msa-note">${escape(words.noInvitations)}</p>`}<form method="post" style="margin-top:12px"><label>${escape(WORDS.fields.inviteEmail)}<input type="email" name="email" required autocomplete="off"></label><label>${escape(WORDS.fields.role)}<select name="role">${roleOptions("member")}</select></label><div><button name="action" value="invite">${escape(words.invite)}</button></div></form></section>` : "";
|
|
1076
|
+
const rename = manages ? `<section><h2>${escape(words.settings)}</h2><form method="post"><label>${escape(WORDS.fields.organization)}<input name="name" value="${escape(full.name)}" required></label><div><button name="action" value="rename">${escape(words.save)}</button></div></form></section>` : "";
|
|
1077
|
+
const leave = me && me.role !== "owner" ? `<section>${rowButton("leave", words.leave, {}, words.leaveForGood)}</section>` : "";
|
|
1078
|
+
return `<p class="msa-error" role="alert">${escape(input.problem)}</p>${switcher}${rename}<section><h2>${escape(words.members)}</h2>${memberRows}</section>${invitations}${leave}`;
|
|
1079
|
+
}
|
|
1080
|
+
/** The few lines passkeys need: the browser's own prompt, between two calls to sign-in. */
|
|
1081
|
+
function passkeyScript(kind, then) {
|
|
1082
|
+
return `(()=>{const b=document.getElementById("msa-passkey");if(!b||!window.PublicKeyCredential)return;
|
|
1083
|
+
const d=(t)=>Uint8Array.from(atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),(c)=>c.charCodeAt(0));
|
|
1084
|
+
const e=(x)=>btoa(String.fromCharCode(...new Uint8Array(x))).replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=+$/,"");
|
|
1085
|
+
const j=(c)=>{const r=c.response,f={clientDataJSON:e(r.clientDataJSON)};if(r.attestationObject){f.attestationObject=e(r.attestationObject);f.transports=r.getTransports?r.getTransports():[]}if(r.authenticatorData){f.authenticatorData=e(r.authenticatorData);f.signature=e(r.signature);if(r.userHandle)f.userHandle=e(r.userHandle)}return{id:c.id,rawId:e(c.rawId),type:c.type,response:f,clientExtensionResults:c.getClientExtensionResults()}};
|
|
1086
|
+
const p=(u,o)=>fetch("/api/auth"+u,o?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),credentials:"include"}:{credentials:"include"}).then(async(r)=>{const t=await r.json().catch(()=>null);if(!r.ok)throw new Error((t&&t.message)||${JSON.stringify(WORDS.errors.generic)});return t});
|
|
1087
|
+
const say=(m)=>{const a=document.querySelector("[data-for=passkeys]")||document.querySelector("[role=alert]");if(a)a.textContent=m};
|
|
1088
|
+
b.addEventListener("click",async()=>{b.disabled=true;try{
|
|
1089
|
+
${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options");o.challenge=d(o.challenge);o.allowCredentials=(o.allowCredentials||[]).map((c)=>({...c,id:d(c.id)}));const c=await navigator.credentials.get({publicKey:o});const q=new URLSearchParams(location.search).has("sig")?{oauth_query:location.search.slice(1)}:{};const a=await p("/passkey/verify-authentication",{response:j(c),...q});location.href=a&&a.redirect&&a.url?a.url:${JSON.stringify(then)}` : `const o=await p("/passkey/generate-register-options");o.challenge=d(o.challenge);o.user.id=d(o.user.id);o.excludeCredentials=(o.excludeCredentials||[]).map((c)=>({...c,id:d(c.id)}));const c=await navigator.credentials.create({publicKey:o});await p("/passkey/verify-registration",{response:j(c)});location.href=${JSON.stringify(then)}`}
|
|
1090
|
+
}catch(x){say(x&&x.name==="NotAllowedError"?${JSON.stringify(WORDS.errors.passkeyCancelled)}:(x&&x.message)||${JSON.stringify(WORDS.errors.generic)})}finally{b.disabled=false}})})()`;
|
|
1091
|
+
}
|
|
1092
|
+
//#endregion
|
|
1093
|
+
//#region src/auth/index.ts
|
|
1094
|
+
/**
|
|
1095
|
+
* Auth: sign-in for the people who use your app, with one import, on Midsummer or anywhere else.
|
|
1096
|
+
*
|
|
1097
|
+
* import { auth } from "@midsummer-ai/sdk/auth"
|
|
1098
|
+
*
|
|
1099
|
+
* app.all("/api/auth/*", (c) => auth.handler(c.req.raw)) // sign-up, sign-in, sign-out, codes, Google, GitHub, the hosted pages
|
|
1100
|
+
* const signedIn = await auth.session(c.req.raw) // { user, session } or null
|
|
1101
|
+
* if (!signedIn) return c.redirect("/api/auth/ui/sign-in")
|
|
1102
|
+
*
|
|
1103
|
+
* Email and password, codes and sign-in links by mail, Google and GitHub when their keys are set, organizations with
|
|
1104
|
+
* roles and invitations, two-factor codes, passkeys and bans. Browsers talk to it with `@midsummer-ai/sdk/auth/client`,
|
|
1105
|
+
* the drop-in screens in `@midsummer-ai/sdk/auth/react`, or the hosted pages under `/api/auth/ui`.
|
|
1106
|
+
*
|
|
1107
|
+
* Users, sessions and accounts are tables in the app's own database (`db/authTables.ts` and `db/auth.ts`, which
|
|
1108
|
+
* `midsummer auth init` writes), so they join with its own tables and branch with it: a preview starts with no users.
|
|
1109
|
+
* A session is kept in its cookie for five minutes, signed, so most requests read no row; a session revoked or a user
|
|
1110
|
+
* banned stops within those five minutes. Mail goes through Email (`./mail.ts`). The app's settings (which ways in
|
|
1111
|
+
* are on, who may sign up, its branding) are a row of the same database, read every few seconds (`./settings.ts`).
|
|
1112
|
+
*
|
|
1113
|
+
* Where it finds its database:
|
|
1114
|
+
* - On Midsummer, the environment's binding (`main`, or `createAuth({ database })`).
|
|
1115
|
+
* - Anywhere else (Vercel, Fly, your laptop), a database key: `DATABASE_KEY` in the server's environment, or
|
|
1116
|
+
* `createAuth({ key })`. Make one with `midsummer db key create`.
|
|
1117
|
+
* - Under `midsummer dev`, the database's Stand-in when `db/` runs, or memory.
|
|
1118
|
+
* It also needs `AUTH_SECRET` (`midsummer env set <project> AUTH_SECRET --kind secret --generate`, once for each
|
|
1119
|
+
* environment; elsewhere any random 32 characters or more), and reads `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`,
|
|
1120
|
+
* `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`, and on previews `AUTH_PRODUCTION_URL` and `AUTH_PROXY_SECRET`, which
|
|
1121
|
+
* `midsummer auth provider set` writes. `AUTH_EMAIL_FROM` sends its mail from a domain of the Team's.
|
|
1122
|
+
*
|
|
1123
|
+
* Agents sign in too, once the app declares what they may do (`createAuth({ scopes })`, `./agents.ts`): a user gives
|
|
1124
|
+
* an agent an API key (`auth.keys.create`), or signs in from an MCP client, which finds the app's own OAuth server
|
|
1125
|
+
* under `/api/auth` and `/.well-known`. `auth.session(request, { scope })` is a person, a key or a client alike, and
|
|
1126
|
+
* `auth.protect(scope, handler)` guards a route such as the app's MCP server.
|
|
1127
|
+
*
|
|
1128
|
+
* Each sign-up, sign-in, ban and key is reported to the platform as an event (`./events.ts`), after the request.
|
|
1129
|
+
* In tests, give it the Stand-in: `createAuth({ store: stand.store, mail: stand.mail })`. Every failure it can name
|
|
1130
|
+
* is an `AuthError`, whose `code` tells you which kind.
|
|
1131
|
+
*/
|
|
1132
|
+
var AuthError = class extends Error {
|
|
1133
|
+
code;
|
|
1134
|
+
/** The scope an agent lacked, when that is why it was refused. */
|
|
1135
|
+
scope;
|
|
1136
|
+
constructor(code, message, scope) {
|
|
1137
|
+
super(message);
|
|
1138
|
+
this.code = code;
|
|
1139
|
+
this.name = "AuthError";
|
|
1140
|
+
if (scope !== void 0) this.scope = scope;
|
|
1141
|
+
}
|
|
1142
|
+
};
|
|
1143
|
+
/** Where sign-in is served, under every address of the app. */
|
|
1144
|
+
const AUTH_PATH = "/api/auth";
|
|
1145
|
+
/** How long a session is kept in its cookie before its row is read again, in seconds. */
|
|
1146
|
+
const SESSION_CACHE_S = 300;
|
|
1147
|
+
/** How long a session the platform's "sign in as" makes lasts, in seconds. */
|
|
1148
|
+
const IMPERSONATION_S = 1800;
|
|
1149
|
+
/** Under `midsummer dev`, where no environment gives a secret: never accepted outside it. */
|
|
1150
|
+
const DEV_SECRET = "midsummer-dev-sign-in-secret-never-used-outside-midsummer-dev";
|
|
1151
|
+
/** How many addresses one process keeps sign-in ready for; past it the oldest is made again when asked. */
|
|
1152
|
+
const KEPT_ORIGINS = 16;
|
|
1153
|
+
const API = "https://api.midsummer.new";
|
|
1154
|
+
const METADATA_BYTES = 8192;
|
|
1155
|
+
/** The origin a request came to, as the dispatcher routed it. */
|
|
1156
|
+
function originOf(request) {
|
|
1157
|
+
return new URL(request.url).origin;
|
|
1158
|
+
}
|
|
1159
|
+
/** The Database connection a request's sign-in uses: one per request in a deployment, one per process elsewhere. */
|
|
1160
|
+
function requestDatabase(open, what) {
|
|
1161
|
+
const perRequest = /* @__PURE__ */ new WeakMap();
|
|
1162
|
+
let shared;
|
|
1163
|
+
return () => {
|
|
1164
|
+
const request = here();
|
|
1165
|
+
const made = () => open().catch((error) => {
|
|
1166
|
+
throw new AuthError("unavailable", `Sign-in couldn't reach ${what}: ${error.message}`);
|
|
1167
|
+
});
|
|
1168
|
+
if (!request) {
|
|
1169
|
+
shared ??= made();
|
|
1170
|
+
shared.catch(() => {
|
|
1171
|
+
shared = void 0;
|
|
1172
|
+
});
|
|
1173
|
+
return shared;
|
|
1174
|
+
}
|
|
1175
|
+
let found = perRequest.get(request);
|
|
1176
|
+
if (!found) {
|
|
1177
|
+
found = made();
|
|
1178
|
+
perRequest.set(request, found);
|
|
1179
|
+
}
|
|
1180
|
+
return found;
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
/** The store sign-in keeps rows in where this code runs. */
|
|
1184
|
+
function storeFor(options, env) {
|
|
1185
|
+
if (options.store) return options.store;
|
|
1186
|
+
const binding = options.database ?? "main";
|
|
1187
|
+
if (here() || env.MIDSUMMER_DATABASE_URL || env.MIDSUMMER_IDENTITY_REQUEST_TOKEN) return databaseStore(requestDatabase(() => connect({ binding }), `the database bound as ${binding}`));
|
|
1188
|
+
const key = options.key ?? env.DATABASE_KEY;
|
|
1189
|
+
if (key) return databaseStore(requestDatabase(() => connect({
|
|
1190
|
+
key,
|
|
1191
|
+
api: options.api ?? API
|
|
1192
|
+
}), "its database with DATABASE_KEY"));
|
|
1193
|
+
if (env.MIDSUMMER_DEV === "1") return devStore();
|
|
1194
|
+
throw new AuthError("forbidden", "Sign-in has no database here. Outside Midsummer, set DATABASE_KEY to a database key (midsummer db key create). In tests, give createAuth the Stand-in: createAuth({ store: standIn().store }).");
|
|
1195
|
+
}
|
|
1196
|
+
/** `midsummer dev` without a database: one Stand-in for the process, its rows gone when it stops. */
|
|
1197
|
+
let devMemory;
|
|
1198
|
+
const devStore = () => devMemory ??= standIn().store;
|
|
1199
|
+
/** Where events go from where this code runs: the request's handle on Midsummer, the platform's API elsewhere, or nowhere. */
|
|
1200
|
+
function eventSendFor(options, env) {
|
|
1201
|
+
if (options.events) return options.events;
|
|
1202
|
+
const handle = here()?.auth;
|
|
1203
|
+
if (handle) return async (batch) => {
|
|
1204
|
+
await handle.report(batch);
|
|
1205
|
+
return "sent";
|
|
1206
|
+
};
|
|
1207
|
+
if (here() || options.store) return null;
|
|
1208
|
+
const key = options.key ?? env.DATABASE_KEY;
|
|
1209
|
+
if (key) return httpSend(`${options.api ?? API}/v1/db/auth/events`, { key });
|
|
1210
|
+
const workload = env.MIDSUMMER_IDENTITY_REQUEST_TOKEN, tokenUrl = env.MIDSUMMER_IDENTITY_TOKEN_URL;
|
|
1211
|
+
if (workload && tokenUrl) return httpSend(`${new URL(tokenUrl).origin}/v1/db/auth/events`, {
|
|
1212
|
+
workload,
|
|
1213
|
+
binding: options.database ?? "main"
|
|
1214
|
+
});
|
|
1215
|
+
return null;
|
|
1216
|
+
}
|
|
1217
|
+
/** Where sign-in mail goes from outside Midsummer: the platform's mail Action, with the same proof events carry. */
|
|
1218
|
+
function remoteMailFor(options, env) {
|
|
1219
|
+
if (here() || options.store) return void 0;
|
|
1220
|
+
const key = options.key ?? env.DATABASE_KEY;
|
|
1221
|
+
if (key) return {
|
|
1222
|
+
url: `${options.api ?? API}/v1/db/auth/mail`,
|
|
1223
|
+
proof: { key }
|
|
1224
|
+
};
|
|
1225
|
+
const workload = env.MIDSUMMER_IDENTITY_REQUEST_TOKEN, tokenUrl = env.MIDSUMMER_IDENTITY_TOKEN_URL;
|
|
1226
|
+
if (workload && tokenUrl) return {
|
|
1227
|
+
url: `${new URL(tokenUrl).origin}/v1/db/auth/mail`,
|
|
1228
|
+
proof: {
|
|
1229
|
+
workload,
|
|
1230
|
+
binding: options.database ?? "main"
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
/** How agents sign in, from the app's options. */
|
|
1235
|
+
const agentSettings = (options) => ({
|
|
1236
|
+
scopes: options.scopes ?? {},
|
|
1237
|
+
mcpPath: options.mcpPath ?? "/mcp",
|
|
1238
|
+
signInPage: options.signInPage ?? `/api/auth/ui/sign-in`,
|
|
1239
|
+
consentPage: options.consentPage ?? CONSENT_PATH
|
|
1240
|
+
});
|
|
1241
|
+
/** Where sign-in's own page asks a person whether to let an MCP client in. */
|
|
1242
|
+
const CONSENT_PATH = `${AUTH_PATH}/agent-consent`;
|
|
1243
|
+
const DAY_S = 86400;
|
|
1244
|
+
const keyOf = (row) => ({
|
|
1245
|
+
id: row.id,
|
|
1246
|
+
name: row.name,
|
|
1247
|
+
start: row.start,
|
|
1248
|
+
scopes: row.permissions?.scope ?? [],
|
|
1249
|
+
createdAt: new Date(row.createdAt),
|
|
1250
|
+
expiresAt: row.expiresAt ? new Date(row.expiresAt) : null,
|
|
1251
|
+
lastUsedAt: row.lastRequest ? new Date(row.lastRequest) : null
|
|
1252
|
+
});
|
|
1253
|
+
/**
|
|
1254
|
+
* What changes the signed-in user or their session as the cookie keeps it: after one, the cookie is written again
|
|
1255
|
+
* from the rows, so the app and the browser see the change at once rather than when the cookie's five minutes end.
|
|
1256
|
+
*/
|
|
1257
|
+
const FRESHENS = /* @__PURE__ */ new Set([
|
|
1258
|
+
"/organization/set-active",
|
|
1259
|
+
"/organization/create",
|
|
1260
|
+
"/organization/leave",
|
|
1261
|
+
"/organization/accept-invitation",
|
|
1262
|
+
"/update-user",
|
|
1263
|
+
"/two-factor/verify-totp",
|
|
1264
|
+
"/two-factor/disable"
|
|
1265
|
+
]);
|
|
1266
|
+
async function freshened(engine, origin, request, answered) {
|
|
1267
|
+
const set = answered.headers.getSetCookie();
|
|
1268
|
+
const cookies = new Map((request.headers.get("cookie") ?? "").split(";").map((pair) => pair.trim()).filter(Boolean).map((pair) => [pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1)]));
|
|
1269
|
+
for (const line of set) {
|
|
1270
|
+
const [pair = ""] = line.split(";");
|
|
1271
|
+
cookies.set(pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1));
|
|
1272
|
+
}
|
|
1273
|
+
const read = await engine.handler(new Request(`${origin}${AUTH_PATH}/get-session?disableCookieCache=true`, { headers: {
|
|
1274
|
+
cookie: [...cookies].map(([name, value]) => `${name}=${value}`).join("; "),
|
|
1275
|
+
origin
|
|
1276
|
+
} }));
|
|
1277
|
+
const headers = new Headers(answered.headers);
|
|
1278
|
+
for (const line of read.headers.getSetCookie()) headers.append("Set-Cookie", line);
|
|
1279
|
+
return new Response(answered.body, {
|
|
1280
|
+
status: answered.status,
|
|
1281
|
+
statusText: answered.statusText,
|
|
1282
|
+
headers
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
/** A refusal from the engine, in our words: its code kept, its message ours. */
|
|
1286
|
+
async function inOurWords(response) {
|
|
1287
|
+
if (response.status < 400 || !response.headers.get("content-type")?.includes("application/json")) return response;
|
|
1288
|
+
const body = await response.clone().json().catch(() => null);
|
|
1289
|
+
if (!body || typeof body.message !== "string") return response;
|
|
1290
|
+
const message = typeof body.code === "string" && REFUSALS[body.code] || ourWords(body.message);
|
|
1291
|
+
if (message === body.message) return response;
|
|
1292
|
+
return new Response(JSON.stringify({
|
|
1293
|
+
...body,
|
|
1294
|
+
message
|
|
1295
|
+
}), {
|
|
1296
|
+
status: response.status,
|
|
1297
|
+
statusText: response.statusText,
|
|
1298
|
+
headers: response.headers
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
/** Sign-in over `options`: nothing is made until the first request, which may be at a module's top. */
|
|
1302
|
+
function createAuth(options = {}) {
|
|
1303
|
+
const kept = /* @__PURE__ */ new Map();
|
|
1304
|
+
let made;
|
|
1305
|
+
const settingsOfAgents = agentSettings(options);
|
|
1306
|
+
const agents = remembering(), users = remembering();
|
|
1307
|
+
const events = reporter({
|
|
1308
|
+
send: () => eventSendFor(options, base().env),
|
|
1309
|
+
keep: (work) => here()?.waitUntil?.(work)
|
|
1310
|
+
});
|
|
1311
|
+
/** The store, the values and the settings: made at the first request. */
|
|
1312
|
+
const base = () => {
|
|
1313
|
+
if (!made) {
|
|
1314
|
+
const env = options.env ?? processEnv();
|
|
1315
|
+
const store = storeFor(options, env);
|
|
1316
|
+
made = {
|
|
1317
|
+
store,
|
|
1318
|
+
env,
|
|
1319
|
+
settings: settingsReader(store, options.clock),
|
|
1320
|
+
allow: rateLimiter(store, options.clock)
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
return made;
|
|
1324
|
+
};
|
|
1325
|
+
const appNameOf = (settings) => settings.branding.name ?? options.appName ?? base().env.APP_NAME ?? "your app";
|
|
1326
|
+
/** Work that follows a request, such as the new-device mail, until it ends. */
|
|
1327
|
+
const background = /* @__PURE__ */ new Set();
|
|
1328
|
+
/** The events each request on Midsummer made so far, reported as its handler ends: never before its answer. */
|
|
1329
|
+
const held = /* @__PURE__ */ new WeakMap();
|
|
1330
|
+
/** What a change sign-in wrote means: its events, and a mail for a sign-in from a device the person hasn't used. */
|
|
1331
|
+
const changed = (origin) => (change) => {
|
|
1332
|
+
const made = eventsOf(change, Date.now()), request = here();
|
|
1333
|
+
const buffer = request ? held.get(request) : void 0;
|
|
1334
|
+
if (buffer) buffer.push(...made);
|
|
1335
|
+
else events.report(made);
|
|
1336
|
+
if (change.table === "authSessions" && change.op === "create") {
|
|
1337
|
+
const work = newDevice(origin, change.rows[0]).catch((error) => console.warn(`[auth] couldn't check for a new device: ${error.message}`));
|
|
1338
|
+
background.add(work);
|
|
1339
|
+
work.finally(() => background.delete(work));
|
|
1340
|
+
here()?.waitUntil?.(work);
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
async function newDevice(origin, session) {
|
|
1344
|
+
if (session.impersonatedBy) return;
|
|
1345
|
+
const { store, settings } = base();
|
|
1346
|
+
const others = (await store.call("findMany", {
|
|
1347
|
+
model: "authSessions",
|
|
1348
|
+
where: [{
|
|
1349
|
+
field: "userId",
|
|
1350
|
+
value: session.userId
|
|
1351
|
+
}],
|
|
1352
|
+
limit: 50
|
|
1353
|
+
})).filter((one) => one.id !== session.id);
|
|
1354
|
+
if (!others.length || others.some((one) => one.userAgent === session.userAgent)) return;
|
|
1355
|
+
const user = await store.call("findOne", {
|
|
1356
|
+
model: "users",
|
|
1357
|
+
where: [{
|
|
1358
|
+
field: "id",
|
|
1359
|
+
value: session.userId
|
|
1360
|
+
}]
|
|
1361
|
+
});
|
|
1362
|
+
if (!user) return;
|
|
1363
|
+
const device = deviceOf(typeof session.userAgent === "string" ? session.userAgent : null);
|
|
1364
|
+
await sendOne(await settings(), {
|
|
1365
|
+
to: String(user.email),
|
|
1366
|
+
kind: "device",
|
|
1367
|
+
url: `${origin}${AUTH_PATH}/ui/account`,
|
|
1368
|
+
...device ? { device } : {}
|
|
1369
|
+
});
|
|
1370
|
+
}
|
|
1371
|
+
/** Sends one mail with the app's name, branding and sender. */
|
|
1372
|
+
async function sendOne(settings, mail) {
|
|
1373
|
+
const brand = {
|
|
1374
|
+
...settings.branding.logo ? { logo: settings.branding.logo } : {},
|
|
1375
|
+
...settings.branding.color ? { color: settings.branding.color } : {}
|
|
1376
|
+
};
|
|
1377
|
+
const full = {
|
|
1378
|
+
...mail,
|
|
1379
|
+
app: appNameOf(settings),
|
|
1380
|
+
...Object.keys(brand).length ? { brand } : {}
|
|
1381
|
+
};
|
|
1382
|
+
await (options.mail ? options.mail(full) : sendSignInMail(full, base().env, settings.sender.from, remoteMailFor(options, base().env)));
|
|
1383
|
+
}
|
|
1384
|
+
/** Whether `email` may become a user, under the sign-up policy now. */
|
|
1385
|
+
async function admit(email) {
|
|
1386
|
+
const { store, settings } = base();
|
|
1387
|
+
const now = await settings();
|
|
1388
|
+
if (now.signUp.policy === "open") return;
|
|
1389
|
+
const [entry, invitations] = await Promise.all([store.call("findOne", {
|
|
1390
|
+
model: "authWaitlist",
|
|
1391
|
+
where: [{
|
|
1392
|
+
field: "email",
|
|
1393
|
+
value: email
|
|
1394
|
+
}]
|
|
1395
|
+
}), store.call("findMany", {
|
|
1396
|
+
model: "authInvitations",
|
|
1397
|
+
where: [{
|
|
1398
|
+
field: "email",
|
|
1399
|
+
value: email
|
|
1400
|
+
}, {
|
|
1401
|
+
field: "status",
|
|
1402
|
+
value: "pending"
|
|
1403
|
+
}],
|
|
1404
|
+
limit: 10
|
|
1405
|
+
})]);
|
|
1406
|
+
const status = entry?.status === "waiting" || entry?.status === "approved" || entry?.status === "declined" ? entry.status : null;
|
|
1407
|
+
const decision = mayJoin(now, email, {
|
|
1408
|
+
invited: status === "approved" || invitations.some((one) => Number(one.expiresAt) > Date.now()),
|
|
1409
|
+
entry: status
|
|
1410
|
+
});
|
|
1411
|
+
if (decision.allowed) return;
|
|
1412
|
+
if (decision.wait) await store.call("create", {
|
|
1413
|
+
model: "authWaitlist",
|
|
1414
|
+
data: {
|
|
1415
|
+
email,
|
|
1416
|
+
status: "waiting",
|
|
1417
|
+
createdAt: Date.now()
|
|
1418
|
+
}
|
|
1419
|
+
}).catch(() => {});
|
|
1420
|
+
throw new JoinRefused(decision.code, decision.message);
|
|
1421
|
+
}
|
|
1422
|
+
const at = async (origin) => {
|
|
1423
|
+
const normal = new URL(origin).origin;
|
|
1424
|
+
const { store, env, settings } = base();
|
|
1425
|
+
const appName = appNameOf(await settings());
|
|
1426
|
+
const id = `${normal}\n${appName}`;
|
|
1427
|
+
let found = kept.get(id);
|
|
1428
|
+
if (!found) {
|
|
1429
|
+
const secret = options.secret || env.AUTH_SECRET || (env.MIDSUMMER_DEV === "1" ? DEV_SECRET : "");
|
|
1430
|
+
if (!secret) throw new AuthError("forbidden", "Sign-in needs AUTH_SECRET in this environment: midsummer env set <team>/<project> AUTH_SECRET --kind secret --generate --environment <environment>. Outside Midsummer, set it to 32 random characters or more.");
|
|
1431
|
+
found = buildEngine({
|
|
1432
|
+
origin: normal,
|
|
1433
|
+
appName,
|
|
1434
|
+
secret,
|
|
1435
|
+
store,
|
|
1436
|
+
env,
|
|
1437
|
+
agents: settingsOfAgents,
|
|
1438
|
+
admit,
|
|
1439
|
+
changed: changed(normal),
|
|
1440
|
+
impersonationS: IMPERSONATION_S,
|
|
1441
|
+
cacheS: 300,
|
|
1442
|
+
invitationUrl: options.invitationUrl ?? ((from, invitation) => `${from}/api/auth/ui/invitation/${invitation}`),
|
|
1443
|
+
send: async (mail) => sendOne(await settings(), mail)
|
|
1444
|
+
});
|
|
1445
|
+
if (kept.size >= KEPT_ORIGINS) kept.delete(kept.keys().next().value);
|
|
1446
|
+
kept.set(id, found);
|
|
1447
|
+
}
|
|
1448
|
+
return found;
|
|
1449
|
+
};
|
|
1450
|
+
const declared = (scope, what) => {
|
|
1451
|
+
if (!Object.hasOwn(settingsOfAgents.scopes, scope)) throw new AuthError("invalid", `${what} the scope ${scope}, which the app doesn't declare: add it to createAuth({ scopes }).`);
|
|
1452
|
+
};
|
|
1453
|
+
/** The person signed in themselves, with their session's cookie. */
|
|
1454
|
+
async function person(request, fresh = false) {
|
|
1455
|
+
const found = await (await at(originOf(request))).api.getSession({
|
|
1456
|
+
headers: request.headers,
|
|
1457
|
+
...fresh ? { query: { disableCookieCache: true } } : {}
|
|
1458
|
+
});
|
|
1459
|
+
return found ? {
|
|
1460
|
+
via: "session",
|
|
1461
|
+
...found
|
|
1462
|
+
} : null;
|
|
1463
|
+
}
|
|
1464
|
+
/** The person a request about their own keys or grants comes from; never an agent, which can't give itself more. */
|
|
1465
|
+
async function owner(request, what) {
|
|
1466
|
+
const found = await person(request);
|
|
1467
|
+
if (!found) throw new AuthError("forbidden", `Sign in to ${what}.`);
|
|
1468
|
+
return found;
|
|
1469
|
+
}
|
|
1470
|
+
async function session(request, asked) {
|
|
1471
|
+
const scope = asked?.scope;
|
|
1472
|
+
if (scope === void 0) return person(request, asked?.fresh);
|
|
1473
|
+
declared(scope, "This route asks for");
|
|
1474
|
+
const credential = credentialOf(request);
|
|
1475
|
+
if (!credential) return person(request, asked?.fresh);
|
|
1476
|
+
const origin = originOf(request), engine = await at(origin);
|
|
1477
|
+
const identity = "key" in credential ? await agentOfKey(engine, credential.key, {
|
|
1478
|
+
get: (name, read) => agents.get(`${origin}\n${name}`, read),
|
|
1479
|
+
forget: (name) => agents.forget(`${origin}\n${name}`)
|
|
1480
|
+
}) : await agentOfToken(engine, credential.token, origin, AUTH_PATH, resourceOf(origin, settingsOfAgents));
|
|
1481
|
+
if (!identity) return null;
|
|
1482
|
+
const user = await users.get(`${origin}\n${identity.userId}`, async () => await engine.findUser(identity.userId) ?? null);
|
|
1483
|
+
if (!user || user.banned) return null;
|
|
1484
|
+
if (!identity.scopes.includes(scope)) throw new AuthError("forbidden", `This ${identity.via === "key" ? "key" : "app"} can't do that: it lacks the scope ${scope}.`, scope);
|
|
1485
|
+
return {
|
|
1486
|
+
via: identity.via,
|
|
1487
|
+
user,
|
|
1488
|
+
scopes: identity.scopes,
|
|
1489
|
+
agent: identity.agent
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1492
|
+
/** Sign-in's own page that asks a person whether to let an MCP client in, and what it does with their answer. */
|
|
1493
|
+
async function consent(request, origin, engine, appName) {
|
|
1494
|
+
const url = new URL(request.url);
|
|
1495
|
+
if (request.method === "POST") {
|
|
1496
|
+
if (request.headers.get("origin") !== origin) return new Response("This form was sent from another site.", { status: 403 });
|
|
1497
|
+
const form = await request.formData();
|
|
1498
|
+
const answered = await engine.handler(new Request(`${origin}${AUTH_PATH}/oauth2/consent`, {
|
|
1499
|
+
method: "POST",
|
|
1500
|
+
headers: {
|
|
1501
|
+
origin,
|
|
1502
|
+
cookie: request.headers.get("cookie") ?? "",
|
|
1503
|
+
"content-type": "application/json"
|
|
1504
|
+
},
|
|
1505
|
+
body: JSON.stringify({
|
|
1506
|
+
accept: form.get("accept") === "true",
|
|
1507
|
+
oauth_query: String(form.get("oauth_query") ?? "")
|
|
1508
|
+
})
|
|
1509
|
+
}));
|
|
1510
|
+
const answer = await answered.json().catch(() => null);
|
|
1511
|
+
if (!answered.ok || !answer?.url) return new Response("This request to sign in has ended. Start again from the app that asked.", { status: 400 });
|
|
1512
|
+
return new Response(null, {
|
|
1513
|
+
status: 302,
|
|
1514
|
+
headers: {
|
|
1515
|
+
Location: answer.url,
|
|
1516
|
+
"Cache-Control": "no-store"
|
|
1517
|
+
}
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
const signedIn = await person(request);
|
|
1521
|
+
if (!signedIn) return new Response(null, {
|
|
1522
|
+
status: 302,
|
|
1523
|
+
headers: { Location: `${settingsOfAgents.signInPage}${url.search}` }
|
|
1524
|
+
});
|
|
1525
|
+
const clientId = url.searchParams.get("client_id") ?? "";
|
|
1526
|
+
const client = await engine.api.getOAuthClientPublic({
|
|
1527
|
+
query: { client_id: clientId },
|
|
1528
|
+
headers: request.headers
|
|
1529
|
+
}).catch(() => null);
|
|
1530
|
+
if (!client) return new Response("No such app asked to sign in.", { status: 400 });
|
|
1531
|
+
const returnsTo = URL.parse(url.searchParams.get("redirect_uri") ?? "")?.host ?? "the app";
|
|
1532
|
+
const html = consentPage({
|
|
1533
|
+
app: appName,
|
|
1534
|
+
client: client.client_name?.trim() || "An app",
|
|
1535
|
+
returnsTo,
|
|
1536
|
+
person: signedIn.user.email,
|
|
1537
|
+
scopes: (url.searchParams.get("scope") ?? "").split(" ").filter(Boolean),
|
|
1538
|
+
described: settingsOfAgents.scopes,
|
|
1539
|
+
query: url.search.slice(1),
|
|
1540
|
+
action: CONSENT_PATH
|
|
1541
|
+
});
|
|
1542
|
+
return new Response(html, { headers: {
|
|
1543
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
1544
|
+
"Cache-Control": "no-store",
|
|
1545
|
+
"X-Frame-Options": "DENY",
|
|
1546
|
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"
|
|
1547
|
+
} });
|
|
1548
|
+
}
|
|
1549
|
+
const keys = {
|
|
1550
|
+
async create(request, input) {
|
|
1551
|
+
const { user } = await owner(request, "make a key");
|
|
1552
|
+
const name = input.name.trim();
|
|
1553
|
+
if (!name || name.length > 32) throw new AuthError("invalid", "A key's name is 1 to 32 characters.");
|
|
1554
|
+
if (!input.scopes.length) throw new AuthError("invalid", "A key carries at least one of the app's scopes.");
|
|
1555
|
+
for (const scope of input.scopes) declared(scope, "A key can't carry");
|
|
1556
|
+
if (input.expiresIn !== void 0 && !(Number.isInteger(input.expiresIn) && input.expiresIn >= DAY_S && input.expiresIn <= 365 * DAY_S)) throw new AuthError("invalid", "A key expires in 1 to 365 days, given in seconds; leave expiresIn out for one that doesn't.");
|
|
1557
|
+
const made = await (await at(originOf(request))).api.createApiKey({ body: {
|
|
1558
|
+
userId: user.id,
|
|
1559
|
+
name,
|
|
1560
|
+
permissions: { scope: [...new Set(input.scopes)] },
|
|
1561
|
+
...input.expiresIn !== void 0 ? { expiresIn: input.expiresIn } : {}
|
|
1562
|
+
} });
|
|
1563
|
+
return {
|
|
1564
|
+
...keyOf(made),
|
|
1565
|
+
key: made.key
|
|
1566
|
+
};
|
|
1567
|
+
},
|
|
1568
|
+
async list(request) {
|
|
1569
|
+
await owner(request, "see your keys");
|
|
1570
|
+
return (await (await at(originOf(request))).api.listApiKeys({ headers: request.headers })).apiKeys.map(keyOf);
|
|
1571
|
+
},
|
|
1572
|
+
async revoke(request, id) {
|
|
1573
|
+
await owner(request, "revoke a key");
|
|
1574
|
+
await (await at(originOf(request))).api.deleteApiKey({
|
|
1575
|
+
body: { keyId: id },
|
|
1576
|
+
headers: request.headers
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
};
|
|
1580
|
+
const grants = {
|
|
1581
|
+
async list(request) {
|
|
1582
|
+
await owner(request, "see the apps you let in");
|
|
1583
|
+
const { api } = await at(originOf(request));
|
|
1584
|
+
const consents = await api.getOAuthConsents({ headers: request.headers });
|
|
1585
|
+
const names = new Map(await Promise.all([...new Set(consents.map((one) => one.clientId))].map(async (id) => [id, (await api.getOAuthClientPublic({
|
|
1586
|
+
query: { client_id: id },
|
|
1587
|
+
headers: request.headers
|
|
1588
|
+
}).catch(() => null))?.client_name ?? null])));
|
|
1589
|
+
return consents.map((one) => ({
|
|
1590
|
+
id: one.id,
|
|
1591
|
+
clientId: one.clientId,
|
|
1592
|
+
client: names.get(one.clientId) ?? null,
|
|
1593
|
+
scopes: one.scopes,
|
|
1594
|
+
createdAt: new Date(one.createdAt)
|
|
1595
|
+
}));
|
|
1596
|
+
},
|
|
1597
|
+
async revoke(request, id) {
|
|
1598
|
+
const { user } = await owner(request, "remove an app's access");
|
|
1599
|
+
const { api } = await at(originOf(request));
|
|
1600
|
+
const theirs = [{
|
|
1601
|
+
field: "clientId",
|
|
1602
|
+
value: (await api.getOAuthConsent({
|
|
1603
|
+
query: { id },
|
|
1604
|
+
headers: request.headers
|
|
1605
|
+
})).clientId
|
|
1606
|
+
}, {
|
|
1607
|
+
field: "userId",
|
|
1608
|
+
value: user.id
|
|
1609
|
+
}];
|
|
1610
|
+
const { store } = base();
|
|
1611
|
+
await Promise.all([store.call("deleteMany", {
|
|
1612
|
+
model: "authRefreshTokens",
|
|
1613
|
+
where: theirs
|
|
1614
|
+
}), store.call("deleteMany", {
|
|
1615
|
+
model: "authAccessTokens",
|
|
1616
|
+
where: theirs
|
|
1617
|
+
})]);
|
|
1618
|
+
await api.deleteOAuthConsent({
|
|
1619
|
+
body: { id },
|
|
1620
|
+
headers: request.headers
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
/** The signed-in person's keys and grants, as JSON for the browser client and the drop-in screens. */
|
|
1625
|
+
async function account(request, path, origin) {
|
|
1626
|
+
const answer = (status, body) => Response.json(body, {
|
|
1627
|
+
status,
|
|
1628
|
+
headers: { "Cache-Control": "no-store" }
|
|
1629
|
+
});
|
|
1630
|
+
if (request.method === "POST") {
|
|
1631
|
+
const from = request.headers.get("origin");
|
|
1632
|
+
if (from && from !== origin || !request.headers.get("content-type")?.includes("application/json")) return answer(403, {
|
|
1633
|
+
code: "INVALID_ORIGIN",
|
|
1634
|
+
message: REFUSALS.INVALID_ORIGIN
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
const body = request.method === "POST" ? await request.json().catch(() => ({})) : {};
|
|
1638
|
+
const id = typeof body.id === "string" ? body.id : "";
|
|
1639
|
+
try {
|
|
1640
|
+
if (path === "/sessions" && request.method === "GET") {
|
|
1641
|
+
const { user } = await owner(request, "see your sessions");
|
|
1642
|
+
const rows = await base().store.call("findMany", {
|
|
1643
|
+
model: "authSessions",
|
|
1644
|
+
where: [{
|
|
1645
|
+
field: "userId",
|
|
1646
|
+
value: user.id
|
|
1647
|
+
}],
|
|
1648
|
+
limit: 200,
|
|
1649
|
+
sortBy: {
|
|
1650
|
+
field: "createdAt",
|
|
1651
|
+
direction: "desc"
|
|
1652
|
+
}
|
|
1653
|
+
});
|
|
1654
|
+
const iso = (value) => new Date(Number(value)).toISOString();
|
|
1655
|
+
return answer(200, rows.filter((row) => Number(row.expiresAt) > Date.now()).map((row) => ({
|
|
1656
|
+
id: row.id,
|
|
1657
|
+
token: row.token,
|
|
1658
|
+
userId: row.userId,
|
|
1659
|
+
createdAt: iso(row.createdAt),
|
|
1660
|
+
expiresAt: iso(row.expiresAt),
|
|
1661
|
+
ipAddress: row.ipAddress ?? null,
|
|
1662
|
+
userAgent: row.userAgent ?? null,
|
|
1663
|
+
activeOrganizationId: row.activeOrganizationId ?? null,
|
|
1664
|
+
impersonatedBy: row.impersonatedBy ?? null
|
|
1665
|
+
})));
|
|
1666
|
+
}
|
|
1667
|
+
if (path === "/keys" && request.method === "GET") return answer(200, await keys.list(request));
|
|
1668
|
+
if (path === "/keys" && request.method === "POST") return answer(200, await keys.create(request, {
|
|
1669
|
+
name: String(body.name ?? ""),
|
|
1670
|
+
scopes: Array.isArray(body.scopes) ? body.scopes.map(String) : [],
|
|
1671
|
+
...typeof body.expiresIn === "number" ? { expiresIn: body.expiresIn } : {}
|
|
1672
|
+
}));
|
|
1673
|
+
if (path === "/keys/revoke" && request.method === "POST") {
|
|
1674
|
+
await keys.revoke(request, id);
|
|
1675
|
+
return answer(200, { ok: true });
|
|
1676
|
+
}
|
|
1677
|
+
if (path === "/grants" && request.method === "GET") return answer(200, await grants.list(request));
|
|
1678
|
+
if (path === "/grants/revoke" && request.method === "POST") {
|
|
1679
|
+
await grants.revoke(request, id);
|
|
1680
|
+
return answer(200, { ok: true });
|
|
1681
|
+
}
|
|
1682
|
+
} catch (error) {
|
|
1683
|
+
if (error instanceof AuthError) return answer(error.code === "invalid" ? 400 : error.code === "forbidden" ? 401 : 503, {
|
|
1684
|
+
code: error.code.toUpperCase(),
|
|
1685
|
+
message: error.message
|
|
1686
|
+
});
|
|
1687
|
+
throw error;
|
|
1688
|
+
}
|
|
1689
|
+
return answer(404, {
|
|
1690
|
+
code: "NOT_FOUND",
|
|
1691
|
+
message: "There's nothing here."
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
/** Serves one request under `/api/auth`: settings, account calls, hosted pages, the guard, then the engine. */
|
|
1695
|
+
async function serve(request) {
|
|
1696
|
+
const origin = originOf(request), { pathname } = new URL(request.url);
|
|
1697
|
+
const { settings: read, env, allow } = base();
|
|
1698
|
+
const settings = await read();
|
|
1699
|
+
const engine = await at(origin), appName = appNameOf(settings);
|
|
1700
|
+
if (pathname === "/.well-known/oauth-authorization-server") return engine.handler(new Request(`${origin}/.well-known/oauth-authorization-server${AUTH_PATH}`, request));
|
|
1701
|
+
if (!pathname.startsWith(`/api/auth/`)) return engine.handler(request);
|
|
1702
|
+
const path = pathname.slice(9);
|
|
1703
|
+
const shown = publicSettings(settings, appName), keyed = (name) => !!(env[`${name}_CLIENT_ID`] && env[`${name}_CLIENT_SECRET`]);
|
|
1704
|
+
const offered = {
|
|
1705
|
+
...shown,
|
|
1706
|
+
methods: {
|
|
1707
|
+
...shown.methods,
|
|
1708
|
+
google: shown.methods.google && keyed("GOOGLE"),
|
|
1709
|
+
github: shown.methods.github && keyed("GITHUB")
|
|
1710
|
+
}
|
|
1711
|
+
};
|
|
1712
|
+
if (path === "/settings" && request.method === "GET") return Response.json({
|
|
1713
|
+
...offered,
|
|
1714
|
+
scopes: settingsOfAgents.scopes
|
|
1715
|
+
}, { headers: { "Cache-Control": "no-store" } });
|
|
1716
|
+
if (path.startsWith("/account/")) return account(request, path.slice(8), origin);
|
|
1717
|
+
if (pathname === CONSENT_PATH && settingsOfAgents.consentPage === CONSENT_PATH) return consent(request, origin, engine, appName);
|
|
1718
|
+
if (path.startsWith("/ui/")) return hostedPage(request, path.slice(3), {
|
|
1719
|
+
auth,
|
|
1720
|
+
settings: offered,
|
|
1721
|
+
scopes: settingsOfAgents.scopes
|
|
1722
|
+
});
|
|
1723
|
+
const refused = await guard(request, path, {
|
|
1724
|
+
settings,
|
|
1725
|
+
env,
|
|
1726
|
+
ip: here()?.ip ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
|
|
1727
|
+
allow,
|
|
1728
|
+
human: options.verifyHuman ?? verifyHuman,
|
|
1729
|
+
leaked: options.leakedPassword ?? leakedPassword
|
|
1730
|
+
});
|
|
1731
|
+
if (refused) return refused;
|
|
1732
|
+
const forwarded = here()?.ip ? new Request(request, { headers: (() => {
|
|
1733
|
+
const headers = new Headers(request.headers);
|
|
1734
|
+
headers.set("x-forwarded-for", here().ip);
|
|
1735
|
+
return headers;
|
|
1736
|
+
})() }) : request;
|
|
1737
|
+
const answered = await inOurWords(await engine.handler(forwarded));
|
|
1738
|
+
return answered.ok && FRESHENS.has(path) ? freshened(engine, origin, forwarded, answered) : answered;
|
|
1739
|
+
}
|
|
1740
|
+
const recordOf = (row) => ({
|
|
1741
|
+
...row,
|
|
1742
|
+
createdAt: Number(row.createdAt)
|
|
1743
|
+
});
|
|
1744
|
+
const fits = (value) => value === void 0 || JSON.stringify(value ?? null).length <= METADATA_BYTES;
|
|
1745
|
+
const auth = {
|
|
1746
|
+
async handler(request) {
|
|
1747
|
+
const current = here();
|
|
1748
|
+
if (!current || held.has(current)) return serve(request);
|
|
1749
|
+
held.set(current, []);
|
|
1750
|
+
try {
|
|
1751
|
+
return await serve(request);
|
|
1752
|
+
} finally {
|
|
1753
|
+
const made = held.get(current) ?? [];
|
|
1754
|
+
held.delete(current);
|
|
1755
|
+
events.report(made);
|
|
1756
|
+
}
|
|
1757
|
+
},
|
|
1758
|
+
session,
|
|
1759
|
+
protect: (scope, handler) => async (request) => {
|
|
1760
|
+
const origin = originOf(request);
|
|
1761
|
+
let signedIn;
|
|
1762
|
+
try {
|
|
1763
|
+
signedIn = await session(request, { scope });
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
if (error instanceof AuthError && error.scope !== void 0) return challenge(origin, settingsOfAgents, scope, true);
|
|
1766
|
+
throw error;
|
|
1767
|
+
}
|
|
1768
|
+
return signedIn ? handler(request, signedIn) : challenge(origin, settingsOfAgents, scope, false);
|
|
1769
|
+
},
|
|
1770
|
+
keys,
|
|
1771
|
+
grants,
|
|
1772
|
+
users: {
|
|
1773
|
+
async get(id) {
|
|
1774
|
+
const row = await base().store.call("findOne", {
|
|
1775
|
+
model: "users",
|
|
1776
|
+
where: [{
|
|
1777
|
+
field: "id",
|
|
1778
|
+
value: id
|
|
1779
|
+
}]
|
|
1780
|
+
});
|
|
1781
|
+
return row ? recordOf(row) : null;
|
|
1782
|
+
},
|
|
1783
|
+
async setMetadata(id, metadata) {
|
|
1784
|
+
if (!fits(metadata.public) || !fits(metadata.private)) throw new AuthError("invalid", "A user's metadata is at most 8 KB of JSON each.");
|
|
1785
|
+
const update = {
|
|
1786
|
+
...metadata.public !== void 0 ? { publicMetadata: metadata.public } : {},
|
|
1787
|
+
...metadata.private !== void 0 ? { privateMetadata: metadata.private } : {},
|
|
1788
|
+
updatedAt: Date.now()
|
|
1789
|
+
};
|
|
1790
|
+
const row = await base().store.call("update", {
|
|
1791
|
+
model: "users",
|
|
1792
|
+
where: [{
|
|
1793
|
+
field: "id",
|
|
1794
|
+
value: id
|
|
1795
|
+
}],
|
|
1796
|
+
update
|
|
1797
|
+
});
|
|
1798
|
+
if (!row) throw new AuthError("invalid", `No user ${id}.`);
|
|
1799
|
+
events.report(eventsOf({
|
|
1800
|
+
op: "update",
|
|
1801
|
+
table: "users",
|
|
1802
|
+
rows: [row],
|
|
1803
|
+
update
|
|
1804
|
+
}, Date.now()));
|
|
1805
|
+
return recordOf(row);
|
|
1806
|
+
}
|
|
1807
|
+
},
|
|
1808
|
+
settings: () => base().settings(),
|
|
1809
|
+
flush: async () => {
|
|
1810
|
+
await Promise.all([...background]);
|
|
1811
|
+
await events.flush();
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
return auth;
|
|
1815
|
+
}
|
|
1816
|
+
/** Sign-in for this deployment, set up from its environment. */
|
|
1817
|
+
const auth = createAuth();
|
|
1818
|
+
//#endregion
|
|
1819
|
+
export { auth as a, LIMIT_WINDOW_MS as c, SESSION_CACHE_S as i, SETTINGS_TTL_MS as l, AuthError as n, createAuth as o, IMPERSONATION_S as r, LIMITS as s, AUTH_PATH as t, databaseStore as u };
|