feat(companion): add release bundle verification mode
This commit is contained in:
@@ -12,6 +12,7 @@ const {
|
||||
mockCreateCompanionBootstrapManifest,
|
||||
mockWriteCompanionReleaseBundle,
|
||||
mockWriteCompanionShellTemplate,
|
||||
mockVerifyCompanionReleaseBundle,
|
||||
} = vi.hoisted(() => {
|
||||
const runtimeCtorArgs: Array<{ url: string; token?: string; autoReconnect?: boolean }> = [];
|
||||
const runtimeInstances: Array<{
|
||||
@@ -112,6 +113,24 @@ const {
|
||||
`${input.outputDir}/README.md`,
|
||||
],
|
||||
}));
|
||||
const verifyCompanionReleaseBundle = vi.fn(async (input: {
|
||||
bundleDir: string;
|
||||
publicKeyPem?: string;
|
||||
expectedKeyId?: string;
|
||||
requireSignature?: boolean;
|
||||
}) => ({
|
||||
bundleDir: input.bundleDir,
|
||||
checksumsPath: `${input.bundleDir}/CHECKSUMS.sha256`,
|
||||
verifiedFiles: [
|
||||
{ name: 'companion.bootstrap.json', expectedSha256: 'a'.repeat(64), actualSha256: 'a'.repeat(64) },
|
||||
{ name: 'run-companion.sh', expectedSha256: 'b'.repeat(64), actualSha256: 'b'.repeat(64) },
|
||||
{ name: 'README.md', expectedSha256: 'c'.repeat(64), actualSha256: 'c'.repeat(64) },
|
||||
],
|
||||
signaturePath: `${input.bundleDir}/CHECKSUMS.sha256.sig`,
|
||||
signaturePresent: true,
|
||||
signatureVerified: Boolean(input.publicKeyPem),
|
||||
signatureKeyId: input.expectedKeyId ?? 'bundle-k1',
|
||||
}));
|
||||
|
||||
return {
|
||||
mockLoadConfigSafe: loadConfigSafe,
|
||||
@@ -121,6 +140,7 @@ const {
|
||||
mockCreateCompanionBootstrapManifest: createCompanionBootstrapManifest,
|
||||
mockWriteCompanionReleaseBundle: writeCompanionReleaseBundle,
|
||||
mockWriteCompanionShellTemplate: writeCompanionShellTemplate,
|
||||
mockVerifyCompanionReleaseBundle: verifyCompanionReleaseBundle,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -133,6 +153,7 @@ vi.mock('../companion/index.js', () => ({
|
||||
createCompanionBootstrapManifest: mockCreateCompanionBootstrapManifest,
|
||||
writeCompanionReleaseBundle: mockWriteCompanionReleaseBundle,
|
||||
writeCompanionShellTemplate: mockWriteCompanionShellTemplate,
|
||||
verifyCompanionReleaseBundle: mockVerifyCompanionReleaseBundle,
|
||||
CompanionRuntimeClient: class {
|
||||
private connectionHandlers: Array<(event: { status: string }) => void> = [];
|
||||
connect = vi.fn(async () => {
|
||||
@@ -174,6 +195,7 @@ describe('companion command', () => {
|
||||
mockCreateCompanionBootstrapManifest.mockClear();
|
||||
mockWriteCompanionReleaseBundle.mockClear();
|
||||
mockWriteCompanionShellTemplate.mockClear();
|
||||
mockVerifyCompanionReleaseBundle.mockClear();
|
||||
mockLoadConfigSafe.mockReturnValue({
|
||||
config: {
|
||||
server: {
|
||||
@@ -496,6 +518,45 @@ describe('companion command', () => {
|
||||
errSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('verifies a release bundle and exits without runtime connection', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const tempDir = await mkdtemp(join(tmpdir(), 'flynn-verify-key-'));
|
||||
const keyPath = join(tempDir, 'release-public-key.pem');
|
||||
await writeFile(keyPath, '---test-public-key---\n', 'utf8');
|
||||
const program = new Command();
|
||||
const { registerCompanionCommand } = await import('./companion.js');
|
||||
registerCompanionCommand(program);
|
||||
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'companion',
|
||||
'--verify-release-bundle',
|
||||
'/tmp/flynn-companion-bundle',
|
||||
'--verify-signing-key',
|
||||
keyPath,
|
||||
'--verify-signing-key-id',
|
||||
'bundle-k1',
|
||||
'--require-signature',
|
||||
]);
|
||||
|
||||
expect(mockVerifyCompanionReleaseBundle).toHaveBeenCalledOnce();
|
||||
expect(mockVerifyCompanionReleaseBundle).toHaveBeenCalledWith({
|
||||
bundleDir: '/tmp/flynn-companion-bundle',
|
||||
publicKeyPem: '---test-public-key---\n',
|
||||
expectedKeyId: 'bundle-k1',
|
||||
requireSignature: true,
|
||||
});
|
||||
expect(mockRuntimeCtorArgs).toEqual([]);
|
||||
expect(mockRuntimeInstances).toEqual([]);
|
||||
expect(errSpy).not.toHaveBeenCalled();
|
||||
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
logSpy.mockRestore();
|
||||
errSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('applies location, push, and status bootstrap settings to runtime registration', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
@@ -580,7 +641,7 @@ describe('companion command', () => {
|
||||
errSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('sets process exit code when multiple export modes are combined', async () => {
|
||||
it('sets process exit code when multiple companion modes are combined', async () => {
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const program = new Command();
|
||||
const { registerCompanionCommand } = await import('./companion.js');
|
||||
@@ -596,6 +657,8 @@ describe('companion command', () => {
|
||||
'/tmp/flynn-companion-bundle',
|
||||
'--export-shell-template',
|
||||
'/tmp/flynn-companion-template',
|
||||
'--verify-release-bundle',
|
||||
'/tmp/flynn-companion-bundle',
|
||||
]);
|
||||
|
||||
expect(errSpy).toHaveBeenCalled();
|
||||
@@ -624,4 +687,24 @@ describe('companion command', () => {
|
||||
|
||||
errSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('sets process exit code when verify-signing-key is provided without verify-release-bundle', async () => {
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const program = new Command();
|
||||
const { registerCompanionCommand } = await import('./companion.js');
|
||||
registerCompanionCommand(program);
|
||||
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'companion',
|
||||
'--verify-signing-key',
|
||||
'/tmp/flynn-release-public.pem',
|
||||
]);
|
||||
|
||||
expect(errSpy).toHaveBeenCalled();
|
||||
expect(process.exitCode).toBe(1);
|
||||
|
||||
errSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
+58
-3
@@ -7,6 +7,7 @@ import type { SetNodeLocationInput, SetNodePushTokenInput, SetNodeStatusInput }
|
||||
import { createCompanionBootstrapManifest } from '../companion/index.js';
|
||||
import { writeCompanionReleaseBundle } from '../companion/index.js';
|
||||
import { writeCompanionShellTemplate } from '../companion/index.js';
|
||||
import { verifyCompanionReleaseBundle } from '../companion/index.js';
|
||||
import { getConfigPath, loadConfigSafe } from './shared.js';
|
||||
|
||||
type CompanionPlatform = SetNodeStatusInput['platform'];
|
||||
@@ -42,8 +43,12 @@ interface CompanionCommandOptions {
|
||||
exportBootstrap?: string;
|
||||
exportReleaseBundle?: string;
|
||||
exportShellTemplate?: string;
|
||||
verifyReleaseBundle?: string;
|
||||
signingKey?: string;
|
||||
signingKeyId?: string;
|
||||
verifySigningKey?: string;
|
||||
verifySigningKeyId?: string;
|
||||
requireSignature?: boolean;
|
||||
once?: boolean;
|
||||
}
|
||||
|
||||
@@ -325,17 +330,32 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
|
||||
const exportBootstrapPath = options.exportBootstrap?.trim();
|
||||
const exportReleaseBundleDir = options.exportReleaseBundle?.trim();
|
||||
const exportShellTemplateDir = options.exportShellTemplate?.trim();
|
||||
const verifyReleaseBundleDir = options.verifyReleaseBundle?.trim();
|
||||
const signingKeyPath = options.signingKey?.trim();
|
||||
const signingKeyId = options.signingKeyId?.trim();
|
||||
const verifySigningKeyPath = options.verifySigningKey?.trim();
|
||||
const verifySigningKeyId = options.verifySigningKeyId?.trim();
|
||||
|
||||
const exportCount = [exportBootstrapPath, exportReleaseBundleDir, exportShellTemplateDir]
|
||||
const modeCount = [exportBootstrapPath, exportReleaseBundleDir, exportShellTemplateDir, verifyReleaseBundleDir]
|
||||
.filter((value) => Boolean(value)).length;
|
||||
if (exportCount > 1) {
|
||||
throw new Error('export-bootstrap, export-release-bundle, and export-shell-template are mutually exclusive');
|
||||
if (modeCount > 1) {
|
||||
throw new Error('export-bootstrap, export-release-bundle, export-shell-template, and verify-release-bundle are mutually exclusive');
|
||||
}
|
||||
if (signingKeyPath && !exportReleaseBundleDir) {
|
||||
throw new Error('signing-key requires --export-release-bundle');
|
||||
}
|
||||
if (signingKeyId && !exportReleaseBundleDir) {
|
||||
throw new Error('signing-key-id requires --export-release-bundle');
|
||||
}
|
||||
if (verifySigningKeyPath && !verifyReleaseBundleDir) {
|
||||
throw new Error('verify-signing-key requires --verify-release-bundle');
|
||||
}
|
||||
if (verifySigningKeyId && !verifyReleaseBundleDir) {
|
||||
throw new Error('verify-signing-key-id requires --verify-release-bundle');
|
||||
}
|
||||
if (options.requireSignature && !verifyReleaseBundleDir) {
|
||||
throw new Error('require-signature requires --verify-release-bundle');
|
||||
}
|
||||
|
||||
const manifest = createCompanionBootstrapManifest({
|
||||
gatewayUrl,
|
||||
@@ -400,6 +420,34 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
|
||||
return;
|
||||
}
|
||||
|
||||
if (verifyReleaseBundleDir) {
|
||||
const verifyKeyPem = verifySigningKeyPath
|
||||
? await readFile(verifySigningKeyPath, 'utf8')
|
||||
: undefined;
|
||||
const verified = await verifyCompanionReleaseBundle({
|
||||
bundleDir: verifyReleaseBundleDir,
|
||||
publicKeyPem: verifyKeyPem,
|
||||
expectedKeyId: verifySigningKeyId && verifySigningKeyId.length > 0 ? verifySigningKeyId : undefined,
|
||||
requireSignature: options.requireSignature ?? false,
|
||||
});
|
||||
console.log(`Verified companion release bundle: ${verified.bundleDir}`);
|
||||
console.log(`- Checksums: ${verified.checksumsPath}`);
|
||||
console.log(`- Files verified: ${verified.verifiedFiles.length}`);
|
||||
for (const file of verified.verifiedFiles) {
|
||||
console.log(` - ${file.name}`);
|
||||
}
|
||||
if (verified.signaturePresent) {
|
||||
console.log(`- Signature file: ${verified.signaturePath}`);
|
||||
console.log(`- Signature verified: ${verified.signatureVerified ? 'yes' : 'no (no public key provided)'}`);
|
||||
if (verified.signatureKeyId) {
|
||||
console.log(`- Signature key_id: ${verified.signatureKeyId}`);
|
||||
}
|
||||
} else {
|
||||
console.log('- Signature file: not present');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const runtime = new CompanionRuntimeClient({
|
||||
url: gatewayUrl,
|
||||
token: gatewayToken,
|
||||
@@ -592,6 +640,13 @@ export function registerCompanionCommand(program: Command): void {
|
||||
'--export-shell-template <dir>',
|
||||
'Write a platform shell template (bootstrap + native starter file + README) and exit',
|
||||
)
|
||||
.option(
|
||||
'--verify-release-bundle <dir>',
|
||||
'Verify release bundle checksums/signature metadata and exit',
|
||||
)
|
||||
.option('--verify-signing-key <path>', 'Optional public-key PEM path for release-bundle signature verification')
|
||||
.option('--verify-signing-key-id <value>', 'Optional expected signature key identifier')
|
||||
.option('--require-signature', 'Require release-bundle signature file during verification', false)
|
||||
.option('--once', 'Connect, register, publish one heartbeat, then exit', false)
|
||||
.action(async (opts: CompanionCommandOptions) => {
|
||||
try {
|
||||
|
||||
@@ -12,6 +12,7 @@ export { CompanionHeartbeatLoop } from './heartbeatLoop.js';
|
||||
export { createCompanionBootstrapManifest } from './bootstrapManifest.js';
|
||||
export { writeCompanionReleaseBundle } from './releaseBundle.js';
|
||||
export { writeCompanionShellTemplate } from './shellTemplate.js';
|
||||
export { verifyCompanionReleaseBundle } from './releaseVerify.js';
|
||||
|
||||
export type {
|
||||
CompanionRuntimeClientOptions,
|
||||
@@ -87,3 +88,8 @@ export type {
|
||||
WriteCompanionShellTemplateInput,
|
||||
WriteCompanionShellTemplateResult,
|
||||
} from './shellTemplate.js';
|
||||
export type {
|
||||
VerifyCompanionReleaseBundleInput,
|
||||
VerifyCompanionReleaseBundleResult,
|
||||
VerifiedReleaseFile,
|
||||
} from './releaseVerify.js';
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { generateKeyPairSync } from 'node:crypto';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { writeCompanionReleaseBundle } from './releaseBundle.js';
|
||||
import { verifyCompanionReleaseBundle } from './releaseVerify.js';
|
||||
|
||||
describe('verifyCompanionReleaseBundle', () => {
|
||||
it('verifies unsigned bundle checksums', async () => {
|
||||
const tempDir = await mkdtemp(join(tmpdir(), 'flynn-release-verify-unsigned-'));
|
||||
const bundleDir = join(tempDir, 'bundle');
|
||||
await writeCompanionReleaseBundle({
|
||||
outputDir: bundleDir,
|
||||
manifest: {
|
||||
schemaVersion: 1,
|
||||
generatedAt: '2026-02-27T00:00:00.000Z',
|
||||
gateway: { url: 'ws://127.0.0.1:18800' },
|
||||
node: {
|
||||
nodeId: 'verify-unsigned',
|
||||
role: 'companion',
|
||||
platform: 'macos',
|
||||
capabilities: ['ui.canvas'],
|
||||
},
|
||||
runtime: {
|
||||
heartbeatSeconds: 30,
|
||||
handoffTimeoutMs: 120000,
|
||||
autoReconnect: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const verified = await verifyCompanionReleaseBundle({
|
||||
bundleDir,
|
||||
});
|
||||
expect(verified.signaturePresent).toBe(false);
|
||||
expect(verified.verifiedFiles.map((file) => file.name)).toEqual([
|
||||
'companion.bootstrap.json',
|
||||
'run-companion.sh',
|
||||
'README.md',
|
||||
]);
|
||||
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('fails when checksum target content is modified', async () => {
|
||||
const tempDir = await mkdtemp(join(tmpdir(), 'flynn-release-verify-mismatch-'));
|
||||
const bundleDir = join(tempDir, 'bundle');
|
||||
await writeCompanionReleaseBundle({
|
||||
outputDir: bundleDir,
|
||||
manifest: {
|
||||
schemaVersion: 1,
|
||||
generatedAt: '2026-02-27T00:00:00.000Z',
|
||||
gateway: { url: 'ws://127.0.0.1:18800' },
|
||||
node: {
|
||||
nodeId: 'verify-mismatch',
|
||||
role: 'companion',
|
||||
platform: 'ios',
|
||||
capabilities: ['ui.canvas'],
|
||||
},
|
||||
runtime: {
|
||||
heartbeatSeconds: 30,
|
||||
handoffTimeoutMs: 120000,
|
||||
autoReconnect: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await writeFile(`${bundleDir}/README.md`, 'tampered\n', 'utf8');
|
||||
await expect(verifyCompanionReleaseBundle({ bundleDir })).rejects.toThrow('Checksum mismatch');
|
||||
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('verifies signature when public key is supplied', async () => {
|
||||
const tempDir = await mkdtemp(join(tmpdir(), 'flynn-release-verify-signed-'));
|
||||
const bundleDir = join(tempDir, 'bundle');
|
||||
const keyPair = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const privatePem = keyPair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
||||
const publicPem = keyPair.publicKey.export({ type: 'spki', format: 'pem' }).toString();
|
||||
|
||||
await writeCompanionReleaseBundle({
|
||||
outputDir: bundleDir,
|
||||
signingKeyPem: privatePem,
|
||||
signingKeyId: 'bundle-k1',
|
||||
manifest: {
|
||||
schemaVersion: 1,
|
||||
generatedAt: '2026-02-27T00:00:00.000Z',
|
||||
gateway: { url: 'ws://127.0.0.1:18800' },
|
||||
node: {
|
||||
nodeId: 'verify-signed',
|
||||
role: 'companion',
|
||||
platform: 'android',
|
||||
capabilities: ['ui.canvas'],
|
||||
},
|
||||
runtime: {
|
||||
heartbeatSeconds: 30,
|
||||
handoffTimeoutMs: 120000,
|
||||
autoReconnect: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const verified = await verifyCompanionReleaseBundle({
|
||||
bundleDir,
|
||||
publicKeyPem: publicPem,
|
||||
expectedKeyId: 'bundle-k1',
|
||||
requireSignature: true,
|
||||
});
|
||||
expect(verified.signaturePresent).toBe(true);
|
||||
expect(verified.signatureVerified).toBe(true);
|
||||
expect(verified.signatureKeyId).toBe('bundle-k1');
|
||||
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { createHash, createPublicKey, verify } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
export interface VerifyCompanionReleaseBundleInput {
|
||||
bundleDir: string;
|
||||
publicKeyPem?: string;
|
||||
expectedKeyId?: string;
|
||||
requireSignature?: boolean;
|
||||
}
|
||||
|
||||
export interface VerifiedReleaseFile {
|
||||
name: string;
|
||||
expectedSha256: string;
|
||||
actualSha256: string;
|
||||
}
|
||||
|
||||
export interface VerifyCompanionReleaseBundleResult {
|
||||
bundleDir: string;
|
||||
checksumsPath: string;
|
||||
verifiedFiles: VerifiedReleaseFile[];
|
||||
signaturePath?: string;
|
||||
signaturePresent: boolean;
|
||||
signatureVerified: boolean;
|
||||
signatureKeyId?: string;
|
||||
}
|
||||
|
||||
interface ParsedSignature {
|
||||
keyId?: string;
|
||||
algorithm: string;
|
||||
encoding: string;
|
||||
signature: string;
|
||||
}
|
||||
|
||||
function parseChecksums(raw: string): Array<{ hash: string; name: string }> {
|
||||
const lines = raw
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0 && !line.startsWith('#'));
|
||||
const entries: Array<{ hash: string; name: string }> = [];
|
||||
for (const line of lines) {
|
||||
const parts = line.split(/\s+/, 2);
|
||||
const hash = parts[0];
|
||||
const name = parts[1];
|
||||
if (!hash || !name) {
|
||||
throw new Error(`Invalid checksum line: ${line}`);
|
||||
}
|
||||
if (!/^[a-f0-9]{64}$/i.test(hash)) {
|
||||
throw new Error(`Invalid SHA-256 checksum for ${name}`);
|
||||
}
|
||||
entries.push({ hash: hash.toLowerCase(), name });
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
throw new Error('No checksum entries found');
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function parseSignature(raw: string): ParsedSignature {
|
||||
const parsed: Partial<ParsedSignature> = {};
|
||||
const lines = raw
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0 && !line.startsWith('#'));
|
||||
for (const line of lines) {
|
||||
const split = line.indexOf('=');
|
||||
if (split <= 0) {
|
||||
continue;
|
||||
}
|
||||
const key = line.slice(0, split);
|
||||
const value = line.slice(split + 1);
|
||||
if (key === 'key_id') {
|
||||
parsed.keyId = value;
|
||||
continue;
|
||||
}
|
||||
if (key === 'algorithm') {
|
||||
parsed.algorithm = value;
|
||||
continue;
|
||||
}
|
||||
if (key === 'encoding') {
|
||||
parsed.encoding = value;
|
||||
continue;
|
||||
}
|
||||
if (key === 'signature') {
|
||||
parsed.signature = value;
|
||||
}
|
||||
}
|
||||
if (!parsed.algorithm || !parsed.encoding || !parsed.signature) {
|
||||
throw new Error('Invalid signature metadata: algorithm/encoding/signature are required');
|
||||
}
|
||||
return parsed as ParsedSignature;
|
||||
}
|
||||
|
||||
async function readOptional(path: string): Promise<string | undefined> {
|
||||
try {
|
||||
return await readFile(path, 'utf8');
|
||||
} catch (error) {
|
||||
if (
|
||||
error
|
||||
&& typeof error === 'object'
|
||||
&& 'code' in error
|
||||
&& (error as { code?: string }).code === 'ENOENT'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyCompanionReleaseBundle(
|
||||
input: VerifyCompanionReleaseBundleInput,
|
||||
): Promise<VerifyCompanionReleaseBundleResult> {
|
||||
const checksumsPath = `${input.bundleDir}/CHECKSUMS.sha256`;
|
||||
const checksumsRaw = await readFile(checksumsPath, 'utf8');
|
||||
const checksumsEntries = parseChecksums(checksumsRaw);
|
||||
const verifiedFiles: VerifiedReleaseFile[] = [];
|
||||
|
||||
for (const entry of checksumsEntries) {
|
||||
const filePath = `${input.bundleDir}/${entry.name}`;
|
||||
const fileRaw = await readFile(filePath);
|
||||
const actualSha256 = createHash('sha256').update(fileRaw).digest('hex');
|
||||
if (actualSha256 !== entry.hash) {
|
||||
throw new Error(`Checksum mismatch for ${entry.name}`);
|
||||
}
|
||||
verifiedFiles.push({
|
||||
name: entry.name,
|
||||
expectedSha256: entry.hash,
|
||||
actualSha256,
|
||||
});
|
||||
}
|
||||
|
||||
const signaturePath = `${input.bundleDir}/CHECKSUMS.sha256.sig`;
|
||||
const signatureRaw = await readOptional(signaturePath);
|
||||
const signaturePresent = signatureRaw !== undefined;
|
||||
let signatureVerified = false;
|
||||
let signatureKeyId: string | undefined;
|
||||
|
||||
if (input.requireSignature && !signaturePresent) {
|
||||
throw new Error('Signature is required but CHECKSUMS.sha256.sig was not found');
|
||||
}
|
||||
|
||||
if (input.publicKeyPem) {
|
||||
if (!signaturePresent) {
|
||||
throw new Error('Public key provided but CHECKSUMS.sha256.sig was not found');
|
||||
}
|
||||
const parsed = parseSignature(signatureRaw);
|
||||
signatureKeyId = parsed.keyId;
|
||||
if (parsed.algorithm !== 'sha256') {
|
||||
throw new Error(`Unsupported signature algorithm: ${parsed.algorithm}`);
|
||||
}
|
||||
if (parsed.encoding !== 'base64') {
|
||||
throw new Error(`Unsupported signature encoding: ${parsed.encoding}`);
|
||||
}
|
||||
if (input.expectedKeyId && parsed.keyId !== input.expectedKeyId) {
|
||||
throw new Error(`Signature key_id mismatch: expected ${input.expectedKeyId}, got ${parsed.keyId ?? 'unset'}`);
|
||||
}
|
||||
|
||||
const verified = verify(
|
||||
'sha256',
|
||||
Buffer.from(checksumsRaw, 'utf8'),
|
||||
createPublicKey(input.publicKeyPem),
|
||||
Buffer.from(parsed.signature, 'base64'),
|
||||
);
|
||||
if (!verified) {
|
||||
throw new Error('Signature verification failed');
|
||||
}
|
||||
signatureVerified = true;
|
||||
}
|
||||
|
||||
return {
|
||||
bundleDir: input.bundleDir,
|
||||
checksumsPath,
|
||||
verifiedFiles,
|
||||
signaturePath: signaturePresent ? signaturePath : undefined,
|
||||
signaturePresent,
|
||||
signatureVerified,
|
||||
signatureKeyId,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user