changeguard 0.0.0-stage → 0.7.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +440 -0
  2. package/LICENSE +202 -0
  3. package/LICENSE-PROPRIETARY +94 -0
  4. package/README.md +317 -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 +84 -4
@@ -0,0 +1,384 @@
1
+ import { isOlder } from '../util/versions.js';
2
+ /** Collapse snake_case / camelCase / dotted differences for same-language compare. */
3
+ function norm(s) {
4
+ return s.toLowerCase().replace(/[_-]/g, '');
5
+ }
6
+ function segments(s) {
7
+ return s.split('.').filter(Boolean);
8
+ }
9
+ function pathEquals(a, b) {
10
+ return norm(a) === norm(b);
11
+ }
12
+ function pathPrefixMatch(prefixPattern, sitePath) {
13
+ const p = segments(prefixPattern.replace(/\.\*$/, ''));
14
+ const s = segments(sitePath);
15
+ if (p.length === 0 || s.length < p.length)
16
+ return false;
17
+ return p.every((seg, i) => norm(seg) === norm(s[i]));
18
+ }
19
+ function sdkPatternsFor(change, lang, scopes) {
20
+ const out = [];
21
+ for (const op of change.operations) {
22
+ if (scopes && !scopes.includes(op.scope))
23
+ continue;
24
+ for (const p of op.sdkPaths?.[lang] ?? [])
25
+ out.push(p);
26
+ }
27
+ return [...new Set(out)];
28
+ }
29
+ const CALL_LEVEL_SCOPES = ['operation', 'sdk-method', 'api-version'];
30
+ function matchSdkPath(change, site, scopes = CALL_LEVEL_SCOPES) {
31
+ const exact = [];
32
+ const prefix = [];
33
+ for (const p of sdkPatternsFor(change, site.language, scopes)) {
34
+ if (p.endsWith('.*')) {
35
+ if (pathPrefixMatch(p, site.path))
36
+ prefix.push(p);
37
+ }
38
+ else if (pathEquals(p, site.path)) {
39
+ exact.push(p);
40
+ }
41
+ else if (pathPrefixMatch(`${p}.*`, site.path) &&
42
+ segments(site.path).length === segments(p).length + 1) {
43
+ // direct child call of a removed namespace
44
+ prefix.push(`${p}.*`);
45
+ }
46
+ }
47
+ return { exact, prefix };
48
+ }
49
+ function httpPathMatch(template, actual) {
50
+ const t = template.split('/').filter(Boolean);
51
+ const a = actual.split('/').filter(Boolean);
52
+ if (t.length !== a.length)
53
+ return false;
54
+ return t.every((seg, i) => /^\{[^}]+\}$/.test(seg) || seg.startsWith(':') || norm(seg) === norm(a[i]));
55
+ }
56
+ function parseEnumList(detail, prefix) {
57
+ if (!detail)
58
+ return [];
59
+ const m = detail.match(new RegExp(`${prefix}:(.+)$`));
60
+ return m
61
+ ? m[1]
62
+ .split(',')
63
+ .map((s) => s.trim())
64
+ .filter(Boolean)
65
+ : [];
66
+ }
67
+ let findingSeq = 0;
68
+ function makeFinding(init) {
69
+ findingSeq += 1;
70
+ return {
71
+ id: `F${String(findingSeq).padStart(4, '0')}`,
72
+ providerId: init.change.providerId,
73
+ changeId: init.change.id,
74
+ change: init.change,
75
+ file: init.site?.file,
76
+ line: init.site?.line,
77
+ language: init.site?.language,
78
+ callPath: init.site ? `${init.site.path}` : undefined,
79
+ codeSnippet: init.site?.callText,
80
+ ruleId: init.ruleId,
81
+ match: init.match,
82
+ severity: init.severity,
83
+ confidence: init.confidence,
84
+ reason: init.reason,
85
+ codemod: init.codemod,
86
+ };
87
+ }
88
+ function kindSeverity(change, matched, deprecated, behavior) {
89
+ if (change.kind === 'breaking')
90
+ return matched;
91
+ if (change.kind === 'deprecation')
92
+ return deprecated;
93
+ if (change.kind === 'behavior')
94
+ return behavior;
95
+ return 'low';
96
+ }
97
+ export function evaluate(input) {
98
+ findingSeq = 0;
99
+ const findings = [];
100
+ const emitted = new Set();
101
+ const matchedChangeIds = new Set();
102
+ const remember = (f) => {
103
+ // reason is part of the key so distinct impacts on the same call
104
+ // (e.g. two removed parameters, per-ecosystem R7 pins) stay separate.
105
+ const key = `${f.changeId}:${f.file ?? ''}:${f.line ?? ''}:${f.ruleId}:${f.match}:${f.callPath ?? ''}:${f.reason}`;
106
+ if (emitted.has(key))
107
+ return;
108
+ emitted.add(key);
109
+ findings.push(f);
110
+ matchedChangeIds.add(f.changeId);
111
+ };
112
+ const providerSites = new Map();
113
+ for (const site of input.sites) {
114
+ if (!site.providerId)
115
+ continue;
116
+ const list = providerSites.get(site.providerId) ?? [];
117
+ list.push(site);
118
+ providerSites.set(site.providerId, list);
119
+ }
120
+ const providerDeps = new Map();
121
+ for (const dep of input.dependencies) {
122
+ if (!dep.providerId)
123
+ continue;
124
+ const list = providerDeps.get(dep.providerId) ?? [];
125
+ list.push(dep);
126
+ providerDeps.set(dep.providerId, list);
127
+ }
128
+ for (const change of input.changes) {
129
+ const sites = providerSites.get(change.providerId) ?? [];
130
+ for (const site of sites) {
131
+ const { exact, prefix } = matchSdkPath(change, site);
132
+ // R1 exact path
133
+ if (exact.length > 0) {
134
+ const ops = change.operations.filter((o) => o.scope === 'operation' || o.scope === 'sdk-method' || o.scope === 'api-version');
135
+ if (ops.length > 0 || change.operations.length === 0) {
136
+ remember(makeFinding({
137
+ change,
138
+ site,
139
+ ruleId: 'R1',
140
+ match: 'exact',
141
+ severity: kindSeverity(change, 'high', 'medium', 'medium'),
142
+ confidence: change.confidence === 'low' ? 'medium' : 'high',
143
+ reason: `Call \`${site.path}\` matches ${change.kind} change "${change.title}"`,
144
+ }));
145
+ }
146
+ }
147
+ // R2 prefix wildcard
148
+ if (prefix.length > 0 && exact.length === 0) {
149
+ remember(makeFinding({
150
+ change,
151
+ site,
152
+ ruleId: 'R2',
153
+ match: 'prefix',
154
+ severity: kindSeverity(change, 'high', 'low', 'medium'),
155
+ confidence: 'medium',
156
+ reason: `Call \`${site.path}\` falls under removed/changed namespace ${prefix.join(', ')}`,
157
+ }));
158
+ }
159
+ // R3 parameters / fields — risk analysis only. A feature note ("new
160
+ // parameter available") is an update-log entry, not a risk signal;
161
+ // R9 excludes feature changes for the same reason.
162
+ if (change.kind !== 'feature') {
163
+ const pathScoped = exact.length > 0 ||
164
+ change.operations.some((o) => (o.sdkPaths?.[site.language] ?? []).length === 0);
165
+ for (const op of change.operations) {
166
+ if (op.scope !== 'parameter' && op.scope !== 'request-field')
167
+ continue;
168
+ if (!op.target)
169
+ continue;
170
+ const sdkList = op.sdkPaths?.[site.language] ?? [];
171
+ const bindsCall = sdkList.length === 0
172
+ ? pathScoped
173
+ : sdkList.some((p) => (!p.endsWith('.*') && pathEquals(p, site.path)) ||
174
+ (p.endsWith('.*') && pathPrefixMatch(p, site.path)));
175
+ if (!bindsCall)
176
+ continue;
177
+ const keyHit = site.argumentKeys.some((k) => {
178
+ const tail = k.split('.').pop();
179
+ return norm(tail) === norm(op.target) || norm(k) === norm(op.target);
180
+ });
181
+ if (keyHit) {
182
+ remember(makeFinding({
183
+ change,
184
+ site,
185
+ ruleId: 'R3',
186
+ match: 'parameter',
187
+ severity: kindSeverity(change, 'high', 'medium', 'medium'),
188
+ confidence: 'high',
189
+ reason: `Call \`${site.path}\` passes ${op.scope === 'parameter' ? 'parameter' : 'field'} \`${op.target}\` affected by "${change.title}"`,
190
+ }));
191
+ }
192
+ }
193
+ }
194
+ // R5 enums / constants
195
+ for (const op of change.operations) {
196
+ if (op.scope !== 'enum')
197
+ continue;
198
+ const removed = parseEnumList(op.detail, 'removed');
199
+ if (removed.length === 0)
200
+ continue;
201
+ const sdkList = op.sdkPaths?.[site.language] ?? [];
202
+ const values = new Set();
203
+ for (const list of Object.values(site.argumentLiterals))
204
+ for (const v of list)
205
+ values.add(v);
206
+ for (const ref of site.memberRefs)
207
+ values.add(ref);
208
+ const hit = removed.find((v) => values.has(v) ||
209
+ [...values].some((used) => norm(used) === norm(v) || used.endsWith(`.${v}`)));
210
+ if (!hit)
211
+ continue;
212
+ // Scope the hit: either the enum declares SDK patterns and the call
213
+ // matches, or the constant reference itself carries the value.
214
+ const binds = sdkList.length > 0
215
+ ? sdkList.some((p) => (!p.endsWith('.*') && pathEquals(p, site.path)) ||
216
+ (p.endsWith('.*') && pathPrefixMatch(p, site.path)))
217
+ : site.memberRefs.some((r) => removed.some((v) => norm(r) === norm(v)));
218
+ if (binds) {
219
+ remember(makeFinding({
220
+ change,
221
+ site,
222
+ ruleId: 'R5',
223
+ match: 'enum',
224
+ severity: 'high',
225
+ confidence: 'high',
226
+ reason: `Usage of removed enum/constant value \`${hit}\` (${op.target ?? 'enum'})`,
227
+ }));
228
+ }
229
+ }
230
+ // R6 raw HTTP
231
+ if (site.http) {
232
+ for (const op of change.operations) {
233
+ if (!op.pathTemplate || op.scope === 'sdk-method')
234
+ continue;
235
+ const methodOk = !op.method || op.method === site.http.method;
236
+ if (methodOk && httpPathMatch(op.pathTemplate, site.path)) {
237
+ remember(makeFinding({
238
+ change,
239
+ site,
240
+ ruleId: 'R6',
241
+ match: 'http-path',
242
+ severity: kindSeverity(change, 'high', 'medium', 'medium'),
243
+ confidence: 'high',
244
+ reason: `Raw HTTP call ${site.http.method} ${site.http.url} hits ${op.method ?? '*'} ${op.pathTemplate}`,
245
+ }));
246
+ }
247
+ }
248
+ }
249
+ // R8 renames -> codemods
250
+ for (const rename of change.renames) {
251
+ if (rename.language && rename.language !== site.language)
252
+ continue;
253
+ if (rename.kind === 'parameter') {
254
+ const sdkList = sdkPatternsFor(change, site.language);
255
+ const bindsCall = sdkList.length === 0
256
+ ? exact.length > 0
257
+ : sdkList.some((p) => !p.endsWith('.*') && pathEquals(p, site.path));
258
+ const usesOld = site.argumentKeys.some((k) => norm(k.split('.').pop()) === norm(rename.from));
259
+ if (bindsCall && usesOld) {
260
+ remember(makeFinding({
261
+ change,
262
+ site,
263
+ ruleId: 'R8',
264
+ match: 'parameter',
265
+ severity: kindSeverity(change, 'high', 'medium', 'medium'),
266
+ confidence: 'high',
267
+ reason: `Parameter \`${rename.from}\` renamed to \`${rename.to}\``,
268
+ codemod: {
269
+ kind: 'rename-parameter',
270
+ from: rename.from,
271
+ to: rename.to,
272
+ language: site.language,
273
+ },
274
+ }));
275
+ }
276
+ }
277
+ else {
278
+ const tailFrom = rename.from.split('.').pop();
279
+ const tailTo = rename.to.split('.').pop();
280
+ const sdkList = sdkPatternsFor(change, site.language);
281
+ const bindsCall = sdkList.some((p) => (!p.endsWith('.*') && pathEquals(p, site.path)) ||
282
+ (p.endsWith('.*') && pathPrefixMatch(p, site.path)));
283
+ const tailMatch = norm(segments(site.path).pop() ?? '') === norm(tailFrom);
284
+ if ((bindsCall || sdkList.length === 0) &&
285
+ (tailMatch || pathEquals(site.path, rename.from))) {
286
+ remember(makeFinding({
287
+ change,
288
+ site,
289
+ ruleId: 'R8',
290
+ match: 'exact',
291
+ severity: change.kind === 'deprecation' ? 'medium' : 'high',
292
+ confidence: bindsCall ? 'high' : 'medium',
293
+ reason: `Method \`${rename.from}\` renamed to \`${rename.to}\``,
294
+ codemod: {
295
+ kind: 'rename-method',
296
+ from: tailFrom,
297
+ to: tailTo,
298
+ language: site.language,
299
+ },
300
+ }));
301
+ }
302
+ }
303
+ }
304
+ }
305
+ // R7 dependency version pins
306
+ for (const dep of providerDeps.get(change.providerId) ?? []) {
307
+ for (const v of change.versions) {
308
+ if (v.ecosystem !== dep.ecosystem || norm(v.package) !== norm(dep.name))
309
+ continue;
310
+ const version = dep.version ?? dep.spec;
311
+ if (v.removedIn && isOlder(version, v.removedIn)) {
312
+ remember(makeFinding({
313
+ change,
314
+ ruleId: 'R7',
315
+ match: 'dependency-version',
316
+ severity: 'high',
317
+ confidence: 'high',
318
+ reason: `Pinned ${dep.ecosystem} package ${dep.name}@${version ?? '?'} is older than removal version ${v.removedIn}`,
319
+ }));
320
+ }
321
+ else if (v.deprecatedIn && isOlder(version, v.deprecatedIn)) {
322
+ remember(makeFinding({
323
+ change,
324
+ ruleId: 'R7',
325
+ match: 'dependency-version',
326
+ severity: 'medium',
327
+ confidence: 'medium',
328
+ reason: `Pinned ${dep.ecosystem} package ${dep.name}@${version ?? '?'} predates deprecation version ${v.deprecatedIn}`,
329
+ }));
330
+ }
331
+ }
332
+ }
333
+ }
334
+ // R9 advisories: provider in use (sites or deps) but nothing concrete
335
+ // matched. Aggregated per provider — one advisory per vendor listing the
336
+ // un-matched changes — because one finding per change buried the matched
337
+ // findings under low-signal entries in online mode (measured: 45 of 59
338
+ // findings were per-change advisories). The severity keeps the original
339
+ // signal strength: any un-matched breaking change keeps the advisory at
340
+ // medium; deprecation/behavior-only groups are low.
341
+ const activeProviders = new Set([...providerSites.keys(), ...providerDeps.keys()]);
342
+ const unmatchedByProvider = new Map();
343
+ for (const change of input.changes) {
344
+ if (matchedChangeIds.has(change.id))
345
+ continue;
346
+ if (!activeProviders.has(change.providerId))
347
+ continue;
348
+ if (change.kind === 'feature')
349
+ continue;
350
+ const list = unmatchedByProvider.get(change.providerId) ?? [];
351
+ list.push(change);
352
+ unmatchedByProvider.set(change.providerId, list);
353
+ }
354
+ for (const [providerId, changes] of unmatchedByProvider) {
355
+ const sorted = [...changes].sort((a, b) => b.date.localeCompare(a.date));
356
+ const breaking = sorted.filter((c) => c.kind === 'breaking');
357
+ const deprecation = sorted.filter((c) => c.kind === 'deprecation');
358
+ const behavior = sorted.filter((c) => c.kind === 'behavior');
359
+ // The representative drives the report's change detail: prefer the newest
360
+ // breaking change, otherwise the newest change of any kind.
361
+ const representative = breaking[0] ?? sorted[0];
362
+ const kinds = [];
363
+ if (breaking.length > 0)
364
+ kinds.push(`${breaking.length} breaking`);
365
+ if (deprecation.length > 0)
366
+ kinds.push(`${deprecation.length} deprecation`);
367
+ if (behavior.length > 0)
368
+ kinds.push(`${behavior.length} behavior`);
369
+ const titles = sorted
370
+ .slice(0, 3)
371
+ .map((c) => `"${c.title}" (${c.date})`)
372
+ .join('; ');
373
+ const more = sorted.length > 3 ? `; +${sorted.length - 3} more` : '';
374
+ remember(makeFinding({
375
+ change: representative,
376
+ ruleId: 'R9',
377
+ match: 'exact',
378
+ severity: breaking.length > 0 ? 'medium' : 'low',
379
+ confidence: 'low',
380
+ reason: `${changes.length} un-matched change(s) from ${providerId} (${kinds.join(', ')}): none of your call sites hit them directly. Latest: ${titles}${more}. Review the changelog if this provider matters to you`,
381
+ }));
382
+ }
383
+ return findings;
384
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Canonical JSON (v1) used for feed signing and verification.
3
+ *
4
+ * Signatures must cover a deterministic byte sequence, never `JSON.stringify`
5
+ * output: key order is not stable in general and whitespace differs by producer.
6
+ *
7
+ * Rules (v1):
8
+ * - objects: keys sorted by UTF-16 code unit order, no whitespace
9
+ * - arrays: order preserved
10
+ * - strings: JSON.stringify escaping (RFC 8259)
11
+ * - numbers: finite only; -0 is normalized to 0; other values use JSON.stringify
12
+ * - `undefined` object members are omitted, matching JSON semantics
13
+ * - null / boolean: as-is
14
+ * - anything else (bigint, function, symbol) throws
15
+ */
16
+ export function canonicalJson(value) {
17
+ if (value === null)
18
+ return 'null';
19
+ switch (typeof value) {
20
+ case 'boolean':
21
+ return value ? 'true' : 'false';
22
+ case 'number': {
23
+ if (!Number.isFinite(value))
24
+ throw new TypeError('canonicalJson: non-finite number');
25
+ if (Object.is(value, -0))
26
+ return '0';
27
+ return JSON.stringify(value);
28
+ }
29
+ case 'string':
30
+ return JSON.stringify(value);
31
+ case 'object': {
32
+ if (Array.isArray(value)) {
33
+ return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
34
+ }
35
+ const obj = value;
36
+ const parts = [];
37
+ for (const key of Object.keys(obj).sort()) {
38
+ const member = obj[key];
39
+ if (member === undefined)
40
+ continue;
41
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(member)}`);
42
+ }
43
+ return `{${parts.join(',')}}`;
44
+ }
45
+ default:
46
+ throw new TypeError(`canonicalJson: unsupported type ${typeof value}`);
47
+ }
48
+ }
49
+ /** UTF-8 bytes of the canonical form. */
50
+ export function canonicalBytes(value) {
51
+ return Buffer.from(canonicalJson(value), 'utf8');
52
+ }
@@ -0,0 +1,63 @@
1
+ import { fetchText } from '../util/http.js';
2
+ import { logger } from '../util/logger.js';
3
+ import { parseNoteEntry } from './note-parser.js';
4
+ function stripTags(html) {
5
+ return html
6
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
7
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
8
+ .replace(/<\/(?:h[1-6]|li|p|div|article|section|tr)>/gi, '\n')
9
+ .replace(/<li[^>]*>/gi, '\n- ')
10
+ .replace(/<br\s*\/?>/gi, '\n')
11
+ .replace(/<[^>]+>/g, '')
12
+ .replace(/&amp;/g, '&')
13
+ .replace(/&lt;/g, '<')
14
+ .replace(/&gt;/g, '>')
15
+ .replace(/&quot;/g, '"')
16
+ .replace(/&#39;|&apos;/g, "'")
17
+ .replace(/&nbsp;/g, ' ')
18
+ .replace(/\n{3,}/g, '\n\n')
19
+ .trim();
20
+ }
21
+ const DATE_RE = /(20\d{2})[-/](\d{2})[-/](\d{2})/g;
22
+ export async function fetchChangelogChanges(cfg) {
23
+ let html;
24
+ try {
25
+ html = await fetchText(cfg.url, { accept: 'text/html' });
26
+ }
27
+ catch (err) {
28
+ logger.debug(`changelog ${cfg.providerId}: ${err instanceof Error ? err.message : String(err)}`);
29
+ return [];
30
+ }
31
+ const text = stripTags(html);
32
+ const out = [];
33
+ // Split into dated blocks: text following a YYYY-MM-DD marker until the next marker.
34
+ const markers = [];
35
+ for (const m of text.matchAll(DATE_RE)) {
36
+ if (m.index !== undefined)
37
+ markers.push({ date: `${m[1]}-${m[2]}-${m[3]}`, index: m.index });
38
+ }
39
+ for (let i = 0; i < markers.length; i++) {
40
+ const start = markers[i];
41
+ if (start.date < cfg.sinceISO)
42
+ continue;
43
+ const end = markers[i + 1]?.index ?? text.length;
44
+ const block = text.slice(start.index, end).trim();
45
+ const chunks = block
46
+ .split(/\n(?=\s*[-•]\s+)/)
47
+ .map((c) => c.trim())
48
+ .filter((c) => c.length > 20);
49
+ for (const chunk of chunks) {
50
+ const language = undefined;
51
+ const record = parseNoteEntry(chunk, {
52
+ providerId: cfg.providerId,
53
+ source: 'changelog',
54
+ sourceUrl: cfg.url,
55
+ date: start.date,
56
+ language,
57
+ });
58
+ if (record && record.kind !== 'feature')
59
+ out.push(record);
60
+ }
61
+ }
62
+ return out;
63
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Feed retrieval + verification. Retrieval never bypasses verification:
3
+ * callers receive either a verified payload or a typed rejection and must
4
+ * fall back on their own (see collectChanges in ./store.ts).
5
+ *
6
+ * Verification order is keyring first, then feed:
7
+ * 1. load built-in root keys (+ CHANGEGUARD_FEED_ROOT_KEYS for local ops)
8
+ * 2. load the signed keyring (file or URL) and verify its root signature
9
+ * 3. only then verify the feed with the signing keys listed in that keyring
10
+ * A keyring rejection stops the flow before the feed is even parsed.
11
+ */
12
+ import { readFileSync } from 'node:fs';
13
+ import { resolve } from 'node:path';
14
+ import { verifyFeed } from './feed.js';
15
+ import { BUILTIN_FEED_KEYRING, resolveRootKeys, verifySignedKeyring } from './feed-keys.js';
16
+ export async function loadVerifiedFeed(cfg) {
17
+ let roots;
18
+ try {
19
+ roots = resolveRootKeys().keys;
20
+ }
21
+ catch (err) {
22
+ return { ok: false, reason: 'keyring', detail: err.message };
23
+ }
24
+ let keyringRaw;
25
+ let keyringSource = 'built-in signed keyring';
26
+ try {
27
+ if (cfg.trustedKeys) {
28
+ keyringSource = cfg.trustedKeys;
29
+ keyringRaw = await readJson(cfg.trustedKeys);
30
+ }
31
+ else if (process.env.CHANGEGUARD_FEED_KEYS) {
32
+ keyringSource = `${process.env.CHANGEGUARD_FEED_KEYS} (env)`;
33
+ keyringRaw = await readJson(process.env.CHANGEGUARD_FEED_KEYS);
34
+ }
35
+ else if (BUILTIN_FEED_KEYRING) {
36
+ keyringSource = 'built-in signed keyring';
37
+ keyringRaw = BUILTIN_FEED_KEYRING;
38
+ }
39
+ else {
40
+ return {
41
+ ok: false,
42
+ reason: 'keyring',
43
+ detail: 'no trusted feed keyring configured; pass --trusted-keys or set CHANGEGUARD_FEED_KEYS ' +
44
+ '(the keyring must be signed by a built-in root key)',
45
+ };
46
+ }
47
+ }
48
+ catch (err) {
49
+ return {
50
+ ok: false,
51
+ reason: 'keyring',
52
+ detail: `cannot read keyring ${keyringSource}: ${err.message}`,
53
+ };
54
+ }
55
+ const keyring = verifySignedKeyring(keyringRaw, roots);
56
+ if (!keyring.ok)
57
+ return keyring;
58
+ const isUrl = /^https?:\/\//i.test(cfg.path);
59
+ let raw;
60
+ try {
61
+ raw = await readJson(cfg.path);
62
+ }
63
+ catch (err) {
64
+ if (err instanceof SyntaxError) {
65
+ return { ok: false, reason: 'malformed', detail: `feed is not valid JSON: ${err.message}` };
66
+ }
67
+ return {
68
+ ok: false,
69
+ reason: 'unreachable',
70
+ detail: `cannot read feed from ${cfg.path}: ${err.message}`,
71
+ };
72
+ }
73
+ const result = verifyFeed(raw, keyring.keys);
74
+ if (!result.ok)
75
+ return result;
76
+ return {
77
+ ok: true,
78
+ payload: result.payload,
79
+ kid: result.key.kid,
80
+ rootKid: keyring.root.kid,
81
+ keySource: `${keyringSource} (root ${keyring.root.kid})`,
82
+ sourceKind: isUrl ? 'url' : 'file',
83
+ };
84
+ }
85
+ async function readJson(source) {
86
+ const text = /^https?:\/\//i.test(source)
87
+ ? await fetchText(source)
88
+ : readFileSync(resolve(source), 'utf8');
89
+ return JSON.parse(text);
90
+ }
91
+ async function fetchText(url) {
92
+ const response = await fetch(url, {
93
+ signal: AbortSignal.timeout(15_000),
94
+ headers: { accept: 'application/json' },
95
+ });
96
+ if (!response.ok)
97
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
98
+ return await response.text();
99
+ }