From cfcc9b386bbe1986703a7057de01e6bbf84eeb51 Mon Sep 17 00:00:00 2001 From: xiewenjun <88080888@163.com> Date: Thu, 15 Oct 2026 17:33:52 +0800 Subject: [PATCH] feat: add client self-service purchases and integration kit Co-Authored-By: Craft Agent --- backend/internal/httpapi/business.go | 12 + .../internal/httpapi/integration_archive.go | 31 +- .../integration_assets/client/purchase-sdk.md | 36 ++ .../client/purchase-sdk.mjs | 142 ++++++ .../client/test-purchase-sdk.mjs | 159 ++++++ .../integration_assets/client/verify.mjs | 52 ++ .../httpapi/integration_assets/openapi.json | 452 +++++++++++++++++- .../httpapi/integration_assets/protocol.md | 6 +- .../httpapi/integration_assets/purchase.md | 24 + backend/internal/httpapi/integration_kit.go | 15 +- .../internal/httpapi/integration_kit_test.go | 26 +- backend/internal/httpapi/operations.go | 7 +- .../httpapi/operations_boundary_test.go | 2 +- backend/internal/httpapi/purchase_admin.go | 269 +++++++++++ backend/internal/httpapi/purchase_claim.go | 116 +++++ backend/internal/httpapi/purchase_client.go | 312 ++++++++++++ backend/internal/httpapi/purchase_test.go | 375 +++++++++++++++ backend/internal/httpapi/readiness.go | 2 +- .../000016_client_purchases.down.sql | 5 + .../migrations/000016_client_purchases.up.sql | 57 +++ client/purchase-sdk.md | 36 ++ client/purchase-sdk.mjs | 142 ++++++ client/test-purchase-sdk.mjs | 159 ++++++ docs/client-integration-center.md | 16 +- docs/client-self-service-purchases.md | 43 ++ frontend/src/purchase-config-api.test.ts | 20 + frontend/src/purchase-config-api.ts | 29 ++ frontend/src/router.ts | 2 +- frontend/src/views/IntegrationPanel.test.ts | 9 +- frontend/src/views/IntegrationPanel.vue | 29 +- frontend/src/views/Overview.vue | 6 +- frontend/src/views/PurchasePlansPanel.test.ts | 14 + frontend/src/views/PurchasePlansPanel.vue | 37 ++ 33 files changed, 2598 insertions(+), 44 deletions(-) create mode 100644 backend/internal/httpapi/integration_assets/client/purchase-sdk.md create mode 100644 backend/internal/httpapi/integration_assets/client/purchase-sdk.mjs create mode 100644 backend/internal/httpapi/integration_assets/client/test-purchase-sdk.mjs create mode 100644 backend/internal/httpapi/integration_assets/client/verify.mjs create mode 100644 backend/internal/httpapi/integration_assets/purchase.md create mode 100644 backend/internal/httpapi/purchase_admin.go create mode 100644 backend/internal/httpapi/purchase_claim.go create mode 100644 backend/internal/httpapi/purchase_client.go create mode 100644 backend/internal/httpapi/purchase_test.go create mode 100644 backend/migrations/000016_client_purchases.down.sql create mode 100644 backend/migrations/000016_client_purchases.up.sql create mode 100644 client/purchase-sdk.md create mode 100644 client/purchase-sdk.mjs create mode 100644 client/test-purchase-sdk.mjs create mode 100644 docs/client-self-service-purchases.md create mode 100644 frontend/src/purchase-config-api.test.ts create mode 100644 frontend/src/purchase-config-api.ts create mode 100644 frontend/src/views/PurchasePlansPanel.test.ts create mode 100644 frontend/src/views/PurchasePlansPanel.vue diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go index 78b4992..69973a2 100644 --- a/backend/internal/httpapi/business.go +++ b/backend/internal/httpapi/business.go @@ -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) diff --git a/backend/internal/httpapi/integration_archive.go b/backend/internal/httpapi/integration_archive.go index cbaca70..1ada491 100644 --- a/backend/internal/httpapi/integration_archive.go +++ b/backend/internal/httpapi/integration_archive.go @@ -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]) diff --git a/backend/internal/httpapi/integration_assets/client/purchase-sdk.md b/backend/internal/httpapi/integration_assets/client/purchase-sdk.md new file mode 100644 index 0000000..e447e57 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/client/purchase-sdk.md @@ -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_`,不显示任意原始 `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`。以上字段已与后端实现会话确认;接入实际服务前仍需运行真实服务集成测试。 diff --git a/backend/internal/httpapi/integration_assets/client/purchase-sdk.mjs b/backend/internal/httpapi/integration_assets/client/purchase-sdk.mjs new file mode 100644 index 0000000..7e19681 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/client/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()); + } +} diff --git a/backend/internal/httpapi/integration_assets/client/test-purchase-sdk.mjs b/backend/internal/httpapi/integration_assets/client/test-purchase-sdk.mjs new file mode 100644 index 0000000..77eef96 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/client/test-purchase-sdk.mjs @@ -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' }); +}); diff --git a/backend/internal/httpapi/integration_assets/client/verify.mjs b/backend/internal/httpapi/integration_assets/client/verify.mjs new file mode 100644 index 0000000..e9d6968 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/client/verify.mjs @@ -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; +} diff --git a/backend/internal/httpapi/integration_assets/openapi.json b/backend/internal/httpapi/integration_assets/openapi.json index 28061c6..64e3cf1 100644 --- a/backend/internal/httpapi/integration_assets/openapi.json +++ b/backend/internal/httpapi/integration_assets/openapi.json @@ -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" } } } diff --git a/backend/internal/httpapi/integration_assets/protocol.md b/backend/internal/httpapi/integration_assets/protocol.md index d46286f..c3160ca 100644 --- a/backend/internal/httpapi/integration_assets/protocol.md +++ b/backend/internal/httpapi/integration_assets/protocol.md @@ -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。配置加密留存后管理员可重复查看并导出;旧实例仅存哈希时无法恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。 diff --git a/backend/internal/httpapi/integration_assets/purchase.md b/backend/internal/httpapi/integration_assets/purchase.md new file mode 100644 index 0000000..2a5bd13 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/purchase.md @@ -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 后关闭窗口,需妥善保护、按需停用或轮换购买凭据。 + +离线测试不能证明生产商户付款、公网通知、真实数据库迁移和实际桌面客户端集成已验收。 diff --git a/backend/internal/httpapi/integration_kit.go b/backend/internal/httpapi/integration_kit.go index 25f9cd3..1734eb6 100644 --- a/backend/internal/httpapi/integration_kit.go +++ b/backend/internal/httpapi/integration_kit.go @@ -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())) diff --git a/backend/internal/httpapi/integration_kit_test.go b/backend/internal/httpapi/integration_kit_test.go index 9e18716..5bbbac2 100644 --- a/backend/internal/httpapi/integration_kit_test.go +++ b/backend/internal/httpapi/integration_kit_test.go @@ -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) diff --git a/backend/internal/httpapi/operations.go b/backend/internal/httpapi/operations.go index c131a93..8008322 100644 --- a/backend/internal/httpapi/operations.go +++ b/backend/internal/httpapi/operations.go @@ -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 } diff --git a/backend/internal/httpapi/operations_boundary_test.go b/backend/internal/httpapi/operations_boundary_test.go index 231a02a..7118384 100644 --- a/backend/internal/httpapi/operations_boundary_test.go +++ b/backend/internal/httpapi/operations_boundary_test.go @@ -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 diff --git a/backend/internal/httpapi/purchase_admin.go b/backend/internal/httpapi/purchase_admin.go new file mode 100644 index 0000000..a74e9a5 --- /dev/null +++ b/backend/internal/httpapi/purchase_admin.go @@ -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", "购买服务暂时不可用") +} diff --git a/backend/internal/httpapi/purchase_claim.go b/backend/internal/httpapi/purchase_claim.go new file mode 100644 index 0000000..218f147 --- /dev/null +++ b/backend/internal/httpapi/purchase_claim.go @@ -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}}) +} diff --git a/backend/internal/httpapi/purchase_client.go b/backend/internal/httpapi/purchase_client.go new file mode 100644 index 0000000..65a6bb5 --- /dev/null +++ b/backend/internal/httpapi/purchase_client.go @@ -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 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) + } + } +} diff --git a/backend/internal/httpapi/readiness.go b/backend/internal/httpapi/readiness.go index 6562251..52ef8de 100644 --- a/backend/internal/httpapi/readiness.go +++ b/backend/internal/httpapi/readiness.go @@ -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) { diff --git a/backend/migrations/000016_client_purchases.down.sql b/backend/migrations/000016_client_purchases.down.sql new file mode 100644 index 0000000..9aa3a79 --- /dev/null +++ b/backend/migrations/000016_client_purchases.down.sql @@ -0,0 +1,5 @@ +DROP TABLE client_purchases; +ALTER TABLE payment_orders DROP FOREIGN KEY fk_payment_plan_version, DROP COLUMN plan_version, DROP COLUMN plan_id; +DROP TABLE purchase_credentials; +DROP TABLE payment_plan_versions; +DROP TABLE payment_plans; diff --git a/backend/migrations/000016_client_purchases.up.sql b/backend/migrations/000016_client_purchases.up.sql new file mode 100644 index 0000000..dbe2c60 --- /dev/null +++ b/backend/migrations/000016_client_purchases.up.sql @@ -0,0 +1,57 @@ +-- Operator-applied only. Fixed days start at successful payment issuance (UTC, 24 hours/day). +CREATE TABLE payment_plans ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + product_id BIGINT UNSIGNED NOT NULL, + code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + name VARCHAR(190) NOT NULL, + amount_cents BIGINT UNSIGNED NOT NULL, + currency CHAR(3) NOT NULL DEFAULT 'CNY', + license_days INT UNSIGNED NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + version BIGINT UNSIGNED NOT NULL DEFAULT 1, + UNIQUE KEY uq_plan_code(product_id,code), + FOREIGN KEY(product_id) REFERENCES products(id) +) ENGINE=InnoDB; +CREATE TABLE payment_plan_versions ( + plan_id BIGINT UNSIGNED NOT NULL, + version BIGINT UNSIGNED NOT NULL, + product_id BIGINT UNSIGNED NOT NULL, + code VARCHAR(64) NOT NULL, + name VARCHAR(190) NOT NULL, + amount_cents BIGINT UNSIGNED NOT NULL, + currency CHAR(3) NOT NULL, + license_days INT UNSIGNED NOT NULL, + enabled BOOLEAN NOT NULL, + created_by BIGINT UNSIGNED NOT NULL, + PRIMARY KEY(plan_id,version), + FOREIGN KEY(plan_id) REFERENCES payment_plans(id), + FOREIGN KEY(created_by) REFERENCES admins(id) +) ENGINE=InnoDB; +CREATE TABLE purchase_credentials ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + token_hash BINARY(32) NOT NULL UNIQUE, + customer_id BIGINT UNSIGNED NOT NULL, + product_id BIGINT UNSIGNED NOT NULL, + label VARCHAR(190) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + created_by BIGINT UNSIGNED NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + FOREIGN KEY(customer_id) REFERENCES customers(id), + FOREIGN KEY(product_id) REFERENCES products(id), + FOREIGN KEY(created_by) REFERENCES admins(id) +) ENGINE=InnoDB; +ALTER TABLE payment_orders + ADD COLUMN plan_id BIGINT UNSIGNED NULL, + ADD COLUMN plan_version BIGINT UNSIGNED NULL, + ADD CONSTRAINT fk_payment_plan_version FOREIGN KEY(plan_id,plan_version) REFERENCES payment_plan_versions(plan_id,version); +CREATE TABLE client_purchases ( + order_id BIGINT UNSIGNED NOT NULL PRIMARY KEY, + credential_id BIGINT UNSIGNED NOT NULL, + installation_id VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + request_fingerprint BINARY(32) NOT NULL, + instance_id CHAR(36) NULL, + UNIQUE KEY uq_client_purchase_key(credential_id,idempotency_key), + FOREIGN KEY(order_id) REFERENCES offline_orders(id), + FOREIGN KEY(credential_id) REFERENCES purchase_credentials(id) +) ENGINE=InnoDB; diff --git a/client/purchase-sdk.md b/client/purchase-sdk.md new file mode 100644 index 0000000..e447e57 --- /dev/null +++ b/client/purchase-sdk.md @@ -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_`,不显示任意原始 `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`。以上字段已与后端实现会话确认;接入实际服务前仍需运行真实服务集成测试。 diff --git a/client/purchase-sdk.mjs b/client/purchase-sdk.mjs new file mode 100644 index 0000000..7e19681 --- /dev/null +++ b/client/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()); + } +} diff --git a/client/test-purchase-sdk.mjs b/client/test-purchase-sdk.mjs new file mode 100644 index 0000000..77eef96 --- /dev/null +++ b/client/test-purchase-sdk.mjs @@ -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' }); +}); diff --git a/docs/client-integration-center.md b/docs/client-integration-center.md index b83e5a0..fc949b0 100644 --- a/docs/client-integration-center.md +++ b/docs/client-integration-center.md @@ -1,6 +1,6 @@ # 客户端接入中心 -管理员登录后进入 `/integration`,选择 Python、Go、Java、.NET 或 Node.js,以及桌面、常驻服务或容器模式。页面提供接口清单、工程提示词、协议、安全约束、字段示例和 ZIP/Markdown 下载。ZIP 现在包含可运行的 Python 与 Node.js 升级参考 SDK;其余语言提供同契约实现要求,不能把参考 SDK 宣称为五种语言均已生产验收。 +管理员登录后进入 `/integration`,选择 Python、Go、Java、.NET 或 Node.js,以及桌面、常驻服务或容器模式。页面提供人工实例交付、客户端扫码新购两种授权获取路径,以及接口清单、工程提示词、协议、安全约束、字段示例和 ZIP/Markdown 下载。ZIP 包含 Python/Node.js 升级参考 SDK 与 Node.js 购买参考 SDK;其余语言的购买 SDK 需自行实现,不能宣称五种语言均已生产验收。 SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权平台根地址;部署可以通过 `LICENSE_API_BASE_URL` 覆盖,但必须是 HTTPS 根地址,不能附加 `/api/v1`。 @@ -8,10 +8,14 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权 - `/api/v1/integration-kit?language=python&mode=service`:JSON 资料。 - `/api/v1/integration-kit/download?...`:UTF-8 Markdown,包含选定提示词、协议、update-v1 升级契约和当前部署验签公钥。 -- `/api/v1/integration-kit/archive?...`:ZIP,包含 README、protocol、upgrade、OpenAPI、prompt、部署公钥、测试向量,以及 Python/Node 升级参考 SDK、对应测试脚本和 `client/requirements.txt`。 +- `/api/v1/integration-kit/archive?...`:ZIP,包含 README、protocol、purchase、upgrade、OpenAPI、prompt、部署公钥、测试向量,Python/Node 升级 SDK,以及 Node 购买 SDK、验签依赖和测试。 公钥必须经可信渠道核对指纹后预置,不能把服务端发现结果自动变成信任根。ZIP 中测试向量使用随机测试密钥,绝不能导入生产。 +## 扫码新购接入 + +人工交付的实例信任 JSON 绑定已有实例,不适用于扫码新购前。管理员先配置既有客户、产品、启用套餐及受限购买凭据,经受控渠道分别交付 Token 与部署公钥;Token 不进入公共 ZIP 或安装包。宿主原子保存幂等键,查询套餐并扫码下单;服务端验签确认付款签发后,claim 幂等领取实例凭据并先安全落盘,然后按现有 license-v2/lease-v2 协议激活、心跳、验签并落盘才启用。二维码展示期限不等于渠道关单,installation_id 也不是 claim 返回的实例 UUID。见 ZIP 内 `purchase.md` 和 `client/purchase-sdk.md`。 + ## update-v1 客户端契约 客户端调用 `POST /api/v1/instances/{instance_id}/updates/check`,提交 `secret`、`current_version`、`platform`、`arch`、`channel`。响应 payload 是 raw UTF-8 JSON 的标准 Base64,签名是无填充标准 Base64 的 DER ECDSA P-256 SHA-256。客户端必须验证固定字段、实例上下文、可信 key_id、服务端时间/过期时间、15 分钟 TTL 和策略 revision 单调性。 @@ -22,7 +26,7 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权 ## 参考 SDK 与限制 -`client/update_sdk.py` 需要 Python 3.11+、`cryptography` 与 `httpx`,`client/update-sdk.mjs` 需要 Node.js 20+。两者覆盖验签、篡改/上下文/TTL/策略回滚拒绝、禁止重定向下载、长度与摘要校验、原子暂存和注入安装器。调用方应增加跨进程锁、持久化防回拨钩子和本地版本比较测试。 +`client/update_sdk.py` 需要 Python 3.11+、`cryptography` 与 `httpx`,`client/update-sdk.mjs` 和 `client/purchase-sdk.mjs` 需要 Node.js 20+。两者覆盖验签、篡改/上下文/TTL/策略回滚拒绝、禁止重定向下载、长度与摘要校验、原子暂存和注入安装器。调用方应增加跨进程锁、持久化防回拨钩子和本地版本比较测试。 离线不能刷新或延长 update-v1 TTL,网络错误不可伪造强制升级;有效 lease 的离线行为仍按既有租约,过期或时钟回拨必须 fail closed。当前不提供百分比灰度或升级回报接口;容器应由受控 CI/CD 或部署代理升级。完全离线、移动端、CI 临时身份和 Kubernetes 多副本需要额外身份方案。 @@ -30,12 +34,12 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权 管理员创建实例并交付 `instance_id`、`license_key`、`secret`。secret 仅保存于系统密钥库、Vault、Secret 或受限加密文件,不能写 URL、日志、镜像或浏览器 LocalStorage。生产公钥通过受控渠道预置,keyring 发现接口不是信任引导。激活和心跳仍使用原有 license-v2/lease-v2 流程,冻结/撤销的离线残留时间受既有租约限制。 -协议源文件为 `backend/internal/httpapi/integration_assets/protocol.md`,OpenAPI 为同目录 `openapi.json`,升级契约为 `upgrade.md`。修改接口时必须同步核对三者和 ZIP 内容。未提交或部署代码由维护流程另行处理。 +协议源文件为 `backend/internal/httpapi/integration_assets/protocol.md`,购买流程为 `purchase.md`,OpenAPI 为同目录 `openapi.json`,升级契约为 `upgrade.md`。修改接口时必须同步核对四者和 ZIP 内容。未提交或部署代码由维护流程另行处理。 ## 下载能力与验收运行 服务端支持 Range(200/206/416),随包参考 SDK 仅执行完整下载,要求 HTTP 200,拒绝 206,不提供断点续传。需要续传时由应用另外实现 Range/Content-Range 校验,最终仍须验证整个包的长度与 SHA-256。 -解压 ZIP 后,在 client 目录运行 `python -m pip install -r requirements.txt`、`python -m unittest test_update_sdk -v`;Node.js 20+ 运行 `node test-update-sdk.mjs`,无需 npm 依赖。这些测试使用本地测试密钥和模拟网络,不验证生产下载或安装。 +解压 ZIP 后,在 client 目录运行 `python -m pip install -r requirements.txt`、`python -m unittest test_update_sdk -v`;Node.js 20+ 运行 `node test-update-sdk.mjs` 和 `node --test test-purchase-sdk.mjs`,无需 npm 依赖。这些测试使用本地测试密钥和模拟网络,不验证生产下载或安装。 -当前参考 SDK 没有完整 LicenseClient、canRun、本地强制升级评估、信任导入器或持久化存储实现。应用必须实现并注入持久化 StateStore,按实例/平台/架构/渠道保存 revision 高水位,并自行实现可信时间防回拨、本地 SemVer 比较和 deadline 判断。下载前及安装前重新检查策略,验证 TTL、授权和当前版本;安装器负责兼容性、跨进程锁、替换、重启、健康检查及回滚。 +升级参考 SDK 没有完整 LicenseClient、canRun、本地强制升级评估、信任导入器或持久化存储实现。Node 购买参考 SDK 覆盖新购、领取、激活、验签和租约,但依赖宿主提供购买凭据安全导入、OS 保护的原子存储、跨进程锁、可信公钥交付及二维码界面。应用必须实现并注入持久化 StateStore,按实例/平台/架构/渠道保存 revision 高水位,并自行实现可信时间防回拨、本地 SemVer 比较和 deadline 判断。下载前及安装前重新检查策略,验证 TTL、授权和当前版本;安装器负责兼容性、跨进程锁、替换、重启、健康检查及回滚。 diff --git a/docs/client-self-service-purchases.md b/docs/client-self-service-purchases.md new file mode 100644 index 0000000..10aee56 --- /dev/null +++ b/docs/client-self-service-purchases.md @@ -0,0 +1,43 @@ +# 后台套餐与客户端扫码新购(2026-10-15) + +本次新增后台套餐管理、限定客户/产品的购买凭据、客户端购买 API 和 Node.js SDK。实际桌面软件工程未提供,当前交付为平台接口与可集成 SDK,不代表真实终端已经上线。 + +## 业务范围 + +管理员先配置有效客户和产品,在套餐管理中设置人民币价格(整数分)、固定天数、名称及启停状态,再为指定客户和产品创建购买凭据。凭据仅创建时返回明文;数据库保存其 SHA-256 摘要。凭据是限定客户/产品的购买入口,不能调用管理员 API,也不是客户账号登录会话。通过安全通道导入对应终端,不得放入 URL、日志或共享安装包。 + +本版仅首次购买新授权;不支持已有许可证在线续费、自注册、重装迁移、退款权益回收、委托自动扣款。期限为固定24小时天数,从服务端确认并签发时起算;30/90/365/1825天不得展示成自然月/季度/年/五年。50/500/800/1000元可作为手动填写示例,没有自动发布或修改这些价格。 + +套餐修改追加不可变版本,使用原版本号进行乐观并发检查。订单冻结套餐版本、金额、币种、期限和支付渠道配置版本。支付与签发复用原有事务,只有官方验签通知或验签查单可以确认付款;当前尚未重构为独立异步履约队列。 + +## API + +后台使用已有管理员会话,并验证来源、禁止缓存: + +- `GET/POST /api/v1/payment-plans` +- `PUT /api/v1/payment-plans/:id`(完整字段和当前 `version`;产品/代码不可改) +- `GET/POST /api/v1/purchase-credentials` +- `PUT /api/v1/purchase-credentials/:id`(`enabled`) + +客户端以下全部使用 `Authorization: Bearer <购买凭据>`,不可使用后台会话代替: + +- `POST /api/v1/client/plans` 返回 `data.plans`(套餐 `id`、`version`)及可用渠道。 +- `POST /api/v1/client/purchases`,请求 `plan_id,plan_version,installation_id,channel` 和 `Idempotency-Key`。 +- `POST /api/v1/client/purchases/status`,请求 `installation_id` 加 `order_no`,响应丢失时可改用原 `idempotency_key` 恢复。 +- `POST /api/v1/client/purchases/claim`,请求 `installation_id,order_no`,成功返回实例 ID、授权密钥、实例 secret 和 license_id。 + +`status` 表示支付状态(created/paid),`order_status` 表示业务订单状态(pending_payment/paid/issued)。`qr_expired` 仅表示二维码展示期限,不表示渠道已经关单;不得据此新建不同渠道订单并假定旧订单无法再支付。claim 只有已付款且签发完成才能成功;重复领取恢复原实例及相同加密保管的凭据。安装 ID 只参与订单归属,服务端另外生成授权实例 UUID。 + +## 客户端接入 + +参见 `client/purchase-sdk.md` 和 `client/purchase-sdk.mjs`。宿主提供产品 ID、稳定安装 ID、管理员安全发放的购买凭据、固定可信签名公钥、OS 保护的原子持久存储及二维码 UI。先持久化订单参数/幂等键再请求下单,网络不确定时恢复同一订单。官方确认付款后领取凭据、落盘、激活、验签证书及租约;全部通过才允许功能启用。后续持续心跳和限制离线租约。 + +Bearer 凭据可被持有者使用,安装 ID 不是硬件证明;不得宣称实现不可复制硬件绑定。本版重复领取用于网络失败恢复,尚未实现 ACK 后关闭领取窗口,必须保护、禁用或轮换购买凭据。客户端进程间并发由宿主锁/CAS控制。 + +## 部署与验证 + +新增迁移 `000016_client_purchases`,服务最低 schema16。启动不会自动迁移;运维先备份并显式执行,不能在现有进程未切换前随意 down。down 会删除套餐版本、购买归属和凭据数据,必须单独审批。历史13—15迁移未修改。 + +所有API进程必须配置相同的独立 `PAYMENT_CONFIG_ENCRYPTION_KEY_FILE` 和 `LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE`,各为绝对路径、32原始字节密钥;配置有效授权签名私钥和可信公钥。支付渠道必须通过后台保存已发布版本;本版客户端购买不使用未发布的环境渠道配置。 + +本轮未连接业务数据库、执行业务迁移、保存真实商户凭据或测试真实支付。Go单元/协议测试、前端测试与构建、SDK离线模拟不能替代MySQL隔离迁移及真实公网小额支付验收。上线前在隔离库验证16 up/down、并发幂等及数据库约束,再验证真实扫码、通知重放、漏通知查单、进程重启和领取响应丢失恢复。 diff --git a/frontend/src/purchase-config-api.test.ts b/frontend/src/purchase-config-api.test.ts new file mode 100644 index 0000000..0be0303 --- /dev/null +++ b/frontend/src/purchase-config-api.test.ts @@ -0,0 +1,20 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { ApiError } from './api' +import { createPaymentPlan, createPurchaseCredential, listPaymentPlans, listPurchaseCredentials, purchaseConfigError, setPurchaseCredentialEnabled, updatePaymentPlan } from './purchase-config-api' +vi.mock('./api',()=>({api:{get:vi.fn(),post:vi.fn(),put:vi.fn()},ApiError:class ApiError extends Error{code?:string;status?:number;constructor(message:string,code?:string,status?:number){super(message);this.code=code;this.status=status}}})) +import { api } from './api' +describe('purchase config API',()=>{ + afterEach(()=>vi.clearAllMocks()) + it('uses admin API endpoints and exact write payloads',async()=>{ + vi.mocked(api.get).mockResolvedValue({data:{data:[]}} as never);vi.mocked(api.post).mockResolvedValue({data:{data:{}}} as never);vi.mocked(api.put).mockResolvedValue({data:{data:{}}} as never) + const input={product_id:3,code:'p30',name:'30天',amount_cents:5000,currency:'CNY' as const,license_days:30,enabled:false} + const update={...input,version:2} + await listPaymentPlans();await createPaymentPlan(input);await updatePaymentPlan(8,update);await listPurchaseCredentials();await createPurchaseCredential({customer_id:4,product_id:3,label:'桌面端'});await setPurchaseCredentialEnabled(9,false) + expect(api.get).toHaveBeenNthCalledWith(1,'/payment-plans');expect(api.post).toHaveBeenCalledWith('/payment-plans',input);expect(api.put).toHaveBeenNthCalledWith(1,'/payment-plans/8',update);expect(api.get).toHaveBeenNthCalledWith(2,'/purchase-credentials');expect(api.post).toHaveBeenCalledWith('/purchase-credentials',{customer_id:4,product_id:3,label:'桌面端'});expect(api.put).toHaveBeenNthCalledWith(2,'/purchase-credentials/9',{enabled:false}) + }) + it('returns fixed allowlisted errors and never returns raw server messages',()=>{ + expect(purchaseConfigError(new ApiError('secret backend detail','invalid_request',400),'fallback')).toBe('填写内容无效,请检查金额、固定天数与客户产品范围') + expect(purchaseConfigError(new ApiError('secret backend detail','unknown_error',500),'安全的默认提示')).toBe('安全的默认提示') + expect(purchaseConfigError(new ApiError('x','x',401),'fallback')).toBe('登录已失效,请重新登录') + }) +}) diff --git a/frontend/src/purchase-config-api.ts b/frontend/src/purchase-config-api.ts new file mode 100644 index 0000000..891488f --- /dev/null +++ b/frontend/src/purchase-config-api.ts @@ -0,0 +1,29 @@ +import { api, ApiError } from './api' + +export type PaymentPlan = { id:number; product_id:number; code:string; name:string; amount_cents:number; currency:'CNY'|string; license_days:number; enabled:boolean; version:number } +export type PurchaseCredential = { id:number; customer_id:number; product_id:number; label:string; enabled:boolean; created_at?:string } +export type PlanInput = Omit +export type PlanUpdate = PlanInput & {version:number} + +export function purchaseConfigError(error:unknown, fallback:string) { + if (!(error instanceof ApiError)) return fallback + if (error.status === 401) return '登录已失效,请重新登录' + if (error.status === 403) return '无权限管理套餐与购买凭据,请联系管理员' + if (error.status === 404) return '服务版本不支持该接口,请更新并重启服务' + const messages:Record = { + plan_conflict:'套餐编码已存在,请使用其他编码', + plan_version_conflict:'套餐已被其他管理员修改,请刷新后重新编辑', + plan_identity_conflict:'套餐产品与编码不可修改,请创建新套餐', + product_unavailable:'产品不可用,请选择有效产品', + scope_unavailable:'客户或产品范围不可用,请重新选择', + invalid_request:'填写内容无效,请检查金额、固定天数与客户产品范围', + purchase_unavailable:'购买服务暂不可用,请稍后重试', + } + return error.code && messages[error.code] || fallback +} +export async function listPaymentPlans() { return api.get<{data:PaymentPlan[]}>('/payment-plans') } +export async function createPaymentPlan(value:PlanInput) { return api.post<{data:PaymentPlan}>('/payment-plans',value) } +export async function updatePaymentPlan(id:number,value:PlanUpdate) { return api.put<{data:PaymentPlan}>(`/payment-plans/${id}`,value) } +export async function listPurchaseCredentials() { return api.get<{data:PurchaseCredential[]}>('/purchase-credentials') } +export async function createPurchaseCredential(value:Pick) { return api.post<{data:PurchaseCredential & {token:string}}>('/purchase-credentials',value) } +export async function setPurchaseCredentialEnabled(id:number,enabled:boolean) { return api.put<{data:PurchaseCredential}>(`/purchase-credentials/${id}`,{enabled}) } diff --git a/frontend/src/router.ts b/frontend/src/router.ts index 6d719be..44b6510 100644 --- a/frontend/src/router.ts +++ b/frontend/src/router.ts @@ -5,7 +5,7 @@ import Checkout from './views/Checkout.vue' export default createRouter({ history: createWebHistory(), routes: [ - ...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})), + ...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/payment-plans',view:'payment-plans'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})), {path:'/checkout',component:Checkout,meta:{public:true}}, {path:'/customer',component:CustomerPortal}, {path:'/:pathMatch(.*)*',redirect:'/'} diff --git a/frontend/src/views/IntegrationPanel.test.ts b/frontend/src/views/IntegrationPanel.test.ts index 901c97b..4edbe61 100644 --- a/frontend/src/views/IntegrationPanel.test.ts +++ b/frontend/src/views/IntegrationPanel.test.ts @@ -14,6 +14,13 @@ describe('IntegrationPanel',()=>{ expect(wrapper.text()).toContain('https://license.yihuiyong.cn');expect(wrapper.text()).toContain('LICENSE_API_BASE_URL') expect(wrapper.find('a[href*="archive"]').attributes('href')).toContain('language=python&mode=service') expect(wrapper.find('a[href*="download"]').exists()).toBe(true) + expect(wrapper.text()).toContain('管理员交付实例') + const purchaseMode = wrapper.find('input[type="radio"][value="purchase"]') + expect(purchaseMode.exists()).toBe(true) + await purchaseMode.setValue(); await flushPromises() + expect(wrapper.text()).toContain('先原子保存购买参数与幂等键') + expect(wrapper.text()).toContain('购买前没有实例') + expect(wrapper.text()).toContain('purchase.md') await wrapper.find('select[aria-label="目标语言"]').setValue('dotnet');await flushPromises() expect(calls.getIntegrationKit).toHaveBeenLastCalledWith('dotnet','service') expect(wrapper.find('a[href*="archive"]').attributes('href')).toContain('language=dotnet') @@ -22,6 +29,6 @@ describe('IntegrationPanel',()=>{ it('shows API failures without retaining old content',async()=>{ calls.getIntegrationKit.mockRejectedValueOnce(new Error('资料不可用')) const wrapper=mount(IntegrationPanel,{global:{plugins:[ElementPlus]}});await flushPromises() - expect(wrapper.text()).toContain('资料不可用');expect(wrapper.find('.prompt-box').exists()).toBe(false);wrapper.unmount() + expect(wrapper.text()).toContain('接入资料加载失败,请稍后重试');expect(wrapper.text()).not.toContain('资料不可用');expect(wrapper.find('.prompt-box').exists()).toBe(false);wrapper.unmount() }) }) diff --git a/frontend/src/views/IntegrationPanel.vue b/frontend/src/views/IntegrationPanel.vue index ee58a24..a57198b 100644 --- a/frontend/src/views/IntegrationPanel.vue +++ b/frontend/src/views/IntegrationPanel.vue @@ -5,6 +5,7 @@ import { ElMessage } from 'element-plus' import { getIntegrationKit, type IntegrationKit, type IntegrationLanguage, type IntegrationMode } from '../admin-api' const language = ref('python') +const acquisition = ref<'manual'|'purchase'>('manual') const mode = ref('service') const kit = ref(null) const loading = ref(false) @@ -23,7 +24,7 @@ async function load() { const sequence = ++requestSequence loading.value = true; error.value = ''; kit.value = null try { const result = await getIntegrationKit(language.value, mode.value); if (sequence === requestSequence) kit.value = result.data.data } - catch (e) { if (sequence === requestSequence) error.value = e instanceof Error ? e.message : '接入资料加载失败' } + catch { if (sequence === requestSequence) error.value = '接入资料加载失败,请稍后重试' } finally { if (sequence === requestSequence) loading.value = false } } async function copyPrompt() { @@ -37,14 +38,21 @@ onMounted(load)