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.
Every emitted placeholder must have an authenticated active-generation mapping durably appended before provider use.
A buffered new-session append is a failure: leave the original value visible, warn, and require extension reload after Pi flushes the first assistant message.
Mapping, collision, capacity, encryption, or append failure leaves the original value visible and warns.
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.
Pi persists a random generation root key and AES-256-GCM encrypted mapping records as custom session entries.
The root key and ciphertext are co-located obfuscation and context isolation, not encryption at rest.
State reconstruction uses only the active branch from getBranch().
Local restoration may happen for tool args and final assistant messages.
Unknown placeholders block every tool.
The sole maintenance exception is write or edit targeting the leaks extension itself; those calls preserve literal placeholder fixtures without hydration.
Placeholders are local capabilities.
Normal Pi workflows must keep working locally when placeholders are copied or moved exactly.
Placeholder format:
__LEAK_V1_<TAG>[_<TAG>...]_<HMAC32>__
HMAC32 is the first 16 HMAC-SHA-256 bytes encoded as 32 lowercase hexadecimal characters.
The generation root key derives separate HMAC and AES-GCM keys with HKDF.
Collisions never gain suffixes; the colliding value remains visible and warns.
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.
When multiple tags are available for the same secret span on first mapping, order them by semantic priority:
- dotenv key name or
ENV_KEY
- structure component
- custom regex label
- built-in type
- 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:
__LEAK_V1_STRIPE_LIVE_SECRET_KEY_STRIPE_TOKEN_8f31aa77c90129a76d253a748660f5b7__
__LEAK_V1_OPENROUTER_API_KEY_OPENROUTER_TOKEN_41c0e9aa1204a7342836516dc01b9490__
__LEAK_V1_DATABASE_URL_DB_PASSWORD_POSTGRES_URL_ba29d4ff8810c412e1341ef2839572aa__
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: rebuild the active generation, initialize settings and learning, update status
session_tree: rebuild from the newly active branch
context: redact message copies opportunistically
before_provider_request: persist mappings, then redact final provider payload authoritatively
tool_call: hydrate known placeholders and block unknown or incompletely inspected input
message_end: restore placeholders in finalized local assistant messages
Persist generations and encrypted mappings with appendEntry.
Do not register tools.
Use one slash command: /leaks.
Settings
Planned settings surface:
{
"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
- provider-shaped values in conservative sensitive-key assignments; ambiguous opaque assignments remain visible unless learned exactly from dotenv or environment input
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:
PASSWORD=horse-battery-correct
Later 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 names use separator-aware complete tokens, never substring containment.
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 names use separator-aware complete tokens, never substring containment.
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 only when they have exactly three strict Base64URL segments, header and payload decode as non-array JSON objects, header alg is a nonempty string, and signature is nonempty strict Base64URL.
JWT signature verification 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.
PuTTY private sections consume exactly the declared Private-Lines payload and never unrelated trailing text.
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 uses complete normalized tokens rather than arbitrary substrings.
High-precision names such as API_KEY, ACCESS_TOKEN, CLIENT_SECRET, PASSWORD, PASSPHRASE, and PRIVATE_KEY authorize non-weak exact learning.
Ambiguous names such as KEY, AUTH, SESSION, COOKIE, JWT, SEED, and database URL names require a parsed secret component or provider-specific value shape.
Metadata suffixes such as _ID, _NAME, _PATH, _FILE, _TYPE, _HOST, _PORT, _MANAGER, _SOCKET, and _ENDPOINT do not authorize learning.
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:
DATABASE_URL=postgres://alice:pw@db/app
Provider output:
DATABASE_URL=postgres://alice:__LEAK_DATABASE_URL_DB_PASSWORD_0123abcdef45__@db/app
Not:
DATABASE_URL=__LEAK_DATABASE_URL_0123abcdef45__
For URL query params:
https://api.example.com/callback?token=abc123&user=me
Provider output:
https://api.example.com/callback?token=__LEAK_QUERY_TOKEN_0123abcdef45__&user=me
For HTTP headers:
Authorization: Bearer abc123
Authorization: Basic dXNlcjpwYXNz
Cookie: session=xyz; theme=dark
X-API-Key: key123
Provider output:
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:
eyJ... .eyJ... .signature
Provider output:
__LEAK_JWT_0123abcdef45__
For private keys:
-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----
Provider output:
__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/degraded plus cumulative provider-bound protected-value count.
Commands remain operational controls and diagnostics:
/leaks status
/leaks reload
/leaks test <text>
/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
- total provider-bound protected-value 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 |
Durable lifecycle tests for HMAC32, AES-GCM, branch state, caps, collisions, and 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 |
Current evidence lives in deterministic tests, dedicated fuzz properties, real agent-loop harness tests, tracked-source corpus checks, and mise run ci.
Detector batches require positive and negative controls.
Diagnostics and corpus failures must never print classified values.
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
Markdown source
File outline
# 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.
Every emitted placeholder must have an authenticated active-generation mapping durably appended before provider use.
A buffered new-session append is a failure: leave the original value visible, warn, and require extension reload after Pi flushes the first assistant message.
Mapping, collision, capacity, encryption, or append failure leaves the original value visible and warns.
`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.
Pi persists a random generation root key and AES-256-GCM encrypted mapping records as custom session entries.
The root key and ciphertext are co-located obfuscation and context isolation, not encryption at rest.
State reconstruction uses only the active branch from `getBranch()`.
Local restoration may happen for tool args and final assistant messages.
Unknown placeholders block every tool.
The sole maintenance exception is `write` or `edit` targeting the `leaks` extension itself; those calls preserve literal placeholder fixtures without hydration.
Placeholders are local capabilities.
Normal Pi workflows must keep working locally when placeholders are copied or moved exactly.
Placeholder format:
```text
__LEAK_V1_<TAG>[_<TAG>...]_<HMAC32>__
```
`HMAC32` is the first 16 HMAC-SHA-256 bytes encoded as 32 lowercase hexadecimal characters.
The generation root key derives separate HMAC and AES-GCM keys with HKDF.
Collisions never gain suffixes; the colliding value remains visible and warns.
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.
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_V1_STRIPE_LIVE_SECRET_KEY_STRIPE_TOKEN_8f31aa77c90129a76d253a748660f5b7__
__LEAK_V1_OPENROUTER_API_KEY_OPENROUTER_TOKEN_41c0e9aa1204a7342836516dc01b9490__
__LEAK_V1_DATABASE_URL_DB_PASSWORD_POSTGRES_URL_ba29d4ff8810c412e1341ef2839572aa__
```
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`: rebuild the active generation, initialize settings and learning, update status
- `session_tree`: rebuild from the newly active branch
- `context`: redact message copies opportunistically
- `before_provider_request`: persist mappings, then redact final provider payload authoritatively
- `tool_call`: hydrate known placeholders and block unknown or incompletely inspected input
- `message_end`: restore placeholders in finalized local assistant messages
Persist generations and encrypted 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
- provider-shaped values in conservative sensitive-key assignments; ambiguous opaque assignments remain visible unless learned exactly from dotenv or environment input
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 names use separator-aware complete tokens, never substring containment.
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 names use separator-aware complete tokens, never substring containment.
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 only when they have exactly three strict Base64URL segments, header and payload decode as non-array JSON objects, header `alg` is a nonempty string, and signature is nonempty strict Base64URL.
JWT signature verification 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.
PuTTY private sections consume exactly the declared `Private-Lines` payload and never unrelated trailing text.
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 uses complete normalized tokens rather than arbitrary substrings.
High-precision names such as `API_KEY`, `ACCESS_TOKEN`, `CLIENT_SECRET`, `PASSWORD`, `PASSPHRASE`, and `PRIVATE_KEY` authorize non-weak exact learning.
Ambiguous names such as `KEY`, `AUTH`, `SESSION`, `COOKIE`, `JWT`, `SEED`, and database URL names require a parsed secret component or provider-specific value shape.
Metadata suffixes such as `_ID`, `_NAME`, `_PATH`, `_FILE`, `_TYPE`, `_HOST`, `_PORT`, `_MANAGER`, `_SOCKET`, and `_ENDPOINT` do not authorize learning.
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/degraded plus cumulative provider-bound protected-value count.
Commands remain operational controls and diagnostics:
- `/leaks status`
- `/leaks reload`
- `/leaks test <text>`
- `/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
- total provider-bound protected-value 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 | Durable lifecycle tests for HMAC32, AES-GCM, branch state, caps, collisions, and 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 |
Current evidence lives in deterministic tests, dedicated fuzz properties, real agent-loop harness tests, tracked-source corpus checks, and `mise run ci`.
Detector batches require positive and negative controls.
Diagnostics and corpus failures must never print classified values.
## 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