@udibo/oauth2 0.46.0 → 0.48.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/client/direct-client.d.ts +15 -0
- package/dist/client/direct-client.js +92 -34
- package/dist/identity/lockout.d.ts +62 -6
- package/dist/identity/lockout.js +37 -2
- package/dist/identity/service.d.ts +4 -1
- package/dist/identity/service.js +55 -9
- package/dist/identity/token-flow.d.ts +24 -3
- package/dist/identity/token-flow.js +24 -6
- package/dist/react/context.d.ts +4 -1
- package/dist/react/provider.js +8 -2
- package/dist/server/grants/device-authorization.d.ts +6 -0
- package/dist/server/grants/device-authorization.js +25 -4
- package/dist/server/services/device-authorization.d.ts +17 -1
- package/dist/server/services/token.d.ts +17 -0
- package/dist/testing/contract/device-authorization.js +83 -0
- package/dist/testing/contract/device-code-exchange.d.ts +112 -0
- package/dist/testing/contract/device-code-exchange.js +242 -0
- package/dist/testing/contract/lockout-store.d.ts +15 -4
- package/dist/testing/contract/lockout-store.js +77 -7
- package/dist/testing/contract/mod.d.ts +6 -0
- package/dist/testing/contract/mod.js +6 -0
- package/dist/testing/contract/token-flow-store.d.ts +10 -0
- package/dist/testing/contract/token-flow-store.js +47 -0
- package/dist/testing/services.d.ts +26 -6
- package/dist/testing/services.js +55 -14
- package/package.json +1 -1
|
@@ -80,6 +80,12 @@ export declare class DeviceAuthorizationGrant<Client extends ClientInterface, Us
|
|
|
80
80
|
*
|
|
81
81
|
* The device code is claimed by revoking it once the user has approved, so
|
|
82
82
|
* concurrent polls of one approved device code cannot both receive a token.
|
|
83
|
+
* When the token service implements
|
|
84
|
+
* {@linkcode TokenServiceInterface.exchangeDeviceCode}, the claim and the
|
|
85
|
+
* token's save are that one call, and a save that fails leaves the approval
|
|
86
|
+
* for the next poll; otherwise the grant revokes and then saves, and a
|
|
87
|
+
* failed save spends the approval. A token that cannot be generated spends
|
|
88
|
+
* it either way.
|
|
83
89
|
* Recording the poll time is bookkeeping for `slow_down` only: it is skipped
|
|
84
90
|
* on every outcome that revokes the authorization. When the store **raises**
|
|
85
91
|
* for the vanished record — as it must, if a lost race is to be
|
|
@@ -75,6 +75,12 @@ export class DeviceAuthorizationGrant extends AbstractGrant {
|
|
|
75
75
|
*
|
|
76
76
|
* The device code is claimed by revoking it once the user has approved, so
|
|
77
77
|
* concurrent polls of one approved device code cannot both receive a token.
|
|
78
|
+
* When the token service implements
|
|
79
|
+
* {@linkcode TokenServiceInterface.exchangeDeviceCode}, the claim and the
|
|
80
|
+
* token's save are that one call, and a save that fails leaves the approval
|
|
81
|
+
* for the next poll; otherwise the grant revokes and then saves, and a
|
|
82
|
+
* failed save spends the approval. A token that cannot be generated spends
|
|
83
|
+
* it either way.
|
|
78
84
|
* Recording the poll time is bookkeeping for `slow_down` only: it is skipped
|
|
79
85
|
* on every outcome that revokes the authorization. When the store **raises**
|
|
80
86
|
* for the vanished record — as it must, if a lost race is to be
|
|
@@ -129,11 +135,26 @@ export class DeviceAuthorizationGrant extends AbstractGrant {
|
|
|
129
135
|
throw new AuthorizationPendingError("authorization request is pending user approval");
|
|
130
136
|
}
|
|
131
137
|
const { user, scope } = authorization;
|
|
132
|
-
|
|
133
|
-
|
|
138
|
+
const exchangeDeviceCode = tokenService.exchangeDeviceCode?.bind(tokenService);
|
|
139
|
+
if (!exchangeDeviceCode) {
|
|
140
|
+
if (!(await deviceAuthorizationService.revoke(authorization))) {
|
|
141
|
+
throw new InvalidGrantError("device_code already used");
|
|
142
|
+
}
|
|
143
|
+
const token = await this.generateToken(client, user, scope, tokenService);
|
|
144
|
+
return await tokenService.save(token);
|
|
145
|
+
}
|
|
146
|
+
let token;
|
|
147
|
+
try {
|
|
148
|
+
token = await this.generateToken(client, user, scope, tokenService);
|
|
134
149
|
}
|
|
135
|
-
|
|
136
|
-
|
|
150
|
+
catch (error) {
|
|
151
|
+
await deviceAuthorizationService.revoke(authorization);
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
const saved = await exchangeDeviceCode(authorization, token);
|
|
155
|
+
if (!saved)
|
|
156
|
+
throw new InvalidGrantError("device_code already used");
|
|
157
|
+
return saved;
|
|
137
158
|
}
|
|
138
159
|
async #recordPoll(deviceAuthorizationService, authorization, deviceCode) {
|
|
139
160
|
try {
|
|
@@ -14,7 +14,7 @@ import type { AbstractScope } from "../../models/scope.ts";
|
|
|
14
14
|
* - Generating and storing device codes and user codes
|
|
15
15
|
* - Looking up device codes for polling
|
|
16
16
|
* - Looking up user codes for user authorization
|
|
17
|
-
* - Marking codes as authorized or denied
|
|
17
|
+
* - Marking pending codes as authorized or denied, once
|
|
18
18
|
* - Cleaning up expired codes
|
|
19
19
|
*
|
|
20
20
|
* **Every method taking a `DeviceAuthorization` must accept the records this
|
|
@@ -82,6 +82,17 @@ export interface DeviceAuthorizationServiceInterface<Client extends ClientInterf
|
|
|
82
82
|
/**
|
|
83
83
|
* Marks a device authorization as authorized by the user.
|
|
84
84
|
*
|
|
85
|
+
* **Approve only a pending authorization, in one conditional write.** The
|
|
86
|
+
* record must still be stored, unexpired, and neither approved nor denied;
|
|
87
|
+
* otherwise reject and change nothing. In SQL this is an `UPDATE ... WHERE
|
|
88
|
+
* device_code = $1 AND NOT authorized AND NOT denied AND expires_at > now()`
|
|
89
|
+
* whose affected-row count decides. Never re-create a record that is gone:
|
|
90
|
+
* the grant claims an authorization by revoking it, so an upsert here
|
|
91
|
+
* after the claim makes the spent device code redeemable for a second
|
|
92
|
+
* token. A second approval must not re-bind the device to another user. To
|
|
93
|
+
* withdraw an approval before the device claims it, call
|
|
94
|
+
* {@linkcode DeviceAuthorizationServiceInterface.revoke}.
|
|
95
|
+
*
|
|
85
96
|
* @param authorization The authorization to approve
|
|
86
97
|
* @param user The user who approved the request
|
|
87
98
|
* @param scope Optional scope (may be narrower than originally requested)
|
|
@@ -89,6 +100,11 @@ export interface DeviceAuthorizationServiceInterface<Client extends ClientInterf
|
|
|
89
100
|
approve(authorization: DeviceAuthorization<Client, User, Scope>, user: User, scope?: Scope | null): Promise<DeviceAuthorization<Client, User, Scope>>;
|
|
90
101
|
/**
|
|
91
102
|
* Marks a device authorization as denied by the user.
|
|
103
|
+
*
|
|
104
|
+
* The same precondition as
|
|
105
|
+
* {@linkcode DeviceAuthorizationServiceInterface.approve} applies: deny only
|
|
106
|
+
* a stored, unexpired authorization that is neither approved nor denied, in
|
|
107
|
+
* one conditional write, and reject otherwise without re-creating it.
|
|
92
108
|
*/
|
|
93
109
|
deny(authorization: DeviceAuthorization<Client, User, Scope>): Promise<DeviceAuthorization<Client, User, Scope>>;
|
|
94
110
|
/**
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ClientInterface } from "../../models/client.ts";
|
|
2
2
|
import type { AuthenticationContext } from "../../models/authentication.ts";
|
|
3
3
|
import type { AuthorizationCode } from "../../models/authorization-code.ts";
|
|
4
|
+
import type { DeviceAuthorization } from "../../models/device-authorization.ts";
|
|
4
5
|
import type { RefreshToken, Token } from "../../models/token.ts";
|
|
5
6
|
import type { AbstractScope, BasicScope } from "../../models/scope.ts";
|
|
6
7
|
import type { ClientServiceInterface } from "./client.ts";
|
|
@@ -236,6 +237,22 @@ export interface TokenServiceInterface<Client extends ClientInterface, User, Sco
|
|
|
236
237
|
* the store's barrier wired between its claim and its insert.
|
|
237
238
|
*/
|
|
238
239
|
exchangeCode?(authorizationCode: AuthorizationCode<Client, User, Scope>, token: Token<Client, User, Scope>): Promise<Token<Client, User, Scope> | undefined>;
|
|
240
|
+
/**
|
|
241
|
+
* Redeems an approved device authorization in one atomic step: claims
|
|
242
|
+
* `authorization` as `DeviceAuthorizationServiceInterface.revoke` would,
|
|
243
|
+
* removing it by both of its codes, and persists `token`, the token issued
|
|
244
|
+
* from it, or does neither. Resolves the saved token, or `undefined` with
|
|
245
|
+
* nothing persisted when the authorization was already claimed or never
|
|
246
|
+
* stored. Concurrent calls for one device code persist exactly one token.
|
|
247
|
+
*
|
|
248
|
+
* When implemented, the device authorization grant calls it instead of
|
|
249
|
+
* claiming with `revoke` and saving with {@linkcode save}. Without it, the
|
|
250
|
+
* grant claims and then saves in two calls, so a save that fails after the
|
|
251
|
+
* claim spends the user's approval and the device must start over. A failed
|
|
252
|
+
* insert must leave the authorization claimable; committing the delete and
|
|
253
|
+
* the insert in one database transaction meets this.
|
|
254
|
+
*/
|
|
255
|
+
exchangeDeviceCode?(authorization: DeviceAuthorization<Client, User, Scope>, token: Token<Client, User, Scope>): Promise<Token<Client, User, Scope> | undefined>;
|
|
239
256
|
/**
|
|
240
257
|
* Looks up a refresh token that has already been revoked/rotated out. The
|
|
241
258
|
* refresh grant's reuse detection reads it, and so does the revocation
|
|
@@ -180,6 +180,89 @@ export function runDeviceAuthorizationServiceContractTests(options) {
|
|
|
180
180
|
const refetched = await deviceService.getByDeviceCode(auth.deviceCode);
|
|
181
181
|
expect(refetched?.denied).toBe(true);
|
|
182
182
|
});
|
|
183
|
+
async function expectRefused(decision, why) {
|
|
184
|
+
let refused = false;
|
|
185
|
+
try {
|
|
186
|
+
await decision;
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
refused = true;
|
|
190
|
+
}
|
|
191
|
+
expect(refused, why).toBe(true);
|
|
192
|
+
}
|
|
193
|
+
it("approve refuses an authorization that was already claimed, without restoring it", async () => {
|
|
194
|
+
const { auth, byUserCode } = await saveDeviceAuth();
|
|
195
|
+
expect(await deviceService.revoke(auth)).toBe(true);
|
|
196
|
+
await expectRefused(deviceService.approve(byUserCode, user), "approving a claimed or cancelled authorization must reject");
|
|
197
|
+
await assertUnreachableByEitherCode(auth);
|
|
198
|
+
});
|
|
199
|
+
it("deny refuses an authorization that was already claimed, without restoring it", async () => {
|
|
200
|
+
const { auth, byUserCode } = await saveDeviceAuth();
|
|
201
|
+
expect(await deviceService.revoke(auth)).toBe(true);
|
|
202
|
+
await expectRefused(deviceService.deny(byUserCode), "denying a claimed or cancelled authorization must reject");
|
|
203
|
+
await assertUnreachableByEitherCode(auth);
|
|
204
|
+
});
|
|
205
|
+
it("approve refuses an authorization the user already approved, keeping the first approval", async () => {
|
|
206
|
+
const { auth, byUserCode } = await saveDeviceAuth();
|
|
207
|
+
const other = makeUser(2);
|
|
208
|
+
await options.addUser(userService, other, "pw");
|
|
209
|
+
await deviceService.approve(byUserCode, user);
|
|
210
|
+
await expectRefused(deviceService.approve(byUserCode, other), "a second approval must not re-bind the device to another user");
|
|
211
|
+
const refetched = await deviceService.getByDeviceCode(auth.deviceCode);
|
|
212
|
+
expect(refetched?.user?.id).toStrictEqual(user.id);
|
|
213
|
+
});
|
|
214
|
+
it("approve refuses a denied authorization, which stays denied", async () => {
|
|
215
|
+
const { auth, byUserCode } = await saveDeviceAuth();
|
|
216
|
+
await deviceService.deny(byUserCode);
|
|
217
|
+
await expectRefused(deviceService.approve(byUserCode, user), "a decision is final: approve after deny must reject");
|
|
218
|
+
const refetched = await deviceService.getByDeviceCode(auth.deviceCode);
|
|
219
|
+
expect(refetched?.denied).toBe(true);
|
|
220
|
+
expect(refetched?.authorized).not.toBe(true);
|
|
221
|
+
});
|
|
222
|
+
it("deny refuses an approved authorization, which stays approved", async () => {
|
|
223
|
+
const { auth, byUserCode } = await saveDeviceAuth();
|
|
224
|
+
await deviceService.approve(byUserCode, user);
|
|
225
|
+
await expectRefused(deviceService.deny(byUserCode), "a decision is final: deny after approve must reject; cancel with revoke");
|
|
226
|
+
const refetched = await deviceService.getByDeviceCode(auth.deviceCode);
|
|
227
|
+
expect(refetched?.authorized).toBe(true);
|
|
228
|
+
expect(refetched?.denied).not.toBe(true);
|
|
229
|
+
});
|
|
230
|
+
it("approve refuses an expired authorization", async () => {
|
|
231
|
+
const auth = {
|
|
232
|
+
...(await makeDeviceAuth()),
|
|
233
|
+
expiresAt: new Date(Date.now() - 1000),
|
|
234
|
+
};
|
|
235
|
+
await deviceService.save(auth);
|
|
236
|
+
const byUserCode = await deviceService.getByUserCode(auth.userCode);
|
|
237
|
+
assert(byUserCode, "getByUserCode should resolve what was saved");
|
|
238
|
+
await expectRefused(deviceService.approve(byUserCode, user), "an expired authorization must not be approved");
|
|
239
|
+
expect((await deviceService.getByDeviceCode(auth.deviceCode))?.authorized).not.toBe(true);
|
|
240
|
+
});
|
|
241
|
+
it("deny refuses an expired authorization", async () => {
|
|
242
|
+
const auth = {
|
|
243
|
+
...(await makeDeviceAuth()),
|
|
244
|
+
expiresAt: new Date(Date.now() - 1000),
|
|
245
|
+
};
|
|
246
|
+
await deviceService.save(auth);
|
|
247
|
+
const byUserCode = await deviceService.getByUserCode(auth.userCode);
|
|
248
|
+
assert(byUserCode, "getByUserCode should resolve what was saved");
|
|
249
|
+
await expectRefused(deviceService.deny(byUserCode), "an expired authorization must not be denied");
|
|
250
|
+
expect((await deviceService.getByDeviceCode(auth.deviceCode))?.denied).not.toBe(true);
|
|
251
|
+
});
|
|
252
|
+
it("approve takes effect for exactly one of two concurrent approvals", async () => {
|
|
253
|
+
const { auth, byUserCode } = await saveDeviceAuth();
|
|
254
|
+
const other = makeUser(2);
|
|
255
|
+
await options.addUser(userService, other, "pw");
|
|
256
|
+
const results = await Promise.allSettled([
|
|
257
|
+
deviceService.approve(byUserCode, user),
|
|
258
|
+
deviceService.approve(byUserCode, other),
|
|
259
|
+
]);
|
|
260
|
+
const approved = results.filter((r) => r.status === "fulfilled");
|
|
261
|
+
expect(approved.length, "approval must be one conditional write on a pending record").toBe(1);
|
|
262
|
+
const winner = approved[0].value.user;
|
|
263
|
+
const refetched = await deviceService.getByDeviceCode(auth.deviceCode);
|
|
264
|
+
expect(refetched?.user?.id).toStrictEqual(winner?.id);
|
|
265
|
+
});
|
|
183
266
|
it("updateLastPolled accepts the record getByDeviceCode returns", async () => {
|
|
184
267
|
const { auth, byDeviceCode } = await saveDeviceAuth();
|
|
185
268
|
const updated = await deviceService.updateLastPolled(byDeviceCode);
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contract test suite for {@link TokenServiceInterface.exchangeDeviceCode},
|
|
3
|
+
* the atomic redemption of an approved device authorization (RFC 8628).
|
|
4
|
+
*
|
|
5
|
+
* The suite checks the exchange under concurrent callers: eight exchanges of
|
|
6
|
+
* one device code, an exchange of an authorization that was already claimed,
|
|
7
|
+
* a second exchange held behind the first, and an exchange whose insert
|
|
8
|
+
* fails. Each case asserts the store's end state, the live tokens and whether
|
|
9
|
+
* the authorization can still be claimed, not only the value each call
|
|
10
|
+
* resolved.
|
|
11
|
+
*
|
|
12
|
+
* The store under test awaits {@link DeviceCodeExchangeBarriers.afterClaim}
|
|
13
|
+
* inside `exchangeDeviceCode`, between its claim and its insert, so the suite
|
|
14
|
+
* can hold an exchange there; a store that never reaches the barrier fails
|
|
15
|
+
* every held case. Only a store whose `exchangeDeviceCode` never awaits
|
|
16
|
+
* between its claim and its insert, such as `MemoryTokenService` paired with
|
|
17
|
+
* its device store, opts out with `exchangeAwaitsBarrier: false`.
|
|
18
|
+
*
|
|
19
|
+
* @example Verify a database-backed store
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { runDeviceCodeExchangeContractTests } from "@udibo/oauth2/testing/contract";
|
|
22
|
+
* import type {
|
|
23
|
+
* DeviceCodeExchangeBarriers,
|
|
24
|
+
* DeviceCodeExchangeContractServices,
|
|
25
|
+
* } from "@udibo/oauth2/testing/contract";
|
|
26
|
+
* import type { MemoryUserShape } from "@udibo/oauth2/testing";
|
|
27
|
+
* import type { ClientInterface } from "@udibo/oauth2/server";
|
|
28
|
+
*
|
|
29
|
+
* declare function freshServices(
|
|
30
|
+
* barriers: DeviceCodeExchangeBarriers,
|
|
31
|
+
* ): Promise<DeviceCodeExchangeContractServices<ClientInterface, MemoryUserShape>>;
|
|
32
|
+
* declare function addUser(service: unknown, user: MemoryUserShape, password: string): Promise<void>;
|
|
33
|
+
* declare function addClient(service: unknown, client: ClientInterface): Promise<void>;
|
|
34
|
+
*
|
|
35
|
+
* runDeviceCodeExchangeContractTests({
|
|
36
|
+
* makeServices: freshServices,
|
|
37
|
+
* addUser,
|
|
38
|
+
* addClient,
|
|
39
|
+
* });
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* @module
|
|
43
|
+
*/
|
|
44
|
+
import type { ClientInterface } from "../../models/client.ts";
|
|
45
|
+
import type { AbstractScope, BasicScope } from "../../models/scope.ts";
|
|
46
|
+
import type { ClientServiceInterface } from "../../server/services/client.ts";
|
|
47
|
+
import type { DeviceAuthorizationServiceInterface } from "../../server/services/device-authorization.ts";
|
|
48
|
+
import type { TokenServiceInterface } from "../../server/services/token.ts";
|
|
49
|
+
import type { UserServiceInterface } from "../../server/services/user.ts";
|
|
50
|
+
import type { MemoryUserShape } from "../services.ts";
|
|
51
|
+
/**
|
|
52
|
+
* The point inside a store's
|
|
53
|
+
* {@linkcode TokenServiceInterface.exchangeDeviceCode} at which
|
|
54
|
+
* {@link runDeviceCodeExchangeContractTests} holds an exchange. Wire it into a
|
|
55
|
+
* test build of the store.
|
|
56
|
+
*/
|
|
57
|
+
export interface DeviceCodeExchangeBarriers {
|
|
58
|
+
/**
|
|
59
|
+
* Await this inside `exchangeDeviceCode` after claiming the authorization
|
|
60
|
+
* and before persisting the token, still inside the atomic step. When it
|
|
61
|
+
* rejects, fail the exchange as a failed insert would: leave the
|
|
62
|
+
* authorization claimable, persist nothing, and reject or resolve
|
|
63
|
+
* `undefined`.
|
|
64
|
+
*/
|
|
65
|
+
afterClaim(): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
/** Services built for each case of {@link runDeviceCodeExchangeContractTests}. */
|
|
68
|
+
export interface DeviceCodeExchangeContractServices<C extends ClientInterface, U extends MemoryUserShape, S extends AbstractScope = BasicScope> {
|
|
69
|
+
/** The user service both stores hydrate users from. */
|
|
70
|
+
userService: UserServiceInterface<U>;
|
|
71
|
+
/** The client service both stores hydrate clients from. */
|
|
72
|
+
clientService: ClientServiceInterface<C, U>;
|
|
73
|
+
/** The device store `exchangeDeviceCode` claims authorizations from. */
|
|
74
|
+
deviceAuthorizationService: DeviceAuthorizationServiceInterface<C, U, S>;
|
|
75
|
+
/** The token service under test. It must implement `exchangeDeviceCode`. */
|
|
76
|
+
tokenService: TokenServiceInterface<C, U, S>;
|
|
77
|
+
}
|
|
78
|
+
/** Options for {@link runDeviceCodeExchangeContractTests}. */
|
|
79
|
+
export interface DeviceCodeExchangeContractOptions<C extends ClientInterface, U extends MemoryUserShape, S extends AbstractScope = BasicScope> {
|
|
80
|
+
/**
|
|
81
|
+
* Returns fresh services for each case, with `exchangeDeviceCode` awaiting
|
|
82
|
+
* `barriers.afterClaim()` between its claim and its insert. A store that
|
|
83
|
+
* sets `exchangeAwaitsBarrier: false` ignores `barriers`.
|
|
84
|
+
*/
|
|
85
|
+
makeServices(barriers: DeviceCodeExchangeBarriers): Promise<DeviceCodeExchangeContractServices<C, U, S>> | DeviceCodeExchangeContractServices<C, U, S>;
|
|
86
|
+
/** Persists a user with the given password into the user service under test. */
|
|
87
|
+
addUser(service: UserServiceInterface<U>, user: U, password: string): Promise<void>;
|
|
88
|
+
/** Persists a client into the client service under test. */
|
|
89
|
+
addClient(service: ClientServiceInterface<C, U>, client: C): Promise<void>;
|
|
90
|
+
/** Builds a distinct user fixture for the given sequence number. Defaults to a minimal `{ id, username }` shape. */
|
|
91
|
+
makeUser?(seq: number): U;
|
|
92
|
+
/** Builds a distinct client fixture for the given sequence number. Defaults to a client granting the device-code grant. */
|
|
93
|
+
makeClient?(seq: number): C;
|
|
94
|
+
/**
|
|
95
|
+
* Whether `exchangeDeviceCode` awaits `barriers.afterClaim()`. Defaults to
|
|
96
|
+
* `true`. Set `false` only when it never awaits between its claim and its
|
|
97
|
+
* insert, as in `MemoryTokenService`; the held cases are then skipped.
|
|
98
|
+
*/
|
|
99
|
+
exchangeAwaitsBarrier?: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Milliseconds the suite lets a call run against a held exchange before it
|
|
102
|
+
* releases the exchange. Defaults to 100.
|
|
103
|
+
*/
|
|
104
|
+
blockedAfterMs?: number;
|
|
105
|
+
/** Overrides the name passed to the outer `describe` block. */
|
|
106
|
+
describeName?: string;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Runs the device code exchange contract suite against a token service that
|
|
110
|
+
* implements {@linkcode TokenServiceInterface.exchangeDeviceCode}.
|
|
111
|
+
*/
|
|
112
|
+
export declare function runDeviceCodeExchangeContractTests<C extends ClientInterface, U extends MemoryUserShape, S extends AbstractScope = BasicScope>(options: DeviceCodeExchangeContractOptions<C, U, S>): void;
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contract test suite for {@link TokenServiceInterface.exchangeDeviceCode},
|
|
3
|
+
* the atomic redemption of an approved device authorization (RFC 8628).
|
|
4
|
+
*
|
|
5
|
+
* The suite checks the exchange under concurrent callers: eight exchanges of
|
|
6
|
+
* one device code, an exchange of an authorization that was already claimed,
|
|
7
|
+
* a second exchange held behind the first, and an exchange whose insert
|
|
8
|
+
* fails. Each case asserts the store's end state, the live tokens and whether
|
|
9
|
+
* the authorization can still be claimed, not only the value each call
|
|
10
|
+
* resolved.
|
|
11
|
+
*
|
|
12
|
+
* The store under test awaits {@link DeviceCodeExchangeBarriers.afterClaim}
|
|
13
|
+
* inside `exchangeDeviceCode`, between its claim and its insert, so the suite
|
|
14
|
+
* can hold an exchange there; a store that never reaches the barrier fails
|
|
15
|
+
* every held case. Only a store whose `exchangeDeviceCode` never awaits
|
|
16
|
+
* between its claim and its insert, such as `MemoryTokenService` paired with
|
|
17
|
+
* its device store, opts out with `exchangeAwaitsBarrier: false`.
|
|
18
|
+
*
|
|
19
|
+
* @example Verify a database-backed store
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { runDeviceCodeExchangeContractTests } from "@udibo/oauth2/testing/contract";
|
|
22
|
+
* import type {
|
|
23
|
+
* DeviceCodeExchangeBarriers,
|
|
24
|
+
* DeviceCodeExchangeContractServices,
|
|
25
|
+
* } from "@udibo/oauth2/testing/contract";
|
|
26
|
+
* import type { MemoryUserShape } from "@udibo/oauth2/testing";
|
|
27
|
+
* import type { ClientInterface } from "@udibo/oauth2/server";
|
|
28
|
+
*
|
|
29
|
+
* declare function freshServices(
|
|
30
|
+
* barriers: DeviceCodeExchangeBarriers,
|
|
31
|
+
* ): Promise<DeviceCodeExchangeContractServices<ClientInterface, MemoryUserShape>>;
|
|
32
|
+
* declare function addUser(service: unknown, user: MemoryUserShape, password: string): Promise<void>;
|
|
33
|
+
* declare function addClient(service: unknown, client: ClientInterface): Promise<void>;
|
|
34
|
+
*
|
|
35
|
+
* runDeviceCodeExchangeContractTests({
|
|
36
|
+
* makeServices: freshServices,
|
|
37
|
+
* addUser,
|
|
38
|
+
* addClient,
|
|
39
|
+
* });
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* @module
|
|
43
|
+
*/
|
|
44
|
+
import { assert, beforeEach, describe, expect, it } from "vitest";
|
|
45
|
+
import { CONCURRENT_CALLERS, race } from "./_race.js";
|
|
46
|
+
const defaultMakeUser = (seq) => ({ id: `u${seq}`, username: `user${seq}` });
|
|
47
|
+
const defaultMakeClient = (seq) => ({
|
|
48
|
+
id: `client-${seq}`,
|
|
49
|
+
grants: ["urn:ietf:params:oauth:grant-type:device_code"],
|
|
50
|
+
});
|
|
51
|
+
async function settledWithin(promise, ms) {
|
|
52
|
+
let timer;
|
|
53
|
+
const timeout = new Promise((resolve) => {
|
|
54
|
+
timer = setTimeout(resolve, ms);
|
|
55
|
+
});
|
|
56
|
+
try {
|
|
57
|
+
await Promise.race([
|
|
58
|
+
promise.then(() => undefined, () => undefined),
|
|
59
|
+
timeout,
|
|
60
|
+
]);
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Runs the device code exchange contract suite against a token service that
|
|
68
|
+
* implements {@linkcode TokenServiceInterface.exchangeDeviceCode}.
|
|
69
|
+
*/
|
|
70
|
+
export function runDeviceCodeExchangeContractTests(options) {
|
|
71
|
+
const makeUser = options.makeUser ?? defaultMakeUser;
|
|
72
|
+
const makeClient = options.makeClient ?? defaultMakeClient;
|
|
73
|
+
const pausable = options.exchangeAwaitsBarrier ?? true;
|
|
74
|
+
const blockedAfterMs = options.blockedAfterMs ?? 100;
|
|
75
|
+
describe(options.describeName ?? "TokenServiceInterface.exchangeDeviceCode contract", () => {
|
|
76
|
+
let deviceService;
|
|
77
|
+
let tokenService;
|
|
78
|
+
let user;
|
|
79
|
+
let client;
|
|
80
|
+
let armed;
|
|
81
|
+
const barriers = {
|
|
82
|
+
async afterClaim() {
|
|
83
|
+
const hold = armed;
|
|
84
|
+
if (!hold)
|
|
85
|
+
return;
|
|
86
|
+
armed = undefined;
|
|
87
|
+
hold.reached.resolve();
|
|
88
|
+
await hold.release.promise;
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
beforeEach(async () => {
|
|
92
|
+
armed = undefined;
|
|
93
|
+
const services = await options.makeServices(barriers);
|
|
94
|
+
deviceService = services.deviceAuthorizationService;
|
|
95
|
+
tokenService = services.tokenService;
|
|
96
|
+
user = makeUser(1);
|
|
97
|
+
client = makeClient(1);
|
|
98
|
+
await options.addUser(services.userService, user, "pw");
|
|
99
|
+
await options.addClient(services.clientService, client);
|
|
100
|
+
});
|
|
101
|
+
function exchange(authorization, token) {
|
|
102
|
+
assert(typeof tokenService.exchangeDeviceCode === "function", "runDeviceCodeExchangeContractTests needs a token service that implements exchangeDeviceCode");
|
|
103
|
+
return tokenService.exchangeDeviceCode(authorization, token);
|
|
104
|
+
}
|
|
105
|
+
async function approved() {
|
|
106
|
+
const authorization = {
|
|
107
|
+
deviceCode: await deviceService.generateDeviceCode(client),
|
|
108
|
+
userCode: await deviceService.generateUserCode(client),
|
|
109
|
+
expiresAt: await deviceService.expiresAt(client),
|
|
110
|
+
client,
|
|
111
|
+
interval: deviceService.interval,
|
|
112
|
+
};
|
|
113
|
+
await deviceService.save(authorization);
|
|
114
|
+
const byUserCode = await deviceService.getByUserCode(authorization.userCode);
|
|
115
|
+
assert(byUserCode, "getByUserCode should resolve what was saved");
|
|
116
|
+
await deviceService.approve(byUserCode, user);
|
|
117
|
+
const byDeviceCode = await deviceService.getByDeviceCode(authorization.deviceCode);
|
|
118
|
+
assert(byDeviceCode, "getByDeviceCode should resolve what was saved");
|
|
119
|
+
return { ...byDeviceCode, userCode: authorization.userCode };
|
|
120
|
+
}
|
|
121
|
+
async function tokenFor() {
|
|
122
|
+
return {
|
|
123
|
+
accessToken: await tokenService.generateAccessToken(client, user),
|
|
124
|
+
accessTokenExpiresAt: new Date(Date.now() + 60_000),
|
|
125
|
+
client,
|
|
126
|
+
user,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
async function live(tokens) {
|
|
130
|
+
const found = [];
|
|
131
|
+
for (const token of tokens) {
|
|
132
|
+
if (await tokenService.getToken(token.accessToken)) {
|
|
133
|
+
found.push(token.accessToken);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return found;
|
|
137
|
+
}
|
|
138
|
+
async function claimable(authorization) {
|
|
139
|
+
return ((await deviceService.getByDeviceCode(authorization.deviceCode)) !==
|
|
140
|
+
undefined);
|
|
141
|
+
}
|
|
142
|
+
function arm() {
|
|
143
|
+
const hold = {
|
|
144
|
+
reached: Promise.withResolvers(),
|
|
145
|
+
release: Promise.withResolvers(),
|
|
146
|
+
};
|
|
147
|
+
armed = hold;
|
|
148
|
+
return hold;
|
|
149
|
+
}
|
|
150
|
+
async function untilHeld(hold, call) {
|
|
151
|
+
const outcome = await Promise.race([
|
|
152
|
+
hold.reached.promise.then(() => "held"),
|
|
153
|
+
call.then(() => "settled", () => "settled"),
|
|
154
|
+
]);
|
|
155
|
+
assert(outcome === "held", "exchangeDeviceCode settled without awaiting barriers.afterClaim; " +
|
|
156
|
+
"wire the barrier in between its claim and its insert, or, only " +
|
|
157
|
+
"if it never awaits between them, set exchangeAwaitsBarrier: false");
|
|
158
|
+
}
|
|
159
|
+
it("implements exchangeDeviceCode", () => {
|
|
160
|
+
assert(typeof tokenService.exchangeDeviceCode === "function", "the device code exchange contract covers exchangeDeviceCode");
|
|
161
|
+
});
|
|
162
|
+
it("claims the authorization by both codes and saves its token in one call", async () => {
|
|
163
|
+
const authorization = await approved();
|
|
164
|
+
const token = await tokenFor();
|
|
165
|
+
const saved = await exchange(authorization, token);
|
|
166
|
+
expect(saved?.accessToken).toBe(token.accessToken);
|
|
167
|
+
expect(await live([token])).toStrictEqual([token.accessToken]);
|
|
168
|
+
expect(await deviceService.getByDeviceCode(authorization.deviceCode), "an exchanged device code must be spent").toBe(undefined);
|
|
169
|
+
expect(await deviceService.getByUserCode(authorization.userCode), "an exchanged authorization must not resolve by its user code").toBe(undefined);
|
|
170
|
+
expect(await deviceService.revoke(authorization.deviceCode)).toBe(false);
|
|
171
|
+
});
|
|
172
|
+
it("refuses an authorization that was already claimed, persisting nothing", async () => {
|
|
173
|
+
const authorization = await approved();
|
|
174
|
+
expect(await deviceService.revoke(authorization)).toBe(true);
|
|
175
|
+
const token = await tokenFor();
|
|
176
|
+
expect(await exchange(authorization, token)).toBe(undefined);
|
|
177
|
+
expect(await live([token])).toStrictEqual([]);
|
|
178
|
+
});
|
|
179
|
+
it(`persists exactly one token for ${CONCURRENT_CALLERS} concurrent exchanges of one device code`, async () => {
|
|
180
|
+
const authorization = await approved();
|
|
181
|
+
const tokens = await race(() => tokenFor());
|
|
182
|
+
const results = await race((caller) => exchange(authorization, tokens[caller]));
|
|
183
|
+
expect(results.filter((result) => result !== undefined).length, "exchangeDeviceCode must claim its authorization once").toBe(1);
|
|
184
|
+
expect(await live(tokens), "a losing exchange must persist nothing: a token saved before the " +
|
|
185
|
+
"claim is decided stays live for a device that was refused").toHaveLength(1);
|
|
186
|
+
});
|
|
187
|
+
it("refuses a second exchange that starts while the first is held after its claim", async ({ skip, }) => {
|
|
188
|
+
skip(!pausable, "exchangeDeviceCode cannot be held (exchangeAwaitsBarrier: false)");
|
|
189
|
+
const authorization = await approved();
|
|
190
|
+
const first = await tokenFor();
|
|
191
|
+
const second = await tokenFor();
|
|
192
|
+
const hold = arm();
|
|
193
|
+
const held = exchange(authorization, first);
|
|
194
|
+
await untilHeld(hold, held);
|
|
195
|
+
const racing = exchange(authorization, second);
|
|
196
|
+
await settledWithin(racing, blockedAfterMs);
|
|
197
|
+
hold.release.resolve();
|
|
198
|
+
expect((await held)?.accessToken).toBe(first.accessToken);
|
|
199
|
+
expect(await racing).toBe(undefined);
|
|
200
|
+
expect(await live([first, second])).toStrictEqual([first.accessToken]);
|
|
201
|
+
});
|
|
202
|
+
it("leaves the authorization claimable and persists nothing when the token cannot be persisted", async () => {
|
|
203
|
+
const authorization = await approved();
|
|
204
|
+
const unpersistable = await tokenFor();
|
|
205
|
+
const accessToken = unpersistable.accessToken;
|
|
206
|
+
Object.defineProperty(unpersistable, "accessToken", {
|
|
207
|
+
enumerable: true,
|
|
208
|
+
get() {
|
|
209
|
+
throw new Error("forced persistence failure");
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
const outcome = await Promise.allSettled([
|
|
213
|
+
exchange(authorization, unpersistable),
|
|
214
|
+
]);
|
|
215
|
+
if (outcome[0].status === "fulfilled") {
|
|
216
|
+
expect(outcome[0].value).toBe(undefined);
|
|
217
|
+
}
|
|
218
|
+
expect(await claimable(authorization), "a failed exchange must not spend the user's approval").toBe(true);
|
|
219
|
+
expect(await tokenService.getToken(accessToken)).toBe(undefined);
|
|
220
|
+
const retry = await tokenFor();
|
|
221
|
+
expect((await exchange(authorization, retry))?.accessToken).toBe(retry.accessToken);
|
|
222
|
+
});
|
|
223
|
+
it("rolls the claim back when the insert fails after it", async ({ skip, }) => {
|
|
224
|
+
skip(!pausable, "exchangeDeviceCode cannot be held (exchangeAwaitsBarrier: false)");
|
|
225
|
+
const authorization = await approved();
|
|
226
|
+
const token = await tokenFor();
|
|
227
|
+
const hold = arm();
|
|
228
|
+
const call = exchange(authorization, token);
|
|
229
|
+
await untilHeld(hold, call);
|
|
230
|
+
hold.release.reject(new Error("forced insert failure"));
|
|
231
|
+
const outcome = await Promise.allSettled([call]);
|
|
232
|
+
if (outcome[0].status === "fulfilled") {
|
|
233
|
+
expect(outcome[0].value).toBe(undefined);
|
|
234
|
+
}
|
|
235
|
+
expect(await claimable(authorization), "the claim and the insert are one step: a failed insert must " +
|
|
236
|
+
"leave the authorization claimable").toBe(true);
|
|
237
|
+
expect(await live([token])).toStrictEqual([]);
|
|
238
|
+
const retry = await tokenFor();
|
|
239
|
+
expect((await exchange(authorization, retry))?.accessToken).toBe(retry.accessToken);
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
}
|
|
@@ -2,10 +2,14 @@
|
|
|
2
2
|
* Contract test suite for {@link LockoutStore} implementations — the
|
|
3
3
|
* per-account failure counter behind `AccountLockout`.
|
|
4
4
|
*
|
|
5
|
-
* `AccountLockout`
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* `AccountLockout` counts each sign-in attempt with `increment` before its
|
|
6
|
+
* password is checked, and admits the attempt only on the count `increment`
|
|
7
|
+
* returns. A store that lets concurrent attempts share a count admits one extra
|
|
8
|
+
* guess for every attempt sharing it: the brute-force floor the lockout is
|
|
9
|
+
* meant to be moves up by however many attempts an attacker can land at once.
|
|
10
|
+
*
|
|
11
|
+
* The optional `lock` cases run when the store implements it and are skipped,
|
|
12
|
+
* with a note naming the gap, when it does not.
|
|
9
13
|
*
|
|
10
14
|
* @example Verify a database-backed store
|
|
11
15
|
* ```ts
|
|
@@ -42,6 +46,13 @@ export interface LockoutStoreContractOptions {
|
|
|
42
46
|
* whose count must stay apart from the first. Defaults to `"user-2"`.
|
|
43
47
|
*/
|
|
44
48
|
otherUserId?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Set to `true` to require the optional {@link LockoutStore.lock}: the suite
|
|
51
|
+
* then fails a store that does not implement it. Left unset, the `lock`
|
|
52
|
+
* cases run when the store implements it and are skipped with a note when
|
|
53
|
+
* it does not.
|
|
54
|
+
*/
|
|
55
|
+
lock?: boolean;
|
|
45
56
|
/**
|
|
46
57
|
* Overrides the name passed to the outer `describe` block. Defaults to
|
|
47
58
|
* `"LockoutStore contract"`.
|