@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.
@@ -1,17 +1,33 @@
1
- import { appendFile, lstat, opendir, stat } from 'node:fs/promises';
2
- import { hostname } from 'node:os';
1
+ import { lstat, opendir, stat } from 'node:fs/promises';
2
+ import { homedir, hostname } from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
5
- import { readRegularFile, writeFileAtomic } from "./fs-safe.js";
5
+ import { appendToRegularFile, isInside, readRegularFile, realpathAllowingMissing, resolveInsideDirectory, writeFileAtomic } from "./fs-safe.js";
6
6
  import { validateKeyId } from "./keys.js";
7
7
  import { CERTIFICATE_FILENAME } from "./tree-digest.js";
8
8
  import { loadTrustContext, unverifiable, verifySkill, } from "./verify.js";
9
9
  export const POLICY_VERSION = 'mago.policy/v1';
10
10
  export const STATE_TYPE = 'mago.host-state/v1';
11
- export const DEFAULT_POLICY_PATH = path.join('.mago-ski', 'policy.json');
12
11
  const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
12
+ /** Per-Skill budget across all certificate candidates (explicit file, policy directories, in-Skill file). */
13
+ export const MAX_CERTIFICATE_CANDIDATES = 64;
14
+ export const MAX_CERTIFICATE_TOTAL_BYTES = 32 * 1024 * 1024;
13
15
  const POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations', 'certificate_dirs', 'skill_dirs', 'state_file', 'decision_log'];
14
16
  const REQUIRED_POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations'];
17
+ /*
18
+ * Where hosts and the CLI read policy when none is given: $MAGO_SKI_POLICY (absolute, or "~/..."), else ~/.mago-ski/policy.json.
19
+ * Never a path in the current directory, because the project being checked may be controlled by the code under review.
20
+ */
21
+ export function defaultPolicyPath(env = process.env, home = homedir()) {
22
+ const configured = env.MAGO_SKI_POLICY;
23
+ if (!configured)
24
+ return path.join(home, '.mago-ski', 'policy.json');
25
+ if (configured === '~' || configured.startsWith('~/'))
26
+ return path.join(home, configured.slice(2));
27
+ if (!path.isAbsolute(configured))
28
+ throw new Error(`MAGO_SKI_POLICY must be an absolute path (or start with "~/"); got "${configured}"`);
29
+ return configured;
30
+ }
15
31
  /** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
16
32
  export async function loadPolicy(policyPath) {
17
33
  const absolute = path.resolve(policyPath);
@@ -37,8 +53,10 @@ export async function loadPolicy(policyPath) {
37
53
  throw new Error('Policy mode must be "shadow" or "enforce"');
38
54
  const base = path.dirname(absolute);
39
55
  const resolvePath = (item, label) => path.resolve(base, requireString(item, `Policy ${label}`, 4096));
56
+ // decision_log and state_file are files this tool writes, so the policy may only place them in its own directory.
57
+ const writablePath = async (item, label) => item === undefined || item === null ? null : await resolveInsideDirectory(base, requireString(item, `Policy ${label}`, 4096), `Policy ${label}`);
40
58
  const optionalList = (item, label) => item === undefined ? [] : requireArray(item, `Policy ${label}`, 256).map((entry, index) => resolvePath(entry, `${label}[${index}]`));
41
- return {
59
+ const policy = {
42
60
  path: absolute,
43
61
  mode: value.mode,
44
62
  rootKeyId: validateKeyId(value.root_fingerprint, 'Policy root_fingerprint'),
@@ -46,9 +64,44 @@ export async function loadPolicy(policyPath) {
46
64
  revocationsPath: resolvePath(value.revocations, 'revocations'),
47
65
  certificateDirs: optionalList(value.certificate_dirs, 'certificate_dirs'),
48
66
  skillDirs: optionalList(value.skill_dirs, 'skill_dirs'),
49
- statePath: value.state_file === undefined || value.state_file === null ? null : resolvePath(value.state_file, 'state_file'),
50
- decisionLogPath: value.decision_log === undefined || value.decision_log === null ? null : resolvePath(value.decision_log, 'decision_log'),
67
+ statePath: await writablePath(value.state_file, 'state_file'),
68
+ decisionLogPath: await writablePath(value.decision_log, 'decision_log'),
51
69
  };
70
+ await rejectWriteTargetsThatOverlapInputs(policy);
71
+ return policy;
72
+ }
73
+ /** A path with symlinks resolved where possible; falls back to the lexical path (the read itself will fail later). */
74
+ async function canonicalOrLexical(target) {
75
+ try {
76
+ return await realpathAllowingMissing(target);
77
+ }
78
+ catch {
79
+ return path.resolve(target);
80
+ }
81
+ }
82
+ /** decision_log and state_file are overwritten or appended to, so they must not be a file the policy reads. */
83
+ async function rejectWriteTargetsThatOverlapInputs(policy) {
84
+ const inputs = [
85
+ ['the policy file', policy.path], ['trust_root', policy.trustRootPath], ['revocations', policy.revocationsPath],
86
+ ];
87
+ const directories = await Promise.all(policy.certificateDirs.map(canonicalOrLexical));
88
+ const targets = [['state_file', policy.statePath], ['decision_log', policy.decisionLogPath]];
89
+ const seen = [];
90
+ for (const [label, target] of targets) {
91
+ if (!target)
92
+ continue;
93
+ const canonical = await canonicalOrLexical(target);
94
+ for (const [name, input] of inputs) {
95
+ if (canonical === await canonicalOrLexical(input))
96
+ throw new Error(`Policy ${label} must not be ${name}`);
97
+ }
98
+ if (directories.some((directory) => isInside(directory, canonical)))
99
+ throw new Error(`Policy ${label} must not be inside a certificate_dirs directory`);
100
+ for (const [other, otherPath] of seen)
101
+ if (canonical === otherPath)
102
+ throw new Error(`Policy ${label} must not be the same file as ${other}`);
103
+ seen.push([label, canonical]);
104
+ }
52
105
  }
53
106
  async function readState(statePath) {
54
107
  let bytes;
@@ -72,8 +125,12 @@ async function readState(statePath) {
72
125
  }
73
126
  return roots;
74
127
  }
75
- /** Loads trust documents for a policy, enforcing rollback protection through the state file. */
76
- export async function loadPolicyTrust(policy, now) {
128
+ /**
129
+ * Loads trust documents for a policy, enforcing rollback protection through the state file.
130
+ * With `recordVersions: false` the state file is still read (the same rollback minimums apply) but never written:
131
+ * for observers such as the GUI, which must not move a host's rollback memory.
132
+ */
133
+ export async function loadPolicyTrust(policy, now, options = {}) {
77
134
  let trustRootBytes;
78
135
  let revocationsBytes;
79
136
  let roots = {};
@@ -89,7 +146,7 @@ export async function loadPolicyTrust(policy, now) {
89
146
  const seen = roots[policy.rootKeyId];
90
147
  const minimum = seen ? { trustRootVersion: seen.trust_root_version, revocationsVersion: seen.revocations_version } : undefined;
91
148
  const result = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: policy.rootKeyId, now, minimum });
92
- if (result.ok && policy.statePath) {
149
+ if (result.ok && policy.statePath && options.recordVersions !== false) {
93
150
  const next = { trust_root_version: result.context.trustRoot.version, revocations_version: result.context.revocations.version };
94
151
  if (!seen || next.trust_root_version > seen.trust_root_version || next.revocations_version > seen.revocations_version) {
95
152
  roots[policy.rootKeyId] = {
@@ -116,23 +173,51 @@ async function readOptional(filePath, label) {
116
173
  throw error;
117
174
  }
118
175
  }
119
- /** Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate. */
120
- export async function discoverCertificates(skillName, skillRoot, certificateDirs, explicit) {
121
- const sources = [];
176
+ /*
177
+ * Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate.
178
+ * Candidates are read lazily, one at a time, so a caller that stops early never reads the rest and none are retained here.
179
+ * Candidates come from the checkout under review, so a Skill may have at most MAX_CERTIFICATE_CANDIDATES candidate files
180
+ * totalling MAX_CERTIFICATE_TOTAL_BYTES; going over throws (the Skill is UNVERIFIABLE) instead of reading further.
181
+ */
182
+ export async function* iterateCertificates(skillName, skillRoot, certificateDirs, explicit) {
183
+ let count = 0;
184
+ let totalBytes = 0;
185
+ const seen = new Set();
186
+ const account = (source, bytes) => {
187
+ count += 1;
188
+ totalBytes += bytes.length;
189
+ if (count > MAX_CERTIFICATE_CANDIDATES)
190
+ throw new Error(`more than ${MAX_CERTIFICATE_CANDIDATES} certificate candidates for this Skill; reduce certificate_dirs or remove stray certificates`);
191
+ if (totalBytes > MAX_CERTIFICATE_TOTAL_BYTES)
192
+ throw new Error(`certificate candidates for this Skill exceed ${MAX_CERTIFICATE_TOTAL_BYTES} bytes in total`);
193
+ return { source, bytes };
194
+ };
122
195
  if (explicit) {
123
- const bytes = await readRegularFile(path.resolve(explicit), 'Certificate', MAX_CERTIFICATE_BYTES);
124
- sources.push({ source: path.resolve(explicit), bytes });
196
+ const candidate = path.resolve(explicit);
197
+ seen.add(candidate);
198
+ yield account(candidate, await readRegularFile(candidate, 'Certificate', MAX_CERTIFICATE_BYTES));
125
199
  }
126
200
  for (const directory of certificateDirs) {
127
201
  const candidate = path.join(directory, `${skillName}.cert.json`);
202
+ if (seen.has(candidate))
203
+ continue;
204
+ seen.add(candidate);
128
205
  const bytes = await readOptional(candidate, 'Certificate');
129
206
  if (bytes)
130
- sources.push({ source: candidate, bytes });
207
+ yield account(candidate, bytes);
131
208
  }
132
209
  const inSkill = path.join(skillRoot, CERTIFICATE_FILENAME);
133
- const bytes = await readOptional(inSkill, 'Certificate');
134
- if (bytes)
135
- sources.push({ source: inSkill, bytes });
210
+ if (!seen.has(inSkill)) {
211
+ const bytes = await readOptional(inSkill, 'Certificate');
212
+ if (bytes)
213
+ yield account(inSkill, bytes);
214
+ }
215
+ }
216
+ /** Collects every candidate (within the same budget). Prefer `iterateCertificates`, which retains nothing. */
217
+ export async function discoverCertificates(skillName, skillRoot, certificateDirs, explicit) {
218
+ const sources = [];
219
+ for await (const source of iterateCertificates(skillName, skillRoot, certificateDirs, explicit))
220
+ sources.push(source);
136
221
  return sources;
137
222
  }
138
223
  /**
@@ -141,13 +226,31 @@ export async function discoverCertificates(skillName, skillRoot, certificateDirs
141
226
  * directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
142
227
  */
143
228
  export const MAX_DISCOVERY_DEPTH = 16;
144
- export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
229
+ /** Work budget for one discovery run over untrusted trees; exceeding either throws DiscoveryBudgetError. */
230
+ export const MAX_DISCOVERED_SKILLS = 1_000;
231
+ export const MAX_DISCOVERY_ENTRIES = 50_000;
232
+ /** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
233
+ export class DiscoveryBudgetError extends Error {
234
+ constructor(message) {
235
+ super(message);
236
+ this.name = 'DiscoveryBudgetError';
237
+ }
238
+ }
239
+ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH, limits = {}) {
240
+ const maxSkills = limits.maxSkills ?? MAX_DISCOVERED_SKILLS;
241
+ const maxEntries = limits.maxEntries ?? MAX_DISCOVERY_ENTRIES;
145
242
  const found = new Set();
146
243
  const tooDeep = new Set();
244
+ let entries = 0;
245
+ const checkSkills = () => {
246
+ if (found.size + tooDeep.size > maxSkills)
247
+ throw new DiscoveryBudgetError(`more than ${maxSkills} Skills found under skill_dirs; narrow skill_dirs or split the repository`);
248
+ };
147
249
  async function walk(directory, depth) {
148
250
  try {
149
251
  await lstat(path.join(directory, 'SKILL.md'));
150
252
  found.add(directory);
253
+ checkSkills();
151
254
  return;
152
255
  }
153
256
  catch (error) {
@@ -164,6 +267,9 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
164
267
  throw error;
165
268
  }
166
269
  for await (const child of dir) {
270
+ entries += 1;
271
+ if (entries > maxEntries)
272
+ throw new DiscoveryBudgetError(`more than ${maxEntries} directory entries under skill_dirs; narrow skill_dirs or split the repository`);
167
273
  const childPath = path.join(directory, child.name);
168
274
  if (child.isSymbolicLink()) {
169
275
  try {
@@ -173,6 +279,7 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
173
279
  catch {
174
280
  // A dangling link has nothing a host could load.
175
281
  }
282
+ checkSkills();
176
283
  continue;
177
284
  }
178
285
  if (!child.isDirectory() || child.name === '.git' || child.name === 'node_modules')
@@ -180,6 +287,7 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
180
287
  // Hosts such as Pi search without a depth limit, so never skip deeper directories silently.
181
288
  if (depth + 1 > maxDepth) {
182
289
  tooDeep.add(childPath);
290
+ checkSkills();
183
291
  continue;
184
292
  }
185
293
  await walk(childPath, depth + 1);
@@ -201,8 +309,12 @@ export function actionFor(mode, verified) {
201
309
  export async function appendDecision(logPath, record) {
202
310
  if (!logPath)
203
311
  return;
204
- await appendFile(logPath, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: 0o600 });
312
+ // One JSON object per line. JSON.stringify escapes newlines and control characters; also escape the Unicode
313
+ // line separators some JSON Lines readers split on, plus C1 controls, DEL and bidi controls. The text is data, not shell syntax: never source a log.
314
+ const line = JSON.stringify(record).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
315
+ await appendToRegularFile(logPath, `${line}\n`, 'Decision log');
205
316
  }
317
+ /* */
206
318
  export function decisionRecord(result, mode, event, host = `${hostname()}`) {
207
319
  return {
208
320
  timestamp: result.checkedAt,
@@ -232,6 +344,6 @@ export async function verifyWithPolicy(policy, skillDir, options) {
232
344
  skillName: options.skillName,
233
345
  context,
234
346
  now: options.now,
235
- certificates: (name, root) => discoverCertificates(name, root, policy.certificateDirs, options.certificate),
347
+ certificates: (name, root) => iterateCertificates(name, root, policy.certificateDirs, options.certificate),
236
348
  });
237
349
  }
@@ -2,7 +2,7 @@ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requi
2
2
  import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
3
3
  import { validateKeyId } from "./keys.js";
4
4
  import { validateDigest } from "./names.js";
5
- import { formatTimestamp, parseTimestamp } from "./time.js";
5
+ import { formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
6
6
  import { TrustDocumentError } from "./trust-root.js";
7
7
  export const REVOCATIONS_PAYLOAD_TYPE = 'application/vnd.mago-ski.revocations+json';
8
8
  export const REVOCATIONS_TYPE = 'mago.revocations/v1';
@@ -63,6 +63,8 @@ export function parseRevocationsPayload(bytes) {
63
63
  };
64
64
  }
65
65
  export function verifyRevocations(bytes, trustRoot, now) {
66
+ // The freshness check below compares against `now`; an invalid Date would let an expired list through.
67
+ requireValidDate(now, 'Verification time');
66
68
  let revocations;
67
69
  try {
68
70
  revocations = readRevocationsForUpdate(bytes, trustRoot.root.keyId, trustRoot.root.publicKey);
@@ -1,9 +1,25 @@
1
1
  /** Allowed clock skew when checking that a signed object was not issued in the future. */
2
2
  export declare const CLOCK_SKEW_MS: number;
3
- /** UTC timestamp with second precision, e.g. 2026-10-09T12:00:00Z. */
3
+ /**
4
+ * Throws unless `date` is a Date that holds a real time.
5
+ * An invalid Date holds NaN, and every comparison with NaN is false,
6
+ * so an expiry check against it would silently pass.
7
+ * Every function that compares documents against the current time calls this on `now` first.
8
+ */
9
+ export declare function requireValidDate(date: Date, label: string): void;
10
+ /**
11
+ * Writes a date as a UTC timestamp with whole seconds, e.g. 2026-10-09T12:00:00Z.
12
+ * Milliseconds are dropped.
13
+ */
4
14
  export declare function formatTimestamp(date: Date): string;
15
+ /**
16
+ * Reads a timestamp in the exact format formatTimestamp writes.
17
+ * Dates that do not exist (2026-02-30, 24:00:00) are rejected.
18
+ */
5
19
  export declare function parseTimestamp(value: unknown, label: string): Date;
6
- /** Parses durations like 90d, 12h, 30m. */
20
+ /** Reads a duration such as 90d, 12h or 30m and returns it in milliseconds. */
7
21
  export declare function parseDuration(value: string, label?: string): number;
8
- export declare function addDuration(now: Date, duration: string, label?: string): Date;
22
+ /** Returns `start` plus a duration such as 90d, rounded down to a whole second. */
23
+ export declare function addDuration(start: Date, duration: string, label?: string): Date;
24
+ /** Drops the milliseconds, so the date survives formatTimestamp and parseTimestamp unchanged. */
9
25
  export declare function truncateToSecond(date: Date): Date;
package/dist/src/time.js CHANGED
@@ -1,32 +1,74 @@
1
+ /** The only timestamp format accepted: UTC with whole seconds, e.g. 2026-10-09T12:00:00Z. */
1
2
  const TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u;
3
+ /** A duration is 1 to 5 digits plus a unit; 99999d (about 273 years) is the largest. */
4
+ const DURATION_PATTERN = /^(\d{1,5})([dhm])$/u;
5
+ const UNIT_MS = {
6
+ d: 24 * 60 * 60 * 1000,
7
+ h: 60 * 60 * 1000,
8
+ m: 60 * 1000,
9
+ };
2
10
  /** Allowed clock skew when checking that a signed object was not issued in the future. */
3
11
  export const CLOCK_SKEW_MS = 5 * 60 * 1000;
4
- /** UTC timestamp with second precision, e.g. 2026-10-09T12:00:00Z. */
12
+ /**
13
+ * Throws unless `date` is a Date that holds a real time.
14
+ * An invalid Date holds NaN, and every comparison with NaN is false,
15
+ * so an expiry check against it would silently pass.
16
+ * Every function that compares documents against the current time calls this on `now` first.
17
+ */
18
+ export function requireValidDate(date, label) {
19
+ if (!(date instanceof Date) || Number.isNaN(date.getTime()))
20
+ throw new Error(`${label} must be a valid date`);
21
+ }
22
+ /**
23
+ * Writes a date as a UTC timestamp with whole seconds, e.g. 2026-10-09T12:00:00Z.
24
+ * Milliseconds are dropped.
25
+ */
5
26
  export function formatTimestamp(date) {
6
- return date.toISOString().replace(/\.\d{3}Z$/u, 'Z');
27
+ requireValidDate(date, 'Date to format');
28
+ const text = date.toISOString().replace(/\.\d{3}Z$/u, 'Z');
29
+ // toISOString writes years outside 0000-9999 as "+010000-..." or "-000001-...".
30
+ // parseTimestamp rejects those, so a document signed with one could never be read back.
31
+ if (!TIMESTAMP_PATTERN.test(text))
32
+ throw new Error('Timestamp must fall between the years 0000 and 9999');
33
+ return text;
7
34
  }
35
+ /**
36
+ * Reads a timestamp in the exact format formatTimestamp writes.
37
+ * Dates that do not exist (2026-02-30, 24:00:00) are rejected.
38
+ */
8
39
  export function parseTimestamp(value, label) {
9
40
  if (typeof value !== 'string' || !TIMESTAMP_PATTERN.test(value))
10
41
  throw new Error(`${label} must be a UTC timestamp like 2026-10-09T12:00:00Z`);
42
+ // Date quietly rolls impossible values over (2026-02-30 becomes March 2),
43
+ // so the parsed date must format back to exactly the same text.
11
44
  const date = new Date(value);
12
45
  if (Number.isNaN(date.getTime()) || formatTimestamp(date) !== value)
13
46
  throw new Error(`${label} is not a valid timestamp`);
14
47
  return date;
15
48
  }
16
- /** Parses durations like 90d, 12h, 30m. */
49
+ /** Reads a duration such as 90d, 12h or 30m and returns it in milliseconds. */
17
50
  export function parseDuration(value, label = 'duration') {
18
- const match = /^(\d{1,5})([dhm])$/u.exec(value);
51
+ // The type says string, but this is a public export: plain JavaScript callers can pass anything.
52
+ const match = typeof value === 'string' ? DURATION_PATTERN.exec(value) : null;
19
53
  if (!match)
20
54
  throw new Error(`${label} must look like 90d, 12h or 30m`);
21
55
  const amount = Number(match[1]);
22
56
  if (amount < 1)
23
57
  throw new Error(`${label} must be positive`);
24
- const unit = match[2] === 'd' ? 86_400_000 : match[2] === 'h' ? 3_600_000 : 60_000;
25
- return amount * unit;
58
+ // Five digits at most keeps the result (at most 8.64e12) well inside the safe integer range.
59
+ const unit = match[2];
60
+ return amount * UNIT_MS[unit];
26
61
  }
27
- export function addDuration(now, duration, label) {
28
- return new Date(Math.floor((now.getTime() + parseDuration(duration, label)) / 1000) * 1000);
62
+ /** Returns `start` plus a duration such as 90d, rounded down to a whole second. */
63
+ export function addDuration(start, duration, label = 'duration') {
64
+ requireValidDate(start, `${label} start`);
65
+ // Past the largest date JavaScript can hold (year 275760) the sum becomes an invalid Date.
66
+ const end = new Date(start.getTime() + parseDuration(duration, label));
67
+ requireValidDate(end, `${label} end`);
68
+ return truncateToSecond(end);
29
69
  }
70
+ /** Drops the milliseconds, so the date survives formatTimestamp and parseTimestamp unchanged. */
30
71
  export function truncateToSecond(date) {
72
+ requireValidDate(date, 'Date to truncate');
31
73
  return new Date(Math.floor(date.getTime() / 1000) * 1000);
32
74
  }
@@ -1,3 +1,4 @@
1
+ import { type BigIntStats } from 'node:fs';
1
2
  export declare const TREE_PROFILE = "mago.skill-tree/v2";
2
3
  export declare const CERTIFICATE_FILENAME = ".mago-ski-cert.json";
3
4
  export declare const IGNORE_FILENAME = ".skilldigestignore";
@@ -33,6 +34,8 @@ export interface IgnoreRule {
33
34
  directoryOnly: boolean;
34
35
  }
35
36
  export declare function parseIgnoreFile(text: string): IgnoreRule[];
37
+ /** Checks that a Skill root exists and is a real directory, with messages that name the path. */
38
+ export declare function requireSkillRoot(root: string): Promise<BigIntStats>;
36
39
  export declare function compareTreePaths(left: string, right: string): number;
37
40
  /** The tree digest is SHA-256 over the canonical JSON of the profile and the sorted per-file list. */
38
41
  export declare function digestFileList(files: readonly TreeFile[]): string;
@@ -17,6 +17,8 @@ const MAX_IGNORE_BYTES = 64 * 1024;
17
17
  const MAX_IGNORE_PATTERNS = 256;
18
18
  const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
19
19
  const noFollow = fsConstants.O_NOFOLLOW ?? 0;
20
+ // A FIFO swapped in after enumeration must fail the fstat check below, not block open(2).
21
+ const nonBlock = fsConstants.O_NONBLOCK ?? 0;
20
22
  function fail(message) {
21
23
  throw new Error(message);
22
24
  }
@@ -28,14 +30,17 @@ function decodeEntryName(name) {
28
30
  catch {
29
31
  fail('Skill tree contains a path that is not valid UTF-8');
30
32
  }
31
- if (decoded.length === 0 || decoded === '.' || decoded === '..' ||
32
- decoded.includes('/') || decoded.includes('\\') || decoded.includes(':') ||
33
+ if (decoded.length === 0 ||
34
+ decoded === '.' ||
35
+ decoded === '..' ||
36
+ decoded.includes('/') ||
37
+ decoded.includes('\\') ||
38
+ decoded.includes(':') ||
33
39
  /[. ]$/u.test(decoded) ||
34
40
  /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/iu.test(decoded) ||
35
41
  /[\u0000-\u001f\u007f]/u.test(decoded) ||
36
- decoded.normalize('NFC') !== decoded) {
42
+ decoded.normalize('NFC') !== decoded)
37
43
  fail(`Skill tree contains an unsupported path component: ${JSON.stringify(decoded)}`);
38
- }
39
44
  return decoded;
40
45
  }
41
46
  function sameFileVersion(left, right) {
@@ -51,7 +56,7 @@ export function isExecutable(mode) {
51
56
  async function readStable(absolutePath, label, expected) {
52
57
  let handle;
53
58
  try {
54
- handle = await open(absolutePath, fsConstants.O_RDONLY | noFollow);
59
+ handle = await open(absolutePath, fsConstants.O_RDONLY | noFollow | nonBlock);
55
60
  const before = await handle.stat({ bigint: true });
56
61
  if (!before.isFile() || (expected && !sameFileVersion(expected, before)))
57
62
  fail(`Skill file changed while being read: ${label}`);
@@ -98,16 +103,21 @@ export function parseIgnoreFile(text) {
98
103
  const rules = [];
99
104
  for (const rawLine of text.split(/\r?\n/u)) {
100
105
  const line = rawLine.trim();
106
+ const directoryOnly = line.endsWith('/');
107
+ const pattern = directoryOnly ? line.slice(0, -1) : line;
108
+ const segments = pattern.split('/');
101
109
  if (line === '' || line.startsWith('#'))
102
110
  continue;
103
111
  if (rules.length >= MAX_IGNORE_PATTERNS)
104
112
  fail(`${IGNORE_FILENAME} exceeds ${MAX_IGNORE_PATTERNS} patterns`);
105
- const directoryOnly = line.endsWith('/');
106
- const pattern = directoryOnly ? line.slice(0, -1) : line;
107
- const segments = pattern.split('/');
108
- if (pattern === '' || pattern.startsWith('/') || pattern.includes('\\') || /[*?[\]!]/u.test(pattern) ||
113
+ if (pattern === '' ||
114
+ pattern.startsWith('/') ||
115
+ pattern.includes('\\') ||
116
+ /[*?[\]!]/u.test(pattern) ||
109
117
  segments.some((segment) => segment === '' || segment === '.' || segment === '..') ||
110
- pattern === IGNORE_FILENAME || pattern === SKILL_FILENAME || pattern.normalize('NFC') !== pattern) {
118
+ pattern === IGNORE_FILENAME ||
119
+ pattern === SKILL_FILENAME ||
120
+ pattern.normalize('NFC') !== pattern) {
111
121
  fail(`${IGNORE_FILENAME} contains an unsupported pattern: ${JSON.stringify(line)} (use plain relative paths; globs are not supported)`);
112
122
  }
113
123
  rules.push({ pattern, directoryOnly });
@@ -123,10 +133,26 @@ function isIgnored(relativePath, isDirectory, rules) {
123
133
  }
124
134
  return false;
125
135
  }
126
- async function enumerate(root) {
127
- const rootStat = await lstat(root, { bigint: true });
128
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink())
136
+ /** Checks that a Skill root exists and is a real directory, with messages that name the path. */
137
+ export async function requireSkillRoot(root) {
138
+ let rootStat;
139
+ try {
140
+ rootStat = await lstat(root, { bigint: true });
141
+ }
142
+ catch (error) {
143
+ const code = error?.code;
144
+ if (code === 'ENOENT' || code === 'ENOTDIR')
145
+ fail(`Skill directory not found: ${root}`);
146
+ throw error;
147
+ }
148
+ if (rootStat.isSymbolicLink())
129
149
  fail('Skill root must be a real directory, not a symbolic link');
150
+ if (!rootStat.isDirectory())
151
+ fail(`Skill path is not a directory: ${root}`);
152
+ return rootStat;
153
+ }
154
+ async function enumerate(root) {
155
+ const rootStat = await requireSkillRoot(root);
130
156
  const canonicalRoot = await realpath(root);
131
157
  let rules = [];
132
158
  const ignorePath = path.join(canonicalRoot, IGNORE_FILENAME);
@@ -151,9 +177,8 @@ async function enumerate(root) {
151
177
  if (depth > 64)
152
178
  fail('Skill tree exceeds the maximum directory depth of 64');
153
179
  const directoryStat = await lstat(directory, { bigint: true });
154
- if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) {
180
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink())
155
181
  fail(`Skill tree contains a changed or symbolic-link directory: ${relativeDirectory || '.'}`);
156
- }
157
182
  const expected = relativeDirectory ? path.join(canonicalRoot, relativeDirectory) : canonicalRoot;
158
183
  if (await realpath(directory) !== expected)
159
184
  fail(`Skill tree directory path changed during traversal: ${relativeDirectory || '.'}`);
@@ -23,6 +23,11 @@ export declare class TrustDocumentError extends Error {
23
23
  }
24
24
  export declare function trustRootPayload(trustRoot: TrustRoot): Record<string, unknown>;
25
25
  export declare function signTrustRoot(trustRoot: TrustRoot, rootPrivateKey: KeyObject): Buffer;
26
+ /**
27
+ * Reads the JSON inside a signed trust root and checks that every part is well formed:
28
+ * the root key, each approver (key, name, scopes, expiry) and the document's own dates.
29
+ * It does not check the signature or whether the trust root has expired; verifyTrustRoot does.
30
+ */
26
31
  export declare function parseTrustRootPayload(bytes: Uint8Array): TrustRoot;
27
32
  /**
28
33
  * Verifies a signed trust root against the pinned root key fingerprint and the current time.
@@ -2,7 +2,7 @@ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requi
2
2
  import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
3
3
  import { parseSpki, validateKeyId } from "./keys.js";
4
4
  import { validateScope } from "./names.js";
5
- import { formatTimestamp, parseTimestamp } from "./time.js";
5
+ import { formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
6
6
  export const TRUST_ROOT_PAYLOAD_TYPE = 'application/vnd.mago-ski.trust-root+json';
7
7
  export const TRUST_ROOT_TYPE = 'mago.trust-root/v1';
8
8
  export const MAX_APPROVERS = 256;
@@ -38,31 +38,48 @@ export function signTrustRoot(trustRoot, rootPrivateKey) {
38
38
  const payload = canonicalBytes(trustRootPayload(trustRoot));
39
39
  return envelopeBytes(signEnvelope(TRUST_ROOT_PAYLOAD_TYPE, payload, trustRoot.root.keyId, rootPrivateKey));
40
40
  }
41
+ /** The exact fields each part of a trust-root payload must have: no more, no fewer. */
42
+ const TRUST_ROOT_FIELDS = ['type', 'version', 'issued_at', 'expires_at', 'root', 'approvers'];
43
+ const ROOT_FIELDS = ['key_id', 'public_key'];
44
+ const APPROVER_FIELDS = ['key_id', 'public_key', 'name', 'scopes', 'expires_at'];
45
+ /**
46
+ * Reads the JSON inside a signed trust root and checks that every part is well formed:
47
+ * the root key, each approver (key, name, scopes, expiry) and the document's own dates.
48
+ * It does not check the signature or whether the trust root has expired; verifyTrustRoot does.
49
+ */
41
50
  export function parseTrustRootPayload(bytes) {
42
51
  const label = 'trust-root payload';
43
- const value = exactKeys(parseCanonicalJsonBytes(bytes, label), ['type', 'version', 'issued_at', 'expires_at', 'root', 'approvers'], label);
52
+ const value = exactKeys(parseCanonicalJsonBytes(bytes, label), TRUST_ROOT_FIELDS, label);
44
53
  if (value.type !== TRUST_ROOT_TYPE)
45
54
  throw new Error(`${label} has unsupported type`);
46
- const rootValue = exactKeys(value.root, ['key_id', 'public_key'], `${label} root`);
47
- const root = parseSpki(rootValue.public_key, `${label} root public_key`, validateKeyId(rootValue.key_id, `${label} root key_id`));
55
+ // The root key: its public key must hash to the key_id it is listed under.
56
+ const rootValue = exactKeys(value.root, ROOT_FIELDS, `${label} root`);
57
+ const rootKeyId = validateKeyId(rootValue.key_id, `${label} root key_id`);
58
+ const root = parseSpki(rootValue.public_key, `${label} root public_key`, rootKeyId);
59
+ // The approvers: at most MAX_APPROVERS of them.
60
+ const approverItems = requireArray(value.approvers, `${label} approvers`, MAX_APPROVERS);
48
61
  const approvers = [];
49
- let previous = '';
50
- for (const [index, item] of requireArray(value.approvers, `${label} approvers`, MAX_APPROVERS).entries()) {
62
+ let previousKeyId = '';
63
+ for (const [index, item] of approverItems.entries()) {
51
64
  const itemLabel = `${label} approvers[${index}]`;
52
- const entry = exactKeys(item, ['key_id', 'public_key', 'name', 'scopes', 'expires_at'], itemLabel);
65
+ const entry = exactKeys(item, APPROVER_FIELDS, itemLabel);
53
66
  const keyId = validateKeyId(entry.key_id, `${itemLabel} key_id`);
54
- if (keyId <= previous)
67
+ // Each key_id must be larger than the one before.
68
+ if (keyId <= previousKeyId)
55
69
  throw new Error(`${label} approvers must be unique and sorted by key_id`);
56
- previous = keyId;
70
+ previousKeyId = keyId;
71
+ // The root key only signs trust roots; it must stay separate from the keys that approve Skills.
57
72
  if (keyId === root.keyId)
58
73
  throw new Error(`${label}: the root key must not also be an approver`);
59
- const scopes = requireArray(entry.scopes, `${itemLabel} scopes`, MAX_SCOPES).map((scope, scopeIndex) => validateScope(scope, `${itemLabel} scopes[${scopeIndex}]`));
74
+ // Scopes name the Skills this approver may sign for: at least one, sorted, no duplicates.
75
+ const scopes = requireArray(entry.scopes, `${itemLabel} scopes`, MAX_SCOPES)
76
+ .map((scope, scopeIndex) => validateScope(scope, `${itemLabel} scopes[${scopeIndex}]`));
60
77
  if (scopes.length === 0)
61
78
  throw new Error(`${itemLabel} needs at least one scope`);
62
- for (let scopeIndex = 1; scopeIndex < scopes.length; scopeIndex += 1) {
79
+ for (let scopeIndex = 1; scopeIndex < scopes.length; scopeIndex += 1)
63
80
  if (scopes[scopeIndex - 1] >= scopes[scopeIndex])
64
81
  throw new Error(`${itemLabel} scopes must be unique and sorted`);
65
- }
82
+ // The approver's public key must hash to its key_id, like the root key above.
66
83
  approvers.push({
67
84
  ...parseSpki(entry.public_key, `${itemLabel} public_key`, keyId),
68
85
  name: requireString(entry.name, `${itemLabel} name`, 128),
@@ -70,17 +87,21 @@ export function parseTrustRootPayload(bytes) {
70
87
  expiresAt: parseTimestamp(entry.expires_at, `${itemLabel} expires_at`),
71
88
  });
72
89
  }
90
+ // The trust root's own lifetime: it must expire after it is issued.
73
91
  const issuedAt = parseTimestamp(value.issued_at, `${label} issued_at`);
74
92
  const expiresAt = parseTimestamp(value.expires_at, `${label} expires_at`);
75
93
  if (expiresAt <= issuedAt)
76
94
  throw new Error(`${label} expires before it is issued`);
77
- return { version: requirePositiveInteger(value.version, `${label} version`), issuedAt, expiresAt, root, approvers };
95
+ const version = requirePositiveInteger(value.version, `${label} version`);
96
+ return { version, issuedAt, expiresAt, root, approvers };
78
97
  }
79
98
  /**
80
99
  * Verifies a signed trust root against the pinned root key fingerprint and the current time.
81
100
  * Rollback (an older version than already seen) is checked separately against host state.
82
101
  */
83
102
  export function verifyTrustRoot(bytes, pinnedRootKeyId, now) {
103
+ // The expiry check below compares against `now`; an invalid Date would make it pass.
104
+ requireValidDate(now, 'Verification time');
84
105
  let trustRoot;
85
106
  try {
86
107
  const envelope = parseEnvelope(bytes, 'trust root');