@udibo/oauth2 0.47.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/identity/lockout.d.ts +24 -0
- package/dist/identity/lockout.js +26 -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
|
@@ -51,6 +51,23 @@ export interface LockoutStore {
|
|
|
51
51
|
* merging: a record with no `lockedUntil` leaves the account unlocked.
|
|
52
52
|
*/
|
|
53
53
|
set(userId: string, record: LockoutRecord): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Optional: lock the account until `record.lockedUntil` only while its stored
|
|
56
|
+
* count is still at least `record.failures`, keeping the stored count, and
|
|
57
|
+
* resolve whether the lock was written. It must be one conditional write
|
|
58
|
+
* (`UPDATE … SET locked_until = $until WHERE failures >= $failures`, checking
|
|
59
|
+
* the row count), never a read then a write. `now` is the clock `increment`
|
|
60
|
+
* was given, for a store that expires records.
|
|
61
|
+
*
|
|
62
|
+
* `AccountLockout` calls it instead of {@link LockoutStore.set} when an
|
|
63
|
+
* attempt's count reaches `maxAttempts`. Without it, the lock is an
|
|
64
|
+
* unconditional `set` after `increment`, so an over-budget attempt whose
|
|
65
|
+
* lock lands after a concurrent {@link LockoutStore.clear} re-locks an
|
|
66
|
+
* account that just signed in, and no lockout event reports it.
|
|
67
|
+
*/
|
|
68
|
+
lock?(userId: string, record: LockoutRecord & {
|
|
69
|
+
lockedUntil: number;
|
|
70
|
+
}, now: number): Promise<boolean>;
|
|
54
71
|
/** Clear the account's record (successful sign-in or unlock). */
|
|
55
72
|
clear(userId: string): Promise<void>;
|
|
56
73
|
}
|
|
@@ -253,6 +270,13 @@ export declare class MemoryLockoutStore implements LockoutStore {
|
|
|
253
270
|
* record for an account with none is timed from now.
|
|
254
271
|
*/
|
|
255
272
|
set(userId: string, record: LockoutRecord): Promise<void>;
|
|
273
|
+
/**
|
|
274
|
+
* Lock `userId` until `record.lockedUntil` when its live record still
|
|
275
|
+
* counts at least `record.failures`; resolves whether it did.
|
|
276
|
+
*/
|
|
277
|
+
lock(userId: string, record: LockoutRecord & {
|
|
278
|
+
lockedUntil: number;
|
|
279
|
+
}, now: number): Promise<boolean>;
|
|
256
280
|
/** Drop `userId`'s record. */
|
|
257
281
|
clear(userId: string): Promise<void>;
|
|
258
282
|
}
|
package/dist/identity/lockout.js
CHANGED
|
@@ -73,7 +73,7 @@ export class AccountLockout {
|
|
|
73
73
|
reserveAttempt(userId, now = Date.now()) {
|
|
74
74
|
return this.#count(userId, now);
|
|
75
75
|
}
|
|
76
|
-
async #count(userId, now = Date.now()) {
|
|
76
|
+
async #count(userId, now = Date.now(), recounted = false) {
|
|
77
77
|
const record = await this.#store.increment(userId, now);
|
|
78
78
|
const { failures } = record;
|
|
79
79
|
if (record.lockedUntil !== undefined && record.lockedUntil > now) {
|
|
@@ -86,7 +86,11 @@ export class AccountLockout {
|
|
|
86
86
|
}
|
|
87
87
|
if (failures >= this.#maxAttempts) {
|
|
88
88
|
const lockedUntil = now + this.#lockDurationMs;
|
|
89
|
-
await this.#
|
|
89
|
+
if (!(await this.#lock(userId, { failures, lockedUntil }, now))) {
|
|
90
|
+
if (!recounted)
|
|
91
|
+
return this.#count(userId, now, true);
|
|
92
|
+
return { failures, locked: false, justLocked: false };
|
|
93
|
+
}
|
|
90
94
|
// Concurrent attempts can overshoot the threshold before the lock lands;
|
|
91
95
|
// only the attempt that hits it exactly reports justLocked, so the
|
|
92
96
|
// lockout event (and any unlock email) fires once.
|
|
@@ -99,6 +103,12 @@ export class AccountLockout {
|
|
|
99
103
|
}
|
|
100
104
|
return { failures, locked: false, justLocked: false };
|
|
101
105
|
}
|
|
106
|
+
async #lock(userId, record, now) {
|
|
107
|
+
if (this.#store.lock)
|
|
108
|
+
return this.#store.lock(userId, record, now);
|
|
109
|
+
await this.#store.set(userId, record);
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
102
112
|
/** Clear the account's failures and any lock (successful sign-in, unlock). */
|
|
103
113
|
reset(userId) {
|
|
104
114
|
return this.#store.clear(userId);
|
|
@@ -195,6 +205,20 @@ export class MemoryLockoutStore {
|
|
|
195
205
|
this.#collect(userId, touchedAt);
|
|
196
206
|
return Promise.resolve();
|
|
197
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Lock `userId` until `record.lockedUntil` when its live record still
|
|
210
|
+
* counts at least `record.failures`; resolves whether it did.
|
|
211
|
+
*/
|
|
212
|
+
lock(userId, record, now) {
|
|
213
|
+
const entry = this.#entries.get(userId);
|
|
214
|
+
if (!entry ||
|
|
215
|
+
this.#expired(entry, now) ||
|
|
216
|
+
entry.record.failures < record.failures) {
|
|
217
|
+
return Promise.resolve(false);
|
|
218
|
+
}
|
|
219
|
+
entry.record = { ...entry.record, lockedUntil: record.lockedUntil };
|
|
220
|
+
return Promise.resolve(true);
|
|
221
|
+
}
|
|
198
222
|
/** Drop `userId`'s record. */
|
|
199
223
|
clear(userId) {
|
|
200
224
|
this.#entries.delete(userId);
|
|
@@ -78,6 +78,20 @@ export interface TokenFlowStore {
|
|
|
78
78
|
* really was used, instead of the generic `invalid`.
|
|
79
79
|
*/
|
|
80
80
|
deleteBySubject?(purpose: string, subject: string): Promise<void>;
|
|
81
|
+
/**
|
|
82
|
+
* Optional: delete every still-pending record for `(record.purpose,
|
|
83
|
+
* record.subject)` and save `record`, as one atomic step. Concurrent calls
|
|
84
|
+
* for one pair must leave exactly one of their records pending, so serialize
|
|
85
|
+
* them on the pair (a row lock or advisory lock taken before the delete, or
|
|
86
|
+
* a unique index on pending rows): two transactions that each delete and
|
|
87
|
+
* then insert under read committed both leave their row behind. Keep
|
|
88
|
+
* consumed records, as {@link TokenFlowStore.deleteBySubject} does.
|
|
89
|
+
*
|
|
90
|
+
* {@link TokenFlowService.create} calls it for `invalidateExisting` when
|
|
91
|
+
* present. Without it, the service deletes and then saves in two calls, so
|
|
92
|
+
* concurrent requests for one pair each leave a live link.
|
|
93
|
+
*/
|
|
94
|
+
replacePending?(record: TokenFlowRecord): Promise<void>;
|
|
81
95
|
}
|
|
82
96
|
/** Options for {@link TokenFlowService.create}. */
|
|
83
97
|
export interface CreateTokenOptions {
|
|
@@ -90,9 +104,11 @@ export interface CreateTokenOptions {
|
|
|
90
104
|
/** Lifetime in milliseconds. */
|
|
91
105
|
ttlMs: number;
|
|
92
106
|
/**
|
|
93
|
-
* Invalidate any existing pending tokens for this `(purpose, subject)
|
|
94
|
-
*
|
|
95
|
-
* {@link TokenFlowStore.
|
|
107
|
+
* Invalidate any existing pending tokens for this `(purpose, subject)`,
|
|
108
|
+
* atomically with saving the new one when the store implements
|
|
109
|
+
* {@link TokenFlowStore.replacePending}. Silently skipped when the store
|
|
110
|
+
* implements neither it nor {@link TokenFlowStore.deleteBySubject}. Defaults
|
|
111
|
+
* to `false`.
|
|
96
112
|
*/
|
|
97
113
|
invalidateExisting?: boolean;
|
|
98
114
|
}
|
|
@@ -211,4 +227,9 @@ export declare class MemoryTokenFlowStore implements TokenFlowStore {
|
|
|
211
227
|
* still report `consumed` rather than the generic `invalid`.
|
|
212
228
|
*/
|
|
213
229
|
deleteBySubject(purpose: string, subject: string): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Drop the pending records for the record's `(purpose, subject)` and save
|
|
232
|
+
* it, in one synchronous step.
|
|
233
|
+
*/
|
|
234
|
+
replacePending(record: TokenFlowRecord): Promise<void>;
|
|
214
235
|
}
|
|
@@ -59,20 +59,26 @@ export class TokenFlowService {
|
|
|
59
59
|
}
|
|
60
60
|
/** Mint a token; stores its hash and returns the raw token (once). */
|
|
61
61
|
async create(opts) {
|
|
62
|
-
if (opts.invalidateExisting) {
|
|
63
|
-
await this.invalidate(opts.purpose, opts.subject);
|
|
64
|
-
}
|
|
65
62
|
const token = randomToken();
|
|
66
63
|
const now = Date.now();
|
|
67
64
|
const expiresAt = now + opts.ttlMs;
|
|
68
|
-
|
|
65
|
+
const record = {
|
|
69
66
|
tokenHash: await sha256Hash(token),
|
|
70
67
|
purpose: opts.purpose,
|
|
71
68
|
subject: opts.subject,
|
|
72
69
|
data: opts.data,
|
|
73
70
|
expiresAt,
|
|
74
71
|
createdAt: now,
|
|
75
|
-
}
|
|
72
|
+
};
|
|
73
|
+
if (opts.invalidateExisting && this.#store.replacePending) {
|
|
74
|
+
await this.#store.replacePending(record);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
if (opts.invalidateExisting) {
|
|
78
|
+
await this.invalidate(opts.purpose, opts.subject);
|
|
79
|
+
}
|
|
80
|
+
await this.#store.save(record);
|
|
81
|
+
}
|
|
76
82
|
return { token, expiresAt };
|
|
77
83
|
}
|
|
78
84
|
/**
|
|
@@ -161,6 +167,19 @@ export class MemoryTokenFlowStore {
|
|
|
161
167
|
* still report `consumed` rather than the generic `invalid`.
|
|
162
168
|
*/
|
|
163
169
|
deleteBySubject(purpose, subject) {
|
|
170
|
+
this.#deletePending(purpose, subject);
|
|
171
|
+
return Promise.resolve();
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Drop the pending records for the record's `(purpose, subject)` and save
|
|
175
|
+
* it, in one synchronous step.
|
|
176
|
+
*/
|
|
177
|
+
replacePending(record) {
|
|
178
|
+
this.#deletePending(record.purpose, record.subject);
|
|
179
|
+
this.#byHash.set(record.tokenHash, record);
|
|
180
|
+
return Promise.resolve();
|
|
181
|
+
}
|
|
182
|
+
#deletePending(purpose, subject) {
|
|
164
183
|
for (const [hash, record] of this.#byHash) {
|
|
165
184
|
if (record.purpose === purpose &&
|
|
166
185
|
record.subject === subject &&
|
|
@@ -168,6 +187,5 @@ export class MemoryTokenFlowStore {
|
|
|
168
187
|
this.#byHash.delete(hash);
|
|
169
188
|
}
|
|
170
189
|
}
|
|
171
|
-
return Promise.resolve();
|
|
172
190
|
}
|
|
173
191
|
}
|
|
@@ -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
|
+
}
|
|
@@ -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
|
|
@@ -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";
|
|
@@ -133,6 +136,50 @@ export function runTokenFlowStoreContractTests(options) {
|
|
|
133
136
|
(await store.get(hash("2")))?.consumedAt !== undefined, "neither stamp may be lost to the other's stale read");
|
|
134
137
|
});
|
|
135
138
|
});
|
|
139
|
+
describe("replacePending (optional)", () => {
|
|
140
|
+
const NOT_IMPLEMENTED = "replacePending is not implemented — TokenFlowService.create with " +
|
|
141
|
+
"invalidateExisting deletes then saves, so concurrent requests can " +
|
|
142
|
+
"each leave a live link";
|
|
143
|
+
if (options.replacePending) {
|
|
144
|
+
it("is implemented", () => {
|
|
145
|
+
assert(typeof store.replacePending === "function", `${NOT_IMPLEMENTED}. Implement it, or drop \`replacePending: true\`.`);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
it("replaces the pair's pending records with the new one", async ({ skip, }) => {
|
|
149
|
+
if (!store.replacePending)
|
|
150
|
+
return skip(NOT_IMPLEMENTED);
|
|
151
|
+
await store.save(record({ tokenHash: hash("old") }));
|
|
152
|
+
await store.replacePending(record({ tokenHash: hash("new") }));
|
|
153
|
+
expect(await store.get(hash("old"))).toBe(null);
|
|
154
|
+
expect((await store.get(hash("new")))?.tokenHash).toBe(hash("new"));
|
|
155
|
+
});
|
|
156
|
+
it("keeps consumed records, other subjects and other purposes", async ({ skip, }) => {
|
|
157
|
+
if (!store.replacePending)
|
|
158
|
+
return skip(NOT_IMPLEMENTED);
|
|
159
|
+
await store.save(record({ tokenHash: hash("used") }));
|
|
160
|
+
expect(await store.markConsumed(hash("used"), Date.now())).toBe(true);
|
|
161
|
+
await store.save(record({ tokenHash: hash("other-subject"), subject: OTHER_SUBJECT }));
|
|
162
|
+
await store.save(record({ tokenHash: hash("other-purpose"), purpose: OTHER_PURPOSE }));
|
|
163
|
+
await store.replacePending(record({ tokenHash: hash("new") }));
|
|
164
|
+
assert((await store.get(hash("used")))?.consumedAt !== undefined, "a consumed record must survive so inspect() can answer `consumed`");
|
|
165
|
+
assert((await store.get(hash("other-subject"))) !== null);
|
|
166
|
+
assert((await store.get(hash("other-purpose"))) !== null);
|
|
167
|
+
});
|
|
168
|
+
it(`leaves exactly one of ${CONCURRENT_CALLERS} concurrent replacements pending`, async ({ skip, }) => {
|
|
169
|
+
if (!store.replacePending)
|
|
170
|
+
return skip(NOT_IMPLEMENTED);
|
|
171
|
+
const replace = store.replacePending.bind(store);
|
|
172
|
+
await race((caller) => replace(record({ tokenHash: hash(`racer-${caller}`) })));
|
|
173
|
+
const pending = [];
|
|
174
|
+
for (let caller = 0; caller < CONCURRENT_CALLERS; caller++) {
|
|
175
|
+
const stored = await store.get(hash(`racer-${caller}`));
|
|
176
|
+
if (stored && stored.consumedAt === undefined)
|
|
177
|
+
pending.push(stored);
|
|
178
|
+
}
|
|
179
|
+
expect(pending.length, "each replacement invalidates the others — interleaved deletes and " +
|
|
180
|
+
"inserts leave several live links to one mailbox").toBe(1);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
136
183
|
if (expectDeleteBySubject) {
|
|
137
184
|
describe("deleteBySubject", () => {
|
|
138
185
|
it("is implemented", () => {
|
|
@@ -157,6 +157,15 @@ export interface MemoryTokenServiceOptions<C extends ClientInterface, U extends
|
|
|
157
157
|
* map, so a subclass that overrides the code store's `revoke` is bypassed.
|
|
158
158
|
*/
|
|
159
159
|
authorizationCodeService?: MemoryAuthorizationCodeService<C, U, S>;
|
|
160
|
+
/**
|
|
161
|
+
* The device-authorization store the device grant claims from. Pass it to
|
|
162
|
+
* give the token service {@linkcode MemoryTokenService.exchangeDeviceCode},
|
|
163
|
+
* so the grant claims an approved device code and saves its token in one
|
|
164
|
+
* step; without it the grant claims and saves in two.
|
|
165
|
+
* `exchangeDeviceCode` claims from the store's own maps, so a subclass that
|
|
166
|
+
* overrides the store's `revoke` is bypassed.
|
|
167
|
+
*/
|
|
168
|
+
deviceAuthorizationService?: MemoryDeviceAuthorizationService<C, U, S>;
|
|
160
169
|
}
|
|
161
170
|
/**
|
|
162
171
|
* In-memory `TokenServiceInterface` implementation. Tokens are hashed on
|
|
@@ -187,11 +196,20 @@ export declare class MemoryTokenService<C extends ClientInterface, U extends Mem
|
|
|
187
196
|
* two calls for a token service that has no code store to claim from.
|
|
188
197
|
*/
|
|
189
198
|
readonly exchangeCode?: (authorizationCode: AuthorizationCode<C, U, S>, token: Token<C, U, S>) => Promise<Token<C, U, S> | undefined>;
|
|
199
|
+
/**
|
|
200
|
+
* Claims an approved authorization from the paired
|
|
201
|
+
* `deviceAuthorizationService` and saves the token issued from it in one
|
|
202
|
+
* step, or does neither, resolving `undefined` when the authorization was
|
|
203
|
+
* already claimed. Present only when the service was constructed with
|
|
204
|
+
* `deviceAuthorizationService`.
|
|
205
|
+
*/
|
|
206
|
+
readonly exchangeDeviceCode?: (authorization: DeviceAuthorization<C, U, S>, token: Token<C, U, S>) => Promise<Token<C, U, S> | undefined>;
|
|
190
207
|
/**
|
|
191
208
|
* Creates an empty token store.
|
|
192
209
|
*
|
|
193
210
|
* @param options Backing client/user services, optional default token
|
|
194
|
-
* lifetimes, and the code
|
|
211
|
+
* lifetimes, and the code and device stores that enable `exchangeCode` and
|
|
212
|
+
* `exchangeDeviceCode`.
|
|
195
213
|
*/
|
|
196
214
|
constructor(options: MemoryTokenServiceOptions<C, U, S>);
|
|
197
215
|
/**
|
|
@@ -393,14 +411,16 @@ export declare class MemoryDeviceAuthorizationService<C extends ClientInterface,
|
|
|
393
411
|
*/
|
|
394
412
|
getByUserCode(userCode: string): Promise<DeviceAuthorization<C, U, S> | undefined>;
|
|
395
413
|
/**
|
|
396
|
-
* Marks the authorization granted by `user`, optionally narrowing
|
|
397
|
-
* so a subsequent device-code poll can exchange it for a token.
|
|
398
|
-
* updated record. Throws when the authorization is not stored
|
|
414
|
+
* Marks the pending authorization granted by `user`, optionally narrowing
|
|
415
|
+
* `scope`, so a subsequent device-code poll can exchange it for a token.
|
|
416
|
+
* Returns the updated record. Throws when the authorization is not stored,
|
|
417
|
+
* has expired, or was already approved or denied.
|
|
399
418
|
*/
|
|
400
419
|
approve(authorization: DeviceAuthorization<C, U, S>, user: U, scope?: S | null): Promise<DeviceAuthorization<C, U, S>>;
|
|
401
420
|
/**
|
|
402
|
-
* Marks the authorization denied so a subsequent poll is rejected.
|
|
403
|
-
* the updated record. Throws when the authorization is not stored
|
|
421
|
+
* Marks the pending authorization denied so a subsequent poll is rejected.
|
|
422
|
+
* Returns the updated record. Throws when the authorization is not stored,
|
|
423
|
+
* has expired, or was already approved or denied.
|
|
404
424
|
*/
|
|
405
425
|
deny(authorization: DeviceAuthorization<C, U, S>): Promise<DeviceAuthorization<C, U, S>>;
|
|
406
426
|
/**
|
package/dist/testing/services.js
CHANGED
|
@@ -216,11 +216,20 @@ export class MemoryTokenService {
|
|
|
216
216
|
* two calls for a token service that has no code store to claim from.
|
|
217
217
|
*/
|
|
218
218
|
exchangeCode;
|
|
219
|
+
/**
|
|
220
|
+
* Claims an approved authorization from the paired
|
|
221
|
+
* `deviceAuthorizationService` and saves the token issued from it in one
|
|
222
|
+
* step, or does neither, resolving `undefined` when the authorization was
|
|
223
|
+
* already claimed. Present only when the service was constructed with
|
|
224
|
+
* `deviceAuthorizationService`.
|
|
225
|
+
*/
|
|
226
|
+
exchangeDeviceCode;
|
|
219
227
|
/**
|
|
220
228
|
* Creates an empty token store.
|
|
221
229
|
*
|
|
222
230
|
* @param options Backing client/user services, optional default token
|
|
223
|
-
* lifetimes, and the code
|
|
231
|
+
* lifetimes, and the code and device stores that enable `exchangeCode` and
|
|
232
|
+
* `exchangeDeviceCode`.
|
|
224
233
|
*/
|
|
225
234
|
constructor(options) {
|
|
226
235
|
this.#clientService = options.clientService;
|
|
@@ -233,6 +242,18 @@ export class MemoryTokenService {
|
|
|
233
242
|
if (codes) {
|
|
234
243
|
this.exchangeCode = (authorizationCode, token) => this.#exchangeCode(codes, authorizationCode, token);
|
|
235
244
|
}
|
|
245
|
+
const devices = options.deviceAuthorizationService;
|
|
246
|
+
if (devices) {
|
|
247
|
+
this.exchangeDeviceCode = (authorization, token) => this.#exchangeDeviceCode(devices, authorization, token);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async #exchangeDeviceCode(devices, authorization, token) {
|
|
251
|
+
const deviceCodeHash = await sha256Hash(authorization.deviceCode);
|
|
252
|
+
const stored = await this.#prepare(token);
|
|
253
|
+
if (!claimStoredDeviceCode(devices, deviceCodeHash))
|
|
254
|
+
return undefined;
|
|
255
|
+
this.#store(stored);
|
|
256
|
+
return token;
|
|
236
257
|
}
|
|
237
258
|
async #exchangeCode(codes, authorizationCode, token) {
|
|
238
259
|
const codeHash = await sha256Hash(authorizationCode.code);
|
|
@@ -639,6 +660,7 @@ export class MemoryAuthorizationCodeService {
|
|
|
639
660
|
return this.#codes.delete(await sha256Hash(code));
|
|
640
661
|
}
|
|
641
662
|
}
|
|
663
|
+
let claimStoredDeviceCode;
|
|
642
664
|
/** In-memory `DeviceAuthorizationServiceInterface` implementation. */
|
|
643
665
|
export class MemoryDeviceAuthorizationService {
|
|
644
666
|
/** Device-authorization lifetime in seconds applied by {@linkcode expiresAt}. */
|
|
@@ -649,6 +671,16 @@ export class MemoryDeviceAuthorizationService {
|
|
|
649
671
|
#userService;
|
|
650
672
|
#byDeviceCode = new Map();
|
|
651
673
|
#byUserCode = new Map();
|
|
674
|
+
static {
|
|
675
|
+
claimStoredDeviceCode = (service, deviceCodeHash) => {
|
|
676
|
+
const stored = service.#byDeviceCode.get(deviceCodeHash);
|
|
677
|
+
if (!stored)
|
|
678
|
+
return false;
|
|
679
|
+
service.#byDeviceCode.delete(deviceCodeHash);
|
|
680
|
+
service.#byUserCode.delete(stored.userCodeHash);
|
|
681
|
+
return true;
|
|
682
|
+
};
|
|
683
|
+
}
|
|
652
684
|
/**
|
|
653
685
|
* Creates an empty device-authorization store.
|
|
654
686
|
*
|
|
@@ -763,16 +795,27 @@ export class MemoryDeviceAuthorizationService {
|
|
|
763
795
|
}
|
|
764
796
|
return undefined;
|
|
765
797
|
}
|
|
766
|
-
|
|
767
|
-
* Marks the authorization granted by `user`, optionally narrowing `scope`,
|
|
768
|
-
* so a subsequent device-code poll can exchange it for a token. Returns the
|
|
769
|
-
* updated record. Throws when the authorization is not stored.
|
|
770
|
-
*/
|
|
771
|
-
async approve(authorization, user, scope) {
|
|
798
|
+
async #findPending(authorization, method) {
|
|
772
799
|
const stored = await this.#findStored(authorization);
|
|
773
800
|
if (!stored) {
|
|
774
|
-
throw new Error(
|
|
801
|
+
throw new Error(`${method}: device authorization not found`);
|
|
802
|
+
}
|
|
803
|
+
if (stored.authorized || stored.denied) {
|
|
804
|
+
throw new Error(`${method}: device authorization already decided`);
|
|
775
805
|
}
|
|
806
|
+
if (stored.expiresAt.getTime() <= Date.now()) {
|
|
807
|
+
throw new Error(`${method}: device authorization expired`);
|
|
808
|
+
}
|
|
809
|
+
return stored;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Marks the pending authorization granted by `user`, optionally narrowing
|
|
813
|
+
* `scope`, so a subsequent device-code poll can exchange it for a token.
|
|
814
|
+
* Returns the updated record. Throws when the authorization is not stored,
|
|
815
|
+
* has expired, or was already approved or denied.
|
|
816
|
+
*/
|
|
817
|
+
async approve(authorization, user, scope) {
|
|
818
|
+
const stored = await this.#findPending(authorization, "approve");
|
|
776
819
|
stored.authorized = true;
|
|
777
820
|
stored.userId = user.id;
|
|
778
821
|
if (scope !== undefined)
|
|
@@ -785,14 +828,12 @@ export class MemoryDeviceAuthorizationService {
|
|
|
785
828
|
};
|
|
786
829
|
}
|
|
787
830
|
/**
|
|
788
|
-
* Marks the authorization denied so a subsequent poll is rejected.
|
|
789
|
-
* the updated record. Throws when the authorization is not stored
|
|
831
|
+
* Marks the pending authorization denied so a subsequent poll is rejected.
|
|
832
|
+
* Returns the updated record. Throws when the authorization is not stored,
|
|
833
|
+
* has expired, or was already approved or denied.
|
|
790
834
|
*/
|
|
791
835
|
async deny(authorization) {
|
|
792
|
-
const stored = await this.#
|
|
793
|
-
if (!stored) {
|
|
794
|
-
throw new Error("deny: device authorization not found");
|
|
795
|
-
}
|
|
836
|
+
const stored = await this.#findPending(authorization, "deny");
|
|
796
837
|
stored.denied = true;
|
|
797
838
|
return { ...authorization, denied: true };
|
|
798
839
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@udibo/oauth2",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.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",
|