@mago-foundation/mago-ski 0.3.0 → 0.4.1
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/README.md +34 -10
- package/action.yml +21 -2
- package/dist/hosts/github/run.d.ts +9 -0
- package/dist/hosts/github/run.js +30 -16
- package/dist/hosts/pi/index.js +40 -18
- package/dist/src/admin.d.ts +2 -1
- package/dist/src/admin.js +3 -2
- package/dist/src/canonical-json.d.ts +6 -0
- package/dist/src/canonical-json.js +11 -0
- package/dist/src/cli.d.ts +13 -1
- package/dist/src/cli.js +426 -8
- package/dist/src/diff.d.ts +5 -0
- package/dist/src/diff.js +2 -1
- package/dist/src/dsse.js +2 -2
- package/dist/src/experimental/sigstore.d.ts +6 -0
- package/dist/src/experimental/sigstore.js +13 -5
- package/dist/src/gate/adapters/claude-code-settings.js +1 -1
- package/dist/src/gate/adapters/claude-code.js +1 -0
- package/dist/src/gate/adapters/codex-names.d.ts +1 -0
- package/dist/src/gate/adapters/codex-names.js +56 -0
- package/dist/src/gate/adapters/codex-requirements.d.ts +11 -0
- package/dist/src/gate/adapters/codex-requirements.js +56 -29
- package/dist/src/gate/adapters/codex.d.ts +3 -0
- package/dist/src/gate/adapters/codex.js +147 -20
- package/dist/src/gate/admin-client.d.ts +19 -0
- package/dist/src/gate/admin-client.js +62 -0
- package/dist/src/gate/generations.js +2 -0
- package/dist/src/gate/instance.d.ts +57 -0
- package/dist/src/gate/instance.js +97 -0
- package/dist/src/gate/proc.d.ts +6 -0
- package/dist/src/gate/proc.js +14 -3
- package/dist/src/gate/service.d.ts +13 -0
- package/dist/src/gate/service.js +344 -37
- package/dist/src/gate/setup.d.ts +210 -0
- package/dist/src/gate/setup.js +1038 -0
- package/dist/src/gate/trust-store.d.ts +14 -0
- package/dist/src/gate/trust-store.js +66 -0
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.js +3 -1
- package/dist/src/policy.d.ts +7 -0
- package/dist/src/policy.js +19 -2
- package/dist/src/recovery-admin.js +7 -4
- package/dist/src/root-events.d.ts +2 -0
- package/dist/src/root-events.js +61 -4
- package/dist/src/tree-digest.d.ts +6 -0
- package/dist/src/tree-digest.js +8 -0
- package/docs/hosts/adapter-interface.md +1 -1
- package/docs/hosts/claude-code.md +108 -0
- package/docs/hosts/codex.md +181 -0
- package/docs/spec/gui-admin-rack-v1.md +1 -1
- package/docs/spec/root-recovery-v1.md +3 -2
- package/docs/spec/trust-documents-v1.md +1 -1
- package/docs/threat-model.md +13 -1
- package/package.json +3 -1
|
@@ -33,4 +33,18 @@ export interface TrustStore {
|
|
|
33
33
|
}, now: Date): Promise<AcceptResult>;
|
|
34
34
|
current(now: Date): Promise<CurrentTrust>;
|
|
35
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Carries a trust store from before the per-root layout (documents directly in `flatDir`, builds before gate-new-root.md) into
|
|
38
|
+
* the folder of its root, `perRootDir`, keeping its rollback memory: the document versions and the highest trusted time.
|
|
39
|
+
* Without this, the per-root store would start empty and accept an older, still valid trust root or revocation list (one
|
|
40
|
+
* from before a revocation). Per-root stores are folders; anything else in `flatDir` is the old store.
|
|
41
|
+
*
|
|
42
|
+
* - The old state verifies under this root and the per-root store is empty: it is copied (documents, then the manifest, the
|
|
43
|
+
* commit point), read back, and the old files are removed (manifest first, so a stop in between is finished next time).
|
|
44
|
+
* - Both hold state: the newer one in both versions is kept, with the later trusted time. The per-root store is never left
|
|
45
|
+
* older than what the gate had accepted before the upgrade.
|
|
46
|
+
* - Anything else throws, and the service does not open a store (fail closed): the old state does not verify under this
|
|
47
|
+
* root (another root, or damaged), documents without a manifest, or the two states are each newer in one document.
|
|
48
|
+
*/
|
|
49
|
+
export declare function migrateFlatTrustStore(flatDir: string, perRootDir: string, rootFingerprint: string): Promise<'none' | 'migrated' | 'kept-newer' | 'cleaned'>;
|
|
36
50
|
export declare function openTrustStore(dir: string, options: TrustStoreOptions): Promise<TrustStore>;
|
|
@@ -84,6 +84,72 @@ async function loadState(dir, rootFingerprint) {
|
|
|
84
84
|
throw new Error('document versions do not match the manifest');
|
|
85
85
|
return { manifest, manifestBytes, trustRootBytes, revocationsBytes };
|
|
86
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* Carries a trust store from before the per-root layout (documents directly in `flatDir`, builds before gate-new-root.md) into
|
|
89
|
+
* the folder of its root, `perRootDir`, keeping its rollback memory: the document versions and the highest trusted time.
|
|
90
|
+
* Without this, the per-root store would start empty and accept an older, still valid trust root or revocation list (one
|
|
91
|
+
* from before a revocation). Per-root stores are folders; anything else in `flatDir` is the old store.
|
|
92
|
+
*
|
|
93
|
+
* - The old state verifies under this root and the per-root store is empty: it is copied (documents, then the manifest, the
|
|
94
|
+
* commit point), read back, and the old files are removed (manifest first, so a stop in between is finished next time).
|
|
95
|
+
* - Both hold state: the newer one in both versions is kept, with the later trusted time. The per-root store is never left
|
|
96
|
+
* older than what the gate had accepted before the upgrade.
|
|
97
|
+
* - Anything else throws, and the service does not open a store (fail closed): the old state does not verify under this
|
|
98
|
+
* root (another root, or damaged), documents without a manifest, or the two states are each newer in one document.
|
|
99
|
+
*/
|
|
100
|
+
export async function migrateFlatTrustStore(flatDir, perRootDir, rootFingerprint) {
|
|
101
|
+
const entries = await readdir(flatDir, { withFileTypes: true }).catch((e) => { if (e.code === 'ENOENT')
|
|
102
|
+
return []; throw e; });
|
|
103
|
+
const old = entries.filter((e) => !e.isDirectory()).map((e) => e.name);
|
|
104
|
+
if (old.length === 0)
|
|
105
|
+
return 'none';
|
|
106
|
+
const refuse = (why) => {
|
|
107
|
+
throw new Error(`trust state from an earlier build is in ${flatDir} and ${why}. Nothing is accepted until it is carried over, so that documents older than the ones already accepted stay refused. `
|
|
108
|
+
+ `If the gate was set up for another root, start it once with that root. To give this state up (the gate then accepts any valid documents of this root), remove the files in ${flatDir}, not its folders`);
|
|
109
|
+
};
|
|
110
|
+
const removeOld = async () => {
|
|
111
|
+
for (const name of [...old].sort((a, b) => Number(b === MANIFEST) - Number(a === MANIFEST)))
|
|
112
|
+
await unlink(path.join(flatDir, name)).catch((e) => { if (e.code !== 'ENOENT')
|
|
113
|
+
throw e; });
|
|
114
|
+
await fsyncDir(flatDir);
|
|
115
|
+
};
|
|
116
|
+
const present = await lstat(perRootDir).then(() => true, (e) => { if (e.code === 'ENOENT')
|
|
117
|
+
return false; throw e; });
|
|
118
|
+
let dest = null;
|
|
119
|
+
if (present)
|
|
120
|
+
dest = await loadState(perRootDir, rootFingerprint).catch(() => refuse(`the store of this root, ${perRootDir}, cannot be read`));
|
|
121
|
+
if (!old.includes(MANIFEST)) { // what an interrupted clean-up leaves, but only when the per-root store is committed
|
|
122
|
+
if (!dest && old.some((name) => !/^\..*\.tmp$/u.test(name)))
|
|
123
|
+
refuse('has documents but no manifest, so what was accepted before is not known');
|
|
124
|
+
await removeOld();
|
|
125
|
+
return dest ? 'cleaned' : 'none';
|
|
126
|
+
}
|
|
127
|
+
const from = (await loadState(flatDir, rootFingerprint).catch((e) => refuse(`does not verify under root ${rootFingerprint} (${e instanceof Error ? e.message : 'unreadable'})`)));
|
|
128
|
+
const v = (st) => [st.manifest.trustRoot.version, st.manifest.revocations.version];
|
|
129
|
+
const highTime = dest && dest.manifest.highTime > from.manifest.highTime ? dest.manifest.highTime : from.manifest.highTime;
|
|
130
|
+
const commit = async (manifest) => {
|
|
131
|
+
await writeFileAtomic(path.join(perRootDir, MANIFEST), manifestJson(manifest), 0o600);
|
|
132
|
+
await fsyncDir(perRootDir);
|
|
133
|
+
};
|
|
134
|
+
if (dest && v(dest)[0] >= v(from)[0] && v(dest)[1] >= v(from)[1]) { // the per-root store is at least as new: keep it
|
|
135
|
+
if (highTime > dest.manifest.highTime)
|
|
136
|
+
await commit({ ...dest.manifest, highTime });
|
|
137
|
+
await removeOld();
|
|
138
|
+
return 'kept-newer';
|
|
139
|
+
}
|
|
140
|
+
if (dest && (v(dest)[0] > v(from)[0] || v(dest)[1] > v(from)[1]))
|
|
141
|
+
refuse(`is newer in one document and older in the other than the store of this root (trust root ${v(from)[0]} and revocations ${v(from)[1]}, against ${v(dest)[0]} and ${v(dest)[1]})`);
|
|
142
|
+
await mkdir(perRootDir, { mode: 0o700 }).catch((e) => { if (e.code !== 'EEXIST')
|
|
143
|
+
throw e; });
|
|
144
|
+
await writeFileAtomic(path.join(perRootDir, from.manifest.trustRoot.file), from.trustRootBytes, 0o600);
|
|
145
|
+
await writeFileAtomic(path.join(perRootDir, from.manifest.revocations.file), from.revocationsBytes, 0o600);
|
|
146
|
+
await commit({ ...from.manifest, highTime });
|
|
147
|
+
const back = await loadState(perRootDir, rootFingerprint); // read back before anything old is removed
|
|
148
|
+
if (!back || v(back)[0] !== v(from)[0] || v(back)[1] !== v(from)[1])
|
|
149
|
+
throw new Error(`carrying the trust state to ${perRootDir} did not verify; the old files are kept`);
|
|
150
|
+
await removeOld();
|
|
151
|
+
return 'migrated';
|
|
152
|
+
}
|
|
87
153
|
export async function openTrustStore(dir, options) {
|
|
88
154
|
requireValidDate(options.now, 'Open time');
|
|
89
155
|
dir = path.resolve(dir);
|
package/dist/src/index.d.ts
CHANGED
|
@@ -13,4 +13,5 @@ export * from './timestamp.ts';
|
|
|
13
13
|
export * from './policy.ts';
|
|
14
14
|
export * from './admin.ts';
|
|
15
15
|
export * from './diff.ts';
|
|
16
|
-
|
|
16
|
+
/** The command line entry. The gate's test seams (a fake root uid, base folder, admin client) are not part of the library surface. */
|
|
17
|
+
export declare const runCli: (argv?: string[], now?: Date) => Promise<number>;
|
package/dist/src/index.js
CHANGED
|
@@ -13,4 +13,6 @@ export * from "./timestamp.js";
|
|
|
13
13
|
export * from "./policy.js";
|
|
14
14
|
export * from "./admin.js";
|
|
15
15
|
export * from "./diff.js";
|
|
16
|
-
|
|
16
|
+
import { runCli as runCliWithSeams } from "./cli.js";
|
|
17
|
+
/** The command line entry. The gate's test seams (a fake root uid, base folder, admin client) are not part of the library surface. */
|
|
18
|
+
export const runCli = (argv, now) => runCliWithSeams(argv, now);
|
package/dist/src/policy.d.ts
CHANGED
|
@@ -59,6 +59,11 @@ export interface Policy {
|
|
|
59
59
|
}
|
|
60
60
|
/** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
|
|
61
61
|
export declare function loadPolicy(policyPath: string): Promise<Policy>;
|
|
62
|
+
/**
|
|
63
|
+
* Two canonical paths that name the same file. On macOS the default file system ignores case, and a path whose last part
|
|
64
|
+
* does not exist yet keeps the case it was written in, so `state.json` and `STATE.JSON` must count as the same file there.
|
|
65
|
+
*/
|
|
66
|
+
export declare function samePath(a: string, b: string, platform?: NodeJS.Platform): boolean;
|
|
62
67
|
/** The host state file exists and was read, but its content or kind is wrong. Every other read error is not this. */
|
|
63
68
|
export declare class HostStateFormatError extends Error {
|
|
64
69
|
constructor(message: string);
|
|
@@ -170,6 +175,8 @@ export interface DiscoveryLimits {
|
|
|
170
175
|
maxSkills?: number;
|
|
171
176
|
/** Maximum directory entries visited across all roots. */
|
|
172
177
|
maxEntries?: number;
|
|
178
|
+
/** Directories (absolute) that are not entered and not reported: another checkout that sits inside a root. */
|
|
179
|
+
exclude?: readonly string[];
|
|
173
180
|
}
|
|
174
181
|
/** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
|
|
175
182
|
export declare class DiscoveryBudgetError extends Error {
|
package/dist/src/policy.js
CHANGED
|
@@ -127,6 +127,13 @@ async function canonicalOrLexical(target) {
|
|
|
127
127
|
return path.resolve(target);
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Two canonical paths that name the same file. On macOS the default file system ignores case, and a path whose last part
|
|
132
|
+
* does not exist yet keeps the case it was written in, so `state.json` and `STATE.JSON` must count as the same file there.
|
|
133
|
+
*/
|
|
134
|
+
export function samePath(a, b, platform = process.platform) {
|
|
135
|
+
return platform === 'darwin' || platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
136
|
+
}
|
|
130
137
|
/** decision_log and state_file are overwritten or appended to, so they must not be a file the policy reads. */
|
|
131
138
|
async function rejectWriteTargetsThatOverlapInputs(policy) {
|
|
132
139
|
const inputs = [
|
|
@@ -142,13 +149,13 @@ async function rejectWriteTargetsThatOverlapInputs(policy) {
|
|
|
142
149
|
continue;
|
|
143
150
|
const canonical = await canonicalOrLexical(target);
|
|
144
151
|
for (const [name, input] of inputs) {
|
|
145
|
-
if (canonical
|
|
152
|
+
if (samePath(canonical, await canonicalOrLexical(input)))
|
|
146
153
|
throw new Error(`Policy ${label} must not be ${name}`);
|
|
147
154
|
}
|
|
148
155
|
if (directories.some((directory) => isInside(directory, canonical)))
|
|
149
156
|
throw new Error(`Policy ${label} must not be inside a certificate_dirs directory`);
|
|
150
157
|
for (const [other, otherPath] of seen)
|
|
151
|
-
if (canonical
|
|
158
|
+
if (samePath(canonical, otherPath))
|
|
152
159
|
throw new Error(`Policy ${label} must not be the same file as ${other}`);
|
|
153
160
|
seen.push([label, canonical]);
|
|
154
161
|
}
|
|
@@ -644,6 +651,13 @@ async function loadTrustBody(policy, now, o) {
|
|
|
644
651
|
const problem = await saveState();
|
|
645
652
|
if (problem)
|
|
646
653
|
return problem;
|
|
654
|
+
// Another load on this host may have accepted newer documents meanwhile (the merge kept the higher versions): then the
|
|
655
|
+
// documents this load read are older than what the host has already accepted, which is a rollback like any other.
|
|
656
|
+
const accepted = state.roots[activeRootKeyId];
|
|
657
|
+
if (accepted && (accepted.trust_root_version > next.trust_root_version || accepted.revocations_version > next.revocations_version))
|
|
658
|
+
return failure(`this host has already accepted trust root ${accepted.trust_root_version} and revocation list ${accepted.revocations_version}; the documents read are older (rollback)`, { rollback: true });
|
|
659
|
+
if (timestamp && walk?.timestampKeyId && (state.timestamps[walk.timestampKeyId]?.version ?? 0) > timestamp.version)
|
|
660
|
+
return failure(`this host has already accepted timestamp ${state.timestamps[walk.timestampKeyId].version}; the timestamp read is older (rollback)`, { rollback: true });
|
|
647
661
|
if (walk) {
|
|
648
662
|
result.context.root = {
|
|
649
663
|
pinnedRootKeyId: policy.rootKeyId,
|
|
@@ -734,12 +748,15 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH, limit
|
|
|
734
748
|
const maxEntries = limits.maxEntries ?? MAX_DISCOVERY_ENTRIES;
|
|
735
749
|
const found = new Set();
|
|
736
750
|
const tooDeep = new Set();
|
|
751
|
+
const excluded = new Set((limits.exclude ?? []).map((dir) => path.resolve(dir)));
|
|
737
752
|
let entries = 0;
|
|
738
753
|
const checkSkills = () => {
|
|
739
754
|
if (found.size + tooDeep.size > maxSkills)
|
|
740
755
|
throw new DiscoveryBudgetError(`more than ${maxSkills} Skills found under skill_dirs; narrow skill_dirs or split the repository`);
|
|
741
756
|
};
|
|
742
757
|
async function walk(directory, depth) {
|
|
758
|
+
if (excluded.has(directory))
|
|
759
|
+
return;
|
|
743
760
|
try {
|
|
744
761
|
await lstat(path.join(directory, 'SKILL.md'));
|
|
745
762
|
found.add(directory);
|
|
@@ -372,8 +372,10 @@ export async function adoptTrustDocuments(options) {
|
|
|
372
372
|
const root = await loadPrivateKey(options.rootKeyPath);
|
|
373
373
|
if (root.keyId === options.fromRootKeyId)
|
|
374
374
|
throw new Error('The new root key is the same as the current one; nothing to adopt');
|
|
375
|
-
const
|
|
376
|
-
const
|
|
375
|
+
const trustRead = await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024);
|
|
376
|
+
const listRead = await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
|
|
377
|
+
const currentTrust = readTrustRootForUpdate(trustRead, options.fromRootKeyId);
|
|
378
|
+
const currentList = readRevocationsForUpdate(listRead, options.fromRootKeyId, currentTrust.root.publicKey);
|
|
377
379
|
if (currentTrust.approvers.some((approver) => approver.keyId === root.keyId))
|
|
378
380
|
throw new Error('The new root key is listed as an approver; remove it first');
|
|
379
381
|
const issuedAt = truncateToSecond(options.now);
|
|
@@ -393,8 +395,9 @@ export async function adoptTrustDocuments(options) {
|
|
|
393
395
|
};
|
|
394
396
|
const trustBytes = signTrustRoot(trustRoot, root.privateKey);
|
|
395
397
|
const listBytes = signRevocations(revocations, root.privateKey);
|
|
396
|
-
|
|
397
|
-
await writeFileAtomic(options.
|
|
398
|
+
// Each file is replaced only if it is still the one that was read and re-signed (like every other root write).
|
|
399
|
+
await writeFileAtomic(options.trustRootPath, trustBytes, undefined, { expectSha256: `sha256:${sha256Hex(trustRead)}` });
|
|
400
|
+
await writeFileAtomic(options.revocationsPath, listBytes, undefined, { expectSha256: `sha256:${sha256Hex(listRead)}` });
|
|
398
401
|
return { trustRoot, trustRootVersion: trustRoot.version, revocationsVersion: revocations.version };
|
|
399
402
|
}
|
|
400
403
|
export { recoverySetJson };
|
|
@@ -95,6 +95,8 @@ export declare function parseRootEventLog(bytes: Uint8Array): Array<MultiEnvelop
|
|
|
95
95
|
/**
|
|
96
96
|
* Walks the root event log from the policy's starting point. Throws (the log is UNVERIFIABLE) if any event after
|
|
97
97
|
* `eventsAfter` breaks a rule; events are never skipped. Hashes every event so rollback and fork checks can use them.
|
|
98
|
+
* Keys that left a role in the events before `eventsAfter` are read without checking signatures and used only to refuse
|
|
99
|
+
* (see keysLeftBeforeStart).
|
|
98
100
|
*/
|
|
99
101
|
export declare function walkRootEvents(bytes: Uint8Array, start: RootStart, now: Date): RootWalk;
|
|
100
102
|
/**
|
package/dist/src/root-events.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// policy, signs numbered root events that revoke or replace the root key. Hosts walk the log from the policy's
|
|
3
3
|
// starting point at every trust check; one event that breaks a rule makes the whole log UNVERIFIABLE.
|
|
4
4
|
import { sign, verify } from 'node:crypto';
|
|
5
|
-
import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
|
|
5
|
+
import { canonicalBytes, exactKeys, isRecord, readableCanonicalBytes, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
|
|
6
6
|
import { preAuthEncoding } from "./dsse.js";
|
|
7
7
|
import { parseSpki, validateKeyId } from "./keys.js";
|
|
8
8
|
import { CLOCK_SKEW_MS, formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
|
|
@@ -177,7 +177,7 @@ export function emptyRootEventLog() {
|
|
|
177
177
|
return canonicalBytes({ events: [], type: ROOT_EVENTS_TYPE });
|
|
178
178
|
}
|
|
179
179
|
export function rootEventLogBytes(envelopes) {
|
|
180
|
-
return
|
|
180
|
+
return readableCanonicalBytes({ events: envelopes, type: ROOT_EVENTS_TYPE }, 'The root event log');
|
|
181
181
|
}
|
|
182
182
|
/** `sha256:` + the SHA-256 of the envelope as canonical JSON with its trailing LF (the host state's event_digest). */
|
|
183
183
|
export function eventDigest(envelope) {
|
|
@@ -307,9 +307,65 @@ function applyEvent(state, envelope, sequence, now) {
|
|
|
307
307
|
}
|
|
308
308
|
return next;
|
|
309
309
|
}
|
|
310
|
+
/**
|
|
311
|
+
* Keys that left a role in the events before `root_events_after`. Those events are not checked (the policy pins the
|
|
312
|
+
* state after them, not the keys that signed them), so what they say is used only to refuse: a key named here can never
|
|
313
|
+
* be an approver or take a role in a walked event, and nothing is ever accepted because of them. Someone who can change
|
|
314
|
+
* the log can make a host refuse more, which they can already do by deleting the log; with freshness, the timestamp
|
|
315
|
+
* covers the whole file anyway. An event here that retires a key the policy pins contradicts the policy and throws.
|
|
316
|
+
*/
|
|
317
|
+
function keysLeftBeforeStart(envelopes, start) {
|
|
318
|
+
const retired = new Set();
|
|
319
|
+
const formerRecovery = new Set();
|
|
320
|
+
let recovery = null;
|
|
321
|
+
let timestampKeyId = null;
|
|
322
|
+
for (let index = 0; index < start.eventsAfter; index += 1) {
|
|
323
|
+
const label = `root event ${index + 1} (before root_events_after)`;
|
|
324
|
+
const envelope = envelopes[index];
|
|
325
|
+
if (envelope.payloadType !== ROOT_EVENT_PAYLOAD_TYPE)
|
|
326
|
+
throw new Error(`${label} has the wrong payload type`);
|
|
327
|
+
let event;
|
|
328
|
+
try {
|
|
329
|
+
event = parseRootEventPayload(envelope.payloadBytes);
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
throw new Error(`${label}: ${error.message}`);
|
|
333
|
+
}
|
|
334
|
+
if (event.sequence !== index + 1)
|
|
335
|
+
throw new Error(`${label} carries sequence ${event.sequence}`);
|
|
336
|
+
if (event.action === 'revoke') {
|
|
337
|
+
retired.add(event.rootKeyId);
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
const newRecovery = event.newRecovery.keyIds;
|
|
341
|
+
if (event.newRoot.keyId !== event.rootKeyId)
|
|
342
|
+
retired.add(event.rootKeyId);
|
|
343
|
+
if (event.newTimestamp) {
|
|
344
|
+
if (timestampKeyId !== null && timestampKeyId !== event.newTimestamp.keyId)
|
|
345
|
+
retired.add(timestampKeyId);
|
|
346
|
+
timestampKeyId = event.newTimestamp.keyId;
|
|
347
|
+
}
|
|
348
|
+
// Signers not in the new set come from the set this event replaces, as does every key of an earlier new set.
|
|
349
|
+
for (const keyId of [...event.signers.map((key) => key.keyId), ...(recovery ?? [])])
|
|
350
|
+
if (!newRecovery.includes(keyId))
|
|
351
|
+
formerRecovery.add(keyId);
|
|
352
|
+
recovery = newRecovery;
|
|
353
|
+
}
|
|
354
|
+
for (const keyId of recovery ?? [])
|
|
355
|
+
if (!start.recovery.keyIds.includes(keyId))
|
|
356
|
+
formerRecovery.add(keyId);
|
|
357
|
+
for (const keyId of retired) {
|
|
358
|
+
const pinned = keyId === start.rootKeyId ? 'root' : keyId === start.timestampKeyId ? 'timestamp' : start.recovery.keyIds.includes(keyId) ? 'recovery' : null;
|
|
359
|
+
if (pinned)
|
|
360
|
+
throw new Error(`the events before root_events_after show key ${keyId} leaving the root or timestamp role, but the policy pins it as the ${pinned} key`);
|
|
361
|
+
}
|
|
362
|
+
return { retired, formerRecovery };
|
|
363
|
+
}
|
|
310
364
|
/**
|
|
311
365
|
* Walks the root event log from the policy's starting point. Throws (the log is UNVERIFIABLE) if any event after
|
|
312
366
|
* `eventsAfter` breaks a rule; events are never skipped. Hashes every event so rollback and fork checks can use them.
|
|
367
|
+
* Keys that left a role in the events before `eventsAfter` are read without checking signatures and used only to refuse
|
|
368
|
+
* (see keysLeftBeforeStart).
|
|
313
369
|
*/
|
|
314
370
|
export function walkRootEvents(bytes, start, now) {
|
|
315
371
|
requireValidDate(now, 'Verification time');
|
|
@@ -317,13 +373,14 @@ export function walkRootEvents(bytes, start, now) {
|
|
|
317
373
|
const envelopes = parseRootEventLog(bytes);
|
|
318
374
|
if (envelopes.length < start.eventsAfter)
|
|
319
375
|
throw new Error(`root event log has ${envelopes.length} event(s), fewer than root_events_after (${start.eventsAfter})`);
|
|
376
|
+
const before = keysLeftBeforeStart(envelopes, start);
|
|
320
377
|
let state = {
|
|
321
378
|
activeRootKeyId: start.rootKeyId,
|
|
322
379
|
recovery: start.recovery,
|
|
323
380
|
timestampKeyId: start.timestampKeyId,
|
|
324
381
|
revoked: null,
|
|
325
|
-
retired:
|
|
326
|
-
formerRecovery:
|
|
382
|
+
retired: before.retired,
|
|
383
|
+
formerRecovery: before.formerRecovery,
|
|
327
384
|
lastIssuedAt: null,
|
|
328
385
|
};
|
|
329
386
|
for (let index = start.eventsAfter; index < envelopes.length; index += 1)
|
|
@@ -2,6 +2,12 @@ import { type BigIntStats } from 'node:fs';
|
|
|
2
2
|
export declare const TREE_PROFILE = "mago.skill-tree/v2";
|
|
3
3
|
export declare const CERTIFICATE_FILENAME = ".mago-ski-cert.json";
|
|
4
4
|
export declare const IGNORE_FILENAME = ".skilldigestignore";
|
|
5
|
+
/**
|
|
6
|
+
* The paths a `.skilldigestignore` keeps out of the digest (the built-in exclusions, `.git/` and the certificate file, are
|
|
7
|
+
* left out). A certificate says nothing about these: they can change, or be added, without invalidating it. Every command
|
|
8
|
+
* that tells a person "approved" or "unchanged" must show them.
|
|
9
|
+
*/
|
|
10
|
+
export declare function pathsNotCovered(excluded: readonly string[]): string[];
|
|
5
11
|
/** Always covered: it holds the instructions and the description hosts show the model. */
|
|
6
12
|
export declare const SKILL_FILENAME = "SKILL.md";
|
|
7
13
|
export declare const MAX_TREE_FILES = 20000;
|
package/dist/src/tree-digest.js
CHANGED
|
@@ -6,6 +6,14 @@ import { canonicalBytes } from "./canonical-json.js";
|
|
|
6
6
|
export const TREE_PROFILE = 'mago.skill-tree/v2';
|
|
7
7
|
export const CERTIFICATE_FILENAME = '.mago-ski-cert.json';
|
|
8
8
|
export const IGNORE_FILENAME = '.skilldigestignore';
|
|
9
|
+
/**
|
|
10
|
+
* The paths a `.skilldigestignore` keeps out of the digest (the built-in exclusions, `.git/` and the certificate file, are
|
|
11
|
+
* left out). A certificate says nothing about these: they can change, or be added, without invalidating it. Every command
|
|
12
|
+
* that tells a person "approved" or "unchanged" must show them.
|
|
13
|
+
*/
|
|
14
|
+
export function pathsNotCovered(excluded) {
|
|
15
|
+
return excluded.filter((item) => item !== '.git/' && item !== CERTIFICATE_FILENAME);
|
|
16
|
+
}
|
|
9
17
|
/** Always covered: it holds the instructions and the description hosts show the model. */
|
|
10
18
|
export const SKILL_FILENAME = 'SKILL.md';
|
|
11
19
|
export const MAX_TREE_FILES = 20_000;
|
|
@@ -34,6 +34,6 @@ When `loadPolicyTrust` fails, report it once for the host (`trustFailureRecord`)
|
|
|
34
34
|
|
|
35
35
|
The [Claude Code spike](../spikes/claude-code-interception.md) found that no hook can change the Skill list (H1) and that a project's settings can turn user hooks off, so enforcement needs managed settings. Without them, only shadow mode is possible.
|
|
36
36
|
|
|
37
|
-
The company gate (`src/gate/`, Linux only,
|
|
37
|
+
The company gate (`src/gate/`, Linux only, from 0.4.0) follows that finding with one change of store. Instead of a mago-ski plugin holding verified copies (the spike's proposal), the gate service installs approved Skills into Claude Code's admin-managed Skill folder (each `<folder>/<name>` is a link to the verified, read-only copy, removed on uninstall or revocation), and the generated managed settings (`src/gate/adapters/claude-code-settings.ts`) set `strictPluginOnlyCustomization: ["skills", "hooks", "agents", "mcp"]`, an empty `strictKnownMarketplaces` and `disableSideloadFlags`, so only managed-folder Skills load. Managed `PreToolUse` (Skill tool) and `UserPromptExpansion` (`/name`) hooks ask the service about every use (H2–H5) and block when it cannot answer. The plugin store stays a possible alternative; both kinds of Skill ran under the lock in our earlier tests. The [live test](../spikes/claude-code-gate-live.md) ran this setup against the real Claude Code 2.1.318 in non-interactive mode (`-p`), with the real service and hook: only gate-installed Skills (symlinks in the managed folder) were listed and loaded, planted and revoked Skills were denied by the hooks, and with the service stopped every use was denied. It passed as root and with Claude Code running as an unprivileged user. Interactive sessions and subagents are not covered by it yet.
|
|
38
38
|
|
|
39
39
|
The same gate serves Codex through `/etc/codex/requirements.toml` and the Codex hook adapter. Its [live test](../spikes/codex-gate-live.md) (codex-cli 0.163.0 and 0.166.0) shows weaker coverage. Codex has no Skill lock, and `deny_read` does not hide user Skills from its catalog, so repo and user Skills stay listed and only the hooks stop their use. The hooks did block every route tested, and failed closed. Because Codex always installs its own bundled Skills, an admin Skill can be invoked only by its linked mention `[$name](/etc/codex/skills/name/SKILL.md)`, never by a bare `$name`.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Claude Code host (the company gate)
|
|
2
|
+
|
|
3
|
+
The company gate is a root service that installs approved Skills into an admin-owned folder and answers Claude Code's hooks each time a Skill is used. It is set up with the `mago-ski gate` commands. Linux only. Tested with Claude Code 2.1.318 in non-interactive (`claude -p`) sessions ([live test](../spikes/claude-code-gate-live.md)); the managed settings need Claude Code 2.1.296 or newer.
|
|
4
|
+
|
|
5
|
+
Codex has its own guide: [codex.md](codex.md).
|
|
6
|
+
|
|
7
|
+
## What you need
|
|
8
|
+
|
|
9
|
+
- Linux with systemd, and root.
|
|
10
|
+
- Node.js and the `mago-ski` package installed system-wide, in root-owned folders. `gate init` refuses a per-user install (nvm, volta) and any package, node or host binary a user could edit, because an editable hook would let a user bypass the gate.
|
|
11
|
+
- The real `claude` binary, root-owned.
|
|
12
|
+
- Your organisation's root fingerprint (printed by `mago-ski root init`), its `trust-root.json` and `revocations.json`, and a certificate for each Skill you want to install.
|
|
13
|
+
|
|
14
|
+
## Set up
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
# 1. See what would be written. Writes nothing, needs no root.
|
|
18
|
+
mago-ski gate init --host claude-code --root-fingerprint sha256:… --print
|
|
19
|
+
|
|
20
|
+
# 2. Write it. The default mode is shadow: decisions are logged, nothing is blocked.
|
|
21
|
+
sudo mago-ski gate init --host claude-code --root-fingerprint sha256:…
|
|
22
|
+
|
|
23
|
+
# 3. Start the service (gate init prints these commands; it never runs systemctl itself).
|
|
24
|
+
sudo systemctl daemon-reload && sudo systemctl enable --now mago-ski-gate@claude-code
|
|
25
|
+
|
|
26
|
+
# 4. Give the gate the organisation's trust documents.
|
|
27
|
+
sudo mago-ski gate trust --host claude-code --trust-root trust-root.json --revocations revocations.json
|
|
28
|
+
|
|
29
|
+
# 5. Install an approved Skill version.
|
|
30
|
+
sudo mago-ski gate install --host claude-code skills/docs-helper --certificate docs-helper.cert.json
|
|
31
|
+
|
|
32
|
+
# 6. Check the whole installation.
|
|
33
|
+
sudo mago-ski gate doctor --host claude-code
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`gate init` writes, all root-owned:
|
|
37
|
+
|
|
38
|
+
| File or folder | Purpose |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `/etc/mago-ski/gate/claude-code.json` | The instance config: mode, root fingerprint, host binaries, folders |
|
|
41
|
+
| `/etc/mago-ski/gate/claude-code-hook.json` | What the hook reads to find the gate |
|
|
42
|
+
| `/etc/mago-ski/gate/claude-code.manifest.json`, `shared.manifest.json` | Which files mago-ski wrote, so a later `gate init` can tell its own files from yours |
|
|
43
|
+
| `/etc/systemd/system/mago-ski-gate@.service` and `mago-ski-gate@claude-code.service.d/paths.conf` | The service unit |
|
|
44
|
+
| `/etc/claude-code/managed-settings.json` | Claude Code's managed settings: the hooks, and in enforce mode the locks |
|
|
45
|
+
| `/etc/claude-code/.claude/skills/` | The managed Skill folder. Each installed Skill is a link to an immutable copy |
|
|
46
|
+
| `/var/lib/mago-ski/gate/claude-code/` | The gate's state, the published Skill versions and the decision log |
|
|
47
|
+
|
|
48
|
+
If one of the host files already exists and mago-ski did not write it, `gate init` stops. `--force` moves the existing file aside to `<file>.mago-ski-bak-<time>` and replaces it.
|
|
49
|
+
|
|
50
|
+
## Shadow first, then enforce
|
|
51
|
+
|
|
52
|
+
Run in shadow mode until the decision log shows only what you expect to be blocked. Then:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
sudo mago-ski gate init --host claude-code --root-fingerprint sha256:… --mode enforce
|
|
56
|
+
sudo systemctl daemon-reload && sudo systemctl restart mago-ski-gate@claude-code
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Enforce mode applies Claude Code's managed locks to **every user of this machine**: project Skills, user Skills and Claude Code's bundled Skills are no longer listed.
|
|
60
|
+
|
|
61
|
+
## What it does
|
|
62
|
+
|
|
63
|
+
| Situation | Enforce mode | Shadow mode |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| A Skill installed by the gate, through the Skill tool or `/name` | Allowed; the hook asks the gate each time | Allowed |
|
|
66
|
+
| A project, user or bundled Skill | Not listed by Claude Code and cannot be loaded (managed lock) | Listed and runs; nothing is blocked |
|
|
67
|
+
| A Skill copied into the managed folder without `gate install` | Claude Code lists it; the hook denies it (`NO_CERTIFICATE`) | Logged |
|
|
68
|
+
| An installed Skill whose approval is revoked | Removed from the managed folder by the gate. A session that was already open is denied at the next use; the session itself keeps running | Removed (a revocation uninstalls in every mode) |
|
|
69
|
+
| An installed Skill whose approval expired, or whose files no longer match | Blocked, and hidden at the next check (at most about 60 seconds later) | Logged |
|
|
70
|
+
| The gate service is down or cannot verify | Blocked: `mago-ski could not verify this Skill; it is blocked until verification works.` | Allowed |
|
|
71
|
+
| A Skill folder that contains a second `SKILL.md` below the top level | `gate install` refuses it, because the nested Skill would be loaded without being approved | Refused at install too |
|
|
72
|
+
|
|
73
|
+
A blocked user sees `This Skill is not approved by your organisation (mago-ski: <verdict>). If it was updated, restart the session to use the new version.`
|
|
74
|
+
|
|
75
|
+
Every decision is written to the gate's decision log, which only root can read.
|
|
76
|
+
|
|
77
|
+
## Keeping it current
|
|
78
|
+
|
|
79
|
+
- **New trust root or revocation list:** `sudo mago-ski gate trust --host claude-code --trust-root FILE --revocations FILE`. A revocation takes effect when the gate receives it.
|
|
80
|
+
- **An inbox instead:** create the instance with `gate init --inbox DIR` and let your distribution drop `trust-root.json` and `revocations.json` there (root-owned, not group- or world-writable). The gate reads the folder about once a minute, or at once with `sudo mago-ski gate refresh --host claude-code`.
|
|
81
|
+
- **Remove a Skill:** `sudo mago-ski gate uninstall --host claude-code NAME`.
|
|
82
|
+
- **State:** `sudo mago-ski gate status --host claude-code` shows the mode, readiness, trust and when the revocation list expires. `gate doctor` prints PASS, FAIL, SKIP or WARN for each check and exits 1 on a FAIL.
|
|
83
|
+
|
|
84
|
+
## After a root rotation
|
|
85
|
+
|
|
86
|
+
The gate does not follow root events by itself. When your organisation has replaced its root key and re-signed its documents (`mago-ski root adopt`), move each gate to the new root:
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
sudo mago-ski gate init --host claude-code --root-fingerprint sha256:<new> --new-root # with the same options as your original init
|
|
90
|
+
sudo systemctl daemon-reload && sudo systemctl restart mago-ski-gate@claude-code
|
|
91
|
+
sudo mago-ski gate trust --host claude-code --trust-root trust-root.json --revocations revocations.json
|
|
92
|
+
sudo mago-ski gate doctor --host claude-code
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
- `gate init` refuses a root fingerprint that differs from the installed one unless `--new-root` is given, so a mistyped fingerprint cannot switch roots by accident. `--print` shows the move without writing anything.
|
|
96
|
+
- Between the restart and `gate trust`, the gate has no documents for the new root. In enforce mode every Skill is blocked during that time, so run the commands together.
|
|
97
|
+
- Installed Skills do not need to be installed again. Their certificates were signed by approvers, and the approvers are kept.
|
|
98
|
+
- The old root's stored documents are kept and no longer used.
|
|
99
|
+
|
|
100
|
+
## Limits
|
|
101
|
+
|
|
102
|
+
- **Linux only.** macOS and Windows are not supported by the gate.
|
|
103
|
+
- **Tested on Claude Code 2.1.318, non-interactive sessions only.** Whether an interactive session reloads its Skill list when the managed folder changes, and whether a subagent's Skill calls reach the managed hook, are not tested yet.
|
|
104
|
+
- **Instructions already read stay.** The gate cannot remove a Skill's text from a session that has already loaded it. A revoked Skill is blocked at its next use, not unread.
|
|
105
|
+
- **After a revoke, the reason shown is `NO_CERTIFICATE`,** not `REVOKED`, because the gate has already removed the Skill. The block is correct; the wording is not.
|
|
106
|
+
- **A user who can run a different Claude Code binary,** or change the machine's managed settings, is outside what the gate controls. Use your organisation's execution control for that.
|
|
107
|
+
- **The gate does not follow root events or timestamps by itself.** It keeps the root fingerprint it was given, so a rotated or revoked root key is not noticed until an administrator moves the gate (see [After a root rotation](#after-a-root-rotation)). On a fleet, that means running the four commands on every machine.
|
|
108
|
+
- An approval records who approved which exact version. It does not say that a Skill is safe.
|