import { test } from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import { createHash } from 'node:crypto'; import { patchOnboarding } from './onboarding-cloud-patch.mjs'; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const source = fs.readFileSync(new URL('./apply-onboarding-prompt.mjs', import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, ''); const hash = value => createHash('sha256').update(value).digest('hex'); const bytes = Buffer.from('generic onboarding archive fixture'); const oldSource = ["var CLASS_JOB = 'FmodeProvisionJob';", 'function unrelated() { return "preserve"; }', 'function trial() {', ' var mxPass = derivedPass || "old";', ' var instruction = ["【Fmode 接入提示词】", "old"].join(\'\\n\');', ' return {', " mode: 'onboarding',", ' instruction: instruction', ' };', '}'].join('\n'); async function fixture({ urlDrift = false, codeDrift = false, badAsset = false, concurrent = false, tamperedCandidate = false } = {}) { const bundle = { version: '1.0.1', image: 'fmode/agent-node:0.21.3', url: 'https://s3.fmode.cn/original.tar.gz', sha256: hash(bytes), bytes: bytes.length }; const candidate = patchOnboarding(oldSource, bundle) + (tamperedCandidate ? '\nfunction unrequested() { return true; }' : ''); const preview = { target: 'VtW1GT93Ax', bundleSha256: bundle.sha256, bundle: { ...bundle }, oldSha256: hash(oldSource), newSha256: hash(candidate) }; if (urlDrift) bundle.url = 'https://s3.fmode.cn/different-url.tar.gz'; let remote = { name: 'fmode-provisioning', version: '0.9.1', code: codeDrift ? oldSource + '\n// external update' : oldSource }; let state = { actions: { publishBundle_fixture: { confirmedAt: 'published', sha256: bundle.sha256, receipt: { url: bundle.url } } } }, pending; const requests = [], writes = new Map(), calls = []; const fakeFs = { readFileSync(file) { calls.push('read:' + file); if (file.endsWith('dev-login.json')) return JSON.stringify({ masterKey: 'fixture-only' }); if (file.endsWith('state.json')) return JSON.stringify(state); if (file.endsWith('bundle.json')) return JSON.stringify(bundle); if (file.includes('cloud-prompt-preview-')) return JSON.stringify(preview); if (file.includes('provision-cloud-candidate-')) return candidate; throw Error('Unexpected read ' + file); }, openSync() { calls.push('lock'); if (concurrent) state.actions.cloudPrompt = { attempted: true, confirmedAt: 'other', proof: 'preserve' }; return 7; }, writeFileSync(file, data) { file = String(file); 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, method: init.method || 'GET', body: init.body }); if (url.startsWith('https://s3.')) return { ok: true, arrayBuffer: async () => badAsset ? Buffer.from('wrong asset') : bytes }; if (init.method === 'PUT') { const body = JSON.parse(init.body); remote = { ...remote, ...body, updatedAt: 'confirmed' }; return { ok: true, status: 200, json: async () => ({ updatedAt: 'confirmed' }) }; } return { ok: true, json: async () => remote }; }; const process = { argv: ['node', 'runner', '--stage=apply', '--tag=fixture-v101'], pid: 7, cwd: () => '/project' }; let error; const run = new AsyncFunction('fs', 'assert', 'createHash', 'patchOnboarding', 'recordProgress', 'process', 'fetch', 'console', source); try { await run(fakeFs, assert, createHash, patchOnboarding, () => {}, process, fetch, { log() {} }); } catch (e) { error = e; } return { state, requests, writes, calls, remote, error }; } test('apply rejects same bytes at a different URL after preview, before any PUT', async () => { const r = await fixture({ urlDrift: true }); assert.match(r.error.message, /完整元数据不一致/); assert.equal(r.requests.length, 0); }); test('apply rejects cloud code drift and unrequested candidate edits', async () => { const drift = await fixture({ codeDrift: true }); assert.match(drift.error.message, /源码在预览后发生变化/); const edit = await fixture({ tamperedCandidate: true }); assert.match(edit.error.message, /指定提示词补丁/); assert.ok([...drift.requests, ...edit.requests].every(x => x.method !== 'PUT')); }); test('apply checks public asset bytes before updating the function', async () => { const r = await fixture({ badAsset: true }); assert.match(r.error.message, /公开包摘要不一致/); assert.ok(r.requests.every(x => x.method !== 'PUT')); }); test('apply locks before reading ledger and does not repeat a concurrent completed PUT', async () => { const r = await fixture({ concurrent: true }); assert.match(r.error.message, /已有动作记录/); assert.equal(r.requests.length, 0); assert.equal(r.state.actions.cloudPrompt.proof, 'preserve'); assert.ok(r.calls.indexOf('lock') < r.calls.findIndex(x => x.endsWith('state.json'))); }); test('apply changes only one verified function and preserves unrelated live code', async () => { const r = await fixture(); assert.equal(r.error, undefined); const puts = r.requests.filter(x => x.method === 'PUT'); assert.equal(puts.length, 1); assert.equal(puts[0].url, 'https://server.fmode.cn/parse/classes/Function/VtW1GT93Ax'); assert.ok(r.remote.code.includes('function unrelated() { return "preserve"; }')); assert.equal(r.state.actions.cloudPrompt.receipt.sha256, hash(r.remote.code)); assert.ok(r.writes.has('test-results/new-account-20261128/cloud-prompt-put-response-fixture-v101.json')); });