@udibo/oauth2 0.48.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.
- package/dist/adapters/hono/identity.d.ts +34 -3
- package/dist/adapters/hono/identity.js +25 -11
- package/dist/identity/delivery.d.ts +6 -0
- package/dist/identity/mod.d.ts +4 -1
- package/dist/identity/mod.js +3 -0
- package/dist/identity/service.d.ts +39 -3
- package/dist/identity/service.js +43 -8
- package/dist/identity/sign-in-link-binding.d.ts +78 -0
- package/dist/identity/sign-in-link-binding.js +83 -0
- package/package.json +1 -1
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* Session creation stays in your app: the `signup`/`signin` routes call your
|
|
30
30
|
* `onAuthenticated(c, user)` hook on success, where you mint your session and
|
|
31
31
|
* return a `Response` (e.g. a redirect via `bff.loginContinuation`). Omit the
|
|
32
|
-
* hook to
|
|
32
|
+
* hook to leave those two routes unmounted. `/email/verify` reads your session
|
|
33
|
+
* through the `sessionUserId(c)` option and is mounted only when you pass it.
|
|
33
34
|
*
|
|
34
35
|
* Accepts JSON or form-encoded bodies. Responses are simple JSON
|
|
35
36
|
* (`{ ok: true }` / `{ error }`); render your own UI around them. Because a
|
|
@@ -52,7 +53,10 @@ export interface HonoIdentityPaths {
|
|
|
52
53
|
requestPasswordReset?: string;
|
|
53
54
|
/** `POST` password reset (consume token). Default `/password/reset`. */
|
|
54
55
|
resetPassword?: string;
|
|
55
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* `POST` email verification (consume token), mounted only with
|
|
58
|
+
* {@link HonoIdentityOptions.sessionUserId}. Default `/email/verify`.
|
|
59
|
+
*/
|
|
56
60
|
verifyEmail?: string;
|
|
57
61
|
}
|
|
58
62
|
/**
|
|
@@ -114,11 +118,38 @@ export interface HonoIdentityOptions<User extends IdentityUser> {
|
|
|
114
118
|
onAuthenticated?: (c: Context, user: User, action: "signUp" | "signIn") => Response | Promise<Response>;
|
|
115
119
|
/** Override the default paths. */
|
|
116
120
|
paths?: HonoIdentityPaths;
|
|
121
|
+
/**
|
|
122
|
+
* Reads the id of the user your app has signed in on this request, or
|
|
123
|
+
* `null`/`undefined` when there is no session. **Required to mount the
|
|
124
|
+
* `/email/verify` route**, which passes it to
|
|
125
|
+
* {@link IdentityService.verifyEmail}: a link verifies only for the account
|
|
126
|
+
* it was minted for. A live link posted with no session answers `401`
|
|
127
|
+
* `{ error: "sign_in_required" }`, and with another account's session `403`
|
|
128
|
+
* `{ error: "wrong_account" }`; both leave the link unspent, so send the
|
|
129
|
+
* person to sign in and post the same token again.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* import { honoIdentityRoutes } from "@udibo/oauth2/hono/identity";
|
|
134
|
+
* import type { IdentityService } from "@udibo/oauth2/identity";
|
|
135
|
+
* import type { Context } from "hono";
|
|
136
|
+
*
|
|
137
|
+
* declare const identity: IdentityService<{ id: string }>;
|
|
138
|
+
* declare function readSession(c: Context): { userId: string } | undefined;
|
|
139
|
+
*
|
|
140
|
+
* honoIdentityRoutes(identity, {
|
|
141
|
+
* sessionUserId: (c) => readSession(c)?.userId,
|
|
142
|
+
* });
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
sessionUserId?: (c: Context) => string | null | undefined | Promise<string | null | undefined>;
|
|
117
146
|
}
|
|
118
147
|
/**
|
|
119
148
|
* Build a Hono app mounting the password-credential endpoints
|
|
120
149
|
* (`/signup`, `/signin`, `/password/reset-request`, `/password/reset`,
|
|
121
|
-
* `/email/verify`) over `service`.
|
|
150
|
+
* `/email/verify`) over `service`. `/signup` and `/signin` need
|
|
151
|
+
* {@link HonoIdentityOptions.onAuthenticated}, and `/email/verify` needs
|
|
152
|
+
* {@link HonoIdentityOptions.sessionUserId}. Mount it wherever you like, e.g.
|
|
122
153
|
* `app.route("/auth", honoIdentityRoutes(service, …))`.
|
|
123
154
|
*
|
|
124
155
|
* A JSON body keeps each field's type except `password`, `identifier`, `email`,
|
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* Session creation stays in your app: the `signup`/`signin` routes call your
|
|
30
30
|
* `onAuthenticated(c, user)` hook on success, where you mint your session and
|
|
31
31
|
* return a `Response` (e.g. a redirect via `bff.loginContinuation`). Omit the
|
|
32
|
-
* hook to
|
|
32
|
+
* hook to leave those two routes unmounted. `/email/verify` reads your session
|
|
33
|
+
* through the `sessionUserId(c)` option and is mounted only when you pass it.
|
|
33
34
|
*
|
|
34
35
|
* Accepts JSON or form-encoded bodies. Responses are simple JSON
|
|
35
36
|
* (`{ ok: true }` / `{ error }`); render your own UI around them. Because a
|
|
@@ -141,7 +142,9 @@ function sameOriginGuard(options) {
|
|
|
141
142
|
/**
|
|
142
143
|
* Build a Hono app mounting the password-credential endpoints
|
|
143
144
|
* (`/signup`, `/signin`, `/password/reset-request`, `/password/reset`,
|
|
144
|
-
* `/email/verify`) over `service`.
|
|
145
|
+
* `/email/verify`) over `service`. `/signup` and `/signin` need
|
|
146
|
+
* {@link HonoIdentityOptions.onAuthenticated}, and `/email/verify` needs
|
|
147
|
+
* {@link HonoIdentityOptions.sessionUserId}. Mount it wherever you like, e.g.
|
|
145
148
|
* `app.route("/auth", honoIdentityRoutes(service, …))`.
|
|
146
149
|
*
|
|
147
150
|
* A JSON body keeps each field's type except `password`, `identifier`, `email`,
|
|
@@ -172,7 +175,7 @@ export function honoIdentityRoutes(service, options = {}) {
|
|
|
172
175
|
verifyEmail: "/email/verify",
|
|
173
176
|
...options.paths,
|
|
174
177
|
};
|
|
175
|
-
const onAuthenticated = options
|
|
178
|
+
const { onAuthenticated, sessionUserId } = options;
|
|
176
179
|
if (options.csrf !== false) {
|
|
177
180
|
app.use("*", sameOriginGuard(options.csrf ?? {}));
|
|
178
181
|
}
|
|
@@ -211,13 +214,24 @@ export function honoIdentityRoutes(service, options = {}) {
|
|
|
211
214
|
? c.json({ ok: true })
|
|
212
215
|
: c.json({ error: "invalid_token" }, 400);
|
|
213
216
|
}));
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
217
|
+
if (sessionUserId) {
|
|
218
|
+
app.post(paths.verifyEmail, handle(async (c) => {
|
|
219
|
+
const body = await readBody(c, maxBodyBytes);
|
|
220
|
+
const result = await service.verifyEmail({
|
|
221
|
+
token: String(body.token ?? ""),
|
|
222
|
+
sessionUserId: (await sessionUserId(c)) ?? null,
|
|
223
|
+
});
|
|
224
|
+
switch (result.status) {
|
|
225
|
+
case "success":
|
|
226
|
+
return c.json({ ok: true, userId: result.userId });
|
|
227
|
+
case "sign-in-required":
|
|
228
|
+
return c.json({ error: "sign_in_required" }, 401);
|
|
229
|
+
case "wrong-account":
|
|
230
|
+
return c.json({ error: "wrong_account" }, 403);
|
|
231
|
+
default:
|
|
232
|
+
return c.json({ error: `token_${result.status}` }, 400);
|
|
233
|
+
}
|
|
234
|
+
}));
|
|
235
|
+
}
|
|
222
236
|
return app;
|
|
223
237
|
}
|
|
@@ -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 VerifyEmailResult, type VerifySignInCodeResult, } from "./service.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";
|
|
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";
|
|
@@ -361,6 +361,12 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
|
|
|
361
361
|
* Outcome of {@link IdentityService.verifyEmail}. `success` carries the verified
|
|
362
362
|
* user; `expired` and `invalid` are distinguished so the UI can offer to resend
|
|
363
363
|
* an expired link rather than showing one generic error.
|
|
364
|
+
*
|
|
365
|
+
* `sign-in-required` (no session) and `wrong-account` (a session for a
|
|
366
|
+
* different user) answer a live link that was not presented by the account it
|
|
367
|
+
* was minted for. The link stays unspent and the address stays unverified, so
|
|
368
|
+
* show a sign-in prompt and let the person retry the same link once signed in
|
|
369
|
+
* as that account.
|
|
364
370
|
*/
|
|
365
371
|
export type VerifyEmailResult = {
|
|
366
372
|
status: "success";
|
|
@@ -370,15 +376,33 @@ export type VerifyEmailResult = {
|
|
|
370
376
|
status: "expired";
|
|
371
377
|
} | {
|
|
372
378
|
status: "invalid";
|
|
379
|
+
} | {
|
|
380
|
+
status: "sign-in-required";
|
|
381
|
+
} | {
|
|
382
|
+
status: "wrong-account";
|
|
373
383
|
};
|
|
384
|
+
/** Input to {@link IdentityService.verifyEmail}. */
|
|
385
|
+
export interface VerifyEmailInput {
|
|
386
|
+
/** The token from the emailed verification link. */
|
|
387
|
+
token: string;
|
|
388
|
+
/**
|
|
389
|
+
* The id of the user signed in on the request presenting the link, or
|
|
390
|
+
* `null` when it carries no session. Only that user's own link verifies;
|
|
391
|
+
* read it from your session, never from the request body.
|
|
392
|
+
*/
|
|
393
|
+
sessionUserId: string | null;
|
|
394
|
+
}
|
|
374
395
|
/**
|
|
375
396
|
* Outcome of {@link IdentityService.consumeSignInLink}. `expired` and
|
|
376
397
|
* `invalid` are distinguished so the UI can offer a fresh link for an expired
|
|
377
|
-
* 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}.
|
|
378
401
|
*/
|
|
379
402
|
export type ConsumeSignInLinkResult = {
|
|
380
403
|
status: "success";
|
|
381
404
|
userId: string;
|
|
405
|
+
email?: string;
|
|
382
406
|
} | {
|
|
383
407
|
status: "expired";
|
|
384
408
|
} | {
|
|
@@ -551,6 +575,11 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
551
575
|
/**
|
|
552
576
|
* Consume a verification token and mark the user's email verified.
|
|
553
577
|
*
|
|
578
|
+
* The token verifies only for a request signed in as the user it was minted
|
|
579
|
+
* for: pass that session's user id as `sessionUserId`. A live token with no
|
|
580
|
+
* session reports `sign-in-required`, and with another user's session
|
|
581
|
+
* `wrong-account`; both leave it unspent and the address unverified.
|
|
582
|
+
*
|
|
554
583
|
* Returns a discriminated {@link VerifyEmailResult} so the UI can tell an
|
|
555
584
|
* **expired** link (offer to resend) from a generically **invalid** one — the
|
|
556
585
|
* `inspect()` distinction, surfaced through the flow. A `valid` token is
|
|
@@ -566,7 +595,7 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
566
595
|
* store that predicates on both never verifies an address the link was not
|
|
567
596
|
* minted for.
|
|
568
597
|
*/
|
|
569
|
-
verifyEmail(
|
|
598
|
+
verifyEmail(input: VerifyEmailInput): Promise<VerifyEmailResult>;
|
|
570
599
|
/**
|
|
571
600
|
* Mint + deliver a single-use account-unlock link after a lockout. Call it
|
|
572
601
|
* with the locked account's email (typically from your `lockout` event
|
|
@@ -606,13 +635,20 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
606
635
|
* key `pwless:<email>`) when a `rateLimiter` — or a tighter
|
|
607
636
|
* `rateLimiters.signInLink` — is configured; throws {@link IdentityError}
|
|
608
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}.
|
|
609
644
|
*/
|
|
610
645
|
requestSignInLink(email: string, options?: {
|
|
611
646
|
ttlMs?: number;
|
|
647
|
+
binding?: string;
|
|
612
648
|
}): Promise<void>;
|
|
613
649
|
/**
|
|
614
650
|
* Consume a sign-in link token (single-use). `success` carries the `userId`
|
|
615
|
-
* 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 —
|
|
616
652
|
* stays your app's job. So does re-resolving the user: a user deleted or
|
|
617
653
|
* disabled since the link was minted must be treated as `invalid` by your
|
|
618
654
|
* user store, not signed in. `expired` and `invalid` are distinguished so
|
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 } 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";
|
|
@@ -32,6 +33,11 @@ const DEFAULT_VERIFY_TTL = 24 * 60 * 60 * 1000;
|
|
|
32
33
|
const DEFAULT_UNLOCK_TTL = 60 * 60 * 1000;
|
|
33
34
|
const DEFAULT_SIGNIN_LINK_TTL = 15 * 60 * 1000;
|
|
34
35
|
const DEFAULT_FAILED_SIGN_IN_FLOOR_MS = 250;
|
|
36
|
+
function sessionRefusal(sessionUserId, subject) {
|
|
37
|
+
if (!sessionUserId)
|
|
38
|
+
return "sign-in-required";
|
|
39
|
+
return sessionUserId === subject ? null : "wrong-account";
|
|
40
|
+
}
|
|
35
41
|
function foldEmail(email) {
|
|
36
42
|
return email.trim().toLowerCase();
|
|
37
43
|
}
|
|
@@ -394,6 +400,11 @@ export class IdentityService {
|
|
|
394
400
|
/**
|
|
395
401
|
* Consume a verification token and mark the user's email verified.
|
|
396
402
|
*
|
|
403
|
+
* The token verifies only for a request signed in as the user it was minted
|
|
404
|
+
* for: pass that session's user id as `sessionUserId`. A live token with no
|
|
405
|
+
* session reports `sign-in-required`, and with another user's session
|
|
406
|
+
* `wrong-account`; both leave it unspent and the address unverified.
|
|
407
|
+
*
|
|
397
408
|
* Returns a discriminated {@link VerifyEmailResult} so the UI can tell an
|
|
398
409
|
* **expired** link (offer to resend) from a generically **invalid** one — the
|
|
399
410
|
* `inspect()` distinction, surfaced through the flow. A `valid` token is
|
|
@@ -409,13 +420,14 @@ export class IdentityService {
|
|
|
409
420
|
* store that predicates on both never verifies an address the link was not
|
|
410
421
|
* minted for.
|
|
411
422
|
*/
|
|
412
|
-
async verifyEmail(
|
|
423
|
+
async verifyEmail(input) {
|
|
413
424
|
const tokens = this.#requireTokens("verifyEmail");
|
|
414
425
|
const result = await this.#consumeToken({
|
|
415
426
|
tokens,
|
|
416
427
|
purpose: TokenPurpose.EmailVerification,
|
|
417
|
-
token,
|
|
428
|
+
token: input.token,
|
|
418
429
|
failed: (reason) => ({ type: "email_verification.failed", reason }),
|
|
430
|
+
refuse: (subject) => sessionRefusal(input.sessionUserId, subject),
|
|
419
431
|
beforeConsume: (subject, data) => this.#users.markEmailVerified?.(subject, emailFromData(data)),
|
|
420
432
|
});
|
|
421
433
|
if (result.status !== "success")
|
|
@@ -517,6 +529,12 @@ export class IdentityService {
|
|
|
517
529
|
* key `pwless:<email>`) when a `rateLimiter` — or a tighter
|
|
518
530
|
* `rateLimiters.signInLink` — is configured; throws {@link IdentityError}
|
|
519
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}.
|
|
520
538
|
*/
|
|
521
539
|
async requestSignInLink(email, options) {
|
|
522
540
|
const tokens = this.#requireTokens("requestSignInLink");
|
|
@@ -537,11 +555,12 @@ export class IdentityService {
|
|
|
537
555
|
email: normalized,
|
|
538
556
|
userId: user.id,
|
|
539
557
|
},
|
|
558
|
+
binding: options?.binding,
|
|
540
559
|
}));
|
|
541
560
|
}
|
|
542
561
|
/**
|
|
543
562
|
* Consume a sign-in link token (single-use). `success` carries the `userId`
|
|
544
|
-
* 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 —
|
|
545
564
|
* stays your app's job. So does re-resolving the user: a user deleted or
|
|
546
565
|
* disabled since the link was minted must be treated as `invalid` by your
|
|
547
566
|
* user store, not signed in. `expired` and `invalid` are distinguished so
|
|
@@ -561,8 +580,11 @@ export class IdentityService {
|
|
|
561
580
|
if (result.status !== "success")
|
|
562
581
|
return result;
|
|
563
582
|
const userId = result.resolved.subject;
|
|
583
|
+
const email = emailFromData(result.resolved.data);
|
|
564
584
|
await this.#emit({ type: "signin_link.consumed", userId });
|
|
565
|
-
return
|
|
585
|
+
return email === undefined
|
|
586
|
+
? { status: "success", userId }
|
|
587
|
+
: { status: "success", userId, email };
|
|
566
588
|
}
|
|
567
589
|
/**
|
|
568
590
|
* Passwordless request: always resolves with the same `void` result. If the
|
|
@@ -844,7 +866,7 @@ export class IdentityService {
|
|
|
844
866
|
ttlMs: request.ttlMs,
|
|
845
867
|
invalidateExisting: true,
|
|
846
868
|
});
|
|
847
|
-
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);
|
|
848
870
|
await this.#emit(request.requested);
|
|
849
871
|
}
|
|
850
872
|
async #consumeToken(input) {
|
|
@@ -860,6 +882,9 @@ export class IdentityService {
|
|
|
860
882
|
await this.#emit(input.failed("invalid"));
|
|
861
883
|
return { status: "invalid" };
|
|
862
884
|
}
|
|
885
|
+
const refusal = input.refuse?.(status.subject);
|
|
886
|
+
if (refusal)
|
|
887
|
+
return { status: refusal };
|
|
863
888
|
await input.beforeConsume?.(status.subject, status.data);
|
|
864
889
|
const resolved = await tokens.consume(purpose, token);
|
|
865
890
|
if (!resolved) {
|
|
@@ -889,15 +914,18 @@ export class IdentityService {
|
|
|
889
914
|
}
|
|
890
915
|
return this.#otp;
|
|
891
916
|
}
|
|
892
|
-
async #deliver(hook, to, token, subject, expiresAt) {
|
|
917
|
+
async #deliver(hook, to, token, subject, expiresAt, binding) {
|
|
893
918
|
const delivery = this.#delivery;
|
|
894
919
|
const send = delivery?.[hook];
|
|
895
920
|
if (!send)
|
|
896
921
|
return;
|
|
897
922
|
const url = this.#baseUrl
|
|
898
|
-
? URL_BUILDERS[hook](this.#baseUrl, token)
|
|
923
|
+
? withBinding(URL_BUILDERS[hook](this.#baseUrl, token), binding)
|
|
899
924
|
: undefined;
|
|
900
|
-
|
|
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 () => {
|
|
901
929
|
await this.#tokens?.consume(DELIVERY_PURPOSES[hook], token);
|
|
902
930
|
});
|
|
903
931
|
}
|
|
@@ -961,6 +989,13 @@ async function logVoidFailure(credential, invalidate) {
|
|
|
961
989
|
`${credential}, usable until expiry:`, error instanceof Error ? error.message : error);
|
|
962
990
|
}
|
|
963
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
|
+
}
|
|
964
999
|
function emailFromData(data) {
|
|
965
1000
|
const email = data?.email;
|
|
966
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.
|
|
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",
|