ai-secure-audit 0.0.0-stage → 0.0.2

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 ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # ai-secure-audit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Status: 0.0.x on npm runs the basic secret check with `npx ai-secure-audit`. v0.1 is not released yet.
4
+ >
5
+ > **มือใหม่เริ่มตรงนี้:** [learn/](learn/) ควรตรวจอะไรก่อน เพราะอะไร และแก้ยังไง (ภาษาไทย)
6
+ >
7
+ > **New here?** Start with [learn/](learn/README.en.md): what to check first, why, and how to fix it.
8
+
9
+ A free, open-source security check for apps built with AI. If you make apps with Claude Code, Codex, Cursor or
10
+ Antigravity but security is not your field, ask your AI assistant to run it on your project:
11
+
12
+ > Run `npx ai-secure-audit` in this project, explain the results in simple words, and help me fix the most serious
13
+ > ones first.
14
+
15
+ Developers can also use it for web apps, APIs, Flutter apps and small self-hosted servers, and check them against
16
+ recognised standards before users or clients find the problems.
17
+
18
+ ## How it works
19
+
20
+ The findings come from established open-source scanners, not from an AI's opinion, so the same code gives the same
21
+ result every run.
22
+
23
+ ```
24
+ npx ai-secure-audit runs pinned versions of the scanners with pinned rules (no AI needed)
25
+ |
26
+ v
27
+ .audit/out/findings.json merged, stably sorted results from the tools
28
+ |
29
+ v
30
+ your AI assistant explains each finding and how to fix it, and lists what the tools cannot check;
31
+ ```
32
+
33
+ - The AI never adds or removes findings; its explanations are kept in a separate section of the report.
34
+ - Tools and rule sets are pinned, so a rerun on the same commit produces an identical `findings.json`.
35
+ - Scanners that send traffic (DAST, port and TLS scans) only run against hosts listed in the audited project's
36
+ `.audit/targets.yml` (see [`config/targets.example.yml`](config/targets.example.yml)).
37
+
38
+ ## Try it now (from a clone)
39
+
40
+ Needs Node.js 18 or later and git. Nothing else.
41
+
42
+ ```bash
43
+ git clone https://github.com/surapas3022/ai-secure-audit.git
44
+ node ai-secure-audit/bin/ai-secure-audit.js /path/to/your/project
45
+ ```
46
+
47
+ To see what it finds without scanning a real project, build the fake demo app first (every key in it is random
48
+ and fake):
49
+
50
+ ```bash
51
+ node ai-secure-audit/examples/vulnerable-app/setup.mjs /tmp/demo-app
52
+ node ai-secure-audit/bin/ai-secure-audit.js /tmp/demo-app
53
+ ```
54
+
55
+ Or ask your AI assistant: *"Run `node <path-to>/ai-secure-audit/bin/ai-secure-audit.js` on this project, explain the
56
+ results in simple words, and help me fix the most serious ones first."*
57
+
58
+ Results go to `.audit/out/` in your project (`report.md` for people, `findings.json` for tools and AI). That folder
59
+ ignores itself in git, so results are not committed by accident.
60
+
61
+ ## Repository layout
62
+
63
+ ```
64
+ bin/, src/ the CLI: see docs/cli.md
65
+ tools.lock.json pinned tool versions and SHA-256 checksums for every platform
66
+ test/ unit tests (npm test)
67
+ profiles/ pinned tool and rule sets per stack (planned)
68
+ rules/ this kit's own opengrep rules (planned)
69
+ config/ example files to copy into the audited project
70
+ docs/ design notes
71
+ learn/ beginner lessons in Thai and English, one topic per file pair
72
+ ```
73
+
74
+ ## Planned coverage
75
+
76
+ ### Basic check: works right after `git clone`
77
+
78
+ Checks are released one at a time, each after passing its own tests. The version in brackets is when each one is
79
+ switched on.
80
+
81
+ For anyone who builds apps with AI and wants to check their own project. You do not need Docker, Homebrew, Python
82
+ or Java. The tools are single files for Windows, macOS and Linux, downloaded at pinned versions and checked against
83
+ SHA-256 checksums. The check reads only your project folder and never uploads your code.
84
+
85
+ | Checks | Tool | License |
86
+ |---|---|---|
87
+ | Passwords, API keys and tokens in the code, in files not committed yet, in git history and in build output (v0.1) | gitleaks | MIT |
88
+ | Libraries with known vulnerabilities (v0.2) | osv-scanner (offline database) | Apache-2.0 |
89
+ | Dockerfile and config mistakes (v0.3) | trivy config | Apache-2.0 |
90
+ | Code mistakes AI-generated apps often make (see below), planned | opengrep + this kit's own rules | LGPL-2.1 (rules: Apache-2.0) |
91
+
92
+ Common mistakes the kit's own rules look for: secret keys in frontend code or `NEXT_PUBLIC_*` variables, Supabase
93
+ `service_role` key outside the server, tables without row-level security, Firebase rules that allow everything,
94
+ API routes without an auth check, permission checks done only in the browser, committed `.env` files, CORS `*`,
95
+ and stack traces returned to users.
96
+
97
+ ### Advanced check: for developers, needs Docker
98
+
99
+ | Layer | Tools | License | Standard |
100
+ |---|---|---|---|
101
+ | Dockerfile, Compose, CI config | hadolint, checkov, this kit's Compose rules | GPL-3.0, Apache-2.0 | CIS Docker Benchmark |
102
+ | Container images, SBOM | trivy image, syft | Apache-2.0 | — |
103
+ | Linux host | lynis | GPL-3.0 | CIS |
104
+ | TLS | testssl.sh | GPL-2.0 | Mozilla TLS guidelines |
105
+ | Running web app / API | OWASP ZAP, nuclei | Apache-2.0, MIT | OWASP ASVS, OWASP API Security Top 10 |
106
+ | Flutter mobile app | MobSF, opengrep | GPL-3.0, LGPL-2.1 | OWASP MASVS |
107
+
108
+ Every tool sends traffic only to hosts listed in `.audit/targets.yml`, and production hosts get passive checks only.
109
+
110
+ ### Not used, and why
111
+
112
+ | Tool | Reason |
113
+ |---|---|
114
+ | Semgrep Registry rules | Under the Semgrep Rules License, which is not open source. The kit writes its own rules for opengrep. |
115
+ | nmap | Under the Nmap Public Source License, which is not OSI-approved and limits bundling. naabu (MIT) covers port checks. |
116
+ | CodeQL | The CLI is not open source and is free only for open-source code. |
117
+
118
+ ## What it does not do
119
+
120
+ - It does not certify anything. A report states which standard and level were self-assessed, on which date and commit.
121
+ - Automated tools cannot fully check business logic or whether one user can reach another user's data;
122
+ the report lists these for manual review.
123
+
124
+ ## Privacy
125
+
126
+ The scan runs locally. The basic check downloads the pinned tools (first run only) and the public vulnerability
127
+ databases, then compares against them on your machine. It never uploads your code or your list of dependencies. The optional AI skill sends parts of the scanned code
128
+ and findings to the AI provider you use. Get permission before running it on code you do not own.
129
+
130
+ ## Use only on systems you are allowed to test
131
+
132
+ Scan your own code and systems, or systems you have written permission to test.
133
+
134
+ ## License
135
+
136
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "ai-secure-audit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Free, open-source security check for apps built with AI. Runs pinned open-source scanners; no AI needed to run.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/surapas3022/ai-secure-audit.git"
9
+ },
10
+ "homepage": "https://github.com/surapas3022/ai-secure-audit",
11
+ "bugs": {
12
+ "url": "https://github.com/surapas3022/ai-secure-audit/issues"
13
+ },
14
+ "type": "module",
15
+ "bin": {
16
+ "ai-secure-audit": "bin/ai-secure-audit.js"
17
+ },
18
+ "files": [
19
+ "bin/",
20
+ "src/",
21
+ "rules/",
22
+ "tools.lock.json"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "scripts": {
28
+ "test": "node --test",
29
+ "update-lock": "node scripts/update-lock.mjs"
30
+ }
31
+ }
package/rules/.gitkeep ADDED
File without changes
package/src/cli.js ADDED
@@ -0,0 +1,126 @@
1
+ import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { scan, outDir } from './scan.js';
4
+ import { reportMarkdown, consoleSummary } from './report.js';
5
+ import { atOrAbove, SEVERITY_ORDER } from './findings.js';
6
+ import { cacheDir, lockedTools, platformKey } from './tools.js';
7
+
8
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
9
+
10
+ const HELP = `ai-secure-audit ${pkg.version}: free security check for apps built with AI
11
+
12
+ Usage: npx ai-secure-audit [command] [path] [options]
13
+
14
+ Commands
15
+ scan [path] basic check of a project folder (default command, default path ".")
16
+ retest [path] run the check again and compare with the last result
17
+ tools list pinned tool versions, licenses and the cache folder
18
+ init install the AI skills into this project (not available yet)
19
+ mcp run as an MCP server (not available yet)
20
+
21
+ Options
22
+ --json print findings.json to stdout instead of the summary
23
+ --fail-on <level> exit 1 if a finding is at or above: ${SEVERITY_ORDER.slice(0, 4).join(', ')}
24
+ --advanced add the Docker-based advanced tools (not available yet)
25
+ -h, --help show this help
26
+ -v, --version show the version
27
+
28
+ Results are written to <path>/.audit/out/ (git-ignored automatically).`;
29
+
30
+ function parseArgs(argv) {
31
+ const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false };
32
+ const rest = [];
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const a = argv[i];
35
+ if (a === '--json') opts.json = true;
36
+ else if (a === '--advanced') opts.advanced = true;
37
+ else if (a === '--fail-on') opts.failOn = argv[++i];
38
+ else if (a.startsWith('--fail-on=')) opts.failOn = a.slice(10);
39
+ else if (a === '-h' || a === '--help') opts.command = 'help';
40
+ else if (a === '-v' || a === '--version') opts.command = 'version';
41
+ else if (a.startsWith('-')) throw new Error(`unknown option: ${a}`);
42
+ else rest.push(a);
43
+ }
44
+ if (opts.command === 'scan' && ['scan', 'retest', 'tools', 'init', 'mcp', 'help'].includes(rest[0])) opts.command = rest.shift();
45
+ if (rest[0]) opts.path = rest[0];
46
+ if (opts.failOn && !SEVERITY_ORDER.slice(0, 4).includes(opts.failOn)) throw new Error(`--fail-on must be one of ${SEVERITY_ORDER.slice(0, 4).join(', ')}`);
47
+ return opts;
48
+ }
49
+
50
+ function compare(prev, curr) {
51
+ const before = new Map(prev.findings.map((f) => [f.fingerprint, f]));
52
+ const after = new Map(curr.findings.map((f) => [f.fingerprint, f]));
53
+ return {
54
+ fixed: [...before.values()].filter((f) => !after.has(f.fingerprint)),
55
+ still: [...after.values()].filter((f) => before.has(f.fingerprint)),
56
+ added: [...after.values()].filter((f) => !before.has(f.fingerprint)),
57
+ };
58
+ }
59
+
60
+ async function runScan(opts, { retest }) {
61
+ const log = opts.json ? () => {} : (m) => process.stderr.write(`${m}\n`);
62
+ let prev = null;
63
+ const prevFile = join(outDir(opts.path), 'findings.json');
64
+ if (retest) {
65
+ if (!existsSync(prevFile)) throw new Error('no previous result to compare with: run `npx ai-secure-audit` first');
66
+ prev = JSON.parse(readFileSync(prevFile, 'utf8'));
67
+ copyFileSync(prevFile, join(outDir(opts.path), 'findings.prev.json'));
68
+ }
69
+
70
+ const { root, out, result } = await scan(opts.path, { log, version: pkg.version });
71
+ writeFileSync(join(out, 'report.md'), reportMarkdown(result, new Date().toISOString().slice(0, 10)));
72
+ const r = relative(process.cwd(), out);
73
+ const outRel = (r && !r.startsWith('..') ? r : out).split('\\').join('/');
74
+
75
+ if (opts.json) process.stdout.write(JSON.stringify(result, null, 2) + '\n');
76
+ else {
77
+ process.stdout.write(consoleSummary(result, outRel) + '\n');
78
+ if (prev) {
79
+ const d = compare(prev, result);
80
+ writeFileSync(join(out, 'retest.json'), JSON.stringify({
81
+ fixed: d.fixed.map((f) => f.fingerprint), still_open: d.still.map((f) => f.fingerprint), new: d.added.map((f) => f.fingerprint),
82
+ }, null, 2) + '\n');
83
+ process.stdout.write(`\nRetest: ${d.fixed.length} fixed · ${d.still.length} still open · ${d.added.length} new\n`);
84
+ for (const f of d.fixed) process.stdout.write(` fixed: ${f.title} (${f.evidence[0].location})\n`);
85
+ for (const f of d.added) process.stdout.write(` new: ${f.title} (${f.evidence[0].location})\n`);
86
+ }
87
+ }
88
+
89
+ if (result.tools.some((t) => t.status !== 'ok')) return 2;
90
+ if (opts.failOn && atOrAbove(result.findings, opts.failOn).length) return 1;
91
+ return 0;
92
+ }
93
+
94
+ export async function main(argv) {
95
+ let opts;
96
+ try {
97
+ opts = parseArgs(argv);
98
+ } catch (err) {
99
+ process.stderr.write(`${err.message}\n\n${HELP}\n`);
100
+ return 2;
101
+ }
102
+ try {
103
+ switch (opts.command) {
104
+ case 'help': process.stdout.write(HELP + '\n'); return 0;
105
+ case 'version': process.stdout.write(pkg.version + '\n'); return 0;
106
+ case 'tools': {
107
+ for (const [id, t] of Object.entries(lockedTools())) process.stdout.write(`${id.padEnd(12)} ${t.version.padEnd(8)} ${t.license.padEnd(11)} ${t.repo}\n`);
108
+ process.stdout.write(`\nplatform: ${platformKey()}\ncache: ${cacheDir()}\n`);
109
+ return 0;
110
+ }
111
+ case 'init':
112
+ case 'mcp':
113
+ process.stderr.write(`\`${opts.command}\` is not available yet. See docs/cli.md.\n`);
114
+ return 2;
115
+ default:
116
+ if (opts.advanced) {
117
+ process.stderr.write('`--advanced` is not available yet. Running the basic check only is the default.\n');
118
+ return 2;
119
+ }
120
+ return await runScan(opts, { retest: opts.command === 'retest' });
121
+ }
122
+ } catch (err) {
123
+ process.stderr.write(`error: ${err.message}\n`);
124
+ return 2;
125
+ }
126
+ }
package/src/extract.js ADDED
@@ -0,0 +1,53 @@
1
+ import { gunzipSync, inflateRawSync } from 'node:zlib';
2
+ import { basename } from 'node:path';
3
+
4
+ // Minimal readers for the two archive formats the pinned tools ship in.
5
+ // Each returns the bytes of the first entry whose file name equals `name`.
6
+
7
+ export function fromTarGz(buf, name) {
8
+ const tar = gunzipSync(buf);
9
+ let longName = null;
10
+ for (let off = 0; off + 512 <= tar.length; ) {
11
+ const header = tar.subarray(off, off + 512);
12
+ if (header.every((b) => b === 0)) break;
13
+ const field = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/s, '');
14
+ const size = parseInt(field(124, 12).trim() || '0', 8);
15
+ const type = field(156, 1);
16
+ const data = tar.subarray(off + 512, off + 512 + size);
17
+ let path = longName ?? (field(345, 155) ? `${field(345, 155)}/${field(0, 100)}` : field(0, 100));
18
+ longName = null;
19
+ if (type === 'L') longName = data.toString('utf8').replace(/\0.*$/s, '');
20
+ else if ((type === '0' || type === '') && basename(path) === name) return Buffer.from(data);
21
+ off += 512 + Math.ceil(size / 512) * 512;
22
+ }
23
+ throw new Error(`${name} not found in archive`);
24
+ }
25
+
26
+ export function fromZip(buf, name) {
27
+ let eocd = -1;
28
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65_557); i--) {
29
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
30
+ }
31
+ if (eocd < 0) throw new Error('not a zip file');
32
+ const count = buf.readUInt16LE(eocd + 10);
33
+ let off = buf.readUInt32LE(eocd + 16);
34
+ for (let n = 0; n < count; n++) {
35
+ if (buf.readUInt32LE(off) !== 0x02014b50) throw new Error('bad zip central directory');
36
+ const method = buf.readUInt16LE(off + 10);
37
+ const compSize = buf.readUInt32LE(off + 20);
38
+ const nameLen = buf.readUInt16LE(off + 28);
39
+ const extraLen = buf.readUInt16LE(off + 30);
40
+ const commentLen = buf.readUInt16LE(off + 32);
41
+ const local = buf.readUInt32LE(off + 42);
42
+ const path = buf.subarray(off + 46, off + 46 + nameLen).toString('utf8');
43
+ if (basename(path) === name) {
44
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
45
+ const data = buf.subarray(start, start + compSize);
46
+ if (method === 0) return Buffer.from(data);
47
+ if (method === 8) return inflateRawSync(data);
48
+ throw new Error(`unsupported zip compression method ${method}`);
49
+ }
50
+ off += 46 + nameLen + extraLen + commentLen;
51
+ }
52
+ throw new Error(`${name} not found in archive`);
53
+ }
@@ -0,0 +1,28 @@
1
+ export const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info'];
2
+ const CATEGORY_ORDER = ['secret', 'dependency', 'config', 'code'];
3
+
4
+ // Stable order: same inputs give byte-identical findings.json.
5
+ export function sortAndNumber(findings) {
6
+ const rank = (list, v) => { const i = list.indexOf(v); return i < 0 ? list.length : i; };
7
+ const sorted = [...findings].sort((a, b) =>
8
+ rank(SEVERITY_ORDER, a.severity.normalized) - rank(SEVERITY_ORDER, b.severity.normalized) ||
9
+ rank(CATEGORY_ORDER, a.category) - rank(CATEGORY_ORDER, b.category) ||
10
+ (a.fingerprint < b.fingerprint ? -1 : a.fingerprint > b.fingerprint ? 1 : 0));
11
+ return sorted.map((f, i) => ({
12
+ id: `AUD-${String(i + 1).padStart(3, '0')}`,
13
+ status: 'Open',
14
+ verification: 'unverified',
15
+ ...f,
16
+ }));
17
+ }
18
+
19
+ export function countBySeverity(findings) {
20
+ const counts = Object.fromEntries(SEVERITY_ORDER.map((s) => [s, 0]));
21
+ for (const f of findings) counts[f.severity.normalized] = (counts[f.severity.normalized] ?? 0) + 1;
22
+ return counts;
23
+ }
24
+
25
+ export function atOrAbove(findings, level) {
26
+ const limit = SEVERITY_ORDER.indexOf(level);
27
+ return findings.filter((f) => SEVERITY_ORDER.indexOf(f.severity.normalized) <= limit);
28
+ }
package/src/http.js ADDED
@@ -0,0 +1,25 @@
1
+ import https from 'node:https';
2
+
3
+ // GET a URL into a Buffer, following redirects (GitHub release downloads redirect to a CDN).
4
+ export function get(url, redirects = 5) {
5
+ return new Promise((resolve, reject) => {
6
+ const req = https.get(url, { headers: { 'user-agent': 'ai-secure-audit' } }, (res) => {
7
+ const { statusCode, headers } = res;
8
+ if (statusCode >= 300 && statusCode < 400 && headers.location) {
9
+ res.resume();
10
+ if (redirects === 0) return reject(new Error(`too many redirects: ${url}`));
11
+ return resolve(get(new URL(headers.location, url).toString(), redirects - 1));
12
+ }
13
+ if (statusCode !== 200) {
14
+ res.resume();
15
+ return reject(new Error(`HTTP ${statusCode} for ${url}`));
16
+ }
17
+ const chunks = [];
18
+ res.on('data', (c) => chunks.push(c));
19
+ res.on('end', () => resolve(Buffer.concat(chunks)));
20
+ res.on('error', reject);
21
+ });
22
+ req.on('error', reject);
23
+ req.setTimeout(120_000, () => req.destroy(new Error(`timeout: ${url}`)));
24
+ });
25
+ }
package/src/paths.js ADDED
@@ -0,0 +1,8 @@
1
+ import { isAbsolute, relative, sep } from 'node:path';
2
+
3
+ // Paths in findings are relative to the scanned folder and use "/", so output is the same on every OS.
4
+ export function rel(root, p) {
5
+ if (!p) return '';
6
+ const r = isAbsolute(p) ? relative(root, p) : p;
7
+ return r.split(sep).join('/');
8
+ }
package/src/report.js ADDED
@@ -0,0 +1,126 @@
1
+ import { countBySeverity } from './findings.js';
2
+
3
+ // Plain-language explanations, by finding category.
4
+ const PLAIN = {
5
+ secret: {
6
+ what: 'A password, API key or token is written in your code.',
7
+ why: 'Anyone who can see the code (or its git history) can use it: spend your money, read your data, or act as you.',
8
+ },
9
+ dependency: {
10
+ what: 'A library your app uses has a known security hole.',
11
+ why: 'Attackers look for apps running versions with published holes, because the method is already public.',
12
+ },
13
+ config: {
14
+ what: 'A setting in your Docker or infrastructure files is unsafe.',
15
+ why: 'Unsafe defaults make a break-in easier or do more damage once someone is in.',
16
+ },
17
+ };
18
+
19
+ function where(f) {
20
+ return f.evidence.map((e) => `\`${e.location}\``).join(', ');
21
+ }
22
+
23
+ function whereSentence(f) {
24
+ return f.evidence.map((e) => {
25
+ const commits = e.commits?.length ? ` (commit ${e.commits.join(', ')})` : '';
26
+ if (e.history_only) {
27
+ return `\`${e.location}\`. This file is no longer in your project, but it is still in git history${commits}, ` +
28
+ 'so anyone with a copy of the repository can still read it';
29
+ }
30
+ if (e.not_committed) return `\`${e.location}\`. This is not in git yet, so you can still keep it out of your history`;
31
+ if (e.built) return `\`${e.location}\`${commits}. This file is build output, the code that gets deployed`;
32
+ return `\`${e.location}\`${commits}`;
33
+ }).join('; ');
34
+ }
35
+
36
+ function whereNote(f) {
37
+ if (f.evidence.some((e) => e.history_only)) return ' (git history only)';
38
+ if (f.evidence.some((e) => e.not_committed)) return ' (not committed yet)';
39
+ return f.evidence.some((e) => e.built) ? ' (build output)' : '';
40
+ }
41
+
42
+ export function reportMarkdown(result, date) {
43
+ const { findings, tools, target } = result;
44
+ const c = countBySeverity(findings);
45
+ const lines = [];
46
+ lines.push('# Security check');
47
+ lines.push('');
48
+ lines.push(`${result.generator} · basic check · ${date}` + (target.commit ? ` · commit \`${target.commit}\`` : ' · not a git repository') +
49
+ (target.uncommitted_changes ? ' (with uncommitted changes)' : ''));
50
+ lines.push('');
51
+ lines.push('This is a self-check with free open-source tools. It is not a certification and does not prove the app is secure.');
52
+ lines.push('');
53
+ lines.push(`**${c.critical} critical · ${c.high} high · ${c.medium} medium · ${c.low} low**`);
54
+ lines.push('');
55
+
56
+ const failed = tools.filter((t) => t.status !== 'ok');
57
+ if (failed.length) {
58
+ lines.push('> **Some checks did not run:** ' + failed.map((t) => `${t.id} (${t.error})`).join('; '));
59
+ lines.push('');
60
+ }
61
+
62
+ const top = findings.filter((f) => ['critical', 'high'].includes(f.severity.normalized)).slice(0, 5);
63
+ if (top.length) {
64
+ lines.push('## Fix these first');
65
+ lines.push('');
66
+ for (const f of top) {
67
+ const p = PLAIN[f.category] ?? {};
68
+ lines.push(`### ${f.id}: ${f.title}`);
69
+ lines.push('');
70
+ if (p.what) lines.push(`**What is wrong:** ${p.what} Found at ${whereSentence(f)}.`);
71
+ if (p.why) lines.push(`**Why it matters:** ${p.why}`);
72
+ if (f.fix) lines.push(`**How to fix it:** ${f.fix}`);
73
+ lines.push('');
74
+ }
75
+ } else if (findings.length === 0 && !failed.length) {
76
+ lines.push('No problems found by these tools. That does not cover the items under "What this check could not see".');
77
+ lines.push('');
78
+ }
79
+
80
+ if (findings.length) {
81
+ lines.push('## All findings');
82
+ lines.push('');
83
+ lines.push('| ID | Severity | Type | Problem | Where |');
84
+ lines.push('|---|---|---|---|---|');
85
+ for (const f of findings) {
86
+ lines.push(`| ${f.id} | ${f.severity.normalized} | ${f.category} | ${f.title.replace(/\|/g, '\\|')} | ${where(f)}${whereNote(f)} |`);
87
+ }
88
+ lines.push('');
89
+ }
90
+
91
+ lines.push('## What this check could not see');
92
+ lines.push('');
93
+ lines.push('- Whether one user can open or change another user\'s data (for example by changing an id in the URL)');
94
+ lines.push('- Business rules: prices, coupons, approvals, payments');
95
+ lines.push('- Database rules such as Supabase row-level security or Firebase security rules (planned)');
96
+ lines.push('- Anything about the live server or website');
97
+ lines.push('- Libraries with known vulnerabilities, and Docker/config mistakes: not in this version yet (coming in v0.2 and v0.3)');
98
+ lines.push('');
99
+ lines.push('## Tools');
100
+ lines.push('');
101
+ lines.push('| Tool | Version | License | Result |');
102
+ lines.push('|---|---|---|---|');
103
+ for (const t of tools) lines.push(`| ${t.id} | ${t.version} | ${t.license} | ${t.status === 'ok' ? `${t.findings} findings` : `failed: ${t.error}`} |`);
104
+ lines.push('');
105
+ return lines.join('\n');
106
+ }
107
+
108
+ export function consoleSummary(result, outRel) {
109
+ const c = countBySeverity(result.findings);
110
+ const failed = result.tools.filter((t) => t.status !== 'ok');
111
+ return [
112
+ `${result.generator} · basic check` + (result.target.commit ? ` · commit ${result.target.commit}` : ''),
113
+ `${c.critical} critical · ${c.high} high · ${c.medium} medium · ${c.low} low report: ${outRel}/report.md`,
114
+ ...failed.map((t) => `NOT RUN: ${t.id}: ${t.error}`),
115
+ '',
116
+ 'For the AI assistant reading this:',
117
+ `- Findings are in ${outRel}/findings.json. Do not add, remove or re-rate findings.`,
118
+ '- Explain them to the user in plain language, most serious first.',
119
+ '- Ask before changing code. Fix one finding at a time; run `npx ai-secure-audit retest` after.',
120
+ '- Use each finding\'s fix field. A key that is in git or was deployed must be rotated at the provider: deleting it from the code is not enough.',
121
+ '- A finding marked not_committed can be moved out of the code without rotating, unless the key was shared or pasted somewhere else.',
122
+ '- Not checked: whether one user can reach another user\'s data, business rules, and (in this version)',
123
+ ' vulnerable libraries and Docker/config files. Say so.',
124
+ ...(failed.length ? ['- Some tools did not run (see NOT RUN above). Tell the user the check is incomplete.'] : []),
125
+ ].join('\n');
126
+ }
package/src/scan.js ADDED
@@ -0,0 +1,92 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { cacheDir, ensureTool, lockedTools } from './tools.js';
5
+ import { sortAndNumber } from './findings.js';
6
+ import gitleaks from './scanners/gitleaks.js';
7
+
8
+ // Scanners are released one at a time, each after passing its own tests (see CLAUDE.md).
9
+ // Scanners still in development are kept outside this repository until they pass.
10
+ export const BASIC_SCANNERS = [gitleaks];
11
+
12
+ function git(root, args) {
13
+ const r = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
14
+ return r.status === 0 ? r.stdout.trim() : null;
15
+ }
16
+
17
+ export function outDir(root) {
18
+ return join(root, '.audit', 'out');
19
+ }
20
+
21
+ export async function scan(target, { log = () => {}, version }) {
22
+ const root = resolve(target);
23
+ if (!existsSync(root)) throw new Error(`folder not found: ${root}`);
24
+
25
+ const out = outDir(root);
26
+ const rawDir = join(out, 'raw');
27
+ mkdirSync(rawDir, { recursive: true });
28
+ // Results can describe real weaknesses: keep them out of git.
29
+ writeFileSync(join(out, '.gitignore'), '*\n');
30
+
31
+ const isGit = git(root, ['rev-parse', '--is-inside-work-tree']) === 'true';
32
+ const ctx = {
33
+ root,
34
+ rawDir,
35
+ cache: cacheDir(),
36
+ isGit,
37
+ commit: isGit ? git(root, ['rev-parse', '--short', 'HEAD']) : null,
38
+ dirty: isGit ? git(root, ['status', '--porcelain']) !== '' : null,
39
+ prefix: isGit ? git(root, ['rev-parse', '--show-prefix']) ?? '' : '',
40
+ isIgnored: (file) => isGit && spawnSync('git', ['-C', root, 'check-ignore', '-q', '--', file]).status === 0,
41
+ };
42
+
43
+ const tools = lockedTools();
44
+ const runs = [];
45
+ let findings = [];
46
+ for (const s of BASIC_SCANNERS) {
47
+ const run = { id: s.id, version: tools[s.id].version, license: tools[s.id].license, status: 'ok' };
48
+ runs.push(run);
49
+ try {
50
+ const bin = await ensureTool(s.id, log);
51
+ const prep = s.prepare?.(ctx) ?? {};
52
+ const defaultRaw = join(rawDir, `${s.id}.json`);
53
+ const passes = s.passes ? s.passes(ctx, rawDir, prep) : [{ rawFile: defaultRaw, args: s.args(ctx, defaultRaw, prep) }];
54
+ log(`running ${s.id} ${run.version} ...`);
55
+ let json = null;
56
+ for (const pass of passes) {
57
+ const r = spawnSync(bin, pass.args, {
58
+ cwd: root,
59
+ env: { ...process.env, ...(s.env?.(ctx) ?? {}) },
60
+ encoding: 'utf8',
61
+ maxBuffer: 64 * 1024 * 1024,
62
+ });
63
+ if (r.error) throw r.error;
64
+ if (!s.okExit.includes(r.status)) {
65
+ throw new Error(`exit code ${r.status}: ${(r.stderr || r.stdout || '').trim().split('\n').slice(-3).join(' ')}`);
66
+ }
67
+ const data = existsSync(pass.rawFile) ? JSON.parse(readFileSync(pass.rawFile, 'utf8') || 'null') : null;
68
+ json = pass.name ? [...(json ?? []), ...(data ?? []).map((item) => ({ ...item, pass: pass.name }))] : data;
69
+ }
70
+ const found = s.parse(json, ctx).map((f) => ({ ...f, source: { ...f.source, tool_version: run.version } }));
71
+ run.findings = found.length;
72
+ findings = findings.concat(found);
73
+ } catch (err) {
74
+ run.status = 'failed';
75
+ run.error = err.message;
76
+ }
77
+ }
78
+
79
+ const result = {
80
+ generator: `ai-secure-audit ${version}`,
81
+ check: 'basic',
82
+ target: { git: isGit, commit: ctx.commit, uncommitted_changes: ctx.dirty },
83
+ tools: runs,
84
+ notes: [
85
+ 'Not checked by this tool: whether one user can reach another user\'s data, business rules, and anything running on a server.',
86
+ `Not checked yet in this version: vulnerable libraries (osv-scanner, coming in v0.2) and Docker/config files (trivy, coming in v0.3).`,
87
+ ],
88
+ findings: sortAndNumber(findings),
89
+ };
90
+ writeFileSync(join(out, 'findings.json'), JSON.stringify(result, null, 2) + '\n');
91
+ return { root, out, result };
92
+ }
@@ -0,0 +1,125 @@
1
+ import { existsSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { rel } from '../paths.js';
4
+
5
+ const SKIP_PATHS = [
6
+ '(^|/)node_modules/',
7
+ '(^|/)\\.git/',
8
+ '(^|/)(coverage|vendor)/',
9
+ '(^|/)\\.audit/out/',
10
+ ];
11
+ // Outside git there is no .gitignore to ask, and a local .env is where secrets belong.
12
+ const LOCAL_ENV = '(^|/)\\.env(\\.[^/]+)?$';
13
+
14
+ // The parts of framework output that are served to visitors.
15
+ const DEPLOYED_OUTPUT = /(^|\/)(\.next\/static|\.output\/public|\.svelte-kit\/output\/client)\//;
16
+ // The rest of framework output is server code, caches and manifests. On real builds this was all false alarms.
17
+ const INTERNAL_OUTPUT = /(^|\/)(\.next|\.nuxt|\.output|\.svelte-kit)\//;
18
+ const PLAIN_OUTPUT = /(^|\/)(dist|build)\//;
19
+
20
+ function fileKind(file) {
21
+ if (DEPLOYED_OUTPUT.test(file)) return 'built';
22
+ if (INTERNAL_OUTPUT.test(file)) return 'internal';
23
+ return PLAIN_OUTPUT.test(file) ? 'built' : 'source';
24
+ }
25
+
26
+ const FIX = {
27
+ committed: 'Revoke or rotate this key at the provider first. Then remove it from the code and load it from an ' +
28
+ 'environment variable on the server. Deleting it from the code is not enough: it stays in git history.',
29
+ notCommitted: 'Move this key out of the code before you commit: load it from an environment variable on the ' +
30
+ 'server, and keep the file that holds it in .gitignore. If the key was ever shared or pasted anywhere else, ' +
31
+ 'rotate it at the provider too.',
32
+ built: 'This is build output, which is what gets deployed, and on a website it is sent to every visitor. Rotate ' +
33
+ 'this key at the provider, keep it on the server only (call the provider from your backend), then rebuild.',
34
+ };
35
+ const MAYBE_FALSE_ALARM = 'This may be a false alarm: minified code often looks like a key, so check the value first. If it is a real key: ';
36
+
37
+ export default {
38
+ id: 'gitleaks',
39
+ category: 'secret',
40
+
41
+ prepare(ctx) {
42
+ const paths = ctx.isGit ? SKIP_PATHS : [...SKIP_PATHS, LOCAL_ENV];
43
+ const config = [
44
+ 'title = "ai-secure-audit"',
45
+ '[extend]',
46
+ 'useDefault = true',
47
+ '[allowlist]',
48
+ 'description = "dependency and output folders"',
49
+ `paths = [${paths.map((p) => `'''${p}'''`).join(', ')}]`,
50
+ '',
51
+ ].join('\n');
52
+ const file = join(ctx.rawDir, 'gitleaks.toml');
53
+ writeFileSync(file, config);
54
+ return { config: file };
55
+ },
56
+
57
+ // gitleaks' git mode reads commits only, so a key that is not committed yet needs a second pass over the files.
58
+ passes(ctx, rawDir, prep) {
59
+ const pass = (name, mode, extra = []) => {
60
+ const rawFile = join(rawDir, `gitleaks-${name}.json`);
61
+ return {
62
+ name,
63
+ rawFile,
64
+ args: [mode, '--config', prep.config, '--redact', '--no-banner', '--log-level', 'error', '--exit-code', '0',
65
+ '--report-format', 'json', '--report-path', rawFile, ...extra, ctx.root],
66
+ };
67
+ };
68
+ const files = pass('files', 'dir', ['--max-target-megabytes', '20']);
69
+ return ctx.isGit && ctx.commit ? [pass('history', 'git'), files] : [files];
70
+ },
71
+
72
+ okExit: [0],
73
+
74
+ parse(json, ctx) {
75
+ const prefix = ctx.prefix ?? '';
76
+ const groups = new Map();
77
+ for (const leak of json ?? []) {
78
+ const fromFiles = leak.pass === 'files';
79
+ let file = rel(ctx.root, leak.File);
80
+ if (!fromFiles && prefix) {
81
+ // History is reported from the top of the repository, which may be above the scanned folder.
82
+ if (!file.startsWith(prefix)) continue;
83
+ file = file.slice(prefix.length);
84
+ }
85
+ const kind = fileKind(file);
86
+ if (kind === 'internal') continue;
87
+ // A file git ignores stays on this machine. Build output is the exception: it gets deployed.
88
+ if (fromFiles && kind === 'source' && ctx.isIgnored?.(file)) continue;
89
+ const key = `gitleaks:${leak.RuleID}:${file}:${leak.StartLine}`;
90
+ const g = groups.get(key) ?? { leak, file, kind, commits: new Set(), inHistory: false };
91
+ if (!fromFiles) g.inHistory = true;
92
+ if (leak.Commit) g.commits.add(leak.Commit.slice(0, 7));
93
+ groups.set(key, g);
94
+ }
95
+ const fileExists = ctx.fileExists ?? ((f) => existsSync(join(ctx.root, f)));
96
+ return [...groups].map(([key, { leak, file, kind, commits, inHistory }]) => {
97
+ const commitList = [...commits].sort();
98
+ // A secret in a file that no longer exists is only in git history. Say so: people look for the file and
99
+ // cannot find it, then think the tool is wrong.
100
+ const historyOnly = ctx.isGit !== false && !fileExists(file);
101
+ const built = kind === 'built';
102
+ const notCommitted = Boolean(ctx.isGit) && !inHistory && !built;
103
+ const guess = built && leak.RuleID === 'generic-api-key';
104
+ const fix = built ? FIX.built : notCommitted ? FIX.notCommitted : FIX.committed;
105
+ return {
106
+ fingerprint: key,
107
+ category: 'secret',
108
+ title: `Secret in code: ${leak.RuleID}`,
109
+ severity: { tool: 'none (gitleaks does not rate)', normalized: guess ? 'medium' : 'high' },
110
+ source: { kind: 'tool', tool: 'gitleaks', rule_id: leak.RuleID },
111
+ evidence: [{
112
+ location: `${file}:${leak.StartLine}`,
113
+ // Never copy Match, Secret, Author or Email: they hold the secret or personal data.
114
+ detail: leak.Description,
115
+ ...(commitList.length ? { commits: commitList } : {}),
116
+ ...(historyOnly ? { history_only: true } : {}),
117
+ ...(notCommitted ? { not_committed: true } : {}),
118
+ ...(built ? { built: true } : {}),
119
+ }],
120
+ fix: guess ? MAYBE_FALSE_ALARM + fix : fix,
121
+ references: { cwe: ['CWE-798'] },
122
+ };
123
+ });
124
+ },
125
+ };
package/src/tools.js ADDED
@@ -0,0 +1,50 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { get } from './http.js';
6
+ import { fromTarGz, fromZip } from './extract.js';
7
+
8
+ const lock = JSON.parse(readFileSync(new URL('../tools.lock.json', import.meta.url), 'utf8'));
9
+
10
+ export function lockedTools() {
11
+ return lock.tools;
12
+ }
13
+
14
+ export function platformKey() {
15
+ return `${process.platform}-${process.arch}`;
16
+ }
17
+
18
+ export function cacheDir() {
19
+ if (process.env.AI_SECURE_AUDIT_CACHE) return process.env.AI_SECURE_AUDIT_CACHE;
20
+ if (process.platform === 'win32') return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'ai-secure-audit');
21
+ return join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'ai-secure-audit');
22
+ }
23
+
24
+ // Returns the path to the pinned binary, downloading and verifying it on first use.
25
+ // A checksum mismatch is fatal: we never run a binary that is not the pinned one.
26
+ export async function ensureTool(id, log = () => {}) {
27
+ const tool = lock.tools[id];
28
+ if (!tool) throw new Error(`unknown tool: ${id}`);
29
+ const p = tool.platforms[platformKey()];
30
+ if (!p) throw new Error(`${id} has no build for ${platformKey()}`);
31
+
32
+ const dir = join(cacheDir(), 'bin', id, tool.version);
33
+ const target = join(dir, p.binary);
34
+ if (existsSync(target)) return target;
35
+
36
+ log(`downloading ${id} ${tool.version} ...`);
37
+ const archive = await get(p.url);
38
+ const sha256 = createHash('sha256').update(archive).digest('hex');
39
+ if (sha256 !== p.sha256) {
40
+ throw new Error(`${id}: checksum mismatch for ${p.url}\n expected ${p.sha256}\n got ${sha256}`);
41
+ }
42
+ const bytes = p.archive === 'tar.gz' ? fromTarGz(archive, p.binary) : p.archive === 'zip' ? fromZip(archive, p.binary) : archive;
43
+
44
+ mkdirSync(dir, { recursive: true });
45
+ const tmp = `${target}.${process.pid}.tmp`;
46
+ writeFileSync(tmp, bytes);
47
+ if (process.platform !== 'win32') chmodSync(tmp, 0o755);
48
+ renameSync(tmp, target);
49
+ return target;
50
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "lockfileVersion": 1,
3
+ "tools": {
4
+ "gitleaks": {
5
+ "version": "8.30.1",
6
+ "license": "MIT",
7
+ "repo": "https://github.com/gitleaks/gitleaks",
8
+ "platforms": {
9
+ "darwin-arm64": {
10
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_darwin_arm64.tar.gz",
11
+ "sha256": "b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5",
12
+ "archive": "tar.gz",
13
+ "binary": "gitleaks"
14
+ },
15
+ "darwin-x64": {
16
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_darwin_x64.tar.gz",
17
+ "sha256": "dfe101a4db2255fc85120ac7f3d25e4342c3c20cf749f2c20a18081af1952709",
18
+ "archive": "tar.gz",
19
+ "binary": "gitleaks"
20
+ },
21
+ "linux-arm64": {
22
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_arm64.tar.gz",
23
+ "sha256": "e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080",
24
+ "archive": "tar.gz",
25
+ "binary": "gitleaks"
26
+ },
27
+ "linux-x64": {
28
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz",
29
+ "sha256": "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb",
30
+ "archive": "tar.gz",
31
+ "binary": "gitleaks"
32
+ },
33
+ "win32-arm64": {
34
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_windows_arm64.zip",
35
+ "sha256": "b95f5e4f5c425cedca7ee203d9afd29597e692c4924a12ed42f970537c72cc0f",
36
+ "archive": "zip",
37
+ "binary": "gitleaks.exe"
38
+ },
39
+ "win32-x64": {
40
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_windows_x64.zip",
41
+ "sha256": "d29144deff3a68aa93ced33dddf84b7fdc26070add4aa0f4513094c8332afc4e",
42
+ "archive": "zip",
43
+ "binary": "gitleaks.exe"
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }