{"_id":"express-idempotency-middleware","_rev":"5-7648d200440da7c060ae3f8cdf609048","name":"express-idempotency-middleware","dist-tags":{"latest":"3.0.0"},"versions":{"1.0.0":{"name":"express-idempotency-middleware","version":"1.0.0","keywords":["express","middleware","idempotency","idempotent","api","webhooks","payments"],"author":{"name":"Yevhen Mykhailenko"},"license":"MIT","_id":"express-idempotency-middleware@1.0.0","maintainers":[{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"}],"homepage":"https://github.com/YevhenMykhailenko/idempotency-express#readme","bugs":{"url":"https://github.com/YevhenMykhailenko/idempotency-express/issues"},"dist":{"shasum":"fbafaca9fb84cc2f92c68364feddae1863e7310c","tarball":"https://registry.npmjs.org/express-idempotency-middleware/-/express-idempotency-middleware-1.0.0.tgz","fileCount":59,"integrity":"sha512-zzSMq13T2cz7RPrn0y2WUtgAJETrX+qL3oqGb4puSBsPQW4Sa0AVDqy39P+Bq3yBnUmGCm04EtWy5l89GVo8dw==","signatures":[{"sig":"MEYCIQDckdJXQpzGdP0rHsU5rQFGNiXRMXU1+rw0Llb/Cah5ywIhAITXkhu4TZMUqe4tTzKwJm+/bac8LXr9Oqane1KPWNJH","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":88824},"main":"./dist/src/index.js","type":"module","types":"./dist/src/index.d.ts","module":"./dist/src/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/src/index.d.ts","default":"./dist/src/index.js"}},"scripts":{"lint":"eslint .","test":"vitest run","build":"tsc -p tsconfig.json","prepublishOnly":"npm run build && npm test"},"_npmUser":{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"},"repository":{"url":"git+https://github.com/YevhenMykhailenko/idempotency-express.git","type":"git"},"_npmVersion":"10.9.2","description":"Express middleware for idempotent POSTs via Idempotency-Key with in-flight control and pluggable stores.","directories":{},"_nodeVersion":"22.13.0","_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.0.0","vitest":"^2.0.0","prettier":"^3.0.0","supertest":"^7.0.0","typescript":"^5.6.0","@types/node":"^20.0.0","@types/express":"^4.17.21","eslint-config-prettier":"^9.0.0","@typescript-eslint/parser":"^7.0.0","@typescript-eslint/eslint-plugin":"^7.0.0"},"peerDependencies":{"express":"^4.18.0 || ^5.0.0"},"_npmOperationalInternal":{"tmp":"tmp/express-idempotency-middleware_1.0.0_1759541856406_0.48662176657032963","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"express-idempotency-middleware","version":"1.0.1","keywords":["express","middleware","idempotency","idempotent","api","webhooks","payments"],"author":{"name":"Yevhen Mykhailenko"},"license":"MIT","_id":"express-idempotency-middleware@1.0.1","maintainers":[{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"}],"homepage":"https://github.com/YevhenMykhailenko/idempotency-express#readme","bugs":{"url":"https://github.com/YevhenMykhailenko/idempotency-express/issues"},"dist":{"shasum":"a41560c1583544a69074c86dd70fb4d9b4e90308","tarball":"https://registry.npmjs.org/express-idempotency-middleware/-/express-idempotency-middleware-1.0.1.tgz","fileCount":59,"integrity":"sha512-TxvoLA+vrO2kdDL5/b3J+97yOTuXT6Iif1AvILDAh4S+rogsVnFdvzwpVAlm0yZNcOSLXH2v3GQM4bWidvsAfQ==","signatures":[{"sig":"MEYCIQC9jt/maaxHr5/vY4hcHEQsPz1MfgGhlTiQBJH4Aox9ewIhAIBwzznizKaAVp9PvuGNPNJbQxJYsOvdH2kBZ7KnM1wq","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":88585},"main":"./dist/src/index.js","type":"module","types":"./dist/src/index.d.ts","module":"./dist/src/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/src/index.d.ts","default":"./dist/src/index.js"}},"gitHead":"f66e440e6a87de8b28308adadb64c0dcc210e82d","scripts":{"lint":"eslint .","test":"vitest run","build":"tsc -p tsconfig.json","prepublishOnly":"npm run build && npm test"},"_npmUser":{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"},"repository":{"url":"git+https://github.com/YevhenMykhailenko/idempotency-express.git","type":"git"},"_npmVersion":"10.9.2","description":"Express middleware for idempotent POSTs via Idempotency-Key with in-flight control and pluggable stores.","directories":{},"_nodeVersion":"22.13.0","_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.0.0","vitest":"^2.0.0","prettier":"^3.0.0","supertest":"^7.0.0","typescript":"^5.6.0","@types/node":"^20.0.0","@types/express":"^4.17.21","eslint-config-prettier":"^9.0.0","@typescript-eslint/parser":"^7.0.0","@typescript-eslint/eslint-plugin":"^7.0.0"},"peerDependencies":{"express":"^4.18.0 || ^5.0.0"},"_npmOperationalInternal":{"tmp":"tmp/express-idempotency-middleware_1.0.1_1759542463906_0.4753413002126192","host":"s3://npm-registry-packages-npm-production"}},"1.0.2":{"name":"express-idempotency-middleware","version":"1.0.2","keywords":["express","middleware","idempotency","idempotent","api","webhooks","payments"],"author":{"name":"Yevhen Mykhailenko"},"license":"MIT","_id":"express-idempotency-middleware@1.0.2","maintainers":[{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"}],"homepage":"https://github.com/YevhenMykhailenko/idempotency-express#readme","bugs":{"url":"https://github.com/YevhenMykhailenko/idempotency-express/issues"},"dist":{"shasum":"856b1941749909e69fcb4f036f502c0d2ae09d32","tarball":"https://registry.npmjs.org/express-idempotency-middleware/-/express-idempotency-middleware-1.0.2.tgz","fileCount":59,"integrity":"sha512-4p+326Zv5ZejBFYgw9OXI7WTqx2NrkWOY8DQdpF3dDvBae0leO/LKMG+gpeYUS9kGKDvUm807n7PQUOkJRVjKg==","signatures":[{"sig":"MEUCIECMuDFDEellZEYKbU9sXyZqsBbEfdSfDcj+2VgoMk93AiEAjEFT8D5DjMWk8oKEqNK5feWfzaLRGis2F/7lPsRFjSo=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":88581},"main":"./dist/src/index.js","type":"module","types":"./dist/src/index.d.ts","module":"./dist/src/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/src/index.d.ts","default":"./dist/src/index.js"}},"gitHead":"5b8b777255e5bfbb58255a9a2268900c6ba25649","scripts":{"lint":"eslint .","test":"vitest run","build":"tsc -p tsconfig.json","prepublishOnly":"npm run build && npm test"},"_npmUser":{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"},"repository":{"url":"git+https://github.com/YevhenMykhailenko/idempotency-express.git","type":"git"},"_npmVersion":"11.6.2","description":"Express middleware for idempotent POSTs via Idempotency-Key with in-flight control and pluggable stores.","directories":{},"_nodeVersion":"22.13.0","_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.0.0","vitest":"^2.0.0","prettier":"^3.0.0","supertest":"^7.0.0","typescript":"^5.6.0","@types/node":"^20.0.0","@types/express":"^4.17.21","eslint-config-prettier":"^9.0.0","@typescript-eslint/parser":"^7.0.0","@typescript-eslint/eslint-plugin":"^7.0.0"},"peerDependencies":{"express":"^4.18.0 || ^5.0.0"},"_npmOperationalInternal":{"tmp":"tmp/express-idempotency-middleware_1.0.2_1767500513603_0.4093885598710263","host":"s3://npm-registry-packages-npm-production"}},"2.0.0":{"name":"express-idempotency-middleware","version":"2.0.0","keywords":["express","middleware","idempotency","idempotent","api","webhooks","payments"],"author":{"name":"Yevhen Mykhailenko"},"license":"MIT","_id":"express-idempotency-middleware@2.0.0","maintainers":[{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"}],"homepage":"https://github.com/YevhenMykhailenko/idempotency-express#readme","bugs":{"url":"https://github.com/YevhenMykhailenko/idempotency-express/issues"},"dist":{"shasum":"4ef4353951f43c9f9f4bd3df9ef769d2848645e5","tarball":"https://registry.npmjs.org/express-idempotency-middleware/-/express-idempotency-middleware-2.0.0.tgz","fileCount":31,"integrity":"sha512-3ZfAZpvcubFSo9UgVpf4EpqoSkdx65VJqguwhsBsv3JjQbjQoZL9KlbQllfBiLE7EEc/4U0m82YUxRb92e//dw==","signatures":[{"sig":"MEQCIGiOiEKWbmaZA4SOkgvtvme3Udsbn9hWCaAowWFZcstEAiBw8bodVpaUGuPEzsEjgoiqj9zOMMhGci5ZjLQHuCTxOQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"sig":"MEUCIFxdsGtJWIz5VOgMNQ0pJSWsUJg13IWyXnrD/Rd3b1iSAiEA/CeG1wMCUxgYYi7CleA91HZQ6tFHlS0ZqVItsjRQ90Q=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":63787},"main":"./dist/src/index.js","type":"module","types":"./dist/src/index.d.ts","module":"./dist/src/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/src/index.d.ts","default":"./dist/src/index.js"}},"gitHead":"e8f5cda91860b67c20134ee5fb932fd16d22ed61","scripts":{"lint":"eslint .","test":"vitest run","build":"tsc -p tsconfig.build.json","typecheck":"tsc -p tsconfig.json --noEmit","prepublishOnly":"npm run build && npm run typecheck && npm test && npm run lint"},"_npmUser":{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"},"repository":{"url":"git+https://github.com/YevhenMykhailenko/idempotency-express.git","type":"git"},"_npmVersion":"11.6.2","description":"Express middleware for idempotent POSTs via Idempotency-Key with in-flight control and pluggable stores.","directories":{},"_nodeVersion":"22.13.0","_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.36.0","vitest":"^5.0.3","express":"^4.22.3","globals":"^17.13.0","supertest":"^7.0.0","typescript":"^5.6.0","@types/node":"^22.0.0","@types/express":"^4.17.23","@types/supertest":"^6.0.3","eslint-plugin-import":"^2.32.0","@typescript-eslint/parser":"^8.71.1","@typescript-eslint/eslint-plugin":"^8.71.1"},"peerDependencies":{"express":"^4.22.3 || ^5.1.0"},"_npmOperationalInternal":{"tmp":"tmp/express-idempotency-middleware_2.0.0_1791558919253_0.5915341365624502","host":"s3://npm-registry-packages-npm-production"}},"3.0.0":{"_id":"express-idempotency-middleware@3.0.0","bugs":{"url":"https://github.com/YevhenMykhailenko/idempotency-express/issues"},"dist":{"shasum":"5233ef246ccdee26a705f2b80abacf1aec1412aa","tarball":"https://registry.npmjs.org/express-idempotency-middleware/-/express-idempotency-middleware-3.0.0.tgz","fileCount":93,"integrity":"sha512-2TITLhVzH6uC9sIGWWGxDkyylgoE0wsDaLypQN2isgZRBBqWNu5YKN3o17pBLwPLRzCWpGiQAEOK4KGYCuWwEQ==","signatures":[{"sig":"MEYCIQCNeLb4QQZ6nbeFQwmoUy3o/ELmUMYDTsi4subg3vS3YAIhAOPJ1uQBQzO3ofToExvKVeVNPlZHQm9iTZAbsqBhBDKH","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIEpcytNg3JCUM6YiI7g6ZStncntV/rGltqHcCsWwyHxsAiA3f40/DSREqVgxmaws8WorX1VrpJc8BcbUdAwST3ff6Q=="}],"unpackedSize":207556},"main":"./dist/src/index.js","name":"express-idempotency-middleware","type":"module","_from":"file:.opencode/releases/3.0.0/09f65a9/express-idempotency-middleware-3.0.0.tgz","types":"./dist/src/index.d.ts","author":{"name":"Yevhen Mykhailenko"},"module":"./dist/src/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/src/index.d.ts","default":"./dist/src/index.js"},"./redis":{"types":"./dist/src/redis.d.ts","default":"./dist/src/redis.js"}},"license":"MIT","scripts":{"lint":"eslint .","test":"vitest run","build":"tsc -p tsconfig.build.json","test:docs":"node scripts/check-docs.mjs","typecheck":"tsc -p tsconfig.json --noEmit","test:redis":"npm run build && vitest run --config vitest.redis.config.ts","test:express":"node scripts/check-express.mjs","test:package":"npm run build && node scripts/check-package.mjs","prepublishOnly":"npm run build && npm run typecheck && npm test && npm run test:redis && npm run test:package && npm run test:docs && npm run lint && npm audit"},"version":"3.0.0","_npmUser":{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"},"homepage":"https://github.com/YevhenMykhailenko/idempotency-express#readme","keywords":["express","middleware","idempotency","idempotent","api","webhooks","payments"],"_resolved":"/Users/yevhen/Projects/idempotency-express/.opencode/releases/3.0.0/09f65a9/express-idempotency-middleware-3.0.0.tgz","_integrity":"sha512-2TITLhVzH6uC9sIGWWGxDkyylgoE0wsDaLypQN2isgZRBBqWNu5YKN3o17pBLwPLRzCWpGiQAEOK4KGYCuWwEQ==","repository":{"url":"git+https://github.com/YevhenMykhailenko/idempotency-express.git","type":"git"},"_npmVersion":"11.6.2","description":"Express middleware for idempotent POSTs via Idempotency-Key with in-flight control and pluggable stores.","directories":{},"maintainers":[{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"}],"_nodeVersion":"22.13.0","_hasShrinkwrap":false,"devDependencies":{"redis":"^5.12.2","eslint":"^9.36.0","vitest":"^5.0.3","express":"^4.22.3","globals":"^17.13.0","supertest":"^7.0.0","@eslint/js":"9.36.0","typescript":"^5.6.0","@types/node":"^22.0.0","compression":"^1.8.2","@types/express":"^4.17.23","@types/supertest":"^6.0.3","@types/compression":"^1.8.1","eslint-plugin-import":"^2.32.0","eslint-config-prettier":"10.1.8","@stylistic/eslint-plugin":"5.10.0","@typescript-eslint/parser":"^8.73.0","@typescript-eslint/eslint-plugin":"^8.73.0"},"peerDependencies":{"express":"^4.22.3 || ^5.1.0"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/express-idempotency-middleware_3.0.0_1795554848442_0.607536095049029"}}},"time":{"created":"2025-10-04T01:37:36.405Z","modified":"2026-11-24T21:14:08.703Z","1.0.0":"2025-10-04T01:37:36.599Z","1.0.1":"2025-10-04T01:47:44.106Z","1.0.2":"2026-01-04T04:21:53.754Z","2.0.0":"2026-10-09T15:15:19.350Z","3.0.0":"2026-11-24T21:14:08.547Z"},"bugs":{"url":"https://github.com/YevhenMykhailenko/idempotency-express/issues"},"author":{"name":"Yevhen Mykhailenko"},"license":"MIT","homepage":"https://github.com/YevhenMykhailenko/idempotency-express#readme","keywords":["express","middleware","idempotency","idempotent","api","webhooks","payments"],"repository":{"url":"git+https://github.com/YevhenMykhailenko/idempotency-express.git","type":"git"},"description":"Express middleware for idempotent POSTs via Idempotency-Key with in-flight control and pluggable stores.","maintainers":[{"name":"yevhen_mykhailenko","email":"yvn.mykh@gmail.com"}],"readme":"# express-idempotency-middleware\n\n[![npm version](https://img.shields.io/npm/v/express-idempotency-middleware.svg)](https://www.npmjs.com/package/express-idempotency-middleware)\n\n> **3.0 — breaking changes from 2.x.** This README describes the v3 API: an explicit namespace and scope, Store protocol v3, and retained completed 4xx/5xx responses. Existing 2.x applications must follow the [migration runbook](docs/migration.md); a new key prefix alone is not a safe cutover.\n\nExpress middleware for coordinating repeated HTTP requests (mainly `POST`) using a scoped `Idempotency-Key`.\nOne request claims the key; identical retries return the stored HTTP result within its TTL, while conflicting payloads get `409`. Buffered responses are sent only after the Store acknowledges commit, including completed 4xx/5xx responses.\n\n**This is not exactly-once execution of external business operations.** A payment and the stored HTTP result are not one transaction. Process crashes, TTL expiry, or lost Store data can leave the result unknown or permit another execution. Use downstream idempotency, business uniqueness, and reconciliation for critical effects.\n\n---\n\n## Highlights\n\n- **Drop-in** per-route middleware\n- **TypeScript-first**, ESM-only, Node ≥ 18\n- Explicit application **namespace** and authenticated user/tenant **scope**\n- Store protocol v3 with mandatory ownership tokens; bounded MemoryStore for dev/tests and a separate Redis adapter\n- **In-flight control**: `wait` (with timeout) or `reject`\n- **Safe headers at rest and replay** with a whitelist and hard denylist\n- **Stable fingerprint**: method + path + normalized body + optional extra inputs\n- **No partial fingerprints**: oversized bodies are rejected instead of being hashed only in part\n- Designed for payments, orders, webhooks, and similar at-least-once scenarios\n\nGuides: [guarantees and reconciliation](docs/guarantees.md) · [authenticated/webhook/multi-instance recipes](docs/recipes.md) · [Redis operations](docs/redis.md) · [2.x migration](docs/migration.md) · [security reporting](SECURITY.md) · [changelog](CHANGELOG.md).\n\n---\n\n## Install\n\nThe examples below use version 3.0:\n\n```bash\nnpm i express-idempotency-middleware@3.0.0\n# peer\nnpm i express\n```\n\nIf 3.0.0 is not yet available in your registry, test a local checkout instead. With development Node 22.12+, run `npm ci`, `npm run build`, and `npm pack` in this repository; then install `/absolute/path/to/express-idempotency-middleware-3.0.0.tgz` in a separate consumer. Packing does not publish the package. An unqualified install follows the registry's `latest` tag, so confirm the installed major before using these examples.\n\n> **ESM-only:** your project should use `\"type\": \"module\"` or native ESM (Node 18+).\n\nNode 18+ compatibility is retained by explicit project decision. **Node 18 and 20 are upstream EOL**; prefer a maintained Node release for production. Library compatibility does not supply missing Node security updates or override a driver's own requirements.\n\n---\n\n## Quick Start\n\n```ts\nimport express from \"express\";\nimport { idempotencyMiddleware, MemoryStore } from \"express-idempotency-middleware\";\n\nconst app = express();\napp.use(express.json());\n\nconst store = new MemoryStore();\n\napp.post(\n  \"/payments\",\n  idempotencyMiddleware({\n    store,\n    namespace: \"payments-demo\",\n    scope: \"public-demo\", // Public demo only. Private APIs require an authenticated identity scope.\n    ttlMs: 24 * 60 * 60 * 1000,\n    inFlight: { strategy: \"wait\", waitTimeoutMs: 3000, pollMs: 100 },\n    replay: { headerWhitelist: [\"location\"] }\n  }),\n  async (req, res) => {\n    // Real payments also need downstream idempotency and business reconciliation.\n    const orderId = \"ord_\" + Math.random().toString(36).slice(2);\n    res.setHeader(\"Location\", `/orders/${orderId}`);\n    res.status(201).json({ orderId });\n  }\n);\n\napp.listen(3000);\n```\n\n**Client header:**\n\n```\nIdempotency-Key: <uuid-v4>\n```\n\nKeys are 1–255 printable ASCII bytes excluding whitespace, commas, and double quotes; UUIDs are optional. Keys are required by default. Missing-key bypass requires explicit `requireKey: false` and has no deduplication guarantee.\n\nRun authentication, **authorization**, body parsing, signature verification, rate limiting, and ordinary validation **before** this middleware, including before a replay. For a private route, derive `scope(req)` from the already authenticated identity, not a raw bearer token or unverified tenant header. Use an unambiguous tuple encoding for tenant + user identity. `fingerprint.custom` is not a substitute for scope.\n\n---\n\n## Examples / Usage\n\nThe **basic Express server** under `examples/` is runnable. The repository also has a Redis connection factory, authenticated tenant/user and verified webhook recipes, and a two-instance Redis demo. See [recipes](docs/recipes.md) for setup and security boundaries. The Postgres file remains a nonfunctional sketch. Examples compile into `dist/examples/` for repository use; they are not shipped in the npm tarball.\n\n### Run the example (from this repo)\n\n```bash\nnpm i\nnpm run build\nnode dist/examples/server-basic.js\n# Server: http://localhost:3000\n```\n\n### 1) First request (create)\n\n```bash\ncurl -i -X POST http://localhost:3000/payments   -H \"Content-Type: application/json\"   -H \"Idempotency-Key: key-123\"   -d '{\"amount\":100}'\n```\n\n**Expected:**\n\n- `HTTP/1.1 201 Created`\n- `Idempotency-Status: created`\n- Body: `{\"orderId\":\"...\"}`\n\n### 2) Replay — same key & same payload\n\n```bash\ncurl -i -X POST http://localhost:3000/payments   -H \"Content-Type: application/json\"   -H \"Idempotency-Key: key-123\"   -d '{\"amount\":100}'\n```\n\n**Expected:**\n\n- `HTTP/1.1 201 Created` (same status as the first response)\n- `Idempotency-Status: cached`\n- `Idempotency-Replayed: true`\n- `Content-Type: application/json; charset=utf-8`\n- Body: **identical** to the first response (same `orderId`)\n\n### 3) Conflict — same key, different payload\n\n```bash\ncurl -i -X POST http://localhost:3000/payments   -H \"Content-Type: application/json\"   -H \"Idempotency-Key: key-123\"   -d '{\"amount\":200}'\n```\n\n**Expected:**\n\n- `HTTP/1.1 409 Conflict`\n- `Idempotency-Status: conflict`\n\n### 4) In-flight duplicates (concurrency)\n\nThe example route simulates ~300 ms of work and uses `inFlight: { strategy: \"wait\", waitTimeoutMs: 3000 }`.\nOpen two terminals and run the same request with the same key as fast as possible.\nThe second request will **wait** and return the cached result:\n\n- `Idempotency-Status: cached`\n- `Idempotency-Replayed: true`\n\n---\n\n## API\n\n```ts\nimport type { RequestHandler, Request } from \"express\";\nimport type { IdempotencyEvent, Store } from \"express-idempotency-middleware\";\n\nfunction idempotencyMiddleware(options: IdemOptions): RequestHandler;\n\ntype KeyOptions =\n  | { keyHeader?: string; getKey?: never }\n  | { getKey: (req: Request) => string | undefined; keyHeader?: never };\n\nexport type IdemOptions = KeyOptions & {\n  store: Store;\n  namespace: string;             // stable application identifier: [A-Za-z0-9._-], 1–128 chars\n  scope: string | ((req: Request) => string); // explicit stable identity; no fallback\n  ttlMs?: number;                // default 24h\n  methods?: string[];            // default [\"POST\"]\n  requireKey?: boolean;          // default true\n  storeTimeoutMs?: number;       // default 2000, applies to each begin/read/commit\n  maxResponseBytes?: number;     // default 256 KiB; range 0–1 MiB\n  inFlight?: {                   // default {strategy: \"reject\"}\n    strategy: \"wait\" | \"reject\";\n    waitTimeoutMs?: number;      // default 5000\n    pollMs?: number;             // default 100\n  };\n  fingerprint?: {\n    includeQuery?: boolean;      // default false\n    maxBodyBytes?: number;       // default 64KB; larger bodies return 413\n    custom?: (req: Request) => string | undefined; // additional result-affecting inputs\n  };\n  replay?: {\n    headerWhitelist?: string[];  // lowercase names, e.g., [\"location\"]\n  };\n  onEvent?: (event: IdempotencyEvent) => void | Promise<void>;\n};\n```\n\nThe default key header is `Idempotency-Key`. Duplicate raw headers are rejected. Custom `getKey` is synchronous, called once, and has no header fallback. For webhooks, verify the provider signature first, then extract the verified event ID.\n\n`scope` is synchronous, nonempty, at most 1024 UTF-8 bytes, and cannot contain control characters. Invalid scope fails closed. Physical keys are `idem:v3:` + SHA-256 of `JSON.stringify([namespace, scope, key])`; method/path stay in the fingerprint, so reusing one key on another endpoint conflicts.\n\n`maxBodyBytes` limits the complete canonical body, without truncation. JSON object keys are sorted; string values and array order are preserved. Buffers are hashed as bytes. Unsupported JavaScript objects/custom callback failures return `500 idempotency_fingerprint_failed` before claim. An unparsed nonempty body returns `400`; an oversized canonical body returns `413`. Keep the parser before this middleware. Fingerprint format 2 is unchanged.\n\n### Store Interface\n\n```ts\nexport type CachedResponse = {\n  status: number;\n  body: Buffer;\n  headers: Record<string, string | string[]>;\n  fingerprint: string;\n  createdAt: number;\n};\n\ntype Reservation = { reservationId: string; expiresAt: number };\ntype StoreEntry = Reservation & (\n  | { kind: \"inflight\"; fingerprint: string }\n  | { kind: \"completed\"; fingerprint: string; cached: CachedResponse }\n);\ntype CompletedEntry = Extract<StoreEntry, { kind: \"completed\" }>;\n\nexport interface Store {\n  readonly protocolVersion: 3;\n  begin(key: string, fingerprint: string, ttlMs: number): Promise<\n    | (Reservation & { kind: \"started\" })\n    | { kind: \"replay\"; entry: CompletedEntry }\n    | { kind: \"conflict\" }\n    | (Reservation & { kind: \"inflight\" })\n  >;\n  read(key: string): Promise<StoreEntry | null>;\n  commit(key: string, data: CachedResponse, reservationId: string): Promise<\n    | { kind: \"committed\" }\n    | { kind: \"already-committed\"; entry: CompletedEntry }\n    | { kind: \"reservation-lost\" }\n  >;\n}\n```\n\n`begin` atomically claims or reads the existing state. `commit` checks live ownership and fingerprint; it never creates a missing reservation. Repeated same-owner commits return the **first** canonical result without overwriting it. There is no `get`, `abort`, or `release` API. Custom stores must implement the full atomic contract, strict data validation, and detached snapshots; the version marker alone does not prove correctness.\n\nTTL starts at claim and is not extended by commit, polling, or replay. Choose it longer than the maximum handler duration plus commit budget. Expiry can allow another handler execution; ownership tokens protect Store records, not external effects. ACK is not a universal guarantee of durability after failover.\n\n`new MemoryStore({ maxEntries: 256 })` is the default bounded, single-process, volatile dev/test Store. A full Store rejects new claims with `503 idempotency_capacity_exceeded`, without evicting live records. Body hard limit is 1 MiB; filtered headers are limited to 16 KiB per record.\n\n---\n\n## Behavior & Headers\n\n- Adds response headers:\n  - `Idempotency-Key`: echoes the key\n  - `Idempotency-Status`: `created | cached | conflict | inflight | inflight-timeout | error`\n  - `Idempotency-Replayed`: `true | false`\n  - On in-flight timeout or reject: `Retry-After: 1`\n- **Replay headers**: only those in `replay.headerWhitelist` are replayed, plus `content-type` is always replayed.\n  Cookies/auth, `proxy-*`, hop-by-hop headers, Connection-nominated headers, content encoding/length, and `idempotency-*` headers are **never stored or replayed**, even if whitelisted. Body data is not redacted; sensitive bodies remain the application's responsibility.\n\n### Failures and buffered responses\n\nSupported: `res.json`, `res.send(string/Buffer)`, and one buffered `res.end` with string/Buffer/Uint8Array/empty body and standard encoding/callback overloads. Empty 204/205/304 results are replayed without synthetic body, Content-Type, or ETag. End/finish/callback happen after commit acknowledgement and transport completion; an end callback does not establish business success.\n\nStreaming/SSE, application `write`/`writeHead`/`flushHeaders`, sendFile/download, trailers, upgrade, and manually compressed bodies are unsupported. Guards reject them without caching partial bytes or releasing the reservation. Direct socket writes are outside the supported protocol. For standard `compression`, the verified order is **compression → idempotency → handler**; stored bytes are uncompressed and replay is negotiated again. Arbitrary response transforms are not covered.\n\nOwn errors are JSON `{ \"error\": { \"code\": \"idempotency_…\", \"message\": \"…\", \"outcome\": \"unknown\" } }`; `outcome` is present for uncertain results. Important cases:\n\n| Case | HTTP / error code |\n| --- | --- |\n| Missing / invalid key | 400 / `idempotency_key_required` / `idempotency_key_invalid` |\n| Scope / extractor callback failure | 500 / `idempotency_scope_invalid` / `idempotency_extractor_failed` |\n| Different fingerprint / outstanding operation / wait deadline | 409 / `idempotency_conflict` / `idempotency_inflight` / `idempotency_wait_timeout` |\n| Begin/read failure or timeout / malformed Store result | 503 / `idempotency_store_unavailable` / `idempotency_store_invalid` |\n| Commit failure/timeout/lost ownership | 503 / `idempotency_result_unknown` |\n| Oversized / unsupported response | 503 / `idempotency_response_too_large` / `idempotency_response_unsupported` |\n\nStore timeouts do not cancel backend work. Late commits may succeed, so a retry with the **same** key can replay the saved result. No failure, wait timeout, completed 5xx, or disconnect automatically releases the key. A disconnected owner's later supported response is still committed when possible. A waiter only reads its original reservation; it never claims a replacement after expiry.\n\n**Do not universally retry with a new key after an unknown result.** Reconcile the business outcome, particularly after retention expiry. A crash after an external effect but before commit cannot be resolved by this middleware alone.\n\n`onEvent` is optional, not awaited, and contains only low-cardinality diagnostics (`type`, optional operation/code/status/durationMs). It never includes raw keys, scope, tokens, fingerprints, bodies, headers, or backend errors. Throwing/rejected observers do not change HTTP/Store decisions. Do not put blocking work in a synchronous observer.\n\n### Breaking changes from 2.x\n\nNamespace/scope are required, keys are required by default, Store protocol v3 is incompatible with v2, `CachedResponse.body` is always Buffer, `Captured`/`setOn` are removed, and completed 5xx responses are now retained.\n\nThe new physical key prefix is **not a safe migration by itself**: a live v2 operation can appear absent in v3. Do not mix live v2/v3 writers, flush legacy keys, or replay legacy responses without verified identity ownership. Follow the [migration runbook](docs/migration.md): stop admission, drain old work, preserve legacy retention and reconcile uncertain business effects before a coordinated switch. Continuous migration requires a separate verified bridge. Policy-model tests do not establish that your production cutover has occurred.\n\n---\n\n## RedisStore\n\nThe separate `express-idempotency-middleware/redis` export does not import a Redis driver. Supply a connected client; the application owns connection/reconnect/shutdown policy. Verified locally with **Redis 7.4.5 standalone + node-redis 5.12.2**. Redis **7.0+** is required. Cluster/Sentinel and failover topologies have not been validated.\n\n```bash\nnpm i redis@5\n```\n\n```ts\nimport { createClient } from \"redis\";\nimport { RedisStore } from \"express-idempotency-middleware/redis\";\n\nconst client = createClient({\n  url: process.env.REDIS_URL,\n  disableOfflineQueue: true,\n});\nclient.on(\"error\", () => { console.error(\"Redis connection error\"); });\nawait client.connect();\nconst store = new RedisStore({ client });\n// Pass store to idempotencyMiddleware with your stable namespace and authorized scope.\n// At application shutdown, after draining requests: await client.close();\n```\n\nThe structural `RedisClient` port is `eval(script, { keys: string[], arguments: string[] }): Promise<unknown>`, with default string replies. Other clients need an explicit compatible wrapper and their own verification. The adapter never retries commands or manages the connection. Middleware deadlines do not cancel Redis work; configure finite client connection/queue budgets too. The example driver's own Node requirements apply independently of the library's runtime declaration.\n\n### Atomicity, storage, and operations\n\n- One physical scoped key and one Lua transition per operation; no process-local coordination. Redis `TIME` establishes expiry. Claim uses `SET PXAT`; owned commit uses `SET XX KEEPTTL`.\n- Wire version 1 stores metadata and a bounded JSON response with canonical base64 body (about 33% binary encoding overhead). Read/replay and repeated commits validate schema, bytes, ownership and fingerprint; snapshots are detached. Corrupt/incompatible live records or altered/missing TTL fail closed without repair, release or overwrite.\n- Use **`maxmemory-policy noeviction`**, adequate capacity, and a consistent authoritative Redis deployment. Evicting/deleting keys, restoring an older backup or losing acknowledged records breaks the deduplication assumption. Do not share these keys with processes that rewrite their values or TTL.\n- Protect Redis with appropriate authentication/ACL, network isolation and TLS where needed. The adapter uses `EVAL` and script commands `TIME`, `TYPE`, `STRLEN`, `GET`, `PEXPIRETIME`, `SET` on `idem:v3:*`. Allow the required commands/keys; Redis errors are not cache misses.\n- **An EVAL ACK is not disk/replica durability.** RDB can lose writes since the last snapshot; AOF `everysec` has a loss window; stronger fsync settings reduce some windows but do not make the business effect and Store atomic. Asynchronous replication/failover can lose acknowledged records. The adapter does not issue `WAIT`/`WAITAOF` or provide a failover durability SLA.\n- Test persistence and recovery for your deployment. The isolated restart test deliberately disables RDB/AOF and demonstrates a second effect after acknowledged Store data is lost. This is the published boundary, not an exactly-once guarantee.\n\nPostgreSQL remains deferred; `examples/postgres-store.ts` is a nonfunctional sketch, not an adapter or an atomic business-transaction integration.\n\n---\n\n## Best Practices\n\n- Generate the key **client-side** (UUID v4) per unsafe request\n- Include every input that affects the operation in the fingerprint. By default query parameters and request headers are excluded; use `includeQuery: true` and `custom` when they matter.\n- Use the shared Redis adapter with the same namespace/scope/fingerprint rules on every instance; verify persistence/failover assumptions for your deployment\n- Whitelist only **safe headers** to replay (e.g., `location`); `content-type` is always replayed\n- Set TTL to cover your retry window and maximum execution + commit duration; do not treat expiry as proof that no effect occurred\n- For webhooks, prefer provider event IDs (e.g., Stripe `event.id`) as the idempotency key\n\n---\n\n## Limitations\n\n- Not designed for streaming responses or long-running jobs\n  For multi-minute operations, prefer queues/outbox + status resources\n- MemoryStore is single-process only and volatile; losing its records loses deduplication\n- No atomic transaction with external effects; no exactly-once claim, even after Store ACK\n\n---\n\n## Troubleshooting\n\n- **`ERR_MODULE_NOT_FOUND` after build**\n  Ensure compiled imports include explicit `.js` extensions and your `package.json` `exports` point to `./dist/src/index.js`.\n\n- **Second request shows `created` instead of `cached`**\n  Check that both requests use the same store instance and the first response completed before the retry. A reservation that expires during a long handler can also allow a new execution; increase `ttlMs` or use a job/status workflow.\n\n- **`r2.body` is `{}` or a JSON string in tests**\n  Make sure `Content-Type: application/json` is set and that replay includes `content-type` (the middleware always replays it by default).\n\n---\n\n## Development (this repo)\n\nDevelopment tools require Node 22.12 or newer. Runtime declaration remains `>=18.0.0`. Locally verified on macOS:\n\n| Node | Express / matching types | Verification |\n| --- | --- | --- |\n| 22.13.0, 24.22.3 | 4.22.3 / @types/express 4.17.23; 5.3.0 / @types/express 5.0.6 | Full source, HTTP/native/Redis/recipe/fault suites, build/types and installed tarball |\n| 18.0.0 | Express 4.22.3 and 5.3.0 | Installed tarball HTTP/binary/204/500/gzip, no-driver imports, public types, Redis round-trip with node-redis 5.11.0 |\n| 18.20.8, 20.20.2 | Express 4.22.3 and 5.3.0 | Same installed-tarball checks with node-redis 5.12.2 |\n\nLegacy rows are runtime compatibility checks, not the Vitest development suite running on EOL Node. Types are compiled using the development runtime. Redis backend verification uses 7.4.5 standalone; other topologies/OS/runtime versions are not implied. CI is configured for Node 22/24 × Express 4/5 plus legacy installed-package jobs, but was not remotely executed during this local development stage.\n\n```bash\nnpm ci\nnpm run build\nnpm test\n# Example server (after build):\nnode dist/examples/server-basic.js\n```\n\n`npm test` runs the non-Redis suites. The separate integration command **requires** a reachable Redis, with no mock/skip fallback:\n\n```bash\nREDIS_URL=redis://127.0.0.1:6379 npm run test:redis\n```\n\nIt uses unique keys and deletes only its own test records, never `FLUSHDB`. To include the persistence-loss demonstration, Docker and a locally available `redis:7-alpine` image are required:\n\n```bash\nREDIS_URL=redis://127.0.0.1:6379 REDIS_RESTART_TEST=1 npm run test:redis\n```\n\nThat extra test restarts/removes only a disposable container it creates, not the supplied Redis service. CI enables it and runs real Redis tests on Node 22/24. `prepublishOnly` includes Redis, installed-package/docs checks and a blocking full `npm audit`; the local chain passed after the targeted development dependency remediation on 2026-11-19. Running the checks is not publication permission or proof that all release gates are complete. A clean development audit does not audit a consumer's Express peer, Store driver or application dependencies.\n\nAdditional checks:\n\n```bash\n# Actual pack/install outside this tree; checks imports with NO Redis driver first, paired public types,\n# HTTP bytes/callbacks/gzip, then installs a driver and checks its structural port + Redis round-trip.\nREDIS_URL=redis://127.0.0.1:6379 IDEM_REQUIRE_REDIS=1 npm run test:package\n# Alternate Express runtime AND matching types in an owned disposable sandbox; working lockfile unchanged:\nREDIS_URL=redis://127.0.0.1:6379 REDIS_RESTART_TEST=1 IDEM_MATRIX_FULL=1 npm run test:express\nnpm run test:docs\n```\n\n`test:express` defaults to Express 5; `IDEM_EXPRESS_MAJOR=4` selects 4. `IDEM_RUNTIME_NODE=/absolute/path/to/node` selects only the installed-package runtime while development tools stay on the host Node. For minimum Node 18.0.0 Redis checks use `IDEM_REDIS_CLIENT_VERSION=5.11.0`; the current 5.12.2 driver requires Node 18.19+. Package consumers and alternate dependencies live in temporary directories and are removed afterwards. `npm pack`/install is not publication. The dependency audit is an independent blocking CI gate, not suppressed by passing functional tests.\n\n---\n\n## License\n\nMIT\n","readmeFilename":"README.md"}