ai-secure-audit 0.0.1 → 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/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # ai-secure-audit
2
2
 
3
- > Status: 0.0.1 is on npm so `npx ai-secure-audit` runs the basic secret check. v0.1 is not released yet.
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.
4
8
 
5
9
  A free, open-source security check for apps built with AI. If you make apps with Claude Code, Codex, Cursor or
6
10
  Antigravity but security is not your field, ask your AI assistant to run it on your project:
@@ -64,6 +68,7 @@ profiles/ pinned tool and rule sets per stack (planned)
64
68
  rules/ this kit's own opengrep rules (planned)
65
69
  config/ example files to copy into the audited project
66
70
  docs/ design notes
71
+ learn/ beginner lessons in Thai and English, one topic per file pair
67
72
  ```
68
73
 
69
74
  ## Planned coverage
@@ -79,7 +84,7 @@ SHA-256 checksums. The check reads only your project folder and never uploads yo
79
84
 
80
85
  | Checks | Tool | License |
81
86
  |---|---|---|
82
- | Passwords, API keys and tokens in the code or git history (v0.1) | gitleaks | MIT |
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 |
83
88
  | Libraries with known vulnerabilities (v0.2) | osv-scanner (offline database) | Apache-2.0 |
84
89
  | Dockerfile and config mistakes (v0.3) | trivy config | Apache-2.0 |
85
90
  | Code mistakes AI-generated apps often make (see below), planned | opengrep + this kit's own rules | LGPL-2.1 (rules: Apache-2.0) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-secure-audit",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
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/report.js CHANGED
@@ -27,10 +27,18 @@ function whereSentence(f) {
27
27
  return `\`${e.location}\`. This file is no longer in your project, but it is still in git history${commits}, ` +
28
28
  'so anyone with a copy of the repository can still read it';
29
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`;
30
32
  return `\`${e.location}\`${commits}`;
31
33
  }).join('; ');
32
34
  }
33
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
+
34
42
  export function reportMarkdown(result, date) {
35
43
  const { findings, tools, target } = result;
36
44
  const c = countBySeverity(findings);
@@ -75,8 +83,7 @@ export function reportMarkdown(result, date) {
75
83
  lines.push('| ID | Severity | Type | Problem | Where |');
76
84
  lines.push('|---|---|---|---|---|');
77
85
  for (const f of findings) {
78
- const note = f.evidence.some((e) => e.history_only) ? ' (git history only)' : '';
79
- lines.push(`| ${f.id} | ${f.severity.normalized} | ${f.category} | ${f.title.replace(/\|/g, '\\|')} | ${where(f)}${note} |`);
86
+ lines.push(`| ${f.id} | ${f.severity.normalized} | ${f.category} | ${f.title.replace(/\|/g, '\\|')} | ${where(f)}${whereNote(f)} |`);
80
87
  }
81
88
  lines.push('');
82
89
  }
@@ -110,7 +117,8 @@ export function consoleSummary(result, outRel) {
110
117
  `- Findings are in ${outRel}/findings.json. Do not add, remove or re-rate findings.`,
111
118
  '- Explain them to the user in plain language, most serious first.',
112
119
  '- Ask before changing code. Fix one finding at a time; run `npx ai-secure-audit retest` after.',
113
- '- A leaked secret must be rotated at the provider. Deleting it from the code is not enough.',
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.',
114
122
  '- Not checked: whether one user can reach another user\'s data, business rules, and (in this version)',
115
123
  ' vulnerable libraries and Docker/config files. Say so.',
116
124
  ...(failed.length ? ['- Some tools did not run (see NOT RUN above). Tell the user the check is incomplete.'] : []),
package/src/scan.js CHANGED
@@ -36,6 +36,8 @@ export async function scan(target, { log = () => {}, version }) {
36
36
  isGit,
37
37
  commit: isGit ? git(root, ['rev-parse', '--short', 'HEAD']) : null,
38
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,
39
41
  };
40
42
 
41
43
  const tools = lockedTools();
@@ -47,19 +49,24 @@ export async function scan(target, { log = () => {}, version }) {
47
49
  try {
48
50
  const bin = await ensureTool(s.id, log);
49
51
  const prep = s.prepare?.(ctx) ?? {};
50
- const rawFile = join(rawDir, `${s.id}.json`);
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) }];
51
54
  log(`running ${s.id} ${run.version} ...`);
52
- const r = spawnSync(bin, s.args(ctx, rawFile, prep), {
53
- cwd: root,
54
- env: { ...process.env, ...(s.env?.(ctx) ?? {}) },
55
- encoding: 'utf8',
56
- maxBuffer: 64 * 1024 * 1024,
57
- });
58
- if (r.error) throw r.error;
59
- if (!s.okExit.includes(r.status)) {
60
- throw new Error(`exit code ${r.status}: ${(r.stderr || r.stdout || '').trim().split('\n').slice(-3).join(' ')}`);
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;
61
69
  }
62
- const json = existsSync(rawFile) ? JSON.parse(readFileSync(rawFile, 'utf8') || 'null') : null;
63
70
  const found = s.parse(json, ctx).map((f) => ({ ...f, source: { ...f.source, tool_version: run.version } }));
64
71
  run.findings = found.length;
65
72
  findings = findings.concat(found);
@@ -5,13 +5,35 @@ import { rel } from '../paths.js';
5
5
  const SKIP_PATHS = [
6
6
  '(^|/)node_modules/',
7
7
  '(^|/)\\.git/',
8
- '(^|/)(dist|build|\\.next|\\.nuxt|\\.output|\\.svelte-kit|coverage|vendor)/',
8
+ '(^|/)(coverage|vendor)/',
9
9
  '(^|/)\\.audit/out/',
10
10
  ];
11
- // A local .env that is not in git is where secrets belong, so folder mode skips it.
12
- // Git mode keeps it: a committed .env is exactly what we want to find.
11
+ // Outside git there is no .gitignore to ask, and a local .env is where secrets belong.
13
12
  const LOCAL_ENV = '(^|/)\\.env(\\.[^/]+)?$';
14
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
+
15
37
  export default {
16
38
  id: 'gitleaks',
17
39
  category: 'secret',
@@ -23,7 +45,7 @@ export default {
23
45
  '[extend]',
24
46
  'useDefault = true',
25
47
  '[allowlist]',
26
- 'description = "dependency, build and output folders"',
48
+ 'description = "dependency and output folders"',
27
49
  `paths = [${paths.map((p) => `'''${p}'''`).join(', ')}]`,
28
50
  '',
29
51
  ].join('\n');
@@ -32,33 +54,59 @@ export default {
32
54
  return { config: file };
33
55
  },
34
56
 
35
- args(ctx, out, prep) {
36
- return [ctx.isGit ? 'git' : 'dir', '--config', prep.config, '--redact', '--no-banner', '--log-level', 'error',
37
- '--exit-code', '0', '--report-format', 'json', '--report-path', out, ctx.root];
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];
38
70
  },
39
71
 
40
72
  okExit: [0],
41
73
 
42
74
  parse(json, ctx) {
75
+ const prefix = ctx.prefix ?? '';
43
76
  const groups = new Map();
44
77
  for (const leak of json ?? []) {
45
- const file = rel(ctx.root, leak.File);
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;
46
89
  const key = `gitleaks:${leak.RuleID}:${file}:${leak.StartLine}`;
47
- const g = groups.get(key) ?? { leak, file, commits: new Set() };
90
+ const g = groups.get(key) ?? { leak, file, kind, commits: new Set(), inHistory: false };
91
+ if (!fromFiles) g.inHistory = true;
48
92
  if (leak.Commit) g.commits.add(leak.Commit.slice(0, 7));
49
93
  groups.set(key, g);
50
94
  }
51
95
  const fileExists = ctx.fileExists ?? ((f) => existsSync(join(ctx.root, f)));
52
- return [...groups].map(([key, { leak, file, commits }]) => {
96
+ return [...groups].map(([key, { leak, file, kind, commits, inHistory }]) => {
53
97
  const commitList = [...commits].sort();
54
98
  // A secret in a file that no longer exists is only in git history. Say so: people look for the file and
55
99
  // cannot find it, then think the tool is wrong.
56
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;
57
105
  return {
58
106
  fingerprint: key,
59
107
  category: 'secret',
60
108
  title: `Secret in code: ${leak.RuleID}`,
61
- severity: { tool: 'none (gitleaks does not rate)', normalized: 'high' },
109
+ severity: { tool: 'none (gitleaks does not rate)', normalized: guess ? 'medium' : 'high' },
62
110
  source: { kind: 'tool', tool: 'gitleaks', rule_id: leak.RuleID },
63
111
  evidence: [{
64
112
  location: `${file}:${leak.StartLine}`,
@@ -66,9 +114,10 @@ export default {
66
114
  detail: leak.Description,
67
115
  ...(commitList.length ? { commits: commitList } : {}),
68
116
  ...(historyOnly ? { history_only: true } : {}),
117
+ ...(notCommitted ? { not_committed: true } : {}),
118
+ ...(built ? { built: true } : {}),
69
119
  }],
70
- fix: 'Revoke or rotate this key at the provider first. Then remove it from the code and load it from an ' +
71
- 'environment variable on the server. Deleting it from the code is not enough: it stays in git history.',
120
+ fix: guess ? MAYBE_FALSE_ALARM + fix : fix,
72
121
  references: { cwe: ['CWE-798'] },
73
122
  };
74
123
  });