ovr 7.0.0-next.14 → 7.0.0-next.16

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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # ovr
2
2
 
3
+ ## 7.0.0-next.16
4
+
5
+ ### Minor Changes
6
+
7
+ - 9d8f561: - A passkey has what tells it apart in a list: `created`, the `origin` it was made at, and a `name`, which the `Add` form takes as an optional field.
8
+ - `auth.link(user, { origin, minutes })` makes a link that signs a user in once, for an origin where they have no passkey or after losing their device. It opens the authentication `page`, where `<Link />` from `auth.forms(c)` is the button that signs them in. Only the link's hash is stored, in the new `auth_links` table.
9
+ - `auth:1` changed for these, since v7 is not released: `auth_credentials` has three more columns and `auth_links` is new. A database migrated with an earlier prerelease needs the same changes made by hand, and the migration's checksum updated.
10
+
11
+ ## 7.0.0-next.15
12
+
13
+ ### Minor Changes
14
+
15
+ - 3d16902: `auth.forms(c)` has an `Add` form that adds another passkey to the account signed in, such as for a second device or one that replaces a lost device. It asks for a passkey for the same account, skips an authenticator that already holds one of the account's, and returns to the page it is on. The docs show how to remove a passkey and how to sign a user in once at a new origin so they can add one there.
16
+
3
17
  ## 7.0.0-next.14
4
18
 
5
19
  ### Patch Changes
@@ -9,17 +9,31 @@ import type { Storage } from "./storage.js";
9
9
  * @template U Users table
10
10
  */
11
11
  export declare function configure<U extends Auth.Users>(options: Auth.Options<U>, storage: Storage, state: (c: State.Context) => State): {
12
- routes: (Route.Used<Route.Get<"/_passkey/client.js", {}, Field.Shape>> | Route.Used<Route.Post<"/_passkey/options/login", {}, {
12
+ routes: (Route.Used<Route.Get<"/_passkey/client.js", {}, Field.Shape>> | Route.Used<Route.Post<"/_passkey/options/add", {}, {
13
+ name: Field.Instance<string | undefined, "input", "text", undefined, undefined, undefined>;
14
+ bootstrap: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
15
+ }>> | Route.Used<Route.Post<"/_passkey/options/login", {}, {
13
16
  bootstrap: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
14
17
  }>> | Route.Used<Route.Post<"/_passkey/options/register", {}, {
15
18
  bootstrap: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
19
+ }>> | Route.Used<Route.Post<"/auth/link", {}, {
20
+ link: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
16
21
  }>> | Route.Used<Route.Post<"/auth/login", {}, {
17
22
  credential: Field.Instance<unknown, "input", "hidden", undefined, undefined, undefined>;
18
23
  ceremony: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
19
- }>> | Route.Used<Route.Post<"/auth/logout", {}, Field.Shape>> | Route.Used<Route.Post<"/auth/register", {}, {
24
+ }>> | Route.Used<Route.Post<"/auth/logout", {}, Field.Shape>> | Route.Used<Route.Post<"/auth/passkey", {}, {
25
+ credential: Field.Instance<unknown, "input", "hidden", undefined, undefined, undefined>;
26
+ ceremony: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
27
+ name: Field.Instance<string | undefined, "input", "text", undefined, undefined, undefined>;
28
+ }>> | Route.Used<Route.Post<"/auth/register", {}, {
20
29
  credential: Field.Instance<unknown, "input", "hidden", undefined, undefined, undefined>;
21
30
  ceremony: Field.Instance<string, "input", "hidden", undefined, undefined, undefined>;
22
31
  }>>)[];
32
+ /** Make a link that signs a user in once, see `Auth.link`. */
33
+ link(user: string, { origin, minutes, }?: {
34
+ origin?: string;
35
+ minutes?: number;
36
+ }): Promise<string>;
23
37
  /** Create forms in the handler before returning JSX, so ovr can set the binding cookie. */
24
38
  forms(c: Auth.Context, props?: {
25
39
  nonce?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"configure.d.ts","sourceRoot":"","sources":["../../src/auth/configure.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAsB,MAAM,kBAAkB,CAAC;AAI7D,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,KAAK,EAAE,IAAI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AE;IAiBzC,2FAA2F;aAEvF,IAAI,CAAC,OAAO,UACR;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GACvB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;EAqF9B"}
@@ -6,6 +6,7 @@ import { Route } from "../route/index.js";
6
6
  import { Header, Time, noStore } from "../util/index.js";
7
7
  import { Issue } from "./issue.js";
8
8
  import { Passkey } from "./passkey.js";
9
+ import { Token } from "./token.js";
9
10
  /**
10
11
  * Construct startup-complete handlers and request-scoped UI components.
11
12
  *
@@ -29,11 +30,14 @@ export function configure(options, storage, state) {
29
30
  const limits = {
30
31
  register: limiter("register", 5, 10 * Time.minute),
31
32
  login: limiter("login", 20, Time.minute),
33
+ add: limiter("add", 5, 10 * Time.minute),
32
34
  };
33
35
  const paths = {
34
36
  register: "/auth/register",
35
37
  login: "/auth/login",
36
38
  logout: "/auth/logout",
39
+ passkey: "/auth/passkey",
40
+ link: "/auth/link",
37
41
  options: "/_passkey/options",
38
42
  };
39
43
  const page = options.page ?? "/login";
@@ -68,15 +72,24 @@ export function configure(options, storage, state) {
68
72
  }
69
73
  return used;
70
74
  };
75
+ /** @returns The page a form was on, if it said, or where a login goes */
76
+ const returning = (c) => {
77
+ const target = new URL(c.url.searchParams.get(Form.params[0]) ?? redirect, options.origin);
78
+ return target.origin === options.origin
79
+ ? target
80
+ : new URL(redirect, options.origin);
81
+ };
71
82
  const back = (c, method, retry = 0) => {
72
- const target = new URL(page, options.origin);
83
+ // a passkey is added from a page of the account, not the login page
84
+ const target = method === "add" ? returning(c) : new URL(page, options.origin);
73
85
  target.searchParams.set("_auth", method);
74
86
  if (retry)
75
87
  target.searchParams.set("_retry", String(retry));
76
88
  c.redirect(target, 303);
77
89
  };
78
90
  const admit = async (c, method, prompt) => {
79
- const admission = await limits[method].check(c, prompt ? "options" : "verify");
91
+ // a link signs in, so it shares a login's limit
92
+ const admission = await limits[method === "link" ? "login" : method].check(c, prompt ? "options" : "verify");
80
93
  if (admission === true)
81
94
  return true;
82
95
  const now = Date.now();
@@ -203,16 +216,103 @@ export function configure(options, storage, state) {
203
216
  action: paths.login,
204
217
  });
205
218
  });
219
+ /** What a person calls a passkey they add, such as "Laptop" */
220
+ const naming = {
221
+ name: Field.text()
222
+ .max(64)
223
+ .optional()
224
+ .label("Name")
225
+ .hint("Such as the device it is on"),
226
+ };
227
+ const add = Route.post(paths.passkey)
228
+ .fields({ ...naming, ...Passkey.shape })
229
+ .use(guard("add"), async (c) => {
230
+ const input = await Issue.data(c);
231
+ if (!input || input.issues)
232
+ throw new Issue("passkey request");
233
+ const session = await state(c).session();
234
+ if (!session)
235
+ throw new Issue("session");
236
+ const credential = await new Passkey(c, state(c)).register();
237
+ // the account that started the ceremony is still the one signed in
238
+ if (credential.user !== session.user)
239
+ throw new Issue("user");
240
+ await storage
241
+ .register(() => { }, {
242
+ ...credential,
243
+ name: input.data.name?.trim() || null,
244
+ })
245
+ .catch((error) => {
246
+ // a passkey that is already an account's
247
+ if (Database.unique(error))
248
+ throw new Issue("passkey");
249
+ throw error;
250
+ });
251
+ c.redirect(returning(c), 303);
252
+ });
253
+ const adding = Route.post(`${paths.options}/add`)
254
+ // the form's own field is sent with it, and saved when it submits
255
+ .fields({ ...naming, bootstrap: Field.hidden() })
256
+ .use(guard("add", true), async (c) => {
257
+ const input = await Issue.data(c);
258
+ if (!input || input.issues)
259
+ throw new Issue("passkey request");
260
+ const session = await state(c).session();
261
+ if (!session)
262
+ return c.text("Sign in to add a passkey.", 401);
263
+ const [account] = await options.database
264
+ .sql `SELECT * FROM ${users} WHERE ${users.columns.id} = ${session.user}`;
265
+ await Passkey.issue(c, state(c), input.data.bootstrap, {
266
+ method: "register",
267
+ action: paths.passkey,
268
+ name: name((account ?? {})),
269
+ user: session.user,
270
+ exclude: await storage.credentials.list(session.user),
271
+ });
272
+ });
273
+ /** The parameter of the authentication page a link's token is in */
274
+ const linked = "_link";
275
+ const link = Route.post(paths.link)
276
+ .fields({ link: Field.hidden() })
277
+ .use(guard("link"), async (c) => {
278
+ const input = await Issue.data(c);
279
+ if (!input || input.issues)
280
+ throw new Issue("link request");
281
+ // once, and only at the origin it was made for
282
+ const user = await storage.links.take(input.data.link, options.origin);
283
+ if (!user)
284
+ throw new Issue("link");
285
+ await enter(c, user);
286
+ });
206
287
  const routes = [
207
288
  register,
208
289
  login,
209
290
  logout,
291
+ add,
292
+ link,
210
293
  registration,
211
294
  assertion,
295
+ adding,
212
296
  Passkey.client,
213
297
  ];
214
298
  return {
215
299
  routes,
300
+ /** Make a link that signs a user in once, see `Auth.link`. */
301
+ async link(user, { origin = options.origin, minutes = 10, } = {}) {
302
+ const target = new URL(page, origin);
303
+ if (target.protocol !== "https:" || target.origin !== origin)
304
+ throw new TypeError("A link's origin must be an HTTPS origin");
305
+ if (!(minutes > 0 && minutes <= 60))
306
+ throw new TypeError("A link lasts at most 60 minutes");
307
+ const token = Token.random();
308
+ await storage.links.set(token, {
309
+ user,
310
+ origin,
311
+ expiration: Date.now() + minutes * Time.minute,
312
+ });
313
+ target.searchParams.set(linked, token);
314
+ return target.href;
315
+ },
216
316
  /** Create forms in the handler before returning JSX, so ovr can set the binding cookie. */
217
317
  forms(c, props = {}) {
218
318
  const passkey = new Passkey(c, state(c));
@@ -242,17 +342,45 @@ export function configure(options, storage, state) {
242
342
  ? `Too many authentication requests. ${wait ? `Try again in ${wait} seconds.` : "Try again now."}${method === "register" ? " If you already registered, sign in." : ""}`
243
343
  : method === "register"
244
344
  ? "Registration could not be completed. If you already registered, sign in; otherwise try again."
245
- : "Authentication failed. Try again."
345
+ : method === "add"
346
+ ? "The passkey could not be added. Try again."
347
+ : method === "link"
348
+ ? "This link has expired or was already used."
349
+ : "Authentication failed. Try again."
246
350
  : undefined),
247
351
  });
352
+ // another passkey for the account signed in, such as on a new device
353
+ const Add = passkey.form(add, "register", {
354
+ ...props,
355
+ endpoint: adding.url(),
356
+ submit: "Add passkey",
357
+ });
248
358
  Register.Issue = error("register", Register.Issue);
249
359
  Login.Issue = error("login", Login.Issue);
360
+ Add.Issue = error("add", Add.Issue);
361
+ // a link's token, from the address the link opened
362
+ const token = c.url.searchParams.get(linked);
363
+ const Link = Object.assign((props) => (token || failure === "link") &&
364
+ jsx(link.Form, {
365
+ ...props,
366
+ children: [
367
+ token && [
368
+ jsx("input", { type: "hidden", name: "link", value: token }),
369
+ props.children ?? jsx("button", { children: "Sign in" }),
370
+ ],
371
+ Link.Issue({}),
372
+ ],
373
+ }), {
374
+ Issue: error("link", (props) => jsx("p", { role: "status", "aria-live": "polite", ...props })),
375
+ });
250
376
  return {
251
377
  Register: Object.assign(Register, {
252
378
  Field: fields.Field,
253
379
  Fields: fields.Fields,
254
380
  }),
255
381
  Login,
382
+ Add,
383
+ Link,
256
384
  Logout: (props) => jsx(logout.Form, {
257
385
  ...props,
258
386
  children: props.children ?? jsx("button", { children: "Log out" }),
@@ -29,6 +29,21 @@ export declare namespace Auth {
29
29
  Login: Route.Form<string> & {
30
30
  Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
31
31
  };
32
+ /**
33
+ * Adds another passkey to the account signed in, such as on a new
34
+ * device. Pass `state={c.url}` to return to the page it is on.
35
+ */
36
+ Add: Route.Form<string> & {
37
+ Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
38
+ };
39
+ /**
40
+ * Signs in with a link from `auth.link`, on the authentication `page`
41
+ * the link opens. It is a button, so only a person uses the link, and
42
+ * renders nothing on a page opened without one.
43
+ */
44
+ Link: ((props: JSX.IntrinsicElements["form"]) => JSX.Element) & {
45
+ Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
46
+ };
32
47
  Logout: Route.Form<string>;
33
48
  }
34
49
  /** A revocable session with a fixed lifetime, from `c.session()`. */
@@ -152,6 +167,12 @@ export declare namespace Auth {
152
167
  eligible: boolean;
153
168
  /** Current backup state, which may change. */
154
169
  backedUp: boolean;
170
+ /** When it was made, in milliseconds. */
171
+ created: number;
172
+ /** Origin it was made at, the only one it signs in at. */
173
+ origin: string;
174
+ /** What the person called it when adding it, such as "Laptop". */
175
+ name: string | null;
155
176
  }
156
177
  export {};
157
178
  }
@@ -173,6 +194,9 @@ export declare class Auth<U extends Auth.Users = Auth.Users, P extends string =
173
194
  counter: Schema<number>;
174
195
  eligible: Schema<boolean>;
175
196
  backedUp: Schema<boolean>;
197
+ created: Schema<number>;
198
+ origin: Schema<string>;
199
+ name: Schema<string | null>;
176
200
  }, {}>, Table<"auth_sessions", {
177
201
  id: Schema<string>;
178
202
  user: Schema<string>;
@@ -204,6 +228,11 @@ export declare class Auth<U extends Auth.Users = Auth.Users, P extends string =
204
228
  challenge: Schema<string | null>;
205
229
  family: Schema<string>;
206
230
  expiration: Schema<number>;
231
+ }, {}>, Table<"auth_links", {
232
+ id: Schema<string>;
233
+ user: Schema<string>;
234
+ origin: Schema<string>;
235
+ expiration: Schema<number>;
207
236
  }, {}>];
208
237
  /**
209
238
  * Read an agent's authorization request on the consent page, with the form
@@ -216,6 +245,26 @@ export declare class Auth<U extends Auth.Users = Auth.Users, P extends string =
216
245
  readonly forms: (c: Auth.Context, props?: {
217
246
  nonce?: string;
218
247
  }) => Auth.Forms<Auth.Fields<U>>;
248
+ /**
249
+ * Make a link that signs a user in once, for when they have no passkey
250
+ * where they need one: at another origin that shares the users table,
251
+ * such as production after registering on `localhost`, or after losing
252
+ * their device. It opens the authentication `page`, where `<Link />` from
253
+ * `auth.forms(c)` signs them in, and they add a passkey.
254
+ *
255
+ * Anyone who has the link is the user until it is used or expires, so
256
+ * make one only for a user your code has already identified, and send it
257
+ * the way you would a password.
258
+ *
259
+ * @param user ID of the user it signs in
260
+ * @param options The origin it is opened at, this one by default, and how
261
+ * many minutes it lasts, 10 by default and at most 60
262
+ * @returns The link
263
+ */
264
+ readonly link: (user: string, options?: {
265
+ origin?: string;
266
+ minutes?: number;
267
+ }) => Promise<string>;
219
268
  /** Configure passkeys, session helpers, and automatic authentication rate limits. */
220
269
  constructor(options: Auth.Options<U, P, R, C>);
221
270
  /** Mounted by `app.use(auth)`, and lets every request read its session. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,KAAK,OAAO,IAAI,WAAW,EAAY,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,KAAK,QAAQ,EAAc,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAQ/C,yBAAiB,IAAI,CAAC;IACrB,uCAAuC;IAEvC,qEAAqE;IACrE,MAAM,MAAM,OAAO,GAAG,IAAI,CACzB,WAAW,EACX,KAAK,GAAG,QAAQ,GAAG,KAAK,GAAG,WAAW,CACtC,GAAG;QAAE,IAAI,EAAE,CAAC,OAAO,CAAC,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;KAAE,CAAC;IAClE;;;;OAIG;IACH,MAAM,WAAW,KAAK,CAAC,KAAK,SAAS,KAAK,CAAC,KAAK;QAC/C,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG;YAC9B,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC;YAC5B,MAAM,E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AAC,OAAO,KAAK,CAAC,CAAC,CAQ/C;IAgCD,2JAA2J;IAC3J,QAAQ,CAAC,KAAK,MACV,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,QAAQ,GAAG,KAAK,CAAC,QACzC,MAAM;;;;OAGX;IAEF,kFAAkF;IAClF,QAAQ,CAAC,MAAM,MAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,QAAQ,GAAG,KAAK,CAAC,mBAEhE;IAEF;;;;;;;;OAQG;IACH,QAAQ,CAAC,UAAU,MACf,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,QAAQ,GAAG,KAAK,CAAC,UACvC,MAAM,mBAKb;CACF"}
@@ -24,6 +24,7 @@ export class Auth {
24
24
  Storage.challenges,
25
25
  Limiter.table,
26
26
  Storage.tokens,
27
+ Storage.links,
27
28
  ];
28
29
  #options;
29
30
  #states = new WeakMap();
@@ -42,6 +43,23 @@ export class Auth {
42
43
  [agents];
43
44
  /** Prepare request-scoped UI in the handler before returning JSX. */
44
45
  forms;
46
+ /**
47
+ * Make a link that signs a user in once, for when they have no passkey
48
+ * where they need one: at another origin that shares the users table,
49
+ * such as production after registering on `localhost`, or after losing
50
+ * their device. It opens the authentication `page`, where `<Link />` from
51
+ * `auth.forms(c)` signs them in, and they add a passkey.
52
+ *
53
+ * Anyone who has the link is the user until it is used or expires, so
54
+ * make one only for a user your code has already identified, and send it
55
+ * the way you would a password.
56
+ *
57
+ * @param user ID of the user it signs in
58
+ * @param options The origin it is opened at, this one by default, and how
59
+ * many minutes it lasts, 10 by default and at most 60
60
+ * @returns The link
61
+ */
62
+ link;
45
63
  /** Configure passkeys, session helpers, and automatic authentication rate limits. */
46
64
  constructor(options) {
47
65
  const origin = new URL(options.origin);
@@ -77,6 +95,7 @@ export class Auth {
77
95
  const signin = oauth(options, storage, (c) => this.#state(c), resources);
78
96
  this.#routes = service.routes;
79
97
  this.forms = service.forms;
98
+ this.link = service.link;
80
99
  this.consent = signin.consent;
81
100
  this[agents] = {
82
101
  origin: options.origin,
@@ -32,6 +32,8 @@ export declare namespace Passkey {
32
32
  readonly nonce?: string;
33
33
  /** Form fields the ceremony is for, from `Passkey.fields`, checked when it starts. */
34
34
  readonly fields?: string;
35
+ /** Text of the form's own button, in place of the method's. */
36
+ readonly submit?: string;
35
37
  }
36
38
  /** The ceremony a signed form may start. */
37
39
  type Expected = {
@@ -43,6 +45,10 @@ export declare namespace Passkey {
43
45
  method: "register";
44
46
  /** Name of the new passkey, at most 256 characters, not blank */
45
47
  name: string;
48
+ /** The account the passkey is added to, a new account without it */
49
+ user?: string;
50
+ /** Credential IDs the account has, which the authenticator skips */
51
+ exclude?: readonly string[];
46
52
  } | {
47
53
  method: "login";
48
54
  /** Credential IDs a login is limited to, for a user already known */
@@ -79,6 +85,9 @@ export declare class Passkey {
79
85
  counter: number;
80
86
  eligible: boolean;
81
87
  backedUp: boolean;
88
+ created: number;
89
+ origin: string;
90
+ name: string | null;
82
91
  }>;
83
92
  /**
84
93
  * Verify login and atomically update the credential.
@@ -96,6 +105,9 @@ export declare class Passkey {
96
105
  user: string;
97
106
  publicKey: string;
98
107
  eligible: boolean;
108
+ created: number;
109
+ origin: string;
110
+ name: string | null;
99
111
  }>;
100
112
  }
101
113
  //# sourceMappingURL=passkey.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"passkey.d.ts","sourceRoot":"","sources":["../../src/auth/passkey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,KAAK,GAAG,EAAO,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAO1C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,KAAK,EAAE,KAA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
76
76
  route.Fields?.(),
77
77
  jsx("button", {
78
- children: method === "register" ? "Create account" : "Log in",
78
+ children: options.submit ??
79
+ (method === "register" ? "Create account" : "Log in"),
79
80
  }),
80
81
  ],
81
82
  // A supplied Issue component takes precedence over this accessible fallback.
@@ -155,8 +156,9 @@ export class Passkey {
155
156
  throw new Issue("bootstrap binding");
156
157
  // the same method as the form's, checked above
157
158
  const register = expected.method === "register";
158
- if (register &&
159
- (!bootstrap.user || Codec.encode(bootstrap.user).length > 64))
159
+ // an account that is signed in, or the new one the form was made for
160
+ const user = (register && expected.user) || bootstrap.user;
161
+ if (register && (!user || Codec.encode(user).length > 64))
160
162
  throw new Issue("user");
161
163
  const rp = new URL(auth.options.origin).hostname;
162
164
  const ceremony = crypto.randomUUID();
@@ -168,7 +170,7 @@ export class Passkey {
168
170
  action: bootstrap.action,
169
171
  origin: bootstrap.origin,
170
172
  expiration: Date.now() + 2 * Time.minute,
171
- ...(bootstrap.user ? { user: bootstrap.user } : {}),
173
+ ...(user ? { user } : {}),
172
174
  ...(expected.fields ? { fields: expected.fields } : {}),
173
175
  })) === false) {
174
176
  return Issue.limited(c, 60);
@@ -181,11 +183,18 @@ export class Passkey {
181
183
  challenge,
182
184
  rp: { id: rp, name: rp },
183
185
  user: {
184
- id: Codec.Base64Url.encode(Codec.encode(bootstrap.user)),
186
+ id: Codec.Base64Url.encode(Codec.encode(user)),
185
187
  name: expected.name,
186
188
  displayName: expected.name,
187
189
  },
188
190
  pubKeyCredParams: [{ type: "public-key", alg: -7 }],
191
+ // an authenticator that holds one of the account's makes no other
192
+ ...(expected.exclude?.length && {
193
+ excludeCredentials: expected.exclude.map((id) => ({
194
+ type: "public-key",
195
+ id,
196
+ })),
197
+ }),
189
198
  authenticatorSelection: {
190
199
  residentKey: "required",
191
200
  requireResidentKey: true,
@@ -341,6 +350,10 @@ export class Passkey {
341
350
  counter: data.counter,
342
351
  eligible: Boolean(data.flags & 8),
343
352
  backedUp: Boolean(data.flags & 16),
353
+ created: Date.now(),
354
+ origin: this.#auth.options.origin,
355
+ // what a person calls one they add
356
+ name: null,
344
357
  };
345
358
  }
346
359
  /**
@@ -76,6 +76,16 @@ export declare class Storage {
76
76
  counter: Schema<number>;
77
77
  eligible: Schema<boolean>;
78
78
  backedUp: Schema<boolean>;
79
+ created: Schema<number>;
80
+ origin: Schema<string>;
81
+ name: Schema<string | null>;
82
+ }, {}>;
83
+ /** One-time sign-in links, by the hash of their token. */
84
+ static readonly links: Table<"auth_links", {
85
+ id: Schema<string>;
86
+ user: Schema<string>;
87
+ origin: Schema<string>;
88
+ expiration: Schema<number>;
79
89
  }, {}>;
80
90
  /** Revocable sessions. */
81
91
  static readonly sessions: Table<"auth_sessions", {
@@ -117,6 +127,9 @@ export declare class Storage {
117
127
  counter: Schema<number>;
118
128
  eligible: Schema<boolean>;
119
129
  backedUp: Schema<boolean>;
130
+ created: Schema<number>;
131
+ origin: Schema<string>;
132
+ name: Schema<string | null>;
120
133
  }, {}>, Table<"auth_sessions", {
121
134
  id: Schema<string>;
122
135
  user: Schema<string>;
@@ -133,6 +146,11 @@ export declare class Storage {
133
146
  challenge: Schema<string | null>;
134
147
  family: Schema<string>;
135
148
  expiration: Schema<number>;
149
+ }, {}>, Table<"auth_links", {
150
+ id: Schema<string>;
151
+ user: Schema<string>;
152
+ origin: Schema<string>;
153
+ expiration: Schema<number>;
136
154
  }, {}>];
137
155
  /**
138
156
  * @param db Database containing the authentication tables
@@ -181,6 +199,26 @@ export declare class Storage {
181
199
  readonly challenges: Storage.Challenges;
182
200
  readonly sessions: Storage.Sessions;
183
201
  readonly credentials: Storage.Credentials;
202
+ readonly links: {
203
+ /**
204
+ * @param token Link's token, stored by its hash
205
+ * @param link Who it signs in, where, and until when
206
+ */
207
+ set: (token: string, link: {
208
+ user: string;
209
+ origin: string;
210
+ expiration: number;
211
+ }) => Promise<void>;
212
+ /**
213
+ * Uses a link once: concurrent calls have one winner.
214
+ *
215
+ * @param token Link's token
216
+ * @param origin Origin it is opened at
217
+ * @returns The user it signs in, nothing when it is used, expired, or
218
+ * for another origin
219
+ */
220
+ take: (token: string, origin: string) => Promise<string | undefined>;
221
+ };
184
222
  /**
185
223
  * Create the account and its first credential in one transaction.
186
224
  *
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/auth/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,QAAQ,EAIb,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC;;;;GAIG;AACH,KAAK,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEhC,yBAAiB,OAAO,CAAC;IACxB,mDAAmD;IACnD,UAAiB,SAAS;QACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;QAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC;QACtC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QACvB,4FAA4F;QAC5F,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;KACzB;IAED,qDAAqD;IACrD,UAAiB,UAAU;QAC1B,uEAAuE;QACvE,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,GAAG,MAAM,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC;QAC9D,+EAA+E;QAC/E,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC,SAAS,GA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,UACA,MAAM,QACP,MAAM,GAAG,SAAS,YACd,CACT,GAAG,EAAE,OAAO,CAAC,KAAK,KACd,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC;QAiExD;;;;;;WAMG;QACH,MAAM,SAAe,MAAM,UAAU,MAAM;QAS3C;;;WAGG;QACH,GAAG,UAAgB,MAAM;MAOxB;IAyEF,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,UAAU,CAsCrC;IAEF,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAuBjC;IAEF,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,WAAW,CAgCvC;IAEF,QAAQ,CAAC,KAAK;QACb;;;WAGG;QACH,GAAG,UACK,MAAM,QACP;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,MAAM,EAAE,MAAM,CAAC;YAAC,UAAU,EAAE,MAAM,CAAA;SAAE;QAM3D;;;;;;;WAOG;QACH,IAAI,UAAgB,MAAM,UAAU,MAAM;MAWzC;IAEF;;;;;OAKG;IACH,QAAQ,CACP,MAAM,EAAE,CAAC,CAAC,EAAE,QAAQ,CAAC,WAAW,EAAE,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,EAC/D,UAAU,EAAE,IAAI,CAAC,UAAU,iBAM3B;CACD"}
@@ -15,6 +15,17 @@ export class Storage {
15
15
  counter: Schema.number().int(),
16
16
  eligible: Schema.boolean(),
17
17
  backedUp: Schema.boolean(),
18
+ // what tells an account's passkeys apart
19
+ created: Schema.number().int(),
20
+ origin: Schema.string(),
21
+ name: Schema.string().nullable(),
22
+ });
23
+ /** One-time sign-in links, by the hash of their token. */
24
+ static links = new Table("auth_links", {
25
+ id: Schema.string(),
26
+ user: Schema.string(),
27
+ origin: Schema.string(),
28
+ expiration: Schema.number().int(),
18
29
  });
19
30
  /** Revocable sessions. */
20
31
  static sessions = new Table("auth_sessions", {
@@ -64,7 +75,10 @@ export class Storage {
64
75
  "publicKey" text NOT NULL,
65
76
  counter bigint NOT NULL,
66
77
  eligible boolean NOT NULL,
67
- "backedUp" boolean NOT NULL
78
+ "backedUp" boolean NOT NULL,
79
+ created bigint NOT NULL,
80
+ origin text NOT NULL,
81
+ name text
68
82
  );
69
83
  CREATE INDEX auth_credentials_user ON auth_credentials ("user");
70
84
 
@@ -105,7 +119,16 @@ CREATE TABLE auth_tokens (
105
119
  );
106
120
  CREATE INDEX auth_tokens_family ON auth_tokens (family);
107
121
  CREATE INDEX auth_tokens_user ON auth_tokens ("user");
108
- CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
122
+ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);
123
+
124
+ CREATE TABLE auth_links (
125
+ id text PRIMARY KEY,
126
+ "user" text NOT NULL,
127
+ origin text NOT NULL,
128
+ expiration bigint NOT NULL
129
+ );
130
+ CREATE INDEX auth_links_user ON auth_links ("user");
131
+ CREATE INDEX auth_links_expiration ON auth_links (expiration);`,
109
132
  },
110
133
  ];
111
134
  /** Tables whose rows belong to a user, and must reference the users table. */
@@ -113,6 +136,7 @@ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
113
136
  Storage.credentials,
114
137
  Storage.sessions,
115
138
  Storage.tokens,
139
+ Storage.links,
116
140
  ];
117
141
  static {
118
142
  for (const table of [...Storage.owners, Storage.challenges])
@@ -151,7 +175,11 @@ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
151
175
  if (Math.abs(now - this.#pruned) < Time.minute)
152
176
  return;
153
177
  this.#pruned = now;
154
- const tables = [Storage.challenges, Storage.sessions];
178
+ const tables = [
179
+ Storage.challenges,
180
+ Storage.sessions,
181
+ Storage.links,
182
+ ];
155
183
  if (this.#oauth)
156
184
  tables.push(Storage.tokens);
157
185
  for (const table of tables)
@@ -395,6 +423,35 @@ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
395
423
  return rows.length === 1;
396
424
  },
397
425
  };
426
+ links = {
427
+ /**
428
+ * @param token Link's token, stored by its hash
429
+ * @param link Who it signs in, where, and until when
430
+ */
431
+ set: async (token, link) => {
432
+ await this.#prune();
433
+ await this.#db
434
+ .sql `INSERT INTO ${Storage.links} ${this.#db.sql.values(Storage.links, { ...link, id: await Storage.hash(token) })}`;
435
+ },
436
+ /**
437
+ * Uses a link once: concurrent calls have one winner.
438
+ *
439
+ * @param token Link's token
440
+ * @param origin Origin it is opened at
441
+ * @returns The user it signs in, nothing when it is used, expired, or
442
+ * for another origin
443
+ */
444
+ take: async (token, origin) => {
445
+ const { columns } = Storage.links;
446
+ const [row] = await this.#db.sql `
447
+ DELETE FROM ${Storage.links}
448
+ WHERE ${columns.id} = ${await Storage.hash(token)}
449
+ AND ${columns.origin} = ${origin} AND ${columns.expiration} > ${Date.now()}
450
+ RETURNING *
451
+ `.parse(Storage.links);
452
+ return row?.user;
453
+ },
454
+ };
398
455
  /**
399
456
  * Create the account and its first credential in one transaction.
400
457
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ovr",
3
3
  "description": "Web apps anyone can use. Each route serves people a page and agents Markdown and MCP tools, with forms, Postgres, and passkey sign-in built in.",
4
- "version": "7.0.0-next.14",
4
+ "version": "7.0.0-next.16",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -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";
@@ -91,19 +95,37 @@ export function configure<U extends Auth.Users>(
91
95
  return used;
92
96
  };
93
97
 
94
- const back = (c: Pick<Context, "redirect">, method: string, retry = 0) => {
95
- const target = new URL(page, options.origin);
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);
96
117
  target.searchParams.set("_auth", method);
97
118
  if (retry) target.searchParams.set("_retry", String(retry));
98
119
  c.redirect(target, 303);
99
120
  };
100
121
 
101
122
  const admit = async (
102
- c: Limiter.Context & Pick<Context, "text" | "redirect">,
103
- method: "register" | "login",
123
+ c: Limiter.Context & Pick<Context, "text" | "redirect" | "url">,
124
+ method: "register" | "login" | "add" | "link",
104
125
  prompt: boolean,
105
126
  ) => {
106
- 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(
107
129
  c,
108
130
  prompt ? "options" : "verify",
109
131
  );
@@ -129,9 +151,12 @@ export function configure<U extends Auth.Users>(
129
151
  c.redirect(state(c).resume(redirect), 303);
130
152
  };
131
153
  const guard =
132
- (method: "register" | "login" | "logout", prompt = false) =>
154
+ (
155
+ method: "register" | "login" | "logout" | "add" | "link",
156
+ prompt = false,
157
+ ) =>
133
158
  async (
134
- c: Limiter.Context & Pick<Context, "text" | "redirect">,
159
+ c: Limiter.Context & Pick<Context, "text" | "redirect" | "url">,
135
160
  next: Middleware.Next,
136
161
  ) => {
137
162
  noStore(c.res.headers);
@@ -241,16 +266,102 @@ export function configure<U extends Auth.Users>(
241
266
  action: paths.login,
242
267
  });
243
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
+ if (!session) return c.text("Sign in to add a passkey.", 401);
307
+ const [account] = await options.database
308
+ .sql`SELECT * FROM ${users} WHERE ${users.columns.id!} = ${session.user}`;
309
+ await Passkey.issue(c, state(c), input.data.bootstrap, {
310
+ method: "register",
311
+ action: paths.passkey,
312
+ name: name((account ?? {}) as Field.Parse.Data<Shape>),
313
+ user: session.user,
314
+ exclude: await storage.credentials.list(session.user),
315
+ });
316
+ });
317
+ /** The parameter of the authentication page a link's token is in */
318
+ const linked = "_link";
319
+ const link = Route.post(paths.link)
320
+ .fields({ link: Field.hidden() })
321
+ .use(guard("link"), async (c) => {
322
+ const input = await Issue.data(c);
323
+ if (!input || input.issues) throw new Issue("link request");
324
+ // once, and only at the origin it was made for
325
+ const user = await storage.links.take(input.data.link, options.origin);
326
+ if (!user) throw new Issue("link");
327
+ await enter(c, user);
328
+ });
244
329
  const routes = [
245
330
  register,
246
331
  login,
247
332
  logout,
333
+ add,
334
+ link,
248
335
  registration,
249
336
  assertion,
337
+ adding,
250
338
  Passkey.client,
251
339
  ];
252
340
  return {
253
341
  routes,
342
+ /** Make a link that signs a user in once, see `Auth.link`. */
343
+ async link(
344
+ user: string,
345
+ {
346
+ origin = options.origin,
347
+ minutes = 10,
348
+ }: { origin?: string; minutes?: number } = {},
349
+ ) {
350
+ const target = new URL(page, origin);
351
+ if (target.protocol !== "https:" || target.origin !== origin)
352
+ throw new TypeError("A link's origin must be an HTTPS origin");
353
+ if (!(minutes > 0 && minutes <= 60))
354
+ throw new TypeError("A link lasts at most 60 minutes");
355
+
356
+ const token = Token.random();
357
+ await storage.links.set(token, {
358
+ user,
359
+ origin,
360
+ expiration: Date.now() + minutes * Time.minute,
361
+ });
362
+ target.searchParams.set(linked, token);
363
+ return target.href;
364
+ },
254
365
  /** Create forms in the handler before returning JSX, so ovr can set the binding cookie. */
255
366
  forms(
256
367
  c: Auth.Context,
@@ -287,17 +398,51 @@ export function configure<U extends Auth.Users>(
287
398
  ? `Too many authentication requests. ${wait ? `Try again in ${wait} seconds.` : "Try again now."}${method === "register" ? " If you already registered, sign in." : ""}`
288
399
  : method === "register"
289
400
  ? "Registration could not be completed. If you already registered, sign in; otherwise try again."
290
- : "Authentication failed. Try again."
401
+ : method === "add"
402
+ ? "The passkey could not be added. Try again."
403
+ : method === "link"
404
+ ? "This link has expired or was already used."
405
+ : "Authentication failed. Try again."
291
406
  : undefined),
292
407
  });
408
+ // another passkey for the account signed in, such as on a new device
409
+ const Add = passkey.form(add, "register", {
410
+ ...props,
411
+ endpoint: adding.url(),
412
+ submit: "Add passkey",
413
+ });
293
414
  Register.Issue = error("register", Register.Issue);
294
415
  Login.Issue = error("login", Login.Issue);
416
+ Add.Issue = error("add", Add.Issue);
417
+ // a link's token, from the address the link opened
418
+ const token = c.url.searchParams.get(linked);
419
+ const Link = Object.assign(
420
+ (props: Parameters<typeof link.Form>[0]) =>
421
+ (token || failure === "link") &&
422
+ jsx(link.Form, {
423
+ ...props,
424
+ children: [
425
+ token && [
426
+ jsx("input", { type: "hidden", name: "link", value: token }),
427
+ props.children ?? jsx("button", { children: "Sign in" }),
428
+ ],
429
+ Link.Issue({}),
430
+ ],
431
+ }),
432
+ {
433
+ Issue: error("link", (props: Parameters<typeof Add.Issue>[0]) =>
434
+ jsx("p", { role: "status", "aria-live": "polite", ...props }),
435
+ ),
436
+ },
437
+ );
295
438
  return {
296
439
  Register: Object.assign(Register, {
297
440
  Field: fields.Field,
298
441
  Fields: fields.Fields,
299
442
  }),
300
443
  Login,
444
+ Add,
445
+ Link,
301
446
  Logout: (props: Parameters<typeof logout.Form>[0]) =>
302
447
  jsx(logout.Form, {
303
448
  ...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.
286
+ *
287
+ * @param user ID of the user it signs in
288
+ * @param options The origin it is opened at, this one by default, and how
289
+ * many minutes it lasts, 10 by default and at most 60
290
+ * @returns The link
291
+ */
292
+ readonly link: (
293
+ user: string,
294
+ options?: { origin?: string; minutes?: number },
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
 
@@ -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
  *