@mago-foundation/mago-ski 0.4.0 → 0.5.0-beta.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.
Files changed (59) hide show
  1. package/README.md +5 -3
  2. package/action.yml +21 -2
  3. package/dist/hosts/github/check.d.ts +21 -0
  4. package/dist/hosts/github/check.js +124 -0
  5. package/dist/hosts/github/publish.d.ts +7 -0
  6. package/dist/hosts/github/publish.js +52 -0
  7. package/dist/hosts/github/run.d.ts +12 -0
  8. package/dist/hosts/github/run.js +32 -18
  9. package/dist/hosts/pi/index.js +40 -18
  10. package/dist/src/admin.d.ts +2 -1
  11. package/dist/src/admin.js +3 -2
  12. package/dist/src/admission-evidence.d.ts +15 -0
  13. package/dist/src/admission-evidence.js +48 -0
  14. package/dist/src/admission.d.ts +102 -0
  15. package/dist/src/admission.js +316 -0
  16. package/dist/src/canonical-json.d.ts +6 -0
  17. package/dist/src/canonical-json.js +11 -0
  18. package/dist/src/cli.d.ts +2 -0
  19. package/dist/src/cli.js +229 -5
  20. package/dist/src/diff.d.ts +9 -0
  21. package/dist/src/diff.js +3 -2
  22. package/dist/src/dsse.js +2 -2
  23. package/dist/src/experimental/sigstore.d.ts +30 -0
  24. package/dist/src/experimental/sigstore.js +35 -5
  25. package/dist/src/fs-safe.d.ts +15 -2
  26. package/dist/src/fs-safe.js +68 -50
  27. package/dist/src/gate/adapters/claude-code.js +8 -5
  28. package/dist/src/gate/adapters/codex.js +5 -6
  29. package/dist/src/gate/generations.js +2 -0
  30. package/dist/src/gate/instance.js +7 -7
  31. package/dist/src/gate/proc.d.ts +6 -0
  32. package/dist/src/gate/proc.js +14 -3
  33. package/dist/src/gate/service.js +3 -0
  34. package/dist/src/gate/setup.d.ts +5 -5
  35. package/dist/src/gate/setup.js +128 -88
  36. package/dist/src/policy.d.ts +7 -0
  37. package/dist/src/policy.js +19 -2
  38. package/dist/src/profile.d.ts +34 -0
  39. package/dist/src/profile.js +182 -0
  40. package/dist/src/published-by.d.ts +64 -0
  41. package/dist/src/published-by.js +227 -0
  42. package/dist/src/recovery-admin.js +7 -4
  43. package/dist/src/root-events.d.ts +2 -0
  44. package/dist/src/root-events.js +61 -4
  45. package/dist/src/tree-digest.d.ts +6 -0
  46. package/dist/src/tree-digest.js +8 -0
  47. package/dist/src/usf-check.d.ts +28 -0
  48. package/dist/src/usf-check.js +128 -0
  49. package/dist/src/usf.d.ts +48 -0
  50. package/dist/src/usf.js +238 -0
  51. package/docs/hosts/publish.md +65 -0
  52. package/docs/hosts/skill-check.md +91 -0
  53. package/docs/spec/admission-v0.md +84 -0
  54. package/docs/spec/gui-admin-rack-v1.md +1 -1
  55. package/docs/spec/observed-profile-v1.md +51 -0
  56. package/docs/spec/root-recovery-v1.md +3 -2
  57. package/docs/spec/trust-documents-v1.md +1 -1
  58. package/docs/threat-model.md +12 -0
  59. package/package.json +5 -1
@@ -0,0 +1,48 @@
1
+ // Collects the facts an admission decision is made from (admission.ts). Everything is recomputed or verified here:
2
+ // the profile and declaration from the bytes, reviews against the organisation's trust root, published-by bundles
3
+ // with the pinned Cosign against a local trusted root. Nothing is fetched. The facts can be logged and replayed.
4
+ import { parseCertificate } from "./certificate.js";
5
+ import { readRegularFile } from "./fs-safe.js";
6
+ import { verifyWithPolicy } from "./policy.js";
7
+ import { describeSkill, publisherOf, verifyPublishedBy } from "./published-by.js";
8
+ import { resolveSkillName } from "./verify.js";
9
+ import path from 'node:path';
10
+ async function review(policy, trust, skillDir, now) {
11
+ const result = await verifyWithPolicy(policy, skillDir, { now, ...(trust ? { context: trust } : {}) });
12
+ if (result.verdict !== 'VERIFIED' || !result.certificateSource || !result.certificateId || !result.approverKeyId)
13
+ return null;
14
+ // The dates come from the certificate that was verified: its id is the hash of its bytes, so a swapped file is refused.
15
+ const certificate = parseCertificate(await readRegularFile(result.certificateSource, 'Certificate', 8 * 1024 * 1024));
16
+ if (certificate.id !== result.certificateId)
17
+ throw new Error('the certificate changed while it was being read');
18
+ return { approver_key_id: result.approverKeyId, certificate_id: result.certificateId, issued_at: certificate.issuedAt.toISOString(), expires_at: certificate.expiresAt.toISOString(), digest: certificate.digest };
19
+ }
20
+ export async function collectSkillFacts(skillDir, evidence, sigstore, now) {
21
+ const record = await describeSkill(skillDir, path.dirname(path.resolve(skillDir)));
22
+ let published_by = null;
23
+ let publishedDigest = record.digest;
24
+ if (evidence.publishedBy !== undefined) {
25
+ if (!sigstore)
26
+ throw new RangeError('a published-by bundle needs --trusted-root and --cosign');
27
+ const facts = await verifyPublishedBy(skillDir, { bundlePath: evidence.publishedBy, ...sigstore });
28
+ // A record that does not match the bytes is not evidence for them.
29
+ if (facts.differences.length > 0)
30
+ throw new Error(`the published-by record does not match these bytes: ${facts.differences.join('; ')}`);
31
+ published_by = publisherOf(facts.publisher);
32
+ publishedDigest = facts.digest;
33
+ }
34
+ const reviewed = evidence.policy ? await review(evidence.policy, evidence.trust, skillDir, now) : null;
35
+ // Every source read the bytes separately: they must all have seen the same version.
36
+ const check = await describeSkill(skillDir, path.dirname(path.resolve(skillDir)));
37
+ if (check.digest !== record.digest || publishedDigest !== record.digest || (reviewed && reviewed.digest !== record.digest))
38
+ throw new Error('the Skill changed while its facts were collected');
39
+ return {
40
+ name: await resolveSkillName(skillDir),
41
+ digest: record.digest,
42
+ profile: record.profile,
43
+ declaration: record.declaration,
44
+ declaration_error: record.declaration_error,
45
+ reviewed_by: reviewed && { approver_key_id: reviewed.approver_key_id, certificate_id: reviewed.certificate_id, issued_at: reviewed.issued_at, expires_at: reviewed.expires_at },
46
+ published_by,
47
+ };
48
+ }
@@ -0,0 +1,102 @@
1
+ import type { ObservedProfile } from './profile.ts';
2
+ import type { Publisher } from './published-by.ts';
3
+ import type { UsfManifest } from './usf.ts';
4
+ export declare const ADMISSION_VERSION = "mago.admission/v0";
5
+ export declare const ACTIONS: readonly ["ALLOW", "LOG_ONLY", "FLAG", "REQUIRE_REVIEW", "BLOCK"];
6
+ export type Action = (typeof ACTIONS)[number];
7
+ export interface Review {
8
+ approver_key_id: string;
9
+ certificate_id: string;
10
+ issued_at: string;
11
+ expires_at: string;
12
+ }
13
+ export interface SkillFacts {
14
+ name: string;
15
+ digest: string;
16
+ profile: ObservedProfile;
17
+ declaration: UsfManifest | null;
18
+ /** Why SKILL.md's declaration could not be read one way only, or null. */
19
+ declaration_error: string | null;
20
+ /** A valid certificate from the organisation's trust root for these exact bytes. */
21
+ reviewed_by: Review | null;
22
+ /** A verified published-by attestation for these exact bytes. */
23
+ published_by: Publisher | null;
24
+ }
25
+ export interface Facts {
26
+ skill: SkillFacts;
27
+ /** The reviewed version this one updates, when one was supplied (its bytes, its review, its publisher). */
28
+ base: SkillFacts | null;
29
+ }
30
+ export interface PublisherCondition {
31
+ repository_id?: string;
32
+ owner_id?: string;
33
+ workflow?: string;
34
+ branch?: string;
35
+ trigger?: string[];
36
+ }
37
+ export interface CapabilityCondition {
38
+ shell?: true;
39
+ websites?: string[];
40
+ any_website?: true;
41
+ undeclared?: true;
42
+ no_declaration?: true;
43
+ incomplete?: true;
44
+ }
45
+ export interface UpdateCondition {
46
+ same_publisher: true;
47
+ max_days_since_review?: number;
48
+ }
49
+ export interface Rule {
50
+ id: string;
51
+ when: {
52
+ publisher?: PublisherCondition;
53
+ reviewed?: boolean;
54
+ capabilities?: CapabilityCondition;
55
+ update?: UpdateCondition;
56
+ };
57
+ action: Action;
58
+ reason?: string;
59
+ }
60
+ export interface Rules {
61
+ admission_version: typeof ADMISSION_VERSION;
62
+ default: Action;
63
+ rules: Rule[];
64
+ digest: string;
65
+ }
66
+ export declare class AdmissionRulesError extends Error {
67
+ }
68
+ /**
69
+ * Parses and lints a rule file. Every mistake the closed language can detect is an error here, not a surprise at
70
+ * decision time: unknown keys, duplicate ids, a loosening rule built on self-declared or heuristic facts, a strict
71
+ * action without a reason, an ALLOW that matches every Skill.
72
+ */
73
+ export declare function parseRules(source: string): Rules;
74
+ export interface Decision {
75
+ action: Action;
76
+ admitted: boolean;
77
+ /** The rule that set the action, or "default" when none matched. */
78
+ rule_id: string;
79
+ matched: string[];
80
+ reason: string | null;
81
+ /** The smallest evidence that would change a REQUIRE_REVIEW or the default, in words. */
82
+ missing: string | null;
83
+ }
84
+ /** Why this version reaches further than its base, or null when it does not. Compares declared and observed together. */
85
+ export declare function escalation(base: SkillFacts, skill: SkillFacts): string | null;
86
+ export declare function evaluate(rules: Rules, facts: Facts, now: Date): Decision;
87
+ export interface AdmissionRecord {
88
+ decided_at: string;
89
+ rules_digest: string;
90
+ facts: Facts;
91
+ decision: Decision;
92
+ }
93
+ export interface Flip {
94
+ decided_at: string;
95
+ skill: string;
96
+ digest: string;
97
+ before: Decision;
98
+ after: Decision;
99
+ }
100
+ export declare function validRecord(value: unknown): value is AdmissionRecord;
101
+ /** Every past decision whose action would change under `next`, each re-evaluated at its own time. */
102
+ export declare function replay(previous: Rules, next: Rules, records: readonly unknown[]): Flip[];
@@ -0,0 +1,316 @@
1
+ // Admission rules (mago.admission/v0): an organisation's short, readable rule file that decides which evidence is
2
+ // enough to admit a Skill. A decision is a pure function of (facts, rules, time): no model, no network, no
3
+ // probability. Facts are computed beforehand from bytes and verified documents (admission-evidence.ts), so the same
4
+ // inputs give the same decision anywhere, and a past decision can be replayed against a new rule file.
5
+ // This is the admission language only. It never describes what an agent may do at runtime.
6
+ import { createHash } from 'node:crypto';
7
+ import { parseDocument } from 'yaml';
8
+ import { hostAllowed } from "./usf.js";
9
+ export const ADMISSION_VERSION = 'mago.admission/v0';
10
+ export const ACTIONS = ['ALLOW', 'LOG_ONLY', 'FLAG', 'REQUIRE_REVIEW', 'BLOCK'];
11
+ /** Stricter actions win: deny wins over allow. */
12
+ const RANK = { ALLOW: 0, LOG_ONLY: 1, FLAG: 2, REQUIRE_REVIEW: 3, BLOCK: 4 };
13
+ const ADMITTED = new Set(['ALLOW', 'LOG_ONLY', 'FLAG']);
14
+ const MAX_RULES = 200;
15
+ const MAX_RULES_BYTES = 256 * 1024;
16
+ export class AdmissionRulesError extends Error {
17
+ }
18
+ const isMap = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ function keys(value, label, allowed, required = []) {
20
+ if (!isMap(value))
21
+ throw new AdmissionRulesError(`${label} must be a block of keys`);
22
+ for (const key of Object.keys(value))
23
+ if (!allowed.includes(key))
24
+ throw new AdmissionRulesError(`${label}: unknown key "${key}" (allowed: ${allowed.join(', ')})`);
25
+ for (const key of required)
26
+ if (!Object.hasOwn(value, key))
27
+ throw new AdmissionRulesError(`${label}: "${key}" is required`);
28
+ return value;
29
+ }
30
+ function action(value, label) {
31
+ if (typeof value !== 'string' || !ACTIONS.includes(value))
32
+ throw new AdmissionRulesError(`${label} must be one of ${ACTIONS.join(', ')}`);
33
+ return value;
34
+ }
35
+ const text = (value, label, pattern, hint) => {
36
+ if (typeof value !== 'string' || !pattern.test(value))
37
+ throw new AdmissionRulesError(`${label} must be ${hint}`);
38
+ return value;
39
+ };
40
+ const yes = (value, label) => {
41
+ if (value !== true)
42
+ throw new AdmissionRulesError(`${label} can only be true`);
43
+ return true;
44
+ };
45
+ /**
46
+ * Parses and lints a rule file. Every mistake the closed language can detect is an error here, not a surprise at
47
+ * decision time: unknown keys, duplicate ids, a loosening rule built on self-declared or heuristic facts, a strict
48
+ * action without a reason, an ALLOW that matches every Skill.
49
+ */
50
+ export function parseRules(source) {
51
+ if (Buffer.byteLength(source) > MAX_RULES_BYTES)
52
+ throw new AdmissionRulesError(`the rule file is larger than ${MAX_RULES_BYTES} bytes`);
53
+ const doc = parseDocument(source, { version: '1.2', uniqueKeys: true, prettyErrors: false });
54
+ if (doc.errors[0])
55
+ throw new AdmissionRulesError(`the rule file is not valid YAML: ${doc.errors[0].message.split('\n')[0]}`);
56
+ let raw;
57
+ try {
58
+ raw = doc.toJS({ maxAliasCount: 0 });
59
+ }
60
+ catch (error) {
61
+ throw new AdmissionRulesError(`the rule file uses aliases, which are not accepted: ${error.message}`);
62
+ }
63
+ const top = keys(raw, 'rule file', ['admission_version', 'default', 'rules'], ['admission_version', 'default', 'rules']);
64
+ if (top.admission_version !== ADMISSION_VERSION)
65
+ throw new AdmissionRulesError(`admission_version must be ${ADMISSION_VERSION}`);
66
+ const fallback = action(top.default, 'default');
67
+ if (!Array.isArray(top.rules) || top.rules.length > MAX_RULES)
68
+ throw new AdmissionRulesError(`rules must be a list of at most ${MAX_RULES} rules`);
69
+ const ids = new Set();
70
+ const rules = top.rules.map((item, index) => {
71
+ const r = keys(item, `rule ${index + 1}`, ['id', 'when', 'action', 'reason'], ['id', 'when', 'action']);
72
+ const id = text(r.id, `rule ${index + 1} id`, /^[a-z0-9][a-z0-9-]{0,62}$/u, 'lower-case letters, digits and dashes');
73
+ if (ids.has(id))
74
+ throw new AdmissionRulesError(`rule id "${id}" is used twice`);
75
+ ids.add(id);
76
+ const label = `rule "${id}"`;
77
+ const w = keys(r.when, `${label} when`, ['publisher', 'reviewed', 'capabilities', 'update']);
78
+ const when = {};
79
+ if (w.publisher !== undefined) {
80
+ const p = keys(w.publisher, `${label} publisher`, ['repository_id', 'owner_id', 'workflow', 'branch', 'trigger']);
81
+ if (Object.keys(p).length === 0)
82
+ throw new AdmissionRulesError(`${label} publisher must name a repository_id, owner_id or workflow`);
83
+ if (p.workflow !== undefined && p.repository_id === undefined)
84
+ throw new AdmissionRulesError(`${label}: a workflow path only means something with a repository_id`);
85
+ when.publisher = {};
86
+ if (p.repository_id !== undefined)
87
+ when.publisher.repository_id = text(p.repository_id, `${label} repository_id`, /^[0-9]{1,20}$/u, 'a numeric repository id, quoted');
88
+ if (p.owner_id !== undefined)
89
+ when.publisher.owner_id = text(p.owner_id, `${label} owner_id`, /^[0-9]{1,20}$/u, 'a numeric owner id, quoted');
90
+ if (p.workflow !== undefined)
91
+ when.publisher.workflow = text(p.workflow, `${label} workflow`, /^\.github\/workflows\/[A-Za-z0-9_.\-/]+\.ya?ml$/u, 'a path such as .github/workflows/publish.yml');
92
+ // Branches only: tags move, so no rule can refer to one.
93
+ if (p.branch !== undefined)
94
+ when.publisher.branch = text(p.branch, `${label} branch`, /^[A-Za-z0-9._\-/]{1,200}$/u, 'a branch name such as main');
95
+ if (p.trigger !== undefined) {
96
+ if (!Array.isArray(p.trigger) || p.trigger.length === 0 || !p.trigger.every((t) => typeof t === 'string' && /^[a-z_]{1,40}$/u.test(t)))
97
+ throw new AdmissionRulesError(`${label} trigger must be a list of GitHub event names such as [release, push]`);
98
+ when.publisher.trigger = p.trigger;
99
+ }
100
+ }
101
+ if (w.reviewed !== undefined) {
102
+ if (typeof w.reviewed !== 'boolean')
103
+ throw new AdmissionRulesError(`${label} reviewed must be true or false`);
104
+ when.reviewed = w.reviewed;
105
+ }
106
+ if (w.capabilities !== undefined) {
107
+ const c = keys(w.capabilities, `${label} capabilities`, ['shell', 'websites', 'any_website', 'undeclared', 'no_declaration', 'incomplete']);
108
+ if (Object.keys(c).length === 0)
109
+ throw new AdmissionRulesError(`${label} capabilities must name at least one condition`);
110
+ when.capabilities = {};
111
+ for (const flag of ['shell', 'any_website', 'undeclared', 'no_declaration', 'incomplete'])
112
+ if (c[flag] !== undefined)
113
+ when.capabilities[flag] = yes(c[flag], `${label} capabilities.${flag}`);
114
+ if (c.websites !== undefined) {
115
+ if (!Array.isArray(c.websites) || c.websites.length === 0 || !c.websites.every((h) => typeof h === 'string' && /^(?:\*\.)?[a-z0-9.-]+$/u.test(h)))
116
+ throw new AdmissionRulesError(`${label} capabilities.websites must be a list of host names`);
117
+ when.capabilities.websites = c.websites;
118
+ }
119
+ }
120
+ if (w.update !== undefined) {
121
+ const u = keys(w.update, `${label} update`, ['same_publisher', 'max_days_since_review'], ['same_publisher']);
122
+ when.update = { same_publisher: yes(u.same_publisher, `${label} update.same_publisher`) };
123
+ if (u.max_days_since_review !== undefined) {
124
+ if (!Number.isInteger(u.max_days_since_review) || u.max_days_since_review < 0 || u.max_days_since_review > 3650)
125
+ throw new AdmissionRulesError(`${label} update.max_days_since_review must be a whole number of days up to 3650`);
126
+ when.update.max_days_since_review = u.max_days_since_review;
127
+ }
128
+ }
129
+ const act = action(r.action, `${label} action`);
130
+ const rule = { id, when, action: act };
131
+ if (r.reason !== undefined)
132
+ rule.reason = text(r.reason, `${label} reason`, /^[^\u0000-\u001f\u007f]{1,300}$/u, 'one line of up to 300 characters');
133
+ // The linter: what a closed language can check completely.
134
+ if ((act === 'BLOCK' || act === 'REQUIRE_REVIEW') && rule.reason === undefined)
135
+ throw new AdmissionRulesError(`${label}: a ${act} rule needs a reason, shown to the person it stops`);
136
+ if (when.capabilities && act === 'ALLOW')
137
+ throw new AdmissionRulesError(`${label}: a rule with capability conditions can only make a decision stricter, so ALLOW would have no effect`);
138
+ // ALLOW, LOG_ONLY and FLAG all admit: a basis rule with one of them must rest on a publisher, a review or an update.
139
+ if (!when.capabilities && (act === 'ALLOW' || act === 'LOG_ONLY' || act === 'FLAG')) {
140
+ if (when.reviewed === false)
141
+ throw new AdmissionRulesError(`${label}: "reviewed: false" cannot be a reason to admit (${act})`);
142
+ if (!when.publisher && when.reviewed !== true && !when.update)
143
+ throw new AdmissionRulesError(`${label}: a ${act} rule must require a publisher, a review or a non-escalating update; this one would admit every Skill`);
144
+ }
145
+ return rule;
146
+ });
147
+ return { admission_version: ADMISSION_VERSION, default: fallback, rules, digest: `sha256:${createHash('sha256').update(source).digest('hex')}` };
148
+ }
149
+ const DAY_MS = 24 * 60 * 60 * 1000;
150
+ /** Everything the Skill may reach: hosts it names or declares, and whether it runs code or declares a shell. */
151
+ function reach(facts) {
152
+ return {
153
+ hosts: new Set([...facts.profile.web_hosts, ...(facts.declaration?.network.allow ?? [])]),
154
+ shell: facts.profile.scripts.length > 0 || facts.declaration?.shell === true,
155
+ };
156
+ }
157
+ /** Why this version reaches further than its base, or null when it does not. Compares declared and observed together. */
158
+ export function escalation(base, skill) {
159
+ // A declaration that cannot be read one way only may say anything to some reader.
160
+ // Even when the base's could not be read either: then nobody can say what the new one grants.
161
+ if (skill.declaration_error !== null && skill.declaration === null)
162
+ return 'its declaration cannot be read reliably';
163
+ if (base.declaration !== null && skill.declaration === null)
164
+ return 'it no longer has a declaration';
165
+ const before = reach(base);
166
+ const after = reach(skill);
167
+ if (after.shell && !before.shell)
168
+ return 'it runs code or asks for a shell, and the reviewed version did not';
169
+ const newHosts = [...after.hosts].filter((host) => host !== '*' && !before.hosts.has(host) && !hostAllowed([...before.hosts], host));
170
+ if (after.hosts.has('*') && !before.hosts.has('*'))
171
+ return 'it declares any website (network.allow: "*")';
172
+ if (newHosts.length > 0)
173
+ return `it reaches new websites: ${newHosts.slice(0, 10).join(', ')}`;
174
+ if (!skill.profile.complete)
175
+ return 'its profile is incomplete';
176
+ const added = (before = [], after = []) => after.filter((value) => !before.includes(value));
177
+ const d0 = base.declaration;
178
+ const d1 = skill.declaration;
179
+ const checks = [
180
+ ['asks to read new files', added(d0?.files.read, d1?.files.read)],
181
+ ['asks to write new files', added(d0?.files.write, d1?.files.write)],
182
+ ['no longer protects files from writes', added(d1?.files.deny_write, d0?.files.deny_write)],
183
+ ['asks for new tools', added(d0?.tools, d1?.tools)],
184
+ ['needs new programs', added(d0?.requires.binaries, d1?.requires.binaries)],
185
+ ['names new programs in shell code', added(base.profile.programs, skill.profile.programs)],
186
+ ['adds declaration keys this version of mago-ski does not know', added(d0?.unknownKeys, d1?.unknownKeys)],
187
+ ['no longer denies other websites (network.deny)', d0?.network.deny === '*' && d1?.network.deny !== '*' ? ['network.deny'] : []],
188
+ ];
189
+ for (const [what, values] of checks)
190
+ if (values.length > 0)
191
+ return `it ${what}: ${values.slice(0, 10).join(', ')}`;
192
+ return null;
193
+ }
194
+ function samePublisher(a, b) {
195
+ return a !== null && b !== null && a.repository_id === b.repository_id && a.workflow === b.workflow;
196
+ }
197
+ function matches(rule, facts, now) {
198
+ const { skill } = facts;
199
+ const { publisher, reviewed, capabilities, update } = rule.when;
200
+ if (publisher) {
201
+ const p = skill.published_by;
202
+ if (!p)
203
+ return false;
204
+ if (publisher.repository_id !== undefined && p.repository_id !== publisher.repository_id)
205
+ return false;
206
+ if (publisher.owner_id !== undefined && p.owner_id !== publisher.owner_id)
207
+ return false;
208
+ if (publisher.workflow !== undefined && p.workflow !== publisher.workflow)
209
+ return false;
210
+ if (publisher.branch !== undefined && p.ref !== `refs/heads/${publisher.branch}`)
211
+ return false;
212
+ if (publisher.trigger !== undefined && !publisher.trigger.includes(p.trigger))
213
+ return false;
214
+ }
215
+ if (reviewed !== undefined && (skill.reviewed_by !== null) !== reviewed)
216
+ return false;
217
+ if (capabilities) {
218
+ const r = reach(skill);
219
+ if (capabilities.shell && !r.shell)
220
+ return false;
221
+ if (capabilities.any_website && r.hosts.size === 0)
222
+ return false;
223
+ if (capabilities.websites && ![...r.hosts].some((host) => hostAllowed(capabilities.websites, host) || host === '*'))
224
+ return false;
225
+ if (capabilities.no_declaration && skill.declaration !== null)
226
+ return false;
227
+ if (capabilities.incomplete && skill.profile.complete)
228
+ return false;
229
+ if (capabilities.undeclared) {
230
+ const d = skill.declaration;
231
+ const undeclared = d !== null && (skill.profile.web_hosts.some((host) => !hostAllowed(d.network.allow, host)) || (skill.profile.scripts.length > 0 && d.shell !== true));
232
+ if (!undeclared)
233
+ return false;
234
+ }
235
+ }
236
+ if (update) {
237
+ const base = facts.base;
238
+ if (!base || base.reviewed_by === null || base.digest === skill.digest || base.name !== skill.name)
239
+ return false;
240
+ if (!samePublisher(base.published_by, skill.published_by))
241
+ return false;
242
+ if (escalation(base, skill) !== null)
243
+ return false;
244
+ if (update.max_days_since_review !== undefined && now.getTime() - Date.parse(base.reviewed_by.issued_at) > update.max_days_since_review * DAY_MS)
245
+ return false;
246
+ }
247
+ return true;
248
+ }
249
+ /** Capability rules only tighten: they come from heuristics and self-declarations, so they can never be why a Skill is admitted. */
250
+ const isTightener = (rule) => rule.when.capabilities !== undefined;
251
+ export function evaluate(rules, facts, now) {
252
+ const matched = rules.rules.filter((rule) => matches(rule, facts, now));
253
+ // Strictest wins; among equals, the first rule in the file names the decision.
254
+ const strictest = (list) => list.reduce((best, rule) => (best === null || RANK[rule.action] > RANK[best.action] ? rule : best), null);
255
+ // The base decision comes from publisher, review and update rules (or the default); tighteners can only raise it.
256
+ const basis = strictest(matched.filter((rule) => !isTightener(rule)));
257
+ const tightener = strictest(matched.filter(isTightener));
258
+ const baseAction = basis?.action ?? rules.default;
259
+ const deciding = tightener && RANK[tightener.action] > RANK[baseAction] ? tightener : basis;
260
+ const act = deciding?.action ?? rules.default;
261
+ let missing = null;
262
+ if (act === 'REQUIRE_REVIEW' || (deciding === null && !ADMITTED.has(act))) {
263
+ if (facts.base && facts.skill.reviewed_by === null) {
264
+ const why = facts.base.name !== facts.skill.name ? `the supplied base is another Skill (${facts.base.name})`
265
+ : facts.base.reviewed_by === null ? 'the supplied base version has no valid review'
266
+ : !samePublisher(facts.base.published_by, facts.skill.published_by) ? 'it was not published by the same repository and workflow as the reviewed version'
267
+ : escalation(facts.base, facts.skill);
268
+ missing = `a review of this exact version (reviewed-by)${why ? `; it is not a plain update because ${why}` : ''}`;
269
+ }
270
+ else if (facts.skill.reviewed_by === null)
271
+ missing = 'a review of this exact version (reviewed-by)';
272
+ }
273
+ return { action: act, admitted: ADMITTED.has(act), rule_id: deciding?.id ?? 'default', matched: matched.map((rule) => rule.id), reason: deciding?.reason ?? null, missing };
274
+ }
275
+ const isList = (value, item) => Array.isArray(value) && value.every(item);
276
+ const isText = (value) => typeof value === 'string';
277
+ const nullOr = (value, check) => value === null || check(value);
278
+ const isDate = (value) => typeof value === 'string' && /^\d{4}-\d\d-\d\dT/u.test(value) && !Number.isNaN(Date.parse(value));
279
+ const texts = (value) => isList(value, isText);
280
+ function validDeclaration(d) {
281
+ return isMap(d) && isMap(d.network) && texts(d.network.allow) && nullOr(d.network.deny, isText)
282
+ && isMap(d.files) && texts(d.files.read) && texts(d.files.write) && texts(d.files.deny_write)
283
+ && nullOr(d.shell, (v) => typeof v === 'boolean') && texts(d.tools) && texts(d.unknownKeys)
284
+ && isMap(d.requires) && texts(d.requires.binaries) && nullOr(d.requires.min_runtime_version, isText);
285
+ }
286
+ /** Checks a logged skill record field by field: a missing field must never read as present (undefined !== null). */
287
+ function validSkillFacts(value) {
288
+ if (!isMap(value))
289
+ return false;
290
+ const p = value.profile;
291
+ return isText(value.name) && isText(value.digest) && isMap(p) && isList(p.web_hosts, isText) && isList(p.programs, isText)
292
+ && isList(p.scripts, (s) => isMap(s) && isText(s.path)) && typeof p.complete === 'boolean'
293
+ && nullOr(value.declaration, validDeclaration) && nullOr(value.declaration_error, isText)
294
+ && nullOr(value.reviewed_by, (r) => isMap(r) && isDate(r.issued_at) && isDate(r.expires_at) && isText(r.certificate_id) && isText(r.approver_key_id))
295
+ && nullOr(value.published_by, (b) => isMap(b) && isText(b.repository_id) && isText(b.workflow));
296
+ }
297
+ export function validRecord(value) {
298
+ return isMap(value) && isText(value.decided_at) && isText(value.rules_digest) && isMap(value.facts)
299
+ && validSkillFacts(value.facts.skill) && nullOr(value.facts.base, validSkillFacts);
300
+ }
301
+ /** Every past decision whose action would change under `next`, each re-evaluated at its own time. */
302
+ export function replay(previous, next, records) {
303
+ const flips = [];
304
+ for (const [index, record] of records.entries()) {
305
+ if (!validRecord(record))
306
+ throw new Error(`log record ${index + 1} is not a complete admission record`);
307
+ const at = new Date(record.decided_at);
308
+ if (Number.isNaN(at.getTime()))
309
+ throw new Error(`log record ${index + 1} has an invalid time`);
310
+ const before = evaluate(previous, record.facts, at);
311
+ const after = evaluate(next, record.facts, at);
312
+ if (before.action !== after.action)
313
+ flips.push({ decided_at: record.decided_at, skill: record.facts.skill.name, digest: record.facts.skill.digest, before, after });
314
+ }
315
+ return flips;
316
+ }
@@ -5,6 +5,12 @@ export type JsonValue = null | boolean | number | string | JsonValue[] | {
5
5
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
6
6
  export declare function serializeCanonicalJson(value: unknown): string;
7
7
  export declare function canonicalBytes(value: unknown): Buffer;
8
+ /**
9
+ * canonicalBytes for a document that will be read back with parseCanonicalJsonBytes: refuses bytes the reader would refuse
10
+ * for size. A signed document must not be written when no verifier can load it (a revocation list that grew too large
11
+ * would otherwise replace a working one and block every host).
12
+ */
13
+ export declare function readableCanonicalBytes(value: unknown, label: string): Buffer;
8
14
  export declare function parseCanonicalJsonBytes(input: Uint8Array, label?: string): unknown;
9
15
  export declare function exactKeys(value: unknown, keys: readonly string[], label: string): Record<string, unknown>;
10
16
  export declare function requireString(value: unknown, label: string, maxLength?: number): string;
@@ -65,6 +65,17 @@ export function serializeCanonicalJson(value) {
65
65
  export function canonicalBytes(value) {
66
66
  return Buffer.from(serializeCanonicalJson(value), 'utf8');
67
67
  }
68
+ /**
69
+ * canonicalBytes for a document that will be read back with parseCanonicalJsonBytes: refuses bytes the reader would refuse
70
+ * for size. A signed document must not be written when no verifier can load it (a revocation list that grew too large
71
+ * would otherwise replace a working one and block every host).
72
+ */
73
+ export function readableCanonicalBytes(value, label) {
74
+ const bytes = canonicalBytes(value);
75
+ if (bytes.byteLength > MAX_CANONICAL_JSON_BYTES)
76
+ throw new Error(`${label} would be ${bytes.byteLength} bytes; the limit for a document is ${MAX_CANONICAL_JSON_BYTES} bytes. Nothing was written`);
77
+ return bytes;
78
+ }
68
79
  export function parseCanonicalJsonBytes(input, label = 'JSON document') {
69
80
  let text;
70
81
  let value;
package/dist/src/cli.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import type { AskAdmin } from './gate/admin-client.ts';
3
3
  import type { DoctorOptions, InitOptions } from './gate/setup.ts';
4
+ /** Text from a Skill or its folder, for one terminal line: control, line-separator and bidirectional characters are escaped. */
5
+ export declare function terminalSafe(value: string): string;
4
6
  export interface GateCliSeams extends Pick<InitOptions, 'base' | 'rootUid' | 'platform' | 'installRoot' | 'nodePath' | 'envPath' | 'checkExec' | 'resolveHostExe' | 'chattr' | 'isImmutable'> {
5
7
  /** The calling uid (default process.getuid()). */
6
8
  uid?: number;