fix: make client integration kit self-contained and clarify capabilities
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -31,7 +31,7 @@ func languageRequirements(language string) string {
|
||||
"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),参照 client/verify.mjs;使用安全整数解析 ID;node:test 覆盖行为;不得将服务端 SDK 打包进浏览器。",
|
||||
"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]
|
||||
}
|
||||
|
||||
@@ -85,12 +85,26 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
files := map[string][]byte{
|
||||
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json。client/update_sdk.py 和 client/update-sdk.mjs 是可运行的参考 SDK,覆盖 update-v1 验签、TTL、策略回滚、禁止重定向下载、长度/摘要校验和注入式安装器;不执行任意命令。prompt.md 可提供给实现工程师。verification-keys.md 包含当前部署验签公钥,经可信渠道核对指纹后预置;test-vectors.json 使用随机测试密钥,绝不能导入生产。\n"),
|
||||
"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"),
|
||||
"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 授权。
|
||||
|
||||
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
|
||||
|
||||
测试使用本地密钥和模拟网络,不证明生产安装可用。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"),
|
||||
}
|
||||
for _, name := range []string{"protocol.md", "upgrade.md", "openapi.json"} {
|
||||
content, err := integrationAsset(name)
|
||||
@@ -102,7 +116,7 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
|
||||
}
|
||||
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"} {
|
||||
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"} {
|
||||
file, err := archive.Create(name)
|
||||
if err == nil {
|
||||
_, err = file.Write(files[name])
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
cryptography>=41
|
||||
httpx>=0.25,<1
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
|
||||
import { mkdtemp, readdir, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { UpdateClient, UpdateError, verifyCheck } from './update-sdk.mjs';
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
||||
const now = Date.now();
|
||||
const payload = {version:'update-v1',instance_id:'i1',product_id:1,customer_id:2,current_version:'1.0.0',platform:'linux',arch:'x64',channel:'stable',server_time:new Date(now).toISOString().replace('.000Z','Z'),expires_at:new Date(now+600000).toISOString().replace('.000Z','Z'),policy_revision:3,policy_enabled:true,recommended_version:'2.0.0',minimum_supported_version:'1.0.0',enforce_after:'',mandatory:false,required_now:false,update_available:true,download_allowed:true,release_id:7,sha256:createHash('sha256').update('good').digest('hex'),size_bytes:4,message:''};
|
||||
function envelope(p = payload) { const raw = Buffer.from(JSON.stringify(p)); return {payload:raw.toString('base64').replace(/=+$/,''),signature:sign('sha256',raw,privateKey).toString('base64').replace(/=+$/,''),key_id:'k1'}; }
|
||||
const keys = {k1:publicKey.export({type:'spki',format:'pem'})};
|
||||
const signed = envelope();
|
||||
verifyCheck(signed, keys, 'i1', {now,expectedPlatform:'linux',expectedArch:'x64',expectedChannel:'stable',expectedCurrentVersion:'1.0.0'});
|
||||
const tampered = {...signed, payload:Buffer.from('{"version":"update-v1"}').toString('base64').replace(/=+$/,'')};
|
||||
assert.throws(() => verifyCheck(tampered, keys, 'i1', {now}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'wrong', {now}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'i1', {now:now+600001}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'i1', {now,previous:{policy_revision:4}}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'i1', {now,expectedCurrentVersion:'0.9'}), UpdateError);
|
||||
|
||||
for (const [status, chunks, expected] of [[200,['good-extra'],'package_too_large'],[206,['good'],'download_http_206'],[302,[],'download_http_302'],[500,[],'download_http_500'],[200,['evil'],'package_integrity_failed']]) {
|
||||
const dir = await mkdtemp(join(tmpdir(),'update-sdk-')); const target = join(dir,'pkg.bin');
|
||||
const fetchImpl = async () => new Response(Readable.toWeb(Readable.from(chunks.map(x => Buffer.from(x)))), {status,headers: status===302?{location:'https://evil.invalid'}:{}});
|
||||
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,fetchImpl});
|
||||
await assert.rejects(client.download({payload},target), e => e instanceof UpdateError && e.message.includes(expected));
|
||||
assert.deepEqual(await readdir(dir), []); await rm(dir,{recursive:true,force:true});
|
||||
}
|
||||
|
||||
let persisted;
|
||||
const state = {load:()=>persisted,saveAtomic:value=>{persisted=value;}};
|
||||
const fetchImpl = async () => Response.json({data:signed});
|
||||
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,state,fetchImpl,clock:()=>now});
|
||||
persisted={scope:JSON.stringify(['i1','windows','x64','stable']),policy_revision:99};
|
||||
assert.equal((await client.check('1.0.0','linux','x64','stable')).payload.policy_revision,3);
|
||||
console.log('Node update SDK negative tests passed');
|
||||
@@ -0,0 +1,72 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import httpx
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
from update_sdk import UpdateClient, UpdateError, verify_check
|
||||
|
||||
|
||||
class MemoryState:
|
||||
def __init__(self, value=None): self.value = value
|
||||
def load(self): return self.value
|
||||
def save_atomic(self, state): self.value = state
|
||||
|
||||
|
||||
class SDKTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.private = ec.generate_private_key(ec.SECP256R1())
|
||||
self.public = self.private.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
||||
self.now = __import__('time').time()
|
||||
stamp = datetime.fromtimestamp(self.now, timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
self.payload = {"version":"update-v1","instance_id":"i1","product_id":1,"customer_id":2,"current_version":"1.0.0","platform":"linux","arch":"x64","channel":"stable","server_time":stamp,"expires_at":datetime.fromtimestamp(self.now+600, timezone.utc).isoformat().replace('+00:00','Z'),"policy_revision":3,"policy_enabled":True,"recommended_version":"2.0.0","minimum_supported_version":"1.0.0","enforce_after":"","mandatory":False,"required_now":False,"update_available":True,"download_allowed":True,"release_id":7,"sha256":hashlib.sha256(b'good').hexdigest(),"size_bytes":4,"message":""}
|
||||
self.envelope = self.sign(self.payload)
|
||||
|
||||
def sign(self, payload):
|
||||
raw = json.dumps(payload, separators=(',', ':')).encode()
|
||||
sig = self.private.sign(raw, ec.ECDSA(hashes.SHA256()))
|
||||
return {"payload":base64.b64encode(raw).decode().rstrip('='),"signature":base64.b64encode(sig).decode().rstrip('='),"key_id":"k1"}
|
||||
|
||||
def test_signature_context_expiry_and_rollback(self):
|
||||
verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_platform="linux", expected_arch="x64", expected_channel="stable", expected_current_version="1.0.0")
|
||||
tampered = dict(self.envelope); tampered["payload"] = base64.b64encode(b'{"version":"update-v1"}').decode().rstrip('=')
|
||||
with self.assertRaises(UpdateError): verify_check(tampered, {"k1":self.public}, "i1", now=self.now)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "wrong", now=self.now)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now+601)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, previous={"policy_revision":4})
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_current_version="0.9")
|
||||
|
||||
def client(self, handler, state=None):
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = httpx.Client(transport=transport, follow_redirects=False)
|
||||
return UpdateClient('https://license.example', 'i1', 'secret', {"k1":self.public}, state=state, client=client)
|
||||
|
||||
def test_stream_download_bounds_redirect_and_cleanup(self):
|
||||
cases = [
|
||||
(lambda req: httpx.Response(200, content=b'good-extra'), 'package_too_large'),
|
||||
(lambda req: httpx.Response(302, headers={"location":"https://evil.invalid"}), 'download_http_302'),
|
||||
(lambda req: httpx.Response(200, content=b'evil'), 'package_integrity_failed'),
|
||||
]
|
||||
for handler, expected_error in cases:
|
||||
with self.subTest(error=expected_error), tempfile.TemporaryDirectory() as directory:
|
||||
target = Path(directory) / 'pkg.bin'
|
||||
sdk = self.client(handler)
|
||||
with self.assertRaises(UpdateError) as caught: sdk.download(type('R', (), {"payload":self.payload})(), target)
|
||||
self.assertIn(expected_error, str(caught.exception))
|
||||
self.assertFalse(target.exists())
|
||||
self.assertEqual(list(Path(directory).iterdir()), [])
|
||||
|
||||
def test_scoped_revision_does_not_leak_between_platforms(self):
|
||||
state = MemoryState({"scope": '["i1","windows","x64","stable"]', "policy_revision":99})
|
||||
sdk = self.client(lambda req: httpx.Response(200, json={"data":self.envelope}), state)
|
||||
result = sdk.check('1.0.0','linux','x64','stable')
|
||||
self.assertEqual(result.payload['policy_revision'], 3)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Reference client for the signed update-v1 contract.
|
||||
|
||||
Requires Python 3.11 and the ``cryptography`` package. No installer is executed
|
||||
Requires Python 3.11+ and the ``cryptography`` and ``httpx`` packages. No installer is executed
|
||||
by this module; callers inject an installer after verification.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -66,7 +66,7 @@ canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校
|
||||
|
||||
## 时间与状态存储
|
||||
|
||||
参照 client/verify.mjs:now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。
|
||||
客户端必须实现以下租约状态判断(升级 SDK 不实现 license-v2/lease-v2 授权):now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。
|
||||
|
||||
验签、范围检查后,先在受保护存储中原子保存实例 ID、租约、enabled、服务端与本地时间高水位,再启用业务。离线每次授权检查都应检查本地时间回拨,并持久化更新本地高水位。应用重新启动不得清除高水位绕过限制。
|
||||
|
||||
@@ -80,7 +80,7 @@ canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校
|
||||
|
||||
## 发布包下载
|
||||
|
||||
POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。支持 Range 续传,处理 200/206/416 和 Content-Range。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。
|
||||
POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。服务端支持 Range 续传,调用方实现续传时须处理 200/206/416 和 Content-Range。随包 Python/Node 升级参考 SDK 仅完整下载并要求 HTTP 200,不实现续传。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。
|
||||
|
||||
## 模式约束
|
||||
|
||||
|
||||
@@ -10,13 +10,13 @@
|
||||
|
||||
`POST /api/v1/instances/{instance_id}/updates/check`
|
||||
|
||||
请求 JSON:`{"secret":"...","current_version":"1.2.3","platform":"windows","arch":"amd64","channel":"stable"}`。
|
||||
请求 JSON:`{"secret":"...","current_version":"1.2.3","platform":"windows","arch":"x64","channel":"stable"}`。
|
||||
|
||||
响应 `200` 的 `data` 是签名 envelope:`{"payload":"<base64(raw UTF-8 JSON)>","signature":"<unpadded standard base64 DER ECDSA>","key_id":"current"}`。使用受控渠道预置的 P-256 公钥,验证 ECDSA SHA-256 对解码后的 raw bytes 签名。不得把服务端返回的 key 当作信任根。解码 JSON 必须严格包含 `version`、`instance_id`、`product_id`、`customer_id`、`current_version`、`platform`、`arch`、`channel`、`server_time`、`expires_at`、`policy_revision`、`policy_enabled`、`recommended_version`、`minimum_supported_version`、`enforce_after`、`mandatory`、`required_now`、`update_available`、`download_allowed`、`release_id`、`sha256`、`size_bytes`、`message`。
|
||||
|
||||
客户端必须核对实例上下文、服务端时间与当前时间偏差不超过 5 分钟、`expires_at` 未过期且不超过 `server_time + 15min`,并持久化拒绝 `policy_revision` 回退。`required_now` 只在签名验证、策略有效且本地版本比较确认低于最低支持版本后生效;`mandatory` 不能绕过用户/维护窗口、下载或包校验。`enforce_after` 为空表示无截止时间。
|
||||
|
||||
无策略或策略关闭时,服务端返回 `policy_enabled=false` 且 release 元数据为空/不可下载。`canRun` 不得把升级检查通过、`download_allowed` 或 active entitlement 当成授权许可;业务运行仍由独立、已验证的 license-v2/lease-v2 状态决定。
|
||||
无策略时,服务端返回 `policy_enabled=false`、空版本/摘要字符串和零 release ID/大小。策略关闭时可能保留 release 元数据,但 `download_allowed=false`、`update_available=false`,不得据此下载。`canRun` 不得把升级检查通过、`download_allowed` 或 active entitlement 当成授权许可;业务运行仍由独立、已验证的 license-v2/lease-v2 状态决定。
|
||||
|
||||
## 下载与安装边界
|
||||
|
||||
@@ -26,8 +26,16 @@ SDK 只提供 check、download、摘要校验和注入式 Installer。安装器
|
||||
|
||||
## 离线、错误与 rollout 限制
|
||||
|
||||
离线不能刷新检查结果或延长 15 分钟 envelope TTL;不能因检查失败伪造强制升级。有效 license lease 的离线运行按既有租约策略执行,过期或回拨必须 fail closed。网络错误、401/403、409、429 和 5xx 只允许有限重试,不把 HTTP 错误解释成策略。灰度由服务端策略决定,客户端不得自行伪造命中;当前协议不提供升级回报接口。策略 revision 是单调高水位,检测到回退立即拒绝。
|
||||
离线不能刷新检查结果或延长 15 分钟 envelope TTL;不能因检查失败伪造强制升级。有效 license lease 的离线运行按既有租约策略执行,过期或回拨必须 fail closed。网络错误、401/403、409、429 和 5xx 只允许有限重试,不把 HTTP 错误解释成策略。当前仅按产品/平台/架构/渠道选择策略,不提供百分比灰度;当前协议不提供升级回报接口。策略 revision 是单调高水位,检测到回退立即拒绝。
|
||||
|
||||
## 参考实现
|
||||
|
||||
仓库提供 `client/update_sdk.py`(Python 3.11 + cryptography)和 `client/update-sdk.mjs`(Node.js 20+,内置 crypto/fetch),包含验签、上下文/TTL/回滚检查、禁止重定向的下载、长度与摘要校验及注入安装器。其它语言应按同一 raw payload、DER ECDSA、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。
|
||||
仓库提供 `client/update_sdk.py`(Python 3.11+、cryptography 和 httpx)和 `client/update-sdk.mjs`(Node.js 20+,内置 crypto/fetch),包含验签、上下文/TTL/回滚检查、禁止重定向的下载、长度与摘要校验及注入安装器。其它语言应按同一 raw payload、DER ECDSA、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。
|
||||
|
||||
## 下载能力与验收运行
|
||||
|
||||
服务端支持 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 依赖。这些测试使用本地测试密钥和模拟网络,不验证生产下载或安装。
|
||||
|
||||
当前参考 SDK 没有完整 LicenseClient、canRun、本地强制升级评估、信任导入器或持久化存储实现。应用必须实现并注入持久化 StateStore,按实例/平台/架构/渠道保存 revision 高水位,并自行实现可信时间防回拨、本地 SemVer 比较和 deadline 判断。下载前及安装前重新检查策略,验证 TTL、授权和当前版本;安装器负责兼容性、跨进程锁、替换、重启、健康检查及回滚。
|
||||
|
||||
@@ -102,7 +102,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,按 upgrade.md 覆盖篡改、上下文、deadline、hash、离线和回退。",
|
||||
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、离线和回退。",
|
||||
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 +123,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。支持管理台导出的 .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。
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -77,7 +78,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(archive.File) != 9 {
|
||||
if len(archive.File) != 12 {
|
||||
t.Fatal("missing files")
|
||||
}
|
||||
for _, file := range archive.File {
|
||||
@@ -99,8 +100,18 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
if file.Name == "upgrade.md" && (!strings.Contains(string(content), "update-v1") || !strings.Contains(string(content), "required_now")) {
|
||||
t.Fatal("missing upgrade plan")
|
||||
}
|
||||
if file.Name == "client/update_sdk.py" && !strings.Contains(string(content), "def verify_check") { t.Fatal("missing Python SDK") }
|
||||
if file.Name == "client/update-sdk.mjs" && !strings.Contains(string(content), "verifyCheck") { t.Fatal("missing Node SDK") }
|
||||
if file.Name == "client/update_sdk.py" && !strings.Contains(string(content), "def verify_check") {
|
||||
t.Fatal("missing Python SDK")
|
||||
}
|
||||
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"`)) {
|
||||
t.Fatal("invalid reference or architecture")
|
||||
}
|
||||
if file.Name == "README.md" && (!strings.Contains(string(content), "requirements.txt") || !strings.Contains(string(content), "不支持 Range")) {
|
||||
t.Fatal("missing SDK setup or capabilities")
|
||||
}
|
||||
if file.Name != "test-vectors.json" {
|
||||
continue
|
||||
}
|
||||
@@ -134,3 +145,15 @@ 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"} {
|
||||
source, err := os.ReadFile("../../../client/" + name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(source, mustReadClientAsset("client/"+name)) {
|
||||
t.Fatalf("SDK copy differs: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
2
client/requirements.txt
Normal file
2
client/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
cryptography>=41
|
||||
httpx>=0.25,<1
|
||||
@@ -8,11 +8,11 @@ import { UpdateClient, UpdateError, verifyCheck } from './update-sdk.mjs';
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
||||
const now = Date.now();
|
||||
const payload = {version:'update-v1',instance_id:'i1',product_id:1,customer_id:2,current_version:'1.0',platform:'linux',arch:'x64',channel:'stable',server_time:new Date(now).toISOString().replace('.000Z','Z'),expires_at:new Date(now+600000).toISOString().replace('.000Z','Z'),policy_revision:3,policy_enabled:true,recommended_version:'2.0',minimum_supported_version:'1.0',enforce_after:null,mandatory:false,required_now:false,update_available:true,download_allowed:true,release_id:7,sha256:createHash('sha256').update('good').digest('hex'),size_bytes:4,message:''};
|
||||
const payload = {version:'update-v1',instance_id:'i1',product_id:1,customer_id:2,current_version:'1.0.0',platform:'linux',arch:'x64',channel:'stable',server_time:new Date(now).toISOString().replace('.000Z','Z'),expires_at:new Date(now+600000).toISOString().replace('.000Z','Z'),policy_revision:3,policy_enabled:true,recommended_version:'2.0.0',minimum_supported_version:'1.0.0',enforce_after:'',mandatory:false,required_now:false,update_available:true,download_allowed:true,release_id:7,sha256:createHash('sha256').update('good').digest('hex'),size_bytes:4,message:''};
|
||||
function envelope(p = payload) { const raw = Buffer.from(JSON.stringify(p)); return {payload:raw.toString('base64').replace(/=+$/,''),signature:sign('sha256',raw,privateKey).toString('base64').replace(/=+$/,''),key_id:'k1'}; }
|
||||
const keys = {k1:publicKey.export({type:'spki',format:'pem'})};
|
||||
const signed = envelope();
|
||||
verifyCheck(signed, keys, 'i1', {now,expectedPlatform:'linux',expectedArch:'x64',expectedChannel:'stable',expectedCurrentVersion:'1.0'});
|
||||
verifyCheck(signed, keys, 'i1', {now,expectedPlatform:'linux',expectedArch:'x64',expectedChannel:'stable',expectedCurrentVersion:'1.0.0'});
|
||||
const tampered = {...signed, payload:Buffer.from('{"version":"update-v1"}').toString('base64').replace(/=+$/,'')};
|
||||
assert.throws(() => verifyCheck(tampered, keys, 'i1', {now}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'wrong', {now}), UpdateError);
|
||||
@@ -33,5 +33,5 @@ const state = {load:()=>persisted,saveAtomic:value=>{persisted=value;}};
|
||||
const fetchImpl = async () => Response.json({data:signed});
|
||||
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,state,fetchImpl,clock:()=>now});
|
||||
persisted={scope:JSON.stringify(['i1','windows','x64','stable']),policy_revision:99};
|
||||
assert.equal((await client.check('1.0','linux','x64','stable')).payload.policy_revision,3);
|
||||
assert.equal((await client.check('1.0.0','linux','x64','stable')).payload.policy_revision,3);
|
||||
console.log('Node update SDK negative tests passed');
|
||||
|
||||
@@ -25,7 +25,7 @@ class SDKTests(unittest.TestCase):
|
||||
self.public = self.private.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
||||
self.now = __import__('time').time()
|
||||
stamp = datetime.fromtimestamp(self.now, timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
self.payload = {"version":"update-v1","instance_id":"i1","product_id":1,"customer_id":2,"current_version":"1.0","platform":"linux","arch":"x64","channel":"stable","server_time":stamp,"expires_at":datetime.fromtimestamp(self.now+600, timezone.utc).isoformat().replace('+00:00','Z'),"policy_revision":3,"policy_enabled":True,"recommended_version":"2.0","minimum_supported_version":"1.0","enforce_after":None,"mandatory":False,"required_now":False,"update_available":True,"download_allowed":True,"release_id":7,"sha256":hashlib.sha256(b'good').hexdigest(),"size_bytes":4,"message":""}
|
||||
self.payload = {"version":"update-v1","instance_id":"i1","product_id":1,"customer_id":2,"current_version":"1.0.0","platform":"linux","arch":"x64","channel":"stable","server_time":stamp,"expires_at":datetime.fromtimestamp(self.now+600, timezone.utc).isoformat().replace('+00:00','Z'),"policy_revision":3,"policy_enabled":True,"recommended_version":"2.0.0","minimum_supported_version":"1.0.0","enforce_after":"","mandatory":False,"required_now":False,"update_available":True,"download_allowed":True,"release_id":7,"sha256":hashlib.sha256(b'good').hexdigest(),"size_bytes":4,"message":""}
|
||||
self.envelope = self.sign(self.payload)
|
||||
|
||||
def sign(self, payload):
|
||||
@@ -34,7 +34,7 @@ class SDKTests(unittest.TestCase):
|
||||
return {"payload":base64.b64encode(raw).decode().rstrip('='),"signature":base64.b64encode(sig).decode().rstrip('='),"key_id":"k1"}
|
||||
|
||||
def test_signature_context_expiry_and_rollback(self):
|
||||
verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_platform="linux", expected_arch="x64", expected_channel="stable", expected_current_version="1.0")
|
||||
verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_platform="linux", expected_arch="x64", expected_channel="stable", expected_current_version="1.0.0")
|
||||
tampered = dict(self.envelope); tampered["payload"] = base64.b64encode(b'{"version":"update-v1"}').decode().rstrip('=')
|
||||
with self.assertRaises(UpdateError): verify_check(tampered, {"k1":self.public}, "i1", now=self.now)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "wrong", now=self.now)
|
||||
@@ -65,7 +65,7 @@ class SDKTests(unittest.TestCase):
|
||||
def test_scoped_revision_does_not_leak_between_platforms(self):
|
||||
state = MemoryState({"scope": '["i1","windows","x64","stable"]', "policy_revision":99})
|
||||
sdk = self.client(lambda req: httpx.Response(200, json={"data":self.envelope}), state)
|
||||
result = sdk.check('1.0','linux','x64','stable')
|
||||
result = sdk.check('1.0.0','linux','x64','stable')
|
||||
self.assertEqual(result.payload['policy_revision'], 3)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Reference client for the signed update-v1 contract.
|
||||
|
||||
Requires Python 3.11 and the ``cryptography`` package. No installer is executed
|
||||
Requires Python 3.11+ and the ``cryptography`` and ``httpx`` packages. No installer is executed
|
||||
by this module; callers inject an installer after verification.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -8,7 +8,7 @@ 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、部署公钥、测试向量,以及 `client/update_sdk.py`、`client/update-sdk.mjs`。
|
||||
- `/api/v1/integration-kit/archive?...`:ZIP,包含 README、protocol、upgrade、OpenAPI、prompt、部署公钥、测试向量,以及 Python/Node 升级参考 SDK、对应测试脚本和 `client/requirements.txt`。
|
||||
|
||||
公钥必须经可信渠道核对指纹后预置,不能把服务端发现结果自动变成信任根。ZIP 中测试向量使用随机测试密钥,绝不能导入生产。
|
||||
|
||||
@@ -16,18 +16,26 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
|
||||
|
||||
客户端调用 `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 单调性。
|
||||
|
||||
`required_now` 是服务端根据 deadline 计算的提示,客户端仍必须使用可信时间、TTL/过期检查和本地版本比较再次判断;`mandatory` 不能绕过用户确认、维护窗口、下载授权或包完整性校验。策略关闭返回 disabled/空 release 元数据。升级检查成功、`download_allowed` 或 active entitlement 都不能实现业务 `canRun`,业务许可仍由独立验签的 license-v2/lease-v2 决定。
|
||||
`required_now` 是服务端根据 deadline 计算的提示,客户端仍必须使用可信时间、TTL/过期检查和本地版本比较再次判断;`mandatory` 不能绕过用户确认、维护窗口、下载授权或包完整性校验。无策略返回 disabled/空 release 元数据;关闭已有策略可能保留元数据,但不允许参考 SDK 下载。升级检查成功、`download_allowed` 或 active entitlement 都不能实现业务 `canRun`,业务许可仍由独立验签的 license-v2/lease-v2 决定。
|
||||
|
||||
只有签名 payload 允许下载时,客户端才调用现有实例认证下载接口。必须同源 HTTPS、禁止重定向、不把 secret 放 URL,验证长度和 SHA-256 后才暂存/交给应用安装器。SDK 不执行 shell、脚本或包内任意命令;安装器、健康检查和回滚由应用注入。
|
||||
|
||||
## 参考 SDK 与限制
|
||||
|
||||
`client/update_sdk.py` 需要 Python 3.11 与 `cryptography`,`client/update-sdk.mjs` 需要 Node.js 20+。两者覆盖验签、篡改/上下文/TTL/策略回滚拒绝、禁止重定向下载、长度与摘要校验、原子暂存和注入安装器。调用方应增加跨进程锁、持久化防回拨钩子和本地版本比较测试。
|
||||
`client/update_sdk.py` 需要 Python 3.11+、`cryptography` 与 `httpx`,`client/update-sdk.mjs` 需要 Node.js 20+。两者覆盖验签、篡改/上下文/TTL/策略回滚拒绝、禁止重定向下载、长度与摘要校验、原子暂存和注入安装器。调用方应增加跨进程锁、持久化防回拨钩子和本地版本比较测试。
|
||||
|
||||
离线不能刷新或延长 update-v1 TTL,网络错误不可伪造强制升级;有效 lease 的离线行为仍按既有租约,过期或时钟回拨必须 fail closed。灰度由服务端决定,当前不提供升级回报接口;容器应由受控 CI/CD 或部署代理升级。完全离线、移动端、CI 临时身份和 Kubernetes 多副本需要额外身份方案。
|
||||
离线不能刷新或延长 update-v1 TTL,网络错误不可伪造强制升级;有效 lease 的离线行为仍按既有租约,过期或时钟回拨必须 fail closed。当前不提供百分比灰度或升级回报接口;容器应由受控 CI/CD 或部署代理升级。完全离线、移动端、CI 临时身份和 Kubernetes 多副本需要额外身份方案。
|
||||
|
||||
## 授权与信任交付
|
||||
|
||||
管理员创建实例并交付 `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 内容。未提交或部署代码由维护流程另行处理。
|
||||
|
||||
## 下载能力与验收运行
|
||||
|
||||
服务端支持 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 依赖。这些测试使用本地测试密钥和模拟网络,不验证生产下载或安装。
|
||||
|
||||
当前参考 SDK 没有完整 LicenseClient、canRun、本地强制升级评估、信任导入器或持久化存储实现。应用必须实现并注入持久化 StateStore,按实例/平台/架构/渠道保存 revision 高水位,并自行实现可信时间防回拨、本地 SemVer 比较和 deadline 判断。下载前及安装前重新检查策略,验证 TTL、授权和当前版本;安装器负责兼容性、跨进程锁、替换、重启、健康检查及回滚。
|
||||
|
||||
@@ -69,7 +69,7 @@ onMounted(load)
|
||||
<h3>首次激活凭据从哪里获取?</h3>
|
||||
<p>进入“License 授权”,签发授权后点击该行“实例”,选择“创建实例并获取激活凭据”。授权码是后台授权密钥(license_key);实例 ID(instance_id)和激活密钥(secret)由平台生成。每条授权仅绑定一个实例,配置加密留存后可重复查看和下载,旧实例仅存哈希时无法恢复。secret 持续用于心跳和下载;验签公钥及实例绑定从管理台交付并由开发团队预置。</p>
|
||||
<h3>客户端升级方案</h3>
|
||||
<p class="subheading">当前支持实例门户版本查询和授权下载;ZIP、Markdown 及工程提示词包含 UpdateClient 查询、下载、校验和安装适配要求。签名升级清单、平台匹配、灰度和升级回报仍待建设。</p>
|
||||
<p class="subheading">当前支持实例门户版本查询和授权下载;ZIP、Markdown 及工程提示词包含 UpdateClient 查询、下载、校验和安装适配要求。已提供 update-v1 签名升级检查;参考 SDK 仅完整下载。应用须实现平台兼容性、强制升级评估、安装与回滚;灰度和升级回报尚未提供。</p>
|
||||
<details><summary>查看升级流程、安全边界与三种部署方案</summary><pre class="vector-box">{{ kit.upgrade }}</pre></details>
|
||||
<h3>租约字段示例</h3>
|
||||
<pre class="vector-box">{{ JSON.stringify(kit.payload_example, null, 2) }}</pre>
|
||||
|
||||
Reference in New Issue
Block a user