@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.
- package/dist/identity/events.d.ts +1 -1
- package/dist/identity/mod.d.ts +1 -1
- package/dist/identity/service.d.ts +30 -5
- package/dist/identity/service.js +30 -7
- package/dist/identity/sign-in-link-binding.d.ts +13 -13
- package/dist/identity/sign-in-link-binding.js +13 -13
- package/dist/identity/token-flow.d.ts +5 -1
- package/dist/models/authentication.d.ts +11 -0
- package/dist/models/authorization-code.d.ts +9 -0
- package/dist/models/token.d.ts +7 -4
- package/dist/server/_resource-indicator.d.ts +13 -1
- package/dist/server/_resource-indicator.js +35 -4
- package/dist/server/authorization-server.d.ts +27 -1
- package/dist/server/authorization-server.js +38 -2
- package/dist/server/grants/authorization-code.d.ts +52 -0
- package/dist/server/grants/authorization-code.js +55 -4
- package/dist/server/grants/client-credentials.d.ts +3 -1
- package/dist/server/grants/client-credentials.js +4 -2
- package/dist/server/grants/refresh-token.d.ts +31 -2
- package/dist/server/grants/refresh-token.js +31 -7
- package/dist/server/services/authorization-code.d.ts +4 -1
- package/dist/server/services/token.d.ts +54 -11
- package/dist/testing/contract/authorization-code.d.ts +7 -0
- package/dist/testing/contract/authorization-code.js +15 -0
- package/dist/testing/contract/code-exchange.d.ts +7 -0
- package/dist/testing/contract/code-exchange.js +11 -0
- package/dist/testing/contract/token-flow-store.js +5 -1
- package/dist/testing/contract/token.d.ts +12 -0
- package/dist/testing/contract/token.js +37 -0
- package/dist/testing/services.d.ts +1 -1
- package/dist/testing/services.js +9 -2
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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
|
|
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
|
|
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}
|
|
119
|
-
*
|
|
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}
|
|
60
|
-
*
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
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.
|
|
63
|
-
* do not support resource indicators
|
|
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
|
|
78
|
-
*
|
|
79
|
-
*
|
|
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
|
|
120
|
-
*
|
|
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);
|
|
@@ -74,7 +74,11 @@ export function runTokenFlowStoreContractTests(options) {
|
|
|
74
74
|
it("round-trips every field of a saved record", async () => {
|
|
75
75
|
const saved = record({
|
|
76
76
|
tokenHash: hash("1"),
|
|
77
|
-
data: {
|
|
77
|
+
data: {
|
|
78
|
+
email: "user@example.com",
|
|
79
|
+
binding: "a-sign-in-link-binding",
|
|
80
|
+
nested: { list: [1, "two"] },
|
|
81
|
+
},
|
|
78
82
|
});
|
|
79
83
|
await store.save(saved);
|
|
80
84
|
const fetched = await store.get(hash("1"));
|
|
@@ -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
|
|
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
|
/**
|
package/dist/testing/services.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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.
|
|
3
|
+
"version": "0.52.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",
|