@mago-foundation/mago-ski 0.4.1 → 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.
- package/README.md +5 -3
- package/dist/hosts/github/check.d.ts +21 -0
- package/dist/hosts/github/check.js +124 -0
- package/dist/hosts/github/publish.d.ts +7 -0
- package/dist/hosts/github/publish.js +52 -0
- package/dist/hosts/github/run.d.ts +3 -0
- package/dist/hosts/github/run.js +2 -2
- package/dist/src/admission-evidence.d.ts +15 -0
- package/dist/src/admission-evidence.js +48 -0
- package/dist/src/admission.d.ts +102 -0
- package/dist/src/admission.js +316 -0
- package/dist/src/cli.js +199 -2
- package/dist/src/diff.d.ts +4 -0
- package/dist/src/diff.js +1 -1
- package/dist/src/experimental/sigstore.d.ts +24 -0
- package/dist/src/experimental/sigstore.js +22 -0
- package/dist/src/fs-safe.d.ts +15 -2
- package/dist/src/fs-safe.js +68 -50
- package/dist/src/gate/adapters/claude-code.js +8 -6
- package/dist/src/gate/adapters/codex.js +2 -6
- package/dist/src/gate/instance.js +7 -8
- package/dist/src/gate/setup.js +36 -46
- package/dist/src/profile.d.ts +34 -0
- package/dist/src/profile.js +182 -0
- package/dist/src/published-by.d.ts +64 -0
- package/dist/src/published-by.js +227 -0
- package/dist/src/usf-check.d.ts +28 -0
- package/dist/src/usf-check.js +128 -0
- package/dist/src/usf.d.ts +48 -0
- package/dist/src/usf.js +238 -0
- package/docs/hosts/publish.md +65 -0
- package/docs/hosts/skill-check.md +91 -0
- package/docs/spec/admission-v0.md +84 -0
- package/docs/spec/observed-profile-v1.md +51 -0
- package/package.json +4 -1
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type ObservedProfile } from './profile.ts';
|
|
2
|
+
import { type UsfManifest } from './usf.ts';
|
|
3
|
+
export declare const PUBLISHED_BY_PREDICATE_TYPE = "https://magofoundation.dev/attestation/published-by/v1";
|
|
4
|
+
export declare const GITHUB_OIDC_ISSUER = "https://token.actions.githubusercontent.com";
|
|
5
|
+
export interface PublishedSkill {
|
|
6
|
+
/** Skill folder, relative to the repository root, with `/` separators. */
|
|
7
|
+
path: string;
|
|
8
|
+
/** Tree digest (mago.skill-tree/v2): the attestation subject. */
|
|
9
|
+
digest: string;
|
|
10
|
+
skill_md_sha256: string;
|
|
11
|
+
/** The USF declaration as read (see usf.ts), or null with the reason. */
|
|
12
|
+
declaration: UsfManifest | null;
|
|
13
|
+
declaration_error: string | null;
|
|
14
|
+
profile: ObservedProfile;
|
|
15
|
+
}
|
|
16
|
+
export interface PublishedByPredicate {
|
|
17
|
+
generator: {
|
|
18
|
+
name: 'mago-ski';
|
|
19
|
+
version: string;
|
|
20
|
+
};
|
|
21
|
+
skills: PublishedSkill[];
|
|
22
|
+
}
|
|
23
|
+
export declare function packageVersion(): string;
|
|
24
|
+
/** The record for one Skill folder, computed from its bytes. */
|
|
25
|
+
export declare function describeSkill(skillDir: string, root: string): Promise<PublishedSkill>;
|
|
26
|
+
/** Subject lines for actions/attest's `subject-checksums` input: `<hex> <name>`. */
|
|
27
|
+
export declare function subjectChecksums(skills: readonly PublishedSkill[]): string;
|
|
28
|
+
/** The Fulcio identity fields of a signing certificate. The certificate itself was verified by Cosign. */
|
|
29
|
+
export declare function fulcioIdentity(certificateDer: Buffer): Record<string, string>;
|
|
30
|
+
export interface VerifyPublishedByOptions {
|
|
31
|
+
bundlePath: string;
|
|
32
|
+
trustedRootPath: string;
|
|
33
|
+
cosignPath: string;
|
|
34
|
+
/** The publishing repository, `OWNER/NAME`; the signer's workflow must belong to it. Without it any GitHub repository is accepted and reported. */
|
|
35
|
+
repository?: string;
|
|
36
|
+
/** Optional workflow file inside it, e.g. `.github/workflows/publish.yml`. */
|
|
37
|
+
workflow?: string;
|
|
38
|
+
/** Optional numeric repository id: survives renames and cannot be claimed by a fork or a new repository of the same name. */
|
|
39
|
+
repositoryId?: string;
|
|
40
|
+
}
|
|
41
|
+
/** The normalised publisher identity (R7): ids and the workflow path survive renames; names are informational. */
|
|
42
|
+
export interface Publisher {
|
|
43
|
+
repository_id: string;
|
|
44
|
+
owner_id: string;
|
|
45
|
+
repository: string;
|
|
46
|
+
workflow: string;
|
|
47
|
+
commit: string;
|
|
48
|
+
ref: string;
|
|
49
|
+
trigger: string;
|
|
50
|
+
}
|
|
51
|
+
export declare function publisherOf(fields: Record<string, string>): Publisher;
|
|
52
|
+
export interface PublishedByFacts {
|
|
53
|
+
digest: string;
|
|
54
|
+
publisher: Record<string, string>;
|
|
55
|
+
/** The record the publisher's CI wrote for these bytes. */
|
|
56
|
+
recorded: PublishedSkill;
|
|
57
|
+
/** Differences between that record and what this verifier computed; empty when they agree. */
|
|
58
|
+
differences: string[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Checks a published-by bundle for a Skill folder. Throws when the bundle does not verify for these exact bytes and
|
|
62
|
+
* this publisher. Returns the publisher facts and any difference between the recorded and the recomputed record.
|
|
63
|
+
*/
|
|
64
|
+
export declare function verifyPublishedBy(skillDir: string, options: VerifyPublishedByOptions): Promise<PublishedByFacts>;
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// published-by (mago.published-by/v1): a publisher's CI states, with its own repository identity and no stored key,
|
|
2
|
+
// "this repository published these exact Skill bytes, with this declaration as read and this observed profile".
|
|
3
|
+
// Signing is done by GitHub's actions/attest (keyless Sigstore, public log for public repositories); this module
|
|
4
|
+
// builds the statement's content and verifies a bundle offline. A verifier recomputes everything from the bytes and
|
|
5
|
+
// never trusts what the publisher's CI computed. The output is facts about who published what; never "safe".
|
|
6
|
+
import { createHash, X509Certificate } from 'node:crypto';
|
|
7
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
8
|
+
import { createRequire } from 'node:module';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { verifySigstoreAttestation } from "./experimental/sigstore.js";
|
|
12
|
+
import { readRegularFile } from "./fs-safe.js";
|
|
13
|
+
import { profileTree } from "./profile.js";
|
|
14
|
+
import { collectSkillTree, SKILL_FILENAME } from "./tree-digest.js";
|
|
15
|
+
import { readUsf } from "./usf.js";
|
|
16
|
+
export const PUBLISHED_BY_PREDICATE_TYPE = 'https://magofoundation.dev/attestation/published-by/v1';
|
|
17
|
+
export const GITHUB_OIDC_ISSUER = 'https://token.actions.githubusercontent.com';
|
|
18
|
+
const IN_TOTO_STATEMENT_V1 = 'https://in-toto.io/Statement/v1';
|
|
19
|
+
const IN_TOTO_PAYLOAD_TYPE = 'application/vnd.in-toto+json';
|
|
20
|
+
const MAX_BUNDLE_BYTES = 16 * 1024 * 1024;
|
|
21
|
+
export function packageVersion() {
|
|
22
|
+
return createRequire(import.meta.url)('#package.json').version ?? 'unknown';
|
|
23
|
+
}
|
|
24
|
+
/** The record for one Skill folder, computed from its bytes. */
|
|
25
|
+
export async function describeSkill(skillDir, root) {
|
|
26
|
+
const tree = await collectSkillTree(skillDir, { includeContents: true });
|
|
27
|
+
const skillMd = tree.contents.get(SKILL_FILENAME);
|
|
28
|
+
const reading = readUsf(skillMd.toString('utf8'));
|
|
29
|
+
return {
|
|
30
|
+
path: path.relative(root, skillDir).split(path.sep).join('/') || '.',
|
|
31
|
+
digest: tree.digest,
|
|
32
|
+
skill_md_sha256: `sha256:${createHash('sha256').update(skillMd).digest('hex')}`,
|
|
33
|
+
declaration: reading.manifest,
|
|
34
|
+
declaration_error: reading.error,
|
|
35
|
+
profile: profileTree(tree),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Subject lines for actions/attest's `subject-checksums` input: `<hex> <name>`. */
|
|
39
|
+
export function subjectChecksums(skills) {
|
|
40
|
+
return skills.map((skill) => {
|
|
41
|
+
const name = `skill:${skill.path}`;
|
|
42
|
+
// One subject per line: a name with a line break (or other control character) would add a subject.
|
|
43
|
+
if (/[\u0000-\u001f\u007f]/u.test(name))
|
|
44
|
+
throw new Error(`Skill path ${JSON.stringify(skill.path)} contains a control character`);
|
|
45
|
+
return `${skill.digest.slice('sha256:'.length)} ${name}\n`;
|
|
46
|
+
}).join('');
|
|
47
|
+
}
|
|
48
|
+
function parseJson(bytes, label) {
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(bytes.toString('utf8'));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
throw new Error(`${label} is not JSON`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function bundleParts(bundle) {
|
|
57
|
+
const b = bundle;
|
|
58
|
+
const envelope = b?.dsseEnvelope;
|
|
59
|
+
if (typeof envelope?.payload !== 'string' || envelope.payloadType !== IN_TOTO_PAYLOAD_TYPE)
|
|
60
|
+
throw new Error('the bundle holds no in-toto DSSE envelope');
|
|
61
|
+
const raw = b.verificationMaterial?.certificate?.rawBytes ?? b.verificationMaterial?.x509CertificateChain?.certificates?.[0]?.rawBytes;
|
|
62
|
+
if (typeof raw !== 'string')
|
|
63
|
+
throw new Error('the bundle holds no signing certificate');
|
|
64
|
+
const statement = parseJson(Buffer.from(envelope.payload, 'base64'), 'the in-toto statement');
|
|
65
|
+
if (statement?._type !== IN_TOTO_STATEMENT_V1 || !Array.isArray(statement.subject))
|
|
66
|
+
throw new Error('the payload is not an in-toto v1 statement');
|
|
67
|
+
return { statement, certificate: Buffer.from(raw, 'base64') };
|
|
68
|
+
}
|
|
69
|
+
function tlv(der, offset, limit) {
|
|
70
|
+
if (offset + 2 > limit)
|
|
71
|
+
throw new Error('certificate DER is truncated');
|
|
72
|
+
const tag = der[offset];
|
|
73
|
+
let length = der[offset + 1];
|
|
74
|
+
let start = offset + 2;
|
|
75
|
+
if (length & 0x80) {
|
|
76
|
+
const bytes = length & 0x7f;
|
|
77
|
+
if (bytes === 0 || bytes > 4 || start + bytes > limit)
|
|
78
|
+
throw new Error('certificate DER has an unsupported length');
|
|
79
|
+
length = 0;
|
|
80
|
+
for (let index = 0; index < bytes; index += 1)
|
|
81
|
+
length = length * 256 + der[start + index];
|
|
82
|
+
start += bytes;
|
|
83
|
+
}
|
|
84
|
+
if (start + length > limit)
|
|
85
|
+
throw new Error('certificate DER is truncated');
|
|
86
|
+
return { tag, start, end: start + length, next: start + length };
|
|
87
|
+
}
|
|
88
|
+
function children(der, parent) {
|
|
89
|
+
const out = [];
|
|
90
|
+
for (let offset = parent.start; offset < parent.end; offset = out[out.length - 1].next)
|
|
91
|
+
out.push(tlv(der, offset, parent.end));
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
function oidString(bytes) {
|
|
95
|
+
const parts = [Math.floor(bytes[0] / 40), bytes[0] % 40];
|
|
96
|
+
let value = 0;
|
|
97
|
+
for (const byte of bytes.subarray(1)) {
|
|
98
|
+
value = value * 128 + (byte & 0x7f);
|
|
99
|
+
if ((byte & 0x80) === 0) {
|
|
100
|
+
parts.push(value);
|
|
101
|
+
value = 0;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return parts.join('.');
|
|
105
|
+
}
|
|
106
|
+
const FULCIO = '1.3.6.1.4.1.57264.1.';
|
|
107
|
+
/** Fulcio's provider-neutral extensions (1.3.6.1.4.1.57264.1.8 onwards), each a DER UTF8String. */
|
|
108
|
+
const FULCIO_FIELDS = {
|
|
109
|
+
'8': 'issuer', '9': 'build_signer_uri', '10': 'build_signer_digest', '11': 'runner_environment', '12': 'source_repository_uri',
|
|
110
|
+
'13': 'source_repository_digest', '14': 'source_repository_ref', '15': 'source_repository_id', '16': 'source_repository_owner_uri',
|
|
111
|
+
'17': 'source_repository_owner_id', '18': 'build_config_uri', '19': 'build_config_digest', '20': 'build_trigger', '21': 'run_invocation_uri',
|
|
112
|
+
};
|
|
113
|
+
/** The Fulcio identity fields of a signing certificate. The certificate itself was verified by Cosign. */
|
|
114
|
+
export function fulcioIdentity(certificateDer) {
|
|
115
|
+
const certificate = tlv(certificateDer, 0, certificateDer.length);
|
|
116
|
+
const tbs = children(certificateDer, certificate)[0];
|
|
117
|
+
if (!tbs)
|
|
118
|
+
throw new Error('certificate has no TBSCertificate');
|
|
119
|
+
const extensionsWrapper = children(certificateDer, tbs).find((item) => item.tag === 0xa3);
|
|
120
|
+
const fields = {};
|
|
121
|
+
if (!extensionsWrapper)
|
|
122
|
+
return fields;
|
|
123
|
+
const [extensions] = children(certificateDer, extensionsWrapper);
|
|
124
|
+
for (const extension of extensions ? children(certificateDer, extensions) : []) {
|
|
125
|
+
const parts = children(certificateDer, extension);
|
|
126
|
+
const oid = parts[0];
|
|
127
|
+
const value = parts[parts.length - 1];
|
|
128
|
+
if (!oid || oid.tag !== 0x06 || !value || value.tag !== 0x04)
|
|
129
|
+
continue;
|
|
130
|
+
const id = oidString(certificateDer.subarray(oid.start, oid.end));
|
|
131
|
+
if (!id.startsWith(FULCIO))
|
|
132
|
+
continue;
|
|
133
|
+
const name = FULCIO_FIELDS[id.slice(FULCIO.length)];
|
|
134
|
+
if (!name)
|
|
135
|
+
continue;
|
|
136
|
+
const inner = tlv(certificateDer, value.start, value.end);
|
|
137
|
+
if (inner.tag !== 0x0c)
|
|
138
|
+
continue;
|
|
139
|
+
fields[name] = certificateDer.subarray(inner.start, inner.end).toString('utf8');
|
|
140
|
+
}
|
|
141
|
+
return fields;
|
|
142
|
+
}
|
|
143
|
+
export function publisherOf(fields) {
|
|
144
|
+
const config = /^https:\/\/github\.com\/[^/]+\/[^/]+\/(\.github\/workflows\/[^@]+)@/u.exec(fields.build_config_uri ?? '');
|
|
145
|
+
const required = {
|
|
146
|
+
repository_id: fields.source_repository_id, owner_id: fields.source_repository_owner_id, repository: fields.source_repository_uri,
|
|
147
|
+
workflow: config?.[1], commit: fields.source_repository_digest, ref: fields.source_repository_ref, trigger: fields.build_trigger,
|
|
148
|
+
};
|
|
149
|
+
for (const [name, value] of Object.entries(required))
|
|
150
|
+
if (!value)
|
|
151
|
+
throw new Error(`the signing certificate has no ${name}`);
|
|
152
|
+
return required;
|
|
153
|
+
}
|
|
154
|
+
const escapeRegexp = (text) => text.replace(/[\\^$.*+?()[\]{}|/]/gu, '\\$&');
|
|
155
|
+
/**
|
|
156
|
+
* Checks a published-by bundle for a Skill folder. Throws when the bundle does not verify for these exact bytes and
|
|
157
|
+
* this publisher. Returns the publisher facts and any difference between the recorded and the recomputed record.
|
|
158
|
+
*/
|
|
159
|
+
export async function verifyPublishedBy(skillDir, options) {
|
|
160
|
+
if (options.repository !== undefined && !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(options.repository))
|
|
161
|
+
throw new RangeError('--repo must be OWNER/NAME');
|
|
162
|
+
if (options.workflow !== undefined && !/^\.github\/workflows\/[A-Za-z0-9_.\-/]+\.ya?ml$/u.test(options.workflow))
|
|
163
|
+
throw new RangeError('--workflow must be a path such as .github/workflows/publish.yml');
|
|
164
|
+
if (options.repositoryId !== undefined && !/^[0-9]{1,20}$/u.test(options.repositoryId))
|
|
165
|
+
throw new RangeError('--repo-id must be the numeric repository id');
|
|
166
|
+
const mine = await describeSkill(skillDir, path.dirname(path.resolve(skillDir)));
|
|
167
|
+
const digestHex = mine.digest.slice('sha256:'.length);
|
|
168
|
+
// Cosign checks a private copy, and the statement is read from the same bytes: the file cannot change in between.
|
|
169
|
+
const bytes = await readRegularFile(options.bundlePath, 'Sigstore bundle', MAX_BUNDLE_BYTES);
|
|
170
|
+
const parts = bundleParts(parseJson(bytes, 'the Sigstore bundle'));
|
|
171
|
+
// Plain-words reasons for the common refusals, read before Cosign runs. Cosign still decides; these only explain.
|
|
172
|
+
if (!parts.statement.subject.some((subject) => subject?.digest?.sha256 === digestHex))
|
|
173
|
+
throw new Error(`the attestation is for other bytes: it does not name this Skill's digest ${mine.digest}`);
|
|
174
|
+
const claimed = fulcioIdentity(parts.certificate);
|
|
175
|
+
if (options.repository !== undefined && !(claimed.build_signer_uri ?? '').toLowerCase().startsWith(`https://github.com/${options.repository.toLowerCase()}/`))
|
|
176
|
+
throw new Error(`the attestation was signed by ${claimed.build_signer_uri ?? 'an unknown signer'}, not by a workflow of ${options.repository}`);
|
|
177
|
+
if (options.workflow !== undefined && !(claimed.build_signer_uri ?? '').includes(`/${options.workflow}@`))
|
|
178
|
+
throw new Error(`the attestation was signed by ${claimed.build_signer_uri ?? 'an unknown signer'}, not by ${options.workflow}`);
|
|
179
|
+
const scratch = await mkdtemp(path.join(os.tmpdir(), 'mago-ski-bundle-'));
|
|
180
|
+
try {
|
|
181
|
+
const copy = path.join(scratch, 'bundle.json');
|
|
182
|
+
await writeFile(copy, bytes, { mode: 0o600, flag: 'wx' });
|
|
183
|
+
const workflow = options.workflow === undefined ? '\\.github/workflows/[^@]+' : escapeRegexp(options.workflow);
|
|
184
|
+
await verifySigstoreAttestation({
|
|
185
|
+
binaryPath: options.cosignPath, bundlePath: copy, trustedRootPath: options.trustedRootPath, digestHex,
|
|
186
|
+
predicateType: PUBLISHED_BY_PREDICATE_TYPE, issuer: GITHUB_OIDC_ISSUER,
|
|
187
|
+
identityRegexp: `^https://github\\.com/${options.repository === undefined ? '[^/]+/[^/]+' : escapeRegexp(options.repository)}/${workflow}@`,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
await rm(scratch, { recursive: true, force: true });
|
|
192
|
+
}
|
|
193
|
+
const { statement, certificate } = parts;
|
|
194
|
+
if (statement.predicateType !== PUBLISHED_BY_PREDICATE_TYPE)
|
|
195
|
+
throw new Error('the statement is not a published-by statement');
|
|
196
|
+
if (!statement.subject.some((subject) => subject?.digest?.sha256 === digestHex))
|
|
197
|
+
throw new Error('the statement does not name this Skill\'s digest');
|
|
198
|
+
const predicate = statement.predicate;
|
|
199
|
+
const recorded = Array.isArray(predicate?.skills) ? predicate.skills.find((skill) => skill?.digest === mine.digest) : undefined;
|
|
200
|
+
if (!recorded)
|
|
201
|
+
throw new Error('the statement has no record for this Skill\'s digest');
|
|
202
|
+
new X509Certificate(certificate); // a parse check only: Cosign verified the chain
|
|
203
|
+
const publisher = fulcioIdentity(certificate);
|
|
204
|
+
if (publisher.issuer !== GITHUB_OIDC_ISSUER)
|
|
205
|
+
throw new Error('the signing certificate was not issued for a GitHub Actions identity');
|
|
206
|
+
// Cosign matched the signing workflow (the certificate's SAN). The repository whose code ran and the top-level workflow
|
|
207
|
+
// are separate fields: with a reusable workflow they differ, so both are required to match as well.
|
|
208
|
+
const normalised = publisherOf(publisher);
|
|
209
|
+
const asciiLower = (value) => value.replace(/[A-Z]/gu, (c) => c.toLowerCase());
|
|
210
|
+
if (options.repository !== undefined && asciiLower(normalised.repository) !== asciiLower(`https://github.com/${options.repository}`))
|
|
211
|
+
throw new Error(`the signed code came from ${normalised.repository}, not ${options.repository}`);
|
|
212
|
+
if (options.workflow !== undefined && normalised.workflow !== options.workflow)
|
|
213
|
+
throw new Error(`the top-level workflow is ${normalised.workflow}, not ${options.workflow}`);
|
|
214
|
+
if (options.repositoryId !== undefined && publisher.source_repository_id !== options.repositoryId)
|
|
215
|
+
throw new Error(`the signer's repository id is ${publisher.source_repository_id ?? 'missing'}, not ${options.repositoryId}`);
|
|
216
|
+
const differences = [];
|
|
217
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
218
|
+
if (recorded.profile?.profile !== mine.profile.profile)
|
|
219
|
+
differences.push(`the record uses ${String(recorded.profile?.profile)}; this verifier computes ${mine.profile.profile}`);
|
|
220
|
+
else if (!same(recorded.profile, mine.profile))
|
|
221
|
+
differences.push('the recorded observed profile differs from the one computed from these bytes');
|
|
222
|
+
if (!same(recorded.declaration, mine.declaration))
|
|
223
|
+
differences.push('the recorded declaration differs from the one read from these bytes');
|
|
224
|
+
if (recorded.skill_md_sha256 !== mine.skill_md_sha256)
|
|
225
|
+
differences.push('the recorded SKILL.md hash differs');
|
|
226
|
+
return { digest: mine.digest, publisher, recorded, differences };
|
|
227
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type ObservedProfile } from './profile.ts';
|
|
2
|
+
import { USF_FORMAT, type UsfManifest } from './usf.ts';
|
|
3
|
+
export interface CheckOptions {
|
|
4
|
+
/** Fail Skills that have no USF manifest (or one that cannot be read). Default false: they are reported. */
|
|
5
|
+
requireManifest?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface SkillCheck {
|
|
8
|
+
format: typeof USF_FORMAT;
|
|
9
|
+
/** Directory relative to the checked root. */
|
|
10
|
+
dir: string;
|
|
11
|
+
ok: boolean;
|
|
12
|
+
/** Null only when the Skill folder could not be read at all. */
|
|
13
|
+
profile: ObservedProfile | null;
|
|
14
|
+
manifest: UsfManifest | null;
|
|
15
|
+
/** Whether SKILL.md has a `permissions` block, readable or not. */
|
|
16
|
+
declared: boolean;
|
|
17
|
+
manifestError: string | null;
|
|
18
|
+
undeclaredHosts: string[];
|
|
19
|
+
/** Plain-word reasons the check failed; empty when it passed. */
|
|
20
|
+
problems: string[];
|
|
21
|
+
/** Plain-word remarks that do not fail the check. */
|
|
22
|
+
notes: string[];
|
|
23
|
+
}
|
|
24
|
+
/** The `permissions` block a Skill could paste, filled in from its profile. */
|
|
25
|
+
export declare function suggestedManifest(check: Pick<SkillCheck, 'profile' | 'manifest'>): string;
|
|
26
|
+
export declare function checkSkill(skillDir: string, root: string, options?: CheckOptions): Promise<SkillCheck>;
|
|
27
|
+
/** What a pull request adds to a Skill, in plain words, compared with the base revision. */
|
|
28
|
+
export declare function describeAdditions(base: SkillCheck | null, head: SkillCheck): string[];
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// The free Skill check. Every Skill gets its observed profile (what its bytes show). When the Skill also declares
|
|
2
|
+
// its needs in an OWASP USF manifest, the declaration must cover the profile: a web address on a site that
|
|
3
|
+
// `network.allow` does not list, or scripts and shell code while `shell` is not true, fail the check.
|
|
4
|
+
// A Skill without a manifest passes with its profile shown, unless the repository requires a manifest.
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { profileTree } from "./profile.js";
|
|
7
|
+
import { collectSkillTree, SKILL_FILENAME } from "./tree-digest.js";
|
|
8
|
+
import { hostAllowed, readUsf, USF_FORMAT } from "./usf.js";
|
|
9
|
+
function list(values, limit = 10) {
|
|
10
|
+
const shown = values.slice(0, limit).join(', ');
|
|
11
|
+
return values.length > limit ? `${shown} and ${values.length - limit} more` : shown;
|
|
12
|
+
}
|
|
13
|
+
/** The `permissions` block a Skill could paste, filled in from its profile. */
|
|
14
|
+
export function suggestedManifest(check) {
|
|
15
|
+
// Host names pass the URL parser, which still allows characters such as backticks; only plain names are suggested.
|
|
16
|
+
const hosts = [...new Set([...(check.manifest?.network.allow ?? []), ...(check.profile?.web_hosts ?? [])])]
|
|
17
|
+
.filter((host) => /^(?:\*|(?:\*\.)?[a-z0-9.-]+|\[[0-9a-f:.]+\])$/u.test(host)).sort();
|
|
18
|
+
const shell = check.manifest?.shell === true || (check.profile?.scripts.length ?? 0) > 0;
|
|
19
|
+
return [
|
|
20
|
+
'permissions:',
|
|
21
|
+
' network:',
|
|
22
|
+
` allow: [${hosts.map((host) => JSON.stringify(host)).join(', ')}]`,
|
|
23
|
+
' deny: "*"',
|
|
24
|
+
` shell: ${shell}`,
|
|
25
|
+
].join('\n');
|
|
26
|
+
}
|
|
27
|
+
export async function checkSkill(skillDir, root, options = {}) {
|
|
28
|
+
const result = {
|
|
29
|
+
format: USF_FORMAT, dir: path.relative(root, skillDir) || '.', ok: false, profile: null, manifest: null, declared: false,
|
|
30
|
+
manifestError: null, undeclaredHosts: [], problems: [], notes: [],
|
|
31
|
+
};
|
|
32
|
+
let tree;
|
|
33
|
+
try {
|
|
34
|
+
tree = await collectSkillTree(skillDir, { includeContents: true });
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
result.problems.push(`the Skill folder could not be read: ${error.message}`);
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
const profile = profileTree(tree);
|
|
41
|
+
result.profile = profile;
|
|
42
|
+
const reading = readUsf(tree.contents.get(SKILL_FILENAME).toString('utf8'));
|
|
43
|
+
result.manifest = reading.manifest;
|
|
44
|
+
result.declared = reading.declared;
|
|
45
|
+
result.manifestError = reading.error;
|
|
46
|
+
const gaps = [];
|
|
47
|
+
if (profile.not_searched.unreadable.length > 0)
|
|
48
|
+
gaps.push(`files that cannot be searched (binary, not UTF-8 text, or larger than 2 MiB): ${list(profile.not_searched.unreadable)}`);
|
|
49
|
+
if (profile.not_searched.ignored.length > 0)
|
|
50
|
+
gaps.push(`files left out by .skilldigestignore: ${list(profile.not_searched.ignored)}`);
|
|
51
|
+
if (!profile.complete && gaps.length === 0)
|
|
52
|
+
gaps.push('too many web addresses to check them all (more than 128 different sites, or more than 100,000 addresses)');
|
|
53
|
+
if (profile.not_searched.media.length > 0)
|
|
54
|
+
result.notes.push(`images, fonts and media files were not searched: ${list(profile.not_searched.media)}`);
|
|
55
|
+
const manifest = reading.manifest;
|
|
56
|
+
if (manifest) {
|
|
57
|
+
// A declaration is only worth something when it covers everything: gaps fail here.
|
|
58
|
+
result.problems.push(...gaps.map((gap) => `the declaration cannot be checked against ${gap}`));
|
|
59
|
+
result.undeclaredHosts = profile.web_hosts.filter((host) => !hostAllowed(manifest.network.allow, host));
|
|
60
|
+
if (result.undeclaredHosts.length > 0)
|
|
61
|
+
result.problems.push(`uses web addresses on sites it does not declare in permissions.network.allow: ${list(result.undeclaredHosts)}`);
|
|
62
|
+
if (manifest.shell !== true && profile.scripts.length > 0)
|
|
63
|
+
result.problems.push(`contains scripts or shell commands, but permissions.shell is ${manifest.shell === false ? 'false' : 'not set'}: ${list(profile.scripts.map((script) => `${script.path} (${script.reason})`), 5)}`);
|
|
64
|
+
const undeclaredPrograms = profile.programs.filter((program) => !manifest.requires.binaries.includes(program));
|
|
65
|
+
if (manifest.requires.binaries.length > 0 && undeclaredPrograms.length > 0)
|
|
66
|
+
result.notes.push(`shell code blocks name programs not in requires.binaries (not checked): ${list(undeclaredPrograms)}`);
|
|
67
|
+
if (manifest.network.allow.includes('*'))
|
|
68
|
+
result.notes.push('declares that it may contact any website (network.allow: "*")');
|
|
69
|
+
if (manifest.network.deny !== null && manifest.network.deny !== '*')
|
|
70
|
+
result.notes.push(`network.deny is "${manifest.network.deny}"; USF expects "*"`);
|
|
71
|
+
if (manifest.unknownKeys.length > 0)
|
|
72
|
+
result.notes.push(`keys this check does not know were not checked: ${list(manifest.unknownKeys)}`);
|
|
73
|
+
}
|
|
74
|
+
else if (reading.declared) {
|
|
75
|
+
// The author meant to declare, but the declaration cannot be read one way only.
|
|
76
|
+
result.problems.push(`the USF declaration in ${SKILL_FILENAME} cannot be read reliably: ${reading.error}`);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
if (reading.error)
|
|
80
|
+
result.notes.push(`${SKILL_FILENAME} frontmatter: ${reading.error}. Hosts may not read this Skill's name and description`);
|
|
81
|
+
const missing = `${SKILL_FILENAME} has no USF "permissions" block, so only what its files show is reported`;
|
|
82
|
+
if (options.requireManifest)
|
|
83
|
+
result.problems.push(missing, ...gaps);
|
|
84
|
+
else
|
|
85
|
+
result.notes.push(missing, ...gaps);
|
|
86
|
+
}
|
|
87
|
+
result.ok = result.problems.length === 0;
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
/** What a pull request adds to a Skill, in plain words, compared with the base revision. */
|
|
91
|
+
export function describeAdditions(base, head) {
|
|
92
|
+
if (base === null)
|
|
93
|
+
return ['adds this Skill'];
|
|
94
|
+
const added = (before, after) => after.filter((value) => !before.includes(value));
|
|
95
|
+
const lines = [];
|
|
96
|
+
const before = base.manifest;
|
|
97
|
+
const after = head.manifest;
|
|
98
|
+
const newSites = added(base.profile?.web_hosts ?? [], head.profile?.web_hosts ?? []);
|
|
99
|
+
if (newSites.length > 0)
|
|
100
|
+
lines.push(`uses new websites: ${list(newSites)}`);
|
|
101
|
+
const newAllowed = added(before?.network.allow ?? [], after?.network.allow ?? []);
|
|
102
|
+
if (newAllowed.length > 0)
|
|
103
|
+
lines.push(`declares permission for new websites: ${list(newAllowed)}`);
|
|
104
|
+
if (before?.shell !== true && after?.shell === true)
|
|
105
|
+
lines.push('asks for permission to run commands (shell: true)');
|
|
106
|
+
const newScripts = added((base.profile?.scripts ?? []).map((script) => script.path), (head.profile?.scripts ?? []).map((script) => script.path));
|
|
107
|
+
if (newScripts.length > 0)
|
|
108
|
+
lines.push(`adds scripts or shell commands: ${list(newScripts)}`);
|
|
109
|
+
const newPrograms = added(base.profile?.programs ?? [], head.profile?.programs ?? []);
|
|
110
|
+
if (newPrograms.length > 0)
|
|
111
|
+
lines.push(`names new programs in shell code: ${list(newPrograms)}`);
|
|
112
|
+
const newReads = added(before?.files.read ?? [], after?.files.read ?? []);
|
|
113
|
+
if (newReads.length > 0)
|
|
114
|
+
lines.push(`asks to read new files: ${list(newReads)}`);
|
|
115
|
+
const newWrites = added(before?.files.write ?? [], after?.files.write ?? []);
|
|
116
|
+
if (newWrites.length > 0)
|
|
117
|
+
lines.push(`asks to write new files: ${list(newWrites)}`);
|
|
118
|
+
const unprotected = (before?.files.deny_write ?? []).filter((file) => !(after?.files.deny_write ?? []).includes(file));
|
|
119
|
+
if (unprotected.length > 0)
|
|
120
|
+
lines.push(`no longer protects these files from writes: ${list(unprotected)}`);
|
|
121
|
+
const newTools = added(before?.tools ?? [], after?.tools ?? []);
|
|
122
|
+
if (newTools.length > 0)
|
|
123
|
+
lines.push(`asks for new tools: ${list(newTools)}`);
|
|
124
|
+
const newBinaries = added(before?.requires.binaries ?? [], after?.requires.binaries ?? []);
|
|
125
|
+
if (newBinaries.length > 0)
|
|
126
|
+
lines.push(`needs new programs: ${list(newBinaries)}`);
|
|
127
|
+
return lines;
|
|
128
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export declare const USF_FORMAT = "owasp.usf/v1.0";
|
|
2
|
+
/** Frontmatter larger than this is not read. */
|
|
3
|
+
export declare const MAX_FRONTMATTER_BYTES: number;
|
|
4
|
+
export interface UsfManifest {
|
|
5
|
+
files: {
|
|
6
|
+
read: string[];
|
|
7
|
+
write: string[];
|
|
8
|
+
deny_write: string[];
|
|
9
|
+
};
|
|
10
|
+
network: {
|
|
11
|
+
allow: string[];
|
|
12
|
+
deny: string | null;
|
|
13
|
+
};
|
|
14
|
+
shell: boolean | null;
|
|
15
|
+
tools: string[];
|
|
16
|
+
requires: {
|
|
17
|
+
binaries: string[];
|
|
18
|
+
min_runtime_version: string | null;
|
|
19
|
+
};
|
|
20
|
+
/** Keys this reader does not know; they are listed, not enforced. */
|
|
21
|
+
unknownKeys: string[];
|
|
22
|
+
}
|
|
23
|
+
export interface UsfReading {
|
|
24
|
+
/** The declaration, when the frontmatter has a `permissions` block that reads the same under YAML 1.1 and 1.2. */
|
|
25
|
+
manifest: UsfManifest | null;
|
|
26
|
+
/** Whether the frontmatter has a `permissions` key at all. */
|
|
27
|
+
declared: boolean;
|
|
28
|
+
/** Why the frontmatter or the declaration could not be read; null when it could. */
|
|
29
|
+
error: string | null;
|
|
30
|
+
/** Fields whose YAML 1.1 and YAML 1.2 readings differ. */
|
|
31
|
+
ambiguous: string[];
|
|
32
|
+
}
|
|
33
|
+
export declare class UsfError extends Error {
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The frontmatter text between the opening and the closing `---`, or null when SKILL.md has none.
|
|
37
|
+
* Lines end at LF or CRLF, as in the Markdown frontmatter convention hosts follow.
|
|
38
|
+
*/
|
|
39
|
+
export declare function frontmatter(skillMd: string): string | null;
|
|
40
|
+
/** A `network.allow` entry: a host name, `*.` plus a host name (its subdomains), a bracketed IPv6 address, or `*` (any host). */
|
|
41
|
+
export declare function normalizeHostEntry(entry: string): string;
|
|
42
|
+
/**
|
|
43
|
+
* Reads the USF declaration from SKILL.md. Never throws on Skill content: a Skill without frontmatter, with
|
|
44
|
+
* frontmatter that is not YAML, or without a `permissions` block simply has no declaration, and `error` says why.
|
|
45
|
+
*/
|
|
46
|
+
export declare function readUsf(skillMd: string): UsfReading;
|
|
47
|
+
/** Whether a declared `network.allow` list covers a host found in the Skill's files. */
|
|
48
|
+
export declare function hostAllowed(allow: readonly string[], host: string): boolean;
|