# leaks spec ## Authority This spec is the source of truth for future `leaks` work. The current implementation is a prototype/reference. When code and this spec disagree, change code to match this spec unless the user explicitly updates the spec first. Implementation must be fresh and spec-shaped. Do not preserve legacy structure for compatibility. Practical path: overwrite `extensions/leaks/index.ts`, tests, and README in place instead of moving the extension directory. Git history is the reference for old code. Avoid creating `extensions/leaks-ref` because extension checks may treat it as a real extension. ## Mission Protect provider-bound plaintext exposure. `leaks` redacts conversation, tool, and session text before model/provider requests. It does not redact provider authentication headers or API keys needed to call the selected provider. It keeps local Pi session and tool behavior unredacted except for placeholder round trips. It is not an exfiltration guard, sandbox, DLP layer, or permission system. Tool-risk control belongs to Pi permissions, sandboxing, and tool policy. ## Core requirements Normal Pi workflows must be unhindered. `leaks` is transparent by default. Local user-visible/session behavior must preserve original values unless provider-bound text needs placeholders. The known exception is semantic transformation of secret internals: the model cannot edit bytes it cannot see. Copying, moving, renaming keys around, or preserving placeholders exactly must keep working. `leaks` runs on every provider turn and can touch every user/tool/assistant text field. Image, audio, binary, and OCR redaction are out of scope. Hot path work must be bounded by input size, rule count, and match count. Avoid O(n²) traps in hot paths. Precompile regexes. Bound learned exact values and restorable placeholder mappings to 8192 each. Bound deep traversal by object identity and depth 64. On learned-value cap overflow, stop learning new dotenv/env exact values and warn once. On restorable-mapping cap overflow, still redact provider-bound secrets with non-restorable placeholders, warn once, and keep existing mappings stable. `leaks` must tolerate faulty user input. The only planned user input is the `regex` setting. Faulty input must fall back and warn. At worst, ignore faulty user input plus warning. `leaks` must never prevent Pi from loading. If detector logic fails at runtime, fail open for that pass, warn, and continue. `leaks` extension UX must never print values it classified or learned as secrets. This applies to notifications, status output, errors, logs, and diagnostics. Normal local session/tool restoration may show original values because local Pi already had them. `/leaks test` is a local diagnostic and may show false negatives because missed secrets are unknown to `leaks`. The provider boundary is the hard gate. Context redaction is opportunistic. Provider payload redaction is authoritative. Redaction must run on context copies and again on provider payloads. Provider serialization may reshape or inject text after context processing. ## Core model Provider sees placeholders. Local Pi keeps placeholder mappings in memory only. Mappings must never be persisted to session files, logs, settings, or disk. Reload, new session, process exit, and `/leaks clear` may make old placeholders unrestorable. Local restoration may happen for tool args and final assistant messages. Placeholders are local capabilities. Normal Pi workflows must keep working locally when placeholders are copied or moved exactly. Placeholder format: ```text __LEAK_[_...]_[_N]__ ``` `HMAC12` is the first 12 lowercase hex chars of an HMAC over the secret value. The HMAC key is random, in-memory, and never persisted. `_N` is used only to resolve an actual placeholder collision inside the current mapping table. Tags preserve metadata. Secret values stay hidden. Metadata is not secret for this extension's threat model. Tag sources: - dotenv key names - `ENV_KEY` for process environment values - custom regex labels - built-in detector names - structure component labels - service/type labels The same secret value must keep one stable placeholder once first seen and stored. Tags do not evolve after first mapping. This avoids confusing the model with multiple placeholders for one secret. Non-restorable overflow placeholders are exempt from stability. When multiple tags are available for the same secret span on first mapping, order them by semantic priority: 1. dotenv key name or `ENV_KEY` 2. structure component 3. custom regex label 4. built-in type 5. generic class Match selection: - merge labels for identical spans before placeholder creation - select component parsers before enclosing exact learned values - select exact learned values before generic regexes - for overlapping non-identical spans, keep the smallest secret-bearing span unless a higher-confidence rule requires a larger span - private key blocks and JWTs are intentionally whole-span rules - never replace text inside an existing placeholder Cap tags to 6 per placeholder. Cap each tag to 64 characters after sanitization. The 8192 restorable-mapping cap is the chosen memory bound. Examples: ```text __LEAK_STRIPE_LIVE_SECRET_KEY_STRIPE_TOKEN_8f31aa77c901__ __LEAK_OPENROUTER_API_KEY_OPENROUTER_TOKEN_41c0e9aa1204__ __LEAK_DATABASE_URL_DB_PASSWORD_POSTGRES_URL_ba29d4ff8810__ ``` Do not encode secret length, alphabet, prefix bytes, suffix bytes, entropy, or shape. Do not provide homomorphic encryption, symbolic transform tools, or secret-byte edit algebra for now. The accepted tradeoff is that the model cannot inspect or transform secret internals. Users enabling leaks cannot rely on the model to semantically edit secret values. Copying, moving, renaming keys around, or preserving placeholders exactly must remain supported. ## Pi integration strategy Use these Pi hooks: - `session_start`: initialize settings, dotenv/env learning, status - `context`: redact message copies opportunistically - `before_provider_request`: redact final provider payload authoritatively - `tool_call`: restore placeholders in tool args before local execution - `message_end`: restore placeholders in finalized local assistant messages Do not persist mappings with `appendEntry`. Do not register tools. Use one slash command: `/leaks`. ## Settings Planned settings surface: ```json { "leaks": { "regex": [{ "pattern": "foo_[A-Za-z0-9]{32}", "label": "FOO_TOKEN" }] } } ``` Allowed setting: - `regex`: custom org/project token patterns. Only `pattern` and `label` are accepted. `flags` is not accepted; unsupported fields warn and are ignored. Pattern length is capped at 512 characters. Label length is capped at 64 characters. Unsafe patterns are ignored with a warning. Safety validation must reject obvious catastrophic constructs: backreferences, lookarounds, nested quantifiers, quantified alternation groups, empty alternatives, and dot-star catchalls. This is not a theorem prover; cheap rejection beats hanging Pi. Custom regex semantics: - zero capture groups redact full match - one capture group redacts group 1 - multiple capture groups redact group 1 and warn Faulty custom regex input must not break Pi startup or provider requests. It must produce minimal, visible UX: - count warnings/errors in `/leaks status` - list safe warning/error text when possible - do not print secret values - include settings file and line only when cheap and reliable - otherwise omit location Regex warning/error examples: - missing label - invalid regex syntax - unsupported fields such as `flags` - too many capture groups - empty label after sanitization - pattern too broad or unsafe by cheap validation Custom regex entries without labels still load with fallback tag `CUSTOM_REGEX`, but they warn. Metadata is a goal; unlabeled regex is bad UX. Custom regex labels must already match `[A-Z0-9_]{1,64}`. Invalid labels warn and fall back to `CUSTOM_REGEX`. Raw labels are never preserved in placeholders. Rejected settings: - `enabled`: no project-level off switch for provider protection. - `keywords`: regex subsumes it. - `exclude`: false positives must be solved by smarter detection, not user patch lists. - `secretFiles`: misleading name and wrong abstraction. ## Built-in detection Built-in token rules are always active. They cover these minimum detector families: - AI provider keys with distinctive prefixes or key context - VCS and package-manager tokens - cloud access keys and credential-like IDs - payment, messaging, webhook, and mail service tokens - auth, OAuth, JWT, cookie, and session secrets - database and cache credentialed connection strings - private key material listed below - generic sensitive-key assignments with non-weak values, including `KEY`, `KEY_DATA`, `PASS`, `PAT`, `PASSPHRASE`, `PEPPER`, `LICENSE_KEY`, `MASTER_KEY`, `ROUTING_KEY`, `ENCRYPTION_KEY`, `SECRET_KEY_BASE`, `SEED`, `UNSEAL_KEY`, and `MNEMONIC` key names Redact credential-like IDs such as AWS access key IDs when a reliable provider-specific pattern exists. Do not redact arbitrary account IDs, customer IDs, org IDs, project IDs, hostnames, or domains. ## Dotenv and environment values Dotenv discovery gives exact-match memory for bare secret values later in logs or prompts. Example: ```env PASSWORD=horse-battery-correct ``` Later text: ```text auth failed for horse-battery-correct ``` The bare value may not match token-shaped rules. The dotenv source teaches `leaks` to redact it exactly. Dotenv source files are fixed and automatic: - `.env` - `.env.local` - `.env.*.local` No recursive dotenv discovery. No user-configured file list. The old `secretFiles` name is misleading because parsing is dotenv-specific. Process environment variables must use the same classifier as dotenv values. Do not report process environment variable names or values in status output. A dotenv/env value is learned for redaction only when: - key name is sensitive and value is not weak/common safe material, or - value shape is high-confidence secret material. Credentialed URL dotenv/env values are parsed before learning. When parsing succeeds, learn/redact parsed secret components, not the whole URL. When parsing fails, fall back to exact-value learning only if the value is non-weak. Credentialed URL redaction must preserve URL structure and redact only parsed secret components. URL usernames are metadata, not secrets. URL passwords are secrets. Query parameter names are metadata. Sensitive query parameter values are secrets and must be redacted in place. HTTP header names are metadata. Sensitive header values are secrets and must be redacted in place. Cookie names are metadata. Sensitive cookie values are secrets and must be redacted in place. Structured config formats are not parsed generically. There are too many formats to support cleanly. Do use common one-line assignment detectors across env, properties, YAML, JSON, TOML, INI, HCL, XML-ish text, and shell-ish text. Redact the value only when the key is sensitive and the value is not weak/common safe material, or when the value is high-confidence secret material. Shell commands are not parsed as shell. Header, query-param, URL, and assignment detectors must catch common secret components inside shell text. Do not redact whole shell commands just because they contain a secret. JWTs are redacted as whole tokens. JWT header/payload decoding is out of scope. Private key material is redacted as whole logical secrets. Covered private-key shapes include PEM/OpenSSH/PGP private key blocks, encrypted cosign key blocks, PuTTY PPK private sections, age secret keys, and minisign secret keys. Boundary/comment metadata becomes placeholder tags instead of being preserved literally. Private key armors are redacted as whole secret values; literal boundaries are not preserved. Public keys and public certificates are metadata, not secrets. Do not redact SSH public keys or certificate blocks unless a private-key-looking block is present. URLs without credentials are not secret just because their key is `DATABASE_URL`, `REDIS_URL`, or `MONGO_URL`. Sensitive key matching is case-insensitive, treats `_` and `-` as equivalent separators, and allows numeric suffixes such as `_1`. Sensitive key examples: - `TOKEN` - `SECRET` - `PASSWORD` - `PASSWD` - `PASS` - `PEPPER` - `API_KEY` - `ACCESS_KEY` - `PRIVATE_KEY` - `KEY` - `KEY_DATA` - `PAT` - `PASSPHRASE` - `LICENSE_KEY` - `MASTER_KEY` - `ROUTING_KEY` - `ENCRYPTION_KEY` - `SECRET_KEY_BASE` - `SEED` - `UNSEAL_KEY` - `MNEMONIC` - `CLIENT_SECRET` - `AUTH` - `CREDENTIAL` - `SESSION` - `COOKIE` - `JWT` - `DATABASE_URL` - `MONGO_URL` - `REDIS_URL` Public key prefixes must not create exact-match secrets by key name alone: - `PUBLIC_` - `NEXT_PUBLIC_` - `VITE_` These prefixes suppress only key-name sensitivity. High-confidence secret value shapes under public prefixes are still redacted. Weak/common values are ignored. Examples: - booleans - nullish words - plain numbers - short strings - ordinary hostnames - ordinary URLs without credentials - usernames and distinguished names - comments, defaults, endpoint labels, and network ranges - IDs unless they match a credential-like provider-specific pattern Bare high-entropy strings are visible unless: - they match a high-confidence built-in secret shape, or - they were learned from a sensitive dotenv/env source. Environment and CI secret references are metadata, not secret values. Do not redact references such as `$API_KEY`, `${API_KEY}`, `${{ secrets.PROD_TOKEN }}`, or `process.env.API_KEY`. Private names, customer names, project codenames, hostnames, and internal domains are metadata, not secret values. Do not redact them with built-ins. Use custom regex only if the user explicitly wants that behavior. ## False positives False positives matter because the model loses semantic content. Transparent restore works only when the model copies the placeholder exactly. If the model must reason about or transform the redacted value, placeholder opacity hurts. Examples: - comparing two URLs - editing one component of a hostname/path - explaining a branch name or package name - preserving hostname but changing port For real secrets, semantic opacity is acceptable. For normal values, it is damage. Detection must stay high-confidence. Mitigation strategy: - leak metadata aggressively - protect secret values only - do not redact bare entropy without secret context - select the smallest secret-bearing span - preserve safe surrounding structure - redact full enclosing value only when no safe component parser exists Examples: ```text DATABASE_URL=postgres://alice:pw@db/app ``` Provider output: ```text DATABASE_URL=postgres://alice:__LEAK_DATABASE_URL_DB_PASSWORD_0123abcdef45__@db/app ``` Not: ```text DATABASE_URL=__LEAK_DATABASE_URL_0123abcdef45__ ``` For URL query params: ```text https://api.example.com/callback?token=abc123&user=me ``` Provider output: ```text https://api.example.com/callback?token=__LEAK_QUERY_TOKEN_0123abcdef45__&user=me ``` For HTTP headers: ```text Authorization: Bearer abc123 Authorization: Basic dXNlcjpwYXNz Cookie: session=xyz; theme=dark X-API-Key: key123 ``` Provider output: ```text Authorization: Bearer __LEAK_AUTHORIZATION_BEARER_0123abcdef45__ Authorization: Basic __LEAK_AUTHORIZATION_BASIC_0123abcdef45__ Cookie: session=__LEAK_COOKIE_SESSION_0123abcdef45__; theme=dark X-API-Key: __LEAK_X_API_KEY_0123abcdef45__ ``` For JWTs: ```text eyJ... .eyJ... .signature ``` Provider output: ```text __LEAK_JWT_0123abcdef45__ ``` For private keys: ```text -----BEGIN OPENSSH PRIVATE KEY----- ... -----END OPENSSH PRIVATE KEY----- ``` Provider output: ```text __LEAK_OPENSSH_PRIVATE_KEY_0123abcdef45__ ``` False-positive policy summary: - redact secret values only - select high-confidence built-ins before generic detectors - learn exact values from sensitive dotenv/env sources - use component parsers for URLs, query params, headers, cookies, and assignments - never redact by entropy alone - never redact names, hosts, domains, IDs, or references unless a high-confidence provider-specific pattern or custom regex matches ## UX and commands `leaks` runs in the background, so human UX must be explicit. Do not spam per secret. Notify once per provider turn with an aggregate summary when new leak values are found. Show safe metadata only. Footer/status must show enabled/off plus last provider redaction count. Commands remain operational controls and diagnostics: - `/leaks status` - `/leaks reload` - `/leaks test ` - `/leaks clear` `/leaks status` is the full report. It must never print secret values. It must show: - active state - built-in rule count - custom regex count - regex warning/error count - learned dotenv/env value count - placeholder mapping count - last provider redaction count - total provider redaction count - recent safe redaction labels - latest safe placeholder tags, not secret values Process environment key names must be collapsed to `ENV_KEY` in status. `/leaks status` must report invalid regex count. ## Validation ledger Every normative sentence in this spec belongs to one validation batch: | Batch | Spec sections | Evidence required | | ---------------------- | ------------------------------------------------ | --------------------------------------------------------------------- | | V0 scope | Authority, Mission, Validation ledger, Non-goals | Pi docs plus spec review | | V1 provider boundary | Core requirements, Pi integration strategy | Pi docs plus temp Pi extension with fake provider | | V2 placeholders | Core model | JS prototype for stability, HMAC length, tags, caps, overlap, restore | | V3 settings | Settings | JS prototype for parsing, regex safety, capture counting, warnings | | V4 built-ins | Built-in detection | Detector corpus tests with positive and negative fixtures | | V5 learned values | Dotenv and environment values | Dotenv/env parser prototype and demo corpus sampling | | V6 component parsers | Dotenv and environment values, False positives | URL/header/cookie/assignment prototypes | | V7 false positives | Dotenv and environment values, False positives | Negative fixtures from demo corpus and hand-written examples | | V8 UX | Core requirements, UX and commands | Command/status prototype or harness test | | V9 performance/failure | Core requirements, Settings | Worst-case regex/cap/deep-walk prototypes | The current `leaks` implementation is obsolete and is not validation evidence. A batch is validated only when its evidence command, fixture class, and result are recorded. Detector batches require positive and negative controls. Demo corpus evidence must report paths, key names, labels, classes, and counts only; never secret values. Evidence recorded so far: | Batch | Command | Fixture class | Result | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | V0 scope | temp Node ledger checker over `extensions/leaks/SPEC.md` | spec headings and normative sentence regex | `misses=[]`; mapped counts: V0=17, V1=34, V2=26, V3=21, V4=4, V5=46, V6=62, V7=62, V8=37, V9=46 | | V1 provider boundary | Pi docs grep for `context`, `before_provider_request`, `tool_call`, `message_end`; temp `pi -p` extension with local fake OpenAI provider | context-stage sentinel, provider-payload sentinel, provider auth header, placeholder tool arg, placeholder assistant text | provider body redacted by both stages; provider auth header present; tool arg restored; assistant message restored | | V2 placeholders | temp Node placeholder/selector prototype | stable same-value mapping, random per-store HMAC key, HMAC12 format, collision suffix, tag caps, overflow cap, restore lookup, overlap selector, existing placeholder skip | stable within store; different across stores; collision `_2`; 6 tags; 64-char tag cap; overflow non-restorable; selected password component plus whole JWT | | V3 settings | temp Node settings/regex compiler prototype | valid rule, zero/one/multi-capture rules, unsupported `flags`, missing/invalid/long labels, syntax error, unsafe regex patterns, 513-char pattern | positive controls pass; unsafe/syntax/long patterns ignored with warnings; group 1 selected with warning for multiple groups; labels fall back to `CUSTOM_REGEX` | | V4 built-ins | detector-family corpus checker over vendored `extensions/leaks/__fixtures__/demo-secrets` | 140 generated secret files; positive controls for all minimum detector families; negative controls for broad opaque keys `lineage` and `value` | all eight minimum families present; no missing families; broad keys remain negative; no unexpected negatives | | V5 learned values | dotenv/env classifier plus sampled vendored `extensions/leaks/__fixtures__/demo-secrets` files | fixed `.env` files, no recursive dotenv, quoted/comment parsing, process env `ENV_KEY`, public prefixes, weak references, credentialed URL components, demo key/class sample | fixed files only; parser strips comments/quotes; env names collapse to `ENV_KEY`; weak refs ignored; URL components learned instead of whole URL; demo key/classes reported without values | | V6 component parsers | URL/header/cookie/assignment tests plus sampled vendored `extensions/leaks/__fixtures__/demo-secrets` files | credentialed URL password/query, URL-without-creds negative, Bearer/Basic/X-API-Key/Cookie, six assignment syntaxes, embedded shell header, four weak metadata negatives | URL structure preserved; secret components redacted; safe URL/header/cookie parts preserved; embedded shell header redacted without redacting whole command; demo classes reported without values | | V7 false positives | false-positive tests plus sampled vendored `extensions/leaks/__fixtures__/demo-secrets` files | 16 hand negative controls, 4 positive controls, custom-regex override, demo metadata classes, SSH public key, TLS certificate | refs, hosts, ordinary URLs, IDs, names, UUID/hex, public prefixes, public keys, and certs stay metadata; high-confidence values still redact; custom regex can override | | V8 UX | temp Node UX/command-state prototype | provider turn summary, footer/status string, `/leaks status`, `/leaks reload`, `/leaks test`, `/leaks clear`, env key name, secret value | one aggregate notification for redacting turn; no notification for clean turn; status has required fields; diagnostics omit secret and env name; test output redacted; clear respects cancel | | V9 performance/failure | temp Node bounded-engine prototype | 40 precompiled rules, operation counter, mapping cap, cyclic object, depth-70 object, throwing detector | compile once; operations bounded by input size × rule count; map cap enforced; depth cap warning; cyclic traversal terminates; detector failure fails open and warns once | ## Non-goals - homomorphic encryption - symbolic secret transform tools - semantic editing of secret bytes by the model - model exfiltration prevention - tool sandboxing - permission enforcement - repository secret scanning - git history cleanup - arbitrary DLP/privacy redaction - image, audio, binary, or OCR redaction