test-onboarding-apply.mjs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { test } from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import fs from 'node:fs';
  4. import { createHash } from 'node:crypto';
  5. import { patchOnboarding } from './onboarding-cloud-patch.mjs';
  6. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
  7. const source = fs.readFileSync(new URL('./apply-onboarding-prompt.mjs', import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, '');
  8. const hash = value => createHash('sha256').update(value).digest('hex');
  9. const bytes = Buffer.from('generic onboarding archive fixture');
  10. const oldSource = ["var CLASS_JOB = 'FmodeProvisionJob';", 'function unrelated() { return "preserve"; }', 'function trial() {',
  11. ' var mxPass = derivedPass || "old";', ' var instruction = ["【Fmode 接入提示词】", "old"].join(\'\\n\');',
  12. ' return {', " mode: 'onboarding',", ' instruction: instruction', ' };', '}'].join('\n');
  13. async function fixture({ urlDrift = false, codeDrift = false, badAsset = false, concurrent = false, tamperedCandidate = false } = {}) {
  14. 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 };
  15. const candidate = patchOnboarding(oldSource, bundle) + (tamperedCandidate ? '\nfunction unrequested() { return true; }' : '');
  16. const preview = { target: 'VtW1GT93Ax', bundleSha256: bundle.sha256, bundle: { ...bundle }, oldSha256: hash(oldSource), newSha256: hash(candidate) };
  17. if (urlDrift) bundle.url = 'https://s3.fmode.cn/different-url.tar.gz';
  18. let remote = { name: 'fmode-provisioning', version: '0.9.1', code: codeDrift ? oldSource + '\n// external update' : oldSource };
  19. let state = { actions: { publishBundle_fixture: { confirmedAt: 'published', sha256: bundle.sha256, receipt: { url: bundle.url } } } }, pending;
  20. const requests = [], writes = new Map(), calls = [];
  21. const fakeFs = {
  22. readFileSync(file) {
  23. calls.push('read:' + file);
  24. if (file.endsWith('dev-login.json')) return JSON.stringify({ masterKey: 'fixture-only' });
  25. if (file.endsWith('state.json')) return JSON.stringify(state);
  26. if (file.endsWith('bundle.json')) return JSON.stringify(bundle);
  27. if (file.includes('cloud-prompt-preview-')) return JSON.stringify(preview);
  28. if (file.includes('provision-cloud-candidate-')) return candidate;
  29. throw Error('Unexpected read ' + file);
  30. },
  31. openSync() { calls.push('lock'); if (concurrent) state.actions.cloudPrompt = { attempted: true, confirmedAt: 'other', proof: 'preserve' }; return 7; },
  32. writeFileSync(file, data) { file = String(file); if (file.endsWith('state.json.next')) pending = JSON.parse(data); else writes.set(file, data); },
  33. renameSync() { state = pending; }, closeSync() {}, unlinkSync() {},
  34. };
  35. const fetch = async (url, init = {}) => {
  36. requests.push({ url, method: init.method || 'GET', body: init.body });
  37. if (url.startsWith('https://s3.')) return { ok: true, arrayBuffer: async () => badAsset ? Buffer.from('wrong asset') : bytes };
  38. if (init.method === 'PUT') { const body = JSON.parse(init.body); remote = { ...remote, ...body, updatedAt: 'confirmed' }; return { ok: true, status: 200, json: async () => ({ updatedAt: 'confirmed' }) }; }
  39. return { ok: true, json: async () => remote };
  40. };
  41. const process = { argv: ['node', 'runner', '--stage=apply', '--tag=fixture-v101'], pid: 7, cwd: () => '/project' };
  42. let error;
  43. const run = new AsyncFunction('fs', 'assert', 'createHash', 'patchOnboarding', 'recordProgress', 'process', 'fetch', 'console', source);
  44. try { await run(fakeFs, assert, createHash, patchOnboarding, () => {}, process, fetch, { log() {} }); } catch (e) { error = e; }
  45. return { state, requests, writes, calls, remote, error };
  46. }
  47. test('apply rejects same bytes at a different URL after preview, before any PUT', async () => {
  48. const r = await fixture({ urlDrift: true }); assert.match(r.error.message, /完整元数据不一致/);
  49. assert.equal(r.requests.length, 0);
  50. });
  51. test('apply rejects cloud code drift and unrequested candidate edits', async () => {
  52. const drift = await fixture({ codeDrift: true }); assert.match(drift.error.message, /源码在预览后发生变化/);
  53. const edit = await fixture({ tamperedCandidate: true }); assert.match(edit.error.message, /指定提示词补丁/);
  54. assert.ok([...drift.requests, ...edit.requests].every(x => x.method !== 'PUT'));
  55. });
  56. test('apply checks public asset bytes before updating the function', async () => {
  57. const r = await fixture({ badAsset: true }); assert.match(r.error.message, /公开包摘要不一致/);
  58. assert.ok(r.requests.every(x => x.method !== 'PUT'));
  59. });
  60. test('apply locks before reading ledger and does not repeat a concurrent completed PUT', async () => {
  61. const r = await fixture({ concurrent: true }); assert.match(r.error.message, /已有动作记录/);
  62. assert.equal(r.requests.length, 0); assert.equal(r.state.actions.cloudPrompt.proof, 'preserve');
  63. assert.ok(r.calls.indexOf('lock') < r.calls.findIndex(x => x.endsWith('state.json')));
  64. });
  65. test('apply changes only one verified function and preserves unrelated live code', async () => {
  66. const r = await fixture(); assert.equal(r.error, undefined);
  67. const puts = r.requests.filter(x => x.method === 'PUT'); assert.equal(puts.length, 1);
  68. assert.equal(puts[0].url, 'https://server.fmode.cn/parse/classes/Function/VtW1GT93Ax');
  69. assert.ok(r.remote.code.includes('function unrelated() { return "preserve"; }'));
  70. assert.equal(r.state.actions.cloudPrompt.receipt.sha256, hash(r.remote.code));
  71. assert.ok(r.writes.has('test-results/new-account-20261128/cloud-prompt-put-response-fixture-v101.json'));
  72. });