| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | import { createHash } from 'node:crypto'; |
| 4 | import { createWriteStream } from 'node:fs'; |
| 5 | import { chmod, link, mkdir, mkdtemp, rm } from 'node:fs/promises'; |
| 6 | import { isAbsolute, join, resolve } from 'node:path'; |
| 7 | import { Readable, Transform } from 'node:stream'; |
| 8 | import { pipeline } from 'node:stream/promises'; |
| 9 | import { pathToFileURL } from 'node:url'; |
| 10 | |
| 11 | const repo = 'Lee-xeo/Claude-Cage'; |
| 12 | const protocol = 1; |
| 13 | export class BootstrapError extends Error { |
| 14 | constructor(code, message, nextAction) { super(message); this.code = code; this.next_action = nextAction; } |
| 15 | } |
| 16 | const fail = (code, message, next = 'plan') => { throw new BootstrapError(code, message, next); }; |
| 17 | |
| 18 | export function parseArgs(args) { |
| 19 | const options = { action: 'plan', platform: `${process.platform}-${process.arch === 'x64' ? 'amd64' : process.arch}`, version: '', destination: '', allowUnsigned: false }; |
| 20 | if (args[0] && !args[0].startsWith('--')) options.action = args.shift(); |
| 21 | for (let i = 0; i < args.length; i++) { |
| 22 | const flag = args[i]; |
| 23 | if (flag === '--allow-unsigned') { options.allowUnsigned = true; continue; } |
| 24 | if (!['--platform', '--version', '--destination'].includes(flag) || !args[i + 1] || args[i + 1].startsWith('--')) fail('invalid_input', 'Usage: agent-bootstrap.mjs plan|download [--version TAG] [--platform darwin-arm64|win32-amd64|linux-amd64] [--destination ABSOLUTE_DIRECTORY] [--allow-unsigned]'); |
| 25 | options[flag.slice(2)] = args[++i]; |
| 26 | } |
| 27 | if (!['plan', 'download'].includes(options.action)) fail('invalid_input', 'Action must be plan or download.'); |
| 28 | if (!['darwin-arm64', 'win32-amd64', 'linux-amd64'].includes(options.platform)) fail('unsupported_platform', 'No desktop package is selected for this platform. Read the platform guide.'); |
| 29 | if (options.version && !/^v?\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(options.version)) fail('invalid_input', 'Use an explicit release tag such as v0.1.6-alpha-preview.'); |
| 30 | if (options.version && !options.version.startsWith('v')) options.version = `v${options.version}`; |
| 31 | if (options.action === 'download' && !isAbsolute(options.destination)) fail('invalid_input', 'download requires --destination with an absolute directory path.'); |
| 32 | return options; |
| 33 | } |
| 34 | |
| 35 | |
| 36 | export async function httpsResponse(url, fetchImpl = fetch) { |
| 37 | for (let redirects = 0; redirects <= 5; redirects++) { |
| 38 | const parsed = new URL(url); |
| 39 | if (parsed.protocol !== 'https:' || parsed.username || parsed.password) fail('unsafe_download', 'Only public HTTPS downloads without embedded credentials are supported.'); |
| 40 | let response; |
| 41 | try { |
| 42 | response = await fetchImpl(parsed, { redirect: 'manual', signal: AbortSignal.timeout(120000), headers: { 'User-Agent': 'Cage-Agent-Bootstrap/1', Accept: 'application/json, application/octet-stream' } }); |
| 43 | } catch { |
| 44 | fail('download_connection_failed', 'Could not connect to the public release service. Check host connectivity and user-configured proxy settings; Node 24 can use --use-env-proxy.', 'check_host_network'); |
| 45 | } |
| 46 | if ([301, 302, 303, 307, 308].includes(response.status)) { |
| 47 | const location = response.headers.get('location'); |
| 48 | await response.body?.cancel(); |
| 49 | if (!location) fail('download_failed', 'Download redirect has no location.'); |
| 50 | url = new URL(location, parsed).href; |
| 51 | continue; |
| 52 | } |
| 53 | if (!response.ok) { await response.body?.cancel(); fail(response.status === 403 || response.status === 429 ? 'rate_limited' : 'download_failed', `Public download returned HTTP ${response.status}. Retry later or choose another published release.`); } |
| 54 | return response; |
| 55 | } |
| 56 | fail('download_failed', 'Too many redirects.'); |
| 57 | } |
| 58 | |
| 59 | async function boundedText(url, fetchImpl) { |
| 60 | const response = await httpsResponse(url, fetchImpl); |
| 61 | const chunks = []; let total = 0; |
| 62 | for await (const chunk of response.body) { total += chunk.length; if (total > 4 * 1024 * 1024) fail('invalid_release', 'Release metadata is too large.'); chunks.push(chunk); } |
| 63 | return Buffer.concat(chunks).toString('utf8').replace(/^\uFEFF/, ''); |
| 64 | } |
| 65 | |
| 66 | export function selectAsset(release, options) { |
| 67 | const tag = release.tag_name; |
| 68 | if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(tag) || release.draft || (options.version && tag !== options.version)) fail('invalid_release', 'Release tag does not match the requested published release.'); |
| 69 | const version = tag.slice(1); |
| 70 | const suffix = { 'darwin-arm64': 'macos-arm64.dmg', 'linux-amd64': 'linux-amd64.deb', 'win32-amd64': 'windows-amd64-setup.exe' }[options.platform]; |
| 71 | let asset = release.assets?.find(a => a.name === `Cage-${version}-${suffix}`); |
| 72 | let unsigned = false; |
| 73 | if (!asset && options.platform === 'win32-amd64') { |
| 74 | asset = release.assets?.find(a => a.name === `Cage-${version}-windows-amd64-setup-unsigned.exe`); |
| 75 | if (asset && !options.allowUnsigned) fail('unsigned_package_requires_consent', 'Only an unsigned Windows preview is available. Ask the user before selecting it with --allow-unsigned.', 'user_decision'); |
| 76 | unsigned = !!asset; |
| 77 | } |
| 78 | const sums = release.assets?.find(a => a.name === 'SHA256SUMS'); |
| 79 | if (!asset || !sums) fail('asset_unavailable', 'This release has no matching package and checksum manifest. Choose a published release containing both.'); |
| 80 | if (!Number.isSafeInteger(asset.size) || asset.size <= 0) fail('invalid_release', 'The package has no valid published size.'); |
| 81 | for (const item of [asset, sums]) { |
| 82 | if (item.browser_download_url !== `https://github.com/${repo}/releases/download/${tag}/${item.name}`) fail('invalid_release', 'Unexpected release asset origin.'); |
| 83 | } |
| 84 | return { asset, sums, unsigned, tag, version }; |
| 85 | } |
| 86 | |
| 87 | export function checksumFor(manifest, name) { |
| 88 | const matches = manifest.split(/\r?\n/).map(line => line.match(/^([a-fA-F0-9]{64}) [ *](\S+)\s*$/)).filter(match => match && match[2] === name); |
| 89 | if (matches.length !== 1) fail('invalid_checksum_manifest', 'Expected exactly one SHA-256 entry for the selected package.'); |
| 90 | return matches[0][1].toLowerCase(); |
| 91 | } |
| 92 | |
| 93 | export async function makePlan(options, fetchImpl = fetch) { |
| 94 | const releaseURL = `https://api.github.com/repos/${repo}/releases/${options.version ? `tags/${options.version}` : 'latest'}`; |
| 95 | let release; |
| 96 | try { release = JSON.parse(await boundedText(releaseURL, fetchImpl)); } catch (error) { if (error instanceof BootstrapError) throw error; fail('invalid_release', 'Could not read public release metadata.'); } |
| 97 | const selected = selectAsset(release, options); |
| 98 | const sha256 = checksumFor(await boundedText(selected.sums.browser_download_url, fetchImpl), selected.asset.name); |
| 99 | const cli = { 'darwin-arm64': '/Applications/Cage.app/Contents/Resources/cage', 'linux-amd64': '/usr/bin/claude-cage', 'win32-amd64': '%LOCALAPPDATA%\\Programs\\Cage\\resources\\cage.exe' }[options.platform]; |
| 100 | const installation = { |
| 101 | 'darwin-arm64': { guide: 'https://lee-xeo.github.io/Claude-Cage/docs/installation/', steps: ['Check codesign and spctl on the mounted Cage.app. Preserve macOS Gatekeeper checks.', 'For an update, save work and stop Cage through its existing UI before replacing app files.', 'Mount the verified DMG read-only with hdiutil attach -readonly -nobrowse. Copy Cage.app to /Applications using the existing installation guide; eject the mounted volume.', 'Run the installed CLI agent capabilities. If agent is unknown, this release predates Agent support; use its documented UI or an authorized newer build.'] }, |
| 102 | 'linux-amd64': { guide: 'https://lee-xeo.github.io/Claude-Cage/docs/installation/', argv: ['sudo', 'apt-get', 'install', '--', '<downloaded_absolute_path>'], steps: ['Save work and stop Cage before an update. Run the package manager in the user-approved privilege context.', 'Run /usr/bin/claude-cage agent capabilities. The name cage belongs to a different Linux program.'] }, |
| 103 | 'win32-amd64': { guide: 'https://lee-xeo.github.io/Claude-Cage/docs/installation/', argv: ['<downloaded_absolute_path>', '/S'], steps: ['Save work and stop Cage before an update. Inspect Get-AuthenticodeSignature on signed packages.', 'Run the installer in the user-approved context; system security prompts require the user.', 'Default per-user CLI: $env:LOCALAPPDATA\\Programs\\Cage\\resources\\cage.exe. Honor any custom install directory; then run agent capabilities.'] }, |
| 104 | }[options.platform]; |
| 105 | return { protocol, status: 'planned', release: selected.tag, release_url: `https://github.com/${repo}/releases/tag/${selected.tag}`, platform: options.platform, asset: selected.asset.name, url: selected.asset.browser_download_url, size: selected.asset.size, sha256, unsigned: selected.unsigned, cli, installation, data_policy: 'Preserve ~/.claude-cage, user projects and persistent VM disks. Downloads and application files are separate from profile data.' }; |
| 106 | } |
| 107 | |
| 108 | export async function downloadPlan(plan, destination, fetchImpl = fetch) { |
| 109 | if (!isAbsolute(destination)) fail('invalid_input', 'Destination must be an absolute directory.'); |
| 110 | await mkdir(destination, { recursive: true }); |
| 111 | const stage = await mkdtemp(join(destination, '.cage-download-')); |
| 112 | try { |
| 113 | const temp = join(stage, plan.asset); |
| 114 | const response = await httpsResponse(plan.url, fetchImpl); |
| 115 | const hash = createHash('sha256'); let size = 0; |
| 116 | const verify = new Transform({ transform(chunk, encoding, callback) { |
| 117 | size += chunk.length; |
| 118 | if (size > plan.size) { callback(new BootstrapError('size_mismatch', 'Package exceeds the release size.', 'plan')); return; } |
| 119 | hash.update(chunk); callback(null, chunk); |
| 120 | } }); |
| 121 | await pipeline(Readable.fromWeb(response.body), verify, createWriteStream(temp, { flags: 'wx', mode: 0o600 })); |
| 122 | if (size !== plan.size || hash.digest('hex') !== plan.sha256) fail('checksum_mismatch', 'Package size or SHA-256 does not match the selected release. The staged download was discarded.'); |
| 123 | await chmod(temp, 0o600); |
| 124 | const path = join(destination, plan.asset); |
| 125 | |
| 126 | await link(temp, path); |
| 127 | const installation = { ...plan.installation }; |
| 128 | if (installation.argv) installation.argv = installation.argv.map(arg => arg === '<downloaded_absolute_path>' ? path : arg); |
| 129 | return { ...plan, status: 'downloaded', path, installation }; |
| 130 | } finally { await rm(stage, { recursive: true, force: true }); } |
| 131 | } |
| 132 | |
| 133 | export async function main(args = process.argv.slice(2)) { |
| 134 | try { |
| 135 | const options = parseArgs([...args]); |
| 136 | let result = await makePlan(options); |
| 137 | if (options.action === 'download') result = await downloadPlan(result, options.destination); |
| 138 | process.stdout.write(`${JSON.stringify(result)}\n`); |
| 139 | } catch (error) { |
| 140 | |
| 141 | const known = error instanceof BootstrapError; |
| 142 | process.stdout.write(`${JSON.stringify({ protocol, status: 'error', error: { code: known ? error.code : error.code === 'EEXIST' ? 'destination_exists' : 'bootstrap_failed', message: known ? error.message : 'Could not prepare the package. Preserve existing files and inspect connectivity, destination permissions and available space.', next_action: known ? error.next_action : 'plan' } })}\n`); |
| 143 | process.exitCode = known && error.code === 'invalid_input' ? 2 : 1; |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) await main(); |