ovr 7.0.0-next.2 → 7.0.0-next.21

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +1157 -0
  2. package/dist/auth/client-source.d.ts +2 -2
  3. package/dist/auth/client-source.d.ts.map +1 -1
  4. package/dist/auth/client-source.js +2 -2
  5. package/dist/auth/client.d.ts.map +1 -1
  6. package/dist/auth/client.js +7 -4
  7. package/dist/auth/configure.d.ts +21 -8
  8. package/dist/auth/configure.d.ts.map +1 -1
  9. package/dist/auth/configure.js +172 -6
  10. package/dist/auth/index.d.ts +48 -0
  11. package/dist/auth/index.d.ts.map +1 -1
  12. package/dist/auth/index.js +19 -0
  13. package/dist/auth/passkey.d.ts +14 -2
  14. package/dist/auth/passkey.d.ts.map +1 -1
  15. package/dist/auth/passkey.js +18 -5
  16. package/dist/auth/state.d.ts +6 -0
  17. package/dist/auth/state.d.ts.map +1 -1
  18. package/dist/auth/state.js +28 -5
  19. package/dist/auth/storage.d.ts +38 -0
  20. package/dist/auth/storage.d.ts.map +1 -1
  21. package/dist/auth/storage.js +60 -3
  22. package/dist/context/index.d.ts +4 -4
  23. package/dist/context/index.d.ts.map +1 -1
  24. package/dist/context/index.js +6 -3
  25. package/dist/form/index.d.ts +239 -31
  26. package/dist/form/index.d.ts.map +1 -1
  27. package/dist/form/index.js +657 -66
  28. package/dist/markdown/index.d.ts +6 -1
  29. package/dist/markdown/index.d.ts.map +1 -1
  30. package/dist/markdown/index.js +180 -9
  31. package/dist/mcp/index.d.ts.map +1 -1
  32. package/dist/mcp/index.js +154 -57
  33. package/dist/schema/index.d.ts +88 -19
  34. package/dist/schema/index.d.ts.map +1 -1
  35. package/dist/schema/index.js +32 -11
  36. package/dist/util/index.d.ts +12 -0
  37. package/dist/util/index.d.ts.map +1 -1
  38. package/dist/util/index.js +19 -0
  39. package/package.json +2 -1
  40. package/src/auth/client-source.ts +2 -2
  41. package/src/auth/client.ts +7 -4
  42. package/src/auth/configure.ts +189 -13
  43. package/src/auth/index.ts +44 -0
  44. package/src/auth/passkey.ts +25 -7
  45. package/src/auth/state.ts +32 -7
  46. package/src/auth/storage.ts +66 -3
  47. package/src/context/index.ts +14 -6
  48. package/src/form/index.ts +1174 -195
  49. package/src/markdown/index.ts +203 -12
  50. package/src/mcp/index.ts +205 -72
  51. package/src/schema/index.ts +195 -52
  52. package/src/util/index.ts +23 -0
@@ -1,6 +1,6 @@
1
1
  import type { Context } from "../context/index.js";
2
2
  import { Database } from "../database/index.js";
3
- import { Field, Form, field } from "../form/index.js";
3
+ import { Field, Form, field, taken } from "../form/index.js";
4
4
  import { jsx } from "../jsx/index.js";
5
5
  import { Limiter } from "../limiter/index.js";
6
6
  import type { Middleware } from "../middleware/index.js";
@@ -11,6 +11,7 @@ import { Issue } from "./issue.js";
11
11
  import { Passkey } from "./passkey.js";
12
12
  import type { State } from "./state.js";
13
13
  import type { Storage } from "./storage.js";
14
+ import { Token } from "./token.js";
14
15
 
15
16
  /**
16
17
  * Construct startup-complete handlers and request-scoped UI components.
@@ -46,11 +47,14 @@ export function configure<U extends Auth.Users>(
46
47
  const limits = {
47
48
  register: limiter("register", 5, 10 * Time.minute),
48
49
  login: limiter("login", 20, Time.minute),
50
+ add: limiter("add", 5, 10 * Time.minute),
49
51
  };
50
52
  const paths = {
51
53
  register: "/auth/register",
52
54
  login: "/auth/login",
53
55
  logout: "/auth/logout",
56
+ passkey: "/auth/passkey",
57
+ link: "/auth/link",
54
58
  options: "/_passkey/options",
55
59
  } as const;
56
60
  const page = options.page ?? "/login";
@@ -74,19 +78,54 @@ export function configure<U extends Auth.Users>(
74
78
  ) as Field.Parse.Data<Shape>;
75
79
  };
76
80
 
77
- const back = (c: Pick<Context, "redirect">, method: string, retry = 0) => {
78
- const target = new URL(page, options.origin);
81
+ /**
82
+ * @param data Registration values
83
+ * @returns The message of each `taken()` field whose value a user has
84
+ */
85
+ const conflicts = async (data: Field.Parse.Data<Shape>) => {
86
+ const used: Record<string, string> = {};
87
+ for (const name of fields.names) {
88
+ const message = shape[name]![taken];
89
+ const value: unknown = Reflect.get(data, name);
90
+ if (message === undefined || value == null || value === "") continue;
91
+ const rows = await options.database
92
+ .sql`SELECT 1 FROM ${users} WHERE ${users.columns[name]!} = ${value} LIMIT 1`;
93
+ if (rows.length) used[name] = message;
94
+ }
95
+ return used;
96
+ };
97
+
98
+ /** @returns The page a form was on, if it said, or where a login goes */
99
+ const returning = (c: Pick<Context, "url">) => {
100
+ const target = new URL(
101
+ c.url.searchParams.get(Form.params[0]) ?? redirect,
102
+ options.origin,
103
+ );
104
+ return target.origin === options.origin
105
+ ? target
106
+ : new URL(redirect, options.origin);
107
+ };
108
+
109
+ const back = (
110
+ c: Pick<Context, "redirect" | "url">,
111
+ method: string,
112
+ retry = 0,
113
+ ) => {
114
+ // a passkey is added from a page of the account, not the login page
115
+ const target =
116
+ method === "add" ? returning(c) : new URL(page, options.origin);
79
117
  target.searchParams.set("_auth", method);
80
118
  if (retry) target.searchParams.set("_retry", String(retry));
81
119
  c.redirect(target, 303);
82
120
  };
83
121
 
84
122
  const admit = async (
85
- c: Limiter.Context & Pick<Context, "text" | "redirect">,
86
- method: "register" | "login",
123
+ c: Limiter.Context & Pick<Context, "text" | "redirect" | "url">,
124
+ method: "register" | "login" | "add" | "link",
87
125
  prompt: boolean,
88
126
  ) => {
89
- const admission = await limits[method].check(
127
+ // a link signs in, so it shares a login's limit
128
+ const admission = await limits[method === "link" ? "login" : method].check(
90
129
  c,
91
130
  prompt ? "options" : "verify",
92
131
  );
@@ -112,9 +151,12 @@ export function configure<U extends Auth.Users>(
112
151
  c.redirect(state(c).resume(redirect), 303);
113
152
  };
114
153
  const guard =
115
- (method: "register" | "login" | "logout", prompt = false) =>
154
+ (
155
+ method: "register" | "login" | "logout" | "add" | "link",
156
+ prompt = false,
157
+ ) =>
116
158
  async (
117
- c: Limiter.Context & Pick<Context, "text" | "redirect">,
159
+ c: Limiter.Context & Pick<Context, "text" | "redirect" | "url">,
118
160
  next: Middleware.Next,
119
161
  ) => {
120
162
  noStore(c.res.headers);
@@ -186,10 +228,15 @@ export function configure<U extends Auth.Users>(
186
228
  const input = await Issue.data(c);
187
229
  if (!input) throw new Issue("registration request");
188
230
  if (input.issues) {
189
- const invalid = fields.names.filter((name) =>
190
- input.issues.some((issue) => issue.path[0] === name),
191
- );
192
- if (!invalid.length) throw new Issue("registration request");
231
+ // each field's own message: checks of what the person typed,
232
+ // which say nothing about other accounts
233
+ const invalid: Record<string, string> = {};
234
+ for (const name of fields.names) {
235
+ const issue = input.issues.find((issue) => issue.path[0] === name);
236
+ if (issue) invalid[name] = issue.message;
237
+ }
238
+ if (!Object.keys(invalid).length)
239
+ throw new Issue("registration request");
193
240
  return c.json({ fields: invalid }, 422);
194
241
  }
195
242
  if (!(await admit(c, "register", true))) return;
@@ -198,6 +245,10 @@ export function configure<U extends Auth.Users>(
198
245
  bootstrap: string;
199
246
  };
200
247
  const application = values(data);
248
+ // a public value already used, such as a username, is said before
249
+ // the passkey prompt, so no passkey is saved for a failed account
250
+ const used = await conflicts(application);
251
+ if (Object.keys(used).length) return c.json({ fields: used }, 422);
201
252
  await Passkey.issue(c, state(c), data.bootstrap, {
202
253
  method: "register",
203
254
  action: paths.register,
@@ -215,16 +266,105 @@ export function configure<U extends Auth.Users>(
215
266
  action: paths.login,
216
267
  });
217
268
  });
269
+ /** What a person calls a passkey they add, such as "Laptop" */
270
+ const naming = {
271
+ name: Field.text()
272
+ .max(64)
273
+ .optional()
274
+ .label("Name")
275
+ .hint("Such as the device it is on"),
276
+ };
277
+ const add = Route.post(paths.passkey)
278
+ .fields({ ...naming, ...Passkey.shape })
279
+ .use(guard("add"), async (c) => {
280
+ const input = await Issue.data(c);
281
+ if (!input || input.issues) throw new Issue("passkey request");
282
+ const session = await state(c).session();
283
+ if (!session) throw new Issue("session");
284
+ const credential = await new Passkey(c, state(c)).register();
285
+ // the account that started the ceremony is still the one signed in
286
+ if (credential.user !== session.user) throw new Issue("user");
287
+ await storage
288
+ .register(() => {}, {
289
+ ...credential,
290
+ name: input.data.name?.trim() || null,
291
+ })
292
+ .catch((error: unknown) => {
293
+ // a passkey that is already an account's
294
+ if (Database.unique(error)) throw new Issue("passkey");
295
+ throw error;
296
+ });
297
+ c.redirect(returning(c), 303);
298
+ });
299
+ const adding = Route.post(`${paths.options}/add`)
300
+ // the form's own field is sent with it, and saved when it submits
301
+ .fields({ ...naming, bootstrap: Field.hidden() })
302
+ .use(guard("add", true), async (c) => {
303
+ const input = await Issue.data(c);
304
+ if (!input || input.issues) throw new Issue("passkey request");
305
+ const session = await state(c).session();
306
+ // a passkey outlasts the session that adds it, so only a person
307
+ // who has just signed in adds one, not whoever holds an old session
308
+ if (!session || !(await state(c).recent(10 * Time.minute)))
309
+ return c.text("Sign in again to add a passkey.", 401);
310
+ const [[account], exclude] = await Promise.all([
311
+ options.database
312
+ .sql`SELECT * FROM ${users} WHERE ${users.columns.id!} = ${session.user}`,
313
+ storage.credentials.list(session.user),
314
+ ]);
315
+ await Passkey.issue(c, state(c), input.data.bootstrap, {
316
+ method: "register",
317
+ action: paths.passkey,
318
+ name: name((account ?? {}) as Field.Parse.Data<Shape>),
319
+ user: session.user,
320
+ exclude,
321
+ });
322
+ });
323
+ /** The parameter of the authentication page a link's token is in */
324
+ const linked = "_link";
325
+ const link = Route.post(paths.link)
326
+ .fields({ link: Field.hidden() })
327
+ .use(guard("link"), async (c) => {
328
+ const input = await Issue.data(c);
329
+ if (!input || input.issues) throw new Issue("link request");
330
+ // once, and only at the origin it was made for
331
+ const user = await storage.links.take(input.data.link, options.origin);
332
+ if (!user) throw new Issue("link");
333
+ await enter(c, user);
334
+ });
218
335
  const routes = [
219
336
  register,
220
337
  login,
221
338
  logout,
339
+ add,
340
+ link,
222
341
  registration,
223
342
  assertion,
343
+ adding,
224
344
  Passkey.client,
225
345
  ];
226
346
  return {
227
347
  routes,
348
+ /** Make a link that signs a user in once, see `Auth.link`. */
349
+ async link(
350
+ user: string,
351
+ { origin = options.origin }: { origin?: string } = {},
352
+ ) {
353
+ const target = new URL(page, origin);
354
+ if (target.protocol !== "https:" || target.origin !== origin)
355
+ throw new TypeError("A link's origin must be an HTTPS origin");
356
+
357
+ const token = Token.random();
358
+ await storage.links.set(token, {
359
+ user,
360
+ origin,
361
+ // long enough to copy and open, and no longer: it signs in
362
+ // without a passkey
363
+ expiration: Date.now() + 5 * Time.minute,
364
+ });
365
+ target.searchParams.set(linked, token);
366
+ return target.href;
367
+ },
228
368
  /** Create forms in the handler before returning JSX, so ovr can set the binding cookie. */
229
369
  forms(
230
370
  c: Auth.Context,
@@ -261,17 +401,53 @@ export function configure<U extends Auth.Users>(
261
401
  ? `Too many authentication requests. ${wait ? `Try again in ${wait} seconds.` : "Try again now."}${method === "register" ? " If you already registered, sign in." : ""}`
262
402
  : method === "register"
263
403
  ? "Registration could not be completed. If you already registered, sign in; otherwise try again."
264
- : "Authentication failed. Try again."
404
+ : method === "add"
405
+ ? "The passkey could not be added. Try again."
406
+ : method === "link"
407
+ ? "This link has expired or was already used."
408
+ : "Authentication failed. Try again."
265
409
  : undefined),
266
410
  });
411
+ // another passkey for the account signed in, such as on a new device
412
+ const Add = passkey.form(add, "register", {
413
+ ...props,
414
+ endpoint: adding.url(),
415
+ submit: "Add passkey",
416
+ });
267
417
  Register.Issue = error("register", Register.Issue);
268
418
  Login.Issue = error("login", Login.Issue);
419
+ Add.Issue = error("add", Add.Issue);
420
+ // a link's token, from the address the link opened
421
+ const token = c.url.searchParams.get(linked);
422
+ // the page's address holds the token, so it is sent to no other site
423
+ if (token) c.res.headers.set("referrer-policy", "no-referrer");
424
+ const Link = Object.assign(
425
+ (props: Parameters<typeof link.Form>[0]) =>
426
+ (token || failure === "link") &&
427
+ jsx(link.Form, {
428
+ ...props,
429
+ children: [
430
+ token && [
431
+ jsx("input", { type: "hidden", name: "link", value: token }),
432
+ props.children ?? jsx("button", { children: "Sign in" }),
433
+ ],
434
+ Link.Issue({}),
435
+ ],
436
+ }),
437
+ {
438
+ Issue: error("link", (props: Parameters<typeof Add.Issue>[0]) =>
439
+ jsx("p", { role: "status", "aria-live": "polite", ...props }),
440
+ ),
441
+ },
442
+ );
269
443
  return {
270
444
  Register: Object.assign(Register, {
271
445
  Field: fields.Field,
272
446
  Fields: fields.Fields,
273
447
  }),
274
448
  Login,
449
+ Add,
450
+ Link,
275
451
  Logout: (props: Parameters<typeof logout.Form>[0]) =>
276
452
  jsx(logout.Form, {
277
453
  ...props,
package/src/auth/index.ts CHANGED
@@ -37,6 +37,21 @@ export namespace Auth {
37
37
  Login: Route.Form<string> & {
38
38
  Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
39
39
  };
40
+ /**
41
+ * Adds another passkey to the account signed in, such as on a new
42
+ * device. Pass `state={c.url}` to return to the page it is on.
43
+ */
44
+ Add: Route.Form<string> & {
45
+ Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
46
+ };
47
+ /**
48
+ * Signs in with a link from `auth.link`, on the authentication `page`
49
+ * the link opens. It is a button, so only a person uses the link, and
50
+ * renders nothing on a page opened without one.
51
+ */
52
+ Link: ((props: JSX.IntrinsicElements["form"]) => JSX.Element) & {
53
+ Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
54
+ };
40
55
  Logout: Route.Form<string>;
41
56
  }
42
57
 
@@ -203,6 +218,12 @@ export namespace Auth {
203
218
  eligible: boolean;
204
219
  /** Current backup state, which may change. */
205
220
  backedUp: boolean;
221
+ /** When it was made, in milliseconds. */
222
+ created: number;
223
+ /** Origin it was made at, the only one it signs in at. */
224
+ origin: string;
225
+ /** What the person called it when adding it, such as "Laptop". */
226
+ name: string | null;
206
227
  }
207
228
  }
208
229
 
@@ -227,6 +248,7 @@ export class Auth<
227
248
  Storage.challenges,
228
249
  Limiter.table,
229
250
  Storage.tokens,
251
+ Storage.links,
230
252
  ] as const;
231
253
 
232
254
  readonly #options: State.Options;
@@ -251,6 +273,27 @@ export class Auth<
251
273
  props?: { nonce?: string },
252
274
  ) => Auth.Forms<Auth.Fields<U>>;
253
275
 
276
+ /**
277
+ * Make a link that signs a user in once, for when they have no passkey
278
+ * where they need one: at another origin that shares the users table,
279
+ * such as production after registering on `localhost`, or after losing
280
+ * their device. It opens the authentication `page`, where `<Link />` from
281
+ * `auth.forms(c)` signs them in, and they add a passkey.
282
+ *
283
+ * Anyone who has the link is the user until it is used or expires, so
284
+ * make one only for a user your code has already identified, and send it
285
+ * the way you would a password. It is best kept to a script or an admin
286
+ * page, not a form any signed-in user can use in production.
287
+ *
288
+ * @param user ID of the user it signs in
289
+ * @param options The origin it is opened at, this one by default
290
+ * @returns The link, which lasts 5 minutes
291
+ */
292
+ readonly link: (
293
+ user: string,
294
+ options?: { origin?: string },
295
+ ) => Promise<string>;
296
+
254
297
  /** Configure passkeys, session helpers, and automatic authentication rate limits. */
255
298
  constructor(options: Auth.Options<U, P, R, C>) {
256
299
  const origin = new URL(options.origin);
@@ -291,6 +334,7 @@ export class Auth<
291
334
  const signin = oauth(options, storage, (c) => this.#state(c), resources);
292
335
  this.#routes = service.routes;
293
336
  this.forms = service.forms;
337
+ this.link = service.link;
294
338
  this.consent = signin.consent;
295
339
  this[agents] = {
296
340
  origin: options.origin,
@@ -44,6 +44,8 @@ export namespace Passkey {
44
44
  readonly nonce?: string;
45
45
  /** Form fields the ceremony is for, from `Passkey.fields`, checked when it starts. */
46
46
  readonly fields?: string;
47
+ /** Text of the form's own button, in place of the method's. */
48
+ readonly submit?: string;
47
49
  }
48
50
  /** The ceremony a signed form may start. */
49
51
  export type Expected = {
@@ -56,6 +58,10 @@ export namespace Passkey {
56
58
  method: "register";
57
59
  /** Name of the new passkey, at most 256 characters, not blank */
58
60
  name: string;
61
+ /** The account the passkey is added to, a new account without it */
62
+ user?: string;
63
+ /** Credential IDs the account has, which the authenticator skips */
64
+ exclude?: readonly string[];
59
65
  }
60
66
  | {
61
67
  method: "login";
@@ -138,7 +144,9 @@ export class Passkey {
138
144
  props.children ?? [
139
145
  route.Fields?.(),
140
146
  jsx("button", {
141
- children: method === "register" ? "Create account" : "Log in",
147
+ children:
148
+ options.submit ??
149
+ (method === "register" ? "Create account" : "Log in"),
142
150
  }),
143
151
  ],
144
152
  // A supplied Issue component takes precedence over this accessible fallback.
@@ -244,10 +252,9 @@ export class Passkey {
244
252
  throw new Issue("bootstrap binding");
245
253
  // the same method as the form's, checked above
246
254
  const register = expected.method === "register";
247
- if (
248
- register &&
249
- (!bootstrap.user || Codec.encode(bootstrap.user).length > 64)
250
- )
255
+ // an account that is signed in, or the new one the form was made for
256
+ const user = (register && expected.user) || bootstrap.user;
257
+ if (register && (!user || Codec.encode(user).length > 64))
251
258
  throw new Issue("user");
252
259
  const rp = new URL(auth.options.origin).hostname;
253
260
  const ceremony = crypto.randomUUID();
@@ -260,7 +267,7 @@ export class Passkey {
260
267
  action: bootstrap.action,
261
268
  origin: bootstrap.origin,
262
269
  expiration: Date.now() + 2 * Time.minute,
263
- ...(bootstrap.user ? { user: bootstrap.user } : {}),
270
+ ...(user ? { user } : {}),
264
271
  ...(expected.fields ? { fields: expected.fields } : {}),
265
272
  })) === false
266
273
  ) {
@@ -274,11 +281,18 @@ export class Passkey {
274
281
  challenge,
275
282
  rp: { id: rp, name: rp },
276
283
  user: {
277
- id: Codec.Base64Url.encode(Codec.encode(bootstrap.user!)),
284
+ id: Codec.Base64Url.encode(Codec.encode(user!)),
278
285
  name: expected.name,
279
286
  displayName: expected.name,
280
287
  },
281
288
  pubKeyCredParams: [{ type: "public-key", alg: -7 }],
289
+ // an authenticator that holds one of the account's makes no other
290
+ ...(expected.exclude?.length && {
291
+ excludeCredentials: expected.exclude.map((id) => ({
292
+ type: "public-key" as const,
293
+ id,
294
+ })),
295
+ }),
282
296
  authenticatorSelection: {
283
297
  residentKey: "required",
284
298
  requireResidentKey: true,
@@ -486,6 +500,10 @@ export class Passkey {
486
500
  counter: data.counter,
487
501
  eligible: Boolean(data.flags & 8),
488
502
  backedUp: Boolean(data.flags & 16),
503
+ created: Date.now(),
504
+ origin: this.#auth.options.origin,
505
+ // what a person calls one they add
506
+ name: null as string | null,
489
507
  };
490
508
  }
491
509
 
package/src/auth/state.ts CHANGED
@@ -113,8 +113,10 @@ export class State {
113
113
  session.id === id &&
114
114
  session.expiration > now &&
115
115
  session.started + this.options.lifetime > now
116
- )
116
+ ) {
117
+ this.#started = session.started;
117
118
  return this.#renew(session, now);
119
+ }
118
120
  this.#clear();
119
121
  return null;
120
122
  }
@@ -146,6 +148,19 @@ export class State {
146
148
  return (this.#session ??= this.#read());
147
149
  }
148
150
 
151
+ /** When the browser's session signed in, once it is read */
152
+ #started: number | undefined;
153
+
154
+ /**
155
+ * @param within Milliseconds
156
+ * @returns `true` when the person signed in that recently, in this
157
+ * browser: what a session taken over later cannot say
158
+ */
159
+ async recent(within: number) {
160
+ await this.session();
161
+ return this.#started !== undefined && Date.now() - this.#started <= within;
162
+ }
163
+
149
164
  /**
150
165
  * Return to a local path after the next login, such as an agent's
151
166
  * authorization request, or the page that sent the user to log in. Any
@@ -181,12 +196,22 @@ export class State {
181
196
  * another host, short enough for a cookie
182
197
  */
183
198
  static #local(path: string) {
184
- return (
185
- path.startsWith("/") &&
186
- !path.startsWith("//") &&
187
- !path.includes("\\") &&
188
- path.length <= 2048
189
- );
199
+ if (
200
+ !path.startsWith("/") ||
201
+ path.startsWith("//") ||
202
+ path.includes("\\") ||
203
+ path.length > 2048
204
+ )
205
+ return false;
206
+
207
+ // as a browser reads it: it drops tabs and new lines, so `/\t/host` is
208
+ // `//host`, another site
209
+ const base = "https://local.invalid";
210
+ try {
211
+ return new URL(path, base).origin === base;
212
+ } catch {
213
+ return false;
214
+ }
190
215
  }
191
216
 
192
217
  /** Replace the current session and issue a new signed, secure cookie. */
@@ -95,6 +95,18 @@ export class Storage {
95
95
  counter: Schema.number().int(),
96
96
  eligible: Schema.boolean(),
97
97
  backedUp: Schema.boolean(),
98
+ // what tells an account's passkeys apart
99
+ created: Schema.number().int(),
100
+ origin: Schema.string(),
101
+ name: Schema.string().nullable(),
102
+ });
103
+
104
+ /** One-time sign-in links, by the hash of their token. */
105
+ static readonly links = new Table("auth_links", {
106
+ id: Schema.string(),
107
+ user: Schema.string(),
108
+ origin: Schema.string(),
109
+ expiration: Schema.number().int(),
98
110
  });
99
111
 
100
112
  /** Revocable sessions. */
@@ -148,7 +160,10 @@ export class Storage {
148
160
  "publicKey" text NOT NULL,
149
161
  counter bigint NOT NULL,
150
162
  eligible boolean NOT NULL,
151
- "backedUp" boolean NOT NULL
163
+ "backedUp" boolean NOT NULL,
164
+ created bigint NOT NULL,
165
+ origin text NOT NULL,
166
+ name text
152
167
  );
153
168
  CREATE INDEX auth_credentials_user ON auth_credentials ("user");
154
169
 
@@ -189,7 +204,16 @@ CREATE TABLE auth_tokens (
189
204
  );
190
205
  CREATE INDEX auth_tokens_family ON auth_tokens (family);
191
206
  CREATE INDEX auth_tokens_user ON auth_tokens ("user");
192
- CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
207
+ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);
208
+
209
+ CREATE TABLE auth_links (
210
+ id text PRIMARY KEY,
211
+ "user" text NOT NULL,
212
+ origin text NOT NULL,
213
+ expiration bigint NOT NULL
214
+ );
215
+ CREATE INDEX auth_links_user ON auth_links ("user");
216
+ CREATE INDEX auth_links_expiration ON auth_links (expiration);`,
193
217
  },
194
218
  ] as const;
195
219
 
@@ -198,6 +222,7 @@ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
198
222
  Storage.credentials,
199
223
  Storage.sessions,
200
224
  Storage.tokens,
225
+ Storage.links,
201
226
  ] as const;
202
227
 
203
228
  static {
@@ -245,7 +270,11 @@ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
245
270
  if (Math.abs(now - this.#pruned) < Time.minute) return;
246
271
 
247
272
  this.#pruned = now;
248
- const tables: Table<string, any>[] = [Storage.challenges, Storage.sessions];
273
+ const tables: Table<string, any>[] = [
274
+ Storage.challenges,
275
+ Storage.sessions,
276
+ Storage.links,
277
+ ];
249
278
  if (this.#oauth) tables.push(Storage.tokens);
250
279
  for (const table of tables)
251
280
  await this.#db.sql`DELETE FROM ${table} WHERE expiration <= ${now}`;
@@ -554,6 +583,40 @@ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
554
583
  },
555
584
  };
556
585
 
586
+ readonly links = {
587
+ /**
588
+ * @param token Link's token, stored by its hash
589
+ * @param link Who it signs in, where, and until when
590
+ */
591
+ set: async (
592
+ token: string,
593
+ link: { user: string; origin: string; expiration: number },
594
+ ) => {
595
+ await this.#prune();
596
+ await this.#db
597
+ .sql`INSERT INTO ${Storage.links} ${this.#db.sql.values(Storage.links, { ...link, id: await Storage.hash(token) })}`;
598
+ },
599
+ /**
600
+ * Uses a link once: concurrent calls have one winner.
601
+ *
602
+ * @param token Link's token
603
+ * @param origin Origin it is opened at
604
+ * @returns The user it signs in, nothing when it is used, expired, or
605
+ * for another origin
606
+ */
607
+ take: async (token: string, origin: string) => {
608
+ const { columns } = Storage.links;
609
+ const [row] = await this.#db.sql`
610
+ DELETE FROM ${Storage.links}
611
+ WHERE ${columns.id} = ${await Storage.hash(token)}
612
+ AND ${columns.origin} = ${origin} AND ${columns.expiration} > ${Date.now()}
613
+ RETURNING *
614
+ `.parse(Storage.links);
615
+
616
+ return row?.user;
617
+ },
618
+ };
619
+
557
620
  /**
558
621
  * Create the account and its first credential in one transaction.
559
622
  *
@@ -17,12 +17,11 @@ export const agent = new WeakMap<
17
17
  Request,
18
18
  {
19
19
  readonly session?: unknown;
20
+ /** The fields the tool call gave, which are all it updates */
21
+ readonly sent?: ReadonlySet<string>;
20
22
  issues?: readonly { readonly path: string; readonly message: string }[];
21
23
  /** The tool a form submits to and its arguments, so a page points to it */
22
- readonly tool?: (
23
- method: string,
24
- action: URL,
25
- ) => { name: string; args: Record<string, string> } | undefined;
24
+ readonly tool?: Markdown.Options[typeof tools];
26
25
  }
27
26
  >();
28
27
 
@@ -341,6 +340,8 @@ export class Context<
341
340
  post
342
341
  ? this.multipart({ parts: form.parts, ...options })
343
342
  : this.url.searchParams,
343
+ [],
344
+ agent.get(this.req)?.sent,
344
345
  );
345
346
 
346
347
  /**
@@ -440,8 +441,15 @@ export class Context<
440
441
  const [mime] = Header.shift(res.headers.get(Header.name.type));
441
442
 
442
443
  if (!mime || mime === Mime.type.html) {
443
- // pages are HTML for browsers and Markdown for agents that ask for it
444
- if (this.#markdown()) {
444
+ // pages are HTML for browsers and Markdown for agents that ask for
445
+ // it, but a file to download, such as a page to print, is HTML
446
+ // for both
447
+ if (
448
+ !/^\s*attachment/i.test(
449
+ res.headers.get("content-disposition") ?? "",
450
+ ) &&
451
+ this.#markdown()
452
+ ) {
445
453
  res.body = Markdown.stream(r, {
446
454
  base: this.url,
447
455
  [tools]: agent.get(this.req)?.tool,