diff --git a/README.md b/README.md index ed1d804..89bfa9a 100644 --- a/README.md +++ b/README.md @@ -1737,6 +1737,7 @@ Companion runtime helper: - `src/companion/bootstrapManifest.ts` provides `createCompanionBootstrapManifest()` for generating a typed gateway/node/runtime bootstrap contract used by packaging flows, including optional initial status/location/push payloads. - `src/companion/releaseBundle.ts` provides `writeCompanionReleaseBundle()` for writing a distributable companion bundle directory (bootstrap JSON + launcher script + README + SHA-256 checksums). - `src/companion/shellTemplate.ts` provides `writeCompanionShellTemplate()` for emitting platform starter shells (macOS/iOS/Android native scaffold snippets + bootstrap JSON). +- `src/companion/releaseVerify.ts` provides `verifyCompanionReleaseBundle()` for validating bundle checksums and optional signature metadata. Minimal companion CLI: - `flynn companion --once` connects to the gateway, registers a node, publishes one heartbeat, then exits. @@ -1746,6 +1747,7 @@ Minimal companion CLI: - `flynn companion --export-release-bundle ./dist/companion-macos` writes a release bundle directory (`companion.bootstrap.json`, `run-companion.sh`, `README.md`, `CHECKSUMS.sha256`) and exits. - `flynn companion --export-release-bundle ./dist/companion-macos --signing-key ./keys/release-private.pem --signing-key-id team-k1` also writes `CHECKSUMS.sha256.sig` for signed verification workflows. - `flynn companion --platform ios --export-shell-template ./dist/companion-ios-template` writes a platform-native starter template directory (`companion.bootstrap.json`, native starter file, `README.md`) and exits. +- `flynn companion --verify-release-bundle ./dist/companion-macos --verify-signing-key ./keys/release-public.pem --verify-signing-key-id team-k1 --require-signature` verifies checksums and signature metadata before install. - `flynn companion --once --platform ios --app-version 1.2.3 --device-name "iPhone" --status-text ready --battery-pct 84 --power-source battery` sends richer initial node status metadata. - `flynn companion --once --latitude 37.3349 --longitude -122.009 --location-source gps` bootstraps node location metadata. - `flynn companion --once --platform android --push-token ` (or `--platform ios --push-token `) registers push routing metadata during bootstrap. diff --git a/docs/api/PROTOCOL.md b/docs/api/PROTOCOL.md index 1d3024d..a70c97b 100644 --- a/docs/api/PROTOCOL.md +++ b/docs/api/PROTOCOL.md @@ -23,7 +23,7 @@ The gateway provides: - **HTTP Server**: Serves static dashboard and handles webhook endpoints - **Node Capability Negotiation**: Optional companion-node role/capability registration -Operational note: onboarding (`flynn setup` / `flynn onboard`) now runs post-save live readiness checks (model/channel/memory/automation) and prints a guided first-success task flow. Companion CLI now also supports bootstrap-manifest export (`flynn companion --export-bootstrap `), release-bundle export (`--export-release-bundle ` with optional `--signing-key`/`--signing-key-id` signature output), platform shell-template export (`--export-shell-template `), plus richer shell bootstrap flags for status/location/push (`--app-version`, `--latitude/--longitude`, `--push-token`, etc.) for desktop/mobile app packaging without changing JSON-RPC method/event shapes. +Operational note: onboarding (`flynn setup` / `flynn onboard`) now runs post-save live readiness checks (model/channel/memory/automation) and prints a guided first-success task flow. Companion CLI now also supports bootstrap-manifest export (`flynn companion --export-bootstrap `), release-bundle export (`--export-release-bundle ` with optional `--signing-key`/`--signing-key-id` signature output), release-bundle verification (`--verify-release-bundle ` with optional `--verify-signing-key`/`--verify-signing-key-id`/`--require-signature`), platform shell-template export (`--export-shell-template `), plus richer shell bootstrap flags for status/location/push (`--app-version`, `--latitude/--longitude`, `--push-token`, etc.) for desktop/mobile app packaging without changing JSON-RPC method/event shapes. ### Execution Model (Sessions + Per-Session Queue) @@ -1864,4 +1864,5 @@ For more implementation details, see: - Platform companion wrappers: `src/companion/platformClients.ts` - Companion bootstrap manifest helper: `src/companion/bootstrapManifest.ts` (typed packaging manifest contract used by `flynn companion --export-bootstrap`, including optional initial status/location/push payloads) - Companion release bundle helper: `src/companion/releaseBundle.ts` (writes bootstrap JSON + launcher script + README + `CHECKSUMS.sha256`; optional `CHECKSUMS.sha256.sig` when a signing key is provided) +- Companion release bundle verifier: `src/companion/releaseVerify.ts` (validates `CHECKSUMS.sha256` and optional signature metadata against a provided public key) - Companion shell template helper: `src/companion/shellTemplate.ts` (writes platform-native starter template files for `macos`, `ios`, and `android` shell scaffolding) diff --git a/docs/architecture/AGENT_DIAGRAM.md b/docs/architecture/AGENT_DIAGRAM.md index 23ec231..be79f35 100644 --- a/docs/architecture/AGENT_DIAGRAM.md +++ b/docs/architecture/AGENT_DIAGRAM.md @@ -158,6 +158,7 @@ Gateway streaming UX signals: - `flynn companion --export-bootstrap ` can emit a resolved companion bootstrap manifest (gateway/node/runtime contract) for desktop/mobile packaging flows without opening a runtime connection. - `flynn companion --export-release-bundle ` can emit a distributable shell bundle (bootstrap JSON + launcher + README + SHA-256 checksums) for desktop/mobile packaging pipelines. - `flynn companion --export-release-bundle ... --signing-key ` can additionally emit `CHECKSUMS.sha256.sig` for signed artifact verification pipelines. +- `flynn companion --verify-release-bundle ` can validate bundle checksums and optional signatures before installation or rollout. - `flynn companion --export-shell-template ` can emit platform starter shell templates (macOS/iOS/Android native scaffold files + bootstrap JSON) for reference app bootstrapping. - `flynn companion` can bootstrap status/location/push metadata on connect (`node.status.set` + optional `node.location.set`/`node.push_token.set`) so thin companion shells can register operational context in one launch. - Canvas artifacts are persisted by the gateway so session UI surfaces can recover after daemon restarts. diff --git a/docs/architecture/GATEWAY_SESSIONS_AND_QUEUE.md b/docs/architecture/GATEWAY_SESSIONS_AND_QUEUE.md index 60cdfd3..1a65da1 100644 --- a/docs/architecture/GATEWAY_SESSIONS_AND_QUEUE.md +++ b/docs/architecture/GATEWAY_SESSIONS_AND_QUEUE.md @@ -23,6 +23,7 @@ If you only want the protocol surface, see `docs/api/PROTOCOL.md`. - Companion packaging/bootstrap can be generated offline via `flynn companion --export-bootstrap `, which emits resolved gateway/node/runtime settings without opening a WebSocket session. - Companion release artifacts can be generated via `flynn companion --export-release-bundle `, producing bootstrap JSON + launcher + README + `CHECKSUMS.sha256` for installable shell distribution workflows. - Companion release-bundle exports can optionally be signed (`--signing-key`, `--signing-key-id`) to emit `CHECKSUMS.sha256.sig` for distribution trust verification. +- Companion release bundles can be verified before install via `flynn companion --verify-release-bundle ` with optional signature-key checks. - Companion platform starter scaffolds can be generated via `flynn companion --export-shell-template ` for macOS/iOS/Android reference app bootstrapping. - Companion CLI supports one-shot shell bootstrap metadata for live sessions (`--app-version`/`--status-text`, `--latitude`/`--longitude`, `--push-token`) so desktop/mobile wrappers can initialize node status/location/push in a single launch flow. - Canvas artifacts are persisted per session under the gateway data directory for UI recovery across restarts. diff --git a/docs/operations/COMPANION_RELEASE_BUNDLE.md b/docs/operations/COMPANION_RELEASE_BUNDLE.md index a5eba26..5fcb2f1 100644 --- a/docs/operations/COMPANION_RELEASE_BUNDLE.md +++ b/docs/operations/COMPANION_RELEASE_BUNDLE.md @@ -68,6 +68,16 @@ Expected result: If signature is present, verify `CHECKSUMS.sha256.sig` with your org signing key policy before launch. +Automated CLI verification mode: + +```bash +flynn companion \ + --verify-release-bundle ./dist/companion-macos \ + --verify-signing-key ./keys/release-public.pem \ + --verify-signing-key-id team-k1 \ + --require-signature +``` + ## Launch ```bash diff --git a/docs/plans/2026-02-26-personal-assistant-productization-plan.md b/docs/plans/2026-02-26-personal-assistant-productization-plan.md index 994203c..8bfa5ad 100644 --- a/docs/plans/2026-02-26-personal-assistant-productization-plan.md +++ b/docs/plans/2026-02-26-personal-assistant-productization-plan.md @@ -49,7 +49,7 @@ Within 8-10 weeks, ship a stable "Personal Assistant Mode" that supports: 2. Ship a minimal mobile companion shell (iOS + Android) for registration, status, push token, and message handoff. 3. Add signed release artifacts and installation docs. -Status update (2026-02-27): companion bootstrap-manifest export is now available via `flynn companion --export-bootstrap ` as a packaging contract for desktop/mobile shells, `flynn companion --export-release-bundle ` now emits bundle artifacts (bootstrap JSON + launcher + README + `CHECKSUMS.sha256`, optional `CHECKSUMS.sha256.sig` with `--signing-key`), `flynn companion --export-shell-template ` now emits macOS/iOS/Android starter shell templates, and `flynn companion` supports one-shot status/location/push bootstrap flags (`--app-version`, `--latitude/--longitude`, `--push-token`) so thin shells can initialize companion metadata in a single run. +Status update (2026-02-27): companion bootstrap-manifest export is now available via `flynn companion --export-bootstrap ` as a packaging contract for desktop/mobile shells, `flynn companion --export-release-bundle ` now emits bundle artifacts (bootstrap JSON + launcher + README + `CHECKSUMS.sha256`, optional `CHECKSUMS.sha256.sig` with `--signing-key`), `flynn companion --verify-release-bundle ` now validates checksum/signature artifacts before install, `flynn companion --export-shell-template ` now emits macOS/iOS/Android starter shell templates, and `flynn companion` supports one-shot status/location/push bootstrap flags (`--app-version`, `--latitude/--longitude`, `--push-token`) so thin shells can initialize companion metadata in a single run. ### Implementation Anchors diff --git a/docs/plans/state.json b/docs/plans/state.json index 3f75f66..a7a5fe7 100644 --- a/docs/plans/state.json +++ b/docs/plans/state.json @@ -7054,10 +7054,31 @@ "docs/plans/state.json" ], "test_status": "pnpm test:run src/cli/companion.test.ts src/companion/releaseBundle.test.ts + pnpm typecheck passing" + }, + "personal-assistant-productization-phase1-companion-bundle-verification-mode": { + "status": "completed", + "date": "2026-02-27", + "updated": "2026-02-27", + "summary": "Added companion release-bundle verification automation. `flynn companion --verify-release-bundle ` now verifies checksum manifests and can validate signature metadata with `--verify-signing-key`, `--verify-signing-key-id`, and `--require-signature` gates. Added reusable `verifyCompanionReleaseBundle()` helper plus regression tests for signed/unsigned/tampered bundles.", + "files_modified": [ + "src/companion/releaseVerify.ts", + "src/companion/releaseVerify.test.ts", + "src/companion/index.ts", + "src/cli/companion.ts", + "src/cli/companion.test.ts", + "README.md", + "docs/api/PROTOCOL.md", + "docs/architecture/AGENT_DIAGRAM.md", + "docs/architecture/GATEWAY_SESSIONS_AND_QUEUE.md", + "docs/operations/COMPANION_RELEASE_BUNDLE.md", + "docs/plans/2026-02-26-personal-assistant-productization-plan.md", + "docs/plans/state.json" + ], + "test_status": "pnpm test:run src/companion/releaseVerify.test.ts src/cli/companion.test.ts src/companion/releaseBundle.test.ts + pnpm typecheck passing" } }, "overall_progress": { - "total_test_count": 2580, + "total_test_count": 2583, "all_tests_passing": true, "p0_completion": "3/3 (100%)", "p1_completion": "4/4 (100%)", @@ -7072,7 +7093,7 @@ "tier2_completion": "4/4 (100%) — inbound webhooks, vector memory search, Dockerfile, heartbeat monitor", "tier3_completion": "5/5 (100%) — lane queue, credential redaction, web UI token dashboard, xAI (Grok) provider, Voyage AI embeddings", "tier4_completion": "4/4 (100%) — gateway lock, shell completion, Tailscale Serve/Funnel, DM pairing codes", - "feature_gap_scorecard": "rebaselined 2026-02-26 and updated 2026-02-27 (phase 3 + phase 1 + phase 2 + phase 4 slices + companion packaging/bundle tooling + shell bootstrap controls + platform templates + signed artifacts) — channel breadth, setup wizard, baseline browser automation, subagent controls, browser workflow reliability primitives (wait/assert/extract/retries/checkpoints/guardrails/budgets), companion reconnect/runtime-handoff foundations, companion packaging primitives (bootstrap export + release-bundle artifacts + checksum manifests + optional signatures), companion install/verification runbook, platform starter shell templates for macOS/iOS/Android, and one-shot status/location/push shell bootstrap controls, voice reliability hardening (talk controls + TTS fallback/health + interruption-safe cancel semantics), and onboarding first-success funnel improvements are implemented; remaining high-impact personal-assistant gaps center on production-grade companion app binaries and distribution hardening automation.", + "feature_gap_scorecard": "rebaselined 2026-02-26 and updated 2026-02-27 (phase 3 + phase 1 + phase 2 + phase 4 slices + companion packaging/bundle tooling + shell bootstrap controls + platform templates + signed/verified artifacts) — channel breadth, setup wizard, baseline browser automation, subagent controls, browser workflow reliability primitives (wait/assert/extract/retries/checkpoints/guardrails/budgets), companion reconnect/runtime-handoff foundations, companion packaging primitives (bootstrap export + release-bundle artifacts + checksum manifests + optional signatures + verification mode), companion install/verification runbook, platform starter shell templates for macOS/iOS/Android, and one-shot status/location/push shell bootstrap controls, voice reliability hardening (talk controls + TTS fallback/health + interruption-safe cancel semantics), and onboarding first-success funnel improvements are implemented; remaining high-impact personal-assistant gaps center on production-grade companion app binaries and distribution automation hardening.", "operator_dx_milestone": "Phase 3 (Live Ops Dashboard): 2/2 plans complete — milestone done", "dashboard_observability": "completed — service health graphs + core service log viewer added to web UI via observability RPCs and bounded backend sampling", "gmail_auth_cli": "flynn gmail-auth command implemented with OAuth2 flow, doctor check, config routed to Telegram", @@ -7105,7 +7126,7 @@ "deeper_surfaces_phase3_companion_canvas_voice": "completed — companion reconnect resilience (auto-reconnect with backoff, pending-wait cancellation on disconnect), canvas artifact persistence (SQLite-backed store, daemon-restart durability), voice TTS fallback coverage (text-only reply on TTS failure, no dropped responses)", "deeper_surfaces_phase4_rollout": "completed — phase 4 rollout and operator readiness plan documented: canary rollout plan by feature flag/surface, explicit rollback playbook, operator docs and architecture/protocol docs synchronized", "post_phase_test_fixes": "completed — fixed 4 test failures introduced by phases 1-3: iOS/Android push listNodes (missing publishHeartbeat before platform-filtered query), server.test agent.send (run_state events now precede done; added sendAndWaitForDone helper), httpBody 413 (req.destroy() closed socket before response could be sent; replaced with Connection: close header on 413 responses)", - "personal_assistant_productization_plan": "in_progress — 8-10 week phased roadmap active; Phase 3 browser workflow reliability shipped, Phase 1 companion runtime reliability includes reconnect state replay + typed handoff support, companion packaging primitives now include bootstrap manifest export, release-bundle artifact generation, checksum manifests, optional signature emission, platform starter shell-template generation, and an install/verification runbook, companion shell bootstrap controls cover status/location/push metadata, Phase 2 voice reliability ships talk controls + TTS provider fallback/health + interruption-safe voice cancel mapping, and Phase 4 onboarding includes Personal Assistant Mode preset + live readiness checks + first-success guidance. Remaining phase focus: production-ready companion app surfaces and distribution automation polish.", + "personal_assistant_productization_plan": "in_progress — 8-10 week phased roadmap active; Phase 3 browser workflow reliability shipped, Phase 1 companion runtime reliability includes reconnect state replay + typed handoff support, companion packaging primitives now include bootstrap manifest export, release-bundle artifact generation, checksum manifests, optional signature emission, verification mode, platform starter shell-template generation, and an install/verification runbook, companion shell bootstrap controls cover status/location/push metadata, Phase 2 voice reliability ships talk controls + TTS provider fallback/health + interruption-safe voice cancel mapping, and Phase 4 onboarding includes Personal Assistant Mode preset + live readiness checks + first-success guidance. Remaining phase focus: production-ready companion app surfaces and distribution automation polish.", "subagents_support": "completed — subagent phases 1-3 shipped with `subagent.spawn/send/list/cancel/delete/summary`, per-child queue mode (`followup|interrupt`), budgets (`max_turns`, `max_total_tokens`, `turn_timeout_ms`), tool-profile overrides, trace-linked audit events, `/subagents` inspection commands, and focused regression tests." }, "soul_md_and_cron_create": { diff --git a/src/cli/companion.test.ts b/src/cli/companion.test.ts index 4fc464b..1eae398 100644 --- a/src/cli/companion.test.ts +++ b/src/cli/companion.test.ts @@ -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(); + }); }); diff --git a/src/cli/companion.ts b/src/cli/companion.ts index 765a55e..c787671 100644 --- a/src/cli/companion.ts +++ b/src/cli/companion.ts @@ -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 ', 'Write a platform shell template (bootstrap + native starter file + README) and exit', ) + .option( + '--verify-release-bundle ', + 'Verify release bundle checksums/signature metadata and exit', + ) + .option('--verify-signing-key ', 'Optional public-key PEM path for release-bundle signature verification') + .option('--verify-signing-key-id ', '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 { diff --git a/src/companion/index.ts b/src/companion/index.ts index 601f756..d2fbc79 100644 --- a/src/companion/index.ts +++ b/src/companion/index.ts @@ -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'; diff --git a/src/companion/releaseVerify.test.ts b/src/companion/releaseVerify.test.ts new file mode 100644 index 0000000..cff2e1c --- /dev/null +++ b/src/companion/releaseVerify.test.ts @@ -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 }); + }); +}); diff --git a/src/companion/releaseVerify.ts b/src/companion/releaseVerify.ts new file mode 100644 index 0000000..20f65b0 --- /dev/null +++ b/src/companion/releaseVerify.ts @@ -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 = {}; + 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 { + 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 { + 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, + }; +}