@midsummer-ai/sdk 0.1.0-staging.3814 → 0.1.0-staging.3817

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/auth/contract.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-C5lH_TF0.mjs";
1
+ import { r as AuthError } from "../auth-BvX0Xd2G.mjs";
2
+ import { d as SETTINGS_TTL_MS, n as LIMIT_WINDOW_MS, t as LIMITS } from "../guard-DrFHnHzr.mjs";
2
3
  import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
3
4
  //#region src/auth/contract.ts
4
5
  /**
package/auth/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-C5lH_TF0.mjs";
1
+ import { a as SESSION_CACHE_S, c as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-BvX0Xd2G.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
3
  import { n as authFiles } from "../files-DhPeWwcT.mjs";
4
4
  export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/password.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { i as hashPassword$1, o as verifyPassword$1 } from "../engine-9WBvqNSV.mjs";
1
+ import { n as hashPassword$1, r as verifyPassword$1 } from "../engine-BEuwy5dz.mjs";
2
2
  import { isBcrypt as isBcrypt$1 } from "./import.mjs";
3
3
  //#region src/auth/password.ts
4
4
  /**
@@ -3,8 +3,8 @@ import { d as userToken, o as connect, s as databaseUrl } from "./client-DD0xZpr
3
3
  import { sendSignInMail } from "./auth/mail.mjs";
4
4
  import "./files-DhPeWwcT.mjs";
5
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-9WBvqNSV.mjs";
7
6
  import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, r as GEIST_WOFF2, s as defaultAppName, t as authCss, u as setupKeyOf } from "./style-CCFT-5rG.mjs";
7
+ import { _ as challenge, a as leakedPassword, b as remembering, c as refusal, f as mayJoin, g as agentOfKey, i as guard, l as verifyHuman, m as settingsReader, o as ourWords, p as publicSettings, r as REFUSALS, s as rateLimiter, u as JoinRefused, v as consentPage, x as resourceOf, y as credentialOf } from "./guard-DrFHnHzr.mjs";
8
8
  import { i as iconSvg, n as qrSvg } from "./qr-BySxqLW6.mjs";
9
9
  //#region src/auth/store.ts
10
10
  const KIND = {
@@ -56,395 +56,6 @@ function databaseStore(database, waitMs = STORE_CALL_MS) {
56
56
  }
57
57
  } };
58
58
  }
59
- //#endregion
60
- //#region src/auth/settings.ts
61
- /** How long a read of the settings is used before it is read again, in ms. */
62
- const SETTINGS_TTL_MS = 5e3;
63
- /** What the settings are when the app has set none. */
64
- const DEFAULT_SETTINGS = {
65
- methods: {
66
- password: true,
67
- code: true,
68
- link: true,
69
- passkey: true,
70
- google: true,
71
- github: true
72
- },
73
- signUp: {
74
- policy: "open",
75
- domains: [],
76
- emails: []
77
- },
78
- confirmEmail: false,
79
- branding: {
80
- name: null,
81
- logo: null,
82
- color: null
83
- },
84
- sender: { from: null },
85
- captcha: null
86
- };
87
- const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
88
- const flag = (value, fallback) => typeof value === "boolean" ? value : fallback;
89
- const line = (value, most) => typeof value === "string" && value.trim() && value.length <= most && !/[\r\n]/.test(value) ? value.trim() : null;
90
- 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])?)+$/;
91
- const COLOR = /^#[0-9a-f]{6}$/i;
92
- const ADDRESS = /^[^\s@<>()",;:]+@[a-z0-9.-]+\.[a-z]{2,}$/i;
93
- const lowered = (value) => Array.isArray(value) ? value.filter((one) => typeof one === "string").map((one) => one.trim().toLowerCase()) : [];
94
- /** The settings a row holds, each field checked on its own: one of the wrong shape is its default. */
95
- function settingsOf(row) {
96
- const given = object(row);
97
- const methods = object(given.methods), signUp = object(given.signUp), branding = object(given.branding), sender = object(given.sender), captcha = object(given.captcha);
98
- const policy = [
99
- "open",
100
- "invite",
101
- "domains",
102
- "waitlist"
103
- ].find((one) => one === signUp.policy) ?? "open";
104
- const logo = line(branding.logo, 2048);
105
- const provider = [
106
- "turnstile",
107
- "hcaptcha",
108
- "recaptcha"
109
- ].find((one) => one === captcha.provider);
110
- const siteKey = line(captcha.siteKey, 200), secretName = line(captcha.secretName, 100);
111
- const d = DEFAULT_SETTINGS.methods;
112
- return {
113
- methods: {
114
- password: flag(methods.password, d.password),
115
- code: flag(methods.code, d.code),
116
- link: flag(methods.link, d.link),
117
- passkey: flag(methods.passkey, d.passkey),
118
- google: flag(methods.google, d.google),
119
- github: flag(methods.github, d.github)
120
- },
121
- signUp: {
122
- policy,
123
- domains: lowered(signUp.domains).filter((one) => DOMAIN.test(one)).slice(0, 50),
124
- emails: lowered(signUp.emails).filter((one) => ADDRESS.test(one)).slice(0, 200)
125
- },
126
- confirmEmail: flag(given.confirmEmail, DEFAULT_SETTINGS.confirmEmail),
127
- branding: {
128
- name: line(branding.name, 80),
129
- logo: logo && URL.parse(logo)?.protocol === "https:" ? logo : null,
130
- color: typeof branding.color === "string" && COLOR.test(branding.color) ? branding.color.toLowerCase() : null
131
- },
132
- sender: { from: typeof sender.from === "string" && ADDRESS.test(sender.from.trim()) ? sender.from.trim() : null },
133
- captcha: provider && siteKey && secretName && /^[A-Z_][A-Z0-9_]*$/.test(secretName) ? {
134
- provider,
135
- siteKey,
136
- secretName
137
- } : null
138
- };
139
- }
140
- /** The settings a browser reads (`GET /api/auth/settings`), with the app's name filled in. */
141
- function publicSettings(settings, appName) {
142
- return {
143
- methods: settings.methods,
144
- signUp: { policy: settings.signUp.policy },
145
- confirmEmail: settings.confirmEmail,
146
- branding: {
147
- ...settings.branding,
148
- name: settings.branding.name ?? appName
149
- },
150
- captcha: settings.captcha ? {
151
- provider: settings.captcha.provider,
152
- siteKey: settings.captcha.siteKey
153
- } : null
154
- };
155
- }
156
- /**
157
- * The app's settings from `store`, read again once `SETTINGS_TTL_MS` has passed since the last read began. Only a
158
- * read that has answered is kept. Reads asked for while one is on its way share it when `scope` gives them the same
159
- * owner (a deployment's request, `here()`), or when it gives none: a request never waits on another request's read,
160
- * which ends when that request does.
161
- */
162
- function settingsReader(store, clock = Date.now, scope = () => void 0) {
163
- let kept;
164
- const reading = /* @__PURE__ */ new WeakMap();
165
- let unscoped;
166
- return () => {
167
- if (kept && kept.until > clock()) return Promise.resolve(kept.value);
168
- const owner = scope();
169
- const pending = owner ? reading.get(owner) : unscoped;
170
- if (pending) return pending;
171
- const began = clock();
172
- const value = store.call("findOne", {
173
- model: "authSettings",
174
- where: [{
175
- field: "key",
176
- value: "settings"
177
- }]
178
- }).then(settingsOf);
179
- value.then((settings) => {
180
- kept = {
181
- until: began + SETTINGS_TTL_MS,
182
- value: settings
183
- };
184
- }, () => {}).finally(() => {
185
- if (owner) reading.delete(owner);
186
- else if (unscoped === value) unscoped = void 0;
187
- });
188
- if (owner) reading.set(owner, value);
189
- else unscoped = value;
190
- return value;
191
- };
192
- }
193
- /**
194
- * The sign-up policy's decision for `email`, given whether it was invited (an approved waitlist entry or a pending
195
- * invitation to an organization) and its waitlist entry. `wait` asks the caller to add a waiting entry.
196
- */
197
- function mayJoin(settings, email, seen) {
198
- const domain = email.slice(email.lastIndexOf("@") + 1).toLowerCase();
199
- switch (settings.signUp.policy) {
200
- case "open": return { allowed: true };
201
- case "domains":
202
- if (settings.signUp.domains.includes(domain) || settings.signUp.emails.includes(email.toLowerCase()) || seen.invited) return { allowed: true };
203
- return {
204
- allowed: false,
205
- code: "SIGN_UP_DOMAIN",
206
- message: settings.signUp.emails.length ? "Sign-up is open to some email addresses only, and this isn't one of them." : `Sign-up is open to some email domains only, and ${domain} isn't one of them.`
207
- };
208
- case "invite": return seen.invited ? { allowed: true } : {
209
- allowed: false,
210
- code: "SIGN_UP_INVITE_ONLY",
211
- message: "You need an invitation to sign up. Ask the people who run this app for one."
212
- };
213
- case "waitlist":
214
- if (seen.invited) return { allowed: true };
215
- if (seen.entry === "declined") return {
216
- allowed: false,
217
- code: "SIGN_UP_DECLINED",
218
- message: "Sign-up isn't open to this email."
219
- };
220
- return {
221
- allowed: false,
222
- code: "SIGN_UP_WAITLIST",
223
- message: "You're on the waitlist. We'll let you know when you can sign up.",
224
- wait: seen.entry === null
225
- };
226
- }
227
- }
228
- //#endregion
229
- //#region src/auth/guard.ts
230
- /** What a path costs one address: its group's tries in a minute. */
231
- const LIMITS = {
232
- "sign-in": 10,
233
- "sign-up": 5,
234
- mail: 5
235
- };
236
- const LIMIT_WINDOW_MS = 6e4;
237
- const PATHS = {
238
- "/sign-in/email": {
239
- method: "password",
240
- limit: "sign-in",
241
- captcha: true
242
- },
243
- "/sign-up/email": {
244
- method: "password",
245
- limit: "sign-up",
246
- captcha: true,
247
- password: "password"
248
- },
249
- "/request-password-reset": {
250
- method: "password",
251
- limit: "mail",
252
- captcha: true
253
- },
254
- "/reset-password": {
255
- method: "password",
256
- password: "newPassword"
257
- },
258
- "/change-password": {
259
- limit: "sign-in",
260
- password: "newPassword"
261
- },
262
- "/email-otp/send-verification-otp": {
263
- method: "code",
264
- limit: "mail",
265
- captcha: true
266
- },
267
- "/sign-in/email-otp": {
268
- method: "code",
269
- limit: "sign-in"
270
- },
271
- "/sign-in/magic-link": {
272
- method: "link",
273
- limit: "mail",
274
- captcha: true
275
- },
276
- "/magic-link/verify": { method: "link" },
277
- "/two-factor/verify-totp": { limit: "sign-in" },
278
- "/two-factor/verify-otp": { limit: "sign-in" },
279
- "/two-factor/verify-backup-code": { limit: "sign-in" },
280
- "/two-factor/send-otp": { limit: "mail" },
281
- "/organization/invite-member": { limit: "mail" },
282
- "/callback/google": { method: "google" },
283
- "/callback/github": { method: "github" }
284
- };
285
- /** Paths no one reaches: signing in as someone is the platform's alone (`/impersonate`). */
286
- const CLOSED = /* @__PURE__ */ new Set(["/admin/impersonate-user", "/admin/stop-impersonating"]);
287
- /** A refusal as the engine's are: JSON `{ code, message }`. */
288
- const refusal = (status, code, message, headers = {}) => Response.json({
289
- code,
290
- message
291
- }, {
292
- status,
293
- headers: {
294
- "Cache-Control": "no-store",
295
- ...headers
296
- }
297
- });
298
- const PROVIDERS = /* @__PURE__ */ new Set(["google", "github"]);
299
- /** The refusal `request` gets before the engine sees it, or null to let it through. `path` is under `/api/auth`. */
300
- async function guard(request, path, deps) {
301
- if (CLOSED.has(path)) return refusal(404, "NOT_FOUND", "There's nothing here.");
302
- const methods = deps.settings.methods;
303
- if (path.startsWith("/passkey/") && !methods.passkey) return refusal(403, "METHOD_OFF", "Passkeys are turned off for this app.");
304
- const rule = PATHS[path];
305
- const body = request.method === "POST" && (rule?.password || path === "/sign-in/social") ? await request.clone().json().catch(() => null) : null;
306
- const method = path === "/sign-in/social" && typeof body?.provider === "string" && PROVIDERS.has(body.provider) ? body.provider : rule?.method;
307
- if (method && !methods[method]) return refusal(403, "METHOD_OFF", `${{
308
- password: "Signing in with a password",
309
- code: "Signing in with a code",
310
- link: "Signing in with a link",
311
- passkey: "Passkeys",
312
- google: "Signing in with Google",
313
- github: "Signing in with GitHub"
314
- }[method]} is turned off for this app.`);
315
- if (!rule || request.method !== "POST") return null;
316
- 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) });
317
- const captcha = deps.settings.captcha;
318
- if (rule.captcha && captcha) {
319
- const token = request.headers.get("x-captcha-response") ?? "";
320
- const secret = deps.env[captcha.secretName];
321
- if (!secret) return refusal(503, "CAPTCHA_UNAVAILABLE", `The bot check has no secret here: set ${captcha.secretName} in this environment.`);
322
- if (!token) return refusal(400, "CAPTCHA_REQUIRED", "Show you're not a bot first.");
323
- let passed;
324
- try {
325
- passed = await deps.human(captcha.provider, secret, token, deps.ip);
326
- } catch {
327
- return refusal(503, "CAPTCHA_UNAVAILABLE", "We couldn't check that you're not a bot. Try again.");
328
- }
329
- if (!passed) return refusal(400, "CAPTCHA_FAILED", "The bot check didn't pass. Try again.");
330
- }
331
- const password = rule.password ? body?.[rule.password] : void 0;
332
- 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.");
333
- return null;
334
- }
335
- /**
336
- * How often one address tries each group, kept in the app's own database (`authRateLimits`): one row per address
337
- * and group, its count since its window began. Only the paths in `PATHS` with a limit count, so reading a session
338
- * writes nothing.
339
- */
340
- function rateLimiter(store, clock = Date.now) {
341
- return async (group, ip) => {
342
- const key = `${group}:${ip}`, now = clock(), since = now - LIMIT_WINDOW_MS;
343
- const where = [
344
- {
345
- field: "key",
346
- value: key
347
- },
348
- {
349
- field: "windowStart",
350
- operator: "gt",
351
- value: since
352
- },
353
- {
354
- field: "count",
355
- operator: "lt",
356
- value: LIMITS[group]
357
- }
358
- ];
359
- if (await store.call("increment", {
360
- model: "authRateLimits",
361
- where,
362
- increment: { count: 1 }
363
- })) return true;
364
- const row = await store.call("findOne", {
365
- model: "authRateLimits",
366
- where: [{
367
- field: "key",
368
- value: key
369
- }]
370
- });
371
- if (row && row.windowStart > since) return false;
372
- if (row) {
373
- await store.call("update", {
374
- model: "authRateLimits",
375
- where: [{
376
- field: "key",
377
- value: key
378
- }],
379
- update: {
380
- count: 1,
381
- windowStart: now
382
- }
383
- });
384
- return true;
385
- }
386
- await store.call("deleteMany", {
387
- model: "authRateLimits",
388
- where: [{
389
- field: "windowStart",
390
- operator: "lt",
391
- value: now - 864e5
392
- }]
393
- });
394
- await store.call("create", {
395
- model: "authRateLimits",
396
- data: {
397
- key,
398
- count: 1,
399
- windowStart: now
400
- }
401
- }).catch(async (error) => {
402
- if (!await store.call("findOne", {
403
- model: "authRateLimits",
404
- where: [{
405
- field: "key",
406
- value: key
407
- }]
408
- })) throw error;
409
- });
410
- return true;
411
- };
412
- }
413
- /** Where each bot check's provider confirms a token: the provider the app's owner chose and connected with their own key. */
414
- const VERIFY = {
415
- turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify",
416
- hcaptcha: "https://api.hcaptcha.com/siteverify",
417
- recaptcha: "https://www.google.com/recaptcha/api/siteverify"
418
- };
419
- /** Asks the app's bot-check provider whether `token` passes. Throws when the provider can't be reached. */
420
- async function verifyHuman(provider, secret, token, ip, fetcher = fetch) {
421
- const response = await fetcher(VERIFY[provider], {
422
- method: "POST",
423
- headers: { "content-type": "application/x-www-form-urlencoded" },
424
- body: new URLSearchParams({
425
- secret,
426
- response: token,
427
- ...ip ? { remoteip: ip } : {}
428
- })
429
- });
430
- if (!response.ok) throw new Error(`The bot check returned ${response.status}.`);
431
- return (await response.json()).success === true;
432
- }
433
- /**
434
- * Whether a password is in the public list of leaked passwords: only the first five characters of its SHA-1 leave
435
- * the server (k-anonymity), and the list's answer is compared here. When the list can't be reached the password is
436
- * taken, since a sign-up should not fail on someone else's outage.
437
- */
438
- async function leakedPassword(password, fetcher = fetch) {
439
- const hex = [...new Uint8Array(await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password)))].map((byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();
440
- const response = await fetcher(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, { headers: { "Add-Padding": "true" } }).catch(() => null);
441
- if (!response?.ok) return false;
442
- const suffix = hex.slice(5);
443
- return (await response.text()).split("\n").some((line) => {
444
- const [rest, count] = line.trim().split(":");
445
- return rest === suffix && Number(count) > 0;
446
- });
447
- }
448
59
  const WAITS_MS = [500, 2e3];
449
60
  const text = (value) => typeof value === "string" ? value : null;
450
61
  const time = (value) => typeof value === "number" ? value : value instanceof Date ? value.getTime() : void 0;
@@ -1618,6 +1229,12 @@ const agentSettings = (options) => ({
1618
1229
  /** Where sign-in's own page asks a person whether to let an MCP client in. */
1619
1230
  const CONSENT_PATH = `${AUTH_PATH}/agent-consent`;
1620
1231
  const DAY_S = 86400;
1232
+ /**
1233
+ * The sign-in engine, loaded by the first request that needs it: importing sign-in, and the requests it answers without
1234
+ * the engine (a session with no cookie, the settings, the hosted pages), never load it. Loaded at import, it added 0.2
1235
+ * to 0.6 s to the first answer of each new copy of a Next.js app's server on Midsummer.
1236
+ */
1237
+ const engineAdapter = () => import("./engine-BEuwy5dz.mjs").then((n) => n.t);
1621
1238
  const keyOf = (row) => ({
1622
1239
  id: row.id,
1623
1240
  name: row.name,
@@ -1832,6 +1449,7 @@ function createAuth(options = {}) {
1832
1449
  const found = kept.get(id);
1833
1450
  if (found) return found;
1834
1451
  const secret = secretOf();
1452
+ const { buildEngine } = await engineAdapter();
1835
1453
  const built = buildEngine({
1836
1454
  origin: normal,
1837
1455
  appName,
@@ -1921,7 +1539,7 @@ function createAuth(options = {}) {
1921
1539
  const identity = "key" in credential ? await agentOfKey(engine, credential.key, {
1922
1540
  get: (name, read) => agents.get(`${origin}\n${name}`, read),
1923
1541
  forget: (name) => agents.forget(`${origin}\n${name}`)
1924
- }) : await agentOfToken(engine, credential.token, origin, AUTH_PATH, resourceOf(origin, settingsOfAgents));
1542
+ }) : await (await engineAdapter()).agentOfToken(engine, credential.token, origin, AUTH_PATH, resourceOf(origin, settingsOfAgents));
1925
1543
  if (!identity) return null;
1926
1544
  const user = await users.get(`${origin}\n${identity.userId}`, async () => await engine.findUser(identity.userId) ?? null);
1927
1545
  if (!user || user.banned) return null;
@@ -2205,10 +1823,12 @@ function createAuth(options = {}) {
2205
1823
  const route = Object.hasOwn(AUTH_ROUTES, path) ? path : void 0;
2206
1824
  if (route && request.method !== AUTH_ROUTES[route].method) return refusal(405, "METHOD_NOT_ALLOWED", `${AUTH_PATH}${route} takes ${AUTH_ROUTES[route].method}.`);
2207
1825
  const inner = route ? new Request(`${origin}${AUTH_PATH}${AUTH_ROUTES[route].engine}${new URL(request.url).search}`, request) : request;
2208
- const refused = await guard(inner, route ? AUTH_ROUTES[route].engine : path, {
1826
+ const enginePath = route ? AUTH_ROUTES[route].engine : path;
1827
+ const ip = here()?.ip ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null;
1828
+ const refused = await guard(inner, enginePath, {
2209
1829
  settings,
2210
1830
  env,
2211
- ip: here()?.ip ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
1831
+ ip,
2212
1832
  allow,
2213
1833
  human: options.verifyHuman ?? verifyHuman,
2214
1834
  leaked: options.leakedPassword ?? leakedPassword
@@ -2314,4 +1934,4 @@ function createAuth(options = {}) {
2314
1934
  /** Sign-in for this deployment, set up from its environment. */
2315
1935
  const auth = createAuth();
2316
1936
  //#endregion
2317
- export { SESSION_CACHE_S as a, LIMITS as c, databaseStore as d, IMPERSONATION_S as i, LIMIT_WINDOW_MS as l, AUTH_ROUTES as n, auth as o, AuthError as r, createAuth as s, AUTH_PATH as t, SETTINGS_TTL_MS as u };
1937
+ export { SESSION_CACHE_S as a, databaseStore as c, IMPERSONATION_S as i, AUTH_ROUTES as n, auth as o, AuthError as r, createAuth as s, AUTH_PATH as t };