import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const source = await readFile( new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8', ); function response(status, payload, jsonError = null) { return { status, ok: status >= 200 && status < 300, json: async () => { if (jsonError) throw jsonError; return payload; }, }; } function fixture(fetchImpl, options = {}) { const context = { Headers, AbortController, setTimeout, clearTimeout, console, Date, Math, Error, TypeError, Object, Array, String, Number, Promise, }; context.window = context; context.globalThis = context; vm.runInNewContext(source, context, { filename: 'admin-request-runtime.js' }); const runtime = context.VenixAdminRequestRuntime.create({ fetchImpl, locationImpl: options.locationImpl || { protocol: 'https:', hostname: 'panel.test' }, csrfToken: options.csrfToken || (() => 'a'.repeat(64)), cryptoImpl: { randomUUID: () => '11111111-2222-4333-8444-555555555555' }, taskReceiptValidator: payload => payload?.task_id === '42' && payload?.status_url === '/api/v1/tasks/42', setTimeoutImpl: options.setTimeoutImpl, clearTimeoutImpl: options.clearTimeoutImpl, }); return runtime; } async function rejection(promise) { try { await promise; assert.fail('Expected request to reject.'); } catch (error) { return error; } } // Reads stay header-light and may expose status metadata only when a caller // has an endpoint-specific protocol decision to make. { const calls = []; const runtime = fixture(async (url, options) => { calls.push({ url, options }); return response(200, { ok: true }); }); assert.deepEqual(await runtime.read('/api/read'), { ok: true }); const metadata = await runtime.read('/api/read-meta', { returnMeta: true }); assert.equal(metadata.status, 200); assert.deepEqual(metadata.payload, { ok: true }); assert.equal(calls.length, 2); assert.equal(calls[0].options.method, 'GET'); assert.equal(calls[0].options.headers.get('X-Admin-CSRF-Token'), null); assert.equal(calls[0].options.headers.get('Idempotency-Key'), null); } // A task mutation is sent exactly once with the canonical security and // idempotency headers, and only a strict HTTP 202 task receipt is accepted. { const calls = []; const runtime = fixture(async (url, options) => { calls.push({ url, options }); return response(202, { task_id: '42', status_url: '/api/v1/tasks/42' }); }); const receipt = await runtime.mutate('/api/task', { method: 'POST', body: { acknowledge: true }, response: 'task', }); assert.equal(receipt.task_id, '42'); assert.equal(calls.length, 1); assert.equal(calls[0].options.headers.get('X-Admin-CSRF-Token'), 'a'.repeat(64)); assert.equal(calls[0].options.headers.get('Idempotency-Key'), '11111111-2222-4333-8444-555555555555'); assert.equal(calls[0].options.body, JSON.stringify({ acknowledge: true })); } // Client-side preconditions fail before dispatch and remain safe to retry. for (const [name, options, code] of [ ['http', { locationImpl: { protocol: 'http:', hostname: 'panel.test' } }, 'https_required'], ['csrf', { csrfToken: () => 'invalid' }, 'csrf_missing'], ]) { let calls = 0; const runtime = fixture(async () => { calls += 1; return response(200, {}); }, options); const error = await rejection(runtime.mutate('/api/write', { body: {} })); assert.equal(error.code, code, `${name} precondition returned the wrong error.`); assert.equal(error.mutationMayHaveApplied, false); assert.equal(error.safeToRetry, true); assert.equal(calls, 0); } // The two public interfaces cannot be used to bypass their security role by // swapping safe and unsafe HTTP methods. { let calls = 0; const runtime = fixture(async () => { calls += 1; return response(200, {}); }); await assert.rejects(runtime.read('/api/read', { method: 'POST' }), TypeError); await assert.rejects(runtime.mutate('/api/write', { method: 'GET' }), TypeError); assert.equal(calls, 0); } // Explicit validation errors are known not to have applied; server failures, // transport loss and protocol-invalid receipts are fenced as unknown effect. { const validation = fixture(async () => response(422, { detail: '输入错误' })); const validationError = await rejection(validation.mutate('/api/write', { body: {} })); assert.equal(validationError.status, 422); assert.equal(validationError.mutationMayHaveApplied, false); assert.equal(validationError.safeToRetry, true); const server = fixture(async () => response(503, { detail: '暂不可用' })); const serverError = await rejection(server.mutate('/api/write', { body: {} })); assert.equal(serverError.mutationMayHaveApplied, true); assert.equal(serverError.safeToRetry, false); let transportCalls = 0; const transport = fixture(async () => { transportCalls += 1; throw new Error('connection reset'); }); const transportError = await rejection(transport.mutate('/api/write', { body: {} })); assert.equal(transportCalls, 1, 'The shared runtime must never replay a mutation.'); assert.equal(transportError.mutationMayHaveApplied, true); assert.equal(transportError.safeToRetry, false); const invalidReceipt = fixture(async () => response(200, { task_id: '42', status_url: '/api/v1/tasks/42' })); const receiptError = await rejection(invalidReceipt.mutate('/api/task', { body: {}, response: 'task', })); assert.equal(receiptError.code, 'invalid_task_receipt'); assert.equal(receiptError.mutationMayHaveApplied, true); assert.equal(receiptError.safeToRetry, false); } // Once timeout handling begins, the mutation is still dispatched only once // and the caller receives the unknown-effect contract. { let calls = 0; const runtime = fixture(async (url, options) => { calls += 1; assert.equal(options.signal.aborted, true); throw new Error('aborted'); }, { setTimeoutImpl: callback => { callback(); return 1; }, clearTimeoutImpl: () => {}, }); const error = await rejection(runtime.mutate('/api/slow', { body: {} })); assert.equal(calls, 1); assert.equal(error.code, 'timeout'); assert.equal(error.mutationMayHaveApplied, true); assert.equal(error.safeToRetry, false); } console.log('Administrator request runtime behavior checks passed.');