@codepulse-oss/core 2.0.1 → 3.1.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/dist/__tests__/all-wasm-languages.test.d.ts +2 -0
- package/dist/__tests__/all-wasm-languages.test.d.ts.map +1 -0
- package/dist/__tests__/all-wasm-languages.test.js +158 -0
- package/dist/__tests__/all-wasm-languages.test.js.map +1 -0
- package/dist/__tests__/v3-architecture.test.d.ts +2 -0
- package/dist/__tests__/v3-architecture.test.d.ts.map +1 -0
- package/dist/__tests__/v3-architecture.test.js +168 -0
- package/dist/__tests__/v3-architecture.test.js.map +1 -0
- package/dist/__tests__/v3.1-intelligence.test.d.ts +2 -0
- package/dist/__tests__/v3.1-intelligence.test.d.ts.map +1 -0
- package/dist/__tests__/v3.1-intelligence.test.js +208 -0
- package/dist/__tests__/v3.1-intelligence.test.js.map +1 -0
- package/dist/ai/privacy-firewall.d.ts +32 -0
- package/dist/ai/privacy-firewall.d.ts.map +1 -0
- package/dist/ai/privacy-firewall.js +143 -0
- package/dist/ai/privacy-firewall.js.map +1 -0
- package/dist/ai/provider.d.ts +50 -0
- package/dist/ai/provider.d.ts.map +1 -1
- package/dist/ai/provider.js +247 -24
- package/dist/ai/provider.js.map +1 -1
- package/dist/audit/archeology.d.ts +34 -0
- package/dist/audit/archeology.d.ts.map +1 -0
- package/dist/audit/archeology.js +162 -0
- package/dist/audit/archeology.js.map +1 -0
- package/dist/audit/architecture-guard.d.ts +35 -0
- package/dist/audit/architecture-guard.d.ts.map +1 -0
- package/dist/audit/architecture-guard.js +213 -0
- package/dist/audit/architecture-guard.js.map +1 -0
- package/dist/audit/baseline.d.ts +43 -0
- package/dist/audit/baseline.d.ts.map +1 -0
- package/dist/audit/baseline.js +140 -0
- package/dist/audit/baseline.js.map +1 -0
- package/dist/audit/dead-code-analyzer.d.ts +22 -0
- package/dist/audit/dead-code-analyzer.d.ts.map +1 -0
- package/dist/audit/dead-code-analyzer.js +265 -0
- package/dist/audit/dead-code-analyzer.js.map +1 -0
- package/dist/audit/iac-scanner.d.ts +12 -0
- package/dist/audit/iac-scanner.d.ts.map +1 -0
- package/dist/audit/iac-scanner.js +282 -0
- package/dist/audit/iac-scanner.js.map +1 -0
- package/dist/audit/live-accessibility.d.ts +26 -0
- package/dist/audit/live-accessibility.d.ts.map +1 -0
- package/dist/audit/live-accessibility.js +360 -0
- package/dist/audit/live-accessibility.js.map +1 -0
- package/dist/audit/main-scanner.d.ts.map +1 -1
- package/dist/audit/main-scanner.js +50 -1
- package/dist/audit/main-scanner.js.map +1 -1
- package/dist/audit/reachability.d.ts +17 -1
- package/dist/audit/reachability.d.ts.map +1 -1
- package/dist/audit/reachability.js +89 -2
- package/dist/audit/reachability.js.map +1 -1
- package/dist/audit/slop-detector.d.ts +14 -0
- package/dist/audit/slop-detector.d.ts.map +1 -0
- package/dist/audit/slop-detector.js +256 -0
- package/dist/audit/slop-detector.js.map +1 -0
- package/dist/autofix/worktree-autofix.d.ts +37 -0
- package/dist/autofix/worktree-autofix.d.ts.map +1 -1
- package/dist/autofix/worktree-autofix.js +141 -10
- package/dist/autofix/worktree-autofix.js.map +1 -1
- package/dist/config/codepulse-config.d.ts +14 -2
- package/dist/config/codepulse-config.d.ts.map +1 -1
- package/dist/config/codepulse-config.js +57 -31
- package/dist/config/codepulse-config.js.map +1 -1
- package/dist/db/database.d.ts +24 -0
- package/dist/db/database.d.ts.map +1 -1
- package/dist/db/database.js +61 -0
- package/dist/db/database.js.map +1 -1
- package/dist/docs/docs-generator.d.ts +1 -0
- package/dist/docs/docs-generator.d.ts.map +1 -1
- package/dist/docs/docs-generator.js +60 -1
- package/dist/docs/docs-generator.js.map +1 -1
- package/dist/graph/pagerank-map.d.ts +67 -0
- package/dist/graph/pagerank-map.d.ts.map +1 -0
- package/dist/graph/pagerank-map.js +273 -0
- package/dist/graph/pagerank-map.js.map +1 -0
- package/dist/graph/tree-sitter-indexer.d.ts +14 -1
- package/dist/graph/tree-sitter-indexer.d.ts.map +1 -1
- package/dist/graph/tree-sitter-indexer.js +415 -67
- package/dist/graph/tree-sitter-indexer.js.map +1 -1
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -1
- package/dist/output/context-pack.d.ts +26 -2
- package/dist/output/context-pack.d.ts.map +1 -1
- package/dist/output/context-pack.js +98 -13
- package/dist/output/context-pack.js.map +1 -1
- package/dist/output/markdown-writer.d.ts.map +1 -1
- package/dist/output/markdown-writer.js +8 -1
- package/dist/output/markdown-writer.js.map +1 -1
- package/dist/output/sarif-writer.d.ts +12 -0
- package/dist/output/sarif-writer.d.ts.map +1 -0
- package/dist/output/sarif-writer.js +147 -0
- package/dist/output/sarif-writer.js.map +1 -0
- package/dist/review/bundler.d.ts.map +1 -1
- package/dist/review/bundler.js +8 -2
- package/dist/review/bundler.js.map +1 -1
- package/dist/review/engine.d.ts.map +1 -1
- package/dist/review/engine.js +20 -5
- package/dist/review/engine.js.map +1 -1
- package/dist/sast/ast-grep-runner.d.ts +28 -0
- package/dist/sast/ast-grep-runner.d.ts.map +1 -0
- package/dist/sast/ast-grep-runner.js +215 -0
- package/dist/sast/ast-grep-runner.js.map +1 -0
- package/dist/sast/ast-queries.d.ts +7 -0
- package/dist/sast/ast-queries.d.ts.map +1 -0
- package/dist/sast/ast-queries.js +701 -0
- package/dist/sast/ast-queries.js.map +1 -0
- package/dist/sast/oxlint-runner.d.ts +24 -0
- package/dist/sast/oxlint-runner.d.ts.map +1 -0
- package/dist/sast/oxlint-runner.js +150 -0
- package/dist/sast/oxlint-runner.js.map +1 -0
- package/dist/sast/runner.d.ts.map +1 -1
- package/dist/sast/runner.js +66 -2
- package/dist/sast/runner.js.map +1 -1
- package/dist/sast/sbom-generator.d.ts +27 -0
- package/dist/sast/sbom-generator.d.ts.map +1 -0
- package/dist/sast/sbom-generator.js +191 -0
- package/dist/sast/sbom-generator.js.map +1 -0
- package/dist/sast/secret-registry.d.ts +18 -0
- package/dist/sast/secret-registry.d.ts.map +1 -0
- package/dist/sast/secret-registry.js +236 -0
- package/dist/sast/secret-registry.js.map +1 -0
- package/dist/types/review.d.ts +39 -0
- package/dist/types/review.d.ts.map +1 -1
- package/dist/types/review.js +16 -0
- package/dist/types/review.js.map +1 -1
- package/package.json +5 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"all-wasm-languages.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/all-wasm-languages.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { EXT_TO_LANGUAGE, TreeSitterGraphIndexer, runAstQueryRules } from '../index.js';
|
|
8
|
+
const LANGUAGE_SAMPLES = [
|
|
9
|
+
{ file: 'app.ts', wasm: 'tree-sitter-typescript.wasm', code: 'import { z } from "zod";\nexport class Api { run(): void { helper(); } }\n' },
|
|
10
|
+
{ file: 'view.tsx', wasm: 'tree-sitter-tsx.wasm', code: 'import React from "react";\nexport function Btn() { return <button onClick={save}>OK</button>; }\n' },
|
|
11
|
+
{ file: 'mod.js', wasm: 'tree-sitter-javascript.wasm', code: 'import fs from "fs";\nfunction run() { return fs.readFileSync("a"); }\n' },
|
|
12
|
+
{ file: 'app.py', wasm: 'tree-sitter-python.wasm', code: 'import os\nclass Repo:\n def run(self):\n return os.getcwd()\n' },
|
|
13
|
+
{ file: 'main.go', wasm: 'tree-sitter-go.wasm', code: 'package main\nimport "fmt"\ntype Server struct{}\nfunc (s *Server) Start() { fmt.Println("ok") }\n' },
|
|
14
|
+
{ file: 'lib.rs', wasm: 'tree-sitter-rust.wasm', code: 'use std::fs;\nstruct Config { port: u16 }\nfn start() { println!("hi"); }\n' },
|
|
15
|
+
{ file: 'Pay.java', wasm: 'tree-sitter-java.wasm', code: 'import java.util.List;\npublic class Pay { public void charge() { log(); } }\n' },
|
|
16
|
+
{ file: 'Auth.cs', wasm: 'tree-sitter-c_sharp.wasm', code: 'using System;\npublic class Auth { public void Login() { Console.WriteLine("ok"); } }\n' },
|
|
17
|
+
{ file: 'Controller.php', wasm: 'tree-sitter-php.wasm', code: '<?php\nuse App\\Service;\nclass Controller { public function index() { return view(); } }\n' },
|
|
18
|
+
{ file: 'Repo.kt', wasm: 'tree-sitter-kotlin.wasm', code: 'import kotlin.math.max\nclass Repo { fun load() { println("ok") } }\n' },
|
|
19
|
+
{ file: 'Auth.swift', wasm: 'tree-sitter-swift.wasm', code: 'import Foundation\nprotocol AuthProto { func verify() }\nclass Auth: AuthProto { func verify() { print("ok") } }\n' },
|
|
20
|
+
{ file: 'repo.dart', wasm: 'tree-sitter-dart.wasm', code: 'import "package:app/main.dart";\nclass UserRepo { void fetchUser() { print("ok"); } }\n' },
|
|
21
|
+
{ file: 'worker.rb', wasm: 'tree-sitter-ruby.wasm', code: 'require "json"\nclass Worker\n def perform(x)\n puts JSON.generate(x)\n end\nend\n' },
|
|
22
|
+
{ file: 'math.c', wasm: 'tree-sitter-c.wasm', code: '#include <stdio.h>\nstruct User { int id; };\nint add(int a, int b) { return printf("%d", a + b); }\n' },
|
|
23
|
+
{ file: 'svc.cpp', wasm: 'tree-sitter-cpp.wasm', code: '#include <vector>\nclass Service { public: int run() { return helper(); } };\n' },
|
|
24
|
+
{ file: 'auth.m', wasm: 'tree-sitter-objc.wasm', code: '#import <Foundation/Foundation.h>\n@implementation Auth\n- (void)login { [self check]; }\n@end\n' },
|
|
25
|
+
{ file: 'Card.vue', wasm: 'tree-sitter-vue.wasm', code: '<template><div class="card"><span>{{ msg }}</span></div></template><script>export default { name: "Card" }</script>\n' },
|
|
26
|
+
{ file: 'Vault.sol', wasm: 'tree-sitter-solidity.wasm', code: 'pragma solidity ^0.8.20;\nimport "./IERC20.sol";\ncontract Vault { function withdraw() public { check(); } }\n' },
|
|
27
|
+
{ file: 'App.scala', wasm: 'tree-sitter-scala.wasm', code: 'import scala.util.Try\nobject App { def main(args: Array[String]): Unit = println("hi") }\n' },
|
|
28
|
+
{ file: 'user.ex', wasm: 'tree-sitter-elixir.wasm', code: 'defmodule App.User do\n import Enum\n def greet(name), do: IO.puts(name)\nend\n' },
|
|
29
|
+
{ file: 'Main.elm', wasm: 'tree-sitter-elm.wasm', code: 'module Main exposing (main)\nimport Html exposing (text)\ngreet name = text name\n' },
|
|
30
|
+
{ file: 'lib.ml', wasm: 'tree-sitter-ocaml.wasm', code: 'open Printf\nlet greet name = printf "%s" name\n' },
|
|
31
|
+
{ file: 'init.lua', wasm: 'tree-sitter-lua.wasm', code: 'local function parse(x) return decode(x) end\n' },
|
|
32
|
+
{ file: 'init.el', wasm: 'tree-sitter-elisp.wasm', code: '(require \'cl-lib)\n(defun greet (name) (message "Hello %s" name))\n' },
|
|
33
|
+
{ file: 'Auth.res', wasm: 'tree-sitter-rescript.wasm', code: 'open Belt\nlet compute = (x) => Js.log(x)\nmodule Auth = { let check = () => true }\n' },
|
|
34
|
+
{ file: 'sink.ql', wasm: 'tree-sitter-ql.wasm', code: 'import javascript\npredicate isSink(Expr e) { e.toString() = "eval" }\n' },
|
|
35
|
+
{ file: 'Lock.tla', wasm: 'tree-sitter-tlaplus.wasm', code: '---- MODULE Lock ----\nEXTENDS Naturals\nVARIABLE x\nInit == x = 0\n====\n' },
|
|
36
|
+
{ file: 'top.rdl', wasm: 'tree-sitter-systemrdl.wasm', code: 'addrmap top_map {\n reg ctrl_reg { field { sw = rw; } en[1]; };\n};\n' },
|
|
37
|
+
{ file: 'main.zig', wasm: 'tree-sitter-zig.wasm', code: 'const std = @import("std");\npub fn main() void { std.debug.print("hi", .{}); }\n' },
|
|
38
|
+
{ file: 'view.erb', wasm: 'tree-sitter-embedded_template.wasm', code: '<%= render_partial("header") %>\n' },
|
|
39
|
+
{ file: 'ci.yml', wasm: 'tree-sitter-yaml.wasm', code: 'name: ci\non:\n push:\n branches: [main]\njobs:\n build:\n runs-on: ubuntu-latest\n' },
|
|
40
|
+
{ file: 'deploy.sh', wasm: 'tree-sitter-bash.wasm', code: 'deploy_app() { echo "deploying"; }\ndeploy_app\n' },
|
|
41
|
+
{ file: 'index.html', wasm: 'tree-sitter-html.wasm', code: '<div class="app"><script src="app.js"></script><button id="save">Go</button></div>\n' },
|
|
42
|
+
{ file: 'site.css', wasm: 'tree-sitter-css.wasm', code: '@import "base.css";\n.btn-primary { color: red; }\n' },
|
|
43
|
+
{ file: 'pkg.json', wasm: 'tree-sitter-json.wasm', code: '{"name": "codepulse", "scripts": {"build": "tsc"}}\n' },
|
|
44
|
+
{ file: 'Cargo.toml', wasm: 'tree-sitter-toml.wasm', code: '[package]\nname = "codepulse"\nversion = "3.1.0"\n' },
|
|
45
|
+
{ file: 'schema.sql', code: 'CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL);\n' }
|
|
46
|
+
];
|
|
47
|
+
test('EXT_TO_LANGUAGE maps every bundled tree-sitter-wasms grammar without missing entries', async () => {
|
|
48
|
+
const wasmDir = TreeSitterGraphIndexer.resolveWasmDir();
|
|
49
|
+
assert.ok(wasmDir, 'tree-sitter-wasms out directory resolved');
|
|
50
|
+
const onDiskWasms = (await fs.readdir(wasmDir)).filter((f) => f.endsWith('.wasm') && f !== 'tree-sitter.wasm');
|
|
51
|
+
const mappedWasms = new Set(Object.values(EXT_TO_LANGUAGE).map((m) => m.wasm).filter(Boolean));
|
|
52
|
+
for (const w of onDiskWasms) {
|
|
53
|
+
assert.ok(mappedWasms.has(w), `Missing EXT_TO_LANGUAGE mapping for bundled grammar ${w}`);
|
|
54
|
+
}
|
|
55
|
+
assert.equal(onDiskWasms.length, 36);
|
|
56
|
+
});
|
|
57
|
+
test('TreeSitterGraphIndexer parses and extracts real symbols across all 36 WASM grammars + SQL', async () => {
|
|
58
|
+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cp-all-wasm-'));
|
|
59
|
+
const indexDistUrl = new URL('../index.js', import.meta.url).href;
|
|
60
|
+
try {
|
|
61
|
+
// Run in bounded batches of 5 languages per child process so large multi-MB WebAssembly grammars stay well under V8 Zone limits
|
|
62
|
+
const batchSize = 5;
|
|
63
|
+
for (let start = 0, idx = 0; start < LANGUAGE_SAMPLES.length; start += batchSize, idx++) {
|
|
64
|
+
const batch = LANGUAGE_SAMPLES.slice(start, start + batchSize);
|
|
65
|
+
const batchDir = path.join(tmpDir, `batch-${idx}`);
|
|
66
|
+
await fs.mkdir(batchDir, { recursive: true });
|
|
67
|
+
for (const s of batch) {
|
|
68
|
+
await fs.writeFile(path.join(batchDir, s.file), s.code, 'utf8');
|
|
69
|
+
}
|
|
70
|
+
const runnerScript = path.join(tmpDir, `run-${idx}.mjs`);
|
|
71
|
+
await fs.writeFile(runnerScript, `import assert from 'node:assert/strict';
|
|
72
|
+
import path from 'node:path';
|
|
73
|
+
import { CodePulseDatabase, TreeSitterGraphIndexer } from ${JSON.stringify(indexDistUrl)};
|
|
74
|
+
|
|
75
|
+
const batchDir = ${JSON.stringify(batchDir)};
|
|
76
|
+
const files = ${JSON.stringify(batch.map((b) => b.file))};
|
|
77
|
+
const db = new CodePulseDatabase(path.join(batchDir, 'cp.db'));
|
|
78
|
+
try {
|
|
79
|
+
const repo = db.upsertRepo({ name: 'polyglot', localPath: batchDir });
|
|
80
|
+
const indexer = new TreeSitterGraphIndexer(db);
|
|
81
|
+
const summary = await indexer.indexRepository(repo.id, batchDir, files);
|
|
82
|
+
assert.equal(summary.reindexedFiles, files.length);
|
|
83
|
+
const nodes = db.getAstNodesForRepo(repo.id);
|
|
84
|
+
for (const f of files) {
|
|
85
|
+
const fileNodes = nodes.filter((n) => n.file === f);
|
|
86
|
+
assert.ok(fileNodes.length > 1, \`Expected symbols beyond module node for \${f}, got \${fileNodes.length}\`);
|
|
87
|
+
}
|
|
88
|
+
} finally {
|
|
89
|
+
db.close();
|
|
90
|
+
}
|
|
91
|
+
`, 'utf8');
|
|
92
|
+
const res = spawnSync(process.execPath, [runnerScript], { encoding: 'utf8' });
|
|
93
|
+
assert.equal(res.status, 0, `Batch ${idx} (${batch.map((b) => b.file).join(', ')}) failed:\nSTDOUT: ${res.stdout}\nSTDERR: ${res.stderr}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
test('Structural AST .scm queries flag real sinks across JS/TS/TSX/Python/Go and ignore comments', async () => {
|
|
101
|
+
const tsBad = [
|
|
102
|
+
'// Comment mentioning db.query(`SELECT * FROM users WHERE id = ${id}`) and innerHTML = bad',
|
|
103
|
+
'async function handler(req, res, db) {',
|
|
104
|
+
' const rows = await db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);',
|
|
105
|
+
' el.innerHTML = req.body.bio;',
|
|
106
|
+
' if (req.headers["x-sig"] === expectedSignature) {}',
|
|
107
|
+
' try { await db.save(rows); } catch (err) {}',
|
|
108
|
+
' db.update(rows);',
|
|
109
|
+
' return rows;',
|
|
110
|
+
'}'
|
|
111
|
+
].join('\n');
|
|
112
|
+
const tsDiags = await runAstQueryRules('routes/auth.ts', tsBad);
|
|
113
|
+
const ids = new Set(tsDiags.map((d) => d.ruleId));
|
|
114
|
+
assert.ok(ids.has('CP-AST-SQLI-TEMPLATE'), 'Expected CP-AST-SQLI-TEMPLATE');
|
|
115
|
+
assert.ok(ids.has('CP-AST-XSS-INNERHTML'), 'Expected CP-AST-XSS-INNERHTML');
|
|
116
|
+
assert.ok(ids.has('CP-AST-TIMING-COMPARE'), 'Expected CP-AST-TIMING-COMPARE');
|
|
117
|
+
assert.ok(ids.has('CP-AST-EMPTY-CATCH'), 'Expected CP-AST-EMPTY-CATCH');
|
|
118
|
+
assert.ok(ids.has('CP-AST-UNAWAITED-MUTATION'), 'Expected CP-AST-UNAWAITED-MUTATION');
|
|
119
|
+
// Ensure line 1 comment was ignored!
|
|
120
|
+
assert.equal(tsDiags.some((d) => d.lineStart === 1), false, 'Comment line must never trigger AST queries');
|
|
121
|
+
const tsxBad = `import React, { useEffect } from 'react';
|
|
122
|
+
export function Widget({ html }) {
|
|
123
|
+
useEffect(() => { window.addEventListener('resize', () => {}); }, []);
|
|
124
|
+
return <div dangerouslySetInnerHTML={{ __html: html }} />;
|
|
125
|
+
}`;
|
|
126
|
+
const tsxDiags = await runAstQueryRules('components/Widget.tsx', tsxBad);
|
|
127
|
+
assert.ok(tsxDiags.some((d) => d.ruleId === 'CP-AST-REACT-USEEFFECT'));
|
|
128
|
+
assert.ok(tsxDiags.some((d) => d.ruleId === 'CP-AST-XSS-DANGEROUSLY'));
|
|
129
|
+
const pyBad = `import subprocess, yaml, pickle
|
|
130
|
+
def run_job(cmd, payload, cursor, user_id):
|
|
131
|
+
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
|
|
132
|
+
subprocess.run(cmd, shell=True)
|
|
133
|
+
yaml.load(payload)
|
|
134
|
+
pickle.loads(payload)
|
|
135
|
+
try:
|
|
136
|
+
do_work()
|
|
137
|
+
except Exception:
|
|
138
|
+
pass
|
|
139
|
+
`;
|
|
140
|
+
const pyDiags = await runAstQueryRules('jobs/worker.py', pyBad);
|
|
141
|
+
const pyIds = new Set(pyDiags.map((d) => d.ruleId));
|
|
142
|
+
assert.ok(pyIds.has('CP-AST-SQLI-PY-FSTRING'));
|
|
143
|
+
assert.ok(pyIds.has('CP-AST-CMD-PY-SHELL'));
|
|
144
|
+
assert.ok(pyIds.has('CP-AST-INSECURE-YAML'));
|
|
145
|
+
assert.ok(pyIds.has('CP-AST-PICKLE-LOADS'));
|
|
146
|
+
assert.ok(pyIds.has('CP-AST-PY-BARE-EXCEPT'));
|
|
147
|
+
const goBad = `package main
|
|
148
|
+
import ("fmt"; "os/exec")
|
|
149
|
+
func handler(db any, id string) {
|
|
150
|
+
q := fmt.Sprintf("SELECT * FROM accounts WHERE id = %s", id)
|
|
151
|
+
_ = exec.Command("sh", "-c", q)
|
|
152
|
+
}`;
|
|
153
|
+
const goDiags = await runAstQueryRules('cmd/server.go', goBad);
|
|
154
|
+
const goIds = new Set(goDiags.map((d) => d.ruleId));
|
|
155
|
+
assert.ok(goIds.has('CP-AST-SQLI-GO-SPRINTF'));
|
|
156
|
+
assert.ok(goIds.has('CP-AST-CMD-GO-SH'));
|
|
157
|
+
});
|
|
158
|
+
//# sourceMappingURL=all-wasm-languages.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"all-wasm-languages.test.js","sourceRoot":"","sources":["../../src/__tests__/all-wasm-languages.test.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,MAAM,MAAM,oBAAoB,CAAC;AACxC,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAErB,MAAM,gBAAgB,GAAyD;IAC7E,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,6BAA6B,EAAE,IAAI,EAAE,4EAA4E,EAAE;IAC3I,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,sBAAsB,EAAE,IAAI,EAAE,oGAAoG,EAAE;IAC9J,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,6BAA6B,EAAE,IAAI,EAAE,yEAAyE,EAAE;IACxI,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,yBAAyB,EAAE,IAAI,EAAE,0EAA0E,EAAE;IACrI,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB,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C,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;IACpD,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;IAC5C,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;IAC7C,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;IAC5C,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC,CAAC;IAE9C,MAAM,KAAK,GAAG;;;;;EAKd,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,gBAAgB,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;IACpD,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAC3C,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"v3-architecture.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/v3-architecture.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { ByokAiClient, CodePulseDatabase, PrivacyFirewall, TreeSitterGraphIndexer, buildGuidedWalkthrough, buildValidatedReviewOutput, detectAiSlopAndHallucinations, estimateScanBudget, filterFindingsByBaseline, renderSarifReport, upsertBaselineSuppression, verifyTeamBaseline } from '../index.js';
|
|
7
|
+
test('PrivacyFirewall deterministically tokenizes secrets/JWTs/DB URIs/emails/IPs before any external AI call', async () => {
|
|
8
|
+
const fw = new PrivacyFirewall();
|
|
9
|
+
const sampleSecret = ['ghp_', 'AbCdEf1234567890GhIjKlMnOpQrStUv'].join('');
|
|
10
|
+
const sampleJwt = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIn0.signaturePayloadXYZ123';
|
|
11
|
+
const prompt = `Inspect key=${sampleSecret} token=${sampleJwt} db=postgres://admin:pass@db.internal:5432/prod ip=10.24.18.9 contact=sec@acme.io`;
|
|
12
|
+
const res = fw.redact(prompt);
|
|
13
|
+
assert.equal(res.redacted.includes(sampleSecret), false);
|
|
14
|
+
assert.equal(res.redacted.includes(sampleJwt), false);
|
|
15
|
+
assert.equal(res.redacted.includes('postgres://admin:pass'), false);
|
|
16
|
+
assert.equal(res.redacted.includes('10.24.18.9'), false);
|
|
17
|
+
assert.equal(res.redacted.includes('sec@acme.io'), false);
|
|
18
|
+
assert.match(res.redacted, /\[REDACTED_SECRET_\d+\]/);
|
|
19
|
+
assert.match(res.redacted, /\[REDACTED_JWT_\d+\]/);
|
|
20
|
+
assert.match(res.redacted, /\[REDACTED_DB_URI_\d+\]/);
|
|
21
|
+
// Wire into ByokAiClient with fallbackProvider on HTTP 429
|
|
22
|
+
let calls = 0;
|
|
23
|
+
let capturedPrompt = '';
|
|
24
|
+
const client = new ByokAiClient({
|
|
25
|
+
provider: 'openai',
|
|
26
|
+
apiKey: ['sk-', 'test12345678901234567890'].join(''),
|
|
27
|
+
model: 'gpt-4.1',
|
|
28
|
+
maxRetries: 0,
|
|
29
|
+
privacyFirewall: true,
|
|
30
|
+
fallbackProvider: {
|
|
31
|
+
provider: 'ollama',
|
|
32
|
+
model: 'qwen2.5-coder:14b'
|
|
33
|
+
},
|
|
34
|
+
fetchImpl: (async (_url, init) => {
|
|
35
|
+
calls++;
|
|
36
|
+
capturedPrompt = String(init?.body ?? '');
|
|
37
|
+
if (calls === 1) {
|
|
38
|
+
return new Response('rate limited', { status: 429 });
|
|
39
|
+
}
|
|
40
|
+
return new Response(JSON.stringify({ choices: [{ message: { content: 'fallback ok' } }], usage: { total_tokens: 42 } }), { status: 200, headers: { 'Content-Type': 'application/json' } });
|
|
41
|
+
})
|
|
42
|
+
});
|
|
43
|
+
const out = await client.complete({ systemPrompt: 'Audit cleanly', userPrompt: prompt });
|
|
44
|
+
assert.equal(out.usedFallback, true);
|
|
45
|
+
assert.equal(out.provider, 'ollama');
|
|
46
|
+
assert.ok(out.redactedItemsCount && out.redactedItemsCount >= 4);
|
|
47
|
+
assert.equal(capturedPrompt.includes(sampleSecret), false);
|
|
48
|
+
});
|
|
49
|
+
test('estimateScanBudget computes deterministic tokens, USD cost, and local free zero-cost estimate', () => {
|
|
50
|
+
const proEst = estimateScanBudget({
|
|
51
|
+
filesCount: 24,
|
|
52
|
+
totalBytes: 180_000,
|
|
53
|
+
mode: 'debate',
|
|
54
|
+
provider: 'gemini',
|
|
55
|
+
model: 'gemini-2.5-pro'
|
|
56
|
+
});
|
|
57
|
+
assert.ok(proEst.estimatedTotalTokens > 0);
|
|
58
|
+
assert.ok(proEst.estimatedCostUsd > 0);
|
|
59
|
+
assert.equal(proEst.isLocalFree, false);
|
|
60
|
+
const localEst = estimateScanBudget({
|
|
61
|
+
filesCount: 24,
|
|
62
|
+
totalBytes: 180_000,
|
|
63
|
+
mode: 'fast',
|
|
64
|
+
provider: 'ollama',
|
|
65
|
+
model: 'qwen2.5-coder:14b'
|
|
66
|
+
});
|
|
67
|
+
assert.equal(localEst.isLocalFree, true);
|
|
68
|
+
assert.equal(localEst.estimatedCostUsd, 0);
|
|
69
|
+
});
|
|
70
|
+
test('detectAiSlopAndHallucinations flags phantom imports, missing npm pkgs, and placeholder stubs', async () => {
|
|
71
|
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cp-slop-'));
|
|
72
|
+
try {
|
|
73
|
+
await fs.writeFile(path.join(dir, 'package.json'), JSON.stringify({ dependencies: { zod: '^4.0.0' } }), 'utf8');
|
|
74
|
+
await fs.mkdir(path.join(dir, 'src'), { recursive: true });
|
|
75
|
+
await fs.writeFile(path.join(dir, 'src', 'service.ts'), [
|
|
76
|
+
"import { missingFn } from './helpers';",
|
|
77
|
+
"import { ghost } from './does-not-exist';",
|
|
78
|
+
"import imaginary from 'nonexistent-hallucinated-pkg';",
|
|
79
|
+
'export function processOrder() {',
|
|
80
|
+
' // TODO: implement refund',
|
|
81
|
+
" throw new Error('Not implemented');",
|
|
82
|
+
'}'
|
|
83
|
+
].join('\n'), 'utf8');
|
|
84
|
+
await fs.writeFile(path.join(dir, 'src', 'helpers.ts'), 'export function realHelper() { return 1; }\n', 'utf8');
|
|
85
|
+
const db = new CodePulseDatabase(path.join(dir, 'cp.db'));
|
|
86
|
+
const repo = db.upsertRepo({ name: 'slop-test', localPath: dir });
|
|
87
|
+
const indexer = new TreeSitterGraphIndexer(db);
|
|
88
|
+
await indexer.indexRepository(repo.id, dir, ['src/service.ts', 'src/helpers.ts']);
|
|
89
|
+
const diags = await detectAiSlopAndHallucinations({
|
|
90
|
+
repoPath: dir,
|
|
91
|
+
files: ['src/service.ts', 'src/helpers.ts'],
|
|
92
|
+
astNodes: db.getAstNodesForRepo(repo.id)
|
|
93
|
+
});
|
|
94
|
+
const ids = new Set(diags.map((d) => d.ruleId));
|
|
95
|
+
assert.ok(ids.has('CP-SLOP-PHANTOM-IMPORT'));
|
|
96
|
+
assert.ok(ids.has('CP-SLOP-PHANTOM-SYMBOL'));
|
|
97
|
+
assert.ok(ids.has('CP-SLOP-PHANTOM-PKG'));
|
|
98
|
+
assert.ok(ids.has('CP-SLOP-PLACEHOLDER-TODO'));
|
|
99
|
+
assert.ok(ids.has('CP-SLOP-NOT-IMPLEMENTED'));
|
|
100
|
+
db.close();
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
test('SARIF v2.1.0 writer, signed team baseline, Security Trends DB, and Guided Walkthrough work end-to-end', async () => {
|
|
107
|
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cp-sarif-base-'));
|
|
108
|
+
try {
|
|
109
|
+
const db = new CodePulseDatabase(path.join(dir, 'cp.db'));
|
|
110
|
+
const repo = db.upsertRepo({ name: 'demo', localPath: dir });
|
|
111
|
+
const finding = {
|
|
112
|
+
id: 'f-1',
|
|
113
|
+
severity: 'high',
|
|
114
|
+
confidence: 0.92,
|
|
115
|
+
category: 'security',
|
|
116
|
+
title: '[CWE-89] Dynamic SQL query',
|
|
117
|
+
body: 'Interpolated template query inside handler.',
|
|
118
|
+
file: 'src/routes/users.ts',
|
|
119
|
+
line_start: 14,
|
|
120
|
+
line_end: 16,
|
|
121
|
+
rule_id: 'CP-AST-SQLI-TEMPLATE',
|
|
122
|
+
source: 'sast',
|
|
123
|
+
reachability: 'external_reachable',
|
|
124
|
+
call_path: ['POST /users', 'usersHandler', 'db.query'],
|
|
125
|
+
compliance_tags: ['OWASP-ASVS-5.3'],
|
|
126
|
+
blast_radius: { risk_score: 72, direct_callers: [], affected_tests: [], impacted_files: [] },
|
|
127
|
+
recommendation: 'Use parameterized bindings.',
|
|
128
|
+
patch_suggestion: 'db.query("SELECT * FROM users WHERE id = $1", [id])',
|
|
129
|
+
status: 'open'
|
|
130
|
+
};
|
|
131
|
+
const output = buildValidatedReviewOutput('Audit summary', [finding], []);
|
|
132
|
+
const sarif = renderSarifReport(output, { toolVersion: '3.1.0' });
|
|
133
|
+
assert.equal(sarif.version, '2.1.0');
|
|
134
|
+
assert.equal(sarif.runs[0].results.length, 1);
|
|
135
|
+
assert.equal(sarif.runs[0].tool.driver.rules.length, 1);
|
|
136
|
+
// Baseline suppression + integrity verification
|
|
137
|
+
await upsertBaselineSuppression(dir, {
|
|
138
|
+
finding,
|
|
139
|
+
reason: 'False positive verified',
|
|
140
|
+
reviewer: 'sec-lead'
|
|
141
|
+
});
|
|
142
|
+
const verified = await verifyTeamBaseline(dir);
|
|
143
|
+
assert.equal(verified.validIntegrity, true);
|
|
144
|
+
assert.equal(verified.activeCount, 1);
|
|
145
|
+
const filtered = await filterFindingsByBaseline(dir, [finding]);
|
|
146
|
+
assert.equal(filtered.suppressedCount, 1);
|
|
147
|
+
assert.equal(filtered.findings.length, 0);
|
|
148
|
+
// Security Trends DB metrics
|
|
149
|
+
const job = db.createJob({ repoId: repo.id, target: 'local_uncommitted', mode: 'debate' });
|
|
150
|
+
db.saveFindings(job.id, repo.id, [finding]);
|
|
151
|
+
db.updateFindingStatus(finding.id, 'verified_fixed');
|
|
152
|
+
db.recordPulseScore({ repoId: repo.id, jobId: job.id, findings: [] });
|
|
153
|
+
const trends = db.getSecurityTrends(repo.id, 90);
|
|
154
|
+
assert.equal(trends.fixedCount, 1);
|
|
155
|
+
assert.equal(trends.latestPulseScore, 100);
|
|
156
|
+
assert.equal(trends.series.length, 1);
|
|
157
|
+
// Guided Walkthrough Ordering
|
|
158
|
+
const groups = buildGuidedWalkthrough(['src/ui/Card.tsx', 'migrations/001.sql', 'src/routes/pay.ts', 'src/core/calc.ts', 'src/__tests__/calc.test.ts']);
|
|
159
|
+
assert.equal(groups.length, 5);
|
|
160
|
+
assert.equal(groups[0].layer, 'schema');
|
|
161
|
+
assert.equal(groups[4].layer, 'tests-config');
|
|
162
|
+
db.close();
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
//# sourceMappingURL=v3-architecture.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"v3-architecture.test.js","sourceRoot":"","s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ot":"","sources":["../../src/__tests__/v3.1-intelligence.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import test from 'node:test';
|
|
6
|
+
import { CodePulseDatabase, PrivacyFirewall, SECRET_SIGNATURE_RULES, TreeSitterGraphIndexer, analyzeDeadCodeAndUnusedDeps, applyAstGrepFix, applySearchReplaceBlocks, buildDataExposureMap, classifySensitiveDataForFinding, compressContextDeterministic, computeWeightedPageRank, createPreFixSnapshot, detectArchitectureLayerViolations, detectCircularDependencies, detectRepoFormattingStyle, generateProjectDocs, generateProjectSbom, getSymbolCallHierarchy, parseCodePulseYamlConfig, parseSearchReplaceBlocks, renderExecutiveAuditHtml, renderRepoPageRankMap, restorePreFixSnapshot, runAstGrepRulesOnFile, runDeepIacScanner, runOxlintOnFiles, scanSecretsWithRegistry } from '../index.js';
|
|
7
|
+
import { runCommand } from '../utils/process.js';
|
|
8
|
+
test('v3.1.0 Weighted PageRank RepoMap, Symbol Hierarchy, Repomix Compression & Interactive Mermaid Docs', async () => {
|
|
9
|
+
const tmpRepo = await fs.mkdtemp(path.join(os.tmpdir(), 'cp-v31-p1-'));
|
|
10
|
+
const db = new CodePulseDatabase(':memory:');
|
|
11
|
+
try {
|
|
12
|
+
await fs.mkdir(path.join(tmpRepo, 'src', 'routes'), { recursive: true });
|
|
13
|
+
await fs.mkdir(path.join(tmpRepo, 'src', 'services'), { recursive: true });
|
|
14
|
+
await fs.mkdir(path.join(tmpRepo, 'src', 'db'), { recursive: true });
|
|
15
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'db', 'users.ts'), `export function findUserById(id: string) { return { id }; }\nexport function unusedDbFn() { return 0; }\n`, 'utf8');
|
|
16
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'services', 'authService.ts'), `import { findUserById } from '../db/users.js';\nexport function authenticateUser(id: string) {\n return findUserById(id);\n}\n`, 'utf8');
|
|
17
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'routes', 'authRoute.ts'), `import { authenticateUser } from '../services/authService.js';\n// POST /api/login\nexport function postLogin(req: { id: string }) {\n return authenticateUser(req.id);\n}\n`, 'utf8');
|
|
18
|
+
const repo = db.upsertRepo({ name: 'v31-demo', localPath: tmpRepo });
|
|
19
|
+
await new TreeSitterGraphIndexer(db).indexRepository(repo.id, tmpRepo);
|
|
20
|
+
const nodes = db.getAstNodesForRepo(repo.id);
|
|
21
|
+
const edges = db.getAstEdgesForRepo(repo.id);
|
|
22
|
+
const ranked = computeWeightedPageRank(nodes, edges);
|
|
23
|
+
assert.ok(ranked.length >= 3);
|
|
24
|
+
assert.ok(ranked[0].normalizedScore > 0);
|
|
25
|
+
const repoMap = renderRepoPageRankMap(nodes, edges, { maxFiles: 10, maxTokens: 2000 });
|
|
26
|
+
assert.ok(repoMap.mapText.includes('Weighted PageRank RepoMap'));
|
|
27
|
+
assert.ok(repoMap.estimatedTokens > 0);
|
|
28
|
+
const hierarchy = getSymbolCallHierarchy(nodes, edges, 'findUserById', 3);
|
|
29
|
+
assert.ok(hierarchy.definitions.length >= 1);
|
|
30
|
+
assert.ok(hierarchy.callers.some((c) => c.callerFile.includes('authService.ts')));
|
|
31
|
+
const fakeSecret = ['ghp_', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'].join('');
|
|
32
|
+
const compressed = compressContextDeterministic([
|
|
33
|
+
{
|
|
34
|
+
file: 'src/routes/authRoute.ts',
|
|
35
|
+
content: `/* huge banner\n boilerplate comment block\n more text */\n\n\nexport const tok = "${fakeSecret}";\n\n\nexport function ok() { return 1; }\n`,
|
|
36
|
+
rankScore: 95
|
|
37
|
+
}
|
|
38
|
+
]);
|
|
39
|
+
assert.equal(compressed.compressedText.includes(fakeSecret), false);
|
|
40
|
+
assert.ok(compressed.firewallRedactions >= 1);
|
|
41
|
+
assert.ok(compressed.compressionRatio >= 1);
|
|
42
|
+
const docs = await generateProjectDocs({ db, repoId: repo.id, repoPath: tmpRepo, repoName: 'v31-demo' });
|
|
43
|
+
assert.ok(docs.architectureMd.includes('call codepulseOpenFromDiagram'));
|
|
44
|
+
assert.ok(docs.sequenceDiagramMd.includes('sequenceDiagram'));
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
db.close();
|
|
48
|
+
await fs.rm(tmpRepo, { recursive: true, force: true });
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
test('v3.1.0 Circular Deps, Layer Boundaries, Knip Dead Code, 155+ Secrets, @ast-grep/napi & oxlint', async () => {
|
|
52
|
+
const tmpRepo = await fs.mkdtemp(path.join(os.tmpdir(), 'cp-v31-p3-'));
|
|
53
|
+
const db = new CodePulseDatabase(':memory:');
|
|
54
|
+
try {
|
|
55
|
+
await fs.mkdir(path.join(tmpRepo, 'src', 'ui'), { recursive: true });
|
|
56
|
+
await fs.mkdir(path.join(tmpRepo, 'src', 'db'), { recursive: true });
|
|
57
|
+
await fs.mkdir(path.join(tmpRepo, 'src', 'orphan'), { recursive: true });
|
|
58
|
+
await fs.mkdir(path.join(tmpRepo, '.codepulse', 'ast-rules'), { recursive: true });
|
|
59
|
+
await fs.writeFile(path.join(tmpRepo, 'package.json'), JSON.stringify({ name: 'layer-demo', main: 'src/index.ts', dependencies: { 'unused-leftpad-pkg': '^1.0.0' } }), 'utf8');
|
|
60
|
+
await fs.writeFile(path.join(tmpRepo, '.codepulse.yml'), `privacy_firewall: true
|
|
61
|
+
architecture:
|
|
62
|
+
forbidCircular: true
|
|
63
|
+
rules:
|
|
64
|
+
- name: no-ui-to-db
|
|
65
|
+
from: "^src/ui/"
|
|
66
|
+
to: "^src/db/"
|
|
67
|
+
`, 'utf8');
|
|
68
|
+
await fs.writeFile(path.join(tmpRepo, '.prettierrc'), JSON.stringify({ singleQuote: false, semi: false, tabWidth: 4 }), 'utf8');
|
|
69
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'index.ts'), `import './ui/panel.js';\nexport const boot = 1;\n`, 'utf8');
|
|
70
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'ui', 'panel.ts'), `import { dbQuery } from '../db/client.js';\nimport { cycleB } from '../db/cycle.js';\nexport function render(el: HTMLElement, val: string) {\n el.innerHTML = val;\n return dbQuery() + cycleB();\n}\n`, 'utf8');
|
|
71
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'db', 'client.ts'), `export function dbQuery() { return 1; }\n`, 'utf8');
|
|
72
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'db', 'cycle.ts'), `import { render } from '../ui/panel.js';\nexport function cycleB() { return typeof render === 'function' ? 2 : 0; }\n`, 'utf8');
|
|
73
|
+
await fs.writeFile(path.join(tmpRepo, 'src', 'orphan', 'deadModule.ts'), `export function neverCalledSymbol() { return 42; }\n`, 'utf8');
|
|
74
|
+
const cfg = parseCodePulseYamlConfig(await fs.readFile(path.join(tmpRepo, '.codepulse.yml'), 'utf8'));
|
|
75
|
+
assert.equal(cfg.architecture.forbidCircular, true);
|
|
76
|
+
assert.equal(cfg.architecture.rules[0]?.name, 'no-ui-to-db');
|
|
77
|
+
const fmt = await detectRepoFormattingStyle(tmpRepo);
|
|
78
|
+
assert.equal(fmt.tool, 'prettier');
|
|
79
|
+
assert.equal(fmt.singleQuote, false);
|
|
80
|
+
assert.equal(fmt.tabWidth, 4);
|
|
81
|
+
const repo = db.upsertRepo({ name: 'layer-demo', localPath: tmpRepo });
|
|
82
|
+
await new TreeSitterGraphIndexer(db).indexRepository(repo.id, tmpRepo);
|
|
83
|
+
const nodes = db.getAstNodesForRepo(repo.id);
|
|
84
|
+
const edges = db.getAstEdgesForRepo(repo.id);
|
|
85
|
+
const cycles = detectCircularDependencies(nodes, edges);
|
|
86
|
+
assert.ok(cycles.length >= 1, 'Expected ui/panel <-> db/cycle cycle');
|
|
87
|
+
const archRes = await detectArchitectureLayerViolations({ repoPath: tmpRepo, nodes, edges });
|
|
88
|
+
assert.ok(archRes.violations.some((v) => v.ruleName === 'no-ui-to-db'));
|
|
89
|
+
const knip = await analyzeDeadCodeAndUnusedDeps(tmpRepo, nodes, edges);
|
|
90
|
+
assert.ok(knip.orphanedFiles.includes('src/orphan/deadModule.ts'));
|
|
91
|
+
assert.ok(knip.unusedExports.some((u) => u.symbol === 'neverCalledSymbol'));
|
|
92
|
+
assert.ok(knip.unusedDependencies.some((d) => d.dependency === 'unused-leftpad-pkg'));
|
|
93
|
+
// 155+ Secret Registry + PrivacyFirewall
|
|
94
|
+
assert.ok(SECRET_SIGNATURE_RULES.length >= 150);
|
|
95
|
+
const stripeKey = ['sk_live_', '51NabcDEFghiJKLmnoPQRstuVWXyz123456'].join('');
|
|
96
|
+
const secDiags = scanSecretsWithRegistry('src/payments.ts', `const k = "${stripeKey}";`);
|
|
97
|
+
assert.ok(secDiags.some((d) => d.ruleId === 'CP-SEC-STR-001'));
|
|
98
|
+
const fw = new PrivacyFirewall();
|
|
99
|
+
assert.equal(fw.redact(`const k = "${stripeKey}";`).redacted.includes(stripeKey), false);
|
|
100
|
+
// @ast-grep/napi search & rewrite
|
|
101
|
+
const sgSample = `el.innerHTML = userBio;\nconst x = JSON.parse(JSON.stringify(obj));\n`;
|
|
102
|
+
const sgDiags = await runAstGrepRulesOnFile('src/ui/panel.ts', sgSample);
|
|
103
|
+
if (sgDiags.length > 0) {
|
|
104
|
+
assert.ok(sgDiags.some((d) => d.ruleId === 'CP-SG-002' || d.ruleId === 'CP-SG-004'));
|
|
105
|
+
const rewrite = await applyAstGrepFix('src/ui/panel.ts', sgSample, {
|
|
106
|
+
pattern: 'JSON.parse(JSON.stringify($OBJ))',
|
|
107
|
+
fix: 'structuredClone($OBJ)'
|
|
108
|
+
});
|
|
109
|
+
assert.ok(rewrite.updatedContent.includes('structuredClone(obj)'));
|
|
110
|
+
}
|
|
111
|
+
// oxlint fast pass
|
|
112
|
+
const oxlintRes = await runOxlintOnFiles({ repoPath: tmpRepo, files: ['src/ui/panel.ts'] });
|
|
113
|
+
assert.equal(typeof oxlintRes.executed, 'boolean');
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
db.close();
|
|
117
|
+
await fs.rm(tmpRepo, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
test('v3.1.0 SBOM, Deep IaC, Data Exposure Map, SEARCH/REPLACE & Pre-Fix Snapshot Undo', async () => {
|
|
121
|
+
const tmpRepo = await fs.mkdtemp(path.join(os.tmpdir(), 'cp-v31-p45-'));
|
|
122
|
+
try {
|
|
123
|
+
await fs.mkdir(path.join(tmpRepo, '.github', 'workflows'), { recursive: true });
|
|
124
|
+
await fs.mkdir(path.join(tmpRepo, 'infra', 'k8s'), { recursive: true });
|
|
125
|
+
await fs.mkdir(path.join(tmpRepo, 'src'), { recursive: true });
|
|
126
|
+
await fs.writeFile(path.join(tmpRepo, 'package-lock.json'), JSON.stringify({
|
|
127
|
+
name: 'demo',
|
|
128
|
+
lockfileVersion: 3,
|
|
129
|
+
packages: {
|
|
130
|
+
'': { name: 'demo', version: '1.0.0' },
|
|
131
|
+
'node_modules/zod': { version: '4.0.0', license: 'MIT' }
|
|
132
|
+
}
|
|
133
|
+
}), 'utf8');
|
|
134
|
+
await fs.writeFile(path.join(tmpRepo, 'Dockerfile'), `FROM node:latest\nRUN curl -fsSL https://x.test/s.sh | sh\n`, 'utf8');
|
|
135
|
+
await fs.writeFile(path.join(tmpRepo, '.github', 'workflows', 'pr.yml'), `on:\n pull_request_target:\npermissions: write-all\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: thirdparty/action@main\n - run: echo "\${{ github.event.pull_request.title }}"\n`, 'utf8');
|
|
136
|
+
await fs.writeFile(path.join(tmpRepo, 'infra', 'main.tf'), `resource "aws_s3_bucket" "b" {\n acl = "public-read"\n}\nresource "aws_db_instance" "db" {\n storage_encrypted = false\n}\n`, 'utf8');
|
|
137
|
+
await fs.writeFile(path.join(tmpRepo, 'infra', 'k8s', 'pod.yml'), `spec:\n containers:\n - name: app\n securityContext:\n privileged: true\n runAsUser: 0\n`, 'utf8');
|
|
138
|
+
const cdx = await generateProjectSbom({ repoPath: tmpRepo, repoName: 'demo', format: 'cyclonedx' });
|
|
139
|
+
assert.equal(cdx.componentCount, 1);
|
|
140
|
+
assert.equal(cdx.components[0]?.purl, 'pkg:npm/zod@4.0.0');
|
|
141
|
+
assert.ok(cdx.serializedJson.includes('"CycloneDX"'));
|
|
142
|
+
const spdx = await generateProjectSbom({ repoPath: tmpRepo, repoName: 'demo', format: 'spdx' });
|
|
143
|
+
assert.ok(spdx.serializedJson.includes('SPDX-2.3'));
|
|
144
|
+
const iacRes = await runDeepIacScanner(tmpRepo, [
|
|
145
|
+
'Dockerfile',
|
|
146
|
+
'.github/workflows/pr.yml',
|
|
147
|
+
'infra/main.tf',
|
|
148
|
+
'infra/k8s/pod.yml'
|
|
149
|
+
]);
|
|
150
|
+
const ruleIds = new Set(iacRes.findings.map((f) => f.rule_id));
|
|
151
|
+
assert.ok(ruleIds.has('CP-IAC-DOCKER-001'));
|
|
152
|
+
assert.ok(ruleIds.has('CP-IAC-GHA-001'));
|
|
153
|
+
assert.ok(ruleIds.has('CP-IAC-TF-001'));
|
|
154
|
+
assert.ok(ruleIds.has('CP-IAC-K8S-001'));
|
|
155
|
+
// Data Exposure classification + Executive HTML report
|
|
156
|
+
const payFinding = {
|
|
157
|
+
id: 'f-pci',
|
|
158
|
+
severity: 'critical',
|
|
159
|
+
confidence: 0.95,
|
|
160
|
+
category: 'finance',
|
|
161
|
+
title: 'Card PAN logged in checkout controller',
|
|
162
|
+
body: 'Logs stripe cardNumber and customer email.',
|
|
163
|
+
file: 'src/routes/checkout.ts',
|
|
164
|
+
line_start: 10,
|
|
165
|
+
line_end: 10,
|
|
166
|
+
source: 'sast',
|
|
167
|
+
reachability: 'external_reachable',
|
|
168
|
+
blast_radius: { risk_score: 90, direct_callers: [], affected_tests: [], impacted_files: [] },
|
|
169
|
+
recommendation: 'Redact card fields.',
|
|
170
|
+
status: 'open'
|
|
171
|
+
};
|
|
172
|
+
const cls = classifySensitiveDataForFinding(payFinding);
|
|
173
|
+
assert.equal(cls.dataClass, 'PCI');
|
|
174
|
+
const exp = buildDataExposureMap([{ ...payFinding, data_class: cls.dataClass }]);
|
|
175
|
+
assert.equal(exp.byClass.PCI, 1);
|
|
176
|
+
assert.equal(exp.externalSensitiveCount, 1);
|
|
177
|
+
const execHtml = renderExecutiveAuditHtml({
|
|
178
|
+
verdict: 'needs-attention',
|
|
179
|
+
summary: 'Test',
|
|
180
|
+
merge_gate: { passed: false, blockers_count: 1, high_count: 0, reason: '1 critical' },
|
|
181
|
+
findings: [{ ...payFinding, data_class: cls.dataClass }],
|
|
182
|
+
next_steps: []
|
|
183
|
+
}, { repoName: 'demo', mode: 'comprehensive', target: 'main_full' });
|
|
184
|
+
assert.ok(execHtml.includes('Sensitive Data Exposure Map'));
|
|
185
|
+
// SEARCH/REPLACE fuzzy match + Pre-fix snapshot Undo
|
|
186
|
+
const srcFileRel = 'src/app.ts';
|
|
187
|
+
const srcFileAbs = path.join(tmpRepo, srcFileRel);
|
|
188
|
+
const originalSrc = `export function greet(name: string) {\n return "hi " + name;\n}\n`;
|
|
189
|
+
await fs.writeFile(srcFileAbs, originalSrc, 'utf8');
|
|
190
|
+
const srText = `<<<<<<< SEARCH\nreturn "hi " + name;\n=======\nreturn \`hello \${name}\`;\n>>>>>>> REPLACE`;
|
|
191
|
+
const blocks = parseSearchReplaceBlocks(srText);
|
|
192
|
+
assert.equal(blocks.length, 1);
|
|
193
|
+
const applied = applySearchReplaceBlocks(originalSrc, blocks);
|
|
194
|
+
assert.equal(applied.appliedCount, 1);
|
|
195
|
+
assert.ok(applied.updatedContent.includes('return `hello ${name}`;'));
|
|
196
|
+
const snap = await createPreFixSnapshot(tmpRepo, srcFileRel);
|
|
197
|
+
await fs.writeFile(srcFileAbs, applied.updatedContent, 'utf8');
|
|
198
|
+
await restorePreFixSnapshot(tmpRepo, snap.snapshotId);
|
|
199
|
+
const restored = await fs.readFile(srcFileAbs, 'utf8');
|
|
200
|
+
assert.equal(restored, originalSrc);
|
|
201
|
+
// Ensure git doesn't complain if checked
|
|
202
|
+
await runCommand('git', ['--version'], { cwd: tmpRepo });
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
await fs.rm(tmpRepo, { recursive: true, force: true });
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
//# sourceMappingURL=v3.1-intelligence.test.js.map
|