@crvouga/mockingbird-service-cognito 3.10.6 → 3.10.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog — @crvouga/mockingbird-service-cognito
2
2
 
3
+ ## 3.10.8 (2026-11-02)
4
+
5
+ ### Fixes and improvements
6
+
7
+ - sign ID and access tokens with separate keys and add jti, origin_jti and event_id ([647326d](https://github.com/crvouga/mockingbird/commit/647326d2d52b5358e7e4d9ccd06004be2ab7265c))
8
+
9
+ ## 3.10.7 (2026-11-02)
10
+
11
+ ### Fixes and improvements
12
+
13
+ - compare the admin key in constant time ([2a43141](https://github.com/crvouga/mockingbird/commit/2a43141f50dab41e698c3bbce0c69bf65b40e24e))
14
+
3
15
  ## 3.10.6 (2026-11-02)
4
16
 
5
17
  ### Fixes and improvements
package/README.md CHANGED
@@ -68,7 +68,7 @@ Responses contain SDK-consumed Cognito fields and AWS-shaped exceptions (`__type
68
68
  - `GET/POST /__admin/users` lists redacted users or seeds one. Passwords and tokens are never returned.
69
69
  - `GET /__admin/codes?username=…` returns local confirmation/reset codes without sending mail.
70
70
  - `POST /__admin/sessions/revoke {"username":"…"}` invalidates access and refresh sessions.
71
- - `POST /__admin/keys/rotate {"retainPrevious":true}` rotates signing keys and retains at most two prior keys. Every new key receives a fresh random UUID `kid`, independently of the virtual clock. Reset starts a fresh key ring.
71
+ - `POST /__admin/keys/rotate {"retainPrevious":true}` rotates signing keys and retains at most two prior keys. As in Cognito, ID and access tokens are signed with different keys, so the JWKS lists one key of each kind per generation and rotation replaces both (the response names them `kid` and `accessKid`). Every new key receives a fresh random UUID `kid`, independently of the virtual clock. Reset starts a fresh key ring.
72
72
  - Fault presets: `throttled`, `unavailable`.
73
73
 
74
74
  The shared runtime supplies reset, clock, snapshots, journals, metrics, faults, branches, and namespace isolation. Select namespaces through `x-mockingbird-namespace`, `/__admin/ns/<name>`, or SigV4 access-key mappings.
package/SUPPORT.md CHANGED
@@ -10,4 +10,4 @@ Generated from `openapi.yaml`; do not edit by hand.
10
10
  | --- | --- | --- | --- | --- |
11
11
  | `CognitoRpc` | `POST /` | ✅ supported | ⚠️ unsafe (opt-in) | |
12
12
  | `Discovery` | `GET /{poolId}/.well-known/openid-configuration` | ✅ supported | ❌ disabled | Namespace-scoped local issuer metadata with configured public origin/prefix. |
13
- | `Jwks` | `GET /{poolId}/.well-known/jwks.json` | ✅ supported | ❌ disabled | Namespace-scoped RS256 keys; portable snapshots retain the current key and two prior keys. |
13
+ | `Jwks` | `GET /{poolId}/.well-known/jwks.json` | ✅ supported | ❌ disabled | Namespace-scoped RS256 keys; one key signs ID tokens and another signs access tokens as in Cognito; portable snapshots retain the current pair and two prior pairs. |
@@ -2507,6 +2507,17 @@ var createNamespaceControls = (options) => {
2507
2507
  };
2508
2508
  };
2509
2509
 
2510
+ // ../core/dist/signing.js
2511
+ var encoder = new TextEncoder();
2512
+ var timingSafeEqual = (a, b) => {
2513
+ if (a.length !== b.length)
2514
+ return false;
2515
+ let diff = 0;
2516
+ for (let i = 0; i < a.length; i++)
2517
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
2518
+ return diff === 0;
2519
+ };
2520
+
2510
2521
  // ../core/dist/surface.js
2511
2522
  var defineMock = (runtime) => runtime;
2512
2523
  var ADMIN_ROUTE_REFERENCE = {
@@ -2625,6 +2636,10 @@ var assertAdminPrefixAvailable = (prefix, paths) => {
2625
2636
  }
2626
2637
  };
2627
2638
  var ADMIN_KEY_HEADER = CONTROL_HEADERS.adminKey;
2639
+ var hasAdminKey = (headers2, adminKey) => {
2640
+ const sent = headers2.get(ADMIN_KEY_HEADER);
2641
+ return sent !== null && timingSafeEqual(sent, adminKey);
2642
+ };
2628
2643
  var NAMESPACE_HEADER = CONTROL_HEADERS.namespace;
2629
2644
  var ADMIN_DOCS_URL = "https://mockingbird.chrisvouga.dev/docs/admin-controls";
2630
2645
  var ADMIN_CONTROL_PAGES = [
@@ -3098,7 +3113,7 @@ var createControlPlane = (context) => {
3098
3113
  }
3099
3114
  const path = url.pathname.slice(adminPrefix.length) || "/";
3100
3115
  const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
3101
- if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
3116
+ if (!shell && context.adminKey !== void 0 && !hasAdminKey(request.headers, context.adminKey)) {
3102
3117
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
3103
3118
  }
3104
3119
  for (const route of routes) {
@@ -3861,7 +3876,7 @@ var stateAdminRoutes = (routes) => {
3861
3876
  };
3862
3877
 
3863
3878
  // ../core/dist/version.js
3864
- var PACKAGE_VERSION = true ? "3.10.6" : UNRELEASED_VERSION;
3879
+ var PACKAGE_VERSION = true ? "3.10.8" : UNRELEASED_VERSION;
3865
3880
 
3866
3881
  // ../core/dist/webhooks.js
3867
3882
  var json4 = (status, body) => new Response(JSON.stringify(body), {
@@ -4840,7 +4855,7 @@ var createRuntime = (options) => {
4840
4855
  throw error;
4841
4856
  }
4842
4857
  const rewinds = at !== void 0 && selectedBranch === "main" && MUTATING_METHODS.has(request.method);
4843
- if ((requested || rewinds) && options.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== options.adminKey)
4858
+ if ((requested || rewinds) && options.adminKey !== void 0 && !hasAdminKey(request.headers, options.adminKey))
4844
4859
  return refuse(401, `control headers need ${ADMIN_KEY_HEADER}`);
4845
4860
  controls.ensure(namespace);
4846
4861
  if (requested?.restore !== void 0 && !snapshotStore.get(namespace, requested.restore))
@@ -5142,7 +5157,7 @@ var credentialRoutes = (registry) => ({
5142
5157
  });
5143
5158
 
5144
5159
  // src/crypto.ts
5145
- var encoder = new TextEncoder();
5160
+ var encoder2 = new TextEncoder();
5146
5161
  var algorithm = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
5147
5162
  var base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5148
5163
  var CognitoSigner = class {
@@ -5181,14 +5196,14 @@ var CognitoSigner = class {
5181
5196
  }
5182
5197
  async sign(claims) {
5183
5198
  const header = base64url(
5184
- encoder.encode(JSON.stringify({ alg: "RS256", kid: this.kid, typ: "JWT" }))
5199
+ encoder2.encode(JSON.stringify({ alg: "RS256", kid: this.kid, typ: "JWT" }))
5185
5200
  );
5186
- const payload = base64url(encoder.encode(JSON.stringify(claims)));
5201
+ const payload = base64url(encoder2.encode(JSON.stringify(claims)));
5187
5202
  const input = `${header}.${payload}`;
5188
5203
  const signature = await crypto.subtle.sign(
5189
5204
  algorithm,
5190
5205
  (await this.pair).privateKey,
5191
- encoder.encode(input)
5206
+ encoder2.encode(input)
5192
5207
  );
5193
5208
  return `${input}.${base64url(new Uint8Array(signature))}`;
5194
5209
  }
@@ -5328,7 +5343,7 @@ var redactedUser = (user) => ({
5328
5343
  });
5329
5344
 
5330
5345
  // src/generated/openapi.ts
5331
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Amazon Cognito Identity Provider (Mockingbird subset)","version":"2016-04-18","description":"Hand-trimmed AWS JSON 1.1 user-pools contract used by the AWS SDK clients."},"servers":[{"url":"https://cognito-idp.us-east-1.amazonaws.com"}],"security":[{"sigv4":[]}],"paths":{"/":{"post":{"operationId":"CognitoRpc","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"X-Amz-Target","in":"header","required":true,"schema":{"type":"string","pattern":"^AWSCognitoIdentityProviderService\\\\.[A-Za-z]+$"}}],"requestBody":{"required":true,"content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}},"application/json":{"schema":{"type":"object","additionalProperties":true}}}},"responses":{"200":{"description":"Operation-specific AWS JSON response.","content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}}}},"400":{"description":"Cognito service exception.","content":{"application/x-amz-json-1.1":{"schema":{"type":"object","required":["__type","message"],"properties":{"__type":{"type":"string"},"message":{"type":"string"}},"additionalProperties":true}}}}}}},"/{poolId}/.well-known/openid-configuration":{"get":{"operationId":"Discovery","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Namespace-scoped local issuer metadata with configured public origin/prefix."}},"parameters":[{"name":"poolId","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"OIDC discovery.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true}}}}}}},"/{poolId}/.well-known/jwks.json":{"get":{"operationId":"Jwks","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Namespace-scoped RS256 keys; portable snapshots retain the current key and two prior keys."}},"parameters":[{"name":"poolId","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"JSON Web Key Set.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true}}}}}}}},"components":{"securitySchemes":{"sigv4":{"type":"apiKey","in":"header","name":"Authorization","description":"AWS SigV4; fixture signatures are accepted and access-key ids select namespaces."}}}}`);
5346
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Amazon Cognito Identity Provider (Mockingbird subset)","version":"2016-04-18","description":"Hand-trimmed AWS JSON 1.1 user-pools contract used by the AWS SDK clients."},"servers":[{"url":"https://cognito-idp.us-east-1.amazonaws.com"}],"security":[{"sigv4":[]}],"paths":{"/":{"post":{"operationId":"CognitoRpc","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"X-Amz-Target","in":"header","required":true,"schema":{"type":"string","pattern":"^AWSCognitoIdentityProviderService\\\\.[A-Za-z]+$"}}],"requestBody":{"required":true,"content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}},"application/json":{"schema":{"type":"object","additionalProperties":true}}}},"responses":{"200":{"description":"Operation-specific AWS JSON response.","content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}}}},"400":{"description":"Cognito service exception.","content":{"application/x-amz-json-1.1":{"schema":{"type":"object","required":["__type","message"],"properties":{"__type":{"type":"string"},"message":{"type":"string"}},"additionalProperties":true}}}}}}},"/{poolId}/.well-known/openid-configuration":{"get":{"operationId":"Discovery","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Namespace-scoped local issuer metadata with configured public origin/prefix."}},"parameters":[{"name":"poolId","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"OIDC discovery.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true}}}}}}},"/{poolId}/.well-known/jwks.json":{"get":{"operationId":"Jwks","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Namespace-scoped RS256 keys; one key signs ID tokens and another signs access tokens as in Cognito; portable snapshots retain the current pair and two prior pairs."}},"parameters":[{"name":"poolId","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"JSON Web Key Set.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true}}}}}}}},"components":{"securitySchemes":{"sigv4":{"type":"apiKey","in":"header","name":"Authorization","description":"AWS SigV4; fixture signatures are accepted and access-key ids select namespaces."}}}}`);
5332
5347
  var operationIds = ["CognitoRpc", "Discovery", "Jwks"];
5333
5348
  var supportedOperationIds = ["CognitoRpc", "Discovery", "Jwks"];
5334
5349
 
@@ -5381,6 +5396,12 @@ var CognitoState = class {
5381
5396
  token(prefix) {
5382
5397
  return this.ids.next(prefix, 32);
5383
5398
  }
5399
+ /** A version-4-shaped UUID from the namespace's seeded sequence, so runs stay reproducible. */
5400
+ uuid(sequence) {
5401
+ const hex = [...this.ids.next(`${sequence}:`, 32).slice(sequence.length + 1)].map((char) => (char.charCodeAt(0) % 16).toString(16)).join("");
5402
+ const variant = (Number.parseInt(hex[16], 16) & 3 | 8).toString(16);
5403
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
5404
+ }
5384
5405
  };
5385
5406
 
5386
5407
  // src/runtime.ts
@@ -5483,6 +5504,7 @@ var headers = (requestId) => ({
5483
5504
  "cache-control": "no-store"
5484
5505
  });
5485
5506
  var attr = (user, name2) => user.attributes.find((value) => value.Name === name2)?.Value;
5507
+ var KEY_RINGS = { id: "ring", access: "access-ring" };
5486
5508
  var publicUser = (user) => ({
5487
5509
  Username: user.username,
5488
5510
  Attributes: [{ Name: "sub", Value: user.sub }, ...user.attributes],
@@ -5494,7 +5516,7 @@ var publicUser = (user) => ({
5494
5516
  var CognitoAPI = class {
5495
5517
  state;
5496
5518
  signingKeys;
5497
- initializingKeys;
5519
+ initializingKeys = /* @__PURE__ */ new Map();
5498
5520
  publicNamespace;
5499
5521
  adminPrefix;
5500
5522
  baseUrl;
@@ -5524,24 +5546,47 @@ var CognitoAPI = class {
5524
5546
  clearNamespace(this.sqlite, this.namespace);
5525
5547
  this.state.seed();
5526
5548
  }
5527
- async keyRing() {
5528
- const stored = this.signingKeys.get("ring");
5549
+ async keyRing(name2) {
5550
+ const stored = this.signingKeys.get(name2);
5529
5551
  if (stored) return stored;
5530
- this.initializingKeys ??= new CognitoSigner().export().then((key) => {
5531
- const ring = this.signingKeys.get("ring") ?? [key];
5532
- this.signingKeys.insert("ring", ring);
5533
- return ring;
5534
- }).finally(() => {
5535
- this.initializingKeys = void 0;
5536
- });
5537
- return this.initializingKeys;
5552
+ let pending = this.initializingKeys.get(name2);
5553
+ if (!pending) {
5554
+ pending = new CognitoSigner().export().then((key) => {
5555
+ const ring = this.signingKeys.get(name2) ?? [key];
5556
+ this.signingKeys.insert(name2, ring);
5557
+ return ring;
5558
+ }).finally(() => this.initializingKeys.delete(name2));
5559
+ this.initializingKeys.set(name2, pending);
5560
+ }
5561
+ return pending;
5538
5562
  }
5539
5563
  async rotateSigningKey(retainPrevious = true) {
5540
- await this.keyRing();
5541
- const key = await new CognitoSigner().export();
5542
- const retained = retainPrevious ? (this.signingKeys.get("ring") ?? []).slice(0, 2) : [];
5543
- this.signingKeys.insert("ring", [key, ...retained]);
5544
- return { kid: key.kid };
5564
+ const rotate = async (name2) => {
5565
+ await this.keyRing(name2);
5566
+ const key = await new CognitoSigner().export();
5567
+ const retained = retainPrevious ? (this.signingKeys.get(name2) ?? []).slice(0, 2) : [];
5568
+ this.signingKeys.insert(name2, [key, ...retained]);
5569
+ return key.kid;
5570
+ };
5571
+ return { kid: await rotate(KEY_RINGS.id), accessKid: await rotate(KEY_RINGS.access) };
5572
+ }
5573
+ /**
5574
+ * Signs each token with its type's current key (picked by `token_use`) and stamps a fresh
5575
+ * `jti` plus the sign-in's `origin_jti` and `event_id`.
5576
+ */
5577
+ async tokenSigner(origin) {
5578
+ const signers = {
5579
+ id: new CognitoSigner((await this.keyRing(KEY_RINGS.id))[0]),
5580
+ access: new CognitoSigner((await this.keyRing(KEY_RINGS.access))[0])
5581
+ };
5582
+ return {
5583
+ sign: (claims) => signers[claims.token_use].sign({
5584
+ ...claims,
5585
+ jti: this.state.uuid("jti"),
5586
+ origin_jti: origin.originJti,
5587
+ event_id: origin.eventId
5588
+ })
5589
+ };
5545
5590
  }
5546
5591
  issuer(request, poolId = this.poolId) {
5547
5592
  const prefix = this.publicNamespace === "default" ? "" : `${this.adminPrefix}/ns/${encodeURIComponent(this.publicNamespace)}`;
@@ -5562,7 +5607,10 @@ var CognitoAPI = class {
5562
5607
  passwordValid(value) {
5563
5608
  return typeof value === "string" && value.length >= 8 && /[A-Z]/.test(value) && /[a-z]/.test(value) && /\d/.test(value);
5564
5609
  }
5565
- async tokens(request, user, clientId, includeRefresh = true) {
5610
+ async tokens(request, user, clientId, includeRefresh = true, origin = {
5611
+ originJti: this.state.uuid("origin_jti"),
5612
+ eventId: this.state.uuid("event_id")
5613
+ }) {
5566
5614
  const now = Math.floor(this.now() / 1e3);
5567
5615
  const issuer = this.issuer(request);
5568
5616
  const identities = redactedUser(user).identities;
@@ -5574,7 +5622,7 @@ var CognitoAPI = class {
5574
5622
  exp: now + 3600,
5575
5623
  ...user.groups.length ? { "cognito:groups": user.groups } : {}
5576
5624
  };
5577
- const signer = new CognitoSigner((await this.keyRing())[0]);
5625
+ const signer = await this.tokenSigner(origin);
5578
5626
  const access = await signer.sign({
5579
5627
  ...common,
5580
5628
  username: user.username,
@@ -5606,7 +5654,8 @@ var CognitoAPI = class {
5606
5654
  clientId,
5607
5655
  expires: (now + 2592e3) * 1e3,
5608
5656
  revoked: false,
5609
- kind: "refresh"
5657
+ kind: "refresh",
5658
+ origin
5610
5659
  });
5611
5660
  }
5612
5661
  return {
@@ -5635,7 +5684,11 @@ var CognitoAPI = class {
5635
5684
  const jwks = /^\/([^/]+)\/\.well-known\/jwks\.json$/.exec(url.pathname);
5636
5685
  if (request.method === "GET" && jwks)
5637
5686
  return Response.json({
5638
- keys: (await Promise.all((await this.keyRing()).map((key) => new CognitoSigner(key).jwks()))).flatMap((set) => set.keys)
5687
+ keys: (await Promise.all(
5688
+ [...await this.keyRing(KEY_RINGS.id), ...await this.keyRing(KEY_RINGS.access)].map(
5689
+ (key) => new CognitoSigner(key).jwks()
5690
+ )
5691
+ )).flatMap((set) => set.keys)
5639
5692
  });
5640
5693
  if (request.method !== "POST" || url.pathname !== "/")
5641
5694
  return this.error("ResourceNotFoundException", "Not found", 404);
@@ -5710,7 +5763,13 @@ var CognitoAPI = class {
5710
5763
  if (session?.kind !== "refresh" || session.clientId !== clientId || session.revoked || session.expires <= this.now() || !user2)
5711
5764
  return this.error("NotAuthorizedException", "Invalid Refresh Token");
5712
5765
  return this.response({
5713
- AuthenticationResult: await this.tokens(request, user2, session.clientId, false)
5766
+ AuthenticationResult: await this.tokens(
5767
+ request,
5768
+ user2,
5769
+ session.clientId,
5770
+ false,
5771
+ session.origin
5772
+ )
5714
5773
  });
5715
5774
  }
5716
5775
  const user = this.requireUser(parameters.USERNAME);
@@ -5908,4 +5967,4 @@ export {
5908
5967
  accessKeyCredential,
5909
5968
  CognitoAPI
5910
5969
  };
5911
- //# sourceMappingURL=chunk-OBLOAALN.js.map
5970
+ //# sourceMappingURL=chunk-7Q2C5EBR.js.map