@udibo/oauth2 0.47.0 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/hono/identity.d.ts +34 -3
- package/dist/adapters/hono/identity.js +25 -11
- package/dist/identity/lockout.d.ts +24 -0
- package/dist/identity/lockout.js +26 -2
- package/dist/identity/mod.d.ts +1 -1
- package/dist/identity/service.d.ts +27 -1
- package/dist/identity/service.js +16 -2
- package/dist/identity/token-flow.d.ts +24 -3
- package/dist/identity/token-flow.js +24 -6
- 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 +10 -0
- package/dist/testing/contract/lockout-store.js +62 -1
- 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
|
@@ -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
|
+
}
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
* guess for every attempt sharing it: the brute-force floor the lockout is
|
|
9
9
|
* meant to be moves up by however many attempts an attacker can land at once.
|
|
10
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.
|
|
13
|
+
*
|
|
11
14
|
* @example Verify a database-backed store
|
|
12
15
|
* ```ts
|
|
13
16
|
* import { runLockoutStoreContractTests } from "@udibo/oauth2/testing/contract";
|
|
@@ -43,6 +46,13 @@ export interface LockoutStoreContractOptions {
|
|
|
43
46
|
* whose count must stay apart from the first. Defaults to `"user-2"`.
|
|
44
47
|
*/
|
|
45
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;
|
|
46
56
|
/**
|
|
47
57
|
* Overrides the name passed to the outer `describe` block. Defaults to
|
|
48
58
|
* `"LockoutStore contract"`.
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
* guess for every attempt sharing it: the brute-force floor the lockout is
|
|
9
9
|
* meant to be moves up by however many attempts an attacker can land at once.
|
|
10
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.
|
|
13
|
+
*
|
|
11
14
|
* @example Verify a database-backed store
|
|
12
15
|
* ```ts
|
|
13
16
|
* import { runLockoutStoreContractTests } from "@udibo/oauth2/testing/contract";
|
|
@@ -23,7 +26,7 @@
|
|
|
23
26
|
*
|
|
24
27
|
* @module
|
|
25
28
|
*/
|
|
26
|
-
import { beforeEach, describe, expect, it } from "vitest";
|
|
29
|
+
import { assert, beforeEach, describe, expect, it } from "vitest";
|
|
27
30
|
/**
|
|
28
31
|
* Runs the {@link LockoutStore} contract suite. Call it from your own test
|
|
29
32
|
* file — it registers `describe` / `it` blocks the test runner picks up.
|
|
@@ -108,6 +111,64 @@ export function runLockoutStoreContractTests(options) {
|
|
|
108
111
|
expect(record?.lockedUntil).toBe(undefined);
|
|
109
112
|
});
|
|
110
113
|
});
|
|
114
|
+
describe("lock (optional)", () => {
|
|
115
|
+
const NOT_IMPLEMENTED = "lock is not implemented — AccountLockout falls back to set, so an " +
|
|
116
|
+
"over-budget attempt can re-lock an account a concurrent sign-in reset";
|
|
117
|
+
if (options.lock) {
|
|
118
|
+
it("is implemented", () => {
|
|
119
|
+
assert(typeof store.lock === "function", `${NOT_IMPLEMENTED}. Implement it, or drop \`lock: true\`.`);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
it("locks the account while its count stands, keeping the count", async ({ skip, }) => {
|
|
123
|
+
if (!store.lock)
|
|
124
|
+
return skip(NOT_IMPLEMENTED);
|
|
125
|
+
for (let i = 0; i < 3; i++)
|
|
126
|
+
await store.increment(USER, now);
|
|
127
|
+
const lockedUntil = now + 60_000;
|
|
128
|
+
expect(await store.lock(USER, { failures: 3, lockedUntil }, now)).toBe(true);
|
|
129
|
+
const record = await store.get(USER);
|
|
130
|
+
expect(record?.failures).toStrictEqual(3);
|
|
131
|
+
expect(record?.lockedUntil).toBe(lockedUntil);
|
|
132
|
+
});
|
|
133
|
+
it("locks when later attempts counted past the lock's own count", async ({ skip, }) => {
|
|
134
|
+
if (!store.lock)
|
|
135
|
+
return skip(NOT_IMPLEMENTED);
|
|
136
|
+
for (let i = 0; i < 5; i++)
|
|
137
|
+
await store.increment(USER, now);
|
|
138
|
+
expect(await store.lock(USER, { failures: 3, lockedUntil: now + 60_000 }, now)).toBe(true);
|
|
139
|
+
expect((await store.get(USER))?.failures).toStrictEqual(5);
|
|
140
|
+
});
|
|
141
|
+
it("refuses once the account was cleared", async ({ skip }) => {
|
|
142
|
+
if (!store.lock)
|
|
143
|
+
return skip(NOT_IMPLEMENTED);
|
|
144
|
+
for (let i = 0; i < 3; i++)
|
|
145
|
+
await store.increment(USER, now);
|
|
146
|
+
await store.clear(USER);
|
|
147
|
+
expect(await store.lock(USER, { failures: 3, lockedUntil: now + 60_000 }, now), "a lock computed before a successful sign-in must not land after it").toBe(false);
|
|
148
|
+
expect(await store.get(USER)).toBe(undefined);
|
|
149
|
+
});
|
|
150
|
+
it("refuses once a fresh count started below the lock's count", async ({ skip, }) => {
|
|
151
|
+
if (!store.lock)
|
|
152
|
+
return skip(NOT_IMPLEMENTED);
|
|
153
|
+
for (let i = 0; i < 3; i++)
|
|
154
|
+
await store.increment(USER, now);
|
|
155
|
+
await store.clear(USER);
|
|
156
|
+
await store.increment(USER, now);
|
|
157
|
+
expect(await store.lock(USER, { failures: 3, lockedUntil: now + 60_000 }, now)).toBe(false);
|
|
158
|
+
const record = await store.get(USER);
|
|
159
|
+
expect(record?.failures).toStrictEqual(1);
|
|
160
|
+
expect(record?.lockedUntil).toBe(undefined);
|
|
161
|
+
});
|
|
162
|
+
it("locks only the account it is given", async ({ skip }) => {
|
|
163
|
+
if (!store.lock)
|
|
164
|
+
return skip(NOT_IMPLEMENTED);
|
|
165
|
+
for (let i = 0; i < 3; i++)
|
|
166
|
+
await store.increment(USER, now);
|
|
167
|
+
await store.increment(OTHER_USER, now);
|
|
168
|
+
await store.lock(USER, { failures: 3, lockedUntil: now + 60_000 }, now);
|
|
169
|
+
expect((await store.get(OTHER_USER))?.lockedUntil).toBe(undefined);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
111
172
|
describe("clear", () => {
|
|
112
173
|
it("drops the account's failures and lock", async () => {
|
|
113
174
|
await store.set(USER, { failures: 10, lockedUntil: now + 60_000 });
|
|
@@ -36,6 +36,11 @@
|
|
|
36
36
|
* and an exchange whose insert fails. A store that awaits between its claim
|
|
37
37
|
* and its insert wires `CodeExchangeBarriers` into `exchangeCode`.
|
|
38
38
|
*
|
|
39
|
+
* `TokenServiceInterface.exchangeDeviceCode` has one as well: concurrent
|
|
40
|
+
* exchanges of one approved device code, an exchange of a claimed
|
|
41
|
+
* authorization, and an exchange whose insert fails, with
|
|
42
|
+
* `DeviceCodeExchangeBarriers` wired the same way.
|
|
43
|
+
*
|
|
39
44
|
* The service runners take a factory plus seed helpers because `add` /
|
|
40
45
|
* `register` methods aren't part of the public service interfaces — the
|
|
41
46
|
* consumer tells the runner how to populate test data.
|
|
@@ -47,6 +52,7 @@ export { type ClientServiceContractOptions, runClientServiceContractTests, } fro
|
|
|
47
52
|
export { runTokenServiceContractTests, type TokenServiceContractOptions, } from "./token.ts";
|
|
48
53
|
export { runTokenRotationContractTests, type TokenRotationBarriers, type TokenRotationContractOptions, type TokenRotationContractServices, } from "./token-rotation.ts";
|
|
49
54
|
export { type CodeExchangeBarriers, type CodeExchangeContractOptions, type CodeExchangeContractServices, runCodeExchangeContractTests, } from "./code-exchange.ts";
|
|
55
|
+
export { type DeviceCodeExchangeBarriers, type DeviceCodeExchangeContractOptions, type DeviceCodeExchangeContractServices, runDeviceCodeExchangeContractTests, } from "./device-code-exchange.ts";
|
|
50
56
|
export { runTokenReaderContractTests, type TokenReaderContractFixture, type TokenReaderContractOptions, } from "./token-reader.ts";
|
|
51
57
|
export { type AuthorizationCodeServiceContractOptions, runAuthorizationCodeServiceContractTests, } from "./authorization-code.ts";
|
|
52
58
|
export { type DeviceAuthorizationServiceContractOptions, runDeviceAuthorizationServiceContractTests, } from "./device-authorization.ts";
|
|
@@ -36,6 +36,11 @@
|
|
|
36
36
|
* and an exchange whose insert fails. A store that awaits between its claim
|
|
37
37
|
* and its insert wires `CodeExchangeBarriers` into `exchangeCode`.
|
|
38
38
|
*
|
|
39
|
+
* `TokenServiceInterface.exchangeDeviceCode` has one as well: concurrent
|
|
40
|
+
* exchanges of one approved device code, an exchange of a claimed
|
|
41
|
+
* authorization, and an exchange whose insert fails, with
|
|
42
|
+
* `DeviceCodeExchangeBarriers` wired the same way.
|
|
43
|
+
*
|
|
39
44
|
* The service runners take a factory plus seed helpers because `add` /
|
|
40
45
|
* `register` methods aren't part of the public service interfaces — the
|
|
41
46
|
* consumer tells the runner how to populate test data.
|
|
@@ -47,6 +52,7 @@ export { runClientServiceContractTests, } from "./client.js";
|
|
|
47
52
|
export { runTokenServiceContractTests, } from "./token.js";
|
|
48
53
|
export { runTokenRotationContractTests, } from "./token-rotation.js";
|
|
49
54
|
export { runCodeExchangeContractTests, } from "./code-exchange.js";
|
|
55
|
+
export { runDeviceCodeExchangeContractTests, } from "./device-code-exchange.js";
|
|
50
56
|
export { runTokenReaderContractTests, } from "./token-reader.js";
|
|
51
57
|
export { runAuthorizationCodeServiceContractTests, } from "./authorization-code.js";
|
|
52
58
|
export { runDeviceAuthorizationServiceContractTests, } from "./device-authorization.js";
|
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* single-use, and only a conditional write survives concurrent requests
|
|
7
7
|
* redeeming one link. This suite races eight of them on one link.
|
|
8
8
|
*
|
|
9
|
+
* The optional `replacePending` cases run when the store implements it and
|
|
10
|
+
* are skipped, with a note naming the gap, when it does not.
|
|
11
|
+
*
|
|
9
12
|
* @example Verify a database-backed store
|
|
10
13
|
* ```ts
|
|
11
14
|
* import { runTokenFlowStoreContractTests } from "@udibo/oauth2/testing/contract";
|
|
@@ -38,6 +41,13 @@ export interface TokenFlowStoreContractOptions {
|
|
|
38
41
|
* that meant to implement it and does not fails loudly.
|
|
39
42
|
*/
|
|
40
43
|
deleteBySubject?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Set to `true` to require the optional
|
|
46
|
+
* {@link TokenFlowStore.replacePending}: the suite then fails a store that
|
|
47
|
+
* does not implement it. Left unset, the `replacePending` cases run when the
|
|
48
|
+
* store implements it and are skipped with a note when it does not.
|
|
49
|
+
*/
|
|
50
|
+
replacePending?: boolean;
|
|
41
51
|
/**
|
|
42
52
|
* The subject the cases issue tokens for, in your application's id format. A
|
|
43
53
|
* store whose rows reference a users table needs it to name a user that
|