Repository navigation
Expand file tree
/
Copy pathidempotency.js
More file actions
2107 lines (1940 loc) · 77.8 KB
/
Copy pathidempotency.js
File metadata and controls
2107 lines (1940 loc) · 77.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module idempotency
* @description Atomic request idempotency lock, canonical payload SHA-256 fingerprinting,
* bounded LRU replay cache, async execution wrapper, and Express / Node HTTP middleware
* (`INV-LEGO-01`, `INV-LEGO-31`) for `@krusch/toolkit`.
*
* Security & correctness invariants enforced:
* 1. Non-throwing runtime boundaries on untrusted keys, headers, payloads, and hostile getters.
* 2. Deterministic canonical JSON SHA-256 fingerprinting over `{ method, path, body }` with
* cycle, nesting-depth, DAG-node, lone-surrogate, and non-JSON-type guards.
* 3. Constant-time (`crypto.timingSafeEqual`) fingerprint and `lockToken` comparisons.
* 4. Fencing tokens (`crypto.randomUUID()`) preventing timed-out handlers from committing or
* releasing locks owned by newer requests (`IDEMPOTENCY_LOCK_LOST`).
* 5. Deep-cloned cached bodies on both `commit` and `REPLAY` to prevent shared-reference mutation,
* and active `IN_FLIGHT` lock preservation under capacity pressure (`IDEMPOTENCY_STORE_FULL`).
*/
import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
import { okEnvelope, errorEnvelope } from './http.js';
/**
* Default configuration constants for `@krusch/toolkit/idempotency` (`INV-LEGO-31`).
*/
export const DEFAULT_IDEMPOTENCY_OPTIONS = Object.freeze({
ttlMs: 86_400_000,
maxEntries: 10_000,
inFlightTimeoutMs: 60_000,
maxKeyLength: 255,
headerName: 'idempotency-key',
});
const MAX_KEY_LENGTH_CEILING = 1024;
const MAX_DEPTH_CEILING = 512;
const MAX_CANONICAL_NODES = 100_000;
const MAX_CLONE_DEPTH = 64;
const MAX_CACHED_RESPONSE_BYTES = 2_097_152; // 2 MiB streaming capture ceiling
const ASCII_CONTROL_CHARS_RE = /[\x00-\x1f\x7f]/;
const HTTP_HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const FORBIDDEN_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const EXCLUDED_REPLAY_HEADERS = new Set([
'connection',
'content-length',
'date',
'idempotency-replayed',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'set-cookie',
'te',
'trailer',
'transfer-encoding',
'upgrade',
]);
/** @type {WeakMap<object, { maxKeyLength: number }>} */
const STORE_METADATA = new WeakMap();
/**
* Safely extract a non-empty `tool` identifier from an untrusted options bag without throwing.
*
* @param {unknown} options - Candidate options object
* @param {string} fallback - Default tool name
* @returns {string}
*/
function resolveSafeTool(options, fallback) {
try {
if (options && typeof options === 'object' && !Array.isArray(options)) {
const raw = /** @type {Record<string, unknown>} */ (options).tool;
if (typeof raw === 'string' && raw.trim().length > 0) {
return raw.trim();
}
}
} catch {
// Ignore hostile getters on options.tool
}
return fallback;
}
/**
* Detect lone UTF-16 high/low surrogates in a string.
*
* @param {string} value - Candidate string
* @returns {boolean}
*/
function hasLoneSurrogate(value) {
if (typeof value.isWellFormed === 'function') {
return !value.isWellFormed();
}
for (let i = 0; i < value.length; i += 1) {
const code = value.charCodeAt(i);
if (code >= 0xd800 && code <= 0xdbff) {
const next = value.charCodeAt(i + 1);
if (!(next >= 0xdc00 && next <= 0xdfff)) return true;
i += 1;
} else if (code >= 0xdc00 && code <= 0xdfff) {
return true;
}
}
return false;
}
/**
* Check whether an object is a raw byte view (`Buffer` or `Uint8Array`, excluding other `TypedArray`s).
*
* @param {unknown} value - Candidate value
* @returns {value is Uint8Array}
*/
function isByteView(value) {
if (!value || typeof value !== 'object') return false;
if (Buffer.isBuffer(value) || value instanceof Uint8Array) return true;
return (
ArrayBuffer.isView(value) &&
value.constructor !== undefined &&
value.constructor.name === 'Uint8Array'
);
}
/**
* Check whether an object has internal exotic/built-in slots or non-plain prototype.
*
* @param {object} value - Non-null object candidate
* @returns {boolean}
*/
function isPlainRecordObject(value) {
if (
Array.isArray(value) ||
value instanceof Date ||
value instanceof RegExp ||
value instanceof Map ||
value instanceof Set ||
value instanceof WeakMap ||
value instanceof WeakSet ||
value instanceof Promise ||
value instanceof Error ||
value instanceof ArrayBuffer ||
ArrayBuffer.isView(value)
) {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === null || proto === Object.prototype;
}
/**
* Compare two non-empty UTF-8 strings in constant time when byte lengths match.
*
* @param {unknown} a - First string
* @param {unknown} b - Second string
* @returns {boolean}
*/
function constantTimeStringEqual(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length === 0 || bufA.length !== bufB.length) {
return false;
}
return timingSafeEqual(bufA, bufB);
}
/**
* Validate and normalize an incoming `Idempotency-Key` string without throwing (`INV-LEGO-31`).
*
* @param {unknown} rawKey - Raw client idempotency key
* @param {object} [options={}] - Validation options
* @param {number} [options.maxKeyLength=255] - Maximum trimmed character length (`1..1024`)
* @param {string} [options.tool='idempotency.key'] - Originating tool identifier
* @returns {{ ok: true, tool: string, summary: string, data: { key: string } } | { ok: false, tool: string, summary: string, error: { code: string, message: string, details?: unknown } }}
*/
export function normalizeIdempotencyKey(rawKey, options = {}) {
const safeTool = resolveSafeTool(options, 'idempotency.key');
try {
if (options !== undefined && options !== null && (typeof options !== 'object' || Array.isArray(options))) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'Idempotency key options must be a plain object',
null,
safeTool
);
}
const opts = /** @type {Record<string, unknown>} */ (options || {});
const maxKeyLength =
opts.maxKeyLength === undefined
? DEFAULT_IDEMPOTENCY_OPTIONS.maxKeyLength
: opts.maxKeyLength;
if (
typeof maxKeyLength !== 'number' ||
!Number.isInteger(maxKeyLength) ||
maxKeyLength < 1 ||
maxKeyLength > MAX_KEY_LENGTH_CEILING
) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
`maxKeyLength must be an integer between 1 and ${MAX_KEY_LENGTH_CEILING}`,
{ maxKeyLength },
safeTool
);
}
if (typeof rawKey !== 'string') {
return errorEnvelope(
'IDEMPOTENCY_KEY_MISSING',
'Idempotency key must be a non-empty string',
null,
safeTool
);
}
const trimmed = rawKey.trim();
if (trimmed.length === 0) {
return errorEnvelope(
'IDEMPOTENCY_KEY_MISSING',
'Idempotency key cannot be empty or whitespace-only',
null,
safeTool
);
}
if (trimmed.length > maxKeyLength) {
return errorEnvelope(
'IDEMPOTENCY_KEY_TOO_LONG',
`Idempotency key exceeds maximum length of ${maxKeyLength} characters`,
{ length: trimmed.length, maxKeyLength },
safeTool
);
}
if (ASCII_CONTROL_CHARS_RE.test(rawKey) || hasLoneSurrogate(rawKey)) {
return errorEnvelope(
'IDEMPOTENCY_KEY_INVALID',
'Idempotency key must not contain ASCII control characters or lone UTF-16 surrogates',
null,
safeTool
);
}
return okEnvelope(safeTool, 'Idempotency key valid', { key: trimmed });
} catch (err) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
err instanceof Error ? err.message : 'Failed to validate idempotency key',
null,
safeTool
);
}
}
/**
* Recursively serialize a payload value into deterministic canonical JSON.
*
* @param {unknown} value - Current value node
* @param {number} depth - Current container nesting depth (`0` at root)
* @param {number} maxDepth - Maximum allowed container nesting depth
* @param {Set<object>} ancestors - Active ancestor chain for cycle detection
* @param {{ nodes: number }} state - Shared visited-node counter guarding against DAG blowups
* @returns {{ ok: true, json: string } | { ok: false, code: string, message: string, details?: Record<string, unknown> }}
*/
function serializeCanonicalValue(value, depth, maxDepth, ancestors, state) {
state.nodes += 1;
if (state.nodes > MAX_CANONICAL_NODES) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: `Payload exceeds maximum canonical node count of ${MAX_CANONICAL_NODES}`,
details: { maxNodes: MAX_CANONICAL_NODES },
};
}
if (value === null || value === undefined) {
return { ok: true, json: 'null' };
}
const valueType = typeof value;
if (valueType === 'boolean') {
return { ok: true, json: value ? 'true' : 'false' };
}
if (valueType === 'number') {
if (!Number.isFinite(value)) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: 'Payload must not contain NaN or Infinity',
};
}
const normalizedNum = value === 0 ? 0 : value;
return { ok: true, json: JSON.stringify(normalizedNum) };
}
if (valueType === 'string') {
const strVal = /** @type {string} */ (value);
if (hasLoneSurrogate(strVal)) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: 'Payload string contains lone UTF-16 surrogate',
};
}
return { ok: true, json: JSON.stringify(strVal) };
}
if (valueType === 'bigint' || valueType === 'symbol' || valueType === 'function') {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: `Unsupported non-JSON payload value type: ${valueType}`,
};
}
const obj = /** @type {object} */ (value);
if (isByteView(obj)) {
const b64 = Buffer.from(obj.buffer, obj.byteOffset, obj.byteLength).toString('base64');
return { ok: true, json: `{"$bytesBase64":${JSON.stringify(b64)}}` };
}
if (obj instanceof Date) {
const timeMs = obj.getTime();
if (!Number.isFinite(timeMs)) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: 'Payload contains an Invalid Date instance',
};
}
return { ok: true, json: `{"$date":${JSON.stringify(obj.toISOString())}}` };
}
if (ancestors.has(obj)) {
return {
ok: false,
code: 'IDEMPOTENCY_CIRCULAR_PAYLOAD',
message: 'Payload contains a circular reference',
};
}
if (Array.isArray(obj)) {
const nextDepth = depth + 1;
if (nextDepth > maxDepth) {
return {
ok: false,
code: 'IDEMPOTENCY_MAX_DEPTH',
message: `Payload exceeds maximum nesting depth of ${maxDepth}`,
details: { maxDepth },
};
}
ancestors.add(obj);
try {
const parts = [];
for (let i = 0; i < obj.length; i += 1) {
const elem = obj[i];
const childRes = serializeCanonicalValue(
elem === undefined ? null : elem,
nextDepth,
maxDepth,
ancestors,
state
);
if (!childRes.ok) return childRes;
parts.push(childRes.json);
}
return { ok: true, json: `[${parts.join(',')}]` };
} finally {
ancestors.delete(obj);
}
}
if (!isPlainRecordObject(obj)) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: 'Payload contains unsupported non-plain class instance',
};
}
if (Object.getOwnPropertySymbols(obj).length > 0) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: 'Payload object must not contain Symbol keys',
};
}
const nextDepth = depth + 1;
if (nextDepth > maxDepth) {
return {
ok: false,
code: 'IDEMPOTENCY_MAX_DEPTH',
message: `Payload exceeds maximum nesting depth of ${maxDepth}`,
details: { maxDepth },
};
}
ancestors.add(obj);
try {
const keys = Object.keys(obj).sort();
const rec = /** @type {Record<string, unknown>} */ (obj);
const parts = [];
for (let i = 0; i < keys.length; i += 1) {
const k = keys[i];
if (hasLoneSurrogate(k)) {
return {
ok: false,
code: 'IDEMPOTENCY_INVALID_PAYLOAD',
message: 'Payload object key contains lone UTF-16 surrogate',
};
}
const propVal = rec[k];
if (propVal === undefined) {
continue;
}
const childRes = serializeCanonicalValue(propVal, nextDepth, maxDepth, ancestors, state);
if (!childRes.ok) return childRes;
parts.push(`${JSON.stringify(k)}:${childRes.json}`);
}
return { ok: true, json: `{${parts.join(',')}}` };
} finally {
ancestors.delete(obj);
}
}
/**
* Compute a deterministic canonical SHA-256 hex digest over `{ method, path, body }` without throwing (`INV-LEGO-31`).
*
* @param {unknown} payload - Request body or operation payload
* @param {object} [options={}] - Fingerprinting options
* @param {string} [options.method=''] - HTTP verb or action method
* @param {string} [options.path=''] - Request route path
* @param {number} [options.maxDepth=32] - Maximum container nesting depth (`1..512`)
* @param {string} [options.tool='idempotency.fingerprint'] - Originating tool identifier
* @returns {{ ok: true, tool: string, summary: string, data: { fingerprint: string } } | { ok: false, tool: string, summary: string, error: { code: string, message: string, details?: unknown } }}
*/
export function computePayloadFingerprint(payload, options = {}) {
const safeTool = resolveSafeTool(options, 'idempotency.fingerprint');
try {
if (options !== undefined && options !== null && (typeof options !== 'object' || Array.isArray(options))) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'Fingerprint options must be a plain object',
null,
safeTool
);
}
const opts = /** @type {Record<string, unknown>} */ (options || {});
const rawMethod = opts.method === undefined || opts.method === null ? '' : opts.method;
const rawPath = opts.path === undefined || opts.path === null ? '' : opts.path;
const maxDepth = opts.maxDepth === undefined ? 32 : opts.maxDepth;
if (typeof rawMethod !== 'string' && typeof rawMethod !== 'number') {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'method option must be a string',
null,
safeTool
);
}
if (typeof rawPath !== 'string' && typeof rawPath !== 'number') {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'path option must be a string',
null,
safeTool
);
}
if (
typeof maxDepth !== 'number' ||
!Number.isInteger(maxDepth) ||
maxDepth < 1 ||
maxDepth > MAX_DEPTH_CEILING
) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
`maxDepth must be an integer between 1 and ${MAX_DEPTH_CEILING}`,
{ maxDepth },
safeTool
);
}
const normMethod = String(rawMethod).trim().toUpperCase();
const normPath = String(rawPath).trim();
if (hasLoneSurrogate(normMethod) || hasLoneSurrogate(normPath)) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_PAYLOAD',
'method or path contains lone UTF-16 surrogate',
null,
safeTool
);
}
const bodySerialized = serializeCanonicalValue(
payload === undefined ? null : payload,
0,
maxDepth,
new Set(),
{ nodes: 0 }
);
if (!bodySerialized.ok) {
return errorEnvelope(
bodySerialized.code,
bodySerialized.message,
bodySerialized.details ?? null,
safeTool
);
}
const envelopeParts = {
method: JSON.stringify(normMethod),
path: JSON.stringify(normPath),
body: bodySerialized.json,
};
const sortedEnvelopeEntries = Object.keys(envelopeParts)
.sort()
.map((k) => `${JSON.stringify(k)}:${envelopeParts[/** @type {keyof typeof envelopeParts} */ (k)]}`);
const canonicalEnvelope = `{${sortedEnvelopeEntries.join(',')}}`;
const fingerprint = createHash('sha256').update(canonicalEnvelope, 'utf8').digest('hex');
return okEnvelope(safeTool, 'Payload fingerprint computed', { fingerprint });
} catch (err) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_PAYLOAD',
err instanceof Error ? err.message : 'Failed to compute payload fingerprint',
null,
safeTool
);
}
}
/**
* Deep-clone a response body while rejecting circular references, excessive nesting,
* lone surrogates, and non-cloneable JS values (`BigInt`, `Symbol`, `Function`, `NaN`, `Infinity`).
*
* @param {unknown} value - Candidate response body
* @param {number} [depth=0] - Current nesting depth
* @param {Set<object>} [ancestors=new Set()] - Active ancestor set
* @param {{ nodes: number }} [state={ nodes: 0 }] - Shared node counter
* @returns {{ ok: true, value: any } | { ok: false, message: string }}
*/
function cloneBodyValue(value, depth = 0, ancestors = new Set(), state = { nodes: 0 }) {
state.nodes += 1;
if (state.nodes > MAX_CANONICAL_NODES) {
return {
ok: false,
message: `Response body exceeds maximum cloneable node count of ${MAX_CANONICAL_NODES}`,
};
}
if (value === null || value === undefined) {
return { ok: true, value: null };
}
const valueType = typeof value;
if (valueType === 'boolean') {
return { ok: true, value };
}
if (valueType === 'number') {
if (!Number.isFinite(value)) {
return { ok: false, message: 'Response body must not contain NaN or Infinity' };
}
return { ok: true, value: value === 0 ? 0 : value };
}
if (valueType === 'string') {
if (hasLoneSurrogate(/** @type {string} */ (value))) {
return { ok: false, message: 'Response body contains lone UTF-16 surrogate' };
}
return { ok: true, value };
}
if (valueType === 'bigint' || valueType === 'symbol' || valueType === 'function') {
return { ok: false, message: `Response body contains non-cloneable ${valueType} value` };
}
const obj = /** @type {object} */ (value);
if (Buffer.isBuffer(obj)) {
return { ok: true, value: Buffer.from(obj) };
}
if (isByteView(obj)) {
return { ok: true, value: new Uint8Array(obj.buffer.slice(obj.byteOffset, obj.byteOffset + obj.byteLength)) };
}
if (obj instanceof Date) {
const ms = obj.getTime();
if (!Number.isFinite(ms)) {
return { ok: false, message: 'Response body contains an Invalid Date instance' };
}
return { ok: true, value: new Date(ms) };
}
if (ancestors.has(obj)) {
return { ok: false, message: 'Response body contains a circular reference' };
}
if (depth + 1 > MAX_CLONE_DEPTH) {
return { ok: false, message: `Response body exceeds maximum nesting depth of ${MAX_CLONE_DEPTH}` };
}
if (Array.isArray(obj)) {
ancestors.add(obj);
try {
const out = new Array(obj.length);
for (let i = 0; i < obj.length; i += 1) {
const elem = obj[i];
const clonedElem = cloneBodyValue(
elem === undefined ? null : elem,
depth + 1,
ancestors,
state
);
if (!clonedElem.ok) return clonedElem;
out[i] = clonedElem.value;
}
return { ok: true, value: out };
} finally {
ancestors.delete(obj);
}
}
if (!isPlainRecordObject(obj) || Object.getOwnPropertySymbols(obj).length > 0) {
return { ok: false, message: 'Response body contains unsupported non-plain object or Symbol keys' };
}
ancestors.add(obj);
try {
/** @type {Record<string, unknown>} */
const out = {};
const rec = /** @type {Record<string, unknown>} */ (obj);
for (const k of Object.keys(rec)) {
if (hasLoneSurrogate(k)) {
return { ok: false, message: 'Response body object key contains lone UTF-16 surrogate' };
}
const propVal = rec[k];
if (propVal === undefined) {
continue;
}
const clonedProp = cloneBodyValue(propVal, depth + 1, ancestors, state);
if (!clonedProp.ok) return clonedProp;
if (k === '__proto__') {
Object.defineProperty(out, k, {
value: clonedProp.value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
out[k] = clonedProp.value;
}
}
return { ok: true, value: out };
} finally {
ancestors.delete(obj);
}
}
/**
* Sanitize response headers for safe storage and replay, stripping CR/LF/NUL characters
* and rejecting prototype-pollution keys.
*
* @param {unknown} rawHeaders - Candidate header map
* @returns {{ ok: true, headers: Record<string, string> } | { ok: false, message: string }}
*/
function sanitizeCachedHeaders(rawHeaders) {
if (rawHeaders === undefined || rawHeaders === null) {
return { ok: true, headers: {} };
}
if (typeof rawHeaders !== 'object' || Array.isArray(rawHeaders)) {
return { ok: false, message: 'headers must be a plain object' };
}
/** @type {Record<string, string>} */
const cleaned = {};
const rec = /** @type {Record<string, unknown>} */ (rawHeaders);
for (const rawKey of Object.keys(rec)) {
if (FORBIDDEN_OBJECT_KEYS.has(rawKey)) continue;
const val = rec[rawKey];
if (val === undefined || val === null) continue;
const cleanName = rawKey.replace(/[\r\n\x00]+/g, '').trim();
if (!cleanName || FORBIDDEN_OBJECT_KEYS.has(cleanName.toLowerCase())) continue;
if (!HTTP_HEADER_NAME_RE.test(cleanName)) continue;
const cleanVal = String(val).replace(/[\r\n\x00]+/g, '');
cleaned[cleanName] = cleanVal;
}
return { ok: true, headers: cleaned };
}
/**
* Create a bounded, prototype-safe, LRU idempotency lock and replay cache store (`INV-LEGO-31`).
*
* Throws `RangeError` only on invalid static developer configuration; all returned store
* operations (`begin`, `commit`, `release`, `get`, `delete`, `clear`, `size`) are non-throwing.
*
* @param {object} [options={}] - Store configuration
* @param {number} [options.ttlMs=86400000] - Replay retention TTL for `COMPLETED` entries (`>= 1`)
* @param {number} [options.maxEntries=10000] - Maximum entries before expired/LRU eviction (`>= 1`)
* @param {number} [options.inFlightTimeoutMs=60000] - Stale `IN_FLIGHT` lock timeout (`>= 1`)
* @param {number} [options.maxKeyLength=255] - Maximum allowed key length (`1..1024`)
* @param {() => number} [options.nowFn=Date.now] - Monotonic/epoch millisecond clock provider
*/
export function createIdempotencyStore(options = {}) {
if (options === null || typeof options !== 'object' || Array.isArray(options)) {
throw new RangeError('createIdempotencyStore options must be a plain object');
}
const {
ttlMs = DEFAULT_IDEMPOTENCY_OPTIONS.ttlMs,
maxEntries = DEFAULT_IDEMPOTENCY_OPTIONS.maxEntries,
inFlightTimeoutMs = DEFAULT_IDEMPOTENCY_OPTIONS.inFlightTimeoutMs,
maxKeyLength = DEFAULT_IDEMPOTENCY_OPTIONS.maxKeyLength,
nowFn = Date.now,
} = options;
if (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs < 1) {
throw new RangeError('ttlMs must be a finite positive number >= 1');
}
if (typeof maxEntries !== 'number' || !Number.isInteger(maxEntries) || maxEntries < 1) {
throw new RangeError('maxEntries must be an integer >= 1');
}
if (
typeof inFlightTimeoutMs !== 'number' ||
!Number.isFinite(inFlightTimeoutMs) ||
inFlightTimeoutMs < 1
) {
throw new RangeError('inFlightTimeoutMs must be a finite positive number >= 1');
}
if (
typeof maxKeyLength !== 'number' ||
!Number.isInteger(maxKeyLength) ||
maxKeyLength < 1 ||
maxKeyLength > MAX_KEY_LENGTH_CEILING
) {
throw new RangeError(`maxKeyLength must be an integer between 1 and ${MAX_KEY_LENGTH_CEILING}`);
}
if (typeof nowFn !== 'function') {
throw new RangeError('nowFn must be a function');
}
/** @type {Map<string, any>} */
const entries = new Map();
const safeNow = () => {
try {
const ts = nowFn();
return typeof ts === 'number' && Number.isFinite(ts) ? ts : Date.now();
} catch {
return Date.now();
}
};
const isExpired = (entry, now) => {
if (entry.state === 'IN_FLIGHT') {
return now - entry.startedAt >= inFlightTimeoutMs;
}
return now >= entry.expiresAt;
};
const sweepExpired = (now) => {
for (const [k, entry] of entries.entries()) {
if (isExpired(entry, now)) {
entries.delete(k);
}
}
};
const evictOldestCompleted = () => {
for (const [k, entry] of entries.entries()) {
if (entry.state === 'COMPLETED') {
entries.delete(k);
return true;
}
}
return false;
};
const begin = (key, fingerprint, beginOptions = {}) => {
const safeTool = resolveSafeTool(beginOptions, 'idempotency.store');
try {
if (
beginOptions !== undefined &&
beginOptions !== null &&
(typeof beginOptions !== 'object' || Array.isArray(beginOptions))
) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'begin options must be a plain object',
null,
safeTool
);
}
const keyRes = normalizeIdempotencyKey(key, { maxKeyLength, tool: safeTool });
if (!keyRes.ok) return keyRes;
const normalizedKey = keyRes.data.key;
if (
typeof fingerprint !== 'string' ||
fingerprint.trim().length === 0 ||
fingerprint.length > MAX_KEY_LENGTH_CEILING ||
ASCII_CONTROL_CHARS_RE.test(fingerprint) ||
hasLoneSurrogate(fingerprint)
) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_FINGERPRINT',
'Fingerprint must be a non-empty valid string',
null,
safeTool
);
}
const normFingerprint = fingerprint.trim();
const now = safeNow();
let existing = entries.get(normalizedKey);
if (existing && isExpired(existing, now)) {
entries.delete(normalizedKey);
existing = undefined;
}
if (existing) {
if (!constantTimeStringEqual(existing.fingerprint, normFingerprint)) {
return errorEnvelope(
'IDEMPOTENCY_PAYLOAD_MISMATCH',
'Idempotency key was already used with a different request payload',
{ key: normalizedKey, statusCode: 422 },
safeTool
);
}
if (existing.state === 'IN_FLIGHT') {
return errorEnvelope(
'IDEMPOTENCY_IN_FLIGHT',
'A request with this idempotency key is currently in flight',
{ key: normalizedKey, statusCode: 409 },
safeTool
);
}
// Refresh LRU order on COMPLETED replay hit
entries.delete(normalizedKey);
entries.set(normalizedKey, existing);
const clonedBody = cloneBodyValue(existing.body);
return okEnvelope(safeTool, 'Idempotency replay hit', {
outcome: 'REPLAY',
key: normalizedKey,
fingerprint: existing.fingerprint,
statusCode: existing.statusCode,
body: clonedBody.ok ? clonedBody.value : null,
headers: { ...existing.headers },
storedAt: existing.storedAt,
});
}
if (entries.size >= maxEntries) {
sweepExpired(now);
while (entries.size >= maxEntries) {
if (!evictOldestCompleted()) {
return errorEnvelope(
'IDEMPOTENCY_STORE_FULL',
'Idempotency store capacity exhausted by active in-flight locks',
{ maxEntries, statusCode: 503 },
safeTool
);
}
}
}
const lockToken = randomUUID();
entries.set(normalizedKey, {
state: 'IN_FLIGHT',
key: normalizedKey,
fingerprint: normFingerprint,
lockToken,
startedAt: now,
expiresAt: now + inFlightTimeoutMs,
});
return okEnvelope(safeTool, 'Idempotency lock acquired', {
outcome: 'ACQUIRED',
key: normalizedKey,
fingerprint: normFingerprint,
lockToken,
});
} catch (err) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
err instanceof Error ? err.message : 'Failed to begin idempotency transaction',
null,
safeTool
);
}
};
const commit = (key, lockToken, commitOptions = {}) => {
const safeTool = resolveSafeTool(commitOptions, 'idempotency.store');
try {
if (
commitOptions !== undefined &&
commitOptions !== null &&
(typeof commitOptions !== 'object' || Array.isArray(commitOptions))
) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'commit options must be a plain object',
null,
safeTool
);
}
const keyRes = normalizeIdempotencyKey(key, { maxKeyLength, tool: safeTool });
if (!keyRes.ok) return keyRes;
const normalizedKey = keyRes.data.key;
if (typeof lockToken !== 'string' || lockToken.trim().length === 0) {
return errorEnvelope(
'IDEMPOTENCY_LOCK_LOST',
'Idempotency lock token is missing or invalid',
{ key: normalizedKey },
safeTool
);
}
const now = safeNow();
const existing = entries.get(normalizedKey);
if (existing && isExpired(existing, now)) {
entries.delete(normalizedKey);
return errorEnvelope(
'IDEMPOTENCY_LOCK_LOST',
'Idempotency lock expired before commit',
{ key: normalizedKey },
safeTool
);
}
if (
!existing ||
existing.state !== 'IN_FLIGHT' ||
!constantTimeStringEqual(existing.lockToken, lockToken)
) {
return errorEnvelope(
'IDEMPOTENCY_LOCK_LOST',
'Idempotency lock is no longer owned by this token',
{ key: normalizedKey },
safeTool
);
}
const opts = /** @type {Record<string, unknown>} */ (commitOptions || {});
const statusCode = opts.statusCode === undefined ? 200 : opts.statusCode;
if (
typeof statusCode !== 'number' ||
!Number.isInteger(statusCode) ||
statusCode < 100 ||
statusCode > 599
) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
'statusCode must be an integer HTTP status code between 100 and 599',
{ statusCode },
safeTool
);
}
const headerRes = sanitizeCachedHeaders(opts.headers);
if (!headerRes.ok) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_OPTIONS',
headerRes.message,
null,
safeTool
);
}
const rawBody = opts.body === undefined ? null : opts.body;
const clonedBody = cloneBodyValue(rawBody);
if (!clonedBody.ok) {
return errorEnvelope(
'IDEMPOTENCY_INVALID_PAYLOAD',
clonedBody.message,
{ key: normalizedKey },
safeTool
);
}
const expiresAt = now + ttlMs;
const completedEntry = {
state: 'COMPLETED',
key: normalizedKey,
fingerprint: existing.fingerprint,
statusCode,
body: clonedBody.value,
headers: headerRes.headers,
storedAt: now,
expiresAt,
};
entries.delete(normalizedKey);
entries.set(normalizedKey, completedEntry);
return okEnvelope(safeTool, 'Idempotency response committed', {
key: normalizedKey,
fingerprint: existing.fingerprint,
statusCode,
storedAt: now,