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

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