@mago-foundation/mago-ski 0.1.0 → 0.3.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.
Files changed (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
@@ -1,5 +1,12 @@
1
+ import type { KeyObject } from 'node:crypto';
2
+ import { type PrivateKeyInfo, type PublicKeyInfo } from './keys.ts';
3
+ import type { ForbiddenKey } from './policy.ts';
4
+ import { type Revocations } from './revocations.ts';
5
+ import { type TrustRoot } from './trust-root.ts';
1
6
  export declare const DEFAULT_TRUST_ROOT_EXPIRY = "365d";
2
7
  export declare const DEFAULT_REVOCATIONS_EXPIRY = "30d";
8
+ /** True if the bytes contain recognizable private-key material. */
9
+ export declare function containsPrivateKey(content: Uint8Array): boolean;
3
10
  export declare function initRoot(options: {
4
11
  rootKeyPath: string;
5
12
  trustRootOut: string;
@@ -12,6 +19,65 @@ export declare function initRoot(options: {
12
19
  trustRoot: string;
13
20
  revocations: string;
14
21
  }>;
22
+ /** A document was older than the lowest version this computer's memory allows. The GUI maps it by class. */
23
+ export declare class StaleDocumentError extends Error {
24
+ constructor(label: string, version: number, minimum: number);
25
+ }
26
+ /** A document changed between prepare and commit. The GUI maps it, and `FileChangedError`, by class. */
27
+ export declare class DocumentChangedError extends Error {
28
+ constructor(label: string);
29
+ }
30
+ export type TrustRootChange = {
31
+ kind: 'add';
32
+ publicKey: PublicKeyInfo;
33
+ name: string;
34
+ scopes: string[];
35
+ expires: string;
36
+ trustRootExpires?: string;
37
+ } | {
38
+ kind: 'remove';
39
+ keyId: string;
40
+ trustRootExpires?: string;
41
+ } | {
42
+ kind: 'renew';
43
+ trustRootExpires: string;
44
+ };
45
+ export interface PreparedTrustRoot {
46
+ kind: 'trust-root';
47
+ /** The trust root read. */
48
+ source: string;
49
+ /** Where commit writes: `out` or the source. */
50
+ target: string;
51
+ /** `sha256:<hex>` of `source` as read. */
52
+ baseSha256: string;
53
+ /** When `target` differs from `source`: its `sha256:<hex>` at prepare, or null when absent. */
54
+ targetBase: string | null;
55
+ rootKeyId: string;
56
+ current: TrustRoot;
57
+ /** Exactly what commit signs. */
58
+ payload: TrustRoot;
59
+ change: TrustRootChange;
60
+ replaces: TrustRoot['approvers'][number] | null;
61
+ }
62
+ /** Reads the trust root once, applies the change and returns the unsigned result. Never signs or writes. */
63
+ export declare function prepareTrustRootChange(o: {
64
+ rootKeyId: string;
65
+ trustRootPath: string;
66
+ out?: string | undefined;
67
+ now: Date;
68
+ change: TrustRootChange;
69
+ forbidden?: ForbiddenKey[] | undefined;
70
+ minimumVersion?: number | undefined;
71
+ }): Promise<PreparedTrustRoot>;
72
+ /** Pure: signs `p.payload` and nothing else. The preview and commit use this one code path. */
73
+ export declare function signPreparedTrustRoot(p: PreparedTrustRoot, key: PrivateKeyInfo): Buffer;
74
+ export declare function commitTrustRoot(p: PreparedTrustRoot, rootKey: PrivateKeyInfo, o?: {
75
+ beforeWrite?: () => void | Promise<void>;
76
+ }): Promise<{
77
+ version: number;
78
+ path: string;
79
+ sha256: string;
80
+ }>;
15
81
  export declare function addApprover(options: {
16
82
  rootKeyPath: string;
17
83
  trustRootPath: string;
@@ -22,6 +88,8 @@ export declare function addApprover(options: {
22
88
  name: string;
23
89
  scopes: string[];
24
90
  expires: string;
91
+ /** Keys that must not be approvers (see `forbiddenApproverKeys`); the CLI passes them with `--policy`. */
92
+ forbidden?: ForbiddenKey[];
25
93
  }): Promise<{
26
94
  version: number;
27
95
  path: string;
@@ -38,6 +106,64 @@ export declare function removeApprover(options: {
38
106
  version: number;
39
107
  path: string;
40
108
  }>;
109
+ /** Re-signs the trust root with a new expiry and the same approvers. */
110
+ export declare function renewTrustRoot(options: {
111
+ rootKeyPath: string;
112
+ trustRootPath: string;
113
+ out?: string;
114
+ now: Date;
115
+ expires: string;
116
+ }): Promise<{
117
+ version: number;
118
+ path: string;
119
+ expiresAt: Date;
120
+ }>;
121
+ export type RevocationChange = {
122
+ kind: 'key';
123
+ keyId: string;
124
+ reason: string;
125
+ } | {
126
+ kind: 'digest';
127
+ digest: string;
128
+ reason: string;
129
+ } | {
130
+ kind: 'both';
131
+ keyId: string;
132
+ digest: string;
133
+ reason: string;
134
+ } | {
135
+ kind: 'refresh';
136
+ };
137
+ export interface PreparedRevocations {
138
+ kind: 'revocations';
139
+ source: string;
140
+ target: string;
141
+ baseSha256: string;
142
+ targetBase: string | null;
143
+ rootKeyId: string;
144
+ current: Revocations;
145
+ payload: Revocations;
146
+ change: RevocationChange;
147
+ }
148
+ export declare function prepareRevocationsChange(o: {
149
+ rootKeyId: string;
150
+ rootPublicKey: KeyObject;
151
+ revocationsPath: string;
152
+ out?: string | undefined;
153
+ now: Date;
154
+ expires: string;
155
+ change: RevocationChange;
156
+ minimumVersion?: number | undefined;
157
+ }): Promise<PreparedRevocations>;
158
+ export declare function signPreparedRevocations(p: PreparedRevocations, key: PrivateKeyInfo): Buffer;
159
+ export declare function commitRevocations(p: PreparedRevocations, rootKey: PrivateKeyInfo, o?: {
160
+ beforeWrite?: () => void | Promise<void>;
161
+ }): Promise<{
162
+ version: number;
163
+ path: string;
164
+ sha256: string;
165
+ expiresAt: Date;
166
+ }>;
41
167
  export declare function updateRevocations(options: {
42
168
  rootKeyPath: string;
43
169
  revocationsPath: string;
@@ -54,13 +180,26 @@ export declare function updateRevocations(options: {
54
180
  }>;
55
181
  export declare function approveSkill(options: {
56
182
  skillDir: string;
57
- approverKeyPath: string;
183
+ /** The approver's private key file; or pass `approverKey`, already loaded (exactly one of the two). */
184
+ approverKeyPath?: string;
185
+ approverKey?: PrivateKeyInfo;
58
186
  now: Date;
59
187
  expires: string;
60
188
  reason: string;
61
189
  name?: string;
62
190
  previous?: string;
63
191
  out?: string;
192
+ /** The digest the approver reviewed; issuance is refused if the bytes on disk differ. */
193
+ expectDigest?: string;
194
+ /** The Skill name the approver reviewed; issuance is refused if the signed SKILL.md yields a different name. */
195
+ expectName?: string;
196
+ /** Write to `<outDir>/<signed name>.cert.json` instead of next to the Skill; exclusive with `out`. */
197
+ outDir?: string;
198
+ /** Awaited after the certificate is built and just before it is written; a throw writes nothing. */
199
+ beforeSign?: (info: {
200
+ skillName: string;
201
+ digest: string;
202
+ }) => void | Promise<void>;
64
203
  }): Promise<{
65
204
  path: string;
66
205
  skillName: string;
package/dist/src/admin.js CHANGED
@@ -1,115 +1,380 @@
1
+ import { unlink } from 'node:fs/promises';
1
2
  import path from 'node:path';
3
+ import { requireString } from "./canonical-json.js";
2
4
  import { issueCertificate, parseCertificate } from "./certificate.js";
3
- import { readRegularFile, resolveOutside, writeFileAtomic, writeNewFile } from "./fs-safe.js";
4
- import { loadPrivateKey, loadPublicKey } from "./keys.js";
5
+ import { readRegularFile, realpathAllowingMissing, resolveOutside, writeFileAtomic, writeNewFile } from "./fs-safe.js";
6
+ import { loadPrivateKey, loadPublicKey, validateKeyId } from "./keys.js";
5
7
  import { validateDigest, validateScope } from "./names.js";
8
+ import { isDisplaySafeText } from "./root-events.js";
6
9
  import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
7
10
  import { addDuration, truncateToSecond } from "./time.js";
8
- import { CERTIFICATE_FILENAME, collectSkillTree } from "./tree-digest.js";
9
- import { readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
10
- import { resolveSkillName } from "./verify.js";
11
+ import { CERTIFICATE_FILENAME, collectSkillTree, sha256Hex, requireSkillRoot, SKILL_FILENAME } from "./tree-digest.js";
12
+ import { MAX_APPROVERS, MAX_SCOPES, readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
13
+ import { skillNameFromSkillFile } from "./verify.js";
11
14
  export const DEFAULT_TRUST_ROOT_EXPIRY = '365d';
12
15
  export const DEFAULT_REVOCATIONS_EXPIRY = '30d';
13
- const PRIVATE_KEY_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/u;
16
+ const MAX_TRUST_ROOT_BYTES = 4 * 1024 * 1024;
17
+ const MAX_REVOCATIONS_BYTES = 8 * 1024 * 1024;
18
+ const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
19
+ const MAX_APPROVER_NAME_LEN = 128;
20
+ const MAX_REVOCATION_REASON = 512;
21
+ const DEFAULT_REVOKE_REASON = 'revoked';
22
+ const latin1Decoder = new TextDecoder('latin1');
23
+ /**
24
+ * Private-key encodings `approve` refuses to certify (a certified file can reach the model through Pi):
25
+ * PEM/OpenSSH/PKCS#8/SSH2 armor ("BEGIN [RSA |EC |DSA |ENCRYPTED |OPENSSH |...]PRIVATE KEY"), OpenPGP armor
26
+ * ("BEGIN PGP PRIVATE KEY BLOCK"), PuTTY .ppk files, and age secret keys. Public keys and PGP PUBLIC KEY
27
+ * BLOCKs do not match. This is a best-effort guard, not a secret scanner.
28
+ */
29
+ // Every quantifier is bounded, so scanning is linear in the input (no backtracking blow-up on long runs of
30
+ // dashes, spaces or "BEGIN "). Three dashes are enough to anchor the header; "---- BEGIN SSH2 ..." contains them.
31
+ const PRIVATE_KEY_PATTERNS = [
32
+ /-{3}\s{0,4}BEGIN [A-Z0-9 ]{0,64}PRIVATE KEY/iu,
33
+ /PuTTY-User-Key-File-\d{1,4}:/u,
34
+ /AGE-SECRET-KEY-1[0-9A-Z]{20,200}/iu,
35
+ ];
36
+ /** True if the bytes contain recognizable private-key material. */
37
+ export function containsPrivateKey(content) {
38
+ const text = latin1Decoder.decode(content);
39
+ return PRIVATE_KEY_PATTERNS.some((pattern) => pattern.test(text));
40
+ }
14
41
  export async function initRoot(options) {
42
+ const trustRootTarget = path.resolve(options.trustRootOut);
43
+ const revocationsTarget = path.resolve(options.revocationsOut);
44
+ const canonicalTrust = await realpathAllowingMissing(trustRootTarget);
45
+ const canonicalRevoke = await realpathAllowingMissing(revocationsTarget);
46
+ if (trustRootTarget === revocationsTarget || canonicalTrust === canonicalRevoke) {
47
+ throw new Error('Trust root and revocation list output paths must differ');
48
+ }
15
49
  const root = await loadPrivateKey(options.rootKeyPath);
16
50
  const issuedAt = truncateToSecond(options.now);
17
51
  const trustRoot = {
18
- version: 1, issuedAt, expiresAt: addDuration(issuedAt, options.trustRootExpires ?? DEFAULT_TRUST_ROOT_EXPIRY, 'trust root expiry'),
19
- root, approvers: [],
52
+ version: 1,
53
+ issuedAt,
54
+ expiresAt: addDuration(issuedAt, options.trustRootExpires ?? DEFAULT_TRUST_ROOT_EXPIRY, 'trust root expiry'),
55
+ root,
56
+ approvers: [],
20
57
  };
21
58
  const revocations = {
22
- version: 1, issuedAt, expiresAt: addDuration(issuedAt, options.revocationsExpires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
23
- rootKeyId: root.keyId, keys: [], digests: [],
59
+ version: 1,
60
+ issuedAt,
61
+ expiresAt: addDuration(issuedAt, options.revocationsExpires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
62
+ rootKeyId: root.keyId,
63
+ keys: [],
64
+ digests: [],
24
65
  };
25
- const trustRootPath = await writeNewFile(options.trustRootOut, signTrustRoot(trustRoot, root.privateKey));
26
- const revocationsPath = await writeNewFile(options.revocationsOut, signRevocations(revocations, root.privateKey));
27
- return { rootKeyId: root.keyId, trustRoot: trustRootPath, revocations: revocationsPath };
66
+ const trustRootBytes = signTrustRoot(trustRoot, root.privateKey);
67
+ const revocationsBytes = signRevocations(revocations, root.privateKey);
68
+ const trustRootPath = await writeNewFile(trustRootTarget, trustRootBytes);
69
+ try {
70
+ const revocationsPath = await writeNewFile(revocationsTarget, revocationsBytes);
71
+ return {
72
+ rootKeyId: root.keyId,
73
+ trustRoot: trustRootPath,
74
+ revocations: revocationsPath,
75
+ };
76
+ }
77
+ catch (error) {
78
+ await unlink(trustRootPath).catch(() => { });
79
+ throw error;
80
+ }
28
81
  }
29
- async function updateTrustRoot(options, change) {
30
- const root = await loadPrivateKey(options.rootKeyPath);
31
- const current = readTrustRootForUpdate(await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024), root.keyId);
32
- const issuedAt = truncateToSecond(options.now);
82
+ /** A document was older than the lowest version this computer's memory allows. The GUI maps it by class. */
83
+ export class StaleDocumentError extends Error {
84
+ constructor(label, version, minimum) {
85
+ super(`${label} version ${version} is older than version ${minimum} this computer has seen`);
86
+ this.name = 'StaleDocumentError';
87
+ }
88
+ }
89
+ /** A document changed between prepare and commit. The GUI maps it, and `FileChangedError`, by class. */
90
+ export class DocumentChangedError extends Error {
91
+ constructor(label) {
92
+ super(`${label} changed after it was prepared; prepare again`);
93
+ this.name = 'DocumentChangedError';
94
+ }
95
+ }
96
+ const sha256Of = (bytes) => `sha256:${sha256Hex(bytes)}`;
97
+ /** `sha256:<hex>` of the regular file at `filePath`, or `null` when it does not exist. */
98
+ async function fileSha256OrNull(filePath, label, maxBytes) {
99
+ try {
100
+ return sha256Of(await readRegularFile(filePath, label, maxBytes));
101
+ }
102
+ catch (error) {
103
+ if (error?.code === 'ENOENT')
104
+ return null;
105
+ throw error;
106
+ }
107
+ }
108
+ const FORBIDDEN_WHY = {
109
+ root: 'the root key',
110
+ recovery: 'a recovery key',
111
+ timestamp: 'the timestamp key',
112
+ retired: 'a key that held the root or timestamp role',
113
+ formerRecovery: 'a former recovery key',
114
+ revoked: 'a revoked key',
115
+ };
116
+ /** Reads the trust root once, applies the change and returns the unsigned result. Never signs or writes. */
117
+ export async function prepareTrustRootChange(o) {
118
+ const change = o.change;
119
+ let approverEntry = null;
120
+ const issuedAt = truncateToSecond(o.now);
121
+ if (change.kind === 'add') {
122
+ const approverName = requireString(change.name, 'Approver name', MAX_APPROVER_NAME_LEN);
123
+ if (!isDisplaySafeText(approverName))
124
+ throw new Error('Approver name contains characters that cannot be shown safely');
125
+ if (change.scopes.length === 0)
126
+ throw new Error('At least one --scope is required');
127
+ const scopes = [...new Set(change.scopes.map((scope) => validateScope(scope)))].sort();
128
+ if (scopes.length > MAX_SCOPES)
129
+ throw new Error(`Approver scopes cannot exceed ${MAX_SCOPES}`);
130
+ approverEntry = {
131
+ ...change.publicKey,
132
+ name: approverName,
133
+ scopes,
134
+ expiresAt: addDuration(issuedAt, change.expires, 'approver expiry'),
135
+ };
136
+ }
137
+ const removeId = change.kind === 'remove' ? validateKeyId(change.keyId, 'Approver key id') : null;
138
+ const source = o.trustRootPath;
139
+ const rawBytes = await readRegularFile(source, 'Trust root', MAX_TRUST_ROOT_BYTES);
140
+ const current = readTrustRootForUpdate(rawBytes, o.rootKeyId);
141
+ if (o.minimumVersion !== undefined && current.version < o.minimumVersion)
142
+ throw new StaleDocumentError('Trust root', current.version, o.minimumVersion);
143
+ const expiresAt = change.trustRootExpires
144
+ ? addDuration(issuedAt, change.trustRootExpires, 'trust root expiry')
145
+ : current.expiresAt;
33
146
  const next = {
34
147
  ...current,
35
148
  version: current.version + 1,
36
149
  issuedAt,
37
- expiresAt: options.expires ? addDuration(issuedAt, options.expires, 'trust root expiry') : current.expiresAt,
150
+ expiresAt,
38
151
  approvers: current.approvers.map((approver) => ({ ...approver, scopes: [...approver.scopes] })),
39
152
  };
40
- change(next);
153
+ let replaces = null;
154
+ if (change.kind === 'add') {
155
+ if (change.publicKey.keyId === next.root.keyId)
156
+ throw new Error('The root key cannot be an approver; generate a separate approver key');
157
+ replaces = next.approvers.find((entry) => entry.keyId === change.publicKey.keyId) ?? null;
158
+ const remaining = next.approvers.filter((entry) => entry.keyId !== change.publicKey.keyId);
159
+ if (remaining.length >= MAX_APPROVERS)
160
+ throw new Error(`Trust root cannot exceed ${MAX_APPROVERS} approvers`);
161
+ remaining.push(approverEntry);
162
+ next.approvers = remaining;
163
+ }
164
+ else if (change.kind === 'remove') {
165
+ const beforeCount = next.approvers.length;
166
+ next.approvers = next.approvers.filter((entry) => entry.keyId !== removeId);
167
+ if (next.approvers.length === beforeCount)
168
+ throw new Error(`No approver with key id ${removeId}`);
169
+ }
41
170
  if (next.expiresAt <= issuedAt)
42
171
  throw new Error('The trust root would already be expired; pass --expires to extend it');
43
- const written = await writeFileAtomic(options.out ?? options.trustRootPath, signTrustRoot(next, root.privateKey));
44
- return { version: next.version, path: written, trustRoot: next };
172
+ for (const entry of o.forbidden ?? []) {
173
+ if (next.approvers.some((approver) => approver.keyId === entry.keyId))
174
+ throw new Error(`Approver ${entry.keyId} cannot stay or be added: it is ${FORBIDDEN_WHY[entry.why]}`);
175
+ }
176
+ const target = o.out ?? source;
177
+ return {
178
+ kind: 'trust-root',
179
+ source,
180
+ target,
181
+ baseSha256: sha256Of(rawBytes),
182
+ targetBase: path.resolve(target) === path.resolve(source) ? null : await fileSha256OrNull(target, 'Trust root output', MAX_TRUST_ROOT_BYTES),
183
+ rootKeyId: o.rootKeyId,
184
+ current,
185
+ payload: next,
186
+ change,
187
+ replaces,
188
+ };
189
+ }
190
+ function requireKey(p, key) {
191
+ if (key.keyId !== p.rootKeyId)
192
+ throw new Error('Key does not match the prepared root key');
193
+ }
194
+ /** Pure: signs `p.payload` and nothing else. The preview and commit use this one code path. */
195
+ export function signPreparedTrustRoot(p, key) {
196
+ return signTrustRoot(p.payload, key.privateKey);
197
+ }
198
+ export async function commitTrustRoot(p, rootKey, o = {}) {
199
+ requireKey(p, rootKey);
200
+ const again = await readRegularFile(p.source, 'Trust root', MAX_TRUST_ROOT_BYTES);
201
+ if (sha256Of(again) !== p.baseSha256)
202
+ throw new DocumentChangedError('Trust root');
203
+ const bytes = signPreparedTrustRoot(p, rootKey);
204
+ await o.beforeWrite?.();
205
+ const sameFile = path.resolve(p.target) === path.resolve(p.source);
206
+ const written = await writeFileAtomic(p.target, bytes, 0o644, { expectSha256: sameFile ? p.baseSha256 : p.targetBase });
207
+ return { version: p.payload.version, path: written, sha256: sha256Of(bytes) };
208
+ }
209
+ async function updateTrustRoot(options, change, forbidden) {
210
+ const root = await loadPrivateKey(options.rootKeyPath);
211
+ const prepared = await prepareTrustRootChange({
212
+ rootKeyId: root.keyId, trustRootPath: options.trustRootPath, out: options.out, now: options.now,
213
+ change: change(options.expires), forbidden,
214
+ });
215
+ const written = await commitTrustRoot(prepared, root);
216
+ return { version: written.version, path: written.path, trustRoot: prepared.payload };
45
217
  }
46
218
  export async function addApprover(options) {
219
+ requireString(options.name, 'Approver name', MAX_APPROVER_NAME_LEN);
47
220
  const approverKey = await loadPublicKey(options.publicKeyPath);
48
- if (options.scopes.length === 0)
49
- throw new Error('At least one --scope is required');
50
- const scopes = [...new Set(options.scopes.map((scope) => validateScope(scope)))].sort();
51
- const result = await updateTrustRoot({ rootKeyPath: options.rootKeyPath, trustRootPath: options.trustRootPath, out: options.out, now: options.now, expires: options.trustRootExpires }, (trustRoot) => {
52
- if (approverKey.keyId === trustRoot.root.keyId)
53
- throw new Error('The root key cannot be an approver; generate a separate approver key');
54
- trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== approverKey.keyId);
55
- trustRoot.approvers.push({ ...approverKey, name: options.name, scopes, expiresAt: addDuration(truncateToSecond(options.now), options.expires, 'approver expiry') });
56
- });
221
+ const result = await updateTrustRoot({ ...options, expires: options.trustRootExpires }, (trustRootExpires) => ({
222
+ kind: 'add', publicKey: approverKey, name: options.name, scopes: options.scopes, expires: options.expires,
223
+ ...(trustRootExpires ? { trustRootExpires } : {}),
224
+ }), options.forbidden);
57
225
  return { version: result.version, path: result.path, keyId: approverKey.keyId };
58
226
  }
59
227
  export async function removeApprover(options) {
60
- return await updateTrustRoot({ rootKeyPath: options.rootKeyPath, trustRootPath: options.trustRootPath, out: options.out, now: options.now, expires: options.trustRootExpires }, (trustRoot) => {
61
- const before = trustRoot.approvers.length;
62
- trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== options.keyId);
63
- if (trustRoot.approvers.length === before)
64
- throw new Error(`No approver with key id ${options.keyId}`);
65
- });
228
+ const targetKeyId = validateKeyId(options.keyId, 'Approver key id');
229
+ return await updateTrustRoot({ ...options, expires: options.trustRootExpires }, (trustRootExpires) => ({ kind: 'remove', keyId: targetKeyId, ...(trustRootExpires ? { trustRootExpires } : {}) }));
66
230
  }
67
- export async function updateRevocations(options) {
68
- const root = await loadPrivateKey(options.rootKeyPath);
69
- const current = readRevocationsForUpdate(await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024), root.keyId, root.publicKey);
70
- const issuedAt = truncateToSecond(options.now);
231
+ /** Re-signs the trust root with a new expiry and the same approvers. */
232
+ export async function renewTrustRoot(options) {
233
+ const result = await updateTrustRoot({ ...options, expires: options.expires }, (expires) => ({ kind: 'renew', trustRootExpires: expires }));
234
+ return { version: result.version, path: result.path, expiresAt: result.trustRoot.expiresAt };
235
+ }
236
+ export async function prepareRevocationsChange(o) {
237
+ const change = o.change;
238
+ const issuedAt = truncateToSecond(o.now);
239
+ let reason = '';
240
+ if (change.kind !== 'refresh') {
241
+ reason = requireString(change.reason, 'Revocation reason', MAX_REVOCATION_REASON);
242
+ if (!isDisplaySafeText(reason))
243
+ throw new Error('Revocation reason contains characters that cannot be shown safely');
244
+ }
245
+ const keyId = change.kind === 'key' || change.kind === 'both' ? validateKeyId(change.keyId, 'Revoked key id') : null;
246
+ const digest = change.kind === 'digest' || change.kind === 'both' ? validateDigest(change.digest) : null;
247
+ const source = o.revocationsPath;
248
+ const rawBytes = await readRegularFile(source, 'Revocation list', MAX_REVOCATIONS_BYTES);
249
+ const current = readRevocationsForUpdate(rawBytes, o.rootKeyId, o.rootPublicKey);
250
+ if (o.minimumVersion !== undefined && current.version < o.minimumVersion)
251
+ throw new StaleDocumentError('Revocation list', current.version, o.minimumVersion);
252
+ const expiresAt = addDuration(issuedAt, o.expires, 'revocation list expiry');
71
253
  const next = {
72
- ...current, version: current.version + 1, issuedAt,
73
- expiresAt: addDuration(issuedAt, options.expires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
74
- keys: [...current.keys], digests: [...current.digests],
254
+ ...current,
255
+ version: current.version + 1,
256
+ issuedAt,
257
+ expiresAt,
258
+ keys: [...current.keys],
259
+ digests: [...current.digests],
75
260
  };
76
- if (options.revokeKey) {
77
- if (next.keys.some((entry) => entry.keyId === options.revokeKey))
78
- throw new Error(`Key ${options.revokeKey} is already revoked`);
79
- next.keys.push({ keyId: options.revokeKey, reason: options.reason ?? 'revoked', revokedAt: issuedAt });
261
+ if (keyId !== null) {
262
+ if (next.keys.some((entry) => entry.keyId === keyId))
263
+ throw new Error(`Key ${keyId} is already revoked`);
264
+ next.keys.push({ keyId, reason, revokedAt: issuedAt });
80
265
  }
81
- if (options.revokeDigest) {
82
- const digest = validateDigest(options.revokeDigest);
266
+ if (digest !== null) {
83
267
  if (next.digests.some((entry) => entry.digest === digest))
84
268
  throw new Error(`Digest ${digest} is already revoked`);
85
- next.digests.push({ digest, reason: options.reason ?? 'revoked', revokedAt: issuedAt });
269
+ next.digests.push({ digest, reason, revokedAt: issuedAt });
86
270
  }
87
- const written = await writeFileAtomic(options.out ?? options.revocationsPath, signRevocations(next, root.privateKey));
88
- return { version: next.version, path: written, expiresAt: next.expiresAt };
271
+ const target = o.out ?? source;
272
+ return {
273
+ kind: 'revocations',
274
+ source,
275
+ target,
276
+ baseSha256: sha256Of(rawBytes),
277
+ targetBase: path.resolve(target) === path.resolve(source) ? null : await fileSha256OrNull(target, 'Revocation list output', MAX_REVOCATIONS_BYTES),
278
+ rootKeyId: o.rootKeyId,
279
+ current,
280
+ payload: next,
281
+ change,
282
+ };
283
+ }
284
+ export function signPreparedRevocations(p, key) {
285
+ return signRevocations(p.payload, key.privateKey);
286
+ }
287
+ export async function commitRevocations(p, rootKey, o = {}) {
288
+ requireKey(p, rootKey);
289
+ const again = await readRegularFile(p.source, 'Revocation list', MAX_REVOCATIONS_BYTES);
290
+ if (sha256Of(again) !== p.baseSha256)
291
+ throw new DocumentChangedError('Revocation list');
292
+ const bytes = signPreparedRevocations(p, rootKey);
293
+ await o.beforeWrite?.();
294
+ const sameFile = path.resolve(p.target) === path.resolve(p.source);
295
+ const written = await writeFileAtomic(p.target, bytes, 0o644, { expectSha256: sameFile ? p.baseSha256 : p.targetBase });
296
+ return { version: p.payload.version, path: written, sha256: sha256Of(bytes), expiresAt: p.payload.expiresAt };
297
+ }
298
+ export async function updateRevocations(options) {
299
+ const root = await loadPrivateKey(options.rootKeyPath);
300
+ const reason = requireString(options.reason ?? DEFAULT_REVOKE_REASON, 'Revocation reason', MAX_REVOCATION_REASON);
301
+ const change = options.revokeKey !== undefined && options.revokeDigest !== undefined ? { kind: 'both', keyId: options.revokeKey, digest: options.revokeDigest, reason }
302
+ : options.revokeKey !== undefined ? { kind: 'key', keyId: options.revokeKey, reason }
303
+ : options.revokeDigest !== undefined ? { kind: 'digest', digest: options.revokeDigest, reason }
304
+ : { kind: 'refresh' };
305
+ const prepared = await prepareRevocationsChange({
306
+ rootKeyId: root.keyId, rootPublicKey: root.publicKey, revocationsPath: options.revocationsPath, out: options.out,
307
+ now: options.now, expires: options.expires ?? DEFAULT_REVOCATIONS_EXPIRY, change,
308
+ });
309
+ const written = await commitRevocations(prepared, root);
310
+ return { version: written.version, path: written.path, expiresAt: written.expiresAt };
89
311
  }
90
312
  export async function approveSkill(options) {
91
313
  const skillDir = path.resolve(options.skillDir);
92
- const approver = await loadPrivateKey(options.approverKeyPath);
93
- await resolveOutside(options.approverKeyPath, skillDir, 'Approver private key');
94
- const skillName = await resolveSkillName(skillDir, options.name);
314
+ const expected = options.expectDigest === undefined ? null : validateDigest(options.expectDigest, 'expected digest');
315
+ if ((options.approverKeyPath === undefined) === (options.approverKey === undefined)) {
316
+ throw new Error('Pass exactly one of approverKeyPath and approverKey');
317
+ }
318
+ if (options.out !== undefined && options.outDir !== undefined) {
319
+ throw new Error('Pass at most one of out and outDir');
320
+ }
321
+ await requireSkillRoot(skillDir);
322
+ let approver;
323
+ if (options.approverKeyPath !== undefined) {
324
+ // Verify the key path is outside the Skill directory before reading the private key.
325
+ await resolveOutside(options.approverKeyPath, skillDir, 'Approver private key');
326
+ approver = await loadPrivateKey(options.approverKeyPath);
327
+ }
328
+ else {
329
+ approver = options.approverKey;
330
+ }
95
331
  const tree = await collectSkillTree(skillDir, { includeContents: true });
332
+ // Taken from the same SKILL.md bytes that are hashed and signed, so the name cannot differ from the reviewed version.
333
+ const skillName = skillNameFromSkillFile(skillDir, tree.contents.get(SKILL_FILENAME), options.name);
334
+ // Checked against the same bytes that are signed, so a change after review can never be certified.
335
+ if (expected !== null && tree.digest !== expected) {
336
+ throw new Error(`Refusing to approve: the Skill changed since it was reviewed (expected ${expected}, found ${tree.digest}). Review the current version and approve again.`);
337
+ }
338
+ if (options.expectName !== undefined && skillName !== options.expectName) {
339
+ throw new Error(`Refusing to approve: the Skill name is "${skillName}", not the reviewed "${options.expectName}"`);
340
+ }
96
341
  for (const [filePath, content] of tree.contents) {
97
- if (PRIVATE_KEY_PATTERN.test(content.toString('latin1'))) {
342
+ if (containsPrivateKey(content)) {
98
343
  throw new Error(`Refusing to approve: ${filePath} contains a private key. Remove it from the Skill and rotate that key.`);
99
344
  }
100
345
  }
101
346
  let previousDigest = null;
102
347
  if (options.previous) {
103
- previousDigest = options.previous.startsWith('sha256:')
104
- ? validateDigest(options.previous, 'previous digest')
105
- : parseCertificate(await readRegularFile(options.previous, 'Previous certificate', 8 * 1024 * 1024)).digest;
348
+ if (options.previous.startsWith('sha256:')) {
349
+ previousDigest = validateDigest(options.previous, 'previous digest');
350
+ }
351
+ else {
352
+ const prevBytes = await readRegularFile(options.previous, 'Previous certificate', MAX_CERTIFICATE_BYTES);
353
+ previousDigest = parseCertificate(prevBytes).digest;
354
+ }
106
355
  }
107
356
  const issuedAt = truncateToSecond(options.now);
108
357
  const expiresAt = addDuration(issuedAt, options.expires, 'certificate expiry');
109
358
  const bytes = issueCertificate({
110
- skillName, digest: tree.digest, files: tree.files, approver, issuedAt, expiresAt, reason: options.reason, previousDigest,
359
+ skillName,
360
+ digest: tree.digest,
361
+ files: tree.files,
362
+ approver,
363
+ issuedAt,
364
+ expiresAt,
365
+ reason: options.reason,
366
+ previousDigest,
111
367
  });
112
- const out = options.out ?? path.join(tree.root, CERTIFICATE_FILENAME);
113
- const written = await writeFileAtomic(out, bytes);
114
- return { path: written, skillName, digest: tree.digest, certificateId: parseCertificate(bytes).id, expiresAt };
368
+ await options.beforeSign?.({ skillName, digest: tree.digest });
369
+ const targetPath = options.out
370
+ ?? (options.outDir === undefined ? path.join(tree.root, CERTIFICATE_FILENAME) : path.join(options.outDir, `${skillName}.cert.json`));
371
+ const written = await writeFileAtomic(targetPath, bytes);
372
+ const parsed = parseCertificate(bytes);
373
+ return {
374
+ path: written,
375
+ skillName,
376
+ digest: tree.digest,
377
+ certificateId: parsed.id,
378
+ expiresAt,
379
+ };
115
380
  }