@mago-foundation/mago-ski 0.1.0 → 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/dist/src/admin.js CHANGED
@@ -1,115 +1,243 @@
1
+ import { unlink } from 'node:fs/promises';
1
2
  import path from 'node:path';
3
+ import { requireString } from "./canonical-json.js";
2
4
  import { issueCertificate, parseCertificate } from "./certificate.js";
3
- import { readRegularFile, resolveOutside, writeFileAtomic, writeNewFile } from "./fs-safe.js";
4
- import { loadPrivateKey, loadPublicKey } from "./keys.js";
5
+ import { readRegularFile, realpathAllowingMissing, resolveOutside, writeFileAtomic, writeNewFile } from "./fs-safe.js";
6
+ import { loadPrivateKey, loadPublicKey, validateKeyId } from "./keys.js";
5
7
  import { validateDigest, validateScope } from "./names.js";
6
8
  import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
7
9
  import { addDuration, truncateToSecond } from "./time.js";
8
- import { CERTIFICATE_FILENAME, collectSkillTree } from "./tree-digest.js";
9
- import { readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
10
- import { resolveSkillName } from "./verify.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";
11
13
  export const DEFAULT_TRUST_ROOT_EXPIRY = '365d';
12
14
  export const DEFAULT_REVOCATIONS_EXPIRY = '30d';
13
- const PRIVATE_KEY_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/u;
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
+ }
14
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
+ }
15
48
  const root = await loadPrivateKey(options.rootKeyPath);
16
49
  const issuedAt = truncateToSecond(options.now);
17
50
  const trustRoot = {
18
- version: 1, issuedAt, expiresAt: addDuration(issuedAt, options.trustRootExpires ?? DEFAULT_TRUST_ROOT_EXPIRY, 'trust root expiry'),
19
- root, approvers: [],
51
+ version: 1,
52
+ issuedAt,
53
+ expiresAt: addDuration(issuedAt, options.trustRootExpires ?? DEFAULT_TRUST_ROOT_EXPIRY, 'trust root expiry'),
54
+ root,
55
+ approvers: [],
20
56
  };
21
57
  const revocations = {
22
- version: 1, issuedAt, expiresAt: addDuration(issuedAt, options.revocationsExpires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
23
- rootKeyId: root.keyId, keys: [], digests: [],
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: [],
24
64
  };
25
- const trustRootPath = await writeNewFile(options.trustRootOut, signTrustRoot(trustRoot, root.privateKey));
26
- const revocationsPath = await writeNewFile(options.revocationsOut, signRevocations(revocations, root.privateKey));
27
- return { rootKeyId: root.keyId, trustRoot: trustRootPath, revocations: revocationsPath };
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
+ }
28
80
  }
29
81
  async function updateTrustRoot(options, change) {
30
82
  const root = await loadPrivateKey(options.rootKeyPath);
31
- const current = readTrustRootForUpdate(await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024), root.keyId);
83
+ const rawBytes = await readRegularFile(options.trustRootPath, 'Trust root', MAX_TRUST_ROOT_BYTES);
84
+ const current = readTrustRootForUpdate(rawBytes, root.keyId);
32
85
  const issuedAt = truncateToSecond(options.now);
86
+ const expiresAt = options.expires
87
+ ? addDuration(issuedAt, options.expires, 'trust root expiry')
88
+ : current.expiresAt;
33
89
  const next = {
34
90
  ...current,
35
91
  version: current.version + 1,
36
92
  issuedAt,
37
- expiresAt: options.expires ? addDuration(issuedAt, options.expires, 'trust root expiry') : current.expiresAt,
38
- approvers: current.approvers.map((approver) => ({ ...approver, scopes: [...approver.scopes] })),
93
+ expiresAt,
94
+ approvers: current.approvers.map((approver) => ({
95
+ ...approver,
96
+ scopes: [...approver.scopes],
97
+ })),
39
98
  };
40
99
  change(next);
41
- if (next.expiresAt <= issuedAt)
100
+ if (next.expiresAt <= issuedAt) {
42
101
  throw new Error('The trust root would already be expired; pass --expires to extend it');
43
- const written = await writeFileAtomic(options.out ?? options.trustRootPath, signTrustRoot(next, root.privateKey));
102
+ }
103
+ const targetPath = options.out ?? options.trustRootPath;
104
+ const written = await writeFileAtomic(targetPath, signTrustRoot(next, root.privateKey));
44
105
  return { version: next.version, path: written, trustRoot: next };
45
106
  }
46
107
  export async function addApprover(options) {
108
+ const approverName = requireString(options.name, 'Approver name', MAX_APPROVER_NAME_LEN);
47
109
  const approverKey = await loadPublicKey(options.publicKeyPath);
48
- if (options.scopes.length === 0)
110
+ if (options.scopes.length === 0) {
49
111
  throw new Error('At least one --scope is required');
112
+ }
50
113
  const scopes = [...new Set(options.scopes.map((scope) => validateScope(scope)))].sort();
51
- const result = await updateTrustRoot({ rootKeyPath: options.rootKeyPath, trustRootPath: options.trustRootPath, out: options.out, now: options.now, expires: options.trustRootExpires }, (trustRoot) => {
52
- if (approverKey.keyId === trustRoot.root.keyId)
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) {
53
127
  throw new Error('The root key cannot be an approver; generate a separate approver key');
54
- trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== approverKey.keyId);
55
- trustRoot.approvers.push({ ...approverKey, name: options.name, scopes, expiresAt: addDuration(truncateToSecond(options.now), options.expires, 'approver expiry') });
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;
56
140
  });
57
141
  return { version: result.version, path: result.path, keyId: approverKey.keyId };
58
142
  }
59
143
  export async function removeApprover(options) {
60
- return await updateTrustRoot({ rootKeyPath: options.rootKeyPath, trustRootPath: options.trustRootPath, out: options.out, now: options.now, expires: options.trustRootExpires }, (trustRoot) => {
61
- const before = trustRoot.approvers.length;
62
- trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== options.keyId);
63
- if (trustRoot.approvers.length === before)
64
- throw new Error(`No approver with key id ${options.keyId}`);
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
+ }
65
157
  });
66
158
  }
67
159
  export async function updateRevocations(options) {
68
160
  const root = await loadPrivateKey(options.rootKeyPath);
69
- const current = readRevocationsForUpdate(await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024), root.keyId, root.publicKey);
161
+ const rawBytes = await readRegularFile(options.revocationsPath, 'Revocation list', MAX_REVOCATIONS_BYTES);
162
+ const current = readRevocationsForUpdate(rawBytes, root.keyId, root.publicKey);
70
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);
71
166
  const next = {
72
- ...current, version: current.version + 1, issuedAt,
73
- expiresAt: addDuration(issuedAt, options.expires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
74
- keys: [...current.keys], digests: [...current.digests],
167
+ ...current,
168
+ version: current.version + 1,
169
+ issuedAt,
170
+ expiresAt,
171
+ keys: [...current.keys],
172
+ digests: [...current.digests],
75
173
  };
76
- if (options.revokeKey) {
77
- if (next.keys.some((entry) => entry.keyId === options.revokeKey))
78
- throw new Error(`Key ${options.revokeKey} is already revoked`);
79
- next.keys.push({ keyId: options.revokeKey, reason: options.reason ?? 'revoked', revokedAt: issuedAt });
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 });
80
180
  }
81
- if (options.revokeDigest) {
181
+ if (options.revokeDigest !== undefined) {
82
182
  const digest = validateDigest(options.revokeDigest);
83
- if (next.digests.some((entry) => entry.digest === digest))
183
+ if (next.digests.some((entry) => entry.digest === digest)) {
84
184
  throw new Error(`Digest ${digest} is already revoked`);
85
- next.digests.push({ digest, reason: options.reason ?? 'revoked', revokedAt: issuedAt });
185
+ }
186
+ next.digests.push({ digest, reason, revokedAt: issuedAt });
86
187
  }
87
- const written = await writeFileAtomic(options.out ?? options.revocationsPath, signRevocations(next, root.privateKey));
188
+ const targetPath = options.out ?? options.revocationsPath;
189
+ const written = await writeFileAtomic(targetPath, signRevocations(next, root.privateKey));
88
190
  return { version: next.version, path: written, expiresAt: next.expiresAt };
89
191
  }
90
192
  export async function approveSkill(options) {
91
193
  const skillDir = path.resolve(options.skillDir);
92
- const approver = await loadPrivateKey(options.approverKeyPath);
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.
93
197
  await resolveOutside(options.approverKeyPath, skillDir, 'Approver private key');
94
- const skillName = await resolveSkillName(skillDir, options.name);
198
+ const approver = await loadPrivateKey(options.approverKeyPath);
95
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
+ }
96
206
  for (const [filePath, content] of tree.contents) {
97
- if (PRIVATE_KEY_PATTERN.test(content.toString('latin1'))) {
207
+ if (containsPrivateKey(content)) {
98
208
  throw new Error(`Refusing to approve: ${filePath} contains a private key. Remove it from the Skill and rotate that key.`);
99
209
  }
100
210
  }
101
211
  let previousDigest = null;
102
212
  if (options.previous) {
103
- previousDigest = options.previous.startsWith('sha256:')
104
- ? validateDigest(options.previous, 'previous digest')
105
- : parseCertificate(await readRegularFile(options.previous, 'Previous certificate', 8 * 1024 * 1024)).digest;
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
+ }
106
220
  }
107
221
  const issuedAt = truncateToSecond(options.now);
108
222
  const expiresAt = addDuration(issuedAt, options.expires, 'certificate expiry');
109
223
  const bytes = issueCertificate({
110
- skillName, digest: tree.digest, files: tree.files, approver, issuedAt, expiresAt, reason: options.reason, previousDigest,
224
+ skillName,
225
+ digest: tree.digest,
226
+ files: tree.files,
227
+ approver,
228
+ issuedAt,
229
+ expiresAt,
230
+ reason: options.reason,
231
+ previousDigest,
111
232
  });
112
- const out = options.out ?? path.join(tree.root, CERTIFICATE_FILENAME);
113
- const written = await writeFileAtomic(out, bytes);
114
- return { path: written, skillName, digest: tree.digest, certificateId: parseCertificate(bytes).id, expiresAt };
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
+ };
115
243
  }
@@ -2,33 +2,56 @@
2
2
  // Parsing rejects any byte sequence that is not exactly the canonical form, so
3
3
  // duplicate keys, alternate escapes and reordered fields cannot change meaning.
4
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;
5
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
+ }
6
14
  export function isRecord(value) {
7
- return value !== null && typeof value === 'object' && !Array.isArray(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;
8
20
  }
9
21
  function canonicalValue(value, depth, state) {
10
22
  state.nodes += 1;
11
- if (state.nodes > 200_000 || depth > 64)
23
+ if (state.nodes > MAX_CANONICAL_JSON_NODES || depth > MAX_CANONICAL_JSON_DEPTH) {
12
24
  throw new Error('Canonical JSON exceeds structural limits');
13
- if (value === null)
25
+ }
26
+ if (value === null) {
14
27
  return 'null';
15
- if (typeof value === 'string')
28
+ }
29
+ if (typeof value === 'string') {
16
30
  return JSON.stringify(value);
17
- if (typeof value === 'boolean')
31
+ }
32
+ if (typeof value === 'boolean') {
18
33
  return value ? 'true' : 'false';
34
+ }
19
35
  if (typeof value === 'number') {
20
- if (!Number.isSafeInteger(value))
36
+ if (!Number.isSafeInteger(value)) {
21
37
  throw new Error('Canonical JSON numbers must be safe integers');
22
- return JSON.stringify(value);
38
+ }
39
+ return Object.is(value, -0) ? '0' : JSON.stringify(value);
23
40
  }
24
41
  if (Array.isArray(value)) {
25
- return `[${value.map((item) => canonicalValue(item, depth + 1, state)).join(',')}]`;
42
+ const elements = value.map((item) => canonicalValue(item, depth + 1, state));
43
+ return `[${elements.join(',')}]`;
26
44
  }
27
45
  if (isRecord(value)) {
28
- const entries = Object.keys(value).sort().map((key) => {
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
+ }
29
51
  const item = value[key];
30
- if (item === undefined)
52
+ if (item === undefined) {
31
53
  throw new Error(`Canonical JSON field ${JSON.stringify(key)} is undefined`);
54
+ }
32
55
  return `${JSON.stringify(key)}:${canonicalValue(item, depth + 1, state)}`;
33
56
  });
34
57
  return `{${entries.join(',')}}`;
@@ -36,64 +59,86 @@ function canonicalValue(value, depth, state) {
36
59
  throw new Error('Canonical JSON contains an unsupported value');
37
60
  }
38
61
  export function serializeCanonicalJson(value) {
39
- return `${canonicalValue(value, 0, { nodes: 0 })}\n`;
62
+ const state = { nodes: 0 };
63
+ return `${canonicalValue(value, 0, state)}\n`;
40
64
  }
41
65
  export function canonicalBytes(value) {
42
66
  return Buffer.from(serializeCanonicalJson(value), 'utf8');
43
67
  }
44
68
  export function parseCanonicalJsonBytes(input, label = 'JSON document') {
45
- const bytes = Buffer.from(input);
46
- if (bytes.length === 0 || bytes.length > MAX_CANONICAL_JSON_BYTES) {
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) {
47
75
  throw new Error(`${label} must be between 1 byte and ${MAX_CANONICAL_JSON_BYTES} bytes`);
48
76
  }
49
- let text;
50
77
  try {
51
- text = utf8Decoder.decode(bytes);
78
+ text = utf8Decoder.decode(input);
52
79
  }
53
80
  catch {
54
81
  throw new Error(`${label} is not valid UTF-8`);
55
82
  }
56
- if (text.charCodeAt(0) === 0xfeff || !text.endsWith('\n')) {
83
+ if (text.charCodeAt(0) === UTF8_BOM_CHAR_CODE || !text.endsWith('\n')) {
57
84
  throw new Error(`${label} must be canonical UTF-8 JSON with one trailing LF`);
58
85
  }
59
- let value;
60
86
  try {
61
- value = JSON.parse(text.slice(0, -1));
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
+ });
62
96
  }
63
97
  catch {
64
98
  throw new Error(`${label} is not valid JSON`);
65
99
  }
66
- let canonical;
67
100
  try {
68
101
  canonical = serializeCanonicalJson(value);
69
102
  }
70
103
  catch (error) {
71
- throw new Error(`${label} is structurally invalid: ${error.message}`);
104
+ throw new Error(`${label} is structurally invalid: ${errorMessage(error)}`);
72
105
  }
73
- if (!bytes.equals(Buffer.from(canonical, 'utf8'))) {
106
+ if (canonical !== text) {
74
107
  throw new Error(`${label} is not canonical JSON (duplicate keys and alternate encodings are rejected)`);
75
108
  }
76
109
  return value;
77
110
  }
78
111
  export function exactKeys(value, keys, label) {
79
- if (!isRecord(value))
112
+ if (!isRecord(value)) {
80
113
  throw new Error(`${label} must be a JSON object`);
81
- const actual = Object.keys(value).sort();
82
- const expected = [...keys].sort();
83
- if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
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])) {
84
119
  throw new Error(`${label} has missing or unsupported fields`);
85
120
  }
86
121
  return value;
87
122
  }
88
- export function requireString(value, label, maxLength = 1024) {
89
- if (typeof value !== 'string' || value.length === 0 || value.length > maxLength || /[\u0000-\u001f\u007f]/u.test(value)) {
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)) {
90
131
  throw new Error(`${label} must be a non-empty string of at most ${maxLength} characters without control characters`);
91
132
  }
92
133
  return value;
93
134
  }
94
135
  export function requireArray(value, label, maxLength) {
95
- if (!Array.isArray(value) || value.length > 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) {
96
140
  throw new Error(`${label} must be an array of at most ${maxLength} items`);
141
+ }
97
142
  return value;
98
143
  }
99
144
  export function requirePositiveInteger(value, label) {
@@ -18,11 +18,19 @@ export function issueCertificate(options) {
18
18
  throw new Error('Certificate must expire after it is issued');
19
19
  const statement = {
20
20
  _type: STATEMENT_TYPE,
21
- subject: [{ name: options.skillName, digest: { [SUBJECT_DIGEST_ALGORITHM]: options.digest.slice('sha256:'.length) } }],
21
+ subject: [{
22
+ name: options.skillName,
23
+ digest: { [SUBJECT_DIGEST_ALGORITHM]: options.digest.slice('sha256:'.length) }
24
+ }],
22
25
  predicateType: CERTIFICATE_PREDICATE_TYPE,
23
26
  predicate: {
24
27
  tree_profile: TREE_PROFILE,
25
- files: options.files.map((file) => ({ path: file.path, size: file.size, sha256: file.sha256, exec: file.exec })),
28
+ files: options.files.map((file) => ({
29
+ path: file.path,
30
+ size: file.size,
31
+ sha256: file.sha256,
32
+ exec: file.exec
33
+ })),
26
34
  approval: {
27
35
  approver_key_id: options.approver.keyId,
28
36
  issued_at: formatTimestamp(options.issuedAt),
@@ -56,37 +64,37 @@ function parseFiles(value, label) {
56
64
  export function parseCertificate(bytes) {
57
65
  const label = 'certificate';
58
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;
59
80
  if (envelope.payloadType !== STATEMENT_PAYLOAD_TYPE)
60
81
  throw new Error(`${label} has the wrong payload type`);
61
- const statement = exactKeys(parseCanonicalJsonBytes(envelope.payloadBytes, `${label} statement`), ['_type', 'subject', 'predicateType', 'predicate'], `${label} statement`);
62
82
  if (statement._type !== STATEMENT_TYPE)
63
83
  throw new Error(`${label} is not an in-toto v1 statement`);
64
84
  if (statement.predicateType !== CERTIFICATE_PREDICATE_TYPE)
65
85
  throw new Error(`${label} has an unsupported predicateType`);
66
- const subjects = requireArray(statement.subject, `${label} subject`, 1);
67
86
  if (subjects.length !== 1)
68
87
  throw new Error(`${label} must have exactly one subject`);
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
88
  if (predicate.tree_profile !== TREE_PROFILE)
75
89
  throw new Error(`${label} uses unsupported tree profile ${String(predicate.tree_profile)}`);
76
- const files = parseFiles(predicate.files, `${label} files`);
77
90
  if (!files.some((file) => file.path === SKILL_FILENAME))
78
91
  throw new Error(`${label} file list does not include ${SKILL_FILENAME}`);
79
92
  if (digestFileList(files) !== digest)
80
93
  throw new Error(`${label} file list does not match its subject digest`);
81
- const approval = exactKeys(predicate.approval, ['approver_key_id', 'issued_at', 'expires_at', 'reason'], `${label} approval`);
82
- const approverKeyId = String(approval.approver_key_id);
83
94
  if (approverKeyId !== envelope.signatures[0].keyid)
84
95
  throw new Error(`${label} approver_key_id does not match the signing key`);
85
- const issuedAt = parseTimestamp(approval.issued_at, `${label} issued_at`);
86
- const expiresAt = parseTimestamp(approval.expires_at, `${label} expires_at`);
87
96
  if (expiresAt <= issuedAt)
88
97
  throw new Error(`${label} expires before it is issued`);
89
- const previous = predicate.previous_digest;
90
98
  if (previous !== null && isRecord(previous))
91
99
  throw new Error(`${label} previous_digest is invalid`);
92
100
  return {