| 1 | |
| 2 | import { createHash } from 'node:crypto'; |
| 3 | import { createWriteStream } from 'node:fs'; |
| 4 | import { mkdir, writeFile, rm } from 'node:fs/promises'; |
| 5 | import { dirname, join, resolve } from 'node:path'; |
| 6 | import { pathToFileURL } from 'node:url'; |
| 7 | import { Readable, Transform } from 'node:stream'; |
| 8 | import { pipeline } from 'node:stream/promises'; |
| 9 | import { parseArgs } from 'node:util'; |
| 10 | |
| 11 | const repository = 'Lee-xeo/Claude-Cage'; |
| 12 | const repoURL = `https://github.com/${repository}`; |
| 13 | const apiURL = `https://api.github.com/repos/${repository}/releases`; |
| 14 | const sourceArchive = name => /^mihomo-v[\d.]+-source\.tar\.gz$/.test(name) || |
| 15 | /^cage-macos-guest-\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?-source\.tar\.gz$/.test(name) || |
| 16 | /^qemu-[0-9a-f]{40}-source\.tar\.gz$/.test(name) || |
| 17 | /^qemu-keycodemapdb-[0-9a-f]{40}-source\.tar\.gz$/.test(name) || |
| 18 | /^qemu-\d+\.\d+\.\d+-cage-changes-source\.tar\.gz$/.test(name) || |
| 19 | /^qemu-\d+\.\d+\.\d+-windows-full-source\.(?:tar\.)?(?:gz|xz|bz2|zst|zip|7z|tar)$/.test(name); |
| 20 | |
| 21 | export async function request(url, timeout = 180_000, { fetchImpl = fetch } = {}) { |
| 22 | const target = new URL(url); |
| 23 | const metadata = target.origin === 'https://api.github.com' && |
| 24 | (target.pathname === `/repos/${repository}/releases` || target.pathname.startsWith(`/repos/${repository}/releases/`)); |
| 25 | const options = { |
| 26 | headers: { 'User-Agent': 'Cage-Release-Verification', Accept: metadata ? 'application/vnd.github+json' : 'application/octet-stream' }, |
| 27 | signal: AbortSignal.timeout(timeout), |
| 28 | }; |
| 29 | let response = await fetchImpl(url, options); |
| 30 | if (metadata && response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0') { |
| 31 | const tag = target.pathname.match(/^\/repos\/Lee-xeo\/Claude-Cage\/releases\/tags\/(v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/)?.[1]; |
| 32 | if (tag) { |
| 33 | await response.body?.cancel(); |
| 34 | console.warn('Anonymous GitHub API is rate limited; reading the requested version from its public checksum manifest.'); |
| 35 | return new Response(JSON.stringify(await publicManifestRelease(tag, fetchImpl))); |
| 36 | } |
| 37 | } |
| 38 | if (!response.ok) throw new Error(`Public download failed: HTTP ${response.status} (${new URL(url).pathname})`); |
| 39 | return response; |
| 40 | } |
| 41 | |
| 42 | export async function publicManifestRelease(tag, fetchImpl = fetch) { |
| 43 | if (!/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(tag)) throw new Error('Invalid public release tag'); |
| 44 | const base = `${repoURL}/releases/download/${tag}/`; |
| 45 | const manifest = await request(`${base}SHA256SUMS`, 180_000, { fetchImpl }); |
| 46 | const text = await manifest.text(); |
| 47 | if (!text.length || Buffer.byteLength(text) > 65536) throw new Error('Invalid public checksum manifest size'); |
| 48 | const names = new Map(); |
| 49 | for (const line of text.split(/\r?\n/).filter(Boolean)) { |
| 50 | const match = /^([a-f0-9]{64}) [ *]([A-Za-z0-9][A-Za-z0-9._-]*)$/i.exec(line); |
| 51 | if (!match || names.has(match[2])) throw new Error('Invalid or duplicate public checksum entry'); |
| 52 | names.set(match[2], match[1].toLowerCase()); |
| 53 | } |
| 54 | const version = tag.slice(1); |
| 55 | const allowed = name => [ |
| 56 | `Cage-${version}-macos-arm64.dmg`, `Cage-${version}-windows-amd64-setup.exe`, |
| 57 | `Cage-${version}-windows-amd64-setup-unsigned.exe`, `Cage-${version}-linux-amd64.deb`, |
| 58 | `Cage-${version}-android-arm64.apk`, |
| 59 | ].includes(name) || sourceArchive(name); |
| 60 | if ([...names.keys()].some(name => !allowed(name))) throw new Error('Unexpected public release asset'); |
| 61 | const assets = [{ name: 'SHA256SUMS', state: 'uploaded', size: Buffer.byteLength(text), browser_download_url: `${base}SHA256SUMS` }]; |
| 62 | for (const [name, digest] of names) { |
| 63 | const response = await fetchImpl(`${base}${name}`, { method: 'HEAD', headers: { 'User-Agent': 'Cage-Release-Verification' }, signal: AbortSignal.timeout(180_000) }); |
| 64 | const size = Number(response.headers.get('content-length')); |
| 65 | const maximum = (sourceArchive(name) ? 2048 : 512) * 1024 * 1024; |
| 66 | if (!response.ok || !Number.isSafeInteger(size) || size <= 0 || size > maximum) throw new Error(`Missing or incomplete public asset: ${name}`); |
| 67 | assets.push({ name, state: 'uploaded', size, digest: `sha256:${digest}`, browser_download_url: `${base}${name}` }); |
| 68 | } |
| 69 | const release = { tag_name: tag, draft: false, prerelease: version.includes('-'), assets }; |
| 70 | releaseAssets(release); |
| 71 | return release; |
| 72 | } |
| 73 | |
| 74 | export function releaseAssets(release) { |
| 75 | if (release.draft || !/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(release.tag_name)) { |
| 76 | throw new Error('Expected a published Cage version tag'); |
| 77 | } |
| 78 | const version = release.tag_name.slice(1); |
| 79 | const names = [`Cage-${version}-macos-arm64.dmg`, 'SHA256SUMS']; |
| 80 | const assets = names.map(name => release.assets.find(asset => asset.name === name)); |
| 81 | const source = release.assets.find(asset => /^mihomo-v[\d.]+-source\.tar\.gz$/.test(asset.name)); |
| 82 | assets.push(source); |
| 83 | for (const asset of assets) { |
| 84 | if (!asset || asset.state !== 'uploaded' || !Number.isSafeInteger(asset.size) || asset.size <= 0 || asset.size > 512 * 1024 * 1024) { |
| 85 | throw new Error(`Release ${release.tag_name} is missing a complete DMG, checksum file, or Mihomo source`); |
| 86 | } |
| 87 | if (asset.browser_download_url !== `${repoURL}/releases/download/${release.tag_name}/${asset.name}`) { |
| 88 | throw new Error('Release asset is outside the expected repository and tag'); |
| 89 | } |
| 90 | } |
| 91 | if (assets[1].size > 64 * 1024) throw new Error('Checksum file is too large'); |
| 92 | const windows = optionalAsset(release, `Cage-${version}-windows-amd64-setup.exe`); |
| 93 | const linux = optionalAsset(release, `Cage-${version}-linux-amd64.deb`); |
| 94 | const android = optionalAsset(release, `Cage-${version}-android-arm64.apk`); |
| 95 | const guestSource = optionalAsset(release, `cage-macos-guest-${version}-source.tar.gz`); |
| 96 | return { version, archive: assets[0], checksums: assets[1], source, windows, linux, android, guestSource }; |
| 97 | } |
| 98 | |
| 99 | function optionalAsset(release, name) { |
| 100 | const matches = release.assets.filter(asset => asset.name === name); |
| 101 | const asset = matches.length === 1 ? matches[0] : undefined; |
| 102 | return asset && asset.state === 'uploaded' && Number.isSafeInteger(asset.size) && |
| 103 | asset.size > 0 && asset.size <= 512 * 1024 * 1024 && |
| 104 | asset.browser_download_url === `${repoURL}/releases/download/${release.tag_name}/${name}` |
| 105 | ? asset : undefined; |
| 106 | } |
| 107 | |
| 108 | export function checksumFor(text, asset) { |
| 109 | const entries = text.split(/\r?\n/).map(line => line.trim().split(/\s+/)) |
| 110 | .filter(fields => fields.length === 2 && fields[1].replace(/^\*/, '') === asset.name); |
| 111 | if (entries.length !== 1 || !/^[a-f0-9]{64}$/i.test(entries[0][0])) throw new Error(`Missing or duplicate SHA-256 for ${asset.name}`); |
| 112 | const digest = entries[0][0].toLowerCase(); |
| 113 | if (asset.digest && asset.digest.toLowerCase() !== `sha256:${digest}`) throw new Error(`GitHub digest disagrees with SHA256SUMS for ${asset.name}`); |
| 114 | return digest; |
| 115 | } |
| 116 | |
| 117 | export function releaseMetadata(release, text) { |
| 118 | const { version, archive, source, windows, linux, android } = releaseAssets(release); |
| 119 | checksumFor(text, archive); |
| 120 | checksumFor(text, source); |
| 121 | const metadata = { version, releaseURL: `${repoURL}/releases/tag/v${version}`, downloadURL: archive.browser_download_url }; |
| 122 | for (const [key, asset] of [['windowsDownloadURL', windows], ['linuxDownloadURL', linux], ['androidDownloadURL', android]]) { |
| 123 | if (!asset) continue; |
| 124 | try { |
| 125 | checksumFor(text, asset); |
| 126 | metadata[key] = asset.browser_download_url; |
| 127 | } catch { |
| 128 | |
| 129 | } |
| 130 | } |
| 131 | if (!metadata.windowsDownloadURL && release.prerelease) { |
| 132 | const unsigned = optionalAsset(release, `Cage-${version}-windows-amd64-setup-unsigned.exe`); |
| 133 | const qemu = release.assets.find(asset => /^qemu-[0-9a-f]{40}-source\.tar\.gz$/.test(asset.name)); |
| 134 | if (unsigned && qemu && optionalAsset(release, qemu.name)) { |
| 135 | try { |
| 136 | checksumFor(text, unsigned); |
| 137 | checksumFor(text, qemu); |
| 138 | metadata.windowsPreview = { version, releaseURL: metadata.releaseURL, downloadURL: unsigned.browser_download_url }; |
| 139 | } catch { |
| 140 | |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | return metadata; |
| 145 | } |
| 146 | |
| 147 | async function checksumText(release) { |
| 148 | const asset = optionalAsset(release, 'SHA256SUMS'); |
| 149 | if (!asset || asset.size > 64 * 1024) throw new Error('Missing complete checksum file'); |
| 150 | const text = await (await request(asset.browser_download_url)).text(); |
| 151 | if (Buffer.byteLength(text) !== asset.size) throw new Error('Checksum file size differs from GitHub metadata'); |
| 152 | return text; |
| 153 | } |
| 154 | |
| 155 | async function download(asset, digest, directory) { |
| 156 | await mkdir(directory, { recursive: true }); |
| 157 | const path = join(directory, asset.name); |
| 158 | const response = await request(asset.browser_download_url, 15 * 60 * 1000); |
| 159 | const hash = createHash('sha256'); |
| 160 | let size = 0; |
| 161 | try { |
| 162 | await pipeline(Readable.fromWeb(response.body), new Transform({ |
| 163 | transform(chunk, encoding, callback) { |
| 164 | size += chunk.length; |
| 165 | if (size > asset.size) return callback(new Error('Release asset exceeds its declared size')); |
| 166 | hash.update(chunk); |
| 167 | callback(null, chunk); |
| 168 | }, |
| 169 | }), createWriteStream(`${path}.part`, { flags: 'wx' })); |
| 170 | if (size !== asset.size || hash.digest('hex') !== digest) throw new Error(`Downloaded bytes do not match SHA256SUMS: ${asset.name}`); |
| 171 | const { rename } = await import('node:fs/promises'); |
| 172 | await rename(`${path}.part`, path); |
| 173 | } finally { |
| 174 | await rm(`${path}.part`, { force: true }); |
| 175 | } |
| 176 | console.log(`Verified public download: ${asset.name} (${size} bytes)`); |
| 177 | } |
| 178 | |
| 179 | async function main() { |
| 180 | const { values } = parseArgs({ options: { |
| 181 | tag: { type: 'string' }, output: { type: 'string', default: 'www/src/data/release.json' }, |
| 182 | 'archive-directory': { type: 'string' }, |
| 183 | } }); |
| 184 | let release; |
| 185 | let releases; |
| 186 | if (values.tag) { |
| 187 | release = await (await request(`${apiURL}/tags/${encodeURIComponent(values.tag)}`)).json(); |
| 188 | } else { |
| 189 | releases = await (await request(`${apiURL}?per_page=100`)).json(); |
| 190 | |
| 191 | release = releases.find(item => { |
| 192 | try { releaseAssets(item); return true; } catch { return false; } |
| 193 | }); |
| 194 | if (!release) throw new Error('No complete public Cage release is available'); |
| 195 | } |
| 196 | const { version, archive, source, guestSource } = releaseAssets(release); |
| 197 | const text = await checksumText(release); |
| 198 | const digest = checksumFor(text, archive); |
| 199 | const sourceDigest = checksumFor(text, source); |
| 200 | const metadata = releaseMetadata(release, text); |
| 201 | if (values['archive-directory']) { |
| 202 | await download(archive, digest, values['archive-directory']); |
| 203 | await download(source, sourceDigest, values['archive-directory']); |
| 204 | if (guestSource) await download(guestSource, checksumFor(text, guestSource), values['archive-directory']); |
| 205 | await writeFile(join(values['archive-directory'], 'SHA256SUMS'), text); |
| 206 | for (const url of [metadata.windowsDownloadURL || metadata.windowsPreview?.downloadURL, metadata.linuxDownloadURL, metadata.androidDownloadURL].filter(Boolean)) { |
| 207 | const asset = release.assets.find(asset => asset.browser_download_url === url); |
| 208 | await download(asset, checksumFor(text, asset), values['archive-directory']); |
| 209 | } |
| 210 | } |
| 211 | const output = resolve(values.output); |
| 212 | await mkdir(dirname(output), { recursive: true }); |
| 213 | await writeFile(output, `${JSON.stringify(metadata, null, 2)}\n`); |
| 214 | console.log(`Website download: Cage ${version}`); |
| 215 | } |
| 216 | |
| 217 | if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { |
| 218 | main().catch(error => { console.error(error.message); process.exitCode = 1; }); |
| 219 | } |