@udibo/oauth2 0.50.0 → 0.52.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.
Files changed (32) hide show
  1. package/dist/identity/events.d.ts +1 -1
  2. package/dist/identity/mod.d.ts +1 -1
  3. package/dist/identity/service.d.ts +30 -5
  4. package/dist/identity/service.js +30 -7
  5. package/dist/identity/sign-in-link-binding.d.ts +13 -13
  6. package/dist/identity/sign-in-link-binding.js +13 -13
  7. package/dist/identity/token-flow.d.ts +5 -1
  8. package/dist/models/authentication.d.ts +11 -0
  9. package/dist/models/authorization-code.d.ts +9 -0
  10. package/dist/models/token.d.ts +7 -4
  11. package/dist/server/_resource-indicator.d.ts +13 -1
  12. package/dist/server/_resource-indicator.js +35 -4
  13. package/dist/server/authorization-server.d.ts +27 -1
  14. package/dist/server/authorization-server.js +38 -2
  15. package/dist/server/grants/authorization-code.d.ts +52 -0
  16. package/dist/server/grants/authorization-code.js +55 -4
  17. package/dist/server/grants/client-credentials.d.ts +3 -1
  18. package/dist/server/grants/client-credentials.js +4 -2
  19. package/dist/server/grants/refresh-token.d.ts +31 -2
  20. package/dist/server/grants/refresh-token.js +31 -7
  21. package/dist/server/services/authorization-code.d.ts +4 -1
  22. package/dist/server/services/token.d.ts +54 -11
  23. package/dist/testing/contract/authorization-code.d.ts +7 -0
  24. package/dist/testing/contract/authorization-code.js +15 -0
  25. package/dist/testing/contract/code-exchange.d.ts +7 -0
  26. package/dist/testing/contract/code-exchange.js +11 -0
  27. package/dist/testing/contract/token-flow-store.js +5 -1
  28. package/dist/testing/contract/token.d.ts +12 -0
  29. package/dist/testing/contract/token.js +37 -0
  30. package/dist/testing/services.d.ts +1 -1
  31. package/dist/testing/services.js +9 -2
  32. package/package.json +1 -1
@@ -190,7 +190,7 @@ export type IdentityEvent = {
190
190
  userId: string;
191
191
  } | {
192
192
  type: "signin_link.failed";
193
- reason: "expired" | "invalid";
193
+ reason: "expired" | "invalid" | "other_browser";
194
194
  } | {
195
195
  type: "signin_link.rate_limited";
196
196
  email: string;
@@ -56,7 +56,7 @@ export { type CreatedToken, type CreateTokenOptions, MemoryTokenFlowStore, type
56
56
  export { buildResetUrl, buildSignInUrl, buildTokenUrl, buildUnlockUrl, buildVerificationUrl, type CodeDeliveryHook, type CodeDeliveryMessage, type DeliveryHook, type DeliveryHooks, type DeliveryMessage, } from "./delivery.ts";
57
57
  export { createSignInLinkBinding, SIGN_IN_LINK_BINDING_PARAM, type SignInLinkBinding, verifySignInLinkBinding, } from "./sign-in-link-binding.ts";
58
58
  export { isRecentlyAuthenticated, type ListableSessionService, type RevocableSessionService, type SessionSummary, supportsSessionListing, } from "./session.ts";
59
- export { type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
59
+ export { type ConsumeSignInLinkOptions, type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
60
60
  export { EmailOtpService, type EmailOtpServiceOptions, MemoryOtpStore, type OtpRecord, type OtpStore, type RequestedOtp, type RequestOtpOptions, type VerifyOtpOptions, type VerifyOtpResult, } from "./otp.ts";
61
61
  export { AccountLockout, type AccountLockoutLike, type AccountLockoutOptions, type LockoutFailureResult, type LockoutRecord, type LockoutStatus, type LockoutStore, MemoryLockoutStore, type MemoryLockoutStoreOptions, } from "./lockout.ts";
62
62
  export type { IdentityEvent, IdentityEventHook, SignInCodeFailureReason, SignInFailureReason, } from "./events.ts";
@@ -398,6 +398,8 @@ export interface VerifyEmailInput {
398
398
  * one. No session is created — do that in your app on `success`. `email` is
399
399
  * the address the link was sent to, as it was requested; it is absent only for
400
400
  * a link minted without one through {@link TokenFlowService.create}.
401
+ * `other-browser` means the link is live but was asked for in another browser;
402
+ * it stays unspent, so the browser that asked can still use it.
401
403
  */
402
404
  export type ConsumeSignInLinkResult = {
403
405
  status: "success";
@@ -407,7 +409,23 @@ export type ConsumeSignInLinkResult = {
407
409
  status: "expired";
408
410
  } | {
409
411
  status: "invalid";
412
+ } | {
413
+ status: "other-browser";
410
414
  };
415
+ /** Options for {@link IdentityService.consumeSignInLink}. */
416
+ export interface ConsumeSignInLinkOptions {
417
+ /**
418
+ * The sign-in link nonce the opening browser holds (from
419
+ * {@link createSignInLinkBinding}, typically read from its cookie). A link
420
+ * requested with a `binding` redeems only when this nonce hashes to it.
421
+ */
422
+ nonce?: string | null;
423
+ /**
424
+ * Refuse a link minted without a binding as `other-browser`, as well as a
425
+ * mismatched one. Set it once every link your app sends is bound.
426
+ */
427
+ requireBinding?: boolean;
428
+ }
411
429
  /**
412
430
  * Outcome of {@link IdentityService.verifySignInCode}. Deliberately only
413
431
  * `success` vs `invalid`: a known email whose code expired or hit its attempt
@@ -637,10 +655,10 @@ export declare class IdentityService<User extends IdentityUser> {
637
655
  * `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
638
656
  *
639
657
  * Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
640
- * requesting browser: the link's URL carries it as the
658
+ * requesting browser: the token stores it, the link's URL carries it as the
641
659
  * {@link SIGN_IN_LINK_BINDING_PARAM} query parameter and the delivery message
642
- * as `binding`. Check it with {@link verifySignInLinkBinding} before
643
- * {@link IdentityService.consumeSignInLink}.
660
+ * as `binding`. {@link IdentityService.consumeSignInLink} then redeems the
661
+ * link only given that browser's `nonce`.
644
662
  */
645
663
  requestSignInLink(email: string, options?: {
646
664
  ttlMs?: number;
@@ -655,8 +673,15 @@ export declare class IdentityService<User extends IdentityUser> {
655
673
  * the UI can offer a fresh link. A link whose address no longer finds this
656
674
  * user through {@link IdentityUserStore.findByEmail} — the account's email
657
675
  * moved after it was mailed — reports `invalid` and stays unspent.
658
- */
659
- consumeSignInLink(token: string): Promise<ConsumeSignInLinkResult>;
676
+ *
677
+ * A link requested with a `binding` redeems only when `options.nonce` is the
678
+ * nonce that binding was made from; any other nonce, or none, reports
679
+ * `other-browser` and leaves the link unspent. The check runs against the
680
+ * binding stored with the token, so it holds against someone who has the
681
+ * link and sets a nonce of their own. An expired or spent link reports
682
+ * `expired` or `invalid` whatever the nonce.
683
+ */
684
+ consumeSignInLink(token: string, options?: ConsumeSignInLinkOptions): Promise<ConsumeSignInLinkResult>;
660
685
  /**
661
686
  * Passwordless request: always resolves with the same `void` result. If the
662
687
  * email maps to a user, mints a one-time numeric code (invalidating any
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import { delay } from "../utils/_delay.js";
21
21
  import { buildResetUrl, buildSignInUrl, buildUnlockUrl, buildVerificationUrl, } from "./delivery.js";
22
- import { SIGN_IN_LINK_BINDING_PARAM } from "./sign-in-link-binding.js";
22
+ import { SIGN_IN_LINK_BINDING_PARAM, verifySignInLinkBinding, } from "./sign-in-link-binding.js";
23
23
  import { PasswordIdentityService, } from "./password.js";
24
24
  import { TokenPurpose, } from "./token-flow.js";
25
25
  import { assertPasswordPolicy, } from "./password-policy.js";
@@ -531,10 +531,10 @@ export class IdentityService {
531
531
  * `rate_limited` in enforce mode. Default link lifetime is 15 minutes.
532
532
  *
533
533
  * Pass `binding` from {@link createSignInLinkBinding} to tie the link to the
534
- * requesting browser: the link's URL carries it as the
534
+ * requesting browser: the token stores it, the link's URL carries it as the
535
535
  * {@link SIGN_IN_LINK_BINDING_PARAM} query parameter and the delivery message
536
- * as `binding`. Check it with {@link verifySignInLinkBinding} before
537
- * {@link IdentityService.consumeSignInLink}.
536
+ * as `binding`. {@link IdentityService.consumeSignInLink} then redeems the
537
+ * link only given that browser's `nonce`.
538
538
  */
539
539
  async requestSignInLink(email, options) {
540
540
  const tokens = this.#requireTokens("requestSignInLink");
@@ -567,8 +567,15 @@ export class IdentityService {
567
567
  * the UI can offer a fresh link. A link whose address no longer finds this
568
568
  * user through {@link IdentityUserStore.findByEmail} — the account's email
569
569
  * moved after it was mailed — reports `invalid` and stays unspent.
570
+ *
571
+ * A link requested with a `binding` redeems only when `options.nonce` is the
572
+ * nonce that binding was made from; any other nonce, or none, reports
573
+ * `other-browser` and leaves the link unspent. The check runs against the
574
+ * binding stored with the token, so it holds against someone who has the
575
+ * link and sets a nonce of their own. An expired or spent link reports
576
+ * `expired` or `invalid` whatever the nonce.
570
577
  */
571
- async consumeSignInLink(token) {
578
+ async consumeSignInLink(token, options) {
572
579
  const tokens = this.#requireTokens("consumeSignInLink");
573
580
  const result = await this.#consumeToken({
574
581
  tokens,
@@ -576,7 +583,12 @@ export class IdentityService {
576
583
  token,
577
584
  failed: (reason) => ({ type: "signin_link.failed", reason }),
578
585
  addressBound: true,
586
+ refuse: (_subject, data) => otherBrowserRefusal(data, options),
579
587
  });
588
+ if (result.status === "other-browser") {
589
+ await this.#emit({ type: "signin_link.failed", reason: "other_browser" });
590
+ return result;
591
+ }
580
592
  if (result.status !== "success")
581
593
  return result;
582
594
  const userId = result.resolved.subject;
@@ -862,7 +874,9 @@ export class IdentityService {
862
874
  const { token, expiresAt } = await tokens.create({
863
875
  purpose: DELIVERY_PURPOSES[request.hook],
864
876
  subject: request.subject,
865
- data: { email: request.to },
877
+ data: request.binding === undefined
878
+ ? { email: request.to }
879
+ : { email: request.to, binding: request.binding },
866
880
  ttlMs: request.ttlMs,
867
881
  invalidateExisting: true,
868
882
  });
@@ -882,7 +896,7 @@ export class IdentityService {
882
896
  await this.#emit(input.failed("invalid"));
883
897
  return { status: "invalid" };
884
898
  }
885
- const refusal = input.refuse?.(status.subject);
899
+ const refusal = input.refuse?.(status.subject, status.data);
886
900
  if (refusal)
887
901
  return { status: refusal };
888
902
  await input.beforeConsume?.(status.subject, status.data);
@@ -996,6 +1010,15 @@ function withBinding(url, binding) {
996
1010
  bound.searchParams.set(SIGN_IN_LINK_BINDING_PARAM, binding);
997
1011
  return bound.toString();
998
1012
  }
1013
+ function otherBrowserRefusal(data, options) {
1014
+ const binding = data?.binding;
1015
+ if (typeof binding !== "string") {
1016
+ return options?.requireBinding ? "other-browser" : null;
1017
+ }
1018
+ return verifySignInLinkBinding(options?.nonce, binding)
1019
+ ? null
1020
+ : "other-browser";
1021
+ }
999
1022
  function emailFromData(data) {
1000
1023
  const email = data?.email;
1001
1024
  return typeof email === "string" ? email : undefined;
@@ -3,17 +3,17 @@
3
3
  *
4
4
  * When a browser asks for a sign-in email, {@link createSignInLinkBinding}
5
5
  * returns a random `nonce` for your app to keep in that browser (an `HttpOnly`
6
- * cookie) and its `binding`, the SHA-256 of the nonce, for the link to carry
7
- * (pass it to {@link IdentityService.requestSignInLink}). When the link is
8
- * opened, {@link verifySignInLinkBinding} checks the browser's nonce against
9
- * the link's binding before you hand the token to
10
- * {@link IdentityService.consumeSignInLink}, so a refusal leaves the link
11
- * unspent and still usable in the browser that asked for it.
6
+ * cookie) and its `binding`, the SHA-256 of the nonce. Pass the binding to
7
+ * {@link IdentityService.requestSignInLink}, which stores it with the token and
8
+ * puts it on the link. When the link is opened, pass the browser's nonce to
9
+ * {@link IdentityService.consumeSignInLink}: it redeems the link only when the
10
+ * nonce hashes to the stored binding, and otherwise leaves the link unspent and
11
+ * still usable in the browser that asked for it.
12
12
  *
13
- * The binding is not a secret: it keeps a link from signing in a browser that
14
- * did not ask for it, and is no protection once someone else holds the link.
15
- * Keep the nonce in a `__Host-` prefixed cookie so another subdomain cannot
16
- * plant one.
13
+ * The binding is not a secret. Because the check runs against the binding
14
+ * stored with the token, holding the link and setting a nonce of one's own is
15
+ * not enough to redeem it. Keep the nonce in a `__Host-` prefixed cookie so
16
+ * another subdomain cannot plant one.
17
17
  *
18
18
  * @module
19
19
  */
@@ -55,9 +55,9 @@ export declare function createSignInLinkBinding(nonce?: string | null): SignInLi
55
55
  /**
56
56
  * Whether a link carrying `binding` was asked for by the browser holding
57
57
  * `nonce`. Compares in constant time and is `false` when either value is
58
- * missing or the nonce is malformed. Call it before
59
- * {@link IdentityService.consumeSignInLink}, so a link opened elsewhere is
60
- * refused without its token being read or spent.
58
+ * missing or the nonce is malformed. {@link IdentityService.consumeSignInLink}
59
+ * runs this check against the binding stored with the token when given a
60
+ * `nonce`; call it yourself only to compare a binding you hold separately.
61
61
  *
62
62
  * @param nonce The nonce the opening browser holds, if any.
63
63
  * @param binding The binding the link carries, if any.
@@ -3,17 +3,17 @@
3
3
  *
4
4
  * When a browser asks for a sign-in email, {@link createSignInLinkBinding}
5
5
  * returns a random `nonce` for your app to keep in that browser (an `HttpOnly`
6
- * cookie) and its `binding`, the SHA-256 of the nonce, for the link to carry
7
- * (pass it to {@link IdentityService.requestSignInLink}). When the link is
8
- * opened, {@link verifySignInLinkBinding} checks the browser's nonce against
9
- * the link's binding before you hand the token to
10
- * {@link IdentityService.consumeSignInLink}, so a refusal leaves the link
11
- * unspent and still usable in the browser that asked for it.
6
+ * cookie) and its `binding`, the SHA-256 of the nonce. Pass the binding to
7
+ * {@link IdentityService.requestSignInLink}, which stores it with the token and
8
+ * puts it on the link. When the link is opened, pass the browser's nonce to
9
+ * {@link IdentityService.consumeSignInLink}: it redeems the link only when the
10
+ * nonce hashes to the stored binding, and otherwise leaves the link unspent and
11
+ * still usable in the browser that asked for it.
12
12
  *
13
- * The binding is not a secret: it keeps a link from signing in a browser that
14
- * did not ask for it, and is no protection once someone else holds the link.
15
- * Keep the nonce in a `__Host-` prefixed cookie so another subdomain cannot
16
- * plant one.
13
+ * The binding is not a secret. Because the check runs against the binding
14
+ * stored with the token, holding the link and setting a nonce of one's own is
15
+ * not enough to redeem it. Keep the nonce in a `__Host-` prefixed cookie so
16
+ * another subdomain cannot plant one.
17
17
  *
18
18
  * @module
19
19
  */
@@ -56,9 +56,9 @@ export function createSignInLinkBinding(nonce) {
56
56
  /**
57
57
  * Whether a link carrying `binding` was asked for by the browser holding
58
58
  * `nonce`. Compares in constant time and is `false` when either value is
59
- * missing or the nonce is malformed. Call it before
60
- * {@link IdentityService.consumeSignInLink}, so a link opened elsewhere is
61
- * refused without its token being read or spent.
59
+ * missing or the nonce is malformed. {@link IdentityService.consumeSignInLink}
60
+ * runs this check against the binding stored with the token when given a
61
+ * `nonce`; call it yourself only to compare a binding you hold separately.
62
62
  *
63
63
  * @param nonce The nonce the opening browser holds, if any.
64
64
  * @param binding The binding the link carries, if any.
@@ -29,7 +29,11 @@ export interface TokenFlowRecord {
29
29
  purpose: string;
30
30
  /** The subject the token acts on (typically a user id). */
31
31
  subject: string;
32
- /** Optional extra payload (e.g. the email being verified). */
32
+ /**
33
+ * Optional extra payload (e.g. the email being verified, a sign-in link's
34
+ * browser binding). A store must persist the whole object, every key
35
+ * included: identity flows enforce checks against keys beyond `email`.
36
+ */
33
37
  data?: Record<string, unknown>;
34
38
  /** Expiry, epoch ms. */
35
39
  expiresAt: number;
@@ -49,4 +49,15 @@ export interface AuthenticationRequest {
49
49
  readonly maxAge?: number;
50
50
  /** Requested `acr_values` in preference order; empty when absent. */
51
51
  readonly acrValues: readonly string[];
52
+ /**
53
+ * The syntactically valid `resource` (RFC 8707) the client asked for,
54
+ * exactly as spelled. It is not yet accepted by `acceptedResource`, which
55
+ * runs after consent; do not record consent for it as granted until a code
56
+ * is actually issued. Set only when the authorization code grant enables
57
+ * `resourceIndicators` and the request names a resource. Show it on the
58
+ * consent screen, and key any remembered consent (the `authorizedScope`
59
+ * that `authenticateUser` returns) by it where access differs between
60
+ * resources.
61
+ */
62
+ readonly resource?: string;
52
63
  }
@@ -29,6 +29,15 @@ export interface AuthorizationCode<Client extends ClientInterface, User, Scope e
29
29
  nonce?: string;
30
30
  /** Verified event captured at issuance; code stores must persist and restore it. */
31
31
  authenticationContext?: AuthenticationContext;
32
+ /**
33
+ * Exact resource URI (RFC 8707) the authorization request named and the
34
+ * resource policy accepted, set only by an authorization code grant with
35
+ * `resourceIndicators` enabled. Code stores used with that option must
36
+ * persist it and restore it unchanged from `get`: the grant refuses to issue
37
+ * a code whose stored record loses it, and the tokens issued from the code
38
+ * are bound to it. Absent for a code issued without a resource.
39
+ */
40
+ resource?: string;
32
41
  }
33
42
  /**
34
43
  * Parameters from an authorization request.
@@ -19,10 +19,13 @@ export interface Token<Client extends ClientInterface, User, Scope extends Abstr
19
19
  /** The user this token was issued for (if applicable). */
20
20
  user?: User;
21
21
  /**
22
- * Exact resource URI accepted by an opted-in client-credentials policy
23
- * (RFC 8707). Persist and restore it on every token read; never derive it
24
- * from a later request or the client's current configuration. Absent for
25
- * legacy issuance. Resource authority still belongs to the application.
22
+ * Exact resource URI (RFC 8707) this token is bound to: accepted by an
23
+ * opted-in client-credentials policy, carried from a resource-bound
24
+ * authorization code, or inherited from a resource-bound refresh token.
25
+ * Persist and restore it on every token read, refresh-token and revoked
26
+ * records included; never derive it from a later request or the client's
27
+ * current configuration. Absent for unbound tokens. Resource authority
28
+ * still belongs to the application.
26
29
  */
27
30
  resource?: string;
28
31
  /** The scope granted to this token. */
@@ -1,7 +1,19 @@
1
+ import type { ClientInterface } from "../models/client.ts";
2
+ import type { AbstractScope } from "../models/scope.ts";
3
+ import type { RefreshToken, Token } from "../models/token.ts";
4
+ import type { TokenServiceInterface } from "./services/token.ts";
1
5
  /**
2
6
  * Read zero or one absolute resource URI without a fragment, preserving its
3
7
  * exact spelling. Multiple values, including equal repeats, are refused.
4
8
  * Call only after opting into the single-resource policy.
5
9
  * @throws {InvalidTargetError} For an empty, repeated, non-string or malformed value.
6
10
  */
7
- export declare function resourceIndicatorOf(body: FormData): string | undefined;
11
+ export declare function resourceIndicatorOf(parameters: Pick<FormData, "getAll"> | URLSearchParams): string | undefined;
12
+ /**
13
+ * Refuse a token whose store lost, changed or invented its resource binding:
14
+ * the saved result must carry `resource`, and a bound token must read back
15
+ * bound through `getToken` and, when it has one, `getRefreshToken`. A refused
16
+ * token is revoked on a best-effort basis before the error is thrown.
17
+ * @throws {ServerError} When storage does not round-trip the binding.
18
+ */
19
+ export declare function assertStoredResource<Client extends ClientInterface, User, Scope extends AbstractScope>(tokenService: TokenServiceInterface<Client, User, Scope>, saved: Token<Client, User, Scope> | RefreshToken<Client, User, Scope>, resource: string | undefined): Promise<void>;
@@ -1,5 +1,5 @@
1
- /** Single-resource syntax for opted-in machine issuance. @module */
2
- import { InvalidTargetError } from "../errors.js";
1
+ /** Single-resource syntax for opted-in resource-bound issuance. @module */
2
+ import { InvalidTargetError, ServerError } from "../errors.js";
3
3
  const PATH = /^(?:[A-Za-z0-9._~!$&'()*+,;=:@/-]|%[A-Fa-f0-9]{2})*$/;
4
4
  const QUERY = /^(?:[A-Za-z0-9._~!$&'()*+,;=:@/?-]|%[A-Fa-f0-9]{2})*$/;
5
5
  const USER_INFO = /^(?:[A-Za-z0-9._~!$&'()*+,;=:-]|%[A-Fa-f0-9]{2})*$/;
@@ -53,8 +53,8 @@ function absoluteUri(value) {
53
53
  * Call only after opting into the single-resource policy.
54
54
  * @throws {InvalidTargetError} For an empty, repeated, non-string or malformed value.
55
55
  */
56
- export function resourceIndicatorOf(body) {
57
- const values = body.getAll("resource");
56
+ export function resourceIndicatorOf(parameters) {
57
+ const values = parameters.getAll("resource");
58
58
  if (values.length === 0)
59
59
  return undefined;
60
60
  const resource = values[0];
@@ -65,3 +65,34 @@ export function resourceIndicatorOf(body) {
65
65
  }
66
66
  return resource;
67
67
  }
68
+ /**
69
+ * Refuse a token whose store lost, changed or invented its resource binding:
70
+ * the saved result must carry `resource`, and a bound token must read back
71
+ * bound through `getToken` and, when it has one, `getRefreshToken`. A refused
72
+ * token is revoked on a best-effort basis before the error is thrown.
73
+ * @throws {ServerError} When storage does not round-trip the binding.
74
+ */
75
+ export async function assertStoredResource(tokenService, saved, resource) {
76
+ if (await storeKeepsResource(tokenService, saved, resource))
77
+ return;
78
+ try {
79
+ await tokenService.revoke(saved);
80
+ }
81
+ catch (error) {
82
+ console.error("[@udibo/oauth2] could not revoke a token whose store dropped its resource:", error instanceof Error ? error.message : error);
83
+ }
84
+ throw new ServerError("token storage did not preserve resource");
85
+ }
86
+ async function storeKeepsResource(tokenService, saved, resource) {
87
+ if ((saved.resource ?? undefined) !== resource)
88
+ return false;
89
+ if (resource === undefined)
90
+ return true;
91
+ const access = await tokenService.getToken(saved.accessToken);
92
+ if (access?.resource !== resource)
93
+ return false;
94
+ const refreshToken = "refreshToken" in saved ? saved.refreshToken : undefined;
95
+ if (!refreshToken)
96
+ return true;
97
+ return ((await tokenService.getRefreshToken(refreshToken))?.resource === resource);
98
+ }
@@ -406,6 +406,19 @@ export type AuthenticateUserFn<User> = (request: Request, authentication?: Authe
406
406
  * With `prompt=consent` the server calls it even when the scope is already
407
407
  * authorized, and the fourth argument, always passed, says so: ask again
408
408
  * rather than reusing a stored grant.
409
+ *
410
+ * When the authorization code grant enables `resourceIndicators` and the
411
+ * request names a `resource`, the fourth argument carries it as
412
+ * `authentication.resource`, exactly as spelled. It is the syntactically
413
+ * valid resource the client asked for, not yet accepted by
414
+ * `acceptedResource`, which runs after consent; do not record consent for it
415
+ * as granted until a code is actually issued. Show it to the person, and
416
+ * key a remembered consent by resource where access differs between
417
+ * resources: the handler is skipped when the `authorizedScope` that
418
+ * `authenticateUser` returns already covers the scope, including under
419
+ * `prompt=none`, and `authenticateUser` receives the same
420
+ * `authentication.resource` so it can return a scope remembered for that
421
+ * resource only.
409
422
  */
410
423
  export type HandleConsentFn<Client extends ClientInterface, S extends AbstractScope> = (client: Client, requestedScope: S | undefined, user: unknown, authentication?: AuthenticationRequest) => Promise<{
411
424
  approved: boolean;
@@ -693,6 +706,19 @@ export declare class AuthorizationServer<Client extends ClientInterface, User, S
693
706
  * registered `redirect_uri` itself carries. A request that resolves no
694
707
  * `issuer` sends none.
695
708
  *
709
+ * When the authorization code grant enables `resourceIndicators`, the
710
+ * request may carry one `resource` (RFC 8707). A malformed or repeated value,
711
+ * or one the token service's `acceptedResource` policy does not accept for
712
+ * the signed-in user and the consented scope, is `invalid_target`, reported
713
+ * like the other failures above. The policy is consulted even when no
714
+ * resource was named, and the accepted value is stored with the code. The
715
+ * policy's fifth argument is `{ grantType: "authorization_code" }`, and
716
+ * `authenticateUser` and `handleConsent` receive the named resource as
717
+ * `authentication.resource`.
718
+ * A code returned without the accepted resource, such as from a
719
+ * `generateAuthorizationCode` override that drops it, is never sent: the
720
+ * request fails with `server_error`.
721
+ *
696
722
  * Requires a grant extending {@linkcode AuthorizationCodeGrant} registered
697
723
  * under `authorization_code`; without one the endpoint answers 500
698
724
  * `server_error` (or rethrows, with `throwOnError`).
@@ -903,7 +929,7 @@ export { PasswordGrant } from "./grants/password.ts";
903
929
  export type { PasswordGrantOptions, PasswordGrantServices, } from "./grants/password.ts";
904
930
  export { DeviceAuthorizationGrant } from "./grants/device-authorization.ts";
905
931
  export type { DeviceAuthorizationGrantOptions, DeviceAuthorizationGrantServices, } from "./grants/device-authorization.ts";
906
- export { AbstractTokenService, type AbstractTokenServiceOptions, type TokenServiceInterface, } from "./services/token.ts";
932
+ export { AbstractTokenService, type AbstractTokenServiceOptions, type ResourcePolicyContext, type TokenServiceInterface, } from "./services/token.ts";
907
933
  export type { ClientServiceInterface } from "./services/client.ts";
908
934
  export { AbstractAuthorizationCodeService, type AbstractAuthorizationCodeServiceOptions, type AuthorizationCodeServiceInterface, } from "./services/authorization-code.ts";
909
935
  export type { DeviceAuthorizationServiceInterface } from "./services/device-authorization.ts";
@@ -21,8 +21,9 @@
21
21
  * @module
22
22
  */
23
23
  import { snapshotAuthenticationContext } from "../utils/authentication-context.js";
24
- import { AccessDeniedError, ConsentRequiredError, InvalidRequestError, InvalidTokenError, isOAuth2Error, LoginRequiredError, OAuth2Error, ServerError, toOAuth2Error, UnauthorizedClientError, UnsupportedGrantTypeError, UnsupportedResponseTypeError, } from "../errors.js";
24
+ import { AccessDeniedError, ConsentRequiredError, InvalidRequestError, InvalidTargetError, InvalidTokenError, isOAuth2Error, LoginRequiredError, OAuth2Error, ServerError, toOAuth2Error, UnauthorizedClientError, UnsupportedGrantTypeError, UnsupportedResponseTypeError, } from "../errors.js";
25
25
  import { authenticateClientCredentials, extractClientCredentials, } from "./client-authentication.js";
26
+ import { resourceIndicatorOf } from "./_resource-indicator.js";
26
27
  import { assertSupportedValues, authenticationShortfall, DEFAULT_PROMPT_VALUES_SUPPORTED, parseAuthenticationRequest, } from "./authentication-request.js";
27
28
  import { isRedirectUriPattern, matchRedirectUri } from "./redirect-uri.js";
28
29
  import { AuthorizationCodeGrant } from "./grants/authorization-code.js";
@@ -773,6 +774,19 @@ export class AuthorizationServer extends ResourceServer {
773
774
  * registered `redirect_uri` itself carries. A request that resolves no
774
775
  * `issuer` sends none.
775
776
  *
777
+ * When the authorization code grant enables `resourceIndicators`, the
778
+ * request may carry one `resource` (RFC 8707). A malformed or repeated value,
779
+ * or one the token service's `acceptedResource` policy does not accept for
780
+ * the signed-in user and the consented scope, is `invalid_target`, reported
781
+ * like the other failures above. The policy is consulted even when no
782
+ * resource was named, and the accepted value is stored with the code. The
783
+ * policy's fifth argument is `{ grantType: "authorization_code" }`, and
784
+ * `authenticateUser` and `handleConsent` receive the named resource as
785
+ * `authentication.resource`.
786
+ * A code returned without the accepted resource, such as from a
787
+ * `generateAuthorizationCode` override that drops it, is never sent: the
788
+ * request fails with `server_error`.
789
+ *
776
790
  * Requires a grant extending {@linkcode AuthorizationCodeGrant} registered
777
791
  * under `authorization_code`; without one the endpoint answers 500
778
792
  * `server_error` (or rethrows, with `throwOnError`).
@@ -806,7 +820,12 @@ export class AuthorizationServer extends ResourceServer {
806
820
  this.#validateResponseType(params.responseType);
807
821
  const requestedScope = grant.parseScope(params.scope);
808
822
  this.#validateChallenge(grant, params);
809
- const authentication = parseAuthenticationRequest(new URL(request.url).searchParams, this.#promptValuesSupported);
823
+ const resourcePolicy = this.#resourcePolicy(grant, services.tokenService);
824
+ const resource = resourcePolicy
825
+ ? resourceIndicatorOf(new URL(request.url).searchParams)
826
+ : undefined;
827
+ const requested = parseAuthenticationRequest(new URL(request.url).searchParams, this.#promptValuesSupported);
828
+ const authentication = resource === undefined ? requested : { ...requested, resource };
810
829
  const silent = authentication.prompt.includes("none");
811
830
  const authResult = await authenticateUser(request, authentication);
812
831
  if (authResult instanceof Response) {
@@ -838,6 +857,10 @@ export class AuthorizationServer extends ResourceServer {
838
857
  });
839
858
  if (consented instanceof Response)
840
859
  return consented;
860
+ if (resourcePolicy &&
861
+ (await resourcePolicy.call(services.tokenService, client, user, resource, consented.scope, { grantType: AUTHORIZATION_CODE_GRANT_TYPE })) !== true) {
862
+ throw new InvalidTargetError("invalid resource");
863
+ }
841
864
  const authorizationCode = await grant.generateAuthorizationCode({
842
865
  client,
843
866
  user,
@@ -846,11 +869,24 @@ export class AuthorizationServer extends ResourceServer {
846
869
  challenge: params.challenge ?? null,
847
870
  challengeMethod: params.challengeMethod ?? null,
848
871
  nonce: params.nonce ?? null,
872
+ resource: resource ?? null,
849
873
  authenticationContext,
850
874
  }, request);
875
+ if (resourcePolicy &&
876
+ (authorizationCode.resource ?? undefined) !== resource) {
877
+ throw new ServerError("authorization code did not keep its resource");
878
+ }
851
879
  redirectUrl.searchParams.set("code", authorizationCode.code);
852
880
  return authorizationResponseRedirect({ url: redirectUrl, issuer });
853
881
  }
882
+ #resourcePolicy(grant, tokenService) {
883
+ if (!grant.resourceIndicators)
884
+ return undefined;
885
+ if (!tokenService.acceptedResource) {
886
+ throw new ServerError("resourceIndicators requires tokenService.acceptedResource");
887
+ }
888
+ return tokenService.acceptedResource;
889
+ }
854
890
  #authorizeErrorResponse(error, target) {
855
891
  const redirectUrl = target.url;
856
892
  if (!redirectUrl || !(error instanceof Error) || !isOAuth2Error(error)) {
@@ -102,6 +102,31 @@ export interface AuthorizationCodeGrantOptions<Client extends ClientInterface, U
102
102
  * client-facing `invalid_grant` a replayed code always yields.
103
103
  */
104
104
  onCodeReuse?: (event: CodeReuseEvent<Client>) => void | Promise<void>;
105
+ /**
106
+ * Opts this grant into single-resource indicators (RFC 8707). Defaults to
107
+ * `false`, which leaves `resource` an ignored extension parameter.
108
+ *
109
+ * When `true`, the authorization endpoint reads zero or one `resource` (an
110
+ * absolute URI without a fragment, kept exactly as spelled), asks the token
111
+ * service's `acceptedResource` policy whether it may be bound for the
112
+ * signed-in user and the consented scope, and stores the accepted value
113
+ * with the code. The token request may then repeat that exact value or omit
114
+ * it; any other value is `invalid_target`, and the code is consumed as on
115
+ * any failed exchange. The access and refresh tokens issued are bound to
116
+ * the stored resource, and a code issued without one yields unbound tokens.
117
+ *
118
+ * Requires a token service implementing `acceptedResource`, an
119
+ * authorization code store that round-trips
120
+ * {@linkcode AuthorizationCode.resource}, and a token store that
121
+ * round-trips {@linkcode Token.resource}; the grant refuses to issue a code
122
+ * or token whose store loses the binding. Enable `resourceIndicators` on the
123
+ * {@linkcode RefreshTokenGrant} as well, or refreshing a bound token is
124
+ * refused with `invalid_target`.
125
+ *
126
+ * @default false
127
+ * @see https://www.rfc-editor.org/rfc/rfc8707.html
128
+ */
129
+ resourceIndicators?: boolean;
105
130
  }
106
131
  /** Client credentials extended with optional PKCE code_verifier. */
107
132
  export interface PKCEClientCredentials extends ClientCredentials {
@@ -126,6 +151,13 @@ export interface GenerateAuthorizationCodeOptions<Client extends ClientInterface
126
151
  challengeMethod?: string | null;
127
152
  /** OIDC nonce to bind to the code (echoed into the id_token). */
128
153
  nonce?: string | null;
154
+ /**
155
+ * Exact resource URI (RFC 8707) the resource policy accepted, to bind to the
156
+ * code and to the tokens issued from it. Only a grant with
157
+ * {@linkcode AuthorizationCodeGrantOptions.resourceIndicators} enabled
158
+ * accepts one.
159
+ */
160
+ resource?: string | null;
129
161
  }
130
162
  /**
131
163
  * The authorization code grant type.
@@ -157,6 +189,11 @@ export declare class AuthorizationCodeGrant<Client extends ClientInterface, User
157
189
  * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4.5
158
190
  */
159
191
  requireClientAuthentication: boolean;
192
+ /**
193
+ * Whether single-resource indicators are enabled. See
194
+ * {@linkcode AuthorizationCodeGrantOptions.resourceIndicators}.
195
+ */
196
+ readonly resourceIndicators: boolean;
160
197
  /** Creates the grant from its {@linkcode AuthorizationCodeGrantOptions}. */
161
198
  constructor(options: AuthorizationCodeGrantOptions<Client, User, S>);
162
199
  /**
@@ -200,6 +237,12 @@ export declare class AuthorizationCodeGrant<Client extends ClientInterface, User
200
237
  /**
201
238
  * Generates and saves an authorization code. Resolves its own
202
239
  * `authorizationCodeService` from the request.
240
+ *
241
+ * A code bound to a `resource` is read back after saving; when the store
242
+ * did not keep the exact value, the code is revoked and never returned.
243
+ *
244
+ * @throws {ServerError} When `resource` is given to a grant without
245
+ * `resourceIndicators`, or the store does not round-trip it.
203
246
  */
204
247
  generateAuthorizationCode(options: GenerateAuthorizationCodeOptions<Client, User, S>, request: Request): Promise<AuthorizationCode<Client, User, S>>;
205
248
  /**
@@ -238,9 +281,18 @@ export declare class AuthorizationCodeGrant<Client extends ClientInterface, User
238
281
  * {@linkcode getAuthenticatedClient} resolved from this same `request`.
239
282
  * A code redeemed with PKCE issues its token with `codeVerifierHash` set.
240
283
  *
284
+ * The tokens issued are bound to the code's
285
+ * {@linkcode AuthorizationCode.resource}, when it has one. With
286
+ * {@linkcode resourceIndicators} enabled, a `resource` on the token request
287
+ * must equal it exactly, character for character; a different, malformed
288
+ * or repeated value, or any value for a code issued without a resource, is
289
+ * `invalid_target` and consumes the code like the checks above.
290
+ *
241
291
  * @throws {InvalidRequestError} When `code` is missing, a required `code_verifier` is absent, or the verifier is malformed.
242
292
  * @throws {InvalidGrantError} When the code is unknown, expired, already claimed, or its verifier or `redirect_uri` does not match.
243
293
  * @throws {InvalidClientError} When the code was issued to another client.
294
+ * @throws {InvalidTargetError} When an opted-in token request names a resource other than the code's.
295
+ * @throws {ServerError} When the token store does not round-trip the code's resource.
244
296
  * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
245
297
  * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4.5
246
298
  */