Files
marqdo-app-harness/scripts/release.ts
cflmy 5f56c23455 feat: add unified egress, bootstrap, diagnostics and app distribution
Implements the four follow-up design issues for MQDH:\n\n- network: one policy/proxy/mirror/offline/audit client for product egress\n- bootstrap: first-run state machine, default Tools, real smoke, doctor/repair\n- diagnostics: local redacted reports and explicit Gitea issue submission\n- distribution: release manifest, user install tree, update/rollback, installer\n\nThe product CLI exposes bootstrap/doctor/repair/report/update/network and the\n/mqdh workbench renders the same services. Marqdo runtime artifacts remain\ndownloaded from trusted releases; unsupported platforms and unrun gates stay\nUNVERIFIED in docs/mqdh/STATUS.md.
2026-11-28 23:07:07 +08:00

130 lines
6.4 KiB
JavaScript
Executable File

#!/usr/bin/env node
/**
* Publish one already-packaged Marqdo Harness release to the authoritative Gitea
* repository. Dry-run by default; `--publish` performs the mutation. This is CI
* release tooling, not product runtime egress: the product itself uses the
* `network` service in `packages/marqdo/harness/src/network/`.
*
* MQDH_GITEA_TOKEN=... node scripts/release.ts --version 0.1.0 \
* --source <40-hex> --assets .ci [--publish] [--repo cflmy/marqdo-app-harness] \
* [--api https://git.cflmy.cn/api/v1]
*/
import { createHash } from 'node:crypto'
import { readFile, stat } from 'node:fs/promises'
import { basename, join, resolve } from 'node:path'
/** Parsed flags. */
function parse(argv: string[]): Map<string, string[]> {
const map = new Map<string, string[]>()
for (let index = 0; index < argv.length; index++) {
const token = argv[index]
if (token === undefined || !token.startsWith('--')) continue
if (token === '--publish') { map.set('publish', ['true']); continue }
const value = argv[index + 1]
if (value === undefined || value.startsWith('--')) throw new Error(`missing value for ${token}`)
map.set(token.slice(2), [...(map.get(token.slice(2)) ?? []), value])
index++
}
return map
}
/** Last flag value. */
function flag(map: Map<string, string[]>, name: string): string | undefined {
return map.get(name)?.at(-1)
}
/** Required flag. */
function required(map: Map<string, string[]>, name: string): string {
const value = flag(map, name)
if (value === undefined || value.trim() === '') throw new Error(`--${name} is required`)
return value
}
const args = parse(process.argv.slice(2))
const version = required(args, 'version')
const source = required(args, 'source')
const assets = resolve(flag(args, 'assets') ?? '.ci')
const repository = flag(args, 'repo') ?? 'cflmy/marqdo-app-harness'
const api = (flag(args, 'api') ?? 'https://git.cflmy.cn/api/v1').replace(/\/$/, '')
const publish = flag(args, 'publish') === 'true'
const tag = `mqdh-v${version}`
if (!/^[0-9a-f]{40}$/.test(source)) throw new Error(`--source must be a 40-hex commit, got ${source}`)
const manifestPath = join(assets, 'mqdh-release.json')
const evidencePath = join(assets, 'release-evidence.json')
const archiveName = `marqdo-harness-${version}-x86_64-unknown-linux-gnu.tar.gz`
const archivePath = join(assets, archiveName)
const sidecarPath = join(assets, `${archiveName}.sha256`)
const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
const app = manifest.app as Record<string, unknown> | undefined
const asset = manifest.asset as Record<string, unknown> | undefined
if (app?.version !== version) throw new Error(`manifest version ${String(app?.version)} does not match ${version}`)
if (app?.source_sha !== source) throw new Error(`manifest source ${String(app?.source_sha)} does not match ${source}`)
if (asset?.name !== archiveName) throw new Error(`manifest asset ${String(asset?.name)} does not match ${archiveName}`)
const archiveBytes = await readFile(archivePath)
const digest = createHash('sha256').update(archiveBytes).digest('hex')
if (asset?.sha256 !== digest) throw new Error(`archive digest ${digest} does not match the manifest`)
const sidecar = await readFile(sidecarPath, 'utf8')
if (!sidecar.startsWith(digest)) throw new Error('sidecar digest does not match the archive')
const evidence = JSON.parse(await readFile(evidencePath, 'utf8')) as Record<string, unknown>
if (evidence.tag !== tag) throw new Error(`release evidence tag ${String(evidence.tag)} does not match ${tag}`)
const uploads = [manifestPath, archivePath, sidecarPath, evidencePath]
if (await stat(join(assets, 'mqdh-release.json.sig')).then(info => info.isFile()).catch(() => false)) {
uploads.push(join(assets, 'mqdh-release.json.sig'))
}
for (const path of uploads) {
const info = await stat(path)
if (!info.isFile() || info.size === 0) throw new Error(`missing release asset: ${path}`)
}
const token = process.env.MQDH_GITEA_TOKEN?.trim()
if (publish && (token === undefined || token === '')) throw new Error('MQDH_GITEA_TOKEN is required with --publish')
const headers: Record<string, string> = { accept: 'application/json' }
if (token !== undefined) headers.authorization = `token ${token}`
const call = async (method: string, path: string, body: BodyInit, contentType: string): Promise<Record<string, unknown>> => {
const response = await fetch(`${api}/repos/${repository}${path}`, {
method,
headers: { ...headers, 'content-type': contentType },
body,
})
const text = await response.text()
if (!response.ok) throw new Error(`${method} ${path} failed: ${response.status} ${text.slice(0, 500)}`)
return text.trim() === '' ? {} : JSON.parse(text) as Record<string, unknown>
}
const existing = await fetch(`${api}/repos/${repository}/releases/tags/${tag}`, { headers })
if (existing.ok) throw new Error(`release ${tag} already exists; releases are immutable`)
if (existing.status !== 404) throw new Error(`cannot verify release ${tag}: HTTP ${existing.status}`)
if (!publish) {
process.stdout.write(`dry-run: would create ${tag} at ${source} and upload ${uploads.length} assets to ${repository}\n`)
for (const path of uploads) process.stdout.write(` ${basename(path)} (${(await stat(path)).size} bytes)\n`)
process.exit(0)
}
const release = await call('POST', '/releases', JSON.stringify({
tag_name: tag,
target_commitish: source,
name: `Marqdo Harness ${version}`,
body: `MQDH ${version} for ${String((manifest.platform as Record<string, unknown> | undefined)?.target ?? 'unknown')}.\n\nSource: \`${source}\`\nManifest: \`mqdh-release.json\`\n`,
draft: false,
prerelease: version.includes('-'),
}), 'application/json')
const releaseId = typeof release.id === 'number' ? release.id : null
if (releaseId === null) throw new Error('Gitea returned no release id')
for (const path of uploads) {
const bytes = await readFile(path)
const form = new FormData()
form.append('attachment', new Blob([bytes]), basename(path))
const response = await fetch(`${api}/repos/${repository}/releases/${releaseId}/assets?name=${encodeURIComponent(basename(path))}`, {
method: 'POST',
headers,
body: form,
})
if (!response.ok) throw new Error(`upload ${basename(path)} failed: ${response.status} ${(await response.text()).slice(0, 300)}`)
process.stdout.write(`uploaded ${basename(path)}\n`)
}
process.stdout.write(`published ${tag}: ${String(release.html_url ?? '')}\n`)