feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -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`。以上字段已与后端实现会话确认;接入实际服务前仍需运行真实服务集成测试。
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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' });
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "License Platform Client API",
|
||||
"version": "1.1.0",
|
||||
"description": "Client-facing instance APIs. Update checks return signed update-v1 metadata; admin sessions are never client credentials. See protocol.md for canonical signature and trust-root rules."
|
||||
"version": "1.2.0",
|
||||
"description": "Client-facing instance APIs. Update checks return signed update-v1 metadata; admin sessions are never client credentials. See protocol.md for canonical signature and trust-root rules. Restricted Bearer purchase flow is documented in purchase.md."
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
@@ -395,6 +395,187 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/client/plans": {
|
||||
"post": {
|
||||
"operationId": "listClientPlans",
|
||||
"summary": "List enabled fixed-day plans for bound product",
|
||||
"security": [
|
||||
{
|
||||
"PurchaseBearer": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PurchaseInstallation"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "data envelope; consult purchase.md for recovery and trust rules",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/ClientPlans"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/client/purchases": {
|
||||
"post": {
|
||||
"operationId": "createClientPurchase",
|
||||
"summary": "Create or recover an idempotent purchase",
|
||||
"security": [
|
||||
{
|
||||
"PurchaseBearer": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/IdempotencyKey"
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PurchaseRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "data envelope; consult purchase.md for recovery and trust rules",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PurchaseOrder"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/client/purchases/status": {
|
||||
"post": {
|
||||
"operationId": "clientPurchaseStatus",
|
||||
"summary": "Recover by order_no or idempotency_key for same installation",
|
||||
"security": [
|
||||
{
|
||||
"PurchaseBearer": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PurchaseLookup"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "data envelope; consult purchase.md for recovery and trust rules",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PurchaseOrder"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/client/purchases/claim": {
|
||||
"post": {
|
||||
"operationId": "claimClientPurchase",
|
||||
"summary": "Claim same issued instance credentials idempotently",
|
||||
"security": [
|
||||
{
|
||||
"PurchaseBearer": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PurchaseClaim"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "data envelope; consult purchase.md for recovery and trust rules",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PurchaseCredentials"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
@@ -772,6 +953,273 @@
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PurchaseInstallation": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"installation_id"
|
||||
],
|
||||
"properties": {
|
||||
"installation_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PaymentPlan": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"product_id",
|
||||
"code",
|
||||
"name",
|
||||
"amount_cents",
|
||||
"currency",
|
||||
"license_days",
|
||||
"enabled",
|
||||
"version"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"product_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"code": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"amount_cents": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"currency": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"CNY"
|
||||
]
|
||||
},
|
||||
"license_days": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
"ClientPlans": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"plans",
|
||||
"channels",
|
||||
"license_duration",
|
||||
"purchase_mode"
|
||||
],
|
||||
"properties": {
|
||||
"plans": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/PaymentPlan"
|
||||
}
|
||||
},
|
||||
"channels": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"alipay",
|
||||
"wechat"
|
||||
]
|
||||
}
|
||||
},
|
||||
"license_duration": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"fixed_days_from_payment"
|
||||
]
|
||||
},
|
||||
"purchase_mode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"new_purchase"
|
||||
]
|
||||
},
|
||||
"customer_setup": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PurchaseRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"plan_id",
|
||||
"plan_version",
|
||||
"installation_id",
|
||||
"channel"
|
||||
],
|
||||
"properties": {
|
||||
"plan_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"plan_version": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"installation_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"channel": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"alipay",
|
||||
"wechat"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"PurchaseLookup": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"installation_id"
|
||||
],
|
||||
"description": "Provide either order_no or original idempotency_key",
|
||||
"properties": {
|
||||
"installation_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"order_no": {
|
||||
"type": "string"
|
||||
},
|
||||
"idempotency_key": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PurchaseClaim": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"installation_id",
|
||||
"order_no"
|
||||
],
|
||||
"properties": {
|
||||
"installation_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"order_no": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PurchaseOrder": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"order_no",
|
||||
"status",
|
||||
"order_status",
|
||||
"code_url",
|
||||
"qr_expired",
|
||||
"expires_at",
|
||||
"amount_cents",
|
||||
"currency",
|
||||
"license_days",
|
||||
"channel"
|
||||
],
|
||||
"properties": {
|
||||
"order_no": {
|
||||
"type": "string"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"created",
|
||||
"paid"
|
||||
]
|
||||
},
|
||||
"order_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"pending_payment",
|
||||
"paid",
|
||||
"issued"
|
||||
]
|
||||
},
|
||||
"code_url": {
|
||||
"type": "string"
|
||||
},
|
||||
"qr_expired": {
|
||||
"type": "boolean",
|
||||
"description": "QR display expiry only; not proof of channel closure"
|
||||
},
|
||||
"expires_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"amount_cents": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"currency": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"CNY"
|
||||
]
|
||||
},
|
||||
"license_days": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"channel": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"alipay",
|
||||
"wechat"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"PurchaseCredentials": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"instance_id",
|
||||
"secret",
|
||||
"license_key",
|
||||
"license_id"
|
||||
],
|
||||
"properties": {
|
||||
"instance_id": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"secret": {
|
||||
"type": "string",
|
||||
"format": "password"
|
||||
},
|
||||
"license_key": {
|
||||
"type": "string",
|
||||
"format": "password"
|
||||
},
|
||||
"license_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"securitySchemes": {
|
||||
"PurchaseBearer": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"description": "Admin-issued 32-random-byte purchase credential, restricted to an existing customer/product; never an admin session"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
本资料对应当前平台实现,不是独立完成生产验收的 SDK。运行 API 基地址由部署方提供,例如 https://license.example.com。必须使用 HTTPS,并验证服务端证书。管理员接口仅用于交付实例凭据,不应封装到客户端中。
|
||||
|
||||
## 交付与激活
|
||||
## 授权获取方式
|
||||
|
||||
本协议保留管理员预创建实例的人工交付方式。对于客户端扫码新购,先阅读 purchase.md:管理员为既有客户/产品配置套餐并交付受限购买凭据;付款确认签发后由 claim 创建实例。新购前没有 instance_id,不能预先创建该笔实例或导入绑定旧实例的信任文件。两条路径在获得实例凭据后共用以下 license-v2 / lease-v2 激活与运行校验。
|
||||
|
||||
## 交付与激活(管理员预创建实例)
|
||||
|
||||
管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和secret。配置加密留存后管理员可重复查看并导出;旧实例仅存哈希时无法恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。
|
||||
|
||||
|
||||
24
backend/internal/httpapi/integration_assets/purchase.md
Normal file
24
backend/internal/httpapi/integration_assets/purchase.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# 客户端扫码新购(固定天数)
|
||||
|
||||
此路径只服务于管理员预配置的既有客户及产品,不提供自注册、续费或客户登录。另一条人工授权路径仍见 protocol.md。支付确认并签发授权不等于客户端已经启用;客户端还必须领取实例凭据、激活、验签证书及租约并原子保存。期限从服务端确认并签发时起算,按固定 24 小时天数,不是自然月。
|
||||
|
||||
## 购买前交付
|
||||
|
||||
管理员在生产环境创建客户、产品、启用套餐及绑定客户/产品的受限购买凭据。购买 Token 创建时只显示一次,只能通过受控渠道交给对应宿主;不能写入本 ZIP、安装包、URL、日志或浏览器 LocalStorage。客户端独立预置 HTTPS 根地址、产品 ID 和经可信渠道核对指纹的生产 P-256 公钥列表;不能从 keyring 发现接口自动建立信任。购买前尚无 instance_id,因此不能导入绑定现有实例的 yhy-license-trust v1 JSON。claim 后须核对签名证书的实例、产品、授权 ID;如部署方要求购买前固定客户 ID,宿主还需单独校验预期客户归属。当前购买凭据是可复制的 Bearer,并非机器硬件绑定或客户登录。
|
||||
|
||||
## Bearer 接口
|
||||
|
||||
四个接口均为 POST JSON,Authorization: Bearer <受限购买 Token>;token 不进入请求正文、URL 或日志。服务端先验证该凭据关联的客户和产品状态。套餐为 id, product_id, code, name, amount_cents, currency=CNY, license_days, enabled, version;金额使用整数分。渠道是全局可用渠道列表,不承诺套餐级支付渠道配置。
|
||||
|
||||
1. POST /api/v1/client/plans,正文 {"installation_id":"稳定安装标识"};data.plans 是已启用套餐,data.channels 为可用支付渠道。宿主只能选择、展示服务端价格与期限,不能决定客户归属、金额和签发者。
|
||||
2. POST /api/v1/client/purchases,头部 Idempotency-Key,正文 {"plan_id":1,"plan_version":1,"installation_id":"稳定安装标识","channel":"wechat"}。先在受 OS 保护的事务存储中保存完整参数和键,再发出请求。data 返回 order_no, status, order_status, code_url, qr_expired, expires_at, amount_cents, currency, license_days, channel。code_url 使用真实二维码组件绘制,不能视为付款凭证。
|
||||
3. POST /api/v1/client/purchases/status,正文 {"installation_id":"...","order_no":"..."};未收到下单响应时改用原 idempotency_key 恢复。status 为 created/paid;order_status 为 pending_payment/paid/issued。轮询应限频,429 按 Retry-After 退避。qr_expired 和 expires_at 仅为二维码展示期限,不表示支付渠道关单,不得自动换渠道重复下单。
|
||||
4. POST /api/v1/client/purchases/claim,正文 {"installation_id":"...","order_no":"..."},仅已付款且已签发时返回 data.instance_id, secret, license_key, license_id。claim 同订单重复请求恢复同一实例和 secret;若冻结、撤销或凭据已禁用,须停止自动领取并联系管理员。先原子持久化凭据及激活幂等键,才可调用 protocol.md 的激活和心跳接口。
|
||||
|
||||
installation_id 只绑定订单;服务端生成的 instance_id 是授权实例 UUID,后续激活、心跳、证书和租约检查均使用后者。客户端核对 license-v2 的 product_id、instance_id、license_id 和已知的 customer_id;签名 lease-v2 必须绑定同一实例,验签、状态和时钟检查后原子落盘才返回 enabled。请参阅 client/purchase-sdk.md;Node.js 20+ 参考实现依赖同目录 verify.mjs。宿主须提供 OS 保护存储、跨进程锁/CAS 和二维码 UI。其他语言尚无购买参考 SDK。
|
||||
|
||||
## 失败恢复
|
||||
|
||||
未收到下单响应时保持原参数和幂等键;网络失败可按同键恢复,不能任意清除待支付快照。plan_version_conflict 应刷新套餐并请用户重新确认;purchase_not_paid 应保留订单、限频查询;idempotency_conflict 应核对本地原请求;authorization_unavailable 与 instance_conflict 停止领取并交管理员。401 停用购买流程,429 有界退避,未知错误只显示固定文案。不得展示任意服务端原始 message,也不得在异常中回显 Token 或 secret。未实现领取 ACK 后关闭窗口,需妥善保护、按需停用或轮换购买凭据。
|
||||
|
||||
离线测试不能证明生产商户付款、公网通知、真实数据库迁移和实际桌面客户端集成已验收。
|
||||
Reference in New Issue
Block a user