diff --git a/.github/workflows/mirror-cnb.yml b/.github/workflows/mirror-cnb.yml new file mode 100644 index 0000000..51c81c6 --- /dev/null +++ b/.github/workflows/mirror-cnb.yml @@ -0,0 +1,66 @@ +name: Mirror to CNB + +# Syncs main's plugin index, deltas, recommendations, latest plugin release archives and SVG icons +# to https://cnb.cool/lithe-idea/Lithe-store so mainland users can browse and download plugins +# directly via CNB with automatic GitHub fallback. +on: + push: + branches: [main] + paths: + - lithe-plugin-index.json + - lithe-plugin-deltas.json + - lithe-plugin-recommendations.json + - assets/** + - scripts/mirror-cnb.mjs + workflow_dispatch: + inputs: + plugin: + description: "Only mirror this plugin ID (empty = all)" + required: false + default: "" + keep_versions: + description: "Number of latest versions to keep per plugin" + required: false + default: "3" + +permissions: + contents: read + +concurrency: + group: mirror-cnb + cancel-in-progress: false + +jobs: + mirror: + name: Mirror store and plugin archives to CNB + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + ref: main + fetch-depth: 0 + + - uses: actions/setup-node@v7 + with: + node-version: 22 + + - name: Sync repository and plugin packages to CNB + env: + CNB_TOKEN: ${{ secrets.CNB_TOKEN }} + PLUGIN: ${{ inputs.plugin }} + KEEP_VERSIONS: ${{ inputs.keep_versions }} + run: | + if [[ -z "${CNB_TOKEN:-}" ]]; then + printf '%s\n' 'CNB_TOKEN is not set; skipping CNB mirror.' + exit 0 + fi + args=() + if [[ -n "$PLUGIN" ]]; then + args+=(--plugin "$PLUGIN") + fi + if [[ -n "$KEEP_VERSIONS" ]]; then + args+=(--keep-versions "$KEEP_VERSIONS") + fi + node scripts/mirror-cnb.mjs "${args[@]}" diff --git a/scripts/mirror-cnb.mjs b/scripts/mirror-cnb.mjs new file mode 100755 index 0000000..9423142 --- /dev/null +++ b/scripts/mirror-cnb.mjs @@ -0,0 +1,496 @@ +#!/usr/bin/env node +/** + * Mirrors Lithe-store index/deltas/recommendations Git files, latest plugin release archives + * (plus matching deltas), and plugin icons to CNB (`https://cnb.cool/lithe-idea/Lithe-store`). + */ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createReadStream, createWriteStream } from "node:fs"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { compareVersions } from "./track-releases.mjs"; + +const execFileAsync = promisify(execFile); + +const DEFAULT_CNB_REPO = "lithe-idea/Lithe-store"; +const DEFAULT_API_BASE = "https://api.cnb.cool"; +const DEFAULT_WEB_BASE = "https://cnb.cool"; +const DEFAULT_KEEP_VERSIONS = 3; +const MAX_CAPABILITY_EXTRA_VERSIONS = 2; +const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024; +const MAX_ICON_BYTES = 2 * 1024 * 1024; +const CHECKSUMS_ASSET = ".mirror-checksums.json"; +const ICONS_TAG = "plugin-icons"; +const PLUGIN_TAG_PREFIX = "plugin-"; +const MAX_ATTEMPTS = 3; +const RETRY_DELAY_MS = 1500; + +export function parseArgs(argv) { + const opts = { + repo: DEFAULT_CNB_REPO, + plugin: "", + keepVersions: DEFAULT_KEEP_VERSIONS, + skipGitPush: false, + help: false, + }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + const next = () => { + if (i + 1 >= argv.length) throw new Error(`Missing value for ${arg}`); + return argv[++i]; + }; + switch (arg) { + case "--help": + case "-h": + opts.help = true; + return opts; + case "--repo": + opts.repo = next(); + break; + case "--plugin": + opts.plugin = next().trim(); + break; + case "--keep-versions": + opts.keepVersions = Number.parseInt(next(), 10); + if (!Number.isInteger(opts.keepVersions) || opts.keepVersions < 1) { + throw new Error("--keep-versions must be a positive integer"); + } + break; + case "--skip-git-push": + opts.skipGitPush = true; + break; + default: + throw new Error(`Unknown argument: ${arg}`); + } + } + return opts; +} + +export function selectVersionsToMirror(versions, keepVersions = DEFAULT_KEEP_VERSIONS) { + const sorted = [...(versions || [])].sort((a, b) => compareVersions(b.version, a.version)); + const selected = []; + const selectedNames = new Set(); + const seenAPIs = new Set(); + + for (const item of sorted.slice(0, keepVersions)) { + selected.push(item); + selectedNames.add(item.version); + seenAPIs.add(item.pluginAPIVersion); + } + + let extra = 0; + for (const item of sorted.slice(keepVersions)) { + if (extra >= MAX_CAPABILITY_EXTRA_VERSIONS) break; + if (!seenAPIs.has(item.pluginAPIVersion)) { + seenAPIs.add(item.pluginAPIVersion); + selected.push(item); + selectedNames.add(item.version); + extra++; + } + } + return selected; +} + +function redactSecret(text, secret) { + if (!secret || !text) return text; + const basic = Buffer.from(`cnb:${secret}`, "utf8").toString("base64"); + return String(text).replaceAll(secret, "[REDACTED]").replaceAll(basic, "[REDACTED]"); +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function withRetry(label, fn) { + let lastErr; + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try { + return await fn(); + } catch (err) { + lastErr = err; + if (err?.retryable === false || attempt === MAX_ATTEMPTS) { + throw err; + } + console.warn(`${label} failed (attempt ${attempt}/${MAX_ATTEMPTS}): ${err.message}; retrying...`); + await sleep(RETRY_DELAY_MS * attempt); + } + } + throw lastErr; +} + +class CNBClient { + constructor(token, apiBase, webBase) { + this.token = token; + this.apiBase = apiBase.replace(/\/+$/, ""); + this.webBase = webBase.replace(/\/+$/, ""); + } + + async request(method, apiPath, body) { + const url = apiPath.startsWith("http://") || apiPath.startsWith("https://") + ? apiPath + : `${this.apiBase}${apiPath}`; + const headers = { + Authorization: `Bearer ${this.token}`, + Accept: "application/json", + }; + const init = { method, headers }; + if (body !== undefined) { + headers["Content-Type"] = "application/json"; + init.body = JSON.stringify(body); + } + const response = await fetch(url, init); + const text = await response.text(); + if (!response.ok) { + const err = new Error(`CNB API ${method} ${apiPath} returned HTTP ${response.status}: ${redactSecret(text.slice(0, 400), this.token)}`); + err.status = response.status; + err.retryable = response.status >= 500 || response.status === 429; + throw err; + } + if (!text.trim()) return null; + try { + return JSON.parse(text); + } catch { + return text; + } + } + + async getReleaseByTag(repo, tag) { + try { + return await this.request("GET", `/${repo}/-/releases/tags/${encodeURIComponent(tag)}`); + } catch (err) { + if (err.status === 404) return null; + throw err; + } + } + + async ensureTag(repo, tag, target) { + try { + await this.request("POST", `/${repo}/-/git/tags`, { name: tag, target }); + } catch (err) { + if (err.status !== 409 && err.status !== 422) { + throw err; + } + } + } + + async ensureRelease(repo, { tag, title, body, targetCommitish = "main" }) { + const existing = await this.getReleaseByTag(repo, tag); + if (existing) { + return existing; + } + try { + return await this.request("POST", `/${repo}/-/releases`, { + tag_name: tag, + target_commitish: targetCommitish, + name: title, + body, + draft: false, + prerelease: true, + make_latest: "false", + }); + } catch (err) { + if (err.status === 400 || err.status === 404 || err.status === 422) { + await this.ensureTag(repo, tag, targetCommitish); + return await this.request("POST", `/${repo}/-/releases`, { + tag_name: tag, + target_commitish: targetCommitish, + name: title, + body, + draft: false, + prerelease: true, + make_latest: "false", + }); + } + throw err; + } + } + + async listAllReleases(repo) { + const all = []; + for (let page = 1; ; page++) { + const batch = await this.request("GET", `/${repo}/-/releases?page=${page}&page_size=100`); + if (!Array.isArray(batch) || batch.length === 0) break; + all.push(...batch); + if (batch.length < 100) break; + } + return all; + } + + async uploadAsset(repo, releaseId, filePath, assetName = path.basename(filePath)) { + const info = await stat(filePath); + await withRetry(`Upload ${assetName}`, async () => { + const ticket = await this.request( + "POST", + `/${repo}/-/releases/${encodeURIComponent(releaseId)}/asset-upload-url`, + { + asset_name: assetName, + size: info.size, + overwrite: true, + ttl: 0, + }, + ); + if (!ticket?.upload_url || !ticket?.verify_url) { + throw new Error(`Invalid CNB upload ticket for ${assetName}`); + } + const uploadRes = await fetch(ticket.upload_url, { + method: "PUT", + headers: { + "Content-Type": "application/octet-stream", + "Content-Length": String(info.size), + }, + body: createReadStream(filePath), + duplex: "half", + }); + if (!uploadRes.ok) { + const err = new Error(`PUT ${assetName} returned HTTP ${uploadRes.status}`); + err.retryable = uploadRes.status >= 500 || uploadRes.status === 429; + throw err; + } + const verifyUrl = ticket.verify_url.includes("ttl=") + ? ticket.verify_url + : `${ticket.verify_url}${ticket.verify_url.includes("?") ? "&" : "?"}ttl=0`; + await this.request("POST", verifyUrl); + }); + } + + async deleteAsset(repo, releaseId, assetId) { + await this.request("DELETE", `/${repo}/-/releases/${encodeURIComponent(releaseId)}/assets/${encodeURIComponent(assetId)}`); + } + + async deleteRelease(repo, releaseId) { + await this.request("DELETE", `/${repo}/-/releases/${encodeURIComponent(releaseId)}`); + } + + async readChecksums(repo, release) { + const asset = (release.assets || []).find((a) => a.name === CHECKSUMS_ASSET); + if (!asset) return {}; + const downloadUrl = asset.browser_download_url + || `${this.webBase}/${repo}/-/releases/download/${encodeURIComponent(release.tag_name)}/${CHECKSUMS_ASSET}`; + try { + const res = await fetch(downloadUrl, { signal: AbortSignal.timeout(15_000) }); + if (!res.ok) return {}; + const parsed = JSON.parse(await res.text()); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } + } +} + +async function downloadAndVerify(url, destPath, expectedSha256, maxBytes) { + return await withRetry(`Download ${path.basename(destPath)}`, async () => { + const res = await fetch(url, { signal: AbortSignal.timeout(60_000) }); + if (!res.ok) { + const err = new Error(`GET ${url} returned HTTP ${res.status}`); + err.retryable = res.status >= 500 || res.status === 429; + throw err; + } + const hash = createHash("sha256"); + let total = 0; + const out = createWriteStream(destPath); + try { + const bodyStream = Readable.fromWeb(res.body); + for await (const chunk of bodyStream) { + total += chunk.length; + if (total > maxBytes) { + const err = new Error(`${url} exceeds size limit (${maxBytes} bytes)`); + err.retryable = false; + throw err; + } + hash.update(chunk); + if (!out.write(chunk)) { + await new Promise((resolve) => out.once("drain", resolve)); + } + } + await new Promise((resolve, reject) => { + out.end((err) => (err ? reject(err) : resolve())); + }); + } catch (err) { + out.destroy(); + throw err; + } + const actualSha256 = hash.digest("hex"); + if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) { + const err = new Error(`SHA-256 mismatch for ${url}: got ${actualSha256}, want ${expectedSha256}`); + err.retryable = false; + throw err; + } + return actualSha256; + }); +} + +async function pushMainToCNB(webBase, repo, token) { + const remote = `${webBase.replace(/\/+$/, "")}/${repo}.git`; + const basic = Buffer.from(`cnb:${token}`, "utf8").toString("base64"); + try { + await execFileAsync("git", ["push", remote, "HEAD:refs/heads/main"], { + env: { + ...process.env, + GIT_TERMINAL_PROMPT: "0", + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: `http.${webBase.replace(/\/+$/, "")}/.extraheader`, + GIT_CONFIG_VALUE_0: `Authorization: Basic ${basic}`, + }, + cwd: process.cwd(), + maxBuffer: 1024 * 1024, + }); + } catch (err) { + throw new Error(`git push HEAD:refs/heads/main to CNB failed: ${redactSecret(err.stderr || err.message, token)}`); + } +} + +async function syncReleaseAssets(client, repo, { tag, title, body, targetCommitish, desiredAssets, scratchDir }) { + const release = await client.ensureRelease(repo, { tag, title, body, targetCommitish }); + const existingNames = new Set((release.assets || []).map((a) => a.name)); + const oldChecksums = await client.readChecksums(repo, release); + const nextChecksums = {}; + let changed = false; + + for (const [assetName, spec] of desiredAssets) { + const knownDigest = oldChecksums[assetName]; + if (existingNames.has(assetName) && knownDigest && (!spec.sha256 || knownDigest === spec.sha256)) { + nextChecksums[assetName] = knownDigest; + continue; + } + const localFile = path.join(scratchDir, assetName); + const actualDigest = await downloadAndVerify(spec.url, localFile, spec.sha256, spec.maxBytes); + await client.uploadAsset(repo, release.id, localFile, assetName); + await rm(localFile, { force: true }); + nextChecksums[assetName] = actualDigest; + changed = true; + } + + for (const asset of release.assets || []) { + if (asset.name === CHECKSUMS_ASSET) continue; + if (!desiredAssets.has(asset.name)) { + console.log(`Pruning stale asset ${asset.name} from ${tag}`); + await client.deleteAsset(repo, release.id, asset.id); + changed = true; + } + } + + if (changed || !existingNames.has(CHECKSUMS_ASSET)) { + const manifestPath = path.join(scratchDir, CHECKSUMS_ASSET); + await writeFile(manifestPath, `${JSON.stringify(nextChecksums, null, 2)}\n`); + await client.uploadAsset(repo, release.id, manifestPath, CHECKSUMS_ASSET); + await rm(manifestPath, { force: true }); + } +} + +export async function run(argv = process.argv.slice(2)) { + const opts = parseArgs(argv); + if (opts.help) { + process.stdout.write("Usage: mirror-cnb.mjs [--repo owner/repo] [--plugin id] [--keep-versions 3] [--skip-git-push]\n"); + return; + } + const token = process.env.CNB_TOKEN || ""; + if (!token) { + throw new Error("CNB_TOKEN is not set"); + } + const apiBase = process.env.CNB_API_BASE || DEFAULT_API_BASE; + const webBase = process.env.CNB_WEB_BASE || DEFAULT_WEB_BASE; + const client = new CNBClient(token, apiBase, webBase); + + const index = JSON.parse(await readFile("lithe-plugin-index.json", "utf8")); + const deltas = JSON.parse(await readFile("lithe-plugin-deltas.json", "utf8")); + + let headSha = "main"; + if (!opts.skipGitPush) { + const rev = await execFileAsync("git", ["rev-parse", "HEAD"], { cwd: process.cwd() }); + headSha = rev.stdout.trim() || "main"; + await pushMainToCNB(webBase, opts.repo, token); + } + + const deltasByPlugin = new Map(); + for (const patch of deltas.patches || []) { + if (!deltasByPlugin.has(patch.pluginID)) deltasByPlugin.set(patch.pluginID, []); + deltasByPlugin.get(patch.pluginID).push(patch); + } + + const plugins = opts.plugin + ? (index.plugins || []).filter((p) => p.id === opts.plugin) + : (index.plugins || []); + if (opts.plugin && plugins.length === 0) { + throw new Error(`Plugin ${opts.plugin} not found in lithe-plugin-index.json`); + } + + const scratchDir = await mkdtemp(path.join(os.tmpdir(), "lithe-store-cnb-")); + try { + for (const plugin of plugins) { + const selectedVersions = selectVersionsToMirror(plugin.versions, opts.keepVersions); + const selectedVersionNames = new Set(selectedVersions.map((v) => v.version)); + const desired = new Map(); + + for (const ver of selectedVersions) { + for (const dl of ver.downloads || []) { + const assetName = path.basename(new URL(dl.downloadURL).pathname); + if (!assetName) throw new Error(`Invalid downloadURL for ${plugin.id}: ${dl.downloadURL}`); + const prev = desired.get(assetName); + if (prev && prev.sha256 !== dl.sha256) { + throw new Error(`Conflicting SHA-256 for asset ${assetName} in ${plugin.id}`); + } + desired.set(assetName, { url: dl.downloadURL, sha256: dl.sha256, maxBytes: MAX_ARCHIVE_BYTES }); + } + } + for (const patch of deltasByPlugin.get(plugin.id) || []) { + if (!selectedVersionNames.has(patch.toVersion)) continue; + const assetName = path.basename(new URL(patch.downloadURL).pathname); + if (!assetName) continue; + desired.set(assetName, { url: patch.downloadURL, sha256: patch.sha256, maxBytes: MAX_ARCHIVE_BYTES }); + } + + const tag = `${PLUGIN_TAG_PREFIX}${plugin.id}`; + await syncReleaseAssets(client, opts.repo, { + tag, + title: `CNB mirror for ${plugin.id}`, + body: `CNB mirror assets for ${plugin.name} (${plugin.id}), automatically synced from GitHub Releases (latest ${opts.keepVersions} versions).`, + targetCommitish: headSha, + desiredAssets: desired, + scratchDir, + }); + } + + if (!opts.plugin) { + const iconAssets = new Map(); + for (const plugin of index.plugins || []) { + if (plugin.icon) { + iconAssets.set(`${plugin.id}.svg`, { url: plugin.icon, sha256: "", maxBytes: MAX_ICON_BYTES }); + } + } + await syncReleaseAssets(client, opts.repo, { + tag: ICONS_TAG, + title: "CNB mirror for plugin icons", + body: "CNB mirror of SVG icons referenced by lithe-plugin-index.json.", + targetCommitish: headSha, + desiredAssets: iconAssets, + scratchDir, + }); + + const activeTags = new Set((index.plugins || []).map((p) => `${PLUGIN_TAG_PREFIX}${p.id}`)); + activeTags.add(ICONS_TAG); + for (const rel of await client.listAllReleases(opts.repo)) { + const tag = rel.tag_name || ""; + if (tag.startsWith(PLUGIN_TAG_PREFIX) && !activeTags.has(tag)) { + console.log(`Deleting delisted plugin mirror release ${tag}`); + await client.deleteRelease(opts.repo, rel.id); + } + } + } + } finally { + await rm(scratchDir, { recursive: true, force: true }); + } + console.log(`CNB mirror sync complete (${plugins.length} plugin(s)).`); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + run().catch((err) => { + const token = process.env.CNB_TOKEN || ""; + console.error(redactSecret(err?.stack || String(err), token)); + process.exit(1); + }); +} diff --git a/scripts/mirror-cnb.test.mjs b/scripts/mirror-cnb.test.mjs new file mode 100644 index 0000000..24f5133 --- /dev/null +++ b/scripts/mirror-cnb.test.mjs @@ -0,0 +1,307 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import http from "node:http"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { run, selectVersionsToMirror } from "./mirror-cnb.mjs"; + +const sha256 = (text) => createHash("sha256").update(text).digest("hex"); + +function startMockServers(githubFiles) { + const releases = new Map(); + let nextId = 1; + const events = []; + + const ghServer = http.createServer((req, res) => { + events.push(`GH GET ${req.url}`); + const body = githubFiles.get(req.url); + if (body === undefined) { + res.writeHead(404); + res.end("not found"); + return; + } + res.writeHead(200); + res.end(body); + }); + + const cnbServer = http.createServer(async (req, res) => { + const url = new URL(req.url, "http://127.0.0.1"); + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + const rawBody = Buffer.concat(chunks); + + if (url.pathname.startsWith("/download/")) { + const [, , tag, name] = url.pathname.split("/"); + const rel = releases.get(tag); + const asset = rel?.assets.find((a) => a.name === name); + if (!asset) { + res.writeHead(404); + res.end("missing"); + return; + } + res.writeHead(200); + res.end(asset.content); + return; + } + + if (url.pathname.startsWith("/upload/")) { + const [, , tag, name] = url.pathname.split("/"); + const rel = releases.get(tag); + events.push(`CNB PUT ${tag}/${name}`); + const existing = rel.assets.find((a) => a.name === name); + const content = rawBody.toString("utf8"); + if (existing) { + existing.content = content; + } else { + rel.assets.push({ + id: `a-${rel.assets.length + 1}`, + name, + content, + browser_download_url: `http://127.0.0.1:${cnbServer.address().port}/download/${tag}/${name}`, + }); + } + res.writeHead(200); + res.end("ok"); + return; + } + + if (req.headers.authorization !== "Bearer cnb-secret") { + res.writeHead(401); + res.end("unauthorized"); + return; + } + + const prefix = "/lithe-idea/Lithe-store/-/releases"; + if (url.pathname === prefix && req.method === "GET") { + const page = Number(url.searchParams.get("page") || "1"); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(page === 1 ? [...releases.values()] : [])); + return; + } + if (url.pathname === prefix && req.method === "POST") { + const body = JSON.parse(rawBody.toString("utf8")); + const rel = { id: `rel-${nextId++}`, ...body, assets: [] }; + releases.set(body.tag_name, rel); + events.push(`CNB POST release ${body.tag_name}`); + res.writeHead(201, { "Content-Type": "application/json" }); + res.end(JSON.stringify(rel)); + return; + } + if (url.pathname.startsWith(`${prefix}/tags/`) && req.method === "GET") { + const tag = decodeURIComponent(url.pathname.slice(`${prefix}/tags/`.length)); + const rel = releases.get(tag); + if (!rel) { + res.writeHead(404); + res.end("not found"); + return; + } + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(rel)); + return; + } + const matchDelRel = new RegExp(`^${prefix}/([^/]+)$`).exec(url.pathname); + if (matchDelRel && req.method === "DELETE") { + const id = decodeURIComponent(matchDelRel[1]); + for (const [tag, rel] of releases) { + if (rel.id === id) { + releases.delete(tag); + events.push(`CNB DELETE release ${tag}`); + break; + } + } + res.writeHead(200); + res.end("{}"); + return; + } + const matchUpload = new RegExp(`^${prefix}/([^/]+)/asset-upload-url$`).exec(url.pathname); + if (matchUpload && req.method === "POST") { + const id = decodeURIComponent(matchUpload[1]); + const rel = [...releases.values()].find((r) => r.id === id); + const body = JSON.parse(rawBody.toString("utf8")); + const base = `http://127.0.0.1:${cnbServer.address().port}`; + res.writeHead(201, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ + upload_url: `${base}/upload/${rel.tag_name}/${body.asset_name}`, + verify_url: `${base}${prefix}/${id}/asset-upload-confirmation/tok/${body.asset_name}`, + })); + return; + } + const matchConfirm = new RegExp(`^${prefix}/([^/]+)/asset-upload-confirmation/tok/(.+)$`).exec(url.pathname); + if (matchConfirm && req.method === "POST") { + res.writeHead(200); + res.end("{}"); + return; + } + const matchDelAsset = new RegExp(`^${prefix}/([^/]+)/assets/([^/]+)$`).exec(url.pathname); + if (matchDelAsset && req.method === "DELETE") { + const id = decodeURIComponent(matchDelAsset[1]); + const aid = decodeURIComponent(matchDelAsset[2]); + const rel = [...releases.values()].find((r) => r.id === id); + rel.assets = rel.assets.filter((a) => a.id !== aid); + events.push(`CNB DELETE asset ${aid}`); + res.writeHead(200); + res.end("{}"); + return; + } + res.writeHead(404); + res.end("not found"); + }); + + return Promise.all([ + new Promise((resolve) => ghServer.listen(0, "127.0.0.1", () => resolve(`http://127.0.0.1:${ghServer.address().port}`))), + new Promise((resolve) => cnbServer.listen(0, "127.0.0.1", () => resolve(`http://127.0.0.1:${cnbServer.address().port}`))), + ]).then(([ghBase, cnbBase]) => ({ + ghBase, + cnbBase, + releases, + events, + close: () => Promise.all([ + new Promise((r) => ghServer.close(r)), + new Promise((r) => cnbServer.close(r)), + ]), + })); +} + +test("selectVersionsToMirror keeps newest N plus distinct pluginAPIVersion fallback", () => { + const picked = selectVersionsToMirror([ + { version: "1.0.0", pluginAPIVersion: 0 }, + { version: "2.1.0", pluginAPIVersion: 1 }, + { version: "2.0.0", pluginAPIVersion: 1 }, + ], 2); + assert.deepEqual(picked.map((v) => v.version), ["2.1.0", "2.0.0", "1.0.0"]); +}); + +test("mirror-cnb syncs latest versions, skips unchanged assets on rerun, prunes old versions and delisted plugins", { timeout: 30000 }, async () => { + const files = new Map([ + ["/v1.0.0/demo-1.0.0-darwin.zip", "zip-1.0.0"], + ["/v1.1.0/demo-1.1.0-darwin.zip", "zip-1.1.0"], + ["/v1.2.0/demo-1.2.0-darwin.zip", "zip-1.2.0"], + ["/v1.2.0/demo-1.2.0-darwin.from-1.1.0.zip.zst", "delta-1.1-to-1.2"], + ["/icons/demo.svg", ""], + ]); + const mock = await startMockServers(files); + const work = await mkdtemp(path.join(os.tmpdir(), "lithe-store-mirror-test-")); + const prevCwd = process.cwd(); + const prevEnv = { ...process.env }; + try { + process.chdir(work); + process.env.CNB_TOKEN = "cnb-secret"; + process.env.CNB_API_BASE = mock.cnbBase; + process.env.CNB_WEB_BASE = mock.cnbBase; + + const index = { + schemaVersion: 0, + plugins: [{ + id: "dev.lithe.test.demo", + name: "Demo", + icon: `${mock.ghBase}/icons/demo.svg`, + versions: [ + { + version: "1.0.0", + pluginAPIVersion: 1, + downloads: [{ platforms: ["darwin-arm64"], downloadURL: `${mock.ghBase}/v1.0.0/demo-1.0.0-darwin.zip`, sha256: sha256("zip-1.0.0") }], + }, + { + version: "1.1.0", + pluginAPIVersion: 1, + downloads: [{ platforms: ["darwin-arm64"], downloadURL: `${mock.ghBase}/v1.1.0/demo-1.1.0-darwin.zip`, sha256: sha256("zip-1.1.0") }], + }, + { + version: "1.2.0", + pluginAPIVersion: 1, + downloads: [{ platforms: ["darwin-arm64"], downloadURL: `${mock.ghBase}/v1.2.0/demo-1.2.0-darwin.zip`, sha256: sha256("zip-1.2.0") }], + }, + ], + }], + }; + const deltas = { + schemaVersion: 0, + patches: [ + { + pluginID: "dev.lithe.test.demo", + platform: "darwin-arm64", + fromVersion: "1.1.0", + toVersion: "1.2.0", + downloadURL: `${mock.ghBase}/v1.2.0/demo-1.2.0-darwin.from-1.1.0.zip.zst`, + sha256: sha256("delta-1.1-to-1.2"), + }, + { + pluginID: "dev.lithe.test.demo", + platform: "darwin-arm64", + fromVersion: "0.9.0", + toVersion: "1.0.0", + downloadURL: `${mock.ghBase}/v1.0.0/demo-1.0.0-darwin.from-0.9.0.zip.zst`, + sha256: sha256("unused"), + }, + ], + }; + await writeFile(path.join(work, "lithe-plugin-index.json"), JSON.stringify(index)); + await writeFile(path.join(work, "lithe-plugin-deltas.json"), JSON.stringify(deltas)); + + // Seed a delisted plugin release to verify cleanup. + mock.releases.set("plugin-dev.lithe.test.removed", { id: "rel-old", tag_name: "plugin-dev.lithe.test.removed", assets: [] }); + + await run(["--keep-versions", "2", "--skip-git-push"]); + + const demoRel = mock.releases.get("plugin-dev.lithe.test.demo"); + assert.ok(demoRel); + assert.deepEqual( + demoRel.assets.map((a) => a.name).sort(), + [".mirror-checksums.json", "demo-1.1.0-darwin.zip", "demo-1.2.0-darwin.from-1.1.0.zip.zst", "demo-1.2.0-darwin.zip"], + ); + assert.equal(mock.releases.has("plugin-dev.lithe.test.removed"), false); + assert.deepEqual( + mock.releases.get("plugin-icons").assets.map((a) => a.name).sort(), + [".mirror-checksums.json", "dev.lithe.test.demo.svg"], + ); + + // Rerun with no changes: nothing should be re-downloaded from GitHub! + const eventCount = mock.events.length; + await run(["--keep-versions", "2", "--skip-git-push"]); + const rerunEvents = mock.events.slice(eventCount); + assert.equal(rerunEvents.some((e) => e.startsWith("GH GET")), false); + assert.equal(rerunEvents.some((e) => e.startsWith("CNB PUT")), false); + } finally { + process.chdir(prevCwd); + process.env = prevEnv; + await rm(work, { recursive: true, force: true }); + await mock.close(); + } +}); + +test("mirror-cnb refuses to upload on SHA-256 mismatch", { timeout: 30000 }, async () => { + const files = new Map([["/v1.0.0/bad.zip", "tampered"]]); + const mock = await startMockServers(files); + const work = await mkdtemp(path.join(os.tmpdir(), "lithe-store-badsha-")); + const prevCwd = process.cwd(); + const prevEnv = { ...process.env }; + try { + process.chdir(work); + process.env.CNB_TOKEN = "cnb-secret"; + process.env.CNB_API_BASE = mock.cnbBase; + process.env.CNB_WEB_BASE = mock.cnbBase; + await writeFile(path.join(work, "lithe-plugin-index.json"), JSON.stringify({ + schemaVersion: 0, + plugins: [{ + id: "dev.lithe.test.bad", + name: "Bad", + versions: [{ + version: "1.0.0", + pluginAPIVersion: 1, + downloads: [{ platforms: ["darwin-arm64"], downloadURL: `${mock.ghBase}/v1.0.0/bad.zip`, sha256: "0".repeat(64) }], + }], + }], + })); + await writeFile(path.join(work, "lithe-plugin-deltas.json"), JSON.stringify({ schemaVersion: 0, patches: [] })); + + await assert.rejects(() => run(["--skip-git-push"]), /SHA-256 mismatch/); + assert.equal(mock.events.some((e) => e.startsWith("CNB PUT")), false); + } finally { + process.chdir(prevCwd); + process.env = prevEnv; + await rm(work, { recursive: true, force: true }); + await mock.close(); + } +});