Files
orca/config/scripts/release/publication/scan-release-artifacts-antivirus.mjs
Neil 6bb2e13c35 refactor(tooling): organize remaining scripts by domain owners (#38407)
* refactor(tooling): group remaining scripts by concrete domain owners

* fix(tooling): preserve relocated launcher resource roots
2026-11-05 00:29:16 -08:00

151 lines
5.2 KiB
JavaScript

#!/usr/bin/env node
// Report release artifact antivirus verdicts (docs/reference/antivirus-prerelease-clearance.md). Default sends SHA-256 only.
// Explicit --upload sends artifact to partner vendors for manual clearance; never automate uploads.
import { createHash } from 'node:crypto'
import { createReadStream, openAsBlob } from 'node:fs'
import { stat } from 'node:fs/promises'
import { basename } from 'node:path'
import { pathToFileURL } from 'node:url'
const VIRUSTOTAL_FILES_ENDPOINT = 'https://www.virustotal.com/api/v3/files'
export async function hashFile(filePath) {
const hash = createHash('sha256')
for await (const chunk of createReadStream(filePath)) {
hash.update(chunk)
}
return hash.digest('hex')
}
// Only malicious/suspicious count as verdicts; undetected/unsupported/timeout/failure are silence, not a clean bill of health.
export function summarizeEngineVerdicts(analysisResults) {
const flagged = []
let scanned = 0
for (const [engine, result] of Object.entries(analysisResults ?? {})) {
scanned += 1
if (result?.category === 'malicious' || result?.category === 'suspicious') {
flagged.push({
engine,
category: result.category,
detection: result.result ?? '<unnamed>'
})
}
}
flagged.sort((left, right) => left.engine.localeCompare(right.engine))
return { scanned, flagged }
}
export function formatArtifactReport({ name, sha256, known, scanned, flagged }) {
if (!known) {
return `${name}\n sha256 ${sha256}\n no report yet — this build has never been scanned`
}
if (flagged.length === 0) {
return `${name}\n sha256 ${sha256}\n clean across ${scanned} engines`
}
const lines = flagged.map(
(entry) => ` ${entry.category.padEnd(10)} ${entry.engine}: ${entry.detection}`
)
return [
name,
` sha256 ${sha256}`,
` ${flagged.length} of ${scanned} engines flag this build:`,
...lines
].join('\n')
}
/** True when any artifact carries a verdict a user could hit. */
export function hasAnyDetection(reports) {
return reports.some((report) => report.flagged.length > 0)
}
async function fetchExistingReport(sha256, apiKey) {
const response = await fetch(`${VIRUSTOTAL_FILES_ENDPOINT}/${sha256}`, {
headers: { 'x-apikey': apiKey }
})
if (response.status === 404) {
return null
}
if (!response.ok) {
throw new Error(`VirusTotal lookup failed for ${sha256}: ${response.status}`)
}
const body = await response.json()
return body?.data?.attributes?.last_analysis_results ?? {}
}
// Use separate upload URL above 32MB; Orca installers exceed direct endpoint limit.
async function uploadArtifact(filePath, apiKey) {
const { size } = await stat(filePath)
let endpoint = VIRUSTOTAL_FILES_ENDPOINT
if (size > 32 * 1024 * 1024) {
const urlResponse = await fetch(`${VIRUSTOTAL_FILES_ENDPOINT}/upload_url`, {
headers: { 'x-apikey': apiKey }
})
if (!urlResponse.ok) {
throw new Error(`Could not obtain a VirusTotal upload URL: ${urlResponse.status}`)
}
endpoint = (await urlResponse.json())?.data
}
// openAsBlob streams from disk; buffering a 200MB installer would not fit.
const form = new FormData()
form.append('file', await openAsBlob(filePath), basename(filePath))
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'x-apikey': apiKey },
body: form
})
if (!response.ok) {
throw new Error(`VirusTotal upload failed for ${filePath}: ${response.status}`)
}
}
export async function scanArtifacts(filePaths, { apiKey, upload = false } = {}) {
const reports = []
for (const filePath of filePaths) {
const sha256 = await hashFile(filePath)
let analysisResults = await fetchExistingReport(sha256, apiKey)
if (analysisResults === null && upload) {
await uploadArtifact(filePath, apiKey)
analysisResults = null
}
const { scanned, flagged } = summarizeEngineVerdicts(analysisResults)
reports.push({
name: basename(filePath),
sha256,
known: analysisResults !== null,
scanned,
flagged
})
}
return reports
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const args = process.argv.slice(2)
const upload = args.includes('--upload')
const filePaths = args.filter((arg) => !arg.startsWith('--'))
if (filePaths.length === 0) {
throw new Error(
'Usage: node config/scripts/release/publication/scan-release-artifacts-antivirus.mjs [--upload] <artifact>...'
)
}
const apiKey = process.env.VIRUSTOTAL_API_KEY
if (!apiKey) {
// Missing secret must not fail parallel release steps before provisioning.
console.log('VIRUSTOTAL_API_KEY is not set; skipping the antivirus detection report.')
process.exit(0)
}
const reports = await scanArtifacts(filePaths, { apiKey, upload })
for (const report of reports) {
console.log(formatArtifactReport(report))
}
if (hasAnyDetection(reports)) {
// Warn for human review: third-party classifiers must not control release success.
console.log(
'\nAt least one engine flags a shipped artifact. Decide before publishing, and submit ' +
'for clearance per docs/reference/antivirus-prerelease-clearance.md.'
)
}
}