@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
package/dist/src/gate/service.js
CHANGED
|
@@ -84,10 +84,10 @@
|
|
|
84
84
|
// and are NOT logged, so a local user flooding the world-accessible socket cannot rotate older records out of the decision
|
|
85
85
|
// log faster than that rate allows for each uid it can name (default 10/s: about 4 KiB/s of records per named uid).
|
|
86
86
|
import { createHash, randomBytes } from 'node:crypto';
|
|
87
|
-
import { chmod, lstat, mkdir, readdir, readFile, rename, symlink, unlink } from 'node:fs/promises';
|
|
87
|
+
import { chmod, lstat, mkdir, readdir, readFile, readlink, rename, rm, symlink, unlink } from 'node:fs/promises';
|
|
88
88
|
import net from 'node:net';
|
|
89
89
|
import path from 'node:path';
|
|
90
|
-
import { isRecord, MAX_CANONICAL_JSON_BYTES } from "../canonical-json.js";
|
|
90
|
+
import { isRecord, MAX_CANONICAL_JSON_BYTES, serializeCanonicalJson } from "../canonical-json.js";
|
|
91
91
|
import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
|
|
92
92
|
import { validateDigest, validateSkillName } from "../names.js";
|
|
93
93
|
import { formatTimestamp } from "../time.js";
|
|
@@ -95,17 +95,25 @@ import { evaluateCertificate, VERDICT_RANK } from "../verify.js";
|
|
|
95
95
|
import { openDecisionLog } from "./decision-log.js";
|
|
96
96
|
import { MAX_SESSIONS, openAdmissionStore } from "./admission.js";
|
|
97
97
|
import { parseGateRequest, serializeGateResult } from "./contract.js";
|
|
98
|
+
import { plainNameLine } from "./adapters/codex-names.js";
|
|
98
99
|
import { installSkill } from "./generations.js";
|
|
99
100
|
import { assertGatePlatform, bootId, bootMs, NotLiveError, nofileSoftLimit, processFacts, processInfo } from "./proc.js";
|
|
100
101
|
import { parseStrictJson, DEFAULT_STRICT_JSON_LIMITS } from "./strict-json.js";
|
|
101
102
|
import { readInbox } from "./refresh.js";
|
|
102
|
-
import { openTrustStore } from "./trust-store.js";
|
|
103
|
+
import { migrateFlatTrustStore, openTrustStore } from "./trust-store.js";
|
|
103
104
|
const SESSION = /^pid:([1-9][0-9]{0,9})$/u;
|
|
104
105
|
const DELETED = ' (deleted)';
|
|
105
106
|
const MAX_CERT_BYTES = 256 * 1024;
|
|
106
107
|
const MAX_CERTS_PER_DIGEST = 16;
|
|
107
108
|
const ADMIN_LIMITS = { maxBytes: 12 * 1024 * 1024, maxDepth: 4, maxMembers: 8, maxStringLength: 6 * 1024 * 1024 };
|
|
108
109
|
const hex = (digest) => validateDigest(digest).slice('sha256:'.length);
|
|
110
|
+
export const REMOVED_NAMES_FILE = '.mago-ski-removed-names.json';
|
|
111
|
+
export const REMOVED_NAMES_TYPE = 'mago-ski.gate.removed-names.v1';
|
|
112
|
+
export const REMOVED_NAMES_CAP = 4096;
|
|
113
|
+
const REMOVED_NAMES_READ_LIMIT = 1024 * 1024;
|
|
114
|
+
const REMOVED_LIMITS = { maxBytes: REMOVED_NAMES_READ_LIMIT, maxDepth: 4, maxMembers: REMOVED_NAMES_CAP + 4, maxStringLength: 1024 };
|
|
115
|
+
const MAX_SKILL_MD_BYTES = 64 * 1024;
|
|
116
|
+
const NAME_REFUSAL = (name) => `SKILL.md must start its frontmatter with one plain line "name: ${name}" so every host names it the same`;
|
|
109
117
|
function b64(value, label, max) {
|
|
110
118
|
if (typeof value !== 'string')
|
|
111
119
|
throw new Error(`${label} must be a base64 string`);
|
|
@@ -118,6 +126,17 @@ function onlyKeys(c, keys) {
|
|
|
118
126
|
if (c['v'] !== 1 || Object.keys(c).some((k) => k !== 'v' && k !== 'cmd' && !keys.includes(k)) || keys.some((k) => !Object.hasOwn(c, k)))
|
|
119
127
|
throw new Error('command has missing or unknown fields');
|
|
120
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* The trust store of one root: `<stateDir>/trust/<64 hex of the root fingerprint>` (design gate-new-root.md N1). Each root has
|
|
131
|
+
* its own documents and its own rollback memory, so moving an instance to a new root never reads, changes or removes the
|
|
132
|
+
* old root's state, and moving back finds it as it was.
|
|
133
|
+
*/
|
|
134
|
+
export function trustStoreDir(stateDir, rootFingerprint) {
|
|
135
|
+
const m = /^sha256:([0-9a-f]{64})$/u.exec(rootFingerprint);
|
|
136
|
+
if (!m)
|
|
137
|
+
throw new Error('root fingerprint must be sha256:<64 lower-case hex>');
|
|
138
|
+
return path.join(stateDir, 'trust', m[1]);
|
|
139
|
+
}
|
|
121
140
|
async function ownedDir(dir, uid, mode, strict) {
|
|
122
141
|
await mkdir(dir, { mode }).catch((e) => { if (e?.code !== 'EEXIST')
|
|
123
142
|
throw e; });
|
|
@@ -142,6 +161,7 @@ async function listen(server, file, mode) {
|
|
|
142
161
|
await unlink(file);
|
|
143
162
|
}
|
|
144
163
|
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(file, 4096, () => { server.off('error', reject); resolve(); }); });
|
|
164
|
+
// nosemgrep: mago-no-path-chown-chmod -- the service's own socket, just made by listen() in a root-owned socket folder
|
|
145
165
|
await chmod(file, mode);
|
|
146
166
|
}
|
|
147
167
|
/** One request line per connection: read to the first newline (bounded, idle deadline), reply with one line, close. Anything else just closes. */
|
|
@@ -221,6 +241,7 @@ export function createGateService(config) {
|
|
|
221
241
|
let trust;
|
|
222
242
|
let admission;
|
|
223
243
|
let ready = false;
|
|
244
|
+
let startError;
|
|
224
245
|
const servers = [];
|
|
225
246
|
const live = new Set();
|
|
226
247
|
let queue = Promise.resolve();
|
|
@@ -291,6 +312,7 @@ export function createGateService(config) {
|
|
|
291
312
|
});
|
|
292
313
|
let reaper;
|
|
293
314
|
let refresher;
|
|
315
|
+
let reconciler;
|
|
294
316
|
/** Engine verdict for exactly this Skill name and digest under the trust context of this moment. */
|
|
295
317
|
const verdictCache = new Map();
|
|
296
318
|
const CACHE_TTL_MS = 1000;
|
|
@@ -512,53 +534,284 @@ export function createGateService(config) {
|
|
|
512
534
|
throw e;
|
|
513
535
|
}
|
|
514
536
|
}
|
|
515
|
-
// REFRESH + RECONCILE (admin queue only
|
|
516
|
-
// nothing and extends nothing. Reconcile then re-checks the
|
|
517
|
-
//
|
|
518
|
-
//
|
|
537
|
+
// REFRESH + RECONCILE (admin queue only; the periodic one too, design codex-profile.md E2, F1, F2, F6.4, F7.1). The inbox is
|
|
538
|
+
// offered to the trust store; a rejected or unreadable inbox changes nothing and extends nothing. Reconcile then re-checks the
|
|
539
|
+
// CURRENT generation of every installed Skill (cache bypassed). SERVABLE = VERIFIED, no nested SKILL.md, plain `name:` equal
|
|
540
|
+
// to the install name. ENFORCE: a non-VERIFIED Skill is uninstalled (name recorded in the removed-names file first, no
|
|
541
|
+
// fallback to an older generation); a VERIFIED but not servable one, or one whose evidence cannot be read, is HIDDEN (link
|
|
542
|
+
// removed, install kept); when trust is not ready every installed Skill is hidden (fail closed), and re-linked once trust
|
|
543
|
+
// is ready again, only if servable. Every uninstall, hide and restore is a durable decision-log record of event `reconcile`.
|
|
544
|
+
// SHADOW: a REVOKED Skill is uninstalled as in enforce (a revocation uninstalls in every mode, F6.4); nothing else is
|
|
545
|
+
// uninstalled or hidden: would-uninstall / would-hide are logged once and listed in status.
|
|
546
|
+
// Reconcile also sweeps `managedDir` for entries with no install record (sweepUnrecorded): the folder is what hosts see.
|
|
519
547
|
const refreshStatus = { atBootMs: null, result: 'never' };
|
|
520
548
|
let autoUninstalled = [];
|
|
521
549
|
let wouldUninstall = [];
|
|
550
|
+
let nameMismatch = [];
|
|
551
|
+
let unrecorded = []; // managedDir entries with no install record that hosts can still see (see sweepUnrecorded)
|
|
552
|
+
const hidden = new Map(); // names hidden by reconcile in this process, with the reason
|
|
553
|
+
const loggedWould = new Set();
|
|
554
|
+
const removedStatus = { count: 0, full: false, evicted: 0, error: null };
|
|
522
555
|
let reconcileError = null; // last reconcile failure (decisions still deny per digest; this is visibility)
|
|
556
|
+
const removedFile = path.join(managedDir, REMOVED_NAMES_FILE);
|
|
557
|
+
async function readRemoved() {
|
|
558
|
+
let bytes;
|
|
559
|
+
try {
|
|
560
|
+
bytes = await readRegularFile(removedFile, 'removed names', REMOVED_NAMES_READ_LIMIT);
|
|
561
|
+
}
|
|
562
|
+
catch (e) {
|
|
563
|
+
if (['ENOENT', 'ENOTDIR'].includes(e.code ?? ''))
|
|
564
|
+
return [];
|
|
565
|
+
throw e;
|
|
566
|
+
}
|
|
567
|
+
const raw = parseStrictJson(bytes, REMOVED_LIMITS);
|
|
568
|
+
if (!isRecord(raw) || raw['type'] !== REMOVED_NAMES_TYPE || !Array.isArray(raw['entries']))
|
|
569
|
+
throw new Error('removed-names file is malformed');
|
|
570
|
+
return raw['entries'].map((e) => {
|
|
571
|
+
if (!isRecord(e) || typeof e['name'] !== 'string' || typeof e['digest'] !== 'string' || typeof e['at'] !== 'string' || (e['kind'] !== 'revoked' && e['kind'] !== 'uninstalled'))
|
|
572
|
+
throw new Error('removed-names entry is malformed');
|
|
573
|
+
return { name: e['name'], digest: e['digest'], kind: e['kind'], at: e['at'] };
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
async function writeRemoved(entries) {
|
|
577
|
+
removedStatus.count = entries.length;
|
|
578
|
+
await writeFileAtomic(removedFile, Buffer.from(serializeCanonicalJson({ type: REMOVED_NAMES_TYPE, entries }), 'utf8'), 0o644);
|
|
579
|
+
}
|
|
580
|
+
/** Records name and digest before the link is removed. Never throws (revocation never fails because of this file): a failure shows in status. */
|
|
581
|
+
async function recordRemoved(name, digest, kind) {
|
|
582
|
+
try {
|
|
583
|
+
let entries = (await readRemoved()).filter((e) => !(e.name === name && e.digest === hex(digest)));
|
|
584
|
+
entries.push({ name, digest: hex(digest), kind, at: formatTimestamp(now()) });
|
|
585
|
+
if (entries.length > REMOVED_NAMES_CAP) { // full: the oldest entries go; blocking rests on the link, so only the message is lost
|
|
586
|
+
const drop = entries.length - REMOVED_NAMES_CAP;
|
|
587
|
+
entries = [...entries].sort((x, y) => (x.at < y.at ? -1 : x.at > y.at ? 1 : 0)).slice(drop);
|
|
588
|
+
removedStatus.full = true;
|
|
589
|
+
removedStatus.evicted += drop;
|
|
590
|
+
}
|
|
591
|
+
await writeRemoved(entries);
|
|
592
|
+
removedStatus.error = null;
|
|
593
|
+
}
|
|
594
|
+
catch (e) {
|
|
595
|
+
removedStatus.error = e instanceof Error ? e.message.slice(0, 200) : 'failed';
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
async function forgetRemoved(name) {
|
|
599
|
+
try {
|
|
600
|
+
const entries = await readRemoved();
|
|
601
|
+
const kept = entries.filter((e) => e.name !== name);
|
|
602
|
+
if (kept.length !== entries.length)
|
|
603
|
+
await writeRemoved(kept);
|
|
604
|
+
removedStatus.error = null;
|
|
605
|
+
}
|
|
606
|
+
catch (e) {
|
|
607
|
+
removedStatus.error = e instanceof Error ? e.message.slice(0, 200) : 'failed';
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
/** One durable decision-log record of event `reconcile`; a failure is counted like any best-effort record. */
|
|
611
|
+
async function logReconcile(result, skill, digest, versions, action = mode === 'shadow' ? 'observe' : 'deny') {
|
|
612
|
+
try {
|
|
613
|
+
const log = await getLog();
|
|
614
|
+
await log.append({
|
|
615
|
+
bootMs: await bootMs(), mode, action, event: 'reconcile', session: null, skill,
|
|
616
|
+
digests: digest ? [digest] : [], trustRootVersion: versions?.trustRootVersion ?? null, revocationsVersion: versions?.revocationsVersion ?? null,
|
|
617
|
+
result, build: config.buildId ?? 'gate-service/v1', elapsedMs: 0,
|
|
618
|
+
}, true);
|
|
619
|
+
logHealthy = true;
|
|
620
|
+
}
|
|
621
|
+
catch {
|
|
622
|
+
logHealthy = false;
|
|
623
|
+
degradedCount++;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
const logOnce = async (key, result, skill, digest) => {
|
|
627
|
+
if (loggedWould.has(key))
|
|
628
|
+
return;
|
|
629
|
+
loggedWould.add(key);
|
|
630
|
+
await logReconcile(result, skill, digest);
|
|
631
|
+
};
|
|
632
|
+
/** Why a generation is not servable (nested SKILL.md, a name that is not the install name), or null. Reads the generation that is linked. */
|
|
633
|
+
async function notServable(name, digest) {
|
|
634
|
+
const dir = path.join(generationsDir, name, hex(digest));
|
|
635
|
+
const nested = await nestedSkillFile(dir);
|
|
636
|
+
if (nested !== null)
|
|
637
|
+
return `nested SKILL.md at ${nested}`;
|
|
638
|
+
return await plainName(dir) === name ? null : 'name-mismatch';
|
|
639
|
+
}
|
|
640
|
+
async function nestedSkillFile(dir) {
|
|
641
|
+
for (const rel of await readdir(dir, { recursive: true }))
|
|
642
|
+
if (path.basename(rel).toLowerCase() === 'skill.md' && rel !== 'SKILL.md')
|
|
643
|
+
return rel;
|
|
644
|
+
return null;
|
|
645
|
+
}
|
|
646
|
+
async function plainName(dir) {
|
|
647
|
+
try {
|
|
648
|
+
return plainNameLine(await readRegularFile(path.join(dir, 'SKILL.md'), 'SKILL.md', MAX_SKILL_MD_BYTES));
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
/** Removes a generation this install just created (sealed read-only folders need their mode back first). */
|
|
655
|
+
async function removeGeneration(name, digest) {
|
|
656
|
+
const gen = path.join(generationsDir, name, hex(digest));
|
|
657
|
+
// nosemgrep: mago-no-path-chown-chmod -- a generation inside the root-owned generation store, being removed
|
|
658
|
+
for (const e of await readdir(gen, { recursive: true, withFileTypes: true }).catch(() => []))
|
|
659
|
+
if (e.isDirectory())
|
|
660
|
+
await chmod(path.join(e.parentPath, e.name), 0o755).catch(() => { });
|
|
661
|
+
// nosemgrep: mago-no-path-chown-chmod -- a generation inside the root-owned generation store, being removed
|
|
662
|
+
await chmod(gen, 0o755).catch(() => { });
|
|
663
|
+
await rm(gen, { recursive: true, force: true });
|
|
664
|
+
await rm(`${gen}.manifest.json`, { force: true });
|
|
665
|
+
}
|
|
666
|
+
async function linkedTo(name, digest) {
|
|
667
|
+
try {
|
|
668
|
+
return await readlink(path.join(managedDir, name)) === path.join(generationsDir, name, hex(digest));
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
523
674
|
// Never throws: a failure is recorded in status; decisions still evaluate every digest, so this is defence in depth.
|
|
675
|
+
// Every failure of the run is kept (one Skill that cannot be hidden does not stop the others, and is not cleared by them).
|
|
524
676
|
async function reconcileInstalls() {
|
|
677
|
+
const failures = [];
|
|
678
|
+
const gone = [];
|
|
525
679
|
try {
|
|
526
|
-
|
|
527
|
-
reconcileError = null;
|
|
528
|
-
return gone;
|
|
680
|
+
await reconcileOnce(gone, failures);
|
|
529
681
|
}
|
|
530
682
|
catch (error) {
|
|
531
|
-
|
|
532
|
-
return [];
|
|
683
|
+
failures.push(error instanceof Error ? error.message : 'reconcile failed');
|
|
533
684
|
}
|
|
685
|
+
reconcileError = failures.length === 0 ? null : `${failures[0].slice(0, 200)}${failures.length > 1 ? ` (and ${failures.length - 1} more)` : ''}`;
|
|
686
|
+
return gone;
|
|
534
687
|
}
|
|
535
|
-
|
|
536
|
-
|
|
688
|
+
/**
|
|
689
|
+
* Host-visible entries of `managedDir` that no install record covers: a link left by an install that stopped between the
|
|
690
|
+
* link and the record, a stale temp link, a link or folder someone else put there. Hosts list them like any Skill (a Codex
|
|
691
|
+
* menu pick reaches the model with no hook), so reconcile looks at the folder itself, not only at the records. ENFORCE: a
|
|
692
|
+
* link is removed and logged; a real folder is never removed by the gate, so it is reported. SHADOW: logged once, reported.
|
|
693
|
+
*/
|
|
694
|
+
async function sweepUnrecorded(installed, enforce, failures) {
|
|
695
|
+
const left = [];
|
|
696
|
+
for (const e of await readdir(managedDir, { withFileTypes: true })) {
|
|
697
|
+
if (installed.has(e.name) || !(e.isSymbolicLink() || e.isDirectory()))
|
|
698
|
+
continue; // plain files are not Skills
|
|
699
|
+
if (!e.isSymbolicLink()) {
|
|
700
|
+
left.push(e.name);
|
|
701
|
+
failures.push(`${path.join(managedDir, e.name)} is a folder with no install record; the gate does not remove folders, so hosts can still load it`);
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
if (!enforce) {
|
|
705
|
+
left.push(e.name);
|
|
706
|
+
await logOnce(`would-remove-unrecorded|${e.name}`, 'would-remove-unrecorded', e.name, null);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
try {
|
|
710
|
+
await hostLink(e.name, null);
|
|
711
|
+
await logReconcile('remove-unrecorded', e.name, null);
|
|
712
|
+
}
|
|
713
|
+
catch (error) {
|
|
714
|
+
left.push(e.name);
|
|
715
|
+
failures.push(error instanceof Error ? error.message : 'unlink failed');
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
unrecorded = left;
|
|
719
|
+
}
|
|
720
|
+
async function reconcileOnce(gone, failures) {
|
|
537
721
|
wouldUninstall = [];
|
|
538
|
-
if (!trust || !admission
|
|
539
|
-
return
|
|
540
|
-
|
|
722
|
+
if (!trust || !admission)
|
|
723
|
+
return;
|
|
724
|
+
const installed = await admission.installed();
|
|
725
|
+
const current = await trust.current(now());
|
|
726
|
+
const versions = current.ready ? current.versions : undefined;
|
|
727
|
+
const enforce = mode !== 'shadow';
|
|
728
|
+
const mismatched = [];
|
|
729
|
+
const fail = (e, fallback) => { failures.push(e instanceof Error ? e.message : fallback); };
|
|
730
|
+
try {
|
|
731
|
+
await sweepUnrecorded(new Set(installed.map((i) => i.name)), enforce, failures);
|
|
732
|
+
}
|
|
733
|
+
catch (e) {
|
|
734
|
+
fail(e, 'managed folder scan failed');
|
|
735
|
+
}
|
|
736
|
+
const hide = async (name, digest, reason) => {
|
|
737
|
+
if (!enforce) {
|
|
738
|
+
await logOnce(`would-hide|${name}|${digest}|${reason}`, `would-hide:${reason}`, name, digest);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
await hostLink(name, null);
|
|
742
|
+
if (hidden.get(name) !== reason) {
|
|
743
|
+
hidden.set(name, reason);
|
|
744
|
+
await logReconcile(reason.startsWith('trust-') ? `hide-all:${reason}` : `hide:${reason}`, name, digest, versions);
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
if (!current.ready) { // fail closed: nothing can be evaluated, so nothing is served (enforce)
|
|
748
|
+
for (const { name, digest } of installed) {
|
|
749
|
+
try {
|
|
750
|
+
await hide(name, digest, `trust-${current.reason}`);
|
|
751
|
+
}
|
|
752
|
+
catch (e) {
|
|
753
|
+
fail(e, 'hide failed');
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
nameMismatch = [];
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
const one = async (name, digest) => {
|
|
541
760
|
let verdict;
|
|
542
761
|
try {
|
|
543
762
|
verdict = await check(name, digest, undefined, true);
|
|
544
763
|
}
|
|
545
764
|
catch {
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
765
|
+
await hide(name, digest, 'evidence-unreadable');
|
|
766
|
+
return;
|
|
767
|
+
} // unreadable evidence: hidden, not skipped
|
|
768
|
+
if (verdict !== 'VERIFIED') {
|
|
769
|
+
// A revocation uninstalls in every mode (codex-profile.md F6.4): it is a signed decision about this digest, not something
|
|
770
|
+
// to try out. Every other verdict (expired, no longer matching) is only recorded in shadow mode.
|
|
771
|
+
if (!enforce && verdict !== 'REVOKED') {
|
|
772
|
+
wouldUninstall.push({ name, digest, verdict });
|
|
773
|
+
await logOnce(`would-uninstall|${name}|${digest}|${verdict}`, `would-uninstall:${verdict}`, name, digest);
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
await recordRemoved(name, digest, 'revoked'); // before the link goes
|
|
777
|
+
await hostLink(name, null); // hide it from hosts first; a failure leaves the record in place and is reported as reconcileError
|
|
778
|
+
const ms = await bootMs();
|
|
779
|
+
if ((await admission.uninstall(name, ms)).ok) {
|
|
780
|
+
gone.push({ name, digest, verdict });
|
|
781
|
+
hidden.delete(name);
|
|
782
|
+
autoUninstalled = [...autoUninstalled, { name, digest, verdict, bootMs: ms }].slice(-100);
|
|
783
|
+
await logReconcile(`uninstall:${verdict}`, name, digest, versions, 'deny'); // done, also in shadow mode
|
|
784
|
+
}
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
let problem;
|
|
788
|
+
try {
|
|
789
|
+
problem = await notServable(name, digest);
|
|
553
790
|
}
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
791
|
+
catch {
|
|
792
|
+
problem = 'unreadable';
|
|
793
|
+
}
|
|
794
|
+
if (problem !== null) {
|
|
795
|
+
mismatched.push(name);
|
|
796
|
+
await hide(name, digest, problem.startsWith('nested') ? 'nested-skill-md' : problem);
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
if (enforce && (hidden.has(name) || !(await linkedTo(name, digest)))) { // servable again (trust recovered) or never linked: restore
|
|
800
|
+
await hostLink(name, digest);
|
|
801
|
+
hidden.delete(name);
|
|
802
|
+
await logReconcile('restore', name, digest, versions);
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
// One Skill that fails (a link that cannot be removed) is reported and does not stop the others.
|
|
806
|
+
for (const { name, digest } of installed) {
|
|
807
|
+
try {
|
|
808
|
+
await one(name, digest);
|
|
809
|
+
}
|
|
810
|
+
catch (e) {
|
|
811
|
+
fail(e, 'reconcile failed');
|
|
559
812
|
}
|
|
560
813
|
}
|
|
561
|
-
|
|
814
|
+
nameMismatch = mismatched;
|
|
562
815
|
}
|
|
563
816
|
async function refreshNow() {
|
|
564
817
|
let out = { result: 'no-inbox' };
|
|
@@ -585,17 +838,18 @@ export function createGateService(config) {
|
|
|
585
838
|
if (!isRecord(raw) || typeof raw['cmd'] !== 'string')
|
|
586
839
|
throw new Error('command must be an object with cmd');
|
|
587
840
|
if (!ready || !trust || !admission)
|
|
588
|
-
return { ok: false, error:
|
|
841
|
+
return { ok: false, error: `service is not ready${startError ? `: ${startError}` : ''}` };
|
|
589
842
|
switch (raw['cmd']) {
|
|
590
843
|
case 'status': {
|
|
591
844
|
onlyKeys(raw, []);
|
|
592
845
|
const c = await trust.current(now());
|
|
593
846
|
const health = await admission.health(); // also retries a store that could not load at start
|
|
594
847
|
return {
|
|
595
|
-
ok: true, ready: ready && health === 'ready', mode, trust: c.ready ? 'ready' : c.reason, admission: health,
|
|
848
|
+
ok: true, ready: ready && health === 'ready', mode, trust: c.ready ? 'ready' : c.reason, admission: health, root_fingerprint: config.rootFingerprint,
|
|
596
849
|
revocationsExpiresAt: c.ready ? formatTimestamp(c.context.revocations.expiresAt) : null, // the remaining offline window
|
|
597
850
|
log: { state: dlog && logHealthy ? 'ready' : 'degraded', degradedCount, unattributed: { ...unattributed }, rateLimited, ...(dlog?.status() ?? { segment: null, lastSeq: 0, chainBreaks: 0 }) },
|
|
598
|
-
lastRefresh: { ...refreshStatus }, reconcileError, autoUninstalled, wouldUninstall,
|
|
851
|
+
lastRefresh: { ...refreshStatus }, reconcileError, autoUninstalled, wouldUninstall, nameMismatch: [...nameMismatch], unrecorded: [...unrecorded], hidden: [...hidden.keys()],
|
|
852
|
+
removedNames: { count: removedStatus.count, full: removedStatus.full, evicted: removedStatus.evicted, error: removedStatus.error },
|
|
599
853
|
};
|
|
600
854
|
}
|
|
601
855
|
case 'accept-trust': {
|
|
@@ -626,21 +880,61 @@ export function createGateService(config) {
|
|
|
626
880
|
if (!r.ok)
|
|
627
881
|
return { ok: false, error: `${r.reason}: ${r.detail}` };
|
|
628
882
|
const digest = r.manifest.treeDigest;
|
|
883
|
+
// Name and nested-file checks (codex-profile.md C4, E3, E6, F6.2): on the generation that will be linked, before the
|
|
884
|
+
// certificate is stored and before anything is linked. A generation this call created is removed again.
|
|
885
|
+
const gen = path.join(generationsDir, name, hex(digest));
|
|
886
|
+
let refusal = null;
|
|
887
|
+
const nested = await nestedSkillFile(gen).catch(() => 'unreadable');
|
|
888
|
+
if (nested !== null)
|
|
889
|
+
refusal = `the Skill contains another SKILL.md at ${nested}; a nested Skill would be loaded without being approved`;
|
|
890
|
+
else if (await plainName(gen) !== name)
|
|
891
|
+
refusal = NAME_REFUSAL(name);
|
|
892
|
+
if (refusal !== null) {
|
|
893
|
+
if (r.created)
|
|
894
|
+
await removeGeneration(name, digest).catch(() => { });
|
|
895
|
+
return { ok: false, error: refusal };
|
|
896
|
+
}
|
|
629
897
|
await storeCertificate(name, digest, cert);
|
|
630
898
|
await hostLink(name, digest); // hosts can load it from here on
|
|
631
899
|
const p = await stamped((ms) => admission.publish(name, digest, ms)); // after the generation is visible
|
|
632
|
-
if (p.ok)
|
|
900
|
+
if (p.ok) {
|
|
901
|
+
hidden.delete(name);
|
|
902
|
+
await forgetRemoved(name);
|
|
633
903
|
return { ok: true, digest, created: r.created };
|
|
904
|
+
}
|
|
634
905
|
await hostLink(name, null).catch(() => { }); // not recorded: hide it rather than serve unrecorded bytes
|
|
635
906
|
return { ok: false, error: `publish refused: ${p.reason}` };
|
|
636
907
|
}
|
|
637
908
|
case 'uninstall': {
|
|
638
909
|
onlyKeys(raw, ['skill_name']);
|
|
639
910
|
const name = validateSkillName(raw['skill_name']);
|
|
911
|
+
const there = (await admission.installed()).find((i) => i.name === name);
|
|
912
|
+
if (there)
|
|
913
|
+
await recordRemoved(name, there.digest, 'uninstalled'); // before the link goes
|
|
640
914
|
await hostLink(name, null); // hidden from hosts before the record changes
|
|
641
915
|
const u = await admission.uninstall(name, await bootMs());
|
|
916
|
+
hidden.delete(name);
|
|
642
917
|
return u.ok ? { ok: true } : { ok: false, error: `uninstall refused: ${u.reason}` };
|
|
643
918
|
}
|
|
919
|
+
case 'prune-removed': { // drops removed-names entries older than N days (age only; blocking rests on the link)
|
|
920
|
+
const keys = Object.hasOwn(raw, 'older_than_days') ? ['older_than_days'] : [];
|
|
921
|
+
onlyKeys(raw, keys);
|
|
922
|
+
const days = keys.length === 0 ? 90 : raw['older_than_days'];
|
|
923
|
+
if (typeof days !== 'number' || !Number.isInteger(days) || days < 7)
|
|
924
|
+
return { ok: false, error: 'older_than_days must be at least 7' };
|
|
925
|
+
const cutoff = now().getTime() - days * 86_400_000;
|
|
926
|
+
const entries = await readRemoved().catch(() => undefined);
|
|
927
|
+
if (!entries)
|
|
928
|
+
return { ok: false, error: 'removed-names file is unreadable or malformed' };
|
|
929
|
+
const kept = entries.filter((e) => !(Date.parse(e.at) < cutoff));
|
|
930
|
+
if (kept.length !== entries.length)
|
|
931
|
+
await writeRemoved(kept);
|
|
932
|
+
else
|
|
933
|
+
removedStatus.count = entries.length;
|
|
934
|
+
if (kept.length < REMOVED_NAMES_CAP)
|
|
935
|
+
removedStatus.full = false;
|
|
936
|
+
return { ok: true, pruned: entries.length - kept.length, remaining: kept.length };
|
|
937
|
+
}
|
|
644
938
|
case 'refresh': {
|
|
645
939
|
onlyKeys(raw, []);
|
|
646
940
|
if (!config.inboxDir)
|
|
@@ -656,6 +950,7 @@ export function createGateService(config) {
|
|
|
656
950
|
return {
|
|
657
951
|
sockets,
|
|
658
952
|
get decisionCap() { return decisionCap; },
|
|
953
|
+
get startError() { return startError; },
|
|
659
954
|
handleDecision,
|
|
660
955
|
handleAdmin,
|
|
661
956
|
async start() {
|
|
@@ -665,21 +960,31 @@ export function createGateService(config) {
|
|
|
665
960
|
for (const d of [stagingDir, certsDir])
|
|
666
961
|
await ownedDir(d, config.rootUid, d === certsDir ? 0o755 : 0o700, d !== certsDir);
|
|
667
962
|
await ownedDir(managedDir, config.rootUid, 0o755, false);
|
|
668
|
-
|
|
963
|
+
await ownedDir(generationsDir, config.rootUid, 0o755, false);
|
|
964
|
+
await ownedDir(path.join(stateDir, 'trust'), config.rootUid, 0o700, true);
|
|
965
|
+
// A store from before the per-root layout is carried over with its rollback memory, or the start fails closed
|
|
966
|
+
// (gate-new-root.md N4): an empty per-root store would accept documents older than the ones already accepted.
|
|
967
|
+
await migrateFlatTrustStore(path.join(stateDir, 'trust'), trustStoreDir(stateDir, config.rootFingerprint), config.rootFingerprint);
|
|
968
|
+
trust = await openTrustStore(trustStoreDir(stateDir, config.rootFingerprint), { rootFingerprint: config.rootFingerprint, now: now(), ...(config.maxListAgeMs !== undefined ? { maxListAgeMs: config.maxListAgeMs } : {}) });
|
|
669
969
|
admission = await openAdmissionStore(path.join(stateDir, 'admission'), { bootId: await bootId(), ...(config.admissionFault ? { fault: config.admissionFault } : {}) });
|
|
670
970
|
ready = true;
|
|
671
971
|
await getLog().catch(() => { logHealthy = false; });
|
|
672
972
|
await exclusive(sweep).catch(() => { });
|
|
673
973
|
reaper = setInterval(() => { void exclusive(sweep).catch(() => { }); }, 60_000);
|
|
674
974
|
reaper.unref();
|
|
975
|
+
reconciler = setInterval(() => { void serial(reconcileInstalls).catch(() => { }); }, config.reconcileIntervalMs ?? 60_000);
|
|
976
|
+
reconciler.unref();
|
|
977
|
+
await readRemoved().then((e) => { removedStatus.count = e.length; }, () => { });
|
|
978
|
+
await serial(reconcileInstalls).catch(() => { }); // a restart with stale trust must hide at once
|
|
675
979
|
if (config.inboxDir) {
|
|
676
980
|
refresher = setInterval(() => { void serial(refreshNow).catch(() => { }); }, config.refreshIntervalMs ?? 60_000);
|
|
677
981
|
refresher.unref();
|
|
678
982
|
}
|
|
679
983
|
}
|
|
680
|
-
catch {
|
|
984
|
+
catch (e) {
|
|
681
985
|
ready = false;
|
|
682
|
-
|
|
986
|
+
startError = e instanceof Error ? e.message : String(e);
|
|
987
|
+
} // stay up and answer trust-unavailable; status reports why
|
|
683
988
|
const soft = config.nofileLimit ?? await nofileSoftLimit();
|
|
684
989
|
if (!(soft - 260 >= 16))
|
|
685
990
|
throw new Error(`RLIMIT_NOFILE soft limit ${soft} is too low (need at least 276)`);
|
|
@@ -714,6 +1019,8 @@ export function createGateService(config) {
|
|
|
714
1019
|
clearInterval(reaper);
|
|
715
1020
|
if (refresher)
|
|
716
1021
|
clearInterval(refresher);
|
|
1022
|
+
if (reconciler)
|
|
1023
|
+
clearInterval(reconciler);
|
|
717
1024
|
await dlog?.close().catch(() => { });
|
|
718
1025
|
await Promise.all(servers.splice(0).map((s) => new Promise((r) => { s.close(() => r()); for (const c of live)
|
|
719
1026
|
c.destroy(); })));
|