Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Secret and sensitivity scanning (key files cluster)
The format-based secret detector shared by sources push, bootstrap verify, the
compiled-context sensitivity scan and the transcripts redactor, and the composed
sensitivity detector built on it.
src/core/secret-scan.ts— pattern-based secret detection shared bysources push, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface,digitaloceando[opr]_v1_+ 64 hex, the AI-provider keysopenroutersk-or-v1-+ 64 lowercase hex,groqgsk_+ 52,xaixai-+ 80,perplexitypplx-+ 48 andreplicater8_+ 37, all fixed-length with a hard right edge, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (bearer— prebuilt two-group layout so only the token is the value, which may hold a JSON-escaped\/(#8266);db_url_credentials— thescheme://user:pass@span of database URLs, host/db kept;url_credentials— the same span forhttp(s)(scheme case-insensitive,gi), user 0–128 stopping at://, password 1–256 excluding whitespace,@,",',/,?,#, with avalidatehook that rejects placeholder passwords (<...>,${...},$VAR, all*, allx);basic_auth— two prebuilt case-insensitive forms,Authorization: Basicwith a 4–2048 char value and bareBasicwith 16–2048, both with a hard right edge and avalidatethat requires the value to base64-decode to printable ASCII containing:; it is NOT in the bearer family, so it joins neither the echo dictionary norsecret:bearer). The pattern contract:CorePatterncarries optionalflags(default'g'),precheck,validate(value)(O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) andsince(the gbrain version that added or last changed the rule;SECURITY_WAVE_SINCE=0.60.31.0ondigitalocean,url_credentials,basic_authandprivate_key_pem,PROVIDER_KEYS_SINCEon the five AI-provider rules (#7959), kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. Every core rule and bothhigh_entropy_assignmentforms also have an escape-boundary twin (#7978), compiled right after the rule under the same name and anchored on a JSON escape (\n,\r,\t,\b,\f,\uXXXX, and since #8266\xNN,\UXXXXXXXX), a percent-escape (%XX), a quoted-printable=3Dor a terminal color code (ESC[…m, raw or written\u001b[/\x1b[/\033[/\e[), whose last character the default boundary reads as a word character; a twin runs only on a lineESCAPE_IN_LINE_REmatches, so other lines run the old list, and a prebuilt rule carries its twin asCorePattern.escaped.patternSince(pattern)reads the map; every finding of such a pattern carriesSecretFinding.since, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters:Bearer <vendor key>keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-onlylabeled_credentialrule (ScanOpts.labeledCredentials) lives insecret-scan-labeled.ts(Security). The opt-inhigh_entropy_assignmentrule (ScanOpts.highEntropy; its shapes and gates live insrc/core/secret-scan-assignment.ts, split out at the 1500-line module cap) is anchored on a credential keyword or on an identifier whose last word iskey(STRIPE_KEY=, neverMONKEY=or a bareKEY=) and requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimatecorrectedEntropy, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after"or', any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy[A-Za-z0-9+/_=-]class plus!#$%*@^~.?<>; never&,()[]{},:,,or;, so query strings, calls and SQLSETlists stay intact, and a password carrying,/;matches only quoted; the last character excludes.?!, so a sentence's full stop is not claimed). Itsvalidaterejects values that start withscheme://,./,~/,${,$(or<REDACTED:, dotted identifier paths (process.env.X) and/-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain,embed-facts.tserror text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist +<ws>/.gbrain-scan-allowper-finding overrides — deliberately NOT the repo's.gitleaks.toml(a public-repo CI fixture policy); the allowlist block (loadWorkspaceAllowlist, the glob dialectglobToRegExp/matchesGlob,valueAllowlisted/pathAllowlisted,SCAN_ALLOW_FILENAME, the 16-hex fingerprint floor, and rule entriespath:<glob> pattern:<rule>:ruleAllowEntry/withoutRuleAlloweddrop only that rule's findings in matching files and report the entry,allowlistProblemsnames malformed rule entries and unknown rule names, which allow nothing, and a barepath:glob;pathAllowlistednever reads a rule entry as a glob;scanFiles(ScanOpts.onAllowed), the range scan (RangeScan.allowed/allowlist_problems,scanAllowProblems), the push scan and bootstrap repo/verify apply and report them,test/secret-scan-rule-allow-2901.test.ts) lives insrc/core/secret-scan-allowlist.tssince wave 16 (G4.1, the 1500-line module cap) and is re-exported here unchanged (test/secret-scan-allowlist.test.ts).correctedEntropyis one histogram pass (distinct count = histogram size; byte-identical to the formershannonEntropy + Setform,test/secret-scan-entropy-equivalence.test.ts; ~80 → ~25 ms per 250 × 4096-char segment).ScanOpts.work/RedactOpts.worktakes aScanWorkaccumulator (src/core/secret-scan-work.ts: lines, regex execs, candidates per pattern, chars handed to the entropy gate counted insidecorrectedEntropy, validate calls, claims, union splits, echo sweeps) pinned exactly on the perf fixture bytest/secret-scan-work-counters.test.ts; the perf file's absolute bounds stay the only guard on per-character cost. Deliberately NOT patterns:sb_publishable_, Supabase project refs (identifiers, not credentials). Never spell a literal database orhttp(s)URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime;scripts/check-pg-url-redaction.shgrepssrc/for everydb_url_credentialsscheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line —db_url_credentials(user ≤128 stopping at://; password 1–256 stopping only at whitespace,@and the string delimiters"/', so unescaped/ { } < > | ^ \and backtick passwords redact),jwt(prebuilt so its boundary excludes-as well as_; segments ≤4096),high_entropy_assignment(≤64 identifier chars after the keyword, value ≤4096),url_credentials(user ≤128, password ≤256),basic_auth(value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-patternprechecksubstring gate on the catch-alls (@for both URL patterns;earer/EARER, since an all-capsBEARERscheme is accepted; a case-insensitivebasic), a carried next-newline position inscanPemBlocks(sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowedbuildPreview(whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment).redactFindings(=planRedaction+applyRedaction) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed bybearer,high_entropy_assignment,labeled_credentialand every vendor orjwtrule (#7978; notbasic_author the two URL userinfo catch-alls) form an echo dictionary (value → pattern; floorsECHO_MIN_CHARS_BEARER=ECHO_MIN_CHARS_VENDOR= 20 /ECHO_MIN_CHARS_ENTROPY= 12, values ≤ECHO_MAX_VALUE_CHARS= 512, the firstECHO_MAX_UNIQUE= 64 unique bearer, assignment and labeled values plus, under their own cap, the firstECHO_MAX_UNIQUE_VENDOR= 32 unique vendor orjwtvalues, in claim order, so planted vendor strings never crowd out a bearer token's echo — a value past a cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (indexOfresuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings.planRedactionfeeds a caller-supplied shared map (RedactOpts.echoValues) andapplyRedactionreads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another.basic_authand the URL userinfo catch-alls redact exactly whatscanTextreports; a vendor value embedded past its boundary (token_<key>) is scrubbed as an echo when the same value is claimed elsewhere in the document, and left as-is otherwise. PRIVATE KEYS:pemClaimsfindsBEGIN/END … PRIVATE KEYfences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END withinPEM_BODY_MAX_CHARS(16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (A-Za-z0-9+/=) indented by up to 16 spaces/tabs; line ends are\n,\r\nor the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421Proc-Type:/DEK-Info:lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays withinPEM_BODY_MAX_CHARS. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carrieslegacyFingerprint, the header-only fingerprint earlier releases reported, soworkspace-push.tscan name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key.privateKeySpans(text)exports the same claims as sorted, disjoint{start, end}spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (>) keys, base64 runs over 128 chars, body past 16384 chars,http(s)passwords containing a literal/,?or#, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing,or;. False-positive budget:scripts/secret-scan-fp-budget.tsdiffs findings against a base ref's scanner (--base, defaultorigin/master) (--dir <brain>reports per-pattern counts only, never content) andtest/secret-scan-fp-budget.test.tspins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests:test/secret-scan-credential-shapes.test.ts,test/secret-scan-private-key-spans.test.ts. Perf pins:test/secret-scan-perf.test.ts. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.src/core/secret-scan-cookie.ts— the transcript-lanecookie_headerrule (GST-2768), run byscanInternalonly underScanOpts.transcriptRules(TRANSCRIPT_LANE_SCAN_OPTSinsecret-scan.ts: redactSession, the recent-transcripts read andtranscripts audit-secrets).cookieHeaderValues(line)reads thename=valuepairs after aCookie:/Set-Cookie:header (any case, quoted or JSON-escaped) or a curl-b/--cookieargument and returns the values only (8+ chars, no placeholder or mask);Set-Cookiestops after its first pair, and parsing stops at the first segment that is notname=value. A quoted value may be JSON-escaped (sid=\"…\", up to three backslashes before each quote), andcurlContinuescarries a curl command across lines ending in\, so a-balone on a continued line (Chrome's "Copy as cURL") is curl's (scanInternalpassesinCurl). Values join the echo dictionary at 12 chars under their own cap,ECHO_MAX_UNIQUE_COOKIE= 64, apart fromECHO_MAX_UNIQUE.test/secret-scan-push-gate-unchanged.test.tspins every non-transcript option set byte-identical on the synthetic corpustest/fixtures/transcripts/synthetic-credentials.ts.src/core/secret-scan-transcript.ts—compileTranscriptPatterns(), the transcript-lane-only labeled rules (TRANSCRIPT_LABELED_PATTERNSfromsecret-scan-labeled.ts: the.netrcforms and thekey/netrccontinuations) compiled aslabeled_credentialforbuildPatternsinsecret-scan.tsunderScanOpts.transcriptRules, after every other rule. Moved out ofsecret-scan.tsat its 1500-line cap with no logic change.src/core/secret-scan-stream.ts—scanTextStream(chunks, opts), the windowed scan of a byte stream too large to hold as one string (the push gate's staged blobs over 25 MiB). Bytes are decoded by a streamingTextDecoder(ignoreBOM, so a split multi-byte character joins and invalid bytes become U+FFFD asBuffer.toStringmakes them) and handed toscanTextSpans(secret-scan.ts:scanTextplus each claim's absolute span, allowlisted claims kept withfinding: null) in windows of at mostSTREAM_SCAN_WINDOW_CHARS(8 Mi UTF-16 units). Each next window starts at a line start at leastSTREAM_SCAN_OVERLAP_CHARS(64 Ki, above the longest claim: a private key's 16384-char body plus fences, a jwt's 3 × 4096) before the previous end, or mid-line at exactly the overlap (never inside a surrogate pair) when the line is too long. A window keeps the claims that start before the next window's start, the last window keeps the rest, and a claim wholly inside a span an earlier window kept (a seam's partial view, or an exact duplicate) is dropped; lines are 1-based over the whole stream.streamScanWork(@internal) counts windows, bytes, scanned chars and the largest window.test/secret-scan-stream.test.tspins equality withscanTextacross both seams of a window, mid-line splits, split multi-byte characters, invalid UTF-8 and a BOM.src/core/context/sensitivity-scan.ts— composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with theBearerkeyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface aspii:bearer. Every family honors the same.gbrain-scan-allowfingerprint escape hatch.formatSensitivityDrop(drop, workspaceRoot)renders the one content-free stderr linegbrain compile-contextprints per dropped entry: reasonsensitivity_scan, the pattern family, the fingerprint and the absolute.gbrain-scan-allowpath, never the value (test/sensitivity-scan.test.ts).