@udibo/oauth2 0.49.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.
- package/dist/identity/delivery.d.ts +6 -0
- package/dist/identity/events.d.ts +1 -1
- package/dist/identity/mod.d.ts +4 -1
- package/dist/identity/mod.js +3 -0
- package/dist/identity/service.d.ts +39 -4
- package/dist/identity/service.js +53 -9
- package/dist/identity/sign-in-link-binding.d.ts +78 -0
- package/dist/identity/sign-in-link-binding.js +83 -0
- package/dist/identity/token-flow.d.ts +5 -1
- package/dist/testing/contract/token-flow-store.js +5 -1
- package/package.json +1 -1
|
@@ -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;
|
package/dist/identity/mod.d.ts
CHANGED
|
@@ -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,8 +54,9 @@ 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
|
-
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";
|
|
57
60
|
export { EmailOtpService, type EmailOtpServiceOptions, MemoryOtpStore, type OtpRecord, type OtpStore, type RequestedOtp, type RequestOtpOptions, type VerifyOtpOptions, type VerifyOtpResult, } from "./otp.ts";
|
|
58
61
|
export { AccountLockout, type AccountLockoutLike, type AccountLockoutOptions, type LockoutFailureResult, type LockoutRecord, type LockoutStatus, type LockoutStore, MemoryLockoutStore, type MemoryLockoutStoreOptions, } from "./lockout.ts";
|
|
59
62
|
export type { IdentityEvent, IdentityEventHook, SignInCodeFailureReason, SignInFailureReason, } from "./events.ts";
|
package/dist/identity/mod.js
CHANGED
|
@@ -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,16 +395,37 @@ 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}.
|
|
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.
|
|
399
403
|
*/
|
|
400
404
|
export type ConsumeSignInLinkResult = {
|
|
401
405
|
status: "success";
|
|
402
406
|
userId: string;
|
|
407
|
+
email?: string;
|
|
403
408
|
} | {
|
|
404
409
|
status: "expired";
|
|
405
410
|
} | {
|
|
406
411
|
status: "invalid";
|
|
412
|
+
} | {
|
|
413
|
+
status: "other-browser";
|
|
407
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
|
+
}
|
|
408
429
|
/**
|
|
409
430
|
* Outcome of {@link IdentityService.verifySignInCode}. Deliberately only
|
|
410
431
|
* `success` vs `invalid`: a known email whose code expired or hit its attempt
|
|
@@ -632,21 +653,35 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
632
653
|
* key `pwless:<email>`) when a `rateLimiter` — or a tighter
|
|
633
654
|
* `rateLimiters.signInLink` — is configured; throws {@link IdentityError}
|
|
634
655
|
* `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
|
|
656
|
+
*
|
|
657
|
+
* Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
|
|
658
|
+
* requesting browser: the token stores it, the link's URL carries it as the
|
|
659
|
+
* {@link SIGN_IN_LINK_BINDING_PARAM} query parameter and the delivery message
|
|
660
|
+
* as `binding`. {@link IdentityService.consumeSignInLink} then redeems the
|
|
661
|
+
* link only given that browser's `nonce`.
|
|
635
662
|
*/
|
|
636
663
|
requestSignInLink(email: string, options?: {
|
|
637
664
|
ttlMs?: number;
|
|
665
|
+
binding?: string;
|
|
638
666
|
}): Promise<void>;
|
|
639
667
|
/**
|
|
640
668
|
* 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 —
|
|
669
|
+
* to sign in and the `email` the link was sent to; establishing the session — and running your MFA gate first —
|
|
642
670
|
* stays your app's job. So does re-resolving the user: a user deleted or
|
|
643
671
|
* disabled since the link was minted must be treated as `invalid` by your
|
|
644
672
|
* user store, not signed in. `expired` and `invalid` are distinguished so
|
|
645
673
|
* the UI can offer a fresh link. A link whose address no longer finds this
|
|
646
674
|
* user through {@link IdentityUserStore.findByEmail} — the account's email
|
|
647
675
|
* moved after it was mailed — reports `invalid` and stays unspent.
|
|
648
|
-
|
|
649
|
-
|
|
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>;
|
|
650
685
|
/**
|
|
651
686
|
* Passwordless request: always resolves with the same `void` result. If the
|
|
652
687
|
* email maps to a user, mints a one-time numeric code (invalidating any
|
package/dist/identity/service.js
CHANGED
|
@@ -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, verifySignInLinkBinding, } 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 token stores it, the link's URL carries it as the
|
|
535
|
+
* {@link SIGN_IN_LINK_BINDING_PARAM} query parameter and the delivery message
|
|
536
|
+
* as `binding`. {@link IdentityService.consumeSignInLink} then redeems the
|
|
537
|
+
* link only given that browser's `nonce`.
|
|
531
538
|
*/
|
|
532
539
|
async requestSignInLink(email, options) {
|
|
533
540
|
const tokens = this.#requireTokens("requestSignInLink");
|
|
@@ -548,19 +555,27 @@ 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
|
|
559
567
|
* the UI can offer a fresh link. A link whose address no longer finds this
|
|
560
568
|
* user through {@link IdentityUserStore.findByEmail} — the account's email
|
|
561
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.
|
|
562
577
|
*/
|
|
563
|
-
async consumeSignInLink(token) {
|
|
578
|
+
async consumeSignInLink(token, options) {
|
|
564
579
|
const tokens = this.#requireTokens("consumeSignInLink");
|
|
565
580
|
const result = await this.#consumeToken({
|
|
566
581
|
tokens,
|
|
@@ -568,12 +583,20 @@ export class IdentityService {
|
|
|
568
583
|
token,
|
|
569
584
|
failed: (reason) => ({ type: "signin_link.failed", reason }),
|
|
570
585
|
addressBound: true,
|
|
586
|
+
refuse: (_subject, data) => otherBrowserRefusal(data, options),
|
|
571
587
|
});
|
|
588
|
+
if (result.status === "other-browser") {
|
|
589
|
+
await this.#emit({ type: "signin_link.failed", reason: "other_browser" });
|
|
590
|
+
return result;
|
|
591
|
+
}
|
|
572
592
|
if (result.status !== "success")
|
|
573
593
|
return result;
|
|
574
594
|
const userId = result.resolved.subject;
|
|
595
|
+
const email = emailFromData(result.resolved.data);
|
|
575
596
|
await this.#emit({ type: "signin_link.consumed", userId });
|
|
576
|
-
return
|
|
597
|
+
return email === undefined
|
|
598
|
+
? { status: "success", userId }
|
|
599
|
+
: { status: "success", userId, email };
|
|
577
600
|
}
|
|
578
601
|
/**
|
|
579
602
|
* Passwordless request: always resolves with the same `void` result. If the
|
|
@@ -851,11 +874,13 @@ export class IdentityService {
|
|
|
851
874
|
const { token, expiresAt } = await tokens.create({
|
|
852
875
|
purpose: DELIVERY_PURPOSES[request.hook],
|
|
853
876
|
subject: request.subject,
|
|
854
|
-
data:
|
|
877
|
+
data: request.binding === undefined
|
|
878
|
+
? { email: request.to }
|
|
879
|
+
: { email: request.to, binding: request.binding },
|
|
855
880
|
ttlMs: request.ttlMs,
|
|
856
881
|
invalidateExisting: true,
|
|
857
882
|
});
|
|
858
|
-
await this.#deliver(request.hook, request.to, token, request.subject, expiresAt);
|
|
883
|
+
await this.#deliver(request.hook, request.to, token, request.subject, expiresAt, request.binding);
|
|
859
884
|
await this.#emit(request.requested);
|
|
860
885
|
}
|
|
861
886
|
async #consumeToken(input) {
|
|
@@ -871,7 +896,7 @@ export class IdentityService {
|
|
|
871
896
|
await this.#emit(input.failed("invalid"));
|
|
872
897
|
return { status: "invalid" };
|
|
873
898
|
}
|
|
874
|
-
const refusal = input.refuse?.(status.subject);
|
|
899
|
+
const refusal = input.refuse?.(status.subject, status.data);
|
|
875
900
|
if (refusal)
|
|
876
901
|
return { status: refusal };
|
|
877
902
|
await input.beforeConsume?.(status.subject, status.data);
|
|
@@ -903,15 +928,18 @@ export class IdentityService {
|
|
|
903
928
|
}
|
|
904
929
|
return this.#otp;
|
|
905
930
|
}
|
|
906
|
-
async #deliver(hook, to, token, subject, expiresAt) {
|
|
931
|
+
async #deliver(hook, to, token, subject, expiresAt, binding) {
|
|
907
932
|
const delivery = this.#delivery;
|
|
908
933
|
const send = delivery?.[hook];
|
|
909
934
|
if (!send)
|
|
910
935
|
return;
|
|
911
936
|
const url = this.#baseUrl
|
|
912
|
-
? URL_BUILDERS[hook](this.#baseUrl, token)
|
|
937
|
+
? withBinding(URL_BUILDERS[hook](this.#baseUrl, token), binding)
|
|
913
938
|
: undefined;
|
|
914
|
-
|
|
939
|
+
const message = { to, url, token, subject, expiresAt };
|
|
940
|
+
if (binding !== undefined)
|
|
941
|
+
message.binding = binding;
|
|
942
|
+
await this.#trapDeliveryFailure(hook, () => send.call(delivery, message), async () => {
|
|
915
943
|
await this.#tokens?.consume(DELIVERY_PURPOSES[hook], token);
|
|
916
944
|
});
|
|
917
945
|
}
|
|
@@ -975,6 +1003,22 @@ async function logVoidFailure(credential, invalidate) {
|
|
|
975
1003
|
`${credential}, usable until expiry:`, error instanceof Error ? error.message : error);
|
|
976
1004
|
}
|
|
977
1005
|
}
|
|
1006
|
+
function withBinding(url, binding) {
|
|
1007
|
+
if (binding === undefined)
|
|
1008
|
+
return url;
|
|
1009
|
+
const bound = new URL(url);
|
|
1010
|
+
bound.searchParams.set(SIGN_IN_LINK_BINDING_PARAM, binding);
|
|
1011
|
+
return bound.toString();
|
|
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
|
+
}
|
|
978
1022
|
function emailFromData(data) {
|
|
979
1023
|
const email = data?.email;
|
|
980
1024
|
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. 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
|
+
*
|
|
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
|
+
*
|
|
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. {@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
|
+
*
|
|
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. 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
|
+
*
|
|
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
|
+
*
|
|
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. {@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
|
+
*
|
|
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
|
+
}
|
|
@@ -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
|
-
/**
|
|
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: {
|
|
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.
|
|
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",
|