keyspill 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +240 -2
- package/bin/keyspill.js +98 -0
- package/package.json +43 -4
- package/src/html.js +134 -0
- package/src/protect.js +65 -0
- package/src/report.js +117 -0
- package/src/rules.js +192 -0
- package/src/scan.js +237 -0
- package/src/sources.js +101 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kazbek Askarov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,241 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# keyspill
|
|
4
|
+
|
|
5
|
+
**Find the secrets your AI coding agents have already seen.**
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/keyspill)
|
|
8
|
+
[](https://github.com/kazbekaskarov/keyspill/actions/workflows/test.yml)
|
|
9
|
+
[](package.json)
|
|
10
|
+
[](LICENSE)
|
|
11
|
+
|
|
12
|
+
[Website](https://kazbekaskarov.github.io/keyspill/) · [npm](https://www.npmjs.com/package/keyspill) · [Changelog](CHANGELOG.md) · [Report a false positive](https://github.com/kazbekaskarov/keyspill/issues/new?template=false-positive.yml)
|
|
13
|
+
|
|
14
|
+
<img src="docs/terminal.png" alt="keyspill output in a terminal" width="760">
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
Coding agents read files to do their job, and your `.env` is a file. Every time Claude Code reads it, Codex runs `cat ~/.aws/credentials`, or you paste a key into Cursor to "just debug this one thing", that secret is sent to a model provider and stays in plain text in a session log on your disk.
|
|
19
|
+
|
|
20
|
+
keyspill reads those logs locally and tells you which keys to rotate, where they came from, and how they got there.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npx keyspill
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
No install, no config, no account. Requires Node.js 18 or later.
|
|
27
|
+
|
|
28
|
+
## Contents
|
|
29
|
+
|
|
30
|
+
- [Features](#features)
|
|
31
|
+
- [Usage](#usage)
|
|
32
|
+
- [Supported agents](#supported-agents)
|
|
33
|
+
- [What it detects](#what-it-detects)
|
|
34
|
+
- [Prevent future leaks](#prevent-future-leaks)
|
|
35
|
+
- [Privacy and security](#privacy-and-security)
|
|
36
|
+
- [Scripting and CI](#scripting-and-ci)
|
|
37
|
+
- [FAQ](#faq)
|
|
38
|
+
- [Contributing](#contributing)
|
|
39
|
+
- [License](#license)
|
|
40
|
+
|
|
41
|
+
## Features
|
|
42
|
+
|
|
43
|
+
- **Seven agents in one command.** Claude Code, Codex, Cursor, GitHub Copilot CLI, Gemini CLI, opencode, and Cline / Roo Code / Kilo Code, on macOS, Linux and Windows.
|
|
44
|
+
- **Tells you how each secret leaked.** The agent read it from a file, you pasted it into chat, or the agent wrote it into a command.
|
|
45
|
+
- **Actionable output.** Severity, agent, project, last-seen date, and a direct link to rotate each key.
|
|
46
|
+
- **Low noise by design.** Documentation example keys, placeholders, public keys and code references are filtered out.
|
|
47
|
+
- **Private.** Runs entirely offline, never shows a full secret, never modifies your files.
|
|
48
|
+
- **Small and auditable.** Zero dependencies and about 850 lines of plain JavaScript.
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
npx keyspill # scan and print a report
|
|
54
|
+
npx keyspill --card # also write an HTML report with a shareable card, and open it
|
|
55
|
+
npx keyspill protect # preview rules that stop agents reading secrets
|
|
56
|
+
npx keyspill protect --apply # write those rules
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Example output
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
keyspill · what your AI agents have already seen
|
|
63
|
+
Scanned 1,284 session files (412 MB) from Claude Code, Codex, Cursor in 3.1s · 100% local, nothing uploaded
|
|
64
|
+
|
|
65
|
+
9 secrets seen by your agents 3 critical · 5 high · 1 medium
|
|
66
|
+
|
|
67
|
+
CRITICAL
|
|
68
|
+
● Stripe live secret key sk_live_••••••••fnwh
|
|
69
|
+
1× · Claude Code · ~/work/shop · last 2026-11-02
|
|
70
|
+
agent read it 1×
|
|
71
|
+
→ rotate: https://dashboard.stripe.com/apikeys
|
|
72
|
+
● Database URL with password postgres://•••:••••••@••••.acme-internal.net
|
|
73
|
+
1× · Claude Code · ~/work/shop · last 2026-11-02
|
|
74
|
+
agent read it 1×
|
|
75
|
+
|
|
76
|
+
HIGH
|
|
77
|
+
● GitHub token ghp_••••••••VKby
|
|
78
|
+
1× · Codex · ~/oss/nanotab · last 2026-11-05
|
|
79
|
+
agent read it 1×
|
|
80
|
+
→ rotate: https://github.com/settings/tokens
|
|
81
|
+
● OpenAI API key sk-proj-••••••••u9Bn
|
|
82
|
+
1× · Claude Code · ~/work/shop · last 2026-11-02
|
|
83
|
+
you pasted it 1×
|
|
84
|
+
→ rotate: https://platform.openai.com/api-keys
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Options
|
|
88
|
+
|
|
89
|
+
| Option | Description |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `--card` | Write `keyspill-report.html` with the full masked report and a share card, then open it |
|
|
92
|
+
| `--html <file>` | Write the HTML report to a specific path |
|
|
93
|
+
| `--json` | Print machine-readable JSON (masked values only) |
|
|
94
|
+
| `--path <dir>` | Also scan another file or folder. Repeatable |
|
|
95
|
+
| `--all` | List every finding instead of the top ones per severity |
|
|
96
|
+
| `--no-open` | Don't open the HTML report automatically |
|
|
97
|
+
| `--no-color` | Plain output. `NO_COLOR` is also respected |
|
|
98
|
+
| `-v`, `--version` | Print the version |
|
|
99
|
+
| `-h`, `--help` | Print help |
|
|
100
|
+
|
|
101
|
+
### Share card
|
|
102
|
+
|
|
103
|
+
`npx keyspill --card` produces a local HTML report. Click **Download share card** to get a PNG that shows the number of findings and key types only, never values.
|
|
104
|
+
|
|
105
|
+
<img src="docs/card.png" alt="keyspill share card: 11 secrets my AI agents have already seen" width="560">
|
|
106
|
+
|
|
107
|
+
## Supported agents
|
|
108
|
+
|
|
109
|
+
| Agent | Where keyspill looks |
|
|
110
|
+
|---|---|
|
|
111
|
+
| Claude Code | `~/.claude/projects/**/*.jsonl` (respects `CLAUDE_CONFIG_DIR`) |
|
|
112
|
+
| Codex | `~/.codex/sessions/**`, `~/.codex/history.jsonl` (respects `CODEX_HOME`) |
|
|
113
|
+
| Cursor | `state.vscdb` in Cursor's global and workspace storage, `~/.cursor/chats` |
|
|
114
|
+
| GitHub Copilot CLI | `~/.copilot/session-state`, `~/.copilot/history-session-state` |
|
|
115
|
+
| Gemini CLI | `~/.gemini/tmp/**` |
|
|
116
|
+
| opencode | `~/.local/share/opencode/storage` (respects `XDG_DATA_HOME`) |
|
|
117
|
+
| Cline / Roo Code / Kilo Code | `globalStorage/<extension>/tasks/*` in VS Code, VS Code Insiders, Cursor, Windsurf and VSCodium |
|
|
118
|
+
|
|
119
|
+
Editor storage resolves to `~/Library/Application Support` on macOS, `%APPDATA%` on Windows and `~/.config` on Linux.
|
|
120
|
+
|
|
121
|
+
Missing your agent? [Open an issue](https://github.com/kazbekaskarov/keyspill/issues/new?template=new-agent.yml) with where it keeps its history.
|
|
122
|
+
|
|
123
|
+
## What it detects
|
|
124
|
+
|
|
125
|
+
30 rules, grouped by severity.
|
|
126
|
+
|
|
127
|
+
| Severity | Secrets |
|
|
128
|
+
|---|---|
|
|
129
|
+
| **Critical** | AWS access keys, AWS secret keys, private keys (PEM), Stripe live keys, database URLs with passwords (Postgres, MySQL, MongoDB, Redis, AMQP, MSSQL), Supabase `service_role` keys |
|
|
130
|
+
| **High** | OpenAI, Anthropic, GitHub, GitLab, Google API, Slack tokens and webhooks, Telegram, Discord, SendGrid, Twilio, npm, PyPI, Hugging Face, Shopify, DigitalOcean, Stripe webhook secrets, Groq, Replicate, Supabase access tokens, Mailgun, AWS temporary keys |
|
|
131
|
+
| **Medium** | Unexpired JWTs, Stripe test keys, local database passwords, `*_SECRET` / `*_PASSWORD` / `*_TOKEN` / `*_API_KEY` values in env and config files |
|
|
132
|
+
|
|
133
|
+
### What it ignores on purpose
|
|
134
|
+
|
|
135
|
+
A false alarm in a security tool costs more trust than a miss, so keyspill skips:
|
|
136
|
+
|
|
137
|
+
- documentation example keys such as `AKIAIOSFODNN7EXAMPLE`
|
|
138
|
+
- placeholders: `your_api_key`, `xxxx`, `<token>`, `${SECRET}`, `USER:PASSWORD@HOST`
|
|
139
|
+
- Supabase `anon` keys, which are public by design
|
|
140
|
+
- expired JWTs
|
|
141
|
+
- default local credentials such as `postgres:postgres@localhost`
|
|
142
|
+
- code references such as `API_KEY = process.env.API_KEY`
|
|
143
|
+
- `NEXT_PUBLIC_*`, `VITE_*` and other public-by-convention variables
|
|
144
|
+
|
|
145
|
+
The same credential seen many times is reported once, with a count.
|
|
146
|
+
|
|
147
|
+
## Prevent future leaks
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
npx keyspill protect # show what would change
|
|
151
|
+
npx keyspill protect --apply # write it
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
This adds `permissions.deny` rules to `~/.claude/settings.json` so Claude Code can't read `.env*`, `*.pem`, `*.key`, `secrets/`, `~/.aws`, `~/.ssh` or `~/.config/gcloud`, and adds a `.cursorignore` to the current project. Your existing settings are merged, not replaced, and backed up first. Running it twice changes nothing.
|
|
155
|
+
|
|
156
|
+
> [!NOTE]
|
|
157
|
+
> Deny rules cover file reads, not shell commands like `cat .env`. Keep reading the commands you approve.
|
|
158
|
+
|
|
159
|
+
## Privacy and security
|
|
160
|
+
|
|
161
|
+
- **Offline.** keyspill makes no network requests. The HTML report loads no fonts, scripts or analytics.
|
|
162
|
+
- **Never shows a full secret.** Terminal, JSON and HTML output show a masked value (`sk_live_••••••••fnwh`) and a short SHA-256 fingerprint. The test suite checks that no 10-character fragment of a secret reaches any output.
|
|
163
|
+
- **Read-only.** Session files are never modified, copied or uploaded. keyspill writes only what you ask for: the HTML report with `--card` / `--html`, and the two files listed above with `protect --apply`.
|
|
164
|
+
- **Auditable.** Zero runtime dependencies. Read [`src/`](src) in about fifteen minutes.
|
|
165
|
+
|
|
166
|
+
Found a security issue? Please report it privately, see [SECURITY.md](SECURITY.md).
|
|
167
|
+
|
|
168
|
+
## Scripting and CI
|
|
169
|
+
|
|
170
|
+
keyspill exits with code `1` when it finds a critical or high secret, `0` otherwise, and `2` on usage errors.
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
npx keyspill --json > keyspill.json
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
```json
|
|
177
|
+
{
|
|
178
|
+
"version": 1,
|
|
179
|
+
"summary": { "total": 9, "critical": 3, "high": 5, "medium": 1 },
|
|
180
|
+
"findings": [
|
|
181
|
+
{
|
|
182
|
+
"rule": "stripe-live",
|
|
183
|
+
"label": "Stripe live secret key",
|
|
184
|
+
"severity": "critical",
|
|
185
|
+
"masked": "sk_live_••••••••fnwh",
|
|
186
|
+
"fingerprint": "3f9a1c0b7e21",
|
|
187
|
+
"count": 1,
|
|
188
|
+
"tools": ["Claude Code"],
|
|
189
|
+
"origins": { "tool": 1, "user": 0, "assistant": 0, "unknown": 0 },
|
|
190
|
+
"lastSeen": "2026-11-02",
|
|
191
|
+
"rotate": "https://dashboard.stripe.com/apikeys"
|
|
192
|
+
}
|
|
193
|
+
]
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Use `--path` to scan exported transcripts or logs anywhere on disk:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
npx keyspill --path ./exported-sessions --json
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## FAQ
|
|
204
|
+
|
|
205
|
+
<details>
|
|
206
|
+
<summary><b>It found a key. What should I do?</b></summary>
|
|
207
|
+
|
|
208
|
+
Rotate it with the provider. Deleting the session log does not undo what the provider already received. Each critical and high finding includes a link to the right settings page.
|
|
209
|
+
</details>
|
|
210
|
+
|
|
211
|
+
<details>
|
|
212
|
+
<summary><b>Does keyspill send my data anywhere?</b></summary>
|
|
213
|
+
|
|
214
|
+
No. It reads local files and prints to your terminal. There is no telemetry and no network code.
|
|
215
|
+
</details>
|
|
216
|
+
|
|
217
|
+
<details>
|
|
218
|
+
<summary><b>Why wasn't my secret detected?</b></summary>
|
|
219
|
+
|
|
220
|
+
keyspill only reports formats it can identify with high confidence. If a real secret was missed, [open an issue](https://github.com/kazbekaskarov/keyspill/issues/new?template=false-positive.yml) describing its format. Never paste the secret itself.
|
|
221
|
+
</details>
|
|
222
|
+
|
|
223
|
+
<details>
|
|
224
|
+
<summary><b>How long does a scan take?</b></summary>
|
|
225
|
+
|
|
226
|
+
Usually seconds. Large histories (around 800 MB) take 20–30 seconds. Progress is shown while it runs.
|
|
227
|
+
</details>
|
|
228
|
+
|
|
229
|
+
## Contributing
|
|
230
|
+
|
|
231
|
+
Contributions are welcome, especially new agents, new rules and false-positive fixes. See [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup and guidelines.
|
|
232
|
+
|
|
233
|
+
```bash
|
|
234
|
+
git clone https://github.com/kazbekaskarov/keyspill.git
|
|
235
|
+
cd keyspill
|
|
236
|
+
npm test
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## License
|
|
240
|
+
|
|
241
|
+
[MIT](LICENSE) © Kazbek Askarov
|
package/bin/keyspill.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { scan, summarize } from '../src/scan.js';
|
|
7
|
+
import { printReport, toJson, c, fmtBytes } from '../src/report.js';
|
|
8
|
+
import { renderHtml } from '../src/html.js';
|
|
9
|
+
import { protect } from '../src/protect.js';
|
|
10
|
+
|
|
11
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
12
|
+
|
|
13
|
+
const HELP = `
|
|
14
|
+
${c.bold('keyspill')} — find the secrets your AI coding agents have already seen
|
|
15
|
+
|
|
16
|
+
${c.bold('Usage')}
|
|
17
|
+
npx keyspill scan local agent history, print a report
|
|
18
|
+
npx keyspill --card also write an HTML report with a share card and open it
|
|
19
|
+
npx keyspill protect show rules that stop agents reading .env/keys
|
|
20
|
+
npx keyspill protect --apply write those rules (backs up your settings first)
|
|
21
|
+
|
|
22
|
+
${c.bold('Options')}
|
|
23
|
+
--json machine-readable output (masked values only)
|
|
24
|
+
--html <file> write the HTML report to <file> (default ./keyspill-report.html)
|
|
25
|
+
--path <dir> also scan this file or folder (repeatable)
|
|
26
|
+
--all list every finding, not just the top ones
|
|
27
|
+
--no-open don't open the HTML report automatically
|
|
28
|
+
--no-color plain output
|
|
29
|
+
-v, --version print version
|
|
30
|
+
|
|
31
|
+
Scans: Claude Code, Codex, Cursor, Gemini CLI, opencode, Copilot CLI, Cline / Roo / Kilo.
|
|
32
|
+
Runs 100% locally. Never uploads, never stores or prints a full secret.
|
|
33
|
+
Exit code: 1 if a critical or high secret is found (handy in scripts), 0 otherwise.
|
|
34
|
+
`;
|
|
35
|
+
|
|
36
|
+
function parseArgs(argv) {
|
|
37
|
+
const a = { paths: [], cmd: 'scan' };
|
|
38
|
+
const value = (i, flag) => {
|
|
39
|
+
const v = argv[i + 1];
|
|
40
|
+
if (!v || v.startsWith('-')) { console.error(`Option ${flag} needs a value.\n${HELP}`); process.exit(2); }
|
|
41
|
+
return v;
|
|
42
|
+
};
|
|
43
|
+
for (let i = 0; i < argv.length; i++) {
|
|
44
|
+
const k = argv[i];
|
|
45
|
+
if (k === 'protect') a.cmd = 'protect';
|
|
46
|
+
else if (k === '--apply') a.apply = true;
|
|
47
|
+
else if (k === '--json') a.json = true;
|
|
48
|
+
else if (k === '--card') a.html = a.html || 'keyspill-report.html';
|
|
49
|
+
else if (k === '--html') a.html = argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : 'keyspill-report.html';
|
|
50
|
+
else if (k === '--path') a.paths.push(path.resolve(value(i++, k)));
|
|
51
|
+
else if (k === '--home') a.home = path.resolve(value(i++, k)); // for testing
|
|
52
|
+
else if (k === '--all') a.all = true;
|
|
53
|
+
else if (k === '--no-open') a.noOpen = true;
|
|
54
|
+
else if (k === '--no-color') { /* read in report.js */ }
|
|
55
|
+
else if (k === '-h' || k === '--help') a.help = true;
|
|
56
|
+
else if (k === '-v' || k === '--version') a.version = true;
|
|
57
|
+
else { console.error(`Unknown option: ${k}\n${HELP}`); process.exit(2); }
|
|
58
|
+
}
|
|
59
|
+
return a;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function openFile(file) {
|
|
63
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
64
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', file] : [file];
|
|
65
|
+
try { spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref(); } catch { /* headless */ }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function main() {
|
|
69
|
+
const args = parseArgs(process.argv.slice(2));
|
|
70
|
+
if (args.help) return console.log(HELP);
|
|
71
|
+
if (args.version) return console.log(VERSION);
|
|
72
|
+
if (args.cmd === 'protect') process.exit(protect({ apply: args.apply, home: args.home }));
|
|
73
|
+
|
|
74
|
+
const live = process.stderr.isTTY && !args.json;
|
|
75
|
+
const result = await scan({
|
|
76
|
+
home: args.home || os.homedir(),
|
|
77
|
+
extraPaths: args.paths,
|
|
78
|
+
onProgress: live ? ({ files, totalFiles, bytes }) => {
|
|
79
|
+
process.stderr.write(`\r ${c.gray(`scanning ${files}/${totalFiles} files · ${fmtBytes(bytes)}`)} `);
|
|
80
|
+
} : undefined,
|
|
81
|
+
});
|
|
82
|
+
if (live) process.stderr.write('\r\x1b[K');
|
|
83
|
+
|
|
84
|
+
if (args.json) console.log(toJson(result));
|
|
85
|
+
else printReport(result, { all: args.all });
|
|
86
|
+
|
|
87
|
+
if (args.html) {
|
|
88
|
+
const out = path.resolve(args.html);
|
|
89
|
+
fs.writeFileSync(out, renderHtml(result));
|
|
90
|
+
if (!args.json) console.log(` ${c.bold('Report:')} ${out}\n`);
|
|
91
|
+
if (!args.noOpen) openFile(out);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const s = summarize(result.findings);
|
|
95
|
+
process.exitCode = s.critical + s.high > 0 ? 1 : 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
main().catch((e) => { console.error(c.red('keyspill failed: ') + (e?.stack || e)); process.exit(2); });
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keyspill",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Find the secrets your AI coding agents have already seen. Scans Claude Code, Codex, Cursor, Gemini CLI, opencode and more. 100% local, zero dependencies.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"keyspill": "bin/keyspill.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test",
|
|
17
|
+
"prepublishOnly": "node --test"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=18"
|
|
21
|
+
},
|
|
22
|
+
"author": "Kazbek Askarov",
|
|
23
|
+
"homepage": "https://kazbekaskarov.github.io/keyspill/",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/kazbekaskarov/keyspill.git"
|
|
27
|
+
},
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/kazbekaskarov/keyspill/issues"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"security",
|
|
33
|
+
"secrets",
|
|
34
|
+
"claude-code",
|
|
35
|
+
"codex",
|
|
36
|
+
"cursor",
|
|
37
|
+
"copilot",
|
|
38
|
+
"ai-agents",
|
|
39
|
+
"api-keys",
|
|
40
|
+
"secret-scanning",
|
|
41
|
+
"llm",
|
|
42
|
+
"cli"
|
|
43
|
+
],
|
|
44
|
+
"license": "MIT"
|
|
45
|
+
}
|
package/src/html.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Self-contained HTML report. No external requests (no fonts, no CDN, no analytics):
|
|
2
|
+
// a security report must not phone home. Secrets only ever appear masked.
|
|
3
|
+
import { summarize } from './scan.js';
|
|
4
|
+
import { fmtDate, fmtBytes, shortPath } from './report.js';
|
|
5
|
+
|
|
6
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]));
|
|
7
|
+
|
|
8
|
+
const COLORS = { paper: '#E4E7EB', ink: '#121417', tag: '#FFCF33', red: '#C8102E', amber: '#B86E00', slate: '#6B7280' };
|
|
9
|
+
|
|
10
|
+
function cardSvg(s, findings, stats) {
|
|
11
|
+
const top = findings.filter((f) => f.severity !== 'medium').slice(0, 4);
|
|
12
|
+
const tools = Object.keys(stats.byTool).join(' + ') || 'my agents';
|
|
13
|
+
const rows = top.map((f, i) => {
|
|
14
|
+
const y = 352 + i * 50;
|
|
15
|
+
const w = 150 + ((f.hash.charCodeAt(0) * 7 + i * 31) % 160);
|
|
16
|
+
const col = f.severity === 'critical' ? COLORS.red : COLORS.amber;
|
|
17
|
+
return `<rect x="96" y="${y - 22}" width="10" height="30" fill="${col}"/>
|
|
18
|
+
<text x="124" y="${y}" font-size="26" font-weight="600" fill="${COLORS.ink}">${esc(f.label)}</text>
|
|
19
|
+
<rect x="${560}" y="${y - 22}" width="${w}" height="30" fill="${COLORS.ink}"/>`;
|
|
20
|
+
}).join('');
|
|
21
|
+
const big = s.total;
|
|
22
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630" width="1200" height="630" font-family="Helvetica Neue, Arial, sans-serif" role="img" aria-label="${big} secrets seen by my AI agents">
|
|
23
|
+
<rect width="1200" height="630" fill="${COLORS.paper}"/>
|
|
24
|
+
<g transform="rotate(-2 600 315)">
|
|
25
|
+
<rect x="60" y="52" width="1080" height="530" rx="18" fill="${COLORS.tag}"/>
|
|
26
|
+
<circle cx="1080" cy="112" r="22" fill="${COLORS.paper}"/>
|
|
27
|
+
<circle cx="1080" cy="112" r="22" fill="none" stroke="${COLORS.ink}" stroke-width="3"/>
|
|
28
|
+
<text x="96" y="122" font-size="28" font-weight="700" fill="${COLORS.ink}" letter-spacing="1">EVIDENCE</text>
|
|
29
|
+
<text x="96" y="152" font-size="22" fill="${COLORS.ink}" opacity=".7">${esc(tools)} · ${fmtDate(Date.now())}</text>
|
|
30
|
+
<text x="90" y="300" font-size="168" font-weight="800" fill="${COLORS.ink}" letter-spacing="-6">${big}</text>
|
|
31
|
+
<text x="${120 + String(big).length * 92}" y="232" font-size="40" font-weight="700" fill="${COLORS.ink}">secret${big === 1 ? '' : 's'} my AI</text>
|
|
32
|
+
<text x="${120 + String(big).length * 92}" y="282" font-size="40" font-weight="700" fill="${COLORS.ink}">agents have already seen</text>
|
|
33
|
+
${rows}
|
|
34
|
+
<text x="96" y="572" font-size="24" fill="${COLORS.ink}"><tspan font-weight="700" fill="${COLORS.red}">${s.critical} critical</tspan> · ${s.high} high · ${s.medium} medium</text>
|
|
35
|
+
<text x="1104" y="572" font-size="24" font-weight="700" text-anchor="end" fill="${COLORS.ink}">npx keyspill</text>
|
|
36
|
+
</g>
|
|
37
|
+
</svg>`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function renderHtml({ findings, stats }) {
|
|
41
|
+
const s = summarize(findings);
|
|
42
|
+
const svg = cardSvg(s, findings, stats);
|
|
43
|
+
const rows = findings.map((f) => `
|
|
44
|
+
<li class="row sev-${f.severity}">
|
|
45
|
+
<span class="sev">${f.severity}</span>
|
|
46
|
+
<div class="what">
|
|
47
|
+
<strong>${esc(f.label)}${f.varName ? ` <em>${esc(f.varName)}</em>` : ''}</strong>
|
|
48
|
+
<code>${esc(f.display)}</code>
|
|
49
|
+
</div>
|
|
50
|
+
<div class="where">
|
|
51
|
+
<span>${f.count}× in ${esc(f.tools.join(', '))}</span>
|
|
52
|
+
${f.projects.length ? `<span>${esc(shortPath(f.projects[0]))}${f.projects.length > 1 ? ` and ${f.projects.length - 1} more` : ''}</span>` : ''}
|
|
53
|
+
<span>Last seen ${fmtDate(f.lastSeen)}</span>
|
|
54
|
+
${originLine(f.origins)}
|
|
55
|
+
</div>
|
|
56
|
+
${f.rotate ? `<a class="rotate" href="${esc(f.rotate)}" target="_blank" rel="noreferrer">Rotate key</a>` : '<span></span>'}
|
|
57
|
+
</li>`).join('');
|
|
58
|
+
|
|
59
|
+
return `<!doctype html>
|
|
60
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
61
|
+
<title>keyspill report: ${s.total} secrets</title>
|
|
62
|
+
<style>
|
|
63
|
+
:root{--paper:${COLORS.paper};--ink:${COLORS.ink};--tag:${COLORS.tag};--red:${COLORS.red};--amber:${COLORS.amber};--slate:${COLORS.slate}}
|
|
64
|
+
*{box-sizing:border-box}
|
|
65
|
+
body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.5 "Helvetica Neue",Arial,system-ui,sans-serif}
|
|
66
|
+
main{max-width:1040px;margin:0 auto;padding:48px 24px 96px}
|
|
67
|
+
h1{font-size:clamp(32px,5vw,52px);line-height:1.05;letter-spacing:-.02em;margin:0 0 8px;font-weight:800;max-width:18ch}
|
|
68
|
+
.lede{color:var(--slate);margin:0 0 32px;max-width:62ch}
|
|
69
|
+
.card{background:#fff;border:2px solid var(--ink);padding:12px;margin:0 0 12px}
|
|
70
|
+
.card svg{display:block;width:100%;height:auto}
|
|
71
|
+
.actions{display:flex;gap:12px;flex-wrap:wrap;margin:0 0 56px;align-items:center}
|
|
72
|
+
button,.rotate{font:inherit;font-weight:700;border:2px solid var(--ink);background:var(--tag);color:var(--ink);padding:10px 16px;cursor:pointer;text-decoration:none}
|
|
73
|
+
button:focus-visible,.rotate:focus-visible{outline:3px solid var(--red);outline-offset:2px}
|
|
74
|
+
.actions small{color:var(--slate)}
|
|
75
|
+
h2{font-size:24px;margin:0 0 4px}
|
|
76
|
+
.sub{color:var(--slate);margin:0 0 20px}
|
|
77
|
+
ol{list-style:none;margin:0;padding:0;border-top:2px solid var(--ink)}
|
|
78
|
+
.row{display:grid;grid-template-columns:96px minmax(0,1.2fr) minmax(0,1.4fr) auto;gap:16px;align-items:start;padding:16px 0;border-bottom:1px solid #c5cad1}
|
|
79
|
+
.sev{font-weight:700;padding-left:10px;border-left:6px solid var(--slate)}
|
|
80
|
+
.sev-critical .sev{border-color:var(--red);color:var(--red)}
|
|
81
|
+
.sev-high .sev{border-color:var(--amber);color:var(--amber)}
|
|
82
|
+
.what strong{display:block}.what em{font-style:normal;color:var(--slate);font-weight:400}
|
|
83
|
+
code{font:14px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--ink);color:var(--paper);padding:2px 6px;display:inline-block;margin-top:4px;word-break:break-all}
|
|
84
|
+
.where{color:var(--slate);font-size:14px;display:flex;flex-direction:column}
|
|
85
|
+
.rotate{background:#fff;font-size:14px;padding:6px 12px}
|
|
86
|
+
.fix{margin-top:56px;border:2px solid var(--ink);background:#fff;padding:24px}
|
|
87
|
+
.fix pre{background:var(--ink);color:var(--paper);padding:12px 16px;overflow:auto}
|
|
88
|
+
footer{margin-top:40px;color:var(--slate);font-size:14px}
|
|
89
|
+
@media (max-width:720px){.row{grid-template-columns:1fr}.rotate{justify-self:start}}
|
|
90
|
+
</style></head>
|
|
91
|
+
<body><main>
|
|
92
|
+
<h1>Your AI agents have seen ${s.total} secret${s.total === 1 ? '' : 's'}.</h1>
|
|
93
|
+
<p class="lede">Found in ${stats.files.toLocaleString()} local session files (${fmtBytes(stats.bytes)}) from ${esc(Object.keys(stats.byTool).join(', ') || 'no agents')}. Everything in a session was sent to a model provider, so treat these keys as exposed. This report never left your machine, and every value below is masked.</p>
|
|
94
|
+
|
|
95
|
+
<div class="card" id="card">${svg}</div>
|
|
96
|
+
<div class="actions">
|
|
97
|
+
<button type="button" id="dl">Download share card</button>
|
|
98
|
+
<small>The card has counts and key types only, never values.</small>
|
|
99
|
+
</div>
|
|
100
|
+
|
|
101
|
+
<h2>Evidence</h2>
|
|
102
|
+
<p class="sub">${s.critical} critical, ${s.high} high, ${s.medium} medium. Rotate critical and high first.</p>
|
|
103
|
+
<ol>${rows || '<li class="row"><span></span><div>Nothing found. Your agents have clean hands.</div></li>'}</ol>
|
|
104
|
+
|
|
105
|
+
<section class="fix">
|
|
106
|
+
<h2>Stop it happening again</h2>
|
|
107
|
+
<p>Block agents from reading env files and keys. This adds deny rules to Claude Code and a <code>.cursorignore</code> to the current project:</p>
|
|
108
|
+
<pre>npx keyspill protect --apply</pre>
|
|
109
|
+
</section>
|
|
110
|
+
<footer>Generated by keyspill on ${new Date().toISOString().slice(0, 16).replace('T', ' ')}. Open source, 100% local.</footer>
|
|
111
|
+
</main>
|
|
112
|
+
<script>
|
|
113
|
+
document.getElementById('dl').addEventListener('click', function () {
|
|
114
|
+
var svg = document.querySelector('#card svg');
|
|
115
|
+
var data = new XMLSerializer().serializeToString(svg);
|
|
116
|
+
var img = new Image();
|
|
117
|
+
img.onload = function () {
|
|
118
|
+
var cv = document.createElement('canvas'); cv.width = 2400; cv.height = 1260;
|
|
119
|
+
var g = cv.getContext('2d'); g.drawImage(img, 0, 0, 2400, 1260);
|
|
120
|
+
var a = document.createElement('a'); a.download = 'keyspill-card.png'; a.href = cv.toDataURL('image/png'); a.click();
|
|
121
|
+
};
|
|
122
|
+
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(data);
|
|
123
|
+
});
|
|
124
|
+
</script>
|
|
125
|
+
</body></html>`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function originLine(o) {
|
|
129
|
+
const parts = [];
|
|
130
|
+
if (o.tool) parts.push(`agent read it ${o.tool}×`);
|
|
131
|
+
if (o.user) parts.push(`you pasted it ${o.user}×`);
|
|
132
|
+
if (o.assistant) parts.push(`agent wrote it ${o.assistant}×`);
|
|
133
|
+
return parts.length ? `<span>${parts.join(', ')}</span>` : '';
|
|
134
|
+
}
|
package/src/protect.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { c } from './report.js';
|
|
5
|
+
|
|
6
|
+
export const CLAUDE_DENY = [
|
|
7
|
+
'Read(./.env)', 'Read(./.env.*)', 'Read(./**/.env)', 'Read(./**/.env.*)',
|
|
8
|
+
'Read(./**/*.pem)', 'Read(./**/*.key)', 'Read(./**/secrets/**)',
|
|
9
|
+
'Read(~/.aws/**)', 'Read(~/.ssh/**)', 'Read(~/.config/gcloud/**)',
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
export const CURSOR_IGNORE = ['.env', '.env.*', '*.pem', '*.key', 'secrets/'];
|
|
13
|
+
|
|
14
|
+
export function protect({ apply = false, home = os.homedir(), env = process.env, cwd = process.cwd() } = {}) {
|
|
15
|
+
const settingsPath = path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'settings.json');
|
|
16
|
+
const ignorePath = path.join(cwd, '.cursorignore');
|
|
17
|
+
|
|
18
|
+
let settings = {};
|
|
19
|
+
let settingsExists = false;
|
|
20
|
+
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); settingsExists = true; } catch (e) {
|
|
21
|
+
if (e.code !== 'ENOENT') {
|
|
22
|
+
console.error(c.red(` Could not parse ${settingsPath}: ${e.message}. Not touching it.`));
|
|
23
|
+
return 1;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const deny = settings.permissions?.deny || [];
|
|
27
|
+
const addDeny = CLAUDE_DENY.filter((r) => !deny.includes(r));
|
|
28
|
+
|
|
29
|
+
let ignore = '';
|
|
30
|
+
try { ignore = fs.readFileSync(ignorePath, 'utf8'); } catch { /* none yet */ }
|
|
31
|
+
const ignoreLines = new Set(ignore.split(/\r?\n/).map((l) => l.trim()));
|
|
32
|
+
const addIgnore = CURSOR_IGNORE.filter((l) => !ignoreLines.has(l));
|
|
33
|
+
|
|
34
|
+
console.log('');
|
|
35
|
+
console.log(` ${c.bold('keyspill protect')} ${c.gray('· keep secrets out of future sessions')}`);
|
|
36
|
+
console.log('');
|
|
37
|
+
console.log(` ${c.bold('Claude Code')} ${c.gray(settingsPath)}`);
|
|
38
|
+
console.log(addDeny.length ? addDeny.map((r) => ` ${c.green('+')} permissions.deny ${r}`).join('\n') : c.gray(' already protected'));
|
|
39
|
+
console.log(` ${c.bold('Cursor')} ${c.gray(ignorePath)}`);
|
|
40
|
+
console.log(addIgnore.length ? addIgnore.map((r) => ` ${c.green('+')} ${r}`).join('\n') : c.gray(' already protected'));
|
|
41
|
+
console.log('');
|
|
42
|
+
|
|
43
|
+
if (!apply) {
|
|
44
|
+
console.log(` Nothing changed yet. Run ${c.cyan('npx keyspill protect --apply')} to write these.`);
|
|
45
|
+
console.log(c.gray(' Note: deny rules cover file reads, not shell commands like `cat .env`. Keep reviewing Bash prompts.'));
|
|
46
|
+
console.log('');
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (addDeny.length) {
|
|
51
|
+
if (settingsExists) fs.copyFileSync(settingsPath, settingsPath + `.keyspill-backup-${Date.now()}`);
|
|
52
|
+
settings.permissions = settings.permissions || {};
|
|
53
|
+
settings.permissions.deny = [...deny, ...addDeny];
|
|
54
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
55
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
|
|
56
|
+
}
|
|
57
|
+
if (addIgnore.length) {
|
|
58
|
+
const sep = ignore && !ignore.endsWith('\n') ? '\n' : '';
|
|
59
|
+
fs.writeFileSync(ignorePath, ignore + sep + '# added by keyspill\n' + addIgnore.join('\n') + '\n');
|
|
60
|
+
}
|
|
61
|
+
console.log(` ${c.green('✔ Done.')} ${settingsExists && addDeny.length ? c.gray('A backup of your old settings.json sits next to it.') : ''}`);
|
|
62
|
+
console.log(c.gray(' Deny rules cover file reads, not shell commands like `cat .env`. Keep reviewing Bash prompts.'));
|
|
63
|
+
console.log('');
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
package/src/report.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import { summarize } from './scan.js';
|
|
3
|
+
|
|
4
|
+
const useColor = () => process.stdout.isTTY && !process.env.NO_COLOR && !process.argv.includes('--no-color');
|
|
5
|
+
const wrap = (code) => (s) => (useColor() ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
6
|
+
export const c = {
|
|
7
|
+
bold: wrap('1'), dim: wrap('2'), red: wrap('31'), green: wrap('32'), yellow: wrap('33'),
|
|
8
|
+
magenta: wrap('35'), cyan: wrap('36'), gray: wrap('90'), bgRed: wrap('41;97;1'),
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const SEV = {
|
|
12
|
+
critical: { dot: c.red('●'), name: (s) => c.red(c.bold(s)) },
|
|
13
|
+
high: { dot: c.yellow('●'), name: (s) => c.yellow(c.bold(s)) },
|
|
14
|
+
medium: { dot: c.gray('●'), name: (s) => c.gray(c.bold(s)) },
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function fmtBytes(n) {
|
|
18
|
+
if (n < 1024) return n + ' B';
|
|
19
|
+
const u = ['KB', 'MB', 'GB'];
|
|
20
|
+
let i = -1;
|
|
21
|
+
do { n /= 1024; i++; } while (n >= 1024 && i < u.length - 1);
|
|
22
|
+
return n.toFixed(n < 10 ? 1 : 0) + ' ' + u[i];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function fmtDate(ms) {
|
|
26
|
+
if (!ms || !Number.isFinite(ms)) return '—';
|
|
27
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function shortPath(p) {
|
|
31
|
+
const h = os.homedir();
|
|
32
|
+
if (!p) return p;
|
|
33
|
+
// Windows paths are case-insensitive and agents log the drive letter either way (c:\ vs C:\).
|
|
34
|
+
const starts = process.platform === 'win32' ? p.toLowerCase().startsWith(h.toLowerCase()) : p.startsWith(h);
|
|
35
|
+
return starts ? '~' + p.slice(h.length) : p;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function originText(o) {
|
|
39
|
+
const parts = [];
|
|
40
|
+
if (o.tool) parts.push(`agent read it ${o.tool}×`);
|
|
41
|
+
if (o.user) parts.push(`you pasted it ${o.user}×`);
|
|
42
|
+
if (o.assistant) parts.push(`agent wrote it ${o.assistant}×`);
|
|
43
|
+
return parts.join(' · ');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function printReport({ findings, stats }, { all = false } = {}) {
|
|
47
|
+
const s = summarize(findings);
|
|
48
|
+
const tools = Object.keys(stats.byTool);
|
|
49
|
+
const out = [];
|
|
50
|
+
out.push('');
|
|
51
|
+
out.push(` ${c.bold('keyspill')} ${c.gray('· what your AI agents have already seen')}`);
|
|
52
|
+
out.push(c.gray(` Scanned ${stats.files.toLocaleString()} session files (${fmtBytes(stats.bytes)}) from ${tools.length ? tools.join(', ') : 'no agents'} in ${(stats.durationMs / 1000).toFixed(1)}s · 100% local, nothing uploaded`));
|
|
53
|
+
out.push('');
|
|
54
|
+
|
|
55
|
+
if (!tools.length) {
|
|
56
|
+
out.push(` ${c.yellow('No agent session history found.')} Looked for Claude Code, Codex, Cursor, Gemini CLI, opencode, Copilot CLI, Cline/Roo.`);
|
|
57
|
+
out.push(c.gray(' Use --path <dir> to scan somewhere else.'));
|
|
58
|
+
out.push('');
|
|
59
|
+
console.log(out.join('\n'));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (!s.total) {
|
|
64
|
+
out.push(` ${c.green('✔ No secrets found.')} Your agents have clean hands. For now.`);
|
|
65
|
+
out.push(c.gray(' Keep it that way: npx keyspill protect'));
|
|
66
|
+
out.push('');
|
|
67
|
+
console.log(out.join('\n'));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const head = ` ${s.total} secret${s.total === 1 ? '' : 's'} seen by your agents `;
|
|
72
|
+
out.push(` ${c.bgRed(head)} ${c.red(s.critical + ' critical')} · ${c.yellow(s.high + ' high')} · ${c.gray(s.medium + ' medium')}`);
|
|
73
|
+
out.push('');
|
|
74
|
+
|
|
75
|
+
for (const sev of ['critical', 'high', 'medium']) {
|
|
76
|
+
const group = findings.filter((f) => f.severity === sev);
|
|
77
|
+
if (!group.length) continue;
|
|
78
|
+
out.push(` ${SEV[sev].name(sev.toUpperCase())}`);
|
|
79
|
+
const limit = all ? group.length : sev === 'medium' ? 5 : 15;
|
|
80
|
+
for (const f of group.slice(0, limit)) {
|
|
81
|
+
const label = f.varName ? `${f.label} (${f.varName})` : f.label;
|
|
82
|
+
out.push(` ${SEV[sev].dot} ${c.bold(label.padEnd(30))} ${c.cyan(f.display)}`);
|
|
83
|
+
const where = [
|
|
84
|
+
`${f.count}×`,
|
|
85
|
+
f.tools.join(', '),
|
|
86
|
+
f.projects.length ? shortPath(f.projects[0]) + (f.projects.length > 1 ? ` +${f.projects.length - 1}` : '') : null,
|
|
87
|
+
'last ' + fmtDate(f.lastSeen),
|
|
88
|
+
].filter(Boolean).join(' · ');
|
|
89
|
+
out.push(c.gray(` ${where}`));
|
|
90
|
+
const o = originText(f.origins);
|
|
91
|
+
if (o) out.push(c.gray(` ${o}`));
|
|
92
|
+
if (f.rotate && sev !== 'medium') out.push(` ${c.magenta('→ rotate:')} ${c.gray(f.rotate)}`);
|
|
93
|
+
}
|
|
94
|
+
if (group.length > limit) out.push(c.gray(` … and ${group.length - limit} more (use --all)`));
|
|
95
|
+
out.push('');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
out.push(c.bold(' What now'));
|
|
99
|
+
out.push(` 1. Rotate every ${c.red('critical')} and ${c.yellow('high')} key above. Once it was in a session, it was sent to a model provider.`);
|
|
100
|
+
out.push(` 2. Stop agents reading .env files: ${c.cyan('npx keyspill protect')}`);
|
|
101
|
+
out.push(` 3. Share your score (no secrets in it): ${c.cyan('npx keyspill --card')}`);
|
|
102
|
+
out.push('');
|
|
103
|
+
console.log(out.join('\n'));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function toJson({ findings, stats }) {
|
|
107
|
+
return JSON.stringify({
|
|
108
|
+
version: 1,
|
|
109
|
+
summary: summarize(findings),
|
|
110
|
+
stats,
|
|
111
|
+
findings: findings.map((f) => ({
|
|
112
|
+
rule: f.rule, label: f.label, severity: f.severity, masked: f.display, fingerprint: f.hash,
|
|
113
|
+
variable: f.varName, count: f.count, tools: f.tools, projects: f.projects, files: f.files,
|
|
114
|
+
origins: f.origins, firstSeen: fmtDate(f.firstSeen), lastSeen: fmtDate(f.lastSeen), rotate: f.rotate,
|
|
115
|
+
})),
|
|
116
|
+
}, null, 2);
|
|
117
|
+
}
|
package/src/rules.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Detection rules. Each rule: id, label, severity, regex (with one capture group = the secret),
|
|
2
|
+
// optional `prefix` (non-secret part safe to show), optional `rotate` URL, optional `check(value, match)`.
|
|
3
|
+
// Keep rules high-signal: a false positive in a security tool costs more trust than a miss.
|
|
4
|
+
|
|
5
|
+
const B = String.raw;
|
|
6
|
+
|
|
7
|
+
export const RULES = [
|
|
8
|
+
// ---------- critical ----------
|
|
9
|
+
{
|
|
10
|
+
id: 'aws-access-key', label: 'AWS access key ID', severity: 'critical', prefix: 'AKIA',
|
|
11
|
+
re: /\b(AKIA[A-Z0-9]{16})\b/g, rotate: 'https://console.aws.amazon.com/iam/home#/security_credentials',
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
id: 'aws-secret-key', label: 'AWS secret access key', severity: 'critical',
|
|
15
|
+
re: /aws_?secret_?access_?key["'\s]*[:=]\s*["']?([A-Za-z0-9/+]{40})(?![A-Za-z0-9/+])/gi,
|
|
16
|
+
rotate: 'https://console.aws.amazon.com/iam/home#/security_credentials',
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
id: 'private-key', label: 'Private key (PEM)', severity: 'critical',
|
|
20
|
+
re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----(?:\s|\\[nr])*([A-Za-z0-9+/=]{40})/g,
|
|
21
|
+
display: () => '-----BEGIN … PRIVATE KEY-----',
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
id: 'stripe-live', label: 'Stripe live secret key', severity: 'critical',
|
|
25
|
+
re: /\b((?:sk|rk)_live_[A-Za-z0-9]{20,})\b/g, prefixFrom: /^(?:sk|rk)_live_/,
|
|
26
|
+
rotate: 'https://dashboard.stripe.com/apikeys',
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
id: 'db-url', label: 'Database URL with password', severity: 'critical',
|
|
30
|
+
re: /\b((?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?|amqps?|mssql):\/\/[^\s:@/"'`\\]+:[^\s:@/"'`\\]{3,}@[^\s"'`\\]+)/g,
|
|
31
|
+
check: checkDbUrl,
|
|
32
|
+
display: displayDbUrl,
|
|
33
|
+
// The same credentials show up with different /db?options tails: one finding per user:pass@host.
|
|
34
|
+
canonical: (v) => { const m = parseDbUrl(v); return m ? `${m.scheme}://${m.user}:${m.pass}@${m.host.toLowerCase()}` : v; },
|
|
35
|
+
// The password alone, so a MONGODB_PASSWORD=... line with the same value is not reported twice.
|
|
36
|
+
secretPart: (v) => parseDbUrl(v)?.pass ?? v,
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
// ---------- high ----------
|
|
40
|
+
{ id: 'aws-temp-key', label: 'AWS temporary key ID', severity: 'high', prefix: 'ASIA', re: /\b(ASIA[A-Z0-9]{16})\b/g },
|
|
41
|
+
{
|
|
42
|
+
id: 'github-token', label: 'GitHub token', severity: 'high',
|
|
43
|
+
re: /\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})\b/g,
|
|
44
|
+
prefixFrom: /^(?:gh[pousr]_|github_pat_)/, rotate: 'https://github.com/settings/tokens',
|
|
45
|
+
},
|
|
46
|
+
{ id: 'gitlab-token', label: 'GitLab token', severity: 'high', re: /\b(glpat-[A-Za-z0-9_-]{20,})\b/g, prefix: 'glpat-', rotate: 'https://gitlab.com/-/user_settings/personal_access_tokens' },
|
|
47
|
+
{
|
|
48
|
+
id: 'openai-key', label: 'OpenAI API key', severity: 'high',
|
|
49
|
+
re: /\b(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{40,}|sk-[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20})\b/g,
|
|
50
|
+
prefixFrom: /^sk-(?:proj-|svcacct-|admin-)?/, rotate: 'https://platform.openai.com/api-keys',
|
|
51
|
+
},
|
|
52
|
+
{ id: 'anthropic-key', label: 'Anthropic API key', severity: 'high', re: /\b(sk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{80,})/g, prefixFrom: /^sk-ant-(?:api|admin)\d{2}-/, rotate: 'https://console.anthropic.com/settings/keys' },
|
|
53
|
+
{ id: 'google-api-key', label: 'Google API key', severity: 'high', re: /\b(AIza[0-9A-Za-z_-]{35})(?![0-9A-Za-z_-])/g, prefix: 'AIza', rotate: 'https://console.cloud.google.com/apis/credentials' },
|
|
54
|
+
{ id: 'slack-token', label: 'Slack token', severity: 'high', re: /\b(xox[abposr]-[A-Za-z0-9-]{10,})\b/g, prefixFrom: /^xox[abposr]-/, rotate: 'https://api.slack.com/apps' },
|
|
55
|
+
{ id: 'slack-webhook', label: 'Slack webhook URL', severity: 'high', re: /(https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{20,})/g, prefix: 'https://hooks.slack.com/services/', rotate: 'https://api.slack.com/apps' },
|
|
56
|
+
{ id: 'telegram-bot', label: 'Telegram bot token', severity: 'high', re: /\b(\d{8,10}:AA[A-Za-z0-9_-]{33})(?![A-Za-z0-9_-])/g, rotate: 'https://t.me/BotFather' },
|
|
57
|
+
{ id: 'discord-bot', label: 'Discord bot token', severity: 'high', re: /\b([MN][A-Za-z\d_-]{23,25}\.[A-Za-z\d_-]{6}\.[A-Za-z\d_-]{27,38})\b/g, rotate: 'https://discord.com/developers/applications' },
|
|
58
|
+
{ id: 'sendgrid', label: 'SendGrid API key', severity: 'high', re: /\b(SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})(?![A-Za-z0-9_-])/g, prefix: 'SG.', rotate: 'https://app.sendgrid.com/settings/api_keys' },
|
|
59
|
+
{ id: 'twilio', label: 'Twilio API key', severity: 'high', re: /\b(SK[0-9a-f]{32})\b/g, prefix: 'SK', rotate: 'https://console.twilio.com/' },
|
|
60
|
+
{ id: 'npm-token', label: 'npm token', severity: 'high', re: /\b(npm_[A-Za-z0-9]{36})\b/g, prefix: 'npm_', rotate: 'https://www.npmjs.com/settings/~/tokens' },
|
|
61
|
+
{ id: 'pypi-token', label: 'PyPI token', severity: 'high', re: /\b(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,})/g, prefix: 'pypi-', rotate: 'https://pypi.org/manage/account/token/' },
|
|
62
|
+
{ id: 'huggingface', label: 'Hugging Face token', severity: 'high', re: /\b(hf_[A-Za-z0-9]{34,})\b/g, prefix: 'hf_', rotate: 'https://huggingface.co/settings/tokens' },
|
|
63
|
+
{ id: 'shopify', label: 'Shopify token', severity: 'high', re: /\b(shp(?:at|ca|pa|ss)_[a-fA-F0-9]{32})\b/g, prefixFrom: /^shp(?:at|ca|pa|ss)_/ },
|
|
64
|
+
{ id: 'digitalocean', label: 'DigitalOcean token', severity: 'high', re: /\b(do[por]_v1_[a-f0-9]{64})\b/g, prefixFrom: /^do[por]_v1_/, rotate: 'https://cloud.digitalocean.com/account/api/tokens' },
|
|
65
|
+
{ id: 'stripe-webhook', label: 'Stripe webhook secret', severity: 'high', re: /\b(whsec_[A-Za-z0-9]{32,})\b/g, prefix: 'whsec_', rotate: 'https://dashboard.stripe.com/webhooks' },
|
|
66
|
+
{ id: 'groq', label: 'Groq API key', severity: 'high', re: /\b(gsk_[A-Za-z0-9]{50,})\b/g, prefix: 'gsk_', rotate: 'https://console.groq.com/keys' },
|
|
67
|
+
{ id: 'replicate', label: 'Replicate token', severity: 'high', re: /\b(r8_[A-Za-z0-9]{37})\b/g, prefix: 'r8_', rotate: 'https://replicate.com/account/api-tokens' },
|
|
68
|
+
{ id: 'supabase-pat', label: 'Supabase access token', severity: 'high', re: /\b(sbp_[a-f0-9]{40})\b/g, prefix: 'sbp_', rotate: 'https://supabase.com/dashboard/account/tokens' },
|
|
69
|
+
{ id: 'mailgun', label: 'Mailgun API key', severity: 'high', re: /\b(key-[a-f0-9]{32})\b/g, prefix: 'key-' },
|
|
70
|
+
|
|
71
|
+
// ---------- JWT (special-cased: Supabase service_role is critical, anon keys are public) ----------
|
|
72
|
+
{
|
|
73
|
+
id: 'jwt', label: 'JWT', severity: 'medium',
|
|
74
|
+
re: /\b(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{20,})\b/g,
|
|
75
|
+
check: checkJwt,
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
// ---------- medium ----------
|
|
79
|
+
{ id: 'stripe-test', label: 'Stripe test key', severity: 'medium', re: /\b((?:sk|rk)_test_[A-Za-z0-9]{20,})\b/g, prefixFrom: /^(?:sk|rk)_test_/ },
|
|
80
|
+
{
|
|
81
|
+
id: 'env-secret', label: 'Secret in env/config', severity: 'medium', generic: true,
|
|
82
|
+
re: new RegExp(B`(?<![A-Za-z0-9_])([A-Z][A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|TOKEN|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY|AUTH_?KEY)[A-Z0-9_]*)["']?([ \t]*[=:][ \t]*)(["']?)([^\s"'\x60\\,;)]{8,})`, 'g'),
|
|
83
|
+
group: 4, nameGroup: 1, check: checkGeneric,
|
|
84
|
+
},
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
const PLACEHOLDER = /(example|sample|dummy|placeholder|your[_-]|changeme|change_me|xxxx|\*\*\*|redacted|<|>|\$\{|\{\{|%s|replace|insert|todo|fake|lorem|\.\.\.|•)/i;
|
|
88
|
+
|
|
89
|
+
export function looksPlaceholder(v) {
|
|
90
|
+
if (PLACEHOLDER.test(v)) return true;
|
|
91
|
+
if (/^(.)\1+$/.test(v)) return true; // aaaaaaa
|
|
92
|
+
if (/^(?:0123456789|1234567890|abcdef)/i.test(v)) return true;
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function entropy(s) {
|
|
97
|
+
const f = {};
|
|
98
|
+
for (const c of s) f[c] = (f[c] || 0) + 1;
|
|
99
|
+
let e = 0;
|
|
100
|
+
for (const k in f) { const p = f[k] / s.length; e -= p * Math.log2(p); }
|
|
101
|
+
return e;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function checkGeneric(value, m) {
|
|
105
|
+
const name = m[1];
|
|
106
|
+
if (/PUBLIC|PUBLISHABLE|_URL$|_PATH$|_FILE$|_NAME$|_ID$|_LENGTH$|_TTL$|_EXPIRES?|_TYPE$|_HEADER$|_FIELD$|_MAX|_MIN|COUNT|SIZE|PORT$|^NEXT_PUBLIC|^VITE_|^REACT_APP_/.test(name)) return false;
|
|
107
|
+
if (looksPlaceholder(value)) return false;
|
|
108
|
+
if (/[(){}[\]]/.test(value)) return false; // code expression
|
|
109
|
+
if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(value)) return false; // dotted identifier: token.ERRORTOKEN
|
|
110
|
+
if (/key|token|secret|pass|auth/i.test(value)) return false; // a label, not a secret
|
|
111
|
+
const spaced = /\s/.test(m[2]);
|
|
112
|
+
const quoted = !!m[3];
|
|
113
|
+
// `NAME = expr` without quotes is code. Allow it only for strongly random values (YAML / compose files).
|
|
114
|
+
if (spaced && !quoted && !(value.length >= 16 && entropy(value) >= 3.5 && /\d/.test(value) && /[A-Za-z]/.test(value))) return false;
|
|
115
|
+
if (/^(?:process\.|os\.|import\.|env\.|getenv|true|false|null|undefined|none|required|optional|string|number)/i.test(value)) return false;
|
|
116
|
+
if (/^[a-z]+(?:[A-Z][a-z]+)+$/.test(value)) return false; // camelCase identifier
|
|
117
|
+
if (/^[a-z_]+$/.test(value) || /^[A-Z_]+$/.test(value)) return false; // plain word / CONSTANT
|
|
118
|
+
if (/^\d+$/.test(value)) return false;
|
|
119
|
+
if (/^(?:https?:)?\/\//.test(value) || value.includes('/')) return false;
|
|
120
|
+
if (entropy(value) < 3.0) return false;
|
|
121
|
+
const classes = [/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/].filter((r) => r.test(value)).length;
|
|
122
|
+
return classes >= 2;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const LOCAL_HOSTS = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|host\.docker\.internal|db|postgres|mysql|mongo|mongodb|redis|rabbitmq|database)(:\d+)?$/i;
|
|
126
|
+
const DEFAULT_PASSWORDS = /^(password|pass|postgres|root|admin|secret|mysql|guest|test|example|changeme|redis|mongo|user|dev|local)$/i;
|
|
127
|
+
|
|
128
|
+
const PLACEHOLDER_WORDS = /^(user|username|usr|login|host|hostname|server|cluster|db|dbname|database|name|pass|password|pwd|passwd|secret|db_?user|db_?password|db_?pass|my_?user|my_?password)$/i;
|
|
129
|
+
|
|
130
|
+
function parseDbUrl(value) {
|
|
131
|
+
const m = value.match(/^([^:]+):\/\/([^:]+):([^@]+)@([^/?#]+)/);
|
|
132
|
+
return m ? { scheme: m[1], user: m[2], pass: m[3], host: m[4] } : null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function checkDbUrl(value) {
|
|
136
|
+
const m = parseDbUrl(value);
|
|
137
|
+
if (!m) return false;
|
|
138
|
+
const { user, pass, host } = m;
|
|
139
|
+
const hostname = host.replace(/:\d+$/, '');
|
|
140
|
+
if (looksPlaceholder(pass) || looksPlaceholder(host) || looksPlaceholder(user)) return false;
|
|
141
|
+
if (/^\$|^%|^\{/.test(pass)) return false;
|
|
142
|
+
// Docs and READMEs: mongodb+srv://USER:PASSWORD@HOST, or the same in another language.
|
|
143
|
+
if (PLACEHOLDER_WORDS.test(pass) || PLACEHOLDER_WORDS.test(hostname) || PLACEHOLDER_WORDS.test(user)) return false;
|
|
144
|
+
if (/[^\x00-\x7F]/.test(user + host)) return false; // real hostnames are ASCII (punycode)
|
|
145
|
+
if (LOCAL_HOSTS.test(host) && DEFAULT_PASSWORDS.test(pass)) return false;
|
|
146
|
+
if (LOCAL_HOSTS.test(host)) return { severity: 'medium', label: 'Local database password' };
|
|
147
|
+
if (!hostname.includes('.') && !/^\d/.test(hostname)) return false; // single-word host that isn't local: a placeholder
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Reports get screenshotted and shared, so only the provider's domain stays readable:
|
|
152
|
+
// mongodb+srv://kaz_db:••••••@••••.mongodb.net postgres://ap•••:••••••@••••.acme-internal.net
|
|
153
|
+
function displayDbUrl(value) {
|
|
154
|
+
const m = parseDbUrl(value);
|
|
155
|
+
if (!m) return maskTail(value);
|
|
156
|
+
const user = m.user.length > 3 ? m.user.slice(0, 2) + '•••' : '•••';
|
|
157
|
+
return `${m.scheme}://${user}:${'•'.repeat(6)}@${maskHost(m.host)}`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function maskHost(host) {
|
|
161
|
+
const name = host.replace(/:\d+$/, '');
|
|
162
|
+
if (LOCAL_HOSTS.test(name)) return name;
|
|
163
|
+
if (/^[\d.]+$/.test(name) || name.startsWith('[')) return '••••'; // IP address
|
|
164
|
+
const labels = name.split('.');
|
|
165
|
+
return labels.length >= 2 ? '••••.' + labels.slice(-2).join('.') : '••••';
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function checkJwt(value) {
|
|
169
|
+
try {
|
|
170
|
+
const payload = JSON.parse(Buffer.from(value.split('.')[1], 'base64url').toString('utf8'));
|
|
171
|
+
if (payload.role === 'anon') return false; // Supabase anon key: public by design
|
|
172
|
+
if (payload.role === 'service_role') return { severity: 'critical', label: 'Supabase service_role key', rotate: 'https://supabase.com/dashboard/project/_/settings/api' };
|
|
173
|
+
// Only report tokens that are still usable. Expired or never-expiring sample tokens are noise.
|
|
174
|
+
if (typeof payload.exp === 'number' && payload.exp * 1000 > Date.now()) return { label: 'Unexpired JWT' };
|
|
175
|
+
return false;
|
|
176
|
+
} catch {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function maskTail(v, prefix = '') {
|
|
182
|
+
const rest = v.slice(prefix.length);
|
|
183
|
+
const tail = rest.length >= 20 ? 4 : rest.length >= 12 ? 2 : 0;
|
|
184
|
+
return prefix + '•'.repeat(8) + (tail ? rest.slice(-tail) : '');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function displayFor(rule, value) {
|
|
188
|
+
if (rule.display) return rule.display(value);
|
|
189
|
+
let prefix = rule.prefix && value.startsWith(rule.prefix) ? rule.prefix : '';
|
|
190
|
+
if (rule.prefixFrom) prefix = (value.match(rule.prefixFrom) || [''])[0];
|
|
191
|
+
return maskTail(value, prefix);
|
|
192
|
+
}
|
package/src/scan.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import readline from 'node:readline';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { RULES, displayFor, looksPlaceholder } from './rules.js';
|
|
6
|
+
import { getSources, walk } from './sources.js';
|
|
7
|
+
|
|
8
|
+
const SEV_RANK = { critical: 3, high: 2, medium: 1 };
|
|
9
|
+
const JSON_WHOLE_LIMIT = 64 * 1024 * 1024;
|
|
10
|
+
const CHUNK_OVERLAP = 4096;
|
|
11
|
+
|
|
12
|
+
export async function scan({ home, env = process.env, extraPaths = [], onProgress = () => {} } = {}) {
|
|
13
|
+
const started = Date.now();
|
|
14
|
+
const sources = getSources(home, env);
|
|
15
|
+
if (extraPaths.length) {
|
|
16
|
+
sources.push({
|
|
17
|
+
id: 'custom', name: 'Custom path', roots: extraPaths,
|
|
18
|
+
match: (f) => /\.(jsonl?|vscdb|db|md|txt|log)$/.test(f),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const findings = new Map();
|
|
23
|
+
const stats = { files: 0, bytes: 0, byTool: {}, durationMs: 0 };
|
|
24
|
+
|
|
25
|
+
// Discover first so progress can show totals.
|
|
26
|
+
const jobs = [];
|
|
27
|
+
for (const src of sources) {
|
|
28
|
+
for (const root of src.roots) {
|
|
29
|
+
for (const f of walk(root, src.match)) jobs.push({ src, root, ...f });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const totalBytes = jobs.reduce((a, j) => a + j.size, 0);
|
|
33
|
+
|
|
34
|
+
for (const job of jobs) {
|
|
35
|
+
const { src, file } = job;
|
|
36
|
+
stats.byTool[src.name] = (stats.byTool[src.name] || 0) + 1;
|
|
37
|
+
const base = {
|
|
38
|
+
tool: src.name, file, mtime: job.mtime,
|
|
39
|
+
project: src.projectFromPath ? src.projectFromPath(file, job.root) : '',
|
|
40
|
+
};
|
|
41
|
+
try {
|
|
42
|
+
if (src.binary || /\.(vscdb|db)$/.test(file)) await scanRaw(file, base, findings);
|
|
43
|
+
else if (file.endsWith('.jsonl')) await scanJsonl(file, base, findings);
|
|
44
|
+
else if (file.endsWith('.json') && job.size < JSON_WHOLE_LIMIT) scanJsonFile(file, base, findings);
|
|
45
|
+
else await scanRaw(file, base, findings);
|
|
46
|
+
} catch {
|
|
47
|
+
// unreadable file (locked DB, permissions): skip silently, it is reported in stats as scanned=false
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
stats.files++;
|
|
51
|
+
stats.bytes += job.size;
|
|
52
|
+
onProgress({ files: stats.files, totalFiles: jobs.length, bytes: stats.bytes, totalBytes });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Drop generic env hits whose value was also caught by a specific rule.
|
|
56
|
+
const specificHashes = new Set([...findings.values()].filter((f) => !f.generic).flatMap((f) => [f.hash, f.secretHash]));
|
|
57
|
+
for (const [k, f] of findings) if (f.generic && specificHashes.has(f.hash)) findings.delete(k);
|
|
58
|
+
|
|
59
|
+
stats.durationMs = Date.now() - started;
|
|
60
|
+
const list = [...findings.values()]
|
|
61
|
+
.map(finalize)
|
|
62
|
+
.sort((a, b) => SEV_RANK[b.severity] - SEV_RANK[a.severity] || b.lastSeen - a.lastSeen);
|
|
63
|
+
return { findings: list, stats };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function finalize({ _seen, secretHash, ...f }) {
|
|
67
|
+
return {
|
|
68
|
+
...f,
|
|
69
|
+
tools: [...f.tools],
|
|
70
|
+
projects: [...f.projects].filter(Boolean),
|
|
71
|
+
files: [...f.files],
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---------- file readers ----------
|
|
76
|
+
|
|
77
|
+
async function scanJsonl(file, base, findings) {
|
|
78
|
+
const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
|
|
79
|
+
const state = { project: base.project, ts: null };
|
|
80
|
+
let n = 0;
|
|
81
|
+
for await (const line of rl) {
|
|
82
|
+
n++;
|
|
83
|
+
if (line.length < 8) continue;
|
|
84
|
+
state.lineKey = n;
|
|
85
|
+
let obj;
|
|
86
|
+
try { obj = JSON.parse(line); } catch { scanString(line, ctx(base, state, 'unknown'), findings); continue; }
|
|
87
|
+
if (obj && typeof obj === 'object') {
|
|
88
|
+
const cwd = obj.cwd || obj.payload?.cwd || obj.data?.context?.cwd || obj.data?.input?.cwd || obj.data?.workingDirectory;
|
|
89
|
+
if (typeof cwd === 'string') state.project = cwd;
|
|
90
|
+
const ts = obj.timestamp || obj.payload?.timestamp || obj.ts;
|
|
91
|
+
if (ts) state.ts = toMs(ts);
|
|
92
|
+
}
|
|
93
|
+
walkJson(obj, 'unknown', (s, origin) => scanString(s, ctx(base, state, origin), findings));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function scanJsonFile(file, base, findings) {
|
|
98
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
99
|
+
let obj;
|
|
100
|
+
try { obj = JSON.parse(text); } catch { scanString(text, ctx(base, {}, 'unknown'), findings); return; }
|
|
101
|
+
const state = { project: base.project || findCwd(obj), ts: null };
|
|
102
|
+
walkJson(obj, 'unknown', (s, origin) => scanString(s, ctx(base, state, origin), findings));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function scanRaw(file, base, findings) {
|
|
106
|
+
const stream = fs.createReadStream(file, { highWaterMark: 1 << 20 });
|
|
107
|
+
let tail = '';
|
|
108
|
+
for await (const buf of stream) {
|
|
109
|
+
const text = tail + buf.toString('latin1');
|
|
110
|
+
scanString(text, { ...ctx(base, {}, 'unknown'), minEnd: tail.length }, findings);
|
|
111
|
+
tail = text.slice(-CHUNK_OVERLAP);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function ctx(base, state, origin) {
|
|
116
|
+
return { ...base, project: state.project || base.project, ts: state.ts || base.mtime, origin, lineKey: state.lineKey };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function toMs(ts) {
|
|
120
|
+
if (typeof ts === 'number') return ts < 1e12 ? ts * 1000 : ts;
|
|
121
|
+
const t = Date.parse(ts);
|
|
122
|
+
return Number.isNaN(t) ? null : t;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function findCwd(obj) {
|
|
126
|
+
let found = '';
|
|
127
|
+
walkJson(obj, 'unknown', () => {}, (node) => {
|
|
128
|
+
if (!found && typeof node.cwd === 'string') found = node.cwd;
|
|
129
|
+
});
|
|
130
|
+
return found;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Walk every string in a JSON value, tracking where it came from:
|
|
134
|
+
// tool = output of a tool call (the agent read a file / ran a command)
|
|
135
|
+
// user = something you typed or pasted
|
|
136
|
+
// assistant = something the agent wrote (e.g. a command it ran)
|
|
137
|
+
// Event `type` values that mark tool output, per agent (Claude Code, Codex, opencode, Copilot CLI).
|
|
138
|
+
const TOOL_TYPES = new Set(['tool_result', 'function_call_output', 'tool', 'tool-result', 'local_shell_call_output', 'tool.execution_complete']);
|
|
139
|
+
// Event `type` values that mark who spoke when there is no `role` field.
|
|
140
|
+
const USER_TYPES = new Map([
|
|
141
|
+
['user', 'user'], ['user.message', 'user'],
|
|
142
|
+
['assistant', 'assistant'], ['assistant.message', 'assistant'], ['model.message', 'assistant'], ['model.response', 'assistant'],
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
function walkJson(root, origin, onString, onObject) {
|
|
146
|
+
const stack = [[root, origin]];
|
|
147
|
+
while (stack.length) {
|
|
148
|
+
const [node, o] = stack.pop();
|
|
149
|
+
if (typeof node === 'string') { if (node.length >= 8) onString(node, o); continue; }
|
|
150
|
+
if (!node || typeof node !== 'object') continue;
|
|
151
|
+
if (Array.isArray(node)) { for (const v of node) stack.push([v, o]); continue; }
|
|
152
|
+
onObject?.(node);
|
|
153
|
+
let here = o;
|
|
154
|
+
const t = node.type;
|
|
155
|
+
if (TOOL_TYPES.has(t) || node.role === 'tool') here = 'tool';
|
|
156
|
+
else if (o !== 'tool') {
|
|
157
|
+
const role = node.role || USER_TYPES.get(t) || null;
|
|
158
|
+
if (role === 'user') here = 'user';
|
|
159
|
+
else if (role === 'assistant' || role === 'model') here = 'assistant';
|
|
160
|
+
}
|
|
161
|
+
for (const [k, v] of Object.entries(node)) {
|
|
162
|
+
const childOrigin = k === 'toolUseResult' || k === 'functionResponse' ? 'tool' : here;
|
|
163
|
+
stack.push([v, childOrigin]);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------- the matcher ----------
|
|
169
|
+
|
|
170
|
+
export function scanString(text, c, findings) {
|
|
171
|
+
const spans = [];
|
|
172
|
+
for (const rule of RULES) {
|
|
173
|
+
if (rule.generic && !/[=:]/.test(text)) continue;
|
|
174
|
+
rule.re.lastIndex = 0;
|
|
175
|
+
let m;
|
|
176
|
+
while ((m = rule.re.exec(text))) {
|
|
177
|
+
const value = m[rule.group || 1];
|
|
178
|
+
const start = m.index + m[0].indexOf(value);
|
|
179
|
+
const end = start + value.length;
|
|
180
|
+
if (c.minEnd && end <= c.minEnd) continue; // already counted in the previous chunk
|
|
181
|
+
if (rule.generic && spans.some(([s, e]) => start < e && end > s)) continue;
|
|
182
|
+
if (rule.id !== 'db-url' && looksPlaceholder(value)) continue;
|
|
183
|
+
let verdict = true;
|
|
184
|
+
if (rule.check) verdict = rule.check(value, m);
|
|
185
|
+
if (!verdict) continue;
|
|
186
|
+
spans.push([start, end]);
|
|
187
|
+
record(rule, value, verdict === true ? {} : verdict, m, c, findings);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function record(rule, value, override, m, c, findings) {
|
|
193
|
+
const sha = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 12);
|
|
194
|
+
const hash = sha(rule.canonical ? rule.canonical(value) : value);
|
|
195
|
+
const key = rule.id + ':' + hash;
|
|
196
|
+
let f = findings.get(key);
|
|
197
|
+
if (!f) {
|
|
198
|
+
f = {
|
|
199
|
+
id: key, rule: rule.id, hash,
|
|
200
|
+
secretHash: rule.secretPart ? sha(rule.secretPart(value)) : hash,
|
|
201
|
+
label: override.label || rule.label,
|
|
202
|
+
severity: override.severity || rule.severity,
|
|
203
|
+
generic: !!rule.generic,
|
|
204
|
+
varName: rule.nameGroup ? m[rule.nameGroup] : undefined,
|
|
205
|
+
display: displayFor(rule, value),
|
|
206
|
+
rotate: override.rotate || rule.rotate,
|
|
207
|
+
count: 0, tools: new Set(), projects: new Set(), files: new Set(),
|
|
208
|
+
origins: { tool: 0, user: 0, assistant: 0, unknown: 0 },
|
|
209
|
+
firstSeen: Infinity, lastSeen: 0,
|
|
210
|
+
};
|
|
211
|
+
findings.set(key, f);
|
|
212
|
+
}
|
|
213
|
+
// One JSONL line is one event; agents often store the same tool output twice in it.
|
|
214
|
+
if (c.lineKey !== undefined && f._seen === c.file + '#' + c.lineKey) return;
|
|
215
|
+
if (c.lineKey !== undefined) f._seen = c.file + '#' + c.lineKey;
|
|
216
|
+
f.count++;
|
|
217
|
+
f.tools.add(c.tool);
|
|
218
|
+
if (c.project) f.projects.add(c.project);
|
|
219
|
+
f.files.add(c.file);
|
|
220
|
+
f.origins[c.origin] = (f.origins[c.origin] || 0) + 1;
|
|
221
|
+
const ts = c.ts || c.mtime;
|
|
222
|
+
if (ts < f.firstSeen) f.firstSeen = ts;
|
|
223
|
+
if (ts > f.lastSeen) f.lastSeen = ts;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function summarize(findings) {
|
|
227
|
+
const s = { total: findings.length, critical: 0, high: 0, medium: 0, byTool: {}, byOrigin: { tool: 0, user: 0, assistant: 0 } };
|
|
228
|
+
for (const f of findings) {
|
|
229
|
+
s[f.severity]++;
|
|
230
|
+
for (const t of f.tools) s.byTool[t] = (s.byTool[t] || 0) + 1;
|
|
231
|
+
const top = Object.entries(f.origins).filter(([k]) => k !== 'unknown').sort((a, b) => b[1] - a[1])[0];
|
|
232
|
+
if (top && top[1] > 0) s.byOrigin[top[0]]++;
|
|
233
|
+
}
|
|
234
|
+
return s;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export const _internal = { walkJson, path };
|
package/src/sources.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Where AI coding agents keep their local session history.
|
|
2
|
+
// Every path here is read-only for keyspill: we never modify, upload or copy these files.
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
|
|
7
|
+
export function getSources(home = os.homedir(), env = process.env) {
|
|
8
|
+
const plat = process.platform;
|
|
9
|
+
const appData = env.APPDATA || path.join(home, 'AppData', 'Roaming');
|
|
10
|
+
const xdgData = env.XDG_DATA_HOME || path.join(home, '.local', 'share');
|
|
11
|
+
const xdgConfig = env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
12
|
+
|
|
13
|
+
// VS Code–family editors (for Cline / Roo Code / Kilo Code task history, and Cursor's own DBs)
|
|
14
|
+
const editorUserDir = (name) =>
|
|
15
|
+
plat === 'darwin' ? path.join(home, 'Library', 'Application Support', name, 'User')
|
|
16
|
+
: plat === 'win32' ? path.join(appData, name, 'User')
|
|
17
|
+
: path.join(xdgConfig, name, 'User');
|
|
18
|
+
|
|
19
|
+
const extensionTasks = [];
|
|
20
|
+
for (const editor of ['Code', 'Code - Insiders', 'Cursor', 'Windsurf', 'VSCodium']) {
|
|
21
|
+
for (const ext of ['saoudrizwan.claude-dev', 'rooveterinaryinc.roo-cline', 'kilocode.kilo-code']) {
|
|
22
|
+
extensionTasks.push(path.join(editorUserDir(editor), 'globalStorage', ext));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return [
|
|
27
|
+
{
|
|
28
|
+
id: 'claude-code', name: 'Claude Code',
|
|
29
|
+
roots: [path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'projects')],
|
|
30
|
+
match: (f) => f.endsWith('.jsonl'),
|
|
31
|
+
projectFromPath: (f, root) => decodeClaudeDir(path.relative(root, f).split(path.sep)[0]),
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
id: 'codex', name: 'Codex',
|
|
35
|
+
roots: [path.join(env.CODEX_HOME || path.join(home, '.codex'), 'sessions'), path.join(env.CODEX_HOME || path.join(home, '.codex'), 'history.jsonl')],
|
|
36
|
+
match: (f) => f.endsWith('.jsonl'),
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
id: 'gemini', name: 'Gemini CLI',
|
|
40
|
+
roots: [path.join(home, '.gemini', 'tmp')],
|
|
41
|
+
match: (f) => f.endsWith('.json') || f.endsWith('.jsonl'),
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
id: 'opencode', name: 'opencode',
|
|
45
|
+
roots: [path.join(xdgData, 'opencode', 'storage'), path.join(xdgData, 'opencode', 'project')],
|
|
46
|
+
match: (f) => f.endsWith('.json'),
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: 'cursor', name: 'Cursor',
|
|
50
|
+
roots: [
|
|
51
|
+
path.join(editorUserDir('Cursor'), 'globalStorage', 'state.vscdb'),
|
|
52
|
+
path.join(editorUserDir('Cursor'), 'workspaceStorage'),
|
|
53
|
+
path.join(home, '.cursor', 'chats'),
|
|
54
|
+
],
|
|
55
|
+
match: (f) => /\.(vscdb|db)$/.test(f),
|
|
56
|
+
binary: true,
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: 'copilot-cli', name: 'Copilot CLI',
|
|
60
|
+
roots: [path.join(home, '.copilot', 'session-state'), path.join(home, '.copilot', 'history-session-state')],
|
|
61
|
+
match: (f) => f.endsWith('.jsonl') || f.endsWith('.json'),
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
id: 'cline', name: 'Cline / Roo / Kilo',
|
|
65
|
+
roots: extensionTasks.map((p) => path.join(p, 'tasks')),
|
|
66
|
+
match: (f) => /(api_conversation_history|ui_messages)\.json$/.test(f),
|
|
67
|
+
},
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ~/.claude/projects/-Users-kaz-work-shop -> /Users/kaz/work/shop (lossy: dashes in names are ambiguous)
|
|
72
|
+
// On Windows: C:\Users\kaz\work -> C--Users-kaz-work -> C:\Users\kaz\work
|
|
73
|
+
export function decodeClaudeDir(name) {
|
|
74
|
+
if (!name) return '';
|
|
75
|
+
const win = name.match(/^([A-Za-z])--(.*)$/);
|
|
76
|
+
if (win) return `${win[1]}:\\${win[2].replace(/-/g, '\\')}`;
|
|
77
|
+
if (!name.startsWith('-')) return name;
|
|
78
|
+
return name.replace(/-/g, '/');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'Cache', 'CachedData', 'GPUCache', 'logs']);
|
|
82
|
+
|
|
83
|
+
export function* walk(root, match, maxDepth = 8) {
|
|
84
|
+
let st;
|
|
85
|
+
try { st = fs.statSync(root); } catch { return; }
|
|
86
|
+
if (st.isFile()) { if (match(root)) yield { file: root, size: st.size, mtime: st.mtimeMs }; return; }
|
|
87
|
+
const stack = [[root, 0]];
|
|
88
|
+
while (stack.length) {
|
|
89
|
+
const [dir, depth] = stack.pop();
|
|
90
|
+
let entries;
|
|
91
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
|
|
92
|
+
for (const e of entries) {
|
|
93
|
+
const p = path.join(dir, e.name);
|
|
94
|
+
if (e.isDirectory()) {
|
|
95
|
+
if (depth < maxDepth && !SKIP_DIRS.has(e.name)) stack.push([p, depth + 1]);
|
|
96
|
+
} else if (e.isFile() && match(p)) {
|
|
97
|
+
try { const s = fs.statSync(p); yield { file: p, size: s.size, mtime: s.mtimeMs }; } catch { /* vanished */ }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|