@mago-foundation/mago-ski 0.1.0 → 0.3.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 (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
@@ -23,8 +23,4 @@ export interface DiffResult {
23
23
  diff_truncated: boolean;
24
24
  files: FileChange[];
25
25
  }
26
- /**
27
- * Compares two Skill directories. Any digest difference requires a new certificate,
28
- * whatever the capability evidence says: unchanged origins never waive a content change.
29
- */
30
26
  export declare function diffSkillTrees(baseRoot: string, candidateRoot: string): Promise<DiffResult>;
package/dist/src/diff.js CHANGED
@@ -1,14 +1,54 @@
1
- import { collectSkillTree } from "./tree-digest.js";
1
+ import { collectSkillTree, compareTreePaths, sha256Hex } from "./tree-digest.js";
2
2
  const textDecoder = new TextDecoder('utf-8', { fatal: true });
3
3
  const MAX_ANALYZED_TEXT_BYTES = 2 * 1024 * 1024;
4
+ /** Before + after bytes, summed over every file: per-file limits alone allow ~500 MiB of parsing. */
5
+ const MAX_SECTION_DIFF_BYTES = 16 * 1024 * 1024;
4
6
  const MAX_REPORTED_FILES = 200;
5
7
  const MAX_REPORTED_SECTIONS = 32;
8
+ const MAX_INDEXED_SECTIONS = 4_096;
6
9
  const MAX_ORIGINS = 128;
10
+ /** Per tree. Each candidate costs a URL parse, and a 256 MiB tree can hold tens of millions. */
11
+ const MAX_URL_CANDIDATES = 100_000;
12
+ /** "https://", a 254-char DNS name (trailing dot included), ":65535". The URL parser accepts longer hosts. */
13
+ const MAX_ORIGIN_CHARS = 8 + 254 + 6;
14
+ const MAX_HEADING_LEVEL = 6;
15
+ /** One Markdown line can be megabytes long; reported labels must not be. */
16
+ const MAX_LABEL_TITLE_CHARS = 200;
17
+ const LABEL_DOCUMENT_BODY = '(document body)';
18
+ const LABEL_EMPTY_HEADING = '(empty heading)';
19
+ const LABEL_FILE_ADDED = '(file added)';
20
+ const LABEL_FILE_REMOVED = '(file removed)';
21
+ const LABEL_WHOLE_FILE = '(whole file)';
22
+ const LABEL_SIZE_LIMIT = '(whole file; size limit)';
23
+ const LABEL_TOTAL_SIZE_LIMIT = '(whole file; total size limit)';
24
+ const LABEL_NON_TEXT = '(whole file; non-text content)';
25
+ const LABEL_EXEC_BIT = '(executable bit)';
26
+ // Every pattern below runs on untrusted Skill content: keep each one free of overlapping quantifiers.
7
27
  const urlPattern = /https?:\/\/[^\s"'`<>()[\]{}]+/giu;
28
+ const trailingPunctuation = '.,;:!?';
29
+ const fenceOpenPattern = /^ {0,3}(`{3,}|~{3,})/u;
30
+ const fenceClosePattern = /^ {0,3}(`{3,}|~{3,})\s*$/u;
31
+ const atxOpenPattern = /^ {0,3}(#{1,6})([ \t]+)/u;
32
+ const whitespacePattern = /\s/u;
33
+ /** What `.` refuses besides CR and LF, which never reach a line. */
34
+ const dotExcludedPattern = /[\u2028\u2029]/u;
35
+ // Sticky: a failed match must not rescan from every later offset (a lone CR made that quadratic).
36
+ const linePattern = /[^\r\n]*(?:\r\n|\r|\n|$)/uy;
37
+ const lineEndingPattern = /(?:\r\n|\r|\n)$/u;
38
+ const crlfPattern = /\r\n/gu;
39
+ /** Drops trailing sentence punctuation. A loop, because /[.,;:!?]+$/ backtracks quadratically on a long run. */
40
+ function trimTrailingPunctuation(value) {
41
+ let end = value.length;
42
+ while (end > 0 && trailingPunctuation.includes(value[end - 1])) {
43
+ end -= 1;
44
+ }
45
+ return value.slice(0, end);
46
+ }
8
47
  function collectOrigins(contents) {
9
48
  const origins = new Set();
10
49
  let complete = true;
11
- for (const content of contents.values()) {
50
+ let candidates = 0;
51
+ scan: for (const content of contents.values()) {
12
52
  if (content.length > MAX_ANALYZED_TEXT_BYTES || content.includes(0)) {
13
53
  complete = false;
14
54
  continue;
@@ -22,99 +62,312 @@ function collectOrigins(contents) {
22
62
  continue;
23
63
  }
24
64
  for (const match of text.matchAll(urlPattern)) {
65
+ candidates += 1;
66
+ if (candidates > MAX_URL_CANDIDATES) {
67
+ complete = false;
68
+ break scan;
69
+ }
70
+ let origin;
25
71
  try {
26
- const parsed = new URL(match[0].replace(/[.,;:!?]+$/u, ''));
72
+ const parsed = new URL(trimTrailingPunctuation(match[0]));
27
73
  if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
28
74
  continue;
29
- const origin = parsed.origin.toLowerCase();
30
- if (origins.has(origin))
31
- continue;
32
- if (origins.size >= MAX_ORIGINS) {
33
- complete = false;
34
- continue;
35
- }
36
- origins.add(origin);
75
+ origin = parsed.origin.toLowerCase();
37
76
  }
38
77
  catch {
39
78
  // URL-like text that does not parse is not capability evidence.
79
+ continue;
80
+ }
81
+ // No DNS name resolves past this length, and one such origin could be megabytes of report.
82
+ if (origin.length > MAX_ORIGIN_CHARS) {
83
+ complete = false;
84
+ continue;
85
+ }
86
+ if (origins.has(origin))
87
+ continue;
88
+ // A full set cannot change any more, so scanning on would only burn CPU.
89
+ if (origins.size >= MAX_ORIGINS) {
90
+ complete = false;
91
+ break scan;
40
92
  }
93
+ origins.add(origin);
41
94
  }
42
95
  }
43
- return { origins: [...origins].sort(), complete };
96
+ return {
97
+ origins: [...origins].sort(),
98
+ complete
99
+ };
44
100
  }
45
- function markdownSections(content) {
46
- let text;
47
- try {
48
- text = textDecoder.decode(content);
49
- }
50
- catch {
101
+ /* ******************************************** */
102
+ /* Markdown Parsing */
103
+ /* ******************************************** */
104
+ /**
105
+ * Linear-time equivalent of /^ {0,3}(#{1,6})[ \t]+(.+?)\s*#*\s*$/u. That regex lets its lazy title
106
+ * overlap the optional closing sequence, and backtracks cubically on a long run of blanks.
107
+ */
108
+ function atxHeading(line) {
109
+ const open = atxOpenPattern.exec(line);
110
+ if (!open)
51
111
  return null;
112
+ const level = open[1].length;
113
+ const spacing = open[2].length;
114
+ const rest = line.slice(open[0].length);
115
+ // Walk back over the closing sequence the title leaves out: blanks, then '#'s, then blanks again.
116
+ let end = rest.length;
117
+ while (end > 0 && whitespacePattern.test(rest[end - 1]))
118
+ end -= 1;
119
+ while (end > 0 && rest[end - 1] === '#')
120
+ end -= 1;
121
+ while (end > 0 && whitespacePattern.test(rest[end - 1]))
122
+ end -= 1;
123
+ // The title needs one character `.` accepts; failing that, the regex borrows one blank from the spacing.
124
+ if (end === 0 && (rest === '' || dotExcludedPattern.test(rest[0]))) {
125
+ return spacing >= 2 ? { level, title: '' } : null;
126
+ }
127
+ const title = rest.slice(0, Math.max(1, end));
128
+ return dotExcludedPattern.test(title) ? null : { level, title: title.trim() };
129
+ }
130
+ function markdownSections(input) {
131
+ const sections = [];
132
+ let text;
133
+ let currentLevel = 0;
134
+ let currentTitle = '';
135
+ let sectionStart = 0;
136
+ let activeFence = null;
137
+ if (typeof input === 'string')
138
+ text = input;
139
+ else {
140
+ try {
141
+ text = textDecoder.decode(input);
142
+ }
143
+ catch {
144
+ return null;
145
+ }
52
146
  }
53
- const sections = new Map();
54
- const occurrence = new Map();
55
- let current = '(document body)';
56
- let body = [];
57
- const flush = () => sections.set(current, body.join('\n'));
58
- for (const line of text.split(/\r?\n/u)) {
59
- const heading = /^(#{1,6})[ \t]+(.+?)\s*#*\s*$/u.exec(line);
60
- if (heading) {
61
- flush();
62
- const label = heading[2].trim() || '(empty heading)';
63
- const count = (occurrence.get(label) ?? 0) + 1;
64
- occurrence.set(label, count);
65
- current = count === 1 ? label : `${label} (${count})`;
66
- body = [line];
147
+ linePattern.lastIndex = 0;
148
+ while (linePattern.lastIndex < text.length) {
149
+ const lineStart = linePattern.lastIndex;
150
+ const match = linePattern.exec(text);
151
+ if (!match || match[0].length === 0)
152
+ break;
153
+ const line = match[0].replace(lineEndingPattern, '');
154
+ // 1. Track fenced code blocks (``` or ~~~) so '#' comments inside code are never mistaken for headings.
155
+ if (activeFence !== null) {
156
+ const close = fenceClosePattern.exec(line);
157
+ if (close && close[1][0] === activeFence.char && close[1].length >= activeFence.minLength) {
158
+ activeFence = null;
159
+ }
160
+ continue;
161
+ }
162
+ const fenceMatch = fenceOpenPattern.exec(line);
163
+ if (fenceMatch) {
164
+ const fenceToken = fenceMatch[1];
165
+ // In CommonMark, backtick info strings cannot contain backticks (inline code on one line).
166
+ if (fenceToken[0] !== '`' || !line.slice(fenceMatch[0].length).includes('`')) {
167
+ activeFence = { char: fenceToken[0], minLength: fenceToken.length };
168
+ continue;
169
+ }
67
170
  }
68
- else {
69
- body.push(line);
171
+ // 2. Outside code blocks, check for ATX headings (# through ######).
172
+ const heading = atxHeading(line);
173
+ if (!heading) {
174
+ continue;
70
175
  }
176
+ if (lineStart > sectionStart || currentLevel > 0) {
177
+ sections.push({
178
+ level: currentLevel,
179
+ title: currentTitle,
180
+ content: text.slice(sectionStart, lineStart),
181
+ });
182
+ // indexSectionsByKey keeps only MAX_INDEXED_SECTIONS; one more is enough for it to report truncation.
183
+ if (sections.length > MAX_INDEXED_SECTIONS) {
184
+ return sections;
185
+ }
186
+ }
187
+ currentLevel = heading.level;
188
+ currentTitle = heading.title;
189
+ sectionStart = lineStart;
190
+ }
191
+ if (text.length > sectionStart || currentLevel > 0) {
192
+ sections.push({
193
+ level: currentLevel,
194
+ title: currentTitle,
195
+ content: text.slice(sectionStart),
196
+ });
71
197
  }
72
- flush();
73
198
  return sections;
74
199
  }
75
- function changedSections(filePath, before, after) {
200
+ function clampHeadingLevel(level) {
201
+ if (!Number.isFinite(level) || level <= 0) {
202
+ return 0;
203
+ }
204
+ return Math.min(MAX_HEADING_LEVEL, Math.floor(level));
205
+ }
206
+ function truncateTitle(title) {
207
+ if (title.length <= MAX_LABEL_TITLE_CHARS) {
208
+ return title;
209
+ }
210
+ let end = MAX_LABEL_TITLE_CHARS;
211
+ const last = title.charCodeAt(end - 1);
212
+ // Never split a surrogate pair.
213
+ if (last >= 0xd800 && last <= 0xdbff) {
214
+ end -= 1;
215
+ }
216
+ return `${title.slice(0, end)}...`;
217
+ }
218
+ function formatSectionLabel(section, occurrence) {
219
+ const safeLevel = clampHeadingLevel(section.level);
220
+ const safeTitle = truncateTitle(section.title.trim()) || LABEL_EMPTY_HEADING;
221
+ const baseLabel = safeLevel === 0
222
+ ? LABEL_DOCUMENT_BODY
223
+ : `${'#'.repeat(safeLevel)} ${safeTitle}`;
224
+ return !Number.isFinite(occurrence) || occurrence <= 1
225
+ ? baseLabel
226
+ : `${baseLabel} (${Math.floor(occurrence)})`;
227
+ }
228
+ /* ******************************************** */
229
+ /* Section Indexing */
230
+ /* ******************************************** */
231
+ function indexSectionsByKey(sections) {
232
+ const indexed = new Map();
233
+ const counts = new Map();
234
+ let truncated = false;
235
+ if (!Array.isArray(sections)) {
236
+ return { indexed, truncated };
237
+ }
238
+ for (const section of sections) {
239
+ if (!section || typeof section !== 'object')
240
+ continue;
241
+ if (indexed.size >= MAX_INDEXED_SECTIONS) {
242
+ truncated = true;
243
+ break;
244
+ }
245
+ const safeLevel = clampHeadingLevel(section.level);
246
+ const rawTitle = typeof section.title === 'string' ? section.title : '';
247
+ const rawContent = typeof section.content === 'string' ? section.content : '';
248
+ const safeTitle = rawTitle.trim().normalize('NFC');
249
+ // A fixed-size key: V8 hashes strings over 16,383 chars by length alone, so raw long titles would all
250
+ // land in one Map bucket. The hex digest also has no delimiter for a crafted title to collide with.
251
+ const baseKey = `${safeLevel}:${sha256Hex(Buffer.from(safeTitle, 'utf8'))}`;
252
+ const occurrence = (counts.get(baseKey) ?? 0) + 1;
253
+ counts.set(baseKey, occurrence);
254
+ const uniqueKey = `${occurrence}:${baseKey}`;
255
+ indexed.set(uniqueKey, {
256
+ label: formatSectionLabel({ level: safeLevel, title: safeTitle, content: rawContent }, occurrence),
257
+ content: rawContent.replace(crlfPattern, '\n'),
258
+ });
259
+ }
260
+ return { indexed, truncated };
261
+ }
262
+ function changedSections(filePath, before, after, budget) {
76
263
  if (!before || !after)
77
- return { sections: [before ? '(file removed)' : '(file added)'], truncated: false };
78
- if (before.equals(after))
264
+ return { sections: [before ? LABEL_FILE_REMOVED : LABEL_FILE_ADDED], truncated: false };
265
+ if (Buffer.compare(before, after) === 0)
79
266
  return { sections: [], truncated: false };
80
267
  if (!/\.md$/iu.test(filePath))
81
- return { sections: ['(whole file)'], truncated: false };
82
- if (before.length > MAX_ANALYZED_TEXT_BYTES || after.length > MAX_ANALYZED_TEXT_BYTES)
83
- return { sections: ['(whole file; size limit)'], truncated: true };
84
- const beforeSections = markdownSections(before);
85
- const afterSections = markdownSections(after);
86
- if (!beforeSections || !afterSections)
87
- return { sections: ['(whole file; non-text content)'], truncated: false };
88
- const names = new Set([...beforeSections.keys(), ...afterSections.keys()]);
89
- const changed = [...names].filter((name) => beforeSections.get(name) !== afterSections.get(name)).sort();
90
- return { sections: changed.slice(0, MAX_REPORTED_SECTIONS), truncated: changed.length > MAX_REPORTED_SECTIONS };
268
+ return { sections: [LABEL_WHOLE_FILE], truncated: false };
269
+ if (before.byteLength > MAX_ANALYZED_TEXT_BYTES || after.byteLength > MAX_ANALYZED_TEXT_BYTES)
270
+ return { sections: [LABEL_SIZE_LIMIT], truncated: true };
271
+ const cost = before.byteLength + after.byteLength;
272
+ if (cost > budget.remainingBytes)
273
+ return { sections: [LABEL_TOTAL_SIZE_LIMIT], truncated: true };
274
+ budget.remainingBytes -= cost;
275
+ const beforeParsed = markdownSections(before);
276
+ const afterParsed = markdownSections(after);
277
+ if (!beforeParsed || !afterParsed)
278
+ return { sections: [LABEL_NON_TEXT], truncated: false };
279
+ const beforeResult = indexSectionsByKey(beforeParsed);
280
+ const afterResult = indexSectionsByKey(afterParsed);
281
+ const beforeMap = beforeResult.indexed;
282
+ const afterMap = afterResult.indexed;
283
+ const allKeys = new Set([...beforeMap.keys(), ...afterMap.keys()]);
284
+ const changed = [];
285
+ for (const key of allKeys) {
286
+ const beforeEntry = beforeMap.get(key);
287
+ const afterEntry = afterMap.get(key);
288
+ if (beforeEntry?.content !== afterEntry?.content) {
289
+ changed.push((afterEntry ?? beforeEntry).label);
290
+ }
291
+ }
292
+ // If bytes differed (e.g. CRLF vs LF) while normalized section contents matched, still report whole-file change.
293
+ if (changed.length === 0) {
294
+ return {
295
+ sections: [LABEL_WHOLE_FILE],
296
+ truncated: beforeResult.truncated || afterResult.truncated,
297
+ };
298
+ }
299
+ changed.sort();
300
+ return {
301
+ sections: changed.slice(0, MAX_REPORTED_SECTIONS),
302
+ truncated: beforeResult.truncated ||
303
+ afterResult.truncated ||
304
+ changed.length > MAX_REPORTED_SECTIONS,
305
+ };
306
+ }
307
+ function classifyFileChange(before, after) {
308
+ if (!before) {
309
+ return 'added';
310
+ }
311
+ if (!after) {
312
+ return 'deleted';
313
+ }
314
+ if (before.sha256 === after.sha256) {
315
+ return 'mode-changed';
316
+ }
317
+ return 'modified';
91
318
  }
92
319
  function fileChanges(beforeFiles, afterFiles, beforeContents, afterContents) {
93
- const beforeByPath = new Map(beforeFiles.map((file) => [file.path, file]));
94
- const afterByPath = new Map(afterFiles.map((file) => [file.path, file]));
95
- const paths = [...new Set([...beforeByPath.keys(), ...afterByPath.keys()])].sort();
96
- const changes = [];
97
- for (const filePath of paths) {
320
+ const beforeByPath = new Map();
321
+ const afterByPath = new Map();
322
+ const pathSet = new Set();
323
+ const files = [];
324
+ const sectionBudget = { remainingBytes: MAX_SECTION_DIFF_BYTES };
325
+ let truncated = false;
326
+ for (const file of beforeFiles) {
327
+ beforeByPath.set(file.path, file);
328
+ pathSet.add(file.path);
329
+ }
330
+ for (const file of afterFiles) {
331
+ afterByPath.set(file.path, file);
332
+ pathSet.add(file.path);
333
+ }
334
+ const sortedPaths = [...pathSet].sort(compareTreePaths);
335
+ for (const filePath of sortedPaths) {
98
336
  const before = beforeByPath.get(filePath);
99
337
  const after = afterByPath.get(filePath);
100
- if (before && after && before.sha256 === after.sha256 && before.exec === after.exec)
338
+ if (before &&
339
+ after &&
340
+ before.sha256 === after.sha256 &&
341
+ before.size === after.size &&
342
+ before.exec === after.exec) {
101
343
  continue;
102
- const change = !before ? 'added' : !after ? 'deleted' : before.sha256 === after.sha256 ? 'mode-changed' : 'modified';
103
- const sections = changedSections(filePath, beforeContents.get(filePath), afterContents.get(filePath));
104
- changes.push({
344
+ }
345
+ // Stop expensive Markdown section diffing once the reported file budget is reached.
346
+ if (files.length >= MAX_REPORTED_FILES) {
347
+ truncated = true;
348
+ break;
349
+ }
350
+ const change = classifyFileChange(before, after);
351
+ const sectionDiff = change === 'mode-changed'
352
+ ? { sections: [LABEL_EXEC_BIT], truncated: false }
353
+ : changedSections(filePath, beforeContents.get(filePath), afterContents.get(filePath), sectionBudget);
354
+ if (sectionDiff.truncated) {
355
+ truncated = true;
356
+ }
357
+ files.push({
105
358
  path: filePath,
106
359
  change,
107
360
  before_bytes: before?.size ?? 0,
108
361
  after_bytes: after?.size ?? 0,
109
362
  exec_before: before?.exec ?? null,
110
363
  exec_after: after?.exec ?? null,
111
- changed_sections: change === 'mode-changed' ? ['(executable bit)'] : sections.sections,
112
- sections_truncated: sections.truncated,
364
+ changed_sections: sectionDiff.sections,
365
+ sections_truncated: sectionDiff.truncated,
113
366
  });
114
367
  }
115
- return changes;
368
+ return { files, truncated };
116
369
  }
117
- /**
370
+ /*
118
371
  * Compares two Skill directories. Any digest difference requires a new certificate,
119
372
  * whatever the capability evidence says: unchanged origins never waive a content change.
120
373
  */
@@ -122,13 +375,16 @@ export async function diffSkillTrees(baseRoot, candidateRoot) {
122
375
  const base = await collectSkillTree(baseRoot, { includeContents: true });
123
376
  const candidate = await collectSkillTree(candidateRoot, { includeContents: true });
124
377
  const changed = base.digest !== candidate.digest;
125
- const changes = changed ? fileChanges(base.files, candidate.files, base.contents, candidate.contents) : [];
126
- const bounded = changes.slice(0, MAX_REPORTED_FILES);
127
- const truncated = changes.length > MAX_REPORTED_FILES || bounded.some((entry) => entry.sections_truncated);
378
+ const diff = changed
379
+ ? fileChanges(base.files, candidate.files, base.contents, candidate.contents)
380
+ : { files: [], truncated: false };
128
381
  const baseOrigins = collectOrigins(base.contents);
129
- const candidateOrigins = collectOrigins(candidate.contents);
130
- const added = candidateOrigins.origins.filter((origin) => !baseOrigins.origins.includes(origin));
131
- const removed = baseOrigins.origins.filter((origin) => !candidateOrigins.origins.includes(origin));
382
+ // Equal digests mean equal contents: a second scan could only repeat the first.
383
+ const candidateOrigins = changed ? collectOrigins(candidate.contents) : baseOrigins;
384
+ const baseOriginSet = new Set(baseOrigins.origins);
385
+ const candidateOriginSet = new Set(candidateOrigins.origins);
386
+ const added = candidateOrigins.origins.filter((origin) => !baseOriginSet.has(origin));
387
+ const removed = baseOrigins.origins.filter((origin) => !candidateOriginSet.has(origin));
132
388
  const capabilityChanged = added.length > 0 || removed.length > 0;
133
389
  return {
134
390
  result: !changed ? 'UNCHANGED' : capabilityChanged ? 'CAPABILITY_CHANGED' : 'CONTENT_CHANGED',
@@ -137,12 +393,12 @@ export async function diffSkillTrees(baseRoot, candidateRoot) {
137
393
  candidate_digest: candidate.digest,
138
394
  capability_evidence: {
139
395
  profile: 'mago.network-origin-scan/v1',
140
- analysis_complete: baseOrigins.complete && candidateOrigins.complete && !truncated,
396
+ analysis_complete: baseOrigins.complete && candidateOrigins.complete && !diff.truncated,
141
397
  added_network_origins: added,
142
398
  removed_network_origins: removed,
143
399
  note: 'Partial evidence: only HTTP(S) origins in text files are detected. No detected change does not make changed content safe or approved.',
144
400
  },
145
- diff_truncated: truncated,
146
- files: bounded,
401
+ diff_truncated: diff.truncated,
402
+ files: diff.files,
147
403
  };
148
404
  }
@@ -2,10 +2,12 @@ import { type KeyObject } from 'node:crypto';
2
2
  export interface Envelope {
3
3
  payloadType: string;
4
4
  payload: string;
5
- signatures: [{
6
- keyid: string;
7
- sig: string;
8
- }];
5
+ signatures: [
6
+ {
7
+ keyid: string;
8
+ sig: string;
9
+ }
10
+ ];
9
11
  }
10
12
  /** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
11
13
  export declare function preAuthEncoding(payloadType: string, payload: Uint8Array): Buffer;
package/dist/src/dsse.js CHANGED
@@ -8,13 +8,22 @@ const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/
8
8
  export function preAuthEncoding(payloadType, payload) {
9
9
  const type = Buffer.from(payloadType, 'utf8');
10
10
  return Buffer.concat([
11
- Buffer.from(`DSSEv1 ${type.length} `, 'ascii'), type,
12
- Buffer.from(` ${payload.length} `, 'ascii'), Buffer.from(payload),
11
+ Buffer.from(`DSSEv1 ${type.length} `, 'ascii'),
12
+ type,
13
+ Buffer.from(` ${payload.length} `, 'ascii'),
14
+ Buffer.from(payload),
13
15
  ]);
14
16
  }
15
17
  export function signEnvelope(payloadType, payload, keyId, privateKey) {
16
18
  const sig = sign(null, preAuthEncoding(payloadType, payload), privateKey).toString('base64');
17
- return { payloadType, payload: Buffer.from(payload).toString('base64'), signatures: [{ keyid: keyId, sig }] };
19
+ return {
20
+ payloadType,
21
+ payload: Buffer.from(payload).toString('base64'),
22
+ signatures: [{
23
+ keyid: keyId,
24
+ sig
25
+ }]
26
+ };
18
27
  }
19
28
  export function envelopeBytes(envelope) {
20
29
  return canonicalBytes(envelope);
@@ -34,15 +43,22 @@ export function parseEnvelope(bytes, label) {
34
43
  const payloadType = requireString(value.payloadType, `${label} payloadType`, 256);
35
44
  const payloadBytes = decodeBase64(value.payload, `${label} payload`, 6 * 1024 * 1024);
36
45
  const signatures = requireArray(value.signatures, `${label} signatures`, 1);
37
- if (signatures.length !== 1)
38
- throw new Error(`${label} must carry exactly one signature`);
39
46
  const signature = exactKeys(signatures[0], ['keyid', 'sig'], `${label} signature`);
40
47
  const keyid = validateKeyId(signature.keyid, `${label} signature keyid`);
41
48
  const sigBytes = decodeBase64(signature.sig, `${label} signature`, 128);
49
+ if (signatures.length !== 1)
50
+ throw new Error(`${label} must carry exactly one signature`);
42
51
  if (sigBytes.length !== 64)
43
52
  throw new Error(`${label} signature must be a 64-byte Ed25519 signature`);
44
53
  return {
45
- payloadType, payload: value.payload, signatures: [{ keyid, sig: signature.sig }], payloadBytes, sigBytes,
54
+ payloadType,
55
+ payload: value.payload,
56
+ signatures: [{
57
+ keyid,
58
+ sig: signature.sig
59
+ }],
60
+ payloadBytes,
61
+ sigBytes,
46
62
  };
47
63
  }
48
64
  export function verifyEnvelopeSignature(envelope, publicKey) {
@@ -1,5 +1,8 @@
1
1
  export declare function isInside(root: string, candidate: string): boolean;
2
- /** Reads a regular, non-symlink file, failing if it changes while being read. */
2
+ /**
3
+ * Reads a regular, non-symlink file, failing if it changes while being read.
4
+ * The type and size are checked before any content is read, and at most `maxBytes` (+1 to detect growth) are read.
5
+ */
3
6
  export declare function readRegularFile(filePath: string, label: string, maxBytes?: number): Promise<Buffer>;
4
7
  /** Resolves a file path and requires it to be outside `root` (both canonicalized). */
5
8
  export declare function resolveOutside(filePath: string, root: string, label: string, { allowMissing }?: {
@@ -7,5 +10,31 @@ export declare function resolveOutside(filePath: string, root: string, label: st
7
10
  }): Promise<string>;
8
11
  /** Creates a new file; refuses to overwrite anything that already exists. */
9
12
  export declare function writeNewFile(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
10
- /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
11
- export declare function writeFileAtomic(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
13
+ /** The file a write was meant to replace was no longer the one that was read (see `writeFileAtomic`'s `expectSha256`). */
14
+ export declare class FileChangedError extends Error {
15
+ constructor(message?: string);
16
+ }
17
+ /**
18
+ * Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one.
19
+ *
20
+ * `options.expectSha256`: `undefined` checks nothing. A `sha256:<hex>` string requires the existing path to be a regular
21
+ * file with that SHA-256, `null` requires the path not to exist. The check runs after the temporary file is written and
22
+ * immediately before the rename; a mismatch removes the temporary file and throws `FileChangedError`. A process that can
23
+ * write the folder can still swap the file between that check and the rename.
24
+ */
25
+ export declare function writeFileAtomic(filePath: string, bytes: Uint8Array, mode?: number, options?: {
26
+ expectSha256?: string | null;
27
+ }): Promise<string>;
28
+ /** Canonical path of `target`, resolving symlinks on the longest existing prefix. A dangling link on the way is an error. */
29
+ export declare function realpathAllowingMissing(target: string): Promise<string>;
30
+ /**
31
+ * Resolves a policy-supplied path against `base` and requires it to name something strictly inside `base`,
32
+ * after symlinks in its parent directories are resolved. An existing final component must be a regular,
33
+ * non-symlink file. Returns the canonical path.
34
+ */
35
+ export declare function resolveInsideDirectory(base: string, item: string, label: string): Promise<string>;
36
+ /**
37
+ * Appends text to a log file, creating it (mode 600) if needed. Refuses symbolic links and anything that is not
38
+ * a regular file; O_NONBLOCK keeps a FIFO from hanging the open.
39
+ */
40
+ export declare function appendToRegularFile(filePath: string, text: string, label: string, mode?: number): Promise<void>;