ai-secure-audit 0.0.9 → 0.0.11

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/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  > Status: 0.0.x on npm runs the basic check with `npx ai-secure-audit`: secrets, libraries with known holes and, from
4
4
  > 0.0.5, code rules for routes anyone can repeat without limit and, from 0.0.9, for session checks that a built-in
5
- > name such as `constructor` passes. v0.1 is not released yet.
5
+ > name such as `constructor` passes. From 0.0.10 it also checks Dockerfiles with trivy (Compose files are not read yet,
6
+ > and the report says so), and from 0.0.11 it warns when a Docker build would copy these results into the image. v0.1 is not released yet.
6
7
  >
7
8
  > **มือใหม่เริ่มตรงนี้:** [learn/](learn/) ควรตรวจอะไรก่อน เพราะอะไร และแก้ยังไง (ภาษาไทย)
8
9
  >
@@ -58,7 +59,10 @@ Or ask your AI assistant: *"Run `node <path-to>/ai-secure-audit/bin/ai-secure-au
58
59
  results in simple words, and help me fix the most serious ones first."*
59
60
 
60
61
  Results go to `.audit/out/` in your project (`report.md` for people, `findings.json` for tools and AI). That folder
61
- ignores itself in git, so results are not committed by accident.
62
+ ignores itself in git, so results are not committed by accident. Git is not the only way out, though: a `Dockerfile`
63
+ with `COPY . .` puts every file in the folder into the image. From 0.0.11 the report warns (under "About these
64
+ results") when a `Dockerfile` at the top of the project copies the whole folder and `.dockerignore` does not leave out
65
+ `.audit`.
62
66
 
63
67
  ## Repository layout
64
68
 
@@ -88,7 +92,7 @@ SHA-256 checksums. The check reads only your project folder and never uploads yo
88
92
  |---|---|---|
89
93
  | Passwords, API keys and tokens in the code, in files not committed yet, in git history and in build output (v0.1) | gitleaks | MIT |
90
94
  | Libraries with known vulnerabilities (v0.2) | osv-scanner (offline database) | Apache-2.0 |
91
- | Dockerfile and config mistakes (v0.3) | trivy config | Apache-2.0 |
95
+ | Dockerfile and config mistakes (0.0.10): Dockerfile, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM, Ansible. trivy does not read Docker Compose files; the report names any it found as not checked | trivy config | Apache-2.0 |
92
96
  | Code mistakes AI-generated apps often make (see below), one rule at a time: sign-in, sign-up and join routes with no limit on repeats (Express 0.0.5, NestJS 0.0.6), vote and like routes that never check who is voting (0.0.6), session, token or admin checks that a built-in name like `constructor` passes (0.0.9); the rest planned | opengrep + this kit's own rules | LGPL-2.1 (rules: Apache-2.0) |
93
97
 
94
98
  Common mistakes the kit's own rules look for: sign-in, sign-up and join routes that anyone can call without limit
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-secure-audit",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "description": "Free, open-source security check for apps built with AI. Runs pinned open-source scanners; no AI needed to run.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/src/coverage.js CHANGED
@@ -27,6 +27,10 @@ const LANGUAGES = {
27
27
  vue: ['.vue'],
28
28
  svelte: ['.svelte'],
29
29
  };
30
+ // Docker Compose files: trivy (the config checker) does not read them, so the report must say they were not checked.
31
+ // compose.yaml, compose.yml, docker-compose.yml, docker-compose.prod.yaml and the like.
32
+ export const isComposeFile = (name) => /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/i.test(name);
33
+
30
34
  const BY_EXT = new Map(Object.entries(LANGUAGES).flatMap(([lang, exts]) => exts.map((e) => [e, lang])));
31
35
 
32
36
  // Lockfiles osv-scanner reads, and whether this kit has tested that ecosystem with known-answer cases.
@@ -81,16 +85,18 @@ export function projectCoverage(root, { rulesDir, limit = 200_000 } = {}) {
81
85
  const covered = ruleLanguages(rulesDir);
82
86
  const counts = new Map();
83
87
  const lockfiles = [];
88
+ const compose = [];
84
89
  for (const f of files) {
85
90
  const name = basename(f);
86
91
  const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
87
92
  const lang = BY_EXT.get(ext);
88
93
  if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
89
94
  if (LOCKFILES[name]) lockfiles.push({ file: f, ...LOCKFILES[name] });
95
+ if (isComposeFile(name)) compose.push(f);
90
96
  }
91
97
  const languages = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
92
98
  .map(([language, n]) => ({ language, files: n, code_rules: covered.has(language) }));
93
- return { languages, lockfiles, truncated: files.length >= limit };
99
+ return { languages, lockfiles, compose, truncated: files.length >= limit };
94
100
  }
95
101
 
96
102
  // Plain sentences for the report and for the AI assistant. Empty when everything found is covered.
@@ -108,6 +114,11 @@ export function coverageGaps(cov) {
108
114
  gaps.push(`Libraries: ${untested.map((l) => `${l.file} (${l.ecosystem})`).join(', ')} ` +
109
115
  'were read by osv-scanner, but this kit has not tested that ecosystem with known answers yet.');
110
116
  }
117
+ if (cov.compose?.length) {
118
+ gaps.push(`Docker Compose: ${cov.compose.join(', ')} ${cov.compose.length === 1 ? 'was' : 'were'} not checked. trivy reads ` +
119
+ 'Dockerfiles but not Compose files, so settings such as privileged: true, network_mode: host, a mounted ' +
120
+ 'docker.sock or a database port open to every network were not looked at; "0 findings" says nothing about them.');
121
+ }
111
122
  if (cov.truncated) gaps.push('The project has more files than this check counts; the lists above may be incomplete.');
112
123
  return gaps;
113
124
  }
@@ -0,0 +1,107 @@
1
+ // Does a Docker build of the scanned folder take this tool's own results (.audit/) into the image?
2
+ // trivy only reads Dockerfile instructions, so nothing else notices: .audit/ appears on the first scan, and a
3
+ // Dockerfile with COPY . . then ships the list of the app's weak points in every image.
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
5
+ import { join, posix } from 'node:path';
6
+
7
+ // The files a scan writes; if any of them gets into the build context, the results do.
8
+ const AUDIT_FILES = ['.audit/out/findings.json', '.audit/out/report.md', '.audit/out/raw/x.json'];
9
+
10
+ const DOCKERFILE = /^(Dockerfile|Containerfile)(\.[\w.-]+)?$|^[\w.-]+\.(Dockerfile|dockerfile)$/;
11
+
12
+ function patternToRegex(p) {
13
+ let re = '';
14
+ for (let i = 0; i < p.length; i++) {
15
+ const c = p[i];
16
+ if (c === '*') {
17
+ if (p[i + 1] === '*') {
18
+ i++;
19
+ if (p[i + 1] === '/') { i++; re += '(?:.*/)?'; } else re += '.*';
20
+ } else re += '[^/]*';
21
+ } else if (c === '?') re += '[^/]';
22
+ else if (c === '[') {
23
+ const end = p.indexOf(']', i + 1);
24
+ if (end < 0) { re += '\\['; continue; }
25
+ re += '[' + p.slice(i + 1, end).replace(/^!/, '^').replace(/\\/g, '\\\\') + ']';
26
+ i = end;
27
+ } else if (c === '\\' && i + 1 < p.length) re += '\\' + p[++i];
28
+ else re += c.replace(/[.+^${}()|]/g, '\\$&');
29
+ }
30
+ return new RegExp(`^${re}$`);
31
+ }
32
+
33
+ // .dockerignore rules as Docker reads them: one pattern per line, # comments, surrounding space trimmed, a leading
34
+ // ! re-includes, paths cleaned (leading /, ./ and trailing / dropped). The last matching line wins.
35
+ export function parseDockerignore(text) {
36
+ const rules = [];
37
+ for (let line of text.split(/\r?\n/)) {
38
+ line = line.trim();
39
+ if (!line || line.startsWith('#')) continue;
40
+ const negate = line.startsWith('!');
41
+ if (negate) line = line.slice(1).trim();
42
+ let p = posix.normalize(line).replace(/^\/+/, '').replace(/\/+$/, '');
43
+ if (!p || p === '.') continue;
44
+ rules.push({ negate, re: patternToRegex(p) });
45
+ }
46
+ return rules;
47
+ }
48
+
49
+ // A path is excluded when a pattern matches it or one of its parent folders.
50
+ export function isExcluded(rules, file) {
51
+ const parts = file.split('/');
52
+ const paths = parts.map((_, i) => parts.slice(0, i + 1).join('/'));
53
+ let excluded = false;
54
+ for (const r of rules) if (paths.some((p) => r.re.test(p))) excluded = !r.negate;
55
+ return excluded;
56
+ }
57
+
58
+ // COPY or ADD whose sources include the whole context: ".", "./", "*" or "./*" (shell or JSON form).
59
+ export function copiesWholeFolder(dockerfile) {
60
+ const text = dockerfile.replace(/\\\r?\n/g, ' ');
61
+ for (const line of text.split(/\r?\n/)) {
62
+ const m = /^\s*(?:COPY|ADD)\s+(.*)$/i.exec(line);
63
+ if (!m) continue;
64
+ let rest = m[1].trim();
65
+ while (/^--\S+/.test(rest)) rest = rest.replace(/^--\S+\s*/, '');
66
+ if (/--from=/i.test(m[1])) continue; // copies from another stage, not from the folder
67
+ let args;
68
+ if (rest.startsWith('[')) {
69
+ try { args = JSON.parse(rest); } catch { continue; }
70
+ } else args = rest.split(/\s+/);
71
+ if (args.slice(0, -1).some((a) => ['.', './', '*', './*'].includes(a))) return true;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ // One notice per Dockerfile at the top of the scanned folder (the usual build context) that would ship .audit/.
77
+ // Not checked: Dockerfiles in subfolders built with a context above them (compose build.context: ..).
78
+ export function dockerignoreNotices(root) {
79
+ let names;
80
+ try { names = readdirSync(root); } catch { return []; }
81
+ const notices = [];
82
+ for (const name of names.filter((n) => DOCKERFILE.test(n)).sort()) {
83
+ let text;
84
+ try { text = readFileSync(join(root, name), 'utf8'); } catch { continue; }
85
+ if (!copiesWholeFolder(text)) continue;
86
+ // BuildKit reads <Dockerfile>.dockerignore next to the Dockerfile first, then .dockerignore.
87
+ const own = `${name}.dockerignore`;
88
+ const ignoreFile = existsSync(join(root, own)) ? own : existsSync(join(root, '.dockerignore')) ? '.dockerignore' : null;
89
+ if (!ignoreFile) {
90
+ notices.push({
91
+ id: 'dockerignore-audit', file: name,
92
+ message: `${name} copies the whole folder and there is no .dockerignore, so this check's results in .audit/ ` +
93
+ '(a list of the app\'s weak points) go into the image, together with .env, .git and anything else in the ' +
94
+ 'folder. Add a .dockerignore with at least these lines: .audit, .env, .git',
95
+ });
96
+ continue;
97
+ }
98
+ const rules = parseDockerignore(readFileSync(join(root, ignoreFile), 'utf8'));
99
+ if (AUDIT_FILES.every((f) => isExcluded(rules, f))) continue;
100
+ notices.push({
101
+ id: 'dockerignore-audit', file: name,
102
+ message: `${name} copies the whole folder and ${ignoreFile} does not exclude .audit/, so this check's results ` +
103
+ `(a list of the app's weak points) go into the image. Add the line .audit to ${ignoreFile}.`,
104
+ });
105
+ }
106
+ return notices;
107
+ }
package/src/report.js CHANGED
@@ -108,13 +108,19 @@ export function reportMarkdown(result, date) {
108
108
  lines.push('');
109
109
  }
110
110
 
111
+ if (result.notices?.length) {
112
+ lines.push('## About these results');
113
+ lines.push('');
114
+ for (const n of result.notices) lines.push(`- ${n.message}`);
115
+ lines.push('');
116
+ }
117
+
111
118
  lines.push('## What this check could not see');
112
119
  lines.push('');
113
120
  lines.push('- Whether one user can open or change another user\'s data (for example by changing an id in the URL)');
114
121
  lines.push('- Business rules: prices, coupons, approvals, payments');
115
122
  lines.push('- Database rules such as Supabase row-level security or Firebase security rules (planned)');
116
123
  lines.push('- Anything about the live server or website');
117
- lines.push('- Docker/config mistakes: not in this version yet (coming in v0.3)');
118
124
  for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
119
125
  lines.push('');
120
126
  lines.push('## Tools');
@@ -142,9 +148,9 @@ export function consoleSummary(result, outRel) {
142
148
  '- A finding marked not_committed can be moved out of the code without rotating, unless the key was shared or pasted somewhere else.',
143
149
  '- Findings of type code come from pattern rules and can be wrong. Read the code at that location and tell the user',
144
150
  ' if a limit or check exists somewhere the rule cannot see (another file, the proxy) before changing anything.',
145
- '- Not checked: whether one user can reach another user\'s data, business rules, and (in this version)',
146
- ' Docker/config files. Say so.',
151
+ '- Not checked: whether one user can reach another user\'s data, and business rules. Say so.',
147
152
  ...(result.coverage?.gaps ?? []).map((g) => `- ${g} Tell the user.`),
153
+ ...(result.notices ?? []).map((n) => `- ${n.message} Tell the user, and ask before editing the file.`),
148
154
  ...(failed.length ? ['- Some tools did not run (see NOT RUN above). Tell the user the check is incomplete.'] : []),
149
155
  ].join('\n');
150
156
  }
package/src/scan.js CHANGED
@@ -4,13 +4,15 @@ import { join, resolve } from 'node:path';
4
4
  import { cacheDir, ensureTool, lockedTools } from './tools.js';
5
5
  import { sortAndNumber } from './findings.js';
6
6
  import { coverageGaps, projectCoverage } from './coverage.js';
7
+ import { dockerignoreNotices } from './dockerignore.js';
7
8
  import gitleaks from './scanners/gitleaks.js';
8
9
  import osv from './scanners/osv.js';
9
10
  import opengrep from './scanners/opengrep.js';
11
+ import trivy from './scanners/trivy.js';
10
12
 
11
13
  // Scanners are released one at a time, each after passing its own tests (see CLAUDE.md).
12
14
  // Scanners still in development are kept outside this repository until they pass.
13
- export const BASIC_SCANNERS = [gitleaks, osv, opengrep];
15
+ export const BASIC_SCANNERS = [gitleaks, osv, opengrep, trivy];
14
16
 
15
17
  function git(root, args) {
16
18
  const r = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
@@ -86,10 +88,13 @@ export async function scan(target, { log = () => {}, version }) {
86
88
  target: { git: isGit, commit: ctx.commit, uncommitted_changes: ctx.dirty },
87
89
  tools: runs,
88
90
  coverage: { ...coverage, gaps: coverageGaps(coverage) },
91
+ // About this tool's own output, not a weakness of the app: kept apart from findings so it is never rated.
92
+ notices: dockerignoreNotices(root),
89
93
  notes: [
90
94
  'Not checked by this tool: whether one user can reach another user\'s data, business rules, and anything running on a server.',
91
95
  'Code rules (category code) are this kit\'s own opengrep rules. They can be wrong: check the location before changing code.',
92
- `Not checked yet in this version: Docker/config files (trivy, coming in v0.3).`,
96
+ 'Config files are checked by trivy: Dockerfiles, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM and Ansible files. ' +
97
+ 'trivy does not read Docker Compose files; coverage.gaps names any that were not checked.',
93
98
  ],
94
99
  findings: sortAndNumber(findings),
95
100
  };
@@ -0,0 +1,40 @@
1
+ import { join } from 'node:path';
2
+ import { rel } from '../paths.js';
3
+
4
+ export default {
5
+ id: 'trivy',
6
+ category: 'config',
7
+
8
+ // --skip-check-update keeps the checks built into the pinned trivy version, so results do not drift.
9
+ args(ctx, out) {
10
+ return ['config', '--format', 'json', '--output', out, '--skip-check-update', '--quiet',
11
+ '--cache-dir', join(ctx.cache, 'trivy'),
12
+ '--skip-dirs', '**/node_modules', '--skip-dirs', '**/.git', ctx.root];
13
+ },
14
+
15
+ okExit: [0],
16
+
17
+ parse(json, ctx) {
18
+ const findings = [];
19
+ for (const result of json?.Results ?? []) {
20
+ const file = rel(ctx.root, result.Target);
21
+ for (const m of result.Misconfigurations ?? []) {
22
+ if (m.Status !== 'FAIL') continue;
23
+ const line = m.CauseMetadata?.StartLine;
24
+ const location = line ? `${file}:${line}` : file;
25
+ const sev = (m.Severity ?? 'UNKNOWN').toLowerCase();
26
+ findings.push({
27
+ fingerprint: `trivy:${m.ID}:${location}`,
28
+ category: 'config',
29
+ title: m.Title,
30
+ severity: { tool: m.Severity, normalized: ['critical', 'high', 'medium', 'low'].includes(sev) ? sev : 'medium' },
31
+ source: { kind: 'tool', tool: 'trivy', rule_id: m.ID },
32
+ evidence: [{ location, detail: m.Message }],
33
+ fix: m.Resolution,
34
+ references: { urls: m.PrimaryURL ? [m.PrimaryURL] : [] },
35
+ });
36
+ }
37
+ }
38
+ return findings;
39
+ },
40
+ };
package/tools.lock.json CHANGED
@@ -165,6 +165,61 @@
165
165
  "binary": "opengrep_windows_x86.exe"
166
166
  }
167
167
  }
168
+ },
169
+ "trivy": {
170
+ "version": "0.76.1",
171
+ "license": "Apache-2.0",
172
+ "repo": "https://github.com/aquasecurity/trivy",
173
+ "platforms": {
174
+ "darwin-arm64": {
175
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_macOS-ARM64.tar.gz",
176
+ "sha256": "11a9b6cd2752011b54f01ea4bd0dbfa9f0c41dc6538d5a3f9d23955f471bf4e5",
177
+ "archive": "tar.gz",
178
+ "binary": "trivy"
179
+ },
180
+ "darwin-x64": {
181
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_macOS-64bit.tar.gz",
182
+ "sha256": "7aa762eacd582052d053b62dcf972a1ab058abe39a57ccae234ed8894945b6b7",
183
+ "archive": "tar.gz",
184
+ "binary": "trivy"
185
+ },
186
+ "linux-arm64": {
187
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
188
+ "sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
189
+ "archive": "tar.gz",
190
+ "binary": "trivy"
191
+ },
192
+ "linux-x64": {
193
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
194
+ "sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
195
+ "archive": "tar.gz",
196
+ "binary": "trivy"
197
+ },
198
+ "linux-arm64-musl": {
199
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
200
+ "sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
201
+ "archive": "tar.gz",
202
+ "binary": "trivy"
203
+ },
204
+ "linux-x64-musl": {
205
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
206
+ "sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
207
+ "archive": "tar.gz",
208
+ "binary": "trivy"
209
+ },
210
+ "win32-arm64": {
211
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
212
+ "sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
213
+ "archive": "zip",
214
+ "binary": "trivy.exe"
215
+ },
216
+ "win32-x64": {
217
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
218
+ "sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
219
+ "archive": "zip",
220
+ "binary": "trivy.exe"
221
+ }
222
+ }
168
223
  }
169
224
  }
170
225
  }