shipclear 0.2.0

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/cli/lib/fix.js ADDED
@@ -0,0 +1,160 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { hasRemote, branchNames, hasStash, hasIdentity, run as git } from './git.js';
4
+
5
+ // Single source for the block both `setup` and the auto-fix append. Ignores
6
+ // SHIP-REPORT.md too: a committed report is a map of exactly where the
7
+ // findings were ("secret at server.js:7, see commit e6c9969") — the last
8
+ // thing to hand a stranger reading a public repo.
9
+ export const GITIGNORE_BLOCK = `
10
+ # Secrets — added by ShipClear
11
+ .env
12
+ .env.*
13
+ !.env.example
14
+ SHIP-REPORT.md
15
+ .shipclear/
16
+ `;
17
+
18
+ // The git pre-commit guard. Fails closed when the scan ran and found
19
+ // secrets (its output contains "ShipClear blocked"); fails open with a
20
+ // warning when the scanner itself couldn't run (offline npx, package not
21
+ // installed) — a guard that blocks every commit during an npm outage,
22
+ // with a wall of "npm error 404", gets deleted rather than fixed.
23
+ export const HOOK_SCRIPT = `#!/bin/sh
24
+ # Installed by ShipClear (shipclear setup). Blocks commits containing secrets.
25
+ # Remove this file to uninstall.
26
+ if [ -x "./node_modules/.bin/shipclear" ]; then
27
+ out=$(./node_modules/.bin/shipclear scan --staged 2>&1); status=$?
28
+ else
29
+ out=$(npx --yes shipclear scan --staged 2>&1); status=$?
30
+ fi
31
+ if [ "$status" -eq 0 ]; then exit 0; fi
32
+ case "$out" in
33
+ *"ShipClear blocked"*) printf '%s\\n' "$out" >&2; exit 1 ;;
34
+ *) printf 'ShipClear guard: could not run the staged scan (is shipclear installed / are you online?). Letting this commit through — run "npx shipclear scan --staged" yourself when you can.\\n' >&2; exit 0 ;;
35
+ esac
36
+ `;
37
+
38
+ /** Install (or refresh) the commit guard. Returns false if a foreign hook is in the way. */
39
+ export function installHook(root) {
40
+ const hookDir = path.join(root, '.git', 'hooks');
41
+ const hookPath = path.join(hookDir, 'pre-commit');
42
+ if (fs.existsSync(hookPath) && !fs.readFileSync(hookPath, 'utf8').includes('ShipClear')) return false;
43
+ fs.mkdirSync(hookDir, { recursive: true });
44
+ fs.writeFileSync(hookPath, HOOK_SCRIPT, { mode: 0o755 });
45
+ return true;
46
+ }
47
+
48
+ function hasOurHook(root) {
49
+ const hookPath = path.join(root, '.git', 'hooks', 'pre-commit');
50
+ return fs.existsSync(hookPath) && fs.readFileSync(hookPath, 'utf8').includes('ShipClear');
51
+ }
52
+
53
+ /** A .env.example built from .env's variable names with every value stripped. */
54
+ export function envExampleFrom(envPath) {
55
+ const keys = fs.readFileSync(envPath, 'utf8')
56
+ .split('\n')
57
+ .map((l) => l.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/))
58
+ .filter(Boolean)
59
+ .map((m) => `${m[1]}=`);
60
+ return '# Copy to .env and fill in real values. Never commit .env.\n' + keys.join('\n') + (keys.length ? '\n' : '');
61
+ }
62
+
63
+ /**
64
+ * Apply the fixes that are safe to do without asking: they only ever add
65
+ * protection, never delete or rewrite anything. Marks the corresponding
66
+ * findings as resolved and returns descriptions of what was done.
67
+ */
68
+ export function applyFixes(root, findings) {
69
+ const applied = [];
70
+
71
+ for (const finding of findings) {
72
+ if (finding.id === 'gitignore-incomplete') {
73
+ const file = path.join(root, '.gitignore');
74
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
75
+ fs.writeFileSync(file, existing + GITIGNORE_BLOCK);
76
+ finding.resolved = true;
77
+ applied.push('Added `.env` protection to .gitignore (created it if missing), and kept SHIP-REPORT.md out of git too.');
78
+ }
79
+
80
+ if (finding.id === 'env-example-missing') {
81
+ fs.writeFileSync(path.join(root, '.env.example'), envExampleFrom(path.join(root, '.env')));
82
+ finding.resolved = true;
83
+ applied.push('Created .env.example with your variable names and no values.');
84
+ }
85
+ }
86
+
87
+ return applied;
88
+ }
89
+
90
+ // Findings the reset itself cures: history is erased, and .env is no longer
91
+ // tracked once .gitignore (guaranteed by the implied additive fixes) excludes
92
+ // it from the fresh `git add -A`. Everything else that's still open would be
93
+ // re-added to the new root commit — baking it into history and forcing a
94
+ // second reset. A green verdict on a repo whose only commit holds four SSNs
95
+ // is the exact false-GO this project exists to prevent.
96
+ const CURED_BY_RESET = new Set(['secret-in-history', 'env-tracked']);
97
+
98
+ /**
99
+ * The one destructive fix, and the only one that is opt-in
100
+ * (`shipclear ship --fix-history`): erase git history so a leaked secret
101
+ * that was committed then deleted stops living in old commits.
102
+ *
103
+ * Exists because the alternative — telling a first-time user to type
104
+ * `rm -rf .git` by hand — is a real hazard (wrong directory, nothing
105
+ * checking for branches or stashes they'd lose). Running it here means it
106
+ * runs on exactly the folder ShipClear just scanned, and refuses in every
107
+ * situation where "start fresh" would silently destroy something — or
108
+ * silently preserve something it shouldn't.
109
+ *
110
+ * Returns { done } on success or { refused } with a plain-English reason.
111
+ * Never touches the key itself — rotation is still the user's job.
112
+ */
113
+ export function resetHistory(root, findings) {
114
+ const targets = findings.filter((f) => f.id === 'secret-in-history' && !f.resolved);
115
+ if (!targets.length) return { refused: 'there are no git-history findings to fix.' };
116
+
117
+ const wouldBeBakedIn = findings.filter(
118
+ (f) => !f.resolved && !CURED_BY_RESET.has(f.id) && ['critical', 'high', 'medium'].includes(f.severity)
119
+ );
120
+ if (wouldBeBakedIn.length) {
121
+ const list = [...new Set(wouldBeBakedIn.map((f) => f.file ? `${f.file}` : f.id))].join(', ');
122
+ return { refused: `other findings are still open (${list}). A fresh start saves whatever is in your project right now as the new first commit — so fix those first, then run --fix-history last. Otherwise they'd end up in history and you'd have to do this twice.` };
123
+ }
124
+ if (hasRemote(root)) {
125
+ return { refused: 'this repo has a remote configured (a copy on GitHub or similar), so old commits may already exist somewhere else — erasing local history would not remove them. Use the steps in the "secret exists in your git history" finding above instead: paste its sentence to your AI assistant, or follow the do-it-yourself commands.' };
126
+ }
127
+ const branches = branchNames(root);
128
+ if (branches.length > 1) {
129
+ return { refused: `this repo has ${branches.length} branches (${branches.join(', ')}) and a reset keeps only the current one. Merge or delete the others first, then run this again.` };
130
+ }
131
+ if (hasStash(root)) {
132
+ return { refused: 'this repo has stashed changes (`git stash list`) that a reset would lose. Apply or drop them first, then run this again.' };
133
+ }
134
+
135
+ const hadGuard = hasOurHook(root);
136
+ fs.rmSync(path.join(root, '.git'), { recursive: true, force: true });
137
+ git(root, ['init', '-q']);
138
+ let identityNote = '';
139
+ if (!hasIdentity(root)) {
140
+ // Local to this repo only — never touches the user's global git config.
141
+ git(root, ['config', 'user.email', 'you@example.com']);
142
+ git(root, ['config', 'user.name', 'You']);
143
+ identityNote = ' Git had no name/email set, so a placeholder was configured for this project only (optional to change — it only affects how your name shows on commits: `git config user.name "Your Name"`).';
144
+ }
145
+ git(root, ['add', '-A']);
146
+ // Plain message on purpose: this becomes the first line of public history
147
+ // if the repo is pushed, and shouldn't announce that there was a leak.
148
+ git(root, ['commit', '-q', '-m', 'Fresh start']);
149
+ // Keep the branch name the user had (main vs master) — a silent rename
150
+ // would look like something went wrong. Best-effort: cosmetic only.
151
+ if (branches[0]) {
152
+ try { git(root, ['branch', '-M', branches[0]]); } catch { /* fine on any git that refuses */ }
153
+ }
154
+ // rm -rf .git took the commit guard with it. Put it back.
155
+ const guardNote = hadGuard && installHook(root) ? ' The commit guard was reinstalled.' : '';
156
+ for (const f of targets) f.resolved = true;
157
+ return {
158
+ done: `Reset git history to remove the leaked secret from old commits — your files are untouched, only the old commits are gone.${guardNote}${identityNote} You still need to rotate the key.`,
159
+ };
160
+ }
package/cli/lib/git.js ADDED
@@ -0,0 +1,112 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ function git(root, args, opts = {}) {
4
+ return execFileSync('git', args, {
5
+ cwd: root,
6
+ encoding: 'utf8',
7
+ maxBuffer: 256 * 1024 * 1024,
8
+ stdio: ['ignore', 'pipe', 'pipe'],
9
+ ...opts,
10
+ });
11
+ }
12
+
13
+ export function isGitRepo(root) {
14
+ try {
15
+ return git(root, ['rev-parse', '--is-inside-work-tree']).trim() === 'true';
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ export function hasCommits(root) {
22
+ try {
23
+ git(root, ['rev-parse', 'HEAD']);
24
+ return true;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ /** Whether this repo has any remote configured (e.g. pushed to GitHub). */
31
+ export function hasRemote(root) {
32
+ try {
33
+ return git(root, ['remote']).trim().length > 0;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ export function branchNames(root) {
40
+ try {
41
+ return git(root, ['branch', '--format=%(refname:short)']).split('\n').filter(Boolean);
42
+ } catch {
43
+ return [];
44
+ }
45
+ }
46
+
47
+ export function hasStash(root) {
48
+ try {
49
+ return git(root, ['stash', 'list']).trim().length > 0;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ /** Whether git has a user identity it could commit with (global or local). */
56
+ export function hasIdentity(root) {
57
+ try {
58
+ return git(root, ['config', 'user.email']).trim().length > 0;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ export function run(root, args) {
65
+ return git(root, args);
66
+ }
67
+
68
+ export function trackedFiles(root) {
69
+ return git(root, ['ls-files']).split('\n').filter(Boolean);
70
+ }
71
+
72
+ export function stagedFiles(root) {
73
+ return git(root, ['diff', '--cached', '--name-only', '--diff-filter=ACM'])
74
+ .split('\n')
75
+ .filter(Boolean);
76
+ }
77
+
78
+ /** Content of a file as staged in the index (what a commit would record). */
79
+ export function stagedContent(root, file) {
80
+ try {
81
+ return git(root, ['show', ':' + file]);
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Every line ever *added* across the full history of all branches, so a
89
+ * secret that was committed and later deleted is still found.
90
+ * Returns [{ commit, file, text }].
91
+ */
92
+ export function historyAddedLines(root) {
93
+ const out = git(root, [
94
+ 'log', '--all', '-p', '--unified=0', '--no-color',
95
+ '--pretty=format:@@shipclear-commit@@ %h',
96
+ ]);
97
+ const added = [];
98
+ let commit = null;
99
+ let file = null;
100
+ for (const line of out.split('\n')) {
101
+ if (line.startsWith('@@shipclear-commit@@ ')) {
102
+ commit = line.slice('@@shipclear-commit@@ '.length).trim();
103
+ } else if (line.startsWith('+++ b/')) {
104
+ file = line.slice('+++ b/'.length);
105
+ } else if (line.startsWith('+++ /dev/null')) {
106
+ file = null;
107
+ } else if (line.startsWith('+') && !line.startsWith('+++') && file) {
108
+ added.push({ commit, file, text: line.slice(1) });
109
+ }
110
+ }
111
+ return added;
112
+ }
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const ALWAYS_IGNORED = ['SHIP-REPORT.md'];
5
+
6
+ function escapeRegex(s) {
7
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
8
+ }
9
+
10
+ /**
11
+ * Load .shipclearignore (one path or simple glob per line, # comments) and
12
+ * return a matcher over repo-relative paths. Directory entries cover
13
+ * everything beneath them.
14
+ */
15
+ export function loadIgnore(root) {
16
+ const patterns = [...ALWAYS_IGNORED];
17
+ const file = path.join(root, '.shipclearignore');
18
+ if (fs.existsSync(file)) {
19
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
20
+ const trimmed = line.trim();
21
+ if (trimmed && !trimmed.startsWith('#')) patterns.push(trimmed);
22
+ }
23
+ }
24
+ const rules = patterns.map((raw) => {
25
+ const pat = raw.replace(/\/+$/, '');
26
+ if (pat.includes('*')) {
27
+ const rx = new RegExp('^' + pat.split('*').map(escapeRegex).join('[^/]*') + '(/.*)?$');
28
+ return (rel) => rx.test(rel);
29
+ }
30
+ return (rel) => rel === pat || rel.startsWith(pat + '/');
31
+ });
32
+ return (rel) => rules.some((rule) => rule(rel));
33
+ }
@@ -0,0 +1,215 @@
1
+ // Detection patterns for the deterministic layer.
2
+ // Rule of the house: every pattern here must be proven by a fixture in
3
+ // tests/fixtures — both that it catches the real shape and that it stays
4
+ // quiet on placeholders.
5
+
6
+ // Passwords that make a connection string a template, not a leak. Tuned
7
+ // against real starter repos (t3, taxonomy, fastapi-template all ship URLs
8
+ // like mysql://root:password@localhost as documentation).
9
+ const TEMPLATE_DB_PASSWORDS = /^(?:(?:my|your)?pass(?:word)?|passw0rd|pwd|secret|changethis|changeme|change-me|root|postgres|mysql|mariadb|redis|mongo|admin|user|username|guest|test|dev|devel|local|localdev|example|sample|docker|1234\d{0,4})$/i;
10
+
11
+ function connectionStringHasRealPassword(match) {
12
+ const beforeAt = match.slice(0, -1); // strip trailing '@'
13
+ const password = beforeAt.slice(beforeAt.lastIndexOf(':') + 1);
14
+ return !TEMPLATE_DB_PASSWORDS.test(password) && !looksPlaceholder(password);
15
+ }
16
+
17
+ function base64UrlDecode(s) {
18
+ try {
19
+ return Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
20
+ } catch {
21
+ return '';
22
+ }
23
+ }
24
+
25
+ // JWTs are everywhere and mostly harmless (expired demos, public Supabase
26
+ // anon keys). The one that must never leak is a Supabase service-role key —
27
+ // identifiable by its payload. Everything else is deliberately ignored.
28
+ function isServiceRoleJwt(match) {
29
+ return base64UrlDecode(match.split('.')[1]).includes('"role":"service_role"');
30
+ }
31
+
32
+ // Provider-specific formats. These are high-confidence: a match is treated as
33
+ // a real secret even if it "looks fake", because a real-shaped key must be
34
+ // rotated anyway once it has touched a tracked file. A pattern may carry a
35
+ // `validate(match)` to veto matches that are provably templates.
36
+ export const SECRET_PATTERNS = [
37
+ { id: 'aws-access-key', name: 'AWS access key', regex: /\bAKIA[0-9A-Z]{16}\b/g },
38
+ { id: 'anthropic-api-key', name: 'Anthropic API key', regex: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/g },
39
+ { id: 'stripe-live-key', name: 'Stripe live secret key', regex: /\bsk_live_[0-9a-zA-Z]{16,}\b/g },
40
+ { id: 'stripe-test-key', name: 'Stripe test secret key', regex: /\bsk_test_[0-9a-zA-Z]{16,}\b/g, severity: 'medium' },
41
+ { id: 'openrouter-api-key', name: 'OpenRouter API key', regex: /\bsk-or-v1-[a-f0-9]{64}\b/g },
42
+ { id: 'openai-api-key', name: 'OpenAI API key', regex: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\b/g },
43
+ { id: 'github-token', name: 'GitHub token', regex: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g },
44
+ { id: 'google-api-key', name: 'Google API key', regex: /\bAIza[0-9A-Za-z_-]{35}\b/g },
45
+ { id: 'slack-token', name: 'Slack token', regex: /\bxox[baprs]-[0-9A-Za-z-]{10,}\b/g },
46
+ { id: 'sendgrid-api-key', name: 'SendGrid API key', regex: /\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b/g },
47
+ { id: 'npm-token', name: 'npm access token', regex: /\bnpm_[A-Za-z0-9]{36}\b/g },
48
+ { id: 'huggingface-token', name: 'Hugging Face token', regex: /\bhf_[A-Za-z0-9]{34}\b/g },
49
+ { id: 'digitalocean-token', name: 'DigitalOcean token', regex: /\bdop_v1_[a-f0-9]{64}\b/g },
50
+ { id: 'groq-api-key', name: 'Groq API key', regex: /\bgsk_[A-Za-z0-9]{20,}\b/g },
51
+ { id: 'xai-api-key', name: 'xAI API key', regex: /\bxai-[A-Za-z0-9]{20,}\b/g },
52
+ { id: 'azure-account-key', name: 'Azure storage account key', regex: /AccountKey=[A-Za-z0-9+/=]{40,}/g },
53
+ { id: 'supabase-service-role', name: 'Supabase service-role key (JWT)', regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, validate: isServiceRoleJwt },
54
+ { id: 'private-key-block', name: 'Private key material', regex: /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY(?: BLOCK)?-----/g },
55
+ { id: 'connection-string', name: 'Database URL with embedded password', regex: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^:/\s'"]+:[^@/\s'"]+@/g, validate: connectionStringHasRealPassword },
56
+ ];
57
+
58
+ // Values that are clearly stand-ins, not real credentials. Only applied to
59
+ // generic matches and validate() hooks — never to raw provider formats.
60
+ // {{ }} covers mustache/jinja templates; env( covers config indirection
61
+ // (supabase config.toml); the all-caps test covers constant-style
62
+ // placeholders like API_KEY_HERE (all tuned on real starter repos).
63
+ const PLACEHOLDER = /xxx|\.\.\.|your[_-]?|example|sample|placeholder|change[_-]?me|dummy|fake[_-]|insert[_-]?|<[^>]*>|\$\{|\{\{|%s|\bTODO\b/i;
64
+
65
+ export function looksPlaceholder(value) {
66
+ return (
67
+ PLACEHOLDER.test(value) ||
68
+ /^env\(/i.test(value) ||
69
+ /^[A-Z0-9]+(?:_[A-Z0-9]+)+$/.test(value)
70
+ );
71
+ }
72
+
73
+ export function entropy(s) {
74
+ const freq = {};
75
+ for (const c of s) freq[c] = (freq[c] || 0) + 1;
76
+ let h = 0;
77
+ for (const c in freq) {
78
+ const p = freq[c] / s.length;
79
+ h -= p * Math.log2(p);
80
+ }
81
+ return h;
82
+ }
83
+
84
+ // Assignments of suspicious names to string literals, e.g. apiKey = "...".
85
+ const GENERIC_ASSIGNMENT = /\b(api[_-]?key|apikey|secret[_-]?key|secret|password|passwd|access[_-]?token|auth[_-]?token|token)\b\s*[:=]\s*['"`]([^'"`\n]{8,})['"`]/gi;
86
+
87
+ export function maskSecret(value) {
88
+ return value.length <= 8 ? value[0] + '…' : value.slice(0, 8) + '…';
89
+ }
90
+
91
+ export function lineOfIndex(content, index) {
92
+ let line = 1;
93
+ for (let i = 0; i < index && i < content.length; i++) {
94
+ if (content.charCodeAt(i) === 10) line++;
95
+ }
96
+ return line;
97
+ }
98
+
99
+ /**
100
+ * Scan a string for secrets. Returns matches with pattern metadata, ordered
101
+ * by position. Overlapping matches are deduplicated in favor of the more
102
+ * specific pattern (SECRET_PATTERNS order, generics last).
103
+ */
104
+ export function findSecrets(content, { includeGeneric = true } = {}) {
105
+ const raw = [];
106
+ for (const p of SECRET_PATTERNS) {
107
+ p.regex.lastIndex = 0;
108
+ let m;
109
+ while ((m = p.regex.exec(content))) {
110
+ if (p.validate && !p.validate(m[0])) continue;
111
+ raw.push({
112
+ patternId: p.id,
113
+ name: p.name,
114
+ index: m.index,
115
+ match: m[0],
116
+ severity: p.severity || 'critical',
117
+ });
118
+ }
119
+ }
120
+ if (includeGeneric) {
121
+ GENERIC_ASSIGNMENT.lastIndex = 0;
122
+ let m;
123
+ while ((m = GENERIC_ASSIGNMENT.exec(content))) {
124
+ const value = m[2];
125
+ if (looksPlaceholder(value)) continue;
126
+ // Low-entropy, digit-free values ("mysecretvalue") are usually stubs.
127
+ if (entropy(value) < 3 && !/\d/.test(value)) continue;
128
+ raw.push({
129
+ patternId: 'generic-secret',
130
+ name: `Hardcoded ${m[1]}`,
131
+ index: m.index,
132
+ match: m[0],
133
+ value,
134
+ severity: 'medium',
135
+ });
136
+ }
137
+ }
138
+ const kept = [];
139
+ for (const cand of raw) {
140
+ const overlaps = kept.some(
141
+ (k) => cand.index < k.index + k.match.length && k.index < cand.index + cand.match.length
142
+ );
143
+ if (!overlaps) kept.push(cand);
144
+ }
145
+ return kept.sort((a, b) => a.index - b.index);
146
+ }
147
+
148
+ // --- PII patterns (used only on data files) ---
149
+
150
+ export const EMAIL = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g;
151
+ export const SSN = /\b\d{3}-\d{2}-\d{4}\b/g;
152
+
153
+ const FAKE_EMAIL_DOMAINS = /@(example\.(?:com|org|net)|test\.com|email\.com|domain\.com|yourdomain\.|acme\.|localhost)/i;
154
+
155
+ export function realLookingEmails(content) {
156
+ EMAIL.lastIndex = 0;
157
+ const seen = new Set();
158
+ let m;
159
+ while ((m = EMAIL.exec(content))) {
160
+ if (!FAKE_EMAIL_DOMAINS.test(m[0])) seen.add(m[0].toLowerCase());
161
+ }
162
+ return [...seen];
163
+ }
164
+
165
+ // --- misc shared patterns ---
166
+
167
+ // Password-ish identifier assigned a short string literal. Deliberately no
168
+ // leading \b: it must also hit inside names like TEST_PASSWORD. The optional
169
+ // quote before the separator covers JSON and quoted-key object literals
170
+ // (`"password": "…"`), the shape an AI writes into a seed or fixture file.
171
+ // Matches password-ish identifiers: password / passwd / pass, plus the short
172
+ // forms pwd / pword an AI sometimes uses (found missed on a monorepo test).
173
+ // No leading \b, so it also fires inside names like TEST_PASSWORD; the
174
+ // two-signal test-account rule (a suspicious account email nearby) keeps the
175
+ // broader match from producing false findings on its own.
176
+ export const PASSWORD_ASSIGNMENT = /(?:pass(?:word|wd)?|pword|pwd)[a-z0-9_]*["']?\s*[:=]\s*['"][^'"\n]{4,}['"]/i;
177
+
178
+ // Quoted email that smells like a built-in account.
179
+ export const SUSPICIOUS_ACCOUNT_EMAIL = /['"][a-z0-9._%+-]*(?:admin|test|demo|root|superuser)[a-z0-9._%+-]*@[a-z0-9.-]+\.[a-z]{2,}['"]/i;
180
+
181
+ // Turning off TLS certificate checking — the "fix" an AI assistant reaches
182
+ // for when a request fails with a certificate error. Deterministic and
183
+ // high-confidence: there is no placeholder form of the disable-verification
184
+ // flag. (Examples live in tests/fixtures, not here — the gate scans this
185
+ // file, and a real matchable form in a comment would flag our own repo.)
186
+ export const TLS_VERIFICATION_OFF = /rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?|\bverify\s*=\s*False\b/g;
187
+
188
+ // The leading lookbehind requires an absolute-path boundary, so a real home
189
+ // path matches but the `/home/` inside an import like `components/home/card`
190
+ // does not (found the hard way on the precedent starter repo).
191
+ // Flask/Werkzeug debug mode left on in code that ships. Scoped to the
192
+ // genuinely dangerous form — a Flask app.run call with debug enabled, or the
193
+ // FLASK_DEBUG env flag — not Django's dev-default DEBUG setting, which would
194
+ // drown users in false positives. Debug mode exposes an interactive Python
195
+ // console to anyone who triggers an error: remote code execution. (Examples
196
+ // live in tests, worded so they don't match this scanned file.)
197
+ export const DEBUG_MODE_ON = /\.run\([^)]*\bdebug\s*=\s*True|FLASK_DEBUG\s*[:=]\s*['"]?1\b|FLASK_ENV\s*[:=]\s*['"]?development\b/g;
198
+
199
+ export const PERSONAL_PATH = /(?<![\w./-])(?:\/(?:home|Users)\/[A-Za-z0-9._-]{3,}|[A-Z]:\\Users\\[A-Za-z0-9._-]{3,})/g;
200
+
201
+ const IMPERSONAL_PATH_USERS = new Set([
202
+ 'user', 'username', 'yourname', 'your-name', 'example', 'runner', 'node',
203
+ 'app', 'ubuntu', 'ec2-user', 'root', 'admin', 'test', 'you', 'name',
204
+ ]);
205
+
206
+ export function personalPaths(content) {
207
+ PERSONAL_PATH.lastIndex = 0;
208
+ const hits = [];
209
+ let m;
210
+ while ((m = PERSONAL_PATH.exec(content))) {
211
+ const user = m[0].split(/[/\\]/).filter(Boolean).pop().toLowerCase();
212
+ if (!IMPERSONAL_PATH_USERS.has(user)) hits.push({ index: m.index, match: m[0] });
213
+ }
214
+ return hits;
215
+ }