Skip to content
Back to search

emulate

Local API emulation for CI and no-network sandboxes

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/vercel-labs/emulate with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/vercel-labs/emulate'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/vercel-labs--emulate/badge.svg)](/listings/vercel-labs--emulate)

HTML

<a href="/listings/vercel-labs--emulate"><img src="/api/listings/vercel-labs--emulate/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npx emulate

All services listen on IPv4 loopback (`127.0.0.1`) by default. No config file needed:

- **Vercel** on `http://localhost:4000` - **GitHub** on `http://localhost:4001` - **Google** on `http://localhost:4002` - **Slack** on `http://localhost:4003` - **Apple** on `http://localhost:4004` - **Microsoft** on `http://localhost:4005` - **Okta** on `http://localhost:4006` - **AWS** on `http://localhost:4007` - **Resend** on `http://localhost:4008` - **Stripe** on `http://localhost:4009` - **MongoDB Atlas** on `http://localhost:4010` - **Clerk** on `http://localhost:4011` - **Linear** on `http://localhost:4012` - **Twilio** on `http://localhost:4013`

Stripe webhooks configured with a secret include a `Stripe-Signature` header signed over the timestamp and raw request body.

Slack event callbacks use `X-Slack-Request-Timestamp` and `X-Slack-Signature` when `slack.signing_secret` is configured. The signature is an HMAC-SHA256 over `v0:<timestamp>:<raw-body>`; configure the receiver with the same secret and verify against the unparsed request body. Existing event subscriptions remain unsigned when the secret is absent or empty.

Resend `POST /emails` and `POST /emails/batch` support 24-hour `Idempotency-Key` replay, returning the original email IDs without duplicate emails or webhooks.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,941 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # emulate
  2. <p>
  3. <a href="https://vercel.com/labs#active-experiments"><img alt="Vercel Labs Experiment" src="https://img.shields.io/badge/LABS-EXPERIMENT-0a0a0a.svg?style=for-the-badge&amp;logo=Vercel&amp;labelColor=000000" height="28"></a>
  4. <a href="https://www.npmjs.com/package/emulate"><img alt="npm version: emulate" src="https://img.shields.io/npm/v/emulate.svg?style=for-the-badge&amp;labelColor=000000" height="28"></a>
  5. <a href="https://github.com/vercel-labs/emulate/blob/main/LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/github/license/vercel-labs/emulate.svg?style=for-the-badge&amp;labelColor=000000" height="28"></a>
  6. <a href="https://www.npmjs.com/package/emulate"><img alt="npm downloads per month: emulate" src="https://img.shields.io/npm/dm/emulate.svg?style=for-the-badge&amp;labelColor=000000&amp;label=npm%20downloads" height="28"></a>
  7. </p>
  8. Local drop-in replacement services for CI and no-network sandboxes. Fully stateful, production-fidelity API emulation. Not mocks.
  9. ## Quick Start
  10. ```bash
  11. npx emulate
  12. ```
  13. All services listen on IPv4 loopback (`127.0.0.1`) by default. No config file needed:
  14. - **Vercel** on `http://localhost:4000`
  15. - **GitHub** on `http://localhost:4001`
  16. - **Google** on `http://localhost:4002`
  17. - **Slack** on `http://localhost:4003`
  18. - **Apple** on `http://localhost:4004`
  19. - **Microsoft** on `http://localhost:4005`
  20. - **Okta** on `http://localhost:4006`
  21. - **AWS** on `http://localhost:4007`
  22. - **Resend** on `http://localhost:4008`
  23. - **Stripe** on `http://localhost:4009`
  24. - **MongoDB Atlas** on `http://localhost:4010`
  25. - **Clerk** on `http://localhost:4011`
  26. - **Linear** on `http://localhost:4012`
  27. - **Twilio** on `http://localhost:4013`
  28. - **AI** on `http://localhost:4014`
  29. Stripe webhooks configured with a secret include a `Stripe-Signature` header signed over the timestamp and raw request body.
  30. Slack event callbacks use `X-Slack-Request-Timestamp` and `X-Slack-Signature` when `slack.signing_secret` is configured. The signature is an HMAC-SHA256 over `v0:<timestamp>:<raw-body>`; configure the receiver with the same secret and verify against the unparsed request body. Existing event subscriptions remain unsigned when the secret is absent or empty.
  31. Resend `POST /emails` and `POST /emails/batch` support 24-hour `Idempotency-Key` replay, returning the original email IDs without duplicate emails or webhooks. Optional `resend.allowlist` restrictions let tests reject recipients while `resend.send_attempts` records accepted and rejected sends.
  32. The AI service answers OpenAI Responses, Chat Completions, and Anthropic Messages requests with deterministic, rule-driven replies, so apps using the `openai` SDK, the Anthropic SDK, the Vercel AI SDK, or an OpenAI-compatible gateway can be tested offline without keys. It covers text, streaming, structured output, tool loops, reasoning, refusals, stored responses, errors, disconnects, and stalls.
  33. ## Custom emulators
  34. Build and share emulators for the third-party HTTP APIs your app uses. Define a provider's behavior in TypeScript, run it alongside built-in services, and reuse it in tests and framework adapters. emulate provides seeds, resets, persistence, and request/state inspection.
  35. Start from a working scaffold and adapt its routes and state to your provider:
  36. ```bash
  37. npm install -D emulate
  38. npx emulate init --custom inventory
  39. npx emulate start --watch
  40. ```
  41. The scaffold implements reservations, stock changes, cancellation, and out-of-stock errors. It creates a runnable Node test and adds the service to a discovered YAML, JSON, TypeScript, or JavaScript config. For an unusual executable config, it prints the import and service entry to add manually. `init` prints the test command and directs you to the service URL and Inspector link printed by `start`; the port depends on the config. Watch mode retries when a missing local import is created, including outside the config directory. Use the inspector to view requests and state or reset to the initial seed. Structured inspection redacts token and secret fields such as `access_token`, `refresh_token`, and `client_secret`.
  42. ```typescript
  43. import { defineEmulator, createEmulator } from 'emulate'
  44. const acme = defineEmulator({
  45. name: 'acme',
  46. state: () => ({ anvils: 100 }),
  47. setup({ app, state }) {
  48. app.get('/inventory', (c) => c.json(state))
  49. app.post('/orders', (c) => {
  50. if (!state.anvils) return c.json({ error: 'sold_out' }, 409)
  51. state.anvils -= 1
  52. return c.json({ shipped: 'anvil', to: 'coyote' }, 201)
  53. })
  54. },
  55. })
  56. const api = await createEmulator({ service: acme, listen: false })
  57. try {
  58. await api.request('/orders', { method: 'POST' })
  59. const checkpoint = api.snapshot()
  60. await api.reset()
  61. await api.restore(checkpoint)
  62. } finally {
  63. await api.close()
  64. }
  65. ```
  66. Use `defineConfig({ services: { acme: { emulator: acme }, github: { emulator: 'github' } } })` in `emulate.config.ts`. YAML/JSON entries accept local module paths and installed packages. `--config` selects a config explicitly; legacy flat configs and `--seed` remain supported. Node loads local TypeScript with path aliases and source locations without additional runtime dependencies. Node 26 supports erasable TypeScript only; compile enums and parameter properties to JavaScript before loading them. Node 24 also supports native TypeScript transforms.
  67. Custom state uses your own record shapes and IDs. Seeds replace the complete initial state. Reset restores the captured seed; successful watch reloads create a new baseline and reset the run. With config auto-discovery, watch mode also detects recognized config files created after startup. Instances are independent. Persistence is opt-in, with versioned snapshots and no cross-process locking. Use `port: 0` for HTTP tests, or `listen: false` to test without opening a port. Custom reset and close are awaitable. Framework adapters keep root-relative custom redirects under the service mount while preserving custom HTML bodies.
  68. Streamed responses persist state changes when their bodies finish or are canceled. Reset and close cancel active streams before running cleanup. `c.header('Set-Cookie', value, { append: true })` retains cookies already set on the response. In a Next.js route, export `OPTIONS` from `createEmulateHandler` to forward preflight requests and custom OPTIONS handlers.
  69. See the [custom emulator guide](https://emulate.dev/docs/custom-emulators) and [complete inventory example](examples/custom-api) for validation, middleware, persistence, adapters, package sharing, and troubleshooting.
  70. ## CLI
  71. ```bash
  72. # Start all services (zero-config)
  73. npx emulate
  74. # Start specific services
  75. npx emulate --service vercel,github
  76. # Custom port
  77. npx emulate --port 3000
  78. # Use a seed config file
  79. npx emulate --seed config.yaml
  80. # Generate omitted service secrets into a private file
  81. npx emulate start --seed config.yaml --generated-secrets-file .emulate-secrets.json
  82. # Generate a starter config
  83. npx emulate init
  84. # Generate config for a specific service
  85. npx emulate init --service vercel
  86. # List available services
  87. npx emulate list
  88. ```
  89. ### Options
  90. | Flag | Default | Description |
  91. |------|---------|-------------|
  92. | `-p, --port` | `4000` | Base port (auto-increments per service) |
  93. | `--host` | `127.0.0.1` | Listening address; use `0.0.0.0` to allow network access |
  94. | `-s, --service` | all | Comma-separated services to enable |
  95. | `--seed` | auto-detect | Path to seed config (YAML or JSON) |
  96. | `--base-url` | none | Override advertised base URL (supports `{service}` template) |
  97. | `--portless` | off | Serve over HTTPS via portless (auto-registers aliases) |
  98. | `--generated-secrets-file` | none | Generate omitted service secrets and write them to a new owner-only JSON file |
  99. The port can also be set via `EMULATE_PORT` or `PORT` environment variables.
  100. For access from a container or another machine, use `npx emulate start --host 0.0.0.0`. Set `--base-url` to a URL reachable by those clients when using OAuth redirects or other advertised URLs.
  101. To control a local emulator from an MCP client, run `npx emulate mcp`. Results remove terminal escapes and redact URL credentials and sensitive query values while preserving clean URLs. See the [MCP server guide](https://emulate.dev/docs/mcp) for client setup and tool behavior.
  102. ## HTTPS with portless
  103. [portless](https://github.com/vercel-labs/portless) gives emulators trusted HTTPS URLs with auto-generated certs and no browser warnings.
  104. ```bash
  105. # Start the portless proxy (first time only)
  106. portless proxy start
  107. # Start emulate with portless integration
  108. npx emulate start --portless
  109. ```
  110. Each service registers as a portless alias and gets a named HTTPS URL:
  111. ```
  112. github https://github.emulate.localhost
  113. google https://google.emulate.localhost
  114. slack https://slack.emulate.localhost
  115. ```
  116. If portless is not installed, emulate will prompt to install it (`npm i -g portless`).
  117. The `--portless` flag overwrites any existing portless aliases matching `*.emulate`. Aliases are removed automatically when emulate shuts down.
  118. For a custom base URL without portless (any reverse proxy), use `--base-url` or the `EMULATE_BASE_URL` env var:
  119. ```bash
  120. npx emulate start --base-url "https://{service}.myproxy.test"
  121. ```
  122. The `PORTLESS_URL` env var is automatically set by the `portless` CLI wrapper when running a command through it (e.g. `portless github.emulate emulate start`), typically to a value like `https://{service}.emulate.localhost`. It supports `{service}` interpolation, just like `--base-url` and `EMULATE_BASE_URL`. When no explicit `baseUrl` is provided, it is used as a fallback.
  123. Per-service overrides are also supported in the seed config (these take highest priority over all other base URL sources):
  124. ```yaml
  125. github:
  126. baseUrl: https://github.emulate.localhost
  127. ```
  128. ## Programmatic API
  129. ```bash
  130. npm install emulate
  131. ```
  132. Each call to `createEmulator` starts a single service:
  133. ```typescript
  134. import { createEmulator } from 'emulate'
  135. const github = await createEmulator({ service: 'github', port: 4001 })
  136. const vercel = await createEmulator({ service: 'vercel', port: 4002 })
  137. github.url // 'http://localhost:4001'
  138. vercel.url // 'http://localhost:4002'
  139. await github.close()
  140. await vercel.close()
  141. ```
  142. When a GitHub App omits `private_key`, `createEmulator` generates an RSA-2048 PKCS#1 key for that emulator instance:
  143. ```typescript
  144. const github = await createEmulator({
  145. service: 'github',
  146. seed: {
  147. github: {
  148. users: [{ login: 'octocat' }],
  149. apps: [{
  150. app_id: 12345,
  151. slug: 'my-github-app',
  152. name: 'My GitHub App',
  153. installations: [{ installation_id: 100, account: 'octocat' }],
  154. }],
  155. },
  156. },
  157. })
  158. const privateKey = github.generatedSecrets.find(
  159. secret => secret.kind === 'github.app_private_key' && secret.id === '12345',
  160. )?.value
  161. ```
  162. Generated keys remain stable across `reset()` calls and appear only in `generatedSecrets`. Explicitly configured keys are never returned there. A new `createEmulator` call generates a new key.
  163. The CLI can also generate omitted GitHub App keys when a delivery file is requested:
  164. ```bash
  165. npx emulate start --service github --seed config.yaml \
  166. --generated-secrets-file .emulate-secrets.json
  167. ```
  168. The destination must not exist. emulate removes inherited ACLs, verifies effective owner-only access, and publishes complete JSON before opening listeners or configuring portless. Handled startup failures remove the invocation-owned artifact so the command can be retried immediately. A hard termination such as `SIGKILL` can leave a complete published artifact that must be removed manually after confirming no invocation is using it. Only generated secrets are included. Explicitly configured keys are never copied into the artifact. Linux requires `setfacl` and `getfacl` from the `acl` package. The flag fails closed when access controls cannot be verified and is not supported on Windows. Without `--generated-secrets-file`, CLI seed files keep requiring `private_key`.
  169. ### Vitest / Jest setup
  170. ```typescript
  171. // vitest.setup.ts
  172. import { createEmulator, type Emulator } from 'emulate'
  173. let github: Emulator
  174. let vercel: Emulator
  175. beforeAll(async () => {
  176. ;[github, vercel] = await Promise.all([
  177. createEmulator({ service: 'github', port: 4001 }),
  178. createEmulator({ service: 'vercel', port: 4002 }),
  179. ])
  180. process.env.GITHUB_EMULATOR_URL = github.url
  181. process.env.VERCEL_EMULATOR_URL = vercel.url
  182. })
  183. afterEach(() => { github.reset(); vercel.reset() })
  184. afterAll(() => Promise.all([github.close(), vercel.close()]))
  185. ```
  186. ### Options
  187. | Option | Default | Description |
  188. |--------|---------|-------------|
  189. | `service` | *(required)* | Service name: `'vercel'`, `'github'`, `'google'`, `'slack'`, `'apple'`, `'microsoft'`, `'okta'`, `'aws'`, `'resend'`, `'stripe'`, `'mongoatlas'`, `'clerk'`, `'linear'`, `'twilio'`, or `'ai'` |
  190. | `port` | `4000` | Port for the HTTP server |
  191. | `hostname` | `127.0.0.1` | Listening address for built-in and custom emulators |
  192. | `seed` | none | Inline seed data (same shape as YAML config) |
  193. | `baseUrl` | none | Override advertised base URL. Per-service `baseUrl` in seed config takes highest priority, then this option, then `EMULATE_BASE_URL` env var (supports `{service}`), then `PORTLESS_URL` (supports `{service}`, automatically set by the `portless` CLI wrapper), then `http://<listening host>:<port>`, with `localhost` for loopback and wildcard hosts. |
  194. Use `hostname: '0.0.0.0'` to allow connections from containers or other machines, and `baseUrl` to advertise a URL reachable by those clients.
  195. ### Instance methods
  196. | Method | Description |
  197. |--------|-------------|
  198. | `url` | Base URL of the running server |
  199. | `generatedSecrets` | Readonly secrets generated while preparing seed data |
  200. | `reset()` | Wipe the store and replay seed data |
  201. | `close()` | Shut down the HTTP server, returns a Promise |
  202. ## Configuration
  203. Configuration is optional. The CLI auto-detects config files in this order: `emulate.config.yaml` / `.yml`, `emulate.config.json`, `service-emulator.config.yaml` / `.yml`, `service-emulator.config.json`. Or pass `--seed <file>` explicitly. Run `npx emulate init` to generate a starter file.
  204. ```yaml
  205. tokens:
  206. my_token:
  207. login: admin
  208. scopes: [repo, user]
  209. vercel:
  210. users:
  211. - username: developer
  212. name: Developer
  213. email: dev@example.com
  214. teams:
  215. - slug: my-team
  216. name: My Team
  217. projects:
  218. - name: my-app
  219. team: my-team
  220. framework: nextjs
  221. github:
  222. users:
  223. - login: octocat
  224. name: The Octocat
  225. email: octocat@github.com
  226. orgs:
  227. - login: my-org
  228. name: My Organization
  229. members:
  230. - login: octocat
  231. role: admin
  232. repos:
  233. - owner: octocat
  234. name: hello-world
  235. language: JavaScript
  236. auto_init: true
  237. strict_scopes: false
  238. google:
  239. users:
  240. - email: testuser@example.com
  241. name: Test User
  242. - email: admin@acme.com
  243. name: Admin
  244. hd: acme.com
  245. oauth_clients:
  246. - client_id: my-client-id.apps.googleusercontent.com
  247. client_secret: GOCSPX-secret
  248. redirect_uris:
  249. - http://localhost:3000/api/auth/callback/google
  250. labels:
  251. - id: Label_ops
  252. user_email: testuser@example.com
  253. name: Ops/Review
  254. color_background: "#DDEEFF"
  255. color_text: "#111111"
  256. messages:
  257. - id: msg_welcome
  258. user_email: testuser@example.com
  259. from: welcome@example.com
  260. to: testuser@example.com
  261. subject: Welcome to the Gmail emulator
  262. body_text: You can now test Gmail, Calendar, and Drive flows locally.
  263. label_ids: [INBOX, UNREAD, CATEGORY_UPDATES]
  264. calendars:
  265. - id: primary
  266. user_email: testuser@example.com
  267. summary: testuser@example.com
  268. primary: true
  269. selected: true
  270. time_zone: UTC
  271. calendar_events:
  272. - id: evt_kickoff
  273. user_email: testuser@example.com
  274. calendar_id: primary
  275. summary: Project Kickoff
  276. start_date_time: 2025-01-10T09:00:00.000Z
  277. end_date_time: 2025-01-10T09:30:00.000Z
  278. drive_items:
  279. - id: drv_docs
  280. user_email: testuser@example.com
  281. name: Docs
  282. mime_type: application/vnd.google-apps.folder
  283. parent_ids: [root]
  284. slack:
  285. team:
  286. name: My Workspace
  287. domain: my-workspace
  288. users:
  289. - name: developer
  290. real_name: Developer
  291. email: dev@example.com
  292. profile:
  293. title: Local Developer
  294. status_text: Testing locally
  295. status_emoji: ":computer:"
  296. presence: active
  297. channels:
  298. - name: general
  299. topic: General discussion
  300. - name: random
  301. topic: Random stuff
  302. bots:
  303. - name: my-bot
  304. oauth_apps:
  305. - client_id: "12345.67890"
  306. client_secret: example_client_secret
  307. app_id: A000000001
  308. name: My Slack App
  309. redirect_uris:
  310. - http://localhost:3000/api/auth/callback/slack
  311. scopes:
  312. - chat:write
  313. - channels:read
  314. - channels:history
  315. - channels:join
  316. - channels:manage
  317. - channels:write
  318. - groups:read
  319. - groups:history
  320. - groups:write
  321. - im:read
  322. - im:history
  323. - im:write
  324. - mpim:read
  325. - mpim:history
  326. - mpim:write
  327. - users:read
  328. - users:read.email
  329. - users.profile:read
  330. - users.profile:write
  331. - users:write
  332. - files:read
  333. - files:write
  334. - pins:read
  335. - pins:write
  336. - bookmarks:read
  337. - bookmarks:write
  338. - reactions:read
  339. - reactions:write
  340. - team:read
  341. user_scopes: [users:read, users.profile:read]
  342. bot_name: my-bot
  343. tokens:
  344. - token: xoxb-local-test
  345. user: developer
  346. scopes:
  347. - chat:write
  348. - channels:read
  349. - channels:history
  350. - channels:join
  351. - channels:manage
  352. - channels:write
  353. - groups:read
  354. - groups:history
  355. - groups:write
  356. - im:read
  357. - im:history
  358. - im:write
  359. - mpim:read
  360. - mpim:history
  361. - mpim:write
  362. - users:read
  363. - users:read.email
  364. - users.profile:read
  365. - users.profile:write
  366. - users:write
  367. - files:read
  368. - files:write
  369. - pins:read
  370. - pins:write
  371. - bookmarks:read
  372. - bookmarks:write
  373. - reactions:read
  374. - reactions:write
  375. - team:read
  376. strict_scopes: false
  377. linear:
  378. organization:
  379. name: Acme
  380. url_key: acme
  381. users:
  382. - email: admin@example.com
  383. name: Admin User
  384. admin: true
  385. - email: dev@example.com
  386. name: Developer
  387. teams:
  388. - key: ENG
  389. name: Engineering
  390. states:
  391. - name: Backlog
  392. type: backlog
  393. - name: Todo
  394. type: unstarted
  395. - name: In Progress
  396. type: started
  397. - name: Done
  398. type: completed
  399. labels:
  400. - name: Bug
  401. color: "#d92d20"
  402. team: ENG
  403. - name: Feature
  404. color: "#2563eb"
  405. team: ENG
  406. issues:
  407. - team: ENG
  408. title: Fix local checkout test
  409. description: Reproduce and fix the checkout failure.
  410. state: Todo
  411. assignee: dev@example.com
  412. labels: [Bug]
  413. oauth_apps:
  414. - client_id: lin_example_client_id
  415. client_secret: example_client_secret
  416. name: My Linear App
  417. redirect_uris:
  418. - http://localhost:3000/api/auth/callback/linear
  419. scopes: [read, write, issues:create, comments:create]
  420. actor: user
  421. tokens:
  422. - token: lin_test_admin
  423. user: admin@example.com
  424. scopes: [read, write, issues:create, comments:create, admin]
  425. strict_scopes: false
  426. apple:
  427. users:
  428. - email: testuser@icloud.com
  429. name: Test User
  430. oauth_clients:
  431. - client_id: com.example.app
  432. team_id: TEAM001
  433. name: My Apple App
  434. redirect_uris:
  435. - http://localhost:3000/api/auth/callback/apple
  436. microsoft:
  437. users:
  438. - email: testuser@outlook.com
  439. name: Test User
  440. oauth_clients:
  441. - client_id: example-client-id
  442. client_secret: example-client-secret
  443. name: My Microsoft App
  444. redirect_uris:
  445. - http://localhost:3000/api/auth/callback/microsoft-entra-id
  446. aws:
  447. region: us-east-1
  448. s3:
  449. buckets:
  450. - name: my-app-bucket
  451. - name: my-app-uploads
  452. sqs:
  453. queues:
  454. - name: my-app-events
  455. - name: my-app-dlq
  456. iam:
  457. users:
  458. - user_name: developer
  459. create_access_key: true
  460. roles:
  461. - role_name: lambda-execution-role
  462. description: Role for Lambda function execution
  463. kms:
  464. keys:
  465. - key_id: 1234abcd-12ab-34cd-56ef-1234567890ab
  466. description: App data key
  467. aliases: [alias/my-app-key]
  468. okta:
  469. users:
  470. - login: testuser@okta.local
  471. email: testuser@okta.local
  472. first_name: Test
  473. last_name: User
  474. groups:
  475. - name: Everyone
  476. description: All users
  477. type: BUILT_IN
  478. okta_id: 00g_everyone
  479. authorization_servers:
  480. - id: default
  481. name: default
  482. audiences: [api://default]
  483. oauth_clients:
  484. - client_id: okta-test-client
  485. client_secret: okta-test-secret
  486. name: Sample OIDC Client
  487. redirect_uris:
  488. - http://localhost:3000/callback
  489. auth_server_id: default
  490. strict_scopes: false
  491. resend:
  492. domains:
  493. - name: example.com
  494. region: us-east-1
  495. contacts:
  496. - email: test@example.com
  497. first_name: Test
  498. last_name: User
  499. stripe:
  500. customers:
  501. - email: test@example.com
  502. name: Test Customer
  503. products:
  504. - name: Pro Plan
  505. description: Monthly pro subscription
  506. prices:
  507. - product_name: Pro Plan
  508. currency: usd
  509. unit_amount: 2000
  510. strict_scopes: false
  511. mongoatlas:
  512. projects:
  513. - name: Project0
  514. clusters:
  515. - name: Cluster0
  516. project: Project0
  517. database_users:
  518. - username: admin
  519. project: Project0
  520. databases:
  521. - cluster: Cluster0
  522. name: test
  523. collections: [items]
  524. clerk:
  525. users:
  526. - first_name: Test
  527. last_name: User
  528. email_addresses: [test@example.com]
  529. password: clerk_test_password
  530. organizations:
  531. - name: My Company
  532. slug: my-company
  533. members:
  534. - email: test@example.com
  535. role: admin
  536. oauth_applications:
  537. - client_id: clerk_emulate_client
  538. client_secret: clerk_emulate_secret
  539. name: Emulate App
  540. redirect_uris:
  541. - http://localhost:3000/api/auth/callback/clerk
  542. twilio:
  543. account:
  544. sid: AC00000000000000000000000000000000
  545. auth_token: twilio_test_auth_token
  546. friendly_name: Local Twilio Account
  547. api_keys:
  548. - sid: SK00000000000000000000000000000000
  549. secret: twilio_test_api_secret
  550. friendly_name: Local API Key
  551. phone_numbers:
  552. - phone_number: "+15551234567"
  553. friendly_name: Local SMS and Voice Number
  554. sms_url: http://localhost:3000/api/twilio/sms
  555. voice_url: http://localhost:3000/api/twilio/voice
  556. messaging_services:
  557. - friendly_name: Local Messaging Service
  558. phone_numbers: ["+15551234567"]
  559. verify_services:
  560. - friendly_name: Local Verify Service
  561. code: "123456"
  562. default_channel: sms
  563. conversations:
  564. services:
  565. - friendly_name: Local Conversations
  566. ai:
  567. strict: false
  568. timing:
  569. ttftMs: 0
  570. chunkDelayMs: 0
  571. models: [gpt-x]
  572. rules:
  573. - id: weather-call
  574. match: { textContains: weather, tool: get_weather, hasToolResult: false }
  575. times: 1
  576. reply:
  577. - type: tool_call
  578. name: get_weather
  579. arguments: { city: Paris }
  580. - id: weather-result
  581. match: { hasToolResult: true }
  582. reply:
  583. - type: text
  584. text: The temperature in Paris is 20 C.
  585. - id: rate-limit-once
  586. match: { textContains: retry }
  587. times: 1
  588. error:
  589. status: 429
  590. message: Injected rate limit. Retry this request.
  591. headers:
  592. retry-after: "1"
  593. ```
  594. GitHub organization `members` are optional. Each entry references a seeded user by `login`; `role` defaults to `member`, while `admin` creates an organization administrator. Unknown users are ignored. Seeded memberships use the synthetic `members` team and grant private organization repository access.
  595. ## OAuth & Integrations
  596. The emulator supports configurable OAuth apps and integrations with strict client validation.
  597. ### Vercel Integrations
  598. ```yaml
  599. vercel:
  600. integrations:
  601. - client_id: "oac_abc123"
  602. client_secret: "secret_abc123"
  603. name: "My Vercel App"
  604. redirect_uris:
  605. - "http://localhost:3000/api/auth/callback/vercel"
  606. ```
  607. ### GitHub OAuth Apps
  608. ```yaml
  609. github:
  610. oauth_apps:
  611. - client_id: "Iv1.abc123"
  612. client_secret: "secret_abc123"
  613. name: "My Web App"
  614. redirect_uris:
  615. - "http://localhost:3000/api/auth/callback/github"
  616. ```
  617. If no `oauth_apps` are configured, the emulator accepts any `client_id` (backward-compatible). With apps configured, strict validation is enforced, and an authorization code can only be exchanged by the app it was issued to.
  618. `DELETE /applications/:client_id/token` and `DELETE /applications/:client_id/grant` take the app's `client_id` and `client_secret` as HTTP Basic credentials and an `access_token` in the JSON body. The first revokes that token; the second revokes the user's grant and every token the app holds for that user. Wrong client credentials return `401`, and a token that is unknown or belongs to another app returns `422`. A revoked token then fails as `401 Bad credentials`, even when unknown tokens fall back to a default user.
  619. ### GitHub Apps
  620. Full GitHub App support with JWT authentication and installation access tokens:
  621. ```yaml
  622. github:
  623. apps:
  624. - app_id: 12345
  625. slug: "my-github-app"
  626. name: "My GitHub App"
  627. permissions:
  628. contents: read
  629. issues: write
  630. events: [push, pull_request]
  631. webhook_url: "http://localhost:3000/webhooks/github"
  632. webhook_secret: "my-secret"
  633. installations:
  634. - installation_id: 100
  635. account: my-org
  636. repository_selection: all
  637. ```
  638. JWT authentication: sign a JWT with `{ iss: "<app_id>" }` using the app's private key (RS256). The emulator verifies the signature and resolves the app. For programmatic `createEmulator` calls, omit `private_key` and read the generated RSA key from `generatedSecrets`. The CLI generates an omitted key only when `--generated-secrets-file <path>` is provided; otherwise it requires an explicit, valid private key. Do not replace the omitted field with a fake PEM placeholder.
  639. Installation access tokens act as the configured GitHub App bot for repository writes. Repository ownership, selected repository access, and requested App permissions remain enforced. Pull request merges require `contents: write` on the base repository. Pull request branch updates require `pull_requests: write` on the pull request repository and `contents: write` on the head repository.
  640. Inspect secret-free metadata for minted installation tokens at `GET /_emulate/installation-tokens`.
  641. **App webhook delivery**: When events occur on repos where a GitHub App is installed, the emulator mirrors real GitHub behavior:
  642. - All webhook payloads (including repo and org hooks) include an `installation` field with `{ id, node_id }`.
  643. - If the app has a `webhook_url`, the emulator delivers the event there with the `installation` field and (if configured) an `X-Hub-Signature-256` header signed with `webhook_secret`.
  644. ### Slack OAuth Apps
  645. ```yaml
  646. slack:
  647. signing_secret: "my_signing_secret"
  648. oauth_apps:
  649. - client_id: "12345.67890"
  650. client_secret: "example_client_secret"
  651. name: "My Slack App"
  652. redirect_uris:
  653. - "http://localhost:3000/api/auth/callback/slack"
  654. ```
  655. The signing secret applies to every outbound Slack event subscription callback. Each signed callback includes `X-Slack-Request-Timestamp` and `X-Slack-Signature`, calculated as `v0=<HMAC-SHA256(secret, "v0:<timestamp>:<raw-body>")>`. Configure the receiver with the same secret and verify the unparsed request body. If the secret is absent or empty, callbacks are unsigned.
  656. ### Linear OAuth Apps
  657. ```yaml
  658. linear:
  659. oauth_apps:
  660. - client_id: "lin_example_client_id"
  661. client_secret: "example_client_secret"
  662. name: "My Linear App"
  663. redirect_uris:
  664. - "http://localhost:3000/api/auth/callback/linear"
  665. scopes: [read, write, issues:create, comments:create]
  666. actor: user
  667. ```
  668. ### Apple OAuth Clients
  669. ```yaml
  670. apple:
  671. oauth_clients:
  672. - client_id: "com.example.app"
  673. team_id: "TEAM001"
  674. name: "My Apple App"
  675. redirect_uris:
  676. - "http://localhost:3000/api/auth/callback/apple"
  677. ```
  678. ### Microsoft OAuth Clients
  679. ```yaml
  680. microsoft:
  681. oauth_clients:
  682. - client_id: "example-client-id"
  683. client_secret: "example-client-secret"
  684. name: "My Microsoft App"
  685. redirect_uris:
  686. - "http://localhost:3000/api/auth/callback/microsoft-entra-id"
  687. ```
  688. ## Vercel API
  689. Every endpoint below is fully stateful with Vercel-style JSON responses and cursor-based pagination.
  690. ### User & Teams
  691. - `GET /v2/user` - authenticated user
  692. - `PATCH /v2/user` - update user
  693. - `GET /v2/teams` - list teams (cursor paginated)
  694. - `GET /v2/teams/:teamId` - get team (by ID or slug)
  695. - `POST /v2/teams` - create team
  696. - `PATCH /v2/teams/:teamId` - update team
  697. - `GET /v2/teams/:teamId/members` - list members
  698. - `POST /v2/teams/:teamId/members` - add member
  699. ### Projects
  700. - `POST /v11/projects` - create project (with optional env vars and git integration)
  701. - `GET /v10/projects` - list projects (search, cursor pagination)
  702. - `GET /v9/projects/:idOrName` - get project (includes env vars)
  703. - `PATCH /v9/projects/:idOrName` - update project
  704. - `DELETE /v9/projects/:idOrName` - delete project (cascades)
  705. - `GET /v1/projects/:projectId/promote/aliases` - promote aliases status
  706. - `PATCH /v1/projects/:idOrName/protection-bypass` - manage bypass secrets
  707. ### Deployments
  708. - `POST /v13/deployments` - create deployment (auto-transitions to READY)
  709. - `GET /v13/deployments/:idOrUrl` - get deployment (by ID or URL)
  710. - `GET /v6/deployments` - list deployments (filter by project, target, state)
  711. - `GET /v7/deployments` - list deployments (filter by project, target, state, commit SHA)
  712. - `DELETE /v13/deployments/:id` - delete deployment (cascades)
  713. - `PATCH /v12/deployments/:id/cancel` - cancel building deployment
  714. - `GET /v2/deployments/:id/aliases` - list deployment aliases
  715. - `GET /v3/deployments/:idOrUrl/events` - get build events/logs
  716. - `GET /v6/deployments/:id/files` - list deployment files
  717. - `POST /v2/files` - upload file (by SHA digest)
  718. ### Domains
  719. - `POST /v10/projects/:idOrName/domains` - add domain (with verification challenge)
  720. - `GET /v9/projects/:idOrName/domains` - list domains
  721. - `GET /v9/projects/:idOrName/domains/:domain` - get domain
  722. - `PATCH /v9/projects/:idOrName/domains/:domain` - update domain
  723. - `DELETE /v9/projects/:idOrName/domains/:domain` - remove domain
  724. - `POST /v9/projects/:idOrName/domains/:domain/verify` - verify domain
  725. ### Environment Variables
  726. - `GET /v10/projects/:idOrName/env` - list env vars (with decrypt option)
  727. - `POST /v10/projects/:idOrName/env` - create env vars (single, batch, upsert)
  728. - `GET /v10/projects/:idOrName/env/:id` - get env var
  729. - `PATCH /v9/projects/:idOrName/env/:id` - update env var
  730. - `DELETE /v9/projects/:idOrName/env/:id` - delete env var
  731. ### Blob
  732. Implements the Vercel Blob API used by the `@vercel/blob` SDK (`put`, `head`, `list`, `del`).
  733. - `PUT /api/blob?pathname=<path>` - upload a blob (honors `x-add-random-suffix`, `x-allow-overwrite`, `x-content-type`, `x-cache-control-max-age`, `x-if-match` headers)
  734. - `PUT /api/blob?pathname=<path>&fromUrl=<url>` - copy a blob (`copy()`); `x-if-match` is compared with the source blob's ETag, and an existing destination is always replaced
  735. - `GET /api/blob?url=<urlOrPathname>` - blob metadata (`head()`)
  736. - `GET /api/blob?prefix=&limit=&cursor=&mode=` - list blobs (`list()`, including folded mode, where folders and root blobs share one sorted page and cursor)
  737. - `POST /api/blob/delete` - delete blobs (`del()`)
  738. - `POST /api/blob/mpu` with `x-mpu-action: create` - start a multipart upload (`createMultipartUpload()`), returning `{ key, uploadId }`
  739. - `GET /blob/:storeId/<pathname>` - serve blob content (public, no auth; `?download=1` adds an attachment disposition)
  740. Upload and deletion rules:
  741. - A single leading slash is removed from the pathname, so `/docs/readme.txt` is stored as `docs/readme.txt`. As in the real service, `//` is otherwise accepted over HTTP, so `//a.txt` is stored as `/a.txt` (the `@vercel/blob` SDK rejects `//` before sending a request). This also applies to copy destinations and multipart uploads.
  742. - The content type is taken from `x-content-type`, then the pathname extension when it is a known type, then the request `Content-Type` header, then `application/octet-stream`.
  743. - `x-cache-control-max-age` has a minimum of 60 seconds (`0` is stored as `public, max-age=60`). Absent or invalid values default to 30 days.
  744. - Deleting with a missing or empty `urls` array returns 400 `Missing urls in request body`. Malformed JSON returns 400 `Cannot delete more than 1,000 urls at once or body is malformed`, more than 1,000 urls returns 400 `Cannot delete more than 1,000 urls at once`, and any non-string entry returns 400 `Some urls are malformed`. Nothing is deleted in any of these cases.
  745. Point the SDK at the emulator with two environment variables:
  746. ```bash
  747. VERCEL_BLOB_API_URL=http://localhost:4000/api/blob
  748. BLOB_READ_WRITE_TOKEN=vercel_blob_rw_mystore_secret
  749. ```
  750. Any token of the form `vercel_blob_rw_<storeId>_<secret>` is accepted; the store id is parsed from the token. Multipart uploads can be created, but uploading parts and completing the upload are not supported yet and return 400. Client (browser) uploads are not supported yet.
  751. ## GitHub API
  752. Every endpoint below is fully stateful. Creates, updates, and deletes persist in memory and affect related entities.
  753. ### Users
  754. - `GET /user` - authenticated user
  755. - `PATCH /user` - update profile
  756. - `GET /users/:username` - get user
  757. - `GET /users` - list users
  758. - `GET /users/:username/repos` - list user repos
  759. - `GET /users/:username/orgs` - list user orgs
  760. - `GET /users/:username/followers` - list followers
  761. - `GET /users/:username/following` - list following
  762. ### Repositories
  763. - `GET /repos/:owner/:repo` - get repo
  764. - `GET /repositories/:id` - get repo by numeric ID
  765. - `POST /user/repos` - create user repo
  766. - `POST /orgs/:org/repos` - create org repo
  767. - `PATCH /repos/:owner/:repo` - update repo
  768. - `DELETE /repos/:owner/:repo` - delete repo (cascades)
  769. - `GET/PUT /repos/:owner/:repo/topics` - get/replace topics
  770. - `GET /repos/:owner/:repo/languages` - languages
  771. - `GET /repos/:owner/:repo/contributors` - contributors
  772. - `GET /repos/:owner/:repo/forks` - list forks
  773. - `POST /repos/:owner/:repo/forks` - create fork
  774. - `GET/PUT/DELETE /repos/:owner/:repo/collaborators/:username` - collaborators
  775. - `GET /repos/:owner/:repo/collaborators/:username/permission`
  776. - `POST /repos/:owner/:repo/transfer` - transfer repo
  777. - `GET /repos/:owner/:repo/tags` - list tags
  778. ### Contents & Commit History
  779. - `GET /repos/:owner/:repo/readme` - get the repository README
  780. - `GET /repos/:owner/:repo/contents/:path` - get a file or list a directory at a ref
  781. - Send `Accept: application/vnd.github.raw` or `application/vnd.github.raw+json` to file Contents and README requests to receive raw bytes; directory and submodule responses remain JSON
  782. - `GET /:owner/:repo/raw/:ref/:path` - download file content from advertised raw URLs; this is separate from Accept negotiation
  783. - `PUT/DELETE /repos/:owner/:repo/contents/:path` - create, update, or delete a file and commit the change
  784. - `GET /repos/:owner/:repo/commits` - list commits with ref, path, author, and date filters
  785. - `GET /repos/:owner/:repo/commits/:ref` - get a commit with file diffs and stats
  786. - `GET /repos/:owner/:repo/compare/:base...:head` - compare two refs
  787. ### Issues
  788. - `GET /repos/:owner/:repo/issues` - list (filter by state, labels, assignee, milestone, creator, since)
  789. - `POST /repos/:owner/:repo/issues` - create
  790. - `GET /repos/:owner/:repo/issues/:number` - get
  791. - `PATCH /repos/:owner/:repo/issues/:number` - update (state transitions, events)
  792. - `PUT/DELETE /repos/:owner/:repo/issues/:number/lock` - lock/unlock
  793. - `GET /repos/:owner/:repo/issues/:number/timeline` - timeline events
  794. - `GET /repos/:owner/:repo/issues/:number/events` - events
  795. - `POST/DELETE /repos/:owner/:repo/issues/:number/assignees` - manage assignees
  796. ### Pull Requests
  797. - `GET /repos/:owner/:repo/pulls` - list (filter by state, head, base)
  798. - `POST /repos/:owner/:repo/pulls` - create
  799. - `GET /repos/:owner/:repo/pulls/:number` - get
  800. - `PATCH /repos/:owner/:repo/pulls/:number` - update
  801. - `PUT /repos/:owner/:repo/pulls/:number/merge` - merge (with branch protection enforcement)
  802. - `GET /repos/:owner/:repo/pulls/:number/commits` - list commits
  803. - `GET /repos/:owner/:repo/pulls/:number/files` - list files
  804. - `POST/DELETE /repos/:owner/:repo/pulls/:number/requested_reviewers` - manage reviewers
  805. - `PUT /repos/:owner/:repo/pulls/:number/update-branch` - update branch
  806. ### Comments
  807. - Issue comments: full CRUD on `/repos/:owner/:repo/issues/:number/comments`
  808. - Review comments: full CRUD on `/repos/:owner/:repo/pulls/:number/comments`
  809. - Commit comments: full CRUD on `/repos/:owner/:repo/commits/:sha/comments`
  810. - Repo-wide listings for each type
  811. ### Reviews
  812. - `GET /repos/:owner/:repo/pulls/:number/reviews` - list
  813. - `POST /repos/:owner/:repo/pulls/:number/reviews` - create (with inline comments)
  814. - `GET/PUT /repos/:owner/:repo/pulls/:number/reviews/:id` - get/update
  815. - `POST /repos/:owner/:repo/pulls/:number/reviews/:id/events` - submit
  816. - `PUT /repos/:owner/:repo/pulls/:number/reviews/:id/dismissals` - dismiss
  817. ### Labels & Milestones
  818. - Labels: full CRUD, add/remove from issues, replace all
  819. - Milestones: full CRUD, state transitions, issue counts
  820. ### Branches & Git Data
  821. - Branches: list, get, protection CRUD (status checks, PR reviews, enforce admins)
  822. - Refs: get, match, create, update, delete
  823. - Commits: get, create
  824. - Trees: get (with recursive), create (with inline content)
  825. - Blobs: get, create
  826. - Tags: get, create
  827. ### Organizations & Teams
  828. - Orgs: get, update, list
  829. - Org members: list, check, remove, get/set membership
  830. - Teams: full CRUD, members, repos
  831. ### Releases
  832. - Releases: full CRUD, latest, by tag
  833. - Release assets: full CRUD, upload
  834. - Generate release notes
  835. ### Webhooks
  836. - Repo webhooks: full CRUD, ping, test, deliveries
  837. - Org webhooks: full CRUD, ping
  838. - Real HTTP delivery to registered URLs on all state changes
  839. ### Search
  840. - `GET /search/repositories` - full query syntax (user, org, language, topic, stars, forks, etc.)
  841. - `GET /search/issues` - issues + PRs (repo, is, author, label, milestone, state, etc.)
  842. - `GET /search/users` - users + orgs
  843. - `GET /search/code` - blob content search
  844. - `GET /search/commits` - commit message search
  845. - `GET /search/topics` - topic search
  846. - `GET /search/labels` - label search
  847. ### Actions
  848. - Workflows: list, get, enable/disable, dispatch
  849. - Workflow runs: list, get, cancel, rerun, delete, logs
  850. - Jobs: list, get, logs
  851. - Artifacts: list, get, delete
  852. - Secrets: repo + org CRUD
  853. ### Checks
  854. - Check runs: create, update, get, annotations, rerequest, list by ref/suite. Ref based lookups accept branch and tag refs containing slashes.
  855. - Check suites: create, get, preferences, rerequest, list by ref. Ref based lookups accept branch and tag refs containing slashes.
  856. - Automatic suite status rollup from check run results
  857. Check-run lists by ref and suite support `page` and `per_page` (default 30, maximum 100) with pagination `Link` headers. Ref lists apply `check_name`, `status`, and `filter` before pagination; `total_count` reports the full filtered count.
  858. Checks created with installation tokens include their GitHub App in API responses and webhooks. Suites are separated by App and commit, and `filter=latest` keeps the newest run for each App and check name. User-token checks return `app: null`; request-body `app_id` cannot set or change attribution.
  859. ### Misc
  860. - `GET /rate_limit` - rate limit status
  861. - `GET /meta` - server metadata
  862. - `GET /octocat` - ASCII art
  863. - `GET /emojis` - emoji URLs
  864. - `GET /zen` - random zen phrase
  865. - `GET /versions` - API versions
  866. ## Google OAuth + Gmail, Calendar, and Drive APIs
  867. OAuth 2.0, OpenID Connect, and mutable Google Workspace-style surfaces for local inbox, calendar, and drive flows.
  868. Google ID tokens are RS256-signed JWTs. The discovery document advertises RS256, and `/oauth2/v3/certs` returns the matching RSA public key used to verify issued tokens.
  869. Google authentication is permissive by default for local bearer-token workflows. Set `google.strict_scopes: true` in seed config to require emulator-issued, unexpired access tokens on Gmail, Calendar, Drive, and userinfo routes. Invalid credentials return `401 UNAUTHENTICATED`; missing method scopes return `403` with `insufficientPermissions`. Strict mode distinguishes read, write, send, settings, and metadata scopes, and userinfo includes only granted identity claims. Revoking an access or refresh token invalidates the linked access and refresh credentials. Discovery, signing keys, and the sign-in page remain public. This mode checks method scopes; resource-specific grants such as `drive.file` and Gmail add-on scopes are not modeled.
  870. - `GET /o/oauth2/v2/auth` - authorization endpoint
  871. - `POST /oauth2/token` - token exchange
  872. - `GET /oauth2/v2/userinfo` - get user info
  873. - `GET /.well-known/openid-configuration` - OIDC discovery document
  874. - `GET /oauth2/v3/certs` - JSON Web Key Set (JWKS) with the RSA public key for ID token verification
  875. - `GET /gmail/v1/users/:userId/messages` - list messages with `q`, `labelIds`, `maxResults`, and `pageToken`
  876. - `GET /gmail/v1/users/:userId/messages/:id` - fetch a Gmail-style message payload in `full`, `metadata`, `minimal`, or `raw` formats
  877. - `GET /gmail/v1/users/:userId/messages/:messageId/attachments/:id` - fetch attachment bodies
  878. - `POST /gmail/v1/users/:userId/messages/send` - create sent mail from `raw` MIME or structured fields
  879. - `POST /gmail/v1/users/:userId/messages/import` - import inbox mail
  880. - `POST /gmail/v1/users/:userId/messages` - insert a message directly
  881. - `POST /gmail/v1/users/:userId/messages/:id/modify` - add/remove labels on one message
  882. - `POST /gmail/v1/users/:userId/messages/batchModify` - add/remove labels across many messages
  883. - `POST /gmail/v1/users/:userId/messages/:id/trash` and `POST /gmail/v1/users/:userId/messages/:id/untrash`
  884. - `GET /gmail/v1/users/:userId/drafts`, `POST /gmail/v1/users/:userId/drafts`, `GET /gmail/v1/users/:userId/drafts/:id`, `PUT /gmail/v1/users/:userId/drafts/:id`, `POST /gmail/v1/users/:userId/drafts/:id/send`, `DELETE /gmail/v1/users/:userId/drafts/:id`
  885. - `POST /gmail/v1/users/:userId/threads/:id/modify` - add/remove labels across a thread
  886. - `GET /gmail/v1/users/:userId/threads` and `GET /gmail/v1/users/:userId/threads/:id`
  887. - `GET /gmail/v1/users/:userId/labels`, `POST /gmail/v1/users/:userId/labels`, `PATCH /gmail/v1/users/:userId/labels/:id`, `DELETE /gmail/v1/users/:userId/labels/:id`
  888. - `GET /gmail/v1/users/:userId/history`, `POST /gmail/v1/users/:userId/watch`, `POST /gmail/v1/users/:userId/stop`
  889. - `GET /gmail/v1/users/:userId/settings/filters`, `POST /gmail/v1/users/:userId/settings/filters`, `DELETE /gmail/v1/users/:userId/settings/filters/:id`
  890. - `GET /gmail/v1/users/:userId/settings/forwardingAddresses`, `GET /gmail/v1/users/:userId/settings/sendAs`
  891. - `GET /discovery/v1/apis/calendar/v3/rest` — public Calendar v3 REST discovery document
  892. - `GET /calendar/v3/users/:userId/calendarList`, `GET /calendar/v3/calendars/:calendarId/events`, `POST /calendar/v3/calendars/:calendarId/events`, `DELETE /calendar/v3/calendars/:calendarId/events/:eventId`, `POST /calendar/v3/freeBusy`
  893. - `GET /drive/v3/files`, `GET /drive/v3/files/:fileId`, `POST /drive/v3/files`, `PATCH /drive/v3/files/:fileId`, `PUT /drive/v3/files/:fileId`, `POST /upload/drive/v3/files`
  894. ## Slack API
  895. Fully stateful Slack Web API emulation with channels, messages, threads, reactions, user profiles, presence, modern file uploads, pins, bookmarks, views, OAuth v2, and incoming webhooks. Chat writes preserve common rich message fields such as `blocks`, `attachments`, `metadata`, formatting flags, unfurl flags, and client message ids. Conversation writes update archive state, names, topics, purposes, membership, DMs, MPIMs, and read cursors. User writes update profile fields, status, custom fields, and deterministic active or away presence. File writes support the current external upload flow with local upload URLs, file share messages, reads, lists, downloads, and deletes. Pin and bookmark writes support channel message pins and link bookmarks. View writes support App Home publishing and modal stacks. Seeded OAuth apps and OAuth installs create bot users and installation records. OAuth exchanges and explicit token seeds create scoped token records. Supported write state changes dispatch Slack `event_callback` payloads to configured webhook URLs.
  896. Set `slack.signing_secret` in seed config to sign every outbound event subscription callback. The emulator sends `X-Slack-Request-Timestamp` and `X-Slack-Signature`, where the signature is `v0=<HMAC-SHA256(secret, "v0:<timestamp>:<raw-body>")>`. Configure the receiver with the same secret and verify the unparsed request body. Without a secret, callbacks are unsigned.
  897. Slack message text is limited to 40,000 Unicode characters across chat writes, incoming webhooks, and file upload initial comments. Longer text is truncated at a Unicode code point boundary before it is stored or dispatched. Successful Web API responses include `warning: "message_truncated"` and `response_metadata` with the matching warning and explanatory message. Rich fields such as `blocks` and `attachments` are preserved unchanged.
  898. `chat.postMessage`, `chat.postEphemeral`, `chat.update`, and `chat.scheduleMessage` accept `markdown_text` in place of `text`. The emulator stores the Markdown source as the message `text` and adds no blocks, since Slack doesn't document how it reads such a message back. Sending `markdown_text` with a non-empty `text` or with `blocks` returns `markdown_text_conflict`, and an empty `markdown_text` counts as no text. Slack's 12,000-character limit for `markdown_text` is not enforced.
  899. ### Auth & Chat
  900. - `POST /api/auth.test` - test authentication
  901. - `POST /api/auth.revoke` - revoke the calling token (`test=1` checks without revoking); later Web API calls with it return `invalid_auth`. Revoking a bot token keeps the app installed but deactivates the bot user and removes it from its channels, so it gets no more `app_mention` events until the app is installed again
  902. - `POST /api/chat.postMessage` - post message with text or rich payload fields (supports threads via `thread_ts` and DM user IDs)
  903. - `POST /api/chat.postEphemeral` - post ephemeral message outside channel history
  904. - `POST /api/chat.update` - update message text and rich payload fields
  905. - `POST /api/chat.delete` - delete message
  906. - `GET /api/chat.getPermalink` / `POST /api/chat.getPermalink` - get message permalink
  907. - `POST /api/chat.scheduleMessage` - schedule pending message
  908. - `POST /api/chat.deleteScheduledMessage` - delete pending scheduled message
  909. - `POST /api/chat.scheduledMessages.list` - list pending scheduled messages
  910. - `POST /api/chat.meMessage` - /me message
  911. ### Conversations
  912. - `POST /api/conversations.list` - list conversations (cursor pagination, `types`, `exclude_archived`)
  913. - `POST /api/conversations.info` - get channel info
  914. - `POST /api/conversations.create` - create channel
  915. - `POST /api/conversations.archive` / `conversations.unarchive` - archive/restore channel
  916. - `POST /api/conversations.rename` - rename channel
  917. - `POST /api/conversations.setTopic` / `conversations.setPurpose` - update topic/purpose
  918. - `POST /api/conversations.history` - channel history with rich message fields
  919. - `POST /api/conversations.replies` - thread replies with rich message fields
  920. - `POST /api/conversations.join` / `conversations.leave` - join/leave
  921. - `POST /api/conversations.invite` / `conversations.kick` - manage membership
  922. - `POST /api/conversations.open` / `conversations.close` - open/close DMs and MPIMs
  923. - `POST /api/conversations.mark` - mark read cursor
  924. - `POST /api/conversations.members` - list members
  925. ### Users & Reactions
  926. - `POST /api/users.list` - list users (cursor pagination)
  927. - `POST /api/users.info` - get user info
  928. - `POST /api/users.lookupByEmail` - lookup by email
  929. - `GET /api/users.profile.get` / `POST /api/users.profile.get` - get user profile fields
  930. - `POST /api/users.profile.set` - update profile fields, status, and custom fields
  931. - `GET /api/users.getPresence` / `POST /api/users.getPresence` - get active or away presence
  932. - `POST /api/users.setPresence` - set the authed user to away or automatic presence
  933. - `POST /api/reactions.add` / `reactions.remove` / `reactions.get` - manage reactions
  934. ### Files
  935. - `POST /api/files.getUploadURLExternal` - create a local external upload session
  936. - `POST /upload/v1/:fileId` - receive raw uploaded file bytes
  937. - `POST /api/files.completeUploadExternal` - complete uploads and optionally share file messages
  938. - `GET /api/files.info` / `POST /api/files.info` - get file metadata
  939. - `GET /api/files.list` / `POST /api/files.list` - list completed files
  940. - `GET /files-pri/:fileId/:filename` - download file bytes with a bearer token that can access the file
  941. - `POST /api/files.delete` - delete a completed file
  942. ### Pins & Bookmarks
  943. - `POST /api/pins.add` - pin a message to a channel
  944. - `GET /api/pins.list` / `POST /api/pins.list` - list pinned message items for a channel
  945. - `POST /api/pins.remove` - remove a message pin from a channel
  946. - `POST /api/bookmarks.add` - add a link bookmark to a channel
  947. - `POST /api/bookmarks.edit` - update a link bookmark
  948. - `POST /api/bookmarks.list` - list channel bookmarks
  949. - `POST /api/bookmarks.remove` - remove a bookmark from a channel
  950. ### Views
  951. - `POST /api/views.publish` - publish or update an App Home view for a user
  952. - `POST /api/views.open` - open a modal view
  953. - `POST /api/views.update` - update a view by `view_id` or `external_id`
  954. - `POST /api/views.push` - push a modal view onto the current modal stack
  955. - `POST /api/views.generateTriggerId` - local helper for tests that need a modal trigger id
  956. Modal opens and pushes accept `trigger_id` or `interactivity_pointer` from an interaction payload or `/api/views.generateTriggerId`. Generate push values with an existing `view_id`. Triggers expire after 3 seconds by default; set `slack.view_trigger_ttl_seconds` to a positive number to allow more time in local tests.
  957. ### Team, Bots & Webhooks
  958. - `POST /api/team.info` - workspace info
  959. - `POST /api/bots.info` - bot info
  960. - `POST /services/:teamId/:botId/:webhookId` - incoming webhook with text or rich payload fields
  961. ### Channel privacy conversions
  962. `POST /api/admin.conversations.convertToPrivate` and `POST /api/admin.conversations.convertToPublic` accept `channel_id`. Use a user token belonging to a seeded admin; bot and test tokens return `not_allowed_token_type`, and non-admin users return `missing_scope`. With `slack.strict_scopes: true`, the token also needs `admin.conversations:write`. For example:
  963. ```yaml
  964. slack:
  965. tokens:
  966. - token: local-admin-user
  967. type: user
  968. user: admin
  969. scopes: [admin.conversations:write, channels:read, groups:read]
  970. ```
  971. Conversions preserve the channel ID, members, and history, update visibility in conversation and file reads, and append a `message` with subtype `channel_convert_to_private` or `channel_convert_to_public`. Event callbacks include the acting user and the new `channel_type` (`group` or `channel`). Admins need not belong to the channel. DMs, MPIMs, and repeated conversions are rejected; `#general` cannot become private.
  972. These methods operate on the emulated workspace without Slack's Enterprise plan or organization-wide installation requirements. Enterprise roles, channel-management policies, and MPIM conversion are not simulated.
  973. ### Slack Connect fixtures
  974. Seed a user with a different `team_id` to test messages from another workspace. `users.info` and `users.list` return that user's workspace and `is_stranger` flag. Omitted user teams default to the emulated workspace. `is_stranger` defaults to `false` and can be seeded to model a user outside the app's visible shared channels.
  975. ```yaml
  976. slack:
  977. users:
  978. - name: partner
  979. team_id: T_PARTNER
  980. is_stranger: false
  981. tokens:
  982. - token: xoxp-partner
  983. type: user
  984. user: partner
  985. scopes: [chat:write]
  986. ```
  987. Use the seeded user token to act as the external user. Invite the user and your app's bot to a channel with `conversations.invite`, then post a message mentioning the bot. The app-mention event includes the author's `user_team` and `source_team`; the outer `team_id` identifies the receiving installation workspace selected by the token, which defaults to the emulated workspace. Ordinary message callbacks retain the author user ID, which can be resolved with `users.info`.
  988. A channel with external members returns `is_ext_shared: true` and `is_shared: true`; its event callbacks include `is_ext_shared_channel: true`. Seed `channels[].is_ext_shared: true` to model an already shared channel. Sharing remains set after the last external member leaves or is removed, including across saved state. Slack Connect invitation and approval flows, workspace disconnection, and per-workspace channel settings are not simulated.
  989. ### Event retries
  990. Use `POST /_slack/simulate/event-retry` with an authenticated emulator token and JSON `{ "event_id": "Ev...", "reason": "http_timeout" }` to test event deduplication. Get the event ID from a received callback or the inspector's Events tab. The simulator resends the latest recorded delivery for that event to its original subscription, preserving the entire payload and event ID. If several subscribers received it, only the latest recipient is retried.
  991. Each attempt gets an increasing `X-Slack-Retry-Num`, starting at `1`, and `X-Slack-Retry-Reason` (default `http_timeout`). Reasons also accept `http_error`, `connection_failed`, `ssl_error`, `too_many_redirects`, and `unknown_error`. When `slack.signing_secret` is configured, the retry gets a fresh request timestamp and signature. The response includes `delivery_id`, `retry_num`, `success`, and `status_code`; a failed callback is recorded and still consumes a retry number.
  992. Retries are explicit, with no automatic scheduling or three-attempt limit. Only the latest 1,000 event deliveries are retained in memory, so retries are unavailable after their history is evicted or the emulator restarts. Unknown events return `event_not_found`, and an inactive subscription returns `subscription_inactive`.
  993. ### Interactivity
  994. Buttons and modal submissions can invoke your app's Interactivity Request URL. Configure `interactivity_url` on a seeded `slack.oauth_apps` entry and set `slack.signing_secret` to the same secret used by your receiver:
  995. ```yaml
  996. slack:
  997. signing_secret: local-signing-secret
  998. oauth_apps:
  999. - app_id: A_MY_APP
  1000. client_id: my-client
  1001. client_secret: my-secret
  1002. name: My App
  1003. redirect_uris: []
  1004. interactivity_url: http://localhost:3000/slack/interactions
  1005. ```
  1006. - `POST /_slack/simulate/block-actions` accepts `channel`, `message_ts`, and a button selector (`action_id`, exact `text`, or `url`), plus the acting `user` ID or name. It supports buttons in actions blocks and section accessories, including ephemeral messages visible to that user. The simulator requires an authenticated emulator token and the acting user must belong to the conversation.
  1007. - `POST /_slack/simulate/view-submission` accepts `view_id`, optional `user`, and `values` keyed by input block ID. Text inputs take strings; static selects and radio buttons take an option value; multi-selects and checkboxes take arrays of option values. Omitted values retain previous input or initial values. Other input elements return `unsupported_element`.
  1008. Callbacks are `application/x-www-form-urlencoded` with one `payload` JSON field, signed over the exact encoded request body. Button payloads include an app-bound, single-use `trigger_id` that can open a modal for the acting user. App ownership is preserved for messages posted with an app's bot or user token. Simulators return the payload and `delivery_id`; attempts and delivery results are saved in `slack.interaction_deliveries`.
  1009. A button payload's `response_url` accepts JSON without a bearer token, up to five times within 30 minutes. It posts an ephemeral reply by default, or a public reply with `response_type: "in_channel"`. Use `replace_original: true` or `delete_original: true` to modify the source message. Replacement retains the source message's visibility. Rich blocks and thread replies are supported.
  1010. A modal receiver must acknowledge within three seconds. An empty HTTP 200 closes the submitted view, while `response_action: "clear"` closes its stack. `errors` retains the view and returns block errors; `update` replaces its contents; `push` adds a new view subject to the three-view limit. Delivery failures and invalid acknowledgements leave the modal open. Shortcuts, slash commands, non-button actions, `view_closed`, and `block_suggestion` are not simulated.
  1011. ### OAuth
  1012. - `GET /oauth/v2/authorize` - authorization (shows user picker)
  1013. - `POST /oauth/v2/authorize/callback` - local user picker callback that creates the auth code
  1014. - `POST /api/oauth.v2.access` - token exchange
  1015. - `POST /api/apps.uninstall` - uninstall an app and revoke its workspace tokens
  1016. `POST /api/apps.uninstall` accepts `client_id`, `client_secret`, and an installation's user token in the Authorization header or POST `token` field. It removes that app's installation in the token's workspace and revokes all associated OAuth bot and user tokens, including earlier grants. Revoked credentials return `token_revoked` on Web API calls even with permissive authentication. Other apps and workspaces keep their credentials. Granular bot tokens cannot uninstall an app and return `no_permission`; configured development tokens without an app binding may uninstall a local installation. No method scope is required.
  1017. Uninstall dispatches `app_uninstalled` and `tokens_revoked` to matching event subscriptions with the removed app's `api_app_id`. `tokens_revoked.tokens.oauth` and `.bot` contain deduplicated user IDs, never token strings. Credentials are invalid before callbacks are delivered. Handlers should accept either event order. The app definition remains available for a new OAuth installation; reinstalling issues fresh tokens without reactivating revoked ones.
  1018. ### Inspector
  1019. - `GET /` - tabbed local inspector for conversations, messages, files, views, auth records, incoming webhooks, event subscriptions, and event deliveries
  1020. When a supported Slack write emits an `event_callback`, the payload contains the inner `event` plus outer `token`, `api_app_id`, `authorizations`, `team_id`, `event_id`, and `event_time`. The team comes from the presented Slack token's installation; development tokens without a stored Slack record fall back to the affected channel, user, or file's team, then the seeded workspace team (or `T000000001`). Incoming webhook posts use their webhook record's team, or the target channel's team when no record matches. `event_time` is an integer Unix timestamp in seconds. Each logical event gets a new `event_id`, shared across deliveries to multiple subscribers.
  1021. Callbacks identify each workspace installation with its recipient `api_app_id` and bot authorization. With multiple installed apps, each receives a separate envelope; configured webhook subscriptions are shared and can route by `api_app_id`. Without an installation, callbacks use `A000000001` and a local user authorization. The legacy `token` field defaults to `emulate-verification-token`; set `slack.verification_token` to match receivers that check it. Use `slack.signing_secret` for request signature verification.
  1022. Every inner event includes `event_ts`. Message events include `channel_type` (`channel`, `group`, `im`, or `mpim`). Posts made with an issued or seeded bot token include the bot's `bot_id`, `app_id`, and `bot_profile` when the corresponding bot record exists. These fields persist in history, replies, and updates so handlers can identify their own messages. Removing an installed bot with `conversations.kick` or `conversations.leave` also emits `channel_left` or `group_left`, with `actor_id` and `event_ts`, for the affected app.
  1023. To test bot handlers, invite an installed app's `bot_user_id` with `conversations.invite`, subscribe to `app_mention`, then post text containing `<@BOT_USER_ID>` with `chat.postMessage`. Channel mentions produce one callback per mentioned app, with outer `api_app_id`, inner `event_ts`, and the original message and thread identity. DMs and MPIMs use `message` events.
  1024. Slack scope checks are relaxed by default so local tests can use simple bearer tokens. Set `slack.strict_scopes: true` in seed config to make supported Web API methods return Slack-style `missing_scope` errors with `needed` and `provided` fields. Strict mode checks `chat:write`, `channels:read`, `channels:history`, `channels:join`, `channels:manage`, `channels:write`, `groups:read`, `groups:history`, `groups:write`, `im:read`, `im:history`, `im:write`, `mpim:read`, `mpim:history`, `mpim:write`, `users:read`, `users:read.email`, `users.profile:read`, `users.profile:write`, `users:write`, `files:read`, `files:write`, `pins:read`, `pins:write`, `bookmarks:read`, `bookmarks:write`, `reactions:read`, `reactions:write`, `team:read`, and `admin.conversations:write`. Slack lists no method-specific scopes for `views.publish`, `views.open`, `views.update`, or `views.push`, so the emulator requires auth but does not add strict-scope checks for those methods. Strict mode also rejects tokens the emulator did not issue: a token that does not come from seed config, server options, or an OAuth exchange returns `invalid_auth` instead of acting as the default user.
  1025. Current Slack limits: Slack Connect invitation and approval flows, per-workspace channel settings, other Enterprise Grid admin APIs, Audit Logs API, SCIM, Legal Holds, Socket Mode, slash commands, shortcuts, and interaction types other than button actions and modal submissions, user groups, reminders, stars, calls, canvases, lists, functions, workflows, chat streaming, legacy `files.upload`, exact rate limiting, and paid-plan behavior are not implemented.
  1026. ## Resend API
  1027. ### Recipient restrictions and send attempts
  1028. Set `resend.allowlist` in seed config to test recipient rejection:
  1029. ```yaml
  1030. resend:
  1031. allowlist:
  1032. - allowed@example.com
  1033. - copy@example.com
  1034. ```
  1035. Omitting `allowlist` accepts every recipient; `allowlist: []` rejects every recipient. Every address in `to`, `cc`, and `bcc` must be listed. Matching ignores surrounding whitespace and letter case; entries are individual addresses, with no wildcard or domain matching. This is a local testing control, independent of Resend's domain verification and account restrictions.
  1036. A rejected send returns `403 validation_error` naming the rejected addresses and configured allowlist. No email ID, email record, idempotency record, or webhook is created. A batch is rejected as a whole if any recipient is disallowed. Retrying a rejected request, even with the same idempotency key, creates a new attempt. Replaying an accepted idempotent request returns its original response even if the allowlist has since changed.
  1037. Validated sends append one record per email to the `resend.send_attempts` store collection, including emails in a rejected batch. Each record contains `from`, `to`, `cc`, `bcc`, `subject`, `idempotency_key` (or `null`), and the store's `id`, `created_at`, and `updated_at`. Message bodies are not copied into attempts. Malformed requests, invalid or conflicting idempotency keys, and idempotency replays do not append attempts.
  1038. Read attempts with `getResendStore(store).sendAttempts.all()` from `@emulators/resend`, or inspect the persisted state. Shared adapter snapshots use the key `resend:resend.send_attempts`. Attempts and recipient restrictions survive saved-state restoration, including rejected sends. There is no additional Resend API endpoint for attempts. A rejected send has an attempt without an email; a send that never happened has neither.
  1039. ## Linear API
  1040. Stateful Linear GraphQL API emulation with seeded organizations, users, teams, workflow states, issues, comments, labels, projects, cycles, OAuth apps, tokens, webhooks, and agent sessions. GraphQL reads and writes mutate in-memory state and use Relay-style connections with opaque cursors. OAuth supports authorization code, PKCE, refresh token, revoke, client credentials, and `actor=app` tokens for local app-actor tests. Supported writes dispatch Linear-shaped webhook payloads with `Linear-Delivery`, `Linear-Event`, `Linear-Timestamp`, and `Linear-Signature` headers when webhooks are configured.
  1041. ### GraphQL
  1042. - `POST /graphql` - GraphQL endpoint for queries and mutations
  1043. - `GET /graphql` - query-string GraphQL endpoint for tooling
  1044. - Queries: `viewer`, `organization`, `users`, `user`, `teams`, `team`, `workflowStates`, `workflowState`, `issues`, `issue`, `comments`, `comment`, `issueLabels`, `issueLabel`, `projects`, `project`, `cycles`, `cycle`, `webhooks`, `webhook`, `agentSessions`, `agentSession`, `agentActivities`, `agentActivity`
  1045. - Mutations: `issueCreate`, `issueUpdate`, `issueDelete`, `issueArchive`, `issueUnarchive`, `commentCreate`, `commentUpdate`, `commentDelete`, `issueLabelCreate`, `issueLabelUpdate`, `issueLabelDelete`, `issueAddLabel`, `issueRemoveLabel`, `webhookCreate`, `webhookDelete`, `agentSessionCreateOnIssue`, `agentSessionCreateOnComment`, `agentSessionUpdate`, `agentSessionUpdateExternalUrl`, `agentActivityCreate`
  1046. Issue selections expose both numeric `priority` and Linear's derived `priorityLabel` values: `No priority`, `Urgent`, `High`, `Medium`, and `Low`.
  1047. ### OAuth
  1048. - `GET /oauth/authorize` - authorization endpoint with local user picker
  1049. - `POST /oauth/authorize/callback` - local user picker callback that creates an authorization code
  1050. - `POST /oauth/token` - authorization code, refresh token, and client credentials grants
  1051. - `POST /oauth/revoke` - revoke access or refresh tokens
  1052. OAuth app `actor` config is authoritative. Apps configured with `actor: user` use authorization code flows. Apps configured with `actor: app` use the app install flow and can request client credentials tokens.
  1053. ### Agent Sessions
  1054. Agent sessions follow Linear's Agent Interaction API, so `@linear/sdk` agent code runs against the emulator with an app actor token. `agentActivityCreate` takes `AgentActivityCreateInput` (`agentSessionId`, a typed `content` object, `ephemeral`, `signal`, `signalMetadata`) and validates it as Linear does. `AgentActivity.content` is the `AgentActivityContent` union, and session `status` follows the latest activity. `agentSessionUpdate` sets plans, summaries, and external links. Webhooks subscribed to `AgentSessionEvent` receive `created` events with `promptContext` and `prompted` events with the prompt activity, in Linear's `AgentSessionEventWebhookPayload` shape. A human token can create `prompt` activities to simulate user messages. The earlier flat input `{ sessionId, type, body }` still works.
  1055. ### Webhooks And Inspector
  1056. - `webhookCreate` / `webhookDelete` manage local webhook subscriptions
  1057. - `GET /` - tabbed local inspector for issues, teams, users, projects, agents, auth records, webhook subscriptions, and deliveries
  1058. Linear scope checks are relaxed by default so local tests can use simple bearer tokens or the seeded `lin_test_admin` token. Set `linear.strict_scopes: true` in seed config to require `read`, `write`, `issues:create`, `comments:create`, or `admin` on supported GraphQL operations.
  1059. Current Linear limits: full schema coverage, exact production rate limiting, notification inbox behavior, rich document APIs, customer APIs, initiative APIs, exact search relevance, archiving agent sessions and activities, session dismissal by users, agent guidance, repository suggestions, and routing `AgentSessionEvent` webhooks to the owning app alone are not implemented.
  1060. ## Twilio API
  1061. Stateful Twilio REST emulation with seeded accounts, Auth Tokens, API keys, incoming phone numbers, Programmable Messaging, Messaging Services, Verify, basic Voice calls, Conversations REST resources, signed webhooks, local simulator routes, and an inspector. No real SMS, MMS, WhatsApp, email, voice, carrier, compliance, billing, or SendGrid traffic is performed.
  1062. Default local credentials:
  1063. ```text
  1064. TWILIO_ACCOUNT_SID=AC00000000000000000000000000000000
  1065. TWILIO_AUTH_TOKEN=twilio_test_auth_token
  1066. TWILIO_API_KEY=SK00000000000000000000000000000000
  1067. TWILIO_API_SECRET=twilio_test_api_secret
  1068. TWILIO_PHONE_NUMBER=+15551234567
  1069. TWILIO_VERIFY_SERVICE_SID=VA00000000000000000000000000000000
  1070. ```
  1071. ### REST Routes
  1072. - `GET /2010-04-01/Accounts/{AccountSid}.json` - fetch account
  1073. - `GET /2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers.json` - list phone numbers
  1074. - `POST /2010-04-01/Accounts/{AccountSid}/Messages.json` - create outbound message
  1075. - `GET /2010-04-01/Accounts/{AccountSid}/Messages.json` - list messages
  1076. - `POST /2010-04-01/Accounts/{AccountSid}/Calls.json` - create outbound call
  1077. - `POST /messaging/v1/Services` - create Messaging Service
  1078. - `POST /verify/v2/Services/{ServiceSid}/Verifications` - start verification
  1079. - `POST /verify/v2/Services/{ServiceSid}/VerificationCheck` - check verification code
  1080. - `POST /conversations/v1/Services` - create Conversation Service
  1081. - `POST /conversations/v1/Services/{ServiceSid}/Conversations` - create Conversation
  1082. - `POST /conversations/v1/Services/{ServiceSid}/Conversations/{ConversationSid}/Participants` - add participant
  1083. - `POST /conversations/v1/Services/{ServiceSid}/Conversations/{ConversationSid}/Messages` - add message
  1084. Twilio uses multiple product hosts. For local SDK tests, rewrite Twilio SDK requests to the emulator and map `messaging.twilio.com` to `/messaging`, `verify.twilio.com` to `/verify`, and `conversations.twilio.com` to `/conversations`.
  1085. Only an `active` account can send messages or place calls. Set the seeded account `status` to `suspended` or `closed`, or update it with `POST /2010-04-01/Accounts/{AccountSid}.json` and `Status`, to test the failure: message and call creation return HTTP 401 with error `20005`, "Account not active". Set the status back to `active` to restore them.
  1086. ### SMS And OTP Testing
  1087. For the common SMS verification loop, the seeded Verify Service uses code `123456`. Start a verification through the normal Verify API, then either submit `123456` in your app test or fetch the latest local code with the authenticated helper route:
  1088. ```sh
  1089. curl -u "$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN" \
  1090. "http://localhost:4000/_twilio/simulate/verification-code?To=%2B15550002222&ServiceSid=$TWILIO_VERIFY_SERVICE_SID"
  1091. ```
  1092. The helper returns the latest local verification for that phone number, including `verification_sid`, `status`, `attempts`, and `code`. It is local-only test support and is not part of Twilio's production API. The Verify inspector also shows each attempted code.
  1093. To test inbound SMS webhooks, configure a seeded phone number `sms_url`, then call `POST /_twilio/simulate/inbound-message` with `To`, `From`, and `Body`. If the destination number is assigned to a Messaging Service with `inbound_request_url`, the simulator sends the inbound webhook there and includes `MessagingServiceSid`; otherwise it uses the phone number `sms_url`. To test outbound delivery transitions, create a message with `StatusCallback`, then call `POST /_twilio/simulate/message-status`.
  1094. ### Simulator And Inspector
  1095. - `POST /_twilio/simulate/inbound-message` - create an inbound message and invoke the configured SMS webhook
  1096. - `POST /_twilio/simulate/message-status` - advance message status and send status callbacks
  1097. - `GET /_twilio/simulate/verification-code` - fetch the latest local Verify code by `VerificationSid` or `To`
  1098. - `POST /_twilio/simulate/inbound-call` - create an inbound call and invoke the configured voice webhook
  1099. - `POST /_twilio/simulate/call-status` - advance call status
  1100. - `POST /_twilio/simulate/verification-status` - force a verification state by `VerificationSid` or `To`
  1101. - `GET /` - tabbed inspector for messages, Verify, calls, Conversations, phone numbers, services, auth, and webhook deliveries
  1102. Current Twilio limits: no carrier delivery, A2P 10DLC, toll-free verification, real phone number purchasing, exact rate limits, Studio, Flex, TaskRouter, Video, Sync, Segment, SendGrid, Conversations SDK websocket behavior, or complete TwiML interpreter.
  1103. ## AI API
  1104. Deterministic OpenAI Responses, Chat Completions, and Anthropic Messages emulation. Replies are scripted by rules, not generated by a model, so the same request returns the same answer on every run. Text, streaming, structured output, tool loops, reasoning, refusals, stored responses, errors, mid-stream disconnects, and stalls are all available on demand, offline and without keys.
  1105. ### Base URL
  1106. ```bash
  1107. npx emulate start --service ai --port 4014
  1108. ```
  1109. A single selected service otherwise uses the base port, normally 4000. In an all-services run, `ai` listens on port 4014. Point clients at `http://localhost:4014/v1`. Any path prefix works, such as `/v1` or `/api/v1`; the format is selected from the end of the request path. API keys are accepted but never required, stored, or logged. Every generation response carries a deterministic request id: `x-request-id` on the OpenAI routes and `request-id` on the Anthropic Messages route.
  1110. ### Clients
  1111. The official OpenAI SDK reads `OPENAI_BASE_URL`, or you can pass the base URL explicitly:
  1112. ```typescript
  1113. import OpenAI from 'openai'
  1114. const openai = new OpenAI({
  1115. baseURL: 'http://localhost:4014/v1',
  1116. apiKey: 'test',
  1117. })
  1118. const chat = await openai.chat.completions.create({
  1119. model: 'gpt-x',
  1120. messages: [{ role: 'user', content: 'Hi' }],
  1121. })
  1122. const response = await openai.responses.create({
  1123. model: 'gpt-x',
  1124. input: 'Hi',
  1125. })
  1126. ```
  1127. The Vercel AI SDK uses the standard OpenAI provider. `openai(...)` posts to `/responses`; `openai.chat(...)` posts to `/chat/completions`:
  1128. ```typescript
  1129. import { createOpenAI } from '@ai-sdk/openai'
  1130. import { generateText } from 'ai'
  1131. const openai = createOpenAI({
  1132. baseURL: 'http://localhost:4014/v1',
  1133. apiKey: 'test',
  1134. })
  1135. const responses = await generateText({
  1136. model: openai('anthropic/claude-sonnet-5'),
  1137. prompt: 'Hi',
  1138. })
  1139. const chat = await generateText({
  1140. model: openai.chat('gpt-x'),
  1141. prompt: 'Hi',
  1142. })
  1143. ```
  1144. `@ai-sdk/openai-compatible` works in Chat mode against the same base URL. Vercel AI Gateway's OpenAI-compatible `/v1` surface works through either provider, and any model slug is accepted and echoed back. `createOpenAICompatible` sends `json_object` without a schema unless the provider sets `supportsStructuredOutputs: true`, so `generateObject` against the default `{}` reply fails its schema check: set `supportsStructuredOutputs: true`, or script the object with an `object` reply rule. The private `@ai-sdk/gateway` protocol is not supported.
  1145. ### Data routes
  1146. - `POST /v1/chat/completions` - Chat Completions, unary or streamed
  1147. - `POST /v1/responses` - Responses, unary or streamed
  1148. - `POST /v1/messages` - Anthropic Messages, unary or streamed
  1149. - `GET /v1/responses/{id}` - retrieve a stored response
  1150. - `DELETE /v1/responses/{id}` - delete a stored response
  1151. - `GET /v1/models` - list configured and previously requested model ids
  1152. An unsupported data path such as `/v1/embeddings` returns the native 404 naming the supported paths.
  1153. ### Rules
  1154. Rules live under `ai.rules` in seed config or are replaced at runtime. They are evaluated in order and the first match wins. Every supplied matcher must hold. `times` is a per-rule budget consumed on every selection, including injected errors, so an exhausted rule is skipped.
  1155. ```yaml
  1156. ai:
  1157. strict: false
  1158. timing:
  1159. ttftMs: 0
  1160. chunkDelayMs: 0
  1161. models: [gpt-x]
  1162. rules:
  1163. - id: weather-call
  1164. match:
  1165. textContains: weather
  1166. tool: get_weather
  1167. hasToolResult: false
  1168. times: 1
  1169. reply:
  1170. - type: tool_call
  1171. name: get_weather
  1172. arguments:
  1173. city: Paris
  1174. - id: weather-result
  1175. match:
  1176. hasToolResult: true
  1177. reply:
  1178. - type: text
  1179. text: The temperature in Paris is 20 C.
  1180. - id: rate-limit-once
  1181. match: { textContains: retry }
  1182. times: 1
  1183. error:
  1184. status: 429
  1185. message: Injected rate limit. Retry this request.
  1186. headers:
  1187. retry-after: "1"
  1188. ```
  1189. In a project config with a `services:` map, the seed goes under `services.<name>.seed`, not a top-level `ai:` block, which would start a second service named `ai`:
  1190. ```yaml
  1191. services:
  1192. llm:
  1193. emulator: ai
  1194. seed: { rules: [{ id: weather, match: { textContains: weather }, reply: [{ type: text, text: Sunny }] }] }
  1195. ```
  1196. Matchers are `model` (with `*` wildcards), `format` (`openai-chat`, `openai-responses`, or `anthropic-messages`), `stream`, `textContains` (case-sensitive, latest user instruction only, excluding tool results), `tool` (a declared tool, with `*` wildcards), `hasToolResult`, and `file` (`true` for any attachment, including one returned inside a tool result, or a media-type glob). Reply events are `text`, `object` (sent as JSON text), `tool_call`, `reasoning` (a Responses summary or a Messages `thinking` block; Chat has no field for it), and `refusal` (native shape). A rule has one of `reply`, `variants`, or `error`. `finish` and `timing` go with `reply` or `variants`, and `fault` also requires `match: { stream: true }`. A `tool_call` event's `arguments` must be a JSON object; a string is rejected at startup and on `PUT /_ai/rules`. A fault disconnects or stalls a stream after a counted number of content chunks.
  1197. Set `timing.ttftMs` and `timing.chunkDelayMs` globally or per rule. Both default to zero, so replies are instant. `ttftMs` is the wait before the first byte of any reply, streamed or not, and `chunkDelayMs` is the gap between the frames of a stream. Delays are abortable: a client close or reset cancels pending timers.
  1198. Request limits apply to every reply, scripted or default. A stop sequence (`stop` on Chat Completions) cuts the reply text at the first match; the sequence is not returned, nothing after it is sent, and the reply ends with `stop`. On Messages, `stop_sequences` works the same way, and the reply reports `stop_reason: "stop_sequence"` with the match in `stop_sequence`. A token cap (`max_completion_tokens` or `max_tokens` on Chat Completions, `max_output_tokens` on Responses) counts output at one token per four characters, the same estimate the usage numbers use. A reply over the cap is cut there and ends with `length`, which Responses reports as `status: "incomplete"` with `incomplete_details.reason: "max_output_tokens"`. A tool call that does not fit is dropped whole rather than sent partially. On Messages, `max_tokens` is the cap, and a reply over it ends with `stop_reason: "max_tokens"`. A rule's own `finish` still wins when it is set.
  1199. ### Defaults and strict mode
  1200. With no matching rule, the service echoes the latest user text, returns a deterministic schema-valid object when a schema was requested, returns `{}` for JSON mode without a schema, generates a call when a tool is forced, acknowledges a tool result or an attachment-only request, and accepts and echoes any model id.
  1201. Supported schema features are `type`, `properties`, `required`, `enum`, `const`, `items`, numeric and length bounds, `nullable`, the first `anyOf` branch that yields a valid sample, the first `oneOf` branch whose sample matches exactly one branch (the native 400 when none does), and local `$ref`, with recursion bounded. Keywords written next to `$ref`, `anyOf`, or `oneOf` shape the sample as well. A schema outside that subset returns a native 400 naming the schema path. A string with `pattern` is generated only when it also has a common `format` the generator knows; otherwise the request returns the native 400 asking for an explicit reply rule. A format sample, `enum` value, or `const` that fails the pattern returns the same 400, and pattern checks run under a time limit.
  1202. Set `ai.strict: true` to turn every unmatched request into a native 400 naming the model and tools and including the missing rule as YAML and as a JSON body for the rules endpoint.
  1203. ### Stored responses and the call record
  1204. Responses are stored by default so multi-turn sessions and item references resolve. Set `store: false` to skip storage. Unknown `previous_response_id` and item references are treated as empty context, so a request still succeeds. A function call with no matching `function_call_output` returns OpenAI's 400, `No tool output found for function call <id>.`, unless the history it refers to is missing.
  1205. Every generation request is recorded with its format, model, `matched`, normalized prompt and tool arguments, and outcome. `matched` is `{ "id": "<rule id>", "remaining": <budget left or null>, "rule": <the rule as it was when it answered> }` for a rule, `{ "default": "<kind>" }` when a default answered, and `null` when strict mode rejected the request. The last 500 calls are kept. Stored responses are capped at the most recent 1000; older ones are evicted. Keys, auth headers, and file bytes are never recorded. Attachment metadata records the name, media type, size, and hash only.
  1206. ### Control routes and inspector
  1207. All control routes and the inspector are same-origin only, reads included. curl and tests without an `Origin` header work; a browser page from another origin gets 403. Data routes accept SDK and server calls, which send no `Origin`, and browser pages served on this machine (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`); a page on any other website gets 403. Startup warns when the service listens beyond loopback. The AI service also checks the request's own host, so a website whose name is rebound to this machine cannot read it: it answers only on loopback names, IP addresses, and the host of its base URL, and any other name gets 403. To allow another name, such as a Docker service name, start with `--base-url http://<host>:<port>`. When embedded through `createEmulateHandler`, set `publicUrl` to the public origin.
  1208. - `GET /_ai/calls` - recorded calls
  1209. - `DELETE /_ai/calls` - clear the call record
  1210. - `GET /_ai/rules` - active rules with remaining budgets
  1211. - `PUT /_ai/rules` - replace the active rules without restarting
  1212. - `POST /_ai/reset` - restore seeded rules and budgets, and clear calls and stored responses
  1213. - `GET /` - read-only inspector with Calls and Rules tabs
  1214. `GET /_ai/calls` returns a bare JSON array, oldest first. `DELETE /_ai/calls` returns `{ "deleted": <count> }`. `GET /_ai/rules` and `PUT /_ai/rules` return `{ "rules": [...], "strict": <bool>, "timing": {...}, "random": { "seed": <number> }, "models": [...] }` with each rule's `remaining` budget (`null` means unlimited), in the shape `PUT` accepts. `POST /_ai/reset` returns `{ "reset": true }`.
  1215. ```bash
  1216. curl -s http://localhost:4014/_ai/calls | jq
  1217. curl -X PUT http://localhost:4014/_ai/rules \
  1218. -H "Content-Type: application/json" \
  1219. -d '{
  1220. "rules": [
  1221. {
  1222. "id": "hello",
  1223. "match": { "textContains": "Hi" },
  1224. "reply": [{ "type": "text", "text": "Hello from emulate." }]
  1225. }
  1226. ]
  1227. }'
  1228. ```
  1229. An invalid replacement returns 400 with the failing path and leaves the previous rules active. `PUT` replaces the whole runtime config, so include `strict`, `timing`, `random`, and `models` in the body to keep them; a body with only `rules` resets them to their defaults, and a reset seed changes the order of seeded variants. Every replacement also restores each rule's full `times` budget. Runtime replacements are ephemeral: reset restores the seeded rules.
  1230. ### Refusals, attachments, and limits
  1231. A refusal rule produces OpenAI's native refusal shape only when a rule asks for one. The AI SDK cannot parse it: `@ai-sdk/openai` 3.x and 4.x reject a native Responses refusal part in non-streaming mode with a parse error and drop it when streaming, and Chat parsing omits `refusal`. Test native refusal handling with the official `openai` SDK; for app behavior through the AI SDK, script the same user-visible content as `text`.
  1232. Attachments are input only. The emulator never reads their contents to produce an answer; rules decide the reply. Inline bytes are hashed, measured, and dropped. Responses accepts `input_file` with inline data, a URL, or a file id, plus `input_image`. Chat accepts `file` parts with inline data or a file id, and `image_url`; Chat files must be PDFs and Chat does not accept file URLs. Malformed inline data returns a native 400. The AI SDK validates attachments before sending, so `@ai-sdk/openai` rejects `text/plain` and other non-PDF, non-image files client-side unless `passThroughUnsupportedFiles` is set.
  1233. On the OpenAI routes, result-changing features outside this version return a native 400 naming the feature: hosted tools, custom tools, allowed tool choice, background mode, the Conversations API, multiple candidates, audio input, audio output, and legacy functions.
  1234. On the Messages route, tools carry `input_schema`, except Anthropic-defined client tools (bash, text editor, computer use, memory), which are accepted by name without one. Server-side tools (web search, web fetch, code execution, tool search, MCP toolset) return a 400. A base64 image source must be `image/jpeg`, `image/png`, `image/gif`, or `image/webp`, and a base64 document source must be `application/pdf`. Messages errors use Anthropic's envelope, and a validation error starts with the failing field, as in `max_tokens: Expected a number.` Unsupported paths under `/v1/messages`, such as `count_tokens`, and any request with an `anthropic-version` header get a `not_found_error` in the same envelope.
  1235. Paths with no route return the native 404 naming the supported paths: Gemini, embeddings, image generation, file uploads, input item listing, token counting, and response cancellation.
  1236. Accepted and ignored, with no effect on replies: OpenRouter `reasoning` fields and unknown optional fields. Reply text is sent as written with no templating.
  1237. ## Apple Sign In
  1238. Sign in with Apple emulation with authorization code flow, PKCE support, RS256 ID tokens, and OIDC discovery.
  1239. - `GET /.well-known/openid-configuration` - OIDC discovery document
  1240. - `GET /auth/keys` - JSON Web Key Set (JWKS)
  1241. - `GET /auth/authorize` - authorization endpoint (shows user picker)
  1242. - `POST /auth/token` - token exchange (authorization code and refresh token grants)
  1243. - `POST /auth/revoke` - token revocation
  1244. ## Microsoft Entra ID
  1245. Microsoft Entra ID (Azure AD) v2.0 OAuth 2.0 and OpenID Connect emulation with authorization code flow, PKCE, client credentials, client-bound refresh tokens, RS256 ID tokens, and OIDC discovery.
  1246. - `GET /.well-known/openid-configuration` - OIDC discovery document
  1247. - `GET /:tenant/v2.0/.well-known/openid-configuration` - tenant-scoped OIDC discovery
  1248. - `GET /discovery/v2.0/keys` - JSON Web Key Set (JWKS)
  1249. - `GET /oauth2/v2.0/authorize` - authorization endpoint (shows user picker)
  1250. - `POST /oauth2/v2.0/token` - token exchange (authorization code, refresh token, client credentials)
  1251. - `GET /oidc/userinfo` - OpenID Connect user info
  1252. - `GET /v1.0/me` - Microsoft Graph user profile
  1253. - `GET /oauth2/v2.0/logout` - end session / logout
  1254. - `POST /oauth2/v2.0/revoke` - token revocation
  1255. Refresh token requests must include the `client_id` and `client_secret` of the client that received the token. Refresh tokens rotate after successful use. Legacy refresh records without a stored client binding remain supported.
  1256. ```bash
  1257. curl -X POST http://localhost:4005/oauth2/v2.0/token \
  1258. -H "Content-Type: application/x-www-form-urlencoded" \
  1259. -d "refresh_token=r_microsoft_...&\
  1260. client_id=example-client-id&\
  1261. client_secret=example-client-secret&\
  1262. grant_type=refresh_token"
  1263. ```
  1264. ## AWS
  1265. S3, SQS, Cognito, IAM, STS, and KMS emulation with AWS SDK-compatible S3 paths. S3 uploads and downloads preserve arbitrary binary payloads, including raw byte lengths and ETags. SQS supports AWS JSON 1.0 and XML Query protocols; IAM and STS use XML Query; KMS uses AWS JSON 1.1.
  1266. ### S3
  1267. S3 routes use root paths matching the real AWS S3 wire format, so the official AWS SDK works out of the box with `forcePathStyle: true`. Legacy `/s3/` prefixed paths are also supported for backward compatibility.
  1268. - `GET /` - list all buckets
  1269. - `PUT /:bucket` - create bucket
  1270. - `DELETE /:bucket` - delete bucket
  1271. - `HEAD /:bucket` - check existence
  1272. - `GET /:bucket` - list objects (prefix, delimiter, max-keys, continuation-token, start-after)
  1273. - `POST /:bucket` - presigned POST upload (browser-style multipart form with policy validation)
  1274. - `PUT /:bucket/:key` - put object (supports copy via `x-amz-copy-source`)
  1275. - `GET /:bucket/:key` - get object
  1276. - `HEAD /:bucket/:key` - head object
  1277. - `DELETE /:bucket/:key` - delete object
  1278. ### SQS
  1279. Current AWS SDK clients work with the `/sqs` endpoint:
  1280. ```typescript
  1281. import { SQSClient, ListQueuesCommand } from "@aws-sdk/client-sqs";
  1282. const sqs = new SQSClient({
  1283. endpoint: "http://localhost:4007/sqs",
  1284. region: "us-east-1",
  1285. credentials: {
  1286. accessKeyId: "AKIAIOSFODNN7EXAMPLE",
  1287. secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
  1288. },
  1289. });
  1290. await sqs.send(new ListQueuesCommand({}));
  1291. ```
  1292. SQS accepts AWS JSON 1.0 requests at `POST /sqs/` with `Content-Type: application/x-amz-json-1.0` and `X-Amz-Target: AmazonSQS.<Action>`, returning JSON results and errors. XML Query requests with an `Action` form parameter remain supported. Queue operations also accept the returned `QueueUrl` as the endpoint.
  1293. Supported operations:
  1294. - `CreateQueue`, `ListQueues`, `GetQueueUrl`, `GetQueueAttributes`
  1295. - `SendMessage`, `ReceiveMessage`, `DeleteMessage`
  1296. - `PurgeQueue`, `DeleteQueue`
  1297. ### IAM
  1298. All operations via `POST /iam/` with `Action` parameter:
  1299. - `CreateUser`, `GetUser`, `ListUsers`, `DeleteUser`
  1300. - `CreateAccessKey`, `ListAccessKeys`, `DeleteAccessKey`
  1301. - `CreateRole`, `GetRole`, `ListRoles`, `DeleteRole`
  1302. ### Cognito
  1303. Use `CognitoIdentityProviderClient` with endpoint `/cognito-idp` and `CognitoIdentityClient` with `/cognito-identity`. Both accept AWS JSON 1.1 and work with the official AWS SDK v3:
  1304. ```typescript
  1305. import { CognitoIdentityProviderClient, InitiateAuthCommand } from "@aws-sdk/client-cognito-identity-provider";
  1306. const cognito = new CognitoIdentityProviderClient({
  1307. endpoint: "http://localhost:4007/cognito-idp",
  1308. region: "us-east-1",
  1309. credentials: { accessKeyId: "local-access-key", secretAccessKey: "local-secret" },
  1310. });
  1311. const result = await cognito.send(new InitiateAuthCommand({
  1312. ClientId: "emulateclient",
  1313. AuthFlow: "USER_PASSWORD_AUTH",
  1314. AuthParameters: { USERNAME: "developer", PASSWORD: "LocalPass123!" },
  1315. }));
  1316. ```
  1317. A default User Pool `us-east-1_emulate`, public app client `emulateclient`, and Identity Pool `us-east-1:00000000-0000-4000-8000-000000000001` are created without users. Seed a confirmed account for the example above:
  1318. ```yaml
  1319. aws:
  1320. cognito:
  1321. user_pools:
  1322. - id: us-east-1_emulate
  1323. confirmation_code: "123456"
  1324. users:
  1325. - username: developer
  1326. password: LocalPass123!
  1327. attributes:
  1328. email: dev@example.com
  1329. email_verified: "true"
  1330. name: Developer
  1331. ```
  1332. User pools also accept `name` and `clients` with `client_id`, optional `client_secret`, exact `redirect_uris`, and allowed `scopes`. Users accept `status` (`CONFIRMED`, `UNCONFIRMED`, or `FORCE_CHANGE_PASSWORD`) and `enabled`. Passwords require at least eight characters and are stored as salted hashes. Confidential clients require Cognito's HMAC `SecretHash` or `SECRET_HASH` for SDK flows.
  1333. - `SignUp`, `ConfirmSignUp`, `ResendConfirmationCode`, `ForgotPassword`, and `ConfirmForgotPassword` model account confirmation and recovery. Codes expire after ten minutes and use the pool's `confirmation_code` fixture, default `123456`. No email or SMS is sent. Inspect active codes at `/_inspector?tab=cognito`; seeded unconfirmed users can request a code with `ResendConfirmationCode`.
  1334. - `InitiateAuth` supports `USER_PASSWORD_AUTH`, `REFRESH_TOKEN_AUTH`, and `REFRESH_TOKEN`. `AdminInitiateAuth` also supports `ADMIN_USER_PASSWORD_AUTH`. Admin-created temporary passwords return `NEW_PASSWORD_REQUIRED`, completed with `RespondToAuthChallenge` or `AdminRespondToAuthChallenge`. Challenge sessions expire after three minutes and are bound to the user and client.
  1335. - `GetUser`, `ChangePassword`, `GlobalSignOut`, and `RevokeToken` use issued tokens. `AdminCreateUser` (with `TemporaryPassword`), `AdminGetUser`, `AdminConfirmSignUp`, `AdminSetUserPassword`, `AdminEnableUser`, `AdminDisableUser`, `AdminDeleteUser`, and paginated `ListUsers` support test setup and administration.
  1336. Tokens are RS256 JWTs with Cognito `token_use` claims. ID tokens identify the app client in `aud`; access tokens use `client_id`. ID and access tokens expire after one hour; refresh tokens after thirty days. Sign-out, revocation, disabling, deletion, and password resets invalidate affected sessions. Users, sessions, identities, and signing keys participate in snapshots, restore, and reset.
  1337. The local issuer is `http://localhost:4007/cognito-idp/USER_POOL_ID`. Discovery and public keys are served at `ISSUER/.well-known/openid-configuration` and `ISSUER/.well-known/jwks.json`. Configure token verifiers with this local issuer and JWKS. `ISSUER/oauth2/authorize` presents a local user picker, `ISSUER/oauth2/token` exchanges authorization codes or refresh tokens, and `ISSUER/oauth2/userInfo` returns scoped profile claims. Authorization codes expire after five minutes, are single-use, and bind the client, exact redirect URI, and optional S256 PKCE challenge. Client authentication accepts `client_secret_basic` or `client_secret_post`. The default client permits `http://localhost:3000/callback`.
  1338. Identity Pools support `GetId` and `GetCredentialsForIdentity`. Supply the ID token in `Logins` under `cognito-idp.REGION.amazonaws.com/USER_POOL_ID`. The default Identity Pool accepts the default User Pool and app client. Custom `aws.cognito.identity_pools` entries take `id`, optional `name`, `providers: [{ user_pool_id, client_id }]`, and `allow_unauthenticated_identities` (default `false`). Identities remain stable for the same authenticated subject. Credentials expire after one hour; login signatures, expiry, audience, and identity ownership are checked.
  1339. SRP, MFA, external identity providers, Lambda triggers, pool/client management APIs, `ListUsers` filters, and Identity Pool role selection are not simulated. Administrative requests follow the AWS emulator's permissive credential behavior: SigV4 signatures and IAM policies are not evaluated. Identity Pool credentials are generated test credentials, without role or policy evaluation.
  1340. ### STS
  1341. All operations via `POST /sts/` with `Action` parameter:
  1342. - `GetCallerIdentity`, `AssumeRole`, `AssumeRoleWithWebIdentity`
  1343. `AssumeRoleWithWebIdentity` exchanges an OpenID Connect ID token for temporary credentials. The request needs no signature or `Authorization` header, so `STSClient` works with the `/sts` endpoint and no credentials. The role must exist: seed it with `aws.iam.roles` or create it with `CreateRole`. An unknown role ARN returns `AccessDenied` (403). The token's `iss`, `sub`, and `aud` claims become `Provider`, `SubjectFromWebIdentityToken`, and `Audience`. A token that is not a JWT returns `InvalidIdentityToken`, and a token whose `exp` has passed returns `ExpiredToken`. With `ProviderId`, the token is treated as an opaque OAuth 2.0 access token. `DurationSeconds` defaults to 3600 and accepts 900 through 43200. Token signatures, IAM OIDC providers, role trust policies, session policies, and the role's maximum session duration are not evaluated.
  1344. ### KMS
  1345. KMS accepts AWS JSON 1.1 requests at `POST /kms/` with `Content-Type: application/x-amz-json-1.1` and `X-Amz-Target: TrentService.<Action>`, returning JSON results and `__type` errors. Use `KMSClient` with endpoint `/kms`.
  1346. - `CreateKey`, `DescribeKey`, `ListKeys`, `Encrypt`, `Decrypt`
  1347. Every `KeyId` accepts a key ID, key ARN, alias name (`alias/...`), or alias ARN. `Encrypt` and `Decrypt` responses return the key ARN as `KeyId`. A default key with alias `alias/emulate-default` is always created. Seed more keys under `aws.kms.keys`; each entry takes an optional `key_id` (a lowercase UUID), `description`, and `aliases`. Plaintext is limited to 4096 bytes. A ciphertext blob records the key that produced it, so `Decrypt` needs no `KeyId`, and a `KeyId` naming a different key returns `IncorrectKeyException`. The encryption context is authenticated: decrypting with a different context or a modified blob returns `InvalidCiphertextException`. Unknown keys and aliases return `NotFoundException`, and `DryRun` returns `DryRunOperationException`. Only symmetric `ENCRYPT_DECRYPT` keys are emulated; other key specs, key usages, origins, and multi-Region keys return `UnsupportedOperationException`. Aliases come from seed config, and seeding an alias that already points at another key, such as `alias/emulate-default`, fails at startup. Alias management, key state changes, key policies, grants, rotation, and data key generation are not implemented, and request signatures are not checked.
  1348. ### External backend
  1349. Set `aws.backend.url` to forward S3, SQS, IAM, STS, and KMS to an AWS-compatible endpoint, such as [AWS Emulator](https://github.com/aws/aws-emulator) started with `--auth off`. The URL cannot include credentials: URLs with userinfo are rejected at startup. Cognito and the inspector stay local, and clients keep using the emulator's port and path prefixes. Seeded buckets, queues, IAM users and roles, and KMS keys are created on the backend once per emulator start; a failed seed is retried on the next forwarded request. See the [AWS docs](https://emulate.dev/aws#external-backend).
  1350. ## Next.js Integration
  1351. Embed emulators directly in your Next.js app so they run on the same origin. This solves the Vercel preview deployment problem where OAuth callback URLs change with every deployment.
  1352. ### Install
  1353. ```bash
  1354. npm install @emulators/adapter-next @emulators/github @emulators/google
  1355. ```
  1356. Only install the emulators you need. Each `@emulators/*` package is published independently.
  1357. ### Route handler
  1358. Create a catch-all route that serves emulator traffic:
  1359. ```typescript
  1360. // app/emulate/[...path]/route.ts
  1361. import { createEmulateHandler } from '@emulators/adapter-next'
  1362. import * as github from '@emulators/github'
  1363. import * as google from '@emulators/google'
  1364. export const { GET, POST, PUT, PATCH, DELETE } = createEmulateHandler({
  1365. services: {
  1366. github: {
  1367. emulator: github,
  1368. seed: {
  1369. users: [{ login: 'octocat', name: 'The Octocat' }],
  1370. repos: [{ owner: 'octocat', name: 'hello-world', auto_init: true }],
  1371. },
  1372. },
  1373. google: {
  1374. emulator: google,
  1375. seed: {
  1376. users: [{ email: 'test@example.com', name: 'Test User' }],
  1377. },
  1378. },
  1379. },
  1380. })
  1381. ```
  1382. GitHub App seeds may omit `private_key`. Retain the handler to call server-only `generatedSecrets()`; explicit keys are excluded. Persisted snapshots contain generated keys, so keep the backend private.
  1383. ### Auth.js / NextAuth configuration
  1384. Point your provider at the emulator paths on the same origin:
  1385. ```typescript
  1386. import GitHub from 'next-auth/providers/github'
  1387. const baseUrl = process.env.VERCEL_URL
  1388. ? `https://${process.env.VERCEL_URL}`
  1389. : 'http://localhost:3000'
  1390. GitHub({
  1391. clientId: 'any-value',
  1392. clientSecret: 'any-value',
  1393. authorization: { url: `${baseUrl}/emulate/github/login/oauth/authorize` },
  1394. token: { url: `${baseUrl}/emulate/github/login/oauth/access_token` },
  1395. userinfo: { url: `${baseUrl}/emulate/github/user` },
  1396. })
  1397. ```
  1398. No `oauth_apps` need to be seeded. When none are configured, the emulator skips `client_id`, `client_secret`, and `redirect_uri` validation.
  1399. ### Font files in serverless
  1400. Emulator UI pages use bundled fonts. Wrap your Next.js config to include them in the serverless trace:
  1401. ```typescript
  1402. // next.config.mjs
  1403. import { withEmulate } from '@emulators/adapter-next'
  1404. export default withEmulate({
  1405. // your normal Next.js config
  1406. })
  1407. ```
  1408. If you mount the catch-all at a custom path, pass the matching prefix:
  1409. ```typescript
  1410. export default withEmulate(nextConfig, { routePrefix: '/api/emulate' })
  1411. ```
  1412. ### Persistence
  1413. By default, emulator state is in-memory and resets on every cold start. To persist state across restarts, pass a `persistence` adapter:
  1414. ```typescript
  1415. import { createEmulateHandler } from '@emulators/adapter-next'
  1416. import * as github from '@emulators/github'
  1417. const kvAdapter = {
  1418. async load() { return await kv.get('emulate-state') },
  1419. async save(data: string) { await kv.set('emulate-state', data) },
  1420. }
  1421. export const { GET, POST, PUT, PATCH, DELETE } = createEmulateHandler({
  1422. services: { github: { emulator: github } },
  1423. persistence: kvAdapter,
  1424. })
  1425. ```
  1426. For local development, `@emulators/core` ships `filePersistence`:
  1427. ```typescript
  1428. import { filePersistence } from '@emulators/core'
  1429. // ...
  1430. persistence: filePersistence('.emulate/state.json'),
  1431. ```
  1432. The persistence adapter loads on cold start and saves after mutations. Generated identities also require atomic create-or-read `initialize`; see `@emulators/core`.
  1433. ## Nuxt Integration
  1434. Embed emulators directly in your Nuxt app so they run on the same origin. This gives OAuth flows stable callback URLs in local and preview deployments.
  1435. ### Install
  1436. ```bash
  1437. npm install @emulators/adapter-nuxt @emulators/github @emulators/google
  1438. ```
  1439. Only install the emulators you need. Each `@emulators/*` package is published independently.
  1440. ### Server route
  1441. Create a named catch-all route that serves emulator traffic:
  1442. ```typescript
  1443. // server/routes/emulate/[...path].ts
  1444. import { createEmulateHandler } from '@emulators/adapter-nuxt'
  1445. import * as github from '@emulators/github'
  1446. import * as google from '@emulators/google'
  1447. export default defineEventHandler(createEmulateHandler({
  1448. services: {
  1449. github: {
  1450. emulator: github,
  1451. seed: {
  1452. users: [{ login: 'octocat', name: 'The Octocat' }],
  1453. repos: [{ owner: 'octocat', name: 'hello-world', auto_init: true }],
  1454. },
  1455. },
  1456. google: {
  1457. emulator: google,
  1458. seed: {
  1459. users: [{ email: 'test@example.com', name: 'Test User' }],
  1460. },
  1461. },
  1462. },
  1463. }))
  1464. ```
  1465. GitHub App seeds may omit `private_key`. Retain the handler to call server-only `generatedSecrets()`; explicit keys are excluded. Persisted snapshots contain generated keys, so keep the backend private.
  1466. ### Nuxt config
  1467. Emulator UI pages use bundled fonts. Wrap your Nuxt config so Nitro traces the core package assets into production builds:
  1468. ```typescript
  1469. // nuxt.config.ts
  1470. import { withEmulate } from '@emulators/adapter-nuxt'
  1471. export default defineNuxtConfig(withEmulate({
  1472. // your normal Nuxt config
  1473. }))
  1474. ```
  1475. ### OAuth configuration
  1476. Point your OAuth provider at the emulator paths on the same origin:
  1477. ```typescript
  1478. const baseUrl = process.env.NUXT_PUBLIC_SITE_URL ?? 'http://localhost:3000'
  1479. export const githubOAuth = {
  1480. clientId: 'any-value',
  1481. clientSecret: 'any-value',
  1482. authorizationUrl: `${baseUrl}/emulate/github/login/oauth/authorize`,
  1483. tokenUrl: `${baseUrl}/emulate/github/login/oauth/access_token`,
  1484. userInfoUrl: `${baseUrl}/emulate/github/user`,
  1485. }
  1486. ```
  1487. No `oauth_apps` need to be seeded. When none are configured, the emulator skips `client_id`, `client_secret`, and `redirect_uri` validation.
  1488. ### Persistence
  1489. By default, emulator state is in-memory and resets on every cold start. To persist state across restarts, pass a `persistence` adapter:
  1490. ```typescript
  1491. import { createEmulateHandler } from '@emulators/adapter-nuxt'
  1492. import * as github from '@emulators/github'
  1493. const storageAdapter = {
  1494. async load() { return await useStorage('emulate').getItem<string>('state') },
  1495. async save(data: string) { await useStorage('emulate').setItem('state', data) },
  1496. }
  1497. export default defineEventHandler(createEmulateHandler({
  1498. services: { github: { emulator: github } },
  1499. persistence: storageAdapter,
  1500. }))
  1501. ```
  1502. The persistence adapter loads on cold start and saves after mutations. Generated identities also require atomic create-or-read `initialize`; see `@emulators/core`.
  1503. ## Architecture
  1504. ```
  1505. packages/
  1506. emulate/ # CLI entry point (commander)
  1507. @emulators/
  1508. core/ # HTTP server, in-memory store, plugin interface, middleware
  1509. adapter-next/ # Next.js App Router integration
  1510. adapter-nuxt/ # Nuxt server route integration
  1511. vercel/ # Vercel API service
  1512. github/ # GitHub API service
  1513. google/ # Google OAuth 2.0 / OIDC + Gmail, Calendar, Drive
  1514. slack/ # Slack Web API, OAuth v2, incoming webhooks
  1515. linear/ # Linear GraphQL API, OAuth, webhooks
  1516. twilio/ # Twilio Messaging, Verify, Voice, webhooks
  1517. ai/ # OpenAI Responses, Chat Completions, and Anthropic Messages
  1518. apple/ # Apple Sign In / OIDC
  1519. microsoft/ # Microsoft Entra ID OAuth 2.0 / OIDC + Graph /me
  1520. aws/ # AWS S3, SQS, IAM, STS
  1521. apps/
  1522. web/ # Documentation site (Next.js)
  1523. ```
  1524. The core provides a generic `Store` with typed `Collection<T>` instances supporting CRUD, indexing, filtering, and pagination. Each service plugin registers its routes with the shared internal app and uses the store for state.
  1525. ## Acknowledgments
  1526. The internal HTTP layer builds on [Hono](https://hono.dev)'s API and design. Thank you to Yusuke Wada and the Hono contributors for their work. Hono's copyright and MIT license notice are included in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and distributed with the npm packages.
  1527. ## Auth
  1528. Tokens are configured in the seed config and map to users. Pass them as `Authorization: Bearer <token>` or `Authorization: token <token>`.
  1529. **Vercel**: All endpoints accept `teamId` or `slug` query params for team scoping. Pagination uses cursor-based `limit`/`since`/`until` with `pagination` response objects.
  1530. **GitHub**: Public repo endpoints work without auth. Private repos and write operations require a valid token. A private repository the caller cannot see returns `404 Not Found`, as on GitHub. Set `github.strict_scopes: true` in seed config to reject tokens the emulator did not issue: a token that does not come from seed config, server options, an OAuth exchange, or an installation token request returns `401 Bad credentials` instead of acting as the default user. Pagination uses `page`/`per_page` with `Link` headers.
  1531. **Google**: Standard OAuth 2.0 authorization code flow with RS256-signed OIDC ID tokens. The discovery document advertises RS256 and `/oauth2/v3/certs` returns the RSA public key used to verify issued tokens. Configure clients in the seed config.
  1532. **Slack**: All Web API endpoints require `Authorization: Bearer <token>`. Seeded OAuth apps create local installation records, and OAuth v2 flow with user picker UI creates scoped bot tokens. Optional strict scope mode returns `missing_scope` when a token lacks a required method scope.
  1533. **Linear**: GraphQL accepts `Authorization: Bearer <token>` or a bare personal API key value. Seeded Linear tokens map to users or app actors, OAuth apps support local authorization code and client credentials flows, and optional strict scope mode checks supported GraphQL operations.
  1534. **Twilio**: HTTP Basic auth accepts the seeded Account SID/Auth Token pair or API Key/API Secret pair. Product-host APIs are exposed under local prefixes such as `/messaging/v1` and `/verify/v2`; the 2010 API lives at `/2010-04-01`.
  1535. **AI**: OpenAI-compatible clients accept any API key, or none. Keys are never required, stored, or logged. Control routes and the inspector are same-origin only. Data routes refuse browser pages from other websites.
  1536. **Apple**: OIDC authorization code flow with RS256 ID tokens. On first auth per user/client pair, a `user` JSON blob is included.
  1537. **Microsoft**: OIDC authorization code flow with PKCE support. Also supports client credentials grants. Microsoft Graph `/v1.0/me` available.
  1538. **AWS**: Bearer tokens or IAM access key credentials. Default key pair always seeded: `AKIAIOSFODNN7EXAMPLE` / `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.