Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(collector): value rule v2 stops redacting identifiers, paths and plain words in source

ogsamrat9f5c441fc14a
diff --git a/apps/server/src/workspace-collector.test.ts b/apps/server/src/workspace-collector.test.ts
index ee471e3a..03f77cfe 100644
--- a/apps/server/src/workspace-collector.test.ts
+++ b/apps/server/src/workspace-collector.test.ts
@@ -29,6 +29,7 @@ import {
redactCollectorJson,
redactCollectorJsonText,
redactCollectorText,
+ redactModeForPath,
stripRemoteUserinfo,
} from "./workspace-collector.js";
@@ -1136,15 +1137,130 @@ describe("workspace collector secret rails", () => {
expect(redactCollectorText(`AccessKeyId,SecretAccessKey\nAKIAIOSFODNN7EXAMPLE,${AWS_SECRET}\n`).text).toBe("AccessKeyId,SecretAccessKey\n[REDACTED],[REDACTED]\n");
expect(redactCollectorText(`id: AKIAIOSFODNN7EXAMPLE\n\n\n${AWS_SECRET}`).text).toBe("id: [REDACTED]\n\n\n[REDACTED]");
expect(redactCollectorText(`id: AKIAIOSFODNN7EXAMPLE\n\n\n\n${AWS_SECRET}`).text).toBe(`id: [REDACTED]\n\n\n\n${AWS_SECRET}`);
- expect(redactCollectorText(`# aws profile\n${AWS_SECRET}`).text).toBe("# aws profile\n[REDACTED]");
+ expect(redactCollectorText(`# aws profile\n# region eu-west-1\n${AWS_SECRET}`).text).toBe("# aws profile\n# region eu-west-1\n[REDACTED]");
expect(redactCollectorText(`${AWS_SECRET}\n\nsecret: yes`).text).toBe("[REDACTED]\n\nsecret: yes");
expect(redactCollectorText(AWS_SECRET).text).toBe(AWS_SECRET);
- expect(redactCollectorText(AWS_SECRET, { context: "AWS master secret.txt" }).text).toBe("[REDACTED]");
+ expect(redactCollectorText(`\n\n${AWS_SECRET}`, { context: "AWS master secret.txt" }).text).toBe("\n\n[REDACTED]");
+ // The proximity pass needs three or more lines (two line breaks); a
+ // shorter document relies on the assignment rule or its JSON key.
+ expect(redactCollectorText(`# aws profile\n${AWS_SECRET}`).text).toBe(`# aws profile\n${AWS_SECRET}`);
+ expect(redactCollectorText(AWS_SECRET, { context: "AWS master secret.txt" }).text).toBe(AWS_SECRET);
+ expect(redactCollectorContent("creds.json", `{"aws_secret_access_key":"${AWS_SECRET}"}`)).toBe('{"aws_secret_access_key":"[REDACTED]"}');
+ expect(redactCollectorContent("creds.json", `{"Credentials":{"AccessKeyId":"AKIAIOSFODNN7EXAMPLE","SecretAccessKey":"${AWS_SECRET}"}}`))
+ .toBe('{"Credentials":{"AccessKeyId":"[REDACTED]","SecretAccessKey":"[REDACTED]"}}');
+ expect(redactCollectorContent("creds.env", `AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\nAWS_SECRET_ACCESS_KEY=${AWS_SECRET}\n`))
+ .toBe("AWS_ACCESS_KEY_ID=[REDACTED]\nAWS_SECRET_ACCESS_KEY=[REDACTED]\n");
// Not mixed case (a git sha), or not exactly 40 characters: left alone.
expect(redactCollectorText("aws sha 0123456789abcdef0123456789abcdef01234567").text).toContain("0123456789abcdef0123456789abcdef01234567");
expect(redactCollectorText(`aws ${AWS_SECRET}extra`).text).toContain(AWS_SECRET);
});
+ test("selects the value rule mode from the file extension", () => {
+ for (const path of ["src/app.js", "lib/x.cjs", "x.mjs", "a/b.ts", "c.tsx", "d.jsx", "e.py", "f.go", "g.rs", "h.java", "i.kt", "j.c", "k.cc", "l.cpp",
+ "m.h", "n.hpp", "o.rb", "p.php", "q.swift", "r.cs", "s.scala", "t.sh", "u.bash", "v.zsh", "w.ps1", "x.lua", "y.dart", "z.vue", "aa.svelte", "bundle.js.map", "UPPER.JS"]) {
+ expect(redactModeForPath(path)).toBe("source");
+ }
+ for (const path of [".env", ".env.local", "settings.ini", "app.cfg", "nginx.conf", "ci.yml", "compose.yaml", "Cargo.toml", "package.json",
+ "app.properties", "notes.txt", "README.md", "Makefile", "Dockerfile", ".bashrc", "archive.tar.gz", "src/token/prod.env"]) {
+ expect(redactModeForPath(path)).toBe("config");
+ }
+ });
+
+ test("value rule v2 leaves source-code assignments byte-identical and still redacts literal secrets", () => {
+ // Every false positive sampled from a v1.0.5 production upload, in the file type it came from.
+ const sampled: Array<[string, string]> = [
+ ["derived.js", "derived.token_estimate = estimate;"],
+ ["middleware.js", "const auth = req.headers.authorization || '';"],
+ ["app.js", "authMethod: 'github-app'"],
+ ["client.js", "token: config.token"],
+ ["metrics.yml", "credentials_file: /run/secrets/prod_metrics_token"],
+ ["pipeline.yml", "token_role: 'pipeline'"],
+ ["pipeline.yml", "token_owner: 'sample-owner'"],
+ ["oauth.js", "const githubOAuthConfig = githubOAuthEnabled"],
+ ["fixtures.js", "META_MUSE_API_KEY: 'synthetic'"],
+ ["heartbeat.py", "credential_hash: server.heartbeat_token_hash"],
+ ["atlas.js", "CONTRACT_POOL_ATLAS_READ_TOKEN_FILE: tokenFile"],
+ ["request.js", "Authorization: Bearer test-token"],
+ // The same lines survive CONFIG mode too, except the quoted 'synthetic' literal.
+ ["config.yml", "token: config.token"],
+ ["heartbeat.yml", "credential_hash: server.heartbeat_token_hash"],
+ ["atlas.yml", "CONTRACT_POOL_ATLAS_READ_TOKEN_FILE: tokenFile"],
+ ["request.txt", "Authorization: Bearer test-token"],
+ ["middleware.diff", "+const auth = req.headers.authorization || '';"],
+ // SOURCE mode: unquoted identifiers are references, paths are paths, short digitless literals are labels.
+ ["a.py", "token = someLongCamelCaseIdentifier2"],
+ ["a.py", "password = hunter2abc"],
+ ["settings.py", "AUTH_TIMEOUT = 30000000"],
+ ["a.py", "password = settings.DATABASE_PASSWORD_1"],
+ ["a.ts", 'const secret = "/etc/ssl/private/key1.pem";'],
+ ["a.ts", 'const secret = "./secrets/key1.pem";'],
+ ["a.ts", 'const secret = "../keys/key1.pem";'],
+ ["a.ts", 'const secret = "~/.aws/credentials1";'],
+ ["a.ts", 'const secret = "C:/Users/me/token1.txt";'],
+ ["a.go", 'password := "secrets/db/primary"'],
+ ["a.rb", 'password = "abcdefghijklmnopqrstuvwxyz"'],
+ ["a.rb", 'password = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"'],
+ ["a.rb", 'token = "abc${FOO}def12"'],
+ ["a.rb", 'token = "<your-token-1>"'],
+ ["a.rb", "token = getToken(12345678)"],
+ ["a.sh", 'TOKEN="$(cat token1.txt)"'],
+ ];
+ for (const [path, text] of sampled) expect(redactCollectorContent(path, text)).toBe(text);
+ expect(redactCollectorText("+const auth = req.headers.authorization || '';", { context: "middleware.js" })).toEqual({ text: "+const auth = req.headers.authorization || '';", count: 0 });
+ expect(filterCollectorDiff("diff --git a/m.js b/m.js\n+const auth = req.headers.authorization || '';\n").diff)
+ .toBe("diff --git a/m.js b/m.js\n+const auth = req.headers.authorization || '';\n");
+
+ const secrets: Array<[string, string, string]> = [
+ ["app.js", `const apiKey = "${sample("sk_live_", "abcdefghijklmnopqrstuvwx")}"`, 'const apiKey = "[REDACTED]"'],
+ ["settings.py", 'password = "hunter2abc"', 'password = "[REDACTED]"'],
+ ["settings.py", 'token = "Abcdefghijklmnopqrstuvwxyz1234"', 'token = "[REDACTED]"'],
+ ["settings.py", 'password = "12345678"', 'password = "[REDACTED]"'],
+ ["settings.py", 'auth = "AbCdEfGhIjKlMnOpQrStUv"', 'auth = "[REDACTED]"'],
+ ["settings.py", "SECRET = Ab1/Cd2+Ef3=", "SECRET = [REDACTED]"],
+ ["ci.yml", `token: ${GITHUB_TOKEN}`, "token: [REDACTED]"],
+ ["config.yml", 'api_key: "abcdef1234567890"', 'api_key: "[REDACTED]"'],
+ ["config.yml", "password: changeme1", "password: [REDACTED]"],
+ ["config.yml", "META_MUSE_API_KEY: 'synthetic'", "META_MUSE_API_KEY: '[REDACTED]'"],
+ ["config.yml", 'token: "config.token"', 'token: "[REDACTED]"'],
+ ["config.yml", "token: config-token", "token: [REDACTED]"],
+ ["request.http", "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", "Authorization: Bearer [REDACTED]"],
+ ["request.js", "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", "Authorization: Bearer [REDACTED]"],
+ ];
+ for (const [path, text, expected] of secrets) {
+ expect(redactCollectorContent(path, text)).toBe(expected);
+ expect(redactCollectorText(text, { mode: redactModeForPath(path) }).count).toBe(1);
+ }
+ // Excluded last segments never name a secret, in either mode.
+ for (const last of ["file", "filename", "dir", "mode", "method", "role", "owner", "type", "kind", "enabled", "estimate", "hash", "digest", "at",
+ "config", "client", "prefix", "suffix", "format", "scheme", "provider", "status", "state", "label", "description", "title", "class", "field",
+ "fields", "list", "names", "version", "timeout", "limit", "max", "min", "interval", "retries", "port"]) {
+ const line = `token_${last}: abcdefgh1234`;
+ expect(redactCollectorContent("x.yml", line)).toBe(line);
+ expect(redactCollectorContent("x.py", line)).toBe(line);
+ }
+ });
+
+ test("redacts a Bearer token only when it looks like a credential", () => {
+ const kept = [
+ "Authorization: Bearer test-token",
+ "Authorization: Bearer yourAccessTokenGoesHere",
+ "Authorization: Bearer your_access_token.goes.here",
+ "Authorization: Bearer ${ACCESS_TOKEN_GOES_HERE}",
+ "Authorization: Bearer <your-access-token-here>",
+ "Authorization: Bearer abcdefghijklmnopqrstuvwxyz",
+ "Authorization: Bearer ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+ ];
+ for (const line of kept) expect(redactCollectorText(line)).toEqual({ text: line, count: 0 });
+ const redacted = [
+ "Authorization: Bearer abcdefghijklmnopqrstuvwxyz0123",
+ "Authorization: Bearer a8f3b2c9d4e5f6a7b8c9d0e1",
+ "Authorization: Bearer Your-Access-Token-Goes-Here",
+ "Authorization: Bearer AbCdEfGhIjKlMnOpQrStUv/wx+yz==",
+ ];
+ for (const line of redacted) expect(redactCollectorText(line)).toEqual({ text: "Authorization: Bearer [REDACTED]", count: 1 });
+ expect(redactCollectorText("authorization: bearer abcdefghijklmnopqrstuvwxyz0123")).toEqual({ text: "authorization: bearer [REDACTED]", count: 1 });
+ });
+
test("keeps a source file named after a token but redacts the literal inside it", async () => {
const root = await mkdtemp(join(tmpdir(), "omnirush-collector-source-"));
roots.push(root);
@@ -1242,13 +1358,21 @@ describe("workspace collector secret rails", () => {
"Ma.".repeat(mebibyte / 3),
"\\n".repeat(mebibyte / 2),
`secret: ${"A1b".repeat(mebibyte / 3)}`,
+ `secret: ${"a.".repeat(mebibyte / 2)}`,
+ `secret: ${"a.".repeat(mebibyte / 2)}/`,
+ `secret: ${"Ab/".repeat(mebibyte / 3)}`,
+ `secret: "${"a1.".repeat(mebibyte / 3)}"`,
+ `Bearer ${"aB".repeat(mebibyte / 2)}`,
+ `Bearer ${"a.".repeat(mebibyte / 2)}`,
];
for (const line of lines) {
- const started = performance.now();
- redactCollectorText(line);
- expect(performance.now() - started).toBeLessThan(2_000);
+ for (const mode of ["config", "source"] as const) {
+ const started = performance.now();
+ redactCollectorText(line, { mode });
+ expect(performance.now() - started).toBeLessThan(2_000);
+ }
}
- }, 30_000);
+ }, 60_000);
});
// --- gateway auth: stale device tokens ---------------------------------------
diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.ts
index 7cff5313..18acb4b5 100644
--- a/apps/server/src/workspace-collector.ts
+++ b/apps/server/src/workspace-collector.ts
@@ -3,7 +3,7 @@ import { execFile, spawn } from "node:child_process";
import { createReadStream, watch, type FSWatcher } from "node:fs";
import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
import { release as osRelease } from "node:os";
-import { basename, dirname, join, relative, resolve, sep } from "node:path";
+import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
import { promisify } from "node:util";
import { zstdCompress } from "node:zlib";
import { minimatch } from "minimatch";
@@ -403,8 +403,36 @@ const SECRET_KEY_PAIRS: Array<[string, string]> = [
["api", "key"], ["access", "key"], ["secret", "key"], ["private", "key"], ["client", "key"], ["client", "secret"],
["session", "key"], ["signing", "key"], ["master", "key"], ["encryption", "key"],
];
-const EXCLUDED_LAST_SEGMENTS = new Set(["length", "ttl", "seconds", "count", "size", "url", "path", "name", "id", "header"]);
-const CODE_EXPRESSION_VALUE = /^(?:process\.|os\.|env\.|\$\{|\$\()/;
+const EXCLUDED_LAST_SEGMENTS = new Set([
+ "length", "ttl", "seconds", "count", "size", "url", "path", "name", "id", "header",
+ "file", "filename", "dir", "mode", "method", "role", "owner", "type", "kind", "enabled", "estimate", "hash", "digest", "at",
+ "config", "client", "prefix", "suffix", "format", "scheme", "provider", "status", "state", "label", "description", "title",
+ "class", "field", "fields", "list", "names", "version", "timeout", "limit", "max", "min", "interval", "retries", "port",
+]);
+
+/**
+ * Value rule v2 (the backend applies the identical rule). A file whose
+ * extension names a programming language is scrubbed in SOURCE mode, where an
+ * assignment's value must look like a generated literal; everything else
+ * (.env*, ini, cfg, conf, yml, yaml, toml, json, properties, txt, md, no or
+ * unknown extension), plus git diffs and the trace, is scrubbed in CONFIG
+ * mode with the permissive rule.
+ */
+export type RedactMode = "source" | "config";
+const SOURCE_EXTENSIONS = new Set([
+ "js", "cjs", "mjs", "ts", "tsx", "jsx", "py", "go", "rs", "java", "kt", "c", "cc", "cpp", "h", "hpp", "rb", "php", "swift",
+ "cs", "scala", "sh", "bash", "zsh", "ps1", "lua", "dart", "vue", "svelte", "map",
+]);
+
+/** SOURCE for a programming-language extension (case-insensitive), CONFIG otherwise. */
+export function redactModeForPath(path: string): RedactMode {
+ return SOURCE_EXTENSIONS.has(extname(path).slice(1).toLowerCase()) ? "source" : "config";
+}
+
+// The value side of the assignment rule (see isSecretAssignmentValue).
+const CODE_EXPRESSION_VALUE = /^(?:process\.|os\.|env\.)/;
+const IDENTIFIER_VALUE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/;
+const PATH_VALUE = /^(?:\/|\.\/|\.\.\/|~\/|[A-Za-z]:[\\/])/;
const MAX_ASSIGNMENT_DEPTH = 4;
// An AWS secret access key is 40 base64 characters with no shape of its own,
@@ -413,6 +441,9 @@ const AWS_SECRET_QUICK = /[A-Za-z0-9/+]{40}/;
const AWS_SECRET_CANDIDATE = tokenPattern(String.raw`[A-Za-z0-9/+]{40}(?![A-Za-z0-9/+])`, "g", String.raw`[A-Za-z0-9/+\\]`);
const AWS_SECRET_CONTEXT = /(?:AKIA|ASIA)[0-9A-Z]{16}|aws|secret/i;
const AWS_SECRET_CONTEXT_LINES = 3;
+// The proximity pass needs neighbouring lines to mean anything: a single-line
+// document (compact JSON, the trace) relies on its JSON key instead.
+const AWS_SECRET_MIN_LINES = 3;
// Runs before the assignment rule so `https://oauth2:<token>@host/...` keeps
// its host instead of being read as an `oauth2:` assignment.
@@ -432,8 +463,10 @@ const SECRET_PATTERNS: Redaction[] = [
[tokenPattern(String.raw`(?:sk|rk|pk)-(?:proj-)?[A-Za-z0-9_-]{16,}\b`), REDACTED],
[tokenPattern(String.raw`eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), REDACTED],
[tokenPattern(String.raw`[MN][A-Za-z0-9_-]{23,}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}`), REDACTED],
- [tokenPattern(String.raw`Bearer[ \t]+[A-Za-z0-9_.~+/=-]{16,}`, "gi"), `Bearer ${REDACTED}`],
];
+// `Bearer <token>`: the token part is decided by isBearerSecret. The character
+// class already excludes `${...}` and `<...>` placeholders.
+const BEARER_TOKEN = tokenPattern(String.raw`(Bearer[ \t]+)([A-Za-z0-9_.~+/=-]{16,})`, "gi");
const PII_PATTERNS: Redaction[] = [
[tokenPattern(String.raw`[A-Z0-9._%+-]{1,64}@[A-Z0-9.-]{1,253}\.[A-Z]{2,}\b`, "gi"), REDACTED_PII],
[tokenPattern(String.raw`(?:\+\d{1,3}[\s.-]?)?(?:\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4})(?!\w)`), REDACTED_PII],
@@ -608,18 +641,48 @@ function isSecretAssignmentKey(key: string): boolean {
}
/**
- * 8+ non-space characters with a letter, and not a code expression, an
- * angle-bracket placeholder (`<your-token>`, a tokenizer's `<|endoftext|>`)
- * or an earlier redaction.
+ * A filesystem path: an absolute, relative, home or drive-letter prefix, or a
+ * `/` anywhere with no digit anywhere (`/run/secrets/x`, `C:/Users/me`).
*/
-function isSecretAssignmentValue(value: string): boolean {
- return value.length >= 8
- && !/\s/.test(value)
- && /[A-Za-z]/.test(value)
- && !value.startsWith("[REDACTED")
- && !value.includes("(")
- && !(value.startsWith("<") && value.endsWith(">"))
- && !CODE_EXPRESSION_VALUE.test(value);
+function isFilesystemPathValue(value: string): boolean {
+ return PATH_VALUE.test(value) || (value.includes("/") && !/\d/.test(value));
+}
+
+/**
+ * Whether the value of a secret-named assignment is redacted (value rule v2).
+ * In both modes it must be 8+ characters with no whitespace, not a code
+ * expression (a `(`, `${` or `$(` anywhere, or a `process.` / `os.` / `env.`
+ * prefix), not an angle-bracket placeholder (`<your-token>`, a tokenizer's
+ * `<|endoftext|>`), not an earlier redaction and not a filesystem path.
+ * SOURCE mode then wants a literal that looks generated: an unquoted value
+ * with identifier or member-expression syntax is a reference (`config.token`,
+ * `tokenFile`, `req.headers.authorization`), never a literal, and the value
+ * must carry a digit or be 20+ characters of mixed case, so `'synthetic'`
+ * and `'github-app'` stay. CONFIG mode keeps the permissive rule (a letter
+ * anywhere), skipping only an unquoted dotted identifier such as YAML's
+ * `token: config.token`.
+ */
+function isSecretAssignmentValue(value: string, mode: RedactMode, quoted: boolean): boolean {
+ if (value.length < 8 || /\s/.test(value) || value.startsWith("[REDACTED")) return false;
+ if (value.includes("(") || value.includes("${") || value.includes("$(") || CODE_EXPRESSION_VALUE.test(value)) return false;
+ if (value.startsWith("<") && value.endsWith(">")) return false;
+ if (isFilesystemPathValue(value)) return false;
+ const identifier = !quoted && IDENTIFIER_VALUE.test(value);
+ if (mode === "source") {
+ return !identifier && (/\d/.test(value) || (value.length >= 20 && /[a-z]/.test(value) && /[A-Z]/.test(value)));
+ }
+ return /[A-Za-z]/.test(value) && !(identifier && value.includes("."));
+}
+
+/**
+ * The token after `Bearer` is a secret when it carries a digit, or is 20+
+ * characters of mixed case that are not a bare identifier or member
+ * expression (`Bearer yourAccessTokenGoesHere` is a placeholder; so is
+ * `Bearer test-token`, too short and digitless).
+ */
+function isBearerSecret(token: string): boolean {
+ if (/\d/.test(token)) return true;
+ return token.length >= 20 && /[a-z]/.test(token) && /[A-Z]/.test(token) && !IDENTIFIER_VALUE.test(token);
}
function applyRedaction(text: string, [pattern, replacement]: Redaction, tally: { count: number }): string {
@@ -631,31 +694,43 @@ function applyRedaction(text: string, [pattern, replacement]: Redaction, tally:
}
/** Redacts the value of every secret-named assignment; one redaction per assignment. */
-function redactAssignments(text: string, tally: { count: number }, depth = 0): string {
+function redactAssignments(text: string, tally: { count: number }, mode: RedactMode, depth = 0): string {
ASSIGNMENT_PATTERN.lastIndex = 0;
return text.replace(ASSIGNMENT_PATTERN, (match: string, _quote: string, key: string, doubleQuoted?: string, singleQuoted?: string, escapedQuoted?: string, bare?: string) => {
const value = doubleQuoted ?? singleQuoted ?? escapedQuoted ?? bare ?? "";
const quote = doubleQuoted !== undefined ? '"' : singleQuoted !== undefined ? "'" : escapedQuoted !== undefined ? '\\"' : "";
const prefix = match.slice(0, match.length - value.length - quote.length * 2);
- if (isSecretAssignmentKey(key) && isSecretAssignmentValue(value)) {
+ if (isSecretAssignmentKey(key) && isSecretAssignmentValue(value, mode, bare === undefined)) {
tally.count += 1;
return `${prefix}${quote}${REDACTED}${quote}`;
}
// An excluded key (`token_url=https://x/?token=...`) or a code expression
// can still carry a secret assignment inside its value.
if (depth >= MAX_ASSIGNMENT_DEPTH) return match;
- return `${prefix}${quote}${redactAssignments(value, tally, depth + 1)}${quote}`;
+ return `${prefix}${quote}${redactAssignments(value, tally, mode, depth + 1)}${quote}`;
+ });
+}
+
+/** Redacts `Bearer <token>` when the token part passes isBearerSecret. */
+function redactBearerTokens(text: string, tally: { count: number }): string {
+ BEARER_TOKEN.lastIndex = 0;
+ return text.replace(BEARER_TOKEN, (match: string, prefix: string, token: string) => {
+ if (!isBearerSecret(token)) return match;
+ tally.count += 1;
+ return `${prefix}${REDACTED}`;
});
}
/**
* Redacts 40-character mixed-case base64 runs that sit within three lines of
* an AWS access key id or of the words aws/secret (or whose surrounding
- * context, such as the file path or JSON key, names them).
+ * context, such as the file path or JSON key, names them). Only a document of
+ * three or more lines (two or more line breaks) is scanned.
*/
function redactAwsSecrets(text: string, context: string | undefined, tally: { count: number }): string {
if (!AWS_SECRET_QUICK.test(text)) return text;
const lines = text.split("\n");
+ if (lines.length < AWS_SECRET_MIN_LINES) return text;
const contextual: Array<boolean | undefined> = new Array(lines.length);
const hasContext = (index: number): boolean => {
if (contextual[index] === undefined) contextual[index] = AWS_SECRET_CONTEXT.test(lines[index]!);
@@ -684,6 +759,8 @@ function redactAwsSecrets(text: string, context: string | undefined, tally: { co
export type RedactCollectorTextOptions = {
/** Text that counts as context for context-dependent rules: the file path, or the JSON key a value sits under. */
context?: string;
+ /** Value rule mode; CONFIG when omitted (git diffs, the trace, JSON). See redactModeForPath. */
+ mode?: RedactMode;
};
/**
@@ -695,16 +772,18 @@ export function redactCollectorText(input: string, options: RedactCollectorTextO
const tally = { count: 0 };
let text = applyRedaction(input, PRIVATE_KEY_BLOCK, tally);
text = applyRedaction(text, URL_USERINFO, tally);
- text = redactAssignments(text, tally);
+ text = redactAssignments(text, tally, options.mode ?? "config");
text = redactAwsSecrets(text, options.context, tally);
for (const redaction of SECRET_PATTERNS) text = applyRedaction(text, redaction, tally);
+ text = redactBearerTokens(text, tally);
for (const redaction of PII_PATTERNS) text = applyRedaction(text, redaction, tally);
return { text, count: tally.count };
}
function redactJsonValue(value: unknown, key: string | undefined, tally: { count: number }): unknown {
if (typeof value === "string") {
- if (key !== undefined && isSecretAssignmentKey(key) && isSecretAssignmentValue(value)) {
+ // A JSON string is always a quoted literal, scrubbed in CONFIG mode.
+ if (key !== undefined && isSecretAssignmentKey(key) && isSecretAssignmentValue(value, "config", true)) {
tally.count += 1;
return REDACTED;
}
@@ -758,14 +837,14 @@ export function redactCollectorJsonText(text: string): string | null {
/**
* Scrubs one workspace file for upload: `.json` files structurally (falling
* back to text when they do not parse), everything else as text with the path
- * as context.
+ * as context and the value rule mode the extension selects.
*/
export function redactCollectorContent(path: string, text: string): string {
if (/\.json$/i.test(path)) {
const json = redactCollectorJsonText(text);
if (json !== null) return json;
}
- return redactCollectorText(text, { context: path }).text;
+ return redactCollectorText(text, { context: path, mode: redactModeForPath(path) }).text;
}
/**
diff --git a/docs/workspace-collector-privacy.md b/docs/workspace-collector-privacy.md
index c6ed2e58..d6a1c4d5 100644
--- a/docs/workspace-collector-privacy.md
+++ b/docs/workspace-collector-privacy.md
@@ -1,3 +1,3 @@
# Workspace collector privacy rails
-The desktop server's workspace collector (`apps/server/src/workspace-collector.ts`) snapshots consented workspace files, git metadata and session traces for omnirush.ai; the backend applies the same denylist and scrubber server-side, so a rule changed on one side must land on the other, and the desktop side may only ever be the stricter of the two. Before anything leaves the machine, credential-named paths are dropped and counted in the envelope's `privacy.denied_file_count`: any path component whose words (split on space, `_`, `-`, `.`) include key(s), secret(s), token(s), password(s), passwd, credential(s), id_rsa, id_ed25519, netrc, npmrc, pypirc, kubeconfig, wallet, seed or mnemonic, plus `.aws`, `.ssh`, `.gnupg` and `.docker/config.json`, on top of the older `.env*`, `credentials*`, `secrets*`, `keys/`, `*.pem`/`*.key` rules. A file with a source-code or docs extension (`.ts`, `.py`, `.md`, `.json`, `.yml`, ...) is kept instead and scrubbed: a secret-named assignment (`password:`, `api_key =`, `"token":`, `export CLIENT_SECRET=`, in INI/YAML/JSON/dotenv/shell/source spelling; the key is split into segments on `_`, `-`, `.`, `:`, camelCase and letter/digit boundaries, and qualifies only when a whole segment or adjacent pair is a listed family word, so `author`, `keywords` and `tokenizer_class` never do) loses its value when that value is 8+ non-space characters with a letter and not a code expression or `<placeholder>`, provider token shapes (AWS access key ids and, near them, secret access keys; GitHub, Slack, Google, Stripe, OpenAI, Anthropic, JWTs, Discord, `Bearer` values, private key blocks, URL userinfo) become `[REDACTED]`, and personal identifiers become `[REDACTED_PII]`. `.json` files and the trace document are scrubbed as JSON (every string, keys included) so a redaction can never break an escape sequence; git diffs stay text. The same denylist filters the manifest, touched paths, git status and diff sections.
+The desktop server's workspace collector (`apps/server/src/workspace-collector.ts`) snapshots consented workspace files, git metadata and session traces for omnirush.ai; the backend applies the same denylist and scrubber server-side, so a rule changed on one side must land on the other, and the desktop side may only ever be the stricter of the two. Before anything leaves the machine, credential-named paths are dropped and counted in the envelope's `privacy.denied_file_count`: any path component whose words (split on space, `_`, `-`, `.`) include key(s), secret(s), token(s), password(s), passwd, credential(s), id_rsa, id_ed25519, netrc, npmrc, pypirc, kubeconfig, wallet, seed or mnemonic, plus `.aws`, `.ssh`, `.gnupg` and `.docker/config.json`, on top of the older `.env*`, `credentials*`, `secrets*`, `keys/`, `*.pem`/`*.key` rules. A file with a source-code or docs extension (`.ts`, `.py`, `.md`, `.json`, `.yml`, ...) is kept instead and scrubbed: a secret-named assignment (`password:`, `api_key =`, `"token":`, `export CLIENT_SECRET=`, in INI/YAML/JSON/dotenv/shell/source spelling; the key is split into segments on `_`, `-`, `.`, `:`, camelCase and letter/digit boundaries, and qualifies only when a whole segment or adjacent pair is a listed family word, so `author`, `keywords` and `tokenizer_class` never do) loses its value under value rule v2: in SOURCE mode (files with a programming-language extension: js, cjs, mjs, ts, tsx, jsx, py, go, rs, java, kt, c, cc, cpp, h, hpp, rb, php, swift, cs, scala, sh, bash, zsh, ps1, lua, dart, vue, svelte, map) a value is redacted only when it is 8+ non-space characters, not a code expression, `<placeholder>` or filesystem path, not an unquoted identifier or member expression (`config.token`, `tokenFile`), and carries a digit or is 20+ mixed-case characters, while CONFIG mode (every other extension, none, git diffs and the trace) keeps the permissive rule of 8+ characters with a letter, skipping only filesystem paths and unquoted dotted identifiers, and a key whose last segment is a structural word (`length`, `ttl`, `url`, `path`, `name`, `id`, `header`, `file`, `filename`, `dir`, `mode`, `method`, `role`, `owner`, `type`, `kind`, `enabled`, `estimate`, `hash`, `digest`, `at`, `config`, `client`, `prefix`, `suffix`, `format`, `scheme`, `provider`, `status`, `state`, `label`, `description`, `title`, `class`, `field`, `fields`, `list`, `names`, `version`, `timeout`, `limit`, `max`, `min`, `interval`, `retries`, `port`) never names a secret. A `Bearer` value is redacted only when its token carries a digit or is 20+ mixed-case characters that are not a bare identifier, the AWS 40-character proximity pass runs only on documents of three or more lines (a single-line JSON document relies on its key), and provider token shapes (AWS access key ids and, near them, secret access keys; GitHub, Slack, Google, Stripe, OpenAI, Anthropic, JWTs, Discord, `Bearer` values, private key blocks, URL userinfo) become `[REDACTED]`, and personal identifiers become `[REDACTED_PII]`. `.json` files and the trace document are scrubbed as JSON (every string, keys included) so a redaction can never break an escape sequence; git diffs stay text. The same denylist filters the manifest, touched paths, git status and diff sections.