mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-05 23:09:55 +08:00
feat: add controlled Motion candidate and test release workflows
This commit is contained in:
89
.github/scripts/motion-registry-smoke.mjs
vendored
Normal file
89
.github/scripts/motion-registry-smoke.mjs
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { access, mkdir, mkdtemp, readFile, readdir, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';
|
||||
|
||||
export function consumerEnvironment(work, source = process.env) {
|
||||
const env = { ...source };
|
||||
for (const key of Object.keys(env)) if (/TOKEN|SECRET|PASSWORD|CREDENTIAL|COOKIE|(?:^|_)KEY$|^GITHUB_|^ACTIONS_|^AWS_|^npm_config_/i.test(key)) delete env[key];
|
||||
for (const key of ['HYPERFRAMES_FFMPEG_PATH', 'HYPERFRAMES_FFPROBE_PATH', 'HYPERFRAMES_BROWSER_PATH', 'FFMPEG_PATH', 'FFPROBE_PATH', 'MOTION_BROWSER_PATH', 'MOTION_TEMPLATES_CONFIG_URL', 'MOTION_TEMPLATES_ENV', 'MOTION_DATA_DIR']) delete env[key];
|
||||
return { ...env, CODEX_HOME: path.join(work, 'codex'), npm_config_cache: path.join(work, 'npm-cache'),
|
||||
npm_config_userconfig: path.join(work, 'user.npmrc'), npm_config_globalconfig: path.join(work, 'global.npmrc'),
|
||||
npm_config_registry: 'https://registry.npmjs.org/', npm_config_ignore_scripts: 'true',
|
||||
OPENMOTION_TELEMETRY: '0', HYPERFRAMES_NO_TELEMETRY: '1' };
|
||||
}
|
||||
|
||||
async function discover(transport, env, version, tools) {
|
||||
const child = spawn(transport.command, transport.args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
||||
const waiting = new Map(); let sequence = 0;
|
||||
const fail = error => { for (const p of waiting.values()) { clearTimeout(p.timer); p.reject(error); } waiting.clear(); };
|
||||
child.on('error', fail); child.on('exit', code => fail(new Error('MCP exited: ' + code)));
|
||||
child.stderr.resume();
|
||||
createInterface({ input: child.stdout }).on('line', line => {
|
||||
try { const result = JSON.parse(line), p = waiting.get(result.id); if (p) { waiting.delete(result.id); clearTimeout(p.timer); result.error ? p.reject(new Error('MCP error')) : p.resolve(result.result); } }
|
||||
catch { fail(new Error('Invalid MCP JSON')); }
|
||||
});
|
||||
const rpc = (method, params) => new Promise((resolve, reject) => {
|
||||
const id = ++sequence, timer = setTimeout(() => { waiting.delete(id); reject(new Error('MCP timed out: ' + method)); }, 120_000);
|
||||
waiting.set(id, { resolve, reject, timer }); child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
|
||||
});
|
||||
try {
|
||||
const hello = await rpc('initialize', { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'motion-registry-acceptance', version: '1' } });
|
||||
assert.equal(hello.serverInfo.version, version);
|
||||
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
|
||||
assert.deepEqual((await rpc('tools/list', {})).tools.map(t => t.name), tools);
|
||||
await rpc('resources/read', { uri: 'motion://workflow/production/start' });
|
||||
await rpc('resources/read', { uri: 'motion://engine/SKILL.md' });
|
||||
} finally { child.stdin.end(); child.kill(); fail(new Error('MCP session closed')); }
|
||||
}
|
||||
|
||||
export async function registrySmoke(directory) {
|
||||
const c = JSON.parse(await readFile(path.join(directory, 'candidate.json')));
|
||||
const platform = process.platform + '-' + process.arch;
|
||||
assert(['darwin-arm64', 'win32-x64'].includes(platform), 'Use a supported native runner');
|
||||
const work = await mkdtemp(path.join(os.tmpdir(), 'om-registry-')), env = consumerEnvironment(work);
|
||||
for (const file of ['user.npmrc', 'global.npmrc']) await writeFile(path.join(work, file), '');
|
||||
const project = path.join(work, 'project'), host = path.join(work, 'host');
|
||||
await mkdir(project); await mkdir(env.CODEX_HOME);
|
||||
await writeFile(path.join(env.CODEX_HOME, 'config.toml'), '[mcp_servers.unrelated]\ncommand = "keep-this-server"\n');
|
||||
const npm = path.join(path.dirname(process.execPath), process.platform === 'win32' ? 'node_modules/npm/bin/npm-cli.js' : '../lib/node_modules/npm/bin/npm-cli.js');
|
||||
const cli = args => runFile(process.execPath, [npm, ...args], { cwd: project, env, timeout: 20 * 60_000 });
|
||||
let metadata;
|
||||
for (let attempt = 0; attempt < 30; attempt++) {
|
||||
const response = await fetch('https://registry.npmjs.org/@openmotion%2fapp/' + c.version, { signal: AbortSignal.timeout(30_000) });
|
||||
if (response.ok) { metadata = await response.json(); break; }
|
||||
assert.equal(response.status, 404, 'Registry lookup failed');
|
||||
await new Promise(resolve => setTimeout(resolve, 10_000));
|
||||
}
|
||||
assert(metadata, 'Registry version did not become visible'); assert.equal(metadata.dist.integrity, c.integrity);
|
||||
const [packed] = JSON.parse(await cli(['pack', `${c.packageName}@${c.version}`, '--ignore-scripts', '--json', '--pack-destination', work]));
|
||||
assert.equal(path.basename(packed.filename), packed.filename);
|
||||
const tgz = path.join(work, packed.filename), bytes = await readFile(tgz);
|
||||
assert.equal(await sha256(tgz), c.tgzSHA256); assert.equal('sha512-' + createHash('sha512').update(bytes).digest('base64'), c.integrity);
|
||||
await cli(['install', '--prefix', host, '--no-save', '--ignore-scripts', '--no-audit', '--no-fund', '@openai/codex@0.166.0']);
|
||||
const codex = path.join(host, 'node_modules/@openai/codex/bin/codex.js');
|
||||
const home = path.join(work, 'app'), data = path.join(work, 'data'), skills = path.join(project, '.agents/skills');
|
||||
const command = ['exec', '--yes', '--package', tgz, '--', 'openmotion'];
|
||||
const setup = [...command, 'setup', '--host', 'codex', '--home', home, '--data-dir', data, '--skills-dir', skills, '--codex', codex];
|
||||
const first = JSON.parse(await cli(setup)), second = JSON.parse(await cli(setup));
|
||||
assert.equal(first.appRoot, second.appRoot); assert.equal((await readdir(path.join(home, 'apps'))).length, 1);
|
||||
assert.match(await readFile(path.join(env.CODEX_HOME, 'config.toml'), 'utf8'), /keep-this-server/);
|
||||
const manifest = JSON.parse(await readFile(path.join(directory, 'release-npm.json')));
|
||||
for (const skill of manifest.skills) await access(path.join(skills, 'openmotion/skills', skill, 'SKILL.md'));
|
||||
await cli([...command, 'prepare', '--home', home]);
|
||||
const installed = JSON.parse(await runFile(process.execPath, [codex, 'mcp', 'get', 'openmotion', '--json'], { cwd: project, env }));
|
||||
assert.equal(installed.transport.command, process.execPath); assert.deepEqual(installed.transport.args, [first.launcher]);
|
||||
await discover(installed.transport, env, c.version, manifest.mcp.tools);
|
||||
const report = { status: 'passed', platform, version: c.version, sourceCommit: c.sourceCommit, tgzSHA256: c.tgzSHA256,
|
||||
node: process.version, codex: '0.166.0', registryColdInstall: 'passed', repeatSetup: 'passed', unrelatedSettings: 'preserved',
|
||||
nativePreparation: 'passed', mcpTools: manifest.mcp.tools.length, skills: manifest.skills.length, resources: 'passed',
|
||||
realModelTurn: 'not-run', humanPlayback: 'not-run', windowsDesktopAcceptance: 'not-run' };
|
||||
await writeJSON(path.join(directory, `registry-${platform}.json`), report); return report;
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await registrySmoke(path.resolve(process.argv[2]));
|
||||
252
.github/scripts/motion-release.mjs
vendored
Normal file
252
.github/scripts/motion-release.mjs
vendored
Normal file
@@ -0,0 +1,252 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';
|
||||
import { checkReleaseVersion } from '../../scripts/release-version.mjs';
|
||||
import { generateInstallGuide } from '../../scripts/install-guide.mjs';
|
||||
import { publishGuide, storagePlan } from './publish-install-guide.mjs';
|
||||
import { scanPackage, scanSource } from './motion-scan.mjs';
|
||||
|
||||
export const repository = 'nexu-io/html-anything';
|
||||
export const candidateWorkflow = '.github/workflows/motion-candidate.yml';
|
||||
const exec = promisify(execFile), hashPattern = /^[a-f0-9]{64}$/;
|
||||
const json = async file => JSON.parse(await readFile(file, 'utf8'));
|
||||
const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64');
|
||||
|
||||
export function releaseInputs(env = process.env) {
|
||||
assert.equal(env.GITHUB_REPOSITORY, repository, 'Wrong repository');
|
||||
assert.equal(env.GITHUB_EVENT_NAME, 'workflow_dispatch', 'Manual invocation required');
|
||||
assert.equal(env.GITHUB_REF, 'refs/heads/main', 'Run the trusted workflow registered on main');
|
||||
assert(['publish-test', 'archive-only'].includes(env.MOTION_RELEASE_ACTION), 'Unknown release action');
|
||||
assert.equal(env.MOTION_APPROVED, 'true', 'Explicit release approval is required');
|
||||
assert.match(env.MOTION_EXPECTED_SHA256 || '', hashPattern, 'Require the accepted tgz SHA256');
|
||||
assert.match(env.MOTION_ACCEPTANCE_SHA256 || '', hashPattern, 'Require the digest of the internal acceptance record');
|
||||
assert(/^[1-9]\d*$/.test(env.MOTION_CANDIDATE_RUN || ''), 'Require a candidate workflow run ID');
|
||||
return { action: env.MOTION_RELEASE_ACTION, expectedSHA256: env.MOTION_EXPECTED_SHA256,
|
||||
acceptanceSHA256: env.MOTION_ACCEPTANCE_SHA256, candidateRun: env.MOTION_CANDIDATE_RUN };
|
||||
}
|
||||
|
||||
export async function validateSource(control, commit, version, run = runFile) {
|
||||
assert.match(commit || '', /^[a-f0-9]{40}$/, 'Use a full immutable source SHA');
|
||||
checkReleaseVersion(version); assert(version.includes('-test.'), 'This workflow builds test versions only');
|
||||
await run('git', ['merge-base', '--is-ancestor', commit, 'refs/remotes/origin/feature/motion'], { cwd: control });
|
||||
}
|
||||
|
||||
export async function sealCandidate(build, output, source, env = process.env) {
|
||||
const manifest = await json(path.join(build, 'release-npm.json'));
|
||||
assert.equal(manifest.commit, (await runFile('git', ['rev-parse', 'HEAD'], { cwd: source })).trim());
|
||||
assert.equal(manifest.commit, env.MOTION_SOURCE_SHA); assert.equal(manifest.version, env.MOTION_VERSION);
|
||||
assert(manifest.version.includes('-test.') && manifest.templateEnvironment === 'prod');
|
||||
assert.match(env.GITHUB_SHA || '', /^[a-f0-9]{40}$/);
|
||||
assert.equal(env.GITHUB_WORKFLOW_REF, `${repository}/${candidateWorkflow}@refs/heads/main`);
|
||||
assert(/^[1-9]\d*$/.test(env.GITHUB_RUN_ID || '') && /^[1-9]\d*$/.test(env.GITHUB_RUN_ATTEMPT || ''));
|
||||
const filename = manifest.installer.url.replace(/^\.\//, '');
|
||||
assert.equal(filename, `openmotion-app-${manifest.version}.tgz`);
|
||||
await mkdir(output, { recursive: true });
|
||||
for (const name of [filename, 'release-npm.json', 'source-scan.json', 'package-scan.json']) await cp(path.join(build, name), path.join(output, name));
|
||||
const guide = await generateInstallGuide(path.join(output, filename), output);
|
||||
assert.equal(guide.packageName, '@openmotion/app'); assert.equal(guide.commit, env.MOTION_SOURCE_SHA);
|
||||
for (const name of ['source-scan.json', 'package-scan.json']) assert.equal((await json(path.join(output, name))).status, 'passed');
|
||||
const names = [filename, 'release-npm.json', 'source-scan.json', 'package-scan.json', 'install.md', 'install-record.json'];
|
||||
const files = Object.fromEntries(await Promise.all(names.map(async name => [name, await sha256(path.join(output, name))])));
|
||||
const candidate = { schemaVersion: 1, kind: 'motion-candidate', packageName: guide.packageName, version: guide.version,
|
||||
sourceCommit: guide.commit, tgz: filename, tgzSHA256: files[filename], integrity: integrity(await readFile(path.join(output, filename))), files,
|
||||
workflow: { repository, path: candidateWorkflow, ref: 'refs/heads/main', sha: env.GITHUB_SHA,
|
||||
runId: Number(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT) },
|
||||
createdAt: new Date().toISOString(), acceptance: 'not-performed' };
|
||||
await writeJSON(path.join(output, 'candidate.json'), candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export function validateRun(run, artifact) {
|
||||
assert.equal(run.event, 'workflow_dispatch'); assert.equal(run.head_branch, 'main');
|
||||
assert.equal(run.head_repository?.full_name, repository); assert.equal(run.status, 'completed'); assert.equal(run.conclusion, 'success');
|
||||
assert.equal(run.path.split('@')[0], candidateWorkflow, 'Candidate must come from the registered workflow');
|
||||
assert.equal(artifact.name, `motion-candidate-${run.id}-${run.run_attempt}`);
|
||||
assert.equal(artifact.workflow_run?.id, run.id); assert.equal(artifact.expired, false);
|
||||
assert.match(artifact.digest || '', /^sha256:[a-f0-9]{64}$/, 'Require the GitHub artifact digest');
|
||||
assert(artifact.size_in_bytes > 0 && artifact.size_in_bytes < 150 * 1024 * 1024, 'Unexpected artifact size');
|
||||
}
|
||||
|
||||
async function github(route, fetcher = fetch) {
|
||||
const response = await fetcher(`https://api.github.com/repos/${repository}${route}`, { redirect: 'error', signal: AbortSignal.timeout(30_000),
|
||||
headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${process.env.GH_TOKEN || process.env.GITHUB_TOKEN}`, 'X-GitHub-Api-Version': '2022-11-28' } });
|
||||
assert(response.ok, 'GitHub metadata request failed: HTTP ' + response.status);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function verifyCandidate(directory, expectedSHA256, run) {
|
||||
const candidate = await json(path.join(directory, 'candidate.json'));
|
||||
assert.equal(candidate.schemaVersion, 1); assert.equal(candidate.kind, 'motion-candidate'); assert.equal(candidate.packageName, '@openmotion/app');
|
||||
checkReleaseVersion(candidate.version); assert(candidate.version.includes('-test.'));
|
||||
assert.equal(candidate.tgz, `openmotion-app-${candidate.version}.tgz`); assert.equal(candidate.tgzSHA256, expectedSHA256);
|
||||
assert.match(expectedSHA256, hashPattern); assert.match(candidate.sourceCommit, /^[a-f0-9]{40}$/);
|
||||
assert.deepEqual(candidate.workflow, { repository, path: candidateWorkflow, ref: 'refs/heads/main', sha: run.head_sha, runId: run.id, attempt: run.run_attempt });
|
||||
const names = [candidate.tgz, 'release-npm.json', 'source-scan.json', 'package-scan.json', 'install.md', 'install-record.json'];
|
||||
assert.deepEqual(Object.keys(candidate.files).sort(), names.sort());
|
||||
for (const name of names) assert.equal(await sha256(path.join(directory, name)), candidate.files[name], 'Candidate file changed: ' + name);
|
||||
assert.equal(await sha256(path.join(directory, candidate.tgz)), expectedSHA256);
|
||||
assert.equal(integrity(await readFile(path.join(directory, candidate.tgz))), candidate.integrity);
|
||||
const guide = await json(path.join(directory, 'install-record.json'));
|
||||
assert.equal(guide.commit, candidate.sourceCommit); assert.equal(guide.version, candidate.version); assert.equal(guide.packageName, candidate.packageName);
|
||||
assert.equal(guide.tgzSHA256, expectedSHA256); assert.equal(guide.channel, 'test'); assert.equal(guide.templateEnvironment, 'prod');
|
||||
assert.equal(guide.guideSHA256, candidate.files['install.md']); assert.equal(guide.candidate, false);
|
||||
const manifest = await json(path.join(directory, 'release-npm.json'));
|
||||
assert.equal(manifest.commit, candidate.sourceCommit); assert.equal(manifest.version, candidate.version);
|
||||
assert.equal(manifest.installer.sha256, expectedSHA256);
|
||||
for (const name of ['source-scan.json', 'package-scan.json']) assert.equal((await json(path.join(directory, name))).status, 'passed');
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export async function verifyDownloaded(directory, expectedSHA256) {
|
||||
const provenance = await json(path.join(directory, 'provenance.json'));
|
||||
return verifyCandidate(directory, expectedSHA256, { head_sha: provenance.head_sha, id: provenance.runId, run_attempt: provenance.attempt });
|
||||
}
|
||||
|
||||
export async function platformReports(directory, candidate) {
|
||||
const reports = [];
|
||||
for (const platform of ['darwin-arm64', 'win32-x64']) {
|
||||
const name = `registry-${platform}.json`, report = await json(path.join(directory, name));
|
||||
assert.equal(report.status, 'passed'); assert.equal(report.platform, platform);
|
||||
assert.equal(report.version, candidate.version); assert.equal(report.tgzSHA256, candidate.tgzSHA256);
|
||||
assert.equal(report.sourceCommit, candidate.sourceCommit);
|
||||
assert.equal(report.registryColdInstall, 'passed'); assert.equal(report.nativePreparation, 'passed');
|
||||
assert.equal(report.repeatSetup, 'passed'); assert.equal(report.resources, 'passed');
|
||||
assert.equal(report.mcpTools, 11); assert.equal(report.skills, 5);
|
||||
reports.push({ platform, reportSHA256: await sha256(path.join(directory, name)) });
|
||||
}
|
||||
return reports;
|
||||
}
|
||||
|
||||
export async function downloadCandidate(runId, directory, expectedSHA256, fetcher = fetch) {
|
||||
assert(/^[1-9]\d*$/.test(runId));
|
||||
const run = await github(`/actions/runs/${runId}`, fetcher);
|
||||
const { artifacts } = await github(`/actions/runs/${runId}/artifacts?per_page=100`, fetcher);
|
||||
const matches = artifacts.filter(a => a.name === `motion-candidate-${run.id}-${run.run_attempt}`); assert.equal(matches.length, 1, 'Candidate artifact missing or ambiguous');
|
||||
const artifact = matches[0]; validateRun(run, artifact);
|
||||
const redirect = await fetcher(`https://api.github.com/repos/${repository}/actions/artifacts/${artifact.id}/zip`, {
|
||||
redirect: 'manual', signal: AbortSignal.timeout(30_000), headers: { Authorization: `Bearer ${process.env.GH_TOKEN || process.env.GITHUB_TOKEN}` } });
|
||||
assert.equal(redirect.status, 302); const url = new URL(redirect.headers.get('location')); assert.equal(url.protocol, 'https:'); assert(!url.username && !url.password);
|
||||
// Signed artifact URLs are fetched without forwarding the GitHub credential.
|
||||
const response = await fetcher(url, { redirect: 'error', signal: AbortSignal.timeout(60_000) }); assert(response.ok);
|
||||
const bytes = Buffer.from(await response.arrayBuffer()); assert(bytes.length < 150 * 1024 * 1024);
|
||||
assert.equal('sha256-' + createHash('sha256').update(bytes).digest('hex'), artifact.digest.replace(':', '-'));
|
||||
const work = await mkdtemp(path.join(os.tmpdir(), 'motion-artifact-'));
|
||||
try {
|
||||
const archive = path.join(work, 'candidate.zip'); await writeFile(archive, bytes);
|
||||
const entries = (await runFile('unzip', ['-Z1', archive])).trim().split('\n');
|
||||
assert(entries.length === 7 && new Set(entries).size === 7, 'Unexpected candidate artifact files');
|
||||
assert(entries.every(name => /^[a-zA-Z0-9._-]+$/.test(name) && name.length < 160), 'Unsafe candidate artifact entry');
|
||||
await mkdir(directory, { recursive: true });
|
||||
for (const name of entries) {
|
||||
const { stdout } = await exec('unzip', ['-p', archive, name], { encoding: 'buffer', maxBuffer: 150 * 1024 * 1024 });
|
||||
await writeFile(path.join(directory, name), stdout);
|
||||
}
|
||||
const candidate = await verifyCandidate(directory, expectedSHA256, run);
|
||||
await writeJSON(path.join(directory, 'provenance.json'), { runId: run.id, attempt: run.run_attempt, head_sha: run.head_sha, artifactId: artifact.id, digest: artifact.digest });
|
||||
return candidate;
|
||||
} finally { await rm(work, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
export async function registryPackage(candidate, fetcher = fetch) {
|
||||
const response = await fetcher('https://registry.npmjs.org/@openmotion%2fapp', { signal: AbortSignal.timeout(30_000) });
|
||||
if (response.status === 404) return { version: null, tags: {} };
|
||||
assert(response.ok, 'Registry metadata request failed'); const data = await response.json();
|
||||
const version = data.versions?.[candidate.version];
|
||||
if (version) assert.equal(version.dist.integrity, candidate.integrity, 'Published npm version has different bytes; never overwrite it');
|
||||
return { version: version || null, tags: data['dist-tags'] || {} };
|
||||
}
|
||||
|
||||
export async function publishNpm(directory, inputs, { fetcher = fetch, run = runFile } = {}) {
|
||||
const candidate = await verifyDownloaded(directory, inputs.expectedSHA256);
|
||||
const before = await registryPackage(candidate, fetcher);
|
||||
if (inputs.action === 'archive-only') assert(before.version, 'Archive-only requires an existing identical npm version');
|
||||
const record = { schemaVersion: 1, version: candidate.version, tgzSHA256: candidate.tgzSHA256, action: inputs.action,
|
||||
previousLatest: before.tags.latest ?? null, status: before.version ? 'already-published-identical' : 'publish-started' };
|
||||
await writeJSON(path.join(directory, 'npm-publication.json'), record);
|
||||
if (!before.version) {
|
||||
await run('npm', ['publish', path.join(directory, candidate.tgz), '--access', 'public', '--tag', 'test', '--ignore-scripts', '--registry=https://registry.npmjs.org/']);
|
||||
record.status = 'published-awaiting-registry'; await writeJSON(path.join(directory, 'npm-publication.json'), record);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
export async function archiveRelease(directory, inputs, config, { run = runFile, fetcher = fetch, env = process.env } = {}) {
|
||||
await writeJSON(path.join(directory, 'release-attempt.json'), { action: inputs.action, tgzSHA256: inputs.expectedSHA256, stage: 'verifying-release', runId: env.GITHUB_RUN_ID });
|
||||
const candidate = await verifyDownloaded(directory, inputs.expectedSHA256);
|
||||
const platforms = await platformReports(directory, candidate);
|
||||
const record = await json(path.join(directory, 'install-record.json')), plan = storagePlan(record, config);
|
||||
assert.equal(candidate.tgzSHA256, inputs.expectedSHA256);
|
||||
const registry = await registryPackage(candidate, fetcher); assert(registry.version, 'Exact npm version is not public');
|
||||
const npm = await json(path.join(directory, 'npm-publication.json'));
|
||||
assert.equal(npm.tgzSHA256, candidate.tgzSHA256);
|
||||
assert.equal(registry.tags.latest ?? null, npm.previousLatest, 'npm latest changed unexpectedly; stop and investigate before promoting a guide');
|
||||
if (inputs.action === 'publish-test') assert.equal(registry.tags.test, candidate.version, 'The test channel changed; use archive-only or a separately approved channel recovery');
|
||||
const prefix = path.posix.dirname(plan.versionKey), work = await mkdtemp(path.join(os.tmpdir(), 'motion-snapshot-'));
|
||||
const aws = async (operation, rest) => JSON.parse(await run('aws', ['--endpoint-url', plan.endpoint, '--region', 'auto', 's3api', operation, '--bucket', plan.bucket, ...rest]) || '{}');
|
||||
try {
|
||||
const get = async key => {
|
||||
const file = path.join(work, 'object');
|
||||
try { await aws('get-object', ['--key', key, file]); return await readFile(file); }
|
||||
catch (error) { if (/NoSuchKey|\(404\)|Not Found/.test(error.message)) return null; throw error; }
|
||||
};
|
||||
const prior = await get(`${prefix}/release-record.json`);
|
||||
let release = { schemaVersion: 1, packageName: candidate.packageName, version: candidate.version, sourceCommit: candidate.sourceCommit,
|
||||
tgzSHA256: candidate.tgzSHA256, integrity: candidate.integrity, candidateRun: candidate.workflow,
|
||||
acceptanceRecordSHA256: inputs.acceptanceSHA256, approvedBy: env.GITHUB_ACTOR, publicationRun: env.GITHUB_RUN_ID,
|
||||
platformVerification: platforms, status: 'registry-verified', publishedAt: new Date().toISOString() };
|
||||
if (prior) {
|
||||
const existing = JSON.parse(prior);
|
||||
for (const key of ['packageName', 'version', 'sourceCommit', 'tgzSHA256', 'integrity', 'acceptanceRecordSHA256']) assert.equal(existing[key], release[key], 'Existing release record differs: ' + key);
|
||||
release = existing;
|
||||
}
|
||||
await writeJSON(path.join(directory, 'release-record.json'), release);
|
||||
const names = [...Object.keys(candidate.files), 'candidate.json', 'registry-darwin-arm64.json', 'registry-win32-x64.json', 'release-record.json'];
|
||||
const objects = [];
|
||||
for (const name of names) {
|
||||
const file = path.join(directory, name), bytes = await readFile(file), key = `${prefix}/${name}`, existing = await get(key);
|
||||
if (existing) assert(existing.equals(bytes), 'Immutable snapshot already has different bytes: ' + name);
|
||||
objects.push({ file, bytes, key, existing });
|
||||
}
|
||||
await writeJSON(path.join(directory, 'release-attempt.json'), { action: inputs.action, version: candidate.version, stage: 'archive-started', runId: env.GITHUB_RUN_ID });
|
||||
for (const object of objects) {
|
||||
if (!object.existing) await aws('put-object', ['--key', object.key, '--body', object.file, '--if-none-match', '*', '--content-type', object.key.endsWith('.md') ? 'text/markdown; charset=utf-8' : object.key.endsWith('.json') ? 'application/json' : 'application/octet-stream', '--cache-control', 'public, max-age=31536000, immutable']);
|
||||
const response = await fetcher(new URL('/' + object.key, plan.publicOrigin), { redirect: 'error', signal: AbortSignal.timeout(30_000), headers: { 'cache-control': 'no-cache' } });
|
||||
assert(response.ok, 'Snapshot public readback failed'); assert(Buffer.from(await response.arrayBuffer()).equals(object.bytes), 'Snapshot public bytes differ');
|
||||
}
|
||||
await publishGuide(directory, config, { run, fetcher, promote: inputs.action === 'publish-test' });
|
||||
await writeJSON(path.join(directory, 'release-attempt.json'), { action: inputs.action, version: candidate.version, stage: inputs.action === 'publish-test' ? 'test-entry-verified' : 'archive-only-verified', runId: env.GITHUB_RUN_ID });
|
||||
return release;
|
||||
} finally { await rm(work, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const [command, directory, extra, final] = process.argv.slice(2);
|
||||
if (command === 'source') await validateSource(directory, process.env.MOTION_SOURCE_SHA, process.env.MOTION_VERSION);
|
||||
else if (command === 'seal') await sealCandidate(directory, extra, final);
|
||||
else {
|
||||
const inputs = releaseInputs();
|
||||
if (command === 'download') await downloadCandidate(inputs.candidateRun, directory, inputs.expectedSHA256);
|
||||
else if (command === 'rescan') {
|
||||
const c = await verifyDownloaded(directory, inputs.expectedSHA256);
|
||||
await validateSource(extra, c.sourceCommit, c.version);
|
||||
const work = await mkdtemp(path.join(os.tmpdir(), 'motion-source-verify-'));
|
||||
try {
|
||||
await runFile('git', ['worktree', 'add', '--detach', work, c.sourceCommit], { cwd: extra });
|
||||
await writeJSON(path.join(directory, 'publication-source-scan.json'), await scanSource(work, final));
|
||||
await writeJSON(path.join(directory, 'publication-package-scan.json'), await scanPackage(path.join(directory, c.tgz), final));
|
||||
} finally { await runFile('git', ['worktree', 'remove', '--force', work], { cwd: extra }).catch(() => {}); }
|
||||
} else if (command === 'verify') await verifyDownloaded(directory, inputs.expectedSHA256);
|
||||
else if (command === 'npm') await publishNpm(directory, inputs);
|
||||
else if (command === 'archive') {
|
||||
for (const name of ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']) assert(process.env[name], 'Missing R2 credential: ' + name);
|
||||
await archiveRelease(directory, inputs, { endpoint: process.env.MOTION_R2_ENDPOINT, bucket: process.env.MOTION_R2_BUCKET, publicOrigin: process.env.MOTION_INSTALL_PUBLIC_ORIGIN });
|
||||
}
|
||||
else throw new Error('Unknown release command');
|
||||
}
|
||||
}
|
||||
150
.github/scripts/motion-scan.mjs
vendored
Normal file
150
.github/scripts/motion-scan.mjs
vendored
Normal file
@@ -0,0 +1,150 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { createGunzip } from 'node:zlib';
|
||||
import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile, chmod } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { download, runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
export const scannerVersion = '8.30.1';
|
||||
const scannerHashes = {
|
||||
'linux_x64': '551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb',
|
||||
'darwin_arm64': 'b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5',
|
||||
};
|
||||
|
||||
export async function installScanner(directory) {
|
||||
const target = `${process.platform}_${process.arch}`;
|
||||
assert(scannerHashes[target], 'Use the supported Linux x64 or Mac arm64 scanner runner');
|
||||
await mkdir(directory, { recursive: true });
|
||||
const archive = path.join(directory, 'gitleaks.tar.gz');
|
||||
await download({ url: `https://github.com/gitleaks/gitleaks/releases/download/v${scannerVersion}/gitleaks_${scannerVersion}_${target}.tar.gz`, sha256: scannerHashes[target] }, archive);
|
||||
await runFile('tar', ['-xzf', archive, '-C', directory, 'gitleaks']);
|
||||
const binary = path.join(directory, 'gitleaks'); await chmod(binary, 0o755);
|
||||
return binary;
|
||||
}
|
||||
|
||||
export function archivePaths(listing) {
|
||||
const names = listing.trim().split('\n');
|
||||
assert(names.length && names.length < 20_000, 'Archive has too many entries');
|
||||
for (const name of names) {
|
||||
assert(name && !/[\\\x00-\x1f]/.test(name) && !path.posix.isAbsolute(name) && !/^[a-z]:/i.test(name)
|
||||
&& !name.split('/').includes('..'), 'Unsafe archive entry');
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
export async function unpackChecked(archive, directory, run = runFile) {
|
||||
assert((await lstat(archive)).size < 150 * 1024 * 1024, 'Archive exceeds release size limit');
|
||||
let expanded = 0;
|
||||
for await (const chunk of createReadStream(archive).pipe(createGunzip())) {
|
||||
expanded += chunk.length; assert(expanded < 350 * 1024 * 1024, 'Expanded archive exceeds release size limit');
|
||||
}
|
||||
archivePaths(await run('tar', ['-tzf', archive]));
|
||||
const details = (await run('tar', ['-tvzf', archive])).trim().split('\n');
|
||||
assert(details.every(line => /^[-d]/.test(line)), 'Archive links and special files are forbidden');
|
||||
await mkdir(directory, { recursive: true });
|
||||
await run('tar', ['-xzf', archive, '-C', directory]);
|
||||
}
|
||||
|
||||
export function privacyFindings(name, text, kind = 'source') {
|
||||
const findings = [], add = rule => findings.push({ path: name, rule });
|
||||
// Public DEV routing and synthetic redaction fixtures are intentional, not credentials or employee paths.
|
||||
if (name === 'prism-templates.ts' || name === './prism-templates.ts') text = text.replace(/https:\/\/r\.powerformer\.net/g, 'https://dev.example.invalid');
|
||||
if (kind === 'source') {
|
||||
const fixtures = {
|
||||
'studio/src/components/feedback/projectProvenance.test.ts': /\/Users\/me\/x/g,
|
||||
'studio/src/player/store/previewQualitySlice.test.ts': /\/Users\/a\/film\.mp3/g,
|
||||
'studio/src/telemetry/breadcrumbs.test.ts': /\/Users\/someone\/(?:private\/path\.html|project\.ts)/g,
|
||||
};
|
||||
if (fixtures[name]) text = text.replace(fixtures[name], '/synthetic/redaction-fixture');
|
||||
}
|
||||
if (/(?:^|\/)(?:outputs|research|node_modules|\.artifacts|\.motion-data(?:-dev)?)(?:\/|$)/.test(name)
|
||||
|| /(?:^|\/)(?:\.npmrc|\.DS_Store|id_rsa|id_ed25519)$/.test(name)
|
||||
|| /\.(?:log|pem|key|p12|pfx)$/.test(name)) add('private-file');
|
||||
if (/(?:^|\/)\.env(?:\.|$)/.test(name) && !(kind === 'source' && /(?:^|\/)\.env\.(?:example|development)$/.test(name))) add('environment-file');
|
||||
if (/https?:\/\/[^\s"'<>)]*(?:powerformer\.(?:net|com)|feishu\.(?:cn|com)|larksuite\.com)/i.test(text)) add('internal-link');
|
||||
if (/\/(?:Users|home)\/[a-zA-Z0-9_.-]+\/|[a-z]:\\Users\\[^\\\s]+\\|\/var\/folders\//i.test(text)) add('personal-path');
|
||||
return findings;
|
||||
}
|
||||
|
||||
async function scanTree(directory, kind, binary) {
|
||||
const findings = []; let files = 0, bytes = 0;
|
||||
const visit = async (dir, prefix = '') => {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const name = prefix + entry.name, filename = path.join(dir, entry.name);
|
||||
assert(!entry.isSymbolicLink(), 'Release scan does not follow links');
|
||||
if (entry.isDirectory()) await visit(filename, name + '/');
|
||||
else {
|
||||
assert(entry.isFile(), 'Special file in release');
|
||||
const data = await readFile(filename); files++; bytes += data.length;
|
||||
assert(bytes < 350 * 1024 * 1024 && files < 20_000, 'Expanded release exceeds scan limit');
|
||||
findings.push(...privacyFindings(name, data.includes(0) ? '' : data.toString('utf8'), kind));
|
||||
}
|
||||
}
|
||||
};
|
||||
await visit(directory);
|
||||
const work = await mkdtemp(path.join(os.tmpdir(), 'motion-secrets-'));
|
||||
try {
|
||||
const report = path.join(work, 'secrets.json'), ignore = path.join(work, 'empty.ignore'); await writeFile(ignore, '');
|
||||
const env = { ...process.env }; delete env.GITLEAKS_CONFIG; delete env.GITLEAKS_CONFIG_TOML;
|
||||
let failure;
|
||||
try { await runFile(binary, ['dir', directory, '--no-banner', '--redact', '--ignore-gitleaks-allow', '--gitleaks-ignore-path', ignore,
|
||||
'--config', path.join(root, '.github/gitleaks.toml'), '--report-format', 'json', '--report-path', report], { cwd: work, env }); }
|
||||
catch (error) { failure = error; }
|
||||
let secrets;
|
||||
try { secrets = JSON.parse(await readFile(report, 'utf8')); }
|
||||
catch { throw new Error('Credential scanner did not produce a valid report'); }
|
||||
for (const hit of secrets) findings.push({ path: path.relative(directory, hit.File), rule: hit.RuleID, line: hit.StartLine });
|
||||
assert(!failure || secrets.length, 'Credential scanner failed before completing');
|
||||
// Never expose matched values or the scanner's raw stdout/report.
|
||||
if (findings.length) throw new Error('Release content rejected: ' + JSON.stringify(findings));
|
||||
return { status: 'passed', kind, files, bytes, scanner: `gitleaks-${scannerVersion}`,
|
||||
policySHA256: createHash('sha256').update(await readFile(path.join(root, '.github/gitleaks.toml'))).update(await readFile(fileURLToPath(import.meta.url))).digest('hex') };
|
||||
} finally { await rm(work, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
export async function scanSource(source, binary) {
|
||||
const names = (await runFile('git', ['ls-files', '-z'], { cwd: source })).split('\0').filter(Boolean);
|
||||
const work = await mkdtemp(path.join(os.tmpdir(), 'motion-source-scan-'));
|
||||
try {
|
||||
for (const name of names) {
|
||||
assert(!name.split('/').includes('..') && !path.isAbsolute(name), 'Unsafe tracked path');
|
||||
const file = path.join(source, name); assert((await lstat(file)).isFile(), 'Tracked links are forbidden');
|
||||
await mkdir(path.dirname(path.join(work, name)), { recursive: true }); await cp(file, path.join(work, name));
|
||||
}
|
||||
return await scanTree(work, 'source', binary);
|
||||
} finally { await rm(work, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
export async function scanPackage(tgz, binary) {
|
||||
const work = await mkdtemp(path.join(os.tmpdir(), 'motion-package-scan-'));
|
||||
try {
|
||||
await unpackChecked(tgz, path.join(work, 'outer'));
|
||||
const outer = path.join(work, 'outer/package');
|
||||
const pkg = JSON.parse(await readFile(path.join(outer, 'package.json')));
|
||||
assert.equal(pkg.name, '@openmotion/app'); assert.equal(pkg.private, false);
|
||||
const manifest = JSON.parse(await readFile(path.join(outer, 'payload/release-npm.json')));
|
||||
assert.equal(manifest.format, 'npm'); assert.equal(manifest.templateEnvironment, 'prod'); assert.equal(manifest.version, pkg.version);
|
||||
const appName = manifest.application.url.replace(/^\.\//, ''); assert.equal(path.basename(appName), appName);
|
||||
const appArchive = path.join(outer, 'payload', appName); assert.equal(await sha256(appArchive), manifest.application.sha256);
|
||||
await unpackChecked(appArchive, path.join(work, 'application'));
|
||||
assert.equal(await sha256(path.join(work, 'application/package-lock.json')), manifest.locks.npm);
|
||||
assert.equal(await sha256(path.join(work, 'application/scripts/runtime-lock.json')), manifest.locks.native);
|
||||
const applicationPkg = JSON.parse(await readFile(path.join(work, 'application/package.json'))); assert.equal(applicationPkg.version, pkg.version);
|
||||
const reports = await Promise.all([scanTree(path.join(work, 'outer'), 'package', binary), scanTree(path.join(work, 'application'), 'package', binary)]);
|
||||
return { status: 'passed', version: pkg.version, tgzSHA256: await sha256(tgz), applicationSHA256: manifest.application.sha256, reports };
|
||||
} finally { await rm(work, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const [command, input, output, binary] = process.argv.slice(2);
|
||||
if (command === 'install') console.log(await installScanner(path.resolve(input)));
|
||||
else {
|
||||
assert(['source', 'package'].includes(command) && input && output && binary, 'Usage: motion-scan.mjs source|package <input> <report> <gitleaks>');
|
||||
await writeJSON(output, await (command === 'source' ? scanSource(path.resolve(input), binary) : scanPackage(path.resolve(input), binary)));
|
||||
console.log('Release content scan passed');
|
||||
}
|
||||
}
|
||||
7
.github/scripts/publish-install-guide.mjs
vendored
7
.github/scripts/publish-install-guide.mjs
vendored
@@ -18,7 +18,7 @@ export function storagePlan(record, { endpoint, bucket, publicOrigin }) {
|
||||
return { endpoint: api.origin, bucket, publicOrigin: origin.origin, versionKey: `${prefix}/${record.version}/install.md`, legacyVersionKey: `${prefix}/versions/${record.version}/install.md`, fixedKey: `${prefix}/install.md` };
|
||||
}
|
||||
|
||||
export async function publishGuide(directory, config, { run = runFile, fetcher = fetch } = {}) {
|
||||
export async function publishGuide(directory, config, { run = runFile, fetcher = fetch, promote = true } = {}) {
|
||||
const file = path.join(directory, 'install.md'), record = JSON.parse(await readFile(path.join(directory, 'install-record.json'), 'utf8'));
|
||||
assert.equal(record.candidate, false, 'Build previews cannot be published');
|
||||
assert.equal(await sha256(file), record.guideSHA256, 'Generated guide changed after validation');
|
||||
@@ -44,6 +44,11 @@ export async function publishGuide(directory, config, { run = runFile, fetcher =
|
||||
if (existing) assert(existing.bytes.equals(expected), 'An immutable version already has different installation instructions');
|
||||
else await put(plan.versionKey, ['--if-none-match', '*'], 'public, max-age=31536000, immutable');
|
||||
await verifyPublic(plan.versionKey);
|
||||
if (!promote) {
|
||||
const publication = { ...record, ...plan, phase: 'version-verified', promoted: false };
|
||||
await writeJSON(path.join(directory, 'publication.json'), publication);
|
||||
return publication;
|
||||
}
|
||||
const previous = await get(plan.fixedKey, path.join(work, 'previous.md'));
|
||||
if (previous) {
|
||||
assert(previous.etag, 'Existing guide requires an ETag for conditional promotion');
|
||||
|
||||
Reference in New Issue
Block a user