feat: add client self-service purchases and integration kit
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-15 17:33:52 +08:00
parent 68a2b4d892
commit cfcc9b386b
33 changed files with 2598 additions and 44 deletions

View File

@@ -0,0 +1,36 @@
# 固定天数新购 SDK (集成说明)
`purchase-sdk.mjs` 是桌面宿主可接入的无 UI 模块。它仅用于**已有客户**由管理员绑定的 product/customer 凭据购买固定天数新授权;不是注册、续费或支付结果的客户端自证。宿主负责安全导入管理员发放的 Bearer 购买凭据、固定可信公钥列表、持久化及界面。当前不提供客户账号登录接口。不得从服务器返回的 keyring 动态替换固定信任根。
```js
import { PurchaseClient } from './purchase-sdk.mjs';
// secureStore 必须是受 OS 保护的持久存储:load() 返回完整快照,
// saveAtomic(snapshot) 必须在同步落盘完成后才 resolve,且崩溃时不能产生部分状态。
const client = new PurchaseClient({
baseUrl: 'https://license.example/',
token: await host.getBoundCustomerToken(),
productId: host.productId,
installationId: host.installationId,
pinnedKeys: host.trustedSigningKeys, // [{key_id, public_key_pem, revoked:false}]
storage: secureStore,
});
const { plans } = await client.plans();
const order = await client.purchase(plans[0].id, plans[0].version, 'wechat');
host.renderPaymentQr(order.code_url); // 使用真实二维码库绘制,不要把 code_url 输出到日志
// 付款过程可轮询状态;网络不确定或重启后继续使用同一个 secureStore。
const payment = await client.status();
if (payment.status === 'paid') {
const { enabled } = await client.claim(); // 自动验证证书、激活并心跳
if (enabled) host.enableLicensedWork();
}
```
- `purchase` **先持久化完整输入和幂等键,再发送请求**。遇到超时/网络错误或重启,使用原套餐、版本、渠道重试 `purchase`;更换任一参数会抛出 `pending_purchase_conflict`。不要直接丢弃待支付状态或创建新键,以免重复付款。`status` 已知订单号时发送 `{order_no,installation_id}`,未收到下单响应时发送 `{idempotency_key,installation_id}` 恢复。服务端返回 `status`(created/paid)、`order_status` 和 `qr_expired`;二维码过期时 `code_url` 为空,不代表支付状态已改成 expired。订单终态需由宿主依据服务端结果和客服流程确认,SDK 不自动清除待支付快照。
- `claim` 要求支付已完成;未支付服务端返回 409 `purchase_not_paid`。`installationId` 仅绑定购买订单;服务端另行生成实例 UUID。SDK 校验 claim 返回的 `instance_id` 为有效 UUID,并将它与 secret/license_key/license_id、激活幂等键一起原子保存。后续激活、心跳及证书/租约归属验证均使用保存的 `credentials.instance_id`,并核对证书中的 license_id;重启恢复不会用安装标识替代实例 UUID。`activate` 使用服务端 `/api/v1/activation/instances/{instance_id}` 的 `license-v2` 证书;`heartbeat` 使用 `/api/v1/instances/{instance_id}/heartbeat` 的 `lease-v2` 租约。心跳请求键和 `client_time` 同时持久化;不确定结果时重试同一请求。若服务端明确返回 409 且需要新心跳,可在确认状态后调用 `heartbeat({resetConflict:true})` 清除旧请求,再发起新请求。
- `heartbeat` 在 `acceptLease` 校验通过且 `saveAtomic` 完成之后才返回 `enabled`。宿主在所有异常时不得根据 HTTP 200、旧内存状态或未落盘状态启用业务;按 `next_heartbeat_seconds` 安排下次心跳,并以 `offlineEnabled()` 检查离线许可。冻结、撤销和过期租约返回 `enabled:false`。
- 服务端非成功响应仅识别购买业务码白名单(例如 `plan_version_conflict`、`purchase_not_paid`、`idempotency_conflict`、`authorization_unavailable`);其他错误统一为 `http_<status>`,不显示任意原始 `message`。`purchase_not_paid` 保留订单并限频查询;版本冲突要重新展示套餐;授权或实例不可用时停止领取。`plans/purchase/status/claim` 使用 Bearer,token 只在 Authorization 头;实例 secret 仅在激活/心跳 JSON 请求体。调用者不要记录请求体、Authorization、二维码原文、存储快照或异常的底层网络对象。SDK 错误只有稳定代码,不包含服务端响应或敏感字段。所有请求接受 `{signal}` 并受 `timeoutMs` 控制;`request_aborted`/`network_error` 可按原状态恢复。
- 购买前没有实例,不适用绑定已有实例的 `yhy-license-trust` v1 文件。受控渠道预置产品 ID 与可信公钥;如还要求固定预期客户 ID,宿主应在接收证书前独立核对,不能只依赖首次证书自报的 customer_id。存储应为每个 product + installation 隔离的事务性安全存储,单实例串行调用 SDK;多个进程/窗口同时购买时宿主须加跨进程锁或 CAS。仅凭 SDK 无法保证机器上的机密性、跨进程隔离或扫码真实性。不要在本地开发示例中存真实 token/secret。
校验:`node --test client/test-purchase-sdk.mjs`。以上字段已与后端实现会话确认;接入实际服务前仍需运行真实服务集成测试。

View File

@@ -0,0 +1,142 @@
import { randomUUID } from 'node:crypto';
import { acceptLease, canRunOffline, verifyEnvelope } from './verify.mjs';
export class PurchaseError extends Error {
constructor(code, status) { super(code); this.name = 'PurchaseError'; this.code = code; this.status = status; }
}
const valid = value => typeof value === 'string' && value.length > 0;
const uuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
const copy = value => structuredClone(value);
const purchaseCodes = new Set(['invalid_purchase_credential', 'invalid_request', 'not_found', 'idempotency_conflict', 'plan_disabled', 'plan_version_conflict', 'purchase_not_paid', 'authorization_unavailable', 'instance_conflict', 'authorization_pending', 'channel_unavailable', 'credentials_unavailable']);
export class PurchaseClient {
constructor({ baseUrl, token, productId, installationId, pinnedKeys, storage, fetchImpl = fetch, clock = () => Date.now(), timeoutMs = 15000 }) {
let url;
try { url = new URL(baseUrl); } catch { throw new PurchaseError('invalid_origin'); }
if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password) throw new PurchaseError('invalid_origin');
if (!valid(token) || !valid(installationId) || !Number.isSafeInteger(productId) || productId <= 0 || !Array.isArray(pinnedKeys) || !storage?.load || !storage?.saveAtomic || !Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new PurchaseError('invalid_config');
this.origin = url; this.token = token; this.productId = productId; this.installationId = installationId;
this.keys = pinnedKeys; this.storage = storage; this.fetch = fetchImpl; this.clock = clock; this.timeoutMs = timeoutMs;
}
async load() {
let state;
try { state = await this.storage.load(); } catch { throw new PurchaseError('storage_load_failed'); }
if (state && (state.installation_id !== this.installationId || state.product_id !== this.productId)) throw new PurchaseError('storage_scope_mismatch');
if (state?.credentials && !uuid(state.credentials.instance_id)) throw new PurchaseError('invalid_instance');
return state ? copy(state) : { installation_id: this.installationId, product_id: this.productId };
}
async save(state) {
try { await this.storage.saveAtomic(copy(state)); } catch { throw new PurchaseError('storage_save_failed'); }
}
async request(path, body, { bearer = false, key, signal } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
const abort = () => controller.abort();
if (signal) { if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once: true }); }
try {
if (controller.signal.aborted) throw new PurchaseError('request_aborted');
const headers = { 'content-type': 'application/json' };
if (bearer) headers.authorization = `Bearer ${this.token}`;
if (key) headers['Idempotency-Key'] = key;
const response = await this.fetch(new URL(path, this.origin), { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal, redirect: 'error' });
if (!response.ok) {
let code;
if (bearer) {
try {
const body = await response.json();
if (typeof body?.error?.code === 'string' && purchaseCodes.has(body.error.code)) code = body.error.code;
} catch { /* Malformed responses use the HTTP status fallback. */ }
}
throw new PurchaseError(code || `http_${response.status}`, response.status);
}
const json = await response.json();
if (!json || typeof json.data !== 'object' || json.data === null) throw new PurchaseError('invalid_response');
return json.data;
} catch (error) {
if (error instanceof PurchaseError) throw error;
throw new PurchaseError(controller.signal.aborted ? 'request_aborted' : 'network_error');
} finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
}
async plans(options = {}) {
return this.request('api/v1/client/plans', { installation_id: this.installationId }, { bearer: true, signal: options.signal });
}
async purchase(planId, planVersion, channel, options = {}) {
if (!valid(channel) || !(valid(planId) || Number.isSafeInteger(planId)) || !(valid(planVersion) || Number.isSafeInteger(planVersion))) throw new PurchaseError('invalid_purchase');
const state = await this.load();
const input = { plan_id: planId, plan_version: planVersion, installation_id: this.installationId, channel };
if (state.purchase && JSON.stringify(state.purchase.input) !== JSON.stringify(input)) throw new PurchaseError('pending_purchase_conflict');
if (!state.purchase) { state.purchase = { input, key: randomUUID() }; await this.save(state); }
const data = await this.request('api/v1/client/purchases', state.purchase.input, { bearer: true, key: state.purchase.key, signal: options.signal });
if (!valid(data.order_no)) throw new PurchaseError('invalid_response');
if (state.purchase.order_no && state.purchase.order_no !== data.order_no) throw new PurchaseError('order_mismatch');
state.purchase.order_no = data.order_no;
await this.save(state);
return data;
}
async status(options = {}) {
const state = await this.load();
if (!state.purchase) throw new PurchaseError('no_pending_purchase');
const lookup = state.purchase.order_no ? { order_no: state.purchase.order_no } : { idempotency_key: state.purchase.key };
const data = await this.request('api/v1/client/purchases/status', { ...lookup, installation_id: this.installationId }, { bearer: true, signal: options.signal });
if (state.purchase.order_no && data.order_no !== state.purchase.order_no) throw new PurchaseError('order_mismatch');
if (!state.purchase.order_no && valid(data.order_no)) { state.purchase.order_no = data.order_no; await this.save(state); }
return data;
}
async claim(options = {}) {
const state = await this.load();
if (state.credentials && state.activation_key) return this.activate(options);
if (!state.purchase?.order_no) await this.status(options);
const current = await this.load();
if (!current.purchase?.order_no) throw new PurchaseError('order_unresolved');
const data = await this.request('api/v1/client/purchases/claim', { order_no: current.purchase.order_no, installation_id: this.installationId }, { bearer: true, signal: options.signal });
if (!uuid(data.instance_id) || !valid(data.secret) || !valid(data.license_key) || !Number.isSafeInteger(data.license_id) || data.license_id <= 0) throw new PurchaseError('invalid_claim');
if (current.credentials && (current.credentials.instance_id !== data.instance_id || current.credentials.secret !== data.secret || current.credentials.license_key !== data.license_key || current.credentials.license_id !== data.license_id)) throw new PurchaseError('claim_conflict');
if (!current.credentials) {
current.lease = null;
current.certificate = null;
current.customer_id = null;
}
current.credentials = { instance_id: data.instance_id, secret: data.secret, license_key: data.license_key, license_id: data.license_id };
if (!current.activation_key) current.activation_key = randomUUID();
await this.save(current);
return this.activate(options);
}
async activate(options = {}) {
const state = await this.load();
if (!state.credentials || !state.activation_key) throw new PurchaseError('no_credentials');
if (!uuid(state.credentials.instance_id)) throw new PurchaseError('invalid_instance');
const data = await this.request(`api/v1/activation/instances/${encodeURIComponent(state.credentials.instance_id)}`, { secret: state.credentials.secret, license_key: state.credentials.license_key }, { key: state.activation_key, signal: options.signal });
const p = verifyEnvelope(data.certificate, this.keys);
if (p.version !== 'license-v2' || p.instance_id !== state.credentials.instance_id || p.product_id !== this.productId || p.license_id !== state.credentials.license_id || (state.customer_id && p.customer_id !== state.customer_id)) throw new PurchaseError('certificate_scope_mismatch');
if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(p.starts_at) || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(p.expires_at) || !Number.isFinite(Date.parse(p.starts_at)) || !Number.isFinite(Date.parse(p.expires_at)) || Date.parse(p.starts_at) > this.clock() || Date.parse(p.expires_at) <= this.clock()) throw new PurchaseError('certificate_not_active');
if (state.certificate && (state.certificate.payload.customer_id !== p.customer_id || state.certificate.payload.license_id !== p.license_id)) throw new PurchaseError('certificate_mismatch');
state.customer_id = p.customer_id; state.certificate = data.certificate;
await this.save(state);
return this.heartbeat(options);
}
async heartbeat(options = {}) {
const state = await this.load();
if (!state.credentials || !state.certificate) throw new PurchaseError('not_activated');
const cert = verifyEnvelope(state.certificate, this.keys);
if (cert.version !== 'license-v2' || cert.instance_id !== state.credentials.instance_id || cert.product_id !== this.productId || cert.customer_id !== state.customer_id || cert.license_id !== state.credentials.license_id || Date.parse(cert.expires_at) <= this.clock()) throw new PurchaseError('certificate_scope_mismatch');
if (!state.heartbeat_request) { state.heartbeat_request = { key: randomUUID(), client_time: new Date(this.clock()).toISOString() }; await this.save(state); }
let data;
try {
data = await this.request(`api/v1/instances/${encodeURIComponent(state.credentials.instance_id)}/heartbeat`, { secret: state.credentials.secret, client_time: state.heartbeat_request.client_time }, { key: state.heartbeat_request.key, signal: options.signal });
} catch (error) {
if (error.status === 409 && options.resetConflict === true) { state.heartbeat_request = null; await this.save(state); }
throw error;
}
const lease = acceptLease(data, this.keys, state.credentials.instance_id, state.lease, this.clock());
if (Date.parse(data.payload.entitlement_expires_at) !== Date.parse(cert.expires_at)) throw new PurchaseError('entitlement_mismatch');
state.lease = lease; state.heartbeat_request = null;
await this.save(state);
return { enabled: lease.enabled, next_heartbeat_seconds: data.next_heartbeat_seconds };
}
async offlineEnabled() {
const state = await this.load();
if (!state.credentials || !state.certificate || !state.lease) return false;
const p = verifyEnvelope(state.certificate, this.keys);
return p.version === 'license-v2' && p.instance_id === state.credentials.instance_id && p.product_id === this.productId && p.customer_id === state.customer_id && Number.isFinite(Date.parse(p.starts_at)) && Number.isFinite(Date.parse(p.expires_at)) && this.clock() >= Date.parse(p.starts_at) && this.clock() < Date.parse(p.expires_at) && canRunOffline(state.lease, state.credentials.instance_id, this.clock());
}
}

View File

@@ -0,0 +1,159 @@
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' });
});

View File

@@ -0,0 +1,52 @@
import { createHash, createPublicKey, verify } from 'node:crypto';
const fields = {
'license-v2': ['version', 'instance_id', 'license_id', 'customer_id', 'product_id', 'starts_at', 'expires_at', 'key_id'],
'lease-v2': ['version', 'instance_id', 'state', 'server_time', 'entitlement_expires_at', 'lease_expires_at', 'key_id'],
};
export function canonical(payload) {
const names = fields[payload.version];
if (!names || Object.keys(payload).length !== names.length) throw new Error('unsupported_payload');
return names.map(name => {
const value = payload[name];
if (['license_id', 'customer_id', 'product_id'].includes(name)) {
if (!Number.isSafeInteger(value) || value <= 0) throw new Error('invalid_id');
} else if (typeof value !== 'string' || !value || /[\r\n\0]/.test(value)) throw new Error('invalid_field');
return `${name}=${value}`;
}).join('\n');
}
export function verifyEnvelope(envelope, pinnedKeys) {
const p = envelope.payload;
if (!p || !/^[a-zA-Z0-9_-]{1,64}$/.test(p.key_id ?? '')) throw new Error('invalid_key_id');
const matches = pinnedKeys.filter(k => k.key_id === p.key_id);
if (matches.length !== 1 || matches[0].revoked) throw new Error('unknown_or_revoked_key');
const key = createPublicKey(matches[0].public_key_pem);
if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails.namedCurve !== 'prime256v1') throw new Error('invalid_key');
const text = canonical(p);
if (typeof envelope.signature !== 'string' || !/^[A-Za-z0-9+/]+$/.test(envelope.signature)) throw new Error('invalid_signature');
if (!verify('sha256', Buffer.from(text), key, Buffer.from(envelope.signature, 'base64'))) throw new Error('invalid_signature');
if (envelope.canonical_sha256 && createHash('sha256').update(text).digest('hex') !== envelope.canonical_sha256) throw new Error('invalid_digest');
return p;
}
function instant(value) {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/.test(value)) throw new Error('invalid_time');
const time = Date.parse(value);
if (!Number.isFinite(time)) throw new Error('invalid_time');
return time;
}
// Persist the returned state atomically in trusted storage BEFORE enabling work.
export function acceptLease(envelope, pinnedKeys, expectedInstance, prior, now) {
const p = verifyEnvelope(envelope, pinnedKeys);
if (p.version !== 'lease-v2' || p.instance_id !== expectedInstance || !Number.isFinite(now)) throw new Error('instance_or_version');
const server = instant(p.server_time), expiry = instant(p.lease_expires_at), entitlement = instant(p.entitlement_expires_at);
const previous = prior ?? { instance_id: expectedInstance, server_high_water: 0, local_high_water: 0, lease_expires: 0, enabled: false };
if (previous.instance_id !== expectedInstance || !Number.isFinite(previous.server_high_water) || !Number.isFinite(previous.local_high_water)) throw new Error('invalid_state');
if (now < previous.local_high_water || server < previous.server_high_water) throw new Error('clock_or_server_rollback');
if (Math.abs(server - now) > 300000 || expiry > entitlement || expiry > server + 14 * 86400000) throw new Error('lease_bounds');
if (!['active', 'frozen', 'revoked', 'expired', 'not_started', 'not_activated'].includes(p.state)) throw new Error('invalid_state');
const enabled = p.state === 'active' && now < expiry && now < entitlement;
return { instance_id: expectedInstance, server_high_water: server, local_high_water: now, lease_expires: expiry, enabled };
}
export function canRunOffline(state, expectedInstance, now) {
return state?.instance_id === expectedInstance && state.enabled === true && Number.isFinite(now) && now >= state.local_high_water && now < state.lease_expires;
}