import { test } from 'node:test'; import fs from 'node:fs'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const source = fs.readFileSync(new URL('./publish-onboarding-bundle.mjs', import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, ''); const bytes = Buffer.from('credential-free generic fixture'), sha256 = createHash('sha256').update(bytes).digest('hex'); const key = 'publishBundle_' + sha256.slice(0, 16); async function fixture({ completedOnLock = false, matchingTest = true, corruptDownload = false, matchingProbe = true } = {}) { let state = { userId: 'owner', actions: { publishBundle: { attempted: true, confirmedAt: 'old', sha256: 'b'.repeat(64), proof: 'must-preserve' }, onboardingLinux101Approved: { confirmedAt: 'tested', exitCode: 0, bundleSha256: matchingTest ? sha256 : 'c'.repeat(64) }, localCandidate: { bundleSha256: sha256 }, trialCleanOutput: { confirmedAt: 'clean', bundleSha256: matchingProbe ? sha256 : 'e'.repeat(64) }, trialChatReady: { proof: {} }, trialFilesV3: { proof: {} }, } }, pending; const writes = new Map(), requests = [], calls = []; const fakeFs = { openSync() { calls.push('lock'); if (completedOnLock) state.actions[key] = { attempted: true, confirmedAt: 'concurrent', proof: 'concurrent-proof' }; return 7; }, readFileSync(file) { calls.push('read:' + file); if (file.endsWith('state.json')) return JSON.stringify(state); if (file.endsWith('receipt.json')) return JSON.stringify({ version: '1.0.1', sha256, archive: '/fixture/archive.tar.gz' }); if (file.endsWith('archive.tar.gz')) return bytes; if (file.endsWith('account.json')) return JSON.stringify({ userId: 'owner', token: 'private-fixture' }); throw Error('unexpected read ' + file); }, writeFileSync(file, data, options) { file = String(file); if (options?.flag === 'wx') assert.ok(!writes.has(file), 'immutable receipt must not be overwritten'); if (file.endsWith('state.json.next')) pending = JSON.parse(data); else writes.set(file, data); }, renameSync() { state = pending; }, closeSync() {}, unlinkSync() {}, }; const fetch = async (url, init = {}) => { requests.push({ url: String(url), method: init.method || 'GET' }); if (requests.length === 1) return { ok: true, json: async () => ({ code: 200, uploadUrl: 'https://s3.invalid/signed', publicUrl: 'https://s3.fmode.cn/fixture.tar.gz', key: 'fixture' }) }; if (requests.length === 2) return { ok: true, status: 200 }; return { ok: true, status: 200, arrayBuffer: async () => corruptDownload ? Buffer.from('corrupt') : bytes }; }; const process = { argv: ['node', 'runner', '--stage=upload', '--package-dir=/fixture/selected'], pid: 7, cwd: () => '/project' }; const run = new AsyncFunction('fs', 'assert', 'createHash', 'recordProgress', 'process', 'fetch', 'console', source); let error; try { await run(fakeFs, assert, createHash, () => {}, process, fetch, { log() {} }); } catch (e) { error = e; } return { state, writes, requests, calls, error }; } test('new package action is checked after lock and never repeats a concurrent completed upload', async () => { const r = await fixture({ completedOnLock: true }); assert.match(r.error.message, /已有记录/); assert.equal(r.requests.length, 0); assert.equal(r.state.actions[key].proof, 'concurrent-proof'); assert.ok(r.calls.indexOf('lock') < r.calls.findIndex(x => x.endsWith('state.json'))); }); test('old successful tests cannot authorize uploading a different package hash', async () => { const r = await fixture({ matchingTest: false }); assert.match(r.error.message, /摘要一致/); assert.equal(r.requests.length, 0); }); test('new package uses distinct action and immutable evidence while retaining old upload', async () => { const r = await fixture(); assert.equal(r.error, undefined); assert.deepEqual(r.requests.map(x => x.method), ['POST', 'PUT', 'GET']); assert.equal(r.state.actions.publishBundle.proof, 'must-preserve'); assert.equal(r.state.actions[key].receipt.sha256, sha256); assert.ok([...r.writes.keys()].some(x => x.endsWith('bundle-published-' + sha256.slice(0, 16) + '-receipt.json'))); assert.ok(!r.writes.has('test-results/new-account-20261128/bundle-published-receipt.json')); assert.ok(!r.writes.has('.local-backup/new-account-20261128/bundle-upload-ticket.json')); }); test('corrupt public readback does not update bundle pointer or confirm success', async () => { const r = await fixture({ corruptDownload: true }); assert.match(r.error.message, /摘要不一致/); assert.equal(r.writes.has('cloud/onboarding/bundle.json'), false); assert.equal(r.state.actions[key].confirmedAt, undefined); }); test('a real probe of an older bundle cannot authorize publishing a new bundle', async () => { const r = await fixture({ matchingProbe: false }); assert.match(r.error.message, /不属于当前包摘要/); assert.equal(r.requests.length, 0); });