archsutra-ai 0.1.5 → 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/CHANGELOG.md +47 -6
- package/README.md +83 -11
- package/dist/audit.js +125 -44
- package/dist/cli.js +184 -96
- package/dist/drift.js +29 -15
- package/dist/fsutil.js +117 -20
- package/dist/history.js +40 -0
- package/dist/html.js +10 -8
- package/dist/map.js +26 -5
- package/dist/mcp.js +70 -55
- package/dist/redact.js +24 -11
- package/dist/report.js +69 -19
- package/dist/rules-extra.js +59 -0
- package/dist/secret-patterns.js +69 -0
- package/dist/suppress.js +31 -19
- package/dist/verify.js +2 -2
- package/dist/write.js +71 -0
- package/docs/architecture/overview.html +29 -12
- package/docs/architecture/overview.md +2 -2
- package/docs/architecture/threat-model.html +28 -11
- package/docs/assets/charts/coverage-dark.svg +11 -0
- package/docs/assets/charts/coverage.svg +11 -0
- package/docs/assets/charts/finding-anatomy-dark.svg +20 -0
- package/docs/assets/charts/finding-anatomy.svg +20 -0
- package/docs/assets/charts/pipeline-dark.svg +13 -0
- package/docs/assets/charts/pipeline.svg +13 -0
- package/docs/assets/charts/precision-by-batch-dark.svg +12 -0
- package/docs/assets/charts/precision-by-batch.svg +12 -0
- package/docs/assets/charts/precision-by-rule-dark.svg +12 -0
- package/docs/assets/charts/precision-by-rule.svg +12 -0
- package/docs/assets/charts/sample-findings-by-severity-dark.svg +11 -0
- package/docs/assets/charts/sample-findings-by-severity.svg +11 -0
- package/docs/assets/charts/scan-time-dark.svg +11 -0
- package/docs/assets/charts/scan-time.svg +11 -0
- package/docs/assets/site.css +259 -138
- package/docs/assets/site.js +92 -6
- package/docs/community/good-first-issues.html +28 -11
- package/docs/compatibility/matrix.html +28 -11
- package/docs/compatibility/smoke-tests/index.html +28 -11
- package/docs/decisions/ADR-0001-deterministic-cli-plus-ide-skills.html +28 -11
- package/docs/guides/cheat-sheet.html +100 -0
- package/docs/guides/cheat-sheet.md +146 -0
- package/docs/guides/ci-recipes.html +170 -0
- package/docs/guides/ci-recipes.md +176 -0
- package/docs/guides/evidence-at-a-glance.html +93 -0
- package/docs/guides/evidence-at-a-glance.md +65 -0
- package/docs/guides/getting-started.html +151 -0
- package/docs/guides/getting-started.md +160 -0
- package/docs/guides/how-it-works.html +161 -0
- package/docs/guides/how-it-works.md +148 -0
- package/docs/guides/mcp-server.html +99 -0
- package/docs/guides/mcp-server.md +81 -0
- package/docs/guides/reading-a-report.html +119 -0
- package/docs/guides/reading-a-report.md +111 -0
- package/docs/guides/real-world-scenarios.html +287 -0
- package/docs/guides/real-world-scenarios.md +377 -0
- package/docs/handbook/01-executive-summary.html +30 -13
- package/docs/handbook/01-executive-summary.md +2 -2
- package/docs/handbook/02-functional-specification.html +30 -13
- package/docs/handbook/02-functional-specification.md +3 -3
- package/docs/handbook/03-technical-specification.html +31 -14
- package/docs/handbook/03-technical-specification.md +3 -3
- package/docs/handbook/04-architecture.html +29 -12
- package/docs/handbook/04-architecture.md +1 -1
- package/docs/handbook/05-user-guide.html +33 -15
- package/docs/handbook/05-user-guide.md +5 -4
- package/docs/handbook/06-cli-reference.html +52 -16
- package/docs/handbook/06-cli-reference.md +47 -4
- package/docs/handbook/07-security-privacy-legal.html +31 -12
- package/docs/handbook/07-security-privacy-legal.md +4 -0
- package/docs/handbook/08-testing-and-proof.html +32 -15
- package/docs/handbook/08-testing-and-proof.md +4 -4
- package/docs/handbook/09-compatibility-and-roadmap.html +29 -12
- package/docs/handbook/09-compatibility-and-roadmap.md +2 -1
- package/docs/handbook/10-contributor-guide.html +29 -12
- package/docs/handbook/10-contributor-guide.md +1 -1
- package/docs/handbook/11-glossary-and-faq.html +34 -13
- package/docs/handbook/11-glossary-and-faq.md +7 -1
- package/docs/handbook/12-rule-catalog.html +59 -19
- package/docs/handbook/12-rule-catalog.md +62 -5
- package/docs/handbook/13-trust-and-assurance.html +29 -12
- package/docs/handbook/13-trust-and-assurance.md +1 -1
- package/docs/handbook/14-real-world-evaluation.html +28 -11
- package/docs/handbook/15-supply-chain-and-release.html +28 -11
- package/docs/handbook/16-performance-and-quality-metrics.html +28 -11
- package/docs/handbook/16-performance-and-quality-metrics.md +1 -1
- package/docs/handbook/README.md +4 -2
- package/docs/handbook/index.html +31 -13
- package/docs/index.html +101 -51
- package/docs/legal/legal-review-brief.html +28 -11
- package/docs/legal/trademark-and-name-clearance.html +28 -11
- package/docs/proof/accessibility.html +28 -11
- package/docs/proof/benchmarks.json +9 -9
- package/docs/proof/benchmarks.md +4 -4
- package/docs/proof/test-results.txt +56 -40
- package/docs/rfc/0001-archsutra-v0.1.html +28 -11
- package/docs/sample-report/architecture-register.json +46 -0
- package/docs/sample-report/audit-report.html +123 -0
- package/docs/sample-report/audit-report.md +314 -0
- package/docs/sample-report/current-state.html +77 -0
- package/docs/sample-report/current-state.md +51 -0
- package/docs/sample-report/findings.json +478 -0
- package/docs/sample-report/findings.sarif +754 -0
- package/docs/sample-report/index.html +57 -0
- package/docs/sample-report/overview.md +11 -0
- package/docs/search-index.json +1 -0
- package/docs/sitemap.xml +39 -28
- package/llms.txt +11 -2
- package/package.json +3 -2
- package/schemas/findings.schema.json +4 -3
- package/skills/architecture-audit/SKILL.md +2 -2
- package/skills/architecture-audit/references/report-template.md +1 -1
- package/skills/architecture-verification/references/fitness-functions.md +1 -1
package/dist/fsutil.js
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
1
2
|
import { promises as fs } from 'node:fs';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
const IGNORED_DIRS = new Set([
|
|
4
|
-
'node_modules', '.git', 'dist', '
|
|
5
|
-
'.next', '.nuxt', 'coverage', '.gradle', '.idea', '.vscode', '
|
|
6
|
-
'graphify-out',
|
|
5
|
+
'node_modules', '.git', 'dist', 'vendor', '.venv', 'venv', '__pycache__',
|
|
6
|
+
'.next', '.nuxt', 'coverage', '.gradle', '.idea', '.vscode', '.terraform', '.archsutra', 'graphify-out',
|
|
7
7
|
]);
|
|
8
|
+
/** These names often hold real source or scripts. They are skipped only when something shows they are build output. */
|
|
9
|
+
const BUILD_DIRS = {
|
|
10
|
+
target: /^(Cargo\.toml|pom\.xml|build\.sbt)$/,
|
|
11
|
+
bin: /\.(cs|fs|vb)proj$/,
|
|
12
|
+
obj: /\.(cs|fs|vb)proj$/,
|
|
13
|
+
build: /^(build\.gradle(\.kts)?|CMakeLists\.txt)$/,
|
|
14
|
+
out: /^(build\.gradle(\.kts)?|CMakeLists\.txt)$/,
|
|
15
|
+
};
|
|
8
16
|
const BINARY_EXT = new Set([
|
|
9
17
|
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz', '.tgz', '.tar', '.7z', '.jar',
|
|
10
18
|
'.class', '.exe', '.dll', '.so', '.dylib', '.woff', '.woff2', '.ttf', '.eot', '.mp3', '.mp4', '.mov',
|
|
11
19
|
'.bin', '.lock', '.map', '.wasm', '.pyc',
|
|
12
20
|
]);
|
|
21
|
+
const MAX_SKIPPED_LISTED = 200;
|
|
13
22
|
function toPosix(p) {
|
|
14
23
|
return p.split(path.sep).join('/');
|
|
15
24
|
}
|
|
@@ -22,7 +31,43 @@ export function safeJoin(root, rel) {
|
|
|
22
31
|
return abs;
|
|
23
32
|
}
|
|
24
33
|
/**
|
|
25
|
-
*
|
|
34
|
+
* Small gitignore-style glob: `*` and `?` stay inside one segment, `**` crosses segments. A pattern
|
|
35
|
+
* without a slash matches at any depth; a matching directory covers everything under it.
|
|
36
|
+
*/
|
|
37
|
+
export function globToRegExp(glob) {
|
|
38
|
+
const g = glob.replace(/\\/g, '/').replace(/^\.?\//, '').replace(/\/$/, '');
|
|
39
|
+
const body = g.split(/(\*\*\/|\*\*|\*|\?)/).map((t) => (t === '**/' ? '(?:.*/)?' : t === '**' ? '.*' : t === '*' ? '[^/]*' : t === '?' ? '[^/]' : t.replace(/[.+^${}()|[\]\\]/g, '\\$&'))).join('');
|
|
40
|
+
return new RegExp(`${g.includes('/') ? '^' : '(?:^|/)'}${body}(?:/|$)`);
|
|
41
|
+
}
|
|
42
|
+
async function ignoreFile(root, name) {
|
|
43
|
+
try {
|
|
44
|
+
return (await fs.readFile(path.join(root, name), 'utf8')).split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('!'));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function gitIgnored(root) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
execFile('git', ['-C', root, 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'], { maxBuffer: 64 * 1024 * 1024 }, (err, stdout) => {
|
|
53
|
+
if (err)
|
|
54
|
+
reject(new Error('--respect-gitignore needs git and a git repository.'));
|
|
55
|
+
else
|
|
56
|
+
resolve(stdout.split('\0').filter(Boolean).map((p) => p.replace(/\/$/, '')));
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/** The folder a file is accounted to in coverage and sampling. */
|
|
61
|
+
function bucketOf(rel) {
|
|
62
|
+
const parts = rel.split('/');
|
|
63
|
+
if (parts.length === 1)
|
|
64
|
+
return '(root)';
|
|
65
|
+
return /^(packages|apps|services|libs|modules|internal|cmd|src)$/.test(parts[0]) && parts.length > 2 ? `${parts[0]}/${parts[1]}` : parts[0];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Bounded, symlink-safe repository walk. Never follows symlinks, never reads file contents (only ignore files).
|
|
69
|
+
* It lists the tree first and then takes files folder by folder in turn, so a limit never silently
|
|
70
|
+
* drops the folders that sort last.
|
|
26
71
|
*/
|
|
27
72
|
export async function walk(root, opts = {}) {
|
|
28
73
|
const limits = {
|
|
@@ -31,71 +76,123 @@ export async function walk(root, opts = {}) {
|
|
|
31
76
|
timeBudgetMs: opts.timeBudgetMs ?? 15000,
|
|
32
77
|
maxTotalBytes: opts.maxTotalBytes ?? 120 * 1024 * 1024,
|
|
33
78
|
};
|
|
34
|
-
let totalBytes = 0;
|
|
35
79
|
const start = Date.now();
|
|
36
|
-
const files = [];
|
|
37
|
-
const skipped = { ignoredDirs: 0, tooLarge: 0, binary: 0, symlinks: 0, overBudget: 0 };
|
|
38
|
-
let truncated = false;
|
|
39
80
|
const absRoot = path.resolve(root);
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
81
|
+
const skipped = { ignoredDirs: 0, tooLarge: 0, binary: 0, symlinks: 0, overBudget: 0, excluded: 0 };
|
|
82
|
+
const skippedPaths = [];
|
|
83
|
+
const note = (rel, reason) => {
|
|
84
|
+
if (skippedPaths.length < MAX_SKIPPED_LISTED)
|
|
85
|
+
skippedPaths.push({ path: rel, reason });
|
|
86
|
+
};
|
|
87
|
+
let truncated = false;
|
|
88
|
+
const expired = () => Date.now() - start > limits.timeBudgetMs;
|
|
89
|
+
const exclude = [...(await ignoreFile(absRoot, '.archsutraignore')), ...(opts.exclude ?? [])].map(globToRegExp);
|
|
90
|
+
const include = (opts.include ?? []).map(globToRegExp);
|
|
91
|
+
const gitignore = new Set((await ignoreFile(absRoot, '.gitignore')).map((l) => l.replace(/^\//, '').replace(/\/$/, '')));
|
|
92
|
+
const fromGit = new Set(opts.respectGitignore ? await gitIgnored(absRoot) : []);
|
|
93
|
+
const buckets = new Map();
|
|
94
|
+
async function list(dir) {
|
|
43
95
|
let entries;
|
|
44
96
|
try {
|
|
45
97
|
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
46
98
|
}
|
|
47
99
|
catch {
|
|
100
|
+
note(toPosix(path.relative(absRoot, dir)) || '.', 'unreadable directory');
|
|
48
101
|
return;
|
|
49
102
|
}
|
|
50
103
|
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
51
104
|
for (const e of entries) {
|
|
52
|
-
if (
|
|
105
|
+
if (expired()) {
|
|
53
106
|
truncated = true;
|
|
54
107
|
skipped.overBudget++;
|
|
55
108
|
return;
|
|
56
109
|
}
|
|
57
110
|
const abs = path.join(dir, e.name);
|
|
111
|
+
const rel = toPosix(path.relative(absRoot, abs));
|
|
58
112
|
if (e.isSymbolicLink()) {
|
|
59
113
|
skipped.symlinks++;
|
|
114
|
+
note(rel, 'symbolic link');
|
|
60
115
|
continue;
|
|
61
116
|
}
|
|
62
|
-
|
|
63
|
-
|
|
117
|
+
const isDir = e.isDirectory();
|
|
118
|
+
if (isDir) {
|
|
119
|
+
const marker = BUILD_DIRS[e.name];
|
|
120
|
+
if (IGNORED_DIRS.has(e.name) || (marker && (gitignore.has(e.name) || gitignore.has(rel) || entries.some((x) => x.isFile() && marker.test(x.name))))) {
|
|
64
121
|
skipped.ignoredDirs++;
|
|
122
|
+
note(rel, 'ignored directory');
|
|
65
123
|
continue;
|
|
66
124
|
}
|
|
67
|
-
|
|
125
|
+
}
|
|
126
|
+
if (fromGit.has(rel) || exclude.some((x) => x.test(rel))) {
|
|
127
|
+
skipped.excluded++;
|
|
128
|
+
note(rel, 'excluded');
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (isDir) {
|
|
132
|
+
await list(abs);
|
|
68
133
|
continue;
|
|
69
134
|
}
|
|
70
135
|
if (!e.isFile())
|
|
71
136
|
continue;
|
|
137
|
+
if (include.length && !include.some((x) => x.test(rel))) {
|
|
138
|
+
skipped.excluded++;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
72
141
|
const ext = path.extname(e.name).toLowerCase();
|
|
73
142
|
if (BINARY_EXT.has(ext)) {
|
|
74
143
|
skipped.binary++;
|
|
75
144
|
continue;
|
|
76
145
|
}
|
|
77
|
-
|
|
146
|
+
const key = bucketOf(rel);
|
|
147
|
+
let bucket = buckets.get(key);
|
|
148
|
+
if (!bucket)
|
|
149
|
+
buckets.set(key, (bucket = []));
|
|
150
|
+
bucket.push({ rel, abs, ext });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
await list(absRoot);
|
|
154
|
+
const files = [];
|
|
155
|
+
const taken = new Map();
|
|
156
|
+
const queues = [...buckets].sort((a, b) => a[0].localeCompare(b[0]));
|
|
157
|
+
let totalBytes = 0;
|
|
158
|
+
const deadline = Date.now() + limits.timeBudgetMs;
|
|
159
|
+
for (let round = 0; queues.some(([, q]) => round < q.length); round++) {
|
|
160
|
+
for (const [name, q] of queues) {
|
|
161
|
+
const f = q[round];
|
|
162
|
+
if (!f)
|
|
163
|
+
continue;
|
|
164
|
+
if (files.length >= limits.maxFiles || Date.now() > deadline) {
|
|
165
|
+
truncated = true;
|
|
166
|
+
skipped.overBudget++;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
let size;
|
|
78
170
|
try {
|
|
79
|
-
size = (await fs.stat(abs)).size;
|
|
171
|
+
size = (await fs.stat(f.abs)).size;
|
|
80
172
|
}
|
|
81
173
|
catch {
|
|
174
|
+
note(f.rel, 'unreadable file');
|
|
82
175
|
continue;
|
|
83
176
|
}
|
|
84
177
|
if (size > limits.maxFileBytes) {
|
|
85
178
|
skipped.tooLarge++;
|
|
179
|
+
note(f.rel, 'larger than the per-file limit');
|
|
86
180
|
continue;
|
|
87
181
|
}
|
|
88
182
|
if (totalBytes + size > limits.maxTotalBytes) {
|
|
89
183
|
truncated = true;
|
|
90
184
|
skipped.overBudget++;
|
|
185
|
+
note(f.rel, 'total size limit');
|
|
91
186
|
continue;
|
|
92
187
|
}
|
|
93
188
|
totalBytes += size;
|
|
94
|
-
files.push({
|
|
189
|
+
files.push({ ...f, size });
|
|
190
|
+
taken.set(name, (taken.get(name) ?? 0) + 1);
|
|
95
191
|
}
|
|
96
192
|
}
|
|
97
|
-
|
|
98
|
-
|
|
193
|
+
files.sort((a, b) => a.rel.localeCompare(b.rel));
|
|
194
|
+
const folders = queues.map(([name, q]) => ({ name, scanned: taken.get(name) ?? 0, total: q.length }));
|
|
195
|
+
return { root: absRoot, files, skipped, skippedPaths, folders, limits, truncated };
|
|
99
196
|
}
|
|
100
197
|
const textCache = new Map();
|
|
101
198
|
const CACHE_LIMIT_BYTES = 160 * 1024 * 1024;
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { detectSecrets, excerpt } from './redact.js';
|
|
4
|
+
export const DEFAULT_HISTORY_LIMIT = 1000;
|
|
5
|
+
/**
|
|
6
|
+
* Secrets in lines that were ever added, read from local git. No network. The generic name=value guess
|
|
7
|
+
* is left out: over a whole history it is mostly noise. Each value is reported once per file.
|
|
8
|
+
*/
|
|
9
|
+
export async function scanHistory(root, limit = DEFAULT_HISTORY_LIMIT) {
|
|
10
|
+
const git = spawn('git', ['-C', root, 'log', '--all', '-p', '-U0', '--no-color', '--no-ext-diff', '--no-textconv', `--max-count=${limit}`, '--format=%x01%h %as', '--relative', '--', '.'], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
11
|
+
const done = new Promise((resolve) => {
|
|
12
|
+
git.on('error', () => resolve(-1));
|
|
13
|
+
git.on('close', (code) => resolve(code ?? -1));
|
|
14
|
+
});
|
|
15
|
+
const found = [];
|
|
16
|
+
const seen = new Set();
|
|
17
|
+
let commit = '';
|
|
18
|
+
let file = '';
|
|
19
|
+
for await (const line of createInterface({ input: git.stdout, crlfDelay: Infinity })) {
|
|
20
|
+
if (line.startsWith('\u0001'))
|
|
21
|
+
commit = line.slice(1);
|
|
22
|
+
else if (line.startsWith('+++ '))
|
|
23
|
+
file = line.slice(4).replace(/^b\//, '');
|
|
24
|
+
else if (line.startsWith('+') && line.length < 2000 && file && !/(^|\/)(node_modules|vendor)\//.test(file)) {
|
|
25
|
+
const text = line.slice(1);
|
|
26
|
+
for (const hit of detectSecrets(text)) {
|
|
27
|
+
if (hit.kind === 'credential-assignment')
|
|
28
|
+
continue;
|
|
29
|
+
const key = `${file}\n${hit.kind}\n${text.trim()}`; // in memory only, never written
|
|
30
|
+
if (seen.has(key))
|
|
31
|
+
continue;
|
|
32
|
+
seen.add(key);
|
|
33
|
+
found.push({ path: file, kind: 'observed', excerpt: `${hit.kind} (git history ${commit}): ${excerpt(text, 80)}` });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if ((await done) !== 0)
|
|
38
|
+
throw new Error('--history needs git and a repository with at least one commit.');
|
|
39
|
+
return found;
|
|
40
|
+
}
|
package/dist/html.js
CHANGED
|
@@ -4,7 +4,7 @@ const MERMAID_SRC = 'https://cdn.jsdelivr.net/npm/mermaid@12.3.0/dist/mermaid.es
|
|
|
4
4
|
export const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
5
5
|
const CSS = `
|
|
6
6
|
:root{--bg:#fbfbfd;--card:#fff;--soft:#f2f3f8;--text:#15181e;--muted:#565e6e;--line:#e1e4ec;--accent:#4338ca;--crit:#b42318;--high:#c2410c;--med:#8a5a00;--low:#1d4ed8;--info:#565e6e;--ok:#17794a;color-scheme:light}
|
|
7
|
-
|
|
7
|
+
html[data-theme=dark]{--bg:#0c0f14;--card:#131820;--soft:#1a202a;--text:#e8ebf2;--muted:#a2abbb;--line:#262e3b;--accent:#a5a8ff;--crit:#ff8a80;--high:#ffab70;--med:#f0c36a;--low:#8fb4ff;--info:#a2abbb;--ok:#5fd39a;color-scheme:dark}
|
|
8
8
|
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:16px/1.6 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
9
9
|
a{color:var(--accent)}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em}
|
|
10
10
|
:not(pre)>code{background:var(--soft);border:1px solid var(--line);padding:.1em .35em;border-radius:6px;overflow-wrap:anywhere}
|
|
@@ -19,7 +19,7 @@ h1{font-size:clamp(1.6rem,3vw,2.2rem);letter-spacing:-.02em;margin:.1em 0}h2{fon
|
|
|
19
19
|
th,td{text-align:left;vertical-align:top;padding:9px 13px;border-bottom:1px solid var(--line)}th{background:var(--soft)}tr:last-child td{border-bottom:0}
|
|
20
20
|
.badge{display:inline-block;padding:1px 9px;border-radius:999px;border:1px solid currentColor;font-size:.78rem;font-weight:650;text-transform:uppercase;letter-spacing:.03em;white-space:nowrap}
|
|
21
21
|
.sev-critical{color:var(--crit)}.sev-high{color:var(--high)}.sev-medium{color:var(--med)}.sev-low{color:var(--low)}.sev-info{color:var(--info)}
|
|
22
|
-
.r-strong{color:var(--ok)}.r-adequate{color:var(--med)}.r-weak{color:var(--high)}.r-critical{color:var(--crit)}.r-not{color:var(--muted)}
|
|
22
|
+
.r-strong{color:var(--ok)}.r-adequate{color:var(--med)}.r-weak{color:var(--high)}.r-critical{color:var(--crit)}.r-no,.r-not{color:var(--muted)}
|
|
23
23
|
.filters{display:flex;flex-wrap:wrap;gap:8px;margin:12px 0}.filters button{font:inherit;font-size:.88rem;padding:5px 12px;border-radius:999px;border:1px solid var(--line);background:var(--card);color:var(--text);cursor:pointer}
|
|
24
24
|
.filters button[aria-pressed=true]{background:var(--accent);color:var(--bg);border-color:var(--accent)}
|
|
25
25
|
details.finding{background:var(--card);border:1px solid var(--line);border-radius:12px;margin:10px 0;padding:4px 16px}
|
|
@@ -29,10 +29,11 @@ pre{background:var(--soft);border:1px solid var(--line);border-radius:10px;paddi
|
|
|
29
29
|
figure.diagram{margin:12px 0;padding:14px;background:var(--card);border:1px solid var(--line);border-radius:12px;overflow-x:auto}pre.mermaid{background:transparent;border:0;padding:0;text-align:center}
|
|
30
30
|
footer{margin-top:40px;padding-top:16px;border-top:1px solid var(--line);color:var(--muted);font-size:.85rem}
|
|
31
31
|
:focus-visible{outline:3px solid var(--accent);outline-offset:2px;border-radius:4px}
|
|
32
|
-
|
|
32
|
+
.tt{float:right;font:inherit;font-size:.85rem;padding:4px 12px;border-radius:999px;border:1px solid var(--line);background:var(--card);color:var(--text);cursor:pointer}
|
|
33
|
+
@media print{.tt{display:none}.filters,.nav{display:none}details.finding{break-inside:avoid}details.finding:not([open])>*{display:block}}
|
|
33
34
|
`;
|
|
34
35
|
const MERMAID_JS = `
|
|
35
|
-
const dark=
|
|
36
|
+
const dark=document.documentElement.dataset.theme==='dark';
|
|
36
37
|
try{const m=(await import('${MERMAID_SRC}')).default;
|
|
37
38
|
m.initialize({startOnLoad:false,securityLevel:'strict',theme:'base',themeVariables:dark?{primaryColor:'#1f2340',primaryTextColor:'#e8ebf2',primaryBorderColor:'#a5a8ff',lineColor:'#a2abbb',edgeLabelBackground:'#131820',textColor:'#e8ebf2'}:{primaryColor:'#eceafd',primaryTextColor:'#15181e',primaryBorderColor:'#4338ca',lineColor:'#565e6e',edgeLabelBackground:'#ffffff',textColor:'#15181e'}});
|
|
38
39
|
await m.run({nodes:document.querySelectorAll('pre.mermaid')});}catch(e){/* offline: diagram source stays visible */}`;
|
|
@@ -49,12 +50,13 @@ function page(title, nav, body, opts = {}) {
|
|
|
49
50
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
50
51
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline' https://cdn.jsdelivr.net; connect-src https://cdn.jsdelivr.net; img-src data:; base-uri 'none'; form-action 'none'">
|
|
51
52
|
<meta name="color-scheme" content="light dark">
|
|
53
|
+
<script>try{if(localStorage.getItem("as-theme")==="dark")document.documentElement.dataset.theme="dark"}catch(e){}</script>
|
|
52
54
|
<meta name="generator" content="ArchSutra AI">
|
|
53
55
|
<title>${esc(title)}</title>
|
|
54
56
|
<style>${CSS}</style>
|
|
55
57
|
</head>
|
|
56
58
|
<body>
|
|
57
|
-
<header class="top"><div class="wrap"><nav class="nav" aria-label="Report pages">${nav}</nav><h1>${esc(title)}</h1><p class="lede">Generated by ArchSutra AI. Deterministic static scan, read-only.</p></div></header>
|
|
59
|
+
<header class="top"><div class="wrap"><button class="tt" type="button" aria-label="Toggle light and dark theme" onclick="var d=document.documentElement,n=d.dataset.theme==='dark'?'light':'dark';if(n==='dark')d.dataset.theme='dark';else delete d.dataset.theme;try{localStorage.setItem('as-theme',n)}catch(e){}if(document.querySelector('pre.mermaid'))location.reload()">Theme</button><nav class="nav" aria-label="Report pages">${nav}</nav><h1>${esc(title)}</h1><p class="lede">Generated by ArchSutra AI. Deterministic static scan, read-only.</p></div></header>
|
|
58
60
|
<main class="wrap">
|
|
59
61
|
${body}
|
|
60
62
|
<footer>Review aid only. Not a certification, compliance attestation, security guarantee or legal advice. Findings marked <code>inferred</code> or <code>unknown</code> are hypotheses; absence of findings does not prove absence of problems. Secrets are redacted.</footer>
|
|
@@ -80,7 +82,7 @@ function findingHtml(f) {
|
|
|
80
82
|
const refs = f.references.length ? f.references.filter((r) => /^https:\/\//.test(r)).map((r) => `<a href="${esc(r)}" rel="noopener noreferrer">${esc(r)}</a>`).join(', ') : '';
|
|
81
83
|
return `<details class="finding sev-${esc(f.severity)}" data-sev="${esc(f.severity)}"${['critical', 'high'].includes(f.severity) ? ' open' : ''}>
|
|
82
84
|
<summary><span class="badge sev-${esc(f.severity)}">${esc(f.severity)}</span><h3>${esc(f.title)}</h3><span class="fid">${esc(f.id)}</span><span class="muted">confidence: ${esc(f.confidence)}</span></summary>
|
|
83
|
-
<div class="fbody"><p class="muted">Category: ${esc(f.category)}</p><p><b>Evidence</b></p><ul class="ev">${f.evidence.map(evHtml).join('')}</ul>
|
|
85
|
+
<div class="fbody"><p class="muted">Category: ${esc(f.category)}</p><p><b>Evidence</b></p><ul class="ev">${f.evidence.slice(0, 10).map(evHtml).join('')}${f.evidence.length > 10 ? `<li class="muted">... and ${f.evidence.length - 10} more (all listed in findings.json)</li>` : ''}</ul>
|
|
84
86
|
<dl>${dl.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join('')}${refs ? `<dt>References</dt><dd>${refs}</dd>` : ''}</dl></div>
|
|
85
87
|
</details>`;
|
|
86
88
|
}
|
|
@@ -99,8 +101,8 @@ export function renderAuditHtml(r) {
|
|
|
99
101
|
<h2 style="border-top:0;margin-top:0">Summary</h2>
|
|
100
102
|
<div class="cards">${cards}</div>
|
|
101
103
|
<p>Files scanned: <b>${r.map.coverage.filesScanned}</b>${r.map.coverage.truncated ? ' <span class="badge sev-high">truncated by budget</span>' : ''}. Stack observed: ${esc(r.map.ecosystems.join(', ') || 'none recognised')}.</p>
|
|
102
|
-
|
|
103
|
-
<div class="table-wrap"><table><thead><tr><th scope="col">Category</th><th scope="col">Rating</th><th scope="col">Basis</th></tr></thead><tbody>${r.scorecard.map((s) => `<tr><td>${esc(s.category)}</td><td><span class="badge ${ratingClass(s.rating)}">${esc(s.rating)}</span></td><td>${esc(s.basis)}</td></tr>`).join('')}</tbody></table></div
|
|
104
|
+
${r.scorecard.length ? `<h2>Scorecard</h2>
|
|
105
|
+
<div class="table-wrap"><table><thead><tr><th scope="col">Category</th><th scope="col">Rating</th><th scope="col">Confidence</th><th scope="col">Basis</th></tr></thead><tbody>${r.scorecard.map((s) => `<tr><td>${esc(s.category)}</td><td><span class="badge ${ratingClass(s.rating)}">${esc(s.rating)}</span></td><td>${esc(s.confidence)}</td><td>${esc(s.basis)}</td></tr>`).join('')}</tbody></table></div>` : ''}
|
|
104
106
|
<h2>Findings</h2>
|
|
105
107
|
${r.findings.length ? `<div class="filters" role="group" aria-label="Filter by severity"><button type="button" data-sev="all" aria-pressed="true">All (${r.findings.length})</button>${['critical', 'high', 'medium', 'low', 'info'].filter((s) => c[s]).map((s) => `<button type="button" data-sev="${s}" aria-pressed="false">${s} (${c[s]})</button>`).join('')}</div>${r.findings.map(findingHtml).join('\n')}` : '<p class="notice">No findings from the implemented rules. This does not prove the absence of problems.</p>'}
|
|
106
108
|
<h2>Scope and blind spots</h2>
|
package/dist/map.js
CHANGED
|
@@ -29,7 +29,10 @@ const DATASTORE_HINTS = {
|
|
|
29
29
|
};
|
|
30
30
|
const NON_CODE_IMPORT = new Set(['.json', '.css', '.scss', '.sass', '.less', '.svg', '.png', '.jpg', '.html', '.md', '.yml', '.yaml', '.txt', '.node', '.wasm']);
|
|
31
31
|
const GROUP_DIRS = new Set(['packages', 'apps', 'services', 'libs', 'modules', 'internal', 'cmd']);
|
|
32
|
-
export function moduleOf(rel) {
|
|
32
|
+
export function moduleOf(rel, workspaces = []) {
|
|
33
|
+
const ws = workspaces.find((w) => rel.startsWith(`${w}/`));
|
|
34
|
+
if (ws)
|
|
35
|
+
return ws;
|
|
33
36
|
const parts = rel.split('/');
|
|
34
37
|
if (parts.length === 1)
|
|
35
38
|
return '(root)';
|
|
@@ -47,6 +50,20 @@ export function resolveRelative(fromRel, spec) {
|
|
|
47
50
|
const dir = path.posix.dirname(fromRel);
|
|
48
51
|
return path.posix.normalize(path.posix.join(dir, spec));
|
|
49
52
|
}
|
|
53
|
+
const MANIFEST_NAME = /^(package\.json|go\.mod|Cargo\.toml|pom\.xml|build\.gradle(\.kts)?|.+\.(cs|fs)proj)$/;
|
|
54
|
+
/** When the root declares a workspace, every folder with its own manifest is a module, deepest first. */
|
|
55
|
+
export async function workspaceDirs(corpus) {
|
|
56
|
+
const text = async (name) => {
|
|
57
|
+
const f = corpus.files.find((x) => x.rel === name);
|
|
58
|
+
return f ? ((await readLines(f)) ?? []).join('\n') : '';
|
|
59
|
+
};
|
|
60
|
+
const declared = /"workspaces"\s*:/.test(await text('package.json')) || Boolean(await text('pnpm-workspace.yaml')) || Boolean(await text('go.work'))
|
|
61
|
+
|| /^\[workspace\]/m.test(await text('Cargo.toml')) || /<modules>/.test(await text('pom.xml')) || corpus.files.some((f) => /^[^/]+\.sln$/.test(f.rel));
|
|
62
|
+
if (!declared)
|
|
63
|
+
return [];
|
|
64
|
+
const dirs = corpus.files.filter((f) => f.rel.includes('/') && MANIFEST_NAME.test(path.posix.basename(f.rel))).map((f) => path.posix.dirname(f.rel));
|
|
65
|
+
return [...new Set(dirs)].sort((a, b) => b.length - a.length);
|
|
66
|
+
}
|
|
50
67
|
export async function readJson(abs) {
|
|
51
68
|
try {
|
|
52
69
|
return JSON.parse(await fs.readFile(abs, 'utf8'));
|
|
@@ -105,7 +122,9 @@ export async function buildMap(root, corpus) {
|
|
|
105
122
|
const entrypoints = [];
|
|
106
123
|
const edgeMap = new Map();
|
|
107
124
|
const blind = new Set();
|
|
108
|
-
const
|
|
125
|
+
const workspaces = await workspaceDirs(c);
|
|
126
|
+
const modOf = (rel) => moduleOf(rel, workspaces);
|
|
127
|
+
const moduleNames = new Set(c.files.map((f) => modOf(f.rel)));
|
|
109
128
|
for (const f of c.files) {
|
|
110
129
|
const base = path.posix.basename(f.rel);
|
|
111
130
|
if (MANIFESTS[base])
|
|
@@ -162,7 +181,7 @@ export async function buildMap(root, corpus) {
|
|
|
162
181
|
const eco = ECOSYSTEM_BY_EXT[f.ext];
|
|
163
182
|
if (!eco)
|
|
164
183
|
continue;
|
|
165
|
-
const mod =
|
|
184
|
+
const mod = modOf(f.rel);
|
|
166
185
|
const lines = await readLines(f);
|
|
167
186
|
if (!lines)
|
|
168
187
|
continue;
|
|
@@ -193,7 +212,7 @@ export async function buildMap(root, corpus) {
|
|
|
193
212
|
return;
|
|
194
213
|
const mt = IMPORT_RE.exec(text);
|
|
195
214
|
if (mt && !NON_CODE_IMPORT.has(path.posix.extname(mt[2]).toLowerCase()))
|
|
196
|
-
addEdge(
|
|
215
|
+
addEdge(modOf(resolveRelative(f.rel, mt[2])), i + 1, text);
|
|
197
216
|
});
|
|
198
217
|
}
|
|
199
218
|
else if (f.ext === '.py') {
|
|
@@ -235,6 +254,8 @@ export async function buildMap(root, corpus) {
|
|
|
235
254
|
blind.add('Scan hit the file-count or time budget; results are partial.');
|
|
236
255
|
if (c.skipped.tooLarge)
|
|
237
256
|
blind.add(`${c.skipped.tooLarge} file(s) over the size limit were not read.`);
|
|
257
|
+
if (c.skipped.excluded)
|
|
258
|
+
blind.add(`${c.skipped.excluded} path(s) were excluded by --include, --exclude, .archsutraignore or git ignore rules.`);
|
|
238
259
|
if (c.skipped.symlinks)
|
|
239
260
|
blind.add(`${c.skipped.symlinks} symlink(s) were not followed.`);
|
|
240
261
|
blind.add('Runtime behaviour, deployed topology, and data volumes are not observable from source alone.');
|
|
@@ -252,6 +273,6 @@ export async function buildMap(root, corpus) {
|
|
|
252
273
|
edges: [...edgeMap.values()].sort((a, b) => b.count - a.count),
|
|
253
274
|
cycles,
|
|
254
275
|
blindSpots: [...blind],
|
|
255
|
-
coverage: { filesScanned: c.files.length, skipped: c.skipped, truncated: c.truncated },
|
|
276
|
+
coverage: { filesScanned: c.files.length, skipped: c.skipped, truncated: c.truncated, skippedPaths: c.skippedPaths, folders: c.folders },
|
|
256
277
|
};
|
|
257
278
|
}
|
package/dist/mcp.js
CHANGED
|
@@ -1,81 +1,96 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
2
5
|
import { runAudit } from './audit.js';
|
|
3
6
|
import { diffFindings } from './drift.js';
|
|
7
|
+
import { safeJoin } from './fsutil.js';
|
|
4
8
|
import { buildMap } from './map.js';
|
|
5
9
|
import { findingsJson } from './report.js';
|
|
10
|
+
const PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
11
|
+
const MAX_TEXT = 200_000;
|
|
12
|
+
const str = { type: 'string' };
|
|
13
|
+
const annotations = { readOnlyHint: true, openWorldHint: false };
|
|
6
14
|
const TOOLS = [
|
|
7
|
-
{ name: 'archsutra_audit', description: 'Offline architecture audit. Returns findings JSON. Read-only. No network.', inputSchema: { type: 'object', properties: { path:
|
|
8
|
-
{ name: 'archsutra_map', description: 'Offline module map: ecosystems, edges, cycles, blind spots. Read-only.', inputSchema: { type: 'object', properties: { path:
|
|
9
|
-
{ name: 'archsutra_drift', description: 'Diff two findings.json files
|
|
15
|
+
{ name: 'archsutra_audit', description: 'Offline architecture audit of a directory inside the server root. Returns findings JSON. Read-only. No network.', inputSchema: { type: 'object', properties: { path: str }, required: ['path'] }, annotations },
|
|
16
|
+
{ name: 'archsutra_map', description: 'Offline module map: ecosystems, edges, cycles, blind spots. Directory must be inside the server root. Read-only.', inputSchema: { type: 'object', properties: { path: str }, required: ['path'] }, annotations },
|
|
17
|
+
{ name: 'archsutra_drift', description: 'Diff two findings.json files inside the server root.', inputSchema: { type: 'object', properties: { before: str, after: str }, required: ['before', 'after'] }, annotations },
|
|
10
18
|
];
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
19
|
+
/** Resolve a tool argument inside the root, following symlinks, so an injected prompt cannot read elsewhere. */
|
|
20
|
+
function within(root, p) {
|
|
21
|
+
const real = realpathSync(safeJoin(root, String(p ?? '.')));
|
|
22
|
+
return safeJoin(root, real);
|
|
14
23
|
}
|
|
15
|
-
async function callTool(name, args) {
|
|
16
|
-
if (name === 'archsutra_audit')
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
if (name === 'archsutra_map') {
|
|
21
|
-
return JSON.stringify(await buildMap(String(args.path ?? '.')));
|
|
22
|
-
}
|
|
24
|
+
async function callTool(root, name, args) {
|
|
25
|
+
if (name === 'archsutra_audit')
|
|
26
|
+
return findingsJson(await runAudit(within(root, args.path)));
|
|
27
|
+
if (name === 'archsutra_map')
|
|
28
|
+
return buildMap(within(root, args.path));
|
|
23
29
|
if (name === 'archsutra_drift') {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
30
|
+
const load = async (p) => {
|
|
31
|
+
const raw = JSON.parse(await readFile(within(root, p), 'utf8'));
|
|
32
|
+
const list = Array.isArray(raw) ? raw : raw.findings;
|
|
33
|
+
if (!Array.isArray(list))
|
|
34
|
+
throw new Error('File has no findings array.');
|
|
35
|
+
return list;
|
|
36
|
+
};
|
|
37
|
+
return diffFindings(await load(args.before), await load(args.after));
|
|
29
38
|
}
|
|
30
39
|
throw new Error(`Unknown tool ${name}`);
|
|
31
40
|
}
|
|
32
|
-
/**
|
|
33
|
-
export async function serveMcp() {
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const headerEnd = text.indexOf('\r\n\r\n', offset);
|
|
42
|
-
if (headerEnd < 0)
|
|
43
|
-
break;
|
|
44
|
-
const header = text.slice(offset, headerEnd);
|
|
45
|
-
const m = /Content-Length:\s*(\d+)/i.exec(header);
|
|
46
|
-
if (!m)
|
|
47
|
-
break;
|
|
48
|
-
const len = Number(m[1]);
|
|
49
|
-
const start = headerEnd + 4;
|
|
50
|
-
const body = text.slice(start, start + len);
|
|
51
|
-
offset = start + len;
|
|
41
|
+
/** MCP stdio transport: one JSON-RPC message per line, answered as it arrives, until stdin closes. */
|
|
42
|
+
export async function serveMcp(rootDir) {
|
|
43
|
+
const root = realpathSync(path.resolve(rootDir));
|
|
44
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
45
|
+
const send = (body) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...body })}\n`);
|
|
46
|
+
const fail = (id, code, message) => send({ id, error: { code, message } });
|
|
47
|
+
for await (const line of createInterface({ input: process.stdin, crlfDelay: Infinity })) {
|
|
48
|
+
if (!line.trim())
|
|
49
|
+
continue;
|
|
52
50
|
let msg;
|
|
53
51
|
try {
|
|
54
|
-
msg = JSON.parse(
|
|
52
|
+
msg = JSON.parse(line);
|
|
55
53
|
}
|
|
56
54
|
catch {
|
|
55
|
+
fail(null, -32700, 'Parse error');
|
|
57
56
|
continue;
|
|
58
57
|
}
|
|
59
|
-
if (msg
|
|
60
|
-
continue;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
58
|
+
if (msg?.id === undefined || msg.id === null)
|
|
59
|
+
continue; // notification
|
|
60
|
+
const { id, method, params } = msg;
|
|
61
|
+
if (method === 'initialize') {
|
|
62
|
+
const asked = String(params?.protocolVersion ?? '');
|
|
63
|
+
send({ id, result: { protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0], capabilities: { tools: {} }, serverInfo: { name: 'archsutra', version } } });
|
|
64
64
|
}
|
|
65
|
-
else if (
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
65
|
+
else if (method === 'ping')
|
|
66
|
+
send({ id, result: {} });
|
|
67
|
+
else if (method === 'tools/list')
|
|
68
|
+
send({ id, result: { tools: TOOLS } });
|
|
69
|
+
else if (method === 'resources/list')
|
|
70
|
+
send({ id, result: { resources: [] } });
|
|
71
|
+
else if (method === 'prompts/list')
|
|
72
|
+
send({ id, result: { prompts: [] } });
|
|
73
|
+
else if (method === 'tools/call') {
|
|
74
|
+
const name = String(params?.name);
|
|
75
|
+
if (!TOOLS.some((t) => t.name === name)) {
|
|
76
|
+
fail(id, -32602, `Unknown tool ${name}`);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
69
79
|
try {
|
|
70
|
-
const
|
|
71
|
-
|
|
80
|
+
const data = await callTool(root, name, params?.arguments ?? {});
|
|
81
|
+
const full = JSON.stringify(data);
|
|
82
|
+
send({
|
|
83
|
+
id,
|
|
84
|
+
result: full.length <= MAX_TEXT
|
|
85
|
+
? { content: [{ type: 'text', text: full }], structuredContent: data }
|
|
86
|
+
: { content: [{ type: 'text', text: `${full.slice(0, MAX_TEXT)}\n[TRUNCATED: ${full.length} characters. Audit a sub-directory for the full result.]` }] },
|
|
87
|
+
});
|
|
72
88
|
}
|
|
73
89
|
catch (e) {
|
|
74
|
-
|
|
90
|
+
send({ id, result: { content: [{ type: 'text', text: e instanceof Error ? e.message : String(e) }], isError: true } });
|
|
75
91
|
}
|
|
76
92
|
}
|
|
77
|
-
else
|
|
78
|
-
|
|
79
|
-
}
|
|
93
|
+
else
|
|
94
|
+
fail(id, -32601, `Method not found: ${method}`);
|
|
80
95
|
}
|
|
81
96
|
}
|
package/dist/redact.js
CHANGED
|
@@ -1,29 +1,39 @@
|
|
|
1
1
|
const PATTERNS = [
|
|
2
|
-
|
|
3
|
-
{ name: '
|
|
4
|
-
{ name: '
|
|
5
|
-
{ name: 'openai-style-key', re: /\bsk-[A-Za-z0-9_-]{20,}\b/g },
|
|
6
|
-
{ name: 'slack-token', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g },
|
|
7
|
-
{ name: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
|
|
8
|
-
{ name: 'private-key', re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/g },
|
|
2
|
+
...PROVIDER_PATTERNS,
|
|
3
|
+
{ name: 'private-key', re: /-----BEGIN (?:(?:RSA|EC|DSA|OPENSSH|PGP|ENCRYPTED) )?PRIVATE KEY(?: BLOCK)?-----/g },
|
|
4
|
+
{ name: 'connection-string', re: /\b((?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^\s:@/"'`]*:)([^\s@/"'`]+)(@)/gi },
|
|
9
5
|
{
|
|
10
6
|
name: 'credential-assignment',
|
|
11
7
|
re: /\b(password|passwd|secret|api[_-]?key|token|access[_-]?key)\b(\s*[:=]\s*)(["'])([^"'\s]{8,})\3/gi,
|
|
12
8
|
},
|
|
13
9
|
];
|
|
14
10
|
import { plausibleSecretValue } from './heuristics.js';
|
|
11
|
+
import { PROVIDER_PATTERNS } from './secret-patterns.js';
|
|
12
|
+
const PLACEHOLDER = /example|placeholder|changeme|your[_-]|x{6,}|(.)\1{9,}/i;
|
|
13
|
+
/** One pass over all prefix patterns: most lines match none, and running 60 patterns on each is slow. */
|
|
14
|
+
const ASSIGNMENT = PATTERNS.filter((p) => p.name === 'credential-assignment');
|
|
15
|
+
const ANY_OTHER = new RegExp(PATTERNS.filter((p) => !ASSIGNMENT.includes(p)).map((p) => `(?:${p.re.source})`).join('|'), 'i');
|
|
15
16
|
/** Return the kinds of secret found in a line (never the value). */
|
|
16
17
|
export function detectSecrets(line) {
|
|
17
18
|
const hits = [];
|
|
18
|
-
for (const p of PATTERNS) {
|
|
19
|
+
for (const p of ANY_OTHER.test(line) ? PATTERNS : ASSIGNMENT) {
|
|
19
20
|
p.re.lastIndex = 0;
|
|
20
21
|
if (p.name === 'credential-assignment') {
|
|
21
22
|
for (const m of line.matchAll(p.re))
|
|
22
|
-
if (plausibleSecretValue(m[4]))
|
|
23
|
+
if (plausibleSecretValue(m[4]) && !PLACEHOLDER.test(m[4]))
|
|
24
|
+
hits.push({ kind: p.name });
|
|
25
|
+
}
|
|
26
|
+
else if (p.name === 'connection-string') {
|
|
27
|
+
for (const m of line.matchAll(p.re))
|
|
28
|
+
if (plausibleSecretValue(m[2]) && !PLACEHOLDER.test(m[2]))
|
|
29
|
+
hits.push({ kind: p.name });
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
// Judge the matched value, never the whole line: the word "example" nearby must not hide a key.
|
|
33
|
+
for (const m of line.matchAll(p.re))
|
|
34
|
+
if (p.name === 'private-key' || !PLACEHOLDER.test(m[0]))
|
|
23
35
|
hits.push({ kind: p.name });
|
|
24
36
|
}
|
|
25
|
-
else if (p.re.test(line))
|
|
26
|
-
hits.push({ kind: p.name });
|
|
27
37
|
}
|
|
28
38
|
return hits;
|
|
29
39
|
}
|
|
@@ -35,6 +45,9 @@ export function redact(text) {
|
|
|
35
45
|
if (p.name === 'credential-assignment') {
|
|
36
46
|
out = out.replace(p.re, (_m, k, sep, q, _v) => `${k}${sep}${q}[REDACTED]${q}`);
|
|
37
47
|
}
|
|
48
|
+
else if (p.name === 'connection-string') {
|
|
49
|
+
out = out.replace(p.re, '$1[REDACTED]$3');
|
|
50
|
+
}
|
|
38
51
|
else {
|
|
39
52
|
out = out.replace(p.re, `[REDACTED:${p.name}]`);
|
|
40
53
|
}
|