@midsummer-ai/sdk 0.1.0-staging.4330 → 0.1.0-staging.4336

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.
@@ -1,6 +1,6 @@
1
- import { n as AuthStore } from "../store-F6n7TyY9.mjs";
1
+ import { n as AuthStore } from "../store-B3KJ3e83.mjs";
2
2
  import { SignInMail } from "./mail.mjs";
3
- import { a as Auth } from "../index-DDYlYmhT.mjs";
3
+ import { a as Auth } from "../index-CkyNDcba.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 { r as AuthError } from "../auth--jtz5BOc.mjs";
1
+ import { c as AuthError } from "../auth-Bx0aYcmG.mjs";
2
2
  import { d as SETTINGS_TTL_MS, n as LIMIT_WINDOW_MS, t as LIMITS } from "../guard-Br3K8CVx.mjs";
3
3
  import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
4
4
  //#region src/auth/contract.ts
@@ -432,6 +432,30 @@ const authContract = [
432
432
  equal(await who(auth, jar), "lin@example.com", "who is signed in again");
433
433
  }
434
434
  },
435
+ {
436
+ name: "a session's row goes as it ends, but when its user was last active stays, and goes with the user",
437
+ async run({ auth, store }) {
438
+ const jar = new Jar();
439
+ const id = await signUp(auth, jar, "ida@example.com");
440
+ equal((await ask(auth, jar, "/sign-out", {})).status, 200, "signing out");
441
+ const activity = () => store.call("findMany", {
442
+ model: "authActivity",
443
+ where: [{
444
+ field: "userId",
445
+ value: id
446
+ }]
447
+ });
448
+ equal((await activity()).map((one) => typeof one.lastActiveAt), ["number"], "when she was last active, once her session is gone");
449
+ await store.call("deleteMany", {
450
+ model: "users",
451
+ where: [{
452
+ field: "id",
453
+ value: id
454
+ }]
455
+ });
456
+ equal(await activity(), [], "what is kept of her once she is removed");
457
+ }
458
+ },
435
459
  {
436
460
  name: "with confirmEmail on, signing up and signing in sign no one in until the link mailed is opened, which signs the person in",
437
461
  async run({ auth, store, outbox, later }) {
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-B553U-d6.mjs";
2
- export { AuthTable, EngineField, FUNCTIONS_FILE, authFiles, authTables, schemaLines, tablesFile, tablesFromEngine };
1
+ import { a as authTables, c as tablesFile, i as authFiles, l as tablesFromEngine, n as EngineField, o as schemaLines, r as FUNCTIONS_FILE, s as schemaUpToDate, t as AuthTable } from "../files-CLuPkXhj.mjs";
2
+ export { AuthTable, EngineField, FUNCTIONS_FILE, authFiles, authTables, schemaLines, schemaUpToDate, 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-DhPeWwcT.mjs";
2
- export { FUNCTIONS_FILE, authFiles, authTables, schemaLines, tablesFile, tablesFromEngine };
1
+ import { a as schemaUpToDate, i as schemaLines, n as authFiles, o as tablesFile, r as authTables, s as tablesFromEngine, t as FUNCTIONS_FILE } from "../files-ZySaprII.mjs";
2
+ export { FUNCTIONS_FILE, authFiles, authTables, schemaLines, schemaUpToDate, 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-F6n7TyY9.mjs";
1
+ import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-B3KJ3e83.mjs";
2
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 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-DDYlYmhT.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 };
4
+ import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthUserRecord, d as SignedIn, f as SignedInAgent, g as AuthErrorCode, h as AuthError, i as AgentKey, l as IMPERSONATION_S, m as createAuth, n as AUTH_ROUTES, o as AuthOptions, p as auth, r as AgentGrant, s as AuthUser, t as AUTH_PATH, u as SESSION_CACHE_S, v as AuthEventBatch, y as AuthEventType } from "../index-CkyNDcba.mjs";
5
+ import { i as authFiles } from "../files-CLuPkXhj.mjs";
6
+ export { AUTH_PATH, AUTH_ROUTES, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, type 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 SESSION_CACHE_S, c as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth--jtz5BOc.mjs";
1
+ import { a as auth, c as AuthError, i as SESSION_CACHE_S, n as AUTH_ROUTES, o as createAuth, r as IMPERSONATION_S, s as databaseStore, t as AUTH_PATH } from "../auth-Bx0aYcmG.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
- import { n as authFiles } from "../files-DhPeWwcT.mjs";
3
+ import { n as authFiles } from "../files-ZySaprII.mjs";
4
4
  export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/key.d.mts CHANGED
@@ -2,7 +2,9 @@
2
2
  /**
3
3
  * An API key as `@midsummer-ai/sdk/auth` makes and checks one: `key_` and 64 random letters, kept only as its
4
4
  * SHA-256 in unpadded base64url, with its first six characters beside it to tell it from another. The platform
5
- * makes a key for a user with this, and the app's sign-in checks it as it checks its own.
5
+ * makes a key for a user with this, and the app's sign-in checks it as it checks its own. A key the platform makes for
6
+ * a retry key is drawn from a salt under the platform's own secret (`derivedKey`): for a day after it is made, the same
7
+ * retry key gives the same key back; after that the salt is deleted and only the key's hash is kept.
6
8
  */
7
9
  /** What every API key starts with, so a bearer token that is one is told from an MCP client's. */
8
10
  declare const KEY_PREFIX = "key_";
@@ -15,5 +17,16 @@ declare function newKey(): Promise<{
15
17
  readonly start: string;
16
18
  readonly prefix: string;
17
19
  }>;
20
+ /**
21
+ * The key `salt` gives under `secret`, the same each time: HMAC-SHA256 of the salt and a round's number, as many rounds
22
+ * as 64 letters take. Only someone with the secret makes it from the salt, which the platform keeps in its own store, a
23
+ * day at most, and never in the app's database beside the key's row.
24
+ */
25
+ declare function derivedKey(secret: string, salt: string): Promise<{
26
+ readonly key: string;
27
+ readonly hash: string;
28
+ readonly start: string;
29
+ readonly prefix: string;
30
+ }>;
18
31
  //#endregion
19
- export { KEY_PREFIX, keyHash, newKey };
32
+ export { KEY_PREFIX, derivedKey, keyHash, newKey };
package/auth/key.mjs CHANGED
@@ -2,7 +2,9 @@
2
2
  /**
3
3
  * An API key as `@midsummer-ai/sdk/auth` makes and checks one: `key_` and 64 random letters, kept only as its
4
4
  * SHA-256 in unpadded base64url, with its first six characters beside it to tell it from another. The platform
5
- * makes a key for a user with this, and the app's sign-in checks it as it checks its own.
5
+ * makes a key for a user with this, and the app's sign-in checks it as it checks its own. A key the platform makes for
6
+ * a retry key is drawn from a salt under the platform's own secret (`derivedKey`): for a day after it is made, the same
7
+ * retry key gives the same key back; after that the salt is deleted and only the key's hash is kept.
6
8
  */
7
9
  /** What every API key starts with, so a bearer token that is one is told from an MCP client's. */
8
10
  const KEY_PREFIX = "key_";
@@ -12,10 +14,17 @@ async function keyHash(key) {
12
14
  const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)));
13
15
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
14
16
  }
15
- /** A new key: the key to show once, and what its row keeps. */
16
- async function newKey() {
17
+ /**
18
+ * 64 letters drawn from the bytes `more` gives, each call the next: a byte past the last whole run of the alphabet is
19
+ * drawn again, so every letter is as likely as another.
20
+ */
21
+ async function lettersFrom(more) {
17
22
  let letters = "";
18
- while (letters.length < 64) for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(96))) if (byte < 208 && letters.length < 64) letters += LETTERS[byte % 52];
23
+ for (let round = 0; letters.length < 64; round++) for (const byte of await more(round)) if (byte < 208 && letters.length < 64) letters += LETTERS[byte % 52];
24
+ return letters;
25
+ }
26
+ /** A key of `letters`: the key to show, and what its row keeps. */
27
+ async function keyOf(letters) {
19
28
  const key = `${KEY_PREFIX}${letters}`;
20
29
  return {
21
30
  key,
@@ -24,5 +33,22 @@ async function newKey() {
24
33
  prefix: KEY_PREFIX
25
34
  };
26
35
  }
36
+ /** A new key: the key to show once, and what its row keeps. */
37
+ async function newKey() {
38
+ return keyOf(await lettersFrom(async () => crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(96))));
39
+ }
40
+ /**
41
+ * The key `salt` gives under `secret`, the same each time: HMAC-SHA256 of the salt and a round's number, as many rounds
42
+ * as 64 letters take. Only someone with the secret makes it from the salt, which the platform keeps in its own store, a
43
+ * day at most, and never in the app's database beside the key's row.
44
+ */
45
+ async function derivedKey(secret, salt) {
46
+ if (!secret) throw new Error("A key is derived under a secret, and none was given.");
47
+ const mac = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
48
+ name: "HMAC",
49
+ hash: "SHA-256"
50
+ }, false, ["sign"]);
51
+ return keyOf(await lettersFrom(async (round) => new Uint8Array(await crypto.subtle.sign("HMAC", mac, new TextEncoder().encode(`auth-key:${salt}:${round}`)))));
52
+ }
27
53
  //#endregion
28
- export { KEY_PREFIX, keyHash, newKey };
54
+ export { KEY_PREFIX, derivedKey, keyHash, newKey };
@@ -1,4 +1,4 @@
1
- import { n as AuthStore } from "../store-F6n7TyY9.mjs";
1
+ import { n as AuthStore } from "../store-B3KJ3e83.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-DhPeWwcT.mjs";
1
+ import { r as authTables } from "../files-ZySaprII.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. */
@@ -91,6 +91,26 @@ function standIn() {
91
91
  for (const other of table(model).values()) if (other.row.id !== row.id && other.row[field] === row[field]) throw new Error(`${model} has a row with this ${field} already`);
92
92
  }
93
93
  };
94
+ /** Keeps when each user of these sessions was last active, in authActivity, as `db/auth.ts`'s `deleteMany` does. */
95
+ const keepActivity = (sessions) => {
96
+ const last = /* @__PURE__ */ new Map();
97
+ for (const row of sessions) {
98
+ const at = Math.max(Number(row.updatedAt) || 0, Number(row.createdAt) || 0);
99
+ if (at > (last.get(String(row.userId)) ?? 0)) last.set(String(row.userId), at);
100
+ }
101
+ for (const [userId, at] of last) {
102
+ if (!table("users").has(userId)) continue;
103
+ const kept = [...table("authActivity").values()].find((one) => one.row.userId === userId);
104
+ if (!kept) run.create({
105
+ model: "authActivity",
106
+ data: {
107
+ userId,
108
+ lastActiveAt: at
109
+ }
110
+ });
111
+ else if (Number(kept.row.lastActiveAt) < at) kept.row.lastActiveAt = at;
112
+ }
113
+ };
94
114
  const run = {
95
115
  create({ model, data }) {
96
116
  const id = crypto.randomUUID().replaceAll("-", "");
@@ -147,7 +167,11 @@ function standIn() {
147
167
  },
148
168
  deleteMany({ model, where }) {
149
169
  const rows = found(model, where);
170
+ if (model === "authSessions") keepActivity(rows);
150
171
  for (const row of rows) table(model).delete(row.id);
172
+ if (model === "users") {
173
+ for (const user of rows) for (const [id, kept] of table("authActivity")) if (kept.row.userId === user.id) table("authActivity").delete(id);
174
+ }
151
175
  return rows.length;
152
176
  },
153
177
  increment({ model, where, increment, set }) {
@@ -1,11 +1,25 @@
1
1
  import { a as processEnv, i as platformApi, n as here } from "./here-C2jhTheQ.mjs";
2
+ import { DatabaseError } from "./database/errors.mjs";
2
3
  import { d as userToken, o as connect, s as databaseUrl } from "./client-DgqbFGUG.mjs";
3
4
  import { sendSignInMail } from "./auth/mail.mjs";
4
- import "./files-DhPeWwcT.mjs";
5
+ import "./files-ZySaprII.mjs";
5
6
  import { standIn } from "./auth/stand-in.mjs";
6
7
  import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, r as GEIST_WOFF2, s as defaultAppName, t as authCss, u as setupKeyOf } from "./style-BJzVvUKV.mjs";
7
8
  import { _ as challenge, a as leakedPassword, b as remembering, c as refusal, f as mayJoin, g as agentOfKey, i as guard, l as verifyHuman, m as settingsReader, o as ourWords, p as publicSettings, r as REFUSALS, s as rateLimiter, u as JoinRefused, v as consentPage, x as resourceOf, y as credentialOf } from "./guard-Br3K8CVx.mjs";
8
9
  import { i as iconSvg, n as qrSvg } from "./qr-BySxqLW6.mjs";
10
+ //#region src/auth/errors.ts
11
+ var AuthError = class extends Error {
12
+ code;
13
+ /** The scope an agent lacked, when that is why it was refused. */
14
+ scope;
15
+ constructor(code, message, scope) {
16
+ super(message);
17
+ this.code = code;
18
+ this.name = "AuthError";
19
+ if (scope !== void 0) this.scope = scope;
20
+ }
21
+ };
22
+ //#endregion
9
23
  //#region src/auth/store.ts
10
24
  const KIND = {
11
25
  create: "mutation",
@@ -25,12 +39,19 @@ const STORE_CALL_MS = 1e4;
25
39
  /**
26
40
  * The app's database as sign-in's store: each call one of `db/auth.ts`'s functions. `database` gives the
27
41
  * connection a call goes over; it is asked for one each call, so it can hand out the request's own. A function
28
- * that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`. A call
42
+ * that isn't there means `db/auth.ts` was never deployed, and an environment that binds no database gives none: each
43
+ * throws `AuthError` `not_set_up`, saying what sets it up (`midsummer auth init`, or the binding). A call
29
44
  * unanswered after `waitMs` (`STORE_CALL_MS`) throws, so a request never waits on the database for longer.
30
45
  */
31
46
  function databaseStore(database, waitMs = STORE_CALL_MS) {
32
47
  const run = async (fn, args) => {
33
- const db = await database();
48
+ let db;
49
+ try {
50
+ db = await database();
51
+ } catch (error) {
52
+ if (error instanceof Error && error.message.includes("binds no database as")) throw new AuthError("not_set_up", error.message);
53
+ throw error;
54
+ }
34
55
  try {
35
56
  return KIND[fn] === "query" ? await db.query({
36
57
  name: `auth.${fn}`,
@@ -40,7 +61,7 @@ function databaseStore(database, waitMs = STORE_CALL_MS) {
40
61
  kind: "mutation"
41
62
  }, args);
42
63
  } catch (error) {
43
- 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
+ if (error instanceof DatabaseError && error.code === "no function") throw new AuthError("not_set_up", `The database has no auth.${fn}: add sign-in's tables and functions with midsummer auth init, then deploy db/.`);
44
65
  throw error;
45
66
  }
46
67
  };
@@ -1043,7 +1064,9 @@ ${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options"
1043
1064
  *
1044
1065
  * Its own routes, for a script or `curl` (`AUTH_ROUTES`): `POST /api/auth/sign-up` and `POST /api/auth/sign-in` return
1045
1066
  * `{ signedIn: true, user }` with the session's cookie, `{ verifyEmail: true }` when the email must be confirmed first,
1046
- * or (signing in) `{ twoFactor: true }`; `POST /api/auth/sign-out` returns `{ signedOut: true }`; `GET /api/auth/session`
1067
+ * or (signing in) `{ twoFactor: true }`; `POST /api/auth/sign-in/code/send` with `{ email }` mails a sign-in code and
1068
+ * returns `{ sent: true }`, and `POST /api/auth/sign-in/code` with `{ email, code }` signs in as a password does;
1069
+ * `POST /api/auth/sign-out` returns `{ signedOut: true }`; `GET /api/auth/session`
1047
1070
  * returns `{ user, session }` or `null`. The session's cookie is `midsummer.session_token` (`__Secure-midsummer.…` over
1048
1071
  * https). Signing up signs the person in at once unless the settings' `confirmEmail` is on (`./settings.ts`).
1049
1072
  * `GET /api/auth/database-token` returns `{ url, token, expiresAt }`: the app's database and a token for the person
@@ -1076,19 +1099,8 @@ ${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options"
1076
1099
  *
1077
1100
  * Each sign-up, sign-in, ban and key is reported to the platform as an event (`./events.ts`), after the request.
1078
1101
  * In tests, give it the Stand-in: `createAuth({ store: stand.store, mail: stand.mail })`. Every failure it can name
1079
- * is an `AuthError`, whose `code` tells you which kind.
1102
+ * is an `AuthError`, whose `code` is the kind of failure.
1080
1103
  */
1081
- var AuthError = class extends Error {
1082
- code;
1083
- /** The scope an agent lacked, when that is why it was refused. */
1084
- scope;
1085
- constructor(code, message, scope) {
1086
- super(message);
1087
- this.code = code;
1088
- this.name = "AuthError";
1089
- if (scope !== void 0) this.scope = scope;
1090
- }
1091
- };
1092
1104
  /** Where sign-in is served, under every address of the app. */
1093
1105
  const AUTH_PATH = "/api/auth";
1094
1106
  /** How long a session is kept in its cookie before its row is read again, in seconds. */
@@ -1110,6 +1122,24 @@ const AUTH_ROUTES = {
1110
1122
  method: "POST",
1111
1123
  engine: "/sign-in/email"
1112
1124
  },
1125
+ /** `{ email }`: `{ sent: true }` once a sign-in code is mailed to it; a first sign-in with it makes the account. */
1126
+ "/sign-in/code/send": {
1127
+ method: "POST",
1128
+ engine: "/email-otp/send-verification-otp",
1129
+ body: (asked) => ({
1130
+ email: asked.email,
1131
+ type: "sign-in"
1132
+ })
1133
+ },
1134
+ /** `{ email, code }`: `{ signedIn: true, user }` or `{ twoFactor: true }`, as with a password. */
1135
+ "/sign-in/code": {
1136
+ method: "POST",
1137
+ engine: "/sign-in/email-otp",
1138
+ body: (asked) => ({
1139
+ email: asked.email,
1140
+ otp: asked.code
1141
+ })
1142
+ },
1113
1143
  /** `{}`: `{ signedOut: true }`, the cookie cleared. */
1114
1144
  "/sign-out": {
1115
1145
  method: "POST",
@@ -1180,7 +1210,7 @@ function storeFor(options, env) {
1180
1210
  api: options.api ?? platformApi()
1181
1211
  }), "its database with DATABASE_KEY"));
1182
1212
  if (env.MIDSUMMER_DEV === "1") return devStore();
1183
- throw new AuthError("forbidden", "Sign-in has no database here. Outside Midsummer, set DATABASE_KEY to a database key (midsummer db key create). In tests, give createAuth the Stand-in: createAuth({ store: standIn().store }).");
1213
+ throw new AuthError("not_set_up", "Sign-in has no database here. Outside Midsummer, set DATABASE_KEY to a database key (midsummer db key create). In tests, give createAuth the Stand-in: createAuth({ store: standIn().store }).");
1184
1214
  }
1185
1215
  /** `midsummer dev` without a database: one Stand-in for the process, its rows gone when it stops. */
1186
1216
  let devMemory;
@@ -1293,6 +1323,18 @@ async function inOurWords(response) {
1293
1323
  headers: response.headers
1294
1324
  });
1295
1325
  }
1326
+ /** `request` sent on to `url` with its JSON body as `shape` makes it: a route in our words, in the engine's. */
1327
+ async function reshaped(request, url, shape) {
1328
+ const asked = await request.clone().json().catch(() => null);
1329
+ const headers = new Headers(request.headers);
1330
+ headers.delete("content-length");
1331
+ headers.set("content-type", "application/json");
1332
+ return new Request(url, {
1333
+ method: request.method,
1334
+ headers,
1335
+ body: JSON.stringify(shape(typeof asked === "object" && asked !== null && !Array.isArray(asked) ? asked : {}))
1336
+ });
1337
+ }
1296
1338
  /** What a person reads when sign-in couldn't serve their request; why is in the server's log. */
1297
1339
  const unavailable = () => Response.json({
1298
1340
  code: "UNAVAILABLE",
@@ -1302,10 +1344,27 @@ const unavailable = () => Response.json({
1302
1344
  headers: { "Cache-Control": "no-store" }
1303
1345
  });
1304
1346
  /**
1347
+ * What a visitor reads of a step of setting up that was missed (`not_set_up`): that sign-in isn't set up, never the team,
1348
+ * the project or the command, which are the developer's, in the log, and in the answer too under `midsummer dev`
1349
+ * (`shown`). A 500, as asking again can't help until someone sets it up.
1350
+ */
1351
+ function notSetUp(error, shown) {
1352
+ console.error(`[auth] Sign-in isn't set up here: ${error.message}`);
1353
+ return Response.json({
1354
+ code: "NOT_SET_UP",
1355
+ message: shown ? `Sign-in isn't set up here yet. ${error.message}` : "Sign-in isn't set up for this app yet. Its developer can see why in the app's logs."
1356
+ }, {
1357
+ status: 500,
1358
+ headers: { "Cache-Control": "no-store" }
1359
+ });
1360
+ }
1361
+ /**
1305
1362
  * A request sign-in couldn't serve, such as one its database refused: the cause is logged, in our words, where the
1306
- * deployment's logs show it, and the person is answered `unavailable`.
1363
+ * deployment's logs show it, and the person is answered `unavailable`; a step of setting up that was missed is
1364
+ * answered as that (`notSetUp`), with why under `midsummer dev` (`shown`).
1307
1365
  */
1308
- function failed(error) {
1366
+ function failed(error, shown = false) {
1367
+ if (error instanceof AuthError && error.code === "not_set_up") return notSetUp(error, shown);
1309
1368
  console.error(`[auth] Sign-in couldn't answer a request: ${ourWords(error instanceof Error ? `${error.name}: ${error.message}` : String(error))}`);
1310
1369
  return unavailable();
1311
1370
  }
@@ -1336,7 +1395,7 @@ function createAuth(options = {}) {
1336
1395
  /** The secret sessions are signed with; throws, saying how to set it, where there is none. */
1337
1396
  const secretOf = () => {
1338
1397
  const secret = options.secret || base().env.AUTH_SECRET;
1339
- 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.");
1398
+ if (!secret) throw new AuthError("not_set_up", "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.");
1340
1399
  return secret;
1341
1400
  };
1342
1401
  /** Throws what a misconfigured app is told (no database to keep rows in, no AUTH_SECRET), reading nothing: before any answer that needs no read. */
@@ -1344,6 +1403,8 @@ function createAuth(options = {}) {
1344
1403
  base();
1345
1404
  secretOf();
1346
1405
  };
1406
+ /** Whether this runs under `midsummer dev`, where a step of setting up that was missed is said in the answer too. */
1407
+ const developing = () => (options.env ?? processEnv()).MIDSUMMER_DEV === "1";
1347
1408
  /** The app's name: its settings', `appName`, `APP_NAME`, else the address it serves at (`shop.acme.dev`), which reads right in every screen and mail. */
1348
1409
  const appNameOf = (settings, origin) => settings.branding.name ?? options.appName ?? base().env.APP_NAME ?? defaultAppName(origin);
1349
1410
  /** Work that follows a request, such as the new-device mail, until it ends. */
@@ -1507,6 +1568,13 @@ function createAuth(options = {}) {
1507
1568
  headers
1508
1569
  });
1509
1570
  if (route === "/sign-in" && answered.status === 403 && body?.code === "EMAIL_NOT_VERIFIED") return shaped({ verifyEmail: true });
1571
+ if (route === "/sign-in/code" && (body?.code === "INVALID_OTP" || body?.code === "OTP_EXPIRED")) return new Response(JSON.stringify({
1572
+ ...body,
1573
+ code: body.code === "INVALID_OTP" ? "INVALID_CODE" : "CODE_EXPIRED"
1574
+ }), {
1575
+ status: answered.status,
1576
+ headers
1577
+ });
1510
1578
  if (!answered.ok) return answered;
1511
1579
  const next = body?.redirect === true && typeof body.url === "string" ? { next: body.url } : {};
1512
1580
  switch (route) {
@@ -1515,11 +1583,13 @@ function createAuth(options = {}) {
1515
1583
  ...body?.user ? { user: body.user } : {},
1516
1584
  ...next
1517
1585
  } : { verifyEmail: true });
1518
- case "/sign-in": return shaped(body?.twoFactorRedirect ? { twoFactor: true } : {
1586
+ case "/sign-in":
1587
+ case "/sign-in/code": return shaped(body?.twoFactorRedirect ? { twoFactor: true } : {
1519
1588
  signedIn: true,
1520
1589
  user: body?.user,
1521
1590
  ...next
1522
1591
  });
1592
+ case "/sign-in/code/send": return shaped({ sent: true });
1523
1593
  case "/sign-out": return shaped({ signedOut: true });
1524
1594
  case "/session": return shaped(body?.user && await confirmed(body.user) ? body : null);
1525
1595
  }
@@ -1743,6 +1813,7 @@ function createAuth(options = {}) {
1743
1813
  return answer(200, { ok: true });
1744
1814
  }
1745
1815
  } catch (error) {
1816
+ if (error instanceof AuthError && error.code === "not_set_up") return notSetUp(error, developing());
1746
1817
  if (error instanceof AuthError) return answer(error.code === "invalid" ? 400 : error.code === "forbidden" ? 401 : 503, {
1747
1818
  code: error.code.toUpperCase(),
1748
1819
  message: error.message
@@ -1823,8 +1894,10 @@ function createAuth(options = {}) {
1823
1894
  if (pathname === CONSENT_PATH && settingsOfAgents.consentPage === CONSENT_PATH) return consent(request, origin, engine, appName);
1824
1895
  const route = Object.hasOwn(AUTH_ROUTES, path) ? path : void 0;
1825
1896
  if (route && request.method !== AUTH_ROUTES[route].method) return refusal(405, "METHOD_NOT_ALLOWED", `${AUTH_PATH}${route} takes ${AUTH_ROUTES[route].method}.`);
1826
- const inner = route ? new Request(`${origin}${AUTH_PATH}${AUTH_ROUTES[route].engine}${new URL(request.url).search}`, request) : request;
1897
+ const shape = route && "body" in AUTH_ROUTES[route] ? AUTH_ROUTES[route].body : void 0;
1827
1898
  const enginePath = route ? AUTH_ROUTES[route].engine : path;
1899
+ const innerUrl = `${origin}${AUTH_PATH}${enginePath}${new URL(request.url).search}`;
1900
+ const inner = !route ? request : shape ? await reshaped(request, innerUrl, shape) : new Request(innerUrl, request);
1828
1901
  const ip = here()?.ip ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null;
1829
1902
  const refused = await guard(inner, enginePath, {
1830
1903
  settings,
@@ -1864,10 +1937,10 @@ function createAuth(options = {}) {
1864
1937
  async handler(given) {
1865
1938
  const request = plainRequest(given);
1866
1939
  const current = here();
1867
- if (!current || held.has(current)) return serve(request).catch(failed);
1940
+ if (!current || held.has(current)) return serve(request).catch((error) => failed(error, developing()));
1868
1941
  held.set(current, []);
1869
1942
  try {
1870
- return await serve(request).catch(failed);
1943
+ return await serve(request).catch((error) => failed(error, developing()));
1871
1944
  } finally {
1872
1945
  const made = held.get(current) ?? [];
1873
1946
  held.delete(current);
@@ -1935,4 +2008,4 @@ function createAuth(options = {}) {
1935
2008
  /** Sign-in for this deployment, set up from its environment. */
1936
2009
  const auth = createAuth();
1937
2010
  //#endregion
1938
- export { SESSION_CACHE_S as a, databaseStore as c, IMPERSONATION_S as i, AUTH_ROUTES as n, auth as o, AuthError as r, createAuth as s, AUTH_PATH as t };
2011
+ export { auth as a, AuthError as c, SESSION_CACHE_S as i, AUTH_ROUTES as n, createAuth as o, IMPERSONATION_S as r, databaseStore as s, AUTH_PATH as t };
@@ -89,6 +89,16 @@ declare const DEPLOYED_ENGINE: EngineName;
89
89
  * gives none. Of the patterns that match, the longest part before `*` wins, then the longest key, as Node orders them.
90
90
  */
91
91
  declare function exported(exports: unknown, sub: string, conditions?: ReadonlySet<string>): string | null;
92
+ /**
93
+ * A deploy's `db/schema.ts` and the files of `db/` it imports (`./authTables`, which `midsummer auth init` writes), read
94
+ * as `midsummer db dev` builds them, for the platform's schema plan: null without a schema. Read as written, types and
95
+ * all, since a schema is literals; one that needs another kind of file, or its types taken out, throws saying it can't
96
+ * be read without building `db/`.
97
+ */
98
+ declare function readSchema(files: Readonly<Record<string, string>>): {
99
+ readonly tables: NonNullable<Built["tables"]>;
100
+ readonly indexes: NonNullable<Built["indexes"]>;
101
+ } | null;
92
102
  /**
93
103
  * Builds a `db/` folder's sources: `{ <path>: text }`, every source at any depth, by its path in the
94
104
  * folder. Without `packages` an import of a package or of a file outside the folder is refused.
@@ -105,4 +115,4 @@ declare function buildDatabase(sources: Readonly<Record<string, string>>, strip:
105
115
  /** A shape as a TypeScript type. */
106
116
  declare function typeOf(shape: Shape | null | undefined): string;
107
117
  //#endregion
108
- export { DEPLOYED_ENGINE as a, Packages as c, buildDatabase as d, enumAsObject as f, unboundCalls as g, typeOf as h, BuiltFunction as i, Refused as l, isSource as m, BUILD_FILES as n, EngineName as o, exported as p, Built as r, MODULE_BYTES as s, BUILD_BYTES as t, blockNames as u };
118
+ export { unboundCalls as _, DEPLOYED_ENGINE as a, Packages as c, buildDatabase as d, enumAsObject as f, typeOf as g, readSchema as h, BuiltFunction as i, Refused as l, isSource as m, BUILD_FILES as n, EngineName as o, exported as p, Built as r, MODULE_BYTES as s, BUILD_BYTES as t, blockNames as u };
@@ -1,4 +1,4 @@
1
- import { t as DatabaseError } from "./errors-CnQduDOt.mjs";
1
+ import { t as DatabaseError } from "./errors-DcEc-3eL.mjs";
2
2
  //#region src/database/door-socket.d.ts
3
3
  /** A TCP + TLS socket as the runtime opens one: its two streams, when it opened and closed, and `close`. */
4
4
  interface StreamSocket {
@@ -1,2 +1,2 @@
1
- import { a as DEPLOYED_ENGINE, c as Packages, d as buildDatabase, f as enumAsObject, g as unboundCalls, h as typeOf, i as BuiltFunction, l as Refused, m as isSource, n as BUILD_FILES, o as EngineName, p as exported, r as Built, s as MODULE_BYTES, t as BUILD_BYTES, u as blockNames } from "../build-Cw1BOzoq.mjs";
2
- export { BUILD_BYTES, BUILD_FILES, Built, BuiltFunction, DEPLOYED_ENGINE, EngineName, MODULE_BYTES, Packages, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
1
+ import { _ as unboundCalls, a as DEPLOYED_ENGINE, c as Packages, d as buildDatabase, f as enumAsObject, g as typeOf, h as readSchema, i as BuiltFunction, l as Refused, m as isSource, n as BUILD_FILES, o as EngineName, p as exported, r as Built, s as MODULE_BYTES, t as BUILD_BYTES, u as blockNames } from "../build-DX7RUtzJ.mjs";
2
+ export { BUILD_BYTES, BUILD_FILES, Built, BuiltFunction, DEPLOYED_ENGINE, EngineName, MODULE_BYTES, Packages, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, readSchema, typeOf, unboundCalls };
@@ -1607,6 +1607,24 @@ function authConfigFrom(file, tree) {
1607
1607
  }
1608
1608
  }
1609
1609
  /**
1610
+ * A deploy's `db/schema.ts` and the files of `db/` it imports (`./authTables`, which `midsummer auth init` writes), read
1611
+ * as `midsummer db dev` builds them, for the platform's schema plan: null without a schema. Read as written, types and
1612
+ * all, since a schema is literals; one that needs another kind of file, or its types taken out, throws saying it can't
1613
+ * be read without building `db/`.
1614
+ */
1615
+ function readSchema(files) {
1616
+ if (!Object.keys(files).length) return null;
1617
+ try {
1618
+ const built = buildDatabase(files, (ts) => ts, { ahead: true });
1619
+ return built.tables ? {
1620
+ tables: built.tables,
1621
+ indexes: built.indexes ?? {}
1622
+ } : null;
1623
+ } catch (error) {
1624
+ throw new Error(`db/schema.ts can't be read without building db/ (${error instanceof Error ? error.message : String(error)}), so its changes aren't planned here. Run midsummer db dev to check it.`);
1625
+ }
1626
+ }
1627
+ /**
1610
1628
  * Builds a `db/` folder's sources: `{ <path>: text }`, every source at any depth, by its path in the
1611
1629
  * folder. Without `packages` an import of a package or of a file outside the folder is refused.
1612
1630
  *
@@ -2164,4 +2182,4 @@ export declare function defineTable<F extends Fields>(fields: F): TableDefinitio
2164
2182
  export declare function defineSchema<T extends Record<string, TableDefinition<any>>>(tables: T): { tables: T };
2165
2183
  `;
2166
2184
  //#endregion
2167
- export { BUILD_BYTES, BUILD_FILES, DEPLOYED_ENGINE, MODULE_BYTES, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
2185
+ export { BUILD_BYTES, BUILD_FILES, DEPLOYED_ENGINE, MODULE_BYTES, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, readSchema, typeOf, unboundCalls };
@@ -1,3 +1,3 @@
1
- import { n as DatabaseErrorCode, t as DatabaseError } from "../errors-CnQduDOt.mjs";
2
- import { C as userToken, S as signedInDatabase, _ as clerk, a as DATABASE_TOKEN_PATH, b as oidc, c as DatabaseToken, d as PROFILE_MOST, f as Reference, g as auth0, h as UserProfile, i as ConnectOptions, l as DoorToken, m as SignedInDatabase, n as AuthState, o as Database, p as ReturnsOf, r as BoundDatabases, s as DatabaseClient, t as ArgsOf, u as FetchToken, v as connect, x as profileClaims, y as databaseUrl } from "../client-D5AG590o.mjs";
1
+ import { n as DatabaseErrorCode, t as DatabaseError } from "../errors-DcEc-3eL.mjs";
2
+ import { C as userToken, S as signedInDatabase, _ as clerk, a as DATABASE_TOKEN_PATH, b as oidc, c as DatabaseToken, d as PROFILE_MOST, f as Reference, g as auth0, h as UserProfile, i as ConnectOptions, l as DoorToken, m as SignedInDatabase, n as AuthState, o as Database, p as ReturnsOf, r as BoundDatabases, s as DatabaseClient, t as ArgsOf, u as FetchToken, v as connect, x as profileClaims, y as databaseUrl } from "../client-DR1sK7yy.mjs";
3
3
  export { ArgsOf, AuthState, BoundDatabases, ConnectOptions, DATABASE_TOKEN_PATH, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, DatabaseToken, DoorToken, FetchToken, PROFILE_MOST, Reference, ReturnsOf, SignedInDatabase, UserProfile, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
@@ -1,2 +1,2 @@
1
- import { n as DatabaseErrorCode, t as DatabaseError } from "../errors-CnQduDOt.mjs";
2
- export { DatabaseError, DatabaseErrorCode };
1
+ import { n as DatabaseErrorCode, r as UNBOUND, t as DatabaseError } from "../errors-DcEc-3eL.mjs";
2
+ export { DatabaseError, DatabaseErrorCode, UNBOUND };
@@ -9,5 +9,12 @@ var DatabaseError = class extends Error {
9
9
  this.name = "DatabaseError";
10
10
  }
11
11
  };
12
+ /**
13
+ * What the platform's refusal of a token says, after the environment's name, when the environment binds no Database
14
+ * by the name asked: `The preview environment binds no database as main. Bind one: …`. A deployment's request reaches
15
+ * the platform over a binding that carries an error's message alone, so this is how the app's code tells that refusal,
16
+ * a setup step missed, from an outage (`@midsummer-ai/sdk/auth`'s `not_set_up`). The platform words it with this.
17
+ */
18
+ const UNBOUND = "binds no database as";
12
19
  //#endregion
13
- export { DatabaseError };
20
+ export { DatabaseError, UNBOUND };
@@ -1,5 +1,5 @@
1
- import { t as DatabaseError } from "../errors-CnQduDOt.mjs";
2
- import { f as Reference, o as Database } from "../client-D5AG590o.mjs";
1
+ import { t as DatabaseError } from "../errors-DcEc-3eL.mjs";
2
+ import { f as Reference, o as Database } from "../client-DR1sK7yy.mjs";
3
3
  import { ReactNode } from "react";
4
4
  //#region src/database/react.d.ts
5
5
  type ArgsOf<F> = F extends Reference<any, infer A, any> ? A : never;
@@ -1,8 +1,8 @@
1
- import { t as DatabaseError } from "../errors-CnQduDOt.mjs";
1
+ import { t as DatabaseError } from "../errors-DcEc-3eL.mjs";
2
2
  import { p as Storage } from "../index-CXiY5knc.mjs";
3
3
  import { t as AuthConfig } from "../auth-B7rCtXFQ.mjs";
4
4
  import { a as FileMetadata, c as FunctionReference, d as HttpRouter, n as CronJob, s as FunctionKind, v as RegisteredFunction, y as Row } from "../server-B5HK2Ou9.mjs";
5
- import { r as Built } from "../build-Cw1BOzoq.mjs";
5
+ import { r as Built } from "../build-DX7RUtzJ.mjs";
6
6
  import { A as VectorControl, M as VectorEngine } from "../index-5INBK1BU.mjs";
7
7
  //#region src/database/stand-in.d.ts
8
8
  /** A Database as its client reaches it: by function name or reference. A refusal throws `DatabaseError`. */
@@ -24,5 +24,12 @@ declare class DatabaseError extends Error {
24
24
  readonly detail?: unknown;
25
25
  constructor(code: DatabaseErrorCode | (string & {}), message?: string, detail?: unknown);
26
26
  }
27
+ /**
28
+ * What the platform's refusal of a token says, after the environment's name, when the environment binds no Database
29
+ * by the name asked: `The preview environment binds no database as main. Bind one: …`. A deployment's request reaches
30
+ * the platform over a binding that carries an error's message alone, so this is how the app's code tells that refusal,
31
+ * a setup step missed, from an outage (`@midsummer-ai/sdk/auth`'s `not_set_up`). The platform words it with this.
32
+ */
33
+ declare const UNBOUND = "binds no database as";
27
34
  //#endregion
28
- export { DatabaseErrorCode as n, DatabaseError as t };
35
+ export { DatabaseErrorCode as n, UNBOUND as r, DatabaseError as t };
@@ -46,10 +46,20 @@ declare function tablesFromEngine(tables: ReadonlyArray<{
46
46
  readonly name: string;
47
47
  readonly fields: Readonly<Record<string, EngineField>>;
48
48
  }>): Readonly<Record<string, AuthTable>>;
49
- /** Every table sign-in keeps: the engine's, and its own settings, waitlist and rate limits. */
49
+ /** Every table sign-in keeps: the engine's, and its own (`OWN`). */
50
50
  declare function authTables(): Readonly<Record<string, AuthTable>>;
51
51
  /** `db/authTables.ts`: each table as `defineTable(...)` with its indexes, and the fields each is looked up by. */
52
52
  declare function tablesFile(tables: Readonly<Record<string, AuthTable>>): string;
53
+ /**
54
+ * `schema`, a `db/schema.ts` an earlier `midsummer auth init` took sign-in's tables into, with the tables of `tables`
55
+ * it doesn't name yet added beside the others: after its last `<table>: authTables.<table>` entry, each on a line of
56
+ * its own where the entries are one a line, else on the same line. One that spreads `...authTables` takes every table
57
+ * already. Null for a schema that names none of sign-in's tables, which is its person's to add them to.
58
+ */
59
+ declare function schemaUpToDate(schema: string, tables?: Readonly<Record<string, AuthTable>>): {
60
+ readonly schema: string;
61
+ readonly added: ReadonlyArray<string>;
62
+ } | null;
53
63
  /** The lines db/schema.ts names sign-in's tables with, inside `defineSchema({ ... })`. */
54
64
  declare function schemaLines(tables: Readonly<Record<string, AuthTable>>): string;
55
65
  /**
@@ -73,4 +83,4 @@ declare function authFiles(): {
73
83
  };
74
84
  };
75
85
  //#endregion
76
- export { authTables as a, tablesFromEngine as c, authFiles as i, EngineField as n, schemaLines as o, FUNCTIONS_FILE as r, tablesFile as s, AuthTable as t };
86
+ export { authTables as a, tablesFile as c, authFiles as i, tablesFromEngine as l, EngineField as n, schemaLines as o, FUNCTIONS_FILE as r, schemaUpToDate as s, AuthTable as t };
@@ -329,7 +329,10 @@ function shapeOf(field) {
329
329
  const base = field.references?.field === "id" ? `v.id(${JSON.stringify(field.references.model)})` : type === "string" ? "v.string()" : type === "number" || type === "date" ? "v.number()" : type === "boolean" ? "v.boolean()" : type === "string[]" ? "v.array(v.string())" : type === "number[]" ? "v.array(v.number())" : Array.isArray(type) ? `v.union(${type.map((one) => `v.literal(${JSON.stringify(one)})`).join(", ")})` : "v.any()";
330
330
  return field.required === true ? base : `v.optional(${base})`;
331
331
  }
332
- /** Sign-in's own tables beside the engine's: its settings, its waitlist and its rate limits. */
332
+ /**
333
+ * Sign-in's own tables beside the engine's: its settings, its waitlist, its rate limits, and when each user was last
334
+ * active (`authActivity`, kept as their sessions go, which the engine deletes as they end).
335
+ */
333
336
  const OWN = {
334
337
  authSettings: {
335
338
  fields: {
@@ -365,6 +368,14 @@ const OWN = {
365
368
  },
366
369
  indexed: ["windowStart"],
367
370
  unique: ["key"]
371
+ },
372
+ authActivity: {
373
+ fields: {
374
+ userId: "v.id(\"users\")",
375
+ lastActiveAt: "v.number()"
376
+ },
377
+ indexed: ["userId", "lastActiveAt"],
378
+ unique: []
368
379
  }
369
380
  };
370
381
  /**
@@ -396,7 +407,7 @@ function tablesFromEngine(tables) {
396
407
  }];
397
408
  }));
398
409
  }
399
- /** Every table sign-in keeps: the engine's, and its own settings, waitlist and rate limits. */
410
+ /** Every table sign-in keeps: the engine's, and its own (`OWN`). */
400
411
  function authTables() {
401
412
  return {
402
413
  ...ENGINE_TABLES,
@@ -424,6 +435,34 @@ ${lookups.join("\n")}
424
435
  }
425
436
  `;
426
437
  }
438
+ /**
439
+ * `schema`, a `db/schema.ts` an earlier `midsummer auth init` took sign-in's tables into, with the tables of `tables`
440
+ * it doesn't name yet added beside the others: after its last `<table>: authTables.<table>` entry, each on a line of
441
+ * its own where the entries are one a line, else on the same line. One that spreads `...authTables` takes every table
442
+ * already. Null for a schema that names none of sign-in's tables, which is its person's to add them to.
443
+ */
444
+ function schemaUpToDate(schema, tables = authTables()) {
445
+ if (/\.\.\.\s*authTables\b/.test(schema)) return {
446
+ schema,
447
+ added: []
448
+ };
449
+ const last = [...schema.matchAll(/\b\w+[ \t]*:[ \t]*authTables\.\w+[ \t]*(,?)/g)].at(-1);
450
+ if (!last || last.index === void 0) return null;
451
+ const added = Object.keys(tables).filter((name) => !new RegExp(`\\bauthTables\\.${name}\\b`).test(schema));
452
+ if (!added.length) return {
453
+ schema,
454
+ added
455
+ };
456
+ const end = last.index + last[0].length;
457
+ const lineStart = schema.lastIndexOf("\n", last.index) + 1;
458
+ const ownLine = !schema.slice(lineStart, last.index).trim();
459
+ const indent = /^[ \t]*/.exec(schema.slice(lineStart))[0];
460
+ const entry = (name) => `${ownLine ? `\n${indent}` : " "}${name}: authTables.${name},`;
461
+ return {
462
+ schema: `${schema.slice(0, end)}${last[1] ? "" : ","}${added.map(entry).join("")}${schema.slice(end)}`,
463
+ added
464
+ };
465
+ }
427
466
  /** The lines db/schema.ts names sign-in's tables with, inside `defineSchema({ ... })`. */
428
467
  function schemaLines(tables) {
429
468
  return Object.keys(tables).map((name) => `${name}: authTables.${name},`).join(" ");
@@ -514,9 +553,13 @@ function matches(row: Shown, clauses: ReadonlyArray<Clause>): boolean {
514
553
  return result
515
554
  }
516
555
  const RANGE: Readonly<Record<string, "lt" | "lte" | "gt" | "gte">> = { lt: "lt", lte: "lte", gt: "gt", gte: "gte" }
517
- /** How one clause is read through an index, or null when none serves it. Lower ranks find fewer rows. */
518
- function readOf(db: Rows, model: string, clause: Clause): { readonly rank: number; read(): Promise<Stored[]> } | null {
556
+ /**
557
+ * How one clause is read through an index, or null when none serves it. Lower ranks find fewer rows. With most, a read
558
+ * takes at most that many rows of the index, for a where of this one clause, whose every row it reads is one it holds.
559
+ */
560
+ function readOf(db: Rows, model: string, clause: Clause, most?: number): { readonly rank: number; read(): Promise<Stored[]> } | null {
519
561
  const operator = clause.operator ?? "eq", { field, value } = clause
562
+ const all = (reading: Reading) => (most === undefined ? reading.collect() : reading.take(most))
520
563
  const loose = clause.mode === "insensitive"
521
564
  if (loose && !(LOWER[model] ?? []).includes(field)) return null
522
565
  const key = (one: unknown) => (loose ? lower(one) : one)
@@ -528,11 +571,11 @@ function readOf(db: Rows, model: string, clause: Clause): { readonly rank: numbe
528
571
  const at = (lookups[model] ?? []).indexOf(field)
529
572
  if (at < 0) return null
530
573
  const index = "by_" + field
531
- if (operator === "eq" && value !== null && value !== undefined) return { rank: 1 + at, read: () => db.query(model).withIndex(index, (q) => q.eq(field, key(value))).collect() }
574
+ if (operator === "eq" && value !== null && value !== undefined) return { rank: 1 + at, read: () => all(db.query(model).withIndex(index, (q) => q.eq(field, key(value)))) }
532
575
  if (operator === "in" && Array.isArray(value)) return { rank: 20 + at, read: async () => (await Promise.all(value.map((one) => db.query(model).withIndex(index, (q) => q.eq(field, key(one))).collect()))).flat() }
533
576
  const bound = RANGE[operator]
534
- if (bound && value !== null && value !== undefined) return { rank: 40 + at, read: () => db.query(model).withIndex(index, (q) => q[bound](field, value)).collect() }
535
- if (operator === "starts_with" && typeof value === "string" && !loose) return { rank: 40 + at, read: () => db.query(model).withIndex(index, (q) => q.gte(field, value).lt(field, value + "￿")).collect() }
577
+ if (bound && value !== null && value !== undefined) return { rank: 40 + at, read: () => all(db.query(model).withIndex(index, (q) => q[bound](field, value))) }
578
+ if (operator === "starts_with" && typeof value === "string" && !loose) return { rank: 40 + at, read: () => all(db.query(model).withIndex(index, (q) => q.gte(field, value).lt(field, value + "￿"))) }
536
579
  return null
537
580
  }
538
581
  /**
@@ -540,8 +583,8 @@ function readOf(db: Rows, model: string, clause: Clause): { readonly rank: numbe
540
583
  * fewest; a where joined by OR reads each clause's index and merges them. A where no index serves is refused, so no
541
584
  * read takes a whole table however many users it has.
542
585
  */
543
- async function candidates(db: Rows, model: string, clauses: ReadonlyArray<Clause>): Promise<Stored[]> {
544
- const reads = clauses.map((clause) => readOf(db, model, clause))
586
+ async function candidates(db: Rows, model: string, clauses: ReadonlyArray<Clause>, most?: number): Promise<Stored[]> {
587
+ const reads = clauses.map((clause) => readOf(db, model, clause, clauses.length === 1 ? most : undefined))
545
588
  if (clauses.some((clause, index) => index > 0 && clause.connector === "OR")) {
546
589
  if (reads.some((read) => read === null)) throw new Error("sign-in asked for " + model + " by a field no index serves: " + clauses.map((clause) => clause.field).join(", "))
547
590
  const merged = new Map<string, Stored>()
@@ -552,14 +595,17 @@ async function candidates(db: Rows, model: string, clauses: ReadonlyArray<Clause
552
595
  if (!best) throw new Error("sign-in asked for " + model + " by a field no index serves: " + clauses.map((clause) => clause.field).join(", "))
553
596
  return best.read()
554
597
  }
555
- /** The rows a where holds; with no where, the newest up to most. */
556
- async function found(db: Rows, model: string, clauses: ReadonlyArray<Clause> | undefined, most?: number): Promise<Shown[]> {
598
+ /**
599
+ * The rows a where holds; with no where, the newest up to most. With taken, a where of one clause reads at most that
600
+ * many, in its index's order: for a list in no other order, so a range such as the last month's reads only a page.
601
+ */
602
+ async function found(db: Rows, model: string, clauses: ReadonlyArray<Clause> | undefined, most?: number, taken?: number): Promise<Shown[]> {
557
603
  const all = clauses ?? []
558
604
  if (!all.length) {
559
605
  if (most === undefined) throw new Error("sign-in asked for every row of " + model + " at once: name a field, or read a page with auth.page.")
560
606
  return (await db.query(model).order("desc").take(Math.min(most, MOST_READ))).map((doc) => shown(doc)!)
561
607
  }
562
- return (await candidates(db, model, all)).map((doc) => shown(doc)!).filter((row) => matches(row, all))
608
+ return (await candidates(db, model, all, taken)).map((doc) => shown(doc)!).filter((row) => matches(row, all))
563
609
  }
564
610
  function ordered(list: Shown[], sortBy: { readonly field: string; readonly direction?: string } | undefined): Shown[] {
565
611
  if (!sortBy) return list
@@ -569,6 +615,30 @@ function ordered(list: Shown[], sortBy: { readonly field: string; readonly direc
569
615
  return (x === null || x === undefined) && (y === null || y === undefined) ? 0 : x === null || x === undefined ? -sign : y === null || y === undefined ? sign : x < y ? -sign : x > y ? sign : 0
570
616
  })
571
617
  }
618
+ /**
619
+ * Keeps when each user of these sessions was last active, in authActivity, as their rows go: the engine deletes a
620
+ * session once it ends, and a revoke or a ban deletes it at once, so when its user was last active would go with it.
621
+ * One row a user, only ever moved later, and none for a user who is gone.
622
+ */
623
+ async function keepActivity(db: Rows, sessions: ReadonlyArray<Shown>): Promise<void> {
624
+ const last = new Map<string, number>()
625
+ for (const row of sessions) {
626
+ const at = Math.max(Number(row.updatedAt) || 0, Number(row.createdAt) || 0)
627
+ if (at > (last.get(String(row.userId)) ?? 0)) last.set(String(row.userId), at)
628
+ }
629
+ await Promise.all([...last].map(async ([userId, at]) => {
630
+ if (!db.normalizeId("users", userId) || !(await db.get("users", userId))) return
631
+ const kept = (await db.query("authActivity").withIndex("by_userId", (q) => q.eq("userId", userId)).collect())[0]
632
+ if (!kept) await db.insert("authActivity", { userId, lastActiveAt: at })
633
+ else if (Number(kept.lastActiveAt) < at) await db.patch("authActivity", kept._id, { lastActiveAt: at })
634
+ }))
635
+ }
636
+ /** Deletes what authActivity keeps of these users, as they go. */
637
+ async function forgetActivity(db: Rows, users: ReadonlyArray<Shown>): Promise<void> {
638
+ await Promise.all(users.map(async (user) => {
639
+ for (const kept of await db.query("authActivity").withIndex("by_userId", (q) => q.eq("userId", user.id)).collect()) await db.delete("authActivity", kept._id)
640
+ }))
641
+ }
572
642
  /** A row's fields as written: sign-in's id is the Database's, and fields kept in lower case are lowered. */
573
643
  function fieldsOf(model: string, data: unknown): Record<string, unknown> {
574
644
  const fields: Record<string, unknown> = {}
@@ -595,8 +665,9 @@ export const findMany = query({
595
665
  args: { model: v.string(), where, limit: v.optional(v.number()), offset: v.optional(v.number()), sortBy: v.optional(v.any()) },
596
666
  handler: async (ctx, args) => {
597
667
  const db = rows(ctx), model = table(args.model)
598
- const offset = args.offset ?? 0
599
- const list = ordered(await found(db, model, args.where as Clause[] | undefined, offset + (args.limit ?? MOST_READ)), args.sortBy as { field: string; direction?: string } | undefined)
668
+ const offset = args.offset ?? 0, most = offset + (args.limit ?? MOST_READ)
669
+ // Sorted by a field, every row the where holds is read first; in the index's own order, only as many as are asked.
670
+ const list = ordered(await found(db, model, args.where as Clause[] | undefined, most, args.sortBy ? undefined : most), args.sortBy as { field: string; direction?: string } | undefined)
600
671
  return list.slice(offset, args.limit === undefined || args.limit === null ? undefined : offset + args.limit)
601
672
  },
602
673
  })
@@ -638,12 +709,15 @@ export const upsert = mutation({
638
709
  return null
639
710
  },
640
711
  })
712
+ /** Deletes the rows a where holds. Sessions leave when their user was last active behind (keepActivity); users take theirs. */
641
713
  export const deleteMany = mutation({
642
714
  args: { model: v.string(), where },
643
715
  handler: async (ctx, args) => {
644
716
  const db = rows(ctx), model = table(args.model)
645
717
  const list = await found(db, model, args.where as Clause[] | undefined)
718
+ if (model === "authSessions") await keepActivity(db, list)
646
719
  await Promise.all(list.map((row) => db.delete(model, row.id)))
720
+ if (model === "users") await forgetActivity(db, list)
647
721
  return list.length
648
722
  },
649
723
  })
@@ -703,4 +777,4 @@ function authFiles() {
703
777
  };
704
778
  }
705
779
  //#endregion
706
- export { tablesFile as a, schemaLines as i, authFiles as n, tablesFromEngine as o, authTables as r, FUNCTIONS_FILE as t };
780
+ export { schemaUpToDate as a, schemaLines as i, authFiles as n, tablesFile as o, authTables as r, tablesFromEngine as s, FUNCTIONS_FILE as t };
package/here-C2jhTheQ.mjs CHANGED
@@ -12,7 +12,7 @@ function processEnv() {
12
12
  * This package's version: `0.0.0-dev` here, and in a published package the version it was published at, which the
13
13
  * release writes in its place as it stages the package (`stampSdk` in `scripts/release/packages.ts`).
14
14
  */
15
- const SDK_VERSION = "0.1.0-staging.4330";
15
+ const SDK_VERSION = "0.1.0-staging.4336";
16
16
  /**
17
17
  * The header that tells Midsummer which client made each of this package's calls: `Midsummer-Client: sdk/<version>
18
18
  * <part>`, `part` the product whose client it is (`database`, `storage`, `queues`, ...), so the platform counts which
@@ -1,4 +1,4 @@
1
- import { n as AuthStore } from "./store-F6n7TyY9.mjs";
1
+ import { n as AuthStore } from "./store-B3KJ3e83.mjs";
2
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
@@ -64,14 +64,25 @@ interface AuthEventBatch {
64
64
  /** Where batches go: the platform, through whatever this code runs with. What it returns says whether to try again. */
65
65
  type EventSend = (batch: AuthEventBatch) => Promise<"sent" | "drop" | "retry">;
66
66
  //#endregion
67
- //#region src/auth/index.d.ts
68
- type AuthErrorCode = "invalid" | "forbidden" | "unavailable";
67
+ //#region src/auth/errors.d.ts
68
+ /**
69
+ * What sign-in throws when it can name the failure: an `AuthError`, whose `code` is the kind of failure.
70
+ *
71
+ * - `invalid`: what was asked doesn't fit, such as metadata past 8 KB.
72
+ * - `forbidden`: the caller may not do this, such as an agent without the scope a route asks for.
73
+ * - `unavailable`: sign-in couldn't answer now, such as a database that didn't answer in time.
74
+ * - `not_set_up`: a step of setting it up was missed, such as `AUTH_SECRET`, a database bound for it or `db/auth.ts`
75
+ * deployed. Its message names the step and what sets it up; asking again doesn't help until then.
76
+ */
77
+ type AuthErrorCode = "invalid" | "forbidden" | "unavailable" | "not_set_up";
69
78
  declare class AuthError extends Error {
70
79
  readonly code: AuthErrorCode;
71
80
  /** The scope an agent lacked, when that is why it was refused. */
72
81
  readonly scope?: string;
73
82
  constructor(code: AuthErrorCode, message: string, scope?: string);
74
83
  }
84
+ //#endregion
85
+ //#region src/auth/index.d.ts
75
86
  /** Where sign-in is served, under every address of the app. */
76
87
  declare const AUTH_PATH = "/api/auth";
77
88
  /** How long a session is kept in its cookie before its row is read again, in seconds. */
@@ -93,6 +104,24 @@ declare const AUTH_ROUTES: {
93
104
  readonly method: "POST";
94
105
  readonly engine: "/sign-in/email";
95
106
  };
107
+ /** `{ email }`: `{ sent: true }` once a sign-in code is mailed to it; a first sign-in with it makes the account. */
108
+ readonly "/sign-in/code/send": {
109
+ readonly method: "POST";
110
+ readonly engine: "/email-otp/send-verification-otp";
111
+ readonly body: (asked: Readonly<Record<string, unknown>>) => {
112
+ email: unknown;
113
+ type: string;
114
+ };
115
+ };
116
+ /** `{ email, code }`: `{ signedIn: true, user }` or `{ twoFactor: true }`, as with a password. */
117
+ readonly "/sign-in/code": {
118
+ readonly method: "POST";
119
+ readonly engine: "/sign-in/email-otp";
120
+ readonly body: (asked: Readonly<Record<string, unknown>>) => {
121
+ email: unknown;
122
+ otp: unknown;
123
+ };
124
+ };
96
125
  /** `{}`: `{ signedOut: true }`, the cookie cleared. */
97
126
  readonly "/sign-out": {
98
127
  readonly method: "POST";
@@ -270,4 +299,4 @@ declare function createAuth(options?: AuthOptions): Auth;
270
299
  /** Sign-in for this deployment, set up from its environment. */
271
300
  declare const auth: Auth;
272
301
  //#endregion
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 };
302
+ export { AuthEvent as _, Auth as a, EventSend as b, AuthUserRecord as c, SignedIn as d, SignedInAgent as f, AuthErrorCode as g, AuthError as h, AgentKey as i, IMPERSONATION_S as l, createAuth as m, AUTH_ROUTES as n, AuthOptions as o, auth as p, AgentGrant as r, AuthUser as s, AUTH_PATH as t, SESSION_CACHE_S 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.4330",
3
+ "version": "0.1.0-staging.4336",
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.",
@@ -1,4 +1,4 @@
1
- import { o as Database } from "./client-D5AG590o.mjs";
1
+ import { o as Database } from "./client-DR1sK7yy.mjs";
2
2
  //#region src/auth/store.d.ts
3
3
  /** One of `db/auth.ts`'s functions. */
4
4
  type AuthCall = "create" | "findOne" | "findMany" | "count" | "update" | "updateMany" | "upsert" | "deleteMany" | "consume" | "increment" | "page";
@@ -9,7 +9,8 @@ interface AuthStore {
9
9
  /**
10
10
  * The app's database as sign-in's store: each call one of `db/auth.ts`'s functions. `database` gives the
11
11
  * connection a call goes over; it is asked for one each call, so it can hand out the request's own. A function
12
- * that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`. A call
12
+ * that isn't there means `db/auth.ts` was never deployed, and an environment that binds no database gives none: each
13
+ * throws `AuthError` `not_set_up`, saying what sets it up (`midsummer auth init`, or the binding). A call
13
14
  * unanswered after `waitMs` (`STORE_CALL_MS`) throws, so a request never waits on the database for longer.
14
15
  */
15
16
  declare function databaseStore(database: () => Promise<Database>, waitMs?: number): AuthStore;