@crvouga/mockingbird-service-cognito

中文文档
3.11.0发布于 2026/11/11MITTypeScriptES Module构建来源已验证近 30 天下载 1.6万

Stateful Amazon Cognito User Pools emulator for AWS SDK and browser authentication tests.

原始使用文档
文档目录7 节
  1. Install
  2. Usage
  3. AWS JSON operations
  4. Admin and deterministic controls
  5. Fleet fixtures and public identity endpoints
  6. Deliberately not modelled
  7. API

@crvouga/mockingbird-service-cognito

Local emulators. Real API contracts. Part of Mockingbird.

Stateful local emulator of Amazon Cognito User Pools for the AWS SDK and amazon-cognito-identity-js. It implements the authentication, user administration, group, federation, recovery, JWT, discovery, and JWKS surface the consumer app uses without contacting AWS.

Install

npm install -D @crvouga/mockingbird-service-cognito

ESM only. Node 22+ or Bun 1.2+.

Usage

Point COGNITO_ENDPOINT or the AWS SDK endpoint option at the served emulator. Fixture SigV4 credentials are accepted for admin operations. Public user-pool operations work without IAM credentials, matching Cognito's client-facing API.

import {
  CognitoIdentityProviderClient,
  InitiateAuthCommand,
} from "@aws-sdk/client-cognito-identity-provider"
import { createServer } from "@crvouga/mockingbird-service-cognito/server"

// Test setup: seed the emulator and point the AWS SDK client your application uses at it.
const emulator = await createServer({
  poolId: "us-east-1_mockingbird",
  clientId: "mockingbird-client",
  users: [
    {
      username: "[email protected]",
      password: "Password1",
      confirmed: true,
      attributes: [{ Name: "email", Value: "[email protected]" }],
    },
  ],
})
const cognito = new CognitoIdentityProviderClient({
  endpoint: emulator.url,
  region: "us-east-1",
  credentials: { accessKeyId: "fixture", secretAccessKey: "fixture" },
})

// Application code: ordinary SDK calls.
const { AuthenticationResult } = await cognito.send(
  new InitiateAuthCommand({
    AuthFlow: "USER_PASSWORD_AUTH",
    ClientId: "mockingbird-client",
    AuthParameters: { USERNAME: "[email protected]", PASSWORD: "Password1" },
  }),
)
// AuthenticationResult: { AccessToken, IdToken, RefreshToken, ExpiresIn, TokenType }

await emulator.close() // after the test

createServer() from ./server is the Node adapter; createRuntime() takes the same options in process. The CLI is npx mockingbird-cognito serve --port 8811 --pool-id us-east-1_mockingbird --client-id mockingbird-client.

AWS JSON operations

POST / dispatches by X-Amz-Target and supports SignUp, ConfirmSignUp, ResendConfirmationCode, InitiateAuth (USER_PASSWORD_AUTH, REFRESH_TOKEN_AUTH), ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, DeleteUser, AdminCreateUser, AdminSetUserPassword, AdminConfirmSignUp, AdminGetUser, AdminUpdateUserAttributes, AdminDeleteUser, ListUsers, AdminLinkProviderForUser, AdminAddUserToGroup, AdminRemoveUserFromGroup, and AdminUserGlobalSignOut.

Responses contain SDK-consumed Cognito fields and AWS-shaped exceptions (__type, message, HTTP status, x-amzn-requestid). Tokens are RS256 JWTs with Cognito issuer, subject, token_use, timestamps and groups. The ID token adds aud, cognito:username, email and linked identities; the access token adds client_id, username and scope, and no user attributes, as Cognito does. Discovery and JWKS are at /<poolId>/.well-known/openid-configuration and /<poolId>/.well-known/jwks.json.

Admin and deterministic controls

  • GET/POST /__admin/users lists redacted users or seeds one. Passwords and tokens are never returned.
  • GET /__admin/codes?username=… returns local confirmation/reset codes without sending mail.
  • POST /__admin/sessions/revoke {"username":"…"} invalidates access and refresh sessions.
  • 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.
  • Fault presets: throttled, unavailable.

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.

Fleet fixtures and public identity endpoints

Use fixtures: { users: [...] } in a fleet service entry, or options: { fixtures: "./synthetic-users.json" } for an explicit JSON file containing the same object. The standalone CLI accepts --fixtures ./synthetic-users.json. Each user requires username and password; optional sub, confirmed, enabled, status, createdAt, attributes, groups, linked identities and inspection codes match the in-process seed fields. Invalid fields, duplicate usernames/subjects/email aliases and conflicting identities fail with field paths before readiness. Diagnostics omit values. Fixture identity objects accept Cognito identity claim fields and the supported provider-link fields, rather than arbitrary nested objects.

Fixtures form the reset baseline for every independent namespace. Importing a snapshot replaces saved state, including deleted fixture users, without reseeding. Synthetic passwords stay in private state/archives; user admin responses redact passwords, session data and inspection codes. Codes remain available only from /__admin/codes.

SurfacePublic origin and path prefixNamespace isolation
Unsigned InitiateAuth / user-pool JSON operationsSupportedHeader and path carriers
RS256 issuer, discovery and JWKSSupported; publicOrigin + publicPath configure the authoritative baseAdvertised URLs carry the selected namespace, including header-selected requests
SigV4-signed AWS admin operationsDirect private listener only; signature validation through proxies is not certifiedFixture signatures remain the local test contract
Mockingbird admin controls / private signing materialPrivate listener onlyNever routed by the reference public ingress
Hosted authorization/token UINot implementedDiscovery metadata does not imply hosted OAuth flow support

In-process callers can set baseUrl, and the CLI accepts --base-url. Fixed configuration determines advertised identity URLs; Host and forwarding headers never override it. Without explicit configuration, the direct request/mount URL supplies the origin. Replacing a fleet behind a stable public endpoint retains the issuer even when private listener ports change.

Current and retained synthetic signing keys live in namespace storage, so namespace snapshots, whole-fleet archives and restored time-travel checkpoints preserve key IDs and pre-snapshot signatures. Subsequent rotation reads the restored ring. Archives created before signing-state persistence contain no recoverable private key; they load with a fresh ring and require reauthentication. Protect portable archives as private synthetic credentials; diagnostic and user-control responses never include key material.

Deliberately not modelled

Operations outside the documented subset, production quotas, email/SMS delivery, MFA, Lambda triggers, device tracking, Cognito Identity Pools, AWS billing, dashboards, and outbound vendor calls are not implemented. Hosted UI federation is represented in linked identity claims; this WIP tier does not render Cognito's hosted login pages.

API

  • CognitoAPI, CognitoAPIOptions: AWS JSON handler and options.
  • createRuntime, CognitoRuntime, CognitoRuntimeOptions: full Mockingbird service runtime.
  • COGNITO_NAMESPACE, COGNITO_PRESETS, accessKeyCredential: service constants and controls.
  • CognitoAttribute, CognitoSeedUser, CognitoUser, CognitoFixtures: state and fixture types.
  • document, operationIds, supportedOperationIds: generated OpenAPI metadata.
  • createServer, CognitoServerOptions, DEFAULT_PORT, serveTarget from ./server: Node HTTP adapter and CLI integration.

Official oracle: Amazon Cognito User Pools API Reference and Cognito ID token claims.

版本与发布记录

@crvouga/mockingbird-service-cognito 共发布 43 个版本,首次发布于 2026/09/23;过去 12 个月发布了 43 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.11.0latest2026/11/11今天
3.10.112026/11/038 天前
3.10.102026/11/038 天前
3.10.92026/11/038 天前
3.10.82026/11/038 天前
3.10.72026/11/038 天前

关于 @crvouga/mockingbird-service-cognito 的常见问题

@crvouga/mockingbird-service-cognito 是什么?

Stateful Amazon Cognito User Pools emulator for AWS SDK and browser authentication tests.

如何安装 @crvouga/mockingbird-service-cognito?

在项目目录运行 npm install @crvouga/mockingbird-service-cognito,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 mockingbird-cognito,可以用 npx mockingbird-cognito 直接运行。

@crvouga/mockingbird-service-cognito 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@crvouga/mockingbird-service-cognito 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@crvouga/mockingbird-service-cognito 可以商用吗?

@crvouga/mockingbird-service-cognito 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@crvouga/mockingbird-service-cognito 的下载量有多少?

根据 npm 官方下载统计,@crvouga/mockingbird-service-cognito 在 2026/10/11 – 2026/11/09 这 30 天内被下载 15,733 次,日均约 524 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@crvouga/mockingbird-service-cognito 还在维护吗?

最新版本 3.11.0 发布于 2026/11/11(今天);至今共发布 43 个版本,其中过去 12 个月发布了 43 个;首次发布于 2026/09/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。