changeguard 0.0.0-stage → 0.7.1

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +450 -0
  2. package/LICENSE +202 -0
  3. package/LICENSE-PROPRIETARY +94 -0
  4. package/README.md +321 -2
  5. package/SECURITY.md +40 -0
  6. package/data/changes/openai.seed.json +87 -0
  7. package/data/changes/shopify.seed.json +42 -0
  8. package/data/changes/stripe.seed.json +60 -0
  9. package/data/changes/supabase.seed.json +56 -0
  10. package/data/changes/twilio.seed.json +63 -0
  11. package/data/openapi/openai/meta.json +9 -0
  12. package/data/openapi/openai/new.json +24 -0
  13. package/data/openapi/openai/old.json +68 -0
  14. package/data/providers/openai.json +60 -0
  15. package/data/providers/shopify.json +52 -0
  16. package/data/providers/stripe.json +57 -0
  17. package/data/providers/supabase.json +56 -0
  18. package/data/providers/twilio.json +57 -0
  19. package/dist/analyze/go-analyzer.js +343 -0
  20. package/dist/analyze/index.js +77 -0
  21. package/dist/analyze/js-analyzer.js +380 -0
  22. package/dist/analyze/parser.js +78 -0
  23. package/dist/analyze/py-analyzer.js +313 -0
  24. package/dist/analyze/rules.js +1 -0
  25. package/dist/analyze/ts-utils.js +62 -0
  26. package/dist/cli.js +335 -0
  27. package/dist/codemod/apply.js +159 -0
  28. package/dist/config.js +121 -0
  29. package/dist/deps/manifests.js +145 -0
  30. package/dist/github/api.js +136 -0
  31. package/dist/github/auth.js +54 -0
  32. package/dist/impact/engine.js +384 -0
  33. package/dist/ingest/canonical.js +52 -0
  34. package/dist/ingest/changelog-html.js +63 -0
  35. package/dist/ingest/feed-client.js +99 -0
  36. package/dist/ingest/feed-keys.js +198 -0
  37. package/dist/ingest/feed.js +178 -0
  38. package/dist/ingest/github-releases.js +59 -0
  39. package/dist/ingest/note-parser.js +274 -0
  40. package/dist/ingest/openapi-diff.js +217 -0
  41. package/dist/ingest/store.js +181 -0
  42. package/dist/llm/explanation.js +273 -0
  43. package/dist/mcp/format.js +116 -0
  44. package/dist/mcp/index.js +29 -0
  45. package/dist/mcp/protocol.js +36 -0
  46. package/dist/mcp/server.js +110 -0
  47. package/dist/mcp/standalone.js +12 -0
  48. package/dist/mcp/tools.js +189 -0
  49. package/dist/notify/index.js +174 -0
  50. package/dist/providers/registry.js +215 -0
  51. package/dist/report/html.js +194 -0
  52. package/dist/report/markdown.js +90 -0
  53. package/dist/report/pr-draft.js +37 -0
  54. package/dist/scan.js +168 -0
  55. package/dist/source/repo-source.js +100 -0
  56. package/dist/types.js +6 -0
  57. package/dist/util/http.js +40 -0
  58. package/dist/util/logger.js +61 -0
  59. package/dist/util/metrics.js +99 -0
  60. package/dist/util/request-context.js +22 -0
  61. package/dist/util/task-queue.js +69 -0
  62. package/dist/util/versions.js +52 -0
  63. package/fixtures/sample-repo/cmd/billing/main.go +47 -0
  64. package/fixtures/sample-repo/go.mod +12 -0
  65. package/fixtures/sample-repo/package.json +17 -0
  66. package/fixtures/sample-repo/requirements.txt +7 -0
  67. package/fixtures/sample-repo/services/ai.py +65 -0
  68. package/fixtures/sample-repo/src/billing.ts +68 -0
  69. package/package.json +110 -4
package/dist/cli.js ADDED
@@ -0,0 +1,335 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ChangeGuard CLI — Apache-2.0 entrypoint.
4
+ *
5
+ * demo offline end-to-end run against the bundled fixture
6
+ * scan <path> scan a local repository
7
+ * pr-preview <path> dry-run PR draft
8
+ * pr-open <owner/repo> open a draft PR with codemod patches
9
+ *
10
+ * Hosted-service commands (serve, tenant, key, plan, audit, bind-installation)
11
+ * live in the proprietary `cli-admin.ts` extension. It is loaded dynamically;
12
+ * when the extension is absent the CLI registers unavailable stubs so the
13
+ * Apache-2.0-only distribution still runs the scan commands normally.
14
+ */
15
+ import { Command } from 'commander';
16
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join, resolve } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { scanRepository } from './scan.js';
20
+ import { enrichReport, templateExplain } from './llm/explanation.js';
21
+ import { renderHtml } from './report/html.js';
22
+ import { renderMarkdown } from './report/markdown.js';
23
+ import { draftPr } from './report/pr-draft.js';
24
+ import { buildPatches } from './codemod/apply.js';
25
+ import { LocalRepoSource } from './source/repo-source.js';
26
+ import { config } from './config.js';
27
+ import { logger } from './util/logger.js';
28
+ const HERE = dirname(fileURLToPath(import.meta.url));
29
+ const PKG_ROOT = resolve(HERE, '..');
30
+ async function writeArtifacts(repoPath, outDir, opts) {
31
+ const source = new LocalRepoSource(repoPath.split(/[\\/]/).pop() ?? repoPath, repoPath);
32
+ const report = await scanRepository({
33
+ source,
34
+ repoPath,
35
+ repoName: source.label,
36
+ sinceISO: opts.since,
37
+ online: opts.online,
38
+ feed: opts.feed ? { path: opts.feed, trustedKeys: opts.trustedKeys } : undefined,
39
+ onlyMatched: opts.onlyMatched,
40
+ });
41
+ if (opts.useLlm)
42
+ await enrichReport(report);
43
+ else {
44
+ // deterministic template explanations, no network
45
+ for (const f of report.findings)
46
+ f.explanation = templateExplain(f.change, f);
47
+ }
48
+ const patches = await buildPatches(source, report.findings);
49
+ const pr = draftPr(report, patches);
50
+ mkdirSync(outDir, { recursive: true });
51
+ const files = [];
52
+ const put = (name, content) => {
53
+ writeFileSync(join(outDir, name), content);
54
+ files.push(name);
55
+ };
56
+ put('report.json', JSON.stringify(report, null, 2));
57
+ put('report.md', renderMarkdown(report));
58
+ put('report.html', renderHtml(report));
59
+ put('pr-body.md', pr.body);
60
+ put('codemod.patch', patches
61
+ .map((p) => p.diff)
62
+ .filter(Boolean)
63
+ .join('\n'));
64
+ return { outDir, files };
65
+ }
66
+ function printSummary(reportPath, files) {
67
+ const report = JSON.parse(readFileSync(join(reportPath, 'report.json'), 'utf8'));
68
+ logger.info('');
69
+ logger.info('──────────────── ChangeGuard ────────────────');
70
+ logger.info(`mode=${report.mode} providers=${report.detectedProviders.join(',')}`);
71
+ logger.info(`deps=${report.dependencies.length} callSites=${report.callSiteCount} vendorChanges=${report.changes.length}`);
72
+ logger.info(`findings=${report.summary.total} HIGH=${report.summary.high} MEDIUM=${report.summary.medium} LOW=${report.summary.low} filesAffected=${report.summary.filesAffected}`);
73
+ logger.info(`artifacts: ${files.map((f) => join(reportPath, f)).join('\n ')}`);
74
+ logger.info('─────────────────────────────────────────────');
75
+ }
76
+ /**
77
+ * CLI version from package.json. Previously hard-coded as '0.1.0', which made
78
+ * `changeguard --version` lie about every release since 0.2.0. Resolves from
79
+ * both src/ (tsx) and dist/ alike — both sit one level below the package root.
80
+ */
81
+ function cliVersion() {
82
+ try {
83
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
84
+ return pkg.version ?? '0.0.0';
85
+ }
86
+ catch {
87
+ return '0.0.0';
88
+ }
89
+ }
90
+ const program = new Command();
91
+ program
92
+ .name('changeguard')
93
+ .description('Detect breaking third-party API/SDK changes that affect your code')
94
+ .version(cliVersion());
95
+ program
96
+ .command('demo')
97
+ .description('Run the full offline pipeline against the bundled sample repository')
98
+ .option('--out <dir>', 'output directory', join(process.cwd(), '.changeguard/out'))
99
+ .action(async (opts) => {
100
+ const fixture = join(PKG_ROOT, 'fixtures', 'sample-repo');
101
+ if (!existsSync(fixture))
102
+ throw new Error(`fixture not found: ${fixture}`);
103
+ const { outDir, files } = await writeArtifacts(fixture, resolve(opts.out), {
104
+ since: '2023-01-01',
105
+ online: false,
106
+ useLlm: false,
107
+ });
108
+ printSummary(outDir, files);
109
+ });
110
+ program
111
+ .command('scan')
112
+ .argument('<path>', 'repository path')
113
+ .description('Scan a local repository for breaking API/SDK changes')
114
+ .option('--since <iso>', 'only include vendor changes since this ISO date')
115
+ .option('--online', 'fetch GitHub releases / changelog pages (cache 6h)', false)
116
+ .option('--feed <path|url>', 'signed change feed; verified records replace the bundled snapshot')
117
+ .option('--trusted-keys <file>', 'keyring with trusted feed public keys (default: env or built-in)')
118
+ .option('--out <dir>', 'write JSON/Markdown/HTML/PR artifacts to this directory')
119
+ .option('--json', 'print the raw ScanReport JSON to stdout', false)
120
+ .option('--only-matched', 'only findings anchored to a concrete file (drop repo/dependency advisories)', false)
121
+ .option('--no-llm', 'disable LLM explanations even if LLM_API_KEY is set')
122
+ .action(async (path, opts) => {
123
+ const repoPath = resolve(path);
124
+ const since = opts.since ?? new Date(Date.now() - 365 * 864e5).toISOString().slice(0, 10);
125
+ const feed = opts.feed ? { path: opts.feed, trustedKeys: opts.trustedKeys } : undefined;
126
+ if (opts.out) {
127
+ const { outDir, files } = await writeArtifacts(repoPath, resolve(opts.out), {
128
+ since,
129
+ online: opts.online,
130
+ useLlm: opts.llm,
131
+ feed: opts.feed,
132
+ trustedKeys: opts.trustedKeys,
133
+ onlyMatched: opts.onlyMatched,
134
+ });
135
+ printSummary(outDir, files);
136
+ return;
137
+ }
138
+ const report = await scanRepository({
139
+ repoPath,
140
+ sinceISO: since,
141
+ online: opts.online,
142
+ feed,
143
+ onlyMatched: opts.onlyMatched,
144
+ });
145
+ if (opts.llm && config.llm.enabled)
146
+ await enrichReport(report);
147
+ else {
148
+ for (const f of report.findings)
149
+ f.explanation = templateExplain(f.change, f);
150
+ }
151
+ if (opts.json) {
152
+ process.stdout.write(JSON.stringify(report, null, 2));
153
+ }
154
+ else {
155
+ process.stdout.write(renderMarkdown(report));
156
+ }
157
+ });
158
+ const ADMIN_COMMANDS = [
159
+ { name: 'serve', description: 'Start the GitHub App webhook receiver' },
160
+ { name: 'tenant', description: 'Manage tenants (multi-tenant admin)' },
161
+ { name: 'key', description: 'Manage tenant API keys' },
162
+ {
163
+ name: 'plan',
164
+ description: 'Set a tenant plan manually (free|pro|team, no Stripe involved)',
165
+ },
166
+ { name: 'bind-installation', description: 'Bind a GitHub App installation to a tenant' },
167
+ { name: 'audit', description: 'Query the audit log' },
168
+ ];
169
+ function isMissingModule(err) {
170
+ const code = err?.code;
171
+ return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND';
172
+ }
173
+ function registerUnavailableAdminCommands(target) {
174
+ for (const spec of ADMIN_COMMANDS) {
175
+ target
176
+ .command(spec.name)
177
+ .argument('[args...]', 'arguments for the proprietary command')
178
+ .description(`${spec.description} (proprietary distribution only)`)
179
+ .allowUnknownOption(true)
180
+ .action(() => {
181
+ logger.error(`The "${spec.name}" command belongs to the proprietary ChangeGuard server distribution and is not included in this Apache-2.0 CLI package.`);
182
+ logger.error('Scan commands (demo, scan, pr-preview, pr-open) work without it. See LICENSE-PROPRIETARY for details.');
183
+ process.exit(1);
184
+ });
185
+ }
186
+ }
187
+ async function registerAdminCommands() {
188
+ try {
189
+ const mod = (await import('./cli-admin.js'));
190
+ mod.registerAdminCommands(program);
191
+ }
192
+ catch (err) {
193
+ if (!isMissingModule(err))
194
+ throw err;
195
+ registerUnavailableAdminCommands(program);
196
+ }
197
+ }
198
+ await registerAdminCommands();
199
+ program
200
+ .command('pr-preview')
201
+ .argument('<path>', 'repository path')
202
+ .description('Dry-run: show the draft PR that would be created (no GitHub API calls)')
203
+ .option('--since <iso>', 'only include vendor changes since this ISO date')
204
+ .option('--base <branch>', 'base branch for the PR', 'main')
205
+ .option('--feed <path|url>', 'signed change feed; verified records replace the bundled snapshot')
206
+ .option('--trusted-keys <file>', 'keyring with trusted feed public keys (default: env or built-in)')
207
+ .action(async (path, opts) => {
208
+ const repoPath = resolve(path);
209
+ const since = opts.since ?? new Date(Date.now() - 2 * 365 * 864e5).toISOString().slice(0, 10);
210
+ const source = new LocalRepoSource(repoPath.split(/[\\/]/).pop() ?? repoPath, repoPath);
211
+ const report = await scanRepository({
212
+ source,
213
+ repoPath,
214
+ repoName: source.label,
215
+ sinceISO: since,
216
+ online: false,
217
+ persist: false,
218
+ feed: opts.feed ? { path: opts.feed, trustedKeys: opts.trustedKeys } : undefined,
219
+ });
220
+ for (const f of report.findings)
221
+ f.explanation = templateExplain(f.change, f);
222
+ const patches = await buildPatches(source, report.findings);
223
+ const pr = draftPr(report, patches);
224
+ const branch = `changeguard/upgrade-${Date.now().toString(36)}`;
225
+ logger.info('');
226
+ logger.info('══════════ ChangeGuard PR Preview (dry-run) ══════════');
227
+ logger.info(`base branch : ${opts.base}`);
228
+ logger.info(`head branch : ${branch}`);
229
+ logger.info(`title : ${pr.title}`);
230
+ logger.info(`findings : ${report.summary.total} (H${report.summary.high}/M${report.summary.medium}/L${report.summary.low})`);
231
+ logger.info(`files to patch: ${patches.length}`);
232
+ for (const p of patches) {
233
+ logger.info(` - ${p.file} (${p.applied.length} codemod(s))`);
234
+ }
235
+ logger.info('');
236
+ logger.info('── PR body ──');
237
+ process.stdout.write(pr.body + '\n');
238
+ logger.info('');
239
+ logger.info('── unified diff ──');
240
+ const diff = patches
241
+ .map((p) => p.diff)
242
+ .filter(Boolean)
243
+ .join('\n');
244
+ process.stdout.write((diff || '(no codemod patches — nothing to commit)') + '\n');
245
+ logger.info('');
246
+ logger.info(patches.length > 0
247
+ ? `To actually open this draft PR, run with GITHUB_TOKEN set and use the webhook/serve flow.`
248
+ : `No automatic patches available. Review report for manual migration steps.`);
249
+ });
250
+ program
251
+ .command('pr-open')
252
+ .argument('<owner/repo>', 'GitHub repository to file a draft PR against')
253
+ .description('Scan a remote repo and open a DRAFT pull request with codemod patches')
254
+ .option('--since <iso>', 'only include vendor changes since this ISO date')
255
+ .option('--base <branch>', 'base branch for the PR (auto-detects main/master if unset)')
256
+ .option('--installation <id>', 'GitHub App installation id (falls back to GITHUB_TOKEN or tokenless)')
257
+ .option('--feed <path|url>', 'signed change feed; verified records replace the bundled snapshot')
258
+ .option('--trusted-keys <file>', 'keyring with trusted feed public keys (default: env or built-in)')
259
+ .action(async (ownerRepo, opts) => {
260
+ const m = ownerRepo.match(/^([^/]+)\/([^/]+)$/);
261
+ if (!m)
262
+ throw new Error('argument must be in owner/repo form (e.g. stripe/stripe-node)');
263
+ const owner = m[1];
264
+ const repo = m[2];
265
+ const since = opts.since ?? new Date(Date.now() - 2 * 365 * 864e5).toISOString().slice(0, 10);
266
+ const { GitHubClient } = await import('./github/api.js');
267
+ const client = await GitHubClient.forInstallation(opts.installation ? Number(opts.installation) : undefined);
268
+ // Resolve base branch — explicit flag wins, otherwise probe main → master.
269
+ let base = opts.base ?? '';
270
+ if (!base) {
271
+ for (const candidate of ['main', 'master']) {
272
+ try {
273
+ await client.get(`/repos/${owner}/${repo}/git/ref/heads/${candidate}`);
274
+ base = candidate;
275
+ break;
276
+ }
277
+ catch {
278
+ /* try next */
279
+ }
280
+ }
281
+ if (!base)
282
+ throw new Error(`could not detect base branch for ${owner}/${repo}`);
283
+ }
284
+ logger.info(`fetching ${owner}/${repo} (base=${base})…`);
285
+ const source = await client.fetchRepoSource(owner, repo, base);
286
+ const report = await scanRepository({
287
+ source,
288
+ repoPath: ownerRepo,
289
+ repoName: `${owner}/${repo}`,
290
+ sinceISO: since,
291
+ online: false,
292
+ persist: false,
293
+ feed: opts.feed ? { path: opts.feed, trustedKeys: opts.trustedKeys } : undefined,
294
+ });
295
+ for (const f of report.findings)
296
+ f.explanation = templateExplain(f.change, f);
297
+ if (report.findings.length === 0) {
298
+ logger.info(`no breaking API changes affect ${owner}/${repo} — skipping PR`);
299
+ return;
300
+ }
301
+ const patches = await buildPatches(source, report.findings);
302
+ const pr = draftPr(report, patches, { base });
303
+ const result = await client.openDraftPr(owner, repo, {
304
+ head: pr.head,
305
+ base,
306
+ title: pr.title,
307
+ body: pr.body,
308
+ patches,
309
+ });
310
+ logger.info('');
311
+ logger.info('══════════ ChangeGuard DRAFT PR opened ══════════');
312
+ logger.info(`repo : ${owner}/${repo}`);
313
+ logger.info(`head branch : ${pr.head}`);
314
+ logger.info(`findings : ${report.summary.total} (H${report.summary.high}/M${report.summary.medium}/L${report.summary.low})`);
315
+ logger.info(`files patched: ${patches.length}`);
316
+ logger.info(`PR #${result.number}: ${result.html_url}`);
317
+ });
318
+ program
319
+ .command('mcp')
320
+ .description('run as an MCP server over stdio (Claude Code / Cursor / VS Code / Cline)')
321
+ .action(async () => {
322
+ // Dynamic import: plain scan/demo invocations never load the MCP module.
323
+ const { runMcpServer } = await import('./mcp/index.js');
324
+ await runMcpServer();
325
+ });
326
+ program.parseAsync(process.argv).catch((err) => {
327
+ logger.error(err instanceof Error ? err.message : String(err));
328
+ process.exitCode = 1;
329
+ // On Windows with Node >= 24, a synchronous process.exit() while tree-sitter
330
+ // WASM / SQLite handles are still closing trips a libuv assertion
331
+ // (src/win/async.c) and dies with 0xC0000409 instead of exiting 1. Prefer a
332
+ // natural exit (process.exitCode above); the unref'd timer below only fires
333
+ // when a resident handle keeps the loop alive, as a bounded fallback.
334
+ setTimeout(() => process.exit(1), 100).unref();
335
+ });
@@ -0,0 +1,159 @@
1
+ function escapeRegExp(s) {
2
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3
+ }
4
+ function applyOne(line, r) {
5
+ let count = 0;
6
+ if (r.kind === 'rename-method') {
7
+ const re = new RegExp(`\\.${escapeRegExp(r.from)}(?=\\s*[(<])`, 'g');
8
+ const text = line.replace(re, () => {
9
+ count++;
10
+ return `.${r.to}`;
11
+ });
12
+ return { text, count };
13
+ }
14
+ // rename-parameter
15
+ if (r.language === 'python') {
16
+ // keyword argument: from_= / from=
17
+ const re = new RegExp(`\\b${escapeRegExp(r.from)}(?=\\s*=)`);
18
+ const text = line.replace(re, () => {
19
+ count++;
20
+ return r.to;
21
+ });
22
+ return { text, count };
23
+ }
24
+ // JS/TS/Go object/struct key: from:
25
+ const re = new RegExp(`\\b${escapeRegExp(r.from)}(?=\\s*:)`);
26
+ const text = line.replace(re, () => {
27
+ count++;
28
+ return r.to;
29
+ });
30
+ return { text, count };
31
+ }
32
+ /**
33
+ * Minimal unified diff (3 lines of context). Codemods only perform same-line
34
+ * substitutions, so changed lines pair 1:1 as '-' / '+'.
35
+ */
36
+ export function unifiedDiff(file, oldContent, newContent) {
37
+ const a = oldContent.split(/\r?\n/);
38
+ const b = newContent.split(/\r?\n/);
39
+ const changed = [];
40
+ const n = Math.max(a.length, b.length);
41
+ for (let i = 0; i < n; i++)
42
+ if (a[i] !== b[i])
43
+ changed.push(i);
44
+ if (changed.length === 0)
45
+ return '';
46
+ // merge changed indices into hunks when gaps are small
47
+ const hunks = [];
48
+ for (const idx of changed) {
49
+ const last = hunks[hunks.length - 1];
50
+ if (last && idx - last[1] <= 7)
51
+ last[1] = idx;
52
+ else
53
+ hunks.push([idx, idx]);
54
+ }
55
+ const out = [`--- a/${file}`, `+++ b/${file}`];
56
+ for (const [start0, end0] of hunks) {
57
+ const ctx = 3;
58
+ const sa = Math.max(0, start0 - ctx);
59
+ const ea = Math.min(a.length, end0 + ctx + 1);
60
+ out.push(`@@ -${sa + 1},${ea - sa} +${sa + 1},${ea - sa} @@`);
61
+ for (let i = sa; i < ea; i++) {
62
+ if (a[i] === b[i]) {
63
+ out.push(` ${a[i] ?? ''}`);
64
+ }
65
+ else {
66
+ out.push(`-${a[i] ?? ''}`);
67
+ out.push(`+${b[i] ?? ''}`);
68
+ }
69
+ }
70
+ }
71
+ return out.join('\n');
72
+ }
73
+ /**
74
+ * Lines spanned by the call expression starting at `startIdx`: walk forward
75
+ * tracking parenthesis depth (multiline arguments), capped at 15 lines.
76
+ */
77
+ function callSpan(lines, startIdx) {
78
+ let depth = 0;
79
+ let started = false;
80
+ const end = Math.min(lines.length, startIdx + 15);
81
+ for (let i = startIdx; i < end; i++) {
82
+ for (const ch of lines[i] ?? '') {
83
+ if (ch === '(') {
84
+ depth++;
85
+ started = true;
86
+ }
87
+ else if (ch === ')')
88
+ depth--;
89
+ }
90
+ if (started && depth <= 0)
91
+ return [startIdx, i];
92
+ }
93
+ return [startIdx, end - 1];
94
+ }
95
+ export function applyCodemods(file, content, findings) {
96
+ // One entry per call site emitting a codemod (dedupe defensively).
97
+ const jobs = new Map();
98
+ for (const f of findings) {
99
+ if (!f.codemod || f.file !== file)
100
+ continue;
101
+ if (f.codemod.kind !== 'rename-method' && f.codemod.kind !== 'rename-parameter')
102
+ continue;
103
+ const key = `${f.codemod.kind}:${f.codemod.language ?? ''}:${f.codemod.from}->${f.codemod.to}@${f.line ?? 0}`;
104
+ jobs.set(key, {
105
+ from: f.codemod.from,
106
+ to: f.codemod.to,
107
+ kind: f.codemod.kind,
108
+ language: f.codemod.language,
109
+ line: f.line ?? 1,
110
+ });
111
+ }
112
+ if (jobs.size === 0)
113
+ return undefined;
114
+ const lines = content.split(/\r?\n/);
115
+ const totals = new Map();
116
+ for (const job of jobs.values()) {
117
+ const [from, to] = callSpan(lines, Math.max(0, job.line - 1));
118
+ let count = 0;
119
+ for (let i = from; i <= to; i++) {
120
+ const res = applyOne(lines[i], job);
121
+ if (res.count > 0) {
122
+ lines[i] = res.text;
123
+ count += res.count;
124
+ }
125
+ }
126
+ if (count > 0) {
127
+ const tKey = `${job.kind}:${job.language ?? ''}:${job.from}->${job.to}`;
128
+ const prev = totals.get(tKey);
129
+ totals.set(tKey, { count: (prev?.count ?? 0) + count, r: job });
130
+ }
131
+ }
132
+ const applied = [];
133
+ for (const { count, r } of totals.values()) {
134
+ applied.push({ from: r.from, to: r.to, count, kind: r.kind, language: r.language });
135
+ }
136
+ if (applied.length === 0)
137
+ return undefined;
138
+ const newContent = lines.join(content.includes('\r\n') ? '\r\n' : '\n');
139
+ return {
140
+ file,
141
+ oldContent: content,
142
+ newContent,
143
+ diff: unifiedDiff(file, content, newContent),
144
+ applied,
145
+ };
146
+ }
147
+ export async function buildPatches(source, findings) {
148
+ const files = [...new Set(findings.filter((f) => f.codemod && f.file).map((f) => f.file))];
149
+ const patches = [];
150
+ for (const file of files) {
151
+ const content = await source.readText(file);
152
+ if (typeof content !== 'string')
153
+ continue;
154
+ const patch = applyCodemods(file, content, findings);
155
+ if (patch)
156
+ patches.push(patch);
157
+ }
158
+ return patches;
159
+ }
package/dist/config.js ADDED
@@ -0,0 +1,121 @@
1
+ import { readFileSync, existsSync, statSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ /** Minimal .env loader (no external dependency). */
4
+ function loadDotEnv() {
5
+ const path = resolve(process.cwd(), '.env');
6
+ if (!existsSync(path))
7
+ return;
8
+ const raw = readFileSync(path, 'utf8');
9
+ for (const line of raw.split(/\r?\n/)) {
10
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
11
+ if (!m)
12
+ continue;
13
+ const key = m[1];
14
+ let val = m[2];
15
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
16
+ val = val.slice(1, -1);
17
+ }
18
+ if (process.env[key] === undefined)
19
+ process.env[key] = val;
20
+ }
21
+ }
22
+ loadDotEnv();
23
+ /** Env booleans accept 1/true/yes/on. Everything else (including unset) is false. */
24
+ function envFlag(value) {
25
+ return /^(1|true|yes|on)$/i.test((value ?? '').trim());
26
+ }
27
+ function pemFromValue(value) {
28
+ if (!value)
29
+ return undefined;
30
+ if (value.includes('BEGIN'))
31
+ return value.replace(/\\n/g, '\n');
32
+ const p = resolve(value);
33
+ try {
34
+ if (statSync(p).isFile())
35
+ return readFileSync(p, 'utf8');
36
+ }
37
+ catch {
38
+ /* fall through */
39
+ }
40
+ return undefined;
41
+ }
42
+ export const config = {
43
+ llm: {
44
+ baseUrl: process.env.LLM_BASE_URL || 'https://api.openai.com/v1',
45
+ apiKey: process.env.LLM_API_KEY || '',
46
+ model: process.env.LLM_MODEL || 'gpt-4o-mini',
47
+ /** Runtime kill-switch for LLM-based explanations. When set, every finding
48
+ * falls back to the deterministic template without any network call.
49
+ * Useful to shut off LLM spending or respond to a prompt-injection incident. */
50
+ disabled: envFlag(process.env.CHANGEGUARD_DISABLE_LLM),
51
+ /** Hard cap on LLM calls per hour per process. 0 = unlimited (not recommended).
52
+ * Prevents runaway spending when a malicious feed floods findings. */
53
+ maxCallsPerHour: Number(process.env.CHANGEGUARD_LLM_MAX_CALLS_PER_HOUR || 200),
54
+ get enabled() {
55
+ return Boolean(this.apiKey);
56
+ },
57
+ },
58
+ github: {
59
+ appId: process.env.GITHUB_APP_ID || '',
60
+ privateKey: pemFromValue(process.env.GITHUB_PRIVATE_KEY),
61
+ webhookSecret: process.env.GITHUB_WEBHOOK_SECRET || '',
62
+ token: process.env.GITHUB_TOKEN || '',
63
+ },
64
+ slackWebhookUrl: process.env.SLACK_WEBHOOK_URL || '',
65
+ smtpUrl: process.env.SMTP_URL || '',
66
+ emailTo: (process.env.EMAIL_TO || '')
67
+ .split(',')
68
+ .map((s) => s.trim())
69
+ .filter(Boolean),
70
+ port: Number(process.env.PORT || 8787),
71
+ cacheDir: resolve(process.cwd(), process.env.CHANGEGUARD_CACHE_DIR || '.changeguard/cache'),
72
+ dbPath: resolve(process.cwd(), process.env.CHANGEGUARD_DB_PATH || '.changeguard/changeguard.db'),
73
+ /** Cron-style interval for scheduled scans, in hours. 0 disables. */
74
+ scanIntervalHours: Number(process.env.CHANGEGUARD_SCAN_INTERVAL_HOURS || 24),
75
+ /** Comma-separated repo paths to scan on schedule (local dirs or owner/repo). */
76
+ scheduledRepos: (process.env.CHANGEGUARD_SCHEDULED_REPOS || '')
77
+ .split(',')
78
+ .map((s) => s.trim())
79
+ .filter(Boolean),
80
+ // ---- commercial (phase 3) ----
81
+ /** When set, the console + JSON API require a session or API key. */
82
+ consolePassword: process.env.CHANGEGUARD_CONSOLE_PASSWORD || '',
83
+ /** Audit-log retention in days (default 90; 0 disables rotation). */
84
+ auditRetentionDays: (() => {
85
+ const raw = process.env.CHANGEGUARD_AUDIT_RETENTION_DAYS;
86
+ if (raw === undefined || raw === '')
87
+ return 90;
88
+ const n = Number(raw);
89
+ return Number.isFinite(n) && n >= 0 ? n : 90;
90
+ })(),
91
+ /** HMAC secret for session cookies. When unset a random secret is generated
92
+ * per process (sessions then do not survive a restart). Set this in production. */
93
+ sessionSecret: process.env.CHANGEGUARD_SESSION_SECRET || '',
94
+ // ---- security escape hatches (default OFF: fail-closed) ----
95
+ /** Dev only: serve the console without any credentials. */
96
+ allowAnonymousConsole: envFlag(process.env.CHANGEGUARD_ALLOW_ANONYMOUS_CONSOLE),
97
+ /** Dev only: accept GitHub webhooks whose signature cannot be verified. */
98
+ allowUnsignedWebhook: envFlag(process.env.CHANGEGUARD_ALLOW_UNSIGNED_WEBHOOK),
99
+ /** CI mode: any signed-feed verification failure exits non-zero (no fallback). */
100
+ feedStrict: envFlag(process.env.CHANGEGUARD_FEED_STRICT),
101
+ /** Behind a reverse proxy that sets X-Forwarded-Proto / X-Forwarded-For. */
102
+ trustProxy: envFlag(process.env.CHANGEGUARD_TRUST_PROXY),
103
+ /** Force the `Secure` attribute on session cookies (TLS terminates upstream). */
104
+ secureCookies: envFlag(process.env.CHANGEGUARD_SECURE_COOKIES),
105
+ stripe: {
106
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET || '',
107
+ secretKey: process.env.STRIPE_SECRET_KEY || '',
108
+ pricePro: process.env.STRIPE_PRICE_PRO || '',
109
+ priceTeam: process.env.STRIPE_PRICE_TEAM || '',
110
+ get enabled() {
111
+ return Boolean(this.webhookSecret);
112
+ },
113
+ },
114
+ githubOAuth: {
115
+ clientId: process.env.GITHUB_OAUTH_CLIENT_ID || '',
116
+ clientSecret: process.env.GITHUB_OAUTH_CLIENT_SECRET || '',
117
+ get enabled() {
118
+ return Boolean(this.clientId && this.clientSecret);
119
+ },
120
+ },
121
+ };