@mago-foundation/mago-ski 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +121 -2
  4. package/action.yml +58 -0
  5. package/dist/hosts/github/run.d.ts +21 -0
  6. package/dist/hosts/github/run.js +119 -0
  7. package/dist/hosts/pi/index.d.ts +11 -0
  8. package/dist/hosts/pi/index.js +388 -0
  9. package/dist/hosts/pi/paths.d.ts +9 -0
  10. package/dist/hosts/pi/paths.js +55 -0
  11. package/dist/src/admin.d.ts +70 -0
  12. package/dist/src/admin.js +115 -0
  13. package/dist/src/canonical-json.d.ts +12 -0
  14. package/dist/src/canonical-json.js +104 -0
  15. package/dist/src/certificate.d.ts +34 -0
  16. package/dist/src/certificate.js +104 -0
  17. package/dist/src/cli.d.ts +2 -0
  18. package/dist/src/cli.js +419 -0
  19. package/dist/src/diff.d.ts +30 -0
  20. package/dist/src/diff.js +148 -0
  21. package/dist/src/dsse.d.ts +23 -0
  22. package/dist/src/dsse.js +55 -0
  23. package/dist/src/experimental/sigstore.d.ts +26 -0
  24. package/dist/src/experimental/sigstore.js +153 -0
  25. package/dist/src/fs-safe.d.ts +11 -0
  26. package/dist/src/fs-safe.js +96 -0
  27. package/dist/src/index.d.ts +14 -0
  28. package/dist/src/index.js +14 -0
  29. package/dist/src/keys.d.ts +21 -0
  30. package/dist/src/keys.js +108 -0
  31. package/dist/src/main-module.d.ts +5 -0
  32. package/dist/src/main-module.js +19 -0
  33. package/dist/src/names.d.ts +7 -0
  34. package/dist/src/names.js +40 -0
  35. package/dist/src/policy.d.ts +59 -0
  36. package/dist/src/policy.js +237 -0
  37. package/dist/src/revocations.d.ts +28 -0
  38. package/dist/src/revocations.js +91 -0
  39. package/dist/src/time.d.ts +9 -0
  40. package/dist/src/time.js +32 -0
  41. package/dist/src/tree-digest.d.ts +43 -0
  42. package/dist/src/tree-digest.js +243 -0
  43. package/dist/src/trust-root.d.ts +33 -0
  44. package/dist/src/trust-root.js +115 -0
  45. package/dist/src/verify.d.ts +73 -0
  46. package/dist/src/verify.js +134 -0
  47. package/docs/hosts/adapter-interface.md +33 -0
  48. package/docs/hosts/github-action.md +45 -0
  49. package/docs/hosts/pi.md +36 -0
  50. package/docs/spec/skill-certificate-v1.md +60 -0
  51. package/docs/spec/skill-tree-v2.md +59 -0
  52. package/docs/spec/trust-documents-v1.md +103 -0
  53. package/docs/spec/verification.md +46 -0
  54. package/docs/threat-model.md +44 -0
  55. package/package.json +74 -4
@@ -0,0 +1,30 @@
1
+ export interface FileChange {
2
+ path: string;
3
+ change: 'added' | 'deleted' | 'modified' | 'mode-changed';
4
+ before_bytes: number;
5
+ after_bytes: number;
6
+ exec_before: boolean | null;
7
+ exec_after: boolean | null;
8
+ changed_sections: string[];
9
+ sections_truncated: boolean;
10
+ }
11
+ export interface DiffResult {
12
+ result: 'UNCHANGED' | 'CAPABILITY_CHANGED' | 'CONTENT_CHANGED';
13
+ recertification_required: boolean;
14
+ base_digest: string;
15
+ candidate_digest: string;
16
+ capability_evidence: {
17
+ profile: 'mago.network-origin-scan/v1';
18
+ analysis_complete: boolean;
19
+ added_network_origins: string[];
20
+ removed_network_origins: string[];
21
+ note: string;
22
+ };
23
+ diff_truncated: boolean;
24
+ files: FileChange[];
25
+ }
26
+ /**
27
+ * Compares two Skill directories. Any digest difference requires a new certificate,
28
+ * whatever the capability evidence says: unchanged origins never waive a content change.
29
+ */
30
+ export declare function diffSkillTrees(baseRoot: string, candidateRoot: string): Promise<DiffResult>;
@@ -0,0 +1,148 @@
1
+ import { collectSkillTree } from "./tree-digest.js";
2
+ const textDecoder = new TextDecoder('utf-8', { fatal: true });
3
+ const MAX_ANALYZED_TEXT_BYTES = 2 * 1024 * 1024;
4
+ const MAX_REPORTED_FILES = 200;
5
+ const MAX_REPORTED_SECTIONS = 32;
6
+ const MAX_ORIGINS = 128;
7
+ const urlPattern = /https?:\/\/[^\s"'`<>()[\]{}]+/giu;
8
+ function collectOrigins(contents) {
9
+ const origins = new Set();
10
+ let complete = true;
11
+ for (const content of contents.values()) {
12
+ if (content.length > MAX_ANALYZED_TEXT_BYTES || content.includes(0)) {
13
+ complete = false;
14
+ continue;
15
+ }
16
+ let text;
17
+ try {
18
+ text = textDecoder.decode(content);
19
+ }
20
+ catch {
21
+ complete = false;
22
+ continue;
23
+ }
24
+ for (const match of text.matchAll(urlPattern)) {
25
+ try {
26
+ const parsed = new URL(match[0].replace(/[.,;:!?]+$/u, ''));
27
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
28
+ continue;
29
+ const origin = parsed.origin.toLowerCase();
30
+ if (origins.has(origin))
31
+ continue;
32
+ if (origins.size >= MAX_ORIGINS) {
33
+ complete = false;
34
+ continue;
35
+ }
36
+ origins.add(origin);
37
+ }
38
+ catch {
39
+ // URL-like text that does not parse is not capability evidence.
40
+ }
41
+ }
42
+ }
43
+ return { origins: [...origins].sort(), complete };
44
+ }
45
+ function markdownSections(content) {
46
+ let text;
47
+ try {
48
+ text = textDecoder.decode(content);
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ const sections = new Map();
54
+ const occurrence = new Map();
55
+ let current = '(document body)';
56
+ let body = [];
57
+ const flush = () => sections.set(current, body.join('\n'));
58
+ for (const line of text.split(/\r?\n/u)) {
59
+ const heading = /^(#{1,6})[ \t]+(.+?)\s*#*\s*$/u.exec(line);
60
+ if (heading) {
61
+ flush();
62
+ const label = heading[2].trim() || '(empty heading)';
63
+ const count = (occurrence.get(label) ?? 0) + 1;
64
+ occurrence.set(label, count);
65
+ current = count === 1 ? label : `${label} (${count})`;
66
+ body = [line];
67
+ }
68
+ else {
69
+ body.push(line);
70
+ }
71
+ }
72
+ flush();
73
+ return sections;
74
+ }
75
+ function changedSections(filePath, before, after) {
76
+ if (!before || !after)
77
+ return { sections: [before ? '(file removed)' : '(file added)'], truncated: false };
78
+ if (before.equals(after))
79
+ return { sections: [], truncated: false };
80
+ if (!/\.md$/iu.test(filePath))
81
+ return { sections: ['(whole file)'], truncated: false };
82
+ if (before.length > MAX_ANALYZED_TEXT_BYTES || after.length > MAX_ANALYZED_TEXT_BYTES)
83
+ return { sections: ['(whole file; size limit)'], truncated: true };
84
+ const beforeSections = markdownSections(before);
85
+ const afterSections = markdownSections(after);
86
+ if (!beforeSections || !afterSections)
87
+ return { sections: ['(whole file; non-text content)'], truncated: false };
88
+ const names = new Set([...beforeSections.keys(), ...afterSections.keys()]);
89
+ const changed = [...names].filter((name) => beforeSections.get(name) !== afterSections.get(name)).sort();
90
+ return { sections: changed.slice(0, MAX_REPORTED_SECTIONS), truncated: changed.length > MAX_REPORTED_SECTIONS };
91
+ }
92
+ function fileChanges(beforeFiles, afterFiles, beforeContents, afterContents) {
93
+ const beforeByPath = new Map(beforeFiles.map((file) => [file.path, file]));
94
+ const afterByPath = new Map(afterFiles.map((file) => [file.path, file]));
95
+ const paths = [...new Set([...beforeByPath.keys(), ...afterByPath.keys()])].sort();
96
+ const changes = [];
97
+ for (const filePath of paths) {
98
+ const before = beforeByPath.get(filePath);
99
+ const after = afterByPath.get(filePath);
100
+ if (before && after && before.sha256 === after.sha256 && before.exec === after.exec)
101
+ continue;
102
+ const change = !before ? 'added' : !after ? 'deleted' : before.sha256 === after.sha256 ? 'mode-changed' : 'modified';
103
+ const sections = changedSections(filePath, beforeContents.get(filePath), afterContents.get(filePath));
104
+ changes.push({
105
+ path: filePath,
106
+ change,
107
+ before_bytes: before?.size ?? 0,
108
+ after_bytes: after?.size ?? 0,
109
+ exec_before: before?.exec ?? null,
110
+ exec_after: after?.exec ?? null,
111
+ changed_sections: change === 'mode-changed' ? ['(executable bit)'] : sections.sections,
112
+ sections_truncated: sections.truncated,
113
+ });
114
+ }
115
+ return changes;
116
+ }
117
+ /**
118
+ * Compares two Skill directories. Any digest difference requires a new certificate,
119
+ * whatever the capability evidence says: unchanged origins never waive a content change.
120
+ */
121
+ export async function diffSkillTrees(baseRoot, candidateRoot) {
122
+ const base = await collectSkillTree(baseRoot, { includeContents: true });
123
+ const candidate = await collectSkillTree(candidateRoot, { includeContents: true });
124
+ const changed = base.digest !== candidate.digest;
125
+ const changes = changed ? fileChanges(base.files, candidate.files, base.contents, candidate.contents) : [];
126
+ const bounded = changes.slice(0, MAX_REPORTED_FILES);
127
+ const truncated = changes.length > MAX_REPORTED_FILES || bounded.some((entry) => entry.sections_truncated);
128
+ const baseOrigins = collectOrigins(base.contents);
129
+ const candidateOrigins = collectOrigins(candidate.contents);
130
+ const added = candidateOrigins.origins.filter((origin) => !baseOrigins.origins.includes(origin));
131
+ const removed = baseOrigins.origins.filter((origin) => !candidateOrigins.origins.includes(origin));
132
+ const capabilityChanged = added.length > 0 || removed.length > 0;
133
+ return {
134
+ result: !changed ? 'UNCHANGED' : capabilityChanged ? 'CAPABILITY_CHANGED' : 'CONTENT_CHANGED',
135
+ recertification_required: changed,
136
+ base_digest: base.digest,
137
+ candidate_digest: candidate.digest,
138
+ capability_evidence: {
139
+ profile: 'mago.network-origin-scan/v1',
140
+ analysis_complete: baseOrigins.complete && candidateOrigins.complete && !truncated,
141
+ added_network_origins: added,
142
+ removed_network_origins: removed,
143
+ note: 'Partial evidence: only HTTP(S) origins in text files are detected. No detected change does not make changed content safe or approved.',
144
+ },
145
+ diff_truncated: truncated,
146
+ files: bounded,
147
+ };
148
+ }
@@ -0,0 +1,23 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ export interface Envelope {
3
+ payloadType: string;
4
+ payload: string;
5
+ signatures: [{
6
+ keyid: string;
7
+ sig: string;
8
+ }];
9
+ }
10
+ /** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
11
+ export declare function preAuthEncoding(payloadType: string, payload: Uint8Array): Buffer;
12
+ export declare function signEnvelope(payloadType: string, payload: Uint8Array, keyId: string, privateKey: KeyObject): Envelope;
13
+ export declare function envelopeBytes(envelope: Envelope): Buffer;
14
+ /** Parses an envelope file. Does not check the signature. */
15
+ export declare function parseEnvelope(bytes: Uint8Array, label: string): Envelope & {
16
+ payloadBytes: Buffer;
17
+ sigBytes: Buffer;
18
+ };
19
+ export declare function verifyEnvelopeSignature(envelope: {
20
+ payloadType: string;
21
+ payloadBytes: Buffer;
22
+ sigBytes: Buffer;
23
+ }, publicKey: KeyObject): boolean;
@@ -0,0 +1,55 @@
1
+ // DSSE (Dead Simple Signing Envelope) v1 with exactly one Ed25519 signature.
2
+ // https://github.com/secure-systems-lab/dsse/blob/master/protocol.md
3
+ import { sign, verify } from 'node:crypto';
4
+ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
5
+ import { validateKeyId } from "./keys.js";
6
+ const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
7
+ /** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
8
+ export function preAuthEncoding(payloadType, payload) {
9
+ const type = Buffer.from(payloadType, 'utf8');
10
+ return Buffer.concat([
11
+ Buffer.from(`DSSEv1 ${type.length} `, 'ascii'), type,
12
+ Buffer.from(` ${payload.length} `, 'ascii'), Buffer.from(payload),
13
+ ]);
14
+ }
15
+ export function signEnvelope(payloadType, payload, keyId, privateKey) {
16
+ const sig = sign(null, preAuthEncoding(payloadType, payload), privateKey).toString('base64');
17
+ return { payloadType, payload: Buffer.from(payload).toString('base64'), signatures: [{ keyid: keyId, sig }] };
18
+ }
19
+ export function envelopeBytes(envelope) {
20
+ return canonicalBytes(envelope);
21
+ }
22
+ function decodeBase64(value, label, maxLength) {
23
+ if (typeof value !== 'string' || value.length === 0 || value.length > maxLength || !BASE64_PATTERN.test(value)) {
24
+ throw new Error(`${label} must be canonical base64`);
25
+ }
26
+ const bytes = Buffer.from(value, 'base64');
27
+ if (bytes.toString('base64') !== value)
28
+ throw new Error(`${label} must be canonical base64`);
29
+ return bytes;
30
+ }
31
+ /** Parses an envelope file. Does not check the signature. */
32
+ export function parseEnvelope(bytes, label) {
33
+ const value = exactKeys(parseCanonicalJsonBytes(bytes, label), ['payloadType', 'payload', 'signatures'], label);
34
+ const payloadType = requireString(value.payloadType, `${label} payloadType`, 256);
35
+ const payloadBytes = decodeBase64(value.payload, `${label} payload`, 6 * 1024 * 1024);
36
+ const signatures = requireArray(value.signatures, `${label} signatures`, 1);
37
+ if (signatures.length !== 1)
38
+ throw new Error(`${label} must carry exactly one signature`);
39
+ const signature = exactKeys(signatures[0], ['keyid', 'sig'], `${label} signature`);
40
+ const keyid = validateKeyId(signature.keyid, `${label} signature keyid`);
41
+ const sigBytes = decodeBase64(signature.sig, `${label} signature`, 128);
42
+ if (sigBytes.length !== 64)
43
+ throw new Error(`${label} signature must be a 64-byte Ed25519 signature`);
44
+ return {
45
+ payloadType, payload: value.payload, signatures: [{ keyid, sig: signature.sig }], payloadBytes, sigBytes,
46
+ };
47
+ }
48
+ export function verifyEnvelopeSignature(envelope, publicKey) {
49
+ try {
50
+ return verify(null, preAuthEncoding(envelope.payloadType, envelope.payloadBytes), publicKey, envelope.sigBytes);
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
@@ -0,0 +1,26 @@
1
+ export declare const COSIGN_PINNED_VERSION = "v3.1.3";
2
+ export declare const COSIGN_BINARY_SHA256: Readonly<Record<string, string>>;
3
+ export declare class CosignVerificationError extends Error {
4
+ readonly exitCode = 1;
5
+ constructor(message?: string);
6
+ }
7
+ export declare function assertPinnedCosignBinary(binaryPath: string): Promise<string>;
8
+ export declare function buildCosignSignArgs(bundlePath: string, payloadPath: string): string[];
9
+ export declare function buildCosignVerifyArgs(bundlePath: string, trustedRootPath: string, identity: string, issuer: string, payloadPath: string): string[];
10
+ export declare function signSigstoreBlob(options: {
11
+ binaryPath: string;
12
+ payloadPath: string;
13
+ bundlePath: string;
14
+ }): Promise<{
15
+ bundlePath: string;
16
+ }>;
17
+ export declare function verifySigstoreBlob(options: {
18
+ binaryPath: string;
19
+ payloadPath: string;
20
+ bundlePath: string;
21
+ trustedRootPath: string;
22
+ certificateIdentity: string;
23
+ certificateOidcIssuer: string;
24
+ }): Promise<{
25
+ valid: true;
26
+ }>;
@@ -0,0 +1,153 @@
1
+ // Sigstore/Cosign adapter, kept from the skill-pki preview. Not on the Phase 1 critical path:
2
+ // the certificate verifier does not use it. It verifies blobs with a checksum-pinned Cosign binary.
3
+ import { execFile } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { constants as fsConstants } from 'node:fs';
6
+ import { lstat, open, realpath } from 'node:fs/promises';
7
+ import { endianness } from 'node:os';
8
+ import path from 'node:path';
9
+ import { promisify } from 'node:util';
10
+ export const COSIGN_PINNED_VERSION = 'v3.1.3';
11
+ // Pins come from the release checksum file, whose authentic public Sigstore bundle is tested offline.
12
+ export const COSIGN_BINARY_SHA256 = Object.freeze({
13
+ 'darwin-arm64': '5cf948c2f4dfe59687bdd0b8523709067383e03982cc543475c8a7dc70e92a76',
14
+ 'darwin-x64': '2347488e5d5b25336644024dfeca5601b190e91197a71a917bda44744aff106c',
15
+ 'linux-arm': '3275e61b43a45aa56a6242b49475d8a01874a07469c08fc32d027ba554996e4c',
16
+ 'linux-arm64': 'c5d324e091826b0d7a78eb16fef316450b4eb9aaec045611c08ba06f5e73220a',
17
+ 'linux-ppc64le': '15619e924681c97e0fb4f79c0eb8ef5d29665a06fe6a25078500985aed79321b',
18
+ 'linux-riscv64': '9736177c6be33e4493304fc34feb8aa29209d531b3d40142d7e2a40bbe2f542f',
19
+ 'linux-s390x': '253b571ef9e1aef72ef56d74f464ef9fe5182dc83b1ab430bbffbc4c8e43e7fd',
20
+ 'linux-x64': '4629c757b7618056f8ddd7e2625ae9fdd94c0372a65049520bc7d9df9efc7f71',
21
+ 'win32-x64': '9fe59be0eca1271873ce019061335eb1ac419b7059202e797828467ddabe33be',
22
+ });
23
+ const execFileAsync = promisify(execFile);
24
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
25
+ const MAX_BINARY_BYTES = 256n * 1024n * 1024n;
26
+ export class CosignVerificationError extends Error {
27
+ exitCode = 1;
28
+ constructor(message = 'Cosign verification failed') {
29
+ super(message);
30
+ this.name = 'CosignVerificationError';
31
+ }
32
+ }
33
+ function platformKey(platform = process.platform, arch = process.arch) {
34
+ if (platform === 'linux' && arch === 'ppc64' && endianness() === 'LE')
35
+ return 'linux-ppc64le';
36
+ return `${platform}-${arch}`;
37
+ }
38
+ async function hashFile(filePath) {
39
+ const handle = await open(filePath, fsConstants.O_RDONLY | noFollow);
40
+ try {
41
+ const initial = await handle.stat({ bigint: true });
42
+ if (!initial.isFile())
43
+ throw new Error('Cosign binary must be a regular file');
44
+ if (initial.size > MAX_BINARY_BYTES)
45
+ throw new Error('Cosign binary exceeds the supported size limit');
46
+ const hash = createHash('sha256');
47
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
48
+ let total = 0n;
49
+ while (true) {
50
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
51
+ if (bytesRead === 0)
52
+ break;
53
+ total += BigInt(bytesRead);
54
+ if (total > MAX_BINARY_BYTES)
55
+ throw new Error('Cosign binary exceeds the supported size limit');
56
+ hash.update(buffer.subarray(0, bytesRead));
57
+ }
58
+ const final = await handle.stat({ bigint: true });
59
+ if (total !== initial.size || initial.dev !== final.dev || initial.ino !== final.ino ||
60
+ initial.size !== final.size || initial.mtimeNs !== final.mtimeNs || initial.ctimeNs !== final.ctimeNs) {
61
+ throw new Error('Cosign binary changed while being checked');
62
+ }
63
+ return hash.digest('hex');
64
+ }
65
+ finally {
66
+ await handle.close();
67
+ }
68
+ }
69
+ async function runProcess(binaryPath, args, timeout) {
70
+ try {
71
+ const { stdout, stderr } = await execFileAsync(binaryPath, args, {
72
+ timeout, maxBuffer: 1024 * 1024, windowsHide: true, encoding: 'utf8', shell: false, env: process.env,
73
+ });
74
+ return { stdout, stderr };
75
+ }
76
+ catch (error) {
77
+ const code = error?.code;
78
+ throw new CosignVerificationError(`Pinned Cosign process failed (exit ${typeof code === 'number' ? code : 'unavailable'})`);
79
+ }
80
+ }
81
+ export async function assertPinnedCosignBinary(binaryPath) {
82
+ const platform = platformKey();
83
+ const expected = COSIGN_BINARY_SHA256[platform];
84
+ if (!expected)
85
+ throw new Error(`Cosign ${COSIGN_PINNED_VERSION} has no pinned official checksum for ${platform}`);
86
+ const requested = await lstat(binaryPath);
87
+ if (requested.isSymbolicLink() || !requested.isFile())
88
+ throw new Error('Cosign binary must be a regular, non-symlink file');
89
+ if (process.platform !== 'win32' && (requested.mode & 0o111) === 0)
90
+ throw new Error('Cosign binary is not executable');
91
+ const canonical = await realpath(binaryPath);
92
+ if (await hashFile(canonical) !== expected)
93
+ throw new Error(`Cosign binary checksum does not match the official ${COSIGN_PINNED_VERSION} pin`);
94
+ const version = await runProcess(canonical, ['version'], 15_000);
95
+ if (!/^GitVersion:\s+v3\.1\.3\s*$/mu.test(`${version.stdout}\n${version.stderr}`)) {
96
+ throw new Error(`Cosign binary is not the pinned ${COSIGN_PINNED_VERSION} version`);
97
+ }
98
+ if (await hashFile(canonical) !== expected)
99
+ throw new Error('Cosign binary changed during version validation');
100
+ return canonical;
101
+ }
102
+ async function requireRegularFile(filePath, label) {
103
+ const stats = await lstat(filePath);
104
+ if (stats.isSymbolicLink() || !stats.isFile())
105
+ throw new Error(`${label} must be a regular, non-symlink file`);
106
+ return await realpath(filePath);
107
+ }
108
+ export function buildCosignSignArgs(bundlePath, payloadPath) {
109
+ return ['sign-blob', '--yes', '--bundle', bundlePath, payloadPath];
110
+ }
111
+ export function buildCosignVerifyArgs(bundlePath, trustedRootPath, identity, issuer, payloadPath) {
112
+ return [
113
+ 'verify-blob', '--bundle', bundlePath, '--trusted-root', trustedRootPath,
114
+ '--certificate-identity', identity, '--certificate-oidc-issuer', issuer, payloadPath,
115
+ ];
116
+ }
117
+ async function runCosign(binaryPath, args, timeout) {
118
+ const canonical = await assertPinnedCosignBinary(binaryPath);
119
+ await runProcess(canonical, args, timeout);
120
+ if (await hashFile(canonical) !== COSIGN_BINARY_SHA256[platformKey()]) {
121
+ throw new CosignVerificationError('Pinned Cosign binary changed during the operation');
122
+ }
123
+ }
124
+ async function newOutputPath(filePath) {
125
+ const target = path.resolve(filePath);
126
+ const output = path.join(await realpath(path.dirname(target)), path.basename(target));
127
+ try {
128
+ await lstat(output);
129
+ throw new Error('Sigstore bundle output already exists; refusing to overwrite');
130
+ }
131
+ catch (error) {
132
+ if (error?.code !== 'ENOENT')
133
+ throw error;
134
+ }
135
+ return output;
136
+ }
137
+ export async function signSigstoreBlob(options) {
138
+ const payload = await requireRegularFile(options.payloadPath, 'Sigstore payload');
139
+ const bundle = await newOutputPath(options.bundlePath);
140
+ await runCosign(options.binaryPath, buildCosignSignArgs(bundle, payload), 120_000);
141
+ return { bundlePath: bundle };
142
+ }
143
+ export async function verifySigstoreBlob(options) {
144
+ const payload = await requireRegularFile(options.payloadPath, 'Sigstore payload');
145
+ const bundle = await requireRegularFile(options.bundlePath, 'Sigstore bundle');
146
+ const trustedRoot = await requireRegularFile(options.trustedRootPath, 'Sigstore trusted root');
147
+ if (!options.certificateIdentity)
148
+ throw new Error('A configured Sigstore certificate identity is required');
149
+ if (!options.certificateOidcIssuer)
150
+ throw new Error('A configured Sigstore OIDC issuer is required');
151
+ await runCosign(options.binaryPath, buildCosignVerifyArgs(bundle, trustedRoot, options.certificateIdentity, options.certificateOidcIssuer, payload), 60_000);
152
+ return { valid: true };
153
+ }
@@ -0,0 +1,11 @@
1
+ export declare function isInside(root: string, candidate: string): boolean;
2
+ /** Reads a regular, non-symlink file, failing if it changes while being read. */
3
+ export declare function readRegularFile(filePath: string, label: string, maxBytes?: number): Promise<Buffer>;
4
+ /** Resolves a file path and requires it to be outside `root` (both canonicalized). */
5
+ export declare function resolveOutside(filePath: string, root: string, label: string, { allowMissing }?: {
6
+ allowMissing?: boolean | undefined;
7
+ }): Promise<string>;
8
+ /** Creates a new file; refuses to overwrite anything that already exists. */
9
+ export declare function writeNewFile(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
10
+ /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
11
+ export declare function writeFileAtomic(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
@@ -0,0 +1,96 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
6
+ export function isInside(root, candidate) {
7
+ const relative = path.relative(root, candidate);
8
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
9
+ }
10
+ /** Reads a regular, non-symlink file, failing if it changes while being read. */
11
+ export async function readRegularFile(filePath, label, maxBytes = 1024 * 1024) {
12
+ const entry = await lstat(filePath);
13
+ if (entry.isSymbolicLink() || !entry.isFile())
14
+ throw new Error(`${label} must be a regular, non-symlink file`);
15
+ if (entry.size > maxBytes)
16
+ throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
17
+ const handle = await open(filePath, fsConstants.O_RDONLY | noFollow);
18
+ try {
19
+ const before = await handle.stat();
20
+ if (!before.isFile() || before.dev !== entry.dev || before.ino !== entry.ino)
21
+ throw new Error(`${label} changed while being read`);
22
+ const bytes = await handle.readFile();
23
+ const after = await handle.stat();
24
+ if (bytes.length > maxBytes || before.size !== after.size || before.mtimeMs !== after.mtimeMs || bytes.length !== after.size) {
25
+ throw new Error(`${label} changed while being read or exceeds its size limit`);
26
+ }
27
+ return bytes;
28
+ }
29
+ finally {
30
+ await handle.close();
31
+ }
32
+ }
33
+ /** Resolves a file path and requires it to be outside `root` (both canonicalized). */
34
+ export async function resolveOutside(filePath, root, label, { allowMissing = false } = {}) {
35
+ const canonicalRoot = await realpath(path.resolve(root));
36
+ const requested = path.resolve(filePath);
37
+ let canonical;
38
+ try {
39
+ const entry = await lstat(requested);
40
+ if (entry.isSymbolicLink())
41
+ throw new Error(`${label} must not be a symbolic link`);
42
+ if (!entry.isFile())
43
+ throw new Error(`${label} must be a regular file`);
44
+ canonical = await realpath(requested);
45
+ }
46
+ catch (error) {
47
+ if (!allowMissing || error?.code !== 'ENOENT')
48
+ throw error;
49
+ canonical = path.join(await realpath(path.dirname(requested)), path.basename(requested));
50
+ }
51
+ if (isInside(canonicalRoot, canonical))
52
+ throw new Error(`${label} must be outside ${canonicalRoot}`);
53
+ return canonical;
54
+ }
55
+ async function writeHandle(filePath, bytes, mode, flags) {
56
+ const handle = await open(filePath, flags, mode);
57
+ try {
58
+ await handle.writeFile(bytes);
59
+ await handle.sync();
60
+ }
61
+ catch (error) {
62
+ await handle.close();
63
+ await unlink(filePath).catch(() => { });
64
+ throw error;
65
+ }
66
+ await handle.close();
67
+ }
68
+ /** Creates a new file; refuses to overwrite anything that already exists. */
69
+ export async function writeNewFile(filePath, bytes, mode = 0o644) {
70
+ const target = path.resolve(filePath);
71
+ await writeHandle(target, bytes, mode, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow);
72
+ return target;
73
+ }
74
+ /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
75
+ export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
76
+ const target = path.resolve(filePath);
77
+ try {
78
+ const existing = await lstat(target);
79
+ if (existing.isSymbolicLink() || !existing.isFile())
80
+ throw new Error(`Refusing to replace non-regular file ${target}`);
81
+ }
82
+ catch (error) {
83
+ if (error?.code !== 'ENOENT')
84
+ throw error;
85
+ }
86
+ const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomBytes(6).toString('hex')}.tmp`);
87
+ await writeHandle(temporary, bytes, mode, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow);
88
+ try {
89
+ await rename(temporary, target);
90
+ }
91
+ catch (error) {
92
+ await unlink(temporary).catch(() => { });
93
+ throw error;
94
+ }
95
+ return target;
96
+ }
@@ -0,0 +1,14 @@
1
+ export * from './canonical-json.ts';
2
+ export * from './tree-digest.ts';
3
+ export * from './keys.ts';
4
+ export * from './dsse.ts';
5
+ export * from './time.ts';
6
+ export * from './names.ts';
7
+ export * from './trust-root.ts';
8
+ export * from './revocations.ts';
9
+ export * from './certificate.ts';
10
+ export * from './verify.ts';
11
+ export * from './policy.ts';
12
+ export * from './admin.ts';
13
+ export * from './diff.ts';
14
+ export { runCli } from './cli.ts';
@@ -0,0 +1,14 @@
1
+ export * from "./canonical-json.js";
2
+ export * from "./tree-digest.js";
3
+ export * from "./keys.js";
4
+ export * from "./dsse.js";
5
+ export * from "./time.js";
6
+ export * from "./names.js";
7
+ export * from "./trust-root.js";
8
+ export * from "./revocations.js";
9
+ export * from "./certificate.js";
10
+ export * from "./verify.js";
11
+ export * from "./policy.js";
12
+ export * from "./admin.js";
13
+ export * from "./diff.js";
14
+ export { runCli } from "./cli.js";
@@ -0,0 +1,21 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ export declare const KEY_ID_PATTERN: RegExp;
3
+ export interface PublicKeyInfo {
4
+ keyId: string;
5
+ publicKey: KeyObject;
6
+ /** Canonical base64 of the DER SubjectPublicKeyInfo. */
7
+ spki: string;
8
+ }
9
+ export interface PrivateKeyInfo extends PublicKeyInfo {
10
+ privateKey: KeyObject;
11
+ }
12
+ export declare function keyIdFromSpkiDer(der: Uint8Array): string;
13
+ export declare function validateKeyId(value: unknown, label: string): string;
14
+ /** Parses a canonical base64 Ed25519 SPKI and, if given, checks it hashes to `expectedKeyId`. */
15
+ export declare function parseSpki(spki: unknown, label: string, expectedKeyId?: string): PublicKeyInfo;
16
+ export declare function generateKeyPair(privatePath: string, publicPath: string): Promise<PublicKeyInfo & {
17
+ privatePath: string;
18
+ publicPath: string;
19
+ }>;
20
+ export declare function loadPrivateKey(filePath: string): Promise<PrivateKeyInfo>;
21
+ export declare function loadPublicKey(filePath: string): Promise<PublicKeyInfo>;