feat: implement license platform business flows and delivery tooling
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation.

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-09 15:33:22 +08:00
parent 3ab651d3a8
commit 54c318c615
142 changed files with 11105 additions and 178 deletions

View File

@@ -0,0 +1,253 @@
package httpapi
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
var packageKeyPattern = regexp.MustCompile(`^[0-9a-f]{64}\.bin$`)
var releaseVersionPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
// Each package must be a regular file directly below a trusted, non-public root.
func localPackage(root, key string) (string, error) {
if root == "" || !filepath.IsAbs(root) || !packageKeyPattern.MatchString(key) {
return "", errors.New("invalid storage configuration")
}
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return "", err
}
path := filepath.Join(realRoot, key)
info, err := os.Lstat(path)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() {
return "", errors.New("not a regular package")
}
return path, nil
}
func (a *BusinessAPI) createRelease(c *gin.Context) {
productID, err := strconv.ParseUint(c.Param("id"), 10, 64)
version := c.Query("version")
root := os.Getenv("PACKAGE_STORAGE_ROOT")
if err != nil || productID == 0 || !releaseVersionPattern.MatchString(version) {
apiError(c, 400, "invalid_request", "产品或版本无效")
return
}
if root == "" || !filepath.IsAbs(root) {
apiError(c, 503, "storage_unavailable", "文件存储未配置")
return
}
root, err = filepath.EvalSymlinks(root)
if err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var active bool
if err = tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", productID).Scan(&active); err != nil || !active {
apiError(c, 409, "invalid_state", "产品不可发布")
return
}
file, err := os.CreateTemp(root, ".upload-")
if err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
defer os.Remove(file.Name())
defer file.Close()
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<20)
hash := sha256.New()
n, err := io.Copy(io.MultiWriter(file, hash), c.Request.Body)
if err != nil || n == 0 {
apiError(c, 400, "invalid_package", "包为空或超过DEV 64MiB限制")
return
}
digest := hex.EncodeToString(hash.Sum(nil))
key := digest + ".bin"
if _, err = tx.ExecContext(c, "INSERT INTO package_objects(sha256,size_bytes) VALUES(?,?) ON DUPLICATE KEY UPDATE sha256=sha256", digest, n); err != nil {
apiError(c, 500, "internal_error", "发布失败")
return
}
var storedSize int64
if err = tx.QueryRowContext(c, "SELECT size_bytes FROM package_objects WHERE sha256=? FOR UPDATE", digest).Scan(&storedSize); err != nil || storedSize != n {
apiError(c, 409, "package_integrity", "包元数据不匹配")
return
}
if err = file.Sync(); err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
file.Close()
// Hard link publishes immutable bytes without overwriting an existing digest.
publishedPath := filepath.Join(root, key)
linked := false
if err = os.Link(file.Name(), publishedPath); err != nil && !os.IsExist(err) {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
if err == nil {
linked = true
}
cleanupPublished := func() {
if linked {
_ = os.Remove(publishedPath)
}
}
path, err := localPackage(root, key)
if err != nil {
cleanupPublished()
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
existing, err := os.Open(path)
if err != nil {
cleanupPublished()
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
verify := sha256.New()
size, err := io.Copy(verify, existing)
existing.Close()
if err != nil || size != n || hex.EncodeToString(verify.Sum(nil)) != digest {
cleanupPublished()
apiError(c, 409, "package_integrity", "已存文件不匹配")
return
}
result, err := tx.ExecContext(c, "INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,?,?,?,?,?)", productID, version, key, digest, n, c.GetUint64("admin_id"))
if err != nil {
cleanupPublished()
apiError(c, 409, "release_conflict", "版本已存在或不可发布")
return
}
id, err := result.LastInsertId()
if err != nil {
cleanupPublished()
apiError(c, 500, "internal_error", "发布失败")
return
}
details, _ := json.Marshal(gin.H{"product_id": productID, "version": version, "sha256": digest, "size_bytes": n})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'release.published','product_release',?,?)", c.GetUint64("admin_id"), id, details); err != nil {
cleanupPublished()
apiError(c, 500, "internal_error", "发布失败")
return
}
if err = tx.Commit(); err != nil {
// Commit can succeed remotely even when its acknowledgement is lost.
// Keep the private content object for reconciliation, never delete here.
apiError(c, 500, "internal_error", "发布失败")
return
}
c.JSON(201, gin.H{"data": gin.H{"id": id, "product_id": productID, "version": version, "sha256": digest, "size_bytes": n}})
}
func (a *BusinessAPI) downloadRelease(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
var in struct {
InstanceID string `json:"instance_id"`
Secret string `json:"secret"`
}
if c.ShouldBindJSON(&in) != nil || len(in.InstanceID) != 36 || len(in.Secret) > 128 {
apiError(c, 400, "invalid_request", "下载请求无效")
return
}
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
if err != nil || len(raw) != 32 {
apiError(c, 403, "forbidden", "下载凭据无效")
return
}
customerID, err := strconv.ParseUint(c.Param("customer_id"), 10, 64)
if err != nil || customerID == 0 {
apiError(c, 400, "invalid_request", "客户无效")
return
}
releaseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || releaseID == 0 {
apiError(c, 400, "invalid_request", "版本无效")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var id, actor, owner, productID uint64
var stored []byte
var status, freeze, licenseStatus, customerStatus string
var active bool
var starts, expires, now time.Time
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.secret_hash,i.status,i.freeze_state,l.status,c.status,p.active,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id AND l.customer_id=i.customer_id AND l.product_id=i.product_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=? FOR UPDATE`, in.InstanceID).Scan(&id, &actor, &owner, &productID, &stored, &status, &freeze, &licenseStatus, &customerStatus, &active, &starts, &expires)
sum := sha256.Sum256(raw)
if err != nil || !bytesEqual(stored, sum[:]) {
apiError(c, 403, "forbidden", "下载凭据无效")
return
}
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
allowed := owner == customerID && leaseState(status, freeze, licenseStatus, customerStatus, active, starts, expires, now) == "active"
var key, digest string
var n uint64
if allowed {
err = tx.QueryRowContext(c, "SELECT storage_key,sha256,size_bytes FROM product_releases WHERE id=? AND product_id=? AND published=1 FOR UPDATE", releaseID, productID).Scan(&key, &digest, &n)
allowed = err == nil
}
action := "release.download_denied"
if allowed {
action = "release.download_authorized"
}
details, _ := json.Marshal(gin.H{"instance_id": in.InstanceID, "customer_id": customerID, "release_id": releaseID, "client_actor": "instance"})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'license_instance',?,?)", actor, action, id, details); err != nil {
apiError(c, 500, "internal_error", "下载审计失败")
return
}
if !allowed {
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "下载审计失败")
return
}
apiError(c, 403, "forbidden", "无下载权限")
return
}
path, err := localPackage(os.Getenv("PACKAGE_STORAGE_ROOT"), key)
if err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
info, err := os.Stat(path)
if err != nil || uint64(info.Size()) != n {
apiError(c, 503, "storage_unavailable", "文件存储不匹配")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "下载审计失败")
return
}
c.Header("X-Accel-Redirect", "/_packages/"+key)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", `attachment; filename="`+key+`"`)
c.Header("X-Package-SHA256", digest)
c.Header("Cache-Control", "private, no-store")
c.Status(200)
}