Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(transcripts): keep redacting dash-leading passwords, setting-like pair users and wide tables (W12 S1-S4)
time-attackc46853cf34cb
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex 67a1a8a7b9..25243bff10 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -24,6 +24,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/scope.ts` — OAuth scope hierarchy + allowlist (the 6 scope strings, `hasScope`, `assertAllowedScopes`, `filterAllowedScopes`, `parseScopeString`, `normalizeScopesInput`) AND the anonymous-registration policy: `DCR_REGISTRABLE_SCOPES` (`read`, `write`) and `dcrScopeViolation(requested, grantTypes)` — returns `null` when the requested scopes fit the Dynamic Client Registration ceiling, otherwise the `invalid_client_metadata` message naming the offending scopes and the operator remedy (`gbrain auth register-client` / admin API / `gbrain auth rescope-client <client_id> --scopes ...`). `agent` keeps its own "operator-approved grant with explicit delegation bindings" wording; when `grantTypes` includes `client_credentials` (only reachable under `--enable-dcr-insecure`) the ceiling is `read` alone; unknown scope strings are ignored here (the unknown-filter drops them). `scopesSupportedForDiscovery({ enableDcr })` is the `scopes_supported` list for OAuth discovery (consumed by `serve-http.ts`'s `authRouterOptions`): the DCR-registrable subset (`read write`, canonical order) while DCR is enabled — so a client that copies discovery into its registration passes `dcrScopeViolation` — and every scope except `agent` otherwise; it never narrows an operator-registered client, because a client that omits `scope` at `/authorize` receives its full registered set via `grantScopes` (`oauth-grants.ts`) and an explicit request is intersected with the registration. The DCR constants and the helper sit BELOW `ALLOWED_SCOPES_LIST`, and no comment line pairs that identifier with `[`, because `scripts/check-admin-scope-drift.sh` extracts the allowlist block with an awk match on exactly that pair. Pinned by `test/scope.test.ts` + `test/oauth-dcr-scope-ceiling.test.ts` + the discovery test in `test/e2e/serve-http-consent.test.ts`.-- `src/core/secret-scan-labeled.ts` — the transcript-lane `labeled_credential` detector (#6147 idea, widened), compiled by `secret-scan.ts` only under `ScanOpts.labeledCredentials` (transcript pages, the recent-transcripts read and `transcripts audit-secrets`), after every other rule so a vendor or entropy claim keeps attribution. SINGLE labels (`password|passwd|passcode|passphrase|pwd`, optional identifier prefix, JSON-key quote, markdown bold) before `:`/`=`/`:`, and PAIR labels (`login|log-in|credentials|creds|user/pass|username/password|…`) before `:`/`=`/`:`/` - `/nothing then `user / pass` or `user:pass`, each in a bare and a quoted/backticked form; only the password half is claimed. `labeledValueIsCredential(value, form, head)` (the scanner passes the match head to `validate`) rejects placeholders, masks, templating, URLs, paths, calls, dotted references, digitless code identifiers, a backtick that closes a code span holding the label, a meeting link's `?pwd=`, and `LABELED_STOPLIST` words; a pair's password also needs 4+ chars with a letter and a digit or symbol, and its user half must not be a stopword. W4.1 widens it: CLI flags with a separate value (`--password X`, `--pass "a b"`; suffixed flags such as `--password-file` are not labels), an env-name suffix after the label (`PASSWORD_DB=`; a setting suffix such as `_FILE`/`_MIN_LENGTH`/`_HINT` rejects via `settingSuffix`), values starting with `-` rejected, and Markdown tables (`tableCredentialCells` with per-scan `TableScanState`: cells under a password-label header column and the value cell of a non-header `| password | X |` row; escaped pipes, no outer pipes, several columns). `danglingLabel` gates the next-line continuation patterns per form: `pair` after a dangling pair, `single` (the whole next line is the value, validated as a single label) after a line ending in a single label and delimiter; such a line, and a table row with a claimed cell, is scanned even when shorter than 8 chars. Claimed values join the echo dictionary at `ECHO_MIN_CHARS_LABELED` = 8 when `labeledEchoEligible`. Every quantifier is bounded (perf-pinned in `test/secret-scan-perf.test.ts`); acceptance table in `test/transcript-labeled-credential.test.ts`; user doc `docs/guides/data-ingestion.md#credential-redaction`.+- `src/core/secret-scan-labeled.ts` — the transcript-lane `labeled_credential` detector (#6147 idea, widened), compiled by `secret-scan.ts` only under `ScanOpts.labeledCredentials` (transcript pages, the recent-transcripts read and `transcripts audit-secrets`), after every other rule so a vendor or entropy claim keeps attribution. SINGLE labels (`password|passwd|passcode|passphrase|pwd`, optional identifier prefix, JSON-key quote, markdown bold) before `:`/`=`/`:`, and PAIR labels (`login|log-in|credentials|creds|user/pass|username/password|…`) before `:`/`=`/`:`/` - `/nothing then `user / pass` or `user:pass`, each in a bare and a quoted/backticked form; only the password half is claimed. `labeledValueIsCredential(value, form, head)` (the scanner passes the match head to `validate`) rejects placeholders, masks, templating, URLs, paths, calls, dotted references, digitless code identifiers, a backtick that closes a code span holding the label, a meeting link's `?pwd=`, and `LABELED_STOPLIST` words; a pair's password also needs 4+ chars with a letter and a digit or symbol, and its user half must not be a stopword. W4.1 widens it: CLI flags with a separate value (`--password X`, `--pass "a b"`; suffixed flags such as `--password-file` are not labels), an env-name suffix after the label (`PASSWORD_DB=`; a setting suffix such as `_FILE`/`_MIN_LENGTH`/`_HINT` rejects via `settingSuffix`), a `cli` form (prefixed flags such as `--db-password`, `--pw`, openssl `-passin pass:`) whose value may not start with `-` (other forms keep `-`-leading passwords), the setting-suffix exemption only for single labels, and Markdown tables (`tableCredentialCells`, `pw`/`Password (prod)` headers, `|-|` separators, a per-row column Set so a row is linear in cells with per-scan `TableScanState`: cells under a password-label header column and the value cell of a non-header `| password | X |` row; escaped pipes, no outer pipes, several columns). `danglingLabel` gates the next-line continuation patterns per form: `pair` after a dangling pair, `single` (the whole next line is the value, validated as a single label) after a line ending in a single label and delimiter; such a line, and a table row with a claimed cell, is scanned even when shorter than 8 chars. Claimed values join the echo dictionary at `ECHO_MIN_CHARS_LABELED` = 8 when `labeledEchoEligible`. Every quantifier is bounded (perf-pinned in `test/secret-scan-perf.test.ts`); acceptance table in `test/transcript-labeled-credential.test.ts`; user doc `docs/guides/data-ingestion.md#credential-redaction`.- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.diff --git a/src/core/secret-scan-labeled.ts b/src/core/secret-scan-labeled.tsindex 80cb6c9c4c..45b2181c10 100644--- a/src/core/secret-scan-labeled.ts+++ b/src/core/secret-scan-labeled.ts@@ -64,11 +64,14 @@ const PAIR_USER = `(?:${QUOTE}[^"'\`\\n/]{1,128}${QUOTE}|[^\\s/:"'\`]{1,128})`;const PAIR_SEP = '(?:\\s{0,4}/\\s{0,4}|:(?![/\\s]))';const LABEL_SUFFIX = '(?:_[A-Za-z0-9]{1,16}){0,2}';const SINGLE_HEAD = `${LEFT}[A-Za-z0-9_]{0,32}${SINGLE_LABEL}${LABEL_SUFFIX}${LABEL_END}${BOLD}${QUOTE}?\\s{0,4}${DELIM}${BOLD}\\s{0,4}`;-const CLI_HEAD = '(?:^|\\s)--?(?:pass(?:word|wd|phrase)?|pwd)(?![A-Za-z0-9_=-])\\s{1,4}';+const CLI_HEAD = '(?:^|\\s)--?(?!(?:no|skip|ask|prompt|reset|show|print|change|check|require)[-_])(?:[A-Za-z0-9]{1,16}[-_]){0,3}(?:pass(?:word|wd|phrase)?|pwd|pw)(?![A-Za-z0-9_=-])\\s{1,4}';+/** openssl's `-passin pass:X` / `-passout pass:X`. */+const OPENSSL_PASS_HEAD = '(?:^|\\s)-pass(?:in|out)\\s{1,4}pass:';export interface LabeledPattern {source: string;- form: 'single' | 'pair';+ /** `cli`: a single label written as a command-line flag, whose value never starts with `-` (that is the next flag). */+ form: 'single' | 'pair' | 'cli';/** Runs only on the line after one that ends in a dangling label of this form. */continuation?: 'single' | 'pair';}@@ -80,15 +83,16 @@ export const LABELED_CREDENTIAL_PATTERNS: readonly LabeledPattern[] = [{ form: 'pair', source: `(${PAIR_HEAD}${PAIR_USER}${PAIR_SEP}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },{ form: 'pair', source: `(${PAIR_HEAD}${PAIR_USER}${PAIR_SEP})(${BARE_PASS})${BARE_END}` },{ form: 'pair', continuation: 'pair', source: `(^\\s{0,8}${QUOTE}?)(${BARE_PASS})${BARE_END}` },- { form: 'single', source: `(${CLI_HEAD}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },- { form: 'single', source: `(${CLI_HEAD})(${BARE_VALUE})${BARE_END}` },+ { form: 'cli', source: `(${CLI_HEAD}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },+ { form: 'cli', source: `(${CLI_HEAD})(${BARE_VALUE})${BARE_END}` },+ { form: 'cli', source: `(${OPENSSL_PASS_HEAD})(${BARE_VALUE})${BARE_END}` },// The whole next line is the value (optionally quoted), so prose under a `Password:` heading is never claimed.{ form: 'single', continuation: 'single', source: `(^\\s{0,8}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE}[,;]?\\s*$)` },{ form: 'single', continuation: 'single', source: `(^\\s{0,8})(${BARE_VALUE})(?=[.,;]?\\s*$)` },];/** Cheap gate before the label regexes run on a line. */-export const LABELED_PRECHECK_RE = /pass|pwd|log-?in|cred/i;+export const LABELED_PRECHECK_RE = /pass|pwd|\bpw\b|log-?in|cred/i;// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- compile-time literal; bounded quantifiersconst PAIR_DANGLING_RE = new RegExp(`${PAIR_HEAD}${PAIR_USER}\\s{0,4}/\\s{0,4}$`, 'i');@@ -196,16 +200,19 @@ const PAIR_USER_TAIL_RE = /([^\s/:"'`*]+)["'`]?\s*[/:]\s*["'`]?$/;* or symbol, and its user half must not be a stoplisted word* (`login page / step2`).*/-export function labeledValueIsCredential(value: string, form: 'single' | 'pair', head = ''): boolean {- if (value.length < 3 || isStopword(value) || value.startsWith('-')) return false;- if (settingSuffix(head)) return false;+export function labeledValueIsCredential(value: string, form: 'single' | 'pair' | 'cli', head = ''): boolean {+ if (value.length < 3 || isStopword(value)) return false;+ // A flag's "value" starting with `-` is the next flag; a typed password may start with `-` (W12 S1).+ if (form === 'cli' && value.startsWith('-')) return false;+ // Only a single env-style label carries a setting suffix (`PASSWORD_FILE=`); a pair's user half may look like one (W12 S2).+ if (form === 'single' && settingSuffix(head)) return false;if (head.endsWith('`') && closesCodeSpan(head)) return false;if (QUERY_PWD_RE.test(head)) return false;if (PLACEHOLDER_PREFIX_RE.test(value) || MASK_RE.test(value) || URL_RE.test(value) || PATH_RE.test(value)) return false;if (value.includes('(') || DOTTED_IDENTIFIER_RE.test(value)) return false;const digitless = !/[0-9]/.test(value);if (IDENTIFIER_RE.test(value) && digitless && (LABEL_WORD_RE.test(value) || COMPOUND_IDENTIFIER_RE.test(value))) return false;- if (form === 'single') return true;+ if (form !== 'pair') return true;const user = PAIR_USER_TAIL_RE.exec(head)?.[1];if (user !== undefined && isStopword(user)) return false;return value.length >= 4 && LETTER_RE.test(value) && PAIR_SYMBOL_RE.test(value) && !VERSION_RE.test(value);@@ -217,8 +224,8 @@ export function labeledEchoEligible(value: string): boolean {}/** A password-label column header or key cell (`Password`, `DB password`, `pwd`), after stripping Markdown emphasis and a colon. */-const TABLE_LABEL_RE = /^(?:[a-z0-9]{1,32}[ _-])?(?:pass(?:word|wd|code|phrase)|pwd)$/;-const TABLE_SEPARATOR_CELL_RE = /^:?-{3,}:?$/;+const TABLE_LABEL_RE = /^(?:[a-z0-9]{1,32}[ _-])?(?:pass(?:word|wd|code|phrase)|pwd|pw)$/;+const TABLE_SEPARATOR_CELL_RE = /^:?-+:?$/;interface TableCell { start: number; text: string }@@ -245,7 +252,8 @@ function isSeparatorRow(cells: TableCell[] | null): boolean {}function isLabelCell(text: string): boolean {- return TABLE_LABEL_RE.test(text.replace(/[*_`]/g, ' ').trim().replace(/:$/, '').replace(/\s+/g, ' ').toLowerCase());+ // A trailing qualifier names the same column (`Password (prod)`).+ return TABLE_LABEL_RE.test(text.replace(/[*_`]/g, ' ').trim().replace(/:$/, '').replace(/\s*\([^()]{0,64}\)$/, '').replace(/\s+/g, ' ').toLowerCase());}/** The value inside a cell: trimmed, without one pair of surrounding backticks or quotes. */@@ -293,10 +301,12 @@ export function tableCredentialCells(line: string, next: string | undefined, staconst v = cell ? cellValue(cell) : null;if (v && !isLabelCell(v.value) && labeledValueIsCredential(v.value, 'single')) out.push(v);};- if (state.columns) for (const k of state.columns) claim(cells[k]);+ // One Set per row keeps the key/value pass linear in cells (W12 S3).+ const columns = new Set(state.columns ?? []);+ for (const k of columns) claim(cells[k]);if (next === undefined || !isSeparatorRow(tableCells(next))) {for (let k = 0; k + 1 < cells.length; k++) {- if (isLabelCell(cells[k]!.text) && !state.columns?.includes(k + 1)) claim(cells[k + 1]);+ if (isLabelCell(cells[k]!.text) && !columns.has(k + 1)) claim(cells[k + 1]);}}return out;diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.tsindex e0e3ac554d..632398fa11 100644--- a/test/secret-scan-perf.test.ts+++ b/test/secret-scan-perf.test.ts@@ -509,6 +509,7 @@ describe('labeled_credential (transcript lane): every candidate start does const['a 10k-row table with two credential columns', ['| user | password | pwd |', '|---|---|---|', ...Array.from({ length: 10_000 }, (_, k) => `| u${k} | s3cret${k} | p${k}x\\|y |`)].join('\n')],['a 200 KB row of escaped pipes', '| password | ' + '\\|'.repeat(100_000) + ' |'],['200 KB of `--password `', '--password '.repeat(20_000)],+ ['a 64k-cell row of label cells under 64k password columns (W12 S3)', ['|' + 'password|'.repeat(64_000), '|' + '---|'.repeat(64_000), '|' + 'pwd|'.repeat(64_000)].join('\n')],];for (const [name, text] of adversaries) {test(`${name}: redact < 400ms`, () => {diff --git a/test/transcript-labeled-credential.test.ts b/test/transcript-labeled-credential.test.tsindex af47a56a10..3f94071db0 100644--- a/test/transcript-labeled-credential.test.ts+++ b/test/transcript-labeled-credential.test.ts@@ -68,6 +68,21 @@ const MUST_REDACT: Array<[string, string]> = [['table with two credential columns', `| password | user | pwd |\n|---|---|---|\n| ${PW} | alice-example | x${PW}y |`],['key/value table row', `| password | ${PW} |`],['table with CRLF', `| user | password |\r\n|---|---|\r\n| alice-example | ${PW} |\r\n`],+ // W12 S1: a password that starts with "-" (redacted before W4.1; only a CLI flag's value may not start with "-")+ ['single label, value starting with -', `password: -${PW}`],+ ['pair, password starting with -', `login: alice-example / -Xy9${PW}!q`],+ ['quoted env value starting with -', `DB_PASSWORD="-${PW}"`],+ ['single label, value starting with --', `password: --${PW}x9`],+ // W12 S2: a pair whose user half looks like a setting suffix+ ['pair with a setting-like user name', `login: pass_auth / ${PW}x9`],+ // W12 S4+ ['prefixed CLI flag', `aws rds modify-db-instance --master-user-password ${PW}x9`],+ ['db-password flag', `tool --db-password ${PW}x9`],+ ['openssl -passin', `openssl rsa -in key.pem -passin pass:${PW}x9`],+ ['pw flag', `client --pw ${PW}x9`],+ ['table with |-|-| separators', `|user|password|\n|-|-|\n|alice-example|${PW}|`],+ ['pw column header', `| user | pw |\n|---|---|\n| alice-example | ${PW} |`],+ ['qualified column header', `| user | Password (prod) |\n|---|---|\n| alice-example | ${PW} |`],];const MUST_KEEP: Array<[string, string]> = [@@ -108,6 +123,10 @@ const MUST_KEEP: Array<[string, string]> = [['pass the test', 'make sure we pass the test suite'],['prose under a password heading', 'Password:\nYou can change it in the settings page'],['pass/fail column', '| test | pass |\n|---|---|\n| auth | ok2 |'],+ // W12 S1/S4: a flag is never a flag's value; boolean and action flags are not labels+ ['flag followed by another flag', 'tool --password --interactive --verbose'],+ ['no-password boolean flag', 'ssh-keygen --no-password build-key'],+ ['skip-password flag', 'tool --skip-password-check release2'],];describe('labeled_credential on the transcript page lane', () => {