@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
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export declare const DEFAULT_TRUST_ROOT_EXPIRY = "365d";
|
|
2
|
+
export declare const DEFAULT_REVOCATIONS_EXPIRY = "30d";
|
|
3
|
+
/** True if the bytes contain recognizable private-key material. */
|
|
4
|
+
export declare function containsPrivateKey(content: Uint8Array): boolean;
|
|
5
|
+
export declare function initRoot(options: {
|
|
6
|
+
rootKeyPath: string;
|
|
7
|
+
trustRootOut: string;
|
|
8
|
+
revocationsOut: string;
|
|
9
|
+
now: Date;
|
|
10
|
+
trustRootExpires?: string;
|
|
11
|
+
revocationsExpires?: string;
|
|
12
|
+
}): Promise<{
|
|
13
|
+
rootKeyId: string;
|
|
14
|
+
trustRoot: string;
|
|
15
|
+
revocations: string;
|
|
16
|
+
}>;
|
|
17
|
+
export declare function addApprover(options: {
|
|
18
|
+
rootKeyPath: string;
|
|
19
|
+
trustRootPath: string;
|
|
20
|
+
out?: string;
|
|
21
|
+
now: Date;
|
|
22
|
+
trustRootExpires?: string;
|
|
23
|
+
publicKeyPath: string;
|
|
24
|
+
name: string;
|
|
25
|
+
scopes: string[];
|
|
26
|
+
expires: string;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
version: number;
|
|
29
|
+
path: string;
|
|
30
|
+
keyId: string;
|
|
31
|
+
}>;
|
|
32
|
+
export declare function removeApprover(options: {
|
|
33
|
+
rootKeyPath: string;
|
|
34
|
+
trustRootPath: string;
|
|
35
|
+
out?: string;
|
|
36
|
+
now: Date;
|
|
37
|
+
trustRootExpires?: string;
|
|
38
|
+
keyId: string;
|
|
39
|
+
}): Promise<{
|
|
40
|
+
version: number;
|
|
41
|
+
path: string;
|
|
42
|
+
}>;
|
|
43
|
+
export declare function updateRevocations(options: {
|
|
44
|
+
rootKeyPath: string;
|
|
45
|
+
revocationsPath: string;
|
|
46
|
+
out?: string;
|
|
47
|
+
now: Date;
|
|
48
|
+
expires?: string;
|
|
49
|
+
revokeKey?: string;
|
|
50
|
+
revokeDigest?: string;
|
|
51
|
+
reason?: string;
|
|
52
|
+
}): Promise<{
|
|
53
|
+
version: number;
|
|
54
|
+
path: string;
|
|
55
|
+
expiresAt: Date;
|
|
56
|
+
}>;
|
|
57
|
+
export declare function approveSkill(options: {
|
|
58
|
+
skillDir: string;
|
|
59
|
+
approverKeyPath: string;
|
|
60
|
+
now: Date;
|
|
61
|
+
expires: string;
|
|
62
|
+
reason: string;
|
|
63
|
+
name?: string;
|
|
64
|
+
previous?: string;
|
|
65
|
+
out?: string;
|
|
66
|
+
/** The digest the approver reviewed; issuance is refused if the bytes on disk differ. */
|
|
67
|
+
expectDigest?: string;
|
|
68
|
+
}): Promise<{
|
|
69
|
+
path: string;
|
|
70
|
+
skillName: string;
|
|
71
|
+
digest: string;
|
|
72
|
+
certificateId: string;
|
|
73
|
+
expiresAt: Date;
|
|
74
|
+
}>;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { unlink } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { requireString } from "./canonical-json.js";
|
|
4
|
+
import { issueCertificate, parseCertificate } from "./certificate.js";
|
|
5
|
+
import { readRegularFile, realpathAllowingMissing, resolveOutside, writeFileAtomic, writeNewFile } from "./fs-safe.js";
|
|
6
|
+
import { loadPrivateKey, loadPublicKey, validateKeyId } from "./keys.js";
|
|
7
|
+
import { validateDigest, validateScope } from "./names.js";
|
|
8
|
+
import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
|
|
9
|
+
import { addDuration, truncateToSecond } from "./time.js";
|
|
10
|
+
import { CERTIFICATE_FILENAME, collectSkillTree, requireSkillRoot, SKILL_FILENAME } from "./tree-digest.js";
|
|
11
|
+
import { MAX_APPROVERS, MAX_SCOPES, readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
|
|
12
|
+
import { skillNameFromSkillFile } from "./verify.js";
|
|
13
|
+
export const DEFAULT_TRUST_ROOT_EXPIRY = '365d';
|
|
14
|
+
export const DEFAULT_REVOCATIONS_EXPIRY = '30d';
|
|
15
|
+
const MAX_TRUST_ROOT_BYTES = 4 * 1024 * 1024;
|
|
16
|
+
const MAX_REVOCATIONS_BYTES = 8 * 1024 * 1024;
|
|
17
|
+
const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
|
|
18
|
+
const MAX_APPROVER_NAME_LEN = 128;
|
|
19
|
+
const MAX_REVOCATION_REASON = 512;
|
|
20
|
+
const DEFAULT_REVOKE_REASON = 'revoked';
|
|
21
|
+
const latin1Decoder = new TextDecoder('latin1');
|
|
22
|
+
/**
|
|
23
|
+
* Private-key encodings `approve` refuses to certify (a certified file can reach the model through Pi):
|
|
24
|
+
* PEM/OpenSSH/PKCS#8/SSH2 armor ("BEGIN [RSA |EC |DSA |ENCRYPTED |OPENSSH |...]PRIVATE KEY"), OpenPGP armor
|
|
25
|
+
* ("BEGIN PGP PRIVATE KEY BLOCK"), PuTTY .ppk files, and age secret keys. Public keys and PGP PUBLIC KEY
|
|
26
|
+
* BLOCKs do not match. This is a best-effort guard, not a secret scanner.
|
|
27
|
+
*/
|
|
28
|
+
// Every quantifier is bounded, so scanning is linear in the input (no backtracking blow-up on long runs of
|
|
29
|
+
// dashes, spaces or "BEGIN "). Three dashes are enough to anchor the header; "---- BEGIN SSH2 ..." contains them.
|
|
30
|
+
const PRIVATE_KEY_PATTERNS = [
|
|
31
|
+
/-{3}\s{0,4}BEGIN [A-Z0-9 ]{0,64}PRIVATE KEY/iu,
|
|
32
|
+
/PuTTY-User-Key-File-\d{1,4}:/u,
|
|
33
|
+
/AGE-SECRET-KEY-1[0-9A-Z]{20,200}/iu,
|
|
34
|
+
];
|
|
35
|
+
/** True if the bytes contain recognizable private-key material. */
|
|
36
|
+
export function containsPrivateKey(content) {
|
|
37
|
+
const text = latin1Decoder.decode(content);
|
|
38
|
+
return PRIVATE_KEY_PATTERNS.some((pattern) => pattern.test(text));
|
|
39
|
+
}
|
|
40
|
+
export async function initRoot(options) {
|
|
41
|
+
const trustRootTarget = path.resolve(options.trustRootOut);
|
|
42
|
+
const revocationsTarget = path.resolve(options.revocationsOut);
|
|
43
|
+
const canonicalTrust = await realpathAllowingMissing(trustRootTarget);
|
|
44
|
+
const canonicalRevoke = await realpathAllowingMissing(revocationsTarget);
|
|
45
|
+
if (trustRootTarget === revocationsTarget || canonicalTrust === canonicalRevoke) {
|
|
46
|
+
throw new Error('Trust root and revocation list output paths must differ');
|
|
47
|
+
}
|
|
48
|
+
const root = await loadPrivateKey(options.rootKeyPath);
|
|
49
|
+
const issuedAt = truncateToSecond(options.now);
|
|
50
|
+
const trustRoot = {
|
|
51
|
+
version: 1,
|
|
52
|
+
issuedAt,
|
|
53
|
+
expiresAt: addDuration(issuedAt, options.trustRootExpires ?? DEFAULT_TRUST_ROOT_EXPIRY, 'trust root expiry'),
|
|
54
|
+
root,
|
|
55
|
+
approvers: [],
|
|
56
|
+
};
|
|
57
|
+
const revocations = {
|
|
58
|
+
version: 1,
|
|
59
|
+
issuedAt,
|
|
60
|
+
expiresAt: addDuration(issuedAt, options.revocationsExpires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
|
|
61
|
+
rootKeyId: root.keyId,
|
|
62
|
+
keys: [],
|
|
63
|
+
digests: [],
|
|
64
|
+
};
|
|
65
|
+
const trustRootBytes = signTrustRoot(trustRoot, root.privateKey);
|
|
66
|
+
const revocationsBytes = signRevocations(revocations, root.privateKey);
|
|
67
|
+
const trustRootPath = await writeNewFile(trustRootTarget, trustRootBytes);
|
|
68
|
+
try {
|
|
69
|
+
const revocationsPath = await writeNewFile(revocationsTarget, revocationsBytes);
|
|
70
|
+
return {
|
|
71
|
+
rootKeyId: root.keyId,
|
|
72
|
+
trustRoot: trustRootPath,
|
|
73
|
+
revocations: revocationsPath,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
await unlink(trustRootPath).catch(() => { });
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function updateTrustRoot(options, change) {
|
|
82
|
+
const root = await loadPrivateKey(options.rootKeyPath);
|
|
83
|
+
const rawBytes = await readRegularFile(options.trustRootPath, 'Trust root', MAX_TRUST_ROOT_BYTES);
|
|
84
|
+
const current = readTrustRootForUpdate(rawBytes, root.keyId);
|
|
85
|
+
const issuedAt = truncateToSecond(options.now);
|
|
86
|
+
const expiresAt = options.expires
|
|
87
|
+
? addDuration(issuedAt, options.expires, 'trust root expiry')
|
|
88
|
+
: current.expiresAt;
|
|
89
|
+
const next = {
|
|
90
|
+
...current,
|
|
91
|
+
version: current.version + 1,
|
|
92
|
+
issuedAt,
|
|
93
|
+
expiresAt,
|
|
94
|
+
approvers: current.approvers.map((approver) => ({
|
|
95
|
+
...approver,
|
|
96
|
+
scopes: [...approver.scopes],
|
|
97
|
+
})),
|
|
98
|
+
};
|
|
99
|
+
change(next);
|
|
100
|
+
if (next.expiresAt <= issuedAt) {
|
|
101
|
+
throw new Error('The trust root would already be expired; pass --expires to extend it');
|
|
102
|
+
}
|
|
103
|
+
const targetPath = options.out ?? options.trustRootPath;
|
|
104
|
+
const written = await writeFileAtomic(targetPath, signTrustRoot(next, root.privateKey));
|
|
105
|
+
return { version: next.version, path: written, trustRoot: next };
|
|
106
|
+
}
|
|
107
|
+
export async function addApprover(options) {
|
|
108
|
+
const approverName = requireString(options.name, 'Approver name', MAX_APPROVER_NAME_LEN);
|
|
109
|
+
const approverKey = await loadPublicKey(options.publicKeyPath);
|
|
110
|
+
if (options.scopes.length === 0) {
|
|
111
|
+
throw new Error('At least one --scope is required');
|
|
112
|
+
}
|
|
113
|
+
const scopes = [...new Set(options.scopes.map((scope) => validateScope(scope)))].sort();
|
|
114
|
+
if (scopes.length > MAX_SCOPES) {
|
|
115
|
+
throw new Error(`Approver scopes cannot exceed ${MAX_SCOPES}`);
|
|
116
|
+
}
|
|
117
|
+
const issuedAt = truncateToSecond(options.now);
|
|
118
|
+
const expiresAt = addDuration(issuedAt, options.expires, 'approver expiry');
|
|
119
|
+
const result = await updateTrustRoot({
|
|
120
|
+
rootKeyPath: options.rootKeyPath,
|
|
121
|
+
trustRootPath: options.trustRootPath,
|
|
122
|
+
out: options.out,
|
|
123
|
+
now: options.now,
|
|
124
|
+
expires: options.trustRootExpires,
|
|
125
|
+
}, (trustRoot) => {
|
|
126
|
+
if (approverKey.keyId === trustRoot.root.keyId) {
|
|
127
|
+
throw new Error('The root key cannot be an approver; generate a separate approver key');
|
|
128
|
+
}
|
|
129
|
+
const remaining = trustRoot.approvers.filter((entry) => entry.keyId !== approverKey.keyId);
|
|
130
|
+
if (remaining.length >= MAX_APPROVERS) {
|
|
131
|
+
throw new Error(`Trust root cannot exceed ${MAX_APPROVERS} approvers`);
|
|
132
|
+
}
|
|
133
|
+
remaining.push({
|
|
134
|
+
...approverKey,
|
|
135
|
+
name: approverName,
|
|
136
|
+
scopes,
|
|
137
|
+
expiresAt,
|
|
138
|
+
});
|
|
139
|
+
trustRoot.approvers = remaining;
|
|
140
|
+
});
|
|
141
|
+
return { version: result.version, path: result.path, keyId: approverKey.keyId };
|
|
142
|
+
}
|
|
143
|
+
export async function removeApprover(options) {
|
|
144
|
+
const targetKeyId = validateKeyId(options.keyId, 'Approver key id');
|
|
145
|
+
return await updateTrustRoot({
|
|
146
|
+
rootKeyPath: options.rootKeyPath,
|
|
147
|
+
trustRootPath: options.trustRootPath,
|
|
148
|
+
out: options.out,
|
|
149
|
+
now: options.now,
|
|
150
|
+
expires: options.trustRootExpires,
|
|
151
|
+
}, (trustRoot) => {
|
|
152
|
+
const beforeCount = trustRoot.approvers.length;
|
|
153
|
+
trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== targetKeyId);
|
|
154
|
+
if (trustRoot.approvers.length === beforeCount) {
|
|
155
|
+
throw new Error(`No approver with key id ${targetKeyId}`);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
export async function updateRevocations(options) {
|
|
160
|
+
const root = await loadPrivateKey(options.rootKeyPath);
|
|
161
|
+
const rawBytes = await readRegularFile(options.revocationsPath, 'Revocation list', MAX_REVOCATIONS_BYTES);
|
|
162
|
+
const current = readRevocationsForUpdate(rawBytes, root.keyId, root.publicKey);
|
|
163
|
+
const issuedAt = truncateToSecond(options.now);
|
|
164
|
+
const expiresAt = addDuration(issuedAt, options.expires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry');
|
|
165
|
+
const reason = requireString(options.reason ?? DEFAULT_REVOKE_REASON, 'Revocation reason', MAX_REVOCATION_REASON);
|
|
166
|
+
const next = {
|
|
167
|
+
...current,
|
|
168
|
+
version: current.version + 1,
|
|
169
|
+
issuedAt,
|
|
170
|
+
expiresAt,
|
|
171
|
+
keys: [...current.keys],
|
|
172
|
+
digests: [...current.digests],
|
|
173
|
+
};
|
|
174
|
+
if (options.revokeKey !== undefined) {
|
|
175
|
+
const keyId = validateKeyId(options.revokeKey, 'Revoked key id');
|
|
176
|
+
if (next.keys.some((entry) => entry.keyId === keyId)) {
|
|
177
|
+
throw new Error(`Key ${keyId} is already revoked`);
|
|
178
|
+
}
|
|
179
|
+
next.keys.push({ keyId, reason, revokedAt: issuedAt });
|
|
180
|
+
}
|
|
181
|
+
if (options.revokeDigest !== undefined) {
|
|
182
|
+
const digest = validateDigest(options.revokeDigest);
|
|
183
|
+
if (next.digests.some((entry) => entry.digest === digest)) {
|
|
184
|
+
throw new Error(`Digest ${digest} is already revoked`);
|
|
185
|
+
}
|
|
186
|
+
next.digests.push({ digest, reason, revokedAt: issuedAt });
|
|
187
|
+
}
|
|
188
|
+
const targetPath = options.out ?? options.revocationsPath;
|
|
189
|
+
const written = await writeFileAtomic(targetPath, signRevocations(next, root.privateKey));
|
|
190
|
+
return { version: next.version, path: written, expiresAt: next.expiresAt };
|
|
191
|
+
}
|
|
192
|
+
export async function approveSkill(options) {
|
|
193
|
+
const skillDir = path.resolve(options.skillDir);
|
|
194
|
+
const expected = options.expectDigest === undefined ? null : validateDigest(options.expectDigest, 'expected digest');
|
|
195
|
+
await requireSkillRoot(skillDir);
|
|
196
|
+
// Verify the key path is outside the Skill directory before reading the private key.
|
|
197
|
+
await resolveOutside(options.approverKeyPath, skillDir, 'Approver private key');
|
|
198
|
+
const approver = await loadPrivateKey(options.approverKeyPath);
|
|
199
|
+
const tree = await collectSkillTree(skillDir, { includeContents: true });
|
|
200
|
+
// Taken from the same SKILL.md bytes that are hashed and signed, so the name cannot differ from the reviewed version.
|
|
201
|
+
const skillName = skillNameFromSkillFile(skillDir, tree.contents.get(SKILL_FILENAME), options.name);
|
|
202
|
+
// Checked against the same bytes that are signed, so a change after review can never be certified.
|
|
203
|
+
if (expected !== null && tree.digest !== expected) {
|
|
204
|
+
throw new Error(`Refusing to approve: the Skill changed since it was reviewed (expected ${expected}, found ${tree.digest}). Review the current version and approve again.`);
|
|
205
|
+
}
|
|
206
|
+
for (const [filePath, content] of tree.contents) {
|
|
207
|
+
if (containsPrivateKey(content)) {
|
|
208
|
+
throw new Error(`Refusing to approve: ${filePath} contains a private key. Remove it from the Skill and rotate that key.`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
let previousDigest = null;
|
|
212
|
+
if (options.previous) {
|
|
213
|
+
if (options.previous.startsWith('sha256:')) {
|
|
214
|
+
previousDigest = validateDigest(options.previous, 'previous digest');
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
const prevBytes = await readRegularFile(options.previous, 'Previous certificate', MAX_CERTIFICATE_BYTES);
|
|
218
|
+
previousDigest = parseCertificate(prevBytes).digest;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const issuedAt = truncateToSecond(options.now);
|
|
222
|
+
const expiresAt = addDuration(issuedAt, options.expires, 'certificate expiry');
|
|
223
|
+
const bytes = issueCertificate({
|
|
224
|
+
skillName,
|
|
225
|
+
digest: tree.digest,
|
|
226
|
+
files: tree.files,
|
|
227
|
+
approver,
|
|
228
|
+
issuedAt,
|
|
229
|
+
expiresAt,
|
|
230
|
+
reason: options.reason,
|
|
231
|
+
previousDigest,
|
|
232
|
+
});
|
|
233
|
+
const targetPath = options.out ?? path.join(tree.root, CERTIFICATE_FILENAME);
|
|
234
|
+
const written = await writeFileAtomic(targetPath, bytes);
|
|
235
|
+
const parsed = parseCertificate(bytes);
|
|
236
|
+
return {
|
|
237
|
+
path: written,
|
|
238
|
+
skillName,
|
|
239
|
+
digest: tree.digest,
|
|
240
|
+
certificateId: parsed.id,
|
|
241
|
+
expiresAt,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const MAX_CANONICAL_JSON_BYTES: number;
|
|
2
|
+
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
6
|
+
export declare function serializeCanonicalJson(value: unknown): string;
|
|
7
|
+
export declare function canonicalBytes(value: unknown): Buffer;
|
|
8
|
+
export declare function parseCanonicalJsonBytes(input: Uint8Array, label?: string): unknown;
|
|
9
|
+
export declare function exactKeys(value: unknown, keys: readonly string[], label: string): Record<string, unknown>;
|
|
10
|
+
export declare function requireString(value: unknown, label: string, maxLength?: number): string;
|
|
11
|
+
export declare function requireArray(value: unknown, label: string, maxLength: number): unknown[];
|
|
12
|
+
export declare function requirePositiveInteger(value: unknown, label: string): number;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Canonical JSON: sorted object keys, no insignificant whitespace, one trailing LF.
|
|
2
|
+
// Parsing rejects any byte sequence that is not exactly the canonical form, so
|
|
3
|
+
// duplicate keys, alternate escapes and reordered fields cannot change meaning.
|
|
4
|
+
export const MAX_CANONICAL_JSON_BYTES = 4 * 1024 * 1024;
|
|
5
|
+
const MAX_CANONICAL_JSON_NODES = 200_000;
|
|
6
|
+
const MAX_CANONICAL_JSON_DEPTH = 64;
|
|
7
|
+
const DEFAULT_MAX_STRING_LENGTH = 1_024;
|
|
8
|
+
const UTF8_BOM_CHAR_CODE = 0xfeff;
|
|
9
|
+
const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
|
|
10
|
+
const controlCharPattern = /[\u0000-\u001f\u007f]/u;
|
|
11
|
+
function errorMessage(error) {
|
|
12
|
+
return error instanceof Error ? error.message : String(error);
|
|
13
|
+
}
|
|
14
|
+
export function isRecord(value) {
|
|
15
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const proto = Object.getPrototypeOf(value);
|
|
19
|
+
return proto === Object.prototype || proto === null;
|
|
20
|
+
}
|
|
21
|
+
function canonicalValue(value, depth, state) {
|
|
22
|
+
state.nodes += 1;
|
|
23
|
+
if (state.nodes > MAX_CANONICAL_JSON_NODES || depth > MAX_CANONICAL_JSON_DEPTH) {
|
|
24
|
+
throw new Error('Canonical JSON exceeds structural limits');
|
|
25
|
+
}
|
|
26
|
+
if (value === null) {
|
|
27
|
+
return 'null';
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === 'string') {
|
|
30
|
+
return JSON.stringify(value);
|
|
31
|
+
}
|
|
32
|
+
if (typeof value === 'boolean') {
|
|
33
|
+
return value ? 'true' : 'false';
|
|
34
|
+
}
|
|
35
|
+
if (typeof value === 'number') {
|
|
36
|
+
if (!Number.isSafeInteger(value)) {
|
|
37
|
+
throw new Error('Canonical JSON numbers must be safe integers');
|
|
38
|
+
}
|
|
39
|
+
return Object.is(value, -0) ? '0' : JSON.stringify(value);
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(value)) {
|
|
42
|
+
const elements = value.map((item) => canonicalValue(item, depth + 1, state));
|
|
43
|
+
return `[${elements.join(',')}]`;
|
|
44
|
+
}
|
|
45
|
+
if (isRecord(value)) {
|
|
46
|
+
const sortedKeys = Object.keys(value).sort();
|
|
47
|
+
const entries = sortedKeys.map((key) => {
|
|
48
|
+
if (key === '__proto__') {
|
|
49
|
+
throw new Error('Canonical JSON forbids "__proto__" object keys');
|
|
50
|
+
}
|
|
51
|
+
const item = value[key];
|
|
52
|
+
if (item === undefined) {
|
|
53
|
+
throw new Error(`Canonical JSON field ${JSON.stringify(key)} is undefined`);
|
|
54
|
+
}
|
|
55
|
+
return `${JSON.stringify(key)}:${canonicalValue(item, depth + 1, state)}`;
|
|
56
|
+
});
|
|
57
|
+
return `{${entries.join(',')}}`;
|
|
58
|
+
}
|
|
59
|
+
throw new Error('Canonical JSON contains an unsupported value');
|
|
60
|
+
}
|
|
61
|
+
export function serializeCanonicalJson(value) {
|
|
62
|
+
const state = { nodes: 0 };
|
|
63
|
+
return `${canonicalValue(value, 0, state)}\n`;
|
|
64
|
+
}
|
|
65
|
+
export function canonicalBytes(value) {
|
|
66
|
+
return Buffer.from(serializeCanonicalJson(value), 'utf8');
|
|
67
|
+
}
|
|
68
|
+
export function parseCanonicalJsonBytes(input, label = 'JSON document') {
|
|
69
|
+
let text;
|
|
70
|
+
let value;
|
|
71
|
+
let canonical;
|
|
72
|
+
if (!(input instanceof Uint8Array) ||
|
|
73
|
+
input.byteLength === 0 ||
|
|
74
|
+
input.byteLength > MAX_CANONICAL_JSON_BYTES) {
|
|
75
|
+
throw new Error(`${label} must be between 1 byte and ${MAX_CANONICAL_JSON_BYTES} bytes`);
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
text = utf8Decoder.decode(input);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new Error(`${label} is not valid UTF-8`);
|
|
82
|
+
}
|
|
83
|
+
if (text.charCodeAt(0) === UTF8_BOM_CHAR_CODE || !text.endsWith('\n')) {
|
|
84
|
+
throw new Error(`${label} must be canonical UTF-8 JSON with one trailing LF`);
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
value = JSON.parse(text.slice(0, -1), (key, parsedValue) => {
|
|
88
|
+
if (key === '__proto__') {
|
|
89
|
+
throw new Error('__proto__ key is forbidden');
|
|
90
|
+
}
|
|
91
|
+
if (typeof parsedValue === 'number' && Object.is(parsedValue, -0)) {
|
|
92
|
+
throw new Error('negative zero is not canonical');
|
|
93
|
+
}
|
|
94
|
+
return parsedValue;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new Error(`${label} is not valid JSON`);
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
canonical = serializeCanonicalJson(value);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
throw new Error(`${label} is structurally invalid: ${errorMessage(error)}`);
|
|
105
|
+
}
|
|
106
|
+
if (canonical !== text) {
|
|
107
|
+
throw new Error(`${label} is not canonical JSON (duplicate keys and alternate encodings are rejected)`);
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
export function exactKeys(value, keys, label) {
|
|
112
|
+
if (!isRecord(value)) {
|
|
113
|
+
throw new Error(`${label} must be a JSON object`);
|
|
114
|
+
}
|
|
115
|
+
const actualKeys = Object.keys(value).sort();
|
|
116
|
+
const expectedKeys = [...new Set(keys)].sort();
|
|
117
|
+
if (actualKeys.length !== expectedKeys.length ||
|
|
118
|
+
actualKeys.some((key, index) => key !== expectedKeys[index])) {
|
|
119
|
+
throw new Error(`${label} has missing or unsupported fields`);
|
|
120
|
+
}
|
|
121
|
+
return value;
|
|
122
|
+
}
|
|
123
|
+
export function requireString(value, label, maxLength = DEFAULT_MAX_STRING_LENGTH) {
|
|
124
|
+
if (!Number.isSafeInteger(maxLength) || maxLength < 1) {
|
|
125
|
+
throw new Error(`Invalid maxLength limit for ${label}`);
|
|
126
|
+
}
|
|
127
|
+
if (typeof value !== 'string' ||
|
|
128
|
+
value.length === 0 ||
|
|
129
|
+
value.length > maxLength ||
|
|
130
|
+
controlCharPattern.test(value)) {
|
|
131
|
+
throw new Error(`${label} must be a non-empty string of at most ${maxLength} characters without control characters`);
|
|
132
|
+
}
|
|
133
|
+
return value;
|
|
134
|
+
}
|
|
135
|
+
export function requireArray(value, label, maxLength) {
|
|
136
|
+
if (!Number.isSafeInteger(maxLength) || maxLength < 0) {
|
|
137
|
+
throw new Error(`Invalid maxLength limit for ${label}`);
|
|
138
|
+
}
|
|
139
|
+
if (!Array.isArray(value) || value.length > maxLength) {
|
|
140
|
+
throw new Error(`${label} must be an array of at most ${maxLength} items`);
|
|
141
|
+
}
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
144
|
+
export function requirePositiveInteger(value, label) {
|
|
145
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
|
|
146
|
+
throw new Error(`${label} must be a positive integer`);
|
|
147
|
+
}
|
|
148
|
+
return value;
|
|
149
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { parseEnvelope } from './dsse.ts';
|
|
2
|
+
import type { PrivateKeyInfo } from './keys.ts';
|
|
3
|
+
import { type TreeFile } from './tree-digest.ts';
|
|
4
|
+
export declare const STATEMENT_TYPE = "https://in-toto.io/Statement/v1";
|
|
5
|
+
export declare const STATEMENT_PAYLOAD_TYPE = "application/vnd.in-toto+json";
|
|
6
|
+
export declare const CERTIFICATE_PREDICATE_TYPE = "https://github.com/mago-foundation/mago-ski/blob/main/docs/spec/skill-certificate-v1.md";
|
|
7
|
+
/** in-toto DigestSet algorithm name for the mago.skill-tree/v2 digest. */
|
|
8
|
+
export declare const SUBJECT_DIGEST_ALGORITHM = "magoSkillTreeV2";
|
|
9
|
+
export interface Certificate {
|
|
10
|
+
/** sha256 of the certificate file bytes; used in logs. */
|
|
11
|
+
id: string;
|
|
12
|
+
skillName: string;
|
|
13
|
+
digest: string;
|
|
14
|
+
files: TreeFile[];
|
|
15
|
+
approverKeyId: string;
|
|
16
|
+
issuedAt: Date;
|
|
17
|
+
expiresAt: Date;
|
|
18
|
+
reason: string;
|
|
19
|
+
previousDigest: string | null;
|
|
20
|
+
envelope: ReturnType<typeof parseEnvelope>;
|
|
21
|
+
}
|
|
22
|
+
export interface IssueOptions {
|
|
23
|
+
skillName: string;
|
|
24
|
+
digest: string;
|
|
25
|
+
files: TreeFile[];
|
|
26
|
+
approver: PrivateKeyInfo;
|
|
27
|
+
issuedAt: Date;
|
|
28
|
+
expiresAt: Date;
|
|
29
|
+
reason: string;
|
|
30
|
+
previousDigest?: string | null;
|
|
31
|
+
}
|
|
32
|
+
export declare function issueCertificate(options: IssueOptions): Buffer;
|
|
33
|
+
/** Parses a certificate's structure. Signature and trust are checked by the verifier. */
|
|
34
|
+
export declare function parseCertificate(bytes: Uint8Array): Certificate;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
|
|
2
|
+
import { envelopeBytes, parseEnvelope, signEnvelope } from "./dsse.js";
|
|
3
|
+
import { validateDigest, validateSkillName } from "./names.js";
|
|
4
|
+
import { formatTimestamp, parseTimestamp } from "./time.js";
|
|
5
|
+
import { digestFileList, MAX_RELATIVE_PATH_BYTES, MAX_TREE_FILES, sha256Hex, SKILL_FILENAME, TREE_PROFILE } from "./tree-digest.js";
|
|
6
|
+
export const STATEMENT_TYPE = 'https://in-toto.io/Statement/v1';
|
|
7
|
+
export const STATEMENT_PAYLOAD_TYPE = 'application/vnd.in-toto+json';
|
|
8
|
+
export const CERTIFICATE_PREDICATE_TYPE = 'https://github.com/mago-foundation/mago-ski/blob/main/docs/spec/skill-certificate-v1.md';
|
|
9
|
+
/** in-toto DigestSet algorithm name for the mago.skill-tree/v2 digest. */
|
|
10
|
+
export const SUBJECT_DIGEST_ALGORITHM = 'magoSkillTreeV2';
|
|
11
|
+
export function issueCertificate(options) {
|
|
12
|
+
validateSkillName(options.skillName);
|
|
13
|
+
if (!options.files.some((file) => file.path === SKILL_FILENAME))
|
|
14
|
+
throw new Error(`Certificate file list must include ${SKILL_FILENAME}`);
|
|
15
|
+
if (digestFileList(options.files) !== options.digest)
|
|
16
|
+
throw new Error('File list does not match the tree digest');
|
|
17
|
+
if (options.expiresAt <= options.issuedAt)
|
|
18
|
+
throw new Error('Certificate must expire after it is issued');
|
|
19
|
+
const statement = {
|
|
20
|
+
_type: STATEMENT_TYPE,
|
|
21
|
+
subject: [{
|
|
22
|
+
name: options.skillName,
|
|
23
|
+
digest: { [SUBJECT_DIGEST_ALGORITHM]: options.digest.slice('sha256:'.length) }
|
|
24
|
+
}],
|
|
25
|
+
predicateType: CERTIFICATE_PREDICATE_TYPE,
|
|
26
|
+
predicate: {
|
|
27
|
+
tree_profile: TREE_PROFILE,
|
|
28
|
+
files: options.files.map((file) => ({
|
|
29
|
+
path: file.path,
|
|
30
|
+
size: file.size,
|
|
31
|
+
sha256: file.sha256,
|
|
32
|
+
exec: file.exec
|
|
33
|
+
})),
|
|
34
|
+
approval: {
|
|
35
|
+
approver_key_id: options.approver.keyId,
|
|
36
|
+
issued_at: formatTimestamp(options.issuedAt),
|
|
37
|
+
expires_at: formatTimestamp(options.expiresAt),
|
|
38
|
+
reason: requireString(options.reason, 'reason', 1024),
|
|
39
|
+
},
|
|
40
|
+
previous_digest: options.previousDigest == null ? null : validateDigest(options.previousDigest, 'previous digest'),
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
const payload = canonicalBytes(statement);
|
|
44
|
+
return envelopeBytes(signEnvelope(STATEMENT_PAYLOAD_TYPE, payload, options.approver.keyId, options.approver.privateKey));
|
|
45
|
+
}
|
|
46
|
+
function parseFiles(value, label) {
|
|
47
|
+
return requireArray(value, label, MAX_TREE_FILES).map((item, index) => {
|
|
48
|
+
const entry = exactKeys(item, ['path', 'size', 'sha256', 'exec'], `${label}[${index}]`);
|
|
49
|
+
const filePath = entry.path;
|
|
50
|
+
if (typeof filePath !== 'string' || filePath.length === 0 || Buffer.byteLength(filePath) > MAX_RELATIVE_PATH_BYTES ||
|
|
51
|
+
filePath.startsWith('/') || filePath.includes('\\') || filePath.split('/').some((part) => part === '' || part === '.' || part === '..')) {
|
|
52
|
+
throw new Error(`${label}[${index}] path is not a safe relative path`);
|
|
53
|
+
}
|
|
54
|
+
if (typeof entry.size !== 'number' || !Number.isSafeInteger(entry.size) || entry.size < 0)
|
|
55
|
+
throw new Error(`${label}[${index}] size is invalid`);
|
|
56
|
+
if (typeof entry.sha256 !== 'string' || !/^[0-9a-f]{64}$/u.test(entry.sha256))
|
|
57
|
+
throw new Error(`${label}[${index}] sha256 is invalid`);
|
|
58
|
+
if (typeof entry.exec !== 'boolean')
|
|
59
|
+
throw new Error(`${label}[${index}] exec must be a boolean`);
|
|
60
|
+
return { path: filePath, size: entry.size, sha256: entry.sha256, exec: entry.exec };
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** Parses a certificate's structure. Signature and trust are checked by the verifier. */
|
|
64
|
+
export function parseCertificate(bytes) {
|
|
65
|
+
const label = 'certificate';
|
|
66
|
+
const envelope = parseEnvelope(bytes, label);
|
|
67
|
+
const statement = exactKeys(parseCanonicalJsonBytes(envelope.payloadBytes, `${label} statement`), ['_type', 'subject', 'predicateType', 'predicate'], `${label} statement`);
|
|
68
|
+
const subjects = requireArray(statement.subject, `${label} subject`, 1);
|
|
69
|
+
const subject = exactKeys(subjects[0], ['name', 'digest'], `${label} subject`);
|
|
70
|
+
const skillName = validateSkillName(subject.name, `${label} subject name`);
|
|
71
|
+
const digestSet = exactKeys(subject.digest, [SUBJECT_DIGEST_ALGORITHM], `${label} subject digest`);
|
|
72
|
+
const digest = validateDigest(`sha256:${String(digestSet[SUBJECT_DIGEST_ALGORITHM])}`, `${label} subject digest`);
|
|
73
|
+
const predicate = exactKeys(statement.predicate, ['tree_profile', 'files', 'approval', 'previous_digest'], `${label} predicate`);
|
|
74
|
+
const files = parseFiles(predicate.files, `${label} files`);
|
|
75
|
+
const approval = exactKeys(predicate.approval, ['approver_key_id', 'issued_at', 'expires_at', 'reason'], `${label} approval`);
|
|
76
|
+
const approverKeyId = String(approval.approver_key_id);
|
|
77
|
+
const issuedAt = parseTimestamp(approval.issued_at, `${label} issued_at`);
|
|
78
|
+
const expiresAt = parseTimestamp(approval.expires_at, `${label} expires_at`);
|
|
79
|
+
const previous = predicate.previous_digest;
|
|
80
|
+
if (envelope.payloadType !== STATEMENT_PAYLOAD_TYPE)
|
|
81
|
+
throw new Error(`${label} has the wrong payload type`);
|
|
82
|
+
if (statement._type !== STATEMENT_TYPE)
|
|
83
|
+
throw new Error(`${label} is not an in-toto v1 statement`);
|
|
84
|
+
if (statement.predicateType !== CERTIFICATE_PREDICATE_TYPE)
|
|
85
|
+
throw new Error(`${label} has an unsupported predicateType`);
|
|
86
|
+
if (subjects.length !== 1)
|
|
87
|
+
throw new Error(`${label} must have exactly one subject`);
|
|
88
|
+
if (predicate.tree_profile !== TREE_PROFILE)
|
|
89
|
+
throw new Error(`${label} uses unsupported tree profile ${String(predicate.tree_profile)}`);
|
|
90
|
+
if (!files.some((file) => file.path === SKILL_FILENAME))
|
|
91
|
+
throw new Error(`${label} file list does not include ${SKILL_FILENAME}`);
|
|
92
|
+
if (digestFileList(files) !== digest)
|
|
93
|
+
throw new Error(`${label} file list does not match its subject digest`);
|
|
94
|
+
if (approverKeyId !== envelope.signatures[0].keyid)
|
|
95
|
+
throw new Error(`${label} approver_key_id does not match the signing key`);
|
|
96
|
+
if (expiresAt <= issuedAt)
|
|
97
|
+
throw new Error(`${label} expires before it is issued`);
|
|
98
|
+
if (previous !== null && isRecord(previous))
|
|
99
|
+
throw new Error(`${label} previous_digest is invalid`);
|
|
100
|
+
return {
|
|
101
|
+
id: `sha256:${sha256Hex(bytes)}`,
|
|
102
|
+
skillName,
|
|
103
|
+
digest,
|
|
104
|
+
files,
|
|
105
|
+
approverKeyId,
|
|
106
|
+
issuedAt,
|
|
107
|
+
expiresAt,
|
|
108
|
+
reason: requireString(approval.reason, `${label} reason`, 1024),
|
|
109
|
+
previousDigest: previous === null ? null : validateDigest(previous, `${label} previous_digest`),
|
|
110
|
+
envelope,
|
|
111
|
+
};
|
|
112
|
+
}
|