feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -85,6 +85,18 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
api.POST("/auth/logout", a.authenticated, a.logout)
|
||||
api.POST("/payments/:channel/notify", a.paymentNotify)
|
||||
api.POST("/payments/checkout", a.paymentCheckout)
|
||||
client := api.Group("/client", a.purchaseAuthenticated)
|
||||
client.POST("/plans", a.clientPlans)
|
||||
client.POST("/purchases", a.clientCreatePurchase)
|
||||
client.POST("/purchases/status", a.clientPurchaseStatus)
|
||||
client.POST("/purchases/claim", a.clientPurchaseClaim)
|
||||
purchaseAdmin := api.Group("", purchaseAdminBoundary, a.authenticated)
|
||||
purchaseAdmin.GET("/payment-plans", a.listPaymentPlans)
|
||||
purchaseAdmin.POST("/payment-plans", a.savePaymentPlan)
|
||||
purchaseAdmin.PUT("/payment-plans/:id", a.savePaymentPlan)
|
||||
purchaseAdmin.GET("/purchase-credentials", a.listPurchaseCredentials)
|
||||
purchaseAdmin.POST("/purchase-credentials", a.createPurchaseCredential)
|
||||
purchaseAdmin.PUT("/purchase-credentials/:id", a.updatePurchaseCredential)
|
||||
secured := api.Group("", a.authenticated)
|
||||
secured.GET("/me", a.me)
|
||||
secured.GET("/admins", a.listAdmins)
|
||||
|
||||
@@ -87,26 +87,33 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
|
||||
files := map[string][]byte{
|
||||
"README.md": []byte(`# 客户端接入参考包
|
||||
|
||||
阅读 protocol.md、upgrade.md 与 openapi.json。Python/Node SDK 提供 update-v1 验签、TTL、revision 检查、完整 HTTP 200 下载及长度/摘要校验;不支持 Range 续传。Installer 仅为应用回调,不替换程序、不重启、不健康检查或回滚,不执行任意命令。LicenseClient、canRun、可信时间、持久化 StateStore 与本地强制升级评估由应用实现,升级检查不能替代 license-v2/lease-v2 授权。
|
||||
先选择人工交付或扫码新购路径,阅读 protocol.md、purchase.md、upgrade.md 与 openapi.json。Python/Node SDK 提供 update-v1 验签、TTL、revision 检查、完整 HTTP 200 下载及长度/摘要校验;不支持 Range 续传。Installer 仅为应用回调,不替换程序、不重启、不健康检查或回滚,不执行任意命令。升级 SDK 不含完整 LicenseClient、canRun、可信时间、持久化 StateStore 与本地强制升级评估;Node 购买 SDK 覆盖新购后证书与租约检查,但宿主仍须提供受保护原子存储和跨进程锁。升级检查不能替代 license-v2/lease-v2 授权。
|
||||
|
||||
扫码新购提供 Node.js 参考 SDK client/purchase-sdk.mjs 与 client/verify.mjs;它依赖受控购买凭据、固定公钥、OS 保护存储和宿主二维码界面,其他语言需按 purchase.md 自行实现。ZIP 不包含真实购买凭据。
|
||||
|
||||
Python 3.11+、Node.js 20+。在 client 目录运行:
|
||||
python -m pip install -r requirements.txt
|
||||
python -m unittest test_update_sdk -v
|
||||
node test-update-sdk.mjs
|
||||
node --test test-purchase-sdk.mjs
|
||||
|
||||
测试使用本地密钥和模拟网络,不证明生产安装可用。test-vectors.json 仅包含 license-v2/lease-v2;update-v1 测试由测试脚本生成本地签名。
|
||||
测试使用本地密钥和模拟网络,不证明生产支付或安装可用。test-vectors.json 仅包含 license-v2/lease-v2;update-v1 测试由测试脚本生成本地签名。
|
||||
prompt.md 可提供给实现工程师。verification-keys.md 为当前部署公钥,须通过可信渠道核对指纹;test-vectors.json 的随机测试密钥绝不能导入生产。
|
||||
`),
|
||||
"verification-keys.md": []byte(keys),
|
||||
"prompt.md": []byte(kit.Prompt),
|
||||
"test-vectors.json": vectors,
|
||||
"client/update_sdk.py": mustReadClientAsset("client/update_sdk.py"),
|
||||
"client/update-sdk.mjs": mustReadClientAsset("client/update-sdk.mjs"),
|
||||
"client/test_update_sdk.py": mustReadClientAsset("client/test_update_sdk.py"),
|
||||
"client/test-update-sdk.mjs": mustReadClientAsset("client/test-update-sdk.mjs"),
|
||||
"client/requirements.txt": mustReadClientAsset("client/requirements.txt"),
|
||||
"verification-keys.md": []byte(keys),
|
||||
"prompt.md": []byte(kit.Prompt),
|
||||
"test-vectors.json": vectors,
|
||||
"client/update_sdk.py": mustReadClientAsset("client/update_sdk.py"),
|
||||
"client/update-sdk.mjs": mustReadClientAsset("client/update-sdk.mjs"),
|
||||
"client/test_update_sdk.py": mustReadClientAsset("client/test_update_sdk.py"),
|
||||
"client/test-update-sdk.mjs": mustReadClientAsset("client/test-update-sdk.mjs"),
|
||||
"client/requirements.txt": mustReadClientAsset("client/requirements.txt"),
|
||||
"client/purchase-sdk.mjs": mustReadClientAsset("client/purchase-sdk.mjs"),
|
||||
"client/verify.mjs": mustReadClientAsset("client/verify.mjs"),
|
||||
"client/test-purchase-sdk.mjs": mustReadClientAsset("client/test-purchase-sdk.mjs"),
|
||||
"client/purchase-sdk.md": mustReadClientAsset("client/purchase-sdk.md"),
|
||||
}
|
||||
for _, name := range []string{"protocol.md", "upgrade.md", "openapi.json"} {
|
||||
for _, name := range []string{"protocol.md", "purchase.md", "upgrade.md", "openapi.json"} {
|
||||
content, err := integrationAsset(name)
|
||||
if err != nil {
|
||||
apiError(c, 500, "internal_error", "接入资料不可用")
|
||||
@@ -116,7 +123,7 @@ prompt.md 可提供给实现工程师。verification-keys.md 为当前部署公
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
archive := zip.NewWriter(&buffer)
|
||||
for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "verification-keys.md", "test-vectors.json", "client/update_sdk.py", "client/update-sdk.mjs", "client/test_update_sdk.py", "client/test-update-sdk.mjs", "client/requirements.txt"} {
|
||||
for _, name := range []string{"README.md", "protocol.md", "purchase.md", "upgrade.md", "openapi.json", "prompt.md", "verification-keys.md", "test-vectors.json", "client/update_sdk.py", "client/update-sdk.mjs", "client/test_update_sdk.py", "client/test-update-sdk.mjs", "client/requirements.txt", "client/purchase-sdk.mjs", "client/verify.mjs", "client/test-purchase-sdk.mjs", "client/purchase-sdk.md"} {
|
||||
file, err := archive.Create(name)
|
||||
if err == nil {
|
||||
_, err = file.Write(files[name])
|
||||
|
||||
@@ -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 后关闭窗口,需妥善保护、按需停用或轮换购买凭据。
|
||||
|
||||
离线测试不能证明生产商户付款、公网通知、真实数据库迁移和实际桌面客户端集成已验收。
|
||||
@@ -86,6 +86,10 @@ func buildIntegrationKit(language, mode string) integrationKitResponse {
|
||||
Mode: mode,
|
||||
ModeLabel: modeLabel,
|
||||
Endpoints: []kitAPI{
|
||||
{Method: "POST", Path: "/api/v1/client/plans", Purpose: "受限购买凭据查询已启用套餐与可用渠道"},
|
||||
{Method: "POST", Path: "/api/v1/client/purchases", Purpose: "Idempotency-Key 幂等扫码下单,冻结套餐版本和价格"},
|
||||
{Method: "POST", Path: "/api/v1/client/purchases/status", Purpose: "按订单号或幂等键恢复支付及签发状态"},
|
||||
{Method: "POST", Path: "/api/v1/client/purchases/claim", Purpose: "已签发订单领取并恢复同一实例凭据"},
|
||||
{Method: "POST", Path: "/api/v1/instances/{instance_id}/updates/check", Purpose: "提交 secret、current_version、platform、arch、channel,验证签名 update-v1 策略"},
|
||||
{Method: "POST", Path: "/api/v1/portal/snapshot", Purpose: "提交 instance_id、secret,查询已发布版本、客户 ID 与下载权限"},
|
||||
{Method: "POST", Path: "/api/v1/activation/instances/{instance_id}", Purpose: "首次激活,提交 license_key、secret 和 Idempotency-Key"},
|
||||
@@ -102,7 +106,7 @@ func buildIntegrationKit(language, mode string) integrationKitResponse {
|
||||
},
|
||||
Protocol: string(protocol),
|
||||
Upgrade: string(upgrade),
|
||||
Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md、upgrade.md 与 openapi.json。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。\n\n客户端升级:优先调用 POST /api/v1/instances/{instance_id}/updates/check,解码 payload Base64 原始 JSON 并验证 update-v1 签名、上下文、15 分钟 TTL、策略 revision 回滚和 required_now 的可信时间/本地版本条件,再调用同源实例下载接口校验长度与 SHA-256。使用可注入 Installer,不执行任意命令;disabled 或检查成功不得替代 canRun 的 license-v2/lease-v2 授权判断。参考源码为 client/update_sdk.py 与 client/update-sdk.mjs,仅完整 HTTP 200 下载,不实现 Range 续传、完整 LicenseClient、canRun、持久化存储或本地强制升级评估;这些能力须由应用实现。下载及安装前重新检查 TTL、策略、当前版本和授权。按 upgrade.md 覆盖篡改、上下文、deadline、hash、离线和回退。",
|
||||
Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n扫码新购:管理员先配置既有客户、产品、启用套餐及受限购买凭据;购买前固定可信公钥和产品范围,但尚无实例。安全导入购买 Bearer、先原子保存安装标识/套餐版本/渠道和幂等键,再查询套餐、下单展示官方二维码、按原键恢复订单;只有服务端确认 paid/issued 后 claim 并原子保存返回的 instance_id、secret、license_key。installation_id 仅绑定订单,不是 instance_id。激活及心跳使用 claim 返回的实例 UUID,验签 license-v2/lease-v2 并核对产品/实例归属,租约保存成功才能启用。二维码过期不等于渠道关单;不要切渠道重复下单。Node.js 购买参考 SDK 见 client/purchase-sdk.mjs、client/verify.mjs;其他语言须自行实现和测试。购买凭据不得进入公共包或日志。\n\n必须阅读接入包 protocol.md、purchase.md、upgrade.md 与 openapi.json。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。\n\n客户端升级:优先调用 POST /api/v1/instances/{instance_id}/updates/check,解码 payload Base64 原始 JSON 并验证 update-v1 签名、上下文、15 分钟 TTL、策略 revision 回滚和 required_now 的可信时间/本地版本条件,再调用同源实例下载接口校验长度与 SHA-256。使用可注入 Installer,不执行任意命令;disabled 或检查成功不得替代 canRun 的 license-v2/lease-v2 授权判断。参考源码为 client/update_sdk.py 与 client/update-sdk.mjs,仅完整 HTTP 200 下载,不实现 Range 续传、完整 LicenseClient、canRun、持久化存储或本地强制升级评估;这些能力须由应用实现。下载及安装前重新检查 TTL、策略、当前版本和授权。按 upgrade.md 覆盖篡改、上下文、deadline、hash、离线和回退。",
|
||||
TestVector: kitVector{
|
||||
Version: "lease-v2", InstanceID: "11111111-2222-3333-4444-555555555555", State: "active",
|
||||
ServerTime: "2026-10-09T03:00:00Z", EntitlementExpiresAt: "2027-10-09T03:00:00Z", LeaseExpiresAt: "2026-10-23T03:00:00Z",
|
||||
@@ -123,7 +127,7 @@ func integrationPrompt(language, mode string) string {
|
||||
|
||||
默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。
|
||||
|
||||
首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 持续用于心跳和下载;配置加密留存后可重复查看,旧实例无法从哈希恢复。公钥及绑定信息从对应管理后台实例页导出 yhy-license-trust v1 JSON(详见 protocol.md),客户端实现严格导入并通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,仅存哈希的旧实例丢失 secret 无法恢复;已加密留存的实例按管理员审计交付流程重新获取。
|
||||
人工交付路径:首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。扫码新购路径则按 purchase.md:管理员只交付受限购买凭据及预置公钥,付款签发后由 claim 返回实例;不得预先创建该笔实例。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 持续用于心跳和下载;配置加密留存后可重复查看,旧实例无法从哈希恢复。公钥及绑定信息从对应管理后台实例页导出 yhy-license-trust v1 JSON(详见 protocol.md),客户端实现严格导入并通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,仅存哈希的旧实例丢失 secret 无法恢复;已加密留存的实例按管理员审计交付流程重新获取。
|
||||
|
||||
实现激活 POST /api/v1/activation/instances/{instance_id},提交 license_key、secret 和 Idempotency-Key;实现心跳 POST /api/v1/instances/{instance_id}/heartbeat,提交 secret、RFC3339 UTC client_time 和 Idempotency-Key。
|
||||
|
||||
@@ -183,7 +187,12 @@ func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) {
|
||||
fmt.Fprintf(&b, "- %s\n", rule)
|
||||
}
|
||||
fmt.Fprintf(&b, "\n## 租约字段示例(不是签名测试向量)\n\n```json\n{\n \"version\": \"%s\",\n \"instance_id\": \"%s\",\n \"state\": \"%s\",\n \"server_time\": \"%s\",\n \"entitlement_expires_at\": \"%s\",\n \"lease_expires_at\": \"%s\"\n}\n```\n", kit.TestVector.Version, kit.TestVector.InstanceID, kit.TestVector.State, kit.TestVector.ServerTime, kit.TestVector.EntitlementExpiresAt, kit.TestVector.LeaseExpiresAt)
|
||||
fmt.Fprintf(&b, "\n\n%s\n\n%s\n", kit.Protocol, kit.Upgrade)
|
||||
purchase, err := integrationAsset("purchase.md")
|
||||
if err != nil {
|
||||
apiError(c, 500, "internal_error", "接入资料不可用")
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(&b, "\n\n%s\n\n%s\n\n%s\n", kit.Protocol, purchase, kit.Upgrade)
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s-integration.md", language, mode))
|
||||
c.Data(http.StatusOK, "text/markdown; charset=utf-8", []byte(b.String()))
|
||||
|
||||
@@ -56,6 +56,20 @@ func TestIntegrationInputs(t *testing.T) {
|
||||
if spec["openapi"] != "3.0.3" {
|
||||
t.Fatal("invalid OpenAPI")
|
||||
}
|
||||
paths := spec["paths"].(map[string]any)
|
||||
kit := buildIntegrationKit("nodejs", "desktop")
|
||||
for _, path := range []string{"/api/v1/client/plans", "/api/v1/client/purchases", "/api/v1/client/purchases/status", "/api/v1/client/purchases/claim"} {
|
||||
found := false
|
||||
for _, endpoint := range kit.Endpoints {
|
||||
found = found || endpoint.Path == path
|
||||
}
|
||||
if paths[path] == nil || !found {
|
||||
t.Fatalf("missing purchase contract: %s", path)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(kit.Prompt, "installation_id") || !strings.Contains(kit.Prompt, "claim 返回") {
|
||||
t.Fatal("missing purchase instructions")
|
||||
}
|
||||
}
|
||||
func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
const public = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----\n"
|
||||
@@ -78,7 +92,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(archive.File) != 12 {
|
||||
if len(archive.File) != 17 {
|
||||
t.Fatal("missing files")
|
||||
}
|
||||
for _, file := range archive.File {
|
||||
@@ -106,7 +120,13 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
if file.Name == "client/update-sdk.mjs" && !strings.Contains(string(content), "verifyCheck") {
|
||||
t.Fatal("missing Node SDK")
|
||||
}
|
||||
if strings.HasSuffix(file.Name, ".md") && (strings.Contains(string(content), "verify.mjs") || strings.Contains(string(content), `"arch":"amd64"`)) {
|
||||
if file.Name == "client/purchase-sdk.mjs" && !strings.Contains(string(content), "class PurchaseClient") {
|
||||
t.Fatal("missing purchase SDK")
|
||||
}
|
||||
if file.Name == "purchase.md" && !strings.Contains(string(content), "/api/v1/client/purchases/claim") {
|
||||
t.Fatal("missing purchase protocol")
|
||||
}
|
||||
if strings.HasSuffix(file.Name, ".md") && strings.Contains(string(content), `"arch":"amd64"`) {
|
||||
t.Fatal("invalid reference or architecture")
|
||||
}
|
||||
if file.Name == "README.md" && (!strings.Contains(string(content), "requirements.txt") || !strings.Contains(string(content), "不支持 Range")) {
|
||||
@@ -147,7 +167,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestIntegrationSDKCopies(t *testing.T) {
|
||||
for _, name := range []string{"update_sdk.py", "update-sdk.mjs", "test_update_sdk.py", "test-update-sdk.mjs", "requirements.txt"} {
|
||||
for _, name := range []string{"update_sdk.py", "update-sdk.mjs", "test_update_sdk.py", "test-update-sdk.mjs", "requirements.txt", "purchase-sdk.mjs", "verify.mjs", "test-purchase-sdk.mjs", "purchase-sdk.md"} {
|
||||
source, err := os.ReadFile("../../../client/" + name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -42,6 +42,8 @@ func operation(path string) string {
|
||||
return "payment_checkout"
|
||||
case "/api/v1/payments/:channel/notify":
|
||||
return "payment_notify"
|
||||
case "/api/v1/client/plans", "/api/v1/client/purchases", "/api/v1/client/purchases/status", "/api/v1/client/purchases/claim":
|
||||
return "client_purchase"
|
||||
case "/api/v1/portal/snapshot":
|
||||
return "login"
|
||||
case "/api/v1/auth/login":
|
||||
@@ -121,11 +123,14 @@ func (o *Operations) Middleware() gin.HandlerFunc {
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
if op == "login" || op == "activation" || op == "heartbeat" || op == "download" || op == "payment_checkout" || op == "payment_notify" {
|
||||
if op == "login" || op == "activation" || op == "heartbeat" || op == "download" || op == "payment_checkout" || op == "payment_notify" || op == "client_purchase" {
|
||||
limit := 60
|
||||
if op == "payment_notify" {
|
||||
limit = 600
|
||||
}
|
||||
if op == "client_purchase" {
|
||||
limit = 60
|
||||
}
|
||||
if op == "login" {
|
||||
limit = 10
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
func TestPublicEntryLimitsBeforeHandlers(t *testing.T) {
|
||||
for _, path := range []string{"/api/v1/auth/login", "/api/v1/activation/instances/:instance_id", "/api/v1/instances/:instance_id/heartbeat", "/api/v1/customers/:customer_id/releases/:id/download"} {
|
||||
for _, path := range []string{"/api/v1/client/plans", "/api/v1/client/purchases", "/api/v1/client/purchases/status", "/api/v1/client/purchases/claim", "/api/v1/auth/login", "/api/v1/activation/instances/:instance_id", "/api/v1/instances/:instance_id/heartbeat", "/api/v1/customers/:customer_id/releases/:id/download"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
|
||||
calls := 0
|
||||
|
||||
269
backend/internal/httpapi/purchase_admin.go
Normal file
269
backend/internal/httpapi/purchase_admin.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type paymentPlan struct {
|
||||
ID uint64 `json:"id"`
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
AmountCents uint64 `json:"amount_cents"`
|
||||
Currency string `json:"currency"`
|
||||
LicenseDays int `json:"license_days"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Version uint64 `json:"version"`
|
||||
}
|
||||
|
||||
const planColumns = "id,product_id,code,name,amount_cents,currency,license_days,enabled,version"
|
||||
|
||||
func scanPlan(row interface{ Scan(...any) error }, p *paymentPlan) error {
|
||||
return row.Scan(&p.ID, &p.ProductID, &p.Code, &p.Name, &p.AmountCents, &p.Currency, &p.LicenseDays, &p.Enabled, &p.Version)
|
||||
}
|
||||
func visibleASCII(s string, max int) bool {
|
||||
if len(s) < 1 || len(s) > max {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < 33 || r > 126 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func validPlan(p paymentPlan) bool {
|
||||
return p.ProductID > 0 && visibleASCII(p.Code, 64) && strings.TrimSpace(p.Name) != "" && len(p.Name) <= 190 && p.AmountCents > 0 && p.AmountCents <= 100000000000 && p.Currency == "CNY" && p.LicenseDays >= 1 && p.LicenseDays <= 3650
|
||||
}
|
||||
func purchaseAdminBoundary(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if !paymentConfigOriginAllowed(c) {
|
||||
apiError(c, 403, "origin_forbidden", "请求来源不允许")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
func (a *BusinessAPI) listPaymentPlans(c *gin.Context) {
|
||||
rows, e := a.db.QueryContext(c, "SELECT "+planColumns+" FROM payment_plans ORDER BY id DESC LIMIT 1000")
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []paymentPlan{}
|
||||
for rows.Next() {
|
||||
var p paymentPlan
|
||||
if scanPlan(rows, &p) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": out})
|
||||
}
|
||||
func (a *BusinessAPI) savePaymentPlan(c *gin.Context) {
|
||||
var p paymentPlan
|
||||
c.Request.Body = limitedPurchaseBody(c, 8192)
|
||||
if c.ShouldBindJSON(&p) != nil || !validPlan(p) {
|
||||
apiError(c, 400, "invalid_request", "套餐字段无效")
|
||||
return
|
||||
}
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
if tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor) != nil {
|
||||
apiError(c, 403, "forbidden", "管理员无效")
|
||||
return
|
||||
}
|
||||
var active bool
|
||||
if tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", p.ProductID).Scan(&active) != nil || !active {
|
||||
apiError(c, 409, "product_unavailable", "产品不可用")
|
||||
return
|
||||
}
|
||||
if c.Param("id") == "" {
|
||||
p.Version = 1
|
||||
r, err := tx.ExecContext(c, "INSERT INTO payment_plans(product_id,code,name,amount_cents,currency,license_days,enabled,version) VALUES(?,?,?,?,?,?,?,1)", p.ProductID, p.Code, p.Name, p.AmountCents, p.Currency, p.LicenseDays, p.Enabled)
|
||||
if err != nil {
|
||||
apiError(c, 409, "plan_conflict", "套餐代码冲突")
|
||||
return
|
||||
}
|
||||
id, _ := r.LastInsertId()
|
||||
p.ID = uint64(id)
|
||||
} else {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 || p.Version == 0 {
|
||||
apiError(c, 400, "invalid_request", "须提供套餐版本")
|
||||
return
|
||||
}
|
||||
var old paymentPlan
|
||||
if scanPlan(tx.QueryRowContext(c, "SELECT "+planColumns+" FROM payment_plans WHERE id=? FOR UPDATE", id), &old) != nil {
|
||||
apiError(c, 404, "not_found", "套餐不存在")
|
||||
return
|
||||
}
|
||||
if p.Version != old.Version {
|
||||
apiError(c, 409, "plan_version_conflict", "套餐版本已变化")
|
||||
return
|
||||
}
|
||||
if p.ProductID != old.ProductID || p.Code != old.Code {
|
||||
apiError(c, 409, "plan_identity_conflict", "套餐产品和代码不可变更")
|
||||
return
|
||||
}
|
||||
p.ID = id
|
||||
p.Version++
|
||||
_, e = tx.ExecContext(c, "UPDATE payment_plans SET name=?,amount_cents=?,currency=?,license_days=?,enabled=?,version=? WHERE id=?", p.Name, p.AmountCents, p.Currency, p.LicenseDays, p.Enabled, p.Version, id)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
_, e = tx.ExecContext(c, "INSERT INTO payment_plan_versions(plan_id,version,product_id,code,name,amount_cents,currency,license_days,enabled,created_by) VALUES(?,?,?,?,?,?,?,?,?,?)", p.ID, p.Version, p.ProductID, p.Code, p.Name, p.AmountCents, p.Currency, p.LicenseDays, p.Enabled, actor)
|
||||
details, _ := json.Marshal(p)
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'payment.plan.saved','payment_plan',?,?)", actor, p.ID, details)
|
||||
}
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": p})
|
||||
}
|
||||
func (a *BusinessAPI) listPurchaseCredentials(c *gin.Context) {
|
||||
rows, e := a.db.QueryContext(c, "SELECT id,customer_id,product_id,label,enabled,created_by FROM purchase_credentials ORDER BY id DESC LIMIT 1000")
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []gin.H{}
|
||||
for rows.Next() {
|
||||
var id, customer, product, actor uint64
|
||||
var label string
|
||||
var enabled bool
|
||||
if rows.Scan(&id, &customer, &product, &label, &enabled, &actor) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out = append(out, gin.H{"id": id, "customer_id": customer, "product_id": product, "label": label, "enabled": enabled, "created_by": actor})
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": out})
|
||||
}
|
||||
func (a *BusinessAPI) updatePurchaseCredential(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
apiError(c, 400, "invalid_request", "凭据 ID 无效")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
c.Request.Body = limitedPurchaseBody(c, 1024)
|
||||
if c.ShouldBindJSON(&in) != nil || in.Enabled == nil {
|
||||
apiError(c, 400, "invalid_request", "enabled 必须为布尔值")
|
||||
return
|
||||
}
|
||||
tx, err := a.db.BeginTx(c, nil)
|
||||
if err != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
if tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor) != nil {
|
||||
apiError(c, 403, "forbidden", "管理员无效")
|
||||
return
|
||||
}
|
||||
var customer, product uint64
|
||||
var label string
|
||||
var created bool
|
||||
if tx.QueryRowContext(c, "SELECT customer_id,product_id,label,enabled FROM purchase_credentials WHERE id=? FOR UPDATE", id).Scan(&customer, &product, &label, &created) != nil {
|
||||
apiError(c, 404, "not_found", "购买凭据不存在")
|
||||
return
|
||||
}
|
||||
if _, err = tx.ExecContext(c, "UPDATE purchase_credentials SET enabled=? WHERE id=?", *in.Enabled, id); err != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
details, _ := json.Marshal(gin.H{"enabled": *in.Enabled})
|
||||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.credential.updated','purchase_credential',?,?)", actor, id, details); err != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"id": id, "customer_id": customer, "product_id": product, "label": label, "enabled": *in.Enabled}})
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) createPurchaseCredential(c *gin.Context) {
|
||||
var in struct {
|
||||
CustomerID uint64 `json:"customer_id"`
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Label string `json:"label"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
c.Request.Body = limitedPurchaseBody(c, 4096)
|
||||
if c.ShouldBindJSON(&in) != nil || in.CustomerID == 0 || in.ProductID == 0 || strings.TrimSpace(in.Label) == "" || len(in.Label) > 190 {
|
||||
apiError(c, 400, "invalid_request", "凭据字段无效")
|
||||
return
|
||||
}
|
||||
token, e := randomPaymentToken(32)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
raw, _ := hex.DecodeString(token)
|
||||
hash := sha256.Sum256(raw)
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
var state string
|
||||
var active bool
|
||||
if tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor) != nil {
|
||||
apiError(c, 403, "forbidden", "管理员无效")
|
||||
return
|
||||
}
|
||||
if tx.QueryRowContext(c, "SELECT status FROM customers WHERE id=? FOR UPDATE", in.CustomerID).Scan(&state) != nil || state != "active" || tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", in.ProductID).Scan(&active) != nil || !active {
|
||||
apiError(c, 409, "scope_unavailable", "请先由管理员配置有效客户及产品")
|
||||
return
|
||||
}
|
||||
enabled := true
|
||||
if in.Enabled != nil {
|
||||
enabled = *in.Enabled
|
||||
}
|
||||
res, e := tx.ExecContext(c, "INSERT INTO purchase_credentials(token_hash,customer_id,product_id,label,enabled,created_by) VALUES(?,?,?,?,?,?)", hash[:], in.CustomerID, in.ProductID, in.Label, enabled, actor)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.credential.created','purchase_credential',?,'{}')", actor, id)
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(201, gin.H{"data": gin.H{"id": id, "customer_id": in.CustomerID, "product_id": in.ProductID, "label": in.Label, "enabled": enabled, "token": token}})
|
||||
}
|
||||
|
||||
// Keep SQL errors and credentials out of public error bodies.
|
||||
func purchaseFailure(c *gin.Context) {
|
||||
apiError(c, 503, "purchase_unavailable", "购买服务暂时不可用")
|
||||
}
|
||||
116
backend/internal/httpapi/purchase_claim.go
Normal file
116
backend/internal/httpapi/purchase_claim.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (a *BusinessAPI) clientPurchaseClaim(c *gin.Context) {
|
||||
s, order, ok := a.lookupClientPurchase(c, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if len(a.credentialEncryptionKey) != 32 {
|
||||
apiError(c, 503, "credentials_unavailable", "请配置独立实例凭据加密密钥")
|
||||
return
|
||||
}
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if lockPurchaseScope(c, tx, s) != nil {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
return
|
||||
}
|
||||
var license sql.NullInt64
|
||||
var state string
|
||||
if tx.QueryRowContext(c, "SELECT status,issued_license_id FROM offline_orders WHERE id=? AND customer_id=? AND product_id=? FOR UPDATE", order, s.Customer, s.Product).Scan(&state, &license) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
if state != "issued" || !license.Valid {
|
||||
apiError(c, 409, "purchase_not_paid", "订单尚未完成支付及授权")
|
||||
return
|
||||
}
|
||||
var paymentState string
|
||||
if tx.QueryRowContext(c, "SELECT status FROM payment_orders WHERE order_id=? FOR UPDATE", order).Scan(&paymentState) != nil || paymentState != "paid" {
|
||||
apiError(c, 409, "purchase_not_paid", "订单尚未完成支付及授权")
|
||||
return
|
||||
}
|
||||
var licenseKey, licenseState string
|
||||
var expires time.Time
|
||||
if tx.QueryRowContext(c, "SELECT license_key,status,expires_at FROM licenses WHERE id=? AND customer_id=? AND product_id=? FOR UPDATE", license.Int64, s.Customer, s.Product).Scan(&licenseKey, &licenseState, &expires) != nil || licenseState != "active" || !time.Now().Before(expires) {
|
||||
apiError(c, 409, "authorization_unavailable", "授权不可用")
|
||||
return
|
||||
}
|
||||
var bound sql.NullString
|
||||
if tx.QueryRowContext(c, "SELECT instance_id FROM client_purchases WHERE order_id=? AND credential_id=? FOR UPDATE", order, s.ID).Scan(&bound) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
var instance, secret string
|
||||
var encrypted []byte
|
||||
var instanceStatus, freezeState string
|
||||
e = tx.QueryRowContext(c, "SELECT instance_id,secret_encrypted,status,freeze_state FROM license_instances WHERE license_id=? FOR UPDATE", license.Int64).Scan(&instance, &encrypted, &instanceStatus, &freezeState)
|
||||
if e == nil {
|
||||
if (instanceStatus != "provisioned" && instanceStatus != "activated") || freezeState != "none" {
|
||||
apiError(c, 409, "authorization_unavailable", "授权实例当前不可交付")
|
||||
return
|
||||
}
|
||||
if !bound.Valid || bound.String != instance {
|
||||
apiError(c, 409, "instance_conflict", "授权已由其他流程绑定实例")
|
||||
return
|
||||
}
|
||||
secret, e = openInstanceSecret(a.credentialEncryptionKey, instance, encrypted)
|
||||
if e != nil {
|
||||
apiError(c, 503, "credentials_unavailable", "凭据解密不可用")
|
||||
return
|
||||
}
|
||||
} else if errors.Is(e, sql.ErrNoRows) {
|
||||
if bound.Valid {
|
||||
apiError(c, 409, "instance_conflict", "实例已被移除")
|
||||
return
|
||||
}
|
||||
instance, e = newInstanceID()
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, e = rand.Read(raw); e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
secret = base64.RawURLEncoding.EncodeToString(raw)
|
||||
hash := sha256.Sum256(raw)
|
||||
encrypted, e = sealInstanceSecret(a.credentialEncryptionKey, instance, secret)
|
||||
if e != nil {
|
||||
apiError(c, 503, "credentials_unavailable", "凭据加密不可用")
|
||||
return
|
||||
}
|
||||
_, e = tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by,secret_encrypted) VALUES(?,?,?,?,?,?,?)", instance, license.Int64, s.Customer, s.Product, hash[:], s.Actor, encrypted)
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "UPDATE client_purchases SET instance_id=? WHERE order_id=?", instance, order)
|
||||
}
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.claimed','order',?,'{}')", s.Actor, order)
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"instance_id": instance, "secret": secret, "license_key": licenseKey, "license_id": license.Int64}})
|
||||
}
|
||||
312
backend/internal/httpapi/purchase_client.go
Normal file
312
backend/internal/httpapi/purchase_client.go
Normal file
@@ -0,0 +1,312 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"io"
|
||||
"license-platform/backend/internal/payments"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type purchaseScope struct{ ID, Customer, Product, Actor uint64 }
|
||||
|
||||
func limitedPurchaseBody(c *gin.Context, n int64) io.ReadCloser {
|
||||
return http.MaxBytesReader(c.Writer, c.Request.Body, n)
|
||||
}
|
||||
func (a *BusinessAPI) purchaseAuthenticated(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
auth := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
raw, e := hex.DecodeString(strings.TrimPrefix(auth, "Bearer "))
|
||||
if e != nil || len(raw) != 32 {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
var s purchaseScope
|
||||
e = a.db.QueryRowContext(c, `SELECT pc.id,pc.customer_id,pc.product_id,pc.created_by FROM purchase_credentials pc JOIN customers cu ON cu.id=pc.customer_id JOIN products p ON p.id=pc.product_id JOIN admins ad ON ad.id=pc.created_by WHERE pc.token_hash=? AND pc.enabled=1 AND cu.status='active' AND p.active=1 AND ad.active=1 AND ad.role='admin'`, sum[:]).Scan(&s.ID, &s.Customer, &s.Product, &s.Actor)
|
||||
if e != nil {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Set("purchase_scope", s)
|
||||
c.Next()
|
||||
}
|
||||
func scopeOf(c *gin.Context) purchaseScope { return c.MustGet("purchase_scope").(purchaseScope) }
|
||||
func (a *BusinessAPI) clientPlans(c *gin.Context) {
|
||||
s := scopeOf(c)
|
||||
rows, e := a.db.QueryContext(c, "SELECT "+planColumns+" FROM payment_plans WHERE product_id=? AND enabled=1 ORDER BY id LIMIT 1000", s.Product)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out := []paymentPlan{}
|
||||
for rows.Next() {
|
||||
var p paymentPlan
|
||||
if scanPlan(rows, &p) != nil {
|
||||
rows.Close()
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
channels := []string{}
|
||||
for _, channel := range []string{"alipay", "wechat"} {
|
||||
var v sql.NullInt64
|
||||
var enabled bool
|
||||
if a.db.QueryRowContext(c, "SELECT c.active_version,v.enabled FROM payment_channel_configs c JOIN payment_channel_config_versions v ON v.channel=c.channel AND v.version=c.active_version WHERE c.channel=?", channel).Scan(&v, &enabled) == nil && enabled {
|
||||
channels = append(channels, channel)
|
||||
}
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"plans": out, "channels": channels, "license_duration": "fixed_days_from_payment", "purchase_mode": "new_purchase", "customer_setup": "由管理员在客户管理中预配置既有客户,并为该客户及产品创建购买凭据"}})
|
||||
}
|
||||
|
||||
type clientPurchaseInput struct {
|
||||
PlanID uint64 `json:"plan_id"`
|
||||
PlanVersion uint64 `json:"plan_version"`
|
||||
Installation string `json:"installation_id"`
|
||||
Channel string `json:"channel"`
|
||||
}
|
||||
|
||||
// A restricted service context, never an admin Gin context. Creator is audit attribution only.
|
||||
func lockPurchaseScope(ctx context.Context, tx *sql.Tx, s purchaseScope) error {
|
||||
var id uint64
|
||||
return tx.QueryRowContext(ctx, `SELECT pc.id FROM purchase_credentials pc JOIN admins a ON a.id=pc.created_by JOIN customers c ON c.id=pc.customer_id JOIN products p ON p.id=pc.product_id WHERE pc.id=? AND pc.customer_id=? AND pc.product_id=? AND pc.enabled=1 AND a.active=1 AND a.role='admin' AND c.status='active' AND p.active=1 FOR UPDATE`, s.ID, s.Customer, s.Product).Scan(&id)
|
||||
}
|
||||
func (a *BusinessAPI) clientCreatePurchase(c *gin.Context) {
|
||||
var in clientPurchaseInput
|
||||
key := c.GetHeader("Idempotency-Key")
|
||||
c.Request.Body = limitedPurchaseBody(c, 4096)
|
||||
if c.ShouldBindJSON(&in) != nil || in.PlanID == 0 || in.PlanVersion == 0 || !visibleASCII(in.Installation, 128) || !visibleASCII(key, 128) || (in.Channel != "alipay" && in.Channel != "wechat") {
|
||||
apiError(c, 400, "invalid_request", "购买参数或幂等键无效")
|
||||
return
|
||||
}
|
||||
if len(a.credentialEncryptionKey) != 32 {
|
||||
apiError(c, 503, "credentials_unavailable", "请配置独立实例凭据加密密钥")
|
||||
return
|
||||
}
|
||||
s := scopeOf(c)
|
||||
payload, _ := json.Marshal(in)
|
||||
fp := sha256.Sum256(payload)
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if lockPurchaseScope(c, tx, s) != nil {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
return
|
||||
}
|
||||
var old []byte
|
||||
var order uint64
|
||||
e = tx.QueryRowContext(c, "SELECT order_id,request_fingerprint FROM client_purchases WHERE credential_id=? AND idempotency_key=?", s.ID, key).Scan(&order, &old)
|
||||
if e == nil {
|
||||
if !bytesEqual(old, fp[:]) {
|
||||
apiError(c, 409, "idempotency_conflict", "幂等键请求冲突")
|
||||
return
|
||||
}
|
||||
if tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
a.respondPurchase(c, s, order, true)
|
||||
return
|
||||
}
|
||||
if !errors.Is(e, sql.ErrNoRows) {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
var p paymentPlan
|
||||
e = scanPlan(tx.QueryRowContext(c, "SELECT "+planColumns+" FROM payment_plans WHERE id=? AND product_id=? FOR UPDATE", in.PlanID, s.Product), &p)
|
||||
if e != nil {
|
||||
apiError(c, 404, "not_found", "套餐不存在")
|
||||
return
|
||||
}
|
||||
if !p.Enabled {
|
||||
apiError(c, 409, "plan_disabled", "套餐已停用")
|
||||
return
|
||||
}
|
||||
if p.Version != in.PlanVersion {
|
||||
apiError(c, 409, "plan_version_conflict", "套餐版本已变化,请刷新套餐")
|
||||
return
|
||||
}
|
||||
if !validPlan(p) || !time.Now().UTC().Add(time.Duration(p.LicenseDays)*24*time.Hour).Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
|
||||
apiError(c, 409, "invalid_plan", "套餐期限无效")
|
||||
return
|
||||
}
|
||||
var version sql.NullInt64
|
||||
if tx.QueryRowContext(c, "SELECT active_version FROM payment_channel_configs WHERE channel=? FOR UPDATE", in.Channel).Scan(&version) != nil || !version.Valid {
|
||||
apiError(c, 503, "channel_unavailable", "请由管理员发布支付渠道配置")
|
||||
return
|
||||
}
|
||||
var enabled bool
|
||||
var encrypted []byte
|
||||
if tx.QueryRowContext(c, "SELECT enabled,config_encrypted FROM payment_channel_config_versions WHERE channel=? AND version=?", in.Channel, version.Int64).Scan(&enabled, &encrypted) != nil || !enabled {
|
||||
apiError(c, 503, "channel_unavailable", "支付渠道未启用")
|
||||
return
|
||||
}
|
||||
config, e := decryptPaymentConfig(a.paymentConfigEncryptionKey, in.Channel, version.Int64, encrypted)
|
||||
if e != nil {
|
||||
apiError(c, 503, "configuration_unavailable", "支付配置不可用")
|
||||
return
|
||||
}
|
||||
if _, e = payments.NewProvider(in.Channel, config); e != nil {
|
||||
apiError(c, 503, "channel_unavailable", "支付渠道不可用")
|
||||
return
|
||||
}
|
||||
orderNo, e := randomPaymentToken(16)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
merchant, e := randomPaymentToken(16)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
checkout, e := randomPaymentToken(32)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
expires := time.Now().UTC().Add(30 * time.Minute)
|
||||
res, e := tx.ExecContext(c, "INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,created_by,payment_channel,payment_expires_at) VALUES(?,?,?,?,?,?,?,?)", orderNo, s.Customer, s.Product, p.AmountCents, p.Currency, s.Actor, in.Channel, expires)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
oid, e := res.LastInsertId()
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
order = uint64(oid)
|
||||
_, e = tx.ExecContext(c, "INSERT INTO payment_orders(order_id,merchant_order_no,channel,amount_cents,currency,license_days,checkout_token,expires_at,provider_config_version,plan_id,plan_version) VALUES(?,?,?,?,?,?,?,?,?,?,?)", order, merchant, in.Channel, p.AmountCents, p.Currency, p.LicenseDays, checkout, expires, version, p.ID, p.Version)
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "INSERT INTO client_purchases(order_id,credential_id,installation_id,idempotency_key,request_fingerprint) VALUES(?,?,?,?,?)", order, s.ID, in.Installation, key, fp[:])
|
||||
}
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.created','order',?,'{}')", s.Actor, order)
|
||||
}
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
a.respondPurchase(c, s, order, true)
|
||||
}
|
||||
|
||||
type purchaseLookup struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Installation string `json:"installation_id"`
|
||||
Key string `json:"idempotency_key"`
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) lookupClientPurchase(c *gin.Context, claim bool) (purchaseScope, uint64, bool) {
|
||||
s := scopeOf(c)
|
||||
var in purchaseLookup
|
||||
c.Request.Body = limitedPurchaseBody(c, 4096)
|
||||
if c.ShouldBindJSON(&in) != nil || !visibleASCII(in.Installation, 128) || (claim && len(in.OrderNo) != 32) || (in.OrderNo == "" && !visibleASCII(in.Key, 128)) || (in.OrderNo != "" && len(in.OrderNo) != 32) {
|
||||
apiError(c, 400, "invalid_request", "订单查询参数无效")
|
||||
return s, 0, false
|
||||
}
|
||||
var order uint64
|
||||
query := "SELECT cp.order_id FROM client_purchases cp JOIN offline_orders o ON o.id=cp.order_id WHERE cp.credential_id=? AND cp.installation_id=? AND "
|
||||
var e error
|
||||
if in.OrderNo != "" {
|
||||
e = a.db.QueryRowContext(c, query+"o.order_no=?", s.ID, in.Installation, in.OrderNo).Scan(&order)
|
||||
} else {
|
||||
e = a.db.QueryRowContext(c, query+"cp.idempotency_key=?", s.ID, in.Installation, in.Key).Scan(&order)
|
||||
}
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
apiError(c, 404, "not_found", "订单不存在")
|
||||
return s, 0, false
|
||||
}
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return s, 0, false
|
||||
}
|
||||
return s, order, true
|
||||
}
|
||||
func (a *BusinessAPI) clientPurchaseStatus(c *gin.Context) {
|
||||
s, order, ok := a.lookupClientPurchase(c, false)
|
||||
if ok {
|
||||
a.respondPurchase(c, s, order, false)
|
||||
}
|
||||
}
|
||||
func (a *BusinessAPI) respondPurchase(c *gin.Context, s purchaseScope, order uint64, create bool) {
|
||||
var no, merchant, channel, status, orderStatus, currency, title string
|
||||
var amount uint64
|
||||
var days int
|
||||
var code sql.NullString
|
||||
var expires time.Time
|
||||
var version sql.NullInt64
|
||||
e := a.db.QueryRowContext(c, `SELECT o.order_no,p.merchant_order_no,p.channel,p.status,o.status,p.currency,p.amount_cents,p.license_days,p.code_url,p.expires_at,p.provider_config_version,pv.name FROM client_purchases cp JOIN offline_orders o ON o.id=cp.order_id JOIN payment_orders p ON p.order_id=o.id JOIN payment_plan_versions pv ON pv.plan_id=p.plan_id AND pv.version=p.plan_version WHERE cp.order_id=? AND cp.credential_id=?`, order, s.ID).Scan(&no, &merchant, &channel, &status, &orderStatus, ¤cy, &amount, &days, &code, &expires, &version, &title)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
if create && status == "created" && !code.Valid && time.Now().Before(expires) {
|
||||
provider, err := a.providerForPaymentVersion(c, channel, version)
|
||||
if err != nil {
|
||||
apiError(c, 503, "channel_unavailable", "历史支付配置不可用")
|
||||
return
|
||||
}
|
||||
url, err := provider.Create(c, merchant, int64(amount), title)
|
||||
if err != nil || url == "" {
|
||||
apiError(c, 502, "channel_error", "渠道下单未完成,请使用相同参数和幂等键重试")
|
||||
return
|
||||
}
|
||||
if _, err = a.db.ExecContext(c, "UPDATE payment_orders SET code_url=? WHERE order_id=? AND status='created'", url, order); err != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
code = sql.NullString{String: url, Valid: true}
|
||||
}
|
||||
if status == "created" {
|
||||
now := time.Now().UTC()
|
||||
res, err := a.db.ExecContext(c, "UPDATE payment_orders SET last_queried_at=? WHERE order_id=? AND (last_queried_at IS NULL OR last_queried_at<?)", now, order, now.Add(-15*time.Second))
|
||||
if err == nil {
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 1 {
|
||||
if provider, err := a.providerForPaymentVersion(c, channel, version); err == nil {
|
||||
notification, err := provider.Query(c, merchant)
|
||||
if err == nil && notification.Paid && notification.MerchantOrderNo == merchant {
|
||||
if a.applyPayment(c, channel, notification, version) != nil {
|
||||
apiError(c, 503, "authorization_pending", "支付已完成,授权处理中")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if a.db.QueryRowContext(c, "SELECT p.status,o.status FROM payment_orders p JOIN offline_orders o ON o.id=p.order_id WHERE p.order_id=?", order).Scan(&status, &orderStatus) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
qrExpired := !time.Now().Before(expires)
|
||||
if qrExpired || status != "created" {
|
||||
code.String = ""
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"order_no": no, "status": status, "order_status": orderStatus, "code_url": code.String, "qr_expired": qrExpired, "expires_at": expires, "amount_cents": amount, "currency": currency, "license_days": days, "channel": channel}})
|
||||
}
|
||||
375
backend/internal/httpapi/purchase_test.go
Normal file
375
backend/internal/httpapi/purchase_test.go
Normal file
@@ -0,0 +1,375 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type purchaseStep struct {
|
||||
sql string
|
||||
rows [][]driver.Value
|
||||
args func([]driver.NamedValue) bool
|
||||
err error
|
||||
}
|
||||
type purchaseTestDB struct {
|
||||
t *testing.T
|
||||
steps []purchaseStep
|
||||
commits int
|
||||
}
|
||||
type purchaseDriver struct{ db *purchaseTestDB }
|
||||
|
||||
func (d purchaseDriver) Open(string) (driver.Conn, error) { return d.db, nil }
|
||||
func (d *purchaseTestDB) Prepare(string) (driver.Stmt, error) { return nil, errors.New("unsupported") }
|
||||
func (d *purchaseTestDB) Close() error { return nil }
|
||||
func (d *purchaseTestDB) Begin() (driver.Tx, error) { return d, nil }
|
||||
func (d *purchaseTestDB) Commit() error { d.commits++; return nil }
|
||||
func (d *purchaseTestDB) Rollback() error { return nil }
|
||||
func (d *purchaseTestDB) next(q string, args []driver.NamedValue) purchaseStep {
|
||||
d.t.Helper()
|
||||
if len(d.steps) == 0 {
|
||||
d.t.Fatalf("unexpected SQL: %s", q)
|
||||
}
|
||||
s := d.steps[0]
|
||||
d.steps = d.steps[1:]
|
||||
if !strings.Contains(q, s.sql) {
|
||||
d.t.Fatalf("SQL %s missing %s", q, s.sql)
|
||||
}
|
||||
if s.args != nil && !s.args(args) {
|
||||
d.t.Fatalf("SQL argument assertion failed for %s", s.sql)
|
||||
}
|
||||
return s
|
||||
}
|
||||
func (d *purchaseTestDB) QueryContext(_ context.Context, q string, a []driver.NamedValue) (driver.Rows, error) {
|
||||
s := d.next(q, a)
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
return &purchaseRows{rows: s.rows}, nil
|
||||
}
|
||||
func (d *purchaseTestDB) ExecContext(_ context.Context, q string, a []driver.NamedValue) (driver.Result, error) {
|
||||
s := d.next(q, a)
|
||||
return purchaseResult{}, s.err
|
||||
}
|
||||
|
||||
type purchaseResult struct{}
|
||||
|
||||
func (purchaseResult) LastInsertId() (int64, error) { return 42, nil }
|
||||
func (purchaseResult) RowsAffected() (int64, error) { return 1, nil }
|
||||
|
||||
type purchaseRows struct{ rows [][]driver.Value }
|
||||
|
||||
func (r *purchaseRows) Columns() []string {
|
||||
n := 1
|
||||
if len(r.rows) > 0 {
|
||||
n = len(r.rows[0])
|
||||
}
|
||||
out := make([]string, n)
|
||||
for i := range out {
|
||||
out[i] = fmt.Sprint(i)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (r *purchaseRows) Close() error { return nil }
|
||||
func (r *purchaseRows) Next(v []driver.Value) error {
|
||||
if len(r.rows) == 0 {
|
||||
return io.EOF
|
||||
}
|
||||
copy(v, r.rows[0])
|
||||
r.rows = r.rows[1:]
|
||||
return nil
|
||||
}
|
||||
|
||||
var purchaseDriverSeq atomic.Uint64
|
||||
|
||||
func purchaseDB(t *testing.T, steps ...purchaseStep) (*sql.DB, *purchaseTestDB) {
|
||||
t.Helper()
|
||||
d := &purchaseTestDB{t: t, steps: steps}
|
||||
name := fmt.Sprintf("purchase-%d", purchaseDriverSeq.Add(1))
|
||||
sql.Register(name, purchaseDriver{d})
|
||||
db, e := sql.Open(name, "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() {
|
||||
db.Close()
|
||||
if len(d.steps) != 0 {
|
||||
t.Errorf("unconsumed SQL steps: %d", len(d.steps))
|
||||
}
|
||||
})
|
||||
return db, d
|
||||
}
|
||||
func one(v ...driver.Value) [][]driver.Value { return [][]driver.Value{v} }
|
||||
func scopeStep() purchaseStep {
|
||||
return purchaseStep{sql: "SELECT pc.id FROM purchase_credentials", rows: one(int64(1))}
|
||||
}
|
||||
func purchaseDirect(a *BusinessAPI, path, body string, handler gin.HandlerFunc) *httptest.ResponseRecorder {
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set("purchase_scope", purchaseScope{1, 2, 3, 4})
|
||||
c.Header("Cache-Control", "no-store")
|
||||
})
|
||||
r.POST(path, handler)
|
||||
req := httptest.NewRequest("POST", path, strings.NewReader(body))
|
||||
req.Header.Set("Idempotency-Key", "attempt-1")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
func TestPurchaseBearerAndAdminBoundary(t *testing.T) {
|
||||
r := paymentTestEngine(nil, nil)
|
||||
for _, path := range []string{"/api/v1/client/plans", "/api/v1/client/purchases", "/api/v1/client/purchases/status", "/api/v1/client/purchases/claim"} {
|
||||
for _, auth := range []string{"", "Bearer broken", "Basic admin", "Bearer " + strings.Repeat("ab", 31)} {
|
||||
req := httptest.NewRequest("POST", path, strings.NewReader("{}"))
|
||||
req.Header.Set("Authorization", auth)
|
||||
req.Header.Set("Cookie", "lp_session=admin")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != 401 || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("%s: status=%d", path, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct{ method, path string }{{"GET", "/api/v1/payment-plans"}, {"POST", "/api/v1/payment-plans"}, {"PUT", "/api/v1/payment-plans/1"}, {"GET", "/api/v1/purchase-credentials"}, {"POST", "/api/v1/purchase-credentials"}, {"PUT", "/api/v1/purchase-credentials/1"}} {
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.Header.Set("Origin", "https://foreign.invalid")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != 403 || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("admin boundary %s status=%d", tc.path, w.Code)
|
||||
}
|
||||
req = httptest.NewRequest(tc.method, tc.path, nil)
|
||||
w = httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != 401 {
|
||||
t.Fatalf("admin auth %s status=%d", tc.path, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestPurchaseBearerScopedHash(t *testing.T) {
|
||||
raw := bytes.Repeat([]byte{7}, 32)
|
||||
sum := sha256.Sum256(raw)
|
||||
db, _ := purchaseDB(t, purchaseStep{sql: "pc.token_hash=? AND pc.enabled=1", rows: one(int64(1), int64(2), int64(3), int64(4)), args: func(args []driver.NamedValue) bool { return bytes.Equal(args[0].Value.([]byte), sum[:]) }})
|
||||
a := &BusinessAPI{db: db}
|
||||
r := gin.New()
|
||||
r.POST("/", a.purchaseAuthenticated, func(c *gin.Context) {
|
||||
s := scopeOf(c)
|
||||
if s.Customer != 2 || s.Product != 3 || s.Actor != 4 {
|
||||
t.Fatal("scope mismatch")
|
||||
}
|
||||
if _, ok := c.Get("admin_id"); ok {
|
||||
t.Fatal("escalated admin context")
|
||||
}
|
||||
c.Status(204)
|
||||
})
|
||||
req := httptest.NewRequest("POST", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+hex.EncodeToString(raw))
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != 204 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
func TestPurchaseInputAndEncryptionGate(t *testing.T) {
|
||||
a := &BusinessAPI{}
|
||||
for _, body := range []string{`{}`, `{"plan_id":1,"plan_version":1,"installation_id":"bad id","channel":"alipay"}`, `{"plan_id":1,"plan_version":1,"installation_id":"install","channel":"cash"}`} {
|
||||
w := purchaseDirect(a, "/", body, a.clientCreatePurchase)
|
||||
if w.Code != 400 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
body := `{"plan_id":1,"plan_version":1,"installation_id":"install","channel":"alipay"}`
|
||||
for _, n := range []int{0, 16, 24, 31, 33} {
|
||||
a.credentialEncryptionKey = make([]byte, n)
|
||||
w := purchaseDirect(a, "/", body, a.clientCreatePurchase)
|
||||
if w.Code != 503 || !strings.Contains(w.Body.String(), "credentials_unavailable") {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestPurchaseIdempotencyAndPlanVersion(t *testing.T) {
|
||||
body := `{"plan_id":1,"plan_version":1,"installation_id":"install","channel":"alipay"}`
|
||||
for _, mode := range []string{"idempotency", "version", "disabled", "scope"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
steps := []purchaseStep{scopeStep()}
|
||||
if mode == "scope" {
|
||||
steps[0].rows = nil
|
||||
} else {
|
||||
old := purchaseStep{sql: "SELECT order_id,request_fingerprint"}
|
||||
if mode == "idempotency" {
|
||||
old.rows = one(int64(8), []byte("different"))
|
||||
}
|
||||
steps = append(steps, old)
|
||||
if mode != "idempotency" {
|
||||
steps = append(steps, purchaseStep{sql: "FROM payment_plans WHERE id=? AND product_id=? FOR UPDATE", rows: one(int64(1), int64(3), "basic", "Basic", int64(100), "CNY", int64(30), mode != "disabled", int64(2)), args: func(a []driver.NamedValue) bool { return a[1].Value == int64(3) }})
|
||||
}
|
||||
}
|
||||
db, _ := purchaseDB(t, steps...)
|
||||
a := &BusinessAPI{db: db, credentialEncryptionKey: make([]byte, 32)}
|
||||
w := purchaseDirect(a, "/", body, a.clientCreatePurchase)
|
||||
want := "plan_version_conflict"
|
||||
if mode == "idempotency" {
|
||||
want = "idempotency_conflict"
|
||||
}
|
||||
if mode == "disabled" {
|
||||
want = "plan_disabled"
|
||||
}
|
||||
if mode == "scope" {
|
||||
want = "invalid_purchase_credential"
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), want) {
|
||||
t.Fatalf("status=%d expected code=%s", w.Code, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestPurchaseLookupInstallationIsolation(t *testing.T) {
|
||||
for _, body := range []string{`{"order_no":"01234567890123456789012345678901","installation_id":"wrong-install"}`, `{"idempotency_key":"attempt-1","installation_id":"wrong-install"}`} {
|
||||
db, _ := purchaseDB(t, purchaseStep{sql: "WHERE cp.credential_id=? AND cp.installation_id=?", args: func(a []driver.NamedValue) bool { return a[0].Value == int64(1) && a[1].Value == "wrong-install" }})
|
||||
a := &BusinessAPI{db: db}
|
||||
w := purchaseDirect(a, "/", body, a.clientPurchaseStatus)
|
||||
if w.Code != 404 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestPurchaseClaimCreateAndRecover(t *testing.T) {
|
||||
key := bytes.Repeat([]byte{9}, 32)
|
||||
var savedID string
|
||||
var savedCipher []byte
|
||||
body := `{"order_no":"01234567890123456789012345678901","installation_id":"install"}`
|
||||
lookup := func() purchaseStep {
|
||||
return purchaseStep{sql: "WHERE cp.credential_id=? AND cp.installation_id=?", rows: one(int64(42))}
|
||||
}
|
||||
common := func() []purchaseStep {
|
||||
return []purchaseStep{lookup(), scopeStep(), {sql: "FROM offline_orders", rows: one("issued", int64(6))}, {sql: "SELECT status FROM payment_orders", rows: one("paid")}, {sql: "FROM licenses", rows: one("license-test", "active", time.Now().Add(24*time.Hour))}}
|
||||
}
|
||||
steps := common()
|
||||
steps = append(steps, purchaseStep{sql: "SELECT instance_id FROM client_purchases", rows: one(nil)}, purchaseStep{sql: "FROM license_instances"}, purchaseStep{sql: "INSERT INTO license_instances", args: func(a []driver.NamedValue) bool {
|
||||
savedID = a[0].Value.(string)
|
||||
savedCipher = append([]byte(nil), a[6].Value.([]byte)...)
|
||||
return len(a[4].Value.([]byte)) == 32
|
||||
}}, purchaseStep{sql: "UPDATE client_purchases"}, purchaseStep{sql: "purchase.claimed"})
|
||||
db, d := purchaseDB(t, steps...)
|
||||
a := &BusinessAPI{db: db, credentialEncryptionKey: key}
|
||||
w := purchaseDirect(a, "/", body, a.clientPurchaseClaim)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("claim status=%d", w.Code)
|
||||
}
|
||||
var first struct {
|
||||
Data struct {
|
||||
Instance string `json:"instance_id"`
|
||||
Secret string `json:"secret"`
|
||||
License int `json:"license_id"`
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &first) != nil || first.Data.Instance != savedID || first.Data.License != 6 {
|
||||
t.Fatal("claim response mismatch")
|
||||
}
|
||||
raw, e := base64.RawURLEncoding.DecodeString(first.Data.Secret)
|
||||
if e != nil || len(raw) != 32 || bytes.Contains(savedCipher, []byte(first.Data.Secret)) {
|
||||
t.Fatal("invalid retained credential")
|
||||
}
|
||||
steps = common()
|
||||
steps = append(steps, purchaseStep{sql: "SELECT instance_id FROM client_purchases", rows: one(savedID)}, purchaseStep{sql: "FROM license_instances", rows: one(savedID, savedCipher, "activated", "none")}, purchaseStep{sql: "purchase.claimed"})
|
||||
d.steps = steps
|
||||
w = purchaseDirect(a, "/", body, a.clientPurchaseClaim)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("reclaim status=%d", w.Code)
|
||||
}
|
||||
var response struct{ Data map[string]any }
|
||||
json.Unmarshal(w.Body.Bytes(), &response)
|
||||
if response.Data["instance_id"] != first.Data.Instance || response.Data["secret"] != first.Data.Secret || d.commits != 2 {
|
||||
t.Fatal("claim did not recover same instance and secret")
|
||||
}
|
||||
}
|
||||
func TestPurchaseClaimUnpaid(t *testing.T) {
|
||||
body := `{"order_no":"01234567890123456789012345678901","installation_id":"install"}`
|
||||
db, d := purchaseDB(t, purchaseStep{sql: "WHERE cp.credential_id", rows: one(int64(42))}, scopeStep(), purchaseStep{sql: "FROM offline_orders", rows: one("pending_payment", nil)})
|
||||
a := &BusinessAPI{db: db, credentialEncryptionKey: make([]byte, 32)}
|
||||
w := purchaseDirect(a, "/", body, a.clientPurchaseClaim)
|
||||
if w.Code != 409 || d.commits != 0 {
|
||||
t.Fatal("unpaid claim accepted")
|
||||
}
|
||||
}
|
||||
func TestPaymentPlanValidation(t *testing.T) {
|
||||
p := paymentPlan{ProductID: 1, Code: "basic", Name: "基础套餐", AmountCents: 1, Currency: "CNY", LicenseDays: 30}
|
||||
if !validPlan(p) {
|
||||
t.Fatal("valid plan rejected")
|
||||
}
|
||||
for _, change := range []func(*paymentPlan){func(p *paymentPlan) { p.Currency = "USD" }, func(p *paymentPlan) { p.LicenseDays = 0 }, func(p *paymentPlan) { p.LicenseDays = 3651 }, func(p *paymentPlan) { p.AmountCents = 0 }, func(p *paymentPlan) { p.Code = "bad code" }} {
|
||||
bad := p
|
||||
change(&bad)
|
||||
if validPlan(bad) {
|
||||
t.Fatal("invalid plan accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPurchaseClaimRejectsInactiveInstance(t *testing.T) {
|
||||
for _, state := range []struct{ status, freeze string }{{"activated", "frozen"}, {"revoked", "none"}, {"unknown", "none"}} {
|
||||
t.Run(state.status+state.freeze, func(t *testing.T) {
|
||||
db, d := purchaseDB(t, purchaseStep{sql: "WHERE cp.credential_id", rows: one(int64(42))}, scopeStep(), purchaseStep{sql: "FROM offline_orders", rows: one("issued", int64(6))}, purchaseStep{sql: "SELECT status FROM payment_orders", rows: one("paid")}, purchaseStep{sql: "FROM licenses", rows: one("license", "active", time.Now().Add(time.Hour))}, purchaseStep{sql: "SELECT instance_id FROM client_purchases", rows: one("instance")}, purchaseStep{sql: "FROM license_instances", rows: one("instance", []byte("cipher"), state.status, state.freeze)})
|
||||
a := &BusinessAPI{db: db, credentialEncryptionKey: make([]byte, 32)}
|
||||
w := purchaseDirect(a, "/", `{"order_no":"01234567890123456789012345678901","installation_id":"install"}`, a.clientPurchaseClaim)
|
||||
if w.Code != 409 || !strings.Contains(w.Body.String(), "authorization_unavailable") || strings.Contains(w.Body.String(), "secret") || d.commits != 0 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestPurchaseCredentialEnableAudit(t *testing.T) {
|
||||
for _, auditFail := range []bool{false, true} {
|
||||
for _, enabled := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(auditFail, enabled), func(t *testing.T) {
|
||||
var auditErr error
|
||||
if auditFail {
|
||||
auditErr = errors.New("audit unavailable")
|
||||
}
|
||||
db, d := purchaseDB(t, purchaseStep{sql: "SELECT id FROM admins", rows: one(int64(4))}, purchaseStep{sql: "FROM purchase_credentials WHERE id=? FOR UPDATE", rows: one(int64(2), int64(3), "label", !enabled)}, purchaseStep{sql: "UPDATE purchase_credentials SET enabled=?", args: func(a []driver.NamedValue) bool { return a[0].Value == enabled && a[1].Value == int64(1) }}, purchaseStep{sql: "purchase.credential.updated", err: auditErr, args: func(a []driver.NamedValue) bool {
|
||||
var details map[string]bool
|
||||
return json.Unmarshal(a[2].Value.([]byte), &details) == nil && details["enabled"] == enabled
|
||||
}})
|
||||
a := &BusinessAPI{db: db}
|
||||
r := gin.New()
|
||||
r.PUT("/:id", purchaseAdminBoundary, func(c *gin.Context) { c.Set("admin_id", uint64(4)) }, a.updatePurchaseCredential)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("PUT", "/1", strings.NewReader(fmt.Sprintf(`{"enabled":%t}`, enabled))))
|
||||
want := 200
|
||||
commits := 1
|
||||
if auditFail {
|
||||
want = 503
|
||||
commits = 0
|
||||
}
|
||||
if w.Code != want || d.commits != commits || w.Header().Get("Cache-Control") != "no-store" || strings.Contains(w.Body.String(), "token") {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, body := range []string{`{}`, `{"enabled":null}`, `{"enabled":"false"}`} {
|
||||
a := &BusinessAPI{}
|
||||
r := gin.New()
|
||||
r.PUT("/:id", a.updatePurchaseCredential)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("PUT", "/1", strings.NewReader(body)))
|
||||
if w.Code != 400 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const RequiredSchemaVersion = 15
|
||||
const RequiredSchemaVersion = 16
|
||||
|
||||
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
|
||||
r.GET("/api/v1/health/ready", func(c *gin.Context) {
|
||||
|
||||
Reference in New Issue
Block a user