681 lines
25 KiB
JavaScript
681 lines
25 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Reims-Go Plugin Market validator & index builder.
|
|
*
|
|
* Supports both:
|
|
* - Continuous GitHub Release tracking ("soft-link" mode): registry entry only
|
|
* declares id, repo, kind, trust, channel (and optional tag_prefix / asset).
|
|
* - Pinned mode (backward compatible): registry entry pins version, sha256,
|
|
* and download_url or (repo + tag + asset).
|
|
*
|
|
* Usage:
|
|
* node scripts/build-index.mjs [--check] [--out-dir dist] [--reims-bin ./reims-go] [--report pr-report.md]
|
|
*
|
|
* Zero third-party npm dependencies (Node 20+).
|
|
*/
|
|
import crypto from 'node:crypto'
|
|
import { spawnSync } from 'node:child_process'
|
|
import fs from 'node:fs'
|
|
import os from 'node:os'
|
|
import path from 'node:path'
|
|
import zlib from 'node:zlib'
|
|
|
|
const RE_ID = /^[a-z0-9][a-z0-9_-]*(\.[a-z0-9][a-z0-9_-]*)+$/
|
|
const RE_SHA256 = /^[0-9a-f]{64}$/
|
|
const ALLOWED_CHANNELS = new Set(['stable', 'alpha'])
|
|
const ALLOWED_TRUST = new Set(['official', 'verified', 'community'])
|
|
const ALLOWED_KINDS = new Set(['theme', 'locale', 'driver', 'tool', 'template', 'runtime'])
|
|
const ALLOWED_ICON_TONES = new Set(['indigo', 'purple', 'sky', 'rose', 'emerald', 'amber', 'teal', 'slate'])
|
|
const MAX_ZIP_BYTES = 256 * 1024 * 1024 // 256 MiB
|
|
const MAX_ICON_SVG_BYTES = 32 * 1024 // 32 KiB
|
|
|
|
function parseArgs(argv) {
|
|
const opts = {
|
|
checkOnly: false,
|
|
outDir: 'dist',
|
|
reimsBin: '',
|
|
reportPath: '',
|
|
}
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const a = argv[i]
|
|
if (a === '--check') opts.checkOnly = true
|
|
else if (a === '--out-dir' && i + 1 < argv.length) opts.outDir = argv[++i]
|
|
else if (a === '--reims-bin' && i + 1 < argv.length) opts.reimsBin = argv[++i]
|
|
else if (a === '--report' && i + 1 < argv.length) opts.reportPath = argv[++i]
|
|
else throw new Error(`Unknown argument: ${a}`)
|
|
}
|
|
return opts
|
|
}
|
|
|
|
function readJSON(filePath) {
|
|
return JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
|
}
|
|
|
|
function normalizeLocalized(val) {
|
|
if (!val) return undefined
|
|
if (typeof val === 'string') {
|
|
const s = val.trim()
|
|
return s ? { 'zh-CN': s, 'en-US': s } : undefined
|
|
}
|
|
if (typeof val === 'object') {
|
|
const out = {}
|
|
for (const [k, v] of Object.entries(val)) {
|
|
if (k === 'extra' && v && typeof v === 'object') {
|
|
for (const [ek, ev] of Object.entries(v)) {
|
|
if (typeof ev === 'string' && ev.trim()) out[ek] = ev.trim()
|
|
}
|
|
continue
|
|
}
|
|
if (typeof v === 'string' && v.trim()) out[k] = v.trim()
|
|
}
|
|
return Object.keys(out).length > 0 ? out : undefined
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
function extractSafeSvg(rawText) {
|
|
const text = String(rawText || '').trim()
|
|
if (!text) return ''
|
|
if (Buffer.byteLength(text, 'utf8') > MAX_ICON_SVG_BYTES) return ''
|
|
if (/<script\b|\bon[a-z]+\s*=|javascript:|<foreignobject\b/i.test(text)) return ''
|
|
const lower = text.toLowerCase()
|
|
const start = lower.indexOf('<svg')
|
|
const end = lower.lastIndexOf('</svg>')
|
|
if (start < 0 || end < start) return ''
|
|
return text.slice(start, end + '</svg>'.length).trim()
|
|
}
|
|
|
|
function extractPluginIcon(buf, manifest) {
|
|
if (!manifest?.icon || typeof manifest.icon !== 'object') return undefined
|
|
const out = {}
|
|
const tone = String(manifest.icon.tone || '').trim().toLowerCase()
|
|
if (ALLOWED_ICON_TONES.has(tone)) out.tone = tone
|
|
const svgRef = String(manifest.icon.svg || '').trim()
|
|
if (svgRef && !svgRef.startsWith('<')) {
|
|
const cleanRel = svgRef.replace(/^\.\//, '').replace(/\\/g, '/')
|
|
if (!cleanRel.startsWith('/') && !cleanRel.includes('..') && cleanRel.toLowerCase().endsWith('.svg')) {
|
|
try {
|
|
const raw = readFileFromZipBuffer(buf, cleanRel)
|
|
const safe = extractSafeSvg(raw.toString('utf8'))
|
|
if (safe) out.svg = safe
|
|
} catch {
|
|
// Ignore missing/unreadable icon SVG; doctor gate handles hard errors.
|
|
}
|
|
}
|
|
}
|
|
return Object.keys(out).length > 0 ? out : undefined
|
|
}
|
|
|
|
/**
|
|
* Pure-Node ZIP reader to extract a single entry without external tools.
|
|
*/
|
|
function readFileFromZipBuffer(buf, targetName) {
|
|
let eocdOffset = -1
|
|
const minPos = Math.max(0, buf.length - 65557)
|
|
for (let pos = buf.length - 22; pos >= minPos; pos--) {
|
|
if (buf.readUInt32LE(pos) === 0x06054b50) {
|
|
eocdOffset = pos
|
|
break
|
|
}
|
|
}
|
|
if (eocdOffset < 0) throw new Error('Invalid ZIP archive: EOCD not found')
|
|
|
|
const totalEntries = buf.readUInt16LE(eocdOffset + 10)
|
|
let cdOffset = buf.readUInt32LE(eocdOffset + 16)
|
|
|
|
for (let i = 0; i < totalEntries; i++) {
|
|
if (buf.readUInt32LE(cdOffset) !== 0x02014b50) {
|
|
throw new Error('Invalid ZIP central directory header')
|
|
}
|
|
const method = buf.readUInt16LE(cdOffset + 10)
|
|
const compSize = buf.readUInt32LE(cdOffset + 20)
|
|
const nameLen = buf.readUInt16LE(cdOffset + 28)
|
|
const extraLen = buf.readUInt16LE(cdOffset + 30)
|
|
const commentLen = buf.readUInt16LE(cdOffset + 32)
|
|
const localHeaderOffset = buf.readUInt32LE(cdOffset + 42)
|
|
const name = buf.subarray(cdOffset + 46, cdOffset + 46 + nameLen).toString('utf8')
|
|
|
|
if (name === targetName || name === `./${targetName}`) {
|
|
if (buf.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
|
|
throw new Error('Invalid ZIP local file header')
|
|
}
|
|
const lNameLen = buf.readUInt16LE(localHeaderOffset + 26)
|
|
const lExtraLen = buf.readUInt16LE(localHeaderOffset + 28)
|
|
const dataStart = localHeaderOffset + 30 + lNameLen + lExtraLen
|
|
const compData = buf.subarray(dataStart, dataStart + compSize)
|
|
if (method === 0) return compData
|
|
if (method === 8) return zlib.inflateRawSync(compData)
|
|
throw new Error(`Unsupported ZIP compression method ${method} for ${targetName}`)
|
|
}
|
|
cdOffset += 46 + nameLen + extraLen + commentLen
|
|
}
|
|
throw new Error(`ZIP archive is missing ${targetName}`)
|
|
}
|
|
|
|
function githubHeaders(extra = {}) {
|
|
const headers = { 'User-Agent': 'reims-go-plugins-ci', ...extra }
|
|
if (process.env.GITHUB_TOKEN) {
|
|
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`
|
|
}
|
|
return headers
|
|
}
|
|
|
|
async function fetchGitHubRepoStats(repo) {
|
|
if (!repo) return { stars: 0 }
|
|
try {
|
|
const resp = await fetch(`https://api.github.com/repos/${repo}`, {
|
|
headers: githubHeaders({ Accept: 'application/vnd.github+json' }),
|
|
redirect: 'follow',
|
|
})
|
|
if (!resp.ok) return { stars: 0 }
|
|
const data = await resp.json()
|
|
return { stars: Number.isFinite(data?.stargazers_count) ? data.stargazers_count : 0 }
|
|
} catch {
|
|
return { stars: 0 }
|
|
}
|
|
}
|
|
|
|
async function fetchGitHubReleases(repo) {
|
|
const url = `https://api.github.com/repos/${repo}/releases?per_page=30`
|
|
const resp = await fetch(url, {
|
|
headers: githubHeaders({ Accept: 'application/vnd.github+json' }),
|
|
redirect: 'follow',
|
|
})
|
|
if (!resp.ok) {
|
|
throw new Error(`HTTP ${resp.status} listing GitHub releases for ${repo}`)
|
|
}
|
|
const data = await resp.json()
|
|
if (!Array.isArray(data)) {
|
|
throw new Error(`Unexpected GitHub releases payload for ${repo}`)
|
|
}
|
|
return data
|
|
}
|
|
|
|
function selectReleaseAsset(release, entry) {
|
|
const assets = Array.isArray(release.assets) ? release.assets : []
|
|
const zips = assets.filter((a) => typeof a?.name === 'string' && a.name.toLowerCase().endsWith('.zip'))
|
|
if (zips.length === 0) return null
|
|
if (entry.asset) {
|
|
return zips.find((a) => a.name === entry.asset) || null
|
|
}
|
|
const idPrefix = `${entry.id.toLowerCase()}-`
|
|
const byID = zips.find((a) => a.name.toLowerCase().startsWith(idPrefix))
|
|
if (byID) return byID
|
|
if (zips.length === 1) return zips[0]
|
|
return null
|
|
}
|
|
|
|
function summarizeReleaseBody(body) {
|
|
if (typeof body !== 'string') return undefined
|
|
const lines = body
|
|
.replace(/\r\n/g, '\n')
|
|
.split('\n')
|
|
.map((l) => l.trim())
|
|
.filter((l) => l && !l.startsWith('#') && !l.startsWith('```') && !l.startsWith('|'))
|
|
if (lines.length === 0) return undefined
|
|
const text = lines.slice(0, 3).join(' ').replace(/\s+/g, ' ').trim()
|
|
if (!text) return undefined
|
|
const clipped = text.length > 240 ? `${text.slice(0, 237)}...` : text
|
|
return { 'zh-CN': clipped, 'en-US': clipped }
|
|
}
|
|
|
|
function parseDigestSha256(digest) {
|
|
if (typeof digest !== 'string') return ''
|
|
const s = digest.trim().toLowerCase()
|
|
if (!s.startsWith('sha256:')) return ''
|
|
const hex = s.slice('sha256:'.length)
|
|
return RE_SHA256.test(hex) ? hex : ''
|
|
}
|
|
|
|
function inferVersionFromTag(tagName, tagPrefix) {
|
|
let s = String(tagName || '').trim()
|
|
if (tagPrefix && s.startsWith(tagPrefix)) {
|
|
s = s.slice(tagPrefix.length)
|
|
}
|
|
s = s.replace(/^v/i, '').trim()
|
|
return s
|
|
}
|
|
|
|
async function resolveLatestReleaseCandidates(entry, channel) {
|
|
if (!entry.repo) {
|
|
throw new Error('auto-tracked plugin entry must specify repo (owner/name)')
|
|
}
|
|
const releases = await fetchGitHubReleases(entry.repo)
|
|
const tagPrefix = typeof entry.tag_prefix === 'string' ? entry.tag_prefix : ''
|
|
const candidates = []
|
|
const allReleases = []
|
|
let totalDownloads = 0
|
|
for (const rel of releases) {
|
|
if (!rel || rel.draft) continue
|
|
if (tagPrefix && !String(rel.tag_name || '').startsWith(tagPrefix)) continue
|
|
const asset = selectReleaseAsset(rel, entry)
|
|
if (!asset || !asset.browser_download_url) continue
|
|
if (Number.isFinite(asset.download_count)) totalDownloads += asset.download_count
|
|
const relChannel = rel.prerelease ? 'alpha' : 'stable'
|
|
const digestSha256 = parseDigestSha256(asset.digest)
|
|
const publishedAt = rel.published_at || rel.created_at || new Date().toISOString()
|
|
const cand = {
|
|
tag: rel.tag_name,
|
|
version: inferVersionFromTag(rel.tag_name, tagPrefix),
|
|
channel: relChannel,
|
|
downloadURL: asset.browser_download_url,
|
|
digestSha256,
|
|
sizeBytes: Number.isFinite(asset.size) ? asset.size : 0,
|
|
publishedAt,
|
|
body: rel.body || '',
|
|
}
|
|
allReleases.push(cand)
|
|
if (channel === 'stable' && rel.prerelease) continue
|
|
candidates.push(cand)
|
|
}
|
|
if (candidates.length === 0) {
|
|
// Fall back to all matching releases (e.g. if repo only has prereleases).
|
|
if (allReleases.length > 0) {
|
|
candidates.push(...allReleases)
|
|
} else {
|
|
throw new Error(`no matching ${channel} GitHub Release with a .zip plugin asset found in ${entry.repo}`)
|
|
}
|
|
}
|
|
return { candidates, allReleases, totalDownloads }
|
|
}
|
|
|
|
async function downloadBuffer(url) {
|
|
const headers = { 'User-Agent': 'reims-go-plugins-ci' }
|
|
if (process.env.GITHUB_TOKEN && url.includes('github.com')) {
|
|
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`
|
|
}
|
|
const resp = await fetch(url, { headers, redirect: 'follow' })
|
|
if (!resp.ok) {
|
|
throw new Error(`HTTP ${resp.status} downloading ${url}`)
|
|
}
|
|
const chunks = []
|
|
let total = 0
|
|
for await (const chunk of resp.body) {
|
|
total += chunk.length
|
|
if (total > MAX_ZIP_BYTES) {
|
|
throw new Error(`Archive exceeds ${MAX_ZIP_BYTES} byte limit`)
|
|
}
|
|
chunks.push(chunk)
|
|
}
|
|
return Buffer.concat(chunks)
|
|
}
|
|
|
|
function runDoctor(reimsBin, zipPath) {
|
|
const proc = spawnSync(reimsBin, ['plugin', 'doctor', '--json', zipPath], {
|
|
encoding: 'utf8',
|
|
maxBuffer: 8 * 1024 * 1024,
|
|
})
|
|
if (proc.error) {
|
|
throw new Error(`Failed to execute ${reimsBin}: ${proc.error.message}`)
|
|
}
|
|
const raw = (proc.stdout || '').trim()
|
|
if (!raw) {
|
|
throw new Error(`reims-go plugin doctor produced empty output (exit=${proc.status}): ${proc.stderr}`)
|
|
}
|
|
const report = JSON.parse(raw)
|
|
return { exitCode: proc.status, report }
|
|
}
|
|
|
|
function validateWithdrawn(withdrawnDoc) {
|
|
if (!withdrawnDoc || withdrawnDoc.schema !== 1 || !Array.isArray(withdrawnDoc.withdrawn)) {
|
|
throw new Error('withdrawn.json must have {"schema": 1, "withdrawn": [...]}')
|
|
}
|
|
const ids = new Set()
|
|
const out = []
|
|
for (const w of withdrawnDoc.withdrawn) {
|
|
if (!w || typeof w.id !== 'string' || !RE_ID.test(w.id)) {
|
|
throw new Error(`Invalid withdrawn plugin id: ${JSON.stringify(w?.id)}`)
|
|
}
|
|
if (ids.has(w.id)) throw new Error(`Duplicate withdrawn id: ${w.id}`)
|
|
ids.add(w.id)
|
|
const reason = normalizeLocalized(w.reason)
|
|
if (!reason) throw new Error(`Withdrawn entry ${w.id} is missing reason`)
|
|
const item = { id: w.id, reason }
|
|
if (w.instead_id) {
|
|
if (!RE_ID.test(w.instead_id)) throw new Error(`Invalid instead_id for ${w.id}: ${w.instead_id}`)
|
|
item.instead_id = w.instead_id
|
|
}
|
|
if (w.instead_name) item.instead_name = String(w.instead_name)
|
|
if (w.withdrawn_at) item.withdrawn_at = String(w.withdrawn_at)
|
|
out.push(item)
|
|
}
|
|
return { ids, list: out }
|
|
}
|
|
|
|
async function verifyAndBuildCandidate({ entry, channel, kind, trust, candidate, allReleases, pinnedVersion, pinnedSHA256, stats, opts, tmpRoot }) {
|
|
const parsedURL = new URL(candidate.downloadURL)
|
|
if (parsedURL.protocol !== 'https:') {
|
|
throw new Error(`download_url must use https:// (got ${candidate.downloadURL})`)
|
|
}
|
|
|
|
const buf = await downloadBuffer(candidate.downloadURL)
|
|
const gotSum = crypto.createHash('sha256').update(buf).digest('hex')
|
|
if (pinnedSHA256 && gotSum !== pinnedSHA256) {
|
|
throw new Error(`SHA-256 mismatch: registry=${pinnedSHA256}, actual=${gotSum}`)
|
|
}
|
|
if (candidate.digestSha256 && gotSum !== candidate.digestSha256) {
|
|
throw new Error(`SHA-256 mismatch: github_digest=${candidate.digestSha256}, actual=${gotSum}`)
|
|
}
|
|
|
|
const manifestRaw = readFileFromZipBuffer(buf, 'plugin.json')
|
|
const manifest = JSON.parse(manifestRaw.toString('utf8'))
|
|
if (manifest.id !== entry.id) {
|
|
throw new Error(`anti-swap id mismatch: registry=${entry.id}, plugin.json=${manifest.id}`)
|
|
}
|
|
const version = String(manifest.version || '').trim()
|
|
if (!version) {
|
|
throw new Error('plugin.json is missing version')
|
|
}
|
|
if (pinnedVersion && version !== pinnedVersion) {
|
|
throw new Error(`anti-swap version mismatch: registry=${pinnedVersion}, plugin.json=${version}`)
|
|
}
|
|
|
|
let scanReport = null
|
|
if (opts.reimsBin) {
|
|
const zipPath = path.join(tmpRoot, `${entry.id}-${version}-${gotSum.slice(0, 8)}.zip`)
|
|
fs.writeFileSync(zipPath, buf)
|
|
const { report } = runDoctor(opts.reimsBin, zipPath)
|
|
scanReport = report
|
|
if (report.hard_blocked) {
|
|
const reasons = (report.hard_findings || [])
|
|
.map((f) => `[${f.check}] ${f.target ? `${f.target}: ` : ''}${f.message}`)
|
|
.join('; ')
|
|
throw new Error(`static security gate blocked: ${reasons}`)
|
|
}
|
|
}
|
|
|
|
const tier = scanReport?.tier || (manifest.entry?.sidecar ? 'L3' : manifest.entry?.panelDir ? 'L4' : 'L1')
|
|
const effectiveTrust = trust === 'official' || trust === 'verified' ? trust : 'community'
|
|
const icon = extractPluginIcon(buf, manifest)
|
|
const primaryChannel = candidate.channel || channel
|
|
const primaryChangelog = normalizeLocalized(entry.changelog) || summarizeReleaseBody(candidate.body)
|
|
const primaryPublished = entry.updated_at || candidate.publishedAt || new Date().toISOString()
|
|
|
|
const releaseList = []
|
|
const seenVersions = new Set()
|
|
const addRelease = (r) => {
|
|
if (!r.version || !RE_SHA256.test(r.sha256) || seenVersions.has(r.version)) return
|
|
seenVersions.add(r.version)
|
|
const clean = {
|
|
version: r.version,
|
|
channel: r.channel || 'stable',
|
|
download_url: r.download_url,
|
|
sha256: r.sha256,
|
|
size_bytes: r.size_bytes > 0 ? r.size_bytes : undefined,
|
|
published_at: r.published_at || undefined,
|
|
changelog: r.changelog || undefined,
|
|
}
|
|
for (const k of Object.keys(clean)) {
|
|
if (clean[k] === undefined) delete clean[k]
|
|
}
|
|
releaseList.push(clean)
|
|
}
|
|
addRelease({
|
|
version,
|
|
channel: primaryChannel,
|
|
download_url: candidate.downloadURL,
|
|
sha256: gotSum,
|
|
size_bytes: buf.length,
|
|
published_at: primaryPublished,
|
|
changelog: primaryChangelog,
|
|
})
|
|
if (Array.isArray(allReleases)) {
|
|
for (const rel of allReleases) {
|
|
if (releaseList.length >= 10) break
|
|
if (!rel.version || !rel.digestSha256) continue
|
|
addRelease({
|
|
version: rel.version,
|
|
channel: rel.channel,
|
|
download_url: rel.downloadURL,
|
|
sha256: rel.digestSha256,
|
|
size_bytes: rel.sizeBytes,
|
|
published_at: rel.publishedAt,
|
|
changelog: summarizeReleaseBody(rel.body),
|
|
})
|
|
}
|
|
}
|
|
|
|
const marketItem = {
|
|
id: manifest.id,
|
|
version,
|
|
name: normalizeLocalized(manifest.name) || { 'en-US': manifest.id },
|
|
description: normalizeLocalized(manifest.description) || { 'en-US': '' },
|
|
publisher: manifest.publisher || (entry.repo ? entry.repo.split('/')[0] : 'community'),
|
|
license: manifest.license || '',
|
|
channel: primaryChannel,
|
|
trust: effectiveTrust,
|
|
kind,
|
|
tier,
|
|
icon,
|
|
homepage: manifest.homepage || (entry.repo ? `https://github.com/${entry.repo}` : undefined),
|
|
readme_url: entry.readme_url || (entry.repo ? `https://github.com/${entry.repo}#readme` : undefined),
|
|
engines: manifest.engines || {},
|
|
platforms: Array.isArray(manifest.platforms) ? manifest.platforms : undefined,
|
|
permissions: Array.isArray(manifest.permissions) ? manifest.permissions : undefined,
|
|
download_url: candidate.downloadURL,
|
|
sha256: gotSum,
|
|
size_bytes: buf.length,
|
|
changelog: primaryChangelog,
|
|
releases: releaseList.length > 0 ? releaseList : undefined,
|
|
tags: Array.isArray(entry.tags) ? entry.tags : undefined,
|
|
stars: stats?.stars > 0 ? stats.stars : undefined,
|
|
downloads: stats?.downloads > 0 ? stats.downloads : undefined,
|
|
updated_at: primaryPublished,
|
|
}
|
|
for (const k of Object.keys(marketItem)) {
|
|
if (marketItem[k] === undefined) delete marketItem[k]
|
|
}
|
|
return {
|
|
marketItem,
|
|
reportRow: {
|
|
status: 'PASS',
|
|
id: marketItem.id,
|
|
version: marketItem.version,
|
|
tier,
|
|
trust: effectiveTrust,
|
|
sizeBytes: buf.length,
|
|
sha256: gotSum,
|
|
capabilities: scanReport?.capabilities || [],
|
|
executables: scanReport?.executables || [],
|
|
pending: scanReport?.pending_findings || [],
|
|
},
|
|
}
|
|
}
|
|
|
|
async function main() {
|
|
const opts = parseArgs(process.argv.slice(2))
|
|
const rootDir = process.cwd()
|
|
const registryDoc = readJSON(path.join(rootDir, 'registry.json'))
|
|
const withdrawnDoc = readJSON(path.join(rootDir, 'withdrawn.json'))
|
|
|
|
if (!registryDoc || registryDoc.schema !== 1 || !Array.isArray(registryDoc.plugins)) {
|
|
throw new Error('registry.json must have {"schema": 1, "plugins": [...]}')
|
|
}
|
|
const { ids: withdrawnIDs, list: withdrawnList } = validateWithdrawn(withdrawnDoc)
|
|
|
|
const seenKey = new Set()
|
|
const marketPlugins = []
|
|
const reportRows = []
|
|
const errors = []
|
|
|
|
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'reims-plugins-build-'))
|
|
try {
|
|
for (const entry of registryDoc.plugins) {
|
|
const label = `${entry?.id || '<missing-id>'}@${entry?.version || 'latest'}`
|
|
try {
|
|
if (!entry || typeof entry.id !== 'string' || !RE_ID.test(entry.id)) {
|
|
throw new Error(`invalid plugin id ${JSON.stringify(entry?.id)}`)
|
|
}
|
|
if (withdrawnIDs.has(entry.id)) {
|
|
throw new Error(`plugin ${entry.id} is listed in withdrawn.json and must be removed from registry.json`)
|
|
}
|
|
|
|
const channel = (entry.channel || 'stable').toLowerCase()
|
|
if (!ALLOWED_CHANNELS.has(channel)) throw new Error(`invalid channel ${JSON.stringify(channel)}`)
|
|
const key = `${entry.id}:${channel}`
|
|
if (seenKey.has(key)) throw new Error(`duplicate registry entry for ${key}`)
|
|
seenKey.add(key)
|
|
|
|
const kind = (entry.kind || '').toLowerCase()
|
|
if (!ALLOWED_KINDS.has(kind)) throw new Error(`invalid kind ${JSON.stringify(kind)}`)
|
|
|
|
const trust = (entry.trust || 'community').toLowerCase()
|
|
if (!ALLOWED_TRUST.has(trust)) throw new Error(`invalid trust ${JSON.stringify(trust)}`)
|
|
|
|
const isPinned = Boolean(entry.version || entry.sha256 || entry.download_url)
|
|
const repoStats = entry.repo ? await fetchGitHubRepoStats(entry.repo) : { stars: 0 }
|
|
if (isPinned) {
|
|
if (typeof entry.version !== 'string' || !entry.version.trim()) {
|
|
throw new Error('pinned entry must specify version')
|
|
}
|
|
const sha256 = String(entry.sha256 || '').toLowerCase().trim()
|
|
if (!RE_SHA256.test(sha256)) throw new Error('sha256 must be a 64-character lowercase hex string')
|
|
let downloadURL = String(entry.download_url || '').trim()
|
|
if (!downloadURL) {
|
|
if (!entry.repo || !entry.asset) {
|
|
throw new Error('either download_url or (repo + asset) must be specified')
|
|
}
|
|
const tag = entry.tag || `v${entry.version}`
|
|
downloadURL = `https://github.com/${entry.repo}/releases/download/${tag}/${entry.asset}`
|
|
}
|
|
const built = await verifyAndBuildCandidate({
|
|
entry,
|
|
channel,
|
|
kind,
|
|
trust,
|
|
candidate: { downloadURL, publishedAt: entry.updated_at || new Date().toISOString(), body: '' },
|
|
pinnedVersion: entry.version.trim(),
|
|
pinnedSHA256: sha256,
|
|
stats: { stars: repoStats.stars, downloads: 0 },
|
|
opts,
|
|
tmpRoot,
|
|
})
|
|
marketPlugins.push(built.marketItem)
|
|
reportRows.push(built.reportRow)
|
|
} else {
|
|
const { candidates, allReleases, totalDownloads } = await resolveLatestReleaseCandidates(entry, channel)
|
|
let built = null
|
|
let lastErr = null
|
|
// In PR --check mode, only accept the latest release; in scheduled publish mode,
|
|
// fall back to an earlier passing release if the newest one fails the gate.
|
|
const maxAttempts = opts.checkOnly ? 1 : Math.min(candidates.length, 5)
|
|
for (let i = 0; i < maxAttempts; i++) {
|
|
try {
|
|
built = await verifyAndBuildCandidate({
|
|
entry,
|
|
channel,
|
|
kind,
|
|
trust,
|
|
candidate: candidates[i],
|
|
allReleases,
|
|
pinnedVersion: '',
|
|
pinnedSHA256: '',
|
|
stats: { stars: repoStats.stars, downloads: totalDownloads },
|
|
opts,
|
|
tmpRoot,
|
|
})
|
|
if (i > 0) {
|
|
console.warn(`WARN ${entry.id}: latest release ${candidates[0].tag} failed (${lastErr?.message}); fell back to ${candidates[i].tag}`)
|
|
}
|
|
break
|
|
} catch (err) {
|
|
lastErr = err
|
|
}
|
|
}
|
|
if (!built) {
|
|
throw lastErr || new Error('no valid release passed verification')
|
|
}
|
|
marketPlugins.push(built.marketItem)
|
|
reportRows.push(built.reportRow)
|
|
}
|
|
} catch (err) {
|
|
errors.push(`${label}: ${err.message}`)
|
|
reportRows.push({
|
|
status: 'FAIL',
|
|
id: entry?.id || 'unknown',
|
|
version: entry?.version || 'latest',
|
|
error: err.message,
|
|
})
|
|
}
|
|
}
|
|
} finally {
|
|
fs.rmSync(tmpRoot, { recursive: true, force: true })
|
|
}
|
|
|
|
const mdLines = [
|
|
'## Reims-Go Plugin Market Gate Report',
|
|
'',
|
|
`- **Entries checked**: ${registryDoc.plugins.length}`,
|
|
`- **Withdrawn entries**: ${withdrawnList.length}`,
|
|
`- **Result**: ${errors.length === 0 ? 'PASS' : `BLOCKED (${errors.length} error(s))`}`,
|
|
'',
|
|
]
|
|
if (reportRows.length === 0) {
|
|
mdLines.push('_No active plugins in `registry.json` yet — schema and `withdrawn.json` validated cleanly._')
|
|
} else {
|
|
for (const r of reportRows) {
|
|
if (r.status === 'FAIL') {
|
|
mdLines.push(`### ❌ \`${r.id}@${r.version}\``)
|
|
mdLines.push(`- **Error**: ${r.error}`)
|
|
mdLines.push('')
|
|
continue
|
|
}
|
|
mdLines.push(`### ✅ \`${r.id}@${r.version}\` (\`${r.tier}\` · \`${r.trust}\`)`)
|
|
mdLines.push(`- Archive: \`${r.sizeBytes}\` bytes · SHA-256: \`${r.sha256}\``)
|
|
if (r.capabilities.length > 0) {
|
|
mdLines.push('- **Capabilities**:')
|
|
for (const c of r.capabilities) {
|
|
mdLines.push(` - \`[${String(c.level || '').toUpperCase()}]\` \`${c.id}\`: ${c.summary?.['zh-CN'] || c.summary?.['en-US'] || ''}`)
|
|
}
|
|
}
|
|
if (r.executables.length > 0) {
|
|
mdLines.push('- **Executables (SHA-256)**:')
|
|
for (const ex of r.executables) {
|
|
mdLines.push(` - \`${ex.path}\` — \`${ex.sha256}\``)
|
|
}
|
|
}
|
|
mdLines.push('')
|
|
}
|
|
}
|
|
|
|
const reportMarkdown = mdLines.join('\n') + '\n'
|
|
if (opts.reportPath) {
|
|
fs.mkdirSync(path.dirname(path.resolve(opts.reportPath)), { recursive: true })
|
|
fs.writeFileSync(opts.reportPath, reportMarkdown, 'utf8')
|
|
}
|
|
|
|
if (errors.length > 0) {
|
|
console.error(reportMarkdown)
|
|
for (const e of errors) console.error('ERROR:', e)
|
|
process.exit(1)
|
|
}
|
|
|
|
if (!opts.checkOnly) {
|
|
const now = new Date().toISOString()
|
|
const indexObj = {
|
|
schema: 1,
|
|
updated_at: now,
|
|
plugins: marketPlugins,
|
|
withdrawn: withdrawnList,
|
|
}
|
|
fs.mkdirSync(opts.outDir, { recursive: true })
|
|
fs.writeFileSync(path.join(opts.outDir, 'index.json'), JSON.stringify(indexObj, null, 2) + '\n', 'utf8')
|
|
const changesObj = {
|
|
schema: 1,
|
|
updated_at: now,
|
|
plugin_count: marketPlugins.length,
|
|
withdrawn_count: withdrawnList.length,
|
|
entries: marketPlugins.map((p) => ({ id: p.id, version: p.version, channel: p.channel, sha256: p.sha256 })),
|
|
}
|
|
fs.writeFileSync(path.join(opts.outDir, 'changes.json'), JSON.stringify(changesObj, null, 2) + '\n', 'utf8')
|
|
console.log(`Built ${path.join(opts.outDir, 'index.json')} (${marketPlugins.length} plugin(s), ${withdrawnList.length} withdrawn)`)
|
|
} else {
|
|
console.log(`Validated registry cleanly (${marketPlugins.length} plugin(s), ${withdrawnList.length} withdrawn)`)
|
|
}
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error('Fatal:', err)
|
|
process.exit(1)
|
|
})
|