@udibo/oauth2 0.48.0 → 0.49.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.
@@ -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 mount only the stateless reset/verify routes.
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
- /** `POST` email verification (consume token). Default `/email/verify`. */
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`. Mount it wherever you like, e.g.
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 mount only the stateless reset/verify routes.
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`. Mount it wherever you like, e.g.
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.onAuthenticated;
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
- app.post(paths.verifyEmail, handle(async (c) => {
215
- const body = await readBody(c, maxBodyBytes);
216
- const result = await service.verifyEmail(String(body.token ?? ""));
217
- if (result.status === "success") {
218
- return c.json({ ok: true, userId: result.userId });
219
- }
220
- return c.json({ error: `token_${result.status}` }, 400);
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
  }
@@ -53,7 +53,7 @@ export { classifyIdentifier, createIdentifierResolver, type IdentifierKind, type
53
53
  export { type CreatedToken, type CreateTokenOptions, MemoryTokenFlowStore, type ResolvedToken, type TokenFlowRecord, TokenFlowService, type TokenFlowStore, TokenPurpose, type TokenStatus, } from "./token-flow.ts";
54
54
  export { buildResetUrl, buildSignInUrl, buildTokenUrl, buildUnlockUrl, buildVerificationUrl, type CodeDeliveryHook, type CodeDeliveryMessage, type DeliveryHook, type DeliveryHooks, type DeliveryMessage, } from "./delivery.ts";
55
55
  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";
56
+ export { type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
57
57
  export { EmailOtpService, type EmailOtpServiceOptions, MemoryOtpStore, type OtpRecord, type OtpStore, type RequestedOtp, type RequestOtpOptions, type VerifyOtpOptions, type VerifyOtpResult, } from "./otp.ts";
58
58
  export { AccountLockout, type AccountLockoutLike, type AccountLockoutOptions, type LockoutFailureResult, type LockoutRecord, type LockoutStatus, type LockoutStore, MemoryLockoutStore, type MemoryLockoutStoreOptions, } from "./lockout.ts";
59
59
  export type { IdentityEvent, IdentityEventHook, SignInCodeFailureReason, SignInFailureReason, } from "./events.ts";
@@ -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,7 +376,22 @@ 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
@@ -551,6 +572,11 @@ export declare class IdentityService<User extends IdentityUser> {
551
572
  /**
552
573
  * Consume a verification token and mark the user's email verified.
553
574
  *
575
+ * The token verifies only for a request signed in as the user it was minted
576
+ * for: pass that session's user id as `sessionUserId`. A live token with no
577
+ * session reports `sign-in-required`, and with another user's session
578
+ * `wrong-account`; both leave it unspent and the address unverified.
579
+ *
554
580
  * Returns a discriminated {@link VerifyEmailResult} so the UI can tell an
555
581
  * **expired** link (offer to resend) from a generically **invalid** one — the
556
582
  * `inspect()` distinction, surfaced through the flow. A `valid` token is
@@ -566,7 +592,7 @@ export declare class IdentityService<User extends IdentityUser> {
566
592
  * store that predicates on both never verifies an address the link was not
567
593
  * minted for.
568
594
  */
569
- verifyEmail(token: string): Promise<VerifyEmailResult>;
595
+ verifyEmail(input: VerifyEmailInput): Promise<VerifyEmailResult>;
570
596
  /**
571
597
  * Mint + deliver a single-use account-unlock link after a lockout. Call it
572
598
  * with the locked account's email (typically from your `lockout` event
@@ -32,6 +32,11 @@ const DEFAULT_VERIFY_TTL = 24 * 60 * 60 * 1000;
32
32
  const DEFAULT_UNLOCK_TTL = 60 * 60 * 1000;
33
33
  const DEFAULT_SIGNIN_LINK_TTL = 15 * 60 * 1000;
34
34
  const DEFAULT_FAILED_SIGN_IN_FLOOR_MS = 250;
35
+ function sessionRefusal(sessionUserId, subject) {
36
+ if (!sessionUserId)
37
+ return "sign-in-required";
38
+ return sessionUserId === subject ? null : "wrong-account";
39
+ }
35
40
  function foldEmail(email) {
36
41
  return email.trim().toLowerCase();
37
42
  }
@@ -394,6 +399,11 @@ export class IdentityService {
394
399
  /**
395
400
  * Consume a verification token and mark the user's email verified.
396
401
  *
402
+ * The token verifies only for a request signed in as the user it was minted
403
+ * for: pass that session's user id as `sessionUserId`. A live token with no
404
+ * session reports `sign-in-required`, and with another user's session
405
+ * `wrong-account`; both leave it unspent and the address unverified.
406
+ *
397
407
  * Returns a discriminated {@link VerifyEmailResult} so the UI can tell an
398
408
  * **expired** link (offer to resend) from a generically **invalid** one — the
399
409
  * `inspect()` distinction, surfaced through the flow. A `valid` token is
@@ -409,13 +419,14 @@ export class IdentityService {
409
419
  * store that predicates on both never verifies an address the link was not
410
420
  * minted for.
411
421
  */
412
- async verifyEmail(token) {
422
+ async verifyEmail(input) {
413
423
  const tokens = this.#requireTokens("verifyEmail");
414
424
  const result = await this.#consumeToken({
415
425
  tokens,
416
426
  purpose: TokenPurpose.EmailVerification,
417
- token,
427
+ token: input.token,
418
428
  failed: (reason) => ({ type: "email_verification.failed", reason }),
429
+ refuse: (subject) => sessionRefusal(input.sessionUserId, subject),
419
430
  beforeConsume: (subject, data) => this.#users.markEmailVerified?.(subject, emailFromData(data)),
420
431
  });
421
432
  if (result.status !== "success")
@@ -860,6 +871,9 @@ export class IdentityService {
860
871
  await this.#emit(input.failed("invalid"));
861
872
  return { status: "invalid" };
862
873
  }
874
+ const refusal = input.refuse?.(status.subject);
875
+ if (refusal)
876
+ return { status: refusal };
863
877
  await input.beforeConsume?.(status.subject, status.data);
864
878
  const resolved = await tokens.consume(purpose, token);
865
879
  if (!resolved) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.48.0",
3
+ "version": "0.49.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",