@midsummer-ai/sdk 0.1.0-staging.3716 → 0.1.0-staging.3722

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/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { r as PublicSettings } from "../settings-si8iBtwc.mjs";
1
+ import { r as PublicSettings } from "../settings-Dz3irtlu.mjs";
2
2
  //#region src/auth/client.d.ts
3
3
  /** A signed-in user as the browser sees them: never their private metadata. */
4
4
  interface ClientUser {
@@ -85,11 +85,17 @@ declare class AuthClientError extends Error {
85
85
  readonly status: number;
86
86
  constructor(code: string, message: string, status: number);
87
87
  }
88
- /** What signing in with a password returns: signed in, or asked for a second factor first. */
88
+ /**
89
+ * What signing up or signing in with a password returns: signed in; asked for a second factor first; or asked to
90
+ * confirm the email, when the app's settings want it confirmed (`confirmEmail`) and a link to do it is on its way.
91
+ * Signing up never asks for a second factor.
92
+ */
89
93
  type SignInResult = {
90
94
  readonly signedIn: true;
91
95
  } | {
92
96
  readonly twoFactor: true;
97
+ } | {
98
+ readonly verifyEmail: true;
93
99
  };
94
100
  interface AuthClient {
95
101
  /** Who is signed in in this browser, or null. */
@@ -100,12 +106,13 @@ interface AuthClient {
100
106
  settings(): Promise<ClientSettings>;
101
107
  /** Calls `listener` whenever this client signs in or out; returns a stop. */
102
108
  onChange(listener: () => void): () => void;
109
+ /** Makes an account, and signs its person in unless the app wants their email confirmed first. */
103
110
  signUp(input: {
104
111
  readonly email: string;
105
112
  readonly password: string;
106
113
  readonly name: string;
107
114
  readonly captcha?: string;
108
- }): Promise<void>;
115
+ }): Promise<SignInResult>;
109
116
  readonly signIn: {
110
117
  password(input: {
111
118
  readonly email: string;
package/auth/client.mjs CHANGED
@@ -114,10 +114,20 @@ function authClient(options = {}) {
114
114
  /** After signing in: on to the page that asks the person about an MCP client, when that is where they came from. */
115
115
  const onward = (answer) => {
116
116
  const next = answer;
117
- if (next?.redirect && next.url) go(next.url);
117
+ const to = next?.next ?? (next?.redirect ? next.url : void 0);
118
+ if (to) go(to);
119
+ };
120
+ /** What sign-in's own `/sign-up` and `/sign-in` returned, as the caller reads it; signed in, it tells listeners and goes on. */
121
+ const result = (returned) => {
122
+ const answer = returned;
123
+ if (answer?.twoFactor) return { twoFactor: true };
124
+ if (answer?.verifyEmail) return { verifyEmail: true };
125
+ changed();
126
+ onward(answer);
127
+ return { signedIn: true };
118
128
  };
119
129
  return {
120
- session: async () => await call("/get-session") ?? null,
130
+ session: async () => await call("/session") ?? null,
121
131
  settings: () => call("/settings"),
122
132
  onChange(listener) {
123
133
  listeners.add(listener);
@@ -125,25 +135,16 @@ function authClient(options = {}) {
125
135
  listeners.delete(listener);
126
136
  };
127
137
  },
128
- async signUp(input) {
129
- onward(await post("/sign-up/email", {
130
- email: input.email,
131
- password: input.password,
132
- name: input.name
133
- }, input.captcha));
134
- changed();
135
- },
138
+ signUp: async (input) => result(await post("/sign-up", {
139
+ email: input.email,
140
+ password: input.password,
141
+ name: input.name
142
+ }, input.captcha)),
136
143
  signIn: {
137
- async password(input) {
138
- const answer = await post("/sign-in/email", {
139
- email: input.email,
140
- password: input.password
141
- }, input.captcha);
142
- if (answer?.twoFactorRedirect) return { twoFactor: true };
143
- changed();
144
- onward(answer);
145
- return { signedIn: true };
146
- },
144
+ password: async (input) => result(await post("/sign-in", {
145
+ email: input.email,
146
+ password: input.password
147
+ }, input.captcha)),
147
148
  code: {
148
149
  async send(email, options = {}) {
149
150
  await post("/email-otp/send-verification-otp", {
@@ -1,6 +1,6 @@
1
- import { n as AuthStore } from "../store-DsWS_MpS.mjs";
1
+ import { n as AuthStore } from "../store-CLGBhEpO.mjs";
2
2
  import { SignInMail } from "./mail.mjs";
3
- import { i as Auth } from "../index-Cc5gCPfV.mjs";
3
+ import { a as Auth } from "../index-DYSS7OGg.mjs";
4
4
  //#region src/auth/contract.d.ts
5
5
  interface AuthHarness {
6
6
  /** Sign-in over a store with no users, made with `scopes: CONTRACT_SCOPES`. */
package/auth/contract.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as LIMIT_WINDOW_MS, l as SETTINGS_TTL_MS, n as AuthError, s as LIMITS } from "../auth-BxXrC_JJ.mjs";
1
+ import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-C9V1Xb0w.mjs";
2
2
  import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
3
3
  //#region src/auth/contract.ts
4
4
  /**
@@ -54,7 +54,7 @@ function equal(actual, expected, what, pick = (value) => value) {
54
54
  if (JSON.stringify(pick(actual)) !== JSON.stringify(expected)) throw new Error(`${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(pick(actual))}`);
55
55
  }
56
56
  async function signUp(auth, jar, email) {
57
- const answer = await ask(auth, jar, "/sign-up/email", {
57
+ const answer = await ask(auth, jar, "/sign-up", {
58
58
  email,
59
59
  password: "correct horse battery",
60
60
  name: email.split("@")[0]
@@ -101,7 +101,7 @@ async function refusalOf(response) {
101
101
  return [response.status, body.code ?? null];
102
102
  }
103
103
  /** A sign-in as a browser at `ip` sends it. */
104
- const tryFrom = (auth, ip, email) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/sign-in/email`, {
104
+ const tryFrom = (auth, ip, email) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/sign-in`, {
105
105
  method: "POST",
106
106
  headers: {
107
107
  origin: CONTRACT_ORIGIN,
@@ -123,7 +123,7 @@ const authContract = [
123
123
  public: { plan: "pro" },
124
124
  private: { customer: "cus_123" }
125
125
  });
126
- const browser = await (await ask(auth, jar, "/get-session?disableCookieCache=true")).json();
126
+ const browser = await (await ask(auth, jar, "/session?disableCookieCache=true")).json();
127
127
  equal([browser.user.publicMetadata, "privateMetadata" in browser.user], [{ plan: "pro" }, false], "what the browser reads");
128
128
  equal((await auth.session(asPerson(jar), { fresh: true }))?.user.publicMetadata, { plan: "pro" }, "what the app's routes read");
129
129
  equal((await auth.users.get(id))?.privateMetadata, { customer: "cus_123" }, "what the server reads");
@@ -177,7 +177,7 @@ const authContract = [
177
177
  {
178
178
  name: "a password that appeared in a leak is refused at sign-up and as a new one",
179
179
  async run({ auth }) {
180
- equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
180
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up", {
181
181
  email: "pat@example.com",
182
182
  password: "password1234",
183
183
  name: "Pat"
@@ -213,7 +213,7 @@ const authContract = [
213
213
  siteKey: "site-key",
214
214
  secretName: "CAPTCHA_SECRET"
215
215
  } });
216
- const signUpWith = (token) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/sign-up/email`, {
216
+ const signUpWith = (token) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/sign-up`, {
217
217
  method: "POST",
218
218
  headers: {
219
219
  origin: CONTRACT_ORIGIN,
@@ -254,7 +254,7 @@ const authContract = [
254
254
  }
255
255
  });
256
256
  const jar = new Jar();
257
- equal(await refusalOf(await ask(auth, jar, "/sign-up/email", {
257
+ equal(await refusalOf(await ask(auth, jar, "/sign-up", {
258
258
  email: "ada@example.com",
259
259
  password: "correct horse battery",
260
260
  name: "Ada"
@@ -280,18 +280,24 @@ const authContract = [
280
280
  }
281
281
  },
282
282
  {
283
- name: "sign-up open only to some email domains takes theirs and refuses the rest",
283
+ name: "sign-up open only to some email domains and addresses takes theirs and refuses the rest",
284
284
  async run({ auth, store }) {
285
285
  await settle(store, { signUp: {
286
286
  policy: "domains",
287
- domains: ["acme.dev"]
287
+ domains: ["acme.dev"],
288
+ emails: ["ola@example.com"]
288
289
  } });
289
- equal((await ask(auth, new Jar(), "/sign-up/email", {
290
+ equal((await ask(auth, new Jar(), "/sign-up", {
290
291
  email: "ada@acme.dev",
291
292
  password: "correct horse battery",
292
293
  name: "Ada"
293
294
  })).status, 200, "an email at acme.dev");
294
- equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
295
+ equal((await ask(auth, new Jar(), "/sign-up", {
296
+ email: "Ola@Example.com",
297
+ password: "correct horse battery",
298
+ name: "Ola"
299
+ })).status, 200, "an address the list names");
300
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up", {
295
301
  email: "lin@example.com",
296
302
  password: "correct horse battery",
297
303
  name: "Lin"
@@ -318,7 +324,7 @@ const authContract = [
318
324
  domains: []
319
325
  } });
320
326
  later(SETTINGS_TTL_MS);
321
- equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
327
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up", {
322
328
  email: "new@example.com",
323
329
  password: "correct horse battery",
324
330
  name: "New"
@@ -333,12 +339,12 @@ const authContract = [
333
339
  decidedBy: "Owner"
334
340
  }
335
341
  });
336
- equal((await ask(auth, new Jar(), "/sign-up/email", {
342
+ equal((await ask(auth, new Jar(), "/sign-up", {
337
343
  email: "New@Example.com",
338
344
  password: "correct horse battery",
339
345
  name: "New"
340
346
  })).status, 200, "someone the owner approved, in any case");
341
- equal((await ask(auth, new Jar(), "/sign-in/email", {
347
+ equal((await ask(auth, new Jar(), "/sign-in", {
342
348
  email: "old@example.com",
343
349
  password: "correct horse battery"
344
350
  })).status, 200, "a user from before");
@@ -351,7 +357,7 @@ const authContract = [
351
357
  policy: "waitlist",
352
358
  domains: []
353
359
  } });
354
- equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
360
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up", {
355
361
  email: "wes@example.com",
356
362
  password: "correct horse battery",
357
363
  name: "Wes"
@@ -375,7 +381,7 @@ const authContract = [
375
381
  decidedBy: "Owner"
376
382
  }
377
383
  });
378
- equal((await ask(auth, new Jar(), "/sign-up/email", {
384
+ equal((await ask(auth, new Jar(), "/sign-up", {
379
385
  email: "wes@example.com",
380
386
  password: "correct horse battery",
381
387
  name: "Wes"
@@ -383,11 +389,29 @@ const authContract = [
383
389
  }
384
390
  },
385
391
  {
386
- name: "signing up with an email and a password signs the person in",
387
- async run({ auth }) {
392
+ name: "signing up with an email and a password signs the person in, and says so",
393
+ async run({ auth, outbox }) {
388
394
  const jar = new Jar();
389
- await signUp(auth, jar, "ada@example.com");
395
+ const answer = await ask(auth, jar, "/sign-up", {
396
+ email: "ada@example.com",
397
+ password: "correct horse battery",
398
+ name: "Ada"
399
+ });
400
+ const body = await answer.json();
401
+ equal([
402
+ answer.status,
403
+ body.signedIn,
404
+ body.user?.email,
405
+ body.user?.emailVerified
406
+ ], [
407
+ 200,
408
+ true,
409
+ "ada@example.com",
410
+ false
411
+ ], "what signing up returns");
390
412
  equal(await who(auth, jar), "ada@example.com", "who the cookie signs in");
413
+ equal([outbox().at(-1)?.to, outbox().at(-1)?.kind], ["ada@example.com", "verify"], "the mail sent");
414
+ equal((await (await ask(auth, jar, "/session")).json())?.user.email, "ada@example.com", "GET /session");
391
415
  }
392
416
  },
393
417
  {
@@ -395,24 +419,79 @@ const authContract = [
395
419
  async run({ auth }) {
396
420
  const jar = new Jar();
397
421
  await signUp(auth, jar, "lin@example.com");
398
- equal((await ask(auth, jar, "/sign-out", {})).status, 200, "signing out");
422
+ const out = await ask(auth, jar, "/sign-out", {});
423
+ equal([out.status, await out.json()], [200, { signedOut: true }], "signing out");
399
424
  equal(await who(auth, jar), null, "who is signed in after signing out");
400
- equal((await ask(auth, jar, "/sign-in/email", {
425
+ equal(await (await ask(auth, jar, "/session")).json(), null, "GET /session after signing out");
426
+ const back = await ask(auth, jar, "/sign-in", {
401
427
  email: "lin@example.com",
402
428
  password: "correct horse battery"
403
- })).status, 200, "signing in");
429
+ });
430
+ equal([back.status, (await back.json()).signedIn], [200, true], "signing in");
404
431
  equal(await who(auth, jar), "lin@example.com", "who is signed in again");
405
432
  }
406
433
  },
434
+ {
435
+ name: "with confirmEmail on, signing up and signing in sign no one in until the link mailed is opened, which signs the person in",
436
+ async run({ auth, store, outbox, later }) {
437
+ const before = new Jar();
438
+ await signUp(auth, before, "old@example.com");
439
+ await settle(store, { confirmEmail: true });
440
+ later(SETTINGS_TTL_MS);
441
+ const jar = new Jar();
442
+ const made = await ask(auth, jar, "/sign-up", {
443
+ email: "ada@example.com",
444
+ password: "correct horse battery",
445
+ name: "Ada"
446
+ });
447
+ equal([made.status, await made.json()], [200, { verifyEmail: true }], "signing up");
448
+ equal(await who(auth, jar), null, "who is signed in after signing up");
449
+ equal(await who(auth, before), null, "someone unconfirmed signed in from before");
450
+ equal(await (await ask(auth, before, "/session")).json(), null, "GET /session for them");
451
+ equal(await (await ask(auth, new Jar(), "/sign-up", {
452
+ email: "ada@example.com",
453
+ password: "another horse battery",
454
+ name: "Ada"
455
+ })).json(), { verifyEmail: true }, "signing up with an email taken");
456
+ const asked = outbox().length;
457
+ const signIn = await ask(auth, jar, "/sign-in", {
458
+ email: "ada@example.com",
459
+ password: "correct horse battery"
460
+ });
461
+ equal([
462
+ signIn.status,
463
+ await signIn.json(),
464
+ outbox().length,
465
+ outbox().at(-1)?.kind
466
+ ], [
467
+ 200,
468
+ { verifyEmail: true },
469
+ asked + 1,
470
+ "verify"
471
+ ], "signing in unconfirmed");
472
+ equal((await ask(auth, new Jar(), "/sign-in", {
473
+ email: "ada@example.com",
474
+ password: "wrong horse battery"
475
+ })).status, 401, "a wrong password");
476
+ const link = new URL(outbox().at(-1).url);
477
+ const opened = await auth.handler(new Request(link, { headers: { origin: CONTRACT_ORIGIN } }));
478
+ jar.take(opened);
479
+ equal(await who(auth, jar), "ada@example.com", "who the link signs in");
480
+ equal((await (await ask(auth, new Jar(), "/sign-in", {
481
+ email: "ada@example.com",
482
+ password: "correct horse battery"
483
+ })).json()).signedIn, true, "signing in once confirmed");
484
+ }
485
+ },
407
486
  {
408
487
  name: "a wrong password and an unknown email are refused alike",
409
488
  async run({ auth }) {
410
489
  await signUp(auth, new Jar(), "grace@example.com");
411
- equal((await ask(auth, new Jar(), "/sign-in/email", {
490
+ equal((await ask(auth, new Jar(), "/sign-in", {
412
491
  email: "grace@example.com",
413
492
  password: "wrong horse battery"
414
493
  })).status, 401, "a wrong password");
415
- equal((await ask(auth, new Jar(), "/sign-in/email", {
494
+ equal((await ask(auth, new Jar(), "/sign-in", {
416
495
  email: "nobody@example.com",
417
496
  password: "correct horse battery"
418
497
  })).status, 401, "an unknown email");
@@ -421,7 +500,7 @@ const authContract = [
421
500
  {
422
501
  name: "a store starts with no users: nobody signs in until someone signs up",
423
502
  async run({ auth }) {
424
- equal((await ask(auth, new Jar(), "/sign-in/email", {
503
+ equal((await ask(auth, new Jar(), "/sign-in", {
425
504
  email: "ada@example.com",
426
505
  password: "correct horse battery"
427
506
  })).status, 401, "signing in to a new store");
@@ -505,7 +584,7 @@ const authContract = [
505
584
  value: id
506
585
  }]
507
586
  });
508
- equal((await ask(auth, new Jar(), "/sign-in/email", {
587
+ equal((await ask(auth, new Jar(), "/sign-in", {
509
588
  email: "zed@example.com",
510
589
  password: "correct horse battery"
511
590
  })).status, 403, "signing in banned");
@@ -697,13 +776,13 @@ const authContract = [
697
776
  const toSignIn = await auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/oauth2/authorize?${asked}`));
698
777
  const signInAt = new URL(toSignIn.headers.get("location") ?? "", CONTRACT_ORIGIN);
699
778
  equal([toSignIn.status, signInAt.pathname], [302, "/api/auth/ui/sign-in"], "authorizing signed out");
700
- const signedUp = await ask(auth, jar, "/sign-up/email", {
779
+ const signedUp = await ask(auth, jar, "/sign-up", {
701
780
  email: "mia@example.com",
702
781
  password: "correct horse battery",
703
782
  name: "Mia",
704
783
  oauth_query: signInAt.search.slice(1)
705
784
  });
706
- const consentAt = new URL((await signedUp.json()).url, CONTRACT_ORIGIN);
785
+ const consentAt = new URL((await signedUp.json()).next, CONTRACT_ORIGIN);
707
786
  equal(consentAt.pathname, "/api/auth/agent-consent", "where signing in leads");
708
787
  const page = await auth.handler(new Request(consentAt, { headers: { cookie: jar.header } }));
709
788
  const html = await page.text();
package/auth/files.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as authTables, c as tablesFromEngine, i as authFiles, n as EngineField, o as schemaLines, r as FUNCTIONS_FILE, s as tablesFile, t as AuthTable } from "../files-C-FvBxT4.mjs";
1
+ import { a as authTables, c as tablesFromEngine, i as authFiles, n as EngineField, o as schemaLines, r as FUNCTIONS_FILE, s as tablesFile, t as AuthTable } from "../files-B553U-d6.mjs";
2
2
  export { AuthTable, EngineField, FUNCTIONS_FILE, authFiles, authTables, schemaLines, tablesFile, tablesFromEngine };
package/auth/files.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as tablesFile, i as schemaLines, n as authFiles, o as tablesFromEngine, r as authTables, t as FUNCTIONS_FILE } from "../files-DAFOuID_.mjs";
1
+ import { a as tablesFile, i as schemaLines, n as authFiles, o as tablesFromEngine, r as authTables, t as FUNCTIONS_FILE } from "../files-DhPeWwcT.mjs";
2
2
  export { FUNCTIONS_FILE, authFiles, authTables, schemaLines, tablesFile, tablesFromEngine };
package/auth/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-DsWS_MpS.mjs";
2
- import { i as SignUpPolicy, n as CaptchaProvider, r as PublicSettings, t as AuthSettings } from "../settings-si8iBtwc.mjs";
1
+ import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-CLGBhEpO.mjs";
2
+ import { i as SignUpPolicy, n as CaptchaProvider, r as PublicSettings, t as AuthSettings } from "../settings-Dz3irtlu.mjs";
3
3
  import { SignInMail, SignInMailKind, checkSignInMail, signInWords } from "./mail.mjs";
4
- import { _ as AuthEventBatch, a as AuthError, c as AuthUser, d as SESSION_CACHE_S, f as SignedIn, g as AuthEvent, h as createAuth, i as Auth, l as AuthUserRecord, m as auth, n as AgentGrant, o as AuthErrorCode, p as SignedInAgent, r as AgentKey, s as AuthOptions, t as AUTH_PATH, u as IMPERSONATION_S, v as AuthEventType, y as EventSend } from "../index-Cc5gCPfV.mjs";
5
- import { i as authFiles } from "../files-C-FvBxT4.mjs";
6
- export { AUTH_PATH, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, AuthErrorCode, type AuthEvent, type AuthEventBatch, type AuthEventType, AuthOptions, type AuthSettings, type AuthStore, AuthUser, AuthUserRecord, type CaptchaProvider, type EventSend, IMPERSONATION_S, type PublicSettings, SESSION_CACHE_S, type SignInMail, type SignInMailKind, type SignUpPolicy, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
4
+ import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthOptions, d as IMPERSONATION_S, f as SESSION_CACHE_S, g as createAuth, h as auth, i as AgentKey, l as AuthUser, m as SignedInAgent, n as AUTH_ROUTES, o as AuthError, p as SignedIn, r as AgentGrant, s as AuthErrorCode, t as AUTH_PATH, u as AuthUserRecord, v as AuthEventBatch, y as AuthEventType } from "../index-DYSS7OGg.mjs";
5
+ import { i as authFiles } from "../files-B553U-d6.mjs";
6
+ export { AUTH_PATH, AUTH_ROUTES, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, AuthErrorCode, type AuthEvent, type AuthEventBatch, type AuthEventType, AuthOptions, type AuthSettings, type AuthStore, AuthUser, AuthUserRecord, type CaptchaProvider, type EventSend, IMPERSONATION_S, type PublicSettings, SESSION_CACHE_S, type SignInMail, type SignInMailKind, type SignUpPolicy, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as auth, i as SESSION_CACHE_S, n as AuthError, o as createAuth, r as IMPERSONATION_S, t as AUTH_PATH, u as databaseStore } from "../auth-BxXrC_JJ.mjs";
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-C9V1Xb0w.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
- import { n as authFiles } from "../files-DAFOuID_.mjs";
4
- export { AUTH_PATH, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
3
+ import { n as authFiles } from "../files-DhPeWwcT.mjs";
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-DsgRC8SR.mjs";
1
+ import { i as hashPassword$1, o as verifyPassword$1 } from "../engine-DDPJ2CET.mjs";
2
2
  import { isBcrypt as isBcrypt$1 } from "./import.mjs";
3
3
  //#region src/auth/password.ts
4
4
  /**
package/auth/react.d.mts CHANGED
@@ -31,7 +31,7 @@ declare function SignIn(props: {
31
31
  readonly wide?: boolean;
32
32
  readonly children?: ReactNode;
33
33
  }> | null;
34
- /** Sign-up with a name, an email and a password; under a waitlist, joining it. */
34
+ /** Sign-up with a name, an email and a password; under a waitlist, joining it; when the app wants emails confirmed, asking for that. */
35
35
  declare function SignUp(props: {
36
36
  readonly redirectTo?: string;
37
37
  readonly signInUrl?: string;
package/auth/react.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as WORDS, c as setupKeyOf, i as CAPTCHA_WIDGETS, o as ago, r as AUTH_CSS, s as deviceOf, t as qrPath } from "../qr-C1mfuCT9.mjs";
1
+ import { a as WORDS, c as setupKeyOf, i as CAPTCHA_WIDGETS, o as ago, r as AUTH_CSS, s as deviceOf, t as qrPath } from "../qr-BR3Ld80n.mjs";
2
2
  import { AuthClientError, authClient } from "./client.mjs";
3
3
  import { Fragment, createContext, createElement, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
4
4
  //#region src/auth/react.ts
@@ -276,6 +276,11 @@ function SignIn(props) {
276
276
  onClick: () => void call.run(() => client.signIn.code.send(email, withCaptcha))
277
277
  }, WORDS.code.again)));
278
278
  if (mode === "link") return createElement(Card, { title: WORDS.signIn.title(app) }, createElement(Note, null, WORDS.link.sent(email)));
279
+ if (mode === "confirm") return createElement(Card, { title: WORDS.signIn.title(app) }, createElement(Note, null, WORDS.confirm.sent(email)), createElement("p", { className: "msa-foot" }, createElement("button", {
280
+ type: "button",
281
+ className: "msa-quiet",
282
+ onClick: () => setMode("start")
283
+ }, WORDS.confirm.back)));
279
284
  const social = ["google", "github"].filter((one) => methods[one]);
280
285
  const byMail = methods.code ? "code" : methods.link ? "link" : null;
281
286
  return createElement(Card, { title: WORDS.signIn.title(app) }, social.length || methods.passkey ? createElement("div", { className: "msa-stack" }, ...social.map((provider) => createElement("button", {
@@ -302,14 +307,19 @@ function SignIn(props) {
302
307
  setMode("code");
303
308
  return;
304
309
  }
305
- if ("twoFactor" in await client.signIn.password({
310
+ const signed = await client.signIn.password({
306
311
  email,
307
312
  password,
308
313
  ...withCaptcha
309
- })) {
314
+ });
315
+ if ("twoFactor" in signed) {
310
316
  setMode("two-factor");
311
317
  return;
312
318
  }
319
+ if ("verifyEmail" in signed) {
320
+ setMode("confirm");
321
+ return;
322
+ }
313
323
  done();
314
324
  })) }, createElement(Field, {
315
325
  label: WORDS.fields.email,
@@ -348,7 +358,7 @@ function SignIn(props) {
348
358
  })
349
359
  }, WORDS.ways.link) : null) : null, createElement("p", { className: "msa-foot" }, methods.password ? createElement(Fragment, null, createElement("a", { href: props.resetUrl ?? "/api/auth/ui/reset-password" }, WORDS.signIn.forgot), " · ") : null, settings.signUp.policy === "invite" ? null : createElement(Fragment, null, `${WORDS.signIn.noAccount} `, createElement("a", { href: props.signUpUrl ?? "/api/auth/ui/sign-up" }, WORDS.signIn.signUp))));
350
360
  }
351
- /** Sign-up with a name, an email and a password; under a waitlist, joining it. */
361
+ /** Sign-up with a name, an email and a password; under a waitlist, joining it; when the app wants emails confirmed, asking for that. */
352
362
  function SignUp(props) {
353
363
  const { client, settings } = useAuth();
354
364
  const [name, setName] = useState(""), [email, setEmail] = useState(""), [password, setPassword] = useState(""), [captcha, setCaptcha] = useState("");
@@ -356,18 +366,21 @@ function SignUp(props) {
356
366
  const call = useCall();
357
367
  if (!settings) return null;
358
368
  const policy = settings.signUp.policy;
359
- if (waiting) return createElement(Card, { title: WORDS.signUp.title(settings.branding.name) }, createElement(Note, null, waiting));
369
+ if (waiting) return createElement(Card, { title: WORDS.signUp.title(settings.branding.name) }, createElement(Note, null, waiting), createElement("p", { className: "msa-foot" }, createElement("a", { href: props.signInUrl ?? "/api/auth/ui/sign-in" }, WORDS.confirm.back)));
360
370
  return createElement(Card, {
361
371
  title: WORDS.signUp.title(settings.branding.name),
362
372
  ...policy === "invite" ? { lead: WORDS.signUp.invite } : {}
363
373
  }, createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
364
374
  try {
365
- await client.signUp({
375
+ if ("verifyEmail" in await client.signUp({
366
376
  name,
367
377
  email,
368
378
  password,
369
379
  ...captcha ? { captcha } : {}
370
- });
380
+ })) {
381
+ setWaiting(WORDS.confirm.sent(email));
382
+ return;
383
+ }
371
384
  go(props.redirectTo ?? "/");
372
385
  } catch (error) {
373
386
  if (error instanceof AuthClientError && error.code === "SIGN_UP_WAITLIST") {
@@ -1,4 +1,4 @@
1
- import { n as AuthStore } from "../store-DsWS_MpS.mjs";
1
+ import { n as AuthStore } from "../store-CLGBhEpO.mjs";
2
2
  import { SignInMail } from "./mail.mjs";
3
3
  //#region src/auth/stand-in.d.ts
4
4
  interface StandIn {
package/auth/stand-in.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { r as authTables } from "../files-DAFOuID_.mjs";
1
+ import { r as authTables } from "../files-DhPeWwcT.mjs";
2
2
  //#region src/auth/stand-in.ts
3
3
  const text = (value) => typeof value === "string" ? value.toLowerCase() : value;
4
4
  /** Whether one clause holds for a row, as `db/auth.ts` decides it. */
@@ -128,6 +128,23 @@ function standIn() {
128
128
  for (const row of rows) Object.assign(row, fieldsOf(model, update));
129
129
  return rows.length;
130
130
  },
131
+ upsert({ model, where, update, create }) {
132
+ const row = found(model, where)[0];
133
+ if (row) {
134
+ unique(model, {
135
+ ...row,
136
+ ...fieldsOf(model, update)
137
+ });
138
+ Object.assign(row, fieldsOf(model, update));
139
+ } else run.create({
140
+ model,
141
+ data: {
142
+ ...create ?? {},
143
+ ...update ?? {}
144
+ }
145
+ });
146
+ return null;
147
+ },
131
148
  deleteMany({ model, where }) {
132
149
  const rows = found(model, where);
133
150
  for (const row of rows) table(model).delete(row.id);
@@ -1,10 +1,10 @@
1
1
  import { r as processEnv, t as here } from "./here-1plIxb0D.mjs";
2
2
  import { connect } from "./database/client.mjs";
3
3
  import { sendSignInMail } from "./auth/mail.mjs";
4
- import "./files-DAFOuID_.mjs";
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-DsgRC8SR.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";
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-DDPJ2CET.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-BR3Ld80n.mjs";
8
8
  //#region src/auth/store.ts
9
9
  const KIND = {
10
10
  create: "mutation",
@@ -13,6 +13,7 @@ const KIND = {
13
13
  count: "query",
14
14
  update: "mutation",
15
15
  updateMany: "mutation",
16
+ upsert: "mutation",
16
17
  deleteMany: "mutation",
17
18
  consume: "mutation",
18
19
  increment: "mutation",
@@ -56,8 +57,10 @@ const DEFAULT_SETTINGS = {
56
57
  },
57
58
  signUp: {
58
59
  policy: "open",
59
- domains: []
60
+ domains: [],
61
+ emails: []
60
62
  },
63
+ confirmEmail: false,
61
64
  branding: {
62
65
  name: null,
63
66
  logo: null,
@@ -72,6 +75,7 @@ const line = (value, most) => typeof value === "string" && value.trim() && value
72
75
  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
76
  const COLOR = /^#[0-9a-f]{6}$/i;
74
77
  const ADDRESS = /^[^\s@<>()",;:]+@[a-z0-9.-]+\.[a-z]{2,}$/i;
78
+ const lowered = (value) => Array.isArray(value) ? value.filter((one) => typeof one === "string").map((one) => one.trim().toLowerCase()) : [];
75
79
  /** The settings a row holds, each field checked on its own: one of the wrong shape is its default. */
76
80
  function settingsOf(row) {
77
81
  const given = object(row);
@@ -101,8 +105,10 @@ function settingsOf(row) {
101
105
  },
102
106
  signUp: {
103
107
  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) : []
108
+ domains: lowered(signUp.domains).filter((one) => DOMAIN.test(one)).slice(0, 50),
109
+ emails: lowered(signUp.emails).filter((one) => ADDRESS.test(one)).slice(0, 200)
105
110
  },
111
+ confirmEmail: flag(given.confirmEmail, DEFAULT_SETTINGS.confirmEmail),
106
112
  branding: {
107
113
  name: line(branding.name, 80),
108
114
  logo: logo && URL.parse(logo)?.protocol === "https:" ? logo : null,
@@ -121,6 +127,7 @@ function publicSettings(settings, appName) {
121
127
  return {
122
128
  methods: settings.methods,
123
129
  signUp: { policy: settings.signUp.policy },
130
+ confirmEmail: settings.confirmEmail,
124
131
  branding: {
125
132
  ...settings.branding,
126
133
  name: settings.branding.name ?? appName
@@ -164,11 +171,13 @@ function mayJoin(settings, email, seen) {
164
171
  const domain = email.slice(email.lastIndexOf("@") + 1).toLowerCase();
165
172
  switch (settings.signUp.policy) {
166
173
  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
- };
174
+ case "domains":
175
+ if (settings.signUp.domains.includes(domain) || settings.signUp.emails.includes(email.toLowerCase()) || seen.invited) return { allowed: true };
176
+ return {
177
+ allowed: false,
178
+ code: "SIGN_UP_DOMAIN",
179
+ 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.`
180
+ };
172
181
  case "invite": return seen.invited ? { allowed: true } : {
173
182
  allowed: false,
174
183
  code: "SIGN_UP_INVITE_ONLY",
@@ -667,7 +676,7 @@ async function hostedPage(request, path, deps) {
667
676
  oauth_query: oauthQuery
668
677
  } : body;
669
678
  /** 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;
679
+ const onward = (answer) => typeof answer?.next === "string" ? answer.next : answer?.redirect === true && typeof answer.url === "string" ? answer.url : redirect;
671
680
  const captchaToken = () => settings.captcha ? form[CAPTCHA_WIDGETS[settings.captcha.provider].field] : void 0;
672
681
  switch (path.replace(/\/+$/, "")) {
673
682
  case "/sign-in": {
@@ -675,13 +684,14 @@ async function hostedPage(request, path, deps) {
675
684
  if (request.method === "POST") {
676
685
  const email = (form.email ?? "").trim();
677
686
  if (form.action === "password") {
678
- const signed = await call("/sign-in/email", withOauth({
687
+ const signed = await call("/sign-in", withOauth({
679
688
  email,
680
689
  password: form.password ?? ""
681
690
  }), 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;
691
+ if (signed.ok && signed.json?.twoFactor) return away(`${UI}/two-factor${url.search}`);
692
+ if (signed.ok && signed.json?.verifyEmail) notice = WORDS.confirm.sent(email);
693
+ else if (signed.ok) return away(onward(signed.json));
694
+ else problem = signed.message;
685
695
  } else if (form.action === "code") {
686
696
  const sent = await call("/email-otp/send-verification-otp", {
687
697
  email,
@@ -712,7 +722,7 @@ async function hostedPage(request, path, deps) {
712
722
  problem = started.message;
713
723
  }
714
724
  }
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);
725
+ return respond(shell(WORDS.signIn.title(app), notice ? `<p class="msa-note" role="status">${escape(notice)}</p>${backTo(url.search)}` : signInForm(settings, problem, url.search), { script: settings.methods.passkey ? passkeyScript("sign-in", redirect) : "" }), problem ? 400 : 200);
716
726
  }
717
727
  case "/two-factor": {
718
728
  let problem = "";
@@ -733,16 +743,18 @@ async function hostedPage(request, path, deps) {
733
743
  case "/sign-up": {
734
744
  let problem = "", notice = "";
735
745
  if (request.method === "POST") {
736
- const made = await call("/sign-up/email", withOauth({
746
+ const email = (form.email ?? "").trim();
747
+ const made = await call("/sign-up", withOauth({
737
748
  name: (form.name ?? "").trim(),
738
- email: (form.email ?? "").trim(),
749
+ email,
739
750
  password: form.password ?? ""
740
751
  }), captchaToken());
741
- if (made.ok) return away(onward(made.json));
742
- if (made.json?.code === "SIGN_UP_WAITLIST") notice = made.message;
752
+ if (made.ok && made.json?.verifyEmail) notice = WORDS.confirm.sent(email);
753
+ else if (made.ok) return away(onward(made.json));
754
+ else if (made.json?.code === "SIGN_UP_WAITLIST") notice = made.message;
743
755
  else problem = made.message;
744
756
  }
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);
757
+ return respond(shell(WORDS.signUp.title(app), notice ? `<p class="msa-note" role="status">${escape(notice)}</p>${backTo(url.search)}` : signUpForm(settings, problem, url.search), settings.signUp.policy === "invite" ? { lead: WORDS.signUp.invite } : {}), problem ? 400 : 200);
746
758
  }
747
759
  case "/reset-password": {
748
760
  const token = url.searchParams.get("token");
@@ -769,7 +781,7 @@ async function hostedPage(request, path, deps) {
769
781
  return respond(shell(WORDS.reset.title, resetForm(settings, ""), { lead: WORDS.reset.lead }));
770
782
  }
771
783
  case "/account": {
772
- const signedIn = (await call("/get-session")).json;
784
+ const signedIn = (await call("/session")).json;
773
785
  if (!signedIn) return away(`${UI}/sign-in?redirect=${encodeURIComponent(`${UI}/account`)}`);
774
786
  let problem = "", notice = "", shown = "";
775
787
  if (request.method === "POST") {
@@ -827,7 +839,7 @@ async function hostedPage(request, path, deps) {
827
839
  }
828
840
  }
829
841
  const [session, sessions, passkeys, keys, grants] = await Promise.all([
830
- call("/get-session").then((one) => one.json ?? signedIn),
842
+ call("/session").then((one) => one.json ?? signedIn),
831
843
  call("/account/sessions").then((one) => Array.isArray(one.json) ? one.json : []),
832
844
  settings.methods.passkey ? call("/passkey/list-user-passkeys").then((one) => Array.isArray(one.json) ? one.json : []) : Promise.resolve([]),
833
845
  Object.keys(deps.scopes).length ? call("/account/keys").then((one) => Array.isArray(one.json) ? one.json : []) : Promise.resolve([]),
@@ -854,7 +866,7 @@ async function hostedPage(request, path, deps) {
854
866
  }), problem ? 400 : 200);
855
867
  }
856
868
  case "/organization": {
857
- const signedIn = (await call("/get-session")).json;
869
+ const signedIn = (await call("/session")).json;
858
870
  if (!signedIn) return away(`${UI}/sign-in?redirect=${encodeURIComponent(`${UI}/organization`)}`);
859
871
  let problem = "";
860
872
  let id = url.searchParams.get("id") ?? (typeof signedIn.session.activeOrganizationId === "string" ? signedIn.session.activeOrganizationId : "");
@@ -919,7 +931,7 @@ async function hostedPage(request, path, deps) {
919
931
  default: {
920
932
  const invitation = /^\/invitation\/([A-Za-z0-9_-]{1,100})$/.exec(path)?.[1];
921
933
  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>`));
934
+ if (!(await call("/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
935
  if (request.method === "POST") {
924
936
  const answered = await call(form.action === "reject" ? "/organization/reject-invitation" : "/organization/accept-invitation", { invitationId: invitation });
925
937
  if (answered.ok) return away(form.action === "reject" ? "/" : `${UI}/organization`);
@@ -993,6 +1005,8 @@ function signInForm(settings, problem, search) {
993
1005
  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
1006
  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
1007
  }
1008
+ /** The way back to the sign-in form from a note that a mail is on its way. */
1009
+ const backTo = (search) => `<p class="msa-foot"><a href="${UI}/sign-in${escape(search)}">${escape(WORDS.confirm.back)}</a></p>`;
996
1010
  function signUpForm(settings, problem, search) {
997
1011
  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
1012
  }
@@ -1100,6 +1114,12 @@ ${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options"
1100
1114
  * const signedIn = await auth.session(c.req.raw) // { user, session } or null
1101
1115
  * if (!signedIn) return c.redirect("/api/auth/ui/sign-in")
1102
1116
  *
1117
+ * Its own routes, for a script or `curl` (`AUTH_ROUTES`): `POST /api/auth/sign-up` and `POST /api/auth/sign-in` return
1118
+ * `{ signedIn: true, user }` with the session's cookie, `{ verifyEmail: true }` when the email must be confirmed first,
1119
+ * or (signing in) `{ twoFactor: true }`; `POST /api/auth/sign-out` returns `{ signedOut: true }`; `GET /api/auth/session`
1120
+ * returns `{ user, session }` or `null`. The session's cookie is `midsummer.session_token` (`__Secure-midsummer.…` over
1121
+ * https). Signing up signs the person in at once unless the settings' `confirmEmail` is on (`./settings.ts`).
1122
+ *
1103
1123
  * Email and password, codes and sign-in links by mail, Google and GitHub when their keys are set, organizations with
1104
1124
  * roles and invitations, two-factor codes, passkeys and bans. Browsers talk to it with `@midsummer-ai/sdk/auth/client`,
1105
1125
  * the drop-in screens in `@midsummer-ai/sdk/auth/react`, or the hosted pages under `/api/auth/ui`.
@@ -1116,7 +1136,7 @@ ${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options"
1116
1136
  * `createAuth({ key })`. Make one with `midsummer db key create`.
1117
1137
  * - Under `midsummer dev`, the database's Stand-in when `db/` runs, or memory.
1118
1138
  * 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`,
1139
+ * environment; `midsummer dev` passes one of its own; elsewhere any random 32 characters or more), and reads `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`,
1120
1140
  * `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`, and on previews `AUTH_PRODUCTION_URL` and `AUTH_PROXY_SECRET`, which
1121
1141
  * `midsummer auth provider set` writes. `AUTH_EMAIL_FROM` sends its mail from a domain of the Team's.
1122
1142
  *
@@ -1146,8 +1166,32 @@ const AUTH_PATH = "/api/auth";
1146
1166
  const SESSION_CACHE_S = 300;
1147
1167
  /** How long a session the platform's "sign in as" makes lasts, in seconds. */
1148
1168
  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";
1169
+ /**
1170
+ * Sign-in's own routes under `AUTH_PATH`, the ones the docs promise: each runs the engine's path under it (`engine`)
1171
+ * and returns Midsummer's shape (`routed`). The engine's other paths serve the browser client and aren't promised.
1172
+ */
1173
+ const AUTH_ROUTES = {
1174
+ /** `{ email, password, name }`: `{ signedIn: true, user }`, or `{ verifyEmail: true }` once a link to confirm is mailed. */
1175
+ "/sign-up": {
1176
+ method: "POST",
1177
+ engine: "/sign-up/email"
1178
+ },
1179
+ /** `{ email, password }`: `{ signedIn: true, user }`, `{ twoFactor: true }`, or `{ verifyEmail: true }` once a new link is mailed. */
1180
+ "/sign-in": {
1181
+ method: "POST",
1182
+ engine: "/sign-in/email"
1183
+ },
1184
+ /** `{}`: `{ signedOut: true }`, the cookie cleared. */
1185
+ "/sign-out": {
1186
+ method: "POST",
1187
+ engine: "/sign-out"
1188
+ },
1189
+ /** `{ user, session }`, or `null` when no one is signed in. */
1190
+ "/session": {
1191
+ method: "GET",
1192
+ engine: "/get-session"
1193
+ }
1194
+ };
1151
1195
  /** How many addresses one process keeps sign-in ready for; past it the oldest is made again when asked. */
1152
1196
  const KEPT_ORIGINS = 16;
1153
1197
  const API = "https://api.midsummer.new";
@@ -1438,11 +1482,11 @@ function createAuth(options = {}) {
1438
1482
  const at = async (origin) => {
1439
1483
  const normal = new URL(origin).origin;
1440
1484
  const { store, env, settings } = base();
1441
- const appName = appNameOf(await settings());
1442
- const id = `${normal}\n${appName}`;
1485
+ const now = await settings(), appName = appNameOf(now);
1486
+ const id = `${normal}\n${appName}\n${now.confirmEmail}`;
1443
1487
  let found = kept.get(id);
1444
1488
  if (!found) {
1445
- const secret = options.secret || env.AUTH_SECRET || (env.MIDSUMMER_DEV === "1" ? DEV_SECRET : "");
1489
+ const secret = options.secret || env.AUTH_SECRET;
1446
1490
  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.");
1447
1491
  found = buildEngine({
1448
1492
  origin: normal,
@@ -1455,6 +1499,7 @@ function createAuth(options = {}) {
1455
1499
  changed: changed(normal),
1456
1500
  impersonationS: IMPERSONATION_S,
1457
1501
  cacheS: 300,
1502
+ confirmEmail: now.confirmEmail,
1458
1503
  invitationUrl: options.invitationUrl ?? ((from, invitation) => `${from}/api/auth/ui/invitation/${invitation}`),
1459
1504
  send: async (mail) => sendOne(await settings(), mail)
1460
1505
  });
@@ -1472,10 +1517,45 @@ function createAuth(options = {}) {
1472
1517
  headers: request.headers,
1473
1518
  ...fresh ? { query: { disableCookieCache: true } } : {}
1474
1519
  });
1475
- return found ? {
1520
+ if (!found || !await confirmed(found.user)) return null;
1521
+ return {
1476
1522
  via: "session",
1477
1523
  ...found
1478
- } : null;
1524
+ };
1525
+ }
1526
+ /** Whether a user counts as signed in under the settings now: always, unless `confirmEmail` is on and their email isn't confirmed. */
1527
+ const confirmed = async (user) => user.emailVerified === true || !(await base().settings()).confirmEmail;
1528
+ /**
1529
+ * One of `AUTH_ROUTES`, from the engine's answer to its path: its refusals as they are, in our words, and what it
1530
+ * returns in Midsummer's shape, its cookies kept.
1531
+ */
1532
+ async function routed(route, answered) {
1533
+ const body = await answered.clone().json().catch(() => null);
1534
+ const headers = new Headers(answered.headers);
1535
+ headers.delete("content-length");
1536
+ headers.set("Content-Type", "application/json");
1537
+ headers.set("Cache-Control", "no-store");
1538
+ const shaped = (value) => new Response(JSON.stringify(value), {
1539
+ status: 200,
1540
+ headers
1541
+ });
1542
+ if (route === "/sign-in" && answered.status === 403 && body?.code === "EMAIL_NOT_VERIFIED") return shaped({ verifyEmail: true });
1543
+ if (!answered.ok) return answered;
1544
+ const next = body?.redirect === true && typeof body.url === "string" ? { next: body.url } : {};
1545
+ switch (route) {
1546
+ case "/sign-up": return shaped(typeof body?.token === "string" && body.token || "next" in next ? {
1547
+ signedIn: true,
1548
+ ...body?.user ? { user: body.user } : {},
1549
+ ...next
1550
+ } : { verifyEmail: true });
1551
+ case "/sign-in": return shaped(body?.twoFactorRedirect ? { twoFactor: true } : {
1552
+ signedIn: true,
1553
+ user: body?.user,
1554
+ ...next
1555
+ });
1556
+ case "/sign-out": return shaped({ signedOut: true });
1557
+ case "/session": return shaped(body?.user && await confirmed(body.user) ? body : null);
1558
+ }
1479
1559
  }
1480
1560
  /** The person a request about their own keys or grants comes from; never an agent, which can't give itself more. */
1481
1561
  async function owner(request, what) {
@@ -1736,7 +1816,10 @@ function createAuth(options = {}) {
1736
1816
  settings: offered,
1737
1817
  scopes: settingsOfAgents.scopes
1738
1818
  });
1739
- const refused = await guard(request, path, {
1819
+ const route = Object.hasOwn(AUTH_ROUTES, path) ? path : void 0;
1820
+ if (route && request.method !== AUTH_ROUTES[route].method) return refusal(405, "METHOD_NOT_ALLOWED", `${AUTH_PATH}${route} takes ${AUTH_ROUTES[route].method}.`);
1821
+ const inner = route ? new Request(`${origin}${AUTH_PATH}${AUTH_ROUTES[route].engine}${new URL(request.url).search}`, request) : request;
1822
+ const refused = await guard(inner, route ? AUTH_ROUTES[route].engine : path, {
1740
1823
  settings,
1741
1824
  env,
1742
1825
  ip: here()?.ip ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
@@ -1745,14 +1828,24 @@ function createAuth(options = {}) {
1745
1828
  leaked: options.leakedPassword ?? leakedPassword
1746
1829
  });
1747
1830
  if (refused) return refused;
1748
- const forwarded = here()?.ip ? new Request(request, { headers: (() => {
1749
- const headers = new Headers(request.headers);
1831
+ if (route === "/sign-up" && settings.confirmEmail) {
1832
+ const asked = await inner.clone().json().catch(() => null);
1833
+ if (typeof asked?.email === "string" && asked.email.includes("@")) try {
1834
+ await admit(asked.email.trim().toLowerCase());
1835
+ } catch (error) {
1836
+ if (error instanceof JoinRefused) return refusal(403, error.code, error.message);
1837
+ throw error;
1838
+ }
1839
+ }
1840
+ const forwarded = here()?.ip ? new Request(inner, { headers: (() => {
1841
+ const headers = new Headers(inner.headers);
1750
1842
  headers.set("x-forwarded-for", here().ip);
1751
1843
  return headers;
1752
- })() }) : request;
1844
+ })() }) : inner;
1753
1845
  const engineAnswer = await engine.handler(forwarded);
1754
1846
  if (engineAnswer.status >= 500 && !engineAnswer.headers.get("content-type")) return unavailable();
1755
1847
  const answered = await inOurWords(engineAnswer);
1848
+ if (route) return routed(route, answered);
1756
1849
  return answered.ok && FRESHENS.has(path) ? freshened(engine, origin, forwarded, answered) : answered;
1757
1850
  }
1758
1851
  const recordOf = (row) => ({
@@ -1834,4 +1927,4 @@ function createAuth(options = {}) {
1834
1927
  /** Sign-in for this deployment, set up from its environment. */
1835
1928
  const auth = createAuth();
1836
1929
  //#endregion
1837
- 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 };
1930
+ 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 };
@@ -48275,6 +48275,7 @@ function optionsFor(config, store) {
48275
48275
  } },
48276
48276
  emailAndPassword: {
48277
48277
  enabled: true,
48278
+ requireEmailVerification: config.confirmEmail,
48278
48279
  sendResetPassword: async ({ user, url }) => send({
48279
48280
  to: user.email,
48280
48281
  kind: "reset",
@@ -48294,6 +48295,7 @@ function optionsFor(config, store) {
48294
48295
  },
48295
48296
  emailVerification: {
48296
48297
  sendOnSignUp: true,
48298
+ sendOnSignIn: config.confirmEmail,
48297
48299
  autoSignInAfterVerification: true,
48298
48300
  sendVerificationEmail: async ({ user, url }) => send({
48299
48301
  to: user.email,
@@ -54,7 +54,8 @@ declare function tablesFile(tables: Readonly<Record<string, AuthTable>>): string
54
54
  declare function schemaLines(tables: Readonly<Record<string, AuthTable>>): string;
55
55
  /**
56
56
  * `db/auth.ts`: what `@midsummer-ai/sdk/auth` and the platform call, `auth.create`, `auth.findOne`, `auth.findMany`,
57
- * `auth.count`, `auth.update`, `auth.updateMany`, `auth.deleteMany`, `auth.increment`, `auth.consume` and `auth.page`.
57
+ * `auth.count`, `auth.update`, `auth.updateMany`, `auth.upsert`, `auth.deleteMany`, `auth.increment`, `auth.consume`
58
+ * and `auth.page`.
58
59
  * A `where` is a list of clauses `{ field, operator, value, connector, mode }`, `id` meaning the row's `_id`. All
59
60
  * joined by AND with an `eq` (or a range) on a field looked up by reads only that index's rows; anything else
60
61
  * reads the table. `auth.page` reads one page of a list, newest first, through the table's order or one index.
@@ -336,6 +336,8 @@ const OWN = {
336
336
  key: "v.string()",
337
337
  methods: "v.optional(v.any())",
338
338
  signUp: "v.optional(v.any())",
339
+ confirmEmail: "v.optional(v.boolean())",
340
+ declared: "v.optional(v.array(v.string()))",
339
341
  branding: "v.optional(v.any())",
340
342
  sender: "v.optional(v.any())",
341
343
  captcha: "v.optional(v.any())",
@@ -428,7 +430,8 @@ function schemaLines(tables) {
428
430
  }
429
431
  /**
430
432
  * `db/auth.ts`: what `@midsummer-ai/sdk/auth` and the platform call, `auth.create`, `auth.findOne`, `auth.findMany`,
431
- * `auth.count`, `auth.update`, `auth.updateMany`, `auth.deleteMany`, `auth.increment`, `auth.consume` and `auth.page`.
433
+ * `auth.count`, `auth.update`, `auth.updateMany`, `auth.upsert`, `auth.deleteMany`, `auth.increment`, `auth.consume`
434
+ * and `auth.page`.
432
435
  * A `where` is a list of clauses `{ field, operator, value, connector, mode }`, `id` meaning the row's `_id`. All
433
436
  * joined by AND with an `eq` (or a range) on a field looked up by reads only that index's rows; anything else
434
437
  * reads the table. `auth.page` reads one page of a list, newest first, through the table's order or one index.
@@ -624,6 +627,17 @@ export const updateMany = mutation({
624
627
  return list.length
625
628
  },
626
629
  })
630
+ /** Changes the first row a where holds, or adds one of create's fields and update's when it holds none, in one step: how a deploy writes the settings midsummer.json declares. */
631
+ export const upsert = mutation({
632
+ args: { model: v.string(), where, update: v.any(), create: v.any() },
633
+ handler: async (ctx, args) => {
634
+ const db = rows(ctx), model = table(args.model)
635
+ const row = (await found(db, model, args.where as Clause[] | undefined))[0]
636
+ if (row) await db.patch(model, row.id, fieldsOf(model, args.update))
637
+ else await db.insert(model, fieldsOf(model, { ...(args.create ?? {}), ...(args.update ?? {}) }))
638
+ return null
639
+ },
640
+ })
627
641
  export const deleteMany = mutation({
628
642
  args: { model: v.string(), where },
629
643
  handler: async (ctx, args) => {
@@ -1,5 +1,5 @@
1
- import { n as AuthStore } from "./store-DsWS_MpS.mjs";
2
- import { n as CaptchaProvider, t as AuthSettings } from "./settings-si8iBtwc.mjs";
1
+ import { n as AuthStore } from "./store-CLGBhEpO.mjs";
2
+ import { n as CaptchaProvider, t as AuthSettings } from "./settings-Dz3irtlu.mjs";
3
3
  import { SignInMail } from "./auth/mail.mjs";
4
4
  //#region src/auth/events.d.ts
5
5
  type AuthEventType = "user.created" | "user.updated" | "user.signed_in" | "user.banned" | "user.deleted" | "user.impersonated" | "session.revoked" | "organization.created" | "organization.member.added" | "organization.member.removed" | "key.created" | "key.revoked" | "grant.created" | "grant.revoked";
@@ -78,6 +78,32 @@ declare const AUTH_PATH = "/api/auth";
78
78
  declare const SESSION_CACHE_S: number;
79
79
  /** How long a session the platform's "sign in as" makes lasts, in seconds. */
80
80
  declare const IMPERSONATION_S: number;
81
+ /**
82
+ * Sign-in's own routes under `AUTH_PATH`, the ones the docs promise: each runs the engine's path under it (`engine`)
83
+ * and returns Midsummer's shape (`routed`). The engine's other paths serve the browser client and aren't promised.
84
+ */
85
+ declare const AUTH_ROUTES: {
86
+ /** `{ email, password, name }`: `{ signedIn: true, user }`, or `{ verifyEmail: true }` once a link to confirm is mailed. */
87
+ readonly "/sign-up": {
88
+ readonly method: "POST";
89
+ readonly engine: "/sign-up/email";
90
+ };
91
+ /** `{ email, password }`: `{ signedIn: true, user }`, `{ twoFactor: true }`, or `{ verifyEmail: true }` once a new link is mailed. */
92
+ readonly "/sign-in": {
93
+ readonly method: "POST";
94
+ readonly engine: "/sign-in/email";
95
+ };
96
+ /** `{}`: `{ signedOut: true }`, the cookie cleared. */
97
+ readonly "/sign-out": {
98
+ readonly method: "POST";
99
+ readonly engine: "/sign-out";
100
+ };
101
+ /** `{ user, session }`, or `null` when no one is signed in. */
102
+ readonly "/session": {
103
+ readonly method: "GET";
104
+ readonly engine: "/get-session";
105
+ };
106
+ };
81
107
  interface AuthOptions {
82
108
  /** The app's name, as its mail, pages and passkeys show it, unless its settings name it. `APP_NAME`, or "your app", when left out. */
83
109
  readonly appName?: string;
@@ -185,7 +211,8 @@ interface Auth {
185
211
  handler(request: Request): Promise<Response>;
186
212
  /**
187
213
  * Who a request is signed in as, or null; read from its cookie while that is fresh, else from its session's row.
188
- * `fresh` reads the row always, for a route that must see a revoke or a ban at once.
214
+ * `fresh` reads the row always, for a route that must see a revoke or a ban at once. With the settings'
215
+ * `confirmEmail` on, a person whose email isn't confirmed is null, whenever their session was made.
189
216
  * With `scope`, the route also takes agents: a request with an API key or an MCP client's token is whoever
190
217
  * it acts for, when it carries that scope, and throws `AuthError` `forbidden` naming the scope when it doesn't.
191
218
  * A person signed in themselves may do everything. Without `scope`, a key or a token signs no one in.
@@ -243,4 +270,4 @@ declare function createAuth(options?: AuthOptions): Auth;
243
270
  /** Sign-in for this deployment, set up from its environment. */
244
271
  declare const auth: Auth;
245
272
  //#endregion
246
- export { AuthEventBatch as _, AuthError as a, AuthUser as c, SESSION_CACHE_S as d, SignedIn as f, AuthEvent as g, createAuth as h, Auth as i, AuthUserRecord as l, auth as m, AgentGrant as n, AuthErrorCode as o, SignedInAgent as p, AgentKey as r, AuthOptions as s, AUTH_PATH as t, IMPERSONATION_S as u, AuthEventType as v, EventSend as y };
273
+ export { AuthEvent as _, Auth as a, EventSend as b, AuthOptions as c, IMPERSONATION_S as d, SESSION_CACHE_S as f, createAuth as g, auth as h, AgentKey as i, AuthUser as l, SignedInAgent as m, AUTH_ROUTES as n, AuthError as o, SignedIn as p, AgentGrant as r, AuthErrorCode as s, AUTH_PATH as t, AuthUserRecord as u, AuthEventBatch as v, AuthEventType as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.3716",
3
+ "version": "0.1.0-staging.3722",
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.",
@@ -104,6 +104,10 @@ const WORDS = {
104
104
  again: "Send a new code"
105
105
  },
106
106
  link: { sent: (email) => `We sent a sign-in link to ${email}. Open it on this device to sign in.` },
107
+ confirm: {
108
+ sent: (email) => `We sent a link to ${email}. Open it to confirm your email and sign in.`,
109
+ back: "Back to sign in"
110
+ },
107
111
  twoFactor: {
108
112
  title: "Confirm it's you",
109
113
  lead: "Enter the code from your authenticator app.",
@@ -10,10 +10,18 @@ interface AuthSettings {
10
10
  readonly google: boolean;
11
11
  readonly github: boolean;
12
12
  };
13
+ /** Who may sign up. Under `domains`, an email on one of `domains`, or one of `emails` itself. */
13
14
  readonly signUp: {
14
15
  readonly policy: SignUpPolicy;
15
16
  readonly domains: ReadonlyArray<string>;
17
+ readonly emails: ReadonlyArray<string>;
16
18
  };
19
+ /**
20
+ * Whether a person is signed in only once their email is confirmed. Off by default: signing up signs them in at
21
+ * once, and `user.emailVerified` stays false until they open the link sign-up mails them. On, signing up and signing
22
+ * in with a password send that link instead, and nobody unconfirmed is signed in, by a session made before too.
23
+ */
24
+ readonly confirmEmail: boolean;
17
25
  readonly branding: {
18
26
  readonly name: string | null;
19
27
  readonly logo: string | null;
@@ -35,6 +43,7 @@ interface PublicSettings {
35
43
  readonly signUp: {
36
44
  readonly policy: SignUpPolicy;
37
45
  };
46
+ readonly confirmEmail: boolean;
38
47
  readonly branding: AuthSettings["branding"] & {
39
48
  readonly name: string;
40
49
  };
@@ -1,7 +1,7 @@
1
1
  import { a as Database } from "./client-D3BZs3LA.mjs";
2
2
  //#region src/auth/store.d.ts
3
3
  /** One of `db/auth.ts`'s functions. */
4
- type AuthCall = "create" | "findOne" | "findMany" | "count" | "update" | "updateMany" | "deleteMany" | "consume" | "increment" | "page";
4
+ type AuthCall = "create" | "findOne" | "findMany" | "count" | "update" | "updateMany" | "upsert" | "deleteMany" | "consume" | "increment" | "page";
5
5
  /** The rows sign-in keeps: each call one of `db/auth.ts`'s functions, as the app's server. */
6
6
  interface AuthStore {
7
7
  call(fn: AuthCall, args: Readonly<Record<string, unknown>>): Promise<unknown>;