@udibo/oauth2 0.49.0 → 0.50.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.
@@ -26,6 +26,12 @@ export interface DeliveryMessage {
26
26
  subject: string;
27
27
  /** Token expiry, epoch ms. */
28
28
  expiresAt: number;
29
+ /**
30
+ * The browser binding a sign-in link carries, when the app passed one to
31
+ * `IdentityService.requestSignInLink`. `url` already includes it; add it to
32
+ * a link you build from `token` yourself.
33
+ */
34
+ binding?: string;
29
35
  }
30
36
  /** A single delivery transport callback. */
31
37
  export type DeliveryHook = (message: DeliveryMessage) => Promise<void> | void;
@@ -23,6 +23,8 @@
23
23
  * - {@link createIdentifierResolver} / {@link classifyIdentifier} — accept
24
24
  * "email or username (or phone)" on a sign-in form without the bespoke branch.
25
25
  * - {@link DeliveryHooks} + URL builders — the seam your mailer/SMS plugs into.
26
+ * - {@link createSignInLinkBinding} / {@link verifySignInLinkBinding} — tie an
27
+ * emailed sign-in link to the browser that asked for it.
26
28
  * - {@link RevocableSessionService} / {@link ListableSessionService} /
27
29
  * {@link isRecentlyAuthenticated} — session revocation on credential change,
28
30
  * the optional listing half ({@link SessionSummary} rows for a "where you're
@@ -52,6 +54,7 @@ export { DEFAULT_PBKDF2_ITERATIONS, generateSalt, hashPassword, LEGACY_PBKDF2_IT
52
54
  export { classifyIdentifier, createIdentifierResolver, type IdentifierKind, type IdentifierLookups, } from "./identifier.ts";
53
55
  export { type CreatedToken, type CreateTokenOptions, MemoryTokenFlowStore, type ResolvedToken, type TokenFlowRecord, TokenFlowService, type TokenFlowStore, TokenPurpose, type TokenStatus, } from "./token-flow.ts";
54
56
  export { buildResetUrl, buildSignInUrl, buildTokenUrl, buildUnlockUrl, buildVerificationUrl, type CodeDeliveryHook, type CodeDeliveryMessage, type DeliveryHook, type DeliveryHooks, type DeliveryMessage, } from "./delivery.ts";
57
+ export { createSignInLinkBinding, SIGN_IN_LINK_BINDING_PARAM, type SignInLinkBinding, verifySignInLinkBinding, } from "./sign-in-link-binding.ts";
55
58
  export { isRecentlyAuthenticated, type ListableSessionService, type RevocableSessionService, type SessionSummary, supportsSessionListing, } from "./session.ts";
56
59
  export { type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
57
60
  export { EmailOtpService, type EmailOtpServiceOptions, MemoryOtpStore, type OtpRecord, type OtpStore, type RequestedOtp, type RequestOtpOptions, type VerifyOtpOptions, type VerifyOtpResult, } from "./otp.ts";
@@ -23,6 +23,8 @@
23
23
  * - {@link createIdentifierResolver} / {@link classifyIdentifier} — accept
24
24
  * "email or username (or phone)" on a sign-in form without the bespoke branch.
25
25
  * - {@link DeliveryHooks} + URL builders — the seam your mailer/SMS plugs into.
26
+ * - {@link createSignInLinkBinding} / {@link verifySignInLinkBinding} — tie an
27
+ * emailed sign-in link to the browser that asked for it.
26
28
  * - {@link RevocableSessionService} / {@link ListableSessionService} /
27
29
  * {@link isRecentlyAuthenticated} — session revocation on credential change,
28
30
  * the optional listing half ({@link SessionSummary} rows for a "where you're
@@ -52,6 +54,7 @@ export { DEFAULT_PBKDF2_ITERATIONS, generateSalt, hashPassword, LEGACY_PBKDF2_IT
52
54
  export { classifyIdentifier, createIdentifierResolver, } from "./identifier.js";
53
55
  export { MemoryTokenFlowStore, TokenFlowService, TokenPurpose, } from "./token-flow.js";
54
56
  export { buildResetUrl, buildSignInUrl, buildTokenUrl, buildUnlockUrl, buildVerificationUrl, } from "./delivery.js";
57
+ export { createSignInLinkBinding, SIGN_IN_LINK_BINDING_PARAM, verifySignInLinkBinding, } from "./sign-in-link-binding.js";
55
58
  export { isRecentlyAuthenticated, supportsSessionListing, } from "./session.js";
56
59
  export { IdentityService, } from "./service.js";
57
60
  export { EmailOtpService, MemoryOtpStore, } from "./otp.js";
@@ -395,11 +395,14 @@ export interface VerifyEmailInput {
395
395
  /**
396
396
  * Outcome of {@link IdentityService.consumeSignInLink}. `expired` and
397
397
  * `invalid` are distinguished so the UI can offer a fresh link for an expired
398
- * one. No session is created — do that in your app on `success`.
398
+ * one. No session is created — do that in your app on `success`. `email` is
399
+ * the address the link was sent to, as it was requested; it is absent only for
400
+ * a link minted without one through {@link TokenFlowService.create}.
399
401
  */
400
402
  export type ConsumeSignInLinkResult = {
401
403
  status: "success";
402
404
  userId: string;
405
+ email?: string;
403
406
  } | {
404
407
  status: "expired";
405
408
  } | {
@@ -632,13 +635,20 @@ export declare class IdentityService<User extends IdentityUser> {
632
635
  * key `pwless:<email>`) when a `rateLimiter` — or a tighter
633
636
  * `rateLimiters.signInLink` — is configured; throws {@link IdentityError}
634
637
  * `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
638
+ *
639
+ * Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
640
+ * requesting browser: the link's URL carries it as the
641
+ * {@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}.
635
644
  */
636
645
  requestSignInLink(email: string, options?: {
637
646
  ttlMs?: number;
647
+ binding?: string;
638
648
  }): Promise<void>;
639
649
  /**
640
650
  * Consume a sign-in link token (single-use). `success` carries the `userId`
641
- * to sign in; establishing the session — and running your MFA gate first —
651
+ * to sign in and the `email` the link was sent to; establishing the session — and running your MFA gate first —
642
652
  * stays your app's job. So does re-resolving the user: a user deleted or
643
653
  * disabled since the link was minted must be treated as `invalid` by your
644
654
  * user store, not signed in. `expired` and `invalid` are distinguished so
@@ -19,6 +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
23
  import { PasswordIdentityService, } from "./password.js";
23
24
  import { TokenPurpose, } from "./token-flow.js";
24
25
  import { assertPasswordPolicy, } from "./password-policy.js";
@@ -528,6 +529,12 @@ export class IdentityService {
528
529
  * key `pwless:<email>`) when a `rateLimiter` — or a tighter
529
530
  * `rateLimiters.signInLink` — is configured; throws {@link IdentityError}
530
531
  * `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
532
+ *
533
+ * Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
534
+ * requesting browser: the link's URL carries it as the
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}.
531
538
  */
532
539
  async requestSignInLink(email, options) {
533
540
  const tokens = this.#requireTokens("requestSignInLink");
@@ -548,11 +555,12 @@ export class IdentityService {
548
555
  email: normalized,
549
556
  userId: user.id,
550
557
  },
558
+ binding: options?.binding,
551
559
  }));
552
560
  }
553
561
  /**
554
562
  * Consume a sign-in link token (single-use). `success` carries the `userId`
555
- * to sign in; establishing the session — and running your MFA gate first —
563
+ * to sign in and the `email` the link was sent to; establishing the session — and running your MFA gate first —
556
564
  * stays your app's job. So does re-resolving the user: a user deleted or
557
565
  * disabled since the link was minted must be treated as `invalid` by your
558
566
  * user store, not signed in. `expired` and `invalid` are distinguished so
@@ -572,8 +580,11 @@ export class IdentityService {
572
580
  if (result.status !== "success")
573
581
  return result;
574
582
  const userId = result.resolved.subject;
583
+ const email = emailFromData(result.resolved.data);
575
584
  await this.#emit({ type: "signin_link.consumed", userId });
576
- return { status: "success", userId };
585
+ return email === undefined
586
+ ? { status: "success", userId }
587
+ : { status: "success", userId, email };
577
588
  }
578
589
  /**
579
590
  * Passwordless request: always resolves with the same `void` result. If the
@@ -855,7 +866,7 @@ export class IdentityService {
855
866
  ttlMs: request.ttlMs,
856
867
  invalidateExisting: true,
857
868
  });
858
- await this.#deliver(request.hook, request.to, token, request.subject, expiresAt);
869
+ await this.#deliver(request.hook, request.to, token, request.subject, expiresAt, request.binding);
859
870
  await this.#emit(request.requested);
860
871
  }
861
872
  async #consumeToken(input) {
@@ -903,15 +914,18 @@ export class IdentityService {
903
914
  }
904
915
  return this.#otp;
905
916
  }
906
- async #deliver(hook, to, token, subject, expiresAt) {
917
+ async #deliver(hook, to, token, subject, expiresAt, binding) {
907
918
  const delivery = this.#delivery;
908
919
  const send = delivery?.[hook];
909
920
  if (!send)
910
921
  return;
911
922
  const url = this.#baseUrl
912
- ? URL_BUILDERS[hook](this.#baseUrl, token)
923
+ ? withBinding(URL_BUILDERS[hook](this.#baseUrl, token), binding)
913
924
  : undefined;
914
- await this.#trapDeliveryFailure(hook, () => send.call(delivery, { to, url, token, subject, expiresAt }), async () => {
925
+ const message = { to, url, token, subject, expiresAt };
926
+ if (binding !== undefined)
927
+ message.binding = binding;
928
+ await this.#trapDeliveryFailure(hook, () => send.call(delivery, message), async () => {
915
929
  await this.#tokens?.consume(DELIVERY_PURPOSES[hook], token);
916
930
  });
917
931
  }
@@ -975,6 +989,13 @@ async function logVoidFailure(credential, invalidate) {
975
989
  `${credential}, usable until expiry:`, error instanceof Error ? error.message : error);
976
990
  }
977
991
  }
992
+ function withBinding(url, binding) {
993
+ if (binding === undefined)
994
+ return url;
995
+ const bound = new URL(url);
996
+ bound.searchParams.set(SIGN_IN_LINK_BINDING_PARAM, binding);
997
+ return bound.toString();
998
+ }
978
999
  function emailFromData(data) {
979
1000
  const email = data?.email;
980
1001
  return typeof email === "string" ? email : undefined;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Binds an emailed sign-in link to the browser that asked for it.
3
+ *
4
+ * When a browser asks for a sign-in email, {@link createSignInLinkBinding}
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.
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.
17
+ *
18
+ * @module
19
+ */
20
+ /**
21
+ * The query parameter {@link IdentityService.requestSignInLink} puts a link's
22
+ * binding in, beside its `token`.
23
+ */
24
+ export declare const SIGN_IN_LINK_BINDING_PARAM = "binding";
25
+ /** A browser's sign-in link nonce and the binding its links carry. */
26
+ export interface SignInLinkBinding {
27
+ /**
28
+ * The secret the requesting browser keeps, 43 base64url characters. Store it
29
+ * where only that browser sends it back, such as an `HttpOnly` cookie; never
30
+ * put it in the link or the email.
31
+ */
32
+ nonce: string;
33
+ /** The nonce's SHA-256, base64url-encoded: what the emailed link carries. */
34
+ binding: string;
35
+ }
36
+ /**
37
+ * The nonce and binding for a sign-in email a browser asks for. Pass the nonce
38
+ * the browser already holds, if any: a well-formed one is kept, so every link
39
+ * that browser was sent while it holds the nonce still works there. Anything
40
+ * else — none, or a malformed value — is replaced by a fresh random nonce.
41
+ *
42
+ * @param nonce The nonce the requesting browser already holds, if any.
43
+ * @returns The nonce to (re)store in the browser and the binding for its link.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { createSignInLinkBinding } from "@udibo/oauth2/identity";
48
+ *
49
+ * const fresh = createSignInLinkBinding();
50
+ * const again = createSignInLinkBinding(fresh.nonce);
51
+ * again.binding === fresh.binding; // true
52
+ * ```
53
+ */
54
+ export declare function createSignInLinkBinding(nonce?: string | null): SignInLinkBinding;
55
+ /**
56
+ * Whether a link carrying `binding` was asked for by the browser holding
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.
61
+ *
62
+ * @param nonce The nonce the opening browser holds, if any.
63
+ * @param binding The binding the link carries, if any.
64
+ * @returns `true` only when `binding` is the SHA-256 of `nonce`.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * import {
69
+ * createSignInLinkBinding,
70
+ * verifySignInLinkBinding,
71
+ * } from "@udibo/oauth2/identity";
72
+ *
73
+ * const { nonce, binding } = createSignInLinkBinding();
74
+ * verifySignInLinkBinding(nonce, binding); // true
75
+ * verifySignInLinkBinding(createSignInLinkBinding().nonce, binding); // false
76
+ * ```
77
+ */
78
+ export declare function verifySignInLinkBinding(nonce: string | null | undefined, binding: string | null | undefined): boolean;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Binds an emailed sign-in link to the browser that asked for it.
3
+ *
4
+ * When a browser asks for a sign-in email, {@link createSignInLinkBinding}
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.
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.
17
+ *
18
+ * @module
19
+ */
20
+ import { createHash } from "node:crypto";
21
+ import { randomToken, timingSafeEqualString } from "../utils/crypto.js";
22
+ /**
23
+ * The query parameter {@link IdentityService.requestSignInLink} puts a link's
24
+ * binding in, beside its `token`.
25
+ */
26
+ export const SIGN_IN_LINK_BINDING_PARAM = "binding";
27
+ const NONCE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
28
+ function isSignInLinkNonce(value) {
29
+ return typeof value === "string" && NONCE_PATTERN.test(value);
30
+ }
31
+ function bindingOf(nonce) {
32
+ return createHash("sha256").update(nonce).digest("base64url");
33
+ }
34
+ /**
35
+ * The nonce and binding for a sign-in email a browser asks for. Pass the nonce
36
+ * the browser already holds, if any: a well-formed one is kept, so every link
37
+ * that browser was sent while it holds the nonce still works there. Anything
38
+ * else — none, or a malformed value — is replaced by a fresh random nonce.
39
+ *
40
+ * @param nonce The nonce the requesting browser already holds, if any.
41
+ * @returns The nonce to (re)store in the browser and the binding for its link.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import { createSignInLinkBinding } from "@udibo/oauth2/identity";
46
+ *
47
+ * const fresh = createSignInLinkBinding();
48
+ * const again = createSignInLinkBinding(fresh.nonce);
49
+ * again.binding === fresh.binding; // true
50
+ * ```
51
+ */
52
+ export function createSignInLinkBinding(nonce) {
53
+ const kept = isSignInLinkNonce(nonce) ? nonce : randomToken(32);
54
+ return { nonce: kept, binding: bindingOf(kept) };
55
+ }
56
+ /**
57
+ * Whether a link carrying `binding` was asked for by the browser holding
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.
62
+ *
63
+ * @param nonce The nonce the opening browser holds, if any.
64
+ * @param binding The binding the link carries, if any.
65
+ * @returns `true` only when `binding` is the SHA-256 of `nonce`.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import {
70
+ * createSignInLinkBinding,
71
+ * verifySignInLinkBinding,
72
+ * } from "@udibo/oauth2/identity";
73
+ *
74
+ * const { nonce, binding } = createSignInLinkBinding();
75
+ * verifySignInLinkBinding(nonce, binding); // true
76
+ * verifySignInLinkBinding(createSignInLinkBinding().nonce, binding); // false
77
+ * ```
78
+ */
79
+ export function verifySignInLinkBinding(nonce, binding) {
80
+ if (!isSignInLinkNonce(nonce) || typeof binding !== "string")
81
+ return false;
82
+ return timingSafeEqualString(binding, bindingOf(nonce));
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.49.0",
3
+ "version": "0.50.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",