@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,27 @@
|
|
|
1
|
+
export declare function isInside(root: string, candidate: string): boolean;
|
|
2
|
+
/**
|
|
3
|
+
* Reads a regular, non-symlink file, failing if it changes while being read.
|
|
4
|
+
* The type and size are checked before any content is read, and at most `maxBytes` (+1 to detect growth) are read.
|
|
5
|
+
*/
|
|
6
|
+
export declare function readRegularFile(filePath: string, label: string, maxBytes?: number): Promise<Buffer>;
|
|
7
|
+
/** Resolves a file path and requires it to be outside `root` (both canonicalized). */
|
|
8
|
+
export declare function resolveOutside(filePath: string, root: string, label: string, { allowMissing }?: {
|
|
9
|
+
allowMissing?: boolean | undefined;
|
|
10
|
+
}): Promise<string>;
|
|
11
|
+
/** Creates a new file; refuses to overwrite anything that already exists. */
|
|
12
|
+
export declare function writeNewFile(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
|
|
13
|
+
/** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
|
|
14
|
+
export declare function writeFileAtomic(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
|
|
15
|
+
/** Canonical path of `target`, resolving symlinks on the longest existing prefix. A dangling link on the way is an error. */
|
|
16
|
+
export declare function realpathAllowingMissing(target: string): Promise<string>;
|
|
17
|
+
/**
|
|
18
|
+
* Resolves a policy-supplied path against `base` and requires it to name something strictly inside `base`,
|
|
19
|
+
* after symlinks in its parent directories are resolved. An existing final component must be a regular,
|
|
20
|
+
* non-symlink file. Returns the canonical path.
|
|
21
|
+
*/
|
|
22
|
+
export declare function resolveInsideDirectory(base: string, item: string, label: string): Promise<string>;
|
|
23
|
+
/**
|
|
24
|
+
* Appends text to a log file, creating it (mode 600) if needed. Refuses symbolic links and anything that is not
|
|
25
|
+
* a regular file; O_NONBLOCK keeps a FIFO from hanging the open.
|
|
26
|
+
*/
|
|
27
|
+
export declare function appendToRegularFile(filePath: string, text: string, label: string, mode?: number): Promise<void>;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { constants as fsConstants } from 'node:fs';
|
|
3
|
+
import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
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
|
+
}
|
|
22
|
+
export function isInside(root, candidate) {
|
|
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)));
|
|
28
|
+
}
|
|
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()) {
|
|
40
|
+
throw new Error(`${label} must be a regular, non-symlink file`);
|
|
41
|
+
}
|
|
42
|
+
if (entry.size > maxLimit) {
|
|
43
|
+
throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
|
|
44
|
+
}
|
|
45
|
+
let handle;
|
|
46
|
+
try {
|
|
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))
|
|
50
|
+
throw new Error(`${label} changed while being read`);
|
|
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));
|
|
63
|
+
}
|
|
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);
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await handle?.close();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Resolves a file path and requires it to be outside `root` (both canonicalized). */
|
|
74
|
+
export async function resolveOutside(filePath, root, label, { allowMissing = false } = {}) {
|
|
75
|
+
const canonicalRoot = await realpath(path.resolve(root));
|
|
76
|
+
const requested = path.resolve(filePath);
|
|
77
|
+
let canonical;
|
|
78
|
+
try {
|
|
79
|
+
const entry = await lstat(requested);
|
|
80
|
+
if (entry.isSymbolicLink())
|
|
81
|
+
throw new Error(`${label} must not be a symbolic link`);
|
|
82
|
+
if (!entry.isFile())
|
|
83
|
+
throw new Error(`${label} must be a regular file`);
|
|
84
|
+
canonical = await realpath(requested);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
const code = error?.code;
|
|
88
|
+
if (!allowMissing || code !== 'ENOENT')
|
|
89
|
+
throw error;
|
|
90
|
+
canonical = path.join(await realpathAllowingMissing(path.dirname(requested)), path.basename(requested));
|
|
91
|
+
}
|
|
92
|
+
if (isInside(canonicalRoot, canonical)) {
|
|
93
|
+
throw new Error(`${label} must be outside ${canonicalRoot}`);
|
|
94
|
+
}
|
|
95
|
+
return canonical;
|
|
96
|
+
}
|
|
97
|
+
async function writeHandle(filePath, bytes, mode, flags) {
|
|
98
|
+
const handle = await open(filePath, flags, mode);
|
|
99
|
+
let succeeded = false;
|
|
100
|
+
try {
|
|
101
|
+
await handle.writeFile(bytes);
|
|
102
|
+
await handle.sync();
|
|
103
|
+
succeeded = true;
|
|
104
|
+
}
|
|
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(() => { });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Creates a new file; refuses to overwrite anything that already exists. */
|
|
117
|
+
export async function writeNewFile(filePath, bytes, mode = DEFAULT_FILE_MODE) {
|
|
118
|
+
const target = path.resolve(filePath);
|
|
119
|
+
const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow;
|
|
120
|
+
await writeHandle(target, bytes, mode, flags);
|
|
121
|
+
return target;
|
|
122
|
+
}
|
|
123
|
+
/** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
|
|
124
|
+
export async function writeFileAtomic(filePath, bytes, mode = DEFAULT_FILE_MODE) {
|
|
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;
|
|
129
|
+
try {
|
|
130
|
+
const existing = await lstat(target);
|
|
131
|
+
if (existing.isSymbolicLink() || !existing.isFile())
|
|
132
|
+
throw new Error(`Refusing to replace non-regular file ${target}`);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (error?.code !== 'ENOENT')
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
await writeHandle(temporary, bytes, mode, flags);
|
|
139
|
+
try {
|
|
140
|
+
await rename(temporary, target);
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
await unlink(temporary).catch(() => { });
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
return target;
|
|
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
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export * from './canonical-json.ts';
|
|
2
|
+
export * from './tree-digest.ts';
|
|
3
|
+
export * from './keys.ts';
|
|
4
|
+
export * from './dsse.ts';
|
|
5
|
+
export * from './time.ts';
|
|
6
|
+
export * from './names.ts';
|
|
7
|
+
export * from './trust-root.ts';
|
|
8
|
+
export * from './revocations.ts';
|
|
9
|
+
export * from './certificate.ts';
|
|
10
|
+
export * from './verify.ts';
|
|
11
|
+
export * from './policy.ts';
|
|
12
|
+
export * from './admin.ts';
|
|
13
|
+
export * from './diff.ts';
|
|
14
|
+
export { runCli } from './cli.ts';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export * from "./canonical-json.js";
|
|
2
|
+
export * from "./tree-digest.js";
|
|
3
|
+
export * from "./keys.js";
|
|
4
|
+
export * from "./dsse.js";
|
|
5
|
+
export * from "./time.js";
|
|
6
|
+
export * from "./names.js";
|
|
7
|
+
export * from "./trust-root.js";
|
|
8
|
+
export * from "./revocations.js";
|
|
9
|
+
export * from "./certificate.js";
|
|
10
|
+
export * from "./verify.js";
|
|
11
|
+
export * from "./policy.js";
|
|
12
|
+
export * from "./admin.js";
|
|
13
|
+
export * from "./diff.js";
|
|
14
|
+
export { runCli } from "./cli.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
export declare const KEY_ID_PATTERN: RegExp;
|
|
3
|
+
export interface PublicKeyInfo {
|
|
4
|
+
keyId: string;
|
|
5
|
+
publicKey: KeyObject;
|
|
6
|
+
/** Canonical base64 of the DER SubjectPublicKeyInfo. */
|
|
7
|
+
spki: string;
|
|
8
|
+
}
|
|
9
|
+
export interface PrivateKeyInfo extends PublicKeyInfo {
|
|
10
|
+
privateKey: KeyObject;
|
|
11
|
+
}
|
|
12
|
+
export declare function keyIdFromSpkiDer(der: Uint8Array): string;
|
|
13
|
+
export declare function validateKeyId(value: unknown, label: string): string;
|
|
14
|
+
/** Parses a canonical base64 Ed25519 SPKI and, if given, checks it hashes to `expectedKeyId`. */
|
|
15
|
+
export declare function parseSpki(spki: unknown, label: string, expectedKeyId?: string): PublicKeyInfo;
|
|
16
|
+
export declare function generateKeyPair(privatePath: string, publicPath: string): Promise<PublicKeyInfo & {
|
|
17
|
+
privatePath: string;
|
|
18
|
+
publicPath: string;
|
|
19
|
+
}>;
|
|
20
|
+
export declare function loadPrivateKey(filePath: string): Promise<PrivateKeyInfo>;
|
|
21
|
+
export declare function loadPublicKey(filePath: string): Promise<PublicKeyInfo>;
|
package/dist/src/keys.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync } from 'node:crypto';
|
|
2
|
+
import { lstat, unlink } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { readRegularFile, realpathAllowingMissing, writeNewFile } from "./fs-safe.js";
|
|
5
|
+
import { SKILL_FILENAME } from "./tree-digest.js";
|
|
6
|
+
export const KEY_ID_PATTERN = /^sha256:[0-9a-f]{64}$/u;
|
|
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;
|
|
13
|
+
export function keyIdFromSpkiDer(der) {
|
|
14
|
+
return `sha256:${createHash('sha256').update(der).digest('hex')}`;
|
|
15
|
+
}
|
|
16
|
+
function describePublicKey(publicKey) {
|
|
17
|
+
if (publicKey.asymmetricKeyType !== 'ed25519')
|
|
18
|
+
throw new Error('Key is not Ed25519');
|
|
19
|
+
const der = publicKey.export({ format: 'der', type: 'spki' });
|
|
20
|
+
return {
|
|
21
|
+
keyId: keyIdFromSpkiDer(der),
|
|
22
|
+
publicKey,
|
|
23
|
+
spki: der.toString('base64'),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function validateKeyId(value, label) {
|
|
27
|
+
if (typeof value !== 'string' || !KEY_ID_PATTERN.test(value))
|
|
28
|
+
throw new Error(`${label} must be a sha256:<64 hex> key identifier`);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
/** Parses a canonical base64 Ed25519 SPKI and, if given, checks it hashes to `expectedKeyId`. */
|
|
32
|
+
export function parseSpki(spki, label, expectedKeyId) {
|
|
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)) {
|
|
40
|
+
throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
|
|
41
|
+
}
|
|
42
|
+
const der = Buffer.from(spki, 'base64');
|
|
43
|
+
if (der.toString('base64') !== spki)
|
|
44
|
+
throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
|
|
45
|
+
try {
|
|
46
|
+
publicKey = createPublicKey({ key: der, format: 'der', type: 'spki' });
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new Error(`${label} is not a valid public key`);
|
|
50
|
+
}
|
|
51
|
+
const info = describePublicKey(publicKey);
|
|
52
|
+
if (info.spki !== spki)
|
|
53
|
+
throw new Error(`${label} is not in canonical DER form`);
|
|
54
|
+
if (expectedKeyId !== undefined && info.keyId !== expectedKeyId)
|
|
55
|
+
throw new Error(`${label} does not match key id ${expectedKeyId}`);
|
|
56
|
+
return info;
|
|
57
|
+
}
|
|
58
|
+
async function refuseInsideSkillAt(targetPath) {
|
|
59
|
+
let directory = path.dirname(targetPath);
|
|
60
|
+
while (true) {
|
|
61
|
+
let hasSkillMd = false;
|
|
62
|
+
try {
|
|
63
|
+
await lstat(path.join(directory, SKILL_FILENAME));
|
|
64
|
+
hasSkillMd = true;
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
const code = error?.code;
|
|
68
|
+
if (code !== 'ENOENT' && code !== 'ENOTDIR')
|
|
69
|
+
throw error;
|
|
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
|
+
}
|
|
74
|
+
const parent = path.dirname(directory);
|
|
75
|
+
if (parent === directory)
|
|
76
|
+
return;
|
|
77
|
+
directory = parent;
|
|
78
|
+
}
|
|
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
|
+
}
|
|
88
|
+
export async function generateKeyPair(privatePath, publicPath) {
|
|
89
|
+
const privateTarget = path.resolve(privatePath);
|
|
90
|
+
const publicTarget = path.resolve(publicPath);
|
|
91
|
+
const canonicalPrivate = await realpathAllowingMissing(privateTarget);
|
|
92
|
+
const canonicalPublic = await realpathAllowingMissing(publicTarget);
|
|
93
|
+
if (privateTarget === publicTarget || canonicalPrivate === canonicalPublic)
|
|
94
|
+
throw new Error('Private and public key paths must differ');
|
|
95
|
+
await refuseInsideSkill(privateTarget);
|
|
96
|
+
const pair = generateKeyPairSync('ed25519');
|
|
97
|
+
const privatePem = Buffer.from(pair.privateKey.export({ type: 'pkcs8', format: 'pem' }));
|
|
98
|
+
const publicPem = Buffer.from(pair.publicKey.export({ type: 'spki', format: 'pem' }));
|
|
99
|
+
try {
|
|
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
|
+
}
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
privatePem.fill(0);
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
...describePublicKey(pair.publicKey),
|
|
114
|
+
privatePath: privateTarget,
|
|
115
|
+
publicPath: publicTarget,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export async function loadPrivateKey(filePath) {
|
|
119
|
+
const entry = await lstat(filePath);
|
|
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)
|
|
123
|
+
throw new Error('Private key permissions must deny group and other access (chmod 600)');
|
|
124
|
+
const pem = await readRegularFile(filePath, 'Private key', MAX_KEY_FILE_BYTES);
|
|
125
|
+
let privateKey;
|
|
126
|
+
try {
|
|
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
|
+
};
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
pem.fill(0);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export async function loadPublicKey(filePath) {
|
|
145
|
+
const pem = await readRegularFile(filePath, 'Public key', MAX_KEY_FILE_BYTES);
|
|
146
|
+
let publicKey;
|
|
147
|
+
try {
|
|
148
|
+
publicKey = createPublicKey({ key: pem, format: 'pem', type: 'spki' });
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
throw new Error('Public key is not a valid SPKI PEM key');
|
|
152
|
+
}
|
|
153
|
+
return describePublicKey(publicKey);
|
|
154
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True when this module is the script Node was asked to run. Paths are compared after resolving
|
|
3
|
+
* symlinks, because npm installs commands as links (node_modules/.bin/mago-ski -> dist/src/cli.js).
|
|
4
|
+
*/
|
|
5
|
+
export declare function isMainModule(moduleUrl: string): boolean;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/**
|
|
5
|
+
* True when this module is the script Node was asked to run. Paths are compared after resolving
|
|
6
|
+
* symlinks, because npm installs commands as links (node_modules/.bin/mago-ski -> dist/src/cli.js).
|
|
7
|
+
*/
|
|
8
|
+
export function isMainModule(moduleUrl) {
|
|
9
|
+
const entry = process.argv[1];
|
|
10
|
+
const self = fileURLToPath(moduleUrl);
|
|
11
|
+
if (!entry)
|
|
12
|
+
return false;
|
|
13
|
+
try {
|
|
14
|
+
return realpathSync(entry) === realpathSync(self);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return path.resolve(entry) === self;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function validateSkillName(value: unknown, label?: string): string;
|
|
2
|
+
/** Scopes: "*" (every Skill), "prefix*" (names starting with prefix), or an exact Skill name. */
|
|
3
|
+
export declare function validateScope(value: unknown, label?: string): string;
|
|
4
|
+
export declare function scopeMatches(scope: string, skillName: string): boolean;
|
|
5
|
+
export declare function validateDigest(value: unknown, label?: string): string;
|
|
6
|
+
/** Reads the `name` field from SKILL.md frontmatter, if present. */
|
|
7
|
+
export declare function skillNameFromFrontmatter(text: string): string | undefined;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const SKILL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
2
|
+
const SCOPE_PATTERN = /^(?:\*|[A-Za-z0-9][A-Za-z0-9._-]{0,127}\*?)$/u;
|
|
3
|
+
const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/u;
|
|
4
|
+
export function validateSkillName(value, label = 'Skill name') {
|
|
5
|
+
if (typeof value !== 'string' || !SKILL_NAME_PATTERN.test(value))
|
|
6
|
+
throw new Error(`${label} must be 1-128 ASCII letters, digits, dot, underscore or hyphen, starting with a letter or digit`);
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
/** Scopes: "*" (every Skill), "prefix*" (names starting with prefix), or an exact Skill name. */
|
|
10
|
+
export function validateScope(value, label = 'scope') {
|
|
11
|
+
if (typeof value !== 'string' || !SCOPE_PATTERN.test(value))
|
|
12
|
+
throw new Error(`${label} must be "*", an exact Skill name, or a name prefix ending in "*"`);
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
export function scopeMatches(scope, skillName) {
|
|
16
|
+
if (scope === '*')
|
|
17
|
+
return true;
|
|
18
|
+
if (scope.endsWith('*'))
|
|
19
|
+
return skillName.startsWith(scope.slice(0, -1));
|
|
20
|
+
return scope === skillName;
|
|
21
|
+
}
|
|
22
|
+
export function validateDigest(value, label = 'digest') {
|
|
23
|
+
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value))
|
|
24
|
+
throw new Error(`${label} must be sha256:<64 lowercase hex>`);
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
/** Reads the `name` field from SKILL.md frontmatter, if present. */
|
|
28
|
+
export function skillNameFromFrontmatter(text) {
|
|
29
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(text);
|
|
30
|
+
if (!match)
|
|
31
|
+
return undefined;
|
|
32
|
+
for (const line of match[1].split(/\r?\n/u)) {
|
|
33
|
+
const field = /^name:\s*(?:"([^"]*)"|'([^']*)'|(\S+))\s*$/u.exec(line);
|
|
34
|
+
if (field)
|
|
35
|
+
return field[1] ?? field[2] ?? field[3];
|
|
36
|
+
}
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type CertificateSource, type TrustContext, type TrustContextResult, type VerificationResult } from './verify.ts';
|
|
2
|
+
export declare const POLICY_VERSION = "mago.policy/v1";
|
|
3
|
+
export declare const STATE_TYPE = "mago.host-state/v1";
|
|
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;
|
|
7
|
+
export type Mode = 'shadow' | 'enforce';
|
|
8
|
+
export declare function defaultPolicyPath(env?: NodeJS.ProcessEnv, home?: string): string;
|
|
9
|
+
export interface Policy {
|
|
10
|
+
path: string;
|
|
11
|
+
mode: Mode;
|
|
12
|
+
rootKeyId: string;
|
|
13
|
+
trustRootPath: string;
|
|
14
|
+
revocationsPath: string;
|
|
15
|
+
certificateDirs: string[];
|
|
16
|
+
skillDirs: string[];
|
|
17
|
+
statePath: string | null;
|
|
18
|
+
decisionLogPath: string | null;
|
|
19
|
+
}
|
|
20
|
+
/** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
|
|
21
|
+
export declare function loadPolicy(policyPath: string): Promise<Policy>;
|
|
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. */
|
|
32
|
+
export declare function discoverCertificates(skillName: string, skillRoot: string, certificateDirs: string[], explicit?: string): Promise<CertificateSource[]>;
|
|
33
|
+
/**
|
|
34
|
+
* Finds Skill directories (directories containing SKILL.md) under the given roots.
|
|
35
|
+
* Symbolic links are never skipped silently: hosts such as Pi follow them, so a linked Skill
|
|
36
|
+
* directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
|
|
37
|
+
*/
|
|
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
|
+
}
|
|
52
|
+
export interface SkillDiscovery {
|
|
53
|
+
skillDirs: string[];
|
|
54
|
+
tooDeep: string[];
|
|
55
|
+
}
|
|
56
|
+
export declare function findSkillDirs(roots: string[], maxDepth?: number, limits?: DiscoveryLimits): Promise<SkillDiscovery>;
|
|
57
|
+
/** Result for a directory discovery could not search; it fails in enforce mode and is reported in shadow mode. */
|
|
58
|
+
export declare function tooDeepResult(directory: string, now: Date): VerificationResult;
|
|
59
|
+
export interface DecisionRecord {
|
|
60
|
+
timestamp: string;
|
|
61
|
+
host: string;
|
|
62
|
+
mode: Mode;
|
|
63
|
+
action: 'allow' | 'block' | 'would-block';
|
|
64
|
+
event: string;
|
|
65
|
+
skill: string;
|
|
66
|
+
skill_dir: string;
|
|
67
|
+
digest: string | null;
|
|
68
|
+
certificate_id: string | null;
|
|
69
|
+
verdict: string;
|
|
70
|
+
reason: string;
|
|
71
|
+
}
|
|
72
|
+
export declare function actionFor(mode: Mode, verified: boolean): DecisionRecord['action'];
|
|
73
|
+
export declare function appendDecision(logPath: string | null, record: DecisionRecord): Promise<void>;
|
|
74
|
+
export declare function decisionRecord(result: VerificationResult, mode: Mode, event: string, host?: string): DecisionRecord;
|
|
75
|
+
/** Verifies one Skill under a policy, including trust loading. */
|
|
76
|
+
export declare function verifyWithPolicy(policy: Policy, skillDir: string, options: {
|
|
77
|
+
now: Date;
|
|
78
|
+
skillName?: string;
|
|
79
|
+
certificate?: string;
|
|
80
|
+
context?: TrustContext;
|
|
81
|
+
}): Promise<VerificationResult>;
|