test-onboarding-publish.mjs 5.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { test } from 'node:test';
  2. import fs from 'node:fs';
  3. import assert from 'node:assert/strict';
  4. import { createHash } from 'node:crypto';
  5. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
  6. const source = fs.readFileSync(new URL('./publish-onboarding-bundle.mjs', import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, '');
  7. const bytes = Buffer.from('credential-free generic fixture'), sha256 = createHash('sha256').update(bytes).digest('hex');
  8. const key = 'publishBundle_' + sha256.slice(0, 16);
  9. async function fixture({ completedOnLock = false, matchingTest = true, corruptDownload = false, matchingProbe = true } = {}) {
  10. let state = { userId: 'owner', actions: {
  11. publishBundle: { attempted: true, confirmedAt: 'old', sha256: 'b'.repeat(64), proof: 'must-preserve' },
  12. onboardingLinux101Approved: { confirmedAt: 'tested', exitCode: 0, bundleSha256: matchingTest ? sha256 : 'c'.repeat(64) },
  13. localCandidate: { bundleSha256: sha256 }, trialCleanOutput: { confirmedAt: 'clean', bundleSha256: matchingProbe ? sha256 : 'e'.repeat(64) }, trialChatReady: { proof: {} }, trialFilesV3: { proof: {} },
  14. } }, pending;
  15. const writes = new Map(), requests = [], calls = [];
  16. const fakeFs = {
  17. openSync() { calls.push('lock'); if (completedOnLock) state.actions[key] = { attempted: true, confirmedAt: 'concurrent', proof: 'concurrent-proof' }; return 7; },
  18. readFileSync(file) {
  19. calls.push('read:' + file);
  20. if (file.endsWith('state.json')) return JSON.stringify(state);
  21. if (file.endsWith('receipt.json')) return JSON.stringify({ version: '1.0.1', sha256, archive: '/fixture/archive.tar.gz' });
  22. if (file.endsWith('archive.tar.gz')) return bytes;
  23. if (file.endsWith('account.json')) return JSON.stringify({ userId: 'owner', token: 'private-fixture' });
  24. throw Error('unexpected read ' + file);
  25. },
  26. writeFileSync(file, data, options) {
  27. file = String(file);
  28. if (options?.flag === 'wx') assert.ok(!writes.has(file), 'immutable receipt must not be overwritten');
  29. if (file.endsWith('state.json.next')) pending = JSON.parse(data); else writes.set(file, data);
  30. },
  31. renameSync() { state = pending; }, closeSync() {}, unlinkSync() {},
  32. };
  33. const fetch = async (url, init = {}) => {
  34. requests.push({ url: String(url), method: init.method || 'GET' });
  35. 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' }) };
  36. if (requests.length === 2) return { ok: true, status: 200 };
  37. return { ok: true, status: 200, arrayBuffer: async () => corruptDownload ? Buffer.from('corrupt') : bytes };
  38. };
  39. const process = { argv: ['node', 'runner', '--stage=upload', '--package-dir=/fixture/selected'], pid: 7, cwd: () => '/project' };
  40. const run = new AsyncFunction('fs', 'assert', 'createHash', 'recordProgress', 'process', 'fetch', 'console', source);
  41. let error;
  42. try { await run(fakeFs, assert, createHash, () => {}, process, fetch, { log() {} }); } catch (e) { error = e; }
  43. return { state, writes, requests, calls, error };
  44. }
  45. test('new package action is checked after lock and never repeats a concurrent completed upload', async () => {
  46. const r = await fixture({ completedOnLock: true });
  47. assert.match(r.error.message, /已有记录/); assert.equal(r.requests.length, 0);
  48. assert.equal(r.state.actions[key].proof, 'concurrent-proof');
  49. assert.ok(r.calls.indexOf('lock') < r.calls.findIndex(x => x.endsWith('state.json')));
  50. });
  51. test('old successful tests cannot authorize uploading a different package hash', async () => {
  52. const r = await fixture({ matchingTest: false });
  53. assert.match(r.error.message, /摘要一致/); assert.equal(r.requests.length, 0);
  54. });
  55. test('new package uses distinct action and immutable evidence while retaining old upload', async () => {
  56. const r = await fixture(); assert.equal(r.error, undefined);
  57. assert.deepEqual(r.requests.map(x => x.method), ['POST', 'PUT', 'GET']);
  58. assert.equal(r.state.actions.publishBundle.proof, 'must-preserve');
  59. assert.equal(r.state.actions[key].receipt.sha256, sha256);
  60. assert.ok([...r.writes.keys()].some(x => x.endsWith('bundle-published-' + sha256.slice(0, 16) + '-receipt.json')));
  61. assert.ok(!r.writes.has('test-results/new-account-20261128/bundle-published-receipt.json'));
  62. assert.ok(!r.writes.has('.local-backup/new-account-20261128/bundle-upload-ticket.json'));
  63. });
  64. test('corrupt public readback does not update bundle pointer or confirm success', async () => {
  65. const r = await fixture({ corruptDownload: true });
  66. assert.match(r.error.message, /摘要不一致/);
  67. assert.equal(r.writes.has('cloud/onboarding/bundle.json'), false);
  68. assert.equal(r.state.actions[key].confirmedAt, undefined);
  69. });
  70. test('a real probe of an older bundle cannot authorize publishing a new bundle', async () => {
  71. const r = await fixture({ matchingProbe: false });
  72. assert.match(r.error.message, /不属于当前包摘要/); assert.equal(r.requests.length, 0);
  73. });