@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.
@@ -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 store that enables `exchangeCode`.
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 `scope`,
397
- * so a subsequent device-code poll can exchange it for a token. Returns the
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. Returns
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
  /**
@@ -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 store that enables `exchangeCode`.
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("approve: device authorization not found");
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. Returns
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.#findStored(authorization);
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.47.0",
3
+ "version": "0.49.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",