@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.
@@ -3,31 +3,71 @@ import { constants as fsConstants } from 'node:fs';
3
3
  import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  const noFollow = fsConstants.O_NOFOLLOW ?? 0;
6
+ // Never block in open(2) on a FIFO swapped in after the lstat check; the fstat below then rejects it.
7
+ const nonBlock = fsConstants.O_NONBLOCK ?? 0;
8
+ const DEFAULT_MAX_READ_BYTES = 1024 * 1024;
9
+ const READ_CHUNK_BYTES = 64 * 1024;
10
+ const DEFAULT_FILE_MODE = 0o644;
11
+ const DEFAULT_LOG_MODE = 0o600;
12
+ const TEMP_RANDOM_BYTES = 6;
13
+ function sameFileIdentity(left, right) {
14
+ return left.dev === right.dev && left.ino === right.ino;
15
+ }
16
+ function sameFileVersion(left, right) {
17
+ return (sameFileIdentity(left, right) &&
18
+ left.size === right.size &&
19
+ left.mtimeNs === right.mtimeNs &&
20
+ left.ctimeNs === right.ctimeNs);
21
+ }
6
22
  export function isInside(root, candidate) {
7
- const relative = path.relative(root, candidate);
8
- return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
23
+ const resolvedRoot = path.resolve(root);
24
+ const resolvedCandidate = path.resolve(candidate);
25
+ const relative = path.relative(resolvedRoot, resolvedCandidate);
26
+ return (relative === '' ||
27
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));
9
28
  }
10
- /** Reads a regular, non-symlink file, failing if it changes while being read. */
11
- export async function readRegularFile(filePath, label, maxBytes = 1024 * 1024) {
12
- const entry = await lstat(filePath);
13
- if (entry.isSymbolicLink() || !entry.isFile())
29
+ /**
30
+ * Reads a regular, non-symlink file, failing if it changes while being read.
31
+ * The type and size are checked before any content is read, and at most `maxBytes` (+1 to detect growth) are read.
32
+ */
33
+ export async function readRegularFile(filePath, label, maxBytes = DEFAULT_MAX_READ_BYTES) {
34
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
35
+ throw new Error(`Invalid maxBytes limit for ${label}`);
36
+ }
37
+ const maxLimit = BigInt(maxBytes);
38
+ const entry = await lstat(filePath, { bigint: true });
39
+ if (entry.isSymbolicLink() || !entry.isFile()) {
14
40
  throw new Error(`${label} must be a regular, non-symlink file`);
15
- if (entry.size > maxBytes)
41
+ }
42
+ if (entry.size > maxLimit) {
16
43
  throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
17
- const handle = await open(filePath, fsConstants.O_RDONLY | noFollow);
44
+ }
45
+ let handle;
18
46
  try {
19
- const before = await handle.stat();
20
- if (!before.isFile() || before.dev !== entry.dev || before.ino !== entry.ino)
47
+ handle = await open(filePath, fsConstants.O_RDONLY | noFollow | nonBlock);
48
+ const before = await handle.stat({ bigint: true });
49
+ if (!before.isFile() || !sameFileIdentity(entry, before))
21
50
  throw new Error(`${label} changed while being read`);
22
- const bytes = await handle.readFile();
23
- const after = await handle.stat();
24
- if (bytes.length > maxBytes || before.size !== after.size || before.mtimeMs !== after.mtimeMs || bytes.length !== after.size) {
25
- throw new Error(`${label} changed while being read or exceeds its size limit`);
51
+ if (before.size > maxLimit)
52
+ throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
53
+ const chunks = [];
54
+ let total = 0;
55
+ while (total <= maxBytes) {
56
+ const remaining = maxBytes + 1 - total;
57
+ const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
58
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
59
+ if (bytesRead === 0)
60
+ break;
61
+ total += bytesRead;
62
+ chunks.push(chunk.subarray(0, bytesRead));
26
63
  }
27
- return bytes;
64
+ const after = await handle.stat({ bigint: true });
65
+ if (total > maxBytes || !sameFileVersion(before, after) || BigInt(total) !== after.size)
66
+ throw new Error(`${label} changed while being read or exceeds its size limit`);
67
+ return Buffer.concat(chunks, total);
28
68
  }
29
69
  finally {
30
- await handle.close();
70
+ await handle?.close();
31
71
  }
32
72
  }
33
73
  /** Resolves a file path and requires it to be outside `root` (both canonicalized). */
@@ -44,36 +84,48 @@ export async function resolveOutside(filePath, root, label, { allowMissing = fal
44
84
  canonical = await realpath(requested);
45
85
  }
46
86
  catch (error) {
47
- if (!allowMissing || error?.code !== 'ENOENT')
87
+ const code = error?.code;
88
+ if (!allowMissing || code !== 'ENOENT')
48
89
  throw error;
49
- canonical = path.join(await realpath(path.dirname(requested)), path.basename(requested));
90
+ canonical = path.join(await realpathAllowingMissing(path.dirname(requested)), path.basename(requested));
50
91
  }
51
- if (isInside(canonicalRoot, canonical))
92
+ if (isInside(canonicalRoot, canonical)) {
52
93
  throw new Error(`${label} must be outside ${canonicalRoot}`);
94
+ }
53
95
  return canonical;
54
96
  }
55
97
  async function writeHandle(filePath, bytes, mode, flags) {
56
98
  const handle = await open(filePath, flags, mode);
99
+ let succeeded = false;
57
100
  try {
58
101
  await handle.writeFile(bytes);
59
102
  await handle.sync();
103
+ succeeded = true;
60
104
  }
61
- catch (error) {
62
- await handle.close();
63
- await unlink(filePath).catch(() => { });
64
- throw error;
105
+ finally {
106
+ await handle.close().catch((closeError) => {
107
+ if (succeeded) {
108
+ succeeded = false;
109
+ throw closeError;
110
+ }
111
+ });
112
+ if (!succeeded)
113
+ await unlink(filePath).catch(() => { });
65
114
  }
66
- await handle.close();
67
115
  }
68
116
  /** Creates a new file; refuses to overwrite anything that already exists. */
69
- export async function writeNewFile(filePath, bytes, mode = 0o644) {
117
+ export async function writeNewFile(filePath, bytes, mode = DEFAULT_FILE_MODE) {
70
118
  const target = path.resolve(filePath);
71
- await writeHandle(target, bytes, mode, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow);
119
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow;
120
+ await writeHandle(target, bytes, mode, flags);
72
121
  return target;
73
122
  }
74
123
  /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
75
- export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
124
+ export async function writeFileAtomic(filePath, bytes, mode = DEFAULT_FILE_MODE) {
76
125
  const target = path.resolve(filePath);
126
+ const randomHex = randomBytes(TEMP_RANDOM_BYTES).toString('hex');
127
+ const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomHex}.tmp`);
128
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow;
77
129
  try {
78
130
  const existing = await lstat(target);
79
131
  if (existing.isSymbolicLink() || !existing.isFile())
@@ -83,8 +135,7 @@ export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
83
135
  if (error?.code !== 'ENOENT')
84
136
  throw error;
85
137
  }
86
- const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomBytes(6).toString('hex')}.tmp`);
87
- await writeHandle(temporary, bytes, mode, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow);
138
+ await writeHandle(temporary, bytes, mode, flags);
88
139
  try {
89
140
  await rename(temporary, target);
90
141
  }
@@ -94,3 +145,85 @@ export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
94
145
  }
95
146
  return target;
96
147
  }
148
+ /** Canonical path of `target`, resolving symlinks on the longest existing prefix. A dangling link on the way is an error. */
149
+ export async function realpathAllowingMissing(target) {
150
+ let current = path.resolve(target);
151
+ const missingParts = [];
152
+ while (true) {
153
+ try {
154
+ const resolvedPrefix = await realpath(current);
155
+ return path.join(resolvedPrefix, ...missingParts.reverse());
156
+ }
157
+ catch (error) {
158
+ if (error?.code !== 'ENOENT')
159
+ throw error;
160
+ // realpath also fails with ENOENT for a dangling symlink; its target could be created later.
161
+ const existsAsDanglingLink = await lstat(current).then(() => true, () => false);
162
+ if (existsAsDanglingLink)
163
+ throw new Error(`${current} is a dangling symbolic link`);
164
+ const parent = path.dirname(current);
165
+ if (parent === current)
166
+ throw error;
167
+ missingParts.push(path.basename(current));
168
+ current = parent;
169
+ }
170
+ }
171
+ }
172
+ /**
173
+ * Resolves a policy-supplied path against `base` and requires it to name something strictly inside `base`,
174
+ * after symlinks in its parent directories are resolved. An existing final component must be a regular,
175
+ * non-symlink file. Returns the canonical path.
176
+ */
177
+ export async function resolveInsideDirectory(base, item, label) {
178
+ const resolvedBase = path.resolve(base);
179
+ const canonicalBase = await realpath(resolvedBase);
180
+ const requested = path.resolve(resolvedBase, item);
181
+ const reject = () => new Error(`${label} must name a file inside the policy file's directory (${canonicalBase}); got "${item}"`);
182
+ if (!isInside(resolvedBase, requested) || requested === resolvedBase) {
183
+ throw reject();
184
+ }
185
+ const canonicalParent = await realpathAllowingMissing(path.dirname(requested));
186
+ const canonical = path.join(canonicalParent, path.basename(requested));
187
+ if (canonical === canonicalBase || !isInside(canonicalBase, canonical))
188
+ throw reject();
189
+ try {
190
+ const entry = await lstat(canonical);
191
+ if (entry.isSymbolicLink() || !entry.isFile())
192
+ throw new Error(`${label} must be a regular, non-symlink file`);
193
+ }
194
+ catch (error) {
195
+ if (error?.code !== 'ENOENT')
196
+ throw error;
197
+ }
198
+ return canonical;
199
+ }
200
+ /**
201
+ * Appends text to a log file, creating it (mode 600) if needed. Refuses symbolic links and anything that is not
202
+ * a regular file; O_NONBLOCK keeps a FIFO from hanging the open.
203
+ */
204
+ export async function appendToRegularFile(filePath, text, label, mode = DEFAULT_LOG_MODE) {
205
+ const target = path.resolve(filePath);
206
+ const flags = fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | noFollow | nonBlock;
207
+ let existing;
208
+ try {
209
+ existing = await lstat(target, { bigint: true });
210
+ if (existing.isSymbolicLink() || !existing.isFile())
211
+ throw new Error(`${label} must be a regular, non-symlink file`);
212
+ }
213
+ catch (error) {
214
+ if (error?.code !== 'ENOENT')
215
+ throw error;
216
+ }
217
+ const handle = await open(target, flags, mode);
218
+ try {
219
+ const opened = await handle.stat({ bigint: true });
220
+ if (!opened.isFile())
221
+ throw new Error(`${label} must be a regular file`);
222
+ if (existing && !sameFileIdentity(existing, opened))
223
+ throw new Error(`${label} changed while being opened`);
224
+ await handle.appendFile(text, 'utf8');
225
+ }
226
+ finally {
227
+ await handle.close();
228
+ }
229
+ }
package/dist/src/keys.js CHANGED
@@ -1,17 +1,27 @@
1
1
  import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync } from 'node:crypto';
2
- import { lstat } from 'node:fs/promises';
2
+ import { lstat, unlink } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { readRegularFile, writeNewFile } from "./fs-safe.js";
4
+ import { readRegularFile, realpathAllowingMissing, writeNewFile } from "./fs-safe.js";
5
+ import { SKILL_FILENAME } from "./tree-digest.js";
5
6
  export const KEY_ID_PATTERN = /^sha256:[0-9a-f]{64}$/u;
6
7
  const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
8
+ const MAX_SPKI_BASE64_LEN = 256;
9
+ const MAX_KEY_FILE_BYTES = 64 * 1024;
10
+ const PRIVATE_KEY_MODE = 0o600;
11
+ const PUBLIC_KEY_MODE = 0o644;
12
+ const GROUP_OTHER_PERMS = 0o077;
7
13
  export function keyIdFromSpkiDer(der) {
8
14
  return `sha256:${createHash('sha256').update(der).digest('hex')}`;
9
15
  }
10
- function describe(publicKey) {
16
+ function describePublicKey(publicKey) {
11
17
  if (publicKey.asymmetricKeyType !== 'ed25519')
12
18
  throw new Error('Key is not Ed25519');
13
19
  const der = publicKey.export({ format: 'der', type: 'spki' });
14
- return { keyId: keyIdFromSpkiDer(der), publicKey, spki: der.toString('base64') };
20
+ return {
21
+ keyId: keyIdFromSpkiDer(der),
22
+ publicKey,
23
+ spki: der.toString('base64'),
24
+ };
15
25
  }
16
26
  export function validateKeyId(value, label) {
17
27
  if (typeof value !== 'string' || !KEY_ID_PATTERN.test(value))
@@ -20,89 +30,125 @@ export function validateKeyId(value, label) {
20
30
  }
21
31
  /** Parses a canonical base64 Ed25519 SPKI and, if given, checks it hashes to `expectedKeyId`. */
22
32
  export function parseSpki(spki, label, expectedKeyId) {
23
- if (typeof spki !== 'string' || spki.length === 0 || spki.length > 256 || !BASE64_PATTERN.test(spki)) {
33
+ let publicKey;
34
+ if (expectedKeyId !== undefined)
35
+ validateKeyId(expectedKeyId, `${label} expectedKeyId`);
36
+ if (typeof spki !== 'string' ||
37
+ spki.length === 0 ||
38
+ spki.length > MAX_SPKI_BASE64_LEN ||
39
+ !BASE64_PATTERN.test(spki)) {
24
40
  throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
25
41
  }
26
42
  const der = Buffer.from(spki, 'base64');
27
43
  if (der.toString('base64') !== spki)
28
44
  throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
29
- let publicKey;
30
45
  try {
31
46
  publicKey = createPublicKey({ key: der, format: 'der', type: 'spki' });
32
47
  }
33
48
  catch {
34
49
  throw new Error(`${label} is not a valid public key`);
35
50
  }
36
- const info = describe(publicKey);
51
+ const info = describePublicKey(publicKey);
37
52
  if (info.spki !== spki)
38
53
  throw new Error(`${label} is not in canonical DER form`);
39
54
  if (expectedKeyId !== undefined && info.keyId !== expectedKeyId)
40
55
  throw new Error(`${label} does not match key id ${expectedKeyId}`);
41
56
  return info;
42
57
  }
43
- /** Private keys must never be written where a Skill (and so its certificate and hosts) could include them. */
44
- async function refuseInsideSkill(filePath) {
45
- let directory = path.dirname(filePath);
58
+ async function refuseInsideSkillAt(targetPath) {
59
+ let directory = path.dirname(targetPath);
46
60
  while (true) {
61
+ let hasSkillMd = false;
47
62
  try {
48
- await lstat(path.join(directory, 'SKILL.md'));
49
- throw new Error(`Refusing to write a private key inside a Skill directory (${directory}); keep keys outside every Skill tree`);
63
+ await lstat(path.join(directory, SKILL_FILENAME));
64
+ hasSkillMd = true;
50
65
  }
51
66
  catch (error) {
52
- if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR')
67
+ const code = error?.code;
68
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
53
69
  throw error;
54
70
  }
71
+ if (hasSkillMd) {
72
+ throw new Error(`Refusing to write a private key inside a Skill directory (${directory}); keep keys outside every Skill tree`);
73
+ }
55
74
  const parent = path.dirname(directory);
56
75
  if (parent === directory)
57
76
  return;
58
77
  directory = parent;
59
78
  }
60
79
  }
80
+ /** Private keys must never be written where a Skill (and so its certificate and hosts) could include them. */
81
+ async function refuseInsideSkill(filePath) {
82
+ const lexicalTarget = path.resolve(filePath);
83
+ const canonicalTarget = await realpathAllowingMissing(lexicalTarget);
84
+ await refuseInsideSkillAt(lexicalTarget);
85
+ if (canonicalTarget !== lexicalTarget)
86
+ await refuseInsideSkillAt(canonicalTarget);
87
+ }
61
88
  export async function generateKeyPair(privatePath, publicPath) {
62
89
  const privateTarget = path.resolve(privatePath);
63
90
  const publicTarget = path.resolve(publicPath);
64
- if (privateTarget === publicTarget)
91
+ const canonicalPrivate = await realpathAllowingMissing(privateTarget);
92
+ const canonicalPublic = await realpathAllowingMissing(publicTarget);
93
+ if (privateTarget === publicTarget || canonicalPrivate === canonicalPublic)
65
94
  throw new Error('Private and public key paths must differ');
66
95
  await refuseInsideSkill(privateTarget);
67
96
  const pair = generateKeyPairSync('ed25519');
68
- const privatePem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' });
69
- const publicPem = pair.publicKey.export({ type: 'spki', format: 'pem' });
70
- await writeNewFile(privateTarget, Buffer.from(privatePem), 0o600);
97
+ const privatePem = Buffer.from(pair.privateKey.export({ type: 'pkcs8', format: 'pem' }));
98
+ const publicPem = Buffer.from(pair.publicKey.export({ type: 'spki', format: 'pem' }));
71
99
  try {
72
- await writeNewFile(publicTarget, Buffer.from(publicPem), 0o644);
100
+ await writeNewFile(privateTarget, privatePem, PRIVATE_KEY_MODE);
101
+ try {
102
+ await writeNewFile(publicTarget, publicPem, PUBLIC_KEY_MODE);
103
+ }
104
+ catch (error) {
105
+ await unlink(privateTarget).catch(() => { });
106
+ throw error;
107
+ }
73
108
  }
74
- catch (error) {
75
- const { unlink } = await import('node:fs/promises');
76
- await unlink(privateTarget).catch(() => { });
77
- throw error;
109
+ finally {
110
+ privatePem.fill(0);
78
111
  }
79
- return { ...describe(pair.publicKey), privatePath: privateTarget, publicPath: publicTarget };
112
+ return {
113
+ ...describePublicKey(pair.publicKey),
114
+ privatePath: privateTarget,
115
+ publicPath: publicTarget,
116
+ };
80
117
  }
81
118
  export async function loadPrivateKey(filePath) {
82
119
  const entry = await lstat(filePath);
83
- if (process.platform !== 'win32' && (entry.mode & 0o077) !== 0) {
120
+ if (entry.isSymbolicLink() || !entry.isFile())
121
+ throw new Error('Private key must be a regular, non-symlink file');
122
+ if (process.platform !== 'win32' && (entry.mode & GROUP_OTHER_PERMS) !== 0)
84
123
  throw new Error('Private key permissions must deny group and other access (chmod 600)');
85
- }
86
- const pem = await readRegularFile(filePath, 'Private key', 64 * 1024);
124
+ const pem = await readRegularFile(filePath, 'Private key', MAX_KEY_FILE_BYTES);
87
125
  let privateKey;
88
126
  try {
89
- privateKey = createPrivateKey(pem);
127
+ try {
128
+ privateKey = createPrivateKey({ key: pem, format: 'pem', type: 'pkcs8' });
129
+ }
130
+ catch {
131
+ throw new Error('Private key is not a valid PKCS#8 key');
132
+ }
133
+ if (privateKey.asymmetricKeyType !== 'ed25519')
134
+ throw new Error('Private key is not Ed25519');
135
+ return {
136
+ ...describePublicKey(createPublicKey(privateKey)),
137
+ privateKey,
138
+ };
90
139
  }
91
- catch {
92
- throw new Error('Private key is not a valid PKCS#8 key');
140
+ finally {
141
+ pem.fill(0);
93
142
  }
94
- if (privateKey.asymmetricKeyType !== 'ed25519')
95
- throw new Error('Private key is not Ed25519');
96
- return { ...describe(createPublicKey(privateKey)), privateKey };
97
143
  }
98
144
  export async function loadPublicKey(filePath) {
99
- const pem = await readRegularFile(filePath, 'Public key', 64 * 1024);
145
+ const pem = await readRegularFile(filePath, 'Public key', MAX_KEY_FILE_BYTES);
100
146
  let publicKey;
101
147
  try {
102
- publicKey = createPublicKey(pem);
148
+ publicKey = createPublicKey({ key: pem, format: 'pem', type: 'spki' });
103
149
  }
104
150
  catch {
105
151
  throw new Error('Public key is not a valid SPKI PEM key');
106
152
  }
107
- return describe(publicKey);
153
+ return describePublicKey(publicKey);
108
154
  }
@@ -7,9 +7,9 @@ import { fileURLToPath } from 'node:url';
7
7
  */
8
8
  export function isMainModule(moduleUrl) {
9
9
  const entry = process.argv[1];
10
+ const self = fileURLToPath(moduleUrl);
10
11
  if (!entry)
11
12
  return false;
12
- const self = fileURLToPath(moduleUrl);
13
13
  try {
14
14
  return realpathSync(entry) === realpathSync(self);
15
15
  }
package/dist/src/names.js CHANGED
@@ -2,16 +2,14 @@ const SKILL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
2
2
  const SCOPE_PATTERN = /^(?:\*|[A-Za-z0-9][A-Za-z0-9._-]{0,127}\*?)$/u;
3
3
  const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/u;
4
4
  export function validateSkillName(value, label = 'Skill name') {
5
- if (typeof value !== 'string' || !SKILL_NAME_PATTERN.test(value)) {
5
+ if (typeof value !== 'string' || !SKILL_NAME_PATTERN.test(value))
6
6
  throw new Error(`${label} must be 1-128 ASCII letters, digits, dot, underscore or hyphen, starting with a letter or digit`);
7
- }
8
7
  return value;
9
8
  }
10
9
  /** Scopes: "*" (every Skill), "prefix*" (names starting with prefix), or an exact Skill name. */
11
10
  export function validateScope(value, label = 'scope') {
12
- if (typeof value !== 'string' || !SCOPE_PATTERN.test(value)) {
11
+ if (typeof value !== 'string' || !SCOPE_PATTERN.test(value))
13
12
  throw new Error(`${label} must be "*", an exact Skill name, or a name prefix ending in "*"`);
14
- }
15
13
  return value;
16
14
  }
17
15
  export function scopeMatches(scope, skillName) {
@@ -1,8 +1,11 @@
1
1
  import { type CertificateSource, type TrustContext, type TrustContextResult, type VerificationResult } from './verify.ts';
2
2
  export declare const POLICY_VERSION = "mago.policy/v1";
3
3
  export declare const STATE_TYPE = "mago.host-state/v1";
4
- export declare const DEFAULT_POLICY_PATH: string;
4
+ /** Per-Skill budget across all certificate candidates (explicit file, policy directories, in-Skill file). */
5
+ export declare const MAX_CERTIFICATE_CANDIDATES = 64;
6
+ export declare const MAX_CERTIFICATE_TOTAL_BYTES: number;
5
7
  export type Mode = 'shadow' | 'enforce';
8
+ export declare function defaultPolicyPath(env?: NodeJS.ProcessEnv, home?: string): string;
6
9
  export interface Policy {
7
10
  path: string;
8
11
  mode: Mode;
@@ -16,9 +19,16 @@ export interface Policy {
16
19
  }
17
20
  /** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
18
21
  export declare function loadPolicy(policyPath: string): Promise<Policy>;
19
- /** Loads trust documents for a policy, enforcing rollback protection through the state file. */
20
- export declare function loadPolicyTrust(policy: Policy, now: Date): Promise<TrustContextResult>;
21
- /** Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate. */
22
+ /**
23
+ * Loads trust documents for a policy, enforcing rollback protection through the state file.
24
+ * With `recordVersions: false` the state file is still read (the same rollback minimums apply) but never written:
25
+ * for observers such as the GUI, which must not move a host's rollback memory.
26
+ */
27
+ export declare function loadPolicyTrust(policy: Policy, now: Date, options?: {
28
+ recordVersions?: boolean;
29
+ }): Promise<TrustContextResult>;
30
+ export declare function iterateCertificates(skillName: string, skillRoot: string, certificateDirs: string[], explicit?: string): AsyncGenerator<CertificateSource>;
31
+ /** Collects every candidate (within the same budget). Prefer `iterateCertificates`, which retains nothing. */
22
32
  export declare function discoverCertificates(skillName: string, skillRoot: string, certificateDirs: string[], explicit?: string): Promise<CertificateSource[]>;
23
33
  /**
24
34
  * Finds Skill directories (directories containing SKILL.md) under the given roots.
@@ -26,12 +36,24 @@ export declare function discoverCertificates(skillName: string, skillRoot: strin
26
36
  * directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
27
37
  */
28
38
  export declare const MAX_DISCOVERY_DEPTH = 16;
39
+ /** Work budget for one discovery run over untrusted trees; exceeding either throws DiscoveryBudgetError. */
40
+ export declare const MAX_DISCOVERED_SKILLS = 1000;
41
+ export declare const MAX_DISCOVERY_ENTRIES = 50000;
42
+ export interface DiscoveryLimits {
43
+ /** Maximum Skills (including directories reported as too deep) found. */
44
+ maxSkills?: number;
45
+ /** Maximum directory entries visited across all roots. */
46
+ maxEntries?: number;
47
+ }
48
+ /** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
49
+ export declare class DiscoveryBudgetError extends Error {
50
+ constructor(message: string);
51
+ }
29
52
  export interface SkillDiscovery {
30
53
  skillDirs: string[];
31
- /** Directories at the depth limit that have subdirectories; Skills below them were not searched. */
32
54
  tooDeep: string[];
33
55
  }
34
- export declare function findSkillDirs(roots: string[], maxDepth?: number): Promise<SkillDiscovery>;
56
+ export declare function findSkillDirs(roots: string[], maxDepth?: number, limits?: DiscoveryLimits): Promise<SkillDiscovery>;
35
57
  /** Result for a directory discovery could not search; it fails in enforce mode and is reported in shadow mode. */
36
58
  export declare function tooDeepResult(directory: string, now: Date): VerificationResult;
37
59
  export interface DecisionRecord {