Files
yhy-mager/backend/internal/httpapi/integration_assets/client/test-purchase-sdk.mjs
xiewenjun cfcc9b386b
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-15 17:33:52 +08:00

160 lines
10 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { generateKeyPairSync, sign } from 'node:crypto';
import { canonical } from './verify.mjs';
import { PurchaseClient } from './purchase-sdk.mjs';
const now = Date.parse('2026-10-15T08:00:00Z');
const instance = '00000000-0000-4000-8000-000000000001';
const claimedInstance = '00000000-0000-4000-8000-000000000002';
const pair = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const keys = [{ key_id: 'fixed', public_key_pem: pair.publicKey.export({ type: 'spki', format: 'pem' }) }];
const cert = (overrides = {}, key = pair.privateKey) => {
const payload = { version: 'license-v2', instance_id: claimedInstance, license_id: 10, customer_id: 20, product_id: 30, starts_at: '2026-10-14T00:00:00Z', expires_at: '2026-10-20T00:00:00Z', key_id: 'fixed', ...overrides };
return { payload, signature: sign('sha256', Buffer.from(canonical(payload)), key).toString('base64').replace(/=+$/, '') };
};
const lease = (overrides = {}, key = pair.privateKey) => {
const payload = { version: 'lease-v2', instance_id: claimedInstance, state: 'active', server_time: '2026-10-15T08:00:00Z', entitlement_expires_at: '2026-10-20T00:00:00Z', lease_expires_at: '2026-10-15T08:10:00Z', key_id: 'fixed', ...overrides };
return { payload, signature: sign('sha256', Buffer.from(canonical(payload)), key).toString('base64').replace(/=+$/, ''), next_heartbeat_seconds: 60 };
};
function harness() {
let persisted = null; let failSave = false; let failPath = null; let certificate = cert(); let signedLease = lease(); let claimInstance = claimedInstance; const calls = [];
const storage = { async load() { return structuredClone(persisted); }, async saveAtomic(value) { if (failSave) throw Error('disk failed'); persisted = structuredClone(value); } };
const fetchImpl = async (url, options) => {
const path = new URL(url).pathname; const body = JSON.parse(options.body);
calls.push({ path, body, key: options.headers['Idempotency-Key'], authorization: options.headers.authorization });
if (path === failPath) throw Error('secret must never appear in error');
let data;
if (path.endsWith('/plans')) data = { plans: [{ plan_id: 1, plan_version: 2, license_days: 30 }] };
else if (path.endsWith('/purchases')) data = { order_no: 'ord-1', code_url: 'weixin://example', status: 'created', amount_cents: 3000, currency: 'CNY', license_days: 30, expires_at: '2026-10-15T08:30:00Z' };
else if (path.endsWith('/status')) data = { order_no: 'ord-1', status: 'paid', order_status: 'issued', qr_expired: false };
else if (path.endsWith('/claim')) data = { instance_id: claimInstance, secret: 'private-secret', license_key: 'private-license', license_id: 10 };
else if (path.includes('/activation/')) data = { certificate };
else if (path.endsWith('/heartbeat')) data = signedLease;
else throw Error('unknown path');
return { ok: true, json: async () => ({ data }) };
};
const client = () => new PurchaseClient({ baseUrl: 'https://license.example/', token: 'private-token', productId: 30, installationId: instance, pinnedKeys: keys, storage, fetchImpl, clock: () => now });
return { client, calls, storage, get state() { return persisted; }, set failSave(v) { failSave = v; }, set failPath(v) { failPath = v; }, set certificate(v) { certificate = v; }, set signedLease(v) { signedLease = v; }, set claimInstance(v) { claimInstance = v; } };
}
test('restart after ambiguous purchase reuses persisted key and request, never changes plan', async () => {
const h = harness(); h.failPath = '/api/v1/client/purchases';
await assert.rejects(h.client().purchase(1, 2, 'wechat'), { code: 'network_error' });
const savedKey = h.state.purchase.key;
await assert.rejects(h.client().purchase(2, 2, 'alipay'), { code: 'pending_purchase_conflict' });
h.failPath = null;
const result = await h.client().purchase(1, 2, 'wechat');
assert.equal(result.order_no, 'ord-1');
assert.equal(h.calls.at(-1).key, savedKey);
assert.equal(h.calls.at(-1).body.channel, 'wechat');
assert.equal((await h.client().status()).status, 'paid');
assert.equal(h.calls.at(-1).authorization, 'Bearer private-token');
assert.deepEqual(h.calls.at(-1).body, { order_no: 'ord-1', installation_id: instance });
});
test('status recovers order by the persisted purchase key after a lost response', async () => {
const h = harness(); h.failPath = '/api/v1/client/purchases';
await assert.rejects(h.client().purchase(1, 2, 'wechat'), { code: 'network_error' });
h.failPath = null;
const result = await h.client().status();
assert.equal(result.order_no, 'ord-1');
assert.deepEqual(h.calls.at(-1).body, { idempotency_key: h.state.purchase.key, installation_id: instance });
assert.equal(h.state.purchase.order_no, 'ord-1');
});
test('save failure prevents placing purchase, claim and heartbeat enabling', async () => {
const h = harness(); h.failSave = true;
await assert.rejects(h.client().purchase(1, 2, 'wechat'));
assert.equal(h.calls.length, 0);
h.failSave = false;
await h.client().purchase(1, 2, 'wechat');
h.failSave = true;
await assert.rejects(h.client().claim());
assert.equal(h.calls.some(x => x.path.endsWith('/activation/instances/' + claimedInstance)), false);
h.failSave = false;
await h.client().claim();
assert.equal(await h.client().offlineEnabled(), true);
const before = h.state.lease;
h.failSave = true;
await assert.rejects(h.client().heartbeat());
assert.deepEqual(h.state.lease, before);
});
test('restart after claim persists credentials retries activation without another claim', async () => {
const h = harness();
await h.client().purchase(1, 2, 'wechat');
h.failPath = `/api/v1/activation/instances/${claimedInstance}`;
await assert.rejects(h.client().claim(), { code: 'network_error' });
const key = h.state.activation_key;
assert.equal(h.state.credentials.secret, 'private-secret');
assert.equal(h.state.credentials.instance_id, claimedInstance);
assert.notEqual(h.state.credentials.instance_id, instance);
h.failPath = null;
assert.equal((await h.client().claim()).enabled, true);
assert.equal(h.calls.filter(x => x.path.endsWith('/claim')).length, 1);
assert.equal(h.calls.filter(x => x.path.includes('/activation/')).at(-1).key, key);
assert.equal(h.calls.at(-1).path, `/api/v1/instances/${claimedInstance}/heartbeat`);
assert.equal(h.calls.filter(x => x.path.includes('/activation/')).at(-1).path, `/api/v1/activation/instances/${claimedInstance}`);
assert.equal(await h.client().offlineEnabled(), true);
});
test('restart rejects a stored instance changed from the signed certificate', async () => {
const h = harness();
await h.client().purchase(1, 2, 'wechat');
await h.client().claim();
const state = await h.storage.load();
state.credentials.instance_id = '00000000-0000-4000-8000-000000000003';
await h.storage.saveAtomic(state);
assert.equal(await h.client().offlineEnabled(), false);
await assert.rejects(h.client().claim(), { code: 'certificate_scope_mismatch' });
});
test('claim rejects malformed instance UUID before saving credentials or activating', async () => {
for (const invalid of [undefined, '', 'installation-only', '../../another-path', '00000000-0000-0000-0000-000000000000']) {
const h = harness(); h.claimInstance = invalid;
await h.client().purchase(1, 2, 'wechat');
await assert.rejects(h.client().claim(), { code: 'invalid_claim' });
assert.equal(h.state.credentials, undefined);
assert.equal(h.calls.some(x => x.path.includes('/activation/')), false);
}
});
test('forged certificate, wrong product and wrong instance fail before enable', async () => {
for (const certificate of [cert({}, generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey), cert({ product_id: 31 }), cert({ instance_id: 'other' }), cert({ instance_id: instance }), cert({ license_id: 11 })]) {
const h = harness(); h.certificate = certificate;
await h.client().purchase(1, 2, 'wechat');
await assert.rejects(h.client().claim());
assert.equal(h.state.lease, null);
assert.equal(await h.client().offlineEnabled(), false);
}
});
test('forged or foreign lease cannot enable and request remains replayable', async () => {
for (const signed of [lease({}, generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey), lease({ instance_id: 'other' }), lease({ instance_id: instance })]) {
const h = harness(); h.signedLease = signed;
await h.client().purchase(1, 2, 'wechat');
await assert.rejects(h.client().claim());
assert.ok(h.state.heartbeat_request.key);
assert.equal(await h.client().offlineEnabled(), false);
}
});
test('only allowlisted purchase errors are exposed to the host', async () => {
const storage = { load: async () => null, saveAtomic: async () => {} };
const makeClient = code => new PurchaseClient({ baseUrl: 'https://license.example/', token: 'private-token', productId: 30, installationId: instance, pinnedKeys: keys, storage, fetchImpl: async () => ({ ok: false, status: 409, json: async () => ({ error: { code, message: 'private-secret' } }) }) });
await assert.rejects(makeClient('purchase_not_paid').plans(), error => error.code === 'purchase_not_paid' && error.status === 409 && !error.message.includes('private-'));
await assert.rejects(makeClient('private-secret').plans(), error => error.code === 'http_409' && !error.message.includes('private-'));
});
test('timeout aborts and errors never echo sensitive response or tokens', async () => {
const h = harness(); await h.client().purchase(1, 2, 'wechat');
h.failPath = '/api/v1/client/purchases/claim';
await assert.rejects(h.client().claim(), error => error.code === 'network_error' && !error.message.includes('private-'));
const controller = new AbortController(); controller.abort();
const c = h.client();
await assert.rejects(c.plans({ signal: controller.signal }), { code: 'request_aborted' });
const timeoutClient = new PurchaseClient({ baseUrl: 'https://license.example/', token: 'private-token', productId: 30, installationId: instance, pinnedKeys: keys, storage: h.storage, fetchImpl: (_url, { signal }) => new Promise((_resolve, reject) => signal.addEventListener('abort', () => reject(Error('private-token')), { once: true })), timeoutMs: 5 });
await assert.rejects(timeoutClient.plans(), { code: 'request_aborted' });
});