@jini-ai/core 0.7.1 → 0.7.3-next.1
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.
- package/README.md +40 -12
- package/dist/admin-runtime/admin-api-error.d.ts +68 -0
- package/dist/admin-runtime/admin-api-error.js +72 -0
- package/dist/admin-runtime/admin-config-error.d.ts +8 -0
- package/dist/admin-runtime/admin-config-error.js +11 -0
- package/dist/admin-runtime/controller-store.d.ts +20 -0
- package/dist/admin-runtime/controller-store.js +32 -0
- package/dist/admin-runtime/index.d.ts +13 -0
- package/dist/admin-runtime/index.js +12 -0
- package/dist/admin-runtime/panel-access.d.ts +88 -0
- package/dist/admin-runtime/panel-access.js +76 -0
- package/dist/admin-runtime/query-suffix.d.ts +5 -0
- package/dist/admin-runtime/query-suffix.js +5 -0
- package/dist/agent-handles/element-handles.d.ts +134 -0
- package/dist/agent-handles/element-handles.js +45 -0
- package/dist/agent-handles/field-descriptor.d.ts +28 -0
- package/dist/agent-handles/field-descriptor.js +3 -0
- package/dist/agent-handles/handle.d.ts +109 -0
- package/dist/agent-handles/handle.js +109 -0
- package/dist/agent-handles/index.d.ts +9 -0
- package/dist/agent-handles/index.js +6 -0
- package/dist/agent-handles/list-handles.d.ts +46 -0
- package/dist/agent-handles/list-handles.js +67 -0
- package/dist/agent-handles/secret-attrs.d.ts +14 -0
- package/dist/agent-handles/secret-attrs.js +13 -0
- package/dist/approval-batch-chain.d.ts +45 -0
- package/dist/approval-batch-chain.js +75 -0
- package/dist/approval.d.ts +33 -14
- package/dist/approval.js +57 -43
- package/dist/batch-tool-inputs.js +24 -20
- package/dist/contracts/admin-module.d.ts +166 -0
- package/dist/contracts/admin-module.js +14 -0
- package/dist/contracts/agents/definition.d.ts +459 -0
- package/dist/contracts/agents/definition.js +2 -0
- package/dist/contracts/agents/index.d.ts +7 -0
- package/dist/contracts/agents/index.js +2 -0
- package/dist/contracts/agents/launch.d.ts +64 -0
- package/dist/contracts/agents/launch.js +2 -0
- package/dist/contracts/agents/model-catalog.d.ts +213 -0
- package/dist/contracts/agents/model-catalog.js +4 -0
- package/dist/contracts/agents/native-tool-policy.d.ts +42 -0
- package/dist/contracts/agents/native-tool-policy.js +2 -0
- package/dist/contracts/ai-trace/capture.d.ts +17 -0
- package/dist/contracts/ai-trace/capture.js +43 -0
- package/dist/contracts/ai-trace/classify.d.ts +12 -0
- package/dist/contracts/ai-trace/classify.js +16 -0
- package/dist/contracts/ai-trace/index.d.ts +13 -0
- package/dist/contracts/ai-trace/index.js +6 -0
- package/dist/contracts/ai-trace/recorder.d.ts +64 -0
- package/dist/contracts/ai-trace/recorder.js +283 -0
- package/dist/contracts/ai-trace/sinks.d.ts +51 -0
- package/dist/contracts/ai-trace/sinks.js +153 -0
- package/dist/contracts/ai-trace/types.d.ts +123 -0
- package/dist/contracts/ai-trace/types.js +17 -0
- package/dist/contracts/ai-trace/usage.d.ts +16 -0
- package/dist/contracts/ai-trace/usage.js +45 -0
- package/dist/contracts/blob.d.ts +31 -0
- package/dist/contracts/blob.js +10 -0
- package/dist/contracts/capabilities.d.ts +95 -0
- package/dist/contracts/capabilities.js +111 -0
- package/dist/contracts/charts.d.ts +75 -0
- package/dist/contracts/charts.js +4 -0
- package/dist/contracts/env.d.ts +96 -0
- package/dist/contracts/env.js +6 -0
- package/dist/contracts/events/change-set.d.ts +106 -0
- package/dist/contracts/events/change-set.js +2 -0
- package/dist/contracts/events/command.d.ts +118 -0
- package/dist/contracts/events/command.js +2 -0
- package/dist/contracts/events/ports.d.ts +172 -0
- package/dist/contracts/events/ports.js +2 -0
- package/dist/contracts/events.d.ts +5 -0
- package/dist/contracts/events.js +2 -0
- package/dist/contracts/forms.d.ts +110 -0
- package/dist/contracts/forms.js +4 -0
- package/dist/contracts/hosted-mcp/config.d.ts +19 -0
- package/dist/contracts/hosted-mcp/record.d.ts +61 -4
- package/dist/contracts/mail/email-sender.d.ts +118 -0
- package/dist/contracts/mail/email-sender.js +20 -0
- package/dist/contracts/mail/smtp-payload.d.ts +32 -0
- package/dist/contracts/mail/smtp-payload.js +2 -0
- package/dist/contracts/mail.d.ts +2 -0
- package/dist/contracts/mail.js +1 -1
- package/dist/contracts/observability.d.ts +232 -0
- package/dist/contracts/observability.js +27 -0
- package/dist/contracts/plugin-sdk.d.ts +186 -0
- package/dist/contracts/plugin-sdk.js +39 -0
- package/dist/contracts/runtime/command.d.ts +41 -0
- package/dist/contracts/runtime/command.js +60 -0
- package/dist/contracts/runtime/environment.d.ts +18 -0
- package/dist/contracts/runtime/environment.js +26 -0
- package/dist/contracts/runtime/file-lock.d.ts +94 -0
- package/dist/contracts/runtime/file-lock.js +25 -0
- package/dist/contracts/runtime/fs.d.ts +33 -0
- package/dist/contracts/runtime/fs.js +2 -0
- package/dist/contracts/runtime/http.d.ts +89 -0
- package/dist/contracts/runtime/http.js +2 -0
- package/dist/contracts/runtime/platform.d.ts +3 -0
- package/dist/contracts/runtime/platform.js +2 -0
- package/dist/contracts/runtime/process.d.ts +40 -0
- package/dist/contracts/runtime/process.js +31 -0
- package/dist/contracts/runtime/reader.d.ts +11 -0
- package/dist/contracts/runtime/reader.js +2 -0
- package/dist/contracts/runtime/terminal.d.ts +99 -0
- package/dist/contracts/runtime/terminal.js +2 -0
- package/dist/contracts/runtime/testing.d.ts +84 -0
- package/dist/contracts/runtime/testing.js +116 -0
- package/dist/contracts/runtime.d.ts +10 -0
- package/dist/contracts/runtime.js +10 -0
- package/dist/contracts/server/api-error.d.ts +43 -0
- package/dist/contracts/server/api-error.js +49 -0
- package/dist/contracts/server/auth.d.ts +20 -0
- package/dist/contracts/server/auth.js +21 -0
- package/dist/contracts/server/conformance.d.ts +25 -0
- package/dist/contracts/server/conformance.js +50 -0
- package/dist/contracts/server/json-route.d.ts +176 -0
- package/dist/contracts/server/json-route.js +155 -0
- package/dist/contracts/server/middleware.d.ts +35 -0
- package/dist/contracts/server/middleware.js +56 -0
- package/dist/contracts/server/origin.d.ts +44 -0
- package/dist/contracts/server/origin.js +32 -0
- package/dist/contracts/server/query.d.ts +16 -0
- package/dist/contracts/server/query.js +69 -0
- package/dist/contracts/server/rate-limit.d.ts +20 -0
- package/dist/contracts/server/rate-limit.js +8 -0
- package/dist/contracts/server/request-body.d.ts +26 -0
- package/dist/contracts/server/request-body.js +82 -0
- package/dist/contracts/server/result.d.ts +17 -0
- package/dist/contracts/server/result.js +5 -0
- package/dist/contracts/server/route-table.d.ts +54 -0
- package/dist/contracts/server/route-table.js +119 -0
- package/dist/contracts/server/same-origin-write.d.ts +18 -0
- package/dist/contracts/server/same-origin-write.js +31 -0
- package/dist/contracts/server/security-headers.d.ts +30 -0
- package/dist/contracts/server/security-headers.js +35 -0
- package/dist/contracts/server/sse.d.ts +82 -0
- package/dist/contracts/server/sse.js +103 -0
- package/dist/contracts/server/testing.d.ts +59 -0
- package/dist/contracts/server/testing.js +68 -0
- package/dist/contracts/server/verified-origin/configured-origin.d.ts +37 -0
- package/dist/contracts/server/verified-origin/configured-origin.js +103 -0
- package/dist/contracts/server/verified-origin/index.d.ts +7 -0
- package/dist/contracts/server/verified-origin/index.js +6 -0
- package/dist/contracts/server/verified-origin/loopback-host.d.ts +9 -0
- package/dist/contracts/server/verified-origin/loopback-host.js +17 -0
- package/dist/contracts/server/verified-origin/origin.d.ts +64 -0
- package/dist/contracts/server/verified-origin/origin.js +162 -0
- package/dist/contracts/server/verified-origin/ports.d.ts +38 -0
- package/dist/contracts/server/verified-origin/ports.js +2 -0
- package/dist/contracts/server/verified-origin/repo.memory.d.ts +32 -0
- package/dist/contracts/server/verified-origin/repo.memory.js +34 -0
- package/dist/contracts/server/verified-origin/site-path.d.ts +113 -0
- package/dist/contracts/server/verified-origin/site-path.js +188 -0
- package/dist/contracts/server/verified-origin/types.d.ts +33 -0
- package/dist/contracts/server/verified-origin/types.js +30 -0
- package/dist/contracts/server.d.ts +46 -2
- package/dist/contracts/server.js +17 -3
- package/dist/contracts/storage/kernel.d.ts +86 -0
- package/dist/contracts/storage/kernel.js +38 -0
- package/dist/contracts/storage/migration.d.ts +32 -0
- package/dist/contracts/storage/migration.js +2 -0
- package/dist/contracts/storage/rows.d.ts +33 -0
- package/dist/contracts/storage/rows.js +42 -0
- package/dist/contracts/storage/sqlite.d.ts +113 -0
- package/dist/contracts/storage/sqlite.js +8 -0
- package/dist/contracts/storage/values.d.ts +25 -0
- package/dist/contracts/storage/values.js +25 -0
- package/dist/contracts/storage.d.ts +8 -0
- package/dist/contracts/storage.js +6 -0
- package/dist/contracts/vault/invariants.d.ts +26 -0
- package/dist/contracts/vault/invariants.js +49 -0
- package/dist/contracts/vault.d.ts +1 -0
- package/dist/contracts/vault.js +1 -1
- package/dist/env/coercers.d.ts +21 -0
- package/dist/env/coercers.js +68 -0
- package/dist/env/describe-env-for-diagnostics.d.ts +16 -0
- package/dist/env/describe-env-for-diagnostics.js +23 -0
- package/dist/env/format-env-issue.d.ts +13 -0
- package/dist/env/format-env-issue.js +22 -0
- package/dist/env/parse-env.d.ts +24 -0
- package/dist/env/parse-env.js +102 -0
- package/dist/env/value-echo.d.ts +17 -0
- package/dist/env/value-echo.js +42 -0
- package/dist/errors/approved-cause.d.ts +36 -0
- package/dist/errors/approved-cause.js +17 -0
- package/dist/errors/bindings.d.ts +61 -0
- package/dist/errors/bindings.js +57 -0
- package/dist/errors/catalog.d.ts +84 -0
- package/dist/errors/catalog.js +151 -0
- package/dist/errors/disclosure.d.ts +48 -0
- package/dist/errors/disclosure.js +27 -0
- package/dist/errors/error-id.d.ts +26 -0
- package/dist/errors/error-id.js +23 -0
- package/dist/errors/idioms.d.ts +73 -0
- package/dist/errors/idioms.js +85 -0
- package/dist/errors/incident-text.d.ts +16 -0
- package/dist/errors/incident-text.js +77 -0
- package/dist/errors/reporter.d.ts +94 -0
- package/dist/errors/reporter.js +152 -0
- package/dist/errors/sentences.d.ts +68 -0
- package/dist/errors/sentences.js +93 -0
- package/dist/errors/testing.d.ts +50 -0
- package/dist/errors/testing.js +44 -0
- package/dist/fetch/cache.d.ts +12 -5
- package/dist/fetch/cache.js +46 -47
- package/dist/fetch/index.d.ts +1 -1
- package/dist/fetch/loader-read.d.ts +6 -2
- package/dist/fetch/loader-read.js +4 -4
- package/dist/format-error-for-log.d.ts +15 -0
- package/dist/format-error-for-log.js +55 -0
- package/dist/host-read-vocabulary.d.ts +47 -0
- package/dist/host-read-vocabulary.js +44 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +4 -0
- package/dist/list-page.d.ts +93 -0
- package/dist/list-page.js +154 -0
- package/dist/model-facing-tool-errors.d.ts +67 -5
- package/dist/model-facing-tool-errors.js +155 -19
- package/dist/net/endpoint-policy.d.ts +39 -0
- package/dist/net/endpoint-policy.js +218 -0
- package/dist/net/fetch-timeouts.d.ts +38 -0
- package/dist/net/fetch-timeouts.js +31 -0
- package/dist/net/index.d.ts +4 -0
- package/dist/net/index.js +4 -0
- package/dist/net/loopback.d.ts +13 -0
- package/dist/net/loopback.js +39 -0
- package/dist/optimistic-concurrency.d.ts +183 -0
- package/dist/optimistic-concurrency.js +222 -0
- package/dist/primitives/errors.d.ts +9 -0
- package/dist/primitives/errors.js +12 -0
- package/dist/primitives/ids.d.ts +0 -2
- package/dist/primitives/ids.js +1 -4
- package/dist/primitives/index.d.ts +3 -0
- package/dist/primitives/index.js +2 -0
- package/dist/primitives/logger.d.ts +36 -1
- package/dist/primitives/logger.js +125 -9
- package/dist/primitives/node-shape.d.ts +24 -0
- package/dist/primitives/node-shape.js +21 -0
- package/dist/primitives/time.d.ts +9 -2
- package/dist/primitives/time.js +4 -3
- package/dist/provider-registry.js +26 -20
- package/dist/records.d.ts +40 -7
- package/dist/records.js +37 -3
- package/dist/redact.d.ts +1 -84
- package/dist/redact.js +2 -826
- package/dist/redaction-collectors.d.ts +7 -0
- package/dist/redaction-collectors.js +152 -0
- package/dist/redaction-exact-secrets.d.ts +14 -0
- package/dist/redaction-exact-secrets.js +115 -0
- package/dist/redaction-labels.d.ts +14 -0
- package/dist/redaction-labels.js +156 -0
- package/dist/redaction-patterns.d.ts +54 -0
- package/dist/redaction-patterns.js +178 -0
- package/dist/redaction-spans.d.ts +31 -0
- package/dist/redaction-spans.js +83 -0
- package/dist/registration-kit.d.ts +1 -1
- package/dist/revision-conflict-error.d.ts +18 -0
- package/dist/revision-conflict-error.js +20 -0
- package/dist/secret-shapes.d.ts +50 -0
- package/dist/secret-shapes.js +105 -0
- package/dist/settings/agent-tools.js +22 -8
- package/dist/settings/agent-value-write-tools.d.ts +4 -1
- package/dist/settings/agent-value-write-tools.js +7 -6
- package/dist/settings/agent-writable-preferences.d.ts +3 -1
- package/dist/settings/agent-writable-preferences.js +1 -1
- package/dist/settings/agent-write-denylist.d.ts +7 -4
- package/dist/settings/agent-write-denylist.js +1 -1
- package/dist/settings/{express/cms-adapter.d.ts → cms-adapter.d.ts} +3 -2
- package/dist/settings/{express/cms-adapter.js → cms-adapter.js} +21 -11
- package/dist/settings/definitions-dispatch.js +3 -1
- package/dist/settings/ensure-definitions.js +3 -1
- package/dist/settings/errors.d.ts +1 -13
- package/dist/settings/errors.js +2 -15
- package/dist/settings/index.d.ts +11 -2
- package/dist/settings/index.js +10 -2
- package/dist/settings/purge-service.js +63 -86
- package/dist/settings/{express/contracts.d.ts → route-policy.d.ts} +53 -47
- package/dist/settings/{express/shared.js → route-policy.js} +1 -16
- package/dist/settings/settings.d.ts +19 -11
- package/dist/settings/settings.js +9 -11
- package/dist/settings/tool-registrations.d.ts +3 -3
- package/dist/settings/tool-registrations.js +130 -125
- package/dist/settings/types.d.ts +1 -1
- package/dist/settings/write-definition-rename.d.ts +37 -0
- package/dist/settings/write-definition-rename.js +119 -0
- package/dist/settings/write-definition-retype.d.ts +61 -0
- package/dist/settings/write-definition-retype.js +109 -0
- package/dist/settings/write-definition-status.d.ts +81 -0
- package/dist/settings/write-definition-status.js +121 -0
- package/dist/settings/write-reset.d.ts +34 -0
- package/dist/settings/write-reset.js +73 -0
- package/dist/settings/write-service.d.ts +16 -287
- package/dist/settings/write-service.js +49 -681
- package/dist/settings/write-value-revisions.d.ts +68 -0
- package/dist/settings/write-value-revisions.js +124 -0
- package/dist/settings/write-values.d.ts +96 -0
- package/dist/settings/write-values.js +83 -0
- package/dist/surface-exchanges.d.ts +2 -2
- package/dist/text/dictionary-translator.d.ts +19 -0
- package/dist/text/dictionary-translator.js +14 -0
- package/dist/text/format-byte-size.d.ts +25 -0
- package/dist/text/format-byte-size.js +25 -0
- package/dist/text/format-timestamp.d.ts +22 -0
- package/dist/text/format-timestamp.js +57 -0
- package/dist/text/index.d.ts +12 -0
- package/dist/text/index.js +9 -0
- package/dist/text/is-abort-error.d.ts +5 -0
- package/dist/text/is-abort-error.js +5 -0
- package/dist/text/mime.d.ts +5 -0
- package/dist/text/mime.js +21 -0
- package/dist/text/redact-urls.d.ts +7 -0
- package/dist/text/redact-urls.js +5 -0
- package/dist/text/resolve-active-tab-id.d.ts +13 -0
- package/dist/text/resolve-active-tab-id.js +15 -0
- package/dist/text/sanitize-untrusted-text.d.ts +1 -1
- package/dist/text/sanitize-untrusted-text.js +2 -1
- package/dist/text/tagged-text-suppression.d.ts +103 -0
- package/dist/text/tagged-text-suppression.js +143 -0
- package/dist/text/template-i18n.d.ts +37 -0
- package/dist/text/template-i18n.js +48 -0
- package/dist/tool-call-text.d.ts +59 -0
- package/dist/tool-call-text.js +62 -0
- package/dist/tool-input-envelope.js +8 -4
- package/dist/tool-input-normalization.js +8 -1
- package/dist/tool-input-repairs.d.ts +58 -0
- package/dist/tool-input-repairs.js +154 -0
- package/dist/tool-tokens.js +1 -1
- package/dist/user-facing-error.d.ts +1 -1
- package/dist/user-facing-error.js +3 -1
- package/package.json +234 -13
- package/dist/settings/express/contracts.js +0 -2
- package/dist/settings/express/http-request.d.ts +0 -33
- package/dist/settings/express/http-request.js +0 -50
- package/dist/settings/express/http.d.ts +0 -10
- package/dist/settings/express/http.js +0 -196
- package/dist/settings/express/index.d.ts +0 -5
- package/dist/settings/express/index.js +0 -4
- package/dist/settings/express/shared.d.ts +0 -68
- package/dist/settings/express/stream.d.ts +0 -24
- package/dist/settings/express/stream.js +0 -171
package/dist/redact.js
CHANGED
|
@@ -31,309 +31,8 @@
|
|
|
31
31
|
* - AWS access key shape: 'AKIA' + 16 uppercase alphanumerics.
|
|
32
32
|
* - Luhn algorithm (credit cards): https://en.wikipedia.org/wiki/Luhn_algorithm
|
|
33
33
|
*/
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
export const PEM_PATTERN_NAME = "PEM private key block";
|
|
37
|
-
const PRIVATE_KEY_HEADER = /-----BEGIN ([A-Z ]*)PRIVATE KEY-----/;
|
|
38
|
-
// Consume the body before any token/label rule can erase the delimiters. A missing footer
|
|
39
|
-
// masks through EOF; a different key type's footer cannot close this block.
|
|
40
|
-
const PRIVATE_KEY_BLOCK = /-----BEGIN ([A-Z ]*)PRIVATE KEY-----[\s\S]*?(?:-----END \1PRIVATE KEY-----|$)/;
|
|
41
|
-
// Share data between static scans and runtime redactors without importing a CLI entry point:
|
|
42
|
-
// top-level argv/path handling in a scanner can crash a daemon that imports it. Keeping the
|
|
43
|
-
// vocabulary dependency-free also avoids making core redaction depend on feature code.
|
|
44
|
-
// Match each vendor's actual alphabet. Fixed-length patterns need lookaround boundaries so a
|
|
45
|
-
// credential-shaped substring of a longer inert value is not mistaken for a complete secret.
|
|
46
|
-
export const SECRET_SHAPE_PATTERNS = [
|
|
47
|
-
{ name: "Google API key (AIza)", pattern: /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9_-])/ },
|
|
48
|
-
{ name: "Anthropic API key (sk-ant-)", pattern: /(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{90,}/ },
|
|
49
|
-
{ name: "generic sk- secret key (OpenAI-shaped)", pattern: /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{40,}/ },
|
|
50
|
-
{ name: "GitHub personal access token (classic, ghp_)", pattern: /(?<!\w)ghp_\w{36}(?!\w)/ },
|
|
51
|
-
{ name: "GitHub OAuth token (gho_)", pattern: /(?<!\w)gho_\w{36}(?!\w)/ },
|
|
52
|
-
{ name: "GitHub fine-grained PAT", pattern: /(?<!\w)github_pat_\w{80,}/ },
|
|
53
|
-
{ name: "npm access token", pattern: /(?<!\w)npm_\w{36}(?!\w)/ },
|
|
54
|
-
{ name: "Slack token", pattern: /(?<![A-Za-z0-9-])xox[baprs]-[A-Za-z0-9-]{12,}/ },
|
|
55
|
-
{ name: "AWS access key ID", pattern: /(?<![0-9A-Z])AKIA[0-9A-Z]{16}(?![0-9A-Z])/ },
|
|
56
|
-
{ name: "Fastmail app password (fm2_)", pattern: /(?<![A-Za-z0-9+/=])fm2_[A-Za-z0-9+/=]{20,}/ },
|
|
57
|
-
{ name: PEM_PATTERN_NAME, pattern: PRIVATE_KEY_BLOCK },
|
|
58
|
-
];
|
|
59
|
-
/**
|
|
60
|
-
* Suppress PEM bodies across complete, ordered text lines before other redactors run.
|
|
61
|
-
* @param _required No ambient state; create one instance per framed output stream.
|
|
62
|
-
* @param _options Reserved optional policy inputs.
|
|
63
|
-
* @returns A line redactor and an EOF reset. Call reset after flushing the final line so a
|
|
64
|
-
* replacement child cannot inherit an unterminated block. Does not frame raw chunks or do I/O.
|
|
65
|
-
* @complexity O(n) per line; O(h) retained state for the open header's key type of length h.
|
|
66
|
-
* @example const keys = createPrivateKeyLineRedactor({}, {}); keys.redact({ text: line }, {});
|
|
67
|
-
*/
|
|
68
|
-
export function createPrivateKeyLineRedactor(_required, _options = {}) {
|
|
69
|
-
let footer;
|
|
70
|
-
return {
|
|
71
|
-
redact({ text }, _optional = {}) {
|
|
72
|
-
let remaining = text;
|
|
73
|
-
let out = '';
|
|
74
|
-
while (remaining) {
|
|
75
|
-
if (footer !== undefined) {
|
|
76
|
-
const end = remaining.indexOf(footer);
|
|
77
|
-
if (end === -1)
|
|
78
|
-
return out;
|
|
79
|
-
remaining = remaining.slice(end + footer.length);
|
|
80
|
-
footer = undefined;
|
|
81
|
-
}
|
|
82
|
-
const header = PRIVATE_KEY_HEADER.exec(remaining);
|
|
83
|
-
if (!header)
|
|
84
|
-
return out + remaining;
|
|
85
|
-
out += remaining.slice(0, header.index) + '[REDACTED:credential]';
|
|
86
|
-
footer = `-----END ${header[1]}PRIVATE KEY-----`;
|
|
87
|
-
remaining = remaining.slice(header.index + header[0].length);
|
|
88
|
-
}
|
|
89
|
-
return out;
|
|
90
|
-
},
|
|
91
|
-
reset(_input, _optional = {}) { footer = undefined; },
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
/** Broad token shapes for agent-failure text; consumers retain their plain [REDACTED] pipeline. */
|
|
95
|
-
const AGENT_FAILURE_TOKEN_SHAPES = [
|
|
96
|
-
/AIza[\w-]+/, // Google API key
|
|
97
|
-
/AQ\.[\w.\/-]+/, // AI Studio key
|
|
98
|
-
/sk-[\w.-]+/, // OpenAI-style secret key
|
|
99
|
-
/gh[pousr]_\w+/, // GitHub token
|
|
100
|
-
/github_pat_\w+/, // GitHub fine-grained token
|
|
101
|
-
/ya29\.[\w.-]+/, // Google OAuth access token
|
|
102
|
-
/eyJ[\w-]+\.[\w-]+(?:\.[\w-]+)?/, // JWT
|
|
103
|
-
];
|
|
104
|
-
export const AGENT_FAILURE_SECRET_SHAPE_RE = new RegExp(`\\b(?:${AGENT_FAILURE_TOKEN_SHAPES.map((shape) => shape.source).join('|')})`, 'g');
|
|
105
|
-
/**
|
|
106
|
-
* Exact path SEGMENT names refused at any depth, matched case-insensitively against each segment
|
|
107
|
-
* of the caller-supplied path (never a substring — a directory named `not-secrets-actually` is not
|
|
108
|
-
* a match). `secrets` is the owner's explicit example: whatever a site or app tree names its
|
|
109
|
-
* credentials folder (`sites/**\/secrets/`, `app/**\/secrets/`, or anywhere else), it never
|
|
110
|
-
* becomes reachable through this domain. A denied segment is refused by the guarded reader
|
|
111
|
-
* AND skipped entirely by the `fs_list_files` walk — its contents are never even enumerated,
|
|
112
|
-
* not merely refused once named. Besides `secrets`, the set names the
|
|
113
|
-
* well-known credential-store directories a home-directory `custom` root can expose: `.aws`
|
|
114
|
-
* (`credentials`), `.docker` (`config.json` with registry auth), `.kube` (`config`), and
|
|
115
|
-
* `gcloud`/`gh` for `.config/gcloud/application_default_credentials.json` and
|
|
116
|
-
* `.config/gh/hosts.yml`. Denied by SEGMENT rather than by leaf filename on purpose: `config`,
|
|
117
|
-
* `config.json`, and `hosts.yml` are generic names that appear harmlessly elsewhere, so denying the
|
|
118
|
-
* directory is the narrower of the two mistakes.
|
|
119
|
-
*
|
|
120
|
-
* A host's install-wide site-key directory (2026-09-24) needs the same protection; the host appends it.
|
|
121
|
-
* Production stores it beside individual site folders on a durable volume; local/dev stores
|
|
122
|
-
* it below the home directory, reachable through an operator-set `custom` root. Its key backs
|
|
123
|
-
* site-key administration, webhook/newsletter signing secrets, and permission checks, so the
|
|
124
|
-
* agent must never read it from disk. Denying the whole directory segment, rather than only
|
|
125
|
-
* a generated key filename, also prevents `fs_list_files` from enumerating its contents — the
|
|
126
|
-
* same "never even advertise it" property `secrets` gets above.
|
|
127
|
-
*/
|
|
128
|
-
// Generic credential-store segments only. A host adds its own product-specific key directory
|
|
129
|
-
// (e.g. its install-wide site-key folder) when it builds its deny-list; core stays product-neutral.
|
|
130
|
-
export const CREDENTIAL_FILE_DENY_SEGMENTS = ["secrets", ".aws", ".docker", ".kube", "gcloud", "gh"];
|
|
131
|
-
// A local tunnel has a loopback socket and may rewrite Host; refuse marker presence, even empty.
|
|
132
|
-
export const LOCAL_OWNER_PROXY_MARKER_PREFIXES = ["x-forwarded-", "x-envoy-", "x-ms-"];
|
|
133
|
-
export const LOCAL_OWNER_PROXY_MARKER_HEADERS = [
|
|
134
|
-
"forwarded", "x-real-ip", "via", "cf-connecting-ip", "true-client-ip", "x-original-host",
|
|
135
|
-
"x-client-ip", "x-cluster-client-ip", "fastly-client-ip", "tailscale-user-login", "x-original-forwarded-for",
|
|
136
|
-
];
|
|
137
|
-
// Order matters: list specific rules before more general ones. Langfuse
|
|
138
|
-
// keys (`sk-lf-...`) would otherwise be eaten by the generic `sk-...`
|
|
139
|
-
// rule and labeled as a generic OpenAI-style key.
|
|
140
|
-
// One IPv4 octet, 0-255, so junk shapes like 999.1.1.1 do not count.
|
|
141
|
-
const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)';
|
|
142
|
-
// Optional +country code, then a bare or parenthesized area code, with optional separators.
|
|
143
|
-
const PHONE_SEPARATOR = '[\\s.-]?';
|
|
144
|
-
const PHONE_COUNTRY_CODE = /(?:\+?\d{1,3}[\s.-]?)?/;
|
|
145
|
-
const PHONE_AREA_CODE = /(?:\(\d{3}\)|\d{3})/;
|
|
146
|
-
const PATTERNS = [
|
|
147
|
-
// Langfuse public/secret keys (pk-lf- / sk-lf-). Must run before the
|
|
148
|
-
// generic sk- rule so the more specific label wins.
|
|
149
|
-
{ name: 'langfuse_key', regex: /\b(?:pk|sk)-lf-[A-Za-z0-9-]{16,}\b/g },
|
|
150
|
-
// Anthropic / OpenAI-style keys: 'sk-' + optional sub-prefix + base64-ish.
|
|
151
|
-
// Both vendors plus a long tail of OpenAI-compatible providers (DeepSeek,
|
|
152
|
-
// MiniMax, Together, etc.) ship keys in this shape, so a single rule
|
|
153
|
-
// covers most "sk-..." secrets a user might paste into a prompt.
|
|
154
|
-
{ name: 'sk_key', regex: /\bsk-(?:proj-|live-|test-|ant-)?[A-Za-z0-9_-]{20,}\b/g },
|
|
155
|
-
// GitHub personal / OAuth / server / user-server / refresh tokens.
|
|
156
|
-
{ name: 'github_token', regex: /\bgh[opsur]_[A-Za-z0-9]{36,}\b/g },
|
|
157
|
-
// GitHub legacy 40-hex personal access tokens that ship with no prefix
|
|
158
|
-
// are indistinguishable from a sha1 hash, so we don't try to match them
|
|
159
|
-
// here — false positives would be brutal in commit logs / artifact slugs.
|
|
160
|
-
// AWS access key id. The matching secret access key is just 40 base64
|
|
161
|
-
// chars with no fixed shape, so we cannot reliably redact it without
|
|
162
|
-
// huge collateral damage; flagging the access key id at least
|
|
163
|
-
// signals a paste happened.
|
|
164
|
-
{ name: 'aws_access_key', regex: /\bAKIA[0-9A-Z]{16}\b/g },
|
|
165
|
-
// Google API keys — legacy AIza… (Maps / AI Studio) and service-account-
|
|
166
|
-
// bound AQ.… keys AI Studio now issues. AQ. must run before the generic
|
|
167
|
-
// sk_ rule would mis-label unrelated tokens.
|
|
168
|
-
{ name: 'google_api_key', regex: /\bAQ\.[A-Za-z0-9_-]{20,}\b/g },
|
|
169
|
-
{ name: 'google_api_key', regex: /\bAIza[0-9A-Za-z_-]{35}\b/g },
|
|
170
|
-
// Slack tokens.
|
|
171
|
-
{ name: 'slack_token', regex: /\bxox[abprs]-[0-9A-Za-z-]{10,}\b/g },
|
|
172
|
-
// Stripe keys.
|
|
173
|
-
{ name: 'stripe_key', regex: /\b(?:sk|pk|rk)_(?:live|test)_[0-9a-zA-Z]{16,}\b/g },
|
|
174
|
-
// JSON Web Tokens. The "header.payload.signature" triple is distinctive
|
|
175
|
-
// enough that false positives are rare (the literal "eyJ" prefix is the
|
|
176
|
-
// base64 encoding of '{"' which is how every JOSE header starts).
|
|
177
|
-
{ name: 'jwt', regex: /(?<!\w)(?<!(?<!\w)eyJ[A-Za-z0-9_-]*?)eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g },
|
|
178
|
-
// Bearer tokens in HTTP Authorization header copy/paste. We only match
|
|
179
|
-
// the value, not the literal 'Bearer ', so the marker stays readable in
|
|
180
|
-
// the redacted output ("Authorization: Bearer [REDACTED:bearer_token]").
|
|
181
|
-
// The leading lookahead only lets the lookbehind run where a value can start, so a long
|
|
182
|
-
// whitespace run is not rescanned from every position inside it.
|
|
183
|
-
{ name: 'bearer_token', regex: /(?=[A-Za-z0-9._~+/-])(?<=\bBearer\s+)[A-Za-z0-9._~+/-]{16,}={0,2}/g },
|
|
184
|
-
// Email addresses. Conservative enough to require a TLD-like trailer. The local part is
|
|
185
|
-
// bounded at the RFC 5321 limit of 64: an unbounded run rescanned the suffix from every word
|
|
186
|
-
// boundary, so `'a.'.repeat(20000)` blocked ~3 s on a large tool response. Matching starts at
|
|
187
|
-
// the `@` and reads the local part in a lookbehind (captured as `local`): starting at every word
|
|
188
|
-
// boundary still cost up to 64 steps per position, ~2.5 s on 10 MiB of `'eyJ-'`.
|
|
189
|
-
// Alphabetic TLDs preserve versioned package paths in error stacks (e.g. pkg@1.2.3).
|
|
190
|
-
{ name: 'email', regex: /@(?<=\b(?<local>[\w.+-]{1,64})@)(?:[\w-]+\.)+[A-Za-z]{2,}\b/g },
|
|
191
|
-
// IPv4. Reject all-zero / 255.255.255.255-ish junk shapes by gating on
|
|
192
|
-
// each octet being 0-255.
|
|
193
|
-
{
|
|
194
|
-
name: 'ipv4',
|
|
195
|
-
regex: new RegExp(`\\b(?:${IPV4_OCTET}\\.){3}${IPV4_OCTET}\\b`, 'g'),
|
|
196
|
-
},
|
|
197
|
-
// Phone numbers. Tight US-leaning shape; a global PII detector would
|
|
198
|
-
// need a real lib. We keep this so US-based test prompts ('call me at
|
|
199
|
-
// (415) 555-...') don't ship. Note: no leading \b — '(' isn't a word
|
|
200
|
-
// char, so a starting boundary would refuse to match `(415)`. Reject
|
|
201
|
-
// adjacent word characters or hyphens so digit segments of UUIDs,
|
|
202
|
-
// hashes and identifiers stay readable; separators within phones still match.
|
|
203
|
-
{
|
|
204
|
-
name: 'phone',
|
|
205
|
-
regex: new RegExp(`(?<![\\w-])${PHONE_COUNTRY_CODE.source}${PHONE_AREA_CODE.source}${PHONE_SEPARATOR}\\d{3}${PHONE_SEPARATOR}\\d{4}(?![\\w-])`, 'g'),
|
|
206
|
-
},
|
|
207
|
-
];
|
|
208
|
-
// Categories the pipeline names directly; pattern rules carry their own names. Masked-value
|
|
209
|
-
// checks and exact-secret masking derive the set of markers redact can generate from these
|
|
210
|
-
// plus the pattern names.
|
|
211
|
-
const CATEGORY = {
|
|
212
|
-
exactSecret: 'exact_secret',
|
|
213
|
-
credential: 'credential',
|
|
214
|
-
urlCredentials: 'url_credentials',
|
|
215
|
-
signedQuery: 'signed_query',
|
|
216
|
-
apiKeyHeader: 'api_key_header',
|
|
217
|
-
apiKeyQuery: 'api_key_query',
|
|
218
|
-
bearerToken: 'bearer_token',
|
|
219
|
-
labeledSecret: 'labeled_secret',
|
|
220
|
-
urlSecretParam: 'url_secret_param',
|
|
221
|
-
opaqueToken: 'opaque_token',
|
|
222
|
-
creditCard: 'credit_card',
|
|
223
|
-
};
|
|
224
|
-
// Only markers redact itself generates count as masked: arbitrary `[REDACTED:<text>]` would let
|
|
225
|
-
// echoed input such as `[REDACTED:<secret>]` keep the real secret. A fixed category alternation
|
|
226
|
-
// also bounds each marker attempt; `[^\]]*` rescanned the suffix after every unterminated
|
|
227
|
-
// `[REDACTED:`, which was quadratic on large tool responses.
|
|
228
|
-
const GENERATED_CATEGORIES = [...PATTERNS.map(({ name }) => name), ...Object.values(CATEGORY)];
|
|
229
|
-
function escapeRegExp(text) {
|
|
230
|
-
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
231
|
-
}
|
|
232
|
-
function markerSource(categories) {
|
|
233
|
-
return `\\[REDACTED:(?:${[...new Set(categories)].map(escapeRegExp).join('|')})\\]`;
|
|
234
|
-
}
|
|
235
|
-
const GENERATED_MARKER = markerSource(GENERATED_CATEGORIES);
|
|
236
|
-
/** Every marker redact can generate from its built-in categories; consumers normalize only these. */
|
|
237
|
-
export const GENERATED_MARKER_RE = new RegExp(GENERATED_MARKER, 'g');
|
|
238
|
-
// Credit card sweep is special: a naive 13-19 digit run matches a lot of
|
|
239
|
-
// non-card numbers (timestamps, IDs, hashes). We isolate the candidate
|
|
240
|
-
// then run a Luhn check before redacting.
|
|
241
|
-
const CARD_CANDIDATE = /\b(?:\d[ -]?){12,18}\d\b/g;
|
|
242
|
-
// Inspect/JSON credentials can contain spaces and escaped quotes; consume the entire value.
|
|
243
|
-
const QUOTED_SECRET_VALUE = String.raw `"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'`;
|
|
244
|
-
const API_KEY_HEADER = new RegExp(`(^|[^?&\\w])(["']?)(x-api-key|api-key|x-goog-api-key)\\2(\\s*[:=]\\s*)(${QUOTED_SECRET_VALUE}|[^\\s,;"'#}]+)`, 'gi');
|
|
245
|
-
const API_KEY_QUERY = /([?&](?:key|api_key|api-key)=)[^&#\s,;"']+/gi;
|
|
246
|
-
// The length guard and the per-digit `d < 0 || d > 9` guard from the origin
|
|
247
|
-
// were both dropped here (a documented deviation from the otherwise-verbatim
|
|
248
|
-
// port — see archived provenance ledger): `isLuhnValid` is private with exactly one call
|
|
249
|
-
// site (the `CARD_CANDIDATE.replace` callbacks below), and `CARD_CANDIDATE`'s
|
|
250
|
-
// own regex (`\b(?:\d[ -]?){12,18}\d\b`) already guarantees any string
|
|
251
|
-
// reaching here is 13-19 characters, and the preceding `match.replace(/\D/g,
|
|
252
|
-
// '')` strip guarantees every character is an ASCII digit — so both guards
|
|
253
|
-
// were provably unreachable, not speculative.
|
|
254
|
-
function isLuhnValid(digits) {
|
|
255
|
-
let sum = 0;
|
|
256
|
-
let alt = false;
|
|
257
|
-
for (let i = digits.length - 1; i >= 0; i -= 1) {
|
|
258
|
-
let d = digits.charCodeAt(i) - 48;
|
|
259
|
-
if (alt) {
|
|
260
|
-
d *= 2;
|
|
261
|
-
if (d > 9)
|
|
262
|
-
d -= 9;
|
|
263
|
-
}
|
|
264
|
-
sum += d;
|
|
265
|
-
alt = !alt;
|
|
266
|
-
}
|
|
267
|
-
return sum % 10 === 0;
|
|
268
|
-
}
|
|
269
|
-
// A labeled credential has its value masked even when too short to have a vendor token shape.
|
|
270
|
-
// Bare long opaque runs are opt-in CLI heuristics: UUIDs, hashes, model IDs and path segments
|
|
271
|
-
// share that alphabet, so the default telemetry policy must leave them readable. Whole
|
|
272
|
-
// correlation IDs, UPPER_SNAKE diagnostic codes and the delegated-tool route stay readable even in aggressive mode;
|
|
273
|
-
// appending secret characters defeats that exception. The host's ERR-XXXX-XXXX-XXXX-XXXX
|
|
274
|
-
// correlation ID uses uppercase hex and is meant to reach the model and be quoted to an
|
|
275
|
-
// operator; delegated-tool-calls is the route segment named in delegated tool failures.
|
|
276
|
-
// Matching the ENTIRE run keeps a secret glued onto either spelling redactable.
|
|
277
|
-
const SECRET_LABELS = 'authorization|bearer|api[-_]?key|access[-_]?token|refresh[-_]?token|client[-_]?secret|password|secret|cookie';
|
|
278
|
-
// Keep historical URL categories and the bounded sanitizer's vocabulary stable.
|
|
279
|
-
const SERIALIZED_SECRET_LABELS = `${SECRET_LABELS}|x[-_](?:goog[-_])?api[-_]?key|api key|token|set[-_]cookie|private[-_]?key`;
|
|
280
|
-
const EMPTY_QUOTED_ASSIGNMENT_RE = new RegExp(`\\b(?:${SERIALIZED_SECRET_LABELS})\\s*[:=]\\s*$`, 'i');
|
|
281
|
-
export const LABELED_SECRET_RE = new RegExp(`\\b(${SECRET_LABELS})\\b\\s*[:=]\\s*\\S+`, 'gi');
|
|
282
|
-
export const OPAQUE_TOKEN_RE = /[A-Za-z0-9_-]{20,}/g;
|
|
283
|
-
// Pattern parts, only ever used inside the anchored NON_SECRET_TOKEN_RE.
|
|
284
|
-
const CORRELATION_ID = 'ERR-[0-9A-F]{4}(?:-[0-9A-F]{4}){3}';
|
|
285
|
-
const UPPER_SNAKE_DIAGNOSTIC = '[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+';
|
|
286
|
-
export const NON_SECRET_TOKEN_RE = new RegExp(`^(?:${CORRELATION_ID}|delegated-tool-calls|${UPPER_SNAKE_DIAGNOSTIC})$`);
|
|
287
|
-
// Runtime markers must survive a second pass; the bounded sanitizer deliberately retains
|
|
288
|
-
// its historical lowercase marker contract and uses the unmodified lexical vocabulary.
|
|
289
|
-
// Reject a masked header/query value before matching, so a following field's credential
|
|
290
|
-
// remains available to the global scan rather than being consumed beside the marker.
|
|
291
|
-
// Only the value's first character is matched; forward-only finders supply its end (see
|
|
292
|
-
// labelValueExtents). Matching `\S+` and rewinding to skip a covered field rescanned the rest of
|
|
293
|
-
// the run per label: quadratic on `'api-key=x;'.repeat(n)`.
|
|
294
|
-
// Bare URL key/token parameters already have owners; leave their empty values and categories
|
|
295
|
-
// to those collectors instead of treating the following `&page=...` as a label's value.
|
|
296
|
-
const RUNTIME_SECRET_LABELS = `${SERIALIZED_SECRET_LABELS}|(?<![?&])(?:key)`;
|
|
297
|
-
const MASK_AWARE_LABELED_SECRET_RE = new RegExp(`(?<![\\w-])(["']?)(${RUNTIME_SECRET_LABELS})\\1\\s*[:=]\\s*`
|
|
298
|
-
+ `(?!Bearer\\s+\\S)(?!${GENERATED_MARKER}[;&])((?!&)\\S)`, 'gi');
|
|
299
|
-
// A label can name another label; resume at it instead of consuming `token:` and leaking its value.
|
|
300
|
-
const CHAINED_LABEL_RE = new RegExp(`(?:${RUNTIME_SECRET_LABELS})\\b["']?\\s*[:=]\\s*(?=\\S)`, 'iy');
|
|
301
|
-
// Provider failures also echo short bearer values. Exclude our own marker on subsequent passes.
|
|
302
|
-
// The value is read in a lookahead so the scan resumes at it (`Bearer Bearer x` masks both),
|
|
303
|
-
// as the earlier lookbehind form did, without a lookbehind test at every position.
|
|
304
|
-
// Quotes and field delimiters end the value; punctuation such as `!` remains credential text.
|
|
305
|
-
const SHORT_BEARER_RE = new RegExp(`Bearer\\s+["']?(?!${GENERATED_MARKER}(?=$|[\\s"',;<>}]))(?=([^\\s"',;<>}]+))`, 'gi');
|
|
306
|
-
const BASIC_AUTH_RE = /\bauthorization["']?\s*[:=]\s*["']?(Basic\s+[^\s"',;}]+)/gi;
|
|
307
|
-
// Cookie pairs belong to one header value, including pairs after a semicolon and a space.
|
|
308
|
-
const COOKIE_HEADER_RE = /\bcookie\s*:\s*([^\r\n]+)/gi;
|
|
309
|
-
const PROVIDER_API_KEY_QUERY = /([?&]key=)([^&\s"']+)/gi;
|
|
310
|
-
// URL userinfo and signed query values have explicit credential context; unlike opaque runs,
|
|
311
|
-
// they are safe to recognize in the conservative policy. Keep scheme/host and query names
|
|
312
|
-
// readable for debugging without exposing credentials that authorize access to the resource.
|
|
313
|
-
// Matching starts at `//` and reads the userinfo forward to `@` within the authority. No scheme
|
|
314
|
-
// scan is needed, so a scheme of any length (glued text included) cannot hide its userinfo:
|
|
315
|
-
// an unbounded scheme run rescanned the suffix from every start
|
|
316
|
-
// (`'a.'.repeat(20000)` blocked ~3.6 s), trying a bounded scheme at every position cost ~2 s on
|
|
317
|
-
// 10 MiB of `'eyJ-'`, and a 32-character scheme lookbehind missed longer schemes.
|
|
318
|
-
// The same authority syntax also appears in scheme-relative URLs (`//user:pw@host`).
|
|
319
|
-
const URL_CREDENTIALS_RE = /\/\/([^/\s?#@]+)@/g;
|
|
320
|
-
const SIGNED_QUERY_RE = /([?&](?:signature|sig|x-amz-signature|x-goog-signature|access_token|refresh_token)=)([^&#\s,;"']+)/gi;
|
|
321
|
-
// A secret word must END a name segment (split at . _ - or the name's end): api_key, apiKey,
|
|
322
|
-
// authtoken, X-Amz-Signature and custom.Token-value are masked, while author, keyword, design,
|
|
323
|
-
// signup and page stay readable. Names that merely end in a secret word (zipcode, error_code,
|
|
324
|
-
// monkey) are masked too; over-masking a URL value is the cheaper failure. Empty values stay.
|
|
325
|
-
// Match through a trailing fragment; field separators (&/;), quotes, parentheses or whitespace end it.
|
|
326
|
-
// Both name runs are bounded so a long separator-free run costs linear time, not quadratic.
|
|
327
|
-
const URL_SECRET_WORDS = 'token|key|secret|signature|sig|code|password|passwd|pwd|auth|authorization|credential';
|
|
328
|
-
const URL_SECRET_PARAM_RE = new RegExp(`[?&#;]([\\w.-]{0,128}?(?:${URL_SECRET_WORDS})s?(?=[._=-])[\\w.-]{0,128})=[^&;\\s"'<>()]+`, 'gi');
|
|
329
|
-
// A parameter the labeled rule already names (password, client_secret, ...) keeps that category.
|
|
330
|
-
const LABELED_URL_PARAM_NAME_RE = new RegExp(`(?:^|[.-])(?:${SECRET_LABELS})$`, 'i');
|
|
331
|
-
// Only an entire generated marker is already masked. A secret glued onto marker-like text still
|
|
332
|
-
// needs masking; a substring check would preserve credential suffixes in echoed header/query values.
|
|
333
|
-
const MASKED_VALUE_RE = new RegExp(`^["']?${GENERATED_MARKER}["']?$`);
|
|
334
|
-
function isMaskedValue(value) {
|
|
335
|
-
return MASKED_VALUE_RE.test(value);
|
|
336
|
-
}
|
|
34
|
+
import { collectSpans } from './redaction-collectors.js';
|
|
35
|
+
import { mergeSpans } from './redaction-spans.js';
|
|
337
36
|
/**
|
|
338
37
|
* Returns `input` with every recognised secret / PII pattern replaced by a
|
|
339
38
|
* `[REDACTED:<kind>]` marker. Under the default policies, idempotent — re-running on already redacted
|
|
@@ -350,59 +49,6 @@ function isMaskedValue(value) {
|
|
|
350
49
|
export function redactSecrets({ input }, options = {}) {
|
|
351
50
|
return redactSecretsWithCounts({ input }, options).redacted;
|
|
352
51
|
}
|
|
353
|
-
/**
|
|
354
|
-
* Universal diagnostic text for any thrown value. Keeps native stacks and structured metadata,
|
|
355
|
-
* then applies the shared credential policy (PII stays readable unless explicitly requested).
|
|
356
|
-
* Diagnostic getters, serialization and coercion can themselves fail; fixed fallback text keeps
|
|
357
|
-
* those failures from replacing the original error or interrupting the caller's recovery.
|
|
358
|
-
* @param required.error - Untrusted thrown value; never mutated.
|
|
359
|
-
* @param options - Shared redaction options, including caller-owned exact secrets.
|
|
360
|
-
* @returns Redacted text; never throws, including for circular objects and hostile accessors.
|
|
361
|
-
* @complexity O(n) serialization in the diagnostic's fields/characters, plus shared redaction passes.
|
|
362
|
-
*/
|
|
363
|
-
export function formatErrorForLog(required, options = {}) {
|
|
364
|
-
try {
|
|
365
|
-
const { error } = required;
|
|
366
|
-
let text;
|
|
367
|
-
if (error instanceof Error) {
|
|
368
|
-
const message = String(error.message);
|
|
369
|
-
text = String(error.stack ?? `${error.name}: ${message}`);
|
|
370
|
-
if (!text.includes(message))
|
|
371
|
-
text += `\n${message}`;
|
|
372
|
-
const fields = Object.fromEntries(Object.getOwnPropertyNames(error)
|
|
373
|
-
.filter(key => !['name', 'message', 'stack'].includes(key)).map(key => [key, Reflect.get(error, key)]));
|
|
374
|
-
if (Object.keys(fields).length)
|
|
375
|
-
text += `\n${diagnosticJson({ error: fields }, options)}`;
|
|
376
|
-
}
|
|
377
|
-
else {
|
|
378
|
-
text = error !== null && typeof error === 'object' ? diagnosticJson({ error }, options) : String(error);
|
|
379
|
-
}
|
|
380
|
-
return redactSecrets({ input: text }, { redactPii: false, ...options });
|
|
381
|
-
}
|
|
382
|
-
catch {
|
|
383
|
-
return '[Unformattable error]';
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
/** JSON preserves structured fields without coercing objects; track cycles and native Error fields.
|
|
387
|
-
* Property access remains inside formatErrorForLog's recovery boundary. O(n) visited fields. */
|
|
388
|
-
function diagnosticJson({ error }, options = {}) {
|
|
389
|
-
const seen = new WeakSet();
|
|
390
|
-
return JSON.stringify(error, (_key, value) => {
|
|
391
|
-
if (value !== null && typeof value === 'object') {
|
|
392
|
-
if (seen.has(value))
|
|
393
|
-
return '[Circular]';
|
|
394
|
-
seen.add(value);
|
|
395
|
-
if (value instanceof Error)
|
|
396
|
-
return Object.fromEntries(Object.getOwnPropertyNames(value).map(key => [key, Reflect.get(value, key)]));
|
|
397
|
-
}
|
|
398
|
-
// Scrub string contents before JSON escapes their credential labels. Exact-only is kept
|
|
399
|
-
// for the final pass so a caller's literal marker is never reprocessed as a supplied secret.
|
|
400
|
-
if (typeof value === 'string' && options.policy !== 'exact-only') {
|
|
401
|
-
return redactSecrets({ input: value }, { redactPii: false, ...options });
|
|
402
|
-
}
|
|
403
|
-
return typeof value === 'bigint' ? String(value) : value;
|
|
404
|
-
}) ?? String(error);
|
|
405
|
-
}
|
|
406
52
|
/**
|
|
407
53
|
* Same as {@link redactSecrets} but also returns per-category counts so the
|
|
408
54
|
* caller can attach an audit summary to the trace metadata ('we stripped 2
|
|
@@ -434,474 +80,4 @@ export function redactSecretsWithCounts({ input }, options = {}) {
|
|
|
434
80
|
}
|
|
435
81
|
return { redacted: redacted + input.slice(cursor), counts };
|
|
436
82
|
}
|
|
437
|
-
/** Every rule's spans over the original text, in rule-precedence order (see {@link mergeSpans}). */
|
|
438
|
-
function collectSpans({ text }, options) {
|
|
439
|
-
const spans = [];
|
|
440
|
-
const add = (start, end, category, suffix) => {
|
|
441
|
-
if (end > start || (end === start && suffix !== undefined))
|
|
442
|
-
spans.push({ start, end, category, suffix });
|
|
443
|
-
};
|
|
444
|
-
if (options.policy === 'exact-only') {
|
|
445
|
-
collectExactSecrets({ text, add, secrets: options.exactSecrets ?? [] }, { literalOnly: true });
|
|
446
|
-
return spans;
|
|
447
|
-
}
|
|
448
|
-
collectExactSecrets({ text, add, secrets: options.exactSecrets ?? [] });
|
|
449
|
-
// Whole PEM blocks use the existing shared vocabulary; every rule sees their original delimiters.
|
|
450
|
-
collectEmptyQuotedAssignments({ text, add });
|
|
451
|
-
collectUrlCredentials({ text, add });
|
|
452
|
-
collectPatterns({ text, add, patterns: credentialPatterns(options.extraPatterns ?? []) });
|
|
453
|
-
collectKeyedCredentials({ text, add });
|
|
454
|
-
collectLabeledSecrets({ text, add }, spans);
|
|
455
|
-
if (options.policy === 'aggressive')
|
|
456
|
-
collectOpaqueTokens({ text, add }, new Set(options.diagnosticToolIds));
|
|
457
|
-
if (options.redactPii !== false)
|
|
458
|
-
collectPii({ text, add }, spans);
|
|
459
|
-
return spans;
|
|
460
|
-
}
|
|
461
|
-
/** Orders spans and merges overlapping or adjacent ones; masking whole merged runs means no rule's
|
|
462
|
-
* leftover can expose part of another rule's value.
|
|
463
|
-
* Category rule: the longest constituent span names the merged span; on a tie the earlier rule in
|
|
464
|
-
* {@link collectSpans} wins, so an exact rule labels a known secret it matches exactly
|
|
465
|
-
* (`t=<known-token>` stays `exact_secret`) and the exact-secret category marks what only it covers.
|
|
466
|
-
* @complexity O(k) time and space for k spans (string offsets fit in unsigned 32 bits). */
|
|
467
|
-
function mergeSpans(spans, { keepAdjacent = false } = {}) {
|
|
468
|
-
const merged = [];
|
|
469
|
-
for (const rank of orderedSpanRanks({ spans })) {
|
|
470
|
-
const span = spans[rank];
|
|
471
|
-
const length = span.end - span.start;
|
|
472
|
-
const last = merged.at(-1);
|
|
473
|
-
if (!last || startsSeparateSpan({ start: span.start, end: last.end, keepAdjacent })) {
|
|
474
|
-
merged.push({ start: span.start, end: span.end, category: span.category, suffix: span.suffix, rank, categoryLength: length });
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
if (span.end >= last.end)
|
|
478
|
-
last.suffix = span.suffix;
|
|
479
|
-
last.end = Math.max(last.end, span.end);
|
|
480
|
-
if (length > last.categoryLength || (length === last.categoryLength && rank < last.rank)) {
|
|
481
|
-
Object.assign(last, { category: span.category, rank, categoryLength: length });
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
return merged;
|
|
485
|
-
}
|
|
486
|
-
/** Literal-only replacements preserve adjacent occurrences as distinct markers and counts. */
|
|
487
|
-
function startsSeparateSpan({ start, end, keepAdjacent }, _options = {}) {
|
|
488
|
-
return keepAdjacent ? start >= end : start > end;
|
|
489
|
-
}
|
|
490
|
-
/** Stable byte-wise radix order of span starts; ranks retain the original rule precedence.
|
|
491
|
-
* Dense labels produce millions of spans: sorting cloned objects both cost k log k and amplified
|
|
492
|
-
* GC. Four counting passes over integer ranks avoid those clones and bound work to O(k), with
|
|
493
|
-
* O(k) scratch space. JavaScript string offsets fit in 32 bits. No caller-owned data is mutated. */
|
|
494
|
-
function orderedSpanRanks({ spans }) {
|
|
495
|
-
let ranks = Uint32Array.from(spans, (_span, rank) => rank);
|
|
496
|
-
let scratch = new Uint32Array(ranks.length);
|
|
497
|
-
const offsets = new Uint32Array(256);
|
|
498
|
-
for (let shift = 0; shift < 32; shift += 8) {
|
|
499
|
-
offsets.fill(0);
|
|
500
|
-
for (const rank of ranks) {
|
|
501
|
-
const bucket = (spans[rank].start >>> shift) & 255;
|
|
502
|
-
offsets[bucket] = (offsets[bucket] ?? 0) + 1;
|
|
503
|
-
}
|
|
504
|
-
let total = 0;
|
|
505
|
-
for (let bucket = 0; bucket < offsets.length; bucket++) {
|
|
506
|
-
const count = offsets[bucket] ?? 0;
|
|
507
|
-
offsets[bucket] = total;
|
|
508
|
-
total += count;
|
|
509
|
-
}
|
|
510
|
-
for (const rank of ranks) {
|
|
511
|
-
const bucket = (spans[rank].start >>> shift) & 255;
|
|
512
|
-
const position = offsets[bucket] ?? 0;
|
|
513
|
-
scratch[position] = rank;
|
|
514
|
-
offsets[bucket] = position + 1;
|
|
515
|
-
}
|
|
516
|
-
[ranks, scratch] = [scratch, ranks];
|
|
517
|
-
}
|
|
518
|
-
return ranks;
|
|
519
|
-
}
|
|
520
|
-
/** Adds one span per match of `regex`; `spanOf` maps a match to its value range, or skips it. */
|
|
521
|
-
function collectMatches({ text, add }, regex, spanOf) {
|
|
522
|
-
// Clone so a caller-owned or shared regex never carries lastIndex state across requests;
|
|
523
|
-
// non-global extra patterns use the same every-occurrence contract as the built-ins.
|
|
524
|
-
const flags = regex.flags.includes('g') ? regex.flags : `${regex.flags}g`;
|
|
525
|
-
for (const match of text.matchAll(new RegExp(regex.source, flags))) {
|
|
526
|
-
const span = spanOf(match, match.index ?? 0);
|
|
527
|
-
if (span)
|
|
528
|
-
add(span.start, span.end, span.category);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
/** Span of the match's trailing capture `group`, unless that value is already a generated marker
|
|
532
|
-
* (already masked values are not new credentials and should not inflate the audit count). */
|
|
533
|
-
function trailingValue(category, group) {
|
|
534
|
-
return (match, index) => {
|
|
535
|
-
const value = match[group] ?? '';
|
|
536
|
-
if (isMaskedValue(value))
|
|
537
|
-
return undefined;
|
|
538
|
-
const end = index + match[0].length;
|
|
539
|
-
return { start: end - value.length, end, category };
|
|
540
|
-
};
|
|
541
|
-
}
|
|
542
|
-
// PII rules are collected last (after credential and opt-in opaque rules) and only when PII
|
|
543
|
-
// redaction is on; splitting once keeps each list in PATTERNS order.
|
|
544
|
-
const PII_PATTERN_NAMES = ['email', 'ipv4', 'phone'];
|
|
545
|
-
const NON_PII_PATTERNS = PATTERNS.filter((pattern) => !PII_PATTERN_NAMES.includes(pattern.name));
|
|
546
|
-
const PII_PATTERNS = PATTERNS.filter((pattern) => PII_PATTERN_NAMES.includes(pattern.name));
|
|
547
|
-
/** Built-in credential rules, then the static-scan shapes (labeled `credential`), then the caller's extra rules. */
|
|
548
|
-
function credentialPatterns(extraPatterns) {
|
|
549
|
-
return [
|
|
550
|
-
...NON_PII_PATTERNS,
|
|
551
|
-
...SECRET_SHAPE_PATTERNS.map((shape) => ({ name: CATEGORY.credential, regex: shape.pattern })),
|
|
552
|
-
...extraPatterns,
|
|
553
|
-
];
|
|
554
|
-
}
|
|
555
|
-
function collectPatterns({ text, add, patterns }) {
|
|
556
|
-
for (const { name, regex } of patterns) {
|
|
557
|
-
collectMatches({ text, add }, regex, (match, index) => ({ start: index, end: index + match[0].length, category: name }));
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
/** URL userinfo and signed query values: credentials recognized by their URL context. */
|
|
561
|
-
function collectUrlCredentials(pass) {
|
|
562
|
-
collectMatches(pass, URL_CREDENTIALS_RE, (match, index) => {
|
|
563
|
-
const userinfo = match[1] ?? '';
|
|
564
|
-
if (isMaskedValue(userinfo))
|
|
565
|
-
return undefined;
|
|
566
|
-
const start = index + '//'.length;
|
|
567
|
-
return { start, end: start + userinfo.length, category: CATEGORY.urlCredentials };
|
|
568
|
-
});
|
|
569
|
-
collectMatches(pass, SIGNED_QUERY_RE, trailingValue(CATEGORY.signedQuery, 2));
|
|
570
|
-
}
|
|
571
|
-
/** Values named by a header, query parameter or bearer prefix. Each rule matches the original
|
|
572
|
-
* text, so overlapping rules (the provider query rule includes a fragment the core rule stops
|
|
573
|
-
* before) merge into one span instead of one leaving a credential suffix beside the other's marker. */
|
|
574
|
-
function collectKeyedCredentials(pass) {
|
|
575
|
-
collectApiKeyHeaders(pass);
|
|
576
|
-
collectMatches(pass, PROVIDER_API_KEY_QUERY, trailingValue(CATEGORY.apiKeyQuery, 2));
|
|
577
|
-
collectMatches(pass, API_KEY_QUERY, (match, index) => {
|
|
578
|
-
const start = index + (match[1] ?? '').length;
|
|
579
|
-
const end = index + match[0].length;
|
|
580
|
-
return isMaskedValue(match[0].slice(start - index)) ? undefined : { start, end, category: CATEGORY.apiKeyQuery };
|
|
581
|
-
});
|
|
582
|
-
collectMatches(pass, SHORT_BEARER_RE, (match, index) => {
|
|
583
|
-
const start = index + match[0].length;
|
|
584
|
-
return { start, end: start + (match[1] ?? '').length, category: CATEGORY.bearerToken };
|
|
585
|
-
});
|
|
586
|
-
collectMatches(pass, BASIC_AUTH_RE, trailingValue(CATEGORY.labeledSecret, 1));
|
|
587
|
-
collectMatches(pass, COOKIE_HEADER_RE, trailingValue(CATEGORY.labeledSecret, 1));
|
|
588
|
-
collectUrlSecretParams(pass);
|
|
589
|
-
}
|
|
590
|
-
/** Header values stop at their quotes; an empty quoted hint cannot borrow the next field.
|
|
591
|
-
* @complexity O(n) over input characters, no I/O. */
|
|
592
|
-
function collectApiKeyHeaders(pass) {
|
|
593
|
-
const hints = emptyAssignmentRanges(pass.text);
|
|
594
|
-
collectMatches(pass, API_KEY_HEADER, (match, index) => {
|
|
595
|
-
const labelStart = index + (match[1] ?? '').length;
|
|
596
|
-
if (hints.has(labelStart))
|
|
597
|
-
return undefined;
|
|
598
|
-
const value = match[5] ?? '';
|
|
599
|
-
if (isMaskedValue(value))
|
|
600
|
-
return undefined;
|
|
601
|
-
const end = index + match[0].length;
|
|
602
|
-
// A quoted value keeps its quotes around the marker.
|
|
603
|
-
const quoted = /^["']/.test(value) ? 1 : 0;
|
|
604
|
-
return { start: end - value.length + quoted, end: end - quoted, category: CATEGORY.apiKeyHeader };
|
|
605
|
-
});
|
|
606
|
-
}
|
|
607
|
-
/** Secret-named URL query/fragment values; values already masked keep their category. */
|
|
608
|
-
function collectUrlSecretParams(pass) {
|
|
609
|
-
collectMatches(pass, URL_SECRET_PARAM_RE, (match, index) => {
|
|
610
|
-
const separator = match[0].indexOf('=') + 1;
|
|
611
|
-
if (isMaskedValue(match[0].slice(separator)))
|
|
612
|
-
return undefined;
|
|
613
|
-
const category = LABELED_URL_PARAM_NAME_RE.test(match[1] ?? '') ? CATEGORY.labeledSecret : CATEGORY.urlSecretParam;
|
|
614
|
-
return { start: index + separator, end: index + match[0].length, category };
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
/** Label values (`password=...`): only the value is masked, so the label stays readable
|
|
618
|
-
* even when no whitespace separates it; a glued credential suffix fails the complete-marker check.
|
|
619
|
-
* A label whose value an earlier rule already masks (see {@link isCoveredField}) is skipped and the
|
|
620
|
-
* scan resumes at the value, so `api-key=x;password=y` and `?password=x&page=2` keep the following
|
|
621
|
-
* field instead of masking it beside the first value. A masked value resumes the scan past its end.
|
|
622
|
-
* @complexity O(n + k) for n chars and k earlier spans; each skip resumes past the label and value
|
|
623
|
-
* ends come from forward-only finders, so no run is rescanned. */
|
|
624
|
-
function collectLabeledSecrets({ text, add }, earlier) {
|
|
625
|
-
const covered = coveredLabelFields({ earlier });
|
|
626
|
-
const hints = emptyAssignmentRanges(text);
|
|
627
|
-
const extentOf = labelValueExtents(text);
|
|
628
|
-
const regex = new RegExp(MASK_AWARE_LABELED_SECRET_RE.source, MASK_AWARE_LABELED_SECRET_RE.flags);
|
|
629
|
-
const chained = new RegExp(CHAINED_LABEL_RE.source, CHAINED_LABEL_RE.flags);
|
|
630
|
-
const urlField = new RegExp(URL_SECRET_PARAM_RE.source, 'iy');
|
|
631
|
-
for (let match = regex.exec(text); match; match = regex.exec(text)) {
|
|
632
|
-
if (hints.has(match.index))
|
|
633
|
-
continue;
|
|
634
|
-
// The URL collector owns complete unquoted parameter values, including quote boundaries.
|
|
635
|
-
// A generic unquoted label would consume the URL's enclosing quote as a secret byte.
|
|
636
|
-
urlField.lastIndex = Math.max(0, match.index - 1);
|
|
637
|
-
if (urlField.exec(text)) {
|
|
638
|
-
regex.lastIndex = urlField.lastIndex;
|
|
639
|
-
continue;
|
|
640
|
-
}
|
|
641
|
-
const start = match.index + match[0].length - 1;
|
|
642
|
-
chained.lastIndex = start;
|
|
643
|
-
if (chained.test(text)) {
|
|
644
|
-
regex.lastIndex = start;
|
|
645
|
-
continue;
|
|
646
|
-
}
|
|
647
|
-
const value = extentOf(start);
|
|
648
|
-
if (covered(start, value) || isMaskedValue(text.slice(start, value.end))) {
|
|
649
|
-
regex.lastIndex = start;
|
|
650
|
-
continue;
|
|
651
|
-
}
|
|
652
|
-
addLabelValue({ text, add, start, value });
|
|
653
|
-
regex.lastIndex = value.end;
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
/** Preserve quoted diagnostic/JSON values, including the closing quote on truncated echoes. */
|
|
657
|
-
function addLabelValue({ text, add, start, value }) {
|
|
658
|
-
const quoted = value.quoted ? 1 : 0;
|
|
659
|
-
const closed = value.closingQuote === value.end - 1;
|
|
660
|
-
add(start + quoted, value.end - (quoted && closed ? 1 : 0), CATEGORY.labeledSecret, quoted ? (closed ? '' : text[start]) : undefined);
|
|
661
|
-
}
|
|
662
|
-
/** Index earlier spans once so each label's coverage check takes O(1), including dense headers.
|
|
663
|
-
* No I/O; O(k) time/space for k earlier spans. */
|
|
664
|
-
function coveredLabelFields({ earlier }) {
|
|
665
|
-
// Per earlier span start: the furthest end (scalars rather than per-start end lists:
|
|
666
|
-
// dense fields yield millions of spans). A separator proves coverage only at the full value end.
|
|
667
|
-
const furthest = new Map();
|
|
668
|
-
for (const { start, end } of earlier) {
|
|
669
|
-
furthest.set(start, Math.max(furthest.get(start) ?? end, end));
|
|
670
|
-
}
|
|
671
|
-
return (start, value) => {
|
|
672
|
-
const at = !value.quoted || furthest.has(start) ? start : start + 1;
|
|
673
|
-
return isCoveredField(furthest.get(at), value);
|
|
674
|
-
};
|
|
675
|
-
}
|
|
676
|
-
/** True when an earlier span starting at the label value (inside its opening quote, for a quoted
|
|
677
|
-
* value) masks it: `reach` is the furthest such span end.
|
|
678
|
-
* Inside quotes only the closing quote ends the value (`;` and `&` are value text:
|
|
679
|
-
* `password="sk-...;hunter2"` once left `hunter2`); unquoted values also need complete coverage
|
|
680
|
-
* so a provider-prefix rule ending at `;`/`&` cannot leave the rest of a secret visible. */
|
|
681
|
-
function isCoveredField(reach, { end, closingQuote }) {
|
|
682
|
-
const target = closingQuote === end - 1 ? closingQuote : end;
|
|
683
|
-
return (reach ?? -1) >= target;
|
|
684
|
-
}
|
|
685
|
-
/** Extent finder for label values whose starts increase between calls. An unquoted value runs to
|
|
686
|
-
* whitespace or a `;`/`&` followed by a new label (or end of text). Quotes inside an unquoted
|
|
687
|
-
* secret are secret bytes, not terminators. A quoted value runs through its closing quote (a backslash-escaped quote does not
|
|
688
|
-
* close it) and any text glued after it up to whitespace, `;`, `&` or `,` (`"abc def"hunter2` once
|
|
689
|
-
* left `hunter2`), or to the line end when the quote never closes, so spaces, `;` and `&` inside
|
|
690
|
-
* quotes stay in the value. Structured field delimiters after a closing quote stay readable.
|
|
691
|
-
* @complexity Amortized O(1) per call; all calls together scan the text once per finder. */
|
|
692
|
-
function labelValueExtents(text) {
|
|
693
|
-
const runEnd = forwardFinder(text, /\s|[;&](?=$|[\w.-]+\s*[:=])/);
|
|
694
|
-
const gluedEnd = forwardFinder(text, /[\s;&,}\]]/);
|
|
695
|
-
const lineEnd = forwardFinder(text, /[\r\n]/);
|
|
696
|
-
const closers = new Map([['"', unescapedQuoteFinder(text, /"/)], ["'", unescapedQuoteFinder(text, /'/)]]);
|
|
697
|
-
return (start) => {
|
|
698
|
-
const whitespace = runEnd(start);
|
|
699
|
-
const closer = closers.get(text[start] ?? '');
|
|
700
|
-
if (!closer)
|
|
701
|
-
return { end: whitespace, closingQuote: -1, quoted: false };
|
|
702
|
-
const closing = closer(start + 1);
|
|
703
|
-
const line = lineEnd(start);
|
|
704
|
-
return closing < text.length
|
|
705
|
-
? { end: quotedValueEnd({ text, closing, gluedEnd: gluedEnd(closing + 1) }), closingQuote: closing, quoted: true }
|
|
706
|
-
: { end: line, closingQuote: -1, quoted: true };
|
|
707
|
-
};
|
|
708
|
-
}
|
|
709
|
-
/** `forwardFinder` for a quote that skips backslash-escaped ones: an odd run of backslashes before a
|
|
710
|
-
* quote escapes it (`\\"` is an escaped backslash, then a real quote). Same non-decreasing `from` rule.
|
|
711
|
-
* @complexity O(n) over all calls: each quote's backslash run is counted once. */
|
|
712
|
-
function unescapedQuoteFinder(text, quote) {
|
|
713
|
-
const next = forwardFinder(text, quote);
|
|
714
|
-
let found = -1;
|
|
715
|
-
return (from) => {
|
|
716
|
-
if (from > found) {
|
|
717
|
-
found = next(from);
|
|
718
|
-
while (found < text.length && isBackslashEscaped(text, found))
|
|
719
|
-
found = next(found + 1);
|
|
720
|
-
}
|
|
721
|
-
return found;
|
|
722
|
-
};
|
|
723
|
-
}
|
|
724
|
-
/** True when an odd run of backslashes ends right before `index`. */
|
|
725
|
-
function isBackslashEscaped(text, index) {
|
|
726
|
-
let backslashes = 0;
|
|
727
|
-
while (text[index - 1 - backslashes] === '\\')
|
|
728
|
-
backslashes++;
|
|
729
|
-
return backslashes % 2 === 1;
|
|
730
|
-
}
|
|
731
|
-
/** `find(from)`: the first index at or after `from` matching `pattern`, or `text.length`. `from` must
|
|
732
|
-
* not decrease between calls: one search answers every later `from` up to its result, since nothing
|
|
733
|
-
* matched between the earlier `from` and that result.
|
|
734
|
-
* @complexity O(n) over all calls for n chars. */
|
|
735
|
-
function forwardFinder(text, pattern) {
|
|
736
|
-
const regex = new RegExp(pattern.source, 'g');
|
|
737
|
-
let found = -1;
|
|
738
|
-
return (from) => {
|
|
739
|
-
if (from > found) {
|
|
740
|
-
regex.lastIndex = from;
|
|
741
|
-
found = regex.exec(text)?.index ?? text.length;
|
|
742
|
-
}
|
|
743
|
-
return found;
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
/** Opt-in bare opaque runs; whole trusted dotted IDs and non-secret diagnostic tokens stay readable. */
|
|
747
|
-
function collectOpaqueTokens({ text, add }, trustedIds) {
|
|
748
|
-
for (const token of text.matchAll(/[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*/g)) {
|
|
749
|
-
if (trustedIds.has(token[0]))
|
|
750
|
-
continue;
|
|
751
|
-
for (const run of token[0].matchAll(OPAQUE_TOKEN_RE)) {
|
|
752
|
-
if (NON_SECRET_TOKEN_RE.test(run[0]))
|
|
753
|
-
continue;
|
|
754
|
-
const start = (token.index ?? 0) + (run.index ?? 0);
|
|
755
|
-
add(start, start + run[0].length, CATEGORY.opaqueToken);
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
/** Email/IPv4/phone rules, then Luhn-checked card candidates. The email rule retains alphabetic TLDs so versioned paths stay readable. An "email" whose `@` ends URL userinfo
|
|
760
|
-
* (`scheme://user:pw@host`) is skipped: its local part is already the credential span, and
|
|
761
|
-
* merging it would mask the host, which stays readable for debugging. */
|
|
762
|
-
function collectPii(pass, earlier) {
|
|
763
|
-
const userinfoEnds = new Set(earlier.filter(({ category }) => category === CATEGORY.urlCredentials).map(({ end }) => end));
|
|
764
|
-
for (const { name, regex } of PII_PATTERNS) {
|
|
765
|
-
collectMatches(pass, regex, (match, index) => name === 'email' && userinfoEnds.has(index) ? undefined
|
|
766
|
-
: { start: index - (match.groups?.local?.length ?? 0), end: index + match[0].length, category: name });
|
|
767
|
-
}
|
|
768
|
-
collectMatches(pass, CARD_CANDIDATE, (match, index) => isLuhnValid(match[0].replace(/\D/g, '')) ? { start: index, end: index + match[0].length, category: CATEGORY.creditCard } : undefined);
|
|
769
|
-
}
|
|
770
|
-
/** Each usable secret plus its JSON-escaped spelling (`ab"cd` echoed inside JSON as `ab\"cd`). */
|
|
771
|
-
function exactNeedles(secrets, literalOnly = false) {
|
|
772
|
-
const needles = new Set();
|
|
773
|
-
for (const secret of secrets) {
|
|
774
|
-
if (typeof secret !== 'string' || secret.length === 0)
|
|
775
|
-
continue;
|
|
776
|
-
needles.add(secret);
|
|
777
|
-
if (!literalOnly)
|
|
778
|
-
needles.add(JSON.stringify(secret).slice(1, -1));
|
|
779
|
-
}
|
|
780
|
-
return needles;
|
|
781
|
-
}
|
|
782
|
-
/** Caller-supplied secrets as plain substrings at any length and every occurrence, overlapping
|
|
783
|
-
* ones included (a secret glued into other text stays masked). Matching the original text retains every value rule
|
|
784
|
-
* while wholly contained syntax occurrences preserve labels, markers and URL prefixes. Occurrences arrive
|
|
785
|
-
* in start order and each one either extends the current run or starts the next, so the runs are
|
|
786
|
-
* exactly the union of all occurrences.
|
|
787
|
-
* @complexity O(e·n + s) for e needles, n text chars and s needle chars; consecutive overlapping
|
|
788
|
-
* hits of one needle share a span. */
|
|
789
|
-
function collectExactSecrets({ text, add, secrets }, options = {}) {
|
|
790
|
-
const needles = exactNeedles(secrets, options.literalOnly);
|
|
791
|
-
if (needles.size === 0)
|
|
792
|
-
return;
|
|
793
|
-
const protectedSyntax = options.literalOnly ? [] : exactSyntaxRanges({ text });
|
|
794
|
-
for (const needle of needles) {
|
|
795
|
-
const insideSyntax = syntaxContainment({ ranges: protectedSyntax });
|
|
796
|
-
let runStart = -1;
|
|
797
|
-
let runEnd = -1;
|
|
798
|
-
forEachOccurrence(text, needle, (at) => {
|
|
799
|
-
if (insideSyntax(at, at + needle.length))
|
|
800
|
-
return;
|
|
801
|
-
if (beginsSecretRun({ at, runEnd, literalOnly: options.literalOnly === true })) {
|
|
802
|
-
add(runStart, runEnd, CATEGORY.exactSecret);
|
|
803
|
-
runStart = at;
|
|
804
|
-
}
|
|
805
|
-
runEnd = at + needle.length;
|
|
806
|
-
});
|
|
807
|
-
add(runStart, runEnd, CATEGORY.exactSecret);
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
/** Preserve diagnostic syntax only when an exact occurrence fits wholly inside it.
|
|
811
|
-
* Crossing a label/marker boundary still masks the complete secret, retaining span-union safety.
|
|
812
|
-
* @complexity O(n + k) time/space over n characters and k syntax ranges; no I/O. */
|
|
813
|
-
function exactSyntaxRanges({ text }, _options = {}) {
|
|
814
|
-
const ranges = [];
|
|
815
|
-
const add = (start, end) => { ranges.push({ start, end, category: 'syntax' }); };
|
|
816
|
-
const pass = { text, add };
|
|
817
|
-
collectMatches(pass, new RegExp(`${GENERATED_MARKER}|\\[redacted\\]`, 'gi'), (m, at) => ({ start: at, end: at + m[0].length, category: 'syntax' }));
|
|
818
|
-
collectMatches(pass, MASK_AWARE_LABELED_SECRET_RE, (m, at) => ({ start: at, end: at + m[0].length - 1, category: 'syntax' }));
|
|
819
|
-
collectMatches(pass, /\bBearer\s+|\bhttps?:\/\/|(?:x-api-key|api-key|x-goog-api-key)\s*[:=]\s*/gi, (m, at) => ({ start: at, end: at + m[0].length, category: 'syntax' }));
|
|
820
|
-
collectMatches(pass, URL_SECRET_PARAM_RE, (m, at) => ({ start: at, end: at + m[0].indexOf('=') + 1, category: 'syntax' }));
|
|
821
|
-
return mergeSpans(ranges);
|
|
822
|
-
}
|
|
823
|
-
/** Increasing occurrence starts let each needle visit every protected range at most once.
|
|
824
|
-
* @complexity O(k + hits) across calls, O(1) retained state; no I/O. */
|
|
825
|
-
function syntaxContainment({ ranges }, _options = {}) {
|
|
826
|
-
let cursor = 0;
|
|
827
|
-
return (start, end) => {
|
|
828
|
-
while (cursor < ranges.length && ranges[cursor].end <= start)
|
|
829
|
-
cursor++;
|
|
830
|
-
const range = ranges[cursor];
|
|
831
|
-
return range !== undefined && range.start <= start && range.end >= end;
|
|
832
|
-
};
|
|
833
|
-
}
|
|
834
|
-
/** Heuristic union joins adjacent hits; exact-only retains one marker for each adjacent occurrence. */
|
|
835
|
-
function beginsSecretRun({ at, runEnd, literalOnly }, _options = {}) {
|
|
836
|
-
return literalOnly ? at >= runEnd : at > runEnd;
|
|
837
|
-
}
|
|
838
|
-
/** Calls `visit` with the start of every occurrence of `needle` in order, overlapping ones included.
|
|
839
|
-
* Knuth-Morris-Pratt: after a hit the scan keeps the needle's longest border instead of retrying one
|
|
840
|
-
* character later (which cost Θ(n·m) on long overlapping needles), so no text character is read
|
|
841
|
-
* twice; while no partial match is pending, native indexOf skips to the next occurrence.
|
|
842
|
-
* @complexity O(n + m) time, O(m) space for n text and m needle chars. */
|
|
843
|
-
function forEachOccurrence(text, needle, visit) {
|
|
844
|
-
const border = borderTable(needle);
|
|
845
|
-
let matched = 0;
|
|
846
|
-
let at = text.indexOf(needle);
|
|
847
|
-
while (at !== -1) {
|
|
848
|
-
const char = text.charCodeAt(at);
|
|
849
|
-
while (matched > 0 && char !== needle.charCodeAt(matched))
|
|
850
|
-
matched = border[matched - 1] ?? 0;
|
|
851
|
-
if (char === needle.charCodeAt(matched))
|
|
852
|
-
matched += 1;
|
|
853
|
-
if (matched === needle.length) {
|
|
854
|
-
visit(at + 1 - needle.length);
|
|
855
|
-
matched = border[matched - 1] ?? 0;
|
|
856
|
-
}
|
|
857
|
-
at = nextSearchOffset({ text, needle, at, matched });
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
/** Keep partial KMP matches moving one character at a time; native indexOf skips unmatched runs. */
|
|
861
|
-
function nextSearchOffset({ text, needle, at, matched }, _options = {}) {
|
|
862
|
-
const next = at + 1;
|
|
863
|
-
if (next >= text.length)
|
|
864
|
-
return -1;
|
|
865
|
-
return matched === 0 ? text.indexOf(needle, next) : next;
|
|
866
|
-
}
|
|
867
|
-
/** KMP failure table: `border[i]` is the length of the longest proper prefix of `needle[0..i]` that
|
|
868
|
-
* is also its suffix. @complexity O(m) time and space. */
|
|
869
|
-
function borderTable(needle) {
|
|
870
|
-
const border = new Int32Array(needle.length);
|
|
871
|
-
let length = 0;
|
|
872
|
-
for (let i = 1; i < needle.length; i += 1) {
|
|
873
|
-
const char = needle.charCodeAt(i);
|
|
874
|
-
while (length > 0 && char !== needle.charCodeAt(length))
|
|
875
|
-
length = border[length - 1] ?? 0;
|
|
876
|
-
if (char === needle.charCodeAt(length))
|
|
877
|
-
length += 1;
|
|
878
|
-
border[i] = length;
|
|
879
|
-
}
|
|
880
|
-
return border;
|
|
881
|
-
}
|
|
882
|
-
/** Quoted empty credential hints must not borrow the next field's key as their value. */
|
|
883
|
-
function emptyAssignmentRanges(text) {
|
|
884
|
-
const starts = new Set();
|
|
885
|
-
for (const match of text.matchAll(new RegExp(QUOTED_SECRET_VALUE, 'g'))) {
|
|
886
|
-
if (!EMPTY_QUOTED_ASSIGNMENT_RE.test(match[0].slice(1, -1)))
|
|
887
|
-
continue;
|
|
888
|
-
// Only credential-label starts inside this quoted hint need skipping; no per-character index.
|
|
889
|
-
const labels = new RegExp(MASK_AWARE_LABELED_SECRET_RE.source, 'gi');
|
|
890
|
-
for (const label of match[0].matchAll(labels))
|
|
891
|
-
starts.add(match.index + label.index);
|
|
892
|
-
}
|
|
893
|
-
return starts;
|
|
894
|
-
}
|
|
895
|
-
/** Preserve the hint's quotes and neighboring fields; O(n) scan, no I/O. */
|
|
896
|
-
function collectEmptyQuotedAssignments(pass) {
|
|
897
|
-
for (const match of pass.text.matchAll(new RegExp(QUOTED_SECRET_VALUE, 'g'))) {
|
|
898
|
-
if (EMPTY_QUOTED_ASSIGNMENT_RE.test(match[0].slice(1, -1))) {
|
|
899
|
-
pass.add(match.index + 1, match.index + match[0].length - 1, CATEGORY.labeledSecret);
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
/** Standalone diagnostic punctuation stays readable; punctuation glued to credential text is masked. */
|
|
904
|
-
function quotedValueEnd({ text, closing, gluedEnd }, _options = {}) {
|
|
905
|
-
return /^[.!)]*$/.test(text.slice(closing + 1, gluedEnd)) ? closing + 1 : gluedEnd;
|
|
906
|
-
}
|
|
907
83
|
//# sourceMappingURL=redact.js.map
|