@midsummer-ai/sdk 0.1.0-staging.3608 → 0.1.0-staging.3620

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,754 @@
1
+ import { r as processEnv, t as here } from "./here-1plIxb0D.mjs";
2
+ import { i as connect } from "./client-C7QtAX5u.mjs";
3
+ import { sendSignInMail } from "./auth/mail.mjs";
4
+ import { standIn } from "./auth/stand-in.mjs";
5
+ import { FUNCTIONS_FILE, authTablesOf, schemaLines, tablesFile } from "./auth/files.mjs";
6
+ import { KEY_PREFIX } from "./auth/key.mjs";
7
+ import { betterAuth } from "better-auth/minimal";
8
+ import { admin } from "better-auth/plugins/admin";
9
+ import { emailOTP } from "better-auth/plugins/email-otp";
10
+ import { magicLink } from "better-auth/plugins/magic-link";
11
+ import { oAuthProxy } from "better-auth/plugins/oauth-proxy";
12
+ import { organization } from "better-auth/plugins/organization";
13
+ import { twoFactor } from "better-auth/plugins/two-factor";
14
+ import { passkey } from "@better-auth/passkey";
15
+ import { createAdapterFactory } from "better-auth/adapters";
16
+ import { verifyJwsAccessToken } from "better-auth/oauth2";
17
+ import { jwt } from "better-auth/plugins/jwt";
18
+ import { apiKey } from "@better-auth/api-key";
19
+ import { mcp } from "@better-auth/mcp";
20
+ //#region src/auth/store.ts
21
+ /**
22
+ * Where sign-in keeps its rows: the Seam under `@midsummer-ai/sdk/auth`. A store is a better-auth database
23
+ * adapter. The real one is `databaseStore`, the Project's own Database through the functions `db/auth.ts`
24
+ * holds (`./files.ts`); the Stand-in (`./stand-in.ts`) keeps them in memory. Both are held to the cases in
25
+ * `@midsummer-ai/sdk/auth/contract`.
26
+ */
27
+ const KIND = {
28
+ create: "mutation",
29
+ findOne: "query",
30
+ findMany: "query",
31
+ count: "query",
32
+ update: "mutation",
33
+ updateMany: "mutation",
34
+ deleteMany: "mutation",
35
+ consume: "mutation",
36
+ increment: "mutation"
37
+ };
38
+ /** A time as the Database keeps it, in milliseconds; anything else as it is. */
39
+ const stored = (value) => value instanceof Date ? value.getTime() : Array.isArray(value) ? value.map(stored) : value;
40
+ const whereOf = (where) => (where ?? []).map((clause) => ({
41
+ ...clause,
42
+ value: stored(clause.value)
43
+ }));
44
+ const fieldsOf = (data) => Object.fromEntries(Object.entries(data).map(([field, value]) => [field, stored(value)]));
45
+ /**
46
+ * The Project's Database as sign-in's store: each call one of `db/auth.ts`'s functions, as the app's server.
47
+ * `database` gives the connection a call goes over; it is asked for one each call, so it can hand out the
48
+ * request's own. A function that isn't there means `db/auth.ts` was never deployed: the error says to run
49
+ * `midsummer auth init`.
50
+ */
51
+ function databaseStore(database) {
52
+ const call = async (fn, args) => {
53
+ const db = await database();
54
+ try {
55
+ return KIND[fn] === "query" ? await db.query({
56
+ name: `auth.${fn}`,
57
+ kind: "query"
58
+ }, args) : await db.mutation({
59
+ name: `auth.${fn}`,
60
+ kind: "mutation"
61
+ }, args);
62
+ } catch (error) {
63
+ 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/.`);
64
+ throw error;
65
+ }
66
+ };
67
+ return createAdapterFactory({
68
+ config: {
69
+ adapterId: "midsummer",
70
+ adapterName: "Midsummer Database",
71
+ usePlural: false,
72
+ disableIdGeneration: true,
73
+ supportsJSON: true,
74
+ supportsArrays: true,
75
+ supportsDates: true,
76
+ supportsBooleans: true,
77
+ transaction: false,
78
+ customTransformInput: ({ data }) => stored(data),
79
+ customTransformOutput: ({ data, fieldAttributes }) => fieldAttributes.type === "date" && typeof data === "number" ? new Date(data) : data
80
+ },
81
+ adapter: () => ({
82
+ create: async ({ model, data }) => await call("create", {
83
+ model,
84
+ data: fieldsOf(data)
85
+ }),
86
+ findOne: async ({ model, where }) => await call("findOne", {
87
+ model,
88
+ where: whereOf(where)
89
+ }),
90
+ findMany: async ({ model, where, limit, offset, sortBy }) => await call("findMany", {
91
+ model,
92
+ where: whereOf(where),
93
+ ...limit !== void 0 ? { limit } : {},
94
+ ...offset !== void 0 ? { offset } : {},
95
+ ...sortBy ? { sortBy } : {}
96
+ }),
97
+ count: async ({ model, where }) => await call("count", {
98
+ model,
99
+ where: whereOf(where)
100
+ }),
101
+ update: async ({ model, where, update }) => await call("update", {
102
+ model,
103
+ where: whereOf(where),
104
+ update: fieldsOf(update)
105
+ }),
106
+ updateMany: async ({ model, where, update }) => await call("updateMany", {
107
+ model,
108
+ where: whereOf(where),
109
+ update: fieldsOf(update)
110
+ }),
111
+ delete: async ({ model, where }) => {
112
+ await call("deleteMany", {
113
+ model,
114
+ where: whereOf(where)
115
+ });
116
+ },
117
+ deleteMany: async ({ model, where }) => await call("deleteMany", {
118
+ model,
119
+ where: whereOf(where)
120
+ }),
121
+ consumeOne: async ({ model, where }) => await call("consume", {
122
+ model,
123
+ where: whereOf(where)
124
+ }),
125
+ incrementOne: async ({ model, where, increment, set }) => await call("increment", {
126
+ model,
127
+ where: whereOf(where),
128
+ increment,
129
+ ...set ? { set: fieldsOf(set) } : {}
130
+ })
131
+ })
132
+ });
133
+ }
134
+ /** How long who a key or a token acts for is kept in memory, in ms. */
135
+ const AGENT_CACHE_MS = 3e4;
136
+ /** How many of them one process keeps; past it the oldest is read again when asked. */
137
+ const KEPT_AGENTS = 1e3;
138
+ /** The scopes the authorization server itself gives meaning to: who the person is, and staying signed in. */
139
+ const IDENTITY_SCOPES = {
140
+ openid: "Know who you are",
141
+ profile: "See your name and picture",
142
+ email: "See your email address",
143
+ offline_access: "Stay connected until you remove it"
144
+ };
145
+ /** The address tokens for `origin`'s MCP server are bound to. */
146
+ const resourceOf = (origin, settings) => `${origin}${settings.mcpPath === "/" ? "" : settings.mcpPath}`;
147
+ /**
148
+ * better-auth's plugins for agents. Their tables are always there, so `db/authTables.ts` is the same for every
149
+ * app; clients can register themselves only once the app declares a scope, since before that there is nothing
150
+ * for one to ask for.
151
+ */
152
+ function agentPlugins(origin, settings) {
153
+ const declared = Object.keys(settings.scopes);
154
+ return [
155
+ jwt({ disableSettingJwtHeader: true }),
156
+ mcp({
157
+ resource: resourceOf(origin, settings),
158
+ loginPage: settings.signInPage,
159
+ consentPage: settings.consentPage,
160
+ scopes: [...Object.keys(IDENTITY_SCOPES), ...declared],
161
+ accessTokenExpiresIn: 300,
162
+ allowDynamicClientRegistration: declared.length > 0,
163
+ allowUnauthenticatedClientRegistration: declared.length > 0,
164
+ clientRegistrationDefaultApplicationType: "infer"
165
+ }),
166
+ apiKey({
167
+ defaultPrefix: KEY_PREFIX,
168
+ rateLimit: { enabled: false },
169
+ enableMetadata: true
170
+ })
171
+ ];
172
+ }
173
+ /** An agent's credential on a request: an API key, an MCP client's access token, or neither. */
174
+ function credentialOf(request) {
175
+ const header = request.headers.get("x-api-key")?.trim();
176
+ if (header) return { key: header };
177
+ const bearer = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
178
+ if (!bearer) return null;
179
+ return bearer.startsWith("key_") ? { key: bearer } : { token: bearer };
180
+ }
181
+ /** A small memory of what was read, each entry for `AGENT_CACHE_MS`. */
182
+ function remembering(clock = Date.now) {
183
+ const kept = /* @__PURE__ */ new Map();
184
+ return {
185
+ async get(name, read) {
186
+ const found = kept.get(name);
187
+ if (found && found.until > clock()) return found.value;
188
+ const value = await read();
189
+ if (kept.size >= KEPT_AGENTS) kept.delete(kept.keys().next().value);
190
+ kept.set(name, {
191
+ until: clock() + AGENT_CACHE_MS,
192
+ value
193
+ });
194
+ return value;
195
+ },
196
+ forget(name) {
197
+ kept.delete(name);
198
+ }
199
+ };
200
+ }
201
+ 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("");
202
+ /**
203
+ * The agent a key signs in, or null for one that is unknown, revoked or expired. A key is checked by
204
+ * better-auth, which notes when it was last used; the answer is kept for `AGENT_CACHE_MS`.
205
+ */
206
+ async function agentOfKey(instance, key, memory) {
207
+ if (!key.startsWith("key_") || key.length > 512) return null;
208
+ return memory.get(`key:${await digest(key)}`, async () => {
209
+ const checked = await instance.api.verifyApiKey({ body: { key } });
210
+ if (!checked.valid || !checked.key) return null;
211
+ return {
212
+ via: "key",
213
+ userId: checked.key.referenceId,
214
+ scopes: checked.key.permissions?.scope ?? [],
215
+ agent: {
216
+ id: checked.key.id,
217
+ ...checked.key.name ? { name: checked.key.name } : {}
218
+ }
219
+ };
220
+ });
221
+ }
222
+ /**
223
+ * The agent an MCP client's access token signs in, or null for one that is not this app's: its signature by the
224
+ * app's own keys, its issuer, that it is bound to the app's MCP address, and its expiry are all checked.
225
+ */
226
+ async function agentOfToken(instance, token, origin, authPath, resource) {
227
+ let claims;
228
+ try {
229
+ claims = await verifyJwsAccessToken(token, {
230
+ jwksFetch: async () => await instance.api.getJwks(),
231
+ jwksCacheKey: instance,
232
+ verifyOptions: {
233
+ issuer: `${origin}${authPath}`,
234
+ audience: resource
235
+ }
236
+ });
237
+ } catch {
238
+ return null;
239
+ }
240
+ const client = typeof claims.azp === "string" ? claims.azp : typeof claims.client_id === "string" ? claims.client_id : null;
241
+ if (typeof claims.sub !== "string" || !client) return null;
242
+ const scopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter((scope) => scope && !(scope in IDENTITY_SCOPES)) : [];
243
+ return {
244
+ via: "client",
245
+ userId: claims.sub,
246
+ scopes,
247
+ agent: { id: client }
248
+ };
249
+ }
250
+ /** 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. */
251
+ function challenge(origin, settings, scope, lacking) {
252
+ const metadata = `${origin}/.well-known/oauth-protected-resource${settings.mcpPath === "/" ? "" : settings.mcpPath}`;
253
+ const parts = [
254
+ ...lacking ? ["error=\"insufficient_scope\""] : [],
255
+ ...scope ? [`scope="${scope}"`] : [],
256
+ `resource_metadata="${metadata}"`
257
+ ];
258
+ const message = lacking ? `This needs the scope ${scope}.` : "Sign in to use this.";
259
+ return Response.json({
260
+ error: lacking ? "insufficient_scope" : "unauthorized",
261
+ message
262
+ }, {
263
+ status: lacking ? 403 : 401,
264
+ headers: {
265
+ "WWW-Authenticate": `Bearer ${parts.join(", ")}`,
266
+ "Cache-Control": "no-store"
267
+ }
268
+ });
269
+ }
270
+ const escape = (text) => text.replace(/[&<>"']/g, (c) => ({
271
+ "&": "&amp;",
272
+ "<": "&lt;",
273
+ ">": "&gt;",
274
+ "\"": "&quot;",
275
+ "'": "&#39;"
276
+ })[c]);
277
+ /**
278
+ * The page that asks a signed-in person whether a client may use the app as them: the client's name, where it
279
+ * goes back to, and each scope it asks for in the app's own words. Its two buttons post the same signed query
280
+ * the page was opened with, so what is granted is what was shown.
281
+ */
282
+ function consentPage(input) {
283
+ const lines = input.scopes.map((scope) => `<li>${escape(input.described[scope] ?? IDENTITY_SCOPES[scope] ?? scope)}</li>`).join("");
284
+ return `<!doctype html>
285
+ <html lang="en">
286
+ <head>
287
+ <meta charset="utf-8">
288
+ <meta name="viewport" content="width=device-width, initial-scale=1">
289
+ <meta name="robots" content="noindex">
290
+ <title>${escape(input.client)} wants to use ${escape(input.app)}</title>
291
+ <style>
292
+ :root { color-scheme: light dark; --text: #111; --quiet: #555; --line: #ddd; --page: #fafafa; --card: #fff; --go: #111; --go-text: #fff }
293
+ @media (prefers-color-scheme: dark) { :root { --text: #f2f2f2; --quiet: #aaa; --line: #333; --page: #111; --card: #1a1a1a; --go: #f2f2f2; --go-text: #111 } }
294
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px; box-sizing: border-box; background: var(--page); color: var(--text); font: 16px/1.5 system-ui, sans-serif }
295
+ main { width: 100%; max-width: 400px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 24px; box-sizing: border-box }
296
+ h1 { font-size: 20px; line-height: 1.3; margin: 0 0 8px }
297
+ p { margin: 0 0 16px; color: var(--quiet) }
298
+ ul { margin: 0 0 24px; padding-left: 20px }
299
+ form { display: flex; gap: 8px; justify-content: flex-end }
300
+ button { font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid var(--line); background: transparent; color: var(--text); cursor: pointer }
301
+ button[value="true"] { background: var(--go); color: var(--go-text); border-color: var(--go) }
302
+ </style>
303
+ </head>
304
+ <body>
305
+ <main>
306
+ <h1>${escape(input.client)} wants to use ${escape(input.app)} as you</h1>
307
+ <p>You're signed in as ${escape(input.person)}. It goes back to ${escape(input.returnsTo)}.</p>
308
+ <ul>${lines}</ul>
309
+ <form method="post" action="${escape(input.action)}">
310
+ <input type="hidden" name="oauth_query" value="${escape(input.query)}">
311
+ <button name="accept" value="false">Don't allow</button>
312
+ <button name="accept" value="true">Allow</button>
313
+ </form>
314
+ </main>
315
+ </body>
316
+ </html>
317
+ `;
318
+ }
319
+ //#endregion
320
+ //#region src/auth/index.ts
321
+ /**
322
+ * Sign-in for the people who use your app, with one import:
323
+ *
324
+ * import { auth } from "@midsummer-ai/sdk/auth"
325
+ *
326
+ * app.all("/api/auth/*", (c) => auth.handler(c.req.raw)) // sign-up, sign-in, sign-out, codes, Google, GitHub
327
+ * const signedIn = await auth.session(c.req.raw) // { user, session } or null
328
+ * if (!signedIn) return c.redirect("/sign-in")
329
+ *
330
+ * It is better-auth, set up for Midsummer: email and password, codes and sign-in links by mail, Google
331
+ * and GitHub when their keys are set, organizations with roles and invitations, two-factor codes,
332
+ * passkeys and bans. Browsers talk to it with better-auth's own client (`better-auth/client` or
333
+ * `better-auth/react`), at `/api/auth`.
334
+ *
335
+ * Users, sessions and accounts are tables in the Project's own Database (`db/authTables.ts` and
336
+ * `db/auth.ts`, which `midsummer auth init` writes), so they show on its page, join with the app's own
337
+ * tables, and branch with it: a preview starts with no users. A session is kept in its cookie for five
338
+ * minutes, signed, so most requests read no row; a session revoked or a user banned stops within those
339
+ * five minutes. Mail goes through Email (`./mail.ts`).
340
+ *
341
+ * It reads what it needs from the environment: `AUTH_SECRET` (`midsummer env set <project> AUTH_SECRET
342
+ * --kind secret --generate`, once for each environment), `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`,
343
+ * `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`, and for Google and GitHub on previews `AUTH_PRODUCTION_URL`
344
+ * and `AUTH_PROXY_SECRET`, which `midsummer auth provider set` writes: previews sign in through
345
+ * production's one callback address. `AUTH_EMAIL_FROM` sends its mail from a domain of the Team's.
346
+ *
347
+ * Agents sign in too, once the app declares what they may do (`createAuth({ scopes })`, `./agents.ts`): a user
348
+ * gives an agent an API key (`auth.keys.create`), or signs in from an MCP client, which finds the app's own
349
+ * OAuth server under `/api/auth` and `/.well-known`. `auth.session(request, { scope })` is a person, a key or a
350
+ * client alike, and `auth.protect(scope, handler)` guards a route such as the app's MCP server.
351
+ *
352
+ * Under `midsummer dev` it keeps rows in the Database's Stand-in when `db/` runs, or in memory, and prints
353
+ * each mail. In tests, give it the Stand-in: `createAuth({ store: stand.store, mail: stand.mail })`.
354
+ * Every failure it can name is an `AuthError`, whose `code` tells you which kind.
355
+ */
356
+ var AuthError = class extends Error {
357
+ code;
358
+ /** The scope an agent lacked, when that is why it was refused. */
359
+ scope;
360
+ constructor(code, message, scope) {
361
+ super(message);
362
+ this.code = code;
363
+ this.name = "AuthError";
364
+ if (scope !== void 0) this.scope = scope;
365
+ }
366
+ };
367
+ /** Where sign-in is served, under every address of the app. */
368
+ const AUTH_PATH = "/api/auth";
369
+ /** How long a session is kept in its cookie before its row is read again, in seconds. */
370
+ const SESSION_CACHE_S = 300;
371
+ /** Under `midsummer dev`, where no environment gives a secret: never accepted outside it. */
372
+ const DEV_SECRET = "midsummer-dev-sign-in-secret-never-used-outside-midsummer-dev";
373
+ /** How many addresses one process keeps sign-in ready for; past it the oldest is made again when asked. */
374
+ const KEPT_ORIGINS = 16;
375
+ /** The origin a request came to, as the dispatcher routed it. */
376
+ function originOf(request) {
377
+ return new URL(request.url).origin;
378
+ }
379
+ /** The Database connection a request's sign-in uses: one per request in a deployment, one per process elsewhere. */
380
+ function requestDatabase(binding) {
381
+ const perRequest = /* @__PURE__ */ new WeakMap();
382
+ let shared;
383
+ return () => {
384
+ const request = here();
385
+ const made = () => connect({ binding }).catch((error) => {
386
+ throw new AuthError("unavailable", `Sign-in couldn't reach the database bound as ${binding}: ${error.message}`);
387
+ });
388
+ if (!request) return shared ??= made();
389
+ let found = perRequest.get(request);
390
+ if (!found) {
391
+ found = made();
392
+ perRequest.set(request, found);
393
+ }
394
+ return found;
395
+ };
396
+ }
397
+ /** The store sign-in keeps rows in where this code runs. */
398
+ function storeFor(options, env) {
399
+ if (options.store) return options.store;
400
+ if (here() || env.MIDSUMMER_DATABASE_URL || env.MIDSUMMER_IDENTITY_REQUEST_TOKEN) return databaseStore(requestDatabase(options.database ?? "main"));
401
+ if (env.MIDSUMMER_DEV === "1") return devStore();
402
+ throw new AuthError("forbidden", "This code runs outside a deployment, so no database keeps its users. In tests, give createAuth the Stand-in: createAuth({ store: standIn().store }).");
403
+ }
404
+ /** `midsummer dev` without a database: one Stand-in for the process, its rows gone when it stops. */
405
+ let devMemory;
406
+ const devStore = () => devMemory ??= standIn().store;
407
+ /** How agents sign in, from the app's options. */
408
+ const agentSettings = (options) => ({
409
+ scopes: options.scopes ?? {},
410
+ mcpPath: options.mcpPath ?? "/mcp",
411
+ signInPage: options.signInPage ?? "/sign-in",
412
+ consentPage: options.consentPage ?? CONSENT_PATH
413
+ });
414
+ /** Where sign-in's own page asks a person whether to let an MCP client in. */
415
+ const CONSENT_PATH = `${AUTH_PATH}/agent-consent`;
416
+ /** better-auth as Midsummer sets it up, for one origin. */
417
+ function instanceFor(origin, options, store, env) {
418
+ const appName = options.appName ?? env.APP_NAME ?? "your app";
419
+ const secret = env.AUTH_SECRET || (env.MIDSUMMER_DEV === "1" ? DEV_SECRET : "");
420
+ 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>");
421
+ const mail = options.mail ?? ((one) => sendSignInMail(one, env));
422
+ const send = (one) => mail({
423
+ ...one,
424
+ app: appName
425
+ });
426
+ const social = {
427
+ ...env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET ? { google: {
428
+ clientId: env.GOOGLE_CLIENT_ID,
429
+ clientSecret: env.GOOGLE_CLIENT_SECRET
430
+ } } : {},
431
+ ...env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET ? { github: {
432
+ clientId: env.GITHUB_CLIENT_ID,
433
+ clientSecret: env.GITHUB_CLIENT_SECRET
434
+ } } : {}
435
+ };
436
+ const production = env.AUTH_PRODUCTION_URL ? URL.parse(env.AUTH_PRODUCTION_URL)?.origin : void 0;
437
+ const invitation = options.invitationUrl ?? ((at, id) => `${at}/accept-invitation/${id}`);
438
+ const plugins = [
439
+ emailOTP({ sendVerificationOTP: async ({ email, otp }) => send({
440
+ to: email,
441
+ kind: "code",
442
+ code: otp
443
+ }) }),
444
+ magicLink({ sendMagicLink: async ({ email, url }) => send({
445
+ to: email,
446
+ kind: "link",
447
+ url
448
+ }) }),
449
+ organization({ sendInvitationEmail: async ({ email, id, organization: joined, inviter }) => send({
450
+ to: email,
451
+ kind: "invite",
452
+ url: invitation(origin, id),
453
+ organization: joined.name.slice(0, 80),
454
+ inviter: (inviter.user.name || inviter.user.email).slice(0, 80)
455
+ }) }),
456
+ twoFactor({
457
+ issuer: appName,
458
+ otpOptions: { sendOTP: async ({ user, otp }) => send({
459
+ to: user.email,
460
+ kind: "code",
461
+ code: otp
462
+ }) }
463
+ }),
464
+ passkey({ rpName: appName }),
465
+ admin(),
466
+ ...agentPlugins(origin, agentSettings(options)),
467
+ ...production && env.AUTH_PROXY_SECRET ? [oAuthProxy({
468
+ productionURL: production,
469
+ secret: env.AUTH_PROXY_SECRET
470
+ })] : [],
471
+ ...options.plugins ?? []
472
+ ];
473
+ return betterAuth({
474
+ appName,
475
+ baseURL: origin,
476
+ basePath: AUTH_PATH,
477
+ secret,
478
+ database: store,
479
+ trustedOrigins: [origin, ...production && production !== origin ? [production] : []],
480
+ emailAndPassword: {
481
+ enabled: true,
482
+ sendResetPassword: async ({ user, url }) => send({
483
+ to: user.email,
484
+ kind: "reset",
485
+ url
486
+ })
487
+ },
488
+ emailVerification: {
489
+ sendOnSignUp: true,
490
+ autoSignInAfterVerification: true,
491
+ sendVerificationEmail: async ({ user, url }) => send({
492
+ to: user.email,
493
+ kind: "verify",
494
+ url
495
+ })
496
+ },
497
+ socialProviders: social,
498
+ session: { cookieCache: {
499
+ enabled: true,
500
+ maxAge: 300
501
+ } },
502
+ telemetry: { enabled: false },
503
+ plugins
504
+ });
505
+ }
506
+ const DAY_S = 86400;
507
+ const keyOf = (row) => ({
508
+ id: row.id,
509
+ name: row.name,
510
+ start: row.start,
511
+ scopes: row.permissions?.scope ?? [],
512
+ createdAt: new Date(row.createdAt),
513
+ expiresAt: row.expiresAt ? new Date(row.expiresAt) : null,
514
+ lastUsedAt: row.lastRequest ? new Date(row.lastRequest) : null
515
+ });
516
+ /** Sign-in over `options`: nothing is made until the first request, which may be at a module's top. */
517
+ function createAuth(options = {}) {
518
+ const kept = /* @__PURE__ */ new Map();
519
+ let store;
520
+ const settings = agentSettings(options);
521
+ const agents = remembering(), users = remembering();
522
+ const at = (origin) => {
523
+ const normal = new URL(origin).origin;
524
+ let found = kept.get(normal);
525
+ if (!found) {
526
+ const env = options.env ?? processEnv();
527
+ store ??= storeFor(options, env);
528
+ found = instanceFor(normal, options, store, env);
529
+ if (kept.size >= KEPT_ORIGINS) kept.delete(kept.keys().next().value);
530
+ kept.set(normal, found);
531
+ }
532
+ return found;
533
+ };
534
+ const apiOf = (instance) => instance.api;
535
+ const declared = (scope, what) => {
536
+ if (!Object.hasOwn(settings.scopes, scope)) throw new AuthError("invalid", `${what} the scope ${scope}, which the app doesn't declare: add it to createAuth({ scopes }).`);
537
+ };
538
+ /** The person signed in themselves, with their session's cookie. */
539
+ async function person(request) {
540
+ const found = await at(originOf(request)).api.getSession({ headers: request.headers });
541
+ return found ? {
542
+ via: "session",
543
+ ...found
544
+ } : null;
545
+ }
546
+ /** The person a request about their own keys or grants comes from; never an agent, which can't give itself more. */
547
+ async function owner(request, what) {
548
+ const found = await person(request);
549
+ if (!found) throw new AuthError("forbidden", `Sign in to ${what}.`);
550
+ return found;
551
+ }
552
+ async function session(request, asked) {
553
+ const scope = asked?.scope;
554
+ if (scope === void 0) return person(request);
555
+ declared(scope, "This route asks for");
556
+ const credential = credentialOf(request);
557
+ if (!credential) return person(request);
558
+ const origin = originOf(request), instance = at(origin);
559
+ const identity = "key" in credential ? await agentOfKey(instance, credential.key, {
560
+ get: (name, read) => agents.get(`${origin}\n${name}`, read),
561
+ forget: (name) => agents.forget(`${origin}\n${name}`)
562
+ }) : await agentOfToken(instance, credential.token, origin, AUTH_PATH, resourceOf(origin, settings));
563
+ if (!identity) return null;
564
+ const user = await users.get(`${origin}\n${identity.userId}`, async () => await (await instance.$context).internalAdapter.findUserById(identity.userId) ?? null);
565
+ if (!user || user.banned) return null;
566
+ 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);
567
+ return {
568
+ via: identity.via,
569
+ user,
570
+ scopes: identity.scopes,
571
+ agent: identity.agent
572
+ };
573
+ }
574
+ /** Sign-in's own page that asks a person whether to let an MCP client in, and what it does with their answer. */
575
+ async function consent(request, origin, instance) {
576
+ const url = new URL(request.url);
577
+ if (request.method === "POST") {
578
+ if (request.headers.get("origin") !== origin) return new Response("This form was sent from another site.", { status: 403 });
579
+ const form = await request.formData();
580
+ const answered = await instance.handler(new Request(`${origin}${AUTH_PATH}/oauth2/consent`, {
581
+ method: "POST",
582
+ headers: {
583
+ origin,
584
+ cookie: request.headers.get("cookie") ?? "",
585
+ "content-type": "application/json"
586
+ },
587
+ body: JSON.stringify({
588
+ accept: form.get("accept") === "true",
589
+ oauth_query: String(form.get("oauth_query") ?? "")
590
+ })
591
+ }));
592
+ const answer = await answered.json().catch(() => null);
593
+ if (!answered.ok || !answer?.url) return new Response("This request to sign in has ended. Start again from the app that asked.", { status: 400 });
594
+ return new Response(null, {
595
+ status: 302,
596
+ headers: {
597
+ Location: answer.url,
598
+ "Cache-Control": "no-store"
599
+ }
600
+ });
601
+ }
602
+ const signedIn = await person(request);
603
+ if (!signedIn) return new Response(null, {
604
+ status: 302,
605
+ headers: { Location: `${settings.signInPage}${url.search}` }
606
+ });
607
+ const clientId = url.searchParams.get("client_id") ?? "";
608
+ const client = await apiOf(instance).getOAuthClientPublic({
609
+ query: { client_id: clientId },
610
+ headers: request.headers
611
+ }).catch(() => null);
612
+ if (!client) return new Response("No such app asked to sign in.", { status: 400 });
613
+ const returnsTo = URL.parse(url.searchParams.get("redirect_uri") ?? "")?.host ?? "the app";
614
+ const html = consentPage({
615
+ app: instance.options.appName ?? "this app",
616
+ client: client.client_name?.trim() || "An app",
617
+ returnsTo,
618
+ person: signedIn.user.email,
619
+ scopes: (url.searchParams.get("scope") ?? "").split(" ").filter(Boolean),
620
+ described: settings.scopes,
621
+ query: url.search.slice(1),
622
+ action: CONSENT_PATH
623
+ });
624
+ return new Response(html, { headers: {
625
+ "Content-Type": "text/html; charset=utf-8",
626
+ "Cache-Control": "no-store",
627
+ "X-Frame-Options": "DENY",
628
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"
629
+ } });
630
+ }
631
+ return {
632
+ async handler(request) {
633
+ const origin = originOf(request), instance = at(origin), { pathname } = new URL(request.url);
634
+ if (pathname === CONSENT_PATH && settings.consentPage === CONSENT_PATH) return consent(request, origin, instance);
635
+ if (pathname === "/.well-known/oauth-authorization-server") return instance.handler(new Request(`${origin}/.well-known/oauth-authorization-server${AUTH_PATH}`, request));
636
+ return instance.handler(request);
637
+ },
638
+ session,
639
+ protect: (scope, handler) => async (request) => {
640
+ const origin = originOf(request);
641
+ let signedIn;
642
+ try {
643
+ signedIn = await session(request, { scope });
644
+ } catch (error) {
645
+ if (error instanceof AuthError && error.scope !== void 0) return challenge(origin, settings, scope, true);
646
+ throw error;
647
+ }
648
+ return signedIn ? handler(request, signedIn) : challenge(origin, settings, scope, false);
649
+ },
650
+ keys: {
651
+ async create(request, input) {
652
+ const { user } = await owner(request, "make a key");
653
+ const name = input.name.trim();
654
+ if (!name || name.length > 32) throw new AuthError("invalid", "A key's name is 1 to 32 characters.");
655
+ if (!input.scopes.length) throw new AuthError("invalid", "A key carries at least one of the app's scopes.");
656
+ for (const scope of input.scopes) declared(scope, "A key can't carry");
657
+ 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.");
658
+ const made = await apiOf(at(originOf(request))).createApiKey({ body: {
659
+ userId: user.id,
660
+ name,
661
+ permissions: { scope: [...new Set(input.scopes)] },
662
+ ...input.expiresIn !== void 0 ? { expiresIn: input.expiresIn } : {}
663
+ } });
664
+ return {
665
+ ...keyOf(made),
666
+ key: made.key
667
+ };
668
+ },
669
+ async list(request) {
670
+ await owner(request, "see your keys");
671
+ return (await apiOf(at(originOf(request))).listApiKeys({ headers: request.headers })).apiKeys.map(keyOf);
672
+ },
673
+ async revoke(request, id) {
674
+ await owner(request, "revoke a key");
675
+ await apiOf(at(originOf(request))).deleteApiKey({
676
+ body: { keyId: id },
677
+ headers: request.headers
678
+ });
679
+ }
680
+ },
681
+ grants: {
682
+ async list(request) {
683
+ await owner(request, "see the apps you let in");
684
+ const api = apiOf(at(originOf(request)));
685
+ const consents = await api.getOAuthConsents({ headers: request.headers });
686
+ const names = new Map(await Promise.all([...new Set(consents.map((one) => one.clientId))].map(async (id) => [id, (await api.getOAuthClientPublic({
687
+ query: { client_id: id },
688
+ headers: request.headers
689
+ }).catch(() => null))?.client_name ?? null])));
690
+ return consents.map((one) => ({
691
+ id: one.id,
692
+ clientId: one.clientId,
693
+ client: names.get(one.clientId) ?? null,
694
+ scopes: one.scopes,
695
+ createdAt: new Date(one.createdAt)
696
+ }));
697
+ },
698
+ async revoke(request, id) {
699
+ const { user } = await owner(request, "remove an app's access");
700
+ const instance = at(originOf(request)), api = apiOf(instance);
701
+ const granted = await api.getOAuthConsent({
702
+ query: { id },
703
+ headers: request.headers
704
+ });
705
+ const { adapter } = await instance.$context;
706
+ const theirs = [{
707
+ field: "clientId",
708
+ value: granted.clientId
709
+ }, {
710
+ field: "userId",
711
+ value: user.id
712
+ }];
713
+ await Promise.all([adapter.deleteMany({
714
+ model: "oauthRefreshToken",
715
+ where: theirs
716
+ }), adapter.deleteMany({
717
+ model: "oauthAccessToken",
718
+ where: theirs
719
+ })]);
720
+ await api.deleteOAuthConsent({
721
+ body: { id },
722
+ headers: request.headers
723
+ });
724
+ }
725
+ },
726
+ at
727
+ };
728
+ }
729
+ /** Sign-in for this deployment, set up from its environment. */
730
+ const auth = createAuth();
731
+ /**
732
+ * The `db/` files sign-in keeps its rows with, by name in `db/`, as `midsummer auth init` writes them, and what
733
+ * `db/schema.ts` takes its tables in with: an import, and an entry for each table inside `defineSchema({ ... })`.
734
+ * `plugins` are the ones given `createAuth`, whose tables are made too.
735
+ */
736
+ function authFiles(options = {}) {
737
+ const tables = authTablesOf(createAuth({
738
+ ...options,
739
+ store: standIn().store,
740
+ env: { AUTH_SECRET: DEV_SECRET }
741
+ }).at("https://app.invalid").options);
742
+ return {
743
+ files: {
744
+ "auth.ts": FUNCTIONS_FILE,
745
+ "authTables.ts": tablesFile(tables)
746
+ },
747
+ schema: {
748
+ import: "import { authTables } from \"./authTables\"",
749
+ tables: schemaLines(tables)
750
+ }
751
+ };
752
+ }
753
+ //#endregion
754
+ export { authFiles as a, auth as i, AuthError as n, createAuth as o, SESSION_CACHE_S as r, databaseStore as s, AUTH_PATH as t };