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

144 lines
7.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpapi
import (
"archive/zip"
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/gin-gonic/gin"
)
func mustReadClientAsset(name string) []byte {
content, err := integrationAssets.ReadFile("integration_assets/" + name)
if err != nil {
panic(err)
}
return content
}
func languageRequirements(language string) string {
return map[string]string{
"python": "Python:使用 cryptography 的 ECDSA(SHA256) 和 httpx;base64 补齐填充后解码 DER;pytest 覆盖验签与状态机。密钥库通过可注入接口实现,禁止以硬编码加密密钥充当保护。",
"go": "Go:使用 crypto/ecdsa.VerifyASN1、crypto/x509、sha256 和 base64.RawStdEncoding;所有网络调用支持 context、超时及取消;sync.Mutex 与跨进程文件锁保护状态;go test 覆盖行为。",
"java": "Java:使用 JCA SHA256withECDSA、KeyFactory EC、X509EncodedKeySpec 与 HttpClient;Base64 解码 DER;受控调度器与原子文件替换;JUnit 覆盖行为。",
"dotnet": ".NET:使用 ECDsa.VerifyData 并显式选择 DSASignatureFormat.Rfc3279DerSequence,不使用默认 P1363;HttpClient、CancellationToken、受控 IHostedService 与可注入受保护存储;xUnit 覆盖行为。",
"nodejs": "Node.js:使用 node:crypto 的 verify('sha256', canonicalBytes, publicKey, DER);license-v2/lease-v2 使用 protocol.md 的 canonical bytes,update-v1 使用解码后的原始 JSON bytes;使用安全整数解析 ID;node:test 覆盖行为;不得将服务端 SDK 打包进浏览器。",
}[language]
}
func signedKitVectors() ([]byte, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
publicDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return nil, err
}
sign := func(payload map[string]any, canonical string) (map[string]any, error) {
digest := sha256.Sum256([]byte(canonical))
signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
if err != nil {
return nil, err
}
return map[string]any{"payload": payload, "signature": base64.RawStdEncoding.EncodeToString(signature), "canonical_sha256": hex.EncodeToString(digest[:]), "canonical": canonical}, nil
}
instance := "11111111-2222-3333-4444-555555555555"
licensePayload := map[string]any{"version": "license-v2", "instance_id": instance, "license_id": 1, "customer_id": 2, "product_id": 3, "starts_at": "2026-10-09T03:00:00Z", "expires_at": "2027-10-09T03:00:00Z", "key_id": "integration-test-only"}
licenseCanonical := "version=license-v2\ninstance_id=" + instance + "\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-10-09T03:00:00Z\nexpires_at=2027-10-09T03:00:00Z\nkey_id=integration-test-only"
leasePayload := map[string]any{"version": "lease-v2", "instance_id": instance, "state": "active", "server_time": "2026-10-09T03:00:00Z", "entitlement_expires_at": "2027-10-09T03:00:00Z", "lease_expires_at": "2026-10-23T03:00:00Z", "key_id": "integration-test-only"}
leaseCanonical := "version=lease-v2\ninstance_id=" + instance + "\nstate=active\nserver_time=2026-10-09T03:00:00Z\nentitlement_expires_at=2027-10-09T03:00:00Z\nlease_expires_at=2026-10-23T03:00:00Z\nkey_id=integration-test-only"
license, err := sign(licensePayload, licenseCanonical)
if err != nil {
return nil, err
}
lease, err := sign(leasePayload, leaseCanonical)
if err != nil {
return nil, err
}
return json.MarshalIndent(map[string]any{"warning": "TEST ONLY: never trust this key in production; use frozen now=2026-10-09T03:00:00Z for state tests", "pinned_keys": []map[string]any{{"key_id": "integration-test-only", "public_key_pem": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER})), "revoked": false}}, "license": license, "lease": lease}, "", " ")
}
func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
language, mode, ok := integrationKitInput(c)
if !ok {
return
}
vectors, err := signedKitVectors()
if err != nil {
apiError(c, 500, "internal_error", "测试资料生成失败")
return
}
kit := buildIntegrationKit(language, mode)
keys, err := a.deploymentVerificationKeys()
if err != nil {
apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥")
return
}
files := map[string][]byte{
"README.md": []byte(`# 客户端接入参考包
先选择人工交付或扫码新购路径,阅读 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 测试由测试脚本生成本地签名。
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"),
"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", "purchase.md", "upgrade.md", "openapi.json"} {
content, err := integrationAsset(name)
if err != nil {
apiError(c, 500, "internal_error", "接入资料不可用")
return
}
files[name] = content
}
var buffer bytes.Buffer
archive := zip.NewWriter(&buffer)
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])
}
if err != nil {
apiError(c, 500, "internal_error", "接入包生成失败")
return
}
}
if err := archive.Close(); err != nil {
apiError(c, 500, "internal_error", "接入包生成失败")
return
}
c.Header("Cache-Control", "no-store")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s.zip", language, mode))
c.Data(200, "application/zip", buffer.Bytes())
}