@udibo/oauth2 0.51.0 → 0.53.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.
@@ -211,6 +211,87 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
211
211
  * Successful sign-ins are never delayed.
212
212
  */
213
213
  failedSignInFloorMs?: number;
214
+ /**
215
+ * Resolve a sign-in whose identifier matches no account, typically by
216
+ * checking the password against the system your users are moving from and
217
+ * creating the account on a match. {@link IdentityService.signIn} calls it
218
+ * only after the sign-in throttle admits the attempt and
219
+ * {@link IdentityUserStore.findByIdentifier} finds no account. It receives
220
+ * the trimmed identifier and the password exactly as submitted.
221
+ *
222
+ * Return the user to sign them in: typically the account you just created
223
+ * for this identifier with this password. The service signs it in only when
224
+ * {@link IdentityUserStore.findByIdentifier} now finds that same account for
225
+ * the identifier and its stored credential accepts the submitted password, so
226
+ * a resolver can never sign in an account the identifier does not reach (a
227
+ * casing variant, an account your store hides from sign-in) or one whose own
228
+ * password differs. On a uniqueness conflict, return `null` or throw rather
229
+ * than the existing row. The service then refuses a locked account under
230
+ * `"enforce"`, as for any other sign-in, and otherwise resets the throttle
231
+ * and the lockout count and emits `sign_in.succeeded`. Return `null` to
232
+ * refuse; an account that fails the check above is refused the same way.
233
+ * A throw
234
+ * also refuses: the service logs that the resolver threw, never the error
235
+ * itself, which may carry the password. A refusal returns the same `null`,
236
+ * runs the same equalizing password hash, emits the same `sign_in.failed`
237
+ * event with reason `unknown_identifier`, and is held to the same
238
+ * {@link failedSignInFloorMs} as an unknown identifier with no resolver.
239
+ *
240
+ * The resolver's own running time adds to the refusal's work, so set
241
+ * {@link failedSignInFloorMs} above its slowest refusal plus one password
242
+ * hash. A refusal after the other system accepted the password (the create
243
+ * failed) is usually the slowest: your request timeout, the hash and write
244
+ * of the create, then the service's hash. Below that, response time tells an
245
+ * unauthenticated caller which identifiers had no local account, or that a
246
+ * guessed password works on the other system. Only the
247
+ * per-identifier throttle bounds how often it runs, and only when a
248
+ * sign-in rate limiter (`rateLimiter` or `rateLimiters.signIn`) is
249
+ * configured: there is no account to lock, the throttle
250
+ * never stops one password tried across many identifiers, and under
251
+ * `protectionMode: "log-only"` it reports without stopping anything. Limit
252
+ * calls inside the resolver when it reaches another system. Compare the
253
+ * other system's answer against the identifier in the same normalized form
254
+ * your store resolves accounts by.
255
+ *
256
+ * @example Create an account from a password check against another system
257
+ * ```ts
258
+ * import {
259
+ * IdentityService,
260
+ * type IdentityUser,
261
+ * type IdentityUserStore,
262
+ * PasswordIdentityService,
263
+ * } from "@udibo/oauth2/identity";
264
+ *
265
+ * interface AppUser extends IdentityUser {
266
+ * email: string;
267
+ * }
268
+ *
269
+ * declare const users: IdentityUserStore<AppUser>;
270
+ * declare function checkPreviousSystem(
271
+ * email: string,
272
+ * password: string,
273
+ * ): Promise<{ email: string } | null>;
274
+ *
275
+ * const passwords = new PasswordIdentityService();
276
+ * const identity = new IdentityService<AppUser>({
277
+ * users,
278
+ * passwords,
279
+ * failedSignInFloorMs: 3_000,
280
+ * resolveUnknownIdentifier: async ({ identifier, password }) => {
281
+ * const profile = await checkPreviousSystem(identifier, password);
282
+ * if (profile?.email !== identifier) return null;
283
+ * return await users.create(
284
+ * { email: profile.email },
285
+ * await passwords.hash(password),
286
+ * );
287
+ * },
288
+ * });
289
+ * ```
290
+ */
291
+ resolveUnknownIdentifier?: (input: {
292
+ identifier: string;
293
+ password: string;
294
+ }) => Promise<User | null>;
214
295
  /**
215
296
  * Session revocation, called on a successful password reset. Optional. When
216
297
  * the user store implements {@link IdentityUserStore.resetCredential}, the
@@ -493,6 +574,10 @@ export declare class IdentityService<User extends IdentityUser> {
493
574
  * longer (typically a foreign KDF) stays visible by its excess. A success
494
575
  * returns as soon as it is done.
495
576
  *
577
+ * With {@link IdentityServiceOptions.resolveUnknownIdentifier} set, an
578
+ * identifier that finds no account is offered to it first; a user it returns
579
+ * signs in, and a refusal is the same `null` an unknown identifier gets.
580
+ *
496
581
  * @throws {IdentityError} `rate_limited` (with `retryAfterMs`) when a
497
582
  * `rateLimiter` is configured, the identifier's limit is hit, and
498
583
  * `protectionMode` is `"enforce"`. Rate-limit rejections throw before the
@@ -70,6 +70,7 @@ export class IdentityService {
70
70
  #onEvent;
71
71
  #legacyVerifiers;
72
72
  #failedSignInFloorMs;
73
+ #resolveUnknownIdentifier;
73
74
  /** Wires the user store and optional collaborators; applies the TTL and hasher defaults. */
74
75
  constructor(options) {
75
76
  this.#users = options.users;
@@ -112,6 +113,7 @@ export class IdentityService {
112
113
  Number.isFinite(floor) && floor >= 0
113
114
  ? floor
114
115
  : DEFAULT_FAILED_SIGN_IN_FLOOR_MS;
116
+ this.#resolveUnknownIdentifier = options.resolveUnknownIdentifier;
115
117
  }
116
118
  /**
117
119
  * Create a user with a hashed password. `profile` is your app's own fields.
@@ -148,6 +150,10 @@ export class IdentityService {
148
150
  * longer (typically a foreign KDF) stays visible by its excess. A success
149
151
  * returns as soon as it is done.
150
152
  *
153
+ * With {@link IdentityServiceOptions.resolveUnknownIdentifier} set, an
154
+ * identifier that finds no account is offered to it first; a user it returns
155
+ * signs in, and a refusal is the same `null` an unknown identifier gets.
156
+ *
151
157
  * @throws {IdentityError} `rate_limited` (with `retryAfterMs`) when a
152
158
  * `rateLimiter` is configured, the identifier's limit is hit, and
153
159
  * `protectionMode` is `"enforce"`. Rate-limit rejections throw before the
@@ -163,13 +169,7 @@ export class IdentityService {
163
169
  });
164
170
  const user = await this.#users.findByIdentifier(identifier);
165
171
  if (!user) {
166
- await this.#equalizeTiming(input.password);
167
- await this.#emit({
168
- type: "sign_in.failed",
169
- identifier,
170
- reason: "unknown_identifier",
171
- });
172
- return await this.#rejectSignIn(startedAt);
172
+ return await this.#signInUnknownIdentifier(identifier, input.password, startedAt);
173
173
  }
174
174
  const lockReported = await this.#reportLock(user.id, identifier);
175
175
  if (lockReported && this.#enforce) {
@@ -198,6 +198,53 @@ export class IdentityService {
198
198
  await attempt.fail();
199
199
  return await this.#rejectSignIn(startedAt);
200
200
  }
201
+ return await this.#completeSignIn(user, identifier);
202
+ }
203
+ async #signInUnknownIdentifier(identifier, password, startedAt) {
204
+ const resolved = await this.#tryResolveUnknownIdentifier(identifier, password);
205
+ const user = resolved &&
206
+ (await this.#bindResolvedUser(resolved, identifier, password));
207
+ if (user) {
208
+ if ((await this.#reportLock(user.id, identifier)) && this.#enforce) {
209
+ await this.#equalizeTiming(password);
210
+ return await this.#rejectSignIn(startedAt);
211
+ }
212
+ return await this.#completeSignIn(user, identifier);
213
+ }
214
+ await this.#equalizeTiming(password);
215
+ await this.#emit({
216
+ type: "sign_in.failed",
217
+ identifier,
218
+ reason: "unknown_identifier",
219
+ });
220
+ return await this.#rejectSignIn(startedAt);
221
+ }
222
+ async #tryResolveUnknownIdentifier(identifier, password) {
223
+ if (!this.#resolveUnknownIdentifier)
224
+ return null;
225
+ try {
226
+ return ((await this.#resolveUnknownIdentifier({ identifier, password })) ?? null);
227
+ }
228
+ catch {
229
+ // Never log the error object: it may echo the submitted password.
230
+ console.error("[@udibo/oauth2] resolveUnknownIdentifier threw");
231
+ return null;
232
+ }
233
+ }
234
+ async #bindResolvedUser(resolved, identifier, password) {
235
+ const found = await this.#users.findByIdentifier(identifier);
236
+ const credential = found?.id === resolved.id
237
+ ? await this.#users.getCredential(found.id)
238
+ : undefined;
239
+ if (found &&
240
+ credential &&
241
+ (await this.#passwords.verify(password, credential))) {
242
+ return found;
243
+ }
244
+ console.error("[@udibo/oauth2] resolveUnknownIdentifier returned an account the identifier and password do not sign in to; refused");
245
+ return null;
246
+ }
247
+ async #completeSignIn(user, identifier) {
201
248
  await this.#resetThrottle("signIn", identifier);
202
249
  if (this.#lockout)
203
250
  await this.#lockout.reset(user.id);
@@ -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
  */
@@ -4,8 +4,9 @@
4
4
  * @module
5
5
  */
6
6
  import { snapshotAuthenticationContext } from "../../utils/authentication-context.js";
7
- import { InvalidClientError, InvalidGrantError, InvalidRequestError, isOAuth2Error, ServerError, } from "../../errors.js";
7
+ import { InvalidClientError, InvalidGrantError, InvalidRequestError, InvalidTargetError, isOAuth2Error, ServerError, } from "../../errors.js";
8
8
  import { challengeMethods as defaultChallengeMethods, getChallengeMethod, validateCodeVerifier, } from "../../utils/pkce.js";
9
+ import { assertStoredResource, resourceIndicatorOf, } from "../_resource-indicator.js";
9
10
  import { authenticateClientCredentials } from "../client-authentication.js";
10
11
  import { sha256Hash } from "../utils/hash.js";
11
12
  import { AbstractGrant, } from "./grant.js";
@@ -38,6 +39,11 @@ export class AuthorizationCodeGrant extends AbstractGrant {
38
39
  * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4.5
39
40
  */
40
41
  requireClientAuthentication;
42
+ /**
43
+ * Whether single-resource indicators are enabled. See
44
+ * {@linkcode AuthorizationCodeGrantOptions.resourceIndicators}.
45
+ */
46
+ resourceIndicators;
41
47
  #onCodeReuse;
42
48
  /** Creates the grant from its {@linkcode AuthorizationCodeGrantOptions}. */
43
49
  constructor(options) {
@@ -50,6 +56,7 @@ export class AuthorizationCodeGrant extends AbstractGrant {
50
56
  this.requireClientAuthentication =
51
57
  options.requireClientAuthentication ?? true;
52
58
  this.#onCodeReuse = options.onCodeReuse;
59
+ this.resourceIndicators = options.resourceIndicators ?? false;
53
60
  }
54
61
  /**
55
62
  * Extracts client credentials from a request, carrying the PKCE
@@ -135,11 +142,20 @@ export class AuthorizationCodeGrant extends AbstractGrant {
135
142
  /**
136
143
  * Generates and saves an authorization code. Resolves its own
137
144
  * `authorizationCodeService` from the request.
145
+ *
146
+ * A code bound to a `resource` is read back after saving; when the store
147
+ * did not keep the exact value, the code is revoked and never returned.
148
+ *
149
+ * @throws {ServerError} When `resource` is given to a grant without
150
+ * `resourceIndicators`, or the store does not round-trip it.
138
151
  */
139
152
  async generateAuthorizationCode(options, request) {
140
153
  const authenticationContext = snapshotAuthenticationContext(options.authenticationContext);
141
154
  const { authorizationCodeService } = await this.resolveServices(request);
142
- const { client, user, scope, redirectUri, challenge, challengeMethod, nonce, } = options;
155
+ const { client, user, scope, redirectUri, challenge, challengeMethod, nonce, resource, } = options;
156
+ if (resource != null && !this.resourceIndicators) {
157
+ throw new ServerError("resource requires resourceIndicators");
158
+ }
143
159
  const authorizationCode = {
144
160
  code: await authorizationCodeService.generateCode(client, user, scope),
145
161
  expiresAt: await authorizationCodeService.expiresAt(client, user, scope),
@@ -159,7 +175,22 @@ export class AuthorizationCodeGrant extends AbstractGrant {
159
175
  if (authenticationContext) {
160
176
  authorizationCode.authenticationContext = authenticationContext;
161
177
  }
162
- return await authorizationCodeService.save(authorizationCode);
178
+ if (resource != null)
179
+ authorizationCode.resource = resource;
180
+ const saved = await authorizationCodeService.save(authorizationCode);
181
+ if (resource != null &&
182
+ (saved.resource !== resource ||
183
+ (await authorizationCodeService.get(authorizationCode.code))
184
+ ?.resource !== resource)) {
185
+ try {
186
+ await authorizationCodeService.revoke(authorizationCode);
187
+ }
188
+ catch (error) {
189
+ console.error("[@udibo/oauth2] could not revoke a code whose store dropped its resource:", error instanceof Error ? error.message : error);
190
+ }
191
+ throw new ServerError("authorization code storage did not preserve resource");
192
+ }
193
+ return saved;
163
194
  }
164
195
  /**
165
196
  * Handles a token request for the authorization code grant.
@@ -197,9 +228,18 @@ export class AuthorizationCodeGrant extends AbstractGrant {
197
228
  * {@linkcode getAuthenticatedClient} resolved from this same `request`.
198
229
  * A code redeemed with PKCE issues its token with `codeVerifierHash` set.
199
230
  *
231
+ * The tokens issued are bound to the code's
232
+ * {@linkcode AuthorizationCode.resource}, when it has one. With
233
+ * {@linkcode resourceIndicators} enabled, a `resource` on the token request
234
+ * must equal it exactly, character for character; a different, malformed
235
+ * or repeated value, or any value for a code issued without a resource, is
236
+ * `invalid_target` and consumes the code like the checks above.
237
+ *
200
238
  * @throws {InvalidRequestError} When `code` is missing, a required `code_verifier` is absent, or the verifier is malformed.
201
239
  * @throws {InvalidGrantError} When the code is unknown, expired, already claimed, or its verifier or `redirect_uri` does not match.
202
240
  * @throws {InvalidClientError} When the code was issued to another client.
241
+ * @throws {InvalidTargetError} When an opted-in token request names a resource other than the code's.
242
+ * @throws {ServerError} When the token store does not round-trip the code's resource.
203
243
  * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
204
244
  * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4.5
205
245
  */
@@ -222,10 +262,11 @@ export class AuthorizationCodeGrant extends AbstractGrant {
222
262
  !(await authorizationCodeService.revoke(authorizationCode))) {
223
263
  throw await this.#refuseClaimedCode(tokenService, replay);
224
264
  }
265
+ const resource = authorizationCode.resource ?? undefined;
225
266
  let token;
226
267
  try {
227
268
  await this.#checkExchange(authorizationCode, client, body);
228
- token = await this.generateToken(client, authorizationCode.user, authorizationCode.scope, tokenService, authorizationCode.authenticationContext);
269
+ token = await this.generateToken(client, authorizationCode.user, authorizationCode.scope, tokenService, authorizationCode.authenticationContext, undefined, resource);
229
270
  }
230
271
  catch (error) {
231
272
  if (exchangeCode) {
@@ -256,6 +297,9 @@ export class AuthorizationCodeGrant extends AbstractGrant {
256
297
  if (!saved) {
257
298
  throw await this.#refuseClaimedCode(tokenService, replay);
258
299
  }
300
+ if (resource !== undefined || this.resourceIndicators) {
301
+ await assertStoredResource(tokenService, saved, resource);
302
+ }
259
303
  if (authorizationCode.nonce)
260
304
  saved.nonce = authorizationCode.nonce;
261
305
  return saved;
@@ -292,6 +336,13 @@ export class AuthorizationCodeGrant extends AbstractGrant {
292
336
  else if (redirectUri) {
293
337
  throw new InvalidGrantError("did not expect redirect_uri parameter");
294
338
  }
339
+ if (this.resourceIndicators) {
340
+ const requested = resourceIndicatorOf(body);
341
+ if (requested !== undefined &&
342
+ requested !== (authorizationCode.resource ?? undefined)) {
343
+ throw new InvalidTargetError("invalid resource");
344
+ }
345
+ }
295
346
  }
296
347
  async #consumeFailedExchange(authorizationCodeService, tokenService, authorizationCode, replay) {
297
348
  try {
@@ -72,7 +72,9 @@ export declare class ClientCredentialsGrant<Client extends ClientInterface, User
72
72
  *
73
73
  * Resource indicators are opt-in through `tokenService.acceptedResource`:
74
74
  * its presence validates one absolute resource URI and requires explicit
75
- * policy acceptance. Its absence preserves legacy extension handling.
75
+ * policy acceptance, and the policy receives
76
+ * `{ grantType: "client_credentials" }` as its fifth argument. Its absence
77
+ * preserves legacy extension handling.
76
78
  *
77
79
  * @throws {InvalidScopeError} If the requested scope is rejected.
78
80
  * @throws {InvalidTargetError} If opted-in resource validation or policy refuses.
@@ -74,7 +74,9 @@ export class ClientCredentialsGrant extends AbstractGrant {
74
74
  *
75
75
  * Resource indicators are opt-in through `tokenService.acceptedResource`:
76
76
  * its presence validates one absolute resource URI and requires explicit
77
- * policy acceptance. Its absence preserves legacy extension handling.
77
+ * policy acceptance, and the policy receives
78
+ * `{ grantType: "client_credentials" }` as its fifth argument. Its absence
79
+ * preserves legacy extension handling.
78
80
  *
79
81
  * @throws {InvalidScopeError} If the requested scope is rejected.
80
82
  * @throws {InvalidTargetError} If opted-in resource validation or policy refuses.
@@ -91,7 +93,7 @@ export class ClientCredentialsGrant extends AbstractGrant {
91
93
  const resourcePolicy = tokenService.acceptedResource;
92
94
  if (resourcePolicy !== undefined) {
93
95
  resource = resourceIndicatorOf(body);
94
- if ((await resourcePolicy.call(tokenService, client, user, resource, scope)) !== true) {
96
+ if ((await resourcePolicy.call(tokenService, client, user, resource, scope, { grantType: this.grantType })) !== true) {
95
97
  throw new InvalidTargetError("invalid resource");
96
98
  }
97
99
  }
@@ -73,6 +73,27 @@ export interface RefreshTokenGrantOptions<Client extends ClientInterface, User,
73
73
  * indefinitely.
74
74
  */
75
75
  replayGraceSeconds?: number;
76
+ /**
77
+ * Opts refresh into single-resource indicators (RFC 8707). Defaults to
78
+ * `false`, which keeps refusing a resource-bound refresh token with
79
+ * `invalid_target` and ignores `resource` on the request.
80
+ *
81
+ * When `true`, a resource-bound refresh token refreshes: the request may
82
+ * repeat its exact {@linkcode RefreshToken.resource} or omit `resource`,
83
+ * and the successor access and refresh tokens keep the binding. For an
84
+ * unbound token any `resource` is `invalid_target`, so a binding is never
85
+ * added at refresh. A different, malformed or repeated value is
86
+ * `invalid_target` and is refused before rotation, leaving the presented
87
+ * token live. Narrowing to, or switching among, other resources is not
88
+ * supported: a token carries at most one.
89
+ *
90
+ * Requires a token store that round-trips {@linkcode Token.resource} on
91
+ * refresh tokens; the grant refuses a successor whose store loses it.
92
+ *
93
+ * @default false
94
+ * @see https://www.rfc-editor.org/rfc/rfc8707.html#section-2.2
95
+ */
96
+ resourceIndicators?: boolean;
76
97
  }
77
98
  /**
78
99
  * The refresh token grant type.
@@ -85,6 +106,11 @@ export declare class RefreshTokenGrant<Client extends ClientInterface, User, S e
85
106
  #private;
86
107
  /** The OAuth2 grant type: `refresh_token`. */
87
108
  readonly grantType = "refresh_token";
109
+ /**
110
+ * Whether single-resource indicators are enabled. See
111
+ * {@linkcode RefreshTokenGrantOptions.resourceIndicators}.
112
+ */
113
+ readonly resourceIndicators: boolean;
88
114
  /** Creates the grant from its {@linkcode RefreshTokenGrantOptions}. */
89
115
  constructor(options: RefreshTokenGrantOptions<Client, User, S>);
90
116
  /**
@@ -115,8 +141,11 @@ export declare class RefreshTokenGrant<Client extends ClientInterface, User, S e
115
141
  * claimed it.
116
142
  * @throws {InvalidClientError} If the token was issued to another client.
117
143
  * @throws {InvalidScopeError} If the requested scope exceeds the original grant.
118
- * @throws {InvalidTargetError} If a stored parent is resource-bound; refreshing
119
- * such a grant is unsupported and refuses before spending the parent.
144
+ * @throws {InvalidTargetError} Before spending the presented token: without
145
+ * {@linkcode resourceIndicators}, when it is resource-bound; with it, when
146
+ * the request names a resource other than the token's own binding.
147
+ * @throws {ServerError} If the token store does not round-trip a successor's
148
+ * resource.
120
149
  */
121
150
  token(request: Request, client: Client, body: FormData): Promise<RefreshToken<Client, User, S>>;
122
151
  }
@@ -4,6 +4,7 @@
4
4
  * @module
5
5
  */
6
6
  import { InvalidClientError, InvalidGrantError, InvalidRequestError, InvalidScopeError, InvalidTargetError, } from "../../errors.js";
7
+ import { assertStoredResource, resourceIndicatorOf, } from "../_resource-indicator.js";
7
8
  import { AbstractGrant, } from "./grant.js";
8
9
  const REPLAY_GRACE_CLOCK_TOLERANCE_SECONDS = 300;
9
10
  /**
@@ -18,6 +19,11 @@ export class RefreshTokenGrant extends AbstractGrant {
18
19
  grantType = "refresh_token";
19
20
  #onTokenReuse;
20
21
  #replayGraceSeconds;
22
+ /**
23
+ * Whether single-resource indicators are enabled. See
24
+ * {@linkcode RefreshTokenGrantOptions.resourceIndicators}.
25
+ */
26
+ resourceIndicators;
21
27
  /** Creates the grant from its {@linkcode RefreshTokenGrantOptions}. */
22
28
  constructor(options) {
23
29
  super({ ...options, allowRefreshToken: true });
@@ -27,6 +33,7 @@ export class RefreshTokenGrant extends AbstractGrant {
27
33
  throw new RangeError(`replayGraceSeconds must be a non-negative number of seconds, got ${graceSeconds}`);
28
34
  }
29
35
  this.#replayGraceSeconds = graceSeconds;
36
+ this.resourceIndicators = options.resourceIndicators ?? false;
30
37
  }
31
38
  /**
32
39
  * Handles a token request for the refresh token grant. Issues a new access
@@ -56,8 +63,11 @@ export class RefreshTokenGrant extends AbstractGrant {
56
63
  * claimed it.
57
64
  * @throws {InvalidClientError} If the token was issued to another client.
58
65
  * @throws {InvalidScopeError} If the requested scope exceeds the original grant.
59
- * @throws {InvalidTargetError} If a stored parent is resource-bound; refreshing
60
- * such a grant is unsupported and refuses before spending the parent.
66
+ * @throws {InvalidTargetError} Before spending the presented token: without
67
+ * {@linkcode resourceIndicators}, when it is resource-bound; with it, when
68
+ * the request names a resource other than the token's own binding.
69
+ * @throws {ServerError} If the token store does not round-trip a successor's
70
+ * resource.
61
71
  */
62
72
  async token(request, client, body) {
63
73
  const { tokenService } = await this.resolveServices(request);
@@ -94,9 +104,16 @@ export class RefreshTokenGrant extends AbstractGrant {
94
104
  if (client.id.toString() !== tokenClient.id.toString()) {
95
105
  throw new InvalidClientError("refresh_token was issued to another client");
96
106
  }
97
- if (currentToken.resource !== undefined) {
98
- // Resource-bound refresh is not implemented. Never spend the parent or
99
- // issue a successor that silently loses its audience restriction.
107
+ const resource = this.resourceIndicators
108
+ ? (currentToken.resource ?? undefined)
109
+ : undefined;
110
+ if (this.resourceIndicators) {
111
+ const requested = resourceIndicatorOf(body);
112
+ if (requested !== undefined && requested !== resource) {
113
+ throw new InvalidTargetError("invalid resource");
114
+ }
115
+ }
116
+ else if (currentToken.resource !== undefined) {
100
117
  throw new InvalidTargetError("resource-bound refresh is not supported");
101
118
  }
102
119
  // RFC 6749 §6: a requested scope may only narrow, never exceed, the original grant.
@@ -117,7 +134,7 @@ export class RefreshTokenGrant extends AbstractGrant {
117
134
  if (familyExpiresAt && familyExpiresAt.getTime() <= Date.now()) {
118
135
  throw new InvalidGrantError("refresh_token family expired");
119
136
  }
120
- const nextToken = await this.generateToken(client, user, nextScope, tokenService, currentToken.authenticationContext, familyExpiresAt);
137
+ const nextToken = await this.generateToken(client, user, nextScope, tokenService, currentToken.authenticationContext, familyExpiresAt, resource);
121
138
  const nextRefreshToken = "refreshToken" in nextToken
122
139
  ? nextToken
123
140
  : {
@@ -139,6 +156,9 @@ export class RefreshTokenGrant extends AbstractGrant {
139
156
  if (!rotated) {
140
157
  throw new InvalidGrantError("refresh_token was already consumed");
141
158
  }
159
+ if (this.resourceIndicators) {
160
+ await assertStoredResource(tokenService, rotated, resource);
161
+ }
142
162
  return rotated;
143
163
  }
144
164
  const claimed = tokenService.revokeRotated
@@ -147,7 +167,11 @@ export class RefreshTokenGrant extends AbstractGrant {
147
167
  if (!claimed) {
148
168
  throw new InvalidGrantError("refresh_token was already consumed");
149
169
  }
150
- return await tokenService.save(nextRefreshToken);
170
+ const saved = await tokenService.save(nextRefreshToken);
171
+ if (this.resourceIndicators) {
172
+ await assertStoredResource(tokenService, saved, resource);
173
+ }
174
+ return saved;
151
175
  }
152
176
  async #withinReplayGrace(tokenService, replayed) {
153
177
  const { rotatedAt, familyId } = replayed;
@@ -21,7 +21,10 @@ export interface AuthorizationCodeServiceInterface<Client extends ClientInterfac
21
21
  get(code: string): Promise<AuthorizationCode<Client, User, Scope> | undefined>;
22
22
  /**
23
23
  * Saves an authorization code, preserving its `authenticationContext`
24
- * snapshot on save and retrieval. Leave legacy context absent.
24
+ * snapshot on save and retrieval. Leave legacy context absent. When the
25
+ * authorization code grant enables `resourceIndicators`, also persist
26
+ * `resource` exactly and restore it from {@linkcode get}; the grant reads
27
+ * the code back after saving it and refuses to issue one that lost it.
25
28
  */
26
29
  save(authorizationCode: AuthorizationCode<Client, User, Scope>): Promise<AuthorizationCode<Client, User, Scope>>;
27
30
  /**
@@ -6,6 +6,29 @@ import type { RefreshToken, Token } from "../../models/token.ts";
6
6
  import type { AbstractScope, BasicScope } from "../../models/scope.ts";
7
7
  import type { ClientServiceInterface } from "./client.ts";
8
8
  import type { UserServiceInterface } from "./user.ts";
9
+ /**
10
+ * Identifies which grant is asking
11
+ * {@linkcode TokenServiceInterface.acceptedResource} for a decision, passed as
12
+ * its fifth argument. One policy serves machine issuance
13
+ * (`client_credentials`, where `user` is whatever
14
+ * `ClientServiceInterface.getUser` resolves for the client and nobody
15
+ * interacts) and user issuance at the authorization endpoint
16
+ * (`authorization_code`, after a person signed in and consented), so a policy
17
+ * that should treat them differently reads `grantType`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const context: ResourcePolicyContext = { grantType: "authorization_code" };
22
+ * ```
23
+ */
24
+ export interface ResourcePolicyContext {
25
+ /**
26
+ * The grant asking: `client_credentials` at the token endpoint, or
27
+ * `authorization_code` at the authorization endpoint. A custom grant may
28
+ * pass its own `grant_type`.
29
+ */
30
+ readonly grantType: string;
31
+ }
9
32
  /**
10
33
  * Minimal interface for reading/validating tokens.
11
34
  *
@@ -51,18 +74,33 @@ export interface TokenServiceInterface<Client extends ClientInterface, User, Sco
51
74
  */
52
75
  acceptedScope(client: Client, user: User | undefined, scope?: Scope | null): Promise<Scope | null | undefined | false>;
53
76
  /**
54
- * Opts client-credentials issuance into one RFC 8707 resource per token.
55
- * Called after client authentication and scope acceptance, even when no
56
- * resource was supplied. Only `true` accepts; other results refuse with
77
+ * Decides whether one RFC 8707 resource may be bound to a token. Its
78
+ * presence opts client-credentials issuance into one resource per token;
79
+ * the authorization code grant consults it at the authorization endpoint
80
+ * only when constructed with `resourceIndicators: true`. Called after
81
+ * client authentication and scope acceptance (after consent at the
82
+ * authorization endpoint, with the consented scope), even when no resource
83
+ * was supplied. Only `true` accepts; other results refuse with
57
84
  * `invalid_target`. The URI is validated and passed unchanged; decide
58
85
  * resource availability, client authority and scope compatibility here.
86
+ * `user` is the signed-in user at the authorization endpoint, and the
87
+ * client's own user, if any, for client credentials.
88
+ *
89
+ * One policy serves both grants. The optional fifth argument names the
90
+ * grant asking ({@linkcode ResourcePolicyContext}); check `client` as well
91
+ * as `user`, or a machine client whose `getUser` resolves a person can be
92
+ * bound to any resource that person may use, with no interaction. The
93
+ * comparison of the bound value at later steps is exact, so accept only the
94
+ * canonical spelling of each resource: a variant spelling accepted here is
95
+ * stored as given and becomes the token's `aud`, which a resource server
96
+ * expecting the canonical value rejects.
59
97
  *
60
98
  * Leave this method absent to preserve legacy extension-parameter behavior.
61
99
  * Enabling it requires persisting `Token.resource` and forwarding the sixth
62
- * `generateAccessToken` argument to signed-token generation. Other grants
63
- * do not support resource indicators yet.
100
+ * `generateAccessToken` argument to signed-token generation. The device
101
+ * authorization and password grants do not support resource indicators.
64
102
  */
65
- acceptedResource?(client: Client, user: User | undefined, resource: string | undefined, scope?: Scope | null): Promise<boolean>;
103
+ acceptedResource?(client: Client, user: User | undefined, resource: string | undefined, scope?: Scope | null, context?: ResourcePolicyContext): Promise<boolean>;
66
104
  /**
67
105
  * Generates an access token string. `user` is `undefined` for a client
68
106
  * acting as its own resource owner (client credentials) — a signed-token
@@ -74,9 +112,11 @@ export interface TokenServiceInterface<Client extends ClientInterface, User, Sco
74
112
  * a signed token's `exp` never outlives what the server itself honors; the
75
113
  * grants always pass it, and a wrapper that drops it leaves offline
76
114
  * verifiers accepting the token past its stored expiry.
77
- * `resource`, when supplied by an opted-in machine grant, is the accepted
78
- * target URI. A signed token must restrict its audience to this value;
79
- * dropping it can issue a token for a different API.
115
+ * `resource`, when supplied, is the URI the token is bound to: accepted by
116
+ * an opted-in client-credentials policy, or carried from a resource-bound
117
+ * authorization code or refresh token. A signed token must restrict its
118
+ * audience to this value; dropping it can issue a token for a different
119
+ * API.
80
120
  */
81
121
  generateAccessToken(client: Client, user: User | undefined, scope?: Scope | null, authenticationContext?: AuthenticationContext, expiresAt?: Date, resource?: string): Promise<string>;
82
122
  /** Generates a refresh token string. */
@@ -116,8 +156,11 @@ export interface TokenServiceInterface<Client extends ClientInterface, User, Sco
116
156
  * Persists either token kind and returns the saved record. Preserve
117
157
  * `authenticationContext` on save and every read, including refresh and
118
158
  * revoked records; never reconstruct it from a user's current session.
119
- * Preserve `resource` exactly too when resource policy is enabled. The
120
- * client-credentials grant refuses a saved result that loses its binding.
159
+ * Preserve `resource` exactly too when resource policy is enabled, on
160
+ * access, refresh and revoked records alike. The grants refuse a saved
161
+ * result that loses its binding, and the authorization code and refresh
162
+ * grants also read a bound token back through `getToken` and
163
+ * `getRefreshToken` to check it.
121
164
  */
122
165
  save(token: Token<Client, User, Scope> | RefreshToken<Client, User, Scope>): Promise<Token<Client, User, Scope> | RefreshToken<Client, User, Scope>>;
123
166
  /** Revokes a token record. Resolves true if a token was revoked. */
@@ -32,6 +32,13 @@ export interface AuthorizationCodeServiceContractOptions<C extends ClientInterfa
32
32
  makeClient?(seq: number): C;
33
33
  /** Overrides the name passed to the outer `describe` block. */
34
34
  describeName?: string;
35
+ /**
36
+ * A resource URI whose exact save/get round trip to check. Supply it when
37
+ * this store backs an authorization code grant with `resourceIndicators`
38
+ * enabled; leave absent for stores that only support codes without a
39
+ * resource.
40
+ */
41
+ supportedResource?: string;
35
42
  }
36
43
  /** Runs the {@link AuthorizationCodeServiceInterface} contract suite. */
37
44
  export declare function runAuthorizationCodeServiceContractTests<C extends ClientInterface, U extends MemoryUserShape, S extends AbstractScope = BasicScope>(options: AuthorizationCodeServiceContractOptions<C, U, S>): void;
@@ -57,6 +57,21 @@ export function runAuthorizationCodeServiceContractTests(options) {
57
57
  expect(fetched?.challenge).toStrictEqual("abc");
58
58
  expect(fetched?.nonce).toStrictEqual("nonce-1");
59
59
  });
60
+ if (options.supportedResource !== undefined) {
61
+ it("preserves the exact resource through save and get", async () => {
62
+ const resource = options.supportedResource;
63
+ const code = await codeService.generateCode(client, user);
64
+ const saved = await codeService.save({
65
+ code,
66
+ expiresAt: await codeService.expiresAt(client, user),
67
+ client,
68
+ user,
69
+ resource,
70
+ });
71
+ expect(saved.resource).toBe(resource);
72
+ expect((await codeService.get(code))?.resource, "a store must retain the accepted resource, not just return its input from save").toBe(resource);
73
+ });
74
+ }
60
75
  it("get returns undefined for an unknown code", async () => {
61
76
  expect(await codeService.get("missing")).toBe(undefined);
62
77
  });
@@ -96,6 +96,13 @@ export interface CodeExchangeContractOptions<C extends ClientInterface, U extend
96
96
  * `exchangeCode` saved. Defaults to `true`.
97
97
  */
98
98
  revokeCodeChecksVerifier?: boolean;
99
+ /**
100
+ * A resource URI whose exact round trip through `exchangeCode` to check:
101
+ * the token it resolves and the token `getToken` reads back keep the
102
+ * code's `resource`. Supply it when this store backs an authorization code
103
+ * grant with `resourceIndicators` enabled; leave absent otherwise.
104
+ */
105
+ supportedResource?: string;
99
106
  /** Overrides the name passed to the outer `describe` block. */
100
107
  describeName?: string;
101
108
  }
@@ -190,6 +190,17 @@ export function runCodeExchangeContractTests(options) {
190
190
  expect(await tokenService.revokeCode(authorizationCode.code, client), "revokeCode must find the token exchangeCode saved by its code").toBe(true);
191
191
  expect(await live([token])).toStrictEqual([]);
192
192
  });
193
+ if (options.supportedResource !== undefined) {
194
+ it("keeps the code's resource on the token it saves", async () => {
195
+ const resource = options.supportedResource;
196
+ const authorizationCode = await savedCode();
197
+ authorizationCode.resource = resource;
198
+ const token = { ...(await tokenFor(authorizationCode)), resource };
199
+ const saved = await exchangeCode(authorizationCode, token);
200
+ expect(saved?.resource).toBe(resource);
201
+ expect((await tokenService.getToken(token.accessToken))?.resource, "a store must retain the binding, not just return its input").toBe(resource);
202
+ });
203
+ }
193
204
  it("revokes the token it saved for the codeVerifierHash it was saved with", async () => {
194
205
  const authorizationCode = await savedCode();
195
206
  const token = await tokenFor(authorizationCode);
@@ -61,6 +61,18 @@ export interface TokenServiceContractOptions<C extends ClientInterface, U extend
61
61
  * not the application's resource authorization policy.
62
62
  */
63
63
  supportedResource?: string;
64
+ /**
65
+ * A resource URI whose exact round trip through refresh tokens to check:
66
+ * `save` and `getRefreshToken` of a bound refresh token and `getToken` of
67
+ * its access token, the successor of a rotation (through `rotate` when the
68
+ * service implements it), and the rotated-out record from
69
+ * `getRevokedRefreshToken` when the service implements it. Supply it when
70
+ * this store backs the authorization code and refresh grants with
71
+ * `resourceIndicators` enabled; a store that drops the field on a later
72
+ * read silently unbinds the next exchange or refresh. Leave absent
73
+ * otherwise; it is independent of {@linkcode supportedResource}.
74
+ */
75
+ supportedRefreshResource?: string;
64
76
  /**
65
77
  * Returns a new rotation-family id the store accepts as a
66
78
  * {@linkcode RefreshToken.familyId}, distinct on every call. The family cases
@@ -106,6 +106,43 @@ export function runTokenServiceContractTests(options) {
106
106
  });
107
107
  }
108
108
  }
109
+ if (options.supportedRefreshResource !== undefined) {
110
+ describe("resource-bound refresh tokens", () => {
111
+ const resource = options.supportedRefreshResource;
112
+ async function boundMember(familyId) {
113
+ return {
114
+ ...(await familyMember(familyId)),
115
+ scope: makeScope(supportedScope),
116
+ resource,
117
+ };
118
+ }
119
+ it("preserves the exact resource through save, getToken and getRefreshToken", async () => {
120
+ const token = await boundMember(makeFamilyId());
121
+ expect((await tokenService.save(token)).resource).toBe(resource);
122
+ expect((await tokenService.getRefreshToken(token.refreshToken))?.resource, "getRefreshToken must restore the binding, or refresh mints unbound tokens").toBe(resource);
123
+ expect((await tokenService.getToken(token.accessToken))?.resource).toBe(resource);
124
+ });
125
+ it("preserves the exact resource on a rotation's successor and on the rotated-out record", async () => {
126
+ const familyId = makeFamilyId();
127
+ const current = await boundMember(familyId);
128
+ await tokenService.save(current);
129
+ const next = await boundMember(familyId);
130
+ if (tokenService.rotate) {
131
+ const rotated = await tokenService.rotate(current, next);
132
+ expect(rotated?.resource).toBe(resource);
133
+ }
134
+ else {
135
+ await rotateTo(current, next);
136
+ }
137
+ expect((await tokenService.getRefreshToken(next.refreshToken))?.resource).toBe(resource);
138
+ expect((await tokenService.getToken(next.accessToken))?.resource).toBe(resource);
139
+ if (tokenService.getRevokedRefreshToken) {
140
+ expect((await tokenService.getRevokedRefreshToken(current.refreshToken))
141
+ ?.resource).toBe(resource);
142
+ }
143
+ });
144
+ });
145
+ }
109
146
  describe("generateAccessToken / generateRefreshToken", () => {
110
147
  it("produces unique access tokens", async () => {
111
148
  const a = await tokenService.generateAccessToken(client, user);
@@ -352,7 +352,7 @@ export declare class MemoryAuthorizationCodeService<C extends ClientInterface, U
352
352
  get(code: string): Promise<AuthorizationCode<C, U, S> | undefined>;
353
353
  /**
354
354
  * Persists an authorization code indexed by its hash, including the PKCE
355
- * challenge and redirect URI. Returns the input unchanged.
355
+ * challenge, redirect URI and resource. Returns the input unchanged.
356
356
  */
357
357
  save(authorizationCode: AuthorizationCode<C, U, S>): Promise<AuthorizationCode<C, U, S>>;
358
358
  /**
@@ -616,7 +616,7 @@ export class MemoryAuthorizationCodeService {
616
616
  const user = await this.#userService.get(stored.userId);
617
617
  if (!client || !user)
618
618
  return undefined;
619
- return {
619
+ const authorizationCode = {
620
620
  code,
621
621
  expiresAt: stored.expiresAt,
622
622
  client,
@@ -628,10 +628,14 @@ export class MemoryAuthorizationCodeService {
628
628
  nonce: stored.nonce,
629
629
  authenticationContext: snapshotAuthenticationContext(stored.authenticationContext),
630
630
  };
631
+ if (stored.resource !== undefined) {
632
+ authorizationCode.resource = stored.resource;
633
+ }
634
+ return authorizationCode;
631
635
  }
632
636
  /**
633
637
  * Persists an authorization code indexed by its hash, including the PKCE
634
- * challenge and redirect URI. Returns the input unchanged.
638
+ * challenge, redirect URI and resource. Returns the input unchanged.
635
639
  */
636
640
  async save(authorizationCode) {
637
641
  const hashed = await sha256Hash(authorizationCode.code);
@@ -646,6 +650,9 @@ export class MemoryAuthorizationCodeService {
646
650
  challengeMethod: authorizationCode.challengeMethod,
647
651
  nonce: authorizationCode.nonce,
648
652
  authenticationContext: snapshotAuthenticationContext(authorizationCode.authenticationContext),
653
+ ...(authorizationCode.resource !== undefined
654
+ ? { resource: authorizationCode.resource }
655
+ : {}),
649
656
  });
650
657
  return authorizationCode;
651
658
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.51.0",
3
+ "version": "0.53.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",