@mago-foundation/mago-ski 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +139 -2
- package/action.yml +58 -0
- package/dist/hosts/github/run.d.ts +27 -0
- package/dist/hosts/github/run.js +152 -0
- package/dist/hosts/pi/index.d.ts +13 -0
- package/dist/hosts/pi/index.js +550 -0
- package/dist/hosts/pi/paths.d.ts +9 -0
- package/dist/hosts/pi/paths.js +55 -0
- package/dist/src/admin.d.ts +74 -0
- package/dist/src/admin.js +243 -0
- package/dist/src/canonical-json.d.ts +12 -0
- package/dist/src/canonical-json.js +149 -0
- package/dist/src/certificate.d.ts +34 -0
- package/dist/src/certificate.js +112 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +595 -0
- package/dist/src/diff.d.ts +26 -0
- package/dist/src/diff.js +404 -0
- package/dist/src/dsse.d.ts +25 -0
- package/dist/src/dsse.js +71 -0
- package/dist/src/experimental/sigstore.d.ts +26 -0
- package/dist/src/experimental/sigstore.js +153 -0
- package/dist/src/fs-safe.d.ts +27 -0
- package/dist/src/fs-safe.js +229 -0
- package/dist/src/index.d.ts +14 -0
- package/dist/src/index.js +14 -0
- package/dist/src/keys.d.ts +21 -0
- package/dist/src/keys.js +154 -0
- package/dist/src/main-module.d.ts +5 -0
- package/dist/src/main-module.js +19 -0
- package/dist/src/names.d.ts +7 -0
- package/dist/src/names.js +38 -0
- package/dist/src/policy.d.ts +81 -0
- package/dist/src/policy.js +349 -0
- package/dist/src/revocations.d.ts +28 -0
- package/dist/src/revocations.js +93 -0
- package/dist/src/time.d.ts +25 -0
- package/dist/src/time.js +74 -0
- package/dist/src/tree-digest.d.ts +46 -0
- package/dist/src/tree-digest.js +268 -0
- package/dist/src/trust-root.d.ts +38 -0
- package/dist/src/trust-root.js +136 -0
- package/dist/src/verify.d.ts +96 -0
- package/dist/src/verify.js +380 -0
- package/docs/hosts/adapter-interface.md +33 -0
- package/docs/hosts/github-action.md +45 -0
- package/docs/hosts/pi.md +41 -0
- package/docs/spec/root-recovery-v1.md +430 -0
- package/docs/spec/skill-certificate-v1.md +60 -0
- package/docs/spec/skill-tree-v2.md +59 -0
- package/docs/spec/trust-documents-v1.md +103 -0
- package/docs/spec/verification.md +56 -0
- package/docs/threat-model.md +45 -0
- package/package.json +77 -4
package/dist/src/diff.js
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import { collectSkillTree, compareTreePaths, sha256Hex } from "./tree-digest.js";
|
|
2
|
+
const textDecoder = new TextDecoder('utf-8', { fatal: true });
|
|
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;
|
|
6
|
+
const MAX_REPORTED_FILES = 200;
|
|
7
|
+
const MAX_REPORTED_SECTIONS = 32;
|
|
8
|
+
const MAX_INDEXED_SECTIONS = 4_096;
|
|
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.
|
|
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
|
+
}
|
|
47
|
+
function collectOrigins(contents) {
|
|
48
|
+
const origins = new Set();
|
|
49
|
+
let complete = true;
|
|
50
|
+
let candidates = 0;
|
|
51
|
+
scan: for (const content of contents.values()) {
|
|
52
|
+
if (content.length > MAX_ANALYZED_TEXT_BYTES || content.includes(0)) {
|
|
53
|
+
complete = false;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
let text;
|
|
57
|
+
try {
|
|
58
|
+
text = textDecoder.decode(content);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
complete = false;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
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;
|
|
71
|
+
try {
|
|
72
|
+
const parsed = new URL(trimTrailingPunctuation(match[0]));
|
|
73
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
|
|
74
|
+
continue;
|
|
75
|
+
origin = parsed.origin.toLowerCase();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
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;
|
|
92
|
+
}
|
|
93
|
+
origins.add(origin);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
origins: [...origins].sort(),
|
|
98
|
+
complete
|
|
99
|
+
};
|
|
100
|
+
}
|
|
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)
|
|
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
|
+
}
|
|
146
|
+
}
|
|
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
|
+
}
|
|
170
|
+
}
|
|
171
|
+
// 2. Outside code blocks, check for ATX headings (# through ######).
|
|
172
|
+
const heading = atxHeading(line);
|
|
173
|
+
if (!heading) {
|
|
174
|
+
continue;
|
|
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
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return sections;
|
|
199
|
+
}
|
|
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) {
|
|
263
|
+
if (!before || !after)
|
|
264
|
+
return { sections: [before ? LABEL_FILE_REMOVED : LABEL_FILE_ADDED], truncated: false };
|
|
265
|
+
if (Buffer.compare(before, after) === 0)
|
|
266
|
+
return { sections: [], truncated: false };
|
|
267
|
+
if (!/\.md$/iu.test(filePath))
|
|
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';
|
|
318
|
+
}
|
|
319
|
+
function fileChanges(beforeFiles, afterFiles, beforeContents, afterContents) {
|
|
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) {
|
|
336
|
+
const before = beforeByPath.get(filePath);
|
|
337
|
+
const after = afterByPath.get(filePath);
|
|
338
|
+
if (before &&
|
|
339
|
+
after &&
|
|
340
|
+
before.sha256 === after.sha256 &&
|
|
341
|
+
before.size === after.size &&
|
|
342
|
+
before.exec === after.exec) {
|
|
343
|
+
continue;
|
|
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({
|
|
358
|
+
path: filePath,
|
|
359
|
+
change,
|
|
360
|
+
before_bytes: before?.size ?? 0,
|
|
361
|
+
after_bytes: after?.size ?? 0,
|
|
362
|
+
exec_before: before?.exec ?? null,
|
|
363
|
+
exec_after: after?.exec ?? null,
|
|
364
|
+
changed_sections: sectionDiff.sections,
|
|
365
|
+
sections_truncated: sectionDiff.truncated,
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return { files, truncated };
|
|
369
|
+
}
|
|
370
|
+
/*
|
|
371
|
+
* Compares two Skill directories. Any digest difference requires a new certificate,
|
|
372
|
+
* whatever the capability evidence says: unchanged origins never waive a content change.
|
|
373
|
+
*/
|
|
374
|
+
export async function diffSkillTrees(baseRoot, candidateRoot) {
|
|
375
|
+
const base = await collectSkillTree(baseRoot, { includeContents: true });
|
|
376
|
+
const candidate = await collectSkillTree(candidateRoot, { includeContents: true });
|
|
377
|
+
const changed = base.digest !== candidate.digest;
|
|
378
|
+
const diff = changed
|
|
379
|
+
? fileChanges(base.files, candidate.files, base.contents, candidate.contents)
|
|
380
|
+
: { files: [], truncated: false };
|
|
381
|
+
const baseOrigins = collectOrigins(base.contents);
|
|
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));
|
|
388
|
+
const capabilityChanged = added.length > 0 || removed.length > 0;
|
|
389
|
+
return {
|
|
390
|
+
result: !changed ? 'UNCHANGED' : capabilityChanged ? 'CAPABILITY_CHANGED' : 'CONTENT_CHANGED',
|
|
391
|
+
recertification_required: changed,
|
|
392
|
+
base_digest: base.digest,
|
|
393
|
+
candidate_digest: candidate.digest,
|
|
394
|
+
capability_evidence: {
|
|
395
|
+
profile: 'mago.network-origin-scan/v1',
|
|
396
|
+
analysis_complete: baseOrigins.complete && candidateOrigins.complete && !diff.truncated,
|
|
397
|
+
added_network_origins: added,
|
|
398
|
+
removed_network_origins: removed,
|
|
399
|
+
note: 'Partial evidence: only HTTP(S) origins in text files are detected. No detected change does not make changed content safe or approved.',
|
|
400
|
+
},
|
|
401
|
+
diff_truncated: diff.truncated,
|
|
402
|
+
files: diff.files,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
export interface Envelope {
|
|
3
|
+
payloadType: string;
|
|
4
|
+
payload: string;
|
|
5
|
+
signatures: [
|
|
6
|
+
{
|
|
7
|
+
keyid: string;
|
|
8
|
+
sig: string;
|
|
9
|
+
}
|
|
10
|
+
];
|
|
11
|
+
}
|
|
12
|
+
/** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
|
|
13
|
+
export declare function preAuthEncoding(payloadType: string, payload: Uint8Array): Buffer;
|
|
14
|
+
export declare function signEnvelope(payloadType: string, payload: Uint8Array, keyId: string, privateKey: KeyObject): Envelope;
|
|
15
|
+
export declare function envelopeBytes(envelope: Envelope): Buffer;
|
|
16
|
+
/** Parses an envelope file. Does not check the signature. */
|
|
17
|
+
export declare function parseEnvelope(bytes: Uint8Array, label: string): Envelope & {
|
|
18
|
+
payloadBytes: Buffer;
|
|
19
|
+
sigBytes: Buffer;
|
|
20
|
+
};
|
|
21
|
+
export declare function verifyEnvelopeSignature(envelope: {
|
|
22
|
+
payloadType: string;
|
|
23
|
+
payloadBytes: Buffer;
|
|
24
|
+
sigBytes: Buffer;
|
|
25
|
+
}, publicKey: KeyObject): boolean;
|
package/dist/src/dsse.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// DSSE (Dead Simple Signing Envelope) v1 with exactly one Ed25519 signature.
|
|
2
|
+
// https://github.com/secure-systems-lab/dsse/blob/master/protocol.md
|
|
3
|
+
import { sign, verify } from 'node:crypto';
|
|
4
|
+
import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
|
|
5
|
+
import { validateKeyId } from "./keys.js";
|
|
6
|
+
const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
|
|
7
|
+
/** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
|
|
8
|
+
export function preAuthEncoding(payloadType, payload) {
|
|
9
|
+
const type = Buffer.from(payloadType, 'utf8');
|
|
10
|
+
return Buffer.concat([
|
|
11
|
+
Buffer.from(`DSSEv1 ${type.length} `, 'ascii'),
|
|
12
|
+
type,
|
|
13
|
+
Buffer.from(` ${payload.length} `, 'ascii'),
|
|
14
|
+
Buffer.from(payload),
|
|
15
|
+
]);
|
|
16
|
+
}
|
|
17
|
+
export function signEnvelope(payloadType, payload, keyId, privateKey) {
|
|
18
|
+
const sig = sign(null, preAuthEncoding(payloadType, payload), privateKey).toString('base64');
|
|
19
|
+
return {
|
|
20
|
+
payloadType,
|
|
21
|
+
payload: Buffer.from(payload).toString('base64'),
|
|
22
|
+
signatures: [{
|
|
23
|
+
keyid: keyId,
|
|
24
|
+
sig
|
|
25
|
+
}]
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function envelopeBytes(envelope) {
|
|
29
|
+
return canonicalBytes(envelope);
|
|
30
|
+
}
|
|
31
|
+
function decodeBase64(value, label, maxLength) {
|
|
32
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > maxLength || !BASE64_PATTERN.test(value)) {
|
|
33
|
+
throw new Error(`${label} must be canonical base64`);
|
|
34
|
+
}
|
|
35
|
+
const bytes = Buffer.from(value, 'base64');
|
|
36
|
+
if (bytes.toString('base64') !== value)
|
|
37
|
+
throw new Error(`${label} must be canonical base64`);
|
|
38
|
+
return bytes;
|
|
39
|
+
}
|
|
40
|
+
/** Parses an envelope file. Does not check the signature. */
|
|
41
|
+
export function parseEnvelope(bytes, label) {
|
|
42
|
+
const value = exactKeys(parseCanonicalJsonBytes(bytes, label), ['payloadType', 'payload', 'signatures'], label);
|
|
43
|
+
const payloadType = requireString(value.payloadType, `${label} payloadType`, 256);
|
|
44
|
+
const payloadBytes = decodeBase64(value.payload, `${label} payload`, 6 * 1024 * 1024);
|
|
45
|
+
const signatures = requireArray(value.signatures, `${label} signatures`, 1);
|
|
46
|
+
const signature = exactKeys(signatures[0], ['keyid', 'sig'], `${label} signature`);
|
|
47
|
+
const keyid = validateKeyId(signature.keyid, `${label} signature keyid`);
|
|
48
|
+
const sigBytes = decodeBase64(signature.sig, `${label} signature`, 128);
|
|
49
|
+
if (signatures.length !== 1)
|
|
50
|
+
throw new Error(`${label} must carry exactly one signature`);
|
|
51
|
+
if (sigBytes.length !== 64)
|
|
52
|
+
throw new Error(`${label} signature must be a 64-byte Ed25519 signature`);
|
|
53
|
+
return {
|
|
54
|
+
payloadType,
|
|
55
|
+
payload: value.payload,
|
|
56
|
+
signatures: [{
|
|
57
|
+
keyid,
|
|
58
|
+
sig: signature.sig
|
|
59
|
+
}],
|
|
60
|
+
payloadBytes,
|
|
61
|
+
sigBytes,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function verifyEnvelopeSignature(envelope, publicKey) {
|
|
65
|
+
try {
|
|
66
|
+
return verify(null, preAuthEncoding(envelope.payloadType, envelope.payloadBytes), publicKey, envelope.sigBytes);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const COSIGN_PINNED_VERSION = "v3.1.3";
|
|
2
|
+
export declare const COSIGN_BINARY_SHA256: Readonly<Record<string, string>>;
|
|
3
|
+
export declare class CosignVerificationError extends Error {
|
|
4
|
+
readonly exitCode = 1;
|
|
5
|
+
constructor(message?: string);
|
|
6
|
+
}
|
|
7
|
+
export declare function assertPinnedCosignBinary(binaryPath: string): Promise<string>;
|
|
8
|
+
export declare function buildCosignSignArgs(bundlePath: string, payloadPath: string): string[];
|
|
9
|
+
export declare function buildCosignVerifyArgs(bundlePath: string, trustedRootPath: string, identity: string, issuer: string, payloadPath: string): string[];
|
|
10
|
+
export declare function signSigstoreBlob(options: {
|
|
11
|
+
binaryPath: string;
|
|
12
|
+
payloadPath: string;
|
|
13
|
+
bundlePath: string;
|
|
14
|
+
}): Promise<{
|
|
15
|
+
bundlePath: string;
|
|
16
|
+
}>;
|
|
17
|
+
export declare function verifySigstoreBlob(options: {
|
|
18
|
+
binaryPath: string;
|
|
19
|
+
payloadPath: string;
|
|
20
|
+
bundlePath: string;
|
|
21
|
+
trustedRootPath: string;
|
|
22
|
+
certificateIdentity: string;
|
|
23
|
+
certificateOidcIssuer: string;
|
|
24
|
+
}): Promise<{
|
|
25
|
+
valid: true;
|
|
26
|
+
}>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Sigstore/Cosign adapter, kept from the skill-pki preview. Not on the Phase 1 critical path:
|
|
2
|
+
// the certificate verifier does not use it. It verifies blobs with a checksum-pinned Cosign binary.
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { constants as fsConstants } from 'node:fs';
|
|
6
|
+
import { lstat, open, realpath } from 'node:fs/promises';
|
|
7
|
+
import { endianness } from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
export const COSIGN_PINNED_VERSION = 'v3.1.3';
|
|
11
|
+
// Pins come from the release checksum file, whose authentic public Sigstore bundle is tested offline.
|
|
12
|
+
export const COSIGN_BINARY_SHA256 = Object.freeze({
|
|
13
|
+
'darwin-arm64': '5cf948c2f4dfe59687bdd0b8523709067383e03982cc543475c8a7dc70e92a76',
|
|
14
|
+
'darwin-x64': '2347488e5d5b25336644024dfeca5601b190e91197a71a917bda44744aff106c',
|
|
15
|
+
'linux-arm': '3275e61b43a45aa56a6242b49475d8a01874a07469c08fc32d027ba554996e4c',
|
|
16
|
+
'linux-arm64': 'c5d324e091826b0d7a78eb16fef316450b4eb9aaec045611c08ba06f5e73220a',
|
|
17
|
+
'linux-ppc64le': '15619e924681c97e0fb4f79c0eb8ef5d29665a06fe6a25078500985aed79321b',
|
|
18
|
+
'linux-riscv64': '9736177c6be33e4493304fc34feb8aa29209d531b3d40142d7e2a40bbe2f542f',
|
|
19
|
+
'linux-s390x': '253b571ef9e1aef72ef56d74f464ef9fe5182dc83b1ab430bbffbc4c8e43e7fd',
|
|
20
|
+
'linux-x64': '4629c757b7618056f8ddd7e2625ae9fdd94c0372a65049520bc7d9df9efc7f71',
|
|
21
|
+
'win32-x64': '9fe59be0eca1271873ce019061335eb1ac419b7059202e797828467ddabe33be',
|
|
22
|
+
});
|
|
23
|
+
const execFileAsync = promisify(execFile);
|
|
24
|
+
const noFollow = fsConstants.O_NOFOLLOW ?? 0;
|
|
25
|
+
const MAX_BINARY_BYTES = 256n * 1024n * 1024n;
|
|
26
|
+
export class CosignVerificationError extends Error {
|
|
27
|
+
exitCode = 1;
|
|
28
|
+
constructor(message = 'Cosign verification failed') {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = 'CosignVerificationError';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function platformKey(platform = process.platform, arch = process.arch) {
|
|
34
|
+
if (platform === 'linux' && arch === 'ppc64' && endianness() === 'LE')
|
|
35
|
+
return 'linux-ppc64le';
|
|
36
|
+
return `${platform}-${arch}`;
|
|
37
|
+
}
|
|
38
|
+
async function hashFile(filePath) {
|
|
39
|
+
const handle = await open(filePath, fsConstants.O_RDONLY | noFollow);
|
|
40
|
+
try {
|
|
41
|
+
const initial = await handle.stat({ bigint: true });
|
|
42
|
+
if (!initial.isFile())
|
|
43
|
+
throw new Error('Cosign binary must be a regular file');
|
|
44
|
+
if (initial.size > MAX_BINARY_BYTES)
|
|
45
|
+
throw new Error('Cosign binary exceeds the supported size limit');
|
|
46
|
+
const hash = createHash('sha256');
|
|
47
|
+
const buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
48
|
+
let total = 0n;
|
|
49
|
+
while (true) {
|
|
50
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
51
|
+
if (bytesRead === 0)
|
|
52
|
+
break;
|
|
53
|
+
total += BigInt(bytesRead);
|
|
54
|
+
if (total > MAX_BINARY_BYTES)
|
|
55
|
+
throw new Error('Cosign binary exceeds the supported size limit');
|
|
56
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
57
|
+
}
|
|
58
|
+
const final = await handle.stat({ bigint: true });
|
|
59
|
+
if (total !== initial.size || initial.dev !== final.dev || initial.ino !== final.ino ||
|
|
60
|
+
initial.size !== final.size || initial.mtimeNs !== final.mtimeNs || initial.ctimeNs !== final.ctimeNs) {
|
|
61
|
+
throw new Error('Cosign binary changed while being checked');
|
|
62
|
+
}
|
|
63
|
+
return hash.digest('hex');
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await handle.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function runProcess(binaryPath, args, timeout) {
|
|
70
|
+
try {
|
|
71
|
+
const { stdout, stderr } = await execFileAsync(binaryPath, args, {
|
|
72
|
+
timeout, maxBuffer: 1024 * 1024, windowsHide: true, encoding: 'utf8', shell: false, env: process.env,
|
|
73
|
+
});
|
|
74
|
+
return { stdout, stderr };
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
const code = error?.code;
|
|
78
|
+
throw new CosignVerificationError(`Pinned Cosign process failed (exit ${typeof code === 'number' ? code : 'unavailable'})`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export async function assertPinnedCosignBinary(binaryPath) {
|
|
82
|
+
const platform = platformKey();
|
|
83
|
+
const expected = COSIGN_BINARY_SHA256[platform];
|
|
84
|
+
if (!expected)
|
|
85
|
+
throw new Error(`Cosign ${COSIGN_PINNED_VERSION} has no pinned official checksum for ${platform}`);
|
|
86
|
+
const requested = await lstat(binaryPath);
|
|
87
|
+
if (requested.isSymbolicLink() || !requested.isFile())
|
|
88
|
+
throw new Error('Cosign binary must be a regular, non-symlink file');
|
|
89
|
+
if (process.platform !== 'win32' && (requested.mode & 0o111) === 0)
|
|
90
|
+
throw new Error('Cosign binary is not executable');
|
|
91
|
+
const canonical = await realpath(binaryPath);
|
|
92
|
+
if (await hashFile(canonical) !== expected)
|
|
93
|
+
throw new Error(`Cosign binary checksum does not match the official ${COSIGN_PINNED_VERSION} pin`);
|
|
94
|
+
const version = await runProcess(canonical, ['version'], 15_000);
|
|
95
|
+
if (!/^GitVersion:\s+v3\.1\.3\s*$/mu.test(`${version.stdout}\n${version.stderr}`)) {
|
|
96
|
+
throw new Error(`Cosign binary is not the pinned ${COSIGN_PINNED_VERSION} version`);
|
|
97
|
+
}
|
|
98
|
+
if (await hashFile(canonical) !== expected)
|
|
99
|
+
throw new Error('Cosign binary changed during version validation');
|
|
100
|
+
return canonical;
|
|
101
|
+
}
|
|
102
|
+
async function requireRegularFile(filePath, label) {
|
|
103
|
+
const stats = await lstat(filePath);
|
|
104
|
+
if (stats.isSymbolicLink() || !stats.isFile())
|
|
105
|
+
throw new Error(`${label} must be a regular, non-symlink file`);
|
|
106
|
+
return await realpath(filePath);
|
|
107
|
+
}
|
|
108
|
+
export function buildCosignSignArgs(bundlePath, payloadPath) {
|
|
109
|
+
return ['sign-blob', '--yes', '--bundle', bundlePath, payloadPath];
|
|
110
|
+
}
|
|
111
|
+
export function buildCosignVerifyArgs(bundlePath, trustedRootPath, identity, issuer, payloadPath) {
|
|
112
|
+
return [
|
|
113
|
+
'verify-blob', '--bundle', bundlePath, '--trusted-root', trustedRootPath,
|
|
114
|
+
'--certificate-identity', identity, '--certificate-oidc-issuer', issuer, payloadPath,
|
|
115
|
+
];
|
|
116
|
+
}
|
|
117
|
+
async function runCosign(binaryPath, args, timeout) {
|
|
118
|
+
const canonical = await assertPinnedCosignBinary(binaryPath);
|
|
119
|
+
await runProcess(canonical, args, timeout);
|
|
120
|
+
if (await hashFile(canonical) !== COSIGN_BINARY_SHA256[platformKey()]) {
|
|
121
|
+
throw new CosignVerificationError('Pinned Cosign binary changed during the operation');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async function newOutputPath(filePath) {
|
|
125
|
+
const target = path.resolve(filePath);
|
|
126
|
+
const output = path.join(await realpath(path.dirname(target)), path.basename(target));
|
|
127
|
+
try {
|
|
128
|
+
await lstat(output);
|
|
129
|
+
throw new Error('Sigstore bundle output already exists; refusing to overwrite');
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
if (error?.code !== 'ENOENT')
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
return output;
|
|
136
|
+
}
|
|
137
|
+
export async function signSigstoreBlob(options) {
|
|
138
|
+
const payload = await requireRegularFile(options.payloadPath, 'Sigstore payload');
|
|
139
|
+
const bundle = await newOutputPath(options.bundlePath);
|
|
140
|
+
await runCosign(options.binaryPath, buildCosignSignArgs(bundle, payload), 120_000);
|
|
141
|
+
return { bundlePath: bundle };
|
|
142
|
+
}
|
|
143
|
+
export async function verifySigstoreBlob(options) {
|
|
144
|
+
const payload = await requireRegularFile(options.payloadPath, 'Sigstore payload');
|
|
145
|
+
const bundle = await requireRegularFile(options.bundlePath, 'Sigstore bundle');
|
|
146
|
+
const trustedRoot = await requireRegularFile(options.trustedRootPath, 'Sigstore trusted root');
|
|
147
|
+
if (!options.certificateIdentity)
|
|
148
|
+
throw new Error('A configured Sigstore certificate identity is required');
|
|
149
|
+
if (!options.certificateOidcIssuer)
|
|
150
|
+
throw new Error('A configured Sigstore OIDC issuer is required');
|
|
151
|
+
await runCosign(options.binaryPath, buildCosignVerifyArgs(bundle, trustedRoot, options.certificateIdentity, options.certificateOidcIssuer, payload), 60_000);
|
|
152
|
+
return { valid: true };
|
|
153
|
+
}
|