@apifuse/provider-sdk 2.2.0-beta.59 → 2.2.0-beta.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/AUTHORING.md +16 -0
  2. package/CHANGELOG.md +4 -0
  3. package/bin/apifuse-dev.ts +2 -1
  4. package/bin/apifuse-perf.ts +41 -4
  5. package/bin/apifuse-record.ts +3 -2
  6. package/dist/config/loader.js +13 -12
  7. package/dist/engine.js +3 -2
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.js +1 -1
  10. package/dist/lint.js +36 -15
  11. package/dist/provider.d.ts +1 -1
  12. package/dist/provider.js +1 -1
  13. package/dist/runtime/browser.js +2 -1
  14. package/dist/runtime/cache.js +3 -2
  15. package/dist/runtime/diagnostic-env-values.d.ts +5 -0
  16. package/dist/runtime/diagnostic-env-values.js +57 -0
  17. package/dist/runtime/diagnostic-env.d.ts +11 -0
  18. package/dist/runtime/diagnostic-env.js +35 -0
  19. package/dist/runtime/diagnostic-redactor.d.ts +49 -0
  20. package/dist/runtime/diagnostic-redactor.js +569 -0
  21. package/dist/runtime/egress-lease.d.ts +2 -0
  22. package/dist/runtime/egress-lease.js +4 -1
  23. package/dist/runtime/env.js +2 -1
  24. package/dist/runtime/instrumentation.js +3 -0
  25. package/dist/runtime/ocr.js +2 -1
  26. package/dist/runtime/otlp.js +5 -4
  27. package/dist/runtime/proxy-nodemaven.js +3 -2
  28. package/dist/runtime/request-options.d.ts +7 -0
  29. package/dist/runtime/request-options.js +62 -22
  30. package/dist/runtime/resolver-vendors/browser.js +0 -1
  31. package/dist/runtime/resolver.js +3 -2
  32. package/dist/runtime/stt.js +3 -2
  33. package/dist/runtime/trace.d.ts +5 -0
  34. package/dist/runtime/trace.js +115 -20
  35. package/dist/schema.d.ts +11 -0
  36. package/dist/schema.js +56 -2
  37. package/dist/server/self-test-redaction.js +8 -33
  38. package/dist/server/sensitive-values.d.ts +26 -0
  39. package/dist/server/sensitive-values.js +131 -0
  40. package/dist/server/serve-implementation.js +219 -78
  41. package/dist/server/trace-output.d.ts +2 -1
  42. package/dist/server/trace-output.js +46 -14
  43. package/dist/trace-sanitization.d.ts +4 -3
  44. package/dist/trace-sanitization.js +45 -22
  45. package/package.json +2 -1
  46. package/src/config/loader.ts +13 -12
  47. package/src/engine.ts +3 -2
  48. package/src/index.ts +2 -0
  49. package/src/lint.ts +42 -16
  50. package/src/provider.ts +1 -0
  51. package/src/runtime/browser.ts +2 -1
  52. package/src/runtime/cache.ts +3 -2
  53. package/src/runtime/diagnostic-env-values.ts +56 -0
  54. package/src/runtime/diagnostic-env.ts +55 -0
  55. package/src/runtime/diagnostic-redactor.ts +662 -0
  56. package/src/runtime/egress-lease.ts +6 -1
  57. package/src/runtime/env.ts +2 -1
  58. package/src/runtime/instrumentation.ts +3 -0
  59. package/src/runtime/ocr.ts +2 -1
  60. package/src/runtime/otlp.ts +5 -4
  61. package/src/runtime/proxy-nodemaven.ts +3 -2
  62. package/src/runtime/request-options.ts +76 -28
  63. package/src/runtime/resolver-vendors/browser.ts +0 -1
  64. package/src/runtime/resolver.ts +3 -2
  65. package/src/runtime/stt.ts +3 -2
  66. package/src/runtime/trace.ts +168 -26
  67. package/src/schema.ts +63 -2
  68. package/src/server/self-test-redaction.ts +10 -40
  69. package/src/server/sensitive-values.ts +200 -0
  70. package/src/server/serve-implementation.ts +301 -96
  71. package/src/server/trace-output.ts +77 -17
  72. package/src/trace-sanitization.ts +70 -23
@@ -0,0 +1,662 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ import {
4
+ allSensitiveValueVariants,
5
+ normalizePercentEscapes,
6
+ REDACTED_QUERY_VALUE,
7
+ type SensitiveValueVariant,
8
+ } from "./request-options.js";
9
+
10
+ export type DiagnosticRedactor = (text: string) => string;
11
+ export const REDACTION_FAILED = "[REDACTION_FAILED]";
12
+ // No supported credential source needs 1–3 character secrets. Registering these
13
+ // common tokens damages unrelated IDs and diagnostics even with token boundaries.
14
+ // Apply the same floor to static, fallback and request inventories (as self-test does).
15
+ const MINIMUM_REGISTERED_VALUE_LENGTH = 4;
16
+
17
+ /** Observer failures must never return the original diagnostic, including via ?? fallbacks. */
18
+ export function redactDiagnosticText(text: string, redact?: DiagnosticRedactor): string {
19
+ try {
20
+ const result = redact ? redact(text) : text;
21
+ return typeof result === "string" ? result : REDACTION_FAILED;
22
+ } catch {
23
+ return REDACTION_FAILED;
24
+ }
25
+ }
26
+
27
+ export interface DiagnosticSensitiveRegistry {
28
+ redact: DiagnosticRedactor;
29
+ readonly redactCritical: DiagnosticRedactor;
30
+ readonly redactStructured: DiagnosticRedactor;
31
+ readonly suppressed: boolean;
32
+ has(value: string): boolean;
33
+ add(values: readonly string[]): void;
34
+ suppress(): void;
35
+ }
36
+
37
+ type Node = { next: Map<string, Node>; boundary?: boolean };
38
+ type Matcher = {
39
+ exact: Node;
40
+ folded: Node;
41
+ hasFolded: boolean;
42
+ canMatchPercentEncoded: boolean;
43
+ size: number;
44
+ minimumLength: number;
45
+ cache: Map<string, string>;
46
+ needles?: SensitiveValueVariant[];
47
+ encoded?: Matcher;
48
+ };
49
+ function node(): Node {
50
+ return { next: new Map() };
51
+ }
52
+
53
+ function compile(variants: readonly SensitiveValueVariant[]): Matcher {
54
+ const matcher: Matcher = {
55
+ exact: node(),
56
+ folded: node(),
57
+ hasFolded: false,
58
+ // Only long values participate in encoded matching. Unreserved ASCII is
59
+ // percent-encodable too (%6f for o); encodeURIComponent(value) === value
60
+ // does NOT prove that residual escapes cannot conceal that credential.
61
+ canMatchPercentEncoded: variants.some((variant) => variant.caseInsensitive),
62
+ size: variants.length,
63
+ minimumLength: variants.reduce(
64
+ (minimum, variant) => Math.min(minimum, variant.value.length),
65
+ Infinity,
66
+ ),
67
+ cache: new Map(),
68
+ };
69
+ if (variants.some((variant) => !variant.caseInsensitive))
70
+ matcher.encoded = compile(variants.filter((variant) => variant.caseInsensitive));
71
+ // A few request credentials are cheaper as native literal searches; large
72
+ // process-static inventories use tries to avoid per-needle scans.
73
+ if (variants.length <= 16) {
74
+ matcher.needles = variants.map((variant) => ({
75
+ ...variant,
76
+ value: variant.caseInsensitive ? variant.value.toLowerCase() : variant.value,
77
+ }));
78
+ matcher.hasFolded = variants.some((variant) => variant.caseInsensitive);
79
+ return matcher;
80
+ }
81
+ for (const variant of variants) {
82
+ let current = variant.caseInsensitive ? matcher.folded : matcher.exact;
83
+ if (variant.caseInsensitive) matcher.hasFolded = true;
84
+ const value = variant.caseInsensitive ? variant.value.toLowerCase() : variant.value;
85
+ for (let index = 0; index < value.length; index++) {
86
+ const character = value[index];
87
+ let child = current.next.get(character);
88
+ if (!child) {
89
+ child = node();
90
+ current.next.set(character, child);
91
+ }
92
+ current = child;
93
+ }
94
+ current.boundary =
95
+ current.boundary === undefined
96
+ ? variant.requiresTokenBoundary
97
+ : current.boundary && variant.requiresTokenBoundary;
98
+ }
99
+ return matcher;
100
+ }
101
+
102
+ /** Opaque handle: callers cannot modify either of the two independently compiled matchers. */
103
+ export interface CompiledDiagnosticSensitiveValues {
104
+ readonly kind: "compiled-diagnostic-sensitive-values";
105
+ }
106
+ const compiledValues = new WeakMap<
107
+ CompiledDiagnosticSensitiveValues,
108
+ {
109
+ primary: Matcher;
110
+ check: Matcher;
111
+ criticalPrimary: Matcher;
112
+ criticalCheck: Matcher;
113
+ values: ReadonlySet<string>;
114
+ }
115
+ >();
116
+
117
+ export function compileDiagnosticSensitiveValues(
118
+ values: readonly string[],
119
+ ): CompiledDiagnosticSensitiveValues {
120
+ const handle: CompiledDiagnosticSensitiveValues = Object.freeze({
121
+ kind: "compiled-diagnostic-sensitive-values",
122
+ });
123
+ const registered = values.filter((value) => value.length >= MINIMUM_REGISTERED_VALUE_LENGTH);
124
+ const variants = allSensitiveValueVariants(registered);
125
+ const primary = compile(variants),
126
+ check = compile(variants);
127
+ compiledValues.set(handle, {
128
+ primary,
129
+ check,
130
+ criticalPrimary: primary.encoded ?? primary,
131
+ criticalCheck: check.encoded ?? check,
132
+ values: new Set(registered),
133
+ });
134
+ return handle;
135
+ }
136
+
137
+ // Outside-context reads are process lifetime data, bounded like request harvesting.
138
+ const PROCESS_VALUE_LIMIT = 1024;
139
+ const PROCESS_BYTE_LIMIT = 64 * 1024;
140
+ function createDiagnosticFallback() {
141
+ return {
142
+ values: new Set<string>(),
143
+ bytes: 0,
144
+ suppressed: false,
145
+ version: 0,
146
+ compiledVersion: -1,
147
+ compiled: undefined as CompiledDiagnosticSensitiveValues | undefined,
148
+ };
149
+ }
150
+ type DiagnosticFallback = ReturnType<typeof createDiagnosticFallback>;
151
+ const processFallback = createDiagnosticFallback();
152
+ const fallbackScopes = new AsyncLocalStorage<DiagnosticFallback>();
153
+ const processCompositions = new WeakMap<CompiledDiagnosticSensitiveValues, DiagnosticFallback>();
154
+
155
+ /**
156
+ * Give an independent runtime/configuration evaluation its own fallback lifetime.
157
+ * Apps created inside the scope retain that inventory, including across awaits and
158
+ * after the callback returns. Ordinary startup/CLI reads keep the process lifetime.
159
+ * This also lets test harnesses isolate synthetic env reads without clearing live
160
+ * apps' credentials or weakening registration, matching, or exhaustion policies.
161
+ */
162
+ export function withDiagnosticFallbackScope<T>(fn: () => T): T {
163
+ return fallbackScopes.run(createDiagnosticFallback(), fn);
164
+ }
165
+
166
+ /** Re-enter the app's existing lifetime, including for detached request callbacks. */
167
+ export function withAppDiagnosticFallback<T>(
168
+ staticValues: CompiledDiagnosticSensitiveValues,
169
+ fn: () => T,
170
+ ): T {
171
+ return fallbackScopes.run(
172
+ processCompositions.get(staticValues) ?? currentDiagnosticFallback(),
173
+ fn,
174
+ );
175
+ }
176
+
177
+ function currentDiagnosticFallback(): DiagnosticFallback {
178
+ return fallbackScopes.getStore() ?? processFallback;
179
+ }
180
+
181
+ export function suppressProcessDiagnosticValues(): void {
182
+ const fallback = currentDiagnosticFallback();
183
+ if (fallback.suppressed) return;
184
+ fallback.suppressed = true;
185
+ console.warn(
186
+ "[apifuse] diagnostic redaction failed closed; reason=static_registry_limit; limit=1024_entries/65536_bytes",
187
+ );
188
+ }
189
+
190
+ export function registerProcessDiagnosticValues(values: readonly string[]): void {
191
+ const fallback = currentDiagnosticFallback();
192
+ if (fallback.suppressed) return;
193
+ for (const value of values) {
194
+ if (value.length < MINIMUM_REGISTERED_VALUE_LENGTH || fallback.values.has(value)) continue;
195
+ const bytes = Buffer.byteLength(value);
196
+ if (
197
+ fallback.values.size >= PROCESS_VALUE_LIMIT ||
198
+ fallback.bytes + bytes > PROCESS_BYTE_LIMIT
199
+ ) {
200
+ suppressProcessDiagnosticValues();
201
+ return;
202
+ }
203
+ fallback.values.add(value);
204
+ fallback.bytes += bytes;
205
+ fallback.version++;
206
+ }
207
+ }
208
+
209
+ /** The app's static inventory and the shared outside-context fallback form one static part. */
210
+ export function compileProcessDiagnosticSensitiveValues(
211
+ values: readonly string[],
212
+ ): CompiledDiagnosticSensitiveValues {
213
+ const handle = compileDiagnosticSensitiveValues(values);
214
+ processCompositions.set(handle, currentDiagnosticFallback());
215
+ return handle;
216
+ }
217
+
218
+ function isTokenCharacter(value: string | undefined): boolean {
219
+ return value !== undefined && /[\p{L}\p{N}]/u.test(value);
220
+ }
221
+
222
+ function matchLength(root: Node, comparable: string, original: string, start: number): number {
223
+ let current = root;
224
+ let length = 0;
225
+ for (let index = start; index < comparable.length; index++) {
226
+ const child = current.next.get(comparable[index]);
227
+ if (!child) break;
228
+ current = child;
229
+ if (
230
+ current.boundary !== undefined &&
231
+ (!current.boundary ||
232
+ (!isTokenCharacter(original[start - 1]) && !isTokenCharacter(original[index + 1])))
233
+ ) {
234
+ length = index - start + 1;
235
+ }
236
+ }
237
+ return length;
238
+ }
239
+
240
+ function replaceNeedles(text: string, matcher: Matcher, checkOnly: boolean): string {
241
+ const comparable = text.includes("%") ? normalizePercentEscapes(text) : text;
242
+ const folded = matcher.hasFolded ? comparable.toLowerCase() : comparable;
243
+ let cursor = 0;
244
+ let output = "";
245
+ while (cursor < text.length) {
246
+ let first = text.length;
247
+ let length = 0;
248
+ for (const variant of matcher.needles ?? []) {
249
+ const source = variant.caseInsensitive ? folded : text;
250
+ let index = source.indexOf(variant.value, cursor);
251
+ while (index !== -1) {
252
+ const end = index + variant.value.length;
253
+ const markerStart = source.lastIndexOf("[", index);
254
+ const withinMarker =
255
+ markerStart !== -1 && index < markerStart + markerLength(comparable, markerStart);
256
+ if (
257
+ !withinMarker &&
258
+ (!variant.requiresTokenBoundary ||
259
+ (!isTokenCharacter(source[index - 1]) && !isTokenCharacter(source[end])))
260
+ )
261
+ break;
262
+ index = source.indexOf(variant.value, index + 1);
263
+ }
264
+ if (index === -1) continue;
265
+ if (checkOnly || (variant.caseInsensitive && folded.length !== text.length))
266
+ return REDACTED_QUERY_VALUE;
267
+ if (index < first || (index === first && variant.value.length > length)) {
268
+ first = index;
269
+ length = variant.value.length;
270
+ }
271
+ }
272
+ if (!length) break;
273
+ output += text.slice(cursor, first) + REDACTED_QUERY_VALUE;
274
+ cursor = first + length;
275
+ }
276
+ return cursor ? output + text.slice(cursor) : text;
277
+ }
278
+
279
+ /** Literal tries have no secret-built regular expressions and no per-needle no-match scans. */
280
+ function replaceMatches(text: string, matchers: readonly Matcher[], checkOnly = false): string {
281
+ if (matchers.length === 1 && matchers[0].needles)
282
+ return replaceNeedles(text, matchers[0], checkOnly);
283
+ const comparable = text.includes("%") ? normalizePercentEscapes(text) : text;
284
+ const folded = matchers.some((matcher) => matcher.hasFolded)
285
+ ? comparable.toLowerCase()
286
+ : comparable;
287
+ // Unicode case folding can change offsets. Suppress the field on a folded match.
288
+ if (folded.length !== comparable.length) {
289
+ for (const matcher of matchers) {
290
+ for (let index = 0; index < folded.length; index++) {
291
+ if (matchLength(matcher.folded, folded, folded, index)) return REDACTED_QUERY_VALUE;
292
+ }
293
+ }
294
+ }
295
+ let cursor = 0;
296
+ let output = "";
297
+ for (let index = 0; index < text.length; index++) {
298
+ // Sentinels are emitted constants, not evidence of a residual credential.
299
+ const marker = markerLength(text, index);
300
+ if (marker) {
301
+ index += marker - 1;
302
+ continue;
303
+ }
304
+ let length = 0;
305
+ for (const matcher of matchers) {
306
+ length = Math.max(length, matchLength(matcher.exact, text, text, index));
307
+ if (matcher.hasFolded && folded.length === comparable.length) {
308
+ length = Math.max(length, matchLength(matcher.folded, folded, text, index));
309
+ }
310
+ }
311
+ if (!length) continue;
312
+ if (checkOnly) return REDACTED_QUERY_VALUE;
313
+ output += text.slice(cursor, index) + REDACTED_QUERY_VALUE;
314
+ cursor = index + length;
315
+ index = cursor - 1;
316
+ }
317
+ return cursor === 0 ? text : output + text.slice(cursor);
318
+ }
319
+
320
+ function decodePercent(text: string): string {
321
+ try {
322
+ return decodeURIComponent(text);
323
+ } catch {
324
+ // An unrelated malformed escape must not hide valid encoded credential text.
325
+ return text.replace(/(?:%[\da-f]{2})+/gi, (part) => {
326
+ try {
327
+ return decodeURIComponent(part);
328
+ } catch {
329
+ return part.replace(/%([\da-f]{2})/gi, (encodedByte, hex: string) => {
330
+ const byte = Number.parseInt(hex, 16);
331
+ return byte < 128 ? String.fromCharCode(byte) : encodedByte;
332
+ });
333
+ }
334
+ });
335
+ }
336
+ }
337
+
338
+ function applyMatcher(text: string, matcher: Matcher): string {
339
+ if (!matcher.size) return text;
340
+ // ASCII cannot grow under NFC/case folding; without escapes, a shorter field
341
+ // cannot contain any needle. Keep decoding and Unicode checks on the full path.
342
+ if (text.length < matcher.minimumLength && !text.includes("%") && !/[\u0080-\uffff]/.test(text))
343
+ return text;
344
+ const cached = matcher.cache.get(text);
345
+ if (cached !== undefined) return cached;
346
+ const matchers = [matcher];
347
+ const direct = replaceMatches(text, matchers);
348
+ let result = direct;
349
+ let normalized = direct;
350
+ for (let round = 0; round < 3 && normalized.includes("%"); round++) {
351
+ const decoded = decodePercent(normalized);
352
+ if (decoded === normalized) break;
353
+ normalized = decoded;
354
+ if (replaceMatches(normalized, [matcher.encoded ?? matcher], true) !== normalized) {
355
+ result = REDACTED_QUERY_VALUE;
356
+ }
357
+ }
358
+ // A residual escape is unresolved after the fixed work budget: emit less,
359
+ // if this nonempty registry can match percent-encoded credentials, even when
360
+ // another representation matched. Both independent roles use this.
361
+ if (matcher.canMatchPercentEncoded && /%[\da-f]{2}/i.test(normalized)) result = REDACTION_FAILED;
362
+ const nfc = normalized.normalize("NFC");
363
+ if (
364
+ result !== REDACTION_FAILED &&
365
+ nfc !== normalized &&
366
+ replaceMatches(nfc, [matcher.encoded ?? matcher], true) !== nfc
367
+ )
368
+ result = REDACTED_QUERY_VALUE;
369
+ // Matchers are immutable; additions compile a new request matcher. Independent
370
+ // request-local caches reuse results across repeated span/resource exports. Bound
371
+ // entry count and input size; process-static lookup data never caches request text.
372
+ if (text.length <= 4096) {
373
+ if (matcher.cache.size >= 256) matcher.cache.clear();
374
+ matcher.cache.set(text, result);
375
+ }
376
+ return result;
377
+ }
378
+
379
+ function applyMatchers(text: string, matchers: readonly Matcher[]): string {
380
+ let result = text;
381
+ for (const matcher of matchers) {
382
+ const candidate = applyMatcher(text, matcher);
383
+ if (candidate === text) continue;
384
+ // Static and request secrets may overlap. Scan original text independently
385
+ // so an earlier replacement cannot hide the rest of a longer credential.
386
+ if (result !== text && result !== candidate) return REDACTED_QUERY_VALUE;
387
+ result = candidate;
388
+ }
389
+ return result;
390
+ }
391
+
392
+ /** One small mutable registry per request, composed with precompiled process-static values. */
393
+ export function createDiagnosticRedactor(
394
+ values: readonly string[] = [],
395
+ staticValues?: CompiledDiagnosticSensitiveValues,
396
+ ): DiagnosticSensitiveRegistry {
397
+ const compiled = staticValues ? compiledValues.get(staticValues) : undefined;
398
+ // Share immutable lookup data only. Raw diagnostic cache keys die with this scope.
399
+ const requestMatcher = (matcher: Matcher): Matcher => ({ ...matcher, cache: new Map() });
400
+ const staticPrimary = compiled?.primary.size ? requestMatcher(compiled.primary) : undefined;
401
+ const staticCheck = compiled?.check.size ? requestMatcher(compiled.check) : undefined;
402
+ const staticCriticalPrimary = compiled?.criticalPrimary.size
403
+ ? compiled.criticalPrimary === compiled.primary
404
+ ? staticPrimary
405
+ : requestMatcher(compiled.criticalPrimary)
406
+ : undefined;
407
+ const staticCriticalCheck = compiled?.criticalCheck.size
408
+ ? compiled.criticalCheck === compiled.check
409
+ ? staticCheck
410
+ : requestMatcher(compiled.criticalCheck)
411
+ : undefined;
412
+ const known = new Set<string>();
413
+ const fallback = staticValues === undefined ? undefined : processCompositions.get(staticValues);
414
+ const has = (value: string) =>
415
+ known.has(value) ||
416
+ compiled?.values.has(value) === true ||
417
+ fallback?.values.has(value) === true;
418
+ let seenProcessVersion = -1;
419
+ let fallbackPrimary: Matcher[] = [];
420
+ let fallbackCheck: Matcher[] = [];
421
+ let fallbackCriticalPrimary: Matcher[] = [];
422
+ let fallbackCriticalCheck: Matcher[] = [];
423
+ let requestPrimary: Matcher | undefined;
424
+ let requestCheck: Matcher | undefined;
425
+ let suppressed = false;
426
+ let primary: Matcher[] = staticPrimary ? [staticPrimary] : [];
427
+ let check: Matcher[] = staticCheck ? [staticCheck] : [];
428
+ let criticalPrimary: Matcher[] = staticCriticalPrimary ? [staticCriticalPrimary] : [];
429
+ let criticalCheck: Matcher[] = staticCriticalCheck ? [staticCriticalCheck] : [];
430
+ const variants: SensitiveValueVariant[] = [];
431
+ let uncompiled: string[] = [];
432
+ const add = (incoming: readonly string[]) => {
433
+ for (const value of incoming) {
434
+ if (value.length < MINIMUM_REGISTERED_VALUE_LENGTH || has(value)) continue;
435
+ known.add(value);
436
+ uncompiled.push(value);
437
+ }
438
+ };
439
+ const ensureCompiled = () => {
440
+ const processChanged = fallback !== undefined && seenProcessVersion !== fallback.version;
441
+ if (!uncompiled.length && !processChanged) return;
442
+ if (processChanged) {
443
+ if (fallback.compiledVersion !== fallback.version) {
444
+ fallback.compiled = compileDiagnosticSensitiveValues([...fallback.values]);
445
+ fallback.compiledVersion = fallback.version;
446
+ }
447
+ const compiledFallback = fallback.compiled && compiledValues.get(fallback.compiled);
448
+ fallbackPrimary = compiledFallback?.primary.size
449
+ ? [requestMatcher(compiledFallback.primary)]
450
+ : [];
451
+ fallbackCheck = compiledFallback?.check.size ? [requestMatcher(compiledFallback.check)] : [];
452
+ fallbackCriticalPrimary = compiledFallback?.criticalPrimary.size
453
+ ? [requestMatcher(compiledFallback.criticalPrimary)]
454
+ : [];
455
+ fallbackCriticalCheck = compiledFallback?.criticalCheck.size
456
+ ? [requestMatcher(compiledFallback.criticalCheck)]
457
+ : [];
458
+ seenProcessVersion = fallback.version;
459
+ }
460
+ if (uncompiled.length) {
461
+ // Generate each value's variants once, lazily on the first actual match.
462
+ variants.push(...allSensitiveValueVariants(uncompiled));
463
+ uncompiled = [];
464
+ requestPrimary = compile(variants);
465
+ requestCheck = compile(variants);
466
+ }
467
+ primary = [
468
+ ...(staticPrimary ? [staticPrimary] : []),
469
+ ...fallbackPrimary,
470
+ ...(requestPrimary ? [requestPrimary] : []),
471
+ ];
472
+ check = [
473
+ ...(staticCheck ? [staticCheck] : []),
474
+ ...fallbackCheck,
475
+ ...(requestCheck ? [requestCheck] : []),
476
+ ];
477
+ criticalPrimary = [
478
+ ...(staticCriticalPrimary ? [staticCriticalPrimary] : []),
479
+ ...fallbackCriticalPrimary,
480
+ ...(requestPrimary ? [requestPrimary.encoded ?? requestPrimary] : []),
481
+ ];
482
+ criticalCheck = [
483
+ ...(staticCriticalCheck ? [staticCriticalCheck] : []),
484
+ ...fallbackCriticalCheck,
485
+ ...(requestCheck ? [requestCheck.encoded ?? requestCheck] : []),
486
+ ];
487
+ };
488
+ add(values);
489
+ const protect =
490
+ (callback: DiagnosticRedactor, critical = false, freeText = !critical): DiagnosticRedactor =>
491
+ (text) => {
492
+ if (text === REDACTED_QUERY_VALUE || text === REDACTION_FAILED) return text;
493
+ if ((suppressed || fallback?.suppressed) && freeText) return REDACTION_FAILED;
494
+ ensureCompiled();
495
+ const result = redactDiagnosticText(text, callback);
496
+ ensureCompiled(); // A replaced callback may register a value during the call.
497
+ if ((suppressed || fallback?.suppressed) && freeText) return REDACTION_FAILED;
498
+ // This private matcher is a separate object from the callback's matcher,
499
+ // survives callback replacement, and sees additions made after trace creation.
500
+ return applyMatchers(result, critical ? criticalCheck : check) === result
501
+ ? result
502
+ : REDACTION_FAILED;
503
+ };
504
+ let safeRedact = protect((text) => applyMatchers(text, primary));
505
+ let safeCritical = protect((text) => applyMatchers(text, criticalPrimary), true);
506
+ let safeStructured = protect((text) => applyMatchers(text, primary), false, false);
507
+ const critical = (text: string) => safeCritical(text);
508
+ const structured = (text: string) => safeStructured(text);
509
+ const isSuppressed = () => suppressed || fallback?.suppressed === true;
510
+ bindCriticalDiagnosticRedactor(safeRedact, critical, structured, isSuppressed);
511
+ return {
512
+ add,
513
+ has,
514
+ redactCritical: critical,
515
+ redactStructured: structured,
516
+ get suppressed() {
517
+ return isSuppressed();
518
+ },
519
+ suppress() {
520
+ suppressed = true;
521
+ },
522
+ get redact() {
523
+ return safeRedact;
524
+ },
525
+ set redact(callback: DiagnosticRedactor) {
526
+ safeRedact = protect(callback);
527
+ safeCritical = protect(callback, true);
528
+ safeStructured = protect(callback, false, false);
529
+ bindCriticalDiagnosticRedactor(safeRedact, critical, structured, isSuppressed);
530
+ },
531
+ };
532
+ }
533
+
534
+ const requestRegistries = new WeakMap<object, DiagnosticSensitiveRegistry>();
535
+
536
+ /** Internal binding; neither the registry nor its values enter provider-facing context types. */
537
+ export function bindDiagnosticSensitiveRegistry(
538
+ trace: object,
539
+ registry: DiagnosticSensitiveRegistry,
540
+ ): void {
541
+ requestRegistries.set(trace, registry);
542
+ }
543
+
544
+ export function registerDiagnosticSensitiveValues(trace: object, values: readonly string[]): void {
545
+ requestRegistries.get(trace)?.add(values);
546
+ }
547
+
548
+ // Policy metadata is internal: public callbacks remain backward-compatible unary functions.
549
+ const criticalRedactors = new WeakMap<DiagnosticRedactor, DiagnosticRedactor>();
550
+ const structuredRedactors = new WeakMap<DiagnosticRedactor, DiagnosticRedactor>();
551
+ const redactionSuppression = new WeakMap<DiagnosticRedactor, () => boolean>();
552
+ export function bindCriticalDiagnosticRedactor(
553
+ redact: DiagnosticRedactor,
554
+ critical: DiagnosticRedactor,
555
+ structured?: DiagnosticRedactor,
556
+ isSuppressed?: () => boolean,
557
+ ): void {
558
+ criticalRedactors.set(redact, critical);
559
+ if (structured) structuredRedactors.set(redact, structured);
560
+ if (isSuppressed) redactionSuppression.set(redact, isSuppressed);
561
+ }
562
+ export function isDiagnosticRedactionSuppressed(redact?: DiagnosticRedactor): boolean {
563
+ return redact ? redactionSuppression.get(redact)?.() === true : false;
564
+ }
565
+ /** Typed values and keys still match known credentials, but never blanket suppression. */
566
+ export function diagnosticStructuredRedactor(
567
+ redact?: DiagnosticRedactor,
568
+ ): DiagnosticRedactor | undefined {
569
+ return redact ? (structuredRedactors.get(redact) ?? redact) : undefined;
570
+ }
571
+ export function redactDiagnosticAttributeKey(key: string, redact?: DiagnosticRedactor): string {
572
+ return redactDiagnosticText(
573
+ key,
574
+ diagnosticStructuredRedactor(diagnosticAttributeRedactor(key, redact)),
575
+ );
576
+ }
577
+ export function redactCriticalDiagnosticText(text: string, redact?: DiagnosticRedactor): string {
578
+ return redactDiagnosticText(text, redact ? (criticalRedactors.get(redact) ?? redact) : undefined);
579
+ }
580
+ export function diagnosticAttributeRedactor(
581
+ key: string,
582
+ redact?: DiagnosticRedactor,
583
+ ): DiagnosticRedactor | undefined {
584
+ if (CLOSED_ENUM_ATTRIBUTE_KEYS.has(key)) return diagnosticStructuredRedactor(redact);
585
+ return CRITICAL_ATTRIBUTE_KEYS.has(key) && redact
586
+ ? (criticalRedactors.get(redact) ?? redact)
587
+ : redact;
588
+ }
589
+ // Structured debugging contracts use only >=8-character values. Other attributes are free text.
590
+ const CRITICAL_ATTRIBUTE_KEYS = new Set([
591
+ "request_id",
592
+ "requestId",
593
+ "trace_id",
594
+ "traceId",
595
+ "span_id",
596
+ "spanId",
597
+ "route",
598
+ "operation_id",
599
+ "operation",
600
+ "http.status_code",
601
+ ]);
602
+
603
+ // SDK-owned closed enums are contracts, like typed numbers and booleans. This
604
+ // exempts only exhaustion suppression; registered credentials still match.
605
+ const CLOSED_ENUM_ATTRIBUTE_KEYS = new Set([
606
+ "outcome",
607
+ "code",
608
+ "errorClass",
609
+ "phase",
610
+ "cacheStatus",
611
+ "identitySource",
612
+ "taxonomy",
613
+ "taxonomyVersion",
614
+ ]);
615
+
616
+ // Bigints normalize to strings for OTLP. Carry their type policy through internal
617
+ // detached copies without treating arbitrary numeric-looking free text as typed.
618
+ const bigintAttributes = new WeakMap<object, ReadonlySet<string>>();
619
+ export function isDiagnosticBigintAttribute(attributes: object, key: string): boolean {
620
+ return bigintAttributes.get(attributes)?.has(key) === true;
621
+ }
622
+ export function copyDiagnosticAttributeTypes<T extends Record<string, unknown>>(
623
+ source: Record<string, unknown>,
624
+ target: T,
625
+ ): T {
626
+ const keys = Object.keys(source).filter(
627
+ (key) =>
628
+ (typeof source[key] === "bigint" || isDiagnosticBigintAttribute(source, key)) &&
629
+ String(source[key]) === target[key],
630
+ );
631
+ if (keys.length) bigintAttributes.set(target, new Set(keys));
632
+ return target;
633
+ }
634
+
635
+ /** Reserve existing keys so independently redacted names never drop an attribute. */
636
+ export function redactedKeyAllocator(keys: Iterable<string>): () => string {
637
+ // Snapshot the inventory now, but allocate its lookup only if a key changes.
638
+ const inventory = [...keys];
639
+ let reserved: Set<string> | undefined;
640
+ let sequence = 0;
641
+ return () => {
642
+ reserved ??= new Set(inventory);
643
+ let key: string;
644
+ do {
645
+ key = `[REDACTED#${++sequence}]`;
646
+ } while (reserved.has(key));
647
+ reserved.add(key);
648
+ return key;
649
+ };
650
+ }
651
+ export function isRedactedKey(key: string): boolean {
652
+ return /^\[REDACTED#\d+\]$/.test(key);
653
+ }
654
+
655
+ function markerLength(text: string, index: number): number {
656
+ if (text[index] !== "[") return 0;
657
+ if (text.startsWith(REDACTED_QUERY_VALUE, index)) return REDACTED_QUERY_VALUE.length;
658
+ if (text.startsWith(REDACTION_FAILED, index)) return REDACTION_FAILED.length;
659
+ if (text.startsWith("[REDACTED#", index))
660
+ return /^\[REDACTED#\d+\]/.exec(text.slice(index))?.[0].length ?? 0;
661
+ return 0;
662
+ }
@@ -1,3 +1,4 @@
1
+ import { readDiagnosticEnv } from "./diagnostic-env.js";
1
2
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
2
3
 
3
4
  import type { ProxyVendorName } from "../config/loader.js";
@@ -234,6 +235,8 @@ export function createCeremonyEgressLeaseRuntime(options: {
234
235
  readonly flowId: string;
235
236
  readonly affinityKey: string;
236
237
  readonly handle?: string;
238
+ /** Server-only registration before a handle can reach request diagnostics. */
239
+ readonly onHandle?: (handle: string) => void;
237
240
  readonly environment?: Readonly<Record<string, string | undefined>>;
238
241
  readonly now?: () => number;
239
242
  }): CeremonyEgressLeaseRuntime {
@@ -251,7 +254,7 @@ export function createCeremonyEgressLeaseRuntime(options: {
251
254
  flowId: options.flowId,
252
255
  affinityKey: options.affinityKey,
253
256
  };
254
- const key = environment[APIFUSE__ENGINE__CEREMONY_LEASE_KEY]?.trim();
257
+ const key = readDiagnosticEnv(APIFUSE__ENGINE__CEREMONY_LEASE_KEY, environment)?.trim();
255
258
  if (!key) {
256
259
  throw new SDKError("The engine ceremony egress lease key is not configured", {
257
260
  code: "EGRESS_LEASE_KEY_MISSING",
@@ -284,6 +287,7 @@ export function createCeremonyEgressLeaseRuntime(options: {
284
287
  payload !== undefined && now() >= payload.expiresAtMs ? dropBinding() : false;
285
288
 
286
289
  if (options.handle !== undefined) {
290
+ options.onHandle?.(options.handle);
287
291
  // Scope mismatch fails GCM authentication because scope is AAD; there is
288
292
  // deliberately no post-decrypt scope comparison fallback.
289
293
  payload = decodeHandle(options.handle, key, scope);
@@ -328,6 +332,7 @@ export function createCeremonyEgressLeaseRuntime(options: {
328
332
  expiresAtMs: mintedAtMs + binding.lifetimeMinutes * 60_000,
329
333
  };
330
334
  currentHandle = encodeHandle(payload, key, scope);
335
+ options.onHandle?.(currentHandle);
331
336
  },
332
337
  handle() {
333
338
  return currentHandle;