@udibo/oauth2 0.50.0 → 0.51.0

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.
@@ -190,7 +190,7 @@ export type IdentityEvent = {
190
190
  userId: string;
191
191
  } | {
192
192
  type: "signin_link.failed";
193
- reason: "expired" | "invalid";
193
+ reason: "expired" | "invalid" | "other_browser";
194
194
  } | {
195
195
  type: "signin_link.rate_limited";
196
196
  email: string;
@@ -56,7 +56,7 @@ export { type CreatedToken, type CreateTokenOptions, MemoryTokenFlowStore, type
56
56
  export { buildResetUrl, buildSignInUrl, buildTokenUrl, buildUnlockUrl, buildVerificationUrl, type CodeDeliveryHook, type CodeDeliveryMessage, type DeliveryHook, type DeliveryHooks, type DeliveryMessage, } from "./delivery.ts";
57
57
  export { createSignInLinkBinding, SIGN_IN_LINK_BINDING_PARAM, type SignInLinkBinding, verifySignInLinkBinding, } from "./sign-in-link-binding.ts";
58
58
  export { isRecentlyAuthenticated, type ListableSessionService, type RevocableSessionService, type SessionSummary, supportsSessionListing, } from "./session.ts";
59
- export { type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
59
+ export { type ConsumeSignInLinkOptions, type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
60
60
  export { EmailOtpService, type EmailOtpServiceOptions, MemoryOtpStore, type OtpRecord, type OtpStore, type RequestedOtp, type RequestOtpOptions, type VerifyOtpOptions, type VerifyOtpResult, } from "./otp.ts";
61
61
  export { AccountLockout, type AccountLockoutLike, type AccountLockoutOptions, type LockoutFailureResult, type LockoutRecord, type LockoutStatus, type LockoutStore, MemoryLockoutStore, type MemoryLockoutStoreOptions, } from "./lockout.ts";
62
62
  export type { IdentityEvent, IdentityEventHook, SignInCodeFailureReason, SignInFailureReason, } from "./events.ts";
@@ -398,6 +398,8 @@ export interface VerifyEmailInput {
398
398
  * one. No session is created — do that in your app on `success`. `email` is
399
399
  * the address the link was sent to, as it was requested; it is absent only for
400
400
  * a link minted without one through {@link TokenFlowService.create}.
401
+ * `other-browser` means the link is live but was asked for in another browser;
402
+ * it stays unspent, so the browser that asked can still use it.
401
403
  */
402
404
  export type ConsumeSignInLinkResult = {
403
405
  status: "success";
@@ -407,7 +409,23 @@ export type ConsumeSignInLinkResult = {
407
409
  status: "expired";
408
410
  } | {
409
411
  status: "invalid";
412
+ } | {
413
+ status: "other-browser";
410
414
  };
415
+ /** Options for {@link IdentityService.consumeSignInLink}. */
416
+ export interface ConsumeSignInLinkOptions {
417
+ /**
418
+ * The sign-in link nonce the opening browser holds (from
419
+ * {@link createSignInLinkBinding}, typically read from its cookie). A link
420
+ * requested with a `binding` redeems only when this nonce hashes to it.
421
+ */
422
+ nonce?: string | null;
423
+ /**
424
+ * Refuse a link minted without a binding as `other-browser`, as well as a
425
+ * mismatched one. Set it once every link your app sends is bound.
426
+ */
427
+ requireBinding?: boolean;
428
+ }
411
429
  /**
412
430
  * Outcome of {@link IdentityService.verifySignInCode}. Deliberately only
413
431
  * `success` vs `invalid`: a known email whose code expired or hit its attempt
@@ -637,10 +655,10 @@ export declare class IdentityService<User extends IdentityUser> {
637
655
  * `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
638
656
  *
639
657
  * Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
640
- * requesting browser: the link's URL carries it as the
658
+ * requesting browser: the token stores it, the link's URL carries it as the
641
659
  * {@link SIGN_IN_LINK_BINDING_PARAM} query parameter and the delivery message
642
- * as `binding`. Check it with {@link verifySignInLinkBinding} before
643
- * {@link IdentityService.consumeSignInLink}.
660
+ * as `binding`. {@link IdentityService.consumeSignInLink} then redeems the
661
+ * link only given that browser's `nonce`.
644
662
  */
645
663
  requestSignInLink(email: string, options?: {
646
664
  ttlMs?: number;
@@ -655,8 +673,15 @@ export declare class IdentityService<User extends IdentityUser> {
655
673
  * the UI can offer a fresh link. A link whose address no longer finds this
656
674
  * user through {@link IdentityUserStore.findByEmail} — the account's email
657
675
  * moved after it was mailed — reports `invalid` and stays unspent.
658
- */
659
- consumeSignInLink(token: string): Promise<ConsumeSignInLinkResult>;
676
+ *
677
+ * A link requested with a `binding` redeems only when `options.nonce` is the
678
+ * nonce that binding was made from; any other nonce, or none, reports
679
+ * `other-browser` and leaves the link unspent. The check runs against the
680
+ * binding stored with the token, so it holds against someone who has the
681
+ * link and sets a nonce of their own. An expired or spent link reports
682
+ * `expired` or `invalid` whatever the nonce.
683
+ */
684
+ consumeSignInLink(token: string, options?: ConsumeSignInLinkOptions): Promise<ConsumeSignInLinkResult>;
660
685
  /**
661
686
  * Passwordless request: always resolves with the same `void` result. If the
662
687
  * email maps to a user, mints a one-time numeric code (invalidating any
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import { delay } from "../utils/_delay.js";
21
21
  import { buildResetUrl, buildSignInUrl, buildUnlockUrl, buildVerificationUrl, } from "./delivery.js";
22
- import { SIGN_IN_LINK_BINDING_PARAM } from "./sign-in-link-binding.js";
22
+ import { SIGN_IN_LINK_BINDING_PARAM, verifySignInLinkBinding, } from "./sign-in-link-binding.js";
23
23
  import { PasswordIdentityService, } from "./password.js";
24
24
  import { TokenPurpose, } from "./token-flow.js";
25
25
  import { assertPasswordPolicy, } from "./password-policy.js";
@@ -531,10 +531,10 @@ export class IdentityService {
531
531
  * `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
532
532
  *
533
533
  * Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
534
- * requesting browser: the link's URL carries it as the
534
+ * requesting browser: the token stores it, the link's URL carries it as the
535
535
  * {@link SIGN_IN_LINK_BINDING_PARAM} query parameter and the delivery message
536
- * as `binding`. Check it with {@link verifySignInLinkBinding} before
537
- * {@link IdentityService.consumeSignInLink}.
536
+ * as `binding`. {@link IdentityService.consumeSignInLink} then redeems the
537
+ * link only given that browser's `nonce`.
538
538
  */
539
539
  async requestSignInLink(email, options) {
540
540
  const tokens = this.#requireTokens("requestSignInLink");
@@ -567,8 +567,15 @@ export class IdentityService {
567
567
  * the UI can offer a fresh link. A link whose address no longer finds this
568
568
  * user through {@link IdentityUserStore.findByEmail} — the account's email
569
569
  * moved after it was mailed — reports `invalid` and stays unspent.
570
+ *
571
+ * A link requested with a `binding` redeems only when `options.nonce` is the
572
+ * nonce that binding was made from; any other nonce, or none, reports
573
+ * `other-browser` and leaves the link unspent. The check runs against the
574
+ * binding stored with the token, so it holds against someone who has the
575
+ * link and sets a nonce of their own. An expired or spent link reports
576
+ * `expired` or `invalid` whatever the nonce.
570
577
  */
571
- async consumeSignInLink(token) {
578
+ async consumeSignInLink(token, options) {
572
579
  const tokens = this.#requireTokens("consumeSignInLink");
573
580
  const result = await this.#consumeToken({
574
581
  tokens,
@@ -576,7 +583,12 @@ export class IdentityService {
576
583
  token,
577
584
  failed: (reason) => ({ type: "signin_link.failed", reason }),
578
585
  addressBound: true,
586
+ refuse: (_subject, data) => otherBrowserRefusal(data, options),
579
587
  });
588
+ if (result.status === "other-browser") {
589
+ await this.#emit({ type: "signin_link.failed", reason: "other_browser" });
590
+ return result;
591
+ }
580
592
  if (result.status !== "success")
581
593
  return result;
582
594
  const userId = result.resolved.subject;
@@ -862,7 +874,9 @@ export class IdentityService {
862
874
  const { token, expiresAt } = await tokens.create({
863
875
  purpose: DELIVERY_PURPOSES[request.hook],
864
876
  subject: request.subject,
865
- data: { email: request.to },
877
+ data: request.binding === undefined
878
+ ? { email: request.to }
879
+ : { email: request.to, binding: request.binding },
866
880
  ttlMs: request.ttlMs,
867
881
  invalidateExisting: true,
868
882
  });
@@ -882,7 +896,7 @@ export class IdentityService {
882
896
  await this.#emit(input.failed("invalid"));
883
897
  return { status: "invalid" };
884
898
  }
885
- const refusal = input.refuse?.(status.subject);
899
+ const refusal = input.refuse?.(status.subject, status.data);
886
900
  if (refusal)
887
901
  return { status: refusal };
888
902
  await input.beforeConsume?.(status.subject, status.data);
@@ -996,6 +1010,15 @@ function withBinding(url, binding) {
996
1010
  bound.searchParams.set(SIGN_IN_LINK_BINDING_PARAM, binding);
997
1011
  return bound.toString();
998
1012
  }
1013
+ function otherBrowserRefusal(data, options) {
1014
+ const binding = data?.binding;
1015
+ if (typeof binding !== "string") {
1016
+ return options?.requireBinding ? "other-browser" : null;
1017
+ }
1018
+ return verifySignInLinkBinding(options?.nonce, binding)
1019
+ ? null
1020
+ : "other-browser";
1021
+ }
999
1022
  function emailFromData(data) {
1000
1023
  const email = data?.email;
1001
1024
  return typeof email === "string" ? email : undefined;
@@ -3,17 +3,17 @@
3
3
  *
4
4
  * When a browser asks for a sign-in email, {@link createSignInLinkBinding}
5
5
  * returns a random `nonce` for your app to keep in that browser (an `HttpOnly`
6
- * cookie) and its `binding`, the SHA-256 of the nonce, for the link to carry
7
- * (pass it to {@link IdentityService.requestSignInLink}). When the link is
8
- * opened, {@link verifySignInLinkBinding} checks the browser's nonce against
9
- * the link's binding before you hand the token to
10
- * {@link IdentityService.consumeSignInLink}, so a refusal leaves the link
11
- * unspent and still usable in the browser that asked for it.
6
+ * cookie) and its `binding`, the SHA-256 of the nonce. Pass the binding to
7
+ * {@link IdentityService.requestSignInLink}, which stores it with the token and
8
+ * puts it on the link. When the link is opened, pass the browser's nonce to
9
+ * {@link IdentityService.consumeSignInLink}: it redeems the link only when the
10
+ * nonce hashes to the stored binding, and otherwise leaves the link unspent and
11
+ * still usable in the browser that asked for it.
12
12
  *
13
- * The binding is not a secret: it keeps a link from signing in a browser that
14
- * did not ask for it, and is no protection once someone else holds the link.
15
- * Keep the nonce in a `__Host-` prefixed cookie so another subdomain cannot
16
- * plant one.
13
+ * The binding is not a secret. Because the check runs against the binding
14
+ * stored with the token, holding the link and setting a nonce of one's own is
15
+ * not enough to redeem it. Keep the nonce in a `__Host-` prefixed cookie so
16
+ * another subdomain cannot plant one.
17
17
  *
18
18
  * @module
19
19
  */
@@ -55,9 +55,9 @@ export declare function createSignInLinkBinding(nonce?: string | null): SignInLi
55
55
  /**
56
56
  * Whether a link carrying `binding` was asked for by the browser holding
57
57
  * `nonce`. Compares in constant time and is `false` when either value is
58
- * missing or the nonce is malformed. Call it before
59
- * {@link IdentityService.consumeSignInLink}, so a link opened elsewhere is
60
- * refused without its token being read or spent.
58
+ * missing or the nonce is malformed. {@link IdentityService.consumeSignInLink}
59
+ * runs this check against the binding stored with the token when given a
60
+ * `nonce`; call it yourself only to compare a binding you hold separately.
61
61
  *
62
62
  * @param nonce The nonce the opening browser holds, if any.
63
63
  * @param binding The binding the link carries, if any.
@@ -3,17 +3,17 @@
3
3
  *
4
4
  * When a browser asks for a sign-in email, {@link createSignInLinkBinding}
5
5
  * returns a random `nonce` for your app to keep in that browser (an `HttpOnly`
6
- * cookie) and its `binding`, the SHA-256 of the nonce, for the link to carry
7
- * (pass it to {@link IdentityService.requestSignInLink}). When the link is
8
- * opened, {@link verifySignInLinkBinding} checks the browser's nonce against
9
- * the link's binding before you hand the token to
10
- * {@link IdentityService.consumeSignInLink}, so a refusal leaves the link
11
- * unspent and still usable in the browser that asked for it.
6
+ * cookie) and its `binding`, the SHA-256 of the nonce. Pass the binding to
7
+ * {@link IdentityService.requestSignInLink}, which stores it with the token and
8
+ * puts it on the link. When the link is opened, pass the browser's nonce to
9
+ * {@link IdentityService.consumeSignInLink}: it redeems the link only when the
10
+ * nonce hashes to the stored binding, and otherwise leaves the link unspent and
11
+ * still usable in the browser that asked for it.
12
12
  *
13
- * The binding is not a secret: it keeps a link from signing in a browser that
14
- * did not ask for it, and is no protection once someone else holds the link.
15
- * Keep the nonce in a `__Host-` prefixed cookie so another subdomain cannot
16
- * plant one.
13
+ * The binding is not a secret. Because the check runs against the binding
14
+ * stored with the token, holding the link and setting a nonce of one's own is
15
+ * not enough to redeem it. Keep the nonce in a `__Host-` prefixed cookie so
16
+ * another subdomain cannot plant one.
17
17
  *
18
18
  * @module
19
19
  */
@@ -56,9 +56,9 @@ export function createSignInLinkBinding(nonce) {
56
56
  /**
57
57
  * Whether a link carrying `binding` was asked for by the browser holding
58
58
  * `nonce`. Compares in constant time and is `false` when either value is
59
- * missing or the nonce is malformed. Call it before
60
- * {@link IdentityService.consumeSignInLink}, so a link opened elsewhere is
61
- * refused without its token being read or spent.
59
+ * missing or the nonce is malformed. {@link IdentityService.consumeSignInLink}
60
+ * runs this check against the binding stored with the token when given a
61
+ * `nonce`; call it yourself only to compare a binding you hold separately.
62
62
  *
63
63
  * @param nonce The nonce the opening browser holds, if any.
64
64
  * @param binding The binding the link carries, if any.
@@ -29,7 +29,11 @@ export interface TokenFlowRecord {
29
29
  purpose: string;
30
30
  /** The subject the token acts on (typically a user id). */
31
31
  subject: string;
32
- /** Optional extra payload (e.g. the email being verified). */
32
+ /**
33
+ * Optional extra payload (e.g. the email being verified, a sign-in link's
34
+ * browser binding). A store must persist the whole object, every key
35
+ * included: identity flows enforce checks against keys beyond `email`.
36
+ */
33
37
  data?: Record<string, unknown>;
34
38
  /** Expiry, epoch ms. */
35
39
  expiresAt: number;
@@ -74,7 +74,11 @@ export function runTokenFlowStoreContractTests(options) {
74
74
  it("round-trips every field of a saved record", async () => {
75
75
  const saved = record({
76
76
  tokenHash: hash("1"),
77
- data: { email: "user@example.com" },
77
+ data: {
78
+ email: "user@example.com",
79
+ binding: "a-sign-in-link-binding",
80
+ nested: { list: [1, "two"] },
81
+ },
78
82
  });
79
83
  await store.save(saved);
80
84
  const fetched = await store.get(hash("1"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.50.0",
3
+ "version": "0.51.0",
4
4
  "description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), Express adapters, and React bindings.",
5
5
  "keywords": [
6
6
  "authorization-server",