mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators configure agent and environment secrets across Environment
variables and Secret access settings
> - Three common mistakes currently fail poorly or leak credentials:
pasting a token into an environment variable name passes validation and
leaks into run settings and logs, converting a plain environment
variable onto an existing secret name dead-ends with a disabled submit
button, and adding an API-access secret does not clarify that processes
will not see `$NAME` unless it is also bound as an environment variable
> - Secret configuration should prevent credential leaks by default and
recover cleanly from common setup mistakes
> - This pull request rejects and redacts secret-shaped environment
variable names and access aliases across shared, server, and UI layers,
adds "Use existing secret" and "Save as new version" recovery actions on
secret name collisions, and explains API-only vs `$NAME` delivery with
an "Also bind as env var" quick action
> - The benefit is safer secret handling with zero raw token leaks in
errors, settings, or logs and a smoother operator workflow
## Linked Issues or Issue Description
**What happened?**
Three issues occur when operators configure agent and environment
secrets:
1. Pasting a credential token (for example `github_pat_...`, `ghp_...`,
or `sk-...`) into an environment variable Name field passes
`^[A-Za-z_][A-Za-z0-9_]*$` for underscore-based tokens (such as
`github_pat_...` and `ghp_...`) or echoes the raw token in the server
error message for dashed tokens (such as `sk-...`). Existing redactors
also scrub only values, not secret-shaped object keys, so legacy or
rejected payloads leak the token in run settings and logs.
2. Converting a plain environment variable to a secret via
`ConvertToSecretPopover` (or creating a secret via
`CreateSecretPopover`) disables submission with `"A secret with this
name already exists"` whenever the suggested name already exists,
forcing the operator to cancel and switch flows manually.
3. Binding a secret under `Secret access > API access (no env var)` does
not state clearly that agent processes and shell scripts will not see
`$NAME` unless the secret is also bound under Environment variables, and
provides no quick action to add the matching environment variable
binding.
**Expected behavior**
1. Both UI and server reject secret-shaped environment variable names
and access aliases with an actionable error that never echoes the token,
mask accidental token input immediately in the UI, and redact
secret-shaped keys in adapter configs, event payloads, command/text
redaction, and HTTP 4xx/5xx request logs.
2. When a secret name already exists in `CreateSecretPopover` /
`ConvertToSecretPopover`, the popover lets the operator bind the
existing secret directly or save the typed value as a new version
(rotate) without dead-ending.
3. `AgentSecretAccessEditor` clearly explains that API-access secrets
are not injected as `$NAME` in the process environment and offers an
`"Also bind as env var"` quick action for API-only bindings.
**Steps to reproduce**
1. Open an agent's Secrets & variables settings and paste a GitHub
fine-grained PAT (`github_pat_...`) into an environment variable Name
field and save; observe that it is accepted and returned verbatim in
redacted adapter config / logs.
2. Create a company secret named `gh_token`, then add a plain env var
`GH_TOKEN` with a value and click "Store as secret"; observe the
disabled `"Store & bind"` dead end.
3. Bind a secret under `Secret access > API access (no env var)` and
observe that no guidance mentions `$NAME` visibility for
processes/scripts and no quick action exists to also bind it as an
environment variable.
**Paperclip version or commit**
Reproduced on `origin/master` commit
`2d065677959b585065ff3fec8718156a4cf6f41d`.
## What Changed
- **Shared credential-token detection
(`packages/shared/src/validators/secret.ts`,
`packages/shared/src/validators/index.ts`,
`packages/shared/src/index.ts`)**: Exported `ENV_VAR_NAME_RE`,
`looksLikeCredentialToken`, `SECRET_SHAPED_ENV_NAME_ERROR`, and
`SECRET_SHAPED_ACCESS_ALIAS_ERROR` as a single source of truth shared by
`adapter-utils`, `server`, and `ui`. Updated pinned registry
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Server validation and defense-in-depth redaction
(`server/src/services/secrets.ts`, `server/src/redaction.ts`,
`server/src/middleware/redact-sensitive.ts`,
`packages/adapter-utils/src/command-redaction.ts`)**:
- Rejected credential-shaped env var names and `access.*` aliases in
`normalizeEnvConfig`, `normalizeAdapterConfigForPersistenceInternal`,
`assertSecretBindingConfigPath`, `resolveEnvBindings`, and
`resolveAdapterConfigForRuntime` without echoing the raw token.
- Redacted secret-shaped object keys in `redactAgentAdapterConfig`,
`sanitizeRecord`, and HTTP log `redactSensitive`, and expanded
`command-redaction.ts` / `redaction.ts` token patterns and hints to
cover `github_pat_`, `sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, Slack
(`xox*-`), AWS (`AKIA`/`ASIA`), Google (`AIza`), and GitLab (`glpat-`)
tokens.
- **UI env-name guardrails
(`ui/src/components/environment-variables-editor/sensitive.ts`,
`model.ts`, `Row.tsx`, `index.tsx`,
`ui/src/components/AgentSecretAccessEditor.tsx`)**:
- Flagged credential-shaped variable names and access aliases
immediately with an inline error, masked the input (`type="password"` +
`ANALYTICS_NO_CAPTURE_CLASS`), redacted credential-shaped names in the
unsaved-changes summary, disabled inline Save while present, and dropped
credential-shaped aliases from emitted access maps.
- **Plain-to-secret collision recovery
(`ui/src/components/environment-variables-editor/CreateSecretPopover.tsx`,
`Row.tsx`, `index.tsx`, `ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/components/AgentConfigForm.tsx`,
`ui/src/pages/CompanyEnvironments.tsx`,
`ui/src/components/ProjectProperties.tsx`)**:
- Replaced the dead-end duplicate-name error in `SecretPopoverForm` with
an inline recovery panel offering `"Use existing secret"` and `"Save as
new version"` (when active and rotatable), wired to `secretsApi.rotate`
across agent, environment, and project editors.
- **API-access vs `$NAME` clarity
(`ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/lib/secret-delivery.ts`,
`ui/src/components/AgentConfigForm.tsx`)**:
- Clarified under `API access (no env var)` that processes and shell
scripts will not see `$NAME` unless bound under Environment variables
above, and added an `"Also bind as env var"` quick action on API-only
secret summaries wired to `AgentConfigForm`.
- **Tests**: Extended existing owner suites
(`server/src/__tests__/redaction.test.ts`,
`server/src/__tests__/redact-sensitive.test.ts`,
`server/src/__tests__/agents-adapter-config-user-secret.test.ts`,
`ui/src/components/environment-variables-editor/model.test.ts`,
`ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx`,
`ui/src/components/AgentSecretAccessEditor.test.tsx`).
## Verification
- `pnpm vitest run
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/sensitive.test.ts
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts` — 6 files, 149/149
passed.
- `pnpm vitest run --hookTimeout=120000 --testTimeout=120000
server/src/__tests__/agents-adapter-config-user-secret.test.ts` — 1
file, 6/6 passed (embedded Postgres route test verifying HTTP 422
rejection without token echo for `github_pat_`, `ghp_`, and `sk-` env
var names).
- `pnpm vitest run packages/adapter-utils/src/command-redaction.test.ts`
— 1 file, 43/43 passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — PASS (0 errors, Storybook catalog clean).
- `pnpm check:token-gates` — PASS (all 4 token gates clean).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts
server/src/__tests__/agents-adapter-config-user-secret.test.ts
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx` — PASS.
- `pnpm verify --base 2d06567795
--explain` — `source-sdk-public-inputs.json` verified in sync; exited 2
due to broad input (`tests/runner-e2e/source-sdk-public-inputs.json`),
deferring repo-wide matrix to sharded PR CI.
## Risks
- Low risk. `looksLikeCredentialToken` matches only explicit provider
credential prefixes (`gh[pousr]_`, `github_pat_`, `sk-`,
`sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, `xox[baprs]-`,
`AKIA`/`ASIA`, `AIza`, `glpat-`, `npm_`, `hf_`, `lin_api_`, `sbp_`,
`SG.`, JWTs, PEM headers, `Bearer `) so ordinary uppercase or long env
var names are unaffected.
- Legacy agent or environment records that already stored a
secret-shaped env var key will now have that key masked as
`***REDACTED***` on reads and skipped with a redacted warning at runtime
(preserving existing heartbeats) and rejected on subsequent saves until
removed/renamed.
- No database migrations are required.
## Model Used
- Google Gemini (Antigravity agentic coding assistant with extended
reasoning, tool use, and local command execution)
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
342 lines
12 KiB
TypeScript
342 lines
12 KiB
TypeScript
import { looksLikeCredentialToken } from "@paperclipai/shared";
|
|
|
|
// Redaction for HTTP log payloads.
|
|
//
|
|
// `customProps` in logger.ts copies `req.body` / `req.params` / `req.query`
|
|
// verbatim into the 4xx/5xx log lines so operators can diagnose. That means
|
|
// Better Auth's `POST /api/auth/sign-in/email` body (which has the user's
|
|
// plaintext password) and similar payloads (sign-up, reset-password, API
|
|
// keys via Authorization header equivalents) end up on disk.
|
|
//
|
|
// This walker returns a shallow copy of the input with values for sensitive
|
|
// keys replaced with the literal string "[REDACTED]". Recurses into nested
|
|
// objects/arrays. Caps depth so a hostile or accidental cycle can't pin
|
|
// the logger.
|
|
|
|
const SENSITIVE_KEYS = new Set<string>([
|
|
// Provider setup payloads deliberately group all durable authentication
|
|
// material under `credentials`. Redact the whole subtree instead of trying
|
|
// to keep an ever-changing allowlist of provider-specific field names in
|
|
// sync with every connector.
|
|
"sealed",
|
|
"handoff",
|
|
"claim",
|
|
"claimid",
|
|
"claim_id",
|
|
"managertoken",
|
|
"manager_token",
|
|
"configurationtoken",
|
|
"configuration_token",
|
|
"credential",
|
|
"credentials",
|
|
// The app-connect/reconnect envelope. Its keys are caller-chosen provider
|
|
// config paths (`credentials.authorization`, `headers.X-Api-Key`), so they
|
|
// never match a leaf name in this set; redact the envelope by name. This is
|
|
// the durable half: the path list in http-log-redaction.ts only ever covers
|
|
// shapes someone has already seen leak.
|
|
"credentialvalues",
|
|
"password",
|
|
"currentpassword",
|
|
"newpassword",
|
|
"passwordconfirmation",
|
|
"password_confirmation",
|
|
"passwordconfirm",
|
|
"password_confirm",
|
|
"confirmpassword",
|
|
"confirm_password",
|
|
// Secret creation/update bodies use a generic `value` field. Failure logs
|
|
// must prefer losing that diagnostic value over persisting credential
|
|
// material. `token` is likewise ambiguous but frequently credential-bearing.
|
|
"value",
|
|
"token",
|
|
"secret",
|
|
"client_secret",
|
|
"clientsecret",
|
|
"access_token",
|
|
"accesstoken",
|
|
"refresh_token",
|
|
"refreshtoken",
|
|
"id_token",
|
|
"idtoken",
|
|
"api_key",
|
|
"apikey",
|
|
// Probe keys are transient, including rejected or future provider names.
|
|
// Redact the whole container instead of maintaining a second key allowlist.
|
|
"testcredentials",
|
|
"authorization",
|
|
"auth_token",
|
|
"authtoken",
|
|
"session_token",
|
|
"sessiontoken",
|
|
"private_key",
|
|
"privatekey",
|
|
// Defense in depth for legacy, malformed, or provider-specific payloads
|
|
// that place a credential outside the standard `credentials` envelope.
|
|
"app_secret",
|
|
"appsecret",
|
|
"application_secret",
|
|
"applicationsecret",
|
|
"bot_token",
|
|
"bottoken",
|
|
"secret_token",
|
|
"secrettoken",
|
|
"signing_secret",
|
|
"signingsecret",
|
|
"webhook_secret",
|
|
"webhooksecret",
|
|
"webhookkey",
|
|
"webhookurl",
|
|
"paperclip_capability",
|
|
// The Claude setup-token and hosted Google redirect login fields.
|
|
// `browserCode` carries a one-time sign-in code or loopback redirect URL,
|
|
// `redirectUrl` carries an OAuth callback URL, and `authorization_code`
|
|
// carries the OAuth code; none may reach a log line.
|
|
"browsercode",
|
|
"redirecturl",
|
|
"redirect_url",
|
|
"authorization_code",
|
|
"code_verifier",
|
|
"codeverifier",
|
|
"authorizationcode",
|
|
// The workspace login handoff ticket (PAP-17572). It is a signed bearer
|
|
// credential carried as a query parameter, so it must never reach a log line
|
|
// even though the exchange itself answers 302.
|
|
"ticket",
|
|
// Not secrets Paperclip holds, but attacker-authored prose: an OAuth provider
|
|
// controls `error_description` / `error_uri` on the callback query string, and
|
|
// `customProps` copies the whole query into 4xx log lines. Paperclip maps the
|
|
// `error` code to its own copy instead of reflecting these, so they have no
|
|
// debugging value here either (PAP-17108).
|
|
"error_description",
|
|
"errordescription",
|
|
"error_uri",
|
|
"erroruri",
|
|
]);
|
|
|
|
const MAX_DEPTH = 6;
|
|
const REDACTED = "[REDACTED]";
|
|
const URLISH_KEYS = new Set<string>([
|
|
"href",
|
|
"locator",
|
|
"source",
|
|
"source_locator",
|
|
"sourcelocator",
|
|
"source_url",
|
|
"sourceurl",
|
|
"uri",
|
|
"url",
|
|
// The Claude setup-token login URL. A structured `loginUrl` that reaches a log
|
|
// sink keeps its origin and path only; the OAuth query, fragment, and any
|
|
// credentials are stripped (SR-5 backstop).
|
|
"loginurl",
|
|
"login_url",
|
|
]);
|
|
|
|
function isSensitiveKey(key: string): boolean {
|
|
return SENSITIVE_KEYS.has(key.toLowerCase());
|
|
}
|
|
|
|
function isUrlishKey(key: string): boolean {
|
|
return URLISH_KEYS.has(key.toLowerCase());
|
|
}
|
|
|
|
export function stripSecretBearingUrlParts(value: string): string {
|
|
const suffixStart = value.search(/[?#]/);
|
|
const withoutQueryOrFragment =
|
|
(suffixStart === -1 ? value : value.slice(0, suffixStart)).replace(
|
|
/(^|^[a-z][a-z\d+.-]*:\/\/[^/]*)(\/(?:(?:api\/)?invites\/(?![^/]+\/revoke(?:\/|$))|invite\/))[^/]+/i,
|
|
"$1$2[REDACTED]",
|
|
);
|
|
|
|
try {
|
|
const url = new URL(withoutQueryOrFragment);
|
|
if (!url.username && !url.password) return withoutQueryOrFragment;
|
|
url.username = "";
|
|
url.password = "";
|
|
return url.toString();
|
|
} catch {
|
|
// Request URLs are normally origin-form paths rather than absolute URLs.
|
|
// They still need the same query/fragment policy as URL-valued payloads.
|
|
return withoutQueryOrFragment;
|
|
}
|
|
}
|
|
|
|
function isCredentialShapedKey(key: string): boolean {
|
|
if (looksLikeCredentialToken(key)) return true;
|
|
if (key.startsWith("access.") && looksLikeCredentialToken(key.slice("access.".length))) return true;
|
|
return false;
|
|
}
|
|
|
|
function createRedactedKeyAllocator(existingKeys: ReadonlySet<string>): () => string {
|
|
let usedBase = false;
|
|
let nextSuffix = 2;
|
|
return () => {
|
|
if (!usedBase) {
|
|
usedBase = true;
|
|
if (!existingKeys.has(REDACTED)) return REDACTED;
|
|
}
|
|
while (existingKeys.has(`${REDACTED}_${nextSuffix}`)) {
|
|
nextSuffix += 1;
|
|
}
|
|
const allocated = `${REDACTED}_${nextSuffix}`;
|
|
nextSuffix += 1;
|
|
return allocated;
|
|
};
|
|
}
|
|
|
|
export function redactSensitive(value: unknown, depth = 0): unknown {
|
|
if (depth > MAX_DEPTH) return undefined;
|
|
if (value === null || typeof value !== "object") return value;
|
|
if (Array.isArray(value)) {
|
|
if (depth + 1 > MAX_DEPTH) return undefined;
|
|
return value.map((entry) => redactSensitive(entry, depth + 1));
|
|
}
|
|
const entries = Object.entries(value as Record<string, unknown>);
|
|
let allocateRedactedKey: (() => string) | null = null;
|
|
const out: Record<string, unknown> = {};
|
|
for (const [key, entry] of entries) {
|
|
if (isCredentialShapedKey(key)) {
|
|
if (!allocateRedactedKey) {
|
|
allocateRedactedKey = createRedactedKeyAllocator(new Set(entries.map(([k]) => k)));
|
|
}
|
|
out[allocateRedactedKey()] = REDACTED;
|
|
continue;
|
|
}
|
|
if (isSensitiveKey(key)) {
|
|
out[key] = REDACTED;
|
|
continue;
|
|
}
|
|
if (typeof entry === "string" && isUrlishKey(key)) {
|
|
out[key] = stripSecretBearingUrlParts(entry);
|
|
continue;
|
|
}
|
|
out[key] = redactSensitive(entry, depth + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function collectSensitiveStringValuesInto(
|
|
value: unknown,
|
|
values: Set<string>,
|
|
collectAll: boolean,
|
|
depth: number,
|
|
): void {
|
|
if (depth > MAX_DEPTH || value === null || value === undefined) return;
|
|
if (typeof value === "string") {
|
|
if (collectAll && value.length > 0) values.add(value);
|
|
return;
|
|
}
|
|
if (typeof value !== "object") return;
|
|
if (Array.isArray(value)) {
|
|
for (const entry of value) {
|
|
collectSensitiveStringValuesInto(entry, values, collectAll, depth + 1);
|
|
}
|
|
return;
|
|
}
|
|
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
|
const credentialKey = isCredentialShapedKey(key);
|
|
if (credentialKey) values.add(key);
|
|
collectSensitiveStringValuesInto(
|
|
entry,
|
|
values,
|
|
collectAll || isSensitiveKey(key) || credentialKey,
|
|
depth + 1,
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Collects submitted credential strings without exposing them to callers' logs. */
|
|
export function collectSensitiveStringValues(value: unknown): string[] {
|
|
const values = new Set<string>();
|
|
collectSensitiveStringValuesInto(value, values, false, 0);
|
|
return [...values];
|
|
}
|
|
|
|
function encodedSensitiveVariants(values: readonly string[]): string[] {
|
|
const variants = new Set<string>();
|
|
for (const value of values) {
|
|
const normalizedValues = new Set([value, value.trim()]);
|
|
for (const normalizedValue of normalizedValues) {
|
|
if (normalizedValue.length === 0) continue;
|
|
variants.add(normalizedValue);
|
|
const json = JSON.stringify(normalizedValue);
|
|
if (json.length >= 2) variants.add(json.slice(1, -1));
|
|
try {
|
|
const urlEncoded = encodeURIComponent(normalizedValue);
|
|
variants.add(urlEncoded);
|
|
variants.add(urlEncoded.replaceAll("%20", "+"));
|
|
} catch {
|
|
// A lone UTF-16 surrogate is not URI-encodable. The raw and JSON-escaped
|
|
// forms are still covered, and error handling must never throw again
|
|
// while trying to sanitize malformed input.
|
|
}
|
|
}
|
|
}
|
|
return [...variants]
|
|
.filter(Boolean)
|
|
.sort((left, right) => right.length - left.length);
|
|
}
|
|
|
|
/** Decode candidate spans rather than enumerating secret encodings. This also
|
|
* finds credentials embedded inside an encoded diagnostic or authorization value.
|
|
* Bound nesting so untrusted provider text cannot cause unbounded decoding work. */
|
|
function redactEncodedSensitiveOccurrences(text: string, variants: readonly string[], depth = 0): string {
|
|
if (depth >= 3 || variants.length === 0) return text;
|
|
const containsSecret = (decoded: string) => variants.some(value => decoded.includes(value))
|
|
|| redactEncodedSensitiveOccurrences(decoded, variants, depth + 1) !== decoded;
|
|
const percentRedacted = text.replace(/[^\s<>"`]+/g, token => {
|
|
if (!/%[0-9a-f]{2}/i.test(token)) return token;
|
|
// Try URI and form encoding separately: '+' is literal in URI components.
|
|
for (const candidate of [token, token.replaceAll("+", " ")]) {
|
|
const decoded = candidate.replace(/(?:%[0-9a-f]{2})+/gi, span => {
|
|
try { return decodeURIComponent(span); }
|
|
catch { return span; } // Keep malformed UTF-8 without hiding valid spans.
|
|
});
|
|
if (containsSecret(decoded)) return REDACTED;
|
|
}
|
|
return token;
|
|
});
|
|
return percentRedacted.replace(/[A-Za-z0-9+/_-]+={0,2}/g, token => {
|
|
if (token.length < 4) return token;
|
|
const canonical = token.replaceAll("-", "+").replaceAll("_", "/").replace(/=+$/, "");
|
|
const bytes = Buffer.from(canonical, "base64");
|
|
// Buffer accepts invalid base64; only inspect a lossless canonical decode.
|
|
if (bytes.toString("base64").replace(/=+$/, "") !== canonical) return token;
|
|
return containsSecret(bytes.toString("utf8")) ? REDACTED : token;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Redacts sensitive-shaped fields, then removes submitted credential values
|
|
* wherever an upstream validator/provider echoed them into otherwise-safe
|
|
* response prose.
|
|
*/
|
|
export function redactSensitiveValueOccurrences(
|
|
value: unknown,
|
|
sensitiveValues: readonly string[],
|
|
): unknown {
|
|
const variants = encodedSensitiveVariants(sensitiveValues);
|
|
const redacted = redactSensitive(value);
|
|
|
|
const visit = (entry: unknown, depth: number): unknown => {
|
|
if (depth > MAX_DEPTH) return undefined;
|
|
if (typeof entry === "string") {
|
|
return variants.reduce(
|
|
(text, sensitiveValue) => text.replaceAll(sensitiveValue, REDACTED),
|
|
redactEncodedSensitiveOccurrences(entry, variants),
|
|
);
|
|
}
|
|
if (entry === null || typeof entry !== "object") return entry;
|
|
if (Array.isArray(entry))
|
|
return entry.map((item) => visit(item, depth + 1));
|
|
return Object.fromEntries(
|
|
Object.entries(entry as Record<string, unknown>).map(([key, item]) => [
|
|
key,
|
|
visit(item, depth + 1),
|
|
]),
|
|
);
|
|
};
|
|
|
|
return visit(redacted, 0);
|
|
}
|