@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.
@@ -0,0 +1,579 @@
1
+ import "./auth/key.mjs";
2
+ import { l as screenName, t as authCss } from "./style-CCFT-5rG.mjs";
3
+ //#region src/auth/agents.ts
4
+ /**
5
+ * Agents as users of your app: API keys, and sign-in for MCP clients, both limited to the scopes your app
6
+ * declares. It is the sign-in engine's API keys and OAuth server set up for MCP: the engine's plugins for them, and
7
+ * checking an MCP client's token, are in its private Adapter (`./engine.ts`), so nothing here checks a key or signs a
8
+ * token itself, and this file loads without the engine.
9
+ *
10
+ * const auth = createAuth({ scopes: { "notes:read": "Read your notes", "notes:write": "Add and change your notes" } })
11
+ *
12
+ * An API key is made for a signed-in person (`auth.keys.create`), shown once, kept only as its SHA-256, and
13
+ * carries a subset of the app's scopes, an expiry and when it was last used. Agents send it as
14
+ * `x-api-key: key_…` or `Authorization: Bearer key_…`.
15
+ *
16
+ * An MCP client (Claude, ChatGPT, Cursor) signs in as one of the app's users through the app's own OAuth 2.1
17
+ * authorization server, under `/api/auth`: it finds it from `/.well-known/oauth-protected-resource`, registers
18
+ * itself (`/api/auth/oauth2/register`), sends the person to sign in and to a page that shows the client's name and
19
+ * the scopes it asks for, and gets an access token bound to the app's MCP address, good for five minutes, with a
20
+ * refresh token. The access token is a JWT checked against the app's own keys, read once every five minutes, so
21
+ * a request with one reads no row.
22
+ *
23
+ * Who a key or a token acts for is kept for 30 seconds in memory, so an agent's burst of calls reads its key and
24
+ * its user once. A key revoked, a grant removed or a user banned therefore stops within 30 seconds for a key,
25
+ * and within five minutes for an MCP client's token already given out.
26
+ */
27
+ /** How long who a key or a token acts for is kept in memory, in ms. */
28
+ const AGENT_CACHE_MS = 3e4;
29
+ /** How many of them one process keeps; past it the oldest is read again when asked. */
30
+ const KEPT_AGENTS = 1e3;
31
+ /** The scopes the authorization server itself gives meaning to: who the person is, and staying signed in. */
32
+ const IDENTITY_SCOPES = {
33
+ openid: "Know who you are",
34
+ profile: "See your name and picture",
35
+ email: "See your email address",
36
+ offline_access: "Stay connected until you remove it"
37
+ };
38
+ /** The address tokens for `origin`'s MCP server are bound to. */
39
+ const resourceOf = (origin, settings) => `${origin}${settings.mcpPath === "/" ? "" : settings.mcpPath}`;
40
+ /** An agent's credential on a request: an API key, an MCP client's access token, or neither. */
41
+ function credentialOf(request) {
42
+ const header = request.headers.get("x-api-key")?.trim();
43
+ if (header) return { key: header };
44
+ const bearer = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
45
+ if (!bearer) return null;
46
+ return bearer.startsWith("key_") ? { key: bearer } : { token: bearer };
47
+ }
48
+ /** A small memory of what was read, each entry for `AGENT_CACHE_MS`. */
49
+ function remembering(clock = Date.now) {
50
+ const kept = /* @__PURE__ */ new Map();
51
+ return {
52
+ async get(name, read) {
53
+ const found = kept.get(name);
54
+ if (found && found.until > clock()) return found.value;
55
+ const value = await read();
56
+ if (kept.size >= KEPT_AGENTS) kept.delete(kept.keys().next().value);
57
+ kept.set(name, {
58
+ until: clock() + AGENT_CACHE_MS,
59
+ value
60
+ });
61
+ return value;
62
+ },
63
+ forget(name) {
64
+ kept.delete(name);
65
+ }
66
+ };
67
+ }
68
+ const digest = async (text) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
69
+ /**
70
+ * The agent a key signs in, or null for one that is unknown, revoked or expired. A key is checked by
71
+ * the engine, which notes when it was last used; the answer is kept for `AGENT_CACHE_MS`.
72
+ */
73
+ async function agentOfKey(instance, key, memory) {
74
+ if (!key.startsWith("key_") || key.length > 512) return null;
75
+ return memory.get(`key:${await digest(key)}`, async () => {
76
+ const checked = await instance.api.verifyApiKey({ body: { key } });
77
+ if (!checked.valid || !checked.key) return null;
78
+ return {
79
+ via: "key",
80
+ userId: checked.key.referenceId,
81
+ scopes: checked.key.permissions?.scope ?? [],
82
+ agent: {
83
+ id: checked.key.id,
84
+ ...checked.key.name ? { name: checked.key.name } : {}
85
+ }
86
+ };
87
+ });
88
+ }
89
+ /** What an MCP client is told when a request needs signing in (401) or a scope its token lacks (403), as RFC 9728 and RFC 6750 say. */
90
+ function challenge(origin, settings, scope, lacking) {
91
+ const metadata = `${origin}/.well-known/oauth-protected-resource${settings.mcpPath === "/" ? "" : settings.mcpPath}`;
92
+ const parts = [
93
+ ...lacking ? ["error=\"insufficient_scope\""] : [],
94
+ ...scope ? [`scope="${scope}"`] : [],
95
+ `resource_metadata="${metadata}"`
96
+ ];
97
+ const message = lacking ? `This needs the scope ${scope}.` : "Sign in to use this.";
98
+ return Response.json({
99
+ error: lacking ? "insufficient_scope" : "unauthorized",
100
+ message
101
+ }, {
102
+ status: lacking ? 403 : 401,
103
+ headers: {
104
+ "WWW-Authenticate": `Bearer ${parts.join(", ")}`,
105
+ "Cache-Control": "no-store"
106
+ }
107
+ });
108
+ }
109
+ const escape = (text) => text.replace(/[&<>"']/g, (c) => ({
110
+ "&": "&amp;",
111
+ "<": "&lt;",
112
+ ">": "&gt;",
113
+ "\"": "&quot;",
114
+ "'": "&#39;"
115
+ })[c]);
116
+ /**
117
+ * The page that asks a signed-in person whether a client may use the app as them: the client's name, where it
118
+ * goes back to, and each scope it asks for in the app's own words. Its two buttons post the same signed query
119
+ * the page was opened with, so what is granted is what was shown.
120
+ */
121
+ function consentPage(input) {
122
+ const lines = input.scopes.map((scope) => `<li>${escape(input.described[scope] ?? IDENTITY_SCOPES[scope] ?? scope)}</li>`).join("");
123
+ const app = screenName(input.app, []);
124
+ const title = `${input.client} wants to use ${app ? `${app} as you` : "your account"}`;
125
+ return `<!doctype html>
126
+ <html lang="en">
127
+ <head>
128
+ <meta charset="utf-8">
129
+ <meta name="viewport" content="width=device-width, initial-scale=1">
130
+ <meta name="robots" content="noindex">
131
+ <meta name="color-scheme" content="light dark">
132
+ <title>${escape(title)}</title>
133
+ <style>${authCss()}</style>
134
+ </head>
135
+ <body class="msa msa-screen">
136
+ <main class="msa-card" aria-labelledby="msa-title">
137
+ <header class="msa-head"><div class="msa-titles"><h1 id="msa-title" class="msa-title">${escape(title)}</h1><p class="msa-lead">You're signed in as <span class="msa-subject msa-inline">${escape(input.person)}</span>. It goes back to <span class="msa-subject msa-inline">${escape(input.returnsTo)}</span>.</p></div></header>
138
+ <div class="msa-body">
139
+ <ul class="msa-list">${lines}</ul>
140
+ <form method="post" action="${escape(input.action)}" class="msa-actions">
141
+ <input type="hidden" name="oauth_query" value="${escape(input.query)}">
142
+ <button class="msa-button msa-secondary" name="accept" value="false">Don't allow</button>
143
+ <button class="msa-button msa-primary" name="accept" value="true">Allow</button>
144
+ </form>
145
+ </div>
146
+ </main>
147
+ </body>
148
+ </html>
149
+ `;
150
+ }
151
+ //#endregion
152
+ //#region src/auth/settings.ts
153
+ /** How long a read of the settings is used before it is read again, in ms. */
154
+ const SETTINGS_TTL_MS = 5e3;
155
+ /** What the settings are when the app has set none. */
156
+ const DEFAULT_SETTINGS = {
157
+ methods: {
158
+ password: true,
159
+ code: true,
160
+ link: true,
161
+ passkey: true,
162
+ google: true,
163
+ github: true
164
+ },
165
+ signUp: {
166
+ policy: "open",
167
+ domains: [],
168
+ emails: []
169
+ },
170
+ confirmEmail: false,
171
+ branding: {
172
+ name: null,
173
+ logo: null,
174
+ color: null
175
+ },
176
+ sender: { from: null },
177
+ captcha: null
178
+ };
179
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
180
+ const flag = (value, fallback) => typeof value === "boolean" ? value : fallback;
181
+ const line = (value, most) => typeof value === "string" && value.trim() && value.length <= most && !/[\r\n]/.test(value) ? value.trim() : null;
182
+ 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])?)+$/;
183
+ const COLOR = /^#[0-9a-f]{6}$/i;
184
+ const ADDRESS = /^[^\s@<>()",;:]+@[a-z0-9.-]+\.[a-z]{2,}$/i;
185
+ const lowered = (value) => Array.isArray(value) ? value.filter((one) => typeof one === "string").map((one) => one.trim().toLowerCase()) : [];
186
+ /** The settings a row holds, each field checked on its own: one of the wrong shape is its default. */
187
+ function settingsOf(row) {
188
+ const given = object(row);
189
+ const methods = object(given.methods), signUp = object(given.signUp), branding = object(given.branding), sender = object(given.sender), captcha = object(given.captcha);
190
+ const policy = [
191
+ "open",
192
+ "invite",
193
+ "domains",
194
+ "waitlist"
195
+ ].find((one) => one === signUp.policy) ?? "open";
196
+ const logo = line(branding.logo, 2048);
197
+ const provider = [
198
+ "turnstile",
199
+ "hcaptcha",
200
+ "recaptcha"
201
+ ].find((one) => one === captcha.provider);
202
+ const siteKey = line(captcha.siteKey, 200), secretName = line(captcha.secretName, 100);
203
+ const d = DEFAULT_SETTINGS.methods;
204
+ return {
205
+ methods: {
206
+ password: flag(methods.password, d.password),
207
+ code: flag(methods.code, d.code),
208
+ link: flag(methods.link, d.link),
209
+ passkey: flag(methods.passkey, d.passkey),
210
+ google: flag(methods.google, d.google),
211
+ github: flag(methods.github, d.github)
212
+ },
213
+ signUp: {
214
+ policy,
215
+ domains: lowered(signUp.domains).filter((one) => DOMAIN.test(one)).slice(0, 50),
216
+ emails: lowered(signUp.emails).filter((one) => ADDRESS.test(one)).slice(0, 200)
217
+ },
218
+ confirmEmail: flag(given.confirmEmail, DEFAULT_SETTINGS.confirmEmail),
219
+ branding: {
220
+ name: line(branding.name, 80),
221
+ logo: logo && URL.parse(logo)?.protocol === "https:" ? logo : null,
222
+ color: typeof branding.color === "string" && COLOR.test(branding.color) ? branding.color.toLowerCase() : null
223
+ },
224
+ sender: { from: typeof sender.from === "string" && ADDRESS.test(sender.from.trim()) ? sender.from.trim() : null },
225
+ captcha: provider && siteKey && secretName && /^[A-Z_][A-Z0-9_]*$/.test(secretName) ? {
226
+ provider,
227
+ siteKey,
228
+ secretName
229
+ } : null
230
+ };
231
+ }
232
+ /** The settings a browser reads (`GET /api/auth/settings`), with the app's name filled in. */
233
+ function publicSettings(settings, appName) {
234
+ return {
235
+ methods: settings.methods,
236
+ signUp: { policy: settings.signUp.policy },
237
+ confirmEmail: settings.confirmEmail,
238
+ branding: {
239
+ ...settings.branding,
240
+ name: settings.branding.name ?? appName
241
+ },
242
+ captcha: settings.captcha ? {
243
+ provider: settings.captcha.provider,
244
+ siteKey: settings.captcha.siteKey
245
+ } : null
246
+ };
247
+ }
248
+ /**
249
+ * The app's settings from `store`, read again once `SETTINGS_TTL_MS` has passed since the last read began. Only a
250
+ * read that has answered is kept. Reads asked for while one is on its way share it when `scope` gives them the same
251
+ * owner (a deployment's request, `here()`), or when it gives none: a request never waits on another request's read,
252
+ * which ends when that request does.
253
+ */
254
+ function settingsReader(store, clock = Date.now, scope = () => void 0) {
255
+ let kept;
256
+ const reading = /* @__PURE__ */ new WeakMap();
257
+ let unscoped;
258
+ return () => {
259
+ if (kept && kept.until > clock()) return Promise.resolve(kept.value);
260
+ const owner = scope();
261
+ const pending = owner ? reading.get(owner) : unscoped;
262
+ if (pending) return pending;
263
+ const began = clock();
264
+ const value = store.call("findOne", {
265
+ model: "authSettings",
266
+ where: [{
267
+ field: "key",
268
+ value: "settings"
269
+ }]
270
+ }).then(settingsOf);
271
+ value.then((settings) => {
272
+ kept = {
273
+ until: began + SETTINGS_TTL_MS,
274
+ value: settings
275
+ };
276
+ }, () => {}).finally(() => {
277
+ if (owner) reading.delete(owner);
278
+ else if (unscoped === value) unscoped = void 0;
279
+ });
280
+ if (owner) reading.set(owner, value);
281
+ else unscoped = value;
282
+ return value;
283
+ };
284
+ }
285
+ /** A sign-up the policy refuses: its code and the words the person reads. */
286
+ var JoinRefused = class extends Error {
287
+ code;
288
+ constructor(code, message) {
289
+ super(message);
290
+ this.code = code;
291
+ this.name = "JoinRefused";
292
+ }
293
+ };
294
+ /**
295
+ * The sign-up policy's decision for `email`, given whether it was invited (an approved waitlist entry or a pending
296
+ * invitation to an organization) and its waitlist entry. `wait` asks the caller to add a waiting entry.
297
+ */
298
+ function mayJoin(settings, email, seen) {
299
+ const domain = email.slice(email.lastIndexOf("@") + 1).toLowerCase();
300
+ switch (settings.signUp.policy) {
301
+ case "open": return { allowed: true };
302
+ case "domains":
303
+ if (settings.signUp.domains.includes(domain) || settings.signUp.emails.includes(email.toLowerCase()) || seen.invited) return { allowed: true };
304
+ return {
305
+ allowed: false,
306
+ code: "SIGN_UP_DOMAIN",
307
+ 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.`
308
+ };
309
+ case "invite": return seen.invited ? { allowed: true } : {
310
+ allowed: false,
311
+ code: "SIGN_UP_INVITE_ONLY",
312
+ message: "You need an invitation to sign up. Ask the people who run this app for one."
313
+ };
314
+ case "waitlist":
315
+ if (seen.invited) return { allowed: true };
316
+ if (seen.entry === "declined") return {
317
+ allowed: false,
318
+ code: "SIGN_UP_DECLINED",
319
+ message: "Sign-up isn't open to this email."
320
+ };
321
+ return {
322
+ allowed: false,
323
+ code: "SIGN_UP_WAITLIST",
324
+ message: "You're on the waitlist. We'll let you know when you can sign up.",
325
+ wait: seen.entry === null
326
+ };
327
+ }
328
+ }
329
+ //#endregion
330
+ //#region src/auth/guard.ts
331
+ /** What a path costs one address: its group's tries in a minute. */
332
+ const LIMITS = {
333
+ "sign-in": 10,
334
+ "sign-up": 5,
335
+ mail: 5
336
+ };
337
+ const LIMIT_WINDOW_MS = 6e4;
338
+ const PATHS = {
339
+ "/sign-in/email": {
340
+ method: "password",
341
+ limit: "sign-in",
342
+ captcha: true
343
+ },
344
+ "/sign-up/email": {
345
+ method: "password",
346
+ limit: "sign-up",
347
+ captcha: true,
348
+ password: "password"
349
+ },
350
+ "/request-password-reset": {
351
+ method: "password",
352
+ limit: "mail",
353
+ captcha: true
354
+ },
355
+ "/reset-password": {
356
+ method: "password",
357
+ password: "newPassword"
358
+ },
359
+ "/change-password": {
360
+ limit: "sign-in",
361
+ password: "newPassword"
362
+ },
363
+ "/email-otp/send-verification-otp": {
364
+ method: "code",
365
+ limit: "mail",
366
+ captcha: true
367
+ },
368
+ "/sign-in/email-otp": {
369
+ method: "code",
370
+ limit: "sign-in"
371
+ },
372
+ "/sign-in/magic-link": {
373
+ method: "link",
374
+ limit: "mail",
375
+ captcha: true
376
+ },
377
+ "/magic-link/verify": { method: "link" },
378
+ "/two-factor/verify-totp": { limit: "sign-in" },
379
+ "/two-factor/verify-otp": { limit: "sign-in" },
380
+ "/two-factor/verify-backup-code": { limit: "sign-in" },
381
+ "/two-factor/send-otp": { limit: "mail" },
382
+ "/organization/invite-member": { limit: "mail" },
383
+ "/callback/google": { method: "google" },
384
+ "/callback/github": { method: "github" }
385
+ };
386
+ /** Paths no one reaches: signing in as someone is the platform's alone (`/impersonate`). */
387
+ const CLOSED = /* @__PURE__ */ new Set(["/admin/impersonate-user", "/admin/stop-impersonating"]);
388
+ /** Engine log lines in Midsummer's words: they never name the engine. */
389
+ function ourWords(text) {
390
+ return text.replace(/\[better[- ]?auth\]:?\s*/gi, "").replace(/BETTER_AUTH_/g, "AUTH_").replace(/better[- ]?auth/gi, "sign-in");
391
+ }
392
+ /** Midsummer's words for the engine's refusals a person sees most, by their code. Any other keeps its message, in our words. */
393
+ const REFUSALS = {
394
+ INVALID_EMAIL_OR_PASSWORD: "That email and password don't match.",
395
+ INVALID_PASSWORD: "That password isn't right.",
396
+ INVALID_EMAIL: "That isn't an email address.",
397
+ USER_NOT_FOUND: "No one signs in with that email.",
398
+ USER_ALREADY_EXISTS: "Someone signs in with that email already. Sign in instead.",
399
+ USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "Someone signs in with that email already. Sign in, or use another email.",
400
+ PASSWORD_TOO_SHORT: "Use a password of at least 8 characters.",
401
+ PASSWORD_TOO_LONG: "Use a password of at most 128 characters.",
402
+ EMAIL_NOT_VERIFIED: "Confirm your email first: open the link we sent you.",
403
+ INVALID_TOKEN: "This link has ended. Ask for a new one.",
404
+ TOKEN_EXPIRED: "This link has ended. Ask for a new one.",
405
+ INVALID_OTP: "That code isn't right.",
406
+ OTP_EXPIRED: "That code has ended. Ask for a new one.",
407
+ TOO_MANY_ATTEMPTS: "Too many wrong codes. Ask for a new one.",
408
+ INVALID_CODE: "That code isn't right.",
409
+ INVALID_TWO_FACTOR_COOKIE: "Your sign-in took too long. Start again.",
410
+ BANNED_USER: "This account can't sign in.",
411
+ SESSION_EXPIRED: "Sign in again to do this.",
412
+ INVALID_ORIGIN: "This request came from another site.",
413
+ CREDENTIAL_ACCOUNT_NOT_FOUND: "This account has no password. Sign in another way.",
414
+ FAILED_TO_UNLINK_LAST_ACCOUNT: "This is your only way to sign in, so it can't be removed.",
415
+ VALIDATION_ERROR: "Check what you entered: a field is missing or isn't right."
416
+ };
417
+ /** A refusal as the engine's are: JSON `{ code, message }`. */
418
+ const refusal = (status, code, message, headers = {}) => Response.json({
419
+ code,
420
+ message
421
+ }, {
422
+ status,
423
+ headers: {
424
+ "Cache-Control": "no-store",
425
+ ...headers
426
+ }
427
+ });
428
+ const PROVIDERS = /* @__PURE__ */ new Set(["google", "github"]);
429
+ /** The refusal `request` gets before the engine sees it, or null to let it through. `path` is under `/api/auth`. */
430
+ async function guard(request, path, deps) {
431
+ if (CLOSED.has(path)) return refusal(404, "NOT_FOUND", "There's nothing here.");
432
+ const methods = deps.settings.methods;
433
+ if (path.startsWith("/passkey/") && !methods.passkey) return refusal(403, "METHOD_OFF", "Passkeys are turned off for this app.");
434
+ const rule = PATHS[path];
435
+ const body = request.method === "POST" && (rule?.password || path === "/sign-in/social") ? await request.clone().json().catch(() => null) : null;
436
+ const method = path === "/sign-in/social" && typeof body?.provider === "string" && PROVIDERS.has(body.provider) ? body.provider : rule?.method;
437
+ if (method && !methods[method]) return refusal(403, "METHOD_OFF", `${{
438
+ password: "Signing in with a password",
439
+ code: "Signing in with a code",
440
+ link: "Signing in with a link",
441
+ passkey: "Passkeys",
442
+ google: "Signing in with Google",
443
+ github: "Signing in with GitHub"
444
+ }[method]} is turned off for this app.`);
445
+ if (!rule || request.method !== "POST") return null;
446
+ 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) });
447
+ const captcha = deps.settings.captcha;
448
+ if (rule.captcha && captcha) {
449
+ const token = request.headers.get("x-captcha-response") ?? "";
450
+ const secret = deps.env[captcha.secretName];
451
+ if (!secret) return refusal(503, "CAPTCHA_UNAVAILABLE", `The bot check has no secret here: set ${captcha.secretName} in this environment.`);
452
+ if (!token) return refusal(400, "CAPTCHA_REQUIRED", "Show you're not a bot first.");
453
+ let passed;
454
+ try {
455
+ passed = await deps.human(captcha.provider, secret, token, deps.ip);
456
+ } catch {
457
+ return refusal(503, "CAPTCHA_UNAVAILABLE", "We couldn't check that you're not a bot. Try again.");
458
+ }
459
+ if (!passed) return refusal(400, "CAPTCHA_FAILED", "The bot check didn't pass. Try again.");
460
+ }
461
+ const password = rule.password ? body?.[rule.password] : void 0;
462
+ 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.");
463
+ return null;
464
+ }
465
+ /**
466
+ * How often one address tries each group, kept in the app's own database (`authRateLimits`): one row per address
467
+ * and group, its count since its window began. Only the paths in `PATHS` with a limit count, so reading a session
468
+ * writes nothing.
469
+ */
470
+ function rateLimiter(store, clock = Date.now) {
471
+ return async (group, ip) => {
472
+ const key = `${group}:${ip}`, now = clock(), since = now - LIMIT_WINDOW_MS;
473
+ const where = [
474
+ {
475
+ field: "key",
476
+ value: key
477
+ },
478
+ {
479
+ field: "windowStart",
480
+ operator: "gt",
481
+ value: since
482
+ },
483
+ {
484
+ field: "count",
485
+ operator: "lt",
486
+ value: LIMITS[group]
487
+ }
488
+ ];
489
+ if (await store.call("increment", {
490
+ model: "authRateLimits",
491
+ where,
492
+ increment: { count: 1 }
493
+ })) return true;
494
+ const row = await store.call("findOne", {
495
+ model: "authRateLimits",
496
+ where: [{
497
+ field: "key",
498
+ value: key
499
+ }]
500
+ });
501
+ if (row && row.windowStart > since) return false;
502
+ if (row) {
503
+ await store.call("update", {
504
+ model: "authRateLimits",
505
+ where: [{
506
+ field: "key",
507
+ value: key
508
+ }],
509
+ update: {
510
+ count: 1,
511
+ windowStart: now
512
+ }
513
+ });
514
+ return true;
515
+ }
516
+ await store.call("deleteMany", {
517
+ model: "authRateLimits",
518
+ where: [{
519
+ field: "windowStart",
520
+ operator: "lt",
521
+ value: now - 864e5
522
+ }]
523
+ });
524
+ await store.call("create", {
525
+ model: "authRateLimits",
526
+ data: {
527
+ key,
528
+ count: 1,
529
+ windowStart: now
530
+ }
531
+ }).catch(async (error) => {
532
+ if (!await store.call("findOne", {
533
+ model: "authRateLimits",
534
+ where: [{
535
+ field: "key",
536
+ value: key
537
+ }]
538
+ })) throw error;
539
+ });
540
+ return true;
541
+ };
542
+ }
543
+ /** Where each bot check's provider confirms a token: the provider the app's owner chose and connected with their own key. */
544
+ const VERIFY = {
545
+ turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify",
546
+ hcaptcha: "https://api.hcaptcha.com/siteverify",
547
+ recaptcha: "https://www.google.com/recaptcha/api/siteverify"
548
+ };
549
+ /** Asks the app's bot-check provider whether `token` passes. Throws when the provider can't be reached. */
550
+ async function verifyHuman(provider, secret, token, ip, fetcher = fetch) {
551
+ const response = await fetcher(VERIFY[provider], {
552
+ method: "POST",
553
+ headers: { "content-type": "application/x-www-form-urlencoded" },
554
+ body: new URLSearchParams({
555
+ secret,
556
+ response: token,
557
+ ...ip ? { remoteip: ip } : {}
558
+ })
559
+ });
560
+ if (!response.ok) throw new Error(`The bot check returned ${response.status}.`);
561
+ return (await response.json()).success === true;
562
+ }
563
+ /**
564
+ * Whether a password is in the public list of leaked passwords: only the first five characters of its SHA-1 leave
565
+ * the server (k-anonymity), and the list's answer is compared here. When the list can't be reached the password is
566
+ * taken, since a sign-up should not fail on someone else's outage.
567
+ */
568
+ async function leakedPassword(password, fetcher = fetch) {
569
+ const hex = [...new Uint8Array(await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password)))].map((byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();
570
+ const response = await fetcher(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, { headers: { "Add-Padding": "true" } }).catch(() => null);
571
+ if (!response?.ok) return false;
572
+ const suffix = hex.slice(5);
573
+ return (await response.text()).split("\n").some((line) => {
574
+ const [rest, count] = line.trim().split(":");
575
+ return rest === suffix && Number(count) > 0;
576
+ });
577
+ }
578
+ //#endregion
579
+ export { challenge as _, leakedPassword as a, remembering as b, refusal as c, SETTINGS_TTL_MS as d, mayJoin as f, agentOfKey as g, IDENTITY_SCOPES as h, guard as i, verifyHuman as l, settingsReader as m, LIMIT_WINDOW_MS as n, ourWords as o, publicSettings as p, REFUSALS as r, rateLimiter as s, LIMITS as t, JoinRefused as u, consentPage as v, resourceOf as x, credentialOf as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.3814",
3
+ "version": "0.1.0-staging.3817",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",