From 54c318c615b218ddc07b274d61218e702bf8bbb6 Mon Sep 17 00:00:00 2001 From: xiewenjun <88080888@163.com> Date: Fri, 9 Oct 2026 15:33:22 +0800 Subject: [PATCH] feat: implement license platform business flows and delivery tooling 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 --- .dockerignore | 14 + .env.example | 35 + .github/workflows/check.yml | 28 +- README.md | 4 +- backend/cmd/admin-init/main.go | 85 ++ backend/cmd/migrate/main.go | 54 + backend/cmd/server/main.go | 98 +- backend/go.mod | 22 +- backend/go.sum | 89 +- backend/internal/config/config.go | 98 ++ backend/internal/config/config_test.go | 64 + backend/internal/httpapi/activation.go | 348 +++++ .../httpapi/activation_integration_test.go | 129 ++ backend/internal/httpapi/activation_public.go | 28 + backend/internal/httpapi/activation_test.go | 49 + backend/internal/httpapi/admin_accounts.go | 246 ++++ .../internal/httpapi/admin_accounts_test.go | 47 + backend/internal/httpapi/admin_settings.go | 255 ++++ .../internal/httpapi/admin_settings_test.go | 99 ++ backend/internal/httpapi/business.go | 372 +++++ .../httpapi/business_integration_test.go | 293 ++++ backend/internal/httpapi/dashboard.go | 111 ++ backend/internal/httpapi/dashboard_test.go | 355 +++++ backend/internal/httpapi/downloads.go | 253 ++++ .../httpapi/downloads_integration_test.go | 270 ++++ backend/internal/httpapi/downloads_test.go | 34 + backend/internal/httpapi/heartbeat.go | 213 +++ .../httpapi/heartbeat_integration_test.go | 140 ++ backend/internal/httpapi/heartbeat_test.go | 67 + backend/internal/httpapi/instance_freeze.go | 92 ++ .../internal/httpapi/integration_archive.go | 106 ++ .../httpapi/integration_assets/openapi.json | 43 + .../httpapi/integration_assets/protocol.md | 75 + backend/internal/httpapi/integration_kit.go | 154 ++ .../internal/httpapi/integration_kit_test.go | 119 ++ backend/internal/httpapi/keyring.go | 91 ++ backend/internal/httpapi/keyring_http_test.go | 36 + backend/internal/httpapi/keyring_test.go | 87 ++ backend/internal/httpapi/licenses.go | 384 +++++ backend/internal/httpapi/licenses_test.go | 102 ++ backend/internal/httpapi/operations.go | 189 +++ .../httpapi/operations_boundary_test.go | 74 + backend/internal/httpapi/operations_test.go | 127 ++ backend/internal/httpapi/orders.go | 346 +++++ .../httpapi/orders_integration_test.go | 150 ++ backend/internal/httpapi/portal.go | 104 ++ .../portal_keyring_integration_test.go | 193 +++ backend/internal/httpapi/portal_test.go | 37 + backend/internal/httpapi/readiness.go | 47 + backend/internal/httpapi/readiness_test.go | 95 ++ backend/internal/httpapi/redis_limiter.go | 84 ++ .../internal/httpapi/redis_limiter_test.go | 83 ++ backend/internal/httpapi/releases_list.go | 42 + backend/internal/httpapi/router.go | 10 +- backend/internal/httpapi/router_test.go | 4 +- backend/internal/httpapi/server.go | 42 + backend/internal/httpapi/server_test.go | 105 ++ .../internal/httpapi/signing_restart_test.go | 178 +++ backend/internal/httpapi/tls_boundary_test.go | 50 + backend/internal/migrations/runner.go | 89 ++ .../migrations/v6_integration_test.go | 83 ++ backend/migrations/000001_core.down.sql | 4 + backend/migrations/000001_core.up.sql | 42 + backend/migrations/000002_licenses.down.sql | 2 + backend/migrations/000002_licenses.up.sql | 32 + .../000003_license_operations.down.sql | 1 + .../000003_license_operations.up.sql | 14 + backend/migrations/000004_orders.down.sql | 2 + backend/migrations/000004_orders.up.sql | 39 + backend/migrations/000005_activation.down.sql | 2 + backend/migrations/000005_activation.up.sql | 39 + .../000006_heartbeat_lease.down.sql | 10 + .../migrations/000006_heartbeat_lease.up.sql | 35 + .../migrations/000007_local_releases.down.sql | 1 + .../migrations/000007_local_releases.up.sql | 15 + .../000008_package_objects.down.sql | 1 + .../migrations/000008_package_objects.up.sql | 5 + .../migrations/000009_admin_settings.down.sql | 2 + .../migrations/000009_admin_settings.up.sql | 11 + .../000010_admin_usernames.down.sql | 2 + .../migrations/000010_admin_usernames.up.sql | 4 + backend/migrations/README.md | 29 + client/verify.mjs | 52 + compose.yaml | 100 ++ deploy/Dockerfile.api | 17 + deploy/Dockerfile.web | 9 + deploy/entrypoint.sh | 10 + deploy/nginx/compose.conf | 22 + deploy/nginx/download-local.conf | 18 + deploy/nginx/tls-proxy.conf.example | 30 + docs/activation-contract-draft.md | 33 + docs/admin-modules.md | 56 + docs/business-contract-draft.md | 28 + docs/business-quickstart.md | 15 + docs/client-integration-center.md | 34 + docs/deployment-delivery.md | 53 + docs/download-contract-draft.md | 32 + docs/heartbeat-lease-contract-draft.md | 53 + docs/keyring-client-contract-draft.md | 37 + docs/license-contract-draft.md | 10 + docs/operations-security.md | 50 + docs/release-gate-matrix.md | 66 + docs/signing-key-operations.md | 11 + docs/task-execution.md | 144 ++ frontend/package-lock.json | 1240 +++++++++++++++++ frontend/package.json | 4 + frontend/src/admin-api.test.ts | 32 + frontend/src/admin-api.ts | 49 + frontend/src/api-health.test.ts | 27 + frontend/src/api-health.ts | 14 + frontend/src/api.ts | 30 + frontend/src/dashboard-api.ts | 3 + frontend/src/date-format.test.ts | 26 + frontend/src/date-format.ts | 16 + frontend/src/orders-api.ts | 9 + frontend/src/router.test.ts | 3 + frontend/src/router.ts | 8 +- frontend/src/style.css | 9 +- frontend/src/views/AdminsPanel.test.ts | 26 + frontend/src/views/AdminsPanel.vue | 16 + frontend/src/views/AuditPanel.test.ts | 60 + frontend/src/views/AuditPanel.vue | 64 + frontend/src/views/CustomerPortal.test.ts | 31 + frontend/src/views/CustomerPortal.vue | 50 + frontend/src/views/DashboardPanel.test.ts | 25 + frontend/src/views/DashboardPanel.vue | 28 + frontend/src/views/IntegrationPanel.test.ts | 27 + frontend/src/views/IntegrationPanel.vue | 62 + frontend/src/views/OrdersPanel.test.ts | 39 + frontend/src/views/OrdersPanel.vue | 90 ++ frontend/src/views/Overview.test.ts | 138 ++ frontend/src/views/Overview.vue | 149 +- frontend/src/views/ReleasesPanel.test.ts | 13 + frontend/src/views/ReleasesPanel.vue | 43 + frontend/src/views/SettingsPanel.test.ts | 53 + frontend/src/views/SettingsPanel.vue | 64 + frontend/vite.config.ts | 15 +- scripts/backup-delivery.sh | 22 + scripts/check-delivery.sh | 18 + scripts/restore-delivery.sh | 22 + ...¶授权与统一管理平台-架构决策与MVP验收规格.md | 79 +- 软件授权与统一管理平台-详细开发任务方案.md | 186 ++- 142 files changed, 11105 insertions(+), 178 deletions(-) create mode 100644 .dockerignore create mode 100644 backend/cmd/admin-init/main.go create mode 100644 backend/cmd/migrate/main.go create mode 100644 backend/internal/config/config.go create mode 100644 backend/internal/config/config_test.go create mode 100644 backend/internal/httpapi/activation.go create mode 100644 backend/internal/httpapi/activation_integration_test.go create mode 100644 backend/internal/httpapi/activation_public.go create mode 100644 backend/internal/httpapi/activation_test.go create mode 100644 backend/internal/httpapi/admin_accounts.go create mode 100644 backend/internal/httpapi/admin_accounts_test.go create mode 100644 backend/internal/httpapi/admin_settings.go create mode 100644 backend/internal/httpapi/admin_settings_test.go create mode 100644 backend/internal/httpapi/business.go create mode 100644 backend/internal/httpapi/business_integration_test.go create mode 100644 backend/internal/httpapi/dashboard.go create mode 100644 backend/internal/httpapi/dashboard_test.go create mode 100644 backend/internal/httpapi/downloads.go create mode 100644 backend/internal/httpapi/downloads_integration_test.go create mode 100644 backend/internal/httpapi/downloads_test.go create mode 100644 backend/internal/httpapi/heartbeat.go create mode 100644 backend/internal/httpapi/heartbeat_integration_test.go create mode 100644 backend/internal/httpapi/heartbeat_test.go create mode 100644 backend/internal/httpapi/instance_freeze.go create mode 100644 backend/internal/httpapi/integration_archive.go create mode 100644 backend/internal/httpapi/integration_assets/openapi.json create mode 100644 backend/internal/httpapi/integration_assets/protocol.md create mode 100644 backend/internal/httpapi/integration_kit.go create mode 100644 backend/internal/httpapi/integration_kit_test.go create mode 100644 backend/internal/httpapi/keyring.go create mode 100644 backend/internal/httpapi/keyring_http_test.go create mode 100644 backend/internal/httpapi/keyring_test.go create mode 100644 backend/internal/httpapi/licenses.go create mode 100644 backend/internal/httpapi/licenses_test.go create mode 100644 backend/internal/httpapi/operations.go create mode 100644 backend/internal/httpapi/operations_boundary_test.go create mode 100644 backend/internal/httpapi/operations_test.go create mode 100644 backend/internal/httpapi/orders.go create mode 100644 backend/internal/httpapi/orders_integration_test.go create mode 100644 backend/internal/httpapi/portal.go create mode 100644 backend/internal/httpapi/portal_keyring_integration_test.go create mode 100644 backend/internal/httpapi/portal_test.go create mode 100644 backend/internal/httpapi/readiness.go create mode 100644 backend/internal/httpapi/readiness_test.go create mode 100644 backend/internal/httpapi/redis_limiter.go create mode 100644 backend/internal/httpapi/redis_limiter_test.go create mode 100644 backend/internal/httpapi/releases_list.go create mode 100644 backend/internal/httpapi/server.go create mode 100644 backend/internal/httpapi/server_test.go create mode 100644 backend/internal/httpapi/signing_restart_test.go create mode 100644 backend/internal/httpapi/tls_boundary_test.go create mode 100644 backend/internal/migrations/runner.go create mode 100644 backend/internal/migrations/v6_integration_test.go create mode 100644 backend/migrations/000001_core.down.sql create mode 100644 backend/migrations/000001_core.up.sql create mode 100644 backend/migrations/000002_licenses.down.sql create mode 100644 backend/migrations/000002_licenses.up.sql create mode 100644 backend/migrations/000003_license_operations.down.sql create mode 100644 backend/migrations/000003_license_operations.up.sql create mode 100644 backend/migrations/000004_orders.down.sql create mode 100644 backend/migrations/000004_orders.up.sql create mode 100644 backend/migrations/000005_activation.down.sql create mode 100644 backend/migrations/000005_activation.up.sql create mode 100644 backend/migrations/000006_heartbeat_lease.down.sql create mode 100644 backend/migrations/000006_heartbeat_lease.up.sql create mode 100644 backend/migrations/000007_local_releases.down.sql create mode 100644 backend/migrations/000007_local_releases.up.sql create mode 100644 backend/migrations/000008_package_objects.down.sql create mode 100644 backend/migrations/000008_package_objects.up.sql create mode 100644 backend/migrations/000009_admin_settings.down.sql create mode 100644 backend/migrations/000009_admin_settings.up.sql create mode 100644 backend/migrations/000010_admin_usernames.down.sql create mode 100644 backend/migrations/000010_admin_usernames.up.sql create mode 100644 backend/migrations/README.md create mode 100644 client/verify.mjs create mode 100644 compose.yaml create mode 100644 deploy/Dockerfile.api create mode 100644 deploy/Dockerfile.web create mode 100644 deploy/entrypoint.sh create mode 100644 deploy/nginx/compose.conf create mode 100644 deploy/nginx/download-local.conf create mode 100644 deploy/nginx/tls-proxy.conf.example create mode 100644 docs/activation-contract-draft.md create mode 100644 docs/admin-modules.md create mode 100644 docs/business-contract-draft.md create mode 100644 docs/business-quickstart.md create mode 100644 docs/client-integration-center.md create mode 100644 docs/deployment-delivery.md create mode 100644 docs/download-contract-draft.md create mode 100644 docs/heartbeat-lease-contract-draft.md create mode 100644 docs/keyring-client-contract-draft.md create mode 100644 docs/license-contract-draft.md create mode 100644 docs/operations-security.md create mode 100644 docs/release-gate-matrix.md create mode 100644 docs/signing-key-operations.md create mode 100644 docs/task-execution.md create mode 100644 frontend/src/admin-api.test.ts create mode 100644 frontend/src/admin-api.ts create mode 100644 frontend/src/api-health.test.ts create mode 100644 frontend/src/api-health.ts create mode 100644 frontend/src/api.ts create mode 100644 frontend/src/dashboard-api.ts create mode 100644 frontend/src/date-format.test.ts create mode 100644 frontend/src/date-format.ts create mode 100644 frontend/src/orders-api.ts create mode 100644 frontend/src/router.test.ts create mode 100644 frontend/src/views/AdminsPanel.test.ts create mode 100644 frontend/src/views/AdminsPanel.vue create mode 100644 frontend/src/views/AuditPanel.test.ts create mode 100644 frontend/src/views/AuditPanel.vue create mode 100644 frontend/src/views/CustomerPortal.test.ts create mode 100644 frontend/src/views/CustomerPortal.vue create mode 100644 frontend/src/views/DashboardPanel.test.ts create mode 100644 frontend/src/views/DashboardPanel.vue create mode 100644 frontend/src/views/IntegrationPanel.test.ts create mode 100644 frontend/src/views/IntegrationPanel.vue create mode 100644 frontend/src/views/OrdersPanel.test.ts create mode 100644 frontend/src/views/OrdersPanel.vue create mode 100644 frontend/src/views/Overview.test.ts create mode 100644 frontend/src/views/ReleasesPanel.test.ts create mode 100644 frontend/src/views/ReleasesPanel.vue create mode 100644 frontend/src/views/SettingsPanel.test.ts create mode 100644 frontend/src/views/SettingsPanel.vue create mode 100644 scripts/backup-delivery.sh create mode 100644 scripts/check-delivery.sh create mode 100644 scripts/restore-delivery.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ca640e0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +.git +.env +.env.* +!.env.example +sessions +sources +skills +node_modules +frontend/node_modules +frontend/dist +backend/**/*.test +**/*.pem +**/*.key +**/secrets diff --git a/.env.example b/.env.example index 4dcbc03..8ecb8f2 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,37 @@ # API listen address (local development) HTTP_ADDR=127.0.0.1:18080 +# Empty means no trusted proxies. Explicit proxy CIDRs only, never /0. +HTTP_TRUSTED_PROXY_CIDRS= +# Set true behind managed TLS termination; forwarded headers alone are insufficient. +SESSION_COOKIE_SECURE=false +HTTP_READ_HEADER_TIMEOUT=5s +HTTP_READ_TIMEOUT=30s +HTTP_WRITE_TIMEOUT=30s +HTTP_IDLE_TIMEOUT=60s +HTTP_SHUTDOWN_TIMEOUT=10s +# Optional separate metrics listener, numeric loopback only; never publish through Web. +METRICS_ADDR= +# Required default: redis. Only controlled development may explicitly use local-dev. +ENTRY_LIMIT_MODE=redis +ENTRY_REDIS_ADDR=127.0.0.1:16379 +ENTRY_REDIS_NAMESPACE=license-platform:entry: +ENTRY_REDIS_USERNAME= +ENTRY_REDIS_PASSWORD_FILE= +# Redis errors fail closed with 503; no automatic local fallback. +# Migration CLI URL. Do not reuse as MYSQL_DSN. +MIGRATION_DSN=mysql://user:password@tcp(127.0.0.1:3306)/license_platform?multiStatements=true +# Go MySQL driver DSN for API and admin-init. +MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/license_platform?parseTime=true +# Optional PEM P-256 ECDSA private key, injected by secret manager; never commit a real key. +LICENSE_SIGNING_PRIVATE_KEY_PEM= +# Alternative absolute protected PEM file; never configure both key sources. +LICENSE_SIGNING_PRIVATE_KEY_FILE= +# Optional absolute public-key ring JSON; opt-in DEV license-v2/lease-v2. +# Lifecycle/rotation approval required; private key NEVER belongs in this JSON. +LICENSE_KEYRING_FILE= +# Absolute existing trusted non-public directory; hard links must be supported. +PACKAGE_STORAGE_ROOT= +# This example is documentation, not a production security profile. +# Compose external path variables (not secret values): MYSQL_APP_SECRET_FILE, +# MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST. +# See docs/deployment-delivery.md for outstanding TLS/cookie/restore blockers. diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 36b3045..b4176d4 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -1,12 +1,31 @@ name: Check on: push: - paths: ['backend/**', 'frontend/**', '.github/workflows/check.yml'] + paths: ['backend/**', 'client/**', 'frontend/**', 'scripts/**', 'deploy/**', 'compose.yaml', '.github/workflows/check.yml'] pull_request: - paths: ['backend/**', 'frontend/**', '.github/workflows/check.yml'] + paths: ['backend/**', 'client/**', 'frontend/**', 'scripts/**', 'deploy/**', 'compose.yaml', '.github/workflows/check.yml'] jobs: + delivery-static: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: sh scripts/check-delivery.sh + - name: Compose configuration only (not runtime acceptance) + env: + MYSQL_APP_SECRET_FILE: /tmp/delivery-app.secret + MYSQL_ROOT_SECRET_FILE: /tmp/delivery-root.secret + LICENSE_SIGNING_KEY_HOST_FILE: /tmp/delivery-signing.pem + PACKAGE_STORAGE_HOST: /tmp/delivery-packages + run: docker compose config --quiet api: runs-on: ubuntu-latest + services: + redis: + image: redis:7-alpine + ports: ['16379:6379'] + options: --health-cmd 'redis-cli ping' --health-interval 5s --health-timeout 3s --health-retries 10 + env: + ENTRY_REDIS_TEST_ADDR: 127.0.0.1:16379 defaults: run: working-directory: backend @@ -16,8 +35,12 @@ jobs: with: go-version-file: backend/go.mod cache-dependency-path: backend/go.sum + - uses: actions/setup-node@v4 + with: + node-version: '24' - run: go test ./... - run: go vet ./... + - run: go test -race ./internal/httpapi -run 'TestOperations|TestOrigin|TestLocalLimiter|TestSessionCookie|TestPublicEntry|TestChunkedBody|TestRedisEntry|TestEntryMode' -count=1 web: runs-on: ubuntu-latest defaults: @@ -31,4 +54,5 @@ jobs: cache: npm cache-dependency-path: frontend/package-lock.json - run: npm ci + - run: npm test - run: npm run build diff --git a/README.md b/README.md index f111a51..7ef8648 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ First implementation slice: Gin API and Vue 3/Vite management shell. This is **n Prerequisites: Go 1.23+, Node 20+. From `backend`, run `go run ./cmd/server`. From `frontend`, run `npm ci` and `npm run dev`. Visit http://127.0.0.1:5173/ (Vite proxies `/api` to the Go server at 127.0.0.1:18080). Set `HTTP_ADDR` to override the Go listen address; update the Vite proxy when changing API port. -Checks: `go test ./...` from `backend`, `npm run build` from `frontend`. `/api/v1/health/live` reports only process liveness and does not prove database readiness. No secret is committed; `.env.example` is documentation only. +Checks: `go test ./...` from `backend`, `npm run build` from `frontend`. `/api/v1/health/live` reports only process liveness and does not prove database readiness. No secret is committed; `.env.example` is documentation only and is not loaded automatically. Export the variables in your shell or deployment environment. HTTP timeout values must be positive Go durations no greater than 5m; invalid configuration fails startup. The server handles SIGTERM/interrupt with a bounded graceful shutdown and does not trust forwarded client IP headers by default. + +Migration conventions: `backend/migrations/README.md`. SQL and migration runner validation are not implemented yet. Task status and verification records: `docs/task-execution.md` and the detailed task plan. T03 remains in progress; no task has been accepted as release-ready. Before implementing binding and issuance: decide the licensed Web product, instance identity across container recreation/replicas and its integration owner. Confirm the remaining ADRs in `软件授权与统一管理平台-架构决策与MVP验收规格.md`. diff --git a/backend/cmd/admin-init/main.go b/backend/cmd/admin-init/main.go new file mode 100644 index 0000000..28e53a4 --- /dev/null +++ b/backend/cmd/admin-init/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "context" + "database/sql" + "errors" + "flag" + "fmt" + "os" + "strings" + + _ "github.com/go-sql-driver/mysql" + "golang.org/x/crypto/bcrypt" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} +func run(args []string) error { + f := flag.NewFlagSet("admin-init", flag.ContinueOnError) + dsn := f.String("dsn", os.Getenv("MYSQL_DSN"), "MySQL driver DSN") + email := f.String("email", "", "admin email") + username := f.String("username", "admin", "admin username (3-32 lowercase letters, digits, _ or -)") + password := f.String("password", "", "admin password (non-empty, up to 72 bytes)") + if err := f.Parse(args); err != nil { + return err + } + *username = strings.ToLower(strings.TrimSpace(*username)) + if *dsn == "" || !strings.Contains(*email, "@") || !validUsername(*username) { + return errors.New("-dsn, valid -email and valid -username are required") + } + if *password == "" { + return errors.New("-password must not be empty") + } + if len(*password) > 72 { + return errors.New("-password must not exceed 72 bytes") + } + db, err := sql.Open("mysql", *dsn) + if err != nil { + return err + } + defer db.Close() + if err = db.PingContext(context.Background()); err != nil { + return err + } + hash, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) + if err != nil { + return err + } + tx, err := db.BeginTx(context.Background(), nil) + if err != nil { + return err + } + defer tx.Rollback() + emailValue := strings.ToLower(strings.TrimSpace(*email)) + var id uint64 + err = tx.QueryRow("SELECT id FROM admins WHERE email=? FOR UPDATE", emailValue).Scan(&id) + if err == sql.ErrNoRows { + _, err = tx.Exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", *username, emailValue, string(hash)) + } else if err == nil { + _, err = tx.Exec("UPDATE admins SET username=?,password_hash=?,active=1 WHERE id=?", *username, string(hash), id) + if err == nil { + _, err = tx.Exec("UPDATE sessions SET revoked_at=UTC_TIMESTAMP(6) WHERE admin_id=? AND revoked_at IS NULL", id) + } + } + if err != nil { + return err + } + return tx.Commit() +} + +func validUsername(value string) bool { + if len(value) < 3 || len(value) > 32 { + return false + } + for _, r := range value { + if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') { + return false + } + } + return true +} diff --git a/backend/cmd/migrate/main.go b/backend/cmd/migrate/main.go new file mode 100644 index 0000000..99feb2e --- /dev/null +++ b/backend/cmd/migrate/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "license-platform/backend/internal/migrations" + "os" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string) error { + flags := flag.NewFlagSet("migrate", flag.ContinueOnError) + dsn := flags.String("dsn", os.Getenv("MIGRATION_DSN"), "MySQL migrate URL, e.g. mysql://user:pass@tcp(host:3306)/db?multiStatements=true (also MIGRATION_DSN)") + directory := flags.String("dir", "./migrations", "migration directory") + forceVersion := flags.Int("version", -2, "version for force; required only with force") + if err := flags.Parse(args); err != nil { + return err + } + if flags.NArg() != 1 { + return errors.New("usage: migrate [-dsn DSN] [-dir DIR] up|down|version|force") + } + runner, err := migrations.Open(*dsn, *directory) + if err != nil { + return err + } + defer runner.Close() + switch flags.Arg(0) { + case "up": + return runner.Up() + case "down": + return runner.Down() + case "version": + version, dirty, err := runner.Version() + if err != nil { + return err + } + fmt.Printf("version=%d dirty=%t\n", version, dirty) + return nil + case "force": + if *forceVersion < -1 { + return errors.New("-version is required for force") + } + return runner.Force(*forceVersion) + default: + return fmt.Errorf("unknown action %q", flags.Arg(0)) + } +} diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index 6aa7524..a56f269 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -1,18 +1,100 @@ package main import ( - "log" - "os" + "context" + "database/sql" + "fmt" + "log/slog" + "net" + "net/http" + _ "github.com/go-sql-driver/mysql" + "os" + "os/signal" + "syscall" + + "license-platform/backend/internal/config" "license-platform/backend/internal/httpapi" ) -func main() { - addr := os.Getenv("HTTP_ADDR") - if addr == "" { - addr = "127.0.0.1:18080" +func run() error { + cfg, err := config.Load(os.Getenv) + if err != nil { + return err } - if err := httpapi.NewRouter().Run(addr); err != nil { - log.Fatal(err) + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + ops := httpapi.NewOperations(logger) + closeLimiter, err := httpapi.ConfigureEntryLimiter(ops, os.Getenv) + if err != nil { + return err + } + defer closeLimiter() + router := httpapi.NewOperationalRouter(ops) + var readinessDB *sql.DB + if dsn := os.Getenv("MYSQL_DSN"); dsn != "" { + db, err := sql.Open("mysql", dsn) + if err != nil { + return err + } + defer db.Close() + if err := db.PingContext(context.Background()); err != nil { + return err + } + if err := httpapi.CheckSchema(context.Background(), db); err != nil { + return fmt.Errorf("database schema is not ready; explicit clean migration to version %d required", httpapi.RequiredSchemaVersion) + } + readinessDB = db + ring, err := httpapi.LoadKeyring(os.Getenv("LICENSE_KEYRING_FILE"), cfg.SigningPrivateKeyPEM) + if err != nil { + return err + } + httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring) + } + // Readiness is registered only on the loopback operations listener. + if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil { + return err + } + server := &http.Server{ + Addr: cfg.HTTPAddr, Handler: router, + ReadHeaderTimeout: cfg.ReadHeaderTimeout, ReadTimeout: cfg.ReadTimeout, + WriteTimeout: cfg.WriteTimeout, IdleTimeout: cfg.IdleTimeout, + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if addr := os.Getenv("METRICS_ADDR"); addr != "" { + host, _, err := net.SplitHostPort(addr) + if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() { + return fmt.Errorf("METRICS_ADDR must use a numeric loopback address") + } + listener, err := net.Listen("tcp", addr) + if err != nil { + return fmt.Errorf("metrics listener unavailable") + } + mux := http.NewServeMux() + mux.HandleFunc("/metrics", ops.Metrics) + internal := httpapi.NewRouter() + httpapi.RegisterReadiness(internal, readinessDB) + mux.Handle("/api/v1/health/ready", internal) + metrics := &http.Server{Handler: mux, ReadHeaderTimeout: cfg.ReadHeaderTimeout, WriteTimeout: cfg.WriteTimeout} + defer metrics.Close() + go func() { + if err := metrics.Serve(listener); err != nil && err != http.ErrServerClosed { + logger.Error("metrics_listener_failed") + stop() + } + }() + } + mode := os.Getenv("ENTRY_LIMIT_MODE") + if mode == "" { + mode = "redis" + } + logger.Info("api_starting", "address", cfg.HTTPAddr, "rate_limit_mode", mode) + return httpapi.Serve(ctx, server, cfg.ShutdownTimeout) +} + +func main() { + if err := run(); err != nil { + slog.New(slog.NewJSONHandler(os.Stderr, nil)).Error("startup_failed", "code", "startup_error") + os.Exit(1) } } diff --git a/backend/go.mod b/backend/go.mod index 673c98e..820f951 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -2,19 +2,29 @@ module license-platform/backend go 1.23.0 -require github.com/gin-gonic/gin v1.10.0 +require ( + github.com/gin-gonic/gin v1.10.0 + github.com/go-sql-driver/mysql v1.5.0 + github.com/golang-migrate/migrate/v4 v4.18.3 + github.com/redis/go-redis/v9 v9.7.3 + golang.org/x/crypto v0.36.0 +) require ( github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/goccy/go-json v0.10.2 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/leodido/go-urn v1.4.0 // indirect @@ -24,11 +34,11 @@ require ( github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect + go.uber.org/atomic v1.7.0 // indirect golang.org/x/arch v0.8.0 // indirect - golang.org/x/crypto v0.23.0 // indirect - golang.org/x/net v0.25.0 // indirect - golang.org/x/sys v0.20.0 // indirect - golang.org/x/text v0.15.0 // indirect - google.golang.org/protobuf v1.34.1 // indirect + golang.org/x/net v0.38.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/backend/go.sum b/backend/go.sum index 7f08abb..7febd83 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,7 +1,17 @@ +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= @@ -9,12 +19,30 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dhui/dktest v0.4.5 h1:uUfYBIVREmj/Rw6MvgmqNAYzTiKOHJak+enB5Di73MM= +github.com/dhui/dktest v0.4.5/go.mod h1:tmcyeHDKagvlDrz7gDKq4UAJOLIfVZYkfD5OnHDwcCo= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4= +github.com/docker/docker v27.2.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= +github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -23,11 +51,22 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs= +github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= @@ -36,17 +75,33 @@ github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZY github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= +github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= +github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -63,23 +118,33 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8= +go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= +go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= +go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc= +go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8= +go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= +go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= +go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= -golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= -golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= -golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= -google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU= +golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..52d3c4e --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,98 @@ +package config + +import ( + "fmt" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +type Config struct { + HTTPAddr string + TrustedProxies []string + ReadHeaderTimeout time.Duration + ReadTimeout time.Duration + WriteTimeout time.Duration + IdleTimeout time.Duration + ShutdownTimeout time.Duration + SigningPrivateKeyPEM string +} + +func Load(getenv func(string) string) (Config, error) { + c := Config{HTTPAddr: "127.0.0.1:18080"} + if v := getenv("HTTP_ADDR"); v != "" { + c.HTTPAddr = v + } + _, port, err := net.SplitHostPort(c.HTTPAddr) + if err != nil { + return Config{}, fmt.Errorf("HTTP_ADDR must be host:port") + } + p, err := strconv.Atoi(port) + if err != nil || p < 1 || p > 65535 { + return Config{}, fmt.Errorf("HTTP_ADDR port must be between 1 and 65535") + } + for _, setting := range []struct { + name string + value *time.Duration + fallback time.Duration + }{ + {"HTTP_READ_HEADER_TIMEOUT", &c.ReadHeaderTimeout, 5 * time.Second}, + {"HTTP_READ_TIMEOUT", &c.ReadTimeout, 30 * time.Second}, + {"HTTP_WRITE_TIMEOUT", &c.WriteTimeout, 30 * time.Second}, + {"HTTP_IDLE_TIMEOUT", &c.IdleTimeout, 60 * time.Second}, + {"HTTP_SHUTDOWN_TIMEOUT", &c.ShutdownTimeout, 10 * time.Second}, + } { + *setting.value = setting.fallback + if v := getenv(setting.name); v != "" { + d, err := time.ParseDuration(v) + if err != nil || d <= 0 || d > 5*time.Minute { + return Config{}, fmt.Errorf("%s must be a duration greater than zero and at most 5m", setting.name) + } + *setting.value = d + } + } + if value := getenv("HTTP_TRUSTED_PROXY_CIDRS"); value != "" { + for _, value := range strings.Split(value, ",") { + value = strings.TrimSpace(value) + _, network, err := net.ParseCIDR(value) + if err != nil { + return Config{}, fmt.Errorf("trusted proxies must be explicit CIDRs") + } + ones, _ := network.Mask.Size() + if ones == 0 { + return Config{}, fmt.Errorf("trust-all proxies are forbidden") + } + c.TrustedProxies = append(c.TrustedProxies, value) + } + } + if value := getenv("SESSION_COOKIE_SECURE"); value != "" && value != "true" && value != "false" { + return Config{}, fmt.Errorf("SESSION_COOKIE_SECURE must be true or false") + } + c.SigningPrivateKeyPEM = getenv("LICENSE_SIGNING_PRIVATE_KEY_PEM") + if path := getenv("LICENSE_SIGNING_PRIVATE_KEY_FILE"); path != "" { + if c.SigningPrivateKeyPEM != "" { + return Config{}, fmt.Errorf("only one signing key source may be configured") + } + if !filepath.IsAbs(path) { + return Config{}, fmt.Errorf("LICENSE_SIGNING_PRIVATE_KEY_FILE must be absolute") + } + data, err := os.ReadFile(path) + if err != nil || len(data) == 0 || len(data) > 16384 { + return Config{}, fmt.Errorf("signing key file must be readable and between 1 and 16384 bytes") + } + c.SigningPrivateKeyPEM = string(data) + } + if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" { + if !filepath.IsAbs(root) { + return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute") + } + info, err := os.Stat(root) + if err != nil || !info.IsDir() { + return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be an existing directory") + } + } + return c, nil +} diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go new file mode 100644 index 0000000..e62aab2 --- /dev/null +++ b/backend/internal/config/config_test.go @@ -0,0 +1,64 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestLoadDefaults(t *testing.T) { + c, err := Load(func(string) string { return "" }) + if err != nil || c.HTTPAddr != "127.0.0.1:18080" || c.ReadHeaderTimeout != 5*time.Second || c.ShutdownTimeout != 10*time.Second { + t.Fatalf("config=%+v err=%v", c, err) + } +} + +func TestLoadOverrides(t *testing.T) { + values := map[string]string{"HTTP_ADDR": "[::1]:18081", "HTTP_WRITE_TIMEOUT": "2m"} + c, err := Load(func(key string) string { return values[key] }) + if err != nil || c.HTTPAddr != values["HTTP_ADDR"] || c.WriteTimeout != 2*time.Minute { + t.Fatalf("config=%+v err=%v", c, err) + } +} + +func TestLoadKeyFileAndStorage(t *testing.T) { + root := t.TempDir() + key := filepath.Join(root, "key.pem") + if err := os.WriteFile(key, []byte("test-only-content"), 0600); err != nil { + t.Fatal(err) + } + values := map[string]string{"LICENSE_SIGNING_PRIVATE_KEY_FILE": key, "PACKAGE_STORAGE_ROOT": root} + cfg, err := Load(func(k string) string { return values[k] }) + if err != nil || cfg.SigningPrivateKeyPEM != "test-only-content" { + t.Fatal("file injection failed") + } + values["LICENSE_SIGNING_PRIVATE_KEY_PEM"] = "conflicting-source" + if _, err := Load(func(k string) string { return values[k] }); err == nil { + t.Fatal("ambiguous key sources accepted") + } +} + +func TestLoadRejectsInvalid(t *testing.T) { + for _, tc := range []struct{ key, value string }{ + {"HTTP_TRUSTED_PROXY_CIDRS", "0.0.0.0/0"}, {"HTTP_TRUSTED_PROXY_CIDRS", "::/0"}, + {"HTTP_TRUSTED_PROXY_CIDRS", "127.0.0.1"}, {"HTTP_TRUSTED_PROXY_CIDRS", "bad"}, + {"SESSION_COOKIE_SECURE", "yes"}, + {"PACKAGE_STORAGE_ROOT", "relative/packages"}, {"LICENSE_SIGNING_PRIVATE_KEY_FILE", "relative/key.pem"}, + {"HTTP_ADDR", "localhost"}, {"HTTP_ADDR", ":0"}, {"HTTP_ADDR", ":65536"}, {"HTTP_ADDR", ":abc"}, + {"HTTP_READ_HEADER_TIMEOUT", "bad"}, {"HTTP_READ_TIMEOUT", "0s"}, + {"HTTP_WRITE_TIMEOUT", "-1s"}, {"HTTP_IDLE_TIMEOUT", "6m"}, {"HTTP_SHUTDOWN_TIMEOUT", "0s"}, + } { + t.Run(tc.key+tc.value, func(t *testing.T) { + _, err := Load(func(key string) string { + if key == tc.key { + return tc.value + } + return "" + }) + if err == nil { + t.Fatal("expected configuration error") + } + }) + } +} diff --git a/backend/internal/httpapi/activation.go b/backend/internal/httpapi/activation.go new file mode 100644 index 0000000..836f9cb --- /dev/null +++ b/backend/internal/httpapi/activation.go @@ -0,0 +1,348 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +type instanceRecord struct { + ID uint64 `json:"id"` + InstanceID string `json:"instance_id"` + LicenseID uint64 `json:"license_id"` + CustomerID uint64 `json:"customer_id"` + ProductID uint64 `json:"product_id"` + Status string `json:"status"` + ActivatedAt *time.Time `json:"activated_at,omitempty"` + CertificateVersion string `json:"certificate_version,omitempty"` + CreatedAt time.Time `json:"created_at"` + LastSeenAt *time.Time `json:"last_seen_at,omitempty"` + LeaseExpiresAt *time.Time `json:"lease_expires_at,omitempty"` + FreezeState string `json:"freeze_state"` + ObservedState string `json:"observed_state"` + EntitlementState string `json:"entitlement_state"` +} + +func newInstanceID() (string, error) { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", err + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%s-%s-%s-%s-%s", hex.EncodeToString(b[:4]), hex.EncodeToString(b[4:6]), hex.EncodeToString(b[6:8]), hex.EncodeToString(b[8:10]), hex.EncodeToString(b[10:])), nil +} + +func readSigningKey(pemText string) (*ecdsa.PrivateKey, error) { + block, _ := pem.Decode([]byte(pemText)) + if block == nil { + return nil, errors.New("missing PEM") + } + if key, err := x509.ParseECPrivateKey(block.Bytes); err == nil && key.Curve == elliptic.P256() { + return key, nil + } + keyAny, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, err + } + key, ok := keyAny.(*ecdsa.PrivateKey) + if !ok || key.Curve != elliptic.P256() { + return nil, errors.New("signing key must be P-256 ECDSA") + } + return key, nil +} + +// canonicalCertificatePayload is newline-delimited key=value with fixed order and no whitespace. +func canonicalCertificatePayload(version, instanceID string, licenseID, customerID, productID uint64, startsAt, expiresAt time.Time) string { + return strings.Join([]string{ + "version=" + version, + "instance_id=" + instanceID, + "license_id=" + strconv.FormatUint(licenseID, 10), + "customer_id=" + strconv.FormatUint(customerID, 10), + "product_id=" + strconv.FormatUint(productID, 10), + "starts_at=" + startsAt.UTC().Format(time.RFC3339Nano), + "expires_at=" + expiresAt.UTC().Format(time.RFC3339Nano), + }, "\n") +} + +func (a *BusinessAPI) provisionInstance(c *gin.Context) { + licenseID, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || licenseID == 0 { + apiError(c, 400, "invalid_request", "授权 ID 无效") + return + } + actor := c.MustGet("admin_id") + instanceID, err := newInstanceID() + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + secretBytes := make([]byte, 32) + if _, err = rand.Read(secretBytes); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + secret := base64.RawURLEncoding.EncodeToString(secretBytes) + hash := sha256.Sum256(secretBytes) + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + var customerID, productID uint64 + var status string + if err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM licenses WHERE id=? FOR UPDATE", licenseID).Scan(&customerID, &productID, &status); errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "授权不存在") + return + } else if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if status == "revoked" { + apiError(c, 409, "invalid_state", "已撤销授权不能创建实例") + return + } + var existing string + if err = tx.QueryRowContext(c, "SELECT instance_id FROM license_instances WHERE license_id=?", licenseID).Scan(&existing); err == nil { + apiError(c, 409, "instance_conflict", "授权已绑定实例") + return + } else if !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + var id uint64 + res, err := tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", instanceID, licenseID, customerID, productID, hash[:], actor) + if err != nil { + apiError(c, 409, "instance_conflict", "实例创建失败") + return + } + id64, _ := res.LastInsertId() + id = uint64(id64) + details, _ := json.Marshal(gin.H{"license_id": licenseID, "instance_id": instanceID}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.provisioned','license_instance',?,?)", actor, id, details); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "secret_expires": "one-time"}) +} + +func (a *BusinessAPI) listInstances(c *gin.Context) { + licenseID, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || licenseID == 0 { + apiError(c, 400, "invalid_request", "授权 ID 无效") + return + } + rows, err := a.db.QueryContext(c, "SELECT id,instance_id,license_id,customer_id,product_id,status,activated_at,COALESCE(certificate_version,''),created_at,last_seen_at,lease_expires_at,freeze_state,observed_state,(SELECT status FROM licenses WHERE id=license_id) FROM license_instances WHERE license_id=? ORDER BY id", licenseID) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer rows.Close() + out := []instanceRecord{} + for rows.Next() { + var x instanceRecord + if err = rows.Scan(&x.ID, &x.InstanceID, &x.LicenseID, &x.CustomerID, &x.ProductID, &x.Status, &x.ActivatedAt, &x.CertificateVersion, &x.CreatedAt, &x.LastSeenAt, &x.LeaseExpiresAt, &x.FreezeState, &x.ObservedState, &x.EntitlementState); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + out = append(out, x) + } + c.JSON(200, gin.H{"data": out}) +} + +func (a *BusinessAPI) activateInstance(c *gin.Context) { + if a.signingPrivateKeyPEM == "" { + apiError(c, 503, "signing_unavailable", "签名密钥未配置") + return + } + instanceID := strings.TrimSpace(c.Param("instance_id")) + if len(instanceID) != 36 { + apiError(c, 400, "invalid_request", "instance_id 无效") + return + } + key, ok := parseOperationKey(c) + if !ok { + return + } + var in struct { + Secret string `json:"secret"` + LicenseKey string `json:"license_key"` + } + if c.ShouldBindJSON(&in) != nil || len(in.Secret) < 20 || len(in.Secret) > 128 { + apiError(c, 400, "invalid_request", "secret 无效") + return + } + secretBytes, err := base64.RawURLEncoding.DecodeString(in.Secret) + if err != nil { + apiError(c, 400, "invalid_request", "secret 无效") + return + } + secretHash := sha256.Sum256(secretBytes) + fingerprint := sha256.Sum256([]byte(instanceID + "\x00" + hex.EncodeToString(secretHash[:]))) + var actor uint64 + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + var inst instanceRecord + var storedHash []byte + var startsAt, expiresAt time.Time + err = tx.QueryRowContext(c, `SELECT i.id,i.instance_id,i.license_id,i.customer_id,i.product_id,i.status,i.activated_at,COALESCE(i.certificate_version,''),i.created_at,i.secret_hash,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.instance_id=? FOR UPDATE`, instanceID).Scan(&inst.ID, &inst.InstanceID, &inst.LicenseID, &inst.CustomerID, &inst.ProductID, &inst.Status, &inst.ActivatedAt, &inst.CertificateVersion, &inst.CreatedAt, &storedHash, &startsAt, &expiresAt) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "实例不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if err = tx.QueryRowContext(c, "SELECT created_by FROM license_instances WHERE id=?", inst.ID).Scan(&actor); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + var licenseKey string + if err = tx.QueryRowContext(c, "SELECT license_key FROM licenses WHERE id=?", inst.LicenseID).Scan(&licenseKey); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if !bytesEqual([]byte(in.LicenseKey), []byte(licenseKey)) || !bytesEqual(storedHash, secretHash[:]) { + apiError(c, 403, "forbidden", "激活凭据无效") + return + } + var opID uint64 + var oldInstance uint64 + var oldFingerprint []byte + var oldResponse []byte + err = tx.QueryRowContext(c, "SELECT id,instance_id,request_fingerprint,response FROM activation_operations WHERE instance_id=? AND idempotency_key=?", inst.ID, key).Scan(&opID, &oldInstance, &oldFingerprint, &oldResponse) + if err == nil { + if oldInstance != inst.ID || !bytesEqual(oldFingerprint, fingerprint[:]) { + apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同激活请求") + return + } + var replay any + _ = json.Unmarshal(oldResponse, &replay) + c.JSON(200, replay) + return + } + if !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if !bytesEqual(storedHash, secretHash[:]) { + apiError(c, 403, "forbidden", "实例secret无效") + return + } + if inst.Status == "activated" { + apiError(c, 409, "invalid_state", "实例已经激活") + return + } + var licenseStatus, customerStatus string + var productActive bool + var licenseCustomer, licenseProduct uint64 + if err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM licenses WHERE id=? FOR UPDATE", inst.LicenseID).Scan(&licenseCustomer, &licenseProduct, &licenseStatus); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if licenseCustomer != inst.CustomerID || licenseProduct != inst.ProductID || currentLicenseStatus(licenseStatus, startsAt, expiresAt, time.Now().UTC()) != "active" { + apiError(c, 409, "invalid_state", "授权归属或有效期无效") + return + } + if err = tx.QueryRowContext(c, "SELECT status FROM customers WHERE id=? FOR UPDATE", inst.CustomerID).Scan(&customerStatus); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if err = tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", inst.ProductID).Scan(&productActive); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if customerStatus != "active" || !productActive { + apiError(c, 409, "invalid_state", "客户或产品未启用") + return + } + var orderCustomer, orderProduct uint64 + var orderStatus string + err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM offline_orders WHERE issued_license_id=? FOR UPDATE", inst.LicenseID).Scan(&orderCustomer, &orderProduct, &orderStatus) + if err == nil && (orderCustomer != inst.CustomerID || orderProduct != inst.ProductID || orderStatus != "issued") { + apiError(c, 409, "invalid_state", "订单归属无效") + return + } + if err != nil && !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + privateKey, err := readSigningKey(a.signingPrivateKeyPEM) + if err != nil { + apiError(c, 503, "signing_unavailable", "签名密钥无效") + return + } + version := "license-v1" + canonical := canonicalCertificatePayload(version, instanceID, inst.LicenseID, inst.CustomerID, inst.ProductID, startsAt, expiresAt) + if a.keyring != nil { + version = "license-v2" + canonical = canonicalCertificatePayload(version, instanceID, inst.LicenseID, inst.CustomerID, inst.ProductID, startsAt, expiresAt) + "\nkey_id=" + a.keyring.Current + } + digest := sha256.Sum256([]byte(canonical)) + signature, err := ecdsa.SignASN1(rand.Reader, privateKey, digest[:]) + if err != nil { + apiError(c, 500, "internal_error", "签发失败") + return + } + payload := gin.H{"version": version, "instance_id": instanceID, "license_id": inst.LicenseID, "customer_id": inst.CustomerID, "product_id": inst.ProductID, "starts_at": startsAt.UTC().Format(time.RFC3339Nano), "expires_at": expiresAt.UTC().Format(time.RFC3339Nano)} + if a.keyring != nil { + payload["key_id"] = a.keyring.Current + } + payloadJSON, _ := json.Marshal(payload) + now := time.Now().UTC().Truncate(time.Microsecond) + if _, err = tx.ExecContext(c, "UPDATE license_instances SET status='activated',activated_at=?,certificate_version=?,certificate_payload=?,certificate_signature=? WHERE id=?", now, version, payloadJSON, base64.RawStdEncoding.EncodeToString(signature), inst.ID); err != nil { + apiError(c, 500, "internal_error", "激活失败") + return + } + response := gin.H{"data": gin.H{"instance_id": instanceID, "status": "activated", "certificate": gin.H{"version": version, "payload": payload, "signature": base64.RawStdEncoding.EncodeToString(signature), "canonical_sha256": hex.EncodeToString(digest[:])}}, "idempotent_replay": false} + responseJSON, _ := json.Marshal(response) + if _, err = tx.ExecContext(c, "INSERT INTO activation_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?)", inst.ID, actor, key, fingerprint[:], responseJSON); err != nil { + apiError(c, 500, "internal_error", "激活失败,请使用相同幂等键重试") + return + } + details, _ := json.Marshal(gin.H{"instance_id": instanceID, "license_id": inst.LicenseID, "certificate_version": version}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.activated','license_instance',?,?)", actor, inst.ID, details); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.JSON(201, response) +} + +func bytesEqual(a, b []byte) bool { + if len(a) != len(b) { + return false + } + var x byte + for i := range a { + x |= a[i] ^ b[i] + } + return x == 0 +} diff --git a/backend/internal/httpapi/activation_integration_test.go b/backend/internal/httpapi/activation_integration_test.go new file mode 100644 index 0000000..a69cd5d --- /dev/null +++ b/backend/internal/httpapi/activation_integration_test.go @@ -0,0 +1,129 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "database/sql" + "encoding/json" + "encoding/pem" + "fmt" + "github.com/gin-gonic/gin" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + der, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + r := NewRouter() + RegisterBusiness(r, db, string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}))) + var licenseID uint64 + var licenseKey string + if err = db.QueryRow("SELECT l.id,l.license_key FROM licenses l JOIN offline_orders o ON o.issued_license_id=l.id WHERE o.status='issued' LIMIT 1").Scan(&licenseID, &licenseKey); err != nil { + t.Fatal(err) + } + request := func(method, path, body, idem string, auth bool) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", idem) + if auth { + req.AddCookie(cookie) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + provisionPath := fmt.Sprintf("/api/v1/licenses/%d/instances", licenseID) + if w := request("POST", provisionPath, "{}", "", false); w.Code != 401 { + t.Fatalf("unauthorized status=%d", w.Code) + } + w := request("POST", provisionPath, "{}", "", true) + if w.Code != 201 { + t.Fatalf("provision status=%d", w.Code) + } + var response struct { + Data struct { + InstanceID string `json:"instance_id"` + Secret string `json:"secret"` + } + } + if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + instanceID, secret := response.Data.InstanceID, response.Data.Secret + if instanceID == "" || secret == "" { + t.Fatal("provision fields missing") + } + if w = request("POST", provisionPath, "{}", "", true); w.Code != 409 || strings.Contains(w.Body.String(), secret) { + t.Fatal("duplicate provision result invalid") + } + w = request("GET", provisionPath, "", "", true) + if w.Code != 200 || strings.Contains(w.Body.String(), secret) || strings.Contains(w.Body.String(), "secret_hash") { + t.Fatal("instance list leaked secret") + } + path := "/api/v1/activation/instances/" + instanceID + bodyBytes, _ := json.Marshal(gin.H{"license_key": licenseKey, "secret": secret}) + body := string(bodyBytes) + badBytes, _ := json.Marshal(gin.H{"license_key": "wrong", "secret": secret}) + if w = request("POST", path, string(badBytes), "activate", false); w.Code != 403 { + t.Fatalf("wrong credential=%d", w.Code) + } + if _, err = db.Exec("CREATE TRIGGER activation_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'"); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS activation_audit_failure") }) + if w = request("POST", path, body, "activate", false); w.Code != 500 { + t.Fatalf("rollback status=%d", w.Code) + } + var status string + db.QueryRow("SELECT status FROM license_instances WHERE instance_id=?", instanceID).Scan(&status) + if status != "provisioned" { + t.Fatal("audit failure committed activation") + } + db.Exec("DROP TRIGGER activation_audit_failure") + var wg sync.WaitGroup + codes := make(chan int, 2) + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { defer wg.Done(); codes <- request("POST", path, body, "activate", false).Code }() + } + wg.Wait() + close(codes) + successes, replays := 0, 0 + for code := range codes { + if code == 201 { + successes++ + } else if code == 200 { + replays++ + } else { + t.Fatalf("concurrent activation=%d", code) + } + } + if successes != 1 || replays != 1 { + t.Fatal("activation did not serialize") + } + if w = request("POST", path, body, "different", false); w.Code != 409 { + t.Fatalf("repeat activation=%d", w.Code) + } + var count int + if err = db.QueryRow("SELECT COUNT(*) FROM activation_operations").Scan(&count); err != nil || count != 1 { + t.Fatal("operation count mismatch") + } + if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.activated'").Scan(&count); err != nil || count != 1 { + t.Fatal("activation audit count mismatch") + } + t.Run("heartbeat", func(t *testing.T) { + testHeartbeatMySQL(t, db, r, cookie, instanceID, secret, licenseID, &key.PublicKey) + }) +} diff --git a/backend/internal/httpapi/activation_public.go b/backend/internal/httpapi/activation_public.go new file mode 100644 index 0000000..1a6ba72 --- /dev/null +++ b/backend/internal/httpapi/activation_public.go @@ -0,0 +1,28 @@ +package httpapi + +import ( + "crypto/x509" + "encoding/pem" + "github.com/gin-gonic/gin" +) + +func (a *BusinessAPI) activationPublicKey(c *gin.Context) { + key, err := readSigningKey(a.signingPrivateKeyPEM) + if err != nil { + apiError(c, 503, "signing_unavailable", "签名密钥未配置或无效") + return + } + der, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + version := "license-v1" + data := gin.H{"algorithm": "ECDSA-P256-SHA256", "signature_encoding": "ASN.1-DER/base64-no-padding", "public_key_pem": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))} + if a.keyring != nil { + version = "license-v2" + data["key_id"] = a.keyring.Current + } + data["certificate_version"] = version + c.JSON(200, gin.H{"data": data}) +} diff --git a/backend/internal/httpapi/activation_test.go b/backend/internal/httpapi/activation_test.go new file mode 100644 index 0000000..c30cde9 --- /dev/null +++ b/backend/internal/httpapi/activation_test.go @@ -0,0 +1,49 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/pem" + "testing" + "time" +) + +func TestActivationCanonicalSignature(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + der, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + loaded, err := readSigningKey(string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}))) + if err != nil { + t.Fatal(err) + } + start := time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC) + end := start.AddDate(1, 0, 0) + canonical := canonicalCertificatePayload("license-v1", "00000000-0000-4000-8000-000000000001", 1, 2, 3, start, end) + expected := "version=license-v1\ninstance_id=00000000-0000-4000-8000-000000000001\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-09-30T00:00:00Z\nexpires_at=2027-09-30T00:00:00Z" + if canonical != expected { + t.Fatal("canonical payload mismatch") + } + sum := sha256.Sum256([]byte(canonical)) + sig, err := ecdsa.SignASN1(rand.Reader, loaded, sum[:]) + if err != nil { + t.Fatal(err) + } + if !ecdsa.VerifyASN1(&loaded.PublicKey, sum[:], sig) { + t.Fatal("signature not valid") + } + modified := sha256.Sum256([]byte(canonical + "x")) + if ecdsa.VerifyASN1(&loaded.PublicKey, modified[:], sig) { + t.Fatal("modified payload accepted") + } + if _, err = readSigningKey(""); err == nil { + t.Fatal("missing key accepted") + } +} diff --git a/backend/internal/httpapi/admin_accounts.go b/backend/internal/httpapi/admin_accounts.go new file mode 100644 index 0000000..e8453f3 --- /dev/null +++ b/backend/internal/httpapi/admin_accounts.go @@ -0,0 +1,246 @@ +package httpapi + +import ( + "errors" + "net/http" + "net/mail" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/go-sql-driver/mysql" + "golang.org/x/crypto/bcrypt" +) + +type adminAccount struct { + ID uint64 `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Active bool `json:"active"` + CreatedAt time.Time `json:"created_at"` +} + +func normalizeAdminUsername(value string) string { return strings.ToLower(strings.TrimSpace(value)) } +func validAdminUsername(value string) bool { + if len(value) < 3 || len(value) > 32 { + return false + } + for _, r := range value { + if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') { + return false + } + } + return true +} +func validAdminPassword(value string) bool { return value != "" && len(value) <= 72 } + +func (a *BusinessAPI) listAdmins(c *gin.Context) { + rows, err := a.db.QueryContext(c, "SELECT id,username,email,active,created_at FROM admins ORDER BY id") + if err != nil { + apiError(c, 500, "internal_error", "管理员列表加载失败") + return + } + defer rows.Close() + items := []adminAccount{} + for rows.Next() { + var item adminAccount + if err = rows.Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil { + apiError(c, 500, "internal_error", "管理员列表加载失败") + return + } + items = append(items, item) + } + if rows.Err() != nil { + apiError(c, 500, "internal_error", "管理员列表加载失败") + return + } + c.JSON(200, gin.H{"data": items}) +} + +func (a *BusinessAPI) createAdmin(c *gin.Context) { + var in struct { + Username string `json:"username"` + Email string `json:"email"` + Password string `json:"password"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "用户名、邮箱和密码不能为空") + return + } + in.Username = normalizeAdminUsername(in.Username) + in.Email = strings.ToLower(strings.TrimSpace(in.Email)) + address, emailErr := mail.ParseAddress(in.Email) + if !validAdminUsername(in.Username) || emailErr != nil || address.Address != in.Email || len(in.Email) > 190 || !validAdminPassword(in.Password) { + apiError(c, 400, "invalid_request", "用户名须为 3–32 位小写字母、数字、下划线或短横线;邮箱和密码必须有效") + return + } + hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost) + if err != nil { + apiError(c, 500, "internal_error", "管理员创建失败") + return + } + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "管理员创建失败") + return + } + defer tx.Rollback() + result, err := tx.ExecContext(c, "INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", in.Username, in.Email, string(hash)) + if err != nil { + var duplicate *mysql.MySQLError + if errors.As(err, &duplicate) && duplicate.Number == 1062 { + apiError(c, 409, "conflict", "用户名或邮箱已存在") + } else { + apiError(c, 500, "internal_error", "管理员创建失败") + } + return + } + id, _ := result.LastInsertId() + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.created','admin',?,?)", c.GetUint64("admin_id"), id, `{"fields":["username","email"]}`); err != nil { + apiError(c, 500, "internal_error", "管理员创建失败") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "管理员创建结果未确认,请刷新检查") + return + } + var item adminAccount + if err = a.db.QueryRowContext(c, "SELECT id,username,email,active,created_at FROM admins WHERE id=?", id).Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil { + apiError(c, 500, "internal_error", "管理员已创建,请刷新检查") + return + } + c.JSON(http.StatusCreated, gin.H{"data": item}) +} + +func (a *BusinessAPI) setAdminActive(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 { + Active *bool `json:"active"` + } + if c.ShouldBindJSON(&in) != nil || in.Active == nil { + apiError(c, 400, "invalid_request", "必须指定 active") + return + } + if id == c.GetUint64("admin_id") && !*in.Active { + 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() + // Lock accounts in a stable order to serialize simultaneous disable operations. + rows, err := tx.QueryContext(c, "SELECT id,active FROM admins ORDER BY id FOR UPDATE") + if err != nil { + apiError(c, 500, "internal_error", "管理员状态更新失败") + return + } + found, current, actorActive := false, false, false + for rows.Next() { + var accountID uint64 + var active bool + if err = rows.Scan(&accountID, &active); err != nil { + break + } + if accountID == id { + found, current = true, active + } + if accountID == c.GetUint64("admin_id") { + actorActive = active + } + } + if err == nil { + err = rows.Err() + } + rows.Close() + if err != nil { + apiError(c, 500, "internal_error", "管理员状态更新失败") + return + } + if !actorActive { + apiError(c, 401, "unauthorized", "当前管理员已停用") + return + } + if !found { + apiError(c, 404, "not_found", "管理员不存在") + return + } + if current == *in.Active { + c.Status(http.StatusNoContent) + return + } + if _, err = tx.ExecContext(c, "UPDATE admins SET active=? WHERE id=?", *in.Active, id); err != nil { + apiError(c, 500, "internal_error", "管理员状态更新失败") + return + } + if !*in.Active { + _, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id) + } + if err == nil { + _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.active_changed','admin',?,?)", c.GetUint64("admin_id"), id, `{"active":`+map[bool]string{true: "true", false: "false"}[*in.Active]+`}`) + } + if err != nil { + apiError(c, 500, "internal_error", "管理员状态更新失败") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "管理员状态更新结果未确认,请刷新检查") + return + } + c.Status(http.StatusNoContent) +} + +func (a *BusinessAPI) resetAdminPassword(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 { + Password string `json:"password"` + } + if c.ShouldBindJSON(&in) != nil || !validAdminPassword(in.Password) { + apiError(c, 400, "invalid_request", "新密码不能为空,且最多 72 字节") + return + } + hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost) + if err != nil { + apiError(c, 500, "internal_error", "密码重置失败") + return + } + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "密码重置失败") + return + } + defer tx.Rollback() + result, err := tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id) + if err != nil { + apiError(c, 500, "internal_error", "密码重置失败") + return + } + affected, _ := result.RowsAffected() + if affected == 0 { + apiError(c, 404, "not_found", "管理员不存在") + return + } + if _, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id); err == nil { + _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_reset','admin',?,?)", c.GetUint64("admin_id"), id, `{"sessions_revoked":true}`) + } + if err != nil { + apiError(c, 500, "internal_error", "密码重置失败") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "密码重置结果未确认,请刷新检查") + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/internal/httpapi/admin_accounts_test.go b/backend/internal/httpapi/admin_accounts_test.go new file mode 100644 index 0000000..d81818e --- /dev/null +++ b/backend/internal/httpapi/admin_accounts_test.go @@ -0,0 +1,47 @@ +package httpapi + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestAdminCredentialValidation(t *testing.T) { + for _, name := range []string{"admin", "admin-1", "ops_team", strings.Repeat("a", 32)} { + if !validAdminUsername(name) { + t.Fatalf("valid username rejected: %s", name) + } + } + for _, name := range []string{"", "ab", "name with space", "root@example.test", "管理员", "ADMIN", strings.Repeat("a", 33)} { + if validAdminUsername(name) { + t.Fatalf("invalid username accepted: %s", name) + } + } + if normalizeAdminUsername(" TEAM_1 ") != "team_1" { + t.Fatal("normalization") + } + for _, password := range []string{"x", strings.Repeat("a", 72), strings.Repeat("中", 24)} { + if !validAdminPassword(password) { + t.Fatal("valid password rejected") + } + } + for _, password := range []string{"", strings.Repeat("a", 73), strings.Repeat("中", 25)} { + if validAdminPassword(password) { + t.Fatal("invalid password accepted") + } + } +} +func TestAdminCannotDisableSelf(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("POST", "/admins/1/active", strings.NewReader(`{"active":false}`)) + c.Request.Header.Set("Content-Type", "application/json") + c.Params = gin.Params{{Key: "id", Value: "1"}} + c.Set("admin_id", uint64(1)) + (&BusinessAPI{}).setAdminActive(c) + if w.Code != 400 || !strings.Contains(w.Body.String(), "不能停用当前登录的管理员") { + t.Fatalf("%d %s", w.Code, w.Body) + } +} diff --git a/backend/internal/httpapi/admin_settings.go b/backend/internal/httpapi/admin_settings.go new file mode 100644 index 0000000..8db9feb --- /dev/null +++ b/backend/internal/httpapi/admin_settings.go @@ -0,0 +1,255 @@ +package httpapi + +import ( + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "net/mail" + "strings" + "time" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "golang.org/x/crypto/bcrypt" +) + +type platformSettings struct { + SiteName string `json:"site_name"` + SupportEmail string `json:"support_email"` + Announcement string `json:"announcement"` + UpdatedAt *time.Time `json:"updated_at"` +} + +func validateSettings(s *platformSettings) bool { + s.SiteName = strings.TrimSpace(s.SiteName) + s.SupportEmail = strings.TrimSpace(s.SupportEmail) + if s.SiteName == "" || utf8.RuneCountInString(s.SiteName) > 100 || len(s.SupportEmail) > 254 || utf8.RuneCountInString(s.Announcement) > 2000 { + return false + } + if s.SupportEmail != "" { + a, err := mail.ParseAddress(s.SupportEmail) + if err != nil || a.Address != s.SupportEmail { + return false + } + } + return true +} +func (a *BusinessAPI) getSettings(c *gin.Context) { + var s platformSettings + if err := a.db.QueryRowContext(c, "SELECT site_name,support_email,announcement,updated_at FROM system_settings WHERE id=1").Scan(&s.SiteName, &s.SupportEmail, &s.Announcement, &s.UpdatedAt); err != nil { + apiError(c, 500, "internal_error", "设置加载失败") + return + } + c.JSON(200, gin.H{"data": s}) +} +func (a *BusinessAPI) updateSettings(c *gin.Context) { + var s platformSettings + if c.ShouldBindJSON(&s) != nil || !validateSettings(&s) { + apiError(c, 400, "invalid_request", "平台名称为1至100字,联系邮箱必须有效,公告最多2000字") + return + } + now := time.Now().UTC() + s.UpdatedAt = &now + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "设置保存失败") + return + } + defer tx.Rollback() + // Lock the singleton so concurrent saves are serialized with their audit record. + var id int + if err = tx.QueryRowContext(c, "SELECT id FROM system_settings WHERE id=1 FOR UPDATE").Scan(&id); err == nil { + _, err = tx.ExecContext(c, "UPDATE system_settings SET site_name=?,support_email=?,announcement=?,updated_at=? WHERE id=1", s.SiteName, s.SupportEmail, s.Announcement, now) + } + if err == nil { + _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'settings.updated','system_settings',1,?)", c.GetUint64("admin_id"), `{"fields":["site_name","support_email","announcement"]}`) + } + if err != nil { + apiError(c, 500, "internal_error", "设置保存失败") + return + } + if tx.Commit() != nil { + apiError(c, 500, "internal_error", "设置保存结果未确认,请刷新检查") + return + } + c.JSON(200, gin.H{"data": s}) +} +func (a *BusinessAPI) changePassword(c *gin.Context) { + var in struct { + Current string `json:"current_password"` + New string `json:"new_password"` + } + if c.ShouldBindJSON(&in) != nil || in.Current == "" || in.New == "" || len(in.New) > 72 { + apiError(c, 400, "invalid_request", "当前密码和新密码不能为空,新密码最多72字节") + return + } + // Hash before acquiring the row lock to keep the write transaction short. + hash, err := bcrypt.GenerateFromPassword([]byte(in.New), bcrypt.DefaultCost) + if err != nil { + apiError(c, 500, "internal_error", "密码修改失败") + return + } + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "密码修改失败") + return + } + defer tx.Rollback() + var old string + id := c.GetUint64("admin_id") + err = tx.QueryRowContext(c, "SELECT password_hash FROM admins WHERE id=? AND active=1 FOR UPDATE", id).Scan(&old) + if err == sql.ErrNoRows { + apiError(c, 401, "unauthorized", "账号已失效") + return + } + if err != nil { + apiError(c, 500, "internal_error", "密码修改失败") + return + } + if bcrypt.CompareHashAndPassword([]byte(old), []byte(in.Current)) != nil { + apiError(c, 400, "invalid_credentials", "当前密码错误") + return + } + raw, _ := c.Cookie("lp_session") + decoded, _ := hex.DecodeString(raw) + sum := sha256.Sum256(decoded) + if _, err = tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id); err == nil { + _, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND token_hash<>? AND revoked_at IS NULL", time.Now().UTC(), id, sum[:]) + } + if err == nil { + _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_changed','admin',?,?)", id, id, `{"other_sessions_revoked":true}`) + } + if err != nil { + apiError(c, 500, "internal_error", "密码修改失败") + return + } + if tx.Commit() != nil { + apiError(c, 500, "internal_error", "密码修改结果未确认,请重新登录检查") + return + } + c.Status(204) +} + +type auditRecord struct { + ID uint64 `json:"id"` + ActorID uint64 `json:"actor_admin_id"` + ActorEmail string `json:"actor_email"` + Action string `json:"action"` + ResourceType string `json:"resource_type"` + ResourceID uint64 `json:"resource_id"` + Details map[string]any `json:"details"` + CreatedAt time.Time `json:"created_at"` +} + +// Expose known business fields only. Future events cannot accidentally expose credentials. +func publicAuditDetails(raw []byte) map[string]any { + var input map[string]any + _ = json.Unmarshal(raw, &input) + out := map[string]any{} + for _, key := range []string{"client_actor", "customer_id", "product_id", "license_id", "order_id", "instance_id", "release_id", "starts_at", "expires_at", "operation", "amount_cents", "currency", "certificate_version", "state", "previous_state", "freeze_state", "lease_expires_at", "version", "sha256", "size_bytes", "fields", "other_sessions_revoked"} { + if v, ok := input[key]; ok { + switch v.(type) { + case string, float64, bool, nil: + out[key] = v + case []any: + if key == "fields" { + out[key] = []string{"site_name", "support_email", "announcement"} + } + } + } + } + return out +} +func auditFilter(c *gin.Context) (string, []any, bool) { + clauses := []string{"1=1"} + args := []any{} + for _, item := range []struct{ key, column string }{{"action", "e.action"}, {"resource_type", "e.resource_type"}} { + if v := strings.TrimSpace(c.Query(item.key)); v != "" { + if len(v) > 64 { + return "", nil, false + } + clauses = append(clauses, item.column+"=?") + args = append(args, v) + } + } + if q := strings.TrimSpace(c.Query("q")); q != "" { + if utf8.RuneCountInString(q) > 200 { + return "", nil, false + } + clauses = append(clauses, "(a.email LIKE ? OR e.action LIKE ? OR e.resource_type LIKE ?)") + for i := 0; i < 3; i++ { + args = append(args, "%"+q+"%") + } + } + var from, to time.Time + for _, key := range []string{"from", "to"} { + if v := c.Query(key); v != "" { + t, err := time.Parse(time.RFC3339, v) + if err != nil { + return "", nil, false + } + op := ">=" + if key == "to" { + op = "<=" + to = t + } else { + from = t + } + clauses = append(clauses, "e.created_at"+op+"?") + args = append(args, t.UTC()) + } + } + if !from.IsZero() && !to.IsZero() && from.After(to) { + return "", nil, false + } + return strings.Join(clauses, " AND "), args, true +} +func (a *BusinessAPI) listAuditEvents(c *gin.Context) { + where, args, ok := auditFilter(c) + if !ok { + apiError(c, 400, "invalid_request", "审计筛选参数无效,时间请使用ISO格式") + return + } + p, size := page(c) + tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true}) + if err != nil { + apiError(c, 500, "internal_error", "日志加载失败") + return + } + defer tx.Rollback() + base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE " + where + var total int64 + if err = tx.QueryRowContext(c, "SELECT COUNT(*)"+base, args...).Scan(&total); err != nil { + apiError(c, 500, "internal_error", "日志加载失败") + return + } + pageArgs := append(append([]any{}, args...), size, (p-1)*size) + rows, err := tx.QueryContext(c, "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at"+base+" ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", pageArgs...) + if err != nil { + apiError(c, 500, "internal_error", "日志加载失败") + return + } + defer rows.Close() + out := []auditRecord{} + for rows.Next() { + var v auditRecord + var raw []byte + if err = rows.Scan(&v.ID, &v.ActorID, &v.ActorEmail, &v.Action, &v.ResourceType, &v.ResourceID, &raw, &v.CreatedAt); err != nil { + apiError(c, 500, "internal_error", "日志加载失败") + return + } + v.Details = publicAuditDetails(raw) + out = append(out, v) + } + if rows.Err() != nil { + apiError(c, 500, "internal_error", "日志加载失败") + return + } + rows.Close() + if tx.Commit() != nil { + apiError(c, 500, "internal_error", "日志加载失败") + return + } + c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}}) +} diff --git a/backend/internal/httpapi/admin_settings_test.go b/backend/internal/httpapi/admin_settings_test.go new file mode 100644 index 0000000..aa03e8a --- /dev/null +++ b/backend/internal/httpapi/admin_settings_test.go @@ -0,0 +1,99 @@ +package httpapi + +import ( + "database/sql/driver" + "encoding/json" + "github.com/gin-gonic/gin" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestAuditListSnapshot(t *testing.T) { + now := time.Date(2026, 10, 9, 2, 0, 0, 0, time.UTC) + base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE 1=1 AND e.action=?" + db, stub := newDashboardTestDB(t, []dashboardQuery{ + {sql: "SELECT COUNT(*)" + base, args: []any{"license.issued"}, rows: [][]driver.Value{{int64(21)}}}, + {sql: "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at" + base + " ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", args: []any{"license.issued", 20, 20}, rows: [][]driver.Value{{int64(1), int64(2), "admin@example.test", "license.issued", "license", int64(3), []byte(`{"license_id":3,"password":"hidden"}`), now}}}, + }) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/?action=license.issued&page=2", nil) + (&BusinessAPI{db: db}).listAuditEvents(c) + if w.Code != 200 || strings.Contains(w.Body.String(), "hidden") { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + var result struct { + Data []auditRecord `json:"data"` + Meta struct { + Total int `json:"total"` + Page int `json:"page"` + } `json:"meta"` + } + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + if result.Meta.Total != 21 || result.Meta.Page != 2 || len(result.Data) != 1 || !stub.committed || !stub.txOptions.ReadOnly { + t.Fatalf("unexpected snapshot: %s", w.Body.String()) + } +} +func TestPlatformSettingsValidation(t *testing.T) { + for _, tc := range []struct { + s platformSettings + ok bool + }{ + {platformSettings{SiteName: " 管理台 "}, true}, + {platformSettings{SiteName: ""}, false}, + {platformSettings{SiteName: strings.Repeat("中", 101)}, false}, + {platformSettings{SiteName: "平台", SupportEmail: "admin@example.test"}, true}, + {platformSettings{SiteName: "平台", SupportEmail: "Name "}, false}, + {platformSettings{SiteName: "平台", Announcement: strings.Repeat("中", 2001)}, false}, + } { + if got := validateSettings(&tc.s); got != tc.ok { + t.Fatalf("validation=%v want %v", got, tc.ok) + } + } +} +func TestAuditDetailsAllowlist(t *testing.T) { + out := publicAuditDetails([]byte(`{"license_id":3,"password":"private","token":"private","instance_secret":"private","state":{"password":"private"},"fields":["private"]}`)) + if len(out) != 2 || out["license_id"] != float64(3) { + t.Fatalf("unsafe details: %#v", out) + } + if len(publicAuditDetails([]byte(`invalid`))) != 0 { + t.Fatal("invalid JSON exposed") + } +} +func TestAuditFilterValidation(t *testing.T) { + for _, tc := range []struct { + query string + ok bool + }{ + {"?action=license.issued&resource_type=license&q=admin", true}, + {"?from=2026-10-09T00:00:00Z&to=2026-10-10T00:00:00Z", true}, + {"?from=not-a-date", false}, + {"?from=2026-10-10T00:00:00Z&to=2026-10-09T00:00:00Z", false}, + {"?action=" + strings.Repeat("x", 65), false}, + } { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", "/"+tc.query, nil) + where, _, ok := auditFilter(c) + if ok != tc.ok { + t.Fatalf("%s got %v", tc.query, ok) + } + if ok && where == "" { + t.Fatal("missing predicate") + } + } +} +func TestAdminModuleAuthentication(t *testing.T) { + r := gin.New() + registerBusinessRoutes(r, &BusinessAPI{}) + for _, tc := range []struct{ method, path string }{{"GET", "/api/v1/audit-events"}, {"GET", "/api/v1/settings"}, {"PUT", "/api/v1/settings"}, {"POST", "/api/v1/settings/password"}} { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil)) + if w.Code != 401 { + t.Fatalf("%s %s: %d", tc.method, tc.path, w.Code) + } + } +} diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go new file mode 100644 index 0000000..3c7eac4 --- /dev/null +++ b/backend/internal/httpapi/business.go @@ -0,0 +1,372 @@ +package httpapi + +import ( + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/hex" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + "golang.org/x/crypto/bcrypt" +) + +type BusinessAPI struct { + db *sql.DB + signingPrivateKeyPEM string + keyring *Keyring +} + +func secureSessionCookie(c *gin.Context) bool { + return c.Request.TLS != nil || os.Getenv("SESSION_COOKIE_SECURE") == "true" +} + +func RegisterBusiness(r *gin.Engine, db *sql.DB, signingPrivateKeyPEM ...string) { + if db == nil { + return + } + a := &BusinessAPI{db: db} + if len(signingPrivateKeyPEM) > 0 { + a.signingPrivateKeyPEM = signingPrivateKeyPEM[0] + } + registerBusinessRoutes(r, a) +} +func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring) { + if db == nil { + return + } + registerBusinessRoutes(r, &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring}) +} +func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { + api := r.Group("/api/v1") + api.POST("/auth/login", a.login) + api.POST("/portal/snapshot", a.portalSnapshot) + api.POST("/activation/instances/:instance_id", a.activateInstance) + api.GET("/activation/public-key", a.activationPublicKey) + api.GET("/activation/keyring", func(c *gin.Context) { + if a.keyring == nil { + apiError(c, 404, "not_found", "Keyring unavailable") + return + } + c.JSON(200, gin.H{"data": a.keyring}) + }) + api.POST("/instances/:instance_id/heartbeat", a.heartbeat) + api.POST("/auth/logout", a.authenticated, a.logout) + secured := api.Group("", a.authenticated) + secured.GET("/me", a.me) + secured.GET("/admins", a.listAdmins) + secured.POST("/admins", a.createAdmin) + secured.POST("/admins/:id/active", a.setAdminActive) + secured.POST("/admins/:id/reset-password", a.resetAdminPassword) + secured.GET("/dashboard/summary", a.dashboardSummary) + secured.GET("/audit-events", a.listAuditEvents) + secured.GET("/settings", a.getSettings) + secured.PUT("/settings", a.updateSettings) + secured.POST("/settings/password", a.changePassword) + secured.GET("/integration-kit", a.integrationKit) + secured.GET("/integration-kit/download", a.downloadIntegrationKit) + secured.GET("/integration-kit/archive", a.downloadIntegrationArchive) + secured.GET("/customers", a.listCustomers) + secured.POST("/customers", a.createCustomer) + secured.PUT("/customers/:id", a.updateCustomer) + secured.DELETE("/customers/:id", a.deleteCustomer) + secured.GET("/products", a.listProducts) + secured.POST("/products", a.createProduct) + secured.PUT("/products/:id", a.updateProduct) + secured.DELETE("/products/:id", a.deleteProduct) + secured.GET("/orders", a.listOrders) + secured.GET("/orders/:id", a.getOrder) + secured.POST("/orders", func(c *gin.Context) { a.writeOrder(c, "create") }) + secured.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") }) + secured.POST("/orders/:id/issue", func(c *gin.Context) { a.writeOrder(c, "issue") }) + secured.GET("/licenses", a.listLicenses) + secured.GET("/licenses/:id", a.getLicense) + secured.GET("/licenses/:id/instances", a.listInstances) + secured.POST("/licenses/:id/instances", a.provisionInstance) + secured.POST("/products/:id/releases", a.createRelease) + secured.GET("/products/:id/releases", a.listReleases) + api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease) + secured.POST("/instances/:instance_id/freeze", a.freezeInstance) + secured.POST("/licenses", a.issueLicense) + secured.POST("/licenses/:id/revoke", func(c *gin.Context) { a.operateLicense(c, "revoke") }) + secured.POST("/licenses/:id/renew", func(c *gin.Context) { a.operateLicense(c, "renew") }) +} + +func (a *BusinessAPI) login(c *gin.Context) { + var in struct { + Username string `json:"username"` + Password string `json:"password"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空") + return + } + username := strings.ToLower(strings.TrimSpace(in.Username)) + if username == "" || in.Password == "" { + apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空") + return + } + var id uint64 + var hash string + var role string + var email string + err := a.db.QueryRowContext(c, "SELECT id,email,password_hash,role FROM admins WHERE username=? AND active=1", username).Scan(&id, &email, &hash, &role) + if err != nil || bcrypt.CompareHashAndPassword([]byte(hash), []byte(in.Password)) != nil { + apiError(c, http.StatusUnauthorized, "invalid_credentials", "用户名或密码错误") + return + } + raw := make([]byte, 32) + if _, err = rand.Read(raw); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + expires := time.Now().UTC().Add(8 * time.Hour) + sum := sha256.Sum256(raw) + if _, err = a.db.ExecContext(c, "INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", id, sum[:], expires); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.SetSameSite(http.SameSiteStrictMode) + secure := secureSessionCookie(c) + c.SetCookie("lp_session", hex.EncodeToString(raw), 8*3600, "/", "", secure, true) + c.JSON(http.StatusOK, gin.H{"data": gin.H{"username": username, "email": email, "role": role, "expires_at": expires}}) +} + +func (a *BusinessAPI) authenticated(c *gin.Context) { + raw, err := c.Cookie("lp_session") + if err != nil || len(raw) != 64 { + apiError(c, 401, "unauthorized", "请先登录") + c.Abort() + return + } + decoded, err := hex.DecodeString(raw) + if err != nil { + apiError(c, 401, "unauthorized", "请先登录") + c.Abort() + return + } + sum := sha256.Sum256(decoded) + var id uint64 + var username, email, role string + err = a.db.QueryRowContext(c, "SELECT a.id,a.username,a.email,a.role FROM sessions s JOIN admins a ON a.id=s.admin_id WHERE s.token_hash=? AND s.revoked_at IS NULL AND s.expires_at>? AND a.active=1", sum[:], time.Now().UTC()).Scan(&id, &username, &email, &role) + if err != nil { + apiError(c, 401, "unauthorized", "会话已失效") + c.Abort() + return + } + if role != "admin" { + apiError(c, http.StatusForbidden, "forbidden", "无权访问管理接口") + c.Abort() + return + } + c.Set("admin_id", id) + c.Set("admin_username", username) + c.Set("admin_email", email) + c.Set("admin_role", role) + c.Next() +} +func (a *BusinessAPI) logout(c *gin.Context) { + if raw, err := c.Cookie("lp_session"); err == nil { + if b, e := hex.DecodeString(raw); e == nil { + sum := sha256.Sum256(b) + _, _ = a.db.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE token_hash=?", time.Now().UTC(), sum[:]) + } + } + c.SetSameSite(http.SameSiteStrictMode) + c.SetCookie("lp_session", "", -1, "/", "", secureSessionCookie(c), true) + c.Status(http.StatusNoContent) +} +func (a *BusinessAPI) me(c *gin.Context) { + c.JSON(200, gin.H{"data": gin.H{"username": c.GetString("admin_username"), "email": c.GetString("admin_email"), "role": c.GetString("admin_role")}}) +} + +type customer struct { + ID uint64 `json:"id"` + Name string `json:"name"` + ContactEmail string `json:"contact_email"` + Status string `json:"status"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} +type product struct { + ID uint64 `json:"id"` + Code string `json:"code"` + Name string `json:"name"` + Description string `json:"description"` + Active bool `json:"active"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func page(c *gin.Context) (int, int) { + p, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + if p < 1 { + p = 1 + } + if size < 1 || size > 100 { + size = 20 + } + return p, size +} +func (a *BusinessAPI) listCustomers(c *gin.Context) { + p, size := page(c) + q := strings.TrimSpace(c.Query("q")) + like := "%" + q + "%" + var total int + if err := a.db.QueryRowContext(c, "SELECT COUNT(*) FROM customers WHERE name LIKE ? OR contact_email LIKE ?", like, like).Scan(&total); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + rows, err := a.db.QueryContext(c, "SELECT id,name,contact_email,status,created_at,updated_at FROM customers WHERE name LIKE ? OR contact_email LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?", like, like, size, (p-1)*size) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer rows.Close() + out := []customer{} + for rows.Next() { + var x customer + if err := rows.Scan(&x.ID, &x.Name, &x.ContactEmail, &x.Status, &x.CreatedAt, &x.UpdatedAt); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + out = append(out, x) + } + c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}}) +} +func (a *BusinessAPI) createCustomer(c *gin.Context) { + var in struct { + Name string `json:"name"` + ContactEmail string `json:"contact_email"` + } + if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") { + apiError(c, 400, "invalid_request", "客户名称和邮箱格式不正确") + return + } + res, err := a.db.ExecContext(c, "INSERT INTO customers(name,contact_email) VALUES(?,?)", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail))) + if err != nil { + apiError(c, 409, "customer_conflict", "客户创建失败") + return + } + id, _ := res.LastInsertId() + c.JSON(201, gin.H{"data": gin.H{"id": id}}) +} +func (a *BusinessAPI) updateCustomer(c *gin.Context) { + id := c.Param("id") + var in struct { + Name string `json:"name"` + ContactEmail string `json:"contact_email"` + Status string `json:"status"` + } + if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") { + apiError(c, 400, "invalid_request", "客户字段不正确") + return + } + res, err := a.db.ExecContext(c, "UPDATE customers SET name=?,contact_email=?,status=? WHERE id=?", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)), in.Status, id) + if err != nil || func() bool { n, _ := res.RowsAffected(); return n == 0 }() { + apiError(c, 404, "not_found", "客户不存在") + return + } + c.Status(204) +} +func (a *BusinessAPI) deleteCustomer(c *gin.Context) { + res, err := a.db.ExecContext(c, "DELETE FROM customers WHERE id=?", c.Param("id")) + if err != nil { + apiError(c, 500, "internal_error", "删除失败") + return + } + n, _ := res.RowsAffected() + if n == 0 { + apiError(c, 404, "not_found", "客户不存在") + return + } + c.Status(204) +} +func (a *BusinessAPI) listProducts(c *gin.Context) { + rows, err := a.db.QueryContext(c, "SELECT id,code,name,description,active,created_at,updated_at FROM products ORDER BY id DESC") + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer rows.Close() + out := []product{} + for rows.Next() { + var x product + if rows.Scan(&x.ID, &x.Code, &x.Name, &x.Description, &x.Active, &x.CreatedAt, &x.UpdatedAt) != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + out = append(out, x) + } + c.JSON(200, gin.H{"data": out}) +} +func (a *BusinessAPI) createProduct(c *gin.Context) { + var in struct { + Code string `json:"code"` + Name string `json:"name"` + Description string `json:"description"` + } + if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 { + apiError(c, 400, "invalid_request", "产品编码和名称不能为空") + return + } + res, err := a.db.ExecContext(c, "INSERT INTO products(code,name,description) VALUES(?,?,?)", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description) + if err != nil { + apiError(c, 409, "product_conflict", "产品编码已存在") + return + } + id, _ := res.LastInsertId() + c.JSON(201, gin.H{"data": gin.H{"id": id}}) +} +func (a *BusinessAPI) updateProduct(c *gin.Context) { + var in struct { + Code string `json:"code"` + Name string `json:"name"` + Description string `json:"description"` + Active *bool `json:"active"` + } + if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 { + apiError(c, 400, "invalid_request", "产品字段不正确") + return + } + active := true + if in.Active != nil { + active = *in.Active + } + res, err := a.db.ExecContext(c, "UPDATE products SET code=?,name=?,description=?,active=? WHERE id=?", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description, active, c.Param("id")) + if err != nil { + apiError(c, 409, "product_conflict", "产品更新失败") + return + } + n, _ := res.RowsAffected() + if n == 0 { + apiError(c, 404, "not_found", "产品不存在") + return + } + c.Status(204) +} +func (a *BusinessAPI) deleteProduct(c *gin.Context) { + res, err := a.db.ExecContext(c, "DELETE FROM products WHERE id=?", c.Param("id")) + if err != nil { + apiError(c, 500, "internal_error", "删除失败") + return + } + n, _ := res.RowsAffected() + if n == 0 { + apiError(c, 404, "not_found", "产品不存在") + return + } + c.Status(204) +} +func apiError(c *gin.Context, status int, code, message string) { + if status >= 500 { + message = "Service unavailable" + } + c.Set("error_code", code) + c.JSON(status, gin.H{"error": gin.H{"code": code, "message": message, "request_id": c.GetString("request_id")}}) +} diff --git a/backend/internal/httpapi/business_integration_test.go b/backend/internal/httpapi/business_integration_test.go new file mode 100644 index 0000000..97c4699 --- /dev/null +++ b/backend/internal/httpapi/business_integration_test.go @@ -0,0 +1,293 @@ +package httpapi + +import ( + "crypto/tls" + "database/sql" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + _ "github.com/go-sql-driver/mysql" + "golang.org/x/crypto/bcrypt" +) + +func TestBusinessMySQLIntegration(t *testing.T) { + dsn := os.Getenv("MYSQL_TEST_DSN") + if dsn == "" { + t.Skip("MYSQL_TEST_DSN is not set") + } + db, err := sql.Open("mysql", dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if err = db.Ping(); err != nil { + t.Fatal(err) + } + for _, table := range []string{"instance_state_operations", "heartbeat_operations", "activation_operations", "license_instances", "order_operations", "offline_orders"} { + if _, err = db.Exec("DELETE FROM " + table); err != nil { + t.Fatal(err) + } + } + if _, err = db.Exec("DELETE FROM audit_events"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("DELETE FROM license_operations"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("DELETE FROM licenses"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("DELETE FROM sessions"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("DELETE FROM products"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("DELETE FROM customers"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("DELETE FROM admins"); err != nil { + t.Fatal(err) + } + hash, err := bcrypt.GenerateFromPassword([]byte("Integration-Test-Password-2026!"), bcrypt.MinCost) + if err != nil { + t.Fatal(err) + } + if _, err = db.Exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", "integration", "integration@example.test", string(hash)); err != nil { + t.Fatal(err) + } + r := NewRouter() + RegisterBusiness(r, db) + request := func(method, path, body, cookie string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if strings.HasPrefix(path, "/api/v1/auth/login") { + req.TLS = &tls.ConnectionState{} + } + if cookie != "" { + req.Header.Set("Cookie", cookie) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + if w := request("GET", "/api/v1/customers", "", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated code=%d body=%s", w.Code, w.Body) + } + w := request("POST", "/api/v1/auth/login", `{"username":"integration","password":"Integration-Test-Password-2026!"}`, "") + if w.Code != 200 { + t.Fatalf("login code=%d body=%s", w.Code, w.Body) + } + cookie := w.Result().Cookies()[0] + if cookie.Name != "lp_session" || !cookie.HttpOnly || !cookie.Secure { + t.Fatalf("insecure session cookie: %+v", cookie) + } + w = request("POST", "/api/v1/customers", `{"name":"Integration customer","contact_email":"customer@example.test"}`, cookie.Name+"="+cookie.Value) + if w.Code != 201 { + t.Fatalf("create customer code=%d body=%s", w.Code, w.Body) + } + var customerID, productID uint64 + if err = db.QueryRow("SELECT id FROM customers ORDER BY id DESC LIMIT 1").Scan(&customerID); err != nil { + t.Fatal(err) + } + w = request("GET", "/api/v1/customers?page=1&page_size=20", "", cookie.Name+"="+cookie.Value) + if w.Code != 200 || !strings.Contains(w.Body.String(), "Integration customer") { + t.Fatalf("list customers code=%d body=%s", w.Code, w.Body) + } + w = request("POST", "/api/v1/products", `{"code":"integration-product","name":"Integration Product","description":"probe"}`, cookie.Name+"="+cookie.Value) + if w.Code != 201 { + t.Fatalf("create product code=%d body=%s", w.Code, w.Body) + } + if err = db.QueryRow("SELECT id FROM products ORDER BY id DESC LIMIT 1").Scan(&productID); err != nil { + t.Fatal(err) + } + w = request("GET", "/api/v1/products", "", cookie.Name+"="+cookie.Value) + if w.Code != 200 || !strings.Contains(w.Body.String(), "integration-product") { + t.Fatalf("list products code=%d body=%s", w.Code, w.Body) + } + issueBody := fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"starts_at":"2026-09-30T00:00:00Z","expires_at":"2027-09-30T00:00:00Z"}`, customerID, productID) + w = request("POST", "/api/v1/licenses", issueBody, "") + if w.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated issue code=%d", w.Code) + } + requestWithKey := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/api/v1/licenses", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "integration-issue-1") + req.AddCookie(cookie) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + w = requestWithKey(issueBody) + if w.Code != http.StatusCreated { + t.Fatalf("issue code=%d body=%s", w.Code, w.Body) + } + var first struct { + Data licenseRecord `json:"data"` + } + if err = json.Unmarshal(w.Body.Bytes(), &first); err != nil { + t.Fatal(err) + } + w = requestWithKey(issueBody) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) || !strings.Contains(w.Body.String(), first.Data.LicenseKey) { + t.Fatalf("idempotent replay code=%d body=%s", w.Code, w.Body) + } + var licenseCount, auditCount int + if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil { + t.Fatal(err) + } + if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='license.issued'").Scan(&auditCount); err != nil { + t.Fatal(err) + } + if licenseCount != 1 || auditCount != 1 { + t.Fatalf("expected single license/audit; got %d/%d", licenseCount, auditCount) + } + w = request("GET", "/api/v1/licenses?page=1&page_size=20", "", cookie.Name+"="+cookie.Value) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"active"`) { + t.Fatalf("list licenses code=%d body=%s", w.Code, w.Body) + } + w = request("GET", fmt.Sprintf("/api/v1/licenses/%d", first.Data.ID), "", cookie.Name+"="+cookie.Value) + if w.Code != 200 || !strings.Contains(w.Body.String(), first.Data.LicenseKey) { + t.Fatalf("license detail code=%d body=%s", w.Code, w.Body) + } + operation := func(method, path, body, key string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", key) + req.AddCookie(cookie) + out := httptest.NewRecorder() + r.ServeHTTP(out, req) + return out + } + licensePath := func(suffix string) string { return fmt.Sprintf("/api/v1/licenses/%d/%s", first.Data.ID, suffix) } + w = operation("POST", licensePath("renew"), `{"expires_at":"2028-01-01T00:00:00Z"}`, "renew-1") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"expires_at":"2028-01-01T00:00:00Z"`) { + t.Fatalf("renew code=%d body=%s", w.Code, w.Body) + } + w = operation("POST", licensePath("renew"), `{"expires_at":"2028-01-01T00:00:00Z"}`, "renew-1") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) { + t.Fatalf("renew replay code=%d body=%s", w.Code, w.Body) + } + w = operation("POST", licensePath("renew"), `{"expires_at":"2029-01-01T00:00:00Z"}`, "renew-1") + if w.Code != 409 { + t.Fatalf("renew conflict code=%d body=%s", w.Code, w.Body) + } + w = operation("POST", licensePath("revoke"), "{}", "revoke-1") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"revoked"`) { + t.Fatalf("revoke code=%d body=%s", w.Code, w.Body) + } + w = operation("POST", licensePath("revoke"), "{}", "revoke-1") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) { + t.Fatalf("revoke replay code=%d body=%s", w.Code, w.Body) + } + w = operation("POST", licensePath("renew"), `{"expires_at":"2029-01-01T00:00:00Z"}`, "renew-after-revoke") + if w.Code != 400 { + t.Fatalf("renew revoked code=%d body=%s", w.Code, w.Body) + } + if err = db.QueryRow("SELECT COUNT(*) FROM audit_events").Scan(&auditCount); err != nil { + t.Fatal(err) + } + if auditCount != 3 { + t.Fatalf("audit count after operations=%d", auditCount) + } + w = requestWithKey(fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"starts_at":"bad","expires_at":"2027-01-01T00:00:00Z"}`, customerID, productID)) + if w.Code != 400 { + t.Fatalf("invalid dates code=%d body=%s", w.Code, w.Body) + } + w = requestWithKey(strings.Replace(issueBody, "2027-09-30", "2027-10-30", 1)) + if w.Code != 409 { + t.Fatalf("changed payload code=%d body=%s", w.Code, w.Body) + } + if _, err = db.Exec("UPDATE admins SET role='viewer' WHERE email='integration@example.test'"); err != nil { + t.Fatal(err) + } + w = requestWithKey(issueBody) + if w.Code != 403 { + t.Fatalf("viewer issue code=%d body=%s", w.Code, w.Body) + } + if _, err = db.Exec("UPDATE admins SET role='admin' WHERE email='integration@example.test'"); err != nil { + t.Fatal(err) + } + // A new key must still validate current master-data state. + if _, err = db.Exec("UPDATE products SET active=0 WHERE id=?", productID); err != nil { + t.Fatal(err) + } + newKeyRequest := func(key string) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/api/v1/licenses", strings.NewReader(issueBody)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", key) + req.AddCookie(cookie) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + w = newKeyRequest("inactive-product") + if w.Code != 400 { + t.Fatalf("inactive product code=%d body=%s", w.Code, w.Body) + } + if _, err = db.Exec("UPDATE products SET active=1 WHERE id=?", productID); err != nil { + t.Fatal(err) + } + // Inject a test-only audit failure to prove issuance rolls back atomically. + if _, err = db.Exec("CREATE TRIGGER integration_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='integration audit failure'"); err != nil { + t.Fatal(err) + } + w = newKeyRequest("audit-failure") + _, dropErr := db.Exec("DROP TRIGGER integration_audit_failure") + if dropErr != nil { + t.Fatal(dropErr) + } + if w.Code != 500 { + t.Fatalf("audit failure code=%d body=%s", w.Code, w.Body) + } + if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil { + t.Fatal(err) + } + if licenseCount != 1 { + t.Fatalf("audit failure left %d licenses", licenseCount) + } + results := make(chan *httptest.ResponseRecorder, 2) + for i := 0; i < 2; i++ { + go func() { results <- newKeyRequest("concurrent-issue") }() + } + created, replayed := 0, 0 + for i := 0; i < 2; i++ { + response := <-results + switch response.Code { + case 201: + created++ + case 200: + replayed++ + default: + t.Fatalf("concurrent issue code=%d body=%s", response.Code, response.Body) + } + } + if created != 1 || replayed != 1 { + t.Fatalf("concurrent created/replayed=%d/%d", created, replayed) + } + if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil { + t.Fatal(err) + } + if err = db.QueryRow("SELECT COUNT(*) FROM audit_events").Scan(&auditCount); err != nil { + t.Fatal(err) + } + if licenseCount != 2 || auditCount != 4 { + t.Fatalf("concurrent license/audit=%d/%d", licenseCount, auditCount) + } + t.Run("orders", func(t *testing.T) { testOrdersMySQL(t, db, r, cookie, customerID, productID) }) + t.Run("activation", func(t *testing.T) { testActivationMySQL(t, db, cookie) }) + w = request("POST", "/api/v1/auth/logout", "", cookie.Name+"="+cookie.Value) + if w.Code != http.StatusNoContent { + t.Fatalf("logout code=%d", w.Code) + } + w = request("GET", "/api/v1/me", "", cookie.Name+"="+cookie.Value) + if w.Code != http.StatusUnauthorized { + t.Fatalf("revoked session code=%d", w.Code) + } +} diff --git a/backend/internal/httpapi/dashboard.go b/backend/internal/httpapi/dashboard.go new file mode 100644 index 0000000..18177b0 --- /dev/null +++ b/backend/internal/httpapi/dashboard.go @@ -0,0 +1,111 @@ +package httpapi + +import ( + "database/sql" + "time" + + "github.com/gin-gonic/gin" +) + +type licenseTrendPoint struct { + Month string `json:"month"` + Issued int64 `json:"issued"` + Expired int64 `json:"expired"` +} + +type dashboardSummaryRecord struct { + ActiveLicenses int64 `json:"active_licenses"` + NewCustomers int64 `json:"new_customers"` + PaidRevenueCents int64 `json:"paid_revenue_cents"` + Currency string `json:"currency"` + ExpiringLicenses int64 `json:"expiring_licenses"` + LicenseTrend []licenseTrendPoint `json:"license_trend"` + UpcomingExpirations []licenseRecord `json:"upcoming_expirations"` + RecentLicenses []licenseRecord `json:"recent_licenses"` + GeneratedAt time.Time `json:"generated_at"` +} + +func dashboardMonths(c *gin.Context) (int, bool) { + switch c.DefaultQuery("months", "6") { + case "6": + return 6, true + case "12": + return 12, true + default: + apiError(c, 400, "invalid_request", "months 必须为 6 或 12") + return 0, false + } +} + +func (a *BusinessAPI) dashboardSummary(c *gin.Context) { + months, ok := dashboardMonths(c) + if !ok { + return + } + now := time.Now().UTC() + out, err := a.loadDashboardSummary(c, now, months) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.JSON(200, gin.H{"data": out}) +} + +// A read-only consistent snapshot prevents concurrent issuance/payment from making +// the summary counts and its lists disagree. No application rows are changed. +func (a *BusinessAPI) loadDashboardSummary(c *gin.Context, now time.Time, months int) (dashboardSummaryRecord, error) { + now = now.UTC() + monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) + nextMonth := monthStart.AddDate(0, 1, 0) + out := dashboardSummaryRecord{Currency: "CNY", GeneratedAt: now, + LicenseTrend: make([]licenseTrendPoint, months), + UpcomingExpirations: []licenseRecord{}, RecentLicenses: []licenseRecord{}} + tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true}) + if err != nil { + return out, err + } + defer tx.Rollback() + err = tx.QueryRowContext(c, `SELECT + (SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?), + (SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at=? AND paid_at'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)`, + now, now, monthStart, nextMonth, monthStart, nextMonth, now, now, now.Add(30*24*time.Hour)).Scan( + &out.ActiveLicenses, &out.NewCustomers, &out.PaidRevenueCents, &out.ExpiringLicenses) + if err != nil { + return out, err + } + // Range aggregates use UTC boundaries rather than the database session's date + // formatting/timezone. Each bucket includes its start and excludes its end. + for i := range out.LicenseTrend { + start := monthStart.AddDate(0, i-months+1, 0) + end := start.AddDate(0, 1, 0) + point := &out.LicenseTrend[i] + point.Month = start.Format("2006-01") + err = tx.QueryRowContext(c, `SELECT + (SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at'revoked' AND expires_at>=? AND expires_at 0 { + width = len(q.rows[0]) + } else if strings.HasPrefix(query, "SELECT l.id") { + width = 11 + } + return &dashboardRows{rows: q.rows, width: width, err: q.rowErr}, nil +} + +type dashboardRows struct { + rows [][]driver.Value + width int + err error +} + +func (r *dashboardRows) Columns() []string { + out := make([]string, r.width) + for i := range out { + out[i] = fmt.Sprint(i) + } + return out +} +func (*dashboardRows) Close() error { return nil } +func (r *dashboardRows) Next(dst []driver.Value) error { + if len(r.rows) == 0 { + if r.err != nil { + return r.err + } + return io.EOF + } + copy(dst, r.rows[0]) + r.rows = r.rows[1:] + return nil +} +func newDashboardTestDB(t *testing.T, queries []dashboardQuery) (*sql.DB, *dashboardDB) { + t.Helper() + stub := &dashboardDB{t: t, queries: queries} + db := sql.OpenDB(stub) + t.Cleanup(func() { + db.Close() + if len(stub.queries) > 0 { + t.Errorf("%d unconsumed SQL expectations", len(stub.queries)) + } + }) + return db, stub +} + +const dashboardTotalsSQL = `SELECT + (SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?), + (SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at=? AND paid_at'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)` +const dashboardTrendSQL = `SELECT + (SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at'revoked' AND expires_at>=? AND expires_at'revoked' AND l.starts_at<=? AND l.expires_at>? AND l.expires_at<=? ORDER BY l.expires_at ASC,l.id ASC LIMIT 10", args: []any{now, now, now.Add(30 * 24 * time.Hour)}, rows: [][]driver.Value{testLicenseRow(1, "active", now.Add(-time.Hour), now.Add(time.Hour), now)}}, + dashboardQuery{sql: licenseSelect + " ORDER BY l.created_at DESC,l.id DESC LIMIT 10", rows: [][]driver.Value{testLicenseRow(2, "active", now.Add(time.Hour), now.Add(2*time.Hour), now)}}) + return queries +} +func testLicenseRow(id int64, status string, start, end, created time.Time) []driver.Value { + return []driver.Value{id, "key", int64(7), "Customer", int64(8), "Product", "code", status, start, end, created} +} +func TestDashboardSummarySnapshot(t *testing.T) { + for _, months := range []int{6, 12} { + t.Run(fmt.Sprint(months), func(t *testing.T) { + // January in UTC+8 is still December in UTC; also tests crossing a year. + now := time.Date(2027, 1, 1, 1, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)).UTC() + db, stub := newDashboardTestDB(t, dashboardExpectations(now, months)) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", "/", nil) + out, err := (&BusinessAPI{db: db}).loadDashboardSummary(c, now, months) + if err != nil { + t.Fatal(err) + } + if out.ActiveLicenses != 123 || out.NewCustomers != 45 || out.PaidRevenueCents != 987654321 || out.ExpiringLicenses != 27 || out.Currency != "CNY" { + t.Fatalf("wrong totals: %+v", out) + } + if !stub.began || !stub.committed || stub.rolledBack || !stub.txOptions.ReadOnly || stub.txOptions.Isolation != driver.IsolationLevel(sql.LevelRepeatableRead) { + t.Fatalf("snapshot transaction: %+v", stub) + } + if len(out.LicenseTrend) != months || out.LicenseTrend[months-1].Month != "2026-12" || out.LicenseTrend[0].Issued != 0 { + t.Fatalf("trend: %+v", out.LicenseTrend) + } + if len(out.UpcomingExpirations) != 1 || len(out.RecentLicenses) != 1 || out.RecentLicenses[0].Status != "scheduled" || out.UpcomingExpirations[0].CustomerName != "Customer" { + t.Fatalf("records: %+v", out) + } + data, err := json.Marshal(out) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + json.Unmarshal(data, &fields) + for _, field := range []string{"active_licenses", "new_customers", "paid_revenue_cents", "currency", "expiring_licenses", "license_trend", "upcoming_expirations", "recent_licenses", "generated_at"} { + if _, ok := fields[field]; !ok { + t.Errorf("missing %s", field) + } + } + var generated string + json.Unmarshal(fields["generated_at"], &generated) + parsed, err := time.Parse(time.RFC3339, generated) + if err != nil || !parsed.Equal(now) { + t.Fatalf("generated_at %s", generated) + } + }) + } +} +func TestDashboardEmptyAndFailure(t *testing.T) { + now := time.Date(2026, 10, 8, 10, 0, 0, 0, time.UTC) + for _, mode := range []string{"empty", "aggregate error", "trend error", "list error", "row error", "scan error"} { + t.Run(mode, func(t *testing.T) { + qs := dashboardExpectations(now, 6) + switch mode { + case "empty": + for i := 0; i < 7; i++ { + for j := range qs[i].rows[0] { + qs[i].rows[0][j] = int64(0) + } + } + qs[7].rows = nil + qs[8].rows = nil + case "aggregate error": + qs = qs[:1] + qs[0].err = errors.New("private database detail") + case "trend error": + qs = qs[:2] + qs[1].err = errors.New("failure") + case "list error": + qs = qs[:8] + qs[7].err = errors.New("failure") + case "row error": + qs = qs[:8] + qs[7].rowErr = errors.New("failure") + case "scan error": + qs = qs[:8] + qs[7].rows[0][0] = "invalid id" + } + db, stub := newDashboardTestDB(t, qs) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", "/", nil) + out, err := (&BusinessAPI{db: db}).loadDashboardSummary(c, now, 6) + if mode == "empty" { + if err != nil || out.PaidRevenueCents != 0 || out.UpcomingExpirations == nil || out.RecentLicenses == nil || len(out.LicenseTrend) != 6 { + t.Fatalf("empty summary %+v %v", out, err) + } + } else if err == nil || !stub.rolledBack || stub.committed { + t.Fatalf("failure err=%v rollback=%v commit=%v", err, stub.rolledBack, stub.committed) + } + }) + } +} +func TestDashboardMonthsValidation(t *testing.T) { + for _, tc := range []struct { + query string + want int + ok bool + }{{"", 6, true}, {"?months=6", 6, true}, {"?months=12", 12, true}, {"?months=", 0, false}, {"?months=3", 0, false}, {"?months=abc", 0, false}, {"?months=06", 0, false}} { + t.Run(tc.query, func(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/"+tc.query, nil) + got, ok := dashboardMonths(c) + if got != tc.want || ok != tc.ok { + t.Fatalf("got %d/%v", got, ok) + } + if !ok && (w.Code != 400 || !strings.Contains(w.Body.String(), "invalid_request")) { + t.Fatal(w.Body.String()) + } + }) + } +} +func TestDashboardAndLicenseAdminRoutes(t *testing.T) { + // Authentication is exercised through real route registration. An unauthorized + // request must never reach summary/list SQL, even with invalid query parameters. + for _, path := range []string{"/api/v1/dashboard/summary?months=invalid", "/api/v1/licenses?status=invalid"} { + for _, mode := range []string{"missing", "malformed", "viewer", "expired", "admin"} { + t.Run(path+mode, func(t *testing.T) { + db, stub := newDashboardTestDB(t, nil) + r := gin.New() + RegisterBusiness(r, db) + req := httptest.NewRequest("GET", path, nil) + if mode == "malformed" { + req.AddCookie(&http.Cookie{Name: "lp_session", Value: strings.Repeat("z", 64)}) + } + if mode == "viewer" || mode == "expired" || mode == "admin" { + req.AddCookie(&http.Cookie{Name: "lp_session", Value: strings.Repeat("0", 64)}) + // The expiry cutoff is generated by authentication; capture and check it in + // a dedicated connector rather than relying on a wall-clock exact match. + db.Close() + auth := &dashboardAuthDB{t: t, mode: mode} + db = sql.OpenDB(auth) + defer db.Close() + r = gin.New() + RegisterBusiness(r, db) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + want := 401 + if mode == "viewer" { + want = 403 + } + if mode == "admin" { + want = 400 // Valid administrator reaches the handler's validation. + } + if w.Code != want { + t.Fatalf("got %d %s", w.Code, w.Body) + } + if stub.began { + t.Fatal("unauthorized aggregate") + } + }) + } + } +} + +// Authentication queries contain a live expiry cutoff, checked independently. +type dashboardAuthDB struct { + t *testing.T + mode string +} + +func (d *dashboardAuthDB) Connect(context.Context) (driver.Conn, error) { return d, nil } +func (d *dashboardAuthDB) Driver() driver.Driver { return dashboardAuthDriver{d} } + +type dashboardAuthDriver struct{ db *dashboardAuthDB } + +func (d dashboardAuthDriver) Open(string) (driver.Conn, error) { return d.db, nil } +func (*dashboardAuthDB) Close() error { return nil } +func (*dashboardAuthDB) Prepare(string) (driver.Stmt, error) { + return nil, errors.New("unexpected prepare") +} +func (*dashboardAuthDB) Begin() (driver.Tx, error) { return nil, errors.New("unexpected transaction") } +func (d *dashboardAuthDB) QueryContext(_ context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { + if !strings.Contains(q, "s.expires_at>?") || !strings.Contains(q, "a.active=1") || len(args) != 2 { + d.t.Errorf("unexpected auth SQL %s", q) + return nil, errors.New("unexpected auth SQL") + } + if cutoff, ok := args[1].Value.(time.Time); !ok || time.Since(cutoff) > time.Second { + d.t.Error("invalid session expiry cutoff") + } + if d.mode == "expired" { + return &dashboardRows{width: 4}, nil + } + role := "viewer" + if d.mode == "admin" { + role = "admin" + } + return &dashboardRows{width: 4, rows: [][]driver.Value{{int64(1), "admin-1", "admin@example.test", role}}}, nil +} + +func TestDashboardSummaryHTTPFailure(t *testing.T) { + db, _ := newDashboardTestDB(t, nil) + // A closed, network-free database exercises the handler's failure response. + db.Close() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/api/v1/dashboard/summary", nil) + (&BusinessAPI{db: db}).dashboardSummary(c) + if w.Code != 500 || !strings.Contains(w.Body.String(), `"code":"internal_error"`) || !strings.Contains(w.Body.String(), `"message":"Service unavailable"`) || strings.Contains(w.Body.String(), "database is closed") { + t.Fatalf("%d %s", w.Code, w.Body) + } +} diff --git a/backend/internal/httpapi/downloads.go b/backend/internal/httpapi/downloads.go new file mode 100644 index 0000000..232634d --- /dev/null +++ b/backend/internal/httpapi/downloads.go @@ -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) +} diff --git a/backend/internal/httpapi/downloads_integration_test.go b/backend/internal/httpapi/downloads_integration_test.go new file mode 100644 index 0000000..59d6fff --- /dev/null +++ b/backend/internal/httpapi/downloads_integration_test.go @@ -0,0 +1,270 @@ +package httpapi + +import ( + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + osexec "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func TestDownloadsMySQLIntegration(t *testing.T) { + dsn := os.Getenv("DOWNLOAD_TEST_DSN") + if dsn == "" { + t.Skip("DOWNLOAD_TEST_DSN must name an isolated migrated database") + } + db, err := sql.Open("mysql", dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + root := t.TempDir() + t.Setenv("PACKAGE_STORAGE_ROOT", root) + exec := func(q string, args ...any) int64 { + t.Helper() + r, e := db.Exec(q, args...) + if e != nil { + t.Fatal(e) + } + id, _ := r.LastInsertId() + return id + } + suffix := fmt.Sprint(time.Now().UnixNano()) + admin := exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@download.test", "unused") + raw := make([]byte, 32) + rand.Read(raw) + sessionHash := sha256.Sum256(raw) + exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", admin, sessionHash[:], time.Now().Add(time.Hour)) + cookie := &http.Cookie{Name: "lp_session", Value: hex.EncodeToString(raw)} + customer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'download@example.test')", suffix) + otherCustomer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'other@example.test')", suffix+"other") + product := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, suffix) + otherProduct := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", suffix) + license := exec("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", hex.EncodeToString(raw[:16]), customer, product, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix, admin) + secret := make([]byte, 32) + rand.Read(secret) + secretHash := sha256.Sum256(secret) + instanceID, _ := newInstanceID() + instanceRow := exec("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,status,created_by) VALUES(?,?,?,?,?,'activated',?)", instanceID, license, customer, product, secretHash[:], admin) + r := NewRouter() + RegisterBusiness(r, db) + req := func(path string, body io.Reader, auth bool) *httptest.ResponseRecorder { + q := httptest.NewRequest("POST", path, body) + if auth { + q.AddCookie(cookie) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + return w + } + publish := func(p int64, v, body string, auth bool) *httptest.ResponseRecorder { + return req(fmt.Sprintf("/api/v1/products/%d/releases?version=%s", p, v), strings.NewReader(body), auth) + } + releaseID := func(w *httptest.ResponseRecorder) int64 { + t.Helper() + if w.Code != 201 { + t.Fatalf("publish %d %s", w.Code, w.Body) + } + var out struct{ Data struct{ ID int64 } } + if e := json.Unmarshal(w.Body.Bytes(), &out); e != nil { + t.Fatal(e) + } + return out.Data.ID + } + if w := publish(product, "unauth", "body", false); w.Code != 401 { + t.Fatal(w.Code) + } + id := releaseID(publish(product, "v1", "package bytes", true)) + otherID := releaseID(publish(otherProduct, "v1", "other bytes", true)) + download := func(cust, id int64, sec string) *httptest.ResponseRecorder { + body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": sec}) + return req(fmt.Sprintf("/api/v1/customers/%d/releases/%d/download", cust, id), strings.NewReader(string(body)), false) + } + encoded := base64.RawURLEncoding.EncodeToString(secret) + auditCount := func(action string) int { + t.Helper() + var n int + if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action=? AND resource_type='license_instance' AND resource_id=?", action, instanceRow).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + check := func(cust, id int64, sec string, code int) { + t.Helper() + w := download(cust, id, sec) + if w.Code != code { + t.Fatalf("download %d want %d: %s", w.Code, code, w.Body) + } + if code != 200 && w.Header().Get("X-Accel-Redirect") != "" { + t.Fatal("denied request exposes file redirect") + } + } + check(customer, id, encoded, 200) + deniedBefore := auditCount("release.download_denied") + exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(-time.Minute), license) + check(customer, id, encoded, 403) + if auditCount("release.download_denied") != deniedBefore+1 { + t.Fatal("expired download was not audited") + } + exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(time.Hour), license) + unpublished := exec("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,published,created_by) VALUES(?,?,?,?,?,0,?)", product, "unpublished", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin", strings.Repeat("a", 64), 1, admin) + deniedBefore = auditCount("release.download_denied") + check(customer, unpublished, encoded, 403) + if auditCount("release.download_denied") != deniedBefore+1 { + t.Fatal("unpublished download was not audited") + } + deniedBefore = auditCount("release.download_denied") + check(customer, id+999999, encoded, 403) + if auditCount("release.download_denied") != deniedBefore+1 { + t.Fatal("missing release was not audited") + } + check(otherCustomer, id, encoded, 403) + check(customer, otherID, encoded, 403) + check(customer, id, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), 403) + for _, state := range []struct{ deny, restore string }{ + {"UPDATE license_instances SET freeze_state='frozen' WHERE license_id=?", "UPDATE license_instances SET freeze_state='none' WHERE license_id=?"}, + {"UPDATE licenses SET status='revoked' WHERE id=?", "UPDATE licenses SET status='active' WHERE id=?"}, + } { + exec(state.deny, license) + check(customer, id, encoded, 403) + exec(state.restore, license) + } + exec("UPDATE customers SET status='inactive' WHERE id=?", customer) + check(customer, id, encoded, 403) + exec("UPDATE customers SET status='active' WHERE id=?", customer) + exec("UPDATE products SET active=0 WHERE id=?", product) + check(customer, id, encoded, 403) + exec("UPDATE products SET active=1 WHERE id=?", product) + exec("CREATE TRIGGER download_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'") + t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS download_audit_failure") }) + check(customer, id, encoded, 500) + failedBody := "audit fails unique body" + digest := sha256.Sum256([]byte(failedBody)) + if w := publish(product, "audit-fails", failedBody, true); w.Code != 500 { + t.Fatalf("audit upload %d", w.Code) + } + var count int + db.QueryRow("SELECT COUNT(*) FROM product_releases WHERE version='audit-fails'").Scan(&count) + if count != 0 { + t.Fatal("failed release committed") + } + if _, e := os.Stat(filepath.Join(root, hex.EncodeToString(digest[:])+".bin")); !os.IsNotExist(e) { + t.Fatal("failed upload left new file") + } + exec("DROP TRIGGER download_audit_failure") + var wg sync.WaitGroup + codes := make(chan int, 2) + for i, p := range []int64{product, otherProduct} { + wg.Add(1) + go func(i int, p int64) { + defer wg.Done() + codes <- publish(p, fmt.Sprintf("concurrent-%d", i), "same digest bytes", true).Code + }(i, p) + } + wg.Wait() + close(codes) + for code := range codes { + if code != 201 { + t.Fatalf("concurrent digest %d", code) + } + } + digest = sha256.Sum256([]byte("same digest bytes")) + data, e := os.ReadFile(filepath.Join(root, hex.EncodeToString(digest[:])+".bin")) + if e != nil || string(data) != "same digest bytes" { + t.Fatal("shared digest damaged") + } + if w := publish(product, "v1", "conflicting version bytes", true); w.Code != 409 { + t.Fatal(w.Code) + } + if w := publish(product, "empty", "", true); w.Code != 400 { + t.Fatal(w.Code) + } + for _, n := range []int64{64 << 20, (64 << 20) + 1} { + w := req(fmt.Sprintf("/api/v1/products/%d/releases?version=limit-%d", product, n), io.LimitReader(zeroReader{}, n), true) + want := 201 + if n > 64<<20 { + want = 400 + } + if w.Code != want { + t.Fatalf("size %d code=%d want=%d %s", n, w.Code, want, w.Body) + } + } + files, _ := filepath.Glob(filepath.Join(root, ".upload-*")) + if len(files) != 0 { + t.Fatal("temporary uploads leaked") + } + if os.Getenv("DOWNLOAD_NGINX_E2E") == "1" { + server := &http.Server{Addr: "0.0.0.0:18082", Handler: r} + go server.ListenAndServe() + defer server.Close() + conf, _ := filepath.Abs("../../../deploy/nginx/download-local.conf") + cmd := osexec.Command("docker", "run", "-d", "--name", "license-download-e2e", "-p", "127.0.0.1:18181:18181", "--mount", "type=bind,source="+root+",target=/srv/license-packages,readonly", "--mount", "type=bind,source="+conf+",target=/etc/nginx/conf.d/default.conf,readonly", "nginx:stable-alpine") + if out, e := cmd.CombinedOutput(); e != nil { + t.Fatalf("nginx start: %v %s", e, out) + } + defer osexec.Command("docker", "stop", "license-download-e2e").Run() + defer osexec.Command("docker", "rm", "-f", "license-download-e2e").Run() + time.Sleep(2 * time.Second) + client := &http.Client{Timeout: 10 * time.Second} + body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": encoded}) + url := fmt.Sprintf("http://127.0.0.1:18181/api/v1/customers/%d/releases/%d/download", customer, id) + for _, partial := range []bool{false, true} { + q, _ := http.NewRequest("POST", url, strings.NewReader(string(body))) + q.Header.Set("Content-Type", "application/json") + if partial { + q.Header.Set("Range", "bytes=0-6") + } + resp, e := client.Do(q) + if e != nil { + t.Fatal(e) + } + b, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if partial { + if resp.StatusCode != 206 || string(b) != "package" { + t.Fatalf("range %d %q", resp.StatusCode, b) + } + } else { + sum := sha256.Sum256(b) + if resp.StatusCode != 200 || string(b) != "package bytes" || hex.EncodeToString(sum[:]) != resp.Header.Get("X-Package-SHA256") { + t.Fatalf("bytes/hash %d %q", resp.StatusCode, b) + } + } + } + direct := download(customer, id, encoded).Header().Get("X-Accel-Redirect") + resp, e := client.Get("http://127.0.0.1:18181" + direct) + if e != nil { + t.Fatal(e) + } + resp.Body.Close() + if resp.StatusCode != 404 && resp.StatusCode != 403 { + t.Fatalf("public internal path %d", resp.StatusCode) + } + resp, e = client.Post(url, "application/json", strings.NewReader("{}")) + if e != nil { + t.Fatal(e) + } + resp.Body.Close() + if resp.StatusCode < 400 { + t.Fatal("unauthenticated download succeeded") + } + t.Log("Nginx 18181: actual bytes/SHA256, Range 206, external internal-path denial and unauthenticated denial verified; temporary E2E service stopped") + } + t.Log("customer/product/state isolation, wrong secret, audit rollback, file cleanup, duplicate digest concurrency and exact 64MiB boundary verified") +} + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { clear(p); return len(p), nil } diff --git a/backend/internal/httpapi/downloads_test.go b/backend/internal/httpapi/downloads_test.go new file mode 100644 index 0000000..7dbe113 --- /dev/null +++ b/backend/internal/httpapi/downloads_test.go @@ -0,0 +1,34 @@ +package httpapi + +import ( + "os" + "path/filepath" + "testing" +) + +func TestLocalPackageRejectsTraversalAndSymlink(t *testing.T) { + root := t.TempDir() + good := filepath.Join(root, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin") + if err := os.WriteFile(good, []byte("ok"), 0600); err != nil { + t.Fatal(err) + } + if _, err := localPackage(root, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin"); err != nil { + t.Fatal(err) + } + for _, key := range []string{"../secret.bin", "short.bin", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.bin"} { + if _, err := localPackage(root, key); err == nil { + t.Fatalf("accepted unsafe key %q", key) + } + } + outside := filepath.Join(t.TempDir(), "outside.bin") + if err := os.WriteFile(outside, []byte("secret"), 0600); err != nil { + t.Fatal(err) + } + link := filepath.Join(root, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.bin") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("symlink unavailable: %v", err) + } + if _, err := localPackage(root, filepath.Base(link)); err == nil { + t.Fatal("accepted symlink package") + } +} diff --git a/backend/internal/httpapi/heartbeat.go b/backend/internal/httpapi/heartbeat.go new file mode 100644 index 0000000..36e3b1c --- /dev/null +++ b/backend/internal/httpapi/heartbeat.go @@ -0,0 +1,213 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +const maxOfflineLease = 14 * 24 * time.Hour +const heartbeatInterval = time.Minute +const clockTolerance = 5 * time.Minute + +type leasePayload struct { + Version string `json:"version"` + InstanceID string `json:"instance_id"` + State string `json:"state"` + ServerTime string `json:"server_time"` + EntitlementExpiresAt string `json:"entitlement_expires_at"` + LeaseExpiresAt string `json:"lease_expires_at"` +} + +func canonicalLease(p leasePayload) string { + return strings.Join([]string{"version=" + p.Version, "instance_id=" + p.InstanceID, "state=" + p.State, "server_time=" + p.ServerTime, "entitlement_expires_at=" + p.EntitlementExpiresAt, "lease_expires_at=" + p.LeaseExpiresAt}, "\n") +} + +func leaseState(instanceStatus, freeze, licenseStatus, customerStatus string, productActive bool, starts, expires, now time.Time) string { + if licenseStatus == "revoked" { + return "revoked" + } + if freeze == "frozen" || customerStatus != "active" || !productActive { + return "frozen" + } + if instanceStatus != "activated" { + return "not_activated" + } + return currentLicenseStatus(licenseStatus, starts, expires, now) +} + +func boundedLease(now, entitlement time.Time) time.Time { + end := now.Add(maxOfflineLease) + if entitlement.Before(end) { + end = entitlement + } + return end +} + +func (a *BusinessAPI) heartbeat(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096) + key, ok := parseOperationKey(c) + if !ok { + return + } + var in struct { + Secret string `json:"secret"` + ClientTime string `json:"client_time"` + } + if c.ShouldBindJSON(&in) != nil || 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 + } + clientTime, err := time.Parse(time.RFC3339Nano, in.ClientTime) + if err != nil { + apiError(c, 400, "invalid_request", "client_time 必须为 RFC3339") + return + } + clientTime = clientTime.UTC().Truncate(time.Microsecond) + hash := sha256.Sum256(raw) + fingerprint := sha256.Sum256([]byte(clientTime.Format(time.RFC3339Nano))) + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + fail := func() { apiError(c, 500, "internal_error", "心跳失败,请使用相同幂等键重试") } + var id, actor uint64 + var stored []byte + var instanceStatus, freeze, licenseStatus, customerStatus string + var productActive bool + var starts, expires time.Time + var last, previousClient sql.NullTime + err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.secret_hash,i.status,i.freeze_state,i.last_seen_at,i.client_seen_at,l.status,l.starts_at,l.expires_at,c.status,p.active FROM license_instances i JOIN licenses l ON l.id=i.license_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`, c.Param("instance_id")).Scan(&id, &actor, &stored, &instanceStatus, &freeze, &last, &previousClient, &licenseStatus, &starts, &expires, &customerStatus, &productActive) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 403, "forbidden", "实例凭据无效") + return + } + if err != nil { + fail() + return + } + if !bytesEqual(stored, hash[:]) { + apiError(c, 403, "forbidden", "实例凭据无效") + return + } + var now time.Time + if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil { + fail() + return + } + now = now.UTC() + if last.Valid && now.Before(last.Time.Add(-clockTolerance)) { + apiError(c, 409, "server_clock_rollback", "服务时钟回拨,暂停签发租约") + return + } + if last.Valid && now.Before(last.Time) { + now = last.Time.UTC() + } + state := leaseState(instanceStatus, freeze, licenseStatus, customerStatus, productActive, starts, expires, now) + var oldFingerprint, oldResponse []byte + var oldState string + err = tx.QueryRowContext(c, "SELECT request_fingerprint,response,state FROM heartbeat_operations WHERE instance_id=? AND idempotency_key=?", id, key).Scan(&oldFingerprint, &oldResponse, &oldState) + if err == nil { + if !bytesEqual(oldFingerprint, fingerprint[:]) { + apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同心跳") + return + } + if oldState != state { + apiError(c, 409, "state_changed", "实例状态已变化,请使用新幂等键心跳") + return + } + var replay any + if json.Unmarshal(oldResponse, &replay) != nil { + fail() + return + } + c.JSON(200, replay) + return + } + if !errors.Is(err, sql.ErrNoRows) { + fail() + return + } + if clientTime.Before(now.Add(-clockTolerance)) || clientTime.After(now.Add(clockTolerance)) || (previousClient.Valid && clientTime.Before(previousClient.Time.Add(-clockTolerance))) { + apiError(c, 409, "clock_skew", "客户端时钟偏差或回拨超过五分钟") + return + } + // State changes bypass the normal interval so revocation/freeze can propagate promptly. + var observed string + if err = tx.QueryRowContext(c, "SELECT observed_state FROM license_instances WHERE id=?", id).Scan(&observed); err != nil { + fail() + return + } + if last.Valid && now.Sub(last.Time) < heartbeatInterval && state == observed { + c.Header("Retry-After", "60") + apiError(c, 429, "rate_limited", "心跳间隔至少一分钟") + return + } + privateKey, err := readSigningKey(a.signingPrivateKeyPEM) + if err != nil { + apiError(c, 503, "signing_unavailable", "签名服务不可用") + return + } + leaseEnd := now + if state == "active" { + leaseEnd = boundedLease(now, expires) + } + payload := leasePayload{"lease-v1", c.Param("instance_id"), state, now.Format(time.RFC3339Nano), expires.UTC().Format(time.RFC3339Nano), leaseEnd.Format(time.RFC3339Nano)} + canonical := canonicalLease(payload) + var responsePayload any = payload + if a.keyring != nil { + payload.Version = "lease-v2" + canonical = canonicalLease(payload) + "\nkey_id=" + a.keyring.Current + responsePayload = gin.H{"version": payload.Version, "instance_id": payload.InstanceID, "state": payload.State, "server_time": payload.ServerTime, "entitlement_expires_at": payload.EntitlementExpiresAt, "lease_expires_at": payload.LeaseExpiresAt, "key_id": a.keyring.Current} + } + digest := sha256.Sum256([]byte(canonical)) + sig, err := ecdsa.SignASN1(rand.Reader, privateKey, digest[:]) + if err != nil { + fail() + return + } + response := gin.H{"data": gin.H{"payload": responsePayload, "signature": base64.RawStdEncoding.EncodeToString(sig), "canonical_sha256": hex.EncodeToString(digest[:]), "algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": 60}} + responseJSON, err := json.Marshal(response) + if err != nil { + fail() + return + } + if previousClient.Valid && clientTime.Before(previousClient.Time) { + clientTime = previousClient.Time.UTC() + } + if _, err = tx.ExecContext(c, "UPDATE license_instances SET last_seen_at=?,client_seen_at=?,lease_expires_at=?,observed_state=? WHERE id=?", now, clientTime, leaseEnd, state, id); err != nil { + fail() + return + } + if _, err = tx.ExecContext(c, "INSERT INTO heartbeat_operations(instance_id,idempotency_key,request_fingerprint,response,state) VALUES(?,?,?,?,?)", id, key, fingerprint[:], responseJSON, state); err != nil { + fail() + return + } + details, _ := json.Marshal(gin.H{"state": state, "previous_state": observed, "lease_expires_at": leaseEnd, "client_actor": "instance"}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.heartbeat','license_instance',?,?)", actor, id, details); err != nil { + fail() + return + } + if err = tx.Commit(); err != nil { + fail() + return + } + c.JSON(200, response) +} diff --git a/backend/internal/httpapi/heartbeat_integration_test.go b/backend/internal/httpapi/heartbeat_integration_test.go new file mode 100644 index 0000000..67781f4 --- /dev/null +++ b/backend/internal/httpapi/heartbeat_integration_test.go @@ -0,0 +1,140 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" +) + +func testHeartbeatMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Cookie, instanceID, secret string, licenseID uint64, publicKey *ecdsa.PublicKey) { + request := func(path, body, key string, auth bool) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", key) + if auth { + req.AddCookie(cookie) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + path := "/api/v1/instances/" + instanceID + "/heartbeat" + bodyFor := func(secret string, at time.Time) string { + b, _ := json.Marshal(gin.H{"secret": secret, "client_time": at.UTC().Format(time.RFC3339Nano)}) + return string(b) + } + now := time.Now().UTC() + body := bodyFor(secret, now) + if w := request(path, bodyFor(base64.RawURLEncoding.EncodeToString(make([]byte, 32)), now), "wrong", false); w.Code != 403 { + t.Fatalf("wrong secret status=%d", w.Code) + } + if _, err := db.Exec("CREATE TRIGGER heartbeat_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'"); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS heartbeat_audit_failure") }) + if w := request(path, body, "first", false); w.Code != 500 { + t.Fatalf("rollback status=%d", w.Code) + } + var last sql.NullTime + db.QueryRow("SELECT last_seen_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&last) + if last.Valid { + t.Fatal("audit failure committed last_seen") + } + db.Exec("DROP TRIGGER heartbeat_audit_failure") + var wg sync.WaitGroup + results := make(chan *httptest.ResponseRecorder, 2) + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { defer wg.Done(); results <- request(path, body, "first", false) }() + } + wg.Wait() + close(results) + var response struct { + Data struct { + Payload leasePayload `json:"payload"` + Signature string `json:"signature"` + } + } + for w := range results { + if w.Code != 200 { + t.Fatalf("concurrent status=%d", w.Code) + } + if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + } + digest := sha256.Sum256([]byte(canonicalLease(response.Data.Payload))) + sig, err := base64.RawStdEncoding.DecodeString(response.Data.Signature) + if err != nil || !ecdsa.VerifyASN1(publicKey, digest[:], sig) { + t.Fatal("lease signature invalid") + } + p := response.Data.Payload + server, _ := time.Parse(time.RFC3339Nano, p.ServerTime) + end, _ := time.Parse(time.RFC3339Nano, p.LeaseExpiresAt) + entitlement, _ := time.Parse(time.RFC3339Nano, p.EntitlementExpiresAt) + if p.State != "active" || end.After(server.Add(maxOfflineLease)) || end.After(entitlement) { + t.Fatal("lease bound invalid") + } + var count int + db.QueryRow("SELECT COUNT(*) FROM heartbeat_operations").Scan(&count) + if count != 1 { + t.Fatal("duplicate heartbeat operation") + } + if w := request(path, body, "new", false); w.Code != 429 { + t.Fatalf("limit status=%d", w.Code) + } + if w := request(path, bodyFor(secret, now.Add(time.Second)), "first", false); w.Code != 409 { + t.Fatalf("conflict=%d", w.Code) + } + if w := request(path, bodyFor(secret, now.Add(-time.Hour)), "clock", false); w.Code != 409 { + t.Fatalf("clock skew=%d", w.Code) + } + freezePath := "/api/v1/instances/" + instanceID + "/freeze" + if w := request(freezePath, `{"frozen":true}`, "freeze", false); w.Code != 401 { + t.Fatal("freeze unauthorized") + } + if w := request(freezePath, `{"frozen":true}`, "freeze", true); w.Code != 200 { + t.Fatalf("freeze=%d", w.Code) + } + if w := request(path, body, "first", false); w.Code != 409 { + t.Fatal("old allow replay masked freeze") + } + w := request(path, body, "frozen", false) + if w.Code != 200 { + t.Fatalf("frozen heartbeat=%d", w.Code) + } + json.Unmarshal(w.Body.Bytes(), &response) + if response.Data.Payload.State != "frozen" || response.Data.Payload.LeaseExpiresAt != response.Data.Payload.ServerTime { + t.Fatal("frozen lease allowed use") + } + if w = request(freezePath, `{"frozen":false}`, "unfreeze", true); w.Code != 200 { + t.Fatal("unfreeze failed") + } + w = request(path, body, "resume", false) + if w.Code != 200 { + t.Fatal("resume heartbeat failed") + } + revokePath := "/api/v1/licenses/" + strconv.FormatUint(licenseID, 10) + "/revoke" + if w = request(revokePath, `{}`, "heartbeat-revoke", true); w.Code != 200 { + t.Fatalf("revoke=%d", w.Code) + } + w = request(path, body, "revoked", false) + if w.Code != 200 { + t.Fatalf("revoked heartbeat=%d", w.Code) + } + json.Unmarshal(w.Body.Bytes(), &response) + if response.Data.Payload.State != "revoked" { + t.Fatal("revocation not propagated") + } +} diff --git a/backend/internal/httpapi/heartbeat_test.go b/backend/internal/httpapi/heartbeat_test.go new file mode 100644 index 0000000..83e78c4 --- /dev/null +++ b/backend/internal/httpapi/heartbeat_test.go @@ -0,0 +1,67 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/pem" + "testing" + "time" +) + +func TestLeaseBoundsAndCanonical(t *testing.T) { + now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC) + far := now.AddDate(10, 0, 0) + if got := boundedLease(now, far); !got.Equal(now.Add(14 * 24 * time.Hour)) { + t.Fatal("far-future entitlement gave permanent offline lease") + } + short := now.Add(time.Hour) + if !boundedLease(now, short).Equal(short) { + t.Fatal("lease exceeded entitlement") + } + p := leasePayload{"lease-v1", "00000000-0000-4000-8000-000000000001", "active", "2026-09-30T12:00:00Z", "2036-09-30T12:00:00Z", "2026-10-14T12:00:00Z"} + expected := "version=lease-v1\ninstance_id=00000000-0000-4000-8000-000000000001\nstate=active\nserver_time=2026-09-30T12:00:00Z\nentitlement_expires_at=2036-09-30T12:00:00Z\nlease_expires_at=2026-10-14T12:00:00Z" + if canonicalLease(p) != expected { + t.Fatal("canonical lease changed") + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + digest := sha256.Sum256([]byte(expected)) + signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:]) + if err != nil { + t.Fatal(err) + } + der, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + t.Fatal(err) + } + if !ecdsa.VerifyASN1(&key.PublicKey, digest[:], signature) { + t.Fatal("signature failed") + } + _ = der + block, _ := pem.Decode([]byte("-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz39VZCPp0fPgbDhKOM0jUHqzJAe3\n7GSZpcSe1TO9UGqv8BO3PBI8Th3Z9Fy5EdPaVggh8V/pjW/dcsUg9QbzWA==\n-----END PUBLIC KEY-----")) + pub, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + t.Fatal(err) + } + fixedSig, err := base64.RawStdEncoding.DecodeString("MEQCIFHuseC8F3iv6Jz9W3yywkacJ5qBOcDRJSNFLdFWS2w9AiBRZEmPGOzti3IJ0VOPccUOmmtVfWs6ZxtjcSDKJLH8BQ") + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(digest[:]) != "777150ed1107b51f17dd1ffaefac303310a32ec415e3d83a4b16cb05b9aac379" || !ecdsa.VerifyASN1(pub.(*ecdsa.PublicKey), digest[:], fixedSig) { + t.Fatal("published vector invalid") + } + changed := sha256.Sum256([]byte(expected + "\n")) + if ecdsa.VerifyASN1(pub.(*ecdsa.PublicKey), changed[:], fixedSig) { + t.Fatal("tampered vector accepted") + } + if leaseState("activated", "frozen", "revoked", "active", true, now.Add(-time.Hour), far, now) != "revoked" { + t.Fatal("revocation must dominate freeze") + } +} diff --git a/backend/internal/httpapi/instance_freeze.go b/backend/internal/httpapi/instance_freeze.go new file mode 100644 index 0000000..57d564b --- /dev/null +++ b/backend/internal/httpapi/instance_freeze.go @@ -0,0 +1,92 @@ +package httpapi + +import ( + "crypto/sha256" + "database/sql" + "encoding/json" + "errors" + + "github.com/gin-gonic/gin" +) + +func (a *BusinessAPI) freezeInstance(c *gin.Context) { + key, ok := parseOperationKey(c) + if !ok { + return + } + var in struct { + Frozen *bool `json:"frozen"` + } + if c.ShouldBindJSON(&in) != nil || in.Frozen == nil { + apiError(c, 400, "invalid_request", "必须指定 frozen") + return + } + state := "none" + if *in.Frozen { + state = "frozen" + } + fingerprint := sha256.Sum256([]byte(c.Param("instance_id") + "\x00" + state)) + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + fail := func() { apiError(c, 500, "internal_error", "冻结操作失败,请使用相同幂等键重试") } + actor := c.MustGet("admin_id") + var adminID uint64 + if err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? FOR UPDATE", actor).Scan(&adminID); err != nil { + fail() + return + } + var id uint64 + var previous string + err = tx.QueryRowContext(c, "SELECT id,freeze_state FROM license_instances WHERE instance_id=? FOR UPDATE", c.Param("instance_id")).Scan(&id, &previous) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "实例不存在") + return + } + if err != nil { + fail() + return + } + var oldFingerprint, oldResponse []byte + err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM instance_state_operations WHERE actor_admin_id=? AND idempotency_key=?", actor, key).Scan(&oldFingerprint, &oldResponse) + if err == nil { + if !bytesEqual(oldFingerprint, fingerprint[:]) { + apiError(c, 409, "idempotency_conflict", "幂等键请求不同") + return + } + var replay any + if json.Unmarshal(oldResponse, &replay) != nil { + fail() + return + } + c.JSON(200, replay) + return + } + if !errors.Is(err, sql.ErrNoRows) { + fail() + return + } + if _, err = tx.ExecContext(c, "UPDATE license_instances SET freeze_state=? WHERE id=?", state, id); err != nil { + fail() + return + } + response := gin.H{"data": gin.H{"instance_id": c.Param("instance_id"), "freeze_state": state}} + encoded, _ := json.Marshal(response) + if _, err = tx.ExecContext(c, "INSERT INTO instance_state_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?)", id, actor, key, fingerprint[:], encoded); err != nil { + fail() + return + } + details, _ := json.Marshal(gin.H{"previous_state": previous, "freeze_state": state}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.freeze_changed','license_instance',?,?)", actor, id, details); err != nil { + fail() + return + } + if err = tx.Commit(); err != nil { + fail() + return + } + c.JSON(200, response) +} diff --git a/backend/internal/httpapi/integration_archive.go b/backend/internal/httpapi/integration_archive.go new file mode 100644 index 0000000..65b383e --- /dev/null +++ b/backend/internal/httpapi/integration_archive.go @@ -0,0 +1,106 @@ +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 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),参照 client/verify.mjs;使用安全整数解析 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) + files := map[string][]byte{ + "README.md": []byte("# 客户端接入包\n\n阅读 protocol.md 与 openapi.json,将 prompt.md 提供给实现工程师。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"), + "prompt.md": []byte(kit.Prompt), + "test-vectors.json": vectors, + } + for _, name := range []string{"protocol.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", "openapi.json", "prompt.md", "test-vectors.json"} { + 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()) +} diff --git a/backend/internal/httpapi/integration_assets/openapi.json b/backend/internal/httpapi/integration_assets/openapi.json new file mode 100644 index 0000000..c89947e --- /dev/null +++ b/backend/internal/httpapi/integration_assets/openapi.json @@ -0,0 +1,43 @@ +{ + "openapi": "3.0.3", + "info": {"title": "License Platform Client API", "version": "1.0.0", "description": "Client-facing endpoints. Admin session is not a client credential. See protocol.md for canonical signature and trust-root rules."}, + "servers": [{"url": "https://license.example.com", "description": "Replace with deployed HTTPS origin"}], + "paths": { + "/api/v1/activation/instances/{instance_id}": {"post": { + "operationId": "activateInstance", "summary": "Activate pre-provisioned instance", + "parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}], + "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["license_key", "secret"], "properties": {"license_key": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}}, + "responses": {"200": {"description": "Activation certificate; verify data.certificate before accepting", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"instance_id": {"type": "string"}, "status": {"type": "string", "enum": ["activated"]}, "certificate": {"$ref": "#/components/schemas/Certificate"}}}, "idempotent_replay": {"type": "boolean"}}}}}}, "default": {"$ref": "#/components/responses/Error"}} + }}, + "/api/v1/instances/{instance_id}/heartbeat": {"post": { + "operationId": "heartbeat", "summary": "Refresh signed runtime lease", + "parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}], + "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["secret", "client_time"], "properties": {"secret": {"type": "string", "format": "password"}, "client_time": {"type": "string", "format": "date-time"}}}}}}, + "responses": {"200": {"description": "Signed lease; HTTP 200 does not imply active state", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Lease"}}}}}}, "429": {"description": "Rate limited; respect Retry-After", "headers": {"Retry-After": {"schema": {"type": "string"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "default": {"$ref": "#/components/responses/Error"}} + }}, + "/api/v1/customers/{customer_id}/releases/{id}/download": {"post": { + "operationId": "downloadRelease", "summary": "Download entitled release; repeat credentials for Range retries", + "parameters": [{"name": "customer_id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "Range", "in": "header", "schema": {"type": "string"}}], + "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["instance_id", "secret"], "properties": {"instance_id": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}}, + "responses": {"200": {"description": "Full file (through configured download gateway)", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "206": {"description": "Partial file", "headers": {"Content-Range": {"schema": {"type": "string"}}}, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "416": {"description": "Unsatisfiable Range"}, "default": {"$ref": "#/components/responses/Error"}} + }}, + "/api/v1/activation/keyring": {"get": { + "operationId": "discoverKeyring", "summary": "Discovery only, NOT a trust-root bootstrap", + "responses": {"200": {"description": "Configured verification keys", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"current_key_id": {"type": "string"}, "keys": {"type": "array", "items": {"type": "object", "properties": {"key_id": {"type": "string"}, "public_key_pem": {"type": "string"}, "revoked": {"type": "boolean"}}}}}}}}}}}, "default": {"$ref": "#/components/responses/Error"}} + }} + }, + "components": { + "parameters": { + "InstanceID": {"name": "instance_id", "in": "path", "required": true, "schema": {"type": "string"}}, + "IdempotencyKey": {"name": "Idempotency-Key", "in": "header", "required": true, "schema": {"type": "string"}, "description": "Same key and unchanged body for retries of one operation; new key for a new operation"} + }, + "responses": {"Error": {"description": "See error.code and HTTP status; never blindly retry conflicts", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}, + "schemas": { + "Error": {"type": "object", "properties": {"error": {"type": "object", "properties": {"code": {"type": "string"}, "message": {"type": "string"}}}}}, + "Certificate": {"type": "object", "required": ["version", "payload", "signature", "canonical_sha256"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "payload": {"$ref": "#/components/schemas/CertificatePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}}}, + "CertificatePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "license_id", "customer_id", "product_id", "starts_at", "expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "instance_id": {"type": "string"}, "license_id": {"type": "integer", "minimum": 1}, "customer_id": {"type": "integer", "minimum": 1}, "product_id": {"type": "integer", "minimum": 1}, "starts_at": {"type": "string", "format": "date-time"}, "expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}}, + "Lease": {"type": "object", "required": ["payload", "signature", "canonical_sha256", "algorithm", "next_heartbeat_seconds"], "properties": {"payload": {"$ref": "#/components/schemas/LeasePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}, "algorithm": {"type": "string", "enum": ["ECDSA-P256-SHA256"]}, "next_heartbeat_seconds": {"type": "integer", "minimum": 60}}}, + "LeasePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "state", "server_time", "entitlement_expires_at", "lease_expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["lease-v2"]}, "instance_id": {"type": "string"}, "state": {"type": "string", "enum": ["active", "frozen", "revoked", "expired", "not_started", "not_activated"]}, "server_time": {"type": "string", "format": "date-time"}, "entitlement_expires_at": {"type": "string", "format": "date-time"}, "lease_expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}} + } + } +} diff --git a/backend/internal/httpapi/integration_assets/protocol.md b/backend/internal/httpapi/integration_assets/protocol.md new file mode 100644 index 0000000..371f0de --- /dev/null +++ b/backend/internal/httpapi/integration_assets/protocol.md @@ -0,0 +1,75 @@ +# 客户端接入协议 1.0 + +本资料对应当前平台实现,不是独立完成生产验收的 SDK。运行 API 基地址由部署方提供,例如 https://license.example.com。必须使用 HTTPS,并验证服务端证书。管理员接口仅用于交付实例凭据,不应封装到客户端中。 + +## 交付与激活 + +管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和一次性 secret。secret 无法从后台恢复;不得跨安装复制共享凭据。 + +POST /api/v1/activation/instances/{instance_id} + +头部:Content-Type: application/json,Idempotency-Key: 唯一业务操作标识。 + +请求:{"license_key":"部署方交付值","secret":"部署方交付值"} + +成功 200:{"data":{"instance_id":"...","status":"activated","certificate":{"version":"license-v2","payload":{},"signature":"...","canonical_sha256":"..."}},"idempotent_replay":false} + +同一次激活的网络重试复用请求内容和 Idempotency-Key。只持久化验签且绑定预期实例、产品、客户及有效期的证书。激活证书不等于运行租约,激活后仍需心跳。 + +## 心跳与运行租约 + +POST /api/v1/instances/{instance_id}/heartbeat + +请求:{"secret":"部署方交付值","client_time":"2026-10-09T03:00:00Z"},要求 Idempotency-Key。 + +成功 200:{"data":{"payload":{"version":"lease-v2","instance_id":"...","state":"active","server_time":"...","entitlement_expires_at":"...","lease_expires_at":"...","key_id":"..."},"signature":"...","canonical_sha256":"...","algorithm":"ECDSA-P256-SHA256","next_heartbeat_seconds":60}} + +服务端允许的租约状态:active、frozen、revoked、expired、not_started、not_activated。非 active 的已签名租约必须关闭业务运行;HTTP 200 本身不代表授权有效。 + +新心跳操作生成新键。网络重试复用原键及原 client_time,不得修改请求时间后继续使用原键。成功 active 心跳最短间隔 60 秒;根据 next_heartbeat_seconds 调度并加少量正向抖动。 + +## 验签规范 + +算法 ECDSA P-256 + SHA-256。公钥为 PEM SubjectPublicKeyInfo。signature 是 ASN.1 DER 的 ECDSA 签名,再进行标准 Base64 编码,不带 = 填充,不是 Base64URL,也不是固定 64 字节 r||s。 + +拒绝未知版本、缺少或额外字段、非法类型、包含 CR/LF/NUL 的字段、未知或撤销的 key_id、公钥不是 P-256,以及绑定到其他实例的信封。 + +按以下固定顺序输出 key=value,用单个 LF 连接,无末尾 LF,以 UTF-8 编码。时间使用收到的原始签名字符串,不能在验签前格式化或重新序列化。 + +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。 + +ID 使用正十进制整数。Node.js 实现限制为安全整数。若部署数据超出安全整数范围,必须先约定解析方案。 + +canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校验,不能代替公钥验签。激活应验证 data.certificate,心跳应验证 data。 + +服务端未配置 keyring 时会生成 legacy v1;本接入方案拒绝 v1。部署前由运维确认 keyring 已配置并交付可信公钥与 key_id。GET /api/v1/activation/keyring、/activation/public-key 只是发现接口,不能自建信任根。 + +## 时间与状态存储 + +参照 client/verify.mjs:now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。 + +验签、范围检查后,先在受保护存储中原子保存实例 ID、租约、enabled、服务端与本地时间高水位,再启用业务。离线每次授权检查都应检查本地时间回拨,并持久化更新本地高水位。应用重新启动不得清除高水位绕过限制。 + +离线冻结和撤销不能立即让旧租约失效,最长残留授权可达 14 天。网络失败不得延长已接受的租约;有有效租约可在策略允许范围内继续,无有效租约必须 fail closed。一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,不能宣称硬件绑定或防克隆。 + +## 重试与错误 + +错误结构为 {"error":{"code":"...","message":"..."}}。根据状态、code 和操作区分错误,不记录 secret 或原始请求正文。 + +400 修复参数;401/403 需要重新交付凭据或人工检查,不做无限重试;409 是冲突,需要检查 code 和实例状态,不自动重激活。429 在至少等待 Retry-After 后有界重试;无该头时指数退避。超时、连接错误和 5xx 有界退避,同一操作维持相同请求与键。心跳拒绝不能替代已签名撤销事件;在未收到可验证的非 active 租约时,已有租约的处理由离线策略决定,不得延长。 + +## 发布包下载 + +POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。支持 Range 续传,处理 200/206/416 和 Content-Range。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。 + +## 模式约束 + +桌面:系统密钥库与单实例状态锁。服务:受限服务账户、超时、取消和受控后台任务。容器:稳定持久卷及 Secret 注入;重建不能生成新身份,多个副本不得共享同一实例凭据冒充独立席位。Kubernetes 集群授权需要额外的 License Agent 和席位策略,不在当前 SDK 范围内。 + +SPA 应通过同源 BFF 调用,不得在浏览器长期保存实例 secret。移动端、CI 短命实例和完全离线设备需要专门身份与交付策略,不能直接承诺当前协议覆盖。 + +## 交付验收 + +覆盖正常验签、篡改字段/签名、未知/撤销密钥、v1/额外字段、实例不匹配、过期和超过 14 天、时钟回拨、非 active、幂等重试、429、掉线与原子存储失败。测试向量只使用随机测试密钥,绝不能导入生产信任配置。 diff --git a/backend/internal/httpapi/integration_kit.go b/backend/internal/httpapi/integration_kit.go new file mode 100644 index 0000000..12c66cb --- /dev/null +++ b/backend/internal/httpapi/integration_kit.go @@ -0,0 +1,154 @@ +package httpapi + +import ( + "embed" + "fmt" + "net/http" + "strings" + + "github.com/gin-gonic/gin" +) + +//go:embed integration_assets/* +var integrationAssets embed.FS + +const defaultIntegrationBaseURL = "https://license.yihuiyong.cn" + +var integrationLanguages = map[string]string{ + "python": "Python 3.11+", + "go": "Go 1.22+", + "java": "Java 17+", + "dotnet": ".NET 8+", + "nodejs": "Node.js 20+", +} + +var integrationModes = map[string]string{ + "desktop": "桌面客户端", + "service": "常驻服务", + "container": "容器部署", +} + +type integrationKitResponse struct { + ProtocolVersion string `json:"protocol_version"` + PlatformBaseURL string `json:"platform_base_url"` + Language string `json:"language"` + LanguageLabel string `json:"language_label"` + Mode string `json:"mode"` + ModeLabel string `json:"mode_label"` + Endpoints []kitAPI `json:"endpoints"` + SecurityRules []string `json:"security_rules"` + Prompt string `json:"prompt"` + TestVector kitVector `json:"payload_example"` + Protocol string `json:"protocol"` +} + +type kitAPI struct { + Method string `json:"method"` + Path string `json:"path"` + Purpose string `json:"purpose"` +} + +type kitVector struct { + Version string `json:"version"` + InstanceID string `json:"instance_id"` + State string `json:"state"` + ServerTime string `json:"server_time"` + EntitlementExpiresAt string `json:"entitlement_expires_at"` + LeaseExpiresAt string `json:"lease_expires_at"` +} + +func integrationKitInput(c *gin.Context) (string, string, bool) { + language, mode := c.DefaultQuery("language", "python"), c.DefaultQuery("mode", "service") + if _, ok := integrationLanguages[language]; !ok { + apiError(c, http.StatusBadRequest, "invalid_request", "不支持的客户端语言") + return "", "", false + } + if _, ok := integrationModes[mode]; !ok { + apiError(c, http.StatusBadRequest, "invalid_request", "不支持的接入模式") + return "", "", false + } + return language, mode, true +} + +func buildIntegrationKit(language, mode string) integrationKitResponse { + label, modeLabel := integrationLanguages[language], integrationModes[mode] + protocol, _ := integrationAsset("protocol.md") + return integrationKitResponse{ + ProtocolVersion: "license-v2 / lease-v2", + PlatformBaseURL: defaultIntegrationBaseURL, + Language: language, + LanguageLabel: label, + Mode: mode, + ModeLabel: modeLabel, + Endpoints: []kitAPI{ + {Method: "POST", Path: "/api/v1/activation/instances/{instance_id}", Purpose: "首次激活,提交 license_key、secret 和 Idempotency-Key"}, + {Method: "POST", Path: "/api/v1/instances/{instance_id}/heartbeat", Purpose: "刷新已签名运行租约,提交 secret、client_time 和 Idempotency-Key"}, + {Method: "POST", Path: "/api/v1/customers/{customer_id}/releases/{release_id}/download", Purpose: "以实例凭据下载当前有权访问的发布包"}, + }, + SecurityRules: []string{ + "仅信任随软件或受控部署渠道固定分发的 P-256 公钥;不得将 keyring 发现接口作为信任根。", + "secret 只可放在系统密钥库、Vault、Docker/Kubernetes Secret 或受限加密文件中;不得进入 URL、日志、镜像、源码或浏览器 LocalStorage。", + "每次网络重试复用同一 Idempotency-Key;新的业务操作必须生成新的键。", + "验签后核对 version、key_id、instance_id、state、授权到期和租约到期;仅 active 且未到期时可执行业务。", + "保存服务端时间与本地时间高水位,拒绝显著回拨;正常心跳最短 60 秒,租约最长 14 天。", + "403/409 进入不可用或人工处理状态;429 遵循 Retry-After;不得无限自动重试。", + }, + Protocol: string(protocol), + Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md 与 openapi.json。签名规范化不是 JSON:固定顺序 key=value、LF 连接、UTF-8、无末尾换行;签名是 DER ECDSA 的无填充标准 Base64。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。", + 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", + }, + } +} + +func integrationAsset(name string) ([]byte, error) { + content, err := integrationAssets.ReadFile("integration_assets/" + name) + if err != nil { + return nil, err + } + return []byte(strings.ReplaceAll(string(content), "https://license.example.com", defaultIntegrationBaseURL)), nil +} + +func integrationPrompt(language, mode string) string { + return fmt.Sprintf(`你正在为 %s %s 接入授权平台。实现可复用的 LicenseClient,不要调用管理员接口,也不要把实例 secret 暴露给浏览器。 + +默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。 + +实现激活 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。 + +必须使用受控渠道预置的 ECDSA P-256 公钥验证 license-v2 / lease-v2 信封,验证 key_id、version、instance_id、state、entitlement_expires_at、lease_expires_at。仅 active 且授权/租约均未过期时允许业务运行。持久化并原子更新已接受租约及本地、服务端时间高水位。secret 不得写入 URL、日志、异常、镜像或源码;403/409 停止自动重试,429 遵循 Retry-After。 + +请交付:LicenseClient、受保护状态存储接口、激活与刷新租约实现、验签单元测试、网络/时钟回拨/过期租约负向测试,以及业务侧 canRun 调用示例。`, language, mode, defaultIntegrationBaseURL) +} + +func (a *BusinessAPI) integrationKit(c *gin.Context) { + language, mode, ok := integrationKitInput(c) + if !ok { + return + } + c.JSON(http.StatusOK, gin.H{"data": buildIntegrationKit(language, mode)}) +} + +func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) { + language, mode, ok := integrationKitInput(c) + if !ok { + return + } + kit := buildIntegrationKit(language, mode) + var b strings.Builder + fmt.Fprintf(&b, "# 授权平台客户端接入包\n\n协议版本:%s\n\n默认授权平台根地址:%s\n\n", kit.ProtocolVersion, kit.PlatformBaseURL) + fmt.Fprintf(&b, "目标:%s,%s\n\n## 工程提示词\n\n%s\n\n## 接口\n\n", kit.LanguageLabel, kit.ModeLabel, kit.Prompt) + for _, endpoint := range kit.Endpoints { + fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose) + } + b.WriteString("\n## 安全检查\n\n") + for _, rule := range kit.SecurityRules { + 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", kit.Protocol) + 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 new file mode 100644 index 0000000..ccec955 --- /dev/null +++ b/backend/internal/httpapi/integration_kit_test.go @@ -0,0 +1,119 @@ +package httpapi + +import ( + "archive/zip" + "bytes" + "crypto/ecdsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "io" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestIntegrationAuthentication(t *testing.T) { + r := gin.New() + registerBusinessRoutes(r, &BusinessAPI{}) + for _, path := range []string{"/api/v1/integration-kit", "/api/v1/integration-kit/download", "/api/v1/integration-kit/archive"} { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Code != 401 { + t.Fatalf("%s: %d", path, w.Code) + } + } +} +func TestIntegrationInputs(t *testing.T) { + for _, query := range []string{"?language=rust", "?mode=browser", "?language=../../secret"} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/"+query, nil) + (&BusinessAPI{}).integrationKit(c) + if w.Code != 400 { + t.Fatalf("%s: %d", query, w.Code) + } + } + for language := range integrationLanguages { + kit := buildIntegrationKit(language, "service") + if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") { + t.Fatal("incomplete kit") + } + } + content, err := integrationAssets.ReadFile("integration_assets/openapi.json") + if err != nil { + t.Fatal(err) + } + var spec map[string]any + if err = json.Unmarshal(content, &spec); err != nil { + t.Fatal(err) + } + if spec["openapi"] != "3.0.3" { + t.Fatal("invalid OpenAPI") + } +} +func TestIntegrationArchiveAndSignatures(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil) + (&BusinessAPI{}).downloadIntegrationArchive(c) + if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" { + t.Fatalf("%d %s", w.Code, w.Body) + } + archive, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len())) + if err != nil { + t.Fatal(err) + } + if len(archive.File) != 5 { + t.Fatal("missing files") + } + for _, file := range archive.File { + reader, err := file.Open() + if err != nil { + t.Fatal(err) + } + content, err := io.ReadAll(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) { + t.Fatal("OpenAPI does not use the default platform address") + } + if file.Name != "test-vectors.json" { + continue + } + var vectors struct { + PinnedKeys []struct { + PublicKey string `json:"public_key_pem"` + } `json:"pinned_keys"` + License, Lease struct{ Signature, Canonical string } + } + if err := json.Unmarshal(content, &vectors); err != nil { + t.Fatal(err) + } + block, _ := pem.Decode([]byte(vectors.PinnedKeys[0].PublicKey)) + key, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + t.Fatal(err) + } + for _, vector := range []struct{ Signature, Canonical string }{vectors.License, vectors.Lease} { + sig, err := base64.RawStdEncoding.DecodeString(vector.Signature) + if err != nil { + t.Fatal(err) + } + digest := sha256.Sum256([]byte(vector.Canonical)) + if !ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), digest[:], sig) { + t.Fatal("bad signature") + } + digest = sha256.Sum256([]byte(vector.Canonical + "tampered")) + if ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), digest[:], sig) { + t.Fatal("accepted tampering") + } + } + } +} diff --git a/backend/internal/httpapi/keyring.go b/backend/internal/httpapi/keyring.go new file mode 100644 index 0000000..5dccc72 --- /dev/null +++ b/backend/internal/httpapi/keyring.go @@ -0,0 +1,91 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "os" + "path/filepath" + "regexp" + "sort" +) + +type VerificationKey struct { + KeyID string `json:"key_id"` + PublicKeyPEM string `json:"public_key_pem"` + Revoked bool `json:"revoked"` +} +type Keyring struct { + Current string `json:"current_key_id"` + Keys []VerificationKey `json:"keys"` +} + +var keyIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`) + +func LoadKeyring(path, privatePEM string) (*Keyring, error) { + if path == "" { + return nil, nil + } + if !filepath.IsAbs(path) { + return nil, errors.New("keyring file must be absolute") + } + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() > 65536 { + return nil, errors.New("invalid keyring file") + } + data, err := os.ReadFile(path) + if err != nil { + return nil, errors.New("keyring unavailable") + } + var ring Keyring + if json.Unmarshal(data, &ring) != nil { + return nil, errors.New("invalid keyring JSON") + } + if err := ring.Validate(privatePEM); err != nil { + return nil, err + } + return &ring, nil +} +func (r *Keyring) Validate(privatePEM string) error { + if !keyIDPattern.MatchString(r.Current) || len(r.Keys) == 0 || len(r.Keys) > 32 { + return errors.New("invalid keyring") + } + private, err := readSigningKey(privatePEM) + if err != nil { + return errors.New("invalid current private key") + } + seen := map[string]bool{} + current := false + for _, k := range r.Keys { + if !keyIDPattern.MatchString(k.KeyID) || seen[k.KeyID] { + return errors.New("duplicate or invalid key ID") + } + seen[k.KeyID] = true + block, rest := pem.Decode([]byte(k.PublicKeyPEM)) + if block == nil || len(rest) != 0 { + return errors.New("invalid public key") + } + parsed, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return errors.New("invalid public key") + } + pub, ok := parsed.(*ecdsa.PublicKey) + if !ok || pub.Curve != elliptic.P256() { + return errors.New("public key must be P256") + } + if k.KeyID == r.Current { + if k.Revoked || !pub.Equal(&private.PublicKey) { + return errors.New("current key revoked or mismatched") + } + current = true + } + } + if !current { + return errors.New("current key missing") + } + sort.Slice(r.Keys, func(i, j int) bool { return r.Keys[i].KeyID < r.Keys[j].KeyID }) + return nil +} diff --git a/backend/internal/httpapi/keyring_http_test.go b/backend/internal/httpapi/keyring_http_test.go new file mode 100644 index 0000000..ffc7f6a --- /dev/null +++ b/backend/internal/httpapi/keyring_http_test.go @@ -0,0 +1,36 @@ +package httpapi + +import ( + "database/sql" + "io" + "log/slog" + "net/http/httptest" + "strings" + "testing" +) + +func TestKeyringHTTPAndFileBoundary(t *testing.T) { + if _, err := LoadKeyring("relative.json", ""); err == nil { + t.Fatal("relative ring accepted") + } + for _, enabled := range []bool{false, true} { + router := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil)))) + var ring *Keyring + if enabled { + ring = &Keyring{Current: "test", Keys: []VerificationKey{{KeyID: "test", PublicKeyPEM: "public-only", Revoked: false}}} + } + RegisterBusinessWithKeyring(router, &sql.DB{}, "", ring) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest("GET", "/api/v1/activation/keyring", nil)) + expected := 404 + if enabled { + expected = 200 + } + if response.Code != expected { + t.Fatal(response.Code) + } + if strings.Contains(response.Body.String(), "PRIVATE KEY") { + t.Fatal("private key disclosure") + } + } +} diff --git a/backend/internal/httpapi/keyring_test.go b/backend/internal/httpapi/keyring_test.go new file mode 100644 index 0000000..b981246 --- /dev/null +++ b/backend/internal/httpapi/keyring_test.go @@ -0,0 +1,87 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestKeyringCrossLanguageRotation(t *testing.T) { + old, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + current, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + public := func(k *ecdsa.PrivateKey) string { + der, _ := x509.MarshalPKIXPublicKey(&k.PublicKey) + return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})) + } + der, _ := x509.MarshalECPrivateKey(current) + private := string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})) + ring := Keyring{Current: "new", Keys: []VerificationKey{{KeyID: "old", PublicKeyPEM: public(old)}, {KeyID: "new", PublicKeyPEM: public(current)}}} + if err := ring.Validate(private); err != nil { + t.Fatal(err) + } + bad := ring + bad.Keys = append([]VerificationKey(nil), ring.Keys...) + for i := range bad.Keys { + if bad.Keys[i].KeyID == "new" { + bad.Keys[i].Revoked = true + } + } + if bad.Validate(private) == nil { + t.Fatal("revoked current accepted") + } + if ring.Validate(string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: func() []byte { d, _ := x509.MarshalECPrivateKey(old); return d }()}))) == nil { + t.Fatal("mismatch accepted") + } + now := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + id := "00000000-0000-4000-8000-000000000001" + sign := func(k *ecdsa.PrivateKey, keyID, kind string) map[string]any { + var p map[string]any + var text string + if kind == "license" { + p = map[string]any{"version": "license-v2", "instance_id": id, "license_id": 1, "customer_id": 2, "product_id": 3, "starts_at": now.Format(time.RFC3339), "expires_at": now.Add(time.Hour).Format(time.RFC3339), "key_id": keyID} + text = canonicalCertificatePayload("license-v2", id, 1, 2, 3, now, now.Add(time.Hour)) + "\nkey_id=" + keyID + } else { + lease := leasePayload{"lease-v2", id, "active", now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)} + p = map[string]any{"version": lease.Version, "instance_id": lease.InstanceID, "state": lease.State, "server_time": lease.ServerTime, "entitlement_expires_at": lease.EntitlementExpiresAt, "lease_expires_at": lease.LeaseExpiresAt, "key_id": keyID} + text = canonicalLease(lease) + "\nkey_id=" + keyID + } + hash := sha256.Sum256([]byte(text)) + sig, _ := ecdsa.SignASN1(rand.Reader, k, hash[:]) + return map[string]any{"payload": p, "signature": base64.RawStdEncoding.EncodeToString(sig)} + } + vectors := map[string]any{"keys": ring.Keys, "old": sign(old, "old", "license"), "current": sign(current, "new", "license"), "lease": sign(current, "new", "lease"), "now": now.UnixMilli(), "instance": id} + data, _ := json.Marshal(vectors) + path := filepath.Join(t.TempDir(), "vectors.json") + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + // Only public keys/signatures leave Go; private keys stay in test process memory. + script := `import fs from 'node:fs'; import assert from 'node:assert/strict'; import {verifyEnvelope,acceptLease,canRunOffline} from '../../../client/verify.mjs'; + const v=JSON.parse(fs.readFileSync(process.argv[1])); + assert.equal(verifyEnvelope(v.old,v.keys).key_id,'old');assert.equal(verifyEnvelope(v.current,v.keys).key_id,'new'); + assert.throws(()=>verifyEnvelope(v.old,v.keys.map(k=>({...k,revoked:k.key_id==='old'}))),/revoked/); + assert.throws(()=>verifyEnvelope(v.current,[]),/unknown/); + assert.throws(()=>verifyEnvelope({...v.current,payload:{...v.current.payload,key_id:'old'}},v.keys),/signature/); + assert.throws(()=>verifyEnvelope({...v.current,payload:{...v.current.payload,product_id:99}},v.keys),/signature/); + const state=acceptLease(v.lease,v.keys,v.instance,null,v.now);assert.ok(state.enabled);assert.ok(canRunOffline(state,v.instance,v.now+1));assert.ok(!canRunOffline(state,v.instance,v.now-1));assert.ok(!canRunOffline(state,v.instance,state.lease_expires)); + assert.throws(()=>acceptLease(v.lease,v.keys,'other',null,v.now),/instance/); + assert.throws(()=>acceptLease(v.lease,v.keys,v.instance,{...state,server_high_water:v.now+1},v.now),/rollback/); + assert.throws(()=>acceptLease(v.lease,v.keys,v.instance,state,v.now-1),/rollback/); + console.log('Go -> Node: old/current signatures, revoked/unknown/tampered rejection, lease high-water passed');` + cmd := exec.Command("node", "--input-type=module", "-e", script, path) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("Node vectors failed: %s", out) + } + t.Log(string(out)) +} diff --git a/backend/internal/httpapi/licenses.go b/backend/internal/httpapi/licenses.go new file mode 100644 index 0000000..15a17f1 --- /dev/null +++ b/backend/internal/httpapi/licenses.go @@ -0,0 +1,384 @@ +package httpapi + +import ( + "bytes" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +type licenseOperation struct { + ID uint64 `json:"id"` + LicenseID uint64 `json:"license_id"` + Operation string `json:"operation"` + IdempotencyKey string `json:"-"` + RequestFingerprint []byte `json:"-"` +} + +type licenseRecord struct { + ID uint64 `json:"id"` + LicenseKey string `json:"license_key"` + CustomerID uint64 `json:"customer_id"` + CustomerName string `json:"customer_name"` + ProductID uint64 `json:"product_id"` + ProductName string `json:"product_name"` + ProductCode string `json:"product_code"` + Status string `json:"status"` + StartsAt time.Time `json:"starts_at"` + ExpiresAt time.Time `json:"expires_at"` + CreatedAt time.Time `json:"created_at"` +} + +func currentLicenseStatus(status string, starts, expires time.Time, now time.Time) string { + if status == "revoked" { + return status + } + if !now.Before(expires) { + return "expired" + } + if now.Before(starts) { + return "scheduled" + } + return "active" +} + +func (a *BusinessAPI) issueLicense(c *gin.Context) { + key := strings.TrimSpace(c.GetHeader("Idempotency-Key")) + if len(key) == 0 || len(key) > 128 { + apiError(c, 400, "invalid_idempotency_key", "Idempotency-Key 必须为 1 至 128 个字符") + return + } + var in struct { + CustomerID uint64 `json:"customer_id"` + ProductID uint64 `json:"product_id"` + StartsAt string `json:"starts_at"` + ExpiresAt string `json:"expires_at"` + } + if c.ShouldBindJSON(&in) != nil || in.CustomerID == 0 || in.ProductID == 0 { + apiError(c, 400, "invalid_request", "客户、产品和期限必填") + return + } + starts, err := time.Parse(time.RFC3339, in.StartsAt) + if err != nil { + apiError(c, 400, "invalid_request", "starts_at 必须为 RFC3339 时间") + return + } + expires, err := time.Parse(time.RFC3339, in.ExpiresAt) + starts = starts.UTC().Truncate(time.Microsecond) + expires = expires.UTC().Truncate(time.Microsecond) + if err != nil || !expires.After(starts) || starts.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) { + apiError(c, 400, "invalid_request", "expires_at 必须为晚于开始时间的 RFC3339 时间") + return + } + adminID, ok := c.Get("admin_id") + if !ok { + apiError(c, 401, "unauthorized", "请先登录") + return + } + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + // Serialize issuance per administrator so concurrent retries see the committed record. + var lockedAdmin uint64 + if err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", adminID).Scan(&lockedAdmin); err != nil { + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 403, "forbidden", "无权签发授权") + } else { + apiError(c, 500, "internal_error", "服务暂时不可用") + } + return + } + var rec licenseRecord + err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.issued_by=? AND l.idempotency_key=?`, adminID, key).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt) + if err == nil { + if rec.CustomerID != in.CustomerID || rec.ProductID != in.ProductID || !rec.StartsAt.Equal(starts) || !rec.ExpiresAt.Equal(expires) { + apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同授权请求") + return + } + rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC()) + c.JSON(200, gin.H{"data": rec, "idempotent_replay": true}) + return + } + if !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + var customerStatus string + var productActive bool + err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", in.CustomerID).Scan(&rec.CustomerName, &customerStatus) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if errors.Is(err, sql.ErrNoRows) || customerStatus != "active" { + apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用") + return + } + err = tx.QueryRowContext(c, "SELECT name,code,active FROM products WHERE id=? FOR UPDATE", in.ProductID).Scan(&rec.ProductName, &rec.ProductCode, &productActive) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if errors.Is(err, sql.ErrNoRows) || !productActive { + apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用") + return + } + raw := make([]byte, 16) + if _, err = rand.Read(raw); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + rec.LicenseKey = hex.EncodeToString(raw) + rec.CustomerID = in.CustomerID + rec.ProductID = in.ProductID + rec.StartsAt = starts.UTC() + rec.ExpiresAt = expires.UTC() + rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC()) + res, err := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", rec.LicenseKey, in.CustomerID, in.ProductID, rec.StartsAt, rec.ExpiresAt, key, adminID) + if err != nil { + apiError(c, 500, "internal_error", "签发失败,请使用相同幂等键重试") + return + } + id, err := res.LastInsertId() + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + rec.ID = uint64(id) + if err = tx.QueryRowContext(c, "SELECT created_at FROM licenses WHERE id=?", rec.ID).Scan(&rec.CreatedAt); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + details, _ := json.Marshal(map[string]any{"customer_id": in.CustomerID, "product_id": in.ProductID, "starts_at": rec.StartsAt, "expires_at": rec.ExpiresAt}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", adminID, rec.ID, details); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.Header("Location", "/api/v1/licenses/"+strconv.FormatUint(rec.ID, 10)) + c.JSON(201, gin.H{"data": rec, "idempotent_replay": false}) +} + +func (a *BusinessAPI) getLicense(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 rec licenseRecord + err = a.db.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=?`, id).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "授权不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC()) + c.JSON(200, gin.H{"data": rec}) +} + +func parseOperationKey(c *gin.Context) (string, bool) { + key := strings.TrimSpace(c.GetHeader("Idempotency-Key")) + if len(key) < 1 || len(key) > 128 { + apiError(c, 400, "invalid_idempotency_key", "Idempotency-Key 必须为 1 至 128 个字符") + return "", false + } + return key, true +} + +func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + apiError(c, 400, "invalid_request", "授权 ID 无效") + return + } + key, ok := parseOperationKey(c) + if !ok { + return + } + var in struct { + ExpiresAt string `json:"expires_at"` + } + if operation == "renew" && c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "expires_at 必填") + return + } + var expires time.Time + if operation == "renew" { + expires, err = time.Parse(time.RFC3339, in.ExpiresAt) + if err != nil { + apiError(c, 400, "invalid_request", "expires_at 必须为 RFC3339 时间") + return + } + expires = expires.UTC().Truncate(time.Microsecond) + if expires.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) { + apiError(c, 400, "invalid_request", "expires_at 超出允许范围") + return + } + } + adminID := c.MustGet("admin_id") + fingerprintInput := operation + "\x00" + strconv.FormatUint(id, 10) + "\x00" + expires.Format(time.RFC3339Nano) + fingerprint := sha256.Sum256([]byte(fingerprintInput)) + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + var rec licenseRecord + err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=? FOR UPDATE`, id).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "授权不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + var op licenseOperation + err = tx.QueryRowContext(c, "SELECT id,license_id,operation,idempotency_key,request_fingerprint FROM license_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", adminID, operation, key).Scan(&op.ID, &op.LicenseID, &op.Operation, &op.IdempotencyKey, &op.RequestFingerprint) + if err == nil { + if op.LicenseID != id || !bytes.Equal(op.RequestFingerprint, fingerprint[:]) { + apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同授权操作") + return + } + rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC()) + c.JSON(200, gin.H{"data": rec, "idempotent_replay": true}) + return + } + if !errors.Is(err, sql.ErrNoRows) { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if operation == "revoke" { + if rec.Status == "revoked" { + apiError(c, 409, "invalid_state", "授权已经撤销") + return + } + if _, err = tx.ExecContext(c, "UPDATE licenses SET status='revoked',revoked_at=? WHERE id=?", time.Now().UTC(), id); err != nil { + apiError(c, 500, "internal_error", "撤销失败") + return + } + } else { + if rec.Status == "revoked" || !expires.After(rec.ExpiresAt) { + apiError(c, 400, "invalid_request", "续期时间必须晚于当前结束时间且授权未撤销") + return + } + if _, err = tx.ExecContext(c, "UPDATE licenses SET expires_at=?,status='active' WHERE id=?", expires, id); err != nil { + apiError(c, 500, "internal_error", "续期失败") + return + } + } + if _, err = tx.ExecContext(c, "INSERT INTO license_operations(license_id,actor_admin_id,operation,idempotency_key,request_fingerprint) VALUES(?,?,?,?,?)", id, adminID, operation, key, fingerprint[:]); err != nil { + apiError(c, 500, "internal_error", "操作失败,请使用相同幂等键重试") + return + } + details, _ := json.Marshal(map[string]any{"operation": operation, "expires_at": expires, "license_id": id}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?, 'license',?,?)", adminID, "license."+operation, id, details); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if operation == "revoke" { + rec.Status = "revoked" + } else { + rec.ExpiresAt = expires + rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC()) + } + c.JSON(200, gin.H{"data": rec, "idempotent_replay": false}) +} + +const licenseFrom = ` FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id` +const licenseSelect = `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at` + licenseFrom + +// Use the same instant and predicate for the count and page, including expiry boundaries. +func licenseFilter(status, q string, now time.Time) (string, []any, bool) { + where := " WHERE 1=1" + args := []any{} + if q != "" { + where += " AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?)" + like := "%" + q + "%" + args = append(args, like, like, like, like) + } + switch status { + case "": + case "revoked": + where += " AND l.status='revoked'" + case "active", "expiring": + where += " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>?" + args = append(args, now, now) + if status == "expiring" { + where += " AND l.expires_at<=?" + args = append(args, now.Add(30*24*time.Hour)) + } + case "pending": + where += " AND l.status<>'revoked' AND l.starts_at>? AND l.expires_at>?" + args = append(args, now, now) + case "expired": + where += " AND l.status<>'revoked' AND l.expires_at<=?" + args = append(args, now) + default: + return "", nil, false + } + return where, args, true +} + +func readLicenseRecords(rows *sql.Rows, now time.Time) ([]licenseRecord, error) { + defer rows.Close() + out := []licenseRecord{} + for rows.Next() { + var x licenseRecord + if err := rows.Scan(&x.ID, &x.LicenseKey, &x.CustomerID, &x.CustomerName, &x.ProductID, &x.ProductName, &x.ProductCode, &x.Status, &x.StartsAt, &x.ExpiresAt, &x.CreatedAt); err != nil { + return nil, err + } + x.Status = currentLicenseStatus(x.Status, x.StartsAt, x.ExpiresAt, now) + out = append(out, x) + } + return out, rows.Err() +} + +func (a *BusinessAPI) listLicenses(c *gin.Context) { + p, size := page(c) + now := time.Now().UTC() + where, args, ok := licenseFilter(strings.TrimSpace(c.Query("status")), strings.TrimSpace(c.Query("q")), now) + if !ok { + apiError(c, 400, "invalid_request", "授权状态无效") + return + } + var total int + if err := a.db.QueryRowContext(c, "SELECT COUNT(*)"+licenseFrom+where, args...).Scan(&total); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + pageArgs := append(append([]any{}, args...), size, (p-1)*size) + rows, err := a.db.QueryContext(c, licenseSelect+where+" ORDER BY l.id DESC LIMIT ? OFFSET ?", pageArgs...) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + out, err := readLicenseRecords(rows, now) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}}) +} diff --git a/backend/internal/httpapi/licenses_test.go b/backend/internal/httpapi/licenses_test.go new file mode 100644 index 0000000..b2b145b --- /dev/null +++ b/backend/internal/httpapi/licenses_test.go @@ -0,0 +1,102 @@ +package httpapi + +import ( + "database/sql/driver" + "encoding/json" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" +) + +func TestCurrentLicenseStatus(t *testing.T) { + now := time.Date(2026, 9, 30, 8, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name, status string + starts, expires time.Time + want string + }{ + {"scheduled", "active", now.Add(time.Hour), now.Add(2 * time.Hour), "scheduled"}, + {"start boundary", "active", now, now.Add(time.Hour), "active"}, + {"expiry boundary", "active", now.Add(-time.Hour), now, "expired"}, + {"revoked", "revoked", now.Add(time.Hour), now.Add(2 * time.Hour), "revoked"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := currentLicenseStatus(tc.status, tc.starts, tc.expires, now); got != tc.want { + t.Fatalf("got %s want %s", got, tc.want) + } + }) + } +} + +func TestLicenseFilterPredicates(t *testing.T) { + now := time.Date(2026, 10, 8, 10, 0, 0, 0, time.UTC) + for _, tc := range []struct { + status, predicate string + times []any + }{ + {"", "", nil}, + {"active", " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>?", []any{now, now}}, + {"pending", " AND l.status<>'revoked' AND l.starts_at>? AND l.expires_at>?", []any{now, now}}, + {"expired", " AND l.status<>'revoked' AND l.expires_at<=?", []any{now}}, + {"revoked", " AND l.status='revoked'", nil}, + {"expiring", " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>? AND l.expires_at<=?", []any{now, now, now.Add(30 * 24 * time.Hour)}}, + } { + t.Run(tc.status, func(t *testing.T) { + where, args, ok := licenseFilter(tc.status, "customer' OR 1=1", now) + want := " WHERE 1=1 AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?)" + tc.predicate + if !ok || where != want { + t.Fatalf("predicate %s", where) + } + expected := []any{"%customer' OR 1=1%", "%customer' OR 1=1%", "%customer' OR 1=1%", "%customer' OR 1=1%"} + expected = append(expected, tc.times...) + if !reflect.DeepEqual(args, expected) { + t.Fatalf("args %#v", args) + } + }) + } + for _, status := range []string{"scheduled", "unknown", "ACTIVE"} { + if _, _, ok := licenseFilter(status, "", now); ok { + t.Errorf("accepted %s", status) + } + } +} + +func TestListLicensesFilteredPage(t *testing.T) { + // No time-dependent predicate is needed here; each status predicate is checked + // above with exact boundaries. Count and page must both join all search fields. + where := " WHERE 1=1 AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?) AND l.status='revoked'" + args := []any{"%Acme%", "%Acme%", "%Acme%", "%Acme%"} + now := time.Now().UTC() + db, _ := newDashboardTestDB(t, []dashboardQuery{ + {sql: "SELECT COUNT(*)" + licenseFrom + where, args: args, rows: [][]driver.Value{{int64(31)}}}, + {sql: licenseSelect + where + " ORDER BY l.id DESC LIMIT ? OFFSET ?", args: append(append([]any{}, args...), 10, 10), rows: [][]driver.Value{testLicenseRow(25, "revoked", now.Add(-time.Hour), now.Add(time.Hour), now)}}, + }) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/api/v1/licenses?q=%20Acme%20&status=%20revoked%20&page=2&page_size=10", nil) + (&BusinessAPI{db: db}).listLicenses(c) + var out struct { + Data []licenseRecord `json:"data"` + Meta struct { + Total, Page int + PageSize int `json:"page_size"` + } `json:"meta"` + } + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || out.Meta.Total != 31 || out.Meta.Page != 2 || out.Meta.PageSize != 10 || len(out.Data) != 1 || out.Data[0].Status != "revoked" { + t.Fatalf("%d %s", w.Code, w.Body) + } +} +func TestListLicensesInvalidStatus(t *testing.T) { + db, _ := newDashboardTestDB(t, nil) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/api/v1/licenses?status=invalid", nil) + (&BusinessAPI{db: db}).listLicenses(c) + if w.Code != 400 || !strings.Contains(w.Body.String(), "invalid_request") { + t.Fatalf("%d %s", w.Code, w.Body) + } +} diff --git a/backend/internal/httpapi/operations.go b/backend/internal/httpapi/operations.go new file mode 100644 index 0000000..bcf5895 --- /dev/null +++ b/backend/internal/httpapi/operations.go @@ -0,0 +1,189 @@ +package httpapi + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "log/slog" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "github.com/gin-gonic/gin" +) + +type operationSample struct { + Count uint64 + Seconds float64 +} +type Operations struct { + mu sync.Mutex + samples map[string]operationSample + buckets map[string]rateBucket + now func() time.Time + logger *slog.Logger + nextSweep time.Time + limiter EntryLimiter +} +type rateBucket struct { + start time.Time + count int +} + +func NewOperations(logger *slog.Logger) *Operations { + return &Operations{samples: make(map[string]operationSample), buckets: make(map[string]rateBucket), now: time.Now, logger: logger} +} +func operation(path string) string { + switch path { + case "/api/v1/portal/snapshot": + return "login" + case "/api/v1/auth/login": + return "login" + case "/api/v1/activation/instances/:instance_id": + return "activation" + case "/api/v1/instances/:instance_id/heartbeat": + return "heartbeat" + case "/api/v1/customers/:customer_id/releases/:id/download": + return "download" + } + if strings.HasPrefix(path, "/api/v1/licenses") { + return "authorization" + } + return "other" +} + +// Local fixed-window limits are deliberately per process, never a distributed guarantee. +func (o *Operations) allow(key string, limit int) bool { + o.mu.Lock() + defer o.mu.Unlock() + now := o.now() + if !now.Before(o.nextSweep) { + for k, b := range o.buckets { + if now.Sub(b.start) >= time.Minute { + delete(o.buckets, k) + } + } + o.nextSweep = now.Add(time.Minute) + } + b, exists := o.buckets[key] + if !exists && len(o.buckets) >= 10000 { + return false + } + if !exists || now.Sub(b.start) >= time.Minute { + b = rateBucket{start: now} + } + if b.count >= limit { + return false + } + b.count++ + o.buckets[key] = b + return true +} +func (o *Operations) Middleware() gin.HandlerFunc { + return func(c *gin.Context) { + raw := make([]byte, 16) + if _, err := rand.Read(raw); err != nil { + c.AbortWithStatus(http.StatusServiceUnavailable) + return + } + id := hex.EncodeToString(raw) + c.Set("request_id", id) + c.Header("X-Request-ID", id) + started := time.Now() + path := c.FullPath() + op := operation(path) + defer func() { + elapsed := time.Since(started).Seconds() + outcome := "success" + if c.Writer.Status() >= 400 { + outcome = "failure" + } + key := op + "/" + outcome + o.mu.Lock() + sample := o.samples[key] + sample.Count++ + sample.Seconds += elapsed + o.samples[key] = sample + o.mu.Unlock() + // No bodies, query strings, raw paths, IPs, cookies, headers, SQL errors or panic values. + o.logger.Info("http_request", "request_id", id, "trace_id", id, "route", path, "operation", op, "status", c.Writer.Status(), "error_code", c.GetString("error_code"), "duration_seconds", elapsed) + }() + defer func() { + if recover() != nil { + apiError(c, 500, "internal_error", "Service unavailable") + c.Abort() + } + }() + if op == "login" || op == "activation" || op == "heartbeat" || op == "download" { + limit := 60 + if op == "login" { + limit = 10 + } + sum := sha256.Sum256([]byte(c.ClientIP())) + key := op + hex.EncodeToString(sum[:]) + allowed := false + if o.limiter != nil { + var err error + allowed, err = o.limiter.Allow(c.Request.Context(), key, limit) + if err != nil { + apiError(c, 503, "rate_limit_unavailable", "Service unavailable") + c.Abort() + return + } + } else { + allowed = o.allow(key, limit) + } + if !allowed { + c.Header("Retry-After", "60") + apiError(c, 429, "rate_limited", "Too many requests") + c.Abort() + return + } + } + if c.Request.Method != "GET" && c.Request.Method != "HEAD" && c.Request.Method != "OPTIONS" { + origin := c.GetHeader("Origin") + if origin != "" { + u, err := url.Parse(origin) + scheme := "http" + if secureSessionCookie(c) { + scheme = "https" + } + if err != nil || u.Host != c.Request.Host || u.Scheme != scheme || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + apiError(c, 403, "origin_forbidden", "Cross-origin request denied") + c.Abort() + return + } + } + if c.GetHeader("Sec-Fetch-Site") == "cross-site" { + apiError(c, 403, "origin_forbidden", "Cross-site request denied") + c.Abort() + return + } + } + // Uploads have their own 64 MiB streaming bound; other JSON routes get a 64 KiB ceiling. + if !(path == "/api/v1/products/:id/releases" && c.Request.Method == "POST") { + if c.Request.ContentLength > 64<<10 { + apiError(c, 413, "body_too_large", "Request body too large") + c.Abort() + return + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<10) + } + c.Next() + } +} + +// Expose only on a separate loopback/private monitoring listener, never the public router. +func (o *Operations) Metrics(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; version=0.0.4") + o.mu.Lock() + defer o.mu.Unlock() + fmt.Fprintln(w, "# TYPE license_requests_total counter\n# TYPE license_request_duration_seconds_sum counter") + for key, s := range o.samples { + parts := strings.Split(key, "/") + fmt.Fprintf(w, "license_requests_total{operation=%q,outcome=%q} %d\nlicense_request_duration_seconds_sum{operation=%q,outcome=%q} %g\n", parts[0], parts[1], s.Count, parts[0], parts[1], s.Seconds) + } +} diff --git a/backend/internal/httpapi/operations_boundary_test.go b/backend/internal/httpapi/operations_boundary_test.go new file mode 100644 index 0000000..231a02a --- /dev/null +++ b/backend/internal/httpapi/operations_boundary_test.go @@ -0,0 +1,74 @@ +package httpapi + +import ( + "github.com/gin-gonic/gin" + "io" + "log/slog" + "net/http/httptest" + "strings" + "testing" +) + +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"} { + t.Run(path, func(t *testing.T) { + r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil)))) + calls := 0 + r.POST(path, func(c *gin.Context) { calls++; c.Status(401) }) + n := 60 + if strings.Contains(path, "login") { + n = 10 + } + for i := 0; i <= n; i++ { + q := httptest.NewRequest("POST", strings.ReplaceAll(strings.ReplaceAll(path, ":instance_id", "x"), ":customer_id", "1"), nil) + q.URL.Path = strings.ReplaceAll(q.URL.Path, ":id", "1") + q.RemoteAddr = "127.0.0.1:1234" + q.Header.Set("X-Forwarded-For", strings.Repeat("1", i)+".2.3.4") + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + if i == n && w.Code != 429 { + t.Fatal(w.Code) + } + } + if calls != n { + t.Fatal(calls) + } + }) + } +} +func TestChunkedBodyCORSAndMalformedSession(t *testing.T) { + r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil)))) + r.POST("/json", func(c *gin.Context) { + var data map[string]any + if c.ShouldBindJSON(&data) != nil { + apiError(c, 400, "invalid_request", "Invalid JSON") + return + } + c.Status(204) + }) + q := httptest.NewRequest("POST", "/json", strings.NewReader(`{"secret":"`+strings.Repeat("x", 65537)+`"}`)) + q.ContentLength = -1 + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + if w.Code != 400 { + t.Fatal(w.Code) + } + q = httptest.NewRequest("OPTIONS", "/json", nil) + q.Header.Set("Origin", "https://evil.example") + w = httptest.NewRecorder() + r.ServeHTTP(w, q) + if w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Fatal("CORS must not allow external origin") + } + a := &BusinessAPI{} + r.GET("/session", a.authenticated, func(c *gin.Context) { t.Fatal("malformed session authenticated") }) + for _, cookie := range []string{"", "lp_session=bad", "lp_session=" + strings.Repeat("z", 64)} { + q = httptest.NewRequest("GET", "/session", nil) + q.Header.Set("Cookie", cookie) + w = httptest.NewRecorder() + r.ServeHTTP(w, q) + if w.Code != 401 { + t.Fatal(w.Code) + } + } +} diff --git a/backend/internal/httpapi/operations_test.go b/backend/internal/httpapi/operations_test.go new file mode 100644 index 0000000..0141110 --- /dev/null +++ b/backend/internal/httpapi/operations_test.go @@ -0,0 +1,127 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "github.com/gin-gonic/gin" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestOperationsSecurity(t *testing.T) { + var logs bytes.Buffer + ops := NewOperations(slog.New(slog.NewJSONHandler(&logs, nil))) + r := NewOperationalRouter(ops) + r.POST("/api/v1/auth/login", func(c *gin.Context) { apiError(c, 401, "invalid_credentials", "Denied") }) + r.GET("/panic/:secret", func(c *gin.Context) { panic("PRIVATE_PEM_password") }) + request := func(method, path, body, origin string) *httptest.ResponseRecorder { + q := httptest.NewRequest(method, path, strings.NewReader(body)) + q.RemoteAddr = "127.0.0.1:1234" + q.Header.Set("Origin", origin) + q.Header.Set("Cookie", "lp_session=PRIVATE_COOKIE") + q.Header.Set("X-Request-ID", "FORGED_ID") + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + return w + } + for i := 0; i < 10; i++ { + if w := request("POST", "/api/v1/auth/login?password=PRIVATE_QUERY", "PRIVATE_PASSWORD", ""); w.Code != 401 { + t.Fatal(w.Code) + } + } + w := request("POST", "/api/v1/auth/login", "", "") + if w.Code != 429 || w.Header().Get("Retry-After") == "" { + t.Fatal(w.Code) + } + w = request("GET", "/panic/PRIVATE_PATH", "", "") + if w.Code != 500 || strings.Contains(w.Body.String(), "PRIVATE") { + t.Fatal(w.Body.String()) + } + if strings.Contains(logs.String(), "PRIVATE") || strings.Contains(logs.String(), "FORGED_ID") { + t.Fatal("secret or forged ID in logs") + } + dec := json.NewDecoder(&logs) + n := 0 + for { + var row map[string]any + err := dec.Decode(&row) + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + if row["request_id"] == "" || row["trace_id"] != row["request_id"] { + t.Fatal(row) + } + n++ + } + if n != 12 { + t.Fatal(n) + } + mw := httptest.NewRecorder() + ops.Metrics(mw, httptest.NewRequest("GET", "/metrics", nil)) + if !strings.Contains(mw.Body.String(), "license_requests_total{operation=\"login\",outcome=\"failure\"} 11") { + t.Fatal(mw.Body.String()) + } + if request("GET", "/metrics", "", "").Code != 404 { + t.Fatal("public metrics exposed") + } +} +func TestOriginAndBodyGuards(t *testing.T) { + r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil)))) + r.POST("/write", func(c *gin.Context) { c.Status(204) }) + for _, tc := range []struct { + origin, body string + status int + }{{"https://evil.example", "", 403}, {"http://example.com", "", 204}, {"", "", 204}, {"", strings.Repeat("x", 65537), 413}} { + q := httptest.NewRequest("POST", "http://example.com/write", strings.NewReader(tc.body)) + q.Header.Set("Origin", tc.origin) + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + if w.Code != tc.status { + t.Fatalf("origin=%s status=%d", tc.origin, w.Code) + } + } +} +func TestLocalLimiterBoundaryAndScope(t *testing.T) { + now := time.Now() + a := NewOperations(slog.Default()) + a.now = func() time.Time { return now } + if !a.allow("test", 1) || a.allow("test", 1) { + t.Fatal("limit not enforced") + } + b := NewOperations(slog.Default()) + if !b.allow("test", 1) { + t.Fatal("independent process scope") + } + now = now.Add(time.Minute) + if !a.allow("test", 1) { + t.Fatal("window not reset") + } + for i := 0; i < 10000; i++ { + a.buckets[string(rune(i))] = rateBucket{start: now} + } + if a.allow("new_key", 1) { + t.Fatal("capacity must fail closed") + } +} +func TestSessionCookieAttributes(t *testing.T) { + t.Setenv("SESSION_COOKIE_SECURE", "true") + r := gin.New() + r.GET("/cookie", func(c *gin.Context) { + c.SetSameSite(http.SameSiteStrictMode) + c.SetCookie("lp_session", "test", 60, "/", "", secureSessionCookie(c), true) + }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/cookie", nil)) + cookies := w.Result().Cookies() + if len(cookies) != 1 || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode { + t.Fatal(cookies) + } +} diff --git a/backend/internal/httpapi/orders.go b/backend/internal/httpapi/orders.go new file mode 100644 index 0000000..681fa51 --- /dev/null +++ b/backend/internal/httpapi/orders.go @@ -0,0 +1,346 @@ +package httpapi + +import ( + "bytes" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +type orderRecord struct { + ID uint64 `json:"id"` + OrderNo string `json:"order_no"` + CustomerID uint64 `json:"customer_id"` + CustomerName string `json:"customer_name"` + ProductID uint64 `json:"product_id"` + ProductName string `json:"product_name"` + AmountCents uint64 `json:"amount_cents"` + Currency string `json:"currency"` + Status string `json:"status"` + PaymentReference *string `json:"payment_reference"` + PaidAt *time.Time `json:"paid_at"` + LicenseID *uint64 `json:"license_id"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +const orderSelect = `SELECT o.id,o.order_no,o.customer_id,c.name,o.product_id,p.name,o.amount_cents,o.currency,o.status,o.payment_reference,o.paid_at,o.issued_license_id,o.created_at,o.updated_at FROM offline_orders o JOIN customers c ON c.id=o.customer_id JOIN products p ON p.id=o.product_id` + +type orderScanner interface{ Scan(...any) error } + +func scanOrder(s orderScanner) (o orderRecord, err error) { + err = s.Scan(&o.ID, &o.OrderNo, &o.CustomerID, &o.CustomerName, &o.ProductID, &o.ProductName, &o.AmountCents, &o.Currency, &o.Status, &o.PaymentReference, &o.PaidAt, &o.LicenseID, &o.CreatedAt, &o.UpdatedAt) + return +} +func (a *BusinessAPI) listOrders(c *gin.Context) { + p, size := page(c) + var total int + if a.db.QueryRowContext(c, "SELECT COUNT(*) FROM offline_orders").Scan(&total) != nil { + apiError(c, 500, "internal_error", "订单加载失败") + return + } + rows, err := a.db.QueryContext(c, orderSelect+" ORDER BY o.id DESC LIMIT ? OFFSET ?", size, (p-1)*size) + if err != nil { + apiError(c, 500, "internal_error", "订单加载失败") + return + } + defer rows.Close() + out := []orderRecord{} + for rows.Next() { + o, e := scanOrder(rows) + if e != nil { + apiError(c, 500, "internal_error", "订单加载失败") + return + } + out = append(out, o) + } + if rows.Err() != nil { + apiError(c, 500, "internal_error", "订单加载失败") + return + } + c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}}) +} +func (a *BusinessAPI) getOrder(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + apiError(c, 400, "invalid_request", "订单 ID 无效") + return + } + o, err := scanOrder(a.db.QueryRowContext(c, orderSelect+" WHERE o.id=?", id)) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "订单不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "订单加载失败") + return + } + c.JSON(200, gin.H{"data": o}) +} + +type orderInput struct { + CustomerID uint64 `json:"customer_id"` + ProductID uint64 `json:"product_id"` + AmountCents uint64 `json:"amount_cents"` + Currency string `json:"currency"` + PaymentReference string `json:"payment_reference"` + StartsAt string `json:"starts_at"` + ExpiresAt string `json:"expires_at"` +} + +func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) { + key, ok := parseOperationKey(c) + if !ok { + return + } + for _, r := range key { + if r < 33 || r > 126 { + apiError(c, 400, "invalid_idempotency_key", "幂等键仅允许可见 ASCII 字符") + return + } + } + var in orderInput + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "订单参数无效") + return + } + var id uint64 + var err error + if operation != "create" { + id, err = strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + apiError(c, 400, "invalid_request", "订单 ID 无效") + return + } + } + var starts, expires time.Time + switch operation { + case "create": + if in.CustomerID == 0 || in.ProductID == 0 || in.AmountCents == 0 || in.AmountCents > 100000000000 || in.Currency != "CNY" { + apiError(c, 400, "invalid_request", "客户产品必填,金额须为1至100000000000分,币种为CNY") + return + } + in = orderInput{CustomerID: in.CustomerID, ProductID: in.ProductID, AmountCents: in.AmountCents, Currency: in.Currency} + case "confirm-payment": + in.PaymentReference = strings.TrimSpace(in.PaymentReference) + if in.AmountCents == 0 || len(in.PaymentReference) == 0 || len(in.PaymentReference) > 190 { + apiError(c, 400, "invalid_request", "实际收款金额和收款凭据编号必填(编号最多190字节)") + return + } + in = orderInput{AmountCents: in.AmountCents, PaymentReference: in.PaymentReference} + case "issue": + starts, err = time.Parse(time.RFC3339, in.StartsAt) + if err != nil { + apiError(c, 400, "invalid_request", "开始时间必须为RFC3339") + return + } + expires, err = time.Parse(time.RFC3339, in.ExpiresAt) + starts = starts.UTC().Truncate(time.Microsecond) + expires = expires.UTC().Truncate(time.Microsecond) + if err != nil || !expires.After(starts) || starts.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) { + apiError(c, 400, "invalid_request", "授权期限无效或超出TIMESTAMP范围") + return + } + in = orderInput{StartsAt: starts.Format(time.RFC3339Nano), ExpiresAt: expires.Format(time.RFC3339Nano)} + default: + apiError(c, 400, "invalid_request", "未知订单操作") + return + } + payload, _ := json.Marshal(struct { + ID uint64 + Input orderInput + }{id, in}) + fingerprint := sha256.Sum256(payload) + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + defer tx.Rollback() + fail := func() { apiError(c, 500, "internal_error", "订单操作失败,请保留相同幂等键重试") } + actor := c.MustGet("admin_id") + // Consistent administrator-first lock order serializes same-actor retry keys across orders. + var locked uint64 + err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", actor).Scan(&locked) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 403, "forbidden", "无权操作订单") + return + } + if err != nil { + fail() + return + } + var storedFingerprint, storedResponse []byte + err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM order_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", actor, operation, key).Scan(&storedFingerprint, &storedResponse) + if err == nil { + if !bytes.Equal(storedFingerprint, fingerprint[:]) { + apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同订单请求") + return + } + var result gin.H + if json.Unmarshal(storedResponse, &result) != nil { + fail() + return + } + result["idempotent_replay"] = true + c.JSON(200, result) + return + } + if !errors.Is(err, sql.ErrNoRows) { + fail() + return + } + var o orderRecord + if operation != "create" { + o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=? FOR UPDATE", id)) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "订单不存在") + return + } + if err != nil { + fail() + return + } + } + var license *licenseRecord + if operation == "create" || operation == "issue" { + customerID, productID := o.CustomerID, o.ProductID + if operation == "create" { + customerID, productID = in.CustomerID, in.ProductID + } + var customerStatus string + var active bool + err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", customerID).Scan(&o.CustomerName, &customerStatus) + if errors.Is(err, sql.ErrNoRows) || err == nil && customerStatus != "active" { + apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用") + return + } + if err != nil { + fail() + return + } + err = tx.QueryRowContext(c, "SELECT name,active FROM products WHERE id=? FOR UPDATE", productID).Scan(&o.ProductName, &active) + if errors.Is(err, sql.ErrNoRows) || err == nil && !active { + apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用") + return + } + if err != nil { + fail() + return + } + } + switch operation { + case "create": + raw := make([]byte, 16) + if _, err = rand.Read(raw); err != nil { + fail() + return + } + res, e := tx.ExecContext(c, "INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,created_by) VALUES(?,?,?,?,?,?)", hex.EncodeToString(raw), in.CustomerID, in.ProductID, in.AmountCents, in.Currency, actor) + if e != nil { + fail() + return + } + n, e := res.LastInsertId() + if e != nil { + fail() + return + } + id = uint64(n) + case "confirm-payment": + if o.Status != "pending_payment" { + apiError(c, 409, "invalid_state", "只有待收款订单可确认收款") + return + } + if o.AmountCents != in.AmountCents { + apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额") + return + } + _, err = tx.ExecContext(c, "UPDATE offline_orders SET status='paid',payment_reference=?,paid_at=?,paid_by=? WHERE id=?", in.PaymentReference, time.Now().UTC(), actor, id) + if err != nil { + fail() + return + } + case "issue": + if o.Status != "paid" || o.LicenseID != nil { + apiError(c, 409, "invalid_state", "只有已收款且未发放的订单可发放授权") + return + } + raw := make([]byte, 16) + if _, err = rand.Read(raw); err != nil { + fail() + return + } + // Random internal key avoids collisions with administrator-supplied direct-issuance keys. + internalKey := "order-" + strconv.FormatUint(id, 10) + "-" + hex.EncodeToString(raw) + res, e := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", hex.EncodeToString(raw), o.CustomerID, o.ProductID, starts, expires, internalKey, actor) + if e != nil { + fail() + return + } + n, e := res.LastInsertId() + if e != nil { + fail() + return + } + _, err = tx.ExecContext(c, "UPDATE offline_orders SET status='issued',issued_license_id=? WHERE id=?", n, id) + if err != nil { + fail() + return + } + l := licenseRecord{} + err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=?`, n).Scan(&l.ID, &l.LicenseKey, &l.CustomerID, &l.CustomerName, &l.ProductID, &l.ProductName, &l.ProductCode, &l.Status, &l.StartsAt, &l.ExpiresAt, &l.CreatedAt) + if err != nil { + fail() + return + } + l.Status = currentLicenseStatus(l.Status, l.StartsAt, l.ExpiresAt, time.Now().UTC()) + license = &l + details, _ := json.Marshal(gin.H{"order_id": id, "customer_id": o.CustomerID, "product_id": o.ProductID, "starts_at": starts, "expires_at": expires}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", actor, n, details); err != nil { + fail() + return + } + } + o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=?", id)) + if err != nil { + fail() + return + } + result := gin.H{"data": o, "idempotent_replay": false} + if license != nil { + result["license"] = license + } + response, err := json.Marshal(result) + if err != nil { + fail() + return + } + if _, err = tx.ExecContext(c, "INSERT INTO order_operations(order_id,actor_admin_id,operation,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?,?)", id, actor, operation, key, fingerprint[:], response); err != nil { + fail() + return + } + details, _ := json.Marshal(gin.H{"customer_id": o.CustomerID, "product_id": o.ProductID, "amount_cents": o.AmountCents, "currency": o.Currency, "license_id": o.LicenseID}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'order',?,?)", actor, "order."+operation, id, details); err != nil { + fail() + return + } + if tx.Commit() != nil { + fail() + return + } + if operation == "create" { + c.Header("Location", "/api/v1/orders/"+strconv.FormatUint(id, 10)) + c.JSON(201, result) + } else { + c.JSON(200, result) + } +} diff --git a/backend/internal/httpapi/orders_integration_test.go b/backend/internal/httpapi/orders_integration_test.go new file mode 100644 index 0000000..1c9382e --- /dev/null +++ b/backend/internal/httpapi/orders_integration_test.go @@ -0,0 +1,150 @@ +package httpapi + +import ( + "database/sql" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func testOrdersMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Cookie, customerID, productID uint64) { + request := func(method, path, body, key string, authenticated bool) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", key) + if authenticated { + req.AddCookie(cookie) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + check := func(w *httptest.ResponseRecorder, code int) { + t.Helper() + if w.Code != code { + t.Fatalf("code=%d want=%d body=%s", w.Code, code, w.Body) + } + } + exec := func(query string, args ...any) { + t.Helper() + if _, err := db.Exec(query, args...); err != nil { + t.Fatal(err) + } + } + body := fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"amount_cents":12800,"currency":"CNY"}`, customerID, productID) + check(request("POST", "/api/v1/orders", body, "create", false), 401) + exec("UPDATE admins SET role='viewer' WHERE email='integration@example.test'") + check(request("POST", "/api/v1/orders", body, "create", true), 403) + exec("UPDATE admins SET role='admin' WHERE email='integration@example.test'") + check(request("POST", "/api/v1/orders", body, "", true), 400) + check(request("POST", "/api/v1/orders", strings.Replace(body, "12800", "0", 1), "invalid", true), 400) + exec("UPDATE customers SET status='inactive' WHERE id=?", customerID) + check(request("POST", "/api/v1/orders", body, "inactive-customer", true), 400) + exec("UPDATE customers SET status='active' WHERE id=?", customerID) + w := request("POST", "/api/v1/orders", body, "create", true) + check(w, 201) + var result struct { + Data orderRecord `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + id := result.Data.ID + path := fmt.Sprintf("/api/v1/orders/%d", id) + check(request("POST", "/api/v1/orders", body, "create", true), 200) + check(request("POST", "/api/v1/orders", strings.Replace(body, "12800", "12900", 1), "create", true), 409) + check(request("GET", path, "", "", true), 200) + check(request("GET", "/api/v1/orders?page=1&page_size=20", "", "", true), 200) + dates := `{"starts_at":"2026-09-30T00:00:00Z","expires_at":"2027-09-30T00:00:00Z"}` + check(request("POST", path+"/issue", dates, "issue", true), 409) + payment := `{"amount_cents":12800,"payment_reference":"BANK-TEST-001"}` + check(request("POST", path+"/confirm-payment", strings.Replace(payment, "12800", "12799", 1), "payment", true), 400) + exec("CREATE TRIGGER order_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'") + t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS order_audit_failure") }) + check(request("POST", path+"/confirm-payment", payment, "payment", true), 500) + exec("DROP TRIGGER order_audit_failure") + var status string + if err := db.QueryRow("SELECT status FROM offline_orders WHERE id=?", id).Scan(&status); err != nil { + t.Fatal(err) + } + if status != "pending_payment" { + t.Fatal("failed payment changed order") + } + check(request("POST", path+"/confirm-payment", payment, "payment", true), 200) + check(request("POST", path+"/confirm-payment", payment, "payment", true), 200) + check(request("POST", path+"/confirm-payment", payment, "different-payment", true), 409) + check(request("POST", path+"/confirm-payment", strings.Replace(payment, "001", "002", 1), "payment", true), 409) + exec("UPDATE products SET active=0 WHERE id=?", productID) + check(request("POST", path+"/issue", dates, "issue", true), 400) + exec("UPDATE products SET active=1 WHERE id=?", productID) + var before int + if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&before); err != nil { + t.Fatal(err) + } + exec("CREATE TRIGGER order_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'") + check(request("POST", path+"/issue", dates, "issue", true), 500) + exec("DROP TRIGGER order_audit_failure") + var after int + if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&after); err != nil { + t.Fatal(err) + } + if before != after { + t.Fatal("failed audit leaked license") + } + if err := db.QueryRow("SELECT status FROM offline_orders WHERE id=?", id).Scan(&status); err != nil { + t.Fatal(err) + } + if status != "paid" { + t.Fatal("failed issuance changed order") + } + results := make(chan *httptest.ResponseRecorder, 2) + for i := 0; i < 2; i++ { + go func() { results <- request("POST", path+"/issue", dates, "issue", true) }() + } + replay := 0 + for i := 0; i < 2; i++ { + w := <-results + check(w, 200) + if strings.Contains(w.Body.String(), `"idempotent_replay":true`) { + replay++ + } + } + if replay != 1 { + t.Fatalf("replays=%d", replay) + } + check(request("POST", path+"/issue", dates, "different-issue", true), 409) + check(request("POST", path+"/issue", strings.Replace(dates, "2027", "2028", 1), "issue", true), 409) + if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&after); err != nil { + t.Fatal(err) + } + if after != before+1 { + t.Fatal("duplicate issuance") + } + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE resource_type='order' AND resource_id=?", id).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 3 { + t.Fatalf("order audits=%d", count) + } + if err := db.QueryRow("SELECT COUNT(*) FROM order_operations WHERE order_id=?", id).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 3 { + t.Fatalf("operations=%d", count) + } + var licenseID uint64 + if err := db.QueryRow("SELECT issued_license_id FROM offline_orders WHERE id=? AND status='issued'", id).Scan(&licenseID); err != nil { + t.Fatal(err) + } + if err := db.QueryRow("SELECT COUNT(*) FROM licenses WHERE id=? AND customer_id=? AND product_id=?", licenseID, customerID, productID).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 1 { + t.Fatal("license scope mismatch") + } +} diff --git a/backend/internal/httpapi/portal.go b/backend/internal/httpapi/portal.go new file mode 100644 index 0000000..21278af --- /dev/null +++ b/backend/internal/httpapi/portal.go @@ -0,0 +1,104 @@ +package httpapi + +import ( + "crypto/sha256" + "database/sql" + "encoding/base64" + "net/http" + "time" + + "github.com/gin-gonic/gin" +) + +// Instance credentials authorize only this instance, never an entire customer account. +func (a *BusinessAPI) portalSnapshot(c *gin.Context) { + c.Header("Cache-Control", "private, no-store") + 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.Query("customer_id") != "" || c.ShouldBindJSON(&in) != nil || len(in.InstanceID) != 36 || len(in.Secret) > 128 { + apiError(c, 400, "invalid_request", "Invalid portal request") + return + } + raw, err := base64.RawURLEncoding.DecodeString(in.Secret) + if err != nil || len(raw) != 32 { + apiError(c, 403, "forbidden", "Invalid credentials") + return + } + sum := sha256.Sum256(raw) + tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead}) + if err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + defer tx.Rollback() + var rowID, actor, owner, productID, licenseID uint64 + var stored []byte + var customerName, customerState, productName, productCode, instanceState, freeze, licenseState, observed string + var active bool + var starts, expires, now time.Time + var seen, lease sql.NullTime + err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.license_id,i.secret_hash,c.name,c.status,p.name,p.code,p.active,i.status,i.freeze_state,l.status,l.starts_at,l.expires_at,i.observed_state,i.last_seen_at,i.lease_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=?`, in.InstanceID).Scan(&rowID, &actor, &owner, &productID, &licenseID, &stored, &customerName, &customerState, &productName, &productCode, &active, &instanceState, &freeze, &licenseState, &starts, &expires, &observed, &seen, &lease) + if err == sql.ErrNoRows || (err == nil && !bytesEqual(stored, sum[:])) { + apiError(c, 403, "forbidden", "Invalid credentials") + return + } + if err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + state := leaseState(instanceState, freeze, licenseState, customerState, active, starts, expires, now) + p, size := page(c) + // Bound offset independently of integer overflow and expensive arbitrary scans. + if p > 10000 { + apiError(c, 400, "invalid_page", "Page out of range") + return + } + var total int + if err = tx.QueryRowContext(c, "SELECT COUNT(*) FROM product_releases WHERE product_id=? AND published=1", productID).Scan(&total); err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + rows, err := tx.QueryContext(c, "SELECT id,version,sha256,size_bytes FROM product_releases WHERE product_id=? AND published=1 ORDER BY id DESC LIMIT ? OFFSET ?", productID, size, (p-1)*size) + if err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + releases := []gin.H{} + for rows.Next() { + var id, sizeBytes uint64 + var version, digest string + if err = rows.Scan(&id, &version, &digest, &sizeBytes); err != nil { + break + } + releases = append(releases, gin.H{"id": id, "version": version, "sha256": digest, "size_bytes": sizeBytes, "download_allowed": state == "active"}) + } + scanErr := rows.Err() + rows.Close() + if err != nil || scanErr != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + // Audit attributes the client to an instance, not to the provisioning administrator. + if _, err = tx.ExecContext(c, `INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'portal.viewed','license_instance',?,JSON_OBJECT('client_actor','instance','customer_id',?))`, actor, rowID, owner); err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 503, "portal_unavailable", "Portal unavailable") + return + } + nullable := func(v sql.NullTime) any { + if v.Valid { + return v.Time + } + return nil + } + c.JSON(200, gin.H{"data": gin.H{"scope": "instance", "customer": gin.H{"id": owner, "name": customerName}, "product": gin.H{"id": productID, "code": productCode, "name": productName}, "license": gin.H{"id": licenseID, "status": licenseState, "starts_at": starts, "expires_at": expires}, "instance": gin.H{"instance_id": in.InstanceID, "status": instanceState, "freeze_state": freeze}, "lease": gin.H{"observed_state": observed, "last_seen_at": nullable(seen), "expires_at": nullable(lease), "current_state": state}, "releases": releases}, "meta": gin.H{"page": p, "page_size": size, "total": total}}) +} diff --git a/backend/internal/httpapi/portal_keyring_integration_test.go b/backend/internal/httpapi/portal_keyring_integration_test.go new file mode 100644 index 0000000..0eb44d4 --- /dev/null +++ b/backend/internal/httpapi/portal_keyring_integration_test.go @@ -0,0 +1,193 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "encoding/pem" + "fmt" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" +) + +func TestPortalKeyringMySQL(t *testing.T) { + dsn := os.Getenv("PORTAL_TEST_DSN") + if dsn == "" { + t.Skip("PORTAL_TEST_DSN isolated schema008 required") + } + db, err := sql.Open("mysql", dsn) + if err != nil { + t.Fatal("database configuration invalid") + } + defer db.Close() + // Never run the fixture against a named business database. + var database string + if err = db.QueryRow("SELECT DATABASE()").Scan(&database); err != nil || !strings.HasPrefix(database, "license_portal_test_") { + t.Fatal("dedicated portal test database required") + } + insert := func(q string, args ...any) int64 { + t.Helper() + r, e := db.Exec(q, args...) + if e != nil { + t.Fatal("fixture SQL failed") + } + id, _ := r.LastInsertId() + return id + } + suffix := fmt.Sprint(time.Now().UnixNano()) + admin := insert("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@portal.test", "unused") + owner := insert("INSERT INTO customers(name,contact_email) VALUES(?,'portal@test.invalid')", suffix) + other := insert("INSERT INTO customers(name,contact_email) VALUES(?,'other@test.invalid')", suffix+"other") + product := insert("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, "PortalProduct") + otherProduct := insert("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", "HiddenProduct") + old, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + next, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + pub := func(k *ecdsa.PrivateKey) string { + d, _ := x509.MarshalPKIXPublicKey(&k.PublicKey) + return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: d})) + } + router := func(k *ecdsa.PrivateKey, id string) *gin.Engine { + d, _ := x509.MarshalECPrivateKey(k) + private := string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: d})) + ring := &Keyring{Current: id, Keys: []VerificationKey{{KeyID: "old", PublicKeyPEM: pub(old)}, {KeyID: "new", PublicKeyPEM: pub(next)}}} + if e := ring.Validate(private); e != nil { + t.Fatal(e) + } + r := NewRouter() + RegisterBusinessWithKeyring(r, db, private, ring) + return r + } + r := router(old, "old") + request := func(path string, body any, idem string) *httptest.ResponseRecorder { + b, _ := json.Marshal(body) + q := httptest.NewRequest("POST", path, strings.NewReader(string(b))) + q.Header.Set("Content-Type", "application/json") + q.Header.Set("Idempotency-Key", idem) + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + return w + } + type fixture struct { + instance, secret, key string + license int64 + } + create := func(customer, prod int64, label string) fixture { + raw := make([]byte, 32) + rand.Read(raw) + key := hex.EncodeToString(raw[:16]) + license := insert("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", key, customer, prod, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix+label, admin) + secret := make([]byte, 32) + rand.Read(secret) + sum := sha256.Sum256(secret) + id, _ := newInstanceID() + insert("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", id, license, customer, prod, sum[:], admin) + return fixture{id, base64.RawURLEncoding.EncodeToString(secret), key, license} + } + first := create(owner, product, "first") + hidden := create(other, otherProduct, "hidden") + activate := func(f fixture) *httptest.ResponseRecorder { + return request("/api/v1/activation/instances/"+f.instance, map[string]string{"secret": f.secret, "license_key": f.key}, "activate") + } + envelopes := []json.RawMessage{} + collect := func(w *httptest.ResponseRecorder, key string) { + t.Helper() + if w.Code != 200 && w.Code != 201 { + t.Fatalf("issuance status %d", w.Code) + } + var out struct { + Data struct { + Certificate json.RawMessage `json:"certificate"` + Payload json.RawMessage `json:"payload"` + Signature string `json:"signature"` + } `json:"data"` + } + if json.Unmarshal(w.Body.Bytes(), &out) != nil { + t.Fatal("invalid response") + } + envelope := out.Data.Certificate + if len(envelope) == 0 { + var err error + envelope, err = json.Marshal(map[string]any{"payload": json.RawMessage(out.Data.Payload), "signature": out.Data.Signature}) + if err != nil { + t.Fatal("invalid heartbeat envelope") + } + } + if !strings.Contains(string(envelope), `"key_id":"`+key+`"`) { + t.Fatal("wrong signing key") + } + envelopes = append(envelopes, envelope) + } + initial := activate(first) + collect(initial, "old") + beat := func(f fixture, idem string) *httptest.ResponseRecorder { + return request("/api/v1/instances/"+f.instance+"/heartbeat", map[string]string{"secret": f.secret, "client_time": time.Now().UTC().Format(time.RFC3339Nano)}, idem) + } + collect(beat(first, "old-beat"), "old") + r = router(next, "new") + replay := activate(first) + collect(replay, "old") + var a, b any + json.Unmarshal(initial.Body.Bytes(), &a) + json.Unmarshal(replay.Body.Bytes(), &b) + aa, _ := json.Marshal(a) + bb, _ := json.Marshal(b) + if string(aa) != string(bb) { + t.Fatal("rotation changed historical replay") + } + second := create(owner, product, "second") + collect(activate(second), "new") + collect(beat(second, "new-beat"), "new") + // Recreate router after rotation with same private material: application re-registration, not OS process restart. + r = router(next, "new") + collect(activate(second), "new") + insert("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,'v1',?,?,1,?)", product, strings.Repeat("a", 64)+".bin", strings.Repeat("a", 64), admin) + insert("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,'hidden-version',?,?,1,?)", otherProduct, strings.Repeat("b", 64)+".bin", strings.Repeat("b", 64), admin) + snapshot := func(f fixture, path string) *httptest.ResponseRecorder { + return request(path, map[string]string{"instance_id": f.instance, "secret": f.secret}, "") + } + w := snapshot(first, "/api/v1/portal/snapshot?page_size=1") + if w.Code != 200 || strings.Contains(w.Body.String(), "HiddenProduct") || strings.Contains(w.Body.String(), "hidden-version") || strings.Contains(w.Body.String(), first.secret) || strings.Contains(w.Body.String(), "secret_hash") { + t.Fatal("portal isolation failed") + } + if len(w.Result().Cookies()) != 0 || w.Header().Get("Cache-Control") != "private, no-store" { + t.Fatal("portal cookie/cache boundary") + } + if w = snapshot(first, "/api/v1/portal/snapshot?customer_id="+fmt.Sprint(other)); w.Code != 400 { + t.Fatal("customer override accepted") + } + bad := first + bad.instance = hidden.instance + if w = snapshot(bad, "/api/v1/portal/snapshot"); w.Code != 403 { + t.Fatal("cross-instance credentials accepted") + } + if w = snapshot(first, "/api/v1/portal/snapshot?page=10001"); w.Code != 400 { + t.Fatal("unbounded pagination") + } + var n int + if db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='portal.viewed'").Scan(&n) != nil || n < 1 { + t.Fatal("portal audit missing") + } + path := filepath.Join(t.TempDir(), "public-vectors.json") + vectors, _ := json.Marshal(map[string]any{"keys": []VerificationKey{{KeyID: "old", PublicKeyPEM: pub(old)}, {KeyID: "new", PublicKeyPEM: pub(next)}}, "envelopes": envelopes}) + if os.WriteFile(path, vectors, 0600) != nil { + t.Fatal("vectors unavailable") + } + output, e := exec.Command("node", "--input-type=module", "-e", `import fs from 'node:fs';import {verifyEnvelope} from '../../../client/verify.mjs';const v=JSON.parse(fs.readFileSync(process.argv[1]));for(const e of v.envelopes)verifyEnvelope(e,v.keys);console.log('MySQL-issued v2 old/new/replay envelopes verified');`, path).CombinedOutput() + if e != nil { + t.Fatalf("Node validation failed: %s", output) + } + t.Log(string(output)) +} diff --git a/backend/internal/httpapi/portal_test.go b/backend/internal/httpapi/portal_test.go new file mode 100644 index 0000000..7d7fa8c --- /dev/null +++ b/backend/internal/httpapi/portal_test.go @@ -0,0 +1,37 @@ +package httpapi + +import ( + "io" + "log/slog" + "net/http/httptest" + "strings" + "testing" +) + +func TestPortalCredentialCookieBoundary(t *testing.T) { + r := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil)))) + a := &BusinessAPI{} + r.POST("/api/v1/portal/snapshot", a.portalSnapshot) + for _, tc := range []struct { + body, path, origin string + want int + }{ + {"{}", "/api/v1/portal/snapshot", "", 400}, + {`{"instance_id":"00000000-0000-4000-8000-000000000001","secret":"wrong"}`, "/api/v1/portal/snapshot", "", 403}, + {"{}", "/api/v1/portal/snapshot?customer_id=2", "", 400}, + {"{}", "/api/v1/portal/snapshot", "https://evil.test", 403}, + } { + q := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)) + q.Header.Set("Cookie", "lp_session=administrator-cookie") + q.Header.Set("Content-Type", "application/json") + q.Header.Set("Origin", tc.origin) + w := httptest.NewRecorder() + r.ServeHTTP(w, q) + if w.Code != tc.want { + t.Fatalf("status %d want %d", w.Code, tc.want) + } + if len(w.Result().Cookies()) != 0 { + t.Fatal("portal issued cookie") + } + } +} diff --git a/backend/internal/httpapi/readiness.go b/backend/internal/httpapi/readiness.go new file mode 100644 index 0000000..1701f59 --- /dev/null +++ b/backend/internal/httpapi/readiness.go @@ -0,0 +1,47 @@ +package httpapi + +import ( + "context" + "database/sql" + "net/http" + "time" + + "github.com/gin-gonic/gin" +) + +const RequiredSchemaVersion = 10 + +func RegisterReadiness(r *gin.Engine, db *sql.DB) { + r.GET("/api/v1/health/ready", func(c *gin.Context) { + ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second) + defer cancel() + if err := CheckSchema(ctx, db); err != nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"status": "not_ready"}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ready"}) + }) +} + +func CheckSchema(ctx context.Context, db *sql.DB) error { + if db == nil { + return sql.ErrConnDone + } + var version uint64 + var dirty bool + rows, err := db.QueryContext(ctx, "SELECT version, dirty FROM schema_migrations") + if err != nil { + return err + } + defer rows.Close() + if !rows.Next() { + return sql.ErrNoRows + } + if err := rows.Scan(&version, &dirty); err != nil { + return err + } + if rows.Next() || rows.Err() != nil || version != RequiredSchemaVersion || dirty { + return sql.ErrNoRows + } + return nil +} diff --git a/backend/internal/httpapi/readiness_test.go b/backend/internal/httpapi/readiness_test.go new file mode 100644 index 0000000..957c90f --- /dev/null +++ b/backend/internal/httpapi/readiness_test.go @@ -0,0 +1,95 @@ +package httpapi + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "io" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +type readinessDriver struct{} +type readinessConn struct{ mode string } +type readinessRows struct { + mode string + read bool +} + +func (readinessDriver) Open(mode string) (driver.Conn, error) { return readinessConn{mode}, nil } +func (readinessConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("not supported") } +func (readinessConn) Close() error { return nil } +func (readinessConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") } +func (c readinessConn) QueryContext(context.Context, string, []driver.NamedValue) (driver.Rows, error) { + if c.mode == "unavailable" { + return nil, errors.New("private connection detail") + } + return &readinessRows{mode: c.mode}, nil +} +func (*readinessRows) Columns() []string { return []string{"version", "dirty"} } +func (*readinessRows) Close() error { return nil } +func (r *readinessRows) Next(values []driver.Value) error { + if r.read || r.mode == "empty" { + return io.EOF + } + r.read = true + version := int64(RequiredSchemaVersion) + if r.mode == "old" { + version-- + } + if r.mode == "future" { + version++ + } + values[0] = version + values[1] = r.mode == "dirty" + return nil +} +func init() { sql.Register("readiness-test", readinessDriver{}) } +func TestReadinessSchemaGate(t *testing.T) { + for _, mode := range []string{"ready", "old", "future", "dirty", "empty", "unavailable", "nil"} { + t.Run(mode, func(t *testing.T) { + var db *sql.DB + if mode != "nil" { + var err error + db, err = sql.Open("readiness-test", mode) + if err != nil { + t.Fatal(err) + } + defer db.Close() + } + r := gin.New() + RegisterReadiness(r, db) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/health/ready", nil)) + want := 503 + body := `{"status":"not_ready"}` + if mode == "ready" { + want = 200 + body = `{"status":"ready"}` + } + if w.Code != want || w.Body.String() != body { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + }) + } +} +func TestSecureSessionCookie(t *testing.T) { + t.Setenv("SESSION_COOKIE_SECURE", "true") + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", "http://localhost/", nil) + if !secureSessionCookie(c) { + t.Fatal("forced secure lost") + } + t.Setenv("SESSION_COOKIE_SECURE", "false") + c.Request.Header.Set("X-Forwarded-Proto", "https") + if secureSessionCookie(c) { + t.Fatal("untrusted header enabled cookie security") + } + c.Request = httptest.NewRequest("GET", "https://localhost/", nil) + if !secureSessionCookie(c) { + t.Fatal("direct TLS must be secure") + } +} diff --git a/backend/internal/httpapi/redis_limiter.go b/backend/internal/httpapi/redis_limiter.go new file mode 100644 index 0000000..8eb04dd --- /dev/null +++ b/backend/internal/httpapi/redis_limiter.go @@ -0,0 +1,84 @@ +package httpapi + +import ( + "context" + "fmt" + "net" + "os" + "path/filepath" + "strings" + "time" + + "github.com/redis/go-redis/v9" +) + +type EntryLimiter interface { + Allow(context.Context, string, int) (bool, error) +} +type RedisLimiter struct { + client *redis.Client + prefix string +} + +var entryLimitScript = redis.NewScript(` +local n = redis.call('INCR', KEYS[1]) +if n == 1 then redis.call('PEXPIRE', KEYS[1], 60000) end +if n > tonumber(ARGV[1]) then return 0 end +return 1 +`) + +func NewRedisLimiter(client *redis.Client, prefix string) *RedisLimiter { + return &RedisLimiter{client: client, prefix: prefix} +} +func (l *RedisLimiter) Allow(ctx context.Context, key string, limit int) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond) + defer cancel() + result, err := entryLimitScript.Run(ctx, l.client, []string{l.prefix + key}, limit).Int() + return result == 1, err +} + +// Redis errors never fall back to per-process counters. +func ConfigureEntryLimiter(ops *Operations, getenv func(string) string) (func(), error) { + mode := getenv("ENTRY_LIMIT_MODE") + if mode == "local-dev" { + return func() {}, nil + } + if mode != "" && mode != "redis" { + return nil, fmt.Errorf("invalid entry limit mode") + } + addr := getenv("ENTRY_REDIS_ADDR") + if addr == "" { + return nil, fmt.Errorf("Redis entry limiting required; local-dev must be explicitly opted into") + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, fmt.Errorf("invalid Redis address") + } + opts := &redis.Options{Addr: addr, Username: getenv("ENTRY_REDIS_USERNAME"), DialTimeout: 500 * time.Millisecond, ReadTimeout: 500 * time.Millisecond, WriteTimeout: 500 * time.Millisecond, MaxRetries: -1, ContextTimeoutEnabled: true} + if path := getenv("ENTRY_REDIS_PASSWORD_FILE"); path != "" { + if !filepath.IsAbs(path) { + return nil, fmt.Errorf("Redis password file must be absolute") + } + bytes, err := os.ReadFile(path) + if err != nil || len(bytes) == 0 || len(bytes) > 4096 { + return nil, fmt.Errorf("invalid Redis password file") + } + opts.Password = strings.TrimSpace(string(bytes)) + } + // Current profile permits only numeric loopback/private IP transport. Remote TLS remains a release gate. + ip := net.ParseIP(host) + if ip == nil || (!ip.IsLoopback() && !ip.IsPrivate()) { + return nil, fmt.Errorf("Redis must use a numeric private or loopback IP") + } + client := redis.NewClient(opts) + prefix := getenv("ENTRY_REDIS_NAMESPACE") + if prefix == "" { + prefix = "license-platform:entry:" + } + if len(prefix) > 100 { + client.Close() + return nil, fmt.Errorf("invalid Redis namespace") + } + ops.limiter = NewRedisLimiter(client, prefix) + return func() { client.Close() }, nil +} diff --git a/backend/internal/httpapi/redis_limiter_test.go b/backend/internal/httpapi/redis_limiter_test.go new file mode 100644 index 0000000..48efc68 --- /dev/null +++ b/backend/internal/httpapi/redis_limiter_test.go @@ -0,0 +1,83 @@ +package httpapi + +import ( + "context" + "fmt" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + "time" +) + +func TestRedisEntryIntegration(t *testing.T) { + addr := os.Getenv("ENTRY_REDIS_TEST_ADDR") + if addr == "" { + t.Skip("isolated Redis required") + } + prefix := fmt.Sprintf("test:entry:%d:", time.Now().UnixNano()) + clients := []*redis.Client{redis.NewClient(&redis.Options{Addr: addr}), redis.NewClient(&redis.Options{Addr: addr})} + for _, c := range clients { + defer c.Close() + if err := c.Ping(context.Background()).Err(); err != nil { + t.Fatal("isolated Redis unavailable") + } + } + servers := make([]*httptest.Server, 2) + calls := 0 + for i := range servers { + ops := NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))) + ops.limiter = NewRedisLimiter(clients[i], prefix) + r := NewOperationalRouter(ops) + r.POST("/api/v1/auth/login", func(c *gin.Context) { calls++; c.Status(401) }) + servers[i] = httptest.NewServer(r) + defer servers[i].Close() + } + for i := 0; i < 11; i++ { + req, _ := http.NewRequest("POST", servers[i%2].URL+"/api/v1/auth/login", nil) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + want := 401 + if i == 10 { + want = 429 + } + if res.StatusCode != want { + t.Fatal(i, res.StatusCode) + } + } + if calls != 10 { + t.Fatal(calls) + } + clients[0].Close() + res, err := http.Post(servers[0].URL+"/api/v1/auth/login", "application/json", nil) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != 503 || calls != 10 { + t.Fatal("Redis failure must block handler", res.StatusCode, calls) + } +} +func TestEntryModeRequiresExplicitDevelopment(t *testing.T) { + ops := NewOperations(slog.Default()) + if _, err := ConfigureEntryLimiter(ops, func(string) string { return "" }); err == nil { + t.Fatal("implicit fallback") + } + close, err := ConfigureEntryLimiter(ops, func(k string) string { + if k == "ENTRY_LIMIT_MODE" { + return "local-dev" + } + return "" + }) + if err != nil { + t.Fatal(err) + } + close() +} diff --git a/backend/internal/httpapi/releases_list.go b/backend/internal/httpapi/releases_list.go new file mode 100644 index 0000000..cc90b82 --- /dev/null +++ b/backend/internal/httpapi/releases_list.go @@ -0,0 +1,42 @@ +package httpapi + +import ( + "github.com/gin-gonic/gin" + "strconv" +) + +func (a *BusinessAPI) listReleases(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + apiError(c, 400, "invalid_request", "产品无效") + return + } + p, size := page(c) + var total int + if err = a.db.QueryRowContext(c, "SELECT COUNT(*) FROM product_releases WHERE product_id=?", id).Scan(&total); err != nil { + apiError(c, 500, "internal_error", "加载失败") + return + } + rows, err := a.db.QueryContext(c, "SELECT id,version,sha256,size_bytes,published FROM product_releases WHERE product_id=? ORDER BY id DESC LIMIT ? OFFSET ?", id, size, (p-1)*size) + if err != nil { + apiError(c, 500, "internal_error", "加载失败") + return + } + defer rows.Close() + data := []gin.H{} + for rows.Next() { + var rid, n uint64 + var version, digest string + var published bool + if err = rows.Scan(&rid, &version, &digest, &n, &published); err != nil { + apiError(c, 500, "internal_error", "加载失败") + return + } + data = append(data, gin.H{"id": rid, "version": version, "sha256": digest, "size_bytes": n, "published": published}) + } + if rows.Err() != nil { + apiError(c, 500, "internal_error", "加载失败") + return + } + c.JSON(200, gin.H{"data": data, "meta": gin.H{"total": total, "page": p, "page_size": size}}) +} diff --git a/backend/internal/httpapi/router.go b/backend/internal/httpapi/router.go index 1457a56..460015b 100644 --- a/backend/internal/httpapi/router.go +++ b/backend/internal/httpapi/router.go @@ -1,14 +1,22 @@ package httpapi import ( + "log/slog" "net/http" + "os" "github.com/gin-gonic/gin" ) func NewRouter() *gin.Engine { + return NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(os.Stdout, nil)))) +} +func NewOperationalRouter(ops *Operations) *gin.Engine { + gin.SetMode(gin.ReleaseMode) r := gin.New() - r.Use(gin.Logger(), gin.Recovery()) + _ = r.SetTrustedProxies(nil) + r.Use(ops.Middleware()) + r.NoRoute(func(c *gin.Context) { apiError(c, 404, "not_found", "Not found") }) r.GET("/api/v1/health/live", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) }) diff --git a/backend/internal/httpapi/router_test.go b/backend/internal/httpapi/router_test.go index a40c0e9..fbb6165 100644 --- a/backend/internal/httpapi/router_test.go +++ b/backend/internal/httpapi/router_test.go @@ -13,7 +13,9 @@ func TestLiveness(t *testing.T) { if w.Code != http.StatusOK { t.Fatalf("status = %d, want 200", w.Code) } - var body struct{ Status string `json:"status"` } + var body struct { + Status string `json:"status"` + } if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Status != "ok" { t.Fatalf("body = %q, err = %v", w.Body.String(), err) } diff --git a/backend/internal/httpapi/server.go b/backend/internal/httpapi/server.go new file mode 100644 index 0000000..675c827 --- /dev/null +++ b/backend/internal/httpapi/server.go @@ -0,0 +1,42 @@ +package httpapi + +import ( + "context" + "errors" + "net" + "net/http" + "time" +) + +func Serve(ctx context.Context, server *http.Server, shutdownTimeout time.Duration) error { + listener, err := net.Listen("tcp", server.Addr) + if err != nil { + return err + } + return serveListener(ctx, server, listener, shutdownTimeout) +} + +func serveListener(ctx context.Context, server *http.Server, listener net.Listener, timeout time.Duration) error { + result := make(chan error, 1) + go func() { result <- server.Serve(listener) }() + select { + case err := <-result: + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err + case <-ctx.Done(): + shutdownCtx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if err := server.Shutdown(shutdownCtx); err != nil { + _ = server.Close() + <-result + return err + } + err := <-result + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err + } +} diff --git a/backend/internal/httpapi/server_test.go b/backend/internal/httpapi/server_test.go new file mode 100644 index 0000000..4e85672 --- /dev/null +++ b/backend/internal/httpapi/server_test.go @@ -0,0 +1,105 @@ +package httpapi + +import ( + "context" + "errors" + "net" + "net/http" + "testing" + "time" +) + +func TestShutdown(t *testing.T) { + for _, graceful := range []bool{true, false} { + name := "timeout" + if graceful { + name = "drain" + } + t.Run(name, func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + started, release := make(chan struct{}), make(chan struct{}) + defer close(release) + handlerDone := make(chan struct{}) + server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + defer close(handlerDone) + select { + case <-release: + case <-r.Context().Done(): + } + w.WriteHeader(http.StatusNoContent) + })} + defer server.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + finished := make(chan error, 1) + go func() { finished <- serveListener(ctx, server, listener, 150*time.Millisecond) }() + requested := make(chan error, 1) + go func() { + client := &http.Client{Timeout: 3 * time.Second} + response, err := client.Get("http://" + listener.Addr().String()) + if err == nil { + response.Body.Close() + if response.StatusCode != http.StatusNoContent { + err = errors.New("unexpected status") + } + } + requested <- err + }() + select { + case <-started: + case <-time.After(3 * time.Second): + t.Fatal("request did not start") + } + cancel() + if graceful { + select { + case err := <-finished: + t.Fatalf("exited with active request: %v", err) + case <-time.After(20 * time.Millisecond): + } + release <- struct{}{} + } + select { + case err := <-finished: + if graceful && err != nil { + t.Fatal(err) + } + if !graceful && !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline: %v", err) + } + case <-time.After(3 * time.Second): + t.Fatal("shutdown did not finish") + } + select { + case err := <-requested: + if graceful && err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("request did not finish") + } + select { + case <-handlerDone: + case <-time.After(3 * time.Second): + t.Fatal("handler did not exit") + } + }) + } +} + +func TestServeListenFailure(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + err = Serve(context.Background(), &http.Server{Addr: listener.Addr().String()}, time.Second) + if err == nil { + t.Fatal("expected address in use error") + } +} diff --git a/backend/internal/httpapi/signing_restart_test.go b/backend/internal/httpapi/signing_restart_test.go new file mode 100644 index 0000000..a7cf573 --- /dev/null +++ b/backend/internal/httpapi/signing_restart_test.go @@ -0,0 +1,178 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/json" + "encoding/pem" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func TestSigningFileAPIRestart(t *testing.T) { + dsn := os.Getenv("SIGNING_RESTART_TEST_DSN") + if dsn == "" { + t.Skip("isolated clean008 MySQL required") + } + // os.MkdirTemp default is outside the repository; never persist test private material in session data. + dir, err := os.MkdirTemp("", "license-protected-restart-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + if runtime.GOOS == "windows" { + user := os.Getenv("USERNAME") + if user == "" { + t.Fatal("user ACL required") + } + if err := exec.Command("icacls", dir, "/inheritance:r", "/grant:r", user+":(OI)(CI)F").Run(); err != nil { + t.Fatal("cannot protect key directory") + } + } else { + if err := os.Chmod(dir, 0700); err != nil { + t.Fatal(err) + } + } + key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + der, _ := x509.MarshalECPrivateKey(key) + keyPath := filepath.Join(dir, "signing.pem") + if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}), 0600); err != nil { + t.Fatal(err) + } + bin := filepath.Join(dir, "api") + if runtime.GOOS == "windows" { + bin += ".exe" + } + build := exec.Command("go", "build", "-o", bin, "../../cmd/server") + if err := build.Run(); err != nil { + t.Fatal("server build failed") + } + now := time.Now().UTC().Truncate(time.Second) + payloads := []string{canonicalCertificatePayload("license-v1", "00000000-0000-4000-8000-000000000001", 1, 2, 3, now, now.Add(time.Hour)), canonicalLease(leasePayload{Version: "lease-v1", InstanceID: "00000000-0000-4000-8000-000000000001", State: "active", ServerTime: now.Format(time.RFC3339), EntitlementExpiresAt: now.Add(time.Hour).Format(time.RFC3339), LeaseExpiresAt: now.Add(time.Hour).Format(time.RFC3339)})} + signatures := make([][]byte, 2) + for i, p := range payloads { + sum := sha256.Sum256([]byte(p)) + signatures[i], err = ecdsa.SignASN1(rand.Reader, key, sum[:]) + if err != nil { + t.Fatal(err) + } + } + var prior string + for iteration := 0; iteration < 2; iteration++ { + listener, _ := net.Listen("tcp", "127.0.0.1:0") + addr := listener.Addr().String() + listener.Close() + monitor, _ := net.Listen("tcp", "127.0.0.1:0") + monitorAddr := monitor.Addr().String() + monitor.Close() + cmd := exec.Command(bin) + cmd.Env = append(os.Environ(), "HTTP_ADDR="+addr, "MYSQL_DSN="+dsn, "LICENSE_SIGNING_PRIVATE_KEY_PEM=", "LICENSE_SIGNING_PRIVATE_KEY_FILE="+keyPath, "METRICS_ADDR="+monitorAddr, "ENTRY_LIMIT_MODE=redis", "ENTRY_REDIS_ADDR="+os.Getenv("ENTRY_REDIS_TEST_ADDR")) + // Discard child output: neither private material nor connection errors become artifacts. + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + func() { + defer func() { cmd.Process.Kill(); cmd.Wait() }() + client := &http.Client{Timeout: time.Second} + var res *http.Response + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); { + res, err = client.Get("http://" + addr + "/api/v1/activation/public-key") + if err == nil { + break + } + time.Sleep(100 * time.Millisecond) + } + if err != nil { + t.Fatal("isolated API unavailable") + } + defer res.Body.Close() + var out struct { + Data struct { + PublicKey string `json:"public_key_pem"` + } + } + if err := json.NewDecoder(res.Body).Decode(&out); err != nil { + t.Fatal(err) + } + if iteration > 0 && out.Data.PublicKey != prior { + t.Fatal("public key changed across restart") + } + prior = out.Data.PublicKey + block, _ := pem.Decode([]byte(prior)) + if block == nil { + t.Fatal("no public key") + } + parsed, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + t.Fatal(err) + } + pub := parsed.(*ecdsa.PublicKey) + for i, p := range payloads { + sum := sha256.Sum256([]byte(p)) + if !ecdsa.VerifyASN1(pub, sum[:], signatures[i]) { + t.Fatal("old certificate/lease signature invalid after restart") + } + } + for _, p := range []string{"/api/v1/health/ready", "/metrics"} { + r, e := client.Get("http://" + addr + p) + if e != nil { + t.Fatal(e) + } + r.Body.Close() + if r.StatusCode != 404 { + t.Fatal("internal route publicly exposed") + } + } + r, e := client.Get("http://" + monitorAddr + "/api/v1/health/ready") + if e != nil { + t.Fatal(e) + } + r.Body.Close() + if r.StatusCode != 200 { + t.Fatal("internal readiness", r.StatusCode) + } + r, e = client.Get("http://" + monitorAddr + "/metrics") + if e != nil { + t.Fatal(e) + } + r.Body.Close() + if r.StatusCode != 200 { + t.Fatal("internal metrics", r.StatusCode) + } + for _, tc := range []struct { + path, body, origin string + status int + }{ + {"/api/v1/products", "", "", 401}, + {"/api/v1/auth/login", "{}", "https://evil.example", 403}, + {"/api/v1/auth/login", strings.Repeat("x", 65537), "", 413}, + } { + q, _ := http.NewRequest("POST", "http://"+addr+tc.path, strings.NewReader(tc.body)) + q.Header.Set("Origin", tc.origin) + q.Header.Set("Content-Type", "application/json") + response, e := client.Do(q) + if e != nil { + t.Fatal(e) + } + response.Body.Close() + if response.StatusCode != tc.status || response.Header.Get("X-Request-ID") == "" { + t.Fatal("new API security smoke", response.StatusCode) + } + } + t.Logf("isolated API start %d: public key stable, old canonical signatures valid, ready/metrics internal only", iteration+1) + }() + } +} diff --git a/backend/internal/httpapi/tls_boundary_test.go b/backend/internal/httpapi/tls_boundary_test.go new file mode 100644 index 0000000..c90aec4 --- /dev/null +++ b/backend/internal/httpapi/tls_boundary_test.go @@ -0,0 +1,50 @@ +package httpapi + +import ( + "github.com/gin-gonic/gin" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestTLSOriginCookieBoundary(t *testing.T) { + r := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil)))) + r.POST("/write", func(c *gin.Context) { + c.SetSameSite(http.SameSiteStrictMode) + c.SetCookie("test_session", "not-a-real-session", 10, "/", "", secureSessionCookie(c), true) + c.JSON(200, gin.H{"ip": c.ClientIP()}) + }) + s := httptest.NewTLSServer(r) + defer s.Close() + client := s.Client() + for _, tc := range []struct { + origin string + status int + }{{s.URL, 200}, {"https://foreign.invalid", 403}, {strings.Replace(s.URL, "https:", "http:", 1), 403}} { + q, _ := http.NewRequest("POST", s.URL+"/write", strings.NewReader("{}")) + q.Header.Set("Origin", tc.origin) + q.Header.Set("X-Forwarded-For", "198.51.100.1") + q.Header.Set("X-Forwarded-Proto", "https") + resp, err := client.Do(q) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != tc.status { + t.Fatal(resp.StatusCode) + } + if tc.status == 200 { + cookies := resp.Cookies() + if len(cookies) != 1 || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode { + t.Fatal("unsafe cookie") + } + if strings.Contains(string(body), "198.51.100.1") { + t.Fatal("untrusted forwarded IP accepted") + } + } + } +} diff --git a/backend/internal/migrations/runner.go b/backend/internal/migrations/runner.go new file mode 100644 index 0000000..6abf689 --- /dev/null +++ b/backend/internal/migrations/runner.go @@ -0,0 +1,89 @@ +package migrations + +import ( + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "strconv" + + "github.com/golang-migrate/migrate/v4" + _ "github.com/golang-migrate/migrate/v4/database/mysql" + _ "github.com/golang-migrate/migrate/v4/source/file" +) + +var ErrDirtyDatabase = errors.New("database migration is dirty; inspect and force the last known good version") + +type Runner struct { + migrate *migrate.Migrate +} + +func Open(dsn, directory string) (*Runner, error) { + if dsn == "" { + return nil, errors.New("migration DSN is required") + } + absolute, err := filepath.Abs(directory) + if err != nil { + return nil, fmt.Errorf("resolve migration directory: %w", err) + } + if _, err := os.Stat(absolute); err != nil { + return nil, fmt.Errorf("migration directory: %w", err) + } + sourceURL := (&url.URL{Scheme: "file", Path: filepath.ToSlash(absolute)}).String() + m, err := migrate.New(sourceURL, dsn) + if err != nil { + return nil, fmt.Errorf("open migration database: %w", err) + } + return &Runner{migrate: m}, nil +} + +func (r *Runner) Close() error { + sourceErr, databaseErr := r.migrate.Close() + if sourceErr != nil { + return sourceErr + } + return databaseErr +} + +func (r *Runner) Up() error { + if err := r.migrate.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { + return r.wrap(err) + } + return nil +} + +func (r *Runner) Down() error { + if err := r.migrate.Down(); err != nil && !errors.Is(err, migrate.ErrNoChange) { + return r.wrap(err) + } + return nil +} + +func (r *Runner) Version() (uint, bool, error) { + return r.migrate.Version() +} + +// Force is deliberately explicit: it only repairs migration metadata after an +// operator has inspected the failed DDL and selected a known-good version. +func (r *Runner) Force(version int) error { + if version < -1 { + return fmt.Errorf("migration version must be >= -1: %d", version) + } + return r.migrate.Force(version) +} + +func (r *Runner) wrap(err error) error { + if _, dirty, versionErr := r.migrate.Version(); versionErr == nil && dirty { + return fmt.Errorf("%w: version=%s: %v", ErrDirtyDatabase, strconv.FormatUint(uint64(versionFrom(r.migrate)), 10), err) + } + return err +} + +func versionFrom(m *migrate.Migrate) uint { + version, _, err := m.Version() + if err != nil { + return 0 + } + return version +} diff --git a/backend/internal/migrations/v6_integration_test.go b/backend/internal/migrations/v6_integration_test.go new file mode 100644 index 0000000..bc3436b --- /dev/null +++ b/backend/internal/migrations/v6_integration_test.go @@ -0,0 +1,83 @@ +package migrations + +import ( + "database/sql" + "os" + "testing" + + migrate "github.com/golang-migrate/migrate/v4" + _ "github.com/golang-migrate/migrate/v4/database/mysql" + _ "github.com/golang-migrate/migrate/v4/source/file" + "net/url" + "path/filepath" +) + +func TestV6Rehearsal(t *testing.T) { + dsn := os.Getenv("MIGRATION_REHEARSAL_DSN") + if dsn == "" { + t.Skip("isolated rehearsal DSN required") + } + directory, err := filepath.Abs("../../migrations") + if err != nil { + t.Fatal(err) + } + m, err := migrate.New((&url.URL{Scheme: "file", Path: filepath.ToSlash(directory)}).String(), "mysql://"+dsn+"?multiStatements=true") + if err != nil { + t.Fatal(err) + } + defer m.Close() + if err = m.Migrate(5); err != nil { + t.Fatal(err) + } + db, err := sql.Open("mysql", dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + statements := []string{ + "INSERT INTO admins(id,email,password_hash) VALUES(1,'rehearsal@example.invalid','not-a-login-hash')", + "INSERT INTO customers(id,name,contact_email) VALUES(1,'rehearsal','rehearsal@example.invalid')", + "INSERT INTO products(id,code,name,description) VALUES(1,'rehearsal','rehearsal','')", + "INSERT INTO licenses(id,license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(1,REPEAT('a',32),1,1,UTC_TIMESTAMP(),DATE_ADD(UTC_TIMESTAMP(),INTERVAL 1 YEAR),'rehearsal',1)", + "INSERT INTO license_instances(id,instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(1,'00000000-0000-4000-8000-000000000001',1,1,1,UNHEX(REPEAT('00',32)),1)", + "INSERT INTO activation_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(1,1,'rehearsal',UNHEX(REPEAT('00',32)),JSON_OBJECT('fixture',true))", + "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(1,'fixture','license_instance',1,JSON_OBJECT('fixture',true))", + } + for _, s := range statements { + if _, err = db.Exec(s); err != nil { + t.Fatal(err) + } + } + if err = m.Migrate(6); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("INSERT INTO heartbeat_operations(instance_id,idempotency_key,request_fingerprint,response,state) VALUES(1,'fixture',UNHEX(REPEAT('00',32)),JSON_OBJECT('fixture',true),'active')"); err != nil { + t.Fatal(err) + } + if _, err = db.Exec("INSERT INTO instance_state_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(1,1,'fixture',UNHEX(REPEAT('00',32)),JSON_OBJECT('fixture',true))"); err != nil { + t.Fatal(err) + } + if err = m.Steps(-1); err != nil { + t.Fatal(err) + } + for _, table := range []string{"admins", "customers", "products", "licenses", "license_instances", "activation_operations", "audit_events"} { + var n int + if err = db.QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 1 { + t.Fatalf("old table %s n=%d err=%v", table, n, err) + } + } + if err = m.Steps(1); err != nil { + t.Fatal(err) + } + for _, table := range []string{"heartbeat_operations", "instance_state_operations"} { + var n int + if err = db.QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 0 { + t.Fatalf("v6 table %s n=%d err=%v", table, n, err) + } + } + v, dirty, err := m.Version() + if err != nil || v != 6 || dirty { + t.Fatalf("version=%d dirty=%v err=%v", v, dirty, err) + } + t.Log("005 -> 006 -> 005 -> 006 clean; seven pre-v6 fixture rows preserved; v6 operation history and lease/freeze fields intentionally removed by down") +} diff --git a/backend/migrations/000001_core.down.sql b/backend/migrations/000001_core.down.sql new file mode 100644 index 0000000..804e31f --- /dev/null +++ b/backend/migrations/000001_core.down.sql @@ -0,0 +1,4 @@ +DROP TABLE IF EXISTS sessions; +DROP TABLE IF EXISTS products; +DROP TABLE IF EXISTS customers; +DROP TABLE IF EXISTS admins; diff --git a/backend/migrations/000001_core.up.sql b/backend/migrations/000001_core.up.sql new file mode 100644 index 0000000..47aa6e1 --- /dev/null +++ b/backend/migrations/000001_core.up.sql @@ -0,0 +1,42 @@ +CREATE TABLE admins ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + email VARCHAR(190) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + role VARCHAR(32) NOT NULL DEFAULT 'admin', + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), UNIQUE KEY uq_admins_email (email) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE sessions ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + admin_id BIGINT UNSIGNED NOT NULL, + token_hash BINARY(32) NOT NULL, + expires_at TIMESTAMP(6) NOT NULL, + revoked_at TIMESTAMP(6) NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), UNIQUE KEY uq_sessions_token_hash (token_hash), + KEY idx_sessions_admin (admin_id), KEY idx_sessions_expiry (expires_at), + CONSTRAINT fk_sessions_admin FOREIGN KEY (admin_id) REFERENCES admins(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE customers ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(190) NOT NULL, + contact_email VARCHAR(190) NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'active', + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), KEY idx_customers_status (status), KEY idx_customers_name (name) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE products ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + code VARCHAR(64) NOT NULL, + name VARCHAR(190) NOT NULL, + description TEXT NOT NULL, + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), UNIQUE KEY uq_products_code (code), KEY idx_products_active (active) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000002_licenses.down.sql b/backend/migrations/000002_licenses.down.sql new file mode 100644 index 0000000..1df0a31 --- /dev/null +++ b/backend/migrations/000002_licenses.down.sql @@ -0,0 +1,2 @@ +DROP TABLE IF EXISTS audit_events; +DROP TABLE IF EXISTS licenses; diff --git a/backend/migrations/000002_licenses.up.sql b/backend/migrations/000002_licenses.up.sql new file mode 100644 index 0000000..207effb --- /dev/null +++ b/backend/migrations/000002_licenses.up.sql @@ -0,0 +1,32 @@ +CREATE TABLE licenses ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + license_key CHAR(32) NOT NULL, + customer_id BIGINT UNSIGNED NOT NULL, + product_id BIGINT UNSIGNED NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'active', + starts_at TIMESTAMP(6) NOT NULL, + expires_at TIMESTAMP(6) NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + issued_by BIGINT UNSIGNED NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + revoked_at TIMESTAMP(6) NULL, + PRIMARY KEY (id), + UNIQUE KEY uq_licenses_key (license_key), + UNIQUE KEY uq_licenses_idempotency (issued_by, idempotency_key), + KEY idx_licenses_customer (customer_id), KEY idx_licenses_product (product_id), KEY idx_licenses_status (status), + CONSTRAINT fk_licenses_customer FOREIGN KEY (customer_id) REFERENCES customers(id), + CONSTRAINT fk_licenses_product FOREIGN KEY (product_id) REFERENCES products(id), + CONSTRAINT fk_licenses_admin FOREIGN KEY (issued_by) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE audit_events ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + actor_admin_id BIGINT UNSIGNED NOT NULL, + action VARCHAR(64) NOT NULL, + resource_type VARCHAR(64) NOT NULL, + resource_id BIGINT UNSIGNED NOT NULL, + details JSON NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), KEY idx_audit_resource (resource_type, resource_id), KEY idx_audit_actor (actor_admin_id), + CONSTRAINT fk_audit_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000003_license_operations.down.sql b/backend/migrations/000003_license_operations.down.sql new file mode 100644 index 0000000..153b93a --- /dev/null +++ b/backend/migrations/000003_license_operations.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS license_operations; diff --git a/backend/migrations/000003_license_operations.up.sql b/backend/migrations/000003_license_operations.up.sql new file mode 100644 index 0000000..ce9f173 --- /dev/null +++ b/backend/migrations/000003_license_operations.up.sql @@ -0,0 +1,14 @@ +CREATE TABLE license_operations ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + license_id BIGINT UNSIGNED NOT NULL, + actor_admin_id BIGINT UNSIGNED NOT NULL, + operation VARCHAR(32) NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + request_fingerprint BINARY(32) NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + UNIQUE KEY uq_license_operation_key (actor_admin_id, operation, idempotency_key), + KEY idx_license_operations_license (license_id), + CONSTRAINT fk_license_operations_license FOREIGN KEY (license_id) REFERENCES licenses(id), + CONSTRAINT fk_license_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000004_orders.down.sql b/backend/migrations/000004_orders.down.sql new file mode 100644 index 0000000..cfeccf6 --- /dev/null +++ b/backend/migrations/000004_orders.down.sql @@ -0,0 +1,2 @@ +DROP TABLE order_operations; +DROP TABLE offline_orders; diff --git a/backend/migrations/000004_orders.up.sql b/backend/migrations/000004_orders.up.sql new file mode 100644 index 0000000..2665462 --- /dev/null +++ b/backend/migrations/000004_orders.up.sql @@ -0,0 +1,39 @@ +CREATE TABLE offline_orders ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + order_no CHAR(32) NOT NULL, + customer_id BIGINT UNSIGNED NOT NULL, + product_id BIGINT UNSIGNED NOT NULL, + amount_cents BIGINT UNSIGNED NOT NULL, + currency CHAR(3) NOT NULL DEFAULT 'CNY', + status VARCHAR(32) NOT NULL DEFAULT 'pending_payment', + payment_reference VARCHAR(190) NULL, + paid_at TIMESTAMP(6) NULL, + paid_by BIGINT UNSIGNED NULL, + issued_license_id BIGINT UNSIGNED NULL, + created_by BIGINT UNSIGNED NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), UNIQUE KEY uq_offline_orders_no (order_no), + UNIQUE KEY uq_offline_orders_license (issued_license_id), + KEY idx_offline_orders_customer (customer_id), KEY idx_offline_orders_status (status), + CONSTRAINT fk_offline_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id), + CONSTRAINT fk_offline_orders_product FOREIGN KEY (product_id) REFERENCES products(id), + CONSTRAINT fk_offline_orders_license FOREIGN KEY (issued_license_id) REFERENCES licenses(id), + CONSTRAINT fk_offline_orders_admin FOREIGN KEY (created_by) REFERENCES admins(id), + CONSTRAINT fk_offline_orders_paid_by FOREIGN KEY (paid_by) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE order_operations ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + order_id BIGINT UNSIGNED NOT NULL, + actor_admin_id BIGINT UNSIGNED NOT NULL, + operation VARCHAR(32) NOT NULL, + idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + request_fingerprint BINARY(32) NOT NULL, + response JSON NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + UNIQUE KEY uq_order_operations_key (actor_admin_id, operation, idempotency_key), + CONSTRAINT fk_order_operations_order FOREIGN KEY (order_id) REFERENCES offline_orders(id), + CONSTRAINT fk_order_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000005_activation.down.sql b/backend/migrations/000005_activation.down.sql new file mode 100644 index 0000000..19927c1 --- /dev/null +++ b/backend/migrations/000005_activation.down.sql @@ -0,0 +1,2 @@ +DROP TABLE IF EXISTS activation_operations; +DROP TABLE IF EXISTS license_instances; diff --git a/backend/migrations/000005_activation.up.sql b/backend/migrations/000005_activation.up.sql new file mode 100644 index 0000000..df13384 --- /dev/null +++ b/backend/migrations/000005_activation.up.sql @@ -0,0 +1,39 @@ +CREATE TABLE license_instances ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + instance_id CHAR(36) NOT NULL, + license_id BIGINT UNSIGNED NOT NULL, + customer_id BIGINT UNSIGNED NOT NULL, + product_id BIGINT UNSIGNED NOT NULL, + secret_hash BINARY(32) NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'provisioned', + activated_at TIMESTAMP(6) NULL, + certificate_version VARCHAR(32) NULL, + certificate_payload JSON NULL, + certificate_signature TEXT NULL, + created_by BIGINT UNSIGNED NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + UNIQUE KEY uq_license_instances_instance (instance_id), + UNIQUE KEY uq_license_instances_license (license_id), + KEY idx_license_instances_customer (customer_id), + KEY idx_license_instances_product (product_id), + CONSTRAINT fk_license_instances_license FOREIGN KEY (license_id) REFERENCES licenses(id), + CONSTRAINT fk_license_instances_customer FOREIGN KEY (customer_id) REFERENCES customers(id), + CONSTRAINT fk_license_instances_product FOREIGN KEY (product_id) REFERENCES products(id), + CONSTRAINT fk_license_instances_admin FOREIGN KEY (created_by) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE activation_operations ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + instance_id BIGINT UNSIGNED NOT NULL, + actor_admin_id BIGINT UNSIGNED NOT NULL, + idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + request_fingerprint BINARY(32) NOT NULL, + response JSON NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + UNIQUE KEY uq_activation_operations_key (instance_id, idempotency_key), + CONSTRAINT fk_activation_operations_instance FOREIGN KEY (instance_id) REFERENCES license_instances(id), + CONSTRAINT fk_activation_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000006_heartbeat_lease.down.sql b/backend/migrations/000006_heartbeat_lease.down.sql new file mode 100644 index 0000000..d1cdddf --- /dev/null +++ b/backend/migrations/000006_heartbeat_lease.down.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS instance_state_operations; +DROP TABLE IF EXISTS heartbeat_operations; +ALTER TABLE license_instances + DROP KEY idx_license_instances_last_seen, + DROP KEY idx_license_instances_lease, + DROP COLUMN freeze_state, + DROP COLUMN lease_expires_at, + DROP COLUMN last_seen_at, + DROP COLUMN client_seen_at, + DROP COLUMN observed_state; diff --git a/backend/migrations/000006_heartbeat_lease.up.sql b/backend/migrations/000006_heartbeat_lease.up.sql new file mode 100644 index 0000000..69af5ba --- /dev/null +++ b/backend/migrations/000006_heartbeat_lease.up.sql @@ -0,0 +1,35 @@ +ALTER TABLE license_instances + ADD COLUMN last_seen_at TIMESTAMP(6) NULL, + ADD COLUMN client_seen_at TIMESTAMP(6) NULL, + ADD COLUMN observed_state VARCHAR(32) NOT NULL DEFAULT 'unknown', + ADD COLUMN lease_expires_at TIMESTAMP(6) NULL, + ADD COLUMN freeze_state VARCHAR(32) NOT NULL DEFAULT 'none', + ADD KEY idx_license_instances_last_seen (last_seen_at), + ADD KEY idx_license_instances_lease (lease_expires_at); + +CREATE TABLE heartbeat_operations ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + instance_id BIGINT UNSIGNED NOT NULL, + idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + request_fingerprint BINARY(32) NOT NULL, + response JSON NOT NULL, + state VARCHAR(32) NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + UNIQUE KEY uq_heartbeat_operations_key (instance_id, idempotency_key), + CONSTRAINT fk_heartbeat_operations_instance FOREIGN KEY (instance_id) REFERENCES license_instances(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +CREATE TABLE instance_state_operations ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + instance_id BIGINT UNSIGNED NOT NULL, + actor_admin_id BIGINT UNSIGNED NOT NULL, + idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + request_fingerprint BINARY(32) NOT NULL, + response JSON NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + UNIQUE KEY uq_instance_state_operations_key (actor_admin_id,idempotency_key), + CONSTRAINT fk_instance_state_operations_instance FOREIGN KEY (instance_id) REFERENCES license_instances(id), + CONSTRAINT fk_instance_state_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000007_local_releases.down.sql b/backend/migrations/000007_local_releases.down.sql new file mode 100644 index 0000000..b6f46d3 --- /dev/null +++ b/backend/migrations/000007_local_releases.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS product_releases; diff --git a/backend/migrations/000007_local_releases.up.sql b/backend/migrations/000007_local_releases.up.sql new file mode 100644 index 0000000..79dd846 --- /dev/null +++ b/backend/migrations/000007_local_releases.up.sql @@ -0,0 +1,15 @@ +CREATE TABLE product_releases ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + product_id BIGINT UNSIGNED NOT NULL, + version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + storage_key CHAR(68) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + size_bytes BIGINT UNSIGNED NOT NULL, + published BOOLEAN NOT NULL DEFAULT TRUE, + created_by BIGINT UNSIGNED NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY(id), + UNIQUE KEY uq_releases_version(product_id,version), + CONSTRAINT fk_release_product FOREIGN KEY(product_id) REFERENCES products(id), + CONSTRAINT fk_release_admin FOREIGN KEY(created_by) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/000008_package_objects.down.sql b/backend/migrations/000008_package_objects.down.sql new file mode 100644 index 0000000..51d7a4c --- /dev/null +++ b/backend/migrations/000008_package_objects.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS package_objects; diff --git a/backend/migrations/000008_package_objects.up.sql b/backend/migrations/000008_package_objects.up.sql new file mode 100644 index 0000000..aec0098 --- /dev/null +++ b/backend/migrations/000008_package_objects.up.sql @@ -0,0 +1,5 @@ +CREATE TABLE package_objects ( + sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, + size_bytes BIGINT UNSIGNED NOT NULL +) ENGINE=InnoDB; +INSERT INTO package_objects(sha256,size_bytes) SELECT sha256,MAX(size_bytes) FROM product_releases GROUP BY sha256; diff --git a/backend/migrations/000009_admin_settings.down.sql b/backend/migrations/000009_admin_settings.down.sql new file mode 100644 index 0000000..8b1794e --- /dev/null +++ b/backend/migrations/000009_admin_settings.down.sql @@ -0,0 +1,2 @@ +DROP INDEX idx_audit_created_id ON audit_events; +DROP TABLE IF EXISTS system_settings; diff --git a/backend/migrations/000009_admin_settings.up.sql b/backend/migrations/000009_admin_settings.up.sql new file mode 100644 index 0000000..73afe16 --- /dev/null +++ b/backend/migrations/000009_admin_settings.up.sql @@ -0,0 +1,11 @@ +CREATE TABLE system_settings ( + id TINYINT UNSIGNED NOT NULL, + site_name VARCHAR(100) NOT NULL DEFAULT '授权管理平台', + support_email VARCHAR(254) NOT NULL DEFAULT '', + announcement TEXT NOT NULL, + updated_at TIMESTAMP(6) NULL, + PRIMARY KEY (id), + CONSTRAINT chk_system_settings_singleton CHECK (id = 1) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +INSERT INTO system_settings(id,announcement) VALUES(1,''); +CREATE INDEX idx_audit_created_id ON audit_events(created_at,id); diff --git a/backend/migrations/000010_admin_usernames.down.sql b/backend/migrations/000010_admin_usernames.down.sql new file mode 100644 index 0000000..c321ab0 --- /dev/null +++ b/backend/migrations/000010_admin_usernames.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE admins DROP INDEX uq_admins_username; +ALTER TABLE admins DROP COLUMN username; diff --git a/backend/migrations/000010_admin_usernames.up.sql b/backend/migrations/000010_admin_usernames.up.sql new file mode 100644 index 0000000..d38d0d2 --- /dev/null +++ b/backend/migrations/000010_admin_usernames.up.sql @@ -0,0 +1,4 @@ +ALTER TABLE admins ADD COLUMN username VARCHAR(32) NULL AFTER id; +UPDATE admins SET username=CONCAT('admin-', id) WHERE username IS NULL; +ALTER TABLE admins MODIFY COLUMN username VARCHAR(32) NOT NULL; +ALTER TABLE admins ADD UNIQUE KEY uq_admins_username (username); diff --git a/backend/migrations/README.md b/backend/migrations/README.md new file mode 100644 index 0000000..f6dec3f --- /dev/null +++ b/backend/migrations/README.md @@ -0,0 +1,29 @@ +# MySQL migration baseline + +Status: DEV schemas are implemented through version 8 (local releases and digest-object locking). Formal entitlement policy acceptance and seed data remain pending. Read-only verification on 2026-09-30: business license_platform is version=7 dirty=false; isolated license_download_260930 is version=8 dirty=false. No business database migration was executed during the deployment-delivery slice. + +## Version 007 to 008 + +007 stores release metadata; 008 adds package_objects digest rows used for SELECT FOR UPDATE serialization and backfills them from existing releases using MAX(size_bytes). Before applying 008, quiesce uploads, back up database and private files, and verify every digest has a single consistent size and an existing matching object; MAX is not an integrity check or repair. Explicit up must finish clean before using the new publication code. Historical migrations are unchanged. 008 down drops the lock inventory and must not be used while new upload handlers are running; 007 down destroys release metadata. Do not run either against business data without backup and approval. + +A file is linked into its digest path before the metadata/audit transaction commits. Ordinary publication failures remove only files linked by that request, preserving pre-existing shared digest objects. Commit acknowledgement failure retains content because commit may have succeeded. Crashes can leave temporary fragments or unreferenced digest files; SQL and filesystem are not one atomic transaction. Orphan reconciliation/automatic GC is NOT implemented. + +Future reconciliation must quiesce publishers or participate in the same digest locks, inventory product_releases/package_objects and private files, enforce a safety age window, recheck references immediately before quarantine, and verify checksums. Never remove a file based only on a missing row observed during an active upload or an uncertain commit. Keep quarantine recoverable and require reviewed deletion. U07 chunk/resume and crash cleanup remain open. + +Version 6 adds independent lease/last-seen fields and heartbeat/freeze operation records. It was explicitly applied to the dedicated MySQL integration database on 2026-09-30. Its down migration drops operation history and lease state; do not execute against existing business data without backup and approval. The v6 isolated down/up rehearsal is still pending. Startup never applies migrations. + +Use versioned pairs named `000001_description.up.sql` and `000001_description.down.sql`. Never edit an applied migration; add a new version. Seed permissions with stable unique codes, never commit an administrator password. SQL targets MySQL 8.0 with UTC timestamps and utf8mb4. + +MySQL DDL may commit implicitly. Do not assume a failed schema migration is transactionally reversible. Before release, run the chosen migration runner against an empty MySQL 8 database, test each down/up pair with fixtures, and record dirty-version recovery. Down migrations that remove business data require backup and explicit operator confirmation. + +The runner is `go run ./cmd/migrate` from `backend`. It accepts a golang-migrate MySQL URL such as `mysql://user:password@tcp(host:3306)/database?multiStatements=true` or `MIGRATION_DSN`. Supported actions are `up`, `down`, `version`, and explicit `force -version N` (flags must precede the action); `force` is only for an operator-reviewed dirty migration and never runs automatically. + +```text +go run ./cmd/migrate -dsn "$MIGRATION_DSN" up +go run ./cmd/migrate -dsn "$MIGRATION_DSN" version +go run ./cmd/migrate -dsn "$MIGRATION_DSN" -version 12 force +``` The server does not run migrations on startup. + +On 2026-09-30, a dedicated MySQL 8.0 container was used to verify an empty database up/down cycle and an intentionally invalid migration: failure left version 2 dirty, normal `up` was blocked, and explicit force to the last known-good version restored clean metadata. The probe migrations and container were removed after the test. Version 3 adds transactional license operation idempotency records for revoke/renew; it must be applied explicitly after version 2. No placeholder SQL is considered an executed business migration; formal entitlement schemas and CI database integration remain T04/T03 acceptance work. + +Schema 10 adds unique administrator usernames. Existing accounts become `admin-{id}` and retain their passwords; login requests must send `username` instead of `email`. Run migrations before starting the current server or `admin-init`. diff --git a/client/verify.mjs b/client/verify.mjs new file mode 100644 index 0000000..e9d6968 --- /dev/null +++ b/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/compose.yaml b/compose.yaml new file mode 100644 index 0000000..19dff35 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,100 @@ +# Local delivery rehearsal only. Not a production security profile. +name: license-platform-dev +services: + mysql: + image: mysql:8.0 + environment: + MYSQL_DATABASE: license_platform + MYSQL_USER: license_app + MYSQL_PASSWORD_FILE: /run/secrets/mysql_app + MYSQL_ROOT_PASSWORD_FILE: /run/secrets/mysql_root + secrets: [mysql_app, mysql_root] + volumes: [mysql_data:/var/lib/mysql] + networks: [private] + healthcheck: + test: [CMD-SHELL, 'MYSQL_PWD=$$(cat /run/secrets/mysql_app) mysql -h 127.0.0.1 -u license_app license_platform -e "SELECT 1" >/dev/null 2>&1'] + interval: 5s + timeout: 5s + retries: 30 + redis: + profiles: [cache] + image: redis:7-alpine + command: [redis-server, --save, '', --appendonly, 'no'] + networks: [private] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 5s + timeout: 3s + retries: 10 + api: + build: + context: . + dockerfile: deploy/Dockerfile.api + environment: + HTTP_ADDR: 0.0.0.0:18080 + HTTP_TRUSTED_PROXY_CIDRS: ${HTTP_TRUSTED_PROXY_CIDRS:-} + SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false} + MYSQL_PASSWORD_FILE: /run/secrets/mysql_app + LICENSE_SIGNING_PRIVATE_KEY_FILE: /run/secrets/signing_key + PACKAGE_STORAGE_ROOT: /srv/license-packages + GIN_MODE: release + METRICS_ADDR: 127.0.0.1:19090 + ENTRY_LIMIT_MODE: ${ENTRY_LIMIT_MODE:-redis} + ENTRY_REDIS_ADDR: ${ENTRY_REDIS_ADDR:-} + ENTRY_REDIS_NAMESPACE: ${ENTRY_REDIS_NAMESPACE:-license-platform:entry:} + secrets: [mysql_app, signing_key] + volumes: + - type: bind + source: ${PACKAGE_STORAGE_HOST:?Set an absolute trusted existing package directory} + target: /srv/license-packages + bind: + create_host_path: false + read_only: true + tmpfs: [/tmp] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + networks: [private] + depends_on: + mysql: {condition: service_healthy} + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:19090/api/v1/health/ready'] + interval: 5s + timeout: 3s + retries: 10 + migrate: + extends: api + profiles: [tools] + command: [/app/migrate, up] + healthcheck: {disable: true} + web: + build: + context: . + dockerfile: deploy/Dockerfile.web + ports: ['127.0.0.1:18083:8080'] + volumes: + - type: bind + source: ${PACKAGE_STORAGE_HOST:?Set an absolute trusted existing package directory} + target: /srv/license-packages + read_only: true + bind: + create_host_path: false + depends_on: + api: {condition: service_healthy} + networks: [private, edge] + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:8080/api/v1/health/live'] + interval: 5s + timeout: 3s + retries: 10 +networks: + private: {internal: true} + edge: {} +volumes: + mysql_data: {} +secrets: + mysql_app: + file: ${MYSQL_APP_SECRET_FILE:?Set protected app database password file} + mysql_root: + file: ${MYSQL_ROOT_SECRET_FILE:?Set protected root database password file} + signing_key: + file: ${LICENSE_SIGNING_KEY_HOST_FILE:?Set protected persistent P256 PEM file} diff --git a/deploy/Dockerfile.api b/deploy/Dockerfile.api new file mode 100644 index 0000000..8c24652 --- /dev/null +++ b/deploy/Dockerfile.api @@ -0,0 +1,17 @@ +FROM golang:1.23-alpine AS build +WORKDIR /src +COPY backend/go.mod backend/go.sum ./ +RUN go mod download +COPY backend/ ./ +RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server && CGO_ENABLED=0 go build -o /out/migrate ./cmd/migrate + +FROM alpine:3.21 +RUN apk add --no-cache ca-certificates wget && addgroup -g 10001 app && adduser -D -u 10001 -G app app +WORKDIR /app +COPY --from=build /out/ /app/ +COPY backend/migrations /app/migrations +COPY deploy/entrypoint.sh /app/entrypoint.sh +RUN chmod 0555 /app/entrypoint.sh +USER 10001:10001 +ENTRYPOINT ["/app/entrypoint.sh"] +CMD ["/app/server"] diff --git a/deploy/Dockerfile.web b/deploy/Dockerfile.web new file mode 100644 index 0000000..b0861c2 --- /dev/null +++ b/deploy/Dockerfile.web @@ -0,0 +1,9 @@ +FROM node:22-alpine AS build +WORKDIR /src +COPY frontend/package.json frontend/package-lock.json ./ +RUN npm ci +COPY frontend/ ./ +RUN npm run build +FROM nginx:stable-alpine +COPY --from=build /src/dist /usr/share/nginx/html +COPY deploy/nginx/compose.conf /etc/nginx/conf.d/default.conf diff --git a/deploy/entrypoint.sh b/deploy/entrypoint.sh new file mode 100644 index 0000000..1c31f9e --- /dev/null +++ b/deploy/entrypoint.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +if [ -n "${MYSQL_PASSWORD_FILE:-}" ]; then + password=$(cat "$MYSQL_PASSWORD_FILE") + case "$password" in ''|*[!a-zA-Z0-9_-]*) echo 'Database secret must be a nonempty URL-safe value' >&2; exit 1;; esac + export MYSQL_DSN="license_app:${password}@tcp(mysql:3306)/license_platform?parseTime=true" + export MIGRATION_DSN="mysql://license_app:${password}@tcp(mysql:3306)/license_platform?multiStatements=true" + unset password +fi +exec "$@" diff --git a/deploy/nginx/compose.conf b/deploy/nginx/compose.conf new file mode 100644 index 0000000..6a450b0 --- /dev/null +++ b/deploy/nginx/compose.conf @@ -0,0 +1,22 @@ +server { + listen 8080; + server_name localhost; + client_max_body_size 64m; + root /usr/share/nginx/html; + location /api/ { + proxy_pass http://api:18080; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 60s; + } + location /_packages/ { + internal; + alias /srv/license-packages/; + autoindex off; + disable_symlinks on; + add_header Cache-Control "private, no-store" always; + add_header X-Package-SHA256 $upstream_http_x_package_sha256 always; + } + location / { try_files $uri $uri/ /index.html; } +} diff --git a/deploy/nginx/download-local.conf b/deploy/nginx/download-local.conf new file mode 100644 index 0000000..315956c --- /dev/null +++ b/deploy/nginx/download-local.conf @@ -0,0 +1,18 @@ +# Isolated development reverse-proxy fragment. Mount PACKAGE_STORAGE_ROOT read-only at /srv/license-packages. +# The upstream application must set X-Accel-Redirect only after authorization and audit commit. +server { + listen 18181; + server_name 127.0.0.1; + location = /_packages { return 404; } + location /_packages/ { + internal; + alias /srv/license-packages/; + autoindex off; + disable_symlinks on; + add_header Cache-Control "private, no-store" always; + add_header X-Package-SHA256 $upstream_http_x_package_sha256 always; + limit_except GET HEAD { deny all; } + } + client_max_body_size 64m; + location / { proxy_pass http://host.docker.internal:18082; } +} diff --git a/deploy/nginx/tls-proxy.conf.example b/deploy/nginx/tls-proxy.conf.example new file mode 100644 index 0000000..b812d82 --- /dev/null +++ b/deploy/nginx/tls-proxy.conf.example @@ -0,0 +1,30 @@ +# Example only. Use certificates issued/managed by your production certificate authority. +# Do not copy a self-signed development certificate into this profile. +# Mount this as a server block and bind /run/tls read-only from the managed certificate path. +server { + listen 443 ssl; + server_name license.example.invalid; + ssl_certificate /run/tls/fullchain.pem; + ssl_certificate_key /run/tls/privatekey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 64m; + + location /api/ { + proxy_pass http://api:18080; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto https; + proxy_read_timeout 60s; + } + location /_packages/ { + internal; + alias /srv/license-packages/; + autoindex off; + disable_symlinks on; + add_header Cache-Control "private, no-store" always; + add_header X-Package-SHA256 $upstream_http_x_package_sha256 always; + } + location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html; } +} +# Restrict listener/network reachability to the actual proxy tier. Configure the API's +# HTTP_TRUSTED_PROXY_CIDRS to exact proxy source CIDRs only when this proxy is in use. diff --git a/docs/activation-contract-draft.md b/docs/activation-contract-draft.md new file mode 100644 index 0000000..6a2355f --- /dev/null +++ b/docs/activation-contract-draft.md @@ -0,0 +1,33 @@ +# v5 实例激活与签名证书契约(DEV 草案) + +## 管理员 API + +- `POST /api/v1/licenses/{license_id}/instances`:需要管理员会话。服务生成 UUIDv4 `instance_id` 与 256-bit bootstrap secret;响应仅此一次返回 `secret`。数据库仅保存 SHA-256(secret),列表/详情永不返回 secret。 +- `GET /api/v1/licenses/{license_id}/instances`:需要管理员会话;只返回 instance_id、状态、激活时间、证书版本,不返回 secret、secret_hash、证书签名私密材料。 +- `GET /api/v1/activation/public-key`:返回 ECDSA P-256/SHA-256 公钥 PEM、证书版本和签名编码。 + +## 集成客户端 API + +`POST /api/v1/activation/instances/{instance_id}`,无需管理员 Cookie。JSON 必须包含 `license_key` 和一次性提交的 `secret`;`Idempotency-Key` 必须为 1 至 128 个字符。服务端校验授权密钥、实例 secret、客户/产品归属、客户和产品启用状态、有效期和 issued 订单(若有关联)。成功返回 v1 certificate;secret 不在任何成功响应中回显。 + +同一实例和幂等键重放相同请求返回首次成功响应;改变 secret/license_key 或使用已激活实例返回 409/403。实例按数据库行锁串行化,一个实例最多成功激活一次。业务写入、幂等记录、审计事件同一事务,审计失败会回滚激活。 + +## 签名格式 + +Canonical payload 是 UTF-8、无 BOM、无尾随换行的固定顺序 `key=value` 行: + +```text +version=license-v1 +instance_id=00000000-0000-4000-8000-000000000001 +license_id=1 +customer_id=2 +product_id=3 +starts_at=2026-09-30T00:00:00Z +expires_at=2027-09-30T00:00:00Z +``` + +对完整 UTF-8 canonical bytes 做 SHA-256,再用环境注入的 P-256 ECDSA 私钥签名。signature 为 ASN.1 DER,base64 无填充。响应同时提供 `canonical_sha256`,便于跨语言测试向量定位。公钥只经接口发布;私钥不入数据库、日志或浏览器。 + +## 明确未实现 + +heartbeat、offline lease、冻结传播、实时撤销推送、租户隔离和离线授权均不属于本 v5 slice。证书签发不构成这些功能的模拟实现。 diff --git a/docs/admin-modules.md b/docs/admin-modules.md new file mode 100644 index 0000000..7335b08 --- /dev/null +++ b/docs/admin-modules.md @@ -0,0 +1,56 @@ +# 审计日志与系统设置 + +管理模块均要求有效的 `lp_session` 管理员会话;非管理员返回403,未登录返回401。写请求继续使用全局同源保护。 + +## 数据库 + +新增 `000009_admin_settings`:单例 `system_settings` 表以及审计时间/ID索引。当前服务要求 clean schema 9。启动服务不自动迁移。已有环境升级前备份并运行标准 migrate up,再启动新代码。down 会删除平台设置,需明确接受数据丢失后执行。 + +2026-10-09 本机仅升级独立开发库 `license_platform_local_261009`;原 `license_platform` 未修改。 + +## 审计日志 + +`GET /api/v1/audit-events` 返回 `{data: [...], meta:{page,page_size,total}}`。 + +支持 `page`、`page_size`(默认20,最大100)、`q`(邮箱/动作/资源类型包含查询,最多200字)、`action`、`resource_type`(精确匹配,最多64字节),以及 `from`、`to`(RFC3339时间,包含端点)。返回按时间、ID倒序,count和分页共享只读一致性快照。 + +记录字段:`id`、`actor_admin_id`、`actor_email`、`action`、`resource_type`、`resource_id`、`details`、`created_at`。详情仅允许已知业务字段;密码、会话令牌、实例凭据不提供。 + +已接入事件来自原有授权、订单、实例、版本发布/下载/门户业务审计,以及新增 `settings.updated`、`admin.password_changed`。这不是覆盖所有HTTP请求的访问日志;旧客户/产品CRUD、登录失败和命令行admin-init没有历史审计事件。实例产生的事件通过 `details.client_actor=instance` 区分;关联管理员字段来自既有业务归属规则。 + +审计只读,不提供编辑或删除接口。 + +## 系统设置 + +`GET /api/v1/settings` 和 `PUT /api/v1/settings` 使用 `{data:{site_name,support_email,announcement,updated_at}}`。PUT提交三个文本字段;平台名称1至100字、联系邮箱可空且最多254字节、公告最多2000字。所有管理员共享;更新时间由服务端生成。设置更新和不包含文本内容的审计记录同事务提交。 + +这些是展示配置,不控制TLS、签名密钥、数据库、限流器和授权有效期;运行参数仍由服务进程环境配置。 + +`POST /api/v1/settings/password` 提交 `{current_password,new_password}`,成功204。必须验证当前密码,新密码非空、最多72字节,无复杂度要求。更新bcrypt哈希、撤销该管理员其他会话、写入不含密码的审计记录同事务提交;当前会话保留。 + +## 日期时间展示 + +前端业务时间统一通过 `frontend/src/date-format.ts` 的 `formatDateTime` 展示,格式为 `YYYY-MM-DD HH:mm:ss`,按浏览器所在时区换算,使用24小时制。License 列表及详情、实例、订单详情、客户门户、审计时间和设置更新时间均采用此约定;缺失或无效时间显示 `—`,部分业务保留“未确认”“暂无租约”“尚未更新”等提示。审计详情中的原始 JSON 保留接口时间值,方便排查。 + +API 的 RFC3339 时间传输及 UTC 存储语义保持不变;审计本地时间筛选仍转换为 UTC 提交,仪表盘月份统计继续使用 UTC。新增页面展示业务时间时复用统一函数,不直接输出原始 ISO 字符串。 + +## 验证 + +后端单元测试覆盖设置边界、审计敏感字段过滤、筛选时间范围及未认证请求。独立开发库真实接口验证覆盖迁移、设置写入读取、非法参数、错误当前密码、密码修改、其他会话撤销、当前会话保留、审计筛选。验证后管理员密码恢复为原来的本地开发密码。 + + +## 多管理员与用户名登录(schema 10) + +管理台登录提交 `{username,password}`,不再使用邮箱登录。用户名统一去除首尾空格并转换为小写,允许 3–32 位字母、数字、下划线和短横线。邮箱作为唯一联系信息保留。现有管理员迁移后用户名为 `admin-{id}`,密码保持原值。 + +管理员账户页面 `/admins` 支持列表、新增、启用、停用、密码重置。所有管理员拥有同等后台权限。不能停用当前登录账户;停用账户和重置密码均撤销目标账户的所有会话。自身修改密码仍通过设置页面完成,保留当前会话。账号操作与审计写入同一事务,密码与哈希不会返回或写入审计详情。 + +接口:`GET /api/v1/admins`、`POST /api/v1/admins`(username/email/password)、`POST /api/v1/admins/:id/active`(active)、`POST /api/v1/admins/:id/reset-password`(password)。用户名或邮箱重复返回 409。 + +新部署先迁移到 schema 10,然后初始化: + +```sh +go run ./cmd/admin-init -username admin -email admin@example.test -password 'YOUR_PASSWORD' +``` + +初始化命令按邮箱识别已有账户,用户名冲突将报错,不会重置另一个账户。重新初始化会撤销该账户的旧会话。已有部署只执行迁移即可,不需要重置密码。原始业务数据库没有在本次开发中迁移;本地隔离数据库的既有账号为 `admin-1`,密码保持 `123456`。 diff --git a/docs/business-contract-draft.md b/docs/business-contract-draft.md new file mode 100644 index 0000000..15ee706 --- /dev/null +++ b/docs/business-contract-draft.md @@ -0,0 +1,28 @@ +# 基础管理台契约草案(待业务确认) + +状态:实现用临时契约,不代表业务签字、正式 OpenAPI 或授权规则冻结。 + +## 本阶段开发假设 + +- 首个管理界面仅供内部管理员使用;管理员账号由部署操作者通过一次性命令初始化,不开放公网自助注册。 +- 当前只有 `admin` 角色;服务端对所有主数据接口强制检查有效会话与 admin 角色。未来角色/权限需由业务签字后细分。 +- 管理员以邮箱标识,bcrypt 哈希密码;服务端仅保存随机会话令牌 SHA-256 摘要。会话固定 8 小时,登出即时撤销。 +- 客户暂用名称、联系邮箱、active/inactive 状态;产品暂用唯一编码、名称、说明、启用标志。 +- 客户列表分页参数为 page/page_size,默认 1/20、每页上限 100,可按名称或邮箱搜索。 +- 删除当前为物理删除,仅适用于无授权关联的基础数据阶段。建立授权关联后必须重新决策为软删除/停用或限制删除。 +- 默认仅绑定 loopback。任何实际环境必须使用 HTTPS、受控网络和备份;不提供生产部署验收。 +- v4 DEV 假设:线下订单是一客户、一产品、一笔 CNY 整数分金额;状态为 `pending_payment -> paid -> issued`。录单、收款确认、一次性发放仅允许 admin,服务端锁定并校验 customer/product active 状态。 +- v4 DEV 状态机:仅 `pending_payment` 可确认收款,实收金额必须等于订单金额;仅 `paid` 可发放一次授权;撤销/退款、作废、审批驳回不在本切片执行。 +- v4 DEV 幂等:每个订单操作要求 `Idempotency-Key`,同一管理员/操作/键匹配请求重放首次响应,指纹冲突返回 409;订单、授权、操作状态和 audit_events 同一事务提交。 +- v4 DEV 权限:当前统一 admin 门禁;审批角色、财务确认角色、退款角色和客户/租户范围尚未冻结。 +- v4 DEV 时间:发放请求显式提供 RFC3339 UTC 开始/结束时间,结束必须晚于开始且在 MySQL TIMESTAMP 范围;续期起始日是否允许早于当前时间仍待确认。 + +## 错误响应草案 + +业务错误统一为 `{"error":{"code":"...","message":"..."}}`。登录失败统一返回 401,不区分账号不存在和密码错误。未经认证返回 401,权限不足返回 403,字段校验错误 400,重复编码等冲突 409。 + +## 尚未确认 + +订单正式状态机及订单号规则、套餐/价格快照、支付渠道与对账、收款凭据格式、发放审批角色、renewal start-date 规则、退款后授权撤销/回收关系、跨客户/产品租户范围、财务报表口径均为可替换 DEV 假设,等待 T01/T02 正式确认。 + +管理员组织/租户归属、多管理员邀请与恢复流程、完整 RBAC 权限矩阵、客户身份唯一性及字段、产品版本/套餐/生命周期、删除/审计保留规则、锁定与速率限制策略、会话空闲续期、正式 API/OpenAPI/error catalog,均待产品、安全和接入负责人确认。授权激活、心跳、续期、退款、克隆、实例绑定规则不在本阶段实现。 diff --git a/docs/business-quickstart.md b/docs/business-quickstart.md new file mode 100644 index 0000000..071250a --- /dev/null +++ b/docs/business-quickstart.md @@ -0,0 +1,15 @@ +# 本地基础管理台运行 + +开发阶段需本机 Go 1.23+、Node 20+、npm 与 Docker。 + +1. 启动专用 MySQL:`docker run -d --name license-platform-mysql-app -e MYSQL_ROOT_PASSWORD=<本地临时密码> -e MYSQL_DATABASE=license_platform -p 13307:3306 mysql:8.0` +2. 在 `backend` 设置 `MIGRATION_DSN='mysql://root:<密码>@tcp(127.0.0.1:13307)/license_platform?multiStatements=true'` 和 `MYSQL_DSN='root:<密码>@tcp(127.0.0.1:13307)/license_platform?parseTime=true'`。 +3. 执行 `go run ./cmd/migrate -dsn "$MIGRATION_DSN" -dir ./migrations up`。 +4. 交互式输入密码初始化管理员,避免密码落入 shell history(当前命令行参数仍可能被本机进程查看,生产初始化需改为安全输入通道):`read -rsp 'Admin password: ' ADMIN_PASSWORD; echo; go run ./cmd/admin-init -dsn "$MYSQL_DSN" -email admin@example.test -password "$ADMIN_PASSWORD"; unset ADMIN_PASSWORD`。密码只要求非空,允许简单数字密码(例如 `123456`),不要求大小写或特殊字符;最多 72 字节。重复初始化同一邮箱会重置密码并启用账号。不要在共享机器使用本文示例邮箱。 +5. 启动后端:`HTTP_ADDR=127.0.0.1:18081 MYSQL_DSN="$MYSQL_DSN" go run ./cmd/server`。 +6. 新终端启动前端:`cd frontend && npm run dev -- --port 15173`,访问 `http://127.0.0.1:15173/`。 + +管理员登录后可新增、搜索、删除客户和新增、查看、删除产品;选择 active 客户和产品、填写开始/结束时间后可签发期限授权并分页查看。迁移需要 version 2 clean,见 `license-contract-draft.md`(DEV-LICENSE-v0.1)。客户下拉目前使用当前搜索结果的第一页,超过 20 条需要搜索定位。已有授权引用的主数据不可物理删除。后端目前也提供客户/产品 PUT 接口,编辑表单尚未接入。开发本地 HTTP Cookie 不设 Secure;直接 TLS 请求设 Secure,不信任任意 X-Forwarded-Proto。TLS 终止代理部署的 Secure Cookie 策略尚未配置,不能直接按此启动方式投入生产。生产使用 HTTPS、明确可信代理边界,并遵循组织密钥管理、数据库备份及安全运维流程。本快速启动不构成生产部署指南或 UAT。 + + +管理员登录现使用用户名和密码。schema 10 迁移后既有账户用户名为 `admin-{id}`;新初始化可指定 `-username admin`(默认 admin)。后台“管理员账户”页面支持新增、启停与密码重置,详见 [管理员模块](admin-modules.md)。 diff --git a/docs/client-integration-center.md b/docs/client-integration-center.md new file mode 100644 index 0000000..eb00072 --- /dev/null +++ b/docs/client-integration-center.md @@ -0,0 +1,34 @@ +# 客户端接入中心 + +管理员登录后进入 `/integration`,选择 Python、Go、Java、.NET 或 Node.js,以及桌面、常驻服务或容器模式。页面提供接口清单、可复制工程提示词、完整协议、安全约束、字段示例和 ZIP/Markdown 下载。首版交付生成资料,不包含五种语言已经实现并完成生产验收的 SDK。 + +SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权平台根地址;部署可以通过 `LICENSE_API_BASE_URL` 覆盖。该值必须是根地址,不能附加 `/api/v1`。协议、OpenAPI、Markdown 与 ZIP 内的资料都使用相同默认值。 + +## 管理员接口 + +以下 GET 路由使用现有管理员会话保护,不属于外部客户端运行 API: + +- `/api/v1/integration-kit?language=python&mode=service`:JSON 资料。 +- `/api/v1/integration-kit/download?language=python&mode=service`:UTF-8 Markdown,包含选定提示词、协议和字段示例。 +- `/api/v1/integration-kit/archive?language=python&mode=service`:ZIP,包含 README.md、protocol.md、openapi.json、prompt.md、test-vectors.json。 + +省略参数默认 python/service。未知语言或模式返回 400,不接受文件路径参数。下载使用 no-store,文件名按受控语言/模式生成。无需新数据库表,不包含任何真实实例 secret、数据库凭据或生产私钥。 + +每次 ZIP 下载为测试向量生成独立随机 P-256 密钥,返回公钥及 license-v2/lease-v2 的有效 DER ECDSA 签名、固定规范化内容及 SHA-256。私钥仅在生成时的内存中使用,不输出,不落盘。向量使用固定历史时间,时间相关测试必须使用给定固定 now;生产不得信任测试公钥。 + +## 协议维护 + +协议源文件在 `backend/internal/httpapi/integration_assets/protocol.md`,OpenAPI 3.0.3 在同目录 `openapi.json`,由 Go embed 嵌入二进制。修改接口实现时必须同时核对这两个文件,重新构建后端后生效。`client/verify.mjs` 提供 v2 验签与运行状态算法参考。 + +选择语言会加入对应加密库、HTTP/取消/状态存储/测试要求;运行模式在提示词中明确,完整协议包括桌面/服务/容器的身份和持久化约束。页面请求使用序列号忽略旧请求返回,避免快速切换后显示过期资料。 + +部署方须确认 keyring 已配置并通过受控渠道交付公钥;legacy v1 默认部署不满足本资料要求。keyring 发现不是信任引导。14 天离线租约意味着冻结/撤销最多可延迟 14 天生效,不能宣传立即离线撤销或硬件防克隆。Kubernetes 集群代理、移动设备、CI 临时身份、完全离线授权需要额外方案。 + +## 验证记录 + +- 后端 `go test ./...` 与 `go vet ./...` 通过。新增测试检查三个管理员接口未认证均为 401、非法选择 400、五种语言提示、OpenAPI JSON、ZIP 五文件及两类签名/篡改失败。 +- 前端类型检查、12 个测试文件共 33 项测试、生产构建通过。新增面板测试检查加载/失败/选择更新及下载参数,路由测试包括 `/integration`。 +- 使用隔离数据库 `license_platform_local_261009` 的真实管理员会话:JSON 与 ZIP 下载均 200,ZIP 包内容与 no-store 响应头已核对。 +- 浏览器实际切换 .NET:专属 DER 格式提示与下载 URL 更新。390×844 窄屏无整体横向溢出,控制台 0 error。 + +未迁移或修改原业务数据库,未提交或推送代码。现有大包构建提示与旧测试的组件 stub 警告仍存在。全仓 `git diff --check` 的两项旧文档末尾空行不在本次功能范围内。 diff --git a/docs/deployment-delivery.md b/docs/deployment-delivery.md new file mode 100644 index 0000000..4a76f04 --- /dev/null +++ b/docs/deployment-delivery.md @@ -0,0 +1,53 @@ +# Deployment delivery rehearsal + +Status: development scaffolding, not production accepted. Existing API 18081 is not restarted by this work. Do not reuse its in-memory signing key lifecycle for deployment. + +## Files and configuration + +The root compose.yaml builds deploy/Dockerfile.api and deploy/Dockerfile.web. Only the web port is bound to host loopback (18083). MySQL, Redis, API and package storage have no published host ports. The private service network is internal. Redis is optional under the `cache` profile; the API currently does not use Redis for sessions or rate limiting. + +Set these non-secret environment paths externally (not secret values in .env): MYSQL_APP_SECRET_FILE, MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST. All refer to protected, pre-existing absolute host paths outside Git and the build context. App DB password must be a randomly generated URL-safe value using letters, digits, underscores and hyphens. The image reads it at runtime, never logs it; driver DSNs remain process environment secrets. Compose local secrets are bind mounts, not an encrypted secret manager. Secure their host ACLs, process access, backups and crash dumps. + +The package directory must be writable by API UID 10001 and readable by Nginx, on a filesystem supporting hard links. Nginx mounts it read-only, serves it only through an internal location, disables directory listing and symlinks. Do not put it in the frontend/public tree. The API is non-root with read-only rootfs, all capabilities dropped and no-new-privileges; this is not a complete container-hardening assessment. + +Run from the repository root, using an independent Compose project/database and protected persistent key: + +```sh +docker compose config --quiet +docker compose build +docker compose up -d mysql +# Optional only: docker compose --profile cache up -d redis +docker compose --profile tools run --rm migrate +docker compose up -d api web +``` + +Migrations are explicit; startup never migrates. The migration profile uses the development app account, which also has DDL privileges in this local profile. Production needs separate least-privilege runtime and migration accounts. No administrator account/password is created by Compose. Stop/restart only this rehearsal project, never the existing 18081 process. Do not run down -v against retained data. + +## Operations slice + +See [operations-security.md](operations-security.md) for JSON logging, optional loopback metrics, local per-process entry limits, cookie/origin/body controls and CI evidence. New server main exposes only liveness publicly; readiness and metrics use numeric-loopback METRICS_ADDR (Compose 19090). Redis Lua shared entry limits are now default, with runtime failure returning 503 and no automatic fallback; local-dev must be explicitly selected for controlled development. ENTRY_REDIS_ADDR must be a numeric private/loopback IP; ENTRY_REDIS_PASSWORD_FILE optionally injects a protected absolute password file. Production Redis TLS/ACL/HA/capacity remain gates; the current Compose cache profile is not automatically wired to the API. Two isolated new API subprocess starts passed key-continuity and internal HTTP checks; unchanged 18081 still runs old source. See the release-gate update in operations-security.md for evidence limits. + +## TLS, proxy trust and Redis + +The loopback HTTP listener is for local rehearsal, not internet exposure. `deploy/nginx/tls-proxy.conf.example` is an example requiring managed CA certificates mounted read-only; it is deliberately not enabled by default and contains no development/self-signed key. Production must restrict upstream reachability, set `SESSION_COOKIE_SECURE=true`, and set `HTTP_TRUSTED_PROXY_CIDRS` to exact proxy source CIDRs only. Config rejects malformed CIDRs and `0.0.0.0/0`/`::/0`; Gin trusts no proxies by default. Nginx overwrites forwarded headers rather than forwarding client-supplied values. Direct TLS also sets Secure. Automated unit tests cover forced Secure and reject treating a bare X-Forwarded-Proto header as trusted. TLS deployment wiring, real certificate verification, ingress restrictions, CSRF/origin controls and end-to-end proxy spoof tests remain outstanding. + +Redis is optional and not used by the current API for sessions, rate limits, or authoritative state. It is under Compose profile `cache`; API startup/readiness does not depend on it. Do not claim Redis-backed behavior. + +The API has `/api/v1/health/live` for process liveness and `/api/v1/health/ready` for database connectivity plus exactly one clean migration row at schema version 8. Startup refuses a database that cannot be pinged or is not exactly at clean version 8; startup never migrates. Readiness returns only generic 503 on DB/schema failure, without internal error details. Compose API/web health checks use readiness. Unit tests cover unavailable DB, no migration row, old/future version and dirty schema; full Compose fault injection is pending. Load/capacity testing, pre-auth rate limiting, pinned image digests and vulnerability remediation remain open. + +## Backup and restore + +`scripts/backup-delivery.sh` creates a MySQL logical dump and deterministic tar of private package storage with checksums. Run only during a maintenance window that quiesces uploads and administrative writes: MySQL `--single-transaction` does not make a filesystem snapshot atomic with SQL. Protect/encrypt the destination and record schema version/checkpoint separately. Signing keys are intentionally excluded; recover them separately from protected secret management, never from SQL or these scripts. Redis is optional and holds no authoritative platform data. + +`scripts/restore-delivery.sh` requires `CONFIRM_EMPTY_RESTORE=YES` and independently refuses both nonempty package directories and databases containing tables. YES does not bypass either check. Supply only a trusted backup and an isolated empty DB/private directory with no listener; the script does not validate arbitrary or malicious SQL/tar inputs. After restore, run explicit migration/version checks and compare all `product_releases`/`package_objects` references, file size/SHA-256 and key fingerprint before any traffic. The restore command is not a substitute for application-level reconciliation. Scripts use MySQL CLI and protected `MYSQL_PASSWORD_FILE`; ensure the image/host has mysql client tools. A minimal isolated dump/restore drill has passed; full-platform reconciliation, production recovery objectives, encrypted backup handling and a complete application recovery drill remain pending. + +## Executed evidence (2026-09-30) + +- docker compose config --quiet: passed with placeholder external paths; no real secrets were printed. +- Web image build: passed, including npm ci and typecheck/Vite build. npm reported two moderate dependency vulnerabilities; no forced upgrade performed. Existing 1.13 MB bundle warning remains. +- API image build: NOT passed. Earlier attempts failed on a base-image layer and DNS. The latest retry resolved proxy.golang.org but TCP/443 was refused during go mod download. No fallback registry or weakened checksum verification was configured. +- Full Compose start, migration and admin/login smoke: NOT executed. API image remains blocked by outbound Docker network refusal to proxy.golang.org; no local Go module cache image was available. Protected deployment inputs are not provisioned. +- Readiness unit tests passed for clean v8, old/future/dirty/empty/unavailable schema and nil DB; startup schema gate now requires exactly version 8 clean. Compose config with protected placeholder paths passed and uses readiness healthchecks. Redis is now an explicit optional `cache` profile because the current API does not use it. +- Isolated backup/restore rehearsal passed in a disposable MySQL 8.0 container: logical dump plus package tar checksums verified, restored schema row was 8 clean, package object size/digest and restored file SHA-256 matched. The signing key was excluded. The final restore used a new empty `license_restore_empty` database and an empty private directory; a second attempt against the nonempty database was rejected. This used a minimal synthetic dataset, not the full business database. Rehearsal containers were stopped; business MySQL and 18081 were untouched. +- Independently executed isolated MySQL/Nginx download integration: passed actual bytes/digest, Range 206, internal-path 404 and unauthenticated denial, plus expired/unpublished/missing release denial audits. This is not equivalent to full Compose acceptance. +- Go test/vet, npm test (10 cases), npm build: passed. Manual logged-in browser acceptance remains separate and pending. diff --git a/docs/download-contract-draft.md b/docs/download-contract-draft.md new file mode 100644 index 0000000..2a0ec8e --- /dev/null +++ b/docs/download-contract-draft.md @@ -0,0 +1,32 @@ +# Local release/download DEV slice + +Status: in progress, not ready for formal acceptance. U07 resumable chunk upload, crash/orphan reconciliation, formal key rotation and authenticated browser acceptance remain incomplete. + +## API + +- Admin GET `/api/v1/products/:id/releases?page=1`: paginated metadata, no physical storage path/key. +- Admin POST `/api/v1/products/:id/releases?version=...`: raw binary, 1 byte through 64 MiB. SHA-256 content address; transactional publication metadata/audit. Apply migrations 007 and 008 before starting this code. +- Instance POST `/api/v1/customers/:customer_id/releases/:id/download`: JSON instance ID/secret. Current customer/product entitlement, freeze/revocation and instance ownership checked before transactional audit and X-Accel-Redirect. Secret must not appear in URLs. +- Downloads use POST with Range headers; clients must repeat credentials for every resumed request. Not a public download URL. + +## Storage and consistency + +`PACKAGE_STORAGE_ROOT` must be an absolute trusted non-public existing directory writable only by the application/storage owner. Digest keys are 64 lowercase hex characters plus `.bin`. Package symlinks are rejected. Directory modification by an untrusted process is outside the safe operating boundary; Nginx also disables symlinks. + +Migration 008 package_objects rows serialize same-digest writes across products. New files are removed for metadata/audit failure before rollback. A commit acknowledgement failure or process crash can leave an unreachable object; preserve it for reconciliation rather than risking deletion of an actually committed package. No crash recovery/automatic garbage collection claim is made. + +## Executed evidence (2026-09-30) + +Dedicated `license_download_260930` database migrated to 008; no destructive cleanup of normal development data. + +`TestDownloadsMySQLIntegration`: customer/product isolation, bad secret, freeze/revoke/customer inactive/product inactive, unauthenticated publication, audit failure blocking redirect and publication, failure file cleanup, concurrent cross-product same digest, conflicting version, empty file, 67108864-byte success and 67108865-byte denial passed. + +Linux container `TestLocalPackageRejectsTraversalAndSymlink` passed without skip. + +Isolated Nginx stable-alpine on http://127.0.0.1:18181 with temporary API 18082: authenticated exact bytes and SHA256 header matched; Range bytes=0-6 returned 206 with `package`; guessed internal path 404; empty credentials 400. Container and temporary API stopped after automated test. Configuration: deploy/nginx/download-local.conf, storage read-only mounted at /srv/license-packages; no unrelated Nginx modified. + +Frontend release list/upload panel compiled; existing frontend tests/build passed, existing bundle-size warning remains. Authenticated browser upload/list/instance interaction needs user login at http://127.0.0.1:15173. + +## Runtime/key boundary + +Existing development 18081 remains v6, development database remains 007; 008 and new code have not been applied to that runtime. Its ephemeral signing key cannot be recovered through supported APIs. Do not rerun the old launcher, since it silently generates a different key. Upgrade requires protected persistent key injection and an explicit decision concerning old DEV certificates/leases, or coordinator approval for deliberate test-only key rotation. See signing-key-operations.md. No private key saved or logged. diff --git a/docs/heartbeat-lease-contract-draft.md b/docs/heartbeat-lease-contract-draft.md new file mode 100644 index 0000000..2a64369 --- /dev/null +++ b/docs/heartbeat-lease-contract-draft.md @@ -0,0 +1,53 @@ +# v6 心跳、租约、冻结传播(DEV 草案) + +未经 T01/T02 签字,不代表正式产品策略或 UAT 验收。 + +## API 与认证 + +客户端 `POST /api/v1/instances/{instance_id}/heartbeat`,JSON `{ "secret": "", "client_time": "" }`,必须带 `Idempotency-Key`。只用 instance_id + secret 认证,解码 32-byte base64url secret 并比较 SHA-256;不记录、不回显明文。请求体最多 4096 bytes。 + +管理员 `POST /api/v1/instances/{instance_id}/freeze`,JSON `{ "frozen": true|false }`,必须带管理员 Cookie 与 Idempotency-Key。冻结状态和操作/audit 同事务。冻结不篡改已发租约时间,也不模拟主动推送。 + +每实例成功心跳间隔至少 60 秒,429 提供 Retry-After。新状态传播不受正常限频限制。相同键/相同 client_time 返回首次成功响应且不更新 last_seen;改变载荷 409。若冻结/撤销等状态变化,则旧成功响应重放返回 409 state_changed,客户端必须新键重试。 + +## 状态与时间 + +成功响应 data.payload:version、instance_id、state、server_time、entitlement_expires_at、lease_expires_at;附 signature、canonical_sha256、algorithm、next_heartbeat_seconds。 + +- `active`:lease_expires_at = min(server_time + 14 天, entitlement_expires_at)。权益截止独立于租约;远期/永久式权益绝不产生永久离线权限。现有数据库只支持有期限权益,真正 null 永久权益尚未实现。 +- `frozen`、`revoked`、`expired`、`pending`、`not_activated`:不给新使用权限,lease_expires_at = server_time。撤销优先于冻结。 +- DEV 假设:联网收到签名冻结/撤销立即停用并清除允许缓存。离线无法获知新的冻结/撤销,旧租约可用至原截止,且最长 14 天;不得声称即时离线撤销。 +- 时间以服务端 MySQL UTC_TIMESTAMP(6) 为准;客户端绝对偏差/相对前次时间回拨超过 5 分钟返回 409 clock_skew。服务端较 last_seen 回拨超过 5 分钟暂停签发;容差内高水位单调不降。 +- 客户端必须验签、核对实例和版本、只接受 active 状态,校验 now < lease_expires_at 且 now < entitlement_expires_at,校验租约跨度 <=14 天,并持久化可信时间高水位/单调时间;本切片没有客户端执行器,不承诺对系统时钟篡改或存储回滚的完整防护。 + +last_seen、租约、observed_state、幂等响应和 audit 同事务。审计 actor 暂借实例 provisioner 外键,details 标明 client_actor=instance,正式客户端主体模型待确认。 + +## Canonical / 跨语言公开向量 + +UTF-8,无 BOM、无尾换行,固定顺序如下。SHA-256 后以 P-256 ECDSA 签名,ASN.1 DER / base64 无填充;公钥是 SPKI PEM。公钥与签名均为公开测试材料,随机生成私钥不持久化。 + +```text +version=lease-v1 +instance_id=00000000-0000-4000-8000-000000000001 +state=active +server_time=2026-09-30T12:00:00Z +entitlement_expires_at=2036-09-30T12:00:00Z +lease_expires_at=2026-10-14T12:00:00Z +``` + +SHA-256: `777150ed1107b51f17dd1ffaefac303310a32ec415e3d83a4b16cb05b9aac379` + +Signature: `MEQCIFHuseC8F3iv6Jz9W3yywkacJ5qBOcDRJSNFLdFWS2w9AiBRZEmPGOzti3IJ0VOPccUOmmtVfWs6ZxtjcSDKJLH8BQ` + +```pem +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz39VZCPp0fPgbDhKOM0jUHqzJAe3 +7GSZpcSe1TO9UGqv8BO3PBI8Th3Z9Fy5EdPaVggh8V/pjW/dcsUg9QbzWA== +-----END PUBLIC KEY----- +``` + +任何一个字段被篡改必须验签失败;license-v1 激活证书不能替代 lease-v1 租约。 + +## 明确阻塞 + +克隆检测、实例迁移、扩容、真正永久权益、客户端可信存储/执行器、密钥轮换 key_id、分布式入口限流、异常激活监测、缓存推送失效、正式策略签字及 UAT 尚未实现。不得以当前 instance secret 认证声称防克隆。 diff --git a/docs/keyring-client-contract-draft.md b/docs/keyring-client-contract-draft.md new file mode 100644 index 0000000..703c4c0 --- /dev/null +++ b/docs/keyring-client-contract-draft.md @@ -0,0 +1,37 @@ +# DEV-KEYRING-v2 / client execution draft + +Status: configurable development implementation, not T01/T02-approved production protocol. Existing 18081 unchanged. No commits/releases. + +## Environment and wire format + +LICENSE_KEYRING_FILE is an absolute JSON file (regular file, <=64 KiB). Structure: + +```json +{"current_key_id":"release_2026_10","keys":[{"key_id":"release_2026_10","public_key_pem":"PUBLIC PEM ONLY","revoked":false},{"key_id":"previous","public_key_pem":"PUBLIC PEM ONLY","revoked":false}]} +``` + +The current private key still comes exclusively from existing protected LICENSE_SIGNING_PRIVATE_KEY_FILE or the existing PEM injection mechanism; do not put private keys in the keyring. Each unique key ID uses [a-zA-Z0-9_-]{1,64}. Maximum 32 entries. Current entry must exist, be non-revoked, be P256 and match the private key or startup fails. Retired verification-only entries need no private key. + +With keyring configured, NEW certificates use license-v2 and NEW heartbeat leases use lease-v2. The existing fixed canonical v1 field order is retained, with the new version and a final newline followed by key_id=. No trailing newline. SHA256, ECDSA P256, ASN.1 DER signature, raw standard base64 (no padding). key_id belongs INSIDE payload and is signed. IDs in Node are positive safe integers; client rejects larger numeric IDs rather than accepting rounded JSON integers. RFC3339 UTC times remain exact signed text, not reformatted by client. + +Without keyring, old v1 signing remains for development compatibility. The new client intentionally refuses all v1 payloads. /api/v1/activation/keyring exposes public metadata, but is discovery ONLY; never trust it automatically. Public keys and revocation policy must be pinned/distributed through a separately authenticated deployment path. Unknown/revoked key fails closed. A revoked signing key cannot be current. + +## Migration and rollback + +No historical SQL migration changed and no new schema migration required: certificate_payload and operation response JSON persist version and key_id; certificate_version stores v2. Existing idempotent activation/heartbeat operations replay original responses without re-signing, including v1. Retry with the SAME idempotency key, never assume replay upgrades a certificate. + +Stage clients and pinned old+new keys BEFORE switching the API current key. Keep old unrevoked PUBLIC key for the full approved historical certificate/lease lifetime, then retire only after explicit lifecycle review. Do not overwrite key IDs with different public keys. Server validates current configuration only; deployment approval must enforce key ID immutability/history. Runtime reload is NOT supported; use approved rolling deployments with persistent protected injection. No current production key was generated or rotated. + +Rollback is configuration/software rollout, not business-data down migration: restore previous API image plus its matching current private key and public keyring while preserving public keys needed for already-issued v2 payloads. Rolling back to a v1-only binary DOES NOT make v2 artifacts verifiable by old clients. Do not delete stored responses/certificates or force schema version. Preserve quiesced backup, issued artifacts and approvals. Formal retention windows, emergency revocation publication, config generation monotonicity and live business rotation drill remain gates. + +## Independent client module + +client/verify.mjs is a Node server-side reference package, NOT the management console and NOT a deployed customer integration. No instance secret/session stored by this module. verifyEnvelope takes caller-pinned keys, rejects unknown/revoked, altered key_id or payload. acceptLease verifies instance binding, signed state, entitlement bound, max14-day lease, 5-minute server skew, monotonic client/server milliseconds. canRunOffline checks previously accepted lease until expiration. Caller must atomically persist returned state BEFORE enabling licensed work, update local high-water before EVERY subsequent execution, protect it from tampering and disable on all errors. This does not resist privileged cloning, disk snapshot rollback or clock manipulation by host owner; monotonic trusted time/storage design still requires T01 approval. Millisecond comparison loses sub-ms precision; server-issued microsecond exact ordering and replay digest persistence are future hardening gates. + +Go test TestKeyringCrossLanguageRotation generates public Go->Node vectors with ephemeral private keys only in memory. Checks old/current certificate verification, revoked/unknown rejection, signed key substitution/payload tamper rejection, lease verification, instance mismatch, local/server high-water rollback, offline expiry. No private test fixture committed. This is cross-language component evidence, not authenticated activation/heartbeat rotation E2E. Node required for backend tests; CI explicitly installs Node24. + +## Integrator API / customer portal boundary + +Provisioning remains administrator-only POST /api/v1/licenses/:id/instances, returning a one-time secret that must reach the authorized integrator via secure channel. Client activation POST /api/v1/activation/instances/:instance_id uses secret + license_key and Idempotency-Key. Heartbeat POST /api/v1/instances/:instance_id/heartbeat uses secret + client_time and Idempotency-Key; follow the current heartbeat draft field contract. Download POST /api/v1/customers/:customer_id/releases/:id/download uses existing credential draft and Nginx internal handoff. No secret belongs in query strings/logs/browser localStorage. Timeouts/429 use bounded backoff; 403/409 must not silently reactivate, bypass checks or reuse mismatched payloads. + +There is NO customer-account authentication domain or customer portal in the current implementation. The Vue UI is administrator management only. T25 remains unstarted, pending tenant identity/account reset/RBAC/renewal contracts. Do not build an unauthenticated customer-data page using administrator cookies or pretend this module is a customer portal. Minimum future portal: customer login/session isolation, only-own licenses/orders/leases/releases, no administrator routes, secure secret delivery/recovery, expiry/renewal requests, logout/reset and tenant-negative tests. diff --git a/docs/license-contract-draft.md b/docs/license-contract-draft.md new file mode 100644 index 0000000..5daf101 --- /dev/null +++ b/docs/license-contract-draft.md @@ -0,0 +1,10 @@ +# 授权签发闭环草案 + +版本:DEV-LICENSE-v0.1(2026-09-30)。状态:开发假设,未替代正式业务决策或 OpenAPI 签字。 + +- 当前授权是后台管理员为 active 客户和 active 产品签发的一条期限记录。 +- `starts_at` 和 `expires_at` 必须是 RFC3339 时间,服务端转 UTC 保存;结束时间必须晚于开始时间,精度为微秒;当前 TIMESTAMP 存储范围限定为 1970-01-01T00:00:01Z 至 2038-01-19T03:14:07Z(上界不含)。 +- 授权初始状态为 `active`,拥有不可预测的 128-bit 十六进制 `license_key`。本阶段仅提供后台查看,不把它当作客户端激活凭证。 +- 请求必须带 `Idempotency-Key`(1 至 128 字符)。同一管理员、同一键、同一请求字段重放返回原授权;字段不一致返回 409。管理员行锁串行化并发签发,客户/产品行锁确保状态校验一致;事务不会产生第二条授权或第二条签发审计。前端网络失败后保留原键重试。 +- 签发事务同时写 `audit_events`,审计只记录管理员、资源、动作和非敏感期限/主数据 ID,不记录密码、会话令牌或完整 HTTP 内容。 +- 本阶段不实现实例身份绑定、激活协议、离线租约、设备扩容/克隆、心跳、退款、客户门户或下载权限。新增的撤销/续期仅是后台期限记录开发假设:管理员级权限、Idempotency-Key、锁定授权行的事务操作记录与审计;续期只允许延后结束时间,撤销后不得续期。它们不等同续费、订单发放、激活或正式冻结/解绑。正式状态机、授权码展示/轮换、租户隔离和审计保留策略待确认。 diff --git a/docs/operations-security.md b/docs/operations-security.md new file mode 100644 index 0000000..210963f --- /dev/null +++ b/docs/operations-security.md @@ -0,0 +1,50 @@ +# Operations and security slice + +Status: isolated integration evidence only, not production acceptance or full Compose runtime acceptance. + +## 2026-10-01 release-gate update (supersedes earlier local-only notes) + +- Production server main now defaults to Redis entry limiting. Missing Redis configuration fails startup unless ENTRY_LIMIT_MODE=local-dev is explicitly selected. Lua INCR+PEXPIRE shares a 60-second fixed window across API instances. Redis runtime errors return 503 rate_limit_unavailable before handlers; no automatic fallback. Numeric private/loopback transport only in this profile; ENTRY_REDIS_PASSWORD_FILE is absolute with a size bound. Redis ACL/TLS, namespace policy, eviction/restart durability, key-cardinality attack capacity and production HA remain gates. Redis memory eviction/reset can reset counters; this is not equivalent to a durable security quota. +- Real isolated Redis integration passed: two independent HTTP servers/clients shared a 10-request login quota (11th=429); closing one Redis client produced 503 and no handler execution. Only login was exercised across clients in the real Redis test; existing unit tests cover all four route classifications. Infrastructure outage/restart/load/HA acceptance remains pending. CI now provides isolated Redis and requests race tests; no remote CI execution claim. +- Server main no longer registers readiness on the public router. METRICS_ADDR loopback operations listener serves readiness and metrics. Public ready and metrics returned 404 in two real API subprocess runs; internal ready/metrics returned 200. API Compose healthcheck uses loopback 19090; Web checks public liveness. If METRICS_ADDR is absent no readiness endpoint is available. This is source and isolated HTTP evidence, not full Compose validation. +- TestSigningFileAPIRestart built and launched the new API twice against isolated clean008 database. A test-only persistent P256 file was stored outside repository in an inheritance-disabled user-only Windows ACL directory, never logged or retained. Both public keys matched and previously signed canonical license-v1 and lease-v1 payloads verified after both launches. Test directory/key were removed by test cleanup. This tests key loading/restart continuity, NOT issuance/activation/heartbeat persistence through a complete business workflow. key_id, multi-key verification windows and rotation are NOT implemented and block production rollout. +- New API subprocesses loaded operations/security and checked internal HTTP boundaries plus real HTTP unauthorized write=401, foreign Origin=403, oversized login body=413, each with server X-Request-ID. Existing 18081 was NOT restarted. Browser at 15173 showed unauthenticated email/password/login form; no credentials entered; it still points to old API and is not new-backend authenticated acceptance. +- Local Linux race attempt found GCC in WSL but no Go; official toolchain download failed/timed out. Windows race previously blocked by CGO disabled. CI race configured, NOT executed here. Do not mark race passed. +- Release blockers: unsigned T01/T02 contracts; persistent production secret injection/rotation/key_id; Redis TLS/ACL/HA and outage-load acceptance; managed TLS/proxy spoof and complete CSRF acceptance; Docker API build/full Compose; logged-in browser/end-to-end issuance lifecycle; U07 chunk/resume/quota/crash reconciliation; compatibility/forced/gray releases; T19 notification/dedup/retries; OSS deferred; production backups/binlogs/restore/reconciliation/rollback; alerts/P95/capacity/vulnerability remediation; race evidence; UAT and signatures. No commit/push/release/task closure. + +The following sections preserve earlier slice evidence; their local-only limiter and publicly accessible readiness descriptions are superseded by the update above. + +## Logging and errors + +The HTTP middleware emits JSON through slog with an allowlist: server-generated request_id/trace_id, route template, operation, HTTP status, error code and elapsed seconds. Client IDs are ignored. trace_id currently equals request_id; no W3C tracing or cross-service propagation is implemented. No request bodies, raw URL paths, query strings, cookies, authorization headers, IP addresses, SQL errors or panic values are logged. Panic handling emits a generic internal_error; startup logs a generic startup_error instead of dumping potentially secret connection errors. Error responses retain code/message and add request_id. Server errors have a generic message. Existing domain codes remain unchanged; a complete contract-signed error registry is still pending. + +Audit details were inspected in activation, heartbeat, download, order and license handlers: they use explicit field lists (resource IDs, state, timestamps, package digest/size), not full request objects. Instance credentials, session tokens, passwords and signing PEM must never be added. This inspection is not a complete automated data-loss-prevention audit. Authentication success/failure metrics are not a durable audit trail. + +## Metrics and exposure + +Set METRICS_ADDR to a numeric loopback address such as 127.0.0.1:19090 to opt into a separate metrics listener. Non-loopback addresses are rejected. /metrics is not registered on the public API router or Nginx. In containers, collection must occur inside that network namespace; no host port publication or container-external collector is configured. Metrics are Prometheus text counters for requests and summed duration, with bounded operation/outcome labels (login, activation, heartbeat, download, authorization, other; success/failure). Authorization means license-route HTTP outcomes, not every internal authorization decision. Download success measures the authorization handoff, not completion of Nginx file transmission. Metrics reset on restart; histogram/P95, alerts, durable aggregation and dashboard setup are pending. + +Liveness/readiness remain existing API endpoints for Compose checks, including the local Web proxy. They return generic statuses but are NOT restricted to an internal listener in the current scaffold. Production ingress must restrict /api/v1/health/ before external exposure; strict internal-only health enforcement is still pending. + +## Entry rate limits + +A bounded local fixed-window limiter runs before login, activation, heartbeat and download handlers: login 10 per minute per effective client IP; other three 60 per minute per IP per operation. Buckets are capped at 10,000; capacity exhaustion denies new keys (fail-closed) with 429/Retry-After. Trusted proxies default to none; production must configure exact proxy CIDRs and prevent direct upstream access. Forwarded IP spoof tests passed with default no-trust configuration. + +IMPORTANT: this implementation is single-process only. Separate processes have independent counters; restart clears them, NAT shares quota and fixed-window boundaries permit bursts. Redis distributed limits, Redis authentication/TLS configuration, atomic distributed counters and outage fail-closed policy are NOT implemented or tested. Redis remains optional and unused. Do not deploy multiple replicas assuming a global limit. Thresholds need capacity acceptance and product approval. + +## Browser and body controls + +Session cookies are HttpOnly, SameSite=Strict, and Secure for direct TLS or explicit SESSION_COOKIE_SECURE=true. Write requests with an Origin must match request Host and effective secure scheme; cross-site Fetch Metadata is rejected. CORS does not allow external origins. Requests without Origin/Fetch Metadata are still allowed for non-browser clients; there is no synchronizer CSRF token, signed origin allowlist or complete browser CSRF acceptance yet. This policy requires same-origin browser deployment. + +General request bodies have a 64 KiB MaxBytesReader; known-length overflows return 413. Unknown-length/chunked overflows reach existing JSON validation and return 400. Uploads retain their streaming 64 MiB bound; activation/heartbeat/download retain more restrictive existing guards where applicable. Path and SQL security still rely on existing digest/path validation and parameterized SQL; no new claim of exhaustive SQL injection testing is made. + +## Executed checks + +- go test ./... and go vet ./... passed after this slice. +- Logging tests verify secret body/query/path/cookie/panic text and forged request IDs are absent. +- All four entry routes tested for pre-handler 429 and forwarded-IP spoof resistance. +- Tests cover origin rejection, no external CORS allow header, known/chunked body limits, malformed sessions, cookie attributes, bucket capacity/reset and independent limiter scope. +- Frontend 10 tests, typecheck and production build passed; existing >500 kB bundle warning remains. +- scripts/check-delivery.sh checks contiguous migration versions, nonempty up/down pairs and shell syntax. Compose placeholder configuration passed. This is not SQL execution or container runtime validation. +- Local race execution was blocked because CGO is disabled. Linux CI now requests focused race tests; that remote workflow has not been run here. +- Existing API 18081 was not restarted and remains live. Docker API build remains blocked by outbound proxy.golang.org TCP/443 refusal; full Compose, production security, load and failure acceptance remain pending. diff --git a/docs/release-gate-matrix.md b/docs/release-gate-matrix.md new file mode 100644 index 0000000..567dd03 --- /dev/null +++ b/docs/release-gate-matrix.md @@ -0,0 +1,66 @@ +# Release gates / 2026-10-01 + +No release approval. No commit/push/task closure. Existing API18081 not restarted. + +## TLS, trusted proxies and CSRF deployment + +Managed certificate chain/private key are read-only protected mounts, never repository/backup artifacts. Terminate TLS1.2/1.3 at reviewed Nginx config deploy/nginx/tls-proxy.conf.example. Set SESSION_COOKIE_SECURE=true on API; only allow API traffic from the actual proxy network. HTTP_TRUSTED_PROXY_CIDRS must use exact proxy sources, never /0; do not configure generic private subnets solely for convenience. Nginx must overwrite Host/X-Forwarded-For/X-Forwarded-Proto; caller-supplied forwarded values are not authority. Keep metrics/readiness loopback only and deny package internal paths publicly. Managed certificate renewal, redirects/HSTS, listener ACL and actual proxy deployment remain unverified. + +Browser session writes require same Origin scheme+Host and reject Sec-Fetch-Site cross-site; cookie HttpOnly+SameSiteStrict+Secure. Missing Origin/Fetch Metadata remains allowed for non-browser clients; this is NOT a formal synchronizer-token implementation. No CORS allowlist/credentialed external frontend. Formal CSRF threat model (sibling domains, DNS/Host trust, missing headers), token policy and TLS proxy acceptance require T01/T02 decision. Never claim broad CSRF acceptance from a unit test. + +TestTLSOriginCookieBoundary passed on real isolated httptest TLS listener with test certificate: same-origin200, foreign Origin403, HTTP Origin on HTTPS403, Secure/HttpOnly/Strict cookie, forwarded spoof IP ignored with no trusted proxies. This is actual direct-TLS component evidence, not Nginx production TLS validation. Existing tests cover explicit CIDR/default proxy controls. No production certificate installed. + +## Compose run gates + +API image build previously failed reaching proxy.golang.org; no successful new image/runtime claim. Redis remains optional cache profile, while API defaults to mandatory Redis with ENTRY_REDIS_ADDR empty. To rehearse explicitly select either controlled ENTRY_LIMIT_MODE=local-dev (NOT production/multi-instance acceptance) or start cache and configure a numeric private Redis address after inspecting the isolated container network. Current address validation does not accept service name redis; static-IP/service-discovery design must be reviewed before reproducible Compose delivery. Redis dependencies/ACL/password/TLS/HA are not wired for production. Placeholder compose config success does not demonstrate startup. LICENSE_KEYRING_FILE is not mounted by base Compose; opt-in development overlay must mount public ring read-only and inject path. Never inject private key through this public ring. + +## Backup / restore / rollback checklist + +1. Obtain approved maintenance/quiesce window; block writes and drain upload/activation/heartbeat transactions. Record image/config/schema IDs and file manifest counts/hashes without secrets. Fail if consistent snapshot cannot be proven. +2. Use existing backup-delivery.sh with trusted SQL/tar only. DB snapshot/binlog position and object files must share a consistency point; existing restore rehearsal is not proof of production binlog consistency. Encrypt production backups/access-control them. Signing private keys are excluded and recovered separately through protected approved secret management. +3. Restore only isolated EMPTY database/private target with no listener and CONFIRM_EMPTY_RESTORE=YES. Refuse nonempty targets regardless of confirmation. Verify schema clean008, every object metadata/hash/size, license/order/operation relations, audits and public-key fingerprints. Restore application should remain offline until approval. +4. Rehearse previous image/config/keyring rollout with both old and newly-issued public keys retained. Do not down migrated business schema or erase idempotency/certificate JSON. Confirm stored v2 artifacts verify after rollout; retain revocation policy. Failed key/schema/readiness checks block listeners and rollback approval. +5. Verify actual isolated activation/heartbeat/download lifecycle, denial, Redis outage, TLS proxy, logs, alerts, lease expiration and recovery reconciliation. Reopen traffic only after evidence review. No production recovery/RTO/RPO/binlog/rollback claim currently. + +## T01-T30 inventory + +Canonical task status remains Chinese task plan; no task accepted/closed by this update. + +| Task | Status | Remaining release gate | +| --- | --- | --- | +| T01 | blocked | Product/integrator owner, deployment identity and business decisions/signatures | +| T02 | blocked | Approved OpenAPI/errors/RBAC/crypto/lifecycle contract | +| T03 | needs acceptance | Actual deployment, remote CI/review | +| T04 | in progress | Full entitlements/schema/seed/RBAC approval | +| T05 | in progress | Customer identity/refresh; Redis shared limiter implemented, TLS/HA acceptance pending | +| T06 | in progress | Permission routes/full CRUD/pagination/browser acceptance | +| T07 | in progress | Quotas/crash reclamation/storage abstraction acceptance | +| T08 | in progress | Build network/Redis wiring/full Compose/managed TLS | +| T09 | in progress | Multi-account/RBAC management and audit | +| T10 | in progress | Customer identities/subaccounts/tenant isolation | +| T11 | in progress | Modules/templates/disable constraints/edit UI | +| T12 | in progress | Full entitlement and state contracts | +| T13 | in progress | Opt-in signed key_id v2 + keyring + Go->Node vectors implemented; rotation E2E and lifecycle approval pending | +| T14 | in progress | Clone/migration/scaling identity approvals | +| T15 | in progress | Reference client verifier/high-water implemented; trusted persistence/host integration/monitoring/UAT missing | +| T16 | deferred | Not first release | +| T17 | in progress | Packages/pricing snapshots/approvals | +| T18 | in progress | Renewal/refund/approval rules | +| T19 | not started | Notifications/dedup/retry | +| T20 | not started | Finance/report/export | +| T21 | in progress | Compatibility/forced/gray release | +| T22 | in progress | Chunk/resume/quota/orphan reclaim | +| T23 | in progress | Version check/real client update | +| T24 | deferred | OSS outside first release | +| T25 | in progress | Instance-credential read-only portal `/customer` + `/api/v1/portal/snapshot` implemented; customer account login/tenant/RBAC/reset contract still absent, so not accepted as account portal | +| T26 | in progress | Audit pagination/filter/retention | +| T27 | in progress | Independent Node verifier and vectors exist; actual integrator E2E absent | +| T28 | in progress | Race/pressure/capacity/outage/security review/vulnerabilities | +| T29 | in progress | Production encrypted recovery/binlog reconciliation/alerts/rollback | +| T30 | blocked | No signed UAT, gray observation, production approval, or release authorization | + +## Matrix evidence boundaries + +Passed: Go full tests/vet; frontend Vitest (10 tests); instance-credential portal unit boundary; isolated MySQL v2 activation/heartbeat old/new key rotation, historical replay, router re-registration, Node public-vector verification, portal pagination/audit/no-store and cross-instance rejection; old v1 compatibility tests; Go->Node ephemeral vector verification/tamper/revocation/unknown rejection and lease high-water; isolated direct TLS boundary; prior isolated Redis shared login and fail-closed; prior new API two-process persistent signing continuity/internal ready. + +Not executed in this increment: OS-process restart with new-v2 keyring continuity (required DSN/Redis test inputs were absent), public keyring HTTP matrix, Redis infrastructure restart/load, Nginx managed TLS, full Compose, Linux race, authenticated customer-account portal, hosted integrator workflow, production rollback and UAT. Browser-only `/customer` layout checks passed at 390x844 and 1440x900 with no horizontal overflow, but no credentials were entered and no authenticated download/cross-tenant browser flow was claimed. Compose was blocked before build by missing protected external paths (`MYSQL_APP_SECRET_FILE`, `MYSQL_ROOT_SECRET_FILE`, `LICENSE_SIGNING_KEY_HOST_FILE`, `PACKAGE_STORAGE_HOST`); earlier API build attempts also hit `proxy.golang.org` TCP/443 refusal. The MySQL evidence uses a newly-created dedicated schema and router re-registration; it does not establish production acceptance. Do not reuse prior v1 isolated startup as v2 end-to-end evidence. diff --git a/docs/signing-key-operations.md b/docs/signing-key-operations.md new file mode 100644 index 0000000..4387b5f --- /dev/null +++ b/docs/signing-key-operations.md @@ -0,0 +1,11 @@ +# Signing key operations (development boundary) + +The v6 smoke launcher generated a fresh P-256 private key in memory on every process start. This is test-only behavior: every restart changes the public key, so certificates and lease signatures issued before restart must not be treated as verifiable across the restart. + +For persistent development and production, inject `LICENSE_SIGNING_PRIVATE_KEY_PEM` from a secret manager or protected process environment. Do not put private keys in Git, database rows, browser storage, `.env` files, logs, crash dumps, or HTTP responses. Restart acceptance requires the same protected key to be injected and `/api/v1/activation/public-key` to remain stable. + +`LICENSE_SIGNING_PRIVATE_KEY_FILE` now supports an absolute protected PEM file path; configuring both file and PEM sources is rejected. The file must be readable, nonempty and at most 16 KiB. Host ACL enforcement, secret-manager provisioning and startup cryptographic format validation are not provided by this config loader; signing handlers still enforce P-256 format. File content is read once at startup, not hot-reloaded. Compose mounts this file read-only. The existing 18081 process has not been restarted or rotated. + +`key_id`, public-key sets and overlapping verification windows are NOT implemented. The current public-key response contains a single public key, and certificate/lease payloads do not carry a key identifier. No persistent key was created or provisioned during this slice. + +Planned rotation contract: add an immutable `key_id` to activation certificates and lease payloads, publish a public-key set by `key_id`, and retain old public keys for the certificate/lease verification window. Rotation and revocation ownership remain pending T01/T02 approval; no automatic key replacement is implemented by this slice. diff --git a/docs/task-execution.md b/docs/task-execution.md new file mode 100644 index 0000000..584a2ef --- /dev/null +++ b/docs/task-execution.md @@ -0,0 +1,144 @@ +# 开发任务执行记录 + +## 2026-10-01:DEV keyring / 独立客户端 / 发布矩阵 + +- 本轮发布证据收口:未执行 OS 进程级 v2 keyring 重启。现有 `TestSigningFileAPIRestart` 只验证持久文件下 v1 canonical license/lease 的公钥连续性,且 `SIGNING_RESTART_TEST_DSN` 与 `ENTRY_REDIS_TEST_ADDR` 当前未配置;不能把进程内 router 重注册或该 v1 测试扩大为 v2 真实激活/心跳重启验收。 +- 浏览器仅检查未认证 `/customer` 页面:`http://127.0.0.1:15173/customer` 在移动 390x844 和桌面 1440x900 下 `document/body scrollWidth == viewport clientWidth`,无横向溢出;未输入、记录或截图任何实例凭据,因此跨租户错误和真实下载仍未做浏览器验收。 +- 隔离 Compose 未启动:`docker compose config --quiet` 和 `docker compose build api` 均在插值阶段拒绝,缺少受保护外部路径 `MYSQL_APP_SECRET_FILE`、`MYSQL_ROOT_SECRET_FILE`、`LICENSE_SIGNING_KEY_HOST_FILE`、`PACKAGE_STORAGE_HOST`;本轮未创建伪密钥、未放宽路径要求、未触碰现有业务服务。此前 API 镜像还曾受 `proxy.golang.org` TCP/443 阻断。 + + +- 显式LICENSE_KEYRING_FILE启用license-v2/lease-v2,签名载荷包含key_id;启动校验当前公私钥匹配、唯一ID、撤销和P256,旧public key保留验证。默认v1不变、历史JSON/幂等重放不改,无新增schema迁移。生命周期尚未批准,不是正式轮换验收。 +- 新client/verify.mjs为Node接入方参考组件而非管理台/客户门户:预置公钥验签、未知/撤销拒绝、实例绑定、14天/权益边界及时间高水位。可信存储/真实宿主集成、防克隆/快照回滚未完成。 +- Go生成只含公钥/签名的临时向量,Node旧/新key、未知/撤销/篡改和租约回拨/离线到期测试通过;私钥只在Go内存,未落盘。真实TLS测试监听同源200/外源403/降级Origin403与Secure/HttpOnly/Strict Cookie、forwarded spoof拒绝通过;这不是生产Nginx证书验收。 +- 完整T01-T30现状、Compose Redis地址/profile缺口、正式TLS/CSRF策略缺口、备份/恢复/回滚步骤见[发布矩阵](release-gate-matrix.md),开发接入文档见[keyring客户端契约](keyring-client-contract-draft.md)。T25客户身份域和门户仍未开始。 +- 真实v2数据库签发/轮换重启、实际接入方、Nginx TLS/fullCompose/Linux race/生产恢复/UAT未执行。18081不重启、不提交/推送/发布/关闭任务。 + + +## 2026-10-01:发布门禁继续推进 + +- 新增Redis Lua分布式入口计数,默认redis模式,缺配置拒绝启动;只允许显式local-dev受控降级,Redis请求故障503且不调用handler。真实隔离Redis两个HTTP实例共享登录额度测试通过,第11次429;关闭客户端503通过。Redis TLS/ACL/HA、eviction/重启计数清零与容量验收未完成。 +- 新API main移走public ready,只在METRICS_ADDR numeric loopback监听ready/metrics。两次真实API启动public ready/metrics=404,internal=200,Compose健康配置改用内部19090,Web仅live。完整Compose运行未验收。 +- 仓库外Windows user-only ACL临时持久key,两次真实API启动公钥一致,旧canonical license-v1与lease-v1签名都验签通过;key测试结束清理、不入仓库/日志。这不是完整真实签发-心跳-重启生命周期验收。key_id/轮换/多key窗口未实现,保持发布阻塞。 +- 浏览器15173未登录表单邮箱/密码/登录快照通过,未输入凭据,仍连旧18081;新API演练为独立子进程加载新源码,演练后停止。 +- Linux race尝试:WSL有gcc无go,官方Go下载网络失败/超时,未获得race结果;CI新增隔离Redis服务及Redis race用例,远端未执行。发布未实现清单见[门禁更新](operations-security.md)。 +- T07/T21/T22/T27/T28/T29仍进行中,T19未开始。没有commit/push/release/close,18081与业务库不动。 + +## 2026-10-01:质量与运维DEV切片 + +- 新增白名单slog JSON请求日志、服务端request_id/trace_id、统一错误关联ID与服务端错误脱敏;panic/startup不输出敏感原始错误。trace_id仅本请求关联,不是分布式trace。 +- 新增可选METRICS_ADDR独立numeric loopback指标监听,公共API无/metrics;记录login/activation/heartbeat/download/license路由成功失败及耗时sum。health仍可经现有Web访问,生产内部限制未完成。 +- 新增认证前四类入口单进程IP固定窗口限流,桶容量10000满时拒绝新key;不是Redis分布式限流,多进程独立计数和重启清零。保留Redis可选且未使用的事实。 +- Cookie增加SameSite=Strict;写请求Origin同源及cross-site Fetch Metadata检查;通用64KiB body上限,上传保留64MiB。无Origin请求仍支持非浏览器客户端,完整CSRF token方案/真实浏览器验收未完成。 +- 新增测试覆盖脱敏、panic、request_id、四入口限流、X-Forwarded-For伪造、请求体known/chunked、Origin/CORS、无效session、Cookie、限流容量/窗口/独立作用域。go test ./...及go vet ./...通过;前端10测试及build通过。race本地因CGO禁用未运行,加入Linux CI但远端执行尚无证据。 +- CI保留Go/frontend检查,新增迁移配对序号/非空、shell语法、Compose config检查;脚本与placeholder config本地通过。这不是SQL/Compose运行验收。必要镜像runtime检查仍受Docker网络阻塞。 +- T07/T27按已实现切片转为进行中,T19未开始,T21/T22/T28/T29保留进行中并更新证据。审计字段仅代码白名单抽查,不代表自动化全量敏感数据验收。详见[运维安全边界](operations-security.md)。 +- 18081未重启、业务库未动、未commit/push/release/close。 + +## 2026-09-30:v6 心跳 / 租约 / 冻结传播 DEV 切片 + +- 新增显式 000006_heartbeat_lease up/down:实例 last_seen/client_seen 高水位、独立 lease_expires_at、freeze_state/observed_state,以及心跳/冻结幂等操作表。专用 MySQL 已显式 up 到006;本轮未执行有数据的 down,回滚演练仍待隔离空库验证。 +- 新增实例凭据心跳与管理员冻结接口;只校验32字节secret的SHA-256,不存储/回显明文。成功心跳、租约、操作记录及audit同事务;60秒限频,重复请求不刷新last_seen,状态变化允许立即传播。 +- lease-v1 P-256签名,UTC服务端时钟,最大14天且不越过entitlement_expires_at;5分钟回拨容差、高水位单调。冻结/撤销联网停用,离线旧租约到原截止的DEV假设见 heartbeat-lease-contract-draft.md。 +- 真实 MySQL TestBusinessMySQLIntegration 通过(3.573s):错误secret、audit失败last_seen回滚、并发幂等、签名验签、限频、载荷冲突、时钟偏差、冻结/恢复/撤销传播。完整 go test ./...、go vet ./... 通过。 +- 前端实例抽屉增加last_seen、租约、冻结、权益与传播状态,不泄露secret;npm test 3文件/9用例及npm run build通过,现有大chunk警告保留。 +- 发布固定公开租约验签向量且单测验证篡改失败;客户端可信存储/执行器、防克隆、迁移、扩容、key_id轮换、异常监测、正式策略/UAT仍阻塞或未实现。T13/T14/T15/T26保持进行中。 +- 21:10后补验:独立库 license_v6_rehearsal_260930 执行005→006→005→006,version=6 dirty=false;admins/customers/products/licenses/license_instances/activation_operations/audit_events夹具保留,006操作表与新增状态在down明确丢弃。新增 TestV6Rehearsal 可复现,需全新专用库,未触碰主测试数据。 +- 已重启18081加载v6源码构建;签名私钥仅启动器内存随机生成/环境注入,不落盘,重启将换DEV公钥且旧租约不适用,生产密钥管理/轮换仍阻塞。真实HTTP:/api/v1/health/live=200 status ok;public-key=200 ECDSA-P256-SHA256;错误secret心跳=403 forbidden;无幂等键=400 invalid_idempotency_key;未登录冻结(含错误参数)=401 unauthorized,认证在参数校验之前。/healthz不存在=404,不是健康路径。 +- 限频由共享MySQL实例FOR UPDATE锁及last_seen时间实现,不是单进程内存计数;认证前全局/来源IP限流、攻击防护、部署容量未验收。 +- 后台新增冻结/恢复确认、幂等重试与刷新状态按钮。浏览器390x844快照获得真实登录表单,但无管理员凭据,且截图display surface不可用;桌面/移动已登录实例操作仍待人工验收,不重置/索要/存储密码。最小操作:用户在15173登录,打开授权实例抽屉,核对无secret,冻结/恢复并由实例下一次真实心跳观察传播状态。 +- 未提交、推送、发布或关闭任务。 + + +任务状态以 [详细开发任务方案](../软件授权与统一管理平台-详细开发任务方案.md) 中的执行状态表为准。每个任务完成后先更新实现/验证依据,再转为待验收;评审、真实环境验收及必要签字全部满足后才标记已验收。阻塞任务不得以建议规则冒充已确认规则。 + +## 2026-09-30:T01/T02 核对,T03 基础设施增量 + +- 保留本轮开始时两份方案文档的已有未提交修改,没有覆盖或回退。 +- T01:阻塞。产品/接入负责人、实例身份、权限矩阵、审批及负载规则仍待确认;现有 ADR 和 U01-U11 是草案。 +- T02:阻塞。正式 OpenAPI、证书、租户与错误码契约依赖 T01。 +- T03:进行中。新增环境配置加载与校验、HTTP 请求超时、禁用默认可信代理、信号优雅退出;新增配置默认值、覆盖值及非法输入测试。 +- 新增可测试的 HTTP 生命周期实现:真实 TCP 监听、在途请求排空、优雅退出超时和监听失败测试均已覆盖。 +- 新增前端 Vitest/jsdom 测试:API 在线/异常检测和首页初次检测/手动重测共 5 个用例通过;CI 已加入 `npm test`。 +- 新增迁移目录规范。未创建业务 SQL,未选择迁移执行器,未执行 MySQL 空库/回滚验收。 +- 本地执行 `cd backend && go test ./...`:通过;`go vet ./...`:通过。 +- 本地执行 `cd frontend && npm test`:2 个测试文件、5 个用例通过;`npm run build`:类型检查及生产构建通过。 +- Element Plus 全量引入导致 JS 大 chunk 警告仍存在;实际迁移验证、代码评审与远端 CI 验证尚缺,因此 T03 未完成。 +- 本轮没有提交或推送;已有开发服务可能仍运行旧进程,新服务入口需重启后生效。 + +## 2026-09-30:后续执行开始 + +- 已核对 git status/diff、两份中文方案及已有实现;未发现根目录 AGENTS.md/CLAUDE.md。保留所有已有增量。 +- T03 继续进行中:选用 golang-migrate v4.18.3(兼容 Go 1.23),专用 MySQL 8 容器只承载本仓库测试夹具,不连接其他项目数据库。 +- T01/T02 继续阻塞;T16/T24 保持暂缓。其余任务只开展不固化未签字业务规则的独立工程子项,不越过正式依赖验收。 +- shell 未提供 apply_patch,使用文件工具精确替换已有内容及创建新文件。 + +## 2026-09-30:T03 迁移与验证增量 + +- 新增 `backend/internal/migrations` 执行器和 `backend/cmd/migrate` 显式命令,支持 `up`、`down`、`version`、人工指定版本的 `force`;服务启动不自动迁移,避免隐式改库。 +- 使用专用 `mysql:8.0` 容器(仅本仓库测试库、独立端口)完成空库 `up`、版本/数据核对、`down`;故意非法 DDL 后确认 `dirty=true`、普通 `up` 被阻断,再显式 force 到版本 1 恢复 clean。演练夹具和容器已删除。 +- `backend/migrations/README.md` 已记录 URL 格式、命令、防误操作边界及演练结果;尚无业务 SQL,T04 仍未开始。 +- Go `test ./...`、`vet ./...` 通过;前端 `npm test` 通过 2 文件/5 用例;`npm run build` 通过(仍有 Element Plus 大 chunk 警告)。生命周期测试继续覆盖真实监听、排空、超时及监听失败。 +- T03 更新为“待验收”:实现和本地检查完成,但真实部署、远端 CI、代码评审仍缺,不能标记“已验收”。 +- 当前下一步:补充客户/产品编辑 UI、API 合同测试和审计/速率限制等安全策略;这些工作需与待确认的正式权限、租户和授权规则保持隔离。 + +## 2026-09-30:基础管理台业务切片 + +- 按继续实施指令完成第一条可运行业务纵向切片:新增核心 MySQL 迁移(管理员、会话、客户、产品),真实数据库 CRUD API,bcrypt 管理员初始化命令,HttpOnly 会话令牌、服务端 admin 角色控制、统一错误结构和客户分页搜索。 +- 新增 Vue 管理台登录、会话恢复/退出、客户新增/搜索/删除、产品新增/查看/删除页面;保留健康检查和错误/空状态。 +- 专用 MySQL 8.0 隔离库已执行 migration version 1 clean;真实集成测试验证未登录 401、bcrypt 登录、会话 cookie、客户/产品写读、登出后会话失效。测试账户仅用于隔离库,容器仍可供本地试用,不代表 UAT。 +- 初始化方式为 `backend/cmd/admin-init`,密码要求至少 12 位,不写入默认密码。`docs/business-contract-draft.md` 记录了未签字的临时契约假设;授权激活、心跳、续期、退款、克隆、实例绑定等未决业务没有固化。 +- `docs/business-quickstart.md` 记录数据库、迁移、管理员初始化、后端和前端启动方式。当前切片完成后仍不是完整授权产品;T01/T02及正式OpenAPI/RBAC/安全运维规则仍待确认,任务保持进行中或待验收。 + +## 2026-09-30:期限授权切片 + +- 新增 migration version 2:licenses 与 audit_events;专用 MySQL 已验证 version 2 clean。迁移仍显式执行,服务启动不自动改库。 +- 管理员 API 新增期限授权签发与分页查看。签发生成 128-bit 十六进制密钥;同一管理员幂等键要求请求字段一致;管理员/客户/产品事务锁保证并发一致;授权插入和 `license.issued` 审计原子提交。 +- 新增前端授权表单和列表,active 客户/产品选择、RFC3339 时间、提交中防重复、失败重试复用幂等键、分页、空/错误状态。该切片不是激活凭证、证书、订单、实例绑定或完整权益模型。 +- 真实 MySQL 集成覆盖未认证 401、首次 201、重放 200、载荷冲突 409、viewer 403、停用产品 400、审计故障回滚、并发一写一重放及一授权一审计;当前 `go test ./...`、`go vet ./...`、前端 `npm test`(6 用例)和 `npm run build` 通过。 +- 已重启隔离后端 `127.0.0.1:18081`,浏览器实际登录并签发第二条授权;桌面 1200px、移动 390px 检查无横向溢出,截图留存于会话下载目录。浏览器驱动 fill/click 异常,交互验证部分使用原生 DOM 事件,不能替代完整 UAT。 +- 文档新增 DEV-LICENSE-v0.1 期限/幂等边界;T02 正式契约、T04 完整模型、生产代理 TLS、客户/产品编辑和完整权限/审计仍未验收。 + +## 2026-09-30:授权详情、撤销与续期切片 + +- 新增 migration version 3 `license_operations`,按管理员、操作类型和幂等键保存请求指纹;迁移已应用到隔离 MySQL,服务启动仍不自动迁移。 +- 新增 `GET /api/v1/licenses/:id`、`POST /api/v1/licenses/:id/revoke`、`POST /api/v1/licenses/:id/renew`。撤销/续期锁定授权行,在同一事务更新授权、写操作幂等记录和审计;重放返回原结果,变更请求返回 409。 +- 续期只延后后台记录的结束时间;已撤销授权不可续期。前端表格提供确认撤销和 RFC3339 续期操作;仍不构成激活、订单、续费、退款或离线授权流程。 +- 真实 MySQL 集成新增详情、续期重放/冲突、撤销重放、撤销后续期拒绝和审计计数;`go test ./...`、`go vet ./...`、真实 MySQL 集成、前端 6 项测试和 `npm run build` 全部通过。构建仍有约 1.1MB JS chunk warning。 +- DEV-LICENSE-v0.1 已记录这些实现假设;T01/T02 正式状态机、权限/错误契约、实例和权益规则仍待确认,T12/T18 保持进行中。 + +## 2026-09-30 v4 线下订单开发切片 + +- 已显式应用 000004_orders 迁移;历史 migrations 不改,启动不自动迁移。 +- 真实接口:GET/POST `/api/v1/orders`、GET `/api/v1/orders/:id`、POST `/:id/confirm-payment`、POST `/:id/issue`。整数分 CNY、active 主数据校验、admin 服务端门禁、待收款->已收款->已发放。 +- Vue OrdersPanel 已接入真实 API,包含录单、分页列表、详情抽屉、收款对话框、发放对话框;未变请求失败后保留幂等键,成功后清除。 +- MySQL 集成覆盖未登录/非admin拒绝、无键/金额错误、inactive 客户/产品、顺序限制、同键重放/异请求冲突、并发发放一写一重放、不同键重复发放拒绝、支付及发放审计故障回滚、授权关联范围、操作与审计计数。 +- `go test ./...`、`go vet ./...`、指定真实 MySQL 集成均通过;前端 9 项 Vitest 和 vue-tsc/Vite build 通过。Element Plus 选择器在单测中使用可控 stub 验证重试逻辑,不等同真实浏览器验证。构建仍有约 1.1MB JS chunk warning。 +- DEV 合同已补充一订单一产品一授权、续期起始日、退款/撤销和审批角色待签字事项。未实现套餐/价格权益快照、审批、退款、激活、证书或报表;T17/T18/T26 仍进行中,T20 尚未实现。 +- 本记录仅为本地开发证据,不代表 UAT/生产验收;未 commit/push,也未关闭任务。 + +## 下载纵向切片补充(2026-09-30) + +- 007 历史未改;新增 008 package_objects 摘要锁表,支持跨产品相同 digest 并发及发布失败文件清理。提交确认丢失/进程崩溃仍需孤立文件对账,不做原子文件系统与 MySQL 承诺。 +- 专用 license_download_260930 真实 MySQL 测试通过:客户/产品隔离、secret 错误、冻结/撤销/主数据停用、未登录发布、审计失败、失败上传文件与记录回滚、重复摘要并发、64 MiB 精确边界。 +- Linux 容器路径与 symlink 测试无 skip 通过。隔离 Nginx 18181 + 临时 API 18082 验证真实字节/SHA256、Range 206、外部 internal 路径拒绝和未鉴权拒绝;测试服务已停止。未改其他项目 Nginx。 +- Vue 版本分页列表/原始文件上传/加载错误态已接入;4 文件 10 项 Vitest、类型检查/build、Go test/vet 通过。现有 bundle warning 保留;用户登录浏览器验收单列未执行。 +- 开发 18081 保留原 v6 临时密钥,未擅自重启轮换;主库仍 007。008 与新版运行待保护性持久密钥注入/明确测试密钥轮换批准。key_id/多公钥版本目前仅方案,未声称实现。 +- T11/T12、U07/U08 仍进行中,不标待验收;分块上传/重试续传、崩溃清理、正式密钥生命周期仍未完成。合同与证据见 docs/download-contract-draft.md 和 docs/signing-key-operations.md。未 commit/push/发布/关闭任务。 + +## 2026-09-30:下载拒绝矩阵与部署交付增量 + +- 新增 expired、unpublished、missing-release 三项真实 MySQL 拒绝测试,均为403、无X-Accel-Redirect,每次增加一条 release.download_denied 审计;有效实例使用数值主键核对审计。隔离 MySQL/Nginx 整体回归通过(4.08s),含真实字节/SHA256、Range 206、internal路径404;临时服务已停止。 +- 配置增加 LICENSE_SIGNING_PRIVATE_KEY_FILE 绝对保护文件注入,拒绝双来源/不可读/空或超限文件;PACKAGE_STORAGE_ROOT 必须是绝对现存目录。配置单测通过;key_id、公钥集合、重叠轮换仍未实现,密钥格式仍在签名handler校验。未生成/保存新的持久密钥,18081未重启。 +- 只读数据库核对:license_platform=007 clean,license_download_260930=008 clean。迁移README补007到008回填前校验、对象并发锁、commit确认不确定保留文件、崩溃孤儿对账与隔离删除语义;自动对账/GC仍未实现。 +- T08推进为进行中:新增compose.yaml、Go API/迁移镜像、Vue/Nginx镜像、保护secret文件、内部网络/健康依赖及只读包挂载。默认不发布MySQL/Redis/API或目录,web只监听宿主127.0.0.1:18083。Redis尚非API功能依赖。 +- docker compose config --quiet通过;web镜像构建通过。API镜像第一次下载层EOF,第二次go mod download被Docker DNS到proxy.golang.org超时阻断,未算成功。完整Compose运行未验收,无自动迁移现有主库。 +- Go test ./...和vet ./...通过;前端4文件10用例、类型检查/Vite构建通过,约1.13MB chunk警告保留;镜像npm ci报告2项moderate依赖漏洞,未强制升级。 +- 新增 `/api/v1/health/ready`:必须能查数据库且唯一schema_migrations为version 8 dirty=false;启动也拒绝旧/未来/dirty/不可用schema;readiness只返回通用503。单测覆盖以上故障矩阵,Compose API/web healthcheck改用ready。HTTP_TRUSTED_PROXY_CIDRS仅接受显式非零CIDR,拒绝trust-all;SESSION_COOKIE_SECURE可显式强制,X-Forwarded-Proto未经代理信任不会令cookie安全。TLS样例要求真实受管证书,未启用自签证书。Redis置于可选cache profile,当前API不依赖Redis。 +- 新增scripts/backup-delivery.sh与restore-delivery.sh:MySQL最小权限dump(no-tablespaces)、私有包tar/sha256,恢复要求YES且目标目录为空,清单不含签名key。一次性隔离MySQL恢复演练通过:schema 8 clean、package_objects和文件SHA256一致,容器已清理;未触碰业务库。 +- docs/deployment-delivery.md已更新TLS/CIDR/Secure cookie、readiness、Redis可选语义及备份证据。Docker API构建仍被proxy.golang.org出站连接拒绝阻断,不能算完整Compose运行。浏览器人工登录、U07、正式合同和UAT仍开放;不提交/推送/发布/关闭任务。 + +## 下一步 + +1. 由产品和集成负责人确认 T01/T02 正式授权、实例、权益、权限和错误契约,再决定是否演进 DEV-LICENSE-v0.1。 +2. 补齐完整 RBAC、审计查询/导出、客户/产品编辑及正式 OpenAPI/契约测试,并完成远端 CI、评审、部署验收。 +3. T16/T24 保持暂缓,其余任务按方案依赖实施并逐项更新,不把当前切片算作完整授权产品。 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 73b2117..39322e9 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -16,11 +16,28 @@ }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", + "@vue/test-utils": "^2.5.1", + "jsdom": "^26.1.0", "typescript": "^5.7.3", "vite": "^6.0.5", + "vitest": "^3.2.7", "vue-tsc": "^2.2.0" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, "node_modules/@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", @@ -67,6 +84,121 @@ "node": ">=6.9.0" } }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmmirror.com/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmmirror.com/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmmirror.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmmirror.com/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@ctrl/tinycolor": { "version": "4.2.1", "resolved": "https://registry.npmmirror.com/@ctrl/tinycolor/-/tinycolor-4.2.1.tgz", @@ -575,6 +707,13 @@ "node": "^22.20 || ^24.12 || >=25" } }, + "node_modules/@one-ini/wasm": { + "version": "0.2.1", + "resolved": "https://registry.npmmirror.com/@one-ini/wasm/-/wasm-0.2.1.tgz", + "integrity": "sha512-TUqERXGNTifZ9y2g3wPxQrw3HpHv/02DsW3D90T9x0hhonrL1ZqpSmNrU2XkoIq0fP1N6gZfVQzy2Fw1ZvGBNg==", + "dev": true, + "license": "MIT" + }, "node_modules/@popperjs/core": { "name": "@sxzz/popperjs-es", "version": "2.11.8", @@ -936,6 +1075,24 @@ "win32" ] }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmmirror.com/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz", @@ -978,6 +1135,131 @@ "vue": "^3.2.25" } }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@volar/language-core": { "version": "2.4.15", "resolved": "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.15.tgz", @@ -1147,6 +1429,27 @@ "integrity": "sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q==", "license": "MIT" }, + "node_modules/@vue/test-utils": { + "version": "2.5.1", + "resolved": "https://registry.npmmirror.com/@vue/test-utils/-/test-utils-2.5.1.tgz", + "integrity": "sha512-V/4a99odJ7hapr0bRt35XxljGk8hefq31gSOnlKTcEq2fUeoj2qb+FcpJYfQu4qfYhW9Ug+O2+CZ3QmZ7gXDzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-beautify": "^2.0.0", + "vue-component-type-helpers": "^3.0.0" + }, + "peerDependencies": { + "@vue/compiler-dom": "3.x", + "@vue/server-renderer": "3.x", + "vue": "3.x" + }, + "peerDependenciesMeta": { + "@vue/server-renderer": { + "optional": true + } + } + }, "node_modules/@vueuse/core": { "version": "15.0.0", "resolved": "https://registry.npmmirror.com/@vueuse/core/-/core-15.0.0.tgz", @@ -1194,6 +1497,16 @@ "vue": "^3.5.0" } }, + "node_modules/abbrev": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/abbrev/-/abbrev-5.0.0.tgz", + "integrity": "sha512-/XrFJgzQQQHpti1raDJC6m4ws6aNktmjBlhk8Fdlk7LwCEuDoieEJJY9OFHjfiFJFFRM2tK+Ky/IsfbbmlMu1w==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/agent-base": { "version": "6.0.2", "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz", @@ -1213,6 +1526,16 @@ "dev": true, "license": "MIT" }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/async-validator": { "version": "4.2.5", "resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz", @@ -1254,6 +1577,16 @@ "balanced-match": "^1.0.0" } }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmmirror.com/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/call-bind-apply-helpers": { "version": "1.0.2", "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", @@ -1267,6 +1600,33 @@ "node": ">= 0.4" } }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmmirror.com/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz", @@ -1279,12 +1639,61 @@ "node": ">= 0.8" } }, + "node_modules/commander": { + "version": "14.0.3", + "resolved": "https://registry.npmmirror.com/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/config-chain": { + "version": "1.1.13", + "resolved": "https://registry.npmmirror.com/config-chain/-/config-chain-1.1.13.tgz", + "integrity": "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/dayjs": { "version": "1.11.23", "resolved": "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.23.tgz", @@ -1315,6 +1724,23 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmmirror.com/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -1338,6 +1764,64 @@ "node": ">= 0.4" } }, + "node_modules/editorconfig": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/editorconfig/-/editorconfig-3.0.2.tgz", + "integrity": "sha512-T0ix8GhtxyKVfUFEcvdNDt3YGqlwkFHbD4/5bgFUDgFmxhI/cSRAeJ87/Sz//Cq8Eam6JX/e23RkoFO71P7aAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@one-ini/wasm": "0.2.1", + "commander": "^14.0.3", + "minimatch": "~10.2.4", + "semver": "^7.7.4" + }, + "bin": { + "editorconfig": "bin/editorconfig" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/editorconfig/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/editorconfig/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/editorconfig/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/element-plus": { "version": "2.14.6", "resolved": "https://registry.npmmirror.com/element-plus/-/element-plus-2.14.6.tgz", @@ -1394,6 +1878,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmmirror.com/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.2", "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.2.tgz", @@ -1469,6 +1960,16 @@ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", "license": "MIT" }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", @@ -1584,6 +2085,63 @@ "node": ">= 0.4" } }, + "node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmmirror.com/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz", @@ -1645,6 +2203,43 @@ "he": "bin/he" } }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/https-proxy-agent": { "version": "5.0.1", "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", @@ -1658,6 +2253,133 @@ "node": ">= 6" } }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmmirror.com/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-beautify": { + "version": "2.0.3", + "resolved": "https://registry.npmmirror.com/js-beautify/-/js-beautify-2.0.3.tgz", + "integrity": "sha512-cyFbh3tkPhknnTD/0bLf0T0yy2ZIbqL05mttzbt4y1Zfr7NxqXQZ62dkBLKs3oHH/lpjmDRAnciJiSUyOy8XwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "config-chain": "^1.1.13", + "editorconfig": "^3.0.2", + "glob": "^13.0.6", + "js-cookie": "^3.0.8", + "nopt": "^10.0.1" + }, + "bin": { + "css-beautify": "js/bin/css-beautify.js", + "html-beautify": "js/bin/html-beautify.js", + "js-beautify": "js/bin/js-beautify.js" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/js-cookie": { + "version": "3.0.8", + "resolved": "https://registry.npmmirror.com/js-cookie/-/js-cookie-3.0.8.tgz", + "integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmmirror.com/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/jsdom/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/lodash": { "version": "4.18.1", "resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.18.1.tgz", @@ -1681,6 +2403,20 @@ "lodash-es": "*" } }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", @@ -1742,6 +2478,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmmirror.com/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", @@ -1773,12 +2519,61 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/nopt": { + "version": "10.0.1", + "resolved": "https://registry.npmmirror.com/nopt/-/nopt-10.0.1.tgz", + "integrity": "sha512-df3sBr/6ax9hSGuC3CspvLlbnX8cP5L5nZwXF8cGN8l0zSWR6BvzmQ6jPUKjvo6+/xdpkNvEcucBNUdBeeV13g==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^5.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/normalize-wheel-es": { "version": "1.2.0", "resolved": "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz", "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", "license": "BSD-3-Clause" }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmmirror.com/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/path-browserify": { "version": "1.0.1", "resolved": "https://registry.npmmirror.com/path-browserify/-/path-browserify-1.0.1.tgz", @@ -1786,6 +2581,50 @@ "dev": true, "license": "MIT" }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmmirror.com/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", @@ -1855,6 +2694,13 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/proto-list": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/proto-list/-/proto-list-1.2.4.tgz", + "integrity": "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==", + "dev": true, + "license": "ISC" + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -1864,6 +2710,16 @@ "node": ">=10" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/rollup": { "version": "4.63.5", "resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.63.5.tgz", @@ -1910,6 +2766,53 @@ "fsevents": "~2.3.2" } }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmmirror.com/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz", @@ -1919,6 +2822,54 @@ "node": ">=0.10.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmmirror.com/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmmirror.com/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -1936,6 +2887,82 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmmirror.com/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmmirror.com/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmmirror.com/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmmirror.com/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz", @@ -2025,6 +3052,102 @@ } } }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, "node_modules/vscode-uri": { "version": "3.2.0", "resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.2.0.tgz", @@ -2116,6 +3239,123 @@ "peerDependencies": { "typescript": ">=5.0.0" } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmmirror.com/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmmirror.com/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" } } } diff --git a/frontend/package.json b/frontend/package.json index 82e2e72..fc1c67f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite --host 127.0.0.1", "build": "vue-tsc --noEmit && vite build", + "test": "vitest run", "typecheck": "vue-tsc --noEmit" }, "dependencies": { @@ -17,8 +18,11 @@ }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", + "@vue/test-utils": "^2.5.1", + "jsdom": "^26.1.0", "typescript": "^5.7.3", "vite": "^6.0.5", + "vitest": "^3.2.7", "vue-tsc": "^2.2.0" } } diff --git a/frontend/src/admin-api.test.ts b/frontend/src/admin-api.test.ts new file mode 100644 index 0000000..8e6ec0e --- /dev/null +++ b/frontend/src/admin-api.test.ts @@ -0,0 +1,32 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +const api = vi.hoisted(() => ({get:vi.fn(),put:vi.fn(),post:vi.fn()})) +vi.mock('./api', () => ({api})) +import { changePassword, getSettings, listAuditEvents, redactAuditDetails, saveSettings, validatePassword, validateSettings } from './admin-api' +beforeEach(() => vi.resetAllMocks()) +describe('admin API contract', () => { + it('uses the exact endpoints, params and request fields', async () => { + const params = {page:2,page_size:50,q:'admin',action:'update',resource_type:'settings',from:'2026-10-01T00:00:00.000Z',to:'2026-10-09T00:00:00.000Z'} + await listAuditEvents(params); expect(api.get).toHaveBeenCalledWith('/audit-events',{params}) + await getSettings(); expect(api.get).toHaveBeenCalledWith('/settings') + const body = {site_name:'License Hub',support_email:'',announcement:'维护公告'} + await saveSettings(body); expect(api.put).toHaveBeenCalledWith('/settings',body) + await changePassword({current_password:'old',new_password:'a'}); expect(api.post).toHaveBeenCalledWith('/settings/password',{current_password:'old',new_password:'a'}) + }) + it('redacts nested, array and encoded password fields without mutating input', () => { + const details = {current_password:'secret',nested:[{newPassword:'secret2',PASSWORD_HASH:'hash',name:'visible'}],payload:'{"password":"encoded"}'} + const result = redactAuditDetails(details) + expect(JSON.stringify(result)).not.toMatch(/secret|hash|encoded/) + expect(JSON.stringify(result)).toContain('visible'); expect(details.current_password).toBe('secret') + }) + it('enforces Unicode character and UTF-8 byte limits without complexity rules', () => { + expect(validatePassword('old','a','a')).toBe('') + expect(validatePassword('old','密'.repeat(24),'密'.repeat(24))).toBe('') + expect(validatePassword('old','密'.repeat(25),'密'.repeat(25))).toContain('72') + expect(validatePassword('old','','')).not.toBe('') + expect(validatePassword('old','a','b')).toContain('不一致') + expect(validateSettings({site_name:'😀'.repeat(100),support_email:'',announcement:'文'.repeat(2000)})).toBe('') + expect(validateSettings({site_name:'x'.repeat(101),support_email:'',announcement:''})).toContain('站点名称') + expect(validateSettings({site_name:'x',support_email:'bad',announcement:''})).toContain('邮箱') + expect(validateSettings({site_name:'x',support_email:'',announcement:'x'.repeat(2001)})).toContain('公告') + }) +}) diff --git a/frontend/src/admin-api.ts b/frontend/src/admin-api.ts new file mode 100644 index 0000000..ee63d8b --- /dev/null +++ b/frontend/src/admin-api.ts @@ -0,0 +1,49 @@ +import { api } from './api' + +export type AuditEvent = { id:number; actor_admin_id:number; actor_email:string; action:string; resource_type:string; resource_id:string|number|null; details:Record; created_at:string } +export type AuditParams = { page:number; page_size:number; q?:string; action?:string; resource_type?:string; from?:string; to?:string } +export type SiteSettings = { site_name:string; support_email:string; announcement:string; updated_at:string|null } +export type SettingsInput = Pick +export const listAuditEvents = (params:AuditParams) => api.get<{data:AuditEvent[];meta:{page:number;page_size:number;total:number}}>('/audit-events', {params}) +export const getSettings = () => api.get<{data:SiteSettings}>('/settings') +export const saveSettings = (body:SettingsInput) => api.put<{data:SiteSettings}>('/settings', body) +export const changePassword = (body:{current_password:string;new_password:string}) => api.post('/settings/password', body) +export type AdminAccount = { id:number; username:string; email:string; active:boolean; created_at:string } +export const listAdmins = () => api.get<{data:AdminAccount[]}>('/admins') +export const createAdmin = (body:{username:string;email:string;password:string}) => api.post<{data:AdminAccount}>('/admins', body) +export const setAdminActive = (id:number, active:boolean) => api.post(`/admins/${id}/active`, {active}) +export const resetAdminPassword = (id:number, password:string) => api.post(`/admins/${id}/reset-password`, {password}) + +export type IntegrationLanguage = 'python'|'go'|'java'|'dotnet'|'nodejs' +export type IntegrationMode = 'desktop'|'service'|'container' +export type IntegrationKit = { + protocol_version:string; platform_base_url:string; language:IntegrationLanguage; language_label:string; mode:IntegrationMode; mode_label:string + endpoints:{method:string;path:string;purpose:string}[]; security_rules:string[]; prompt:string + protocol:string + payload_example:{version:string;instance_id:string;state:string;server_time:string;entitlement_expires_at:string;lease_expires_at:string} +} +export const getIntegrationKit = (language:IntegrationLanguage, mode:IntegrationMode) => api.get<{data:IntegrationKit}>('/integration-kit', {params:{language,mode}}) + +// Apply at every depth, including arrays and serialized JSON, before rendering. +export function redactAuditDetails(value:unknown):unknown { + if (Array.isArray(value)) return value.map(redactAuditDetails) + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /password|passwd|pwd|密码/i.test(key) ? '[已隐藏]' : redactAuditDetails(item)])) + } + if (typeof value === 'string') { + try { return redactAuditDetails(JSON.parse(value)) } catch { return value } + } + return value +} +export function validateSettings(value:SettingsInput):string { + if (!value.site_name.trim() || Array.from(value.site_name).length > 100) return '站点名称须为 1–100 个字符' + if (Array.from(value.support_email).length > 254 || (value.support_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.support_email))) return '联系邮箱须为空或合法邮箱,最多 254 个字符' + if (Array.from(value.announcement).length > 2000) return '公告最多 2000 个字符' + return '' +} +export function validatePassword(current:string, next:string, confirmation:string):string { + if (!current) return '请输入当前密码' + if (!next || new TextEncoder().encode(next).length > 72) return '新密码不能为空,且 UTF-8 编码不得超过 72 字节' + if (next !== confirmation) return '两次输入的新密码不一致' + return '' +} diff --git a/frontend/src/api-health.test.ts b/frontend/src/api-health.test.ts new file mode 100644 index 0000000..dfe9c4a --- /dev/null +++ b/frontend/src/api-health.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it, vi } from 'vitest' +import axios from 'axios' +import { checkApiHealth } from './api-health' + +describe('checkApiHealth', () => { + it('returns online for the live response', async () => { + const request = vi.fn().mockResolvedValue({ data: { status: 'ok' } }) + await expect(checkApiHealth(request)).resolves.toBe('online') + expect(request).toHaveBeenCalledWith('/api/v1/health/live', { timeout: 3000 }) + }) + + it('returns offline for invalid status', async () => { + await expect(checkApiHealth(vi.fn().mockResolvedValue({ data: { status: 'degraded' } }))).resolves.toBe('offline') + await expect(checkApiHealth(vi.fn().mockResolvedValue({ data: null }))).resolves.toBe('offline') + }) + + it('returns offline when the request rejects', async () => { + await expect(checkApiHealth(vi.fn().mockRejectedValue(new Error('network unavailable')))).resolves.toBe('offline') + }) + + it('uses Axios by default', async () => { + const request = vi.spyOn(axios, 'get').mockResolvedValue({ data: { status: 'ok' } } as never) + await expect(checkApiHealth()).resolves.toBe('online') + expect(request).toHaveBeenCalledOnce() + request.mockRestore() + }) +}) diff --git a/frontend/src/api-health.ts b/frontend/src/api-health.ts new file mode 100644 index 0000000..950fc1c --- /dev/null +++ b/frontend/src/api-health.ts @@ -0,0 +1,14 @@ +import axios from 'axios' + +export type Connection = 'checking' | 'online' | 'offline' + +export async function checkApiHealth( + request: typeof axios.get = axios.get, +): Promise> { + try { + const { data } = await request<{ status: string }>('/api/v1/health/live', { timeout: 3000 }) + return data.status === 'ok' ? 'online' : 'offline' + } catch { + return 'offline' + } +} diff --git a/frontend/src/api.ts b/frontend/src/api.ts new file mode 100644 index 0000000..1c4a944 --- /dev/null +++ b/frontend/src/api.ts @@ -0,0 +1,30 @@ +import axios from 'axios' + +export const api = axios.create({ baseURL: '/api/v1', timeout: 8000, withCredentials: true }) +api.interceptors.response.use((response) => response, (error) => { + const message = error.response?.data?.error?.message || '请求失败,请稍后重试' + return Promise.reject(new Error(message)) +}) + +export type Customer = { id:number; name:string; contact_email:string; status:string; created_at:string; updated_at:string } +export type Product = { id:number; code:string; name:string; description:string; active:boolean; created_at:string; updated_at:string } +export async function login(username:string,password:string) { return api.post('/auth/login',{username,password}) } +export async function logout() { return api.post('/auth/logout') } +export async function me() { return api.get('/me') } +export async function listCustomers(params?:Record) { return api.get<{data:Customer[];meta:{page:number;page_size:number;total:number}}>('/customers',{params}) } +export async function createCustomer(value:Pick) { return api.post('/customers',value) } +export async function updateCustomer(id:number,value:Partial) { return api.put(`/customers/${id}`,value) } +export async function deleteCustomer(id:number) { return api.delete(`/customers/${id}`) } +export async function listProducts() { return api.get<{data:Product[]}>('/products') } +export async function createProduct(value:Pick) { return api.post('/products',value) } +export async function updateProduct(id:number,value:Partial) { return api.put(`/products/${id}`,value) } +export async function deleteProduct(id:number) { return api.delete(`/products/${id}`) } +export type License = { id:number; license_key:string; customer_id:number; customer_name:string; product_id:number; product_name:string; product_code:string; status:'active'|'scheduled'|'expired'|'revoked'|string; starts_at:string; expires_at:string; created_at:string } +export async function listLicenses(params?:Record) { return api.get<{data:License[];meta:{page:number;page_size:number;total:number}}>('/licenses',{params}) } +export async function issueLicense(value:{customer_id:number;product_id:number;starts_at:string;expires_at:string}, idempotencyKey:string) { return api.post('/licenses',value,{headers:{'Idempotency-Key':idempotencyKey}}) } +export type LicenseInstance = { id:number; instance_id:string; license_id:number; customer_id:number; product_id:number; status:string; activated_at?:string; certificate_version?:string; created_at:string; last_seen_at?:string; lease_expires_at?:string; freeze_state:string; observed_state:string; entitlement_state:string } +export async function setInstanceFrozen(instanceID:string,frozen:boolean,key:string) { return api.post(`/instances/${instanceID}/freeze`,{frozen},{headers:{'Idempotency-Key':key}}) } +export async function listLicenseInstances(id:number) { return api.get<{data:LicenseInstance[]}>(`/licenses/${id}/instances`) } +export async function getLicense(id:number) { return api.get<{data:License}>(`/licenses/${id}`) } +export async function revokeLicense(id:number,idempotencyKey:string) { return api.post(`/licenses/${id}/revoke`,{}, {headers:{'Idempotency-Key':idempotencyKey}}) } +export async function renewLicense(id:number,expires_at:string,idempotencyKey:string) { return api.post(`/licenses/${id}/renew`,{expires_at},{headers:{'Idempotency-Key':idempotencyKey}}) } diff --git a/frontend/src/dashboard-api.ts b/frontend/src/dashboard-api.ts new file mode 100644 index 0000000..1ed9b61 --- /dev/null +++ b/frontend/src/dashboard-api.ts @@ -0,0 +1,3 @@ +import { api, type License } from './api' +export type DashboardSummary = { active_licenses:number; new_customers:number; paid_revenue_cents:number; currency:string; expiring_licenses:number; generated_at:string; license_trend:{month:string;issued:number;expired:number}[]; upcoming_expirations:License[]; recent_licenses:License[] } +export async function getDashboard(months:number) { return api.get<{data:DashboardSummary}>('/dashboard/summary', {params:{months}}) } diff --git a/frontend/src/date-format.test.ts b/frontend/src/date-format.test.ts new file mode 100644 index 0000000..697f505 --- /dev/null +++ b/frontend/src/date-format.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { formatDateTime } from './date-format' + +function localExpected(date: Date) { + const pad = (value: number) => String(value).padStart(2, '0') + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +} + +describe('formatDateTime', () => { + it('formats an API UTC timestamp in the browser local timezone, including seconds', () => { + const value = '2026-10-08T23:04:05Z' + expect(formatDateTime(value)).toBe(localExpected(new Date(value))) + expect(formatDateTime('2026-10-09T07:04:05+08:00')).toBe(formatDateTime(value)) + }) + + it('pads date components and displays midnight as 00', () => { + expect(formatDateTime(new Date(2026, 0, 2, 0, 3, 4))).toBe('2026-01-02 00:03:04') + }) + + it('handles missing and invalid timestamps without leaking Invalid Date or epoch dates', () => { + for (const value of [null, undefined, '', 'not-a-date', new Date(NaN)]) { + expect(formatDateTime(value)).toBe('—') + expect(formatDateTime(value, '暂无租约')).toBe('暂无租约') + } + }) +}) diff --git a/frontend/src/date-format.ts b/frontend/src/date-format.ts new file mode 100644 index 0000000..b7f7b4f --- /dev/null +++ b/frontend/src/date-format.ts @@ -0,0 +1,16 @@ +const formatter = new Intl.DateTimeFormat('zh-CN', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + hour12: false, +}) + +export function formatDateTime(value: string | Date | null | undefined, empty = '—'): string { + if (!value) return empty + const date = value instanceof Date ? value : new Date(value) + if (Number.isNaN(date.getTime())) return empty + return formatter.format(date).replace(/\//g, '-') +} diff --git a/frontend/src/orders-api.ts b/frontend/src/orders-api.ts new file mode 100644 index 0000000..349e5f4 --- /dev/null +++ b/frontend/src/orders-api.ts @@ -0,0 +1,9 @@ +import { api, type License } from './api' + +export type Order = { id:number; order_no:string; customer_id:number; customer_name:string; product_id:number; product_name:string; amount_cents:number; currency:string; status:string; payment_reference:string|null; paid_at:string|null; license_id:number|null; created_at:string; updated_at:string } +export type NewOrder = { customer_id:number; product_id:number; amount_cents:number; currency:string } +export const listOrders = (page:number) => api.get<{data:Order[];meta:{total:number}}>('/orders',{params:{page,page_size:20}}) +export const getOrder = (id:number) => api.get<{data:Order}>(`/orders/${id}`) +export const createOrder = (body:NewOrder,key:string) => api.post('/orders',body,{headers:{'Idempotency-Key':key}}) +export const confirmPayment = (id:number,body:{amount_cents:number;payment_reference:string},key:string) => api.post(`/orders/${id}/confirm-payment`,body,{headers:{'Idempotency-Key':key}}) +export const issueOrder = (id:number,body:{starts_at:string;expires_at:string},key:string) => api.post<{data:Order;license:License}>(`/orders/${id}/issue`,body,{headers:{'Idempotency-Key':key}}) diff --git a/frontend/src/router.test.ts b/frontend/src/router.test.ts new file mode 100644 index 0000000..3555c35 --- /dev/null +++ b/frontend/src/router.test.ts @@ -0,0 +1,3 @@ +import { describe, expect, it } from 'vitest' +import router from './router' +describe('administration routes',()=>{it('provides a destination for all management navigation items while preserving the customer portal',()=>{const paths=router.getRoutes().map(route=>route.path);for(const path of ['/','/licenses','/customers','/products','/orders','/releases','/integration','/audit','/settings','/customer'])expect(paths).toContain(path)})}) diff --git a/frontend/src/router.ts b/frontend/src/router.ts index 1340484..5643028 100644 --- a/frontend/src/router.ts +++ b/frontend/src/router.ts @@ -1,7 +1,11 @@ import { createRouter, createWebHistory } from 'vue-router' import Overview from './views/Overview.vue' - +import CustomerPortal from './views/CustomerPortal.vue' export default createRouter({ history: createWebHistory(), - routes: [{ path: '/', component: Overview }] + routes: [ + ...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{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:'/customer',component:CustomerPortal}, + {path:'/:pathMatch(.*)*',redirect:'/'} + ] }) diff --git a/frontend/src/style.css b/frontend/src/style.css index 502bf73..65a8c43 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -1 +1,8 @@ -:root{font-family:Inter,"Microsoft YaHei",system-ui,sans-serif;color:#1c2832;background:#f5f7f8;font-synthesis:none}*{box-sizing:border-box}body{margin:0}.workspace{min-height:100vh}.topbar{height:66px;background:#fff;border-bottom:1px solid #e0e5e6;padding:0 clamp(20px,5vw,72px);display:flex;align-items:center;justify-content:space-between}.wordmark{display:flex;align-items:center;gap:11px;font-size:16px;font-weight:700}.mark{display:grid;place-items:center;width:30px;height:30px;border-radius:6px;color:#fff;background:#16675a}.environment{color:#68767b;font-size:13px}.content{max-width:1100px;margin:0 auto;padding:clamp(25px,5vw,56px) 22px}.heading{display:flex;align-items:end;justify-content:space-between;gap:20px;margin-bottom:35px}.eyebrow{color:#16675a;font-weight:700;font-size:12px;margin:0 0 12px}.heading h1{font-size:clamp(24px,4vw,32px);margin:0}.subheading{color:#64737b;margin:8px 0 0}.status-section{background:#fff;border:1px solid #e0e5e6;border-radius:7px;padding:22px 25px;display:flex;justify-content:space-between;align-items:center;gap:20px}.status-section h2,.scope h2{font-size:17px;margin:0 0 5px}.status-section p{margin:0;color:#64737b;font-size:13px}.status{font-size:13px;white-space:nowrap;border-radius:4px;padding:5px 11px}.status.online{background:#e5f5ec;color:#16734a}.status.offline{background:#fff0ea;color:#b44830}.status.checking{background:#f1f3f4;color:#64737b}.scope{margin-top:38px}.scope dl{border-top:1px solid #dfe5e7;margin:16px 0 0}.scope dl div{display:grid;grid-template-columns:180px 1fr;padding:17px 0;border-bottom:1px solid #dfe5e7;gap:12px}.scope dt{color:#64737b}.scope dd{margin:0;font-weight:500}.footnote{color:#64737b;font-size:13px;margin-top:30px}@media(max-width:600px){.heading{align-items:start}.status-section{align-items:start;flex-direction:column}.scope dl div{grid-template-columns:1fr;gap:4px}.environment{display:none}} +:root{font-family:Inter,"Microsoft YaHei",system-ui,sans-serif;color:#1c2832;background:#f5f7f8;font-synthesis:none}*{box-sizing:border-box}body{margin:0}.workspace{min-height:100vh}.topbar{height:66px;background:#fff;border-bottom:1px solid #e0e5e6;padding:0 clamp(20px,5vw,72px);display:flex;align-items:center;justify-content:space-between}.wordmark{display:flex;align-items:center;gap:11px;font-size:16px;font-weight:700}.mark{display:grid;place-items:center;width:30px;height:30px;border-radius:6px;color:#fff;background:#16675a}.environment{color:#68767b;font-size:13px}.content{max-width:1100px;margin:0 auto;padding:clamp(25px,5vw,56px) 22px}.login-panel{max-width:420px;margin:10vh auto;background:#fff;border:1px solid #e0e5e6;border-radius:7px;padding:30px}.login-panel h1{margin:0 0 8px}.login-panel form{display:grid;gap:14px;margin-top:24px}.error{color:#b44830;font-size:13px}.data-section{background:#fff;border:1px solid #e0e5e6;border-radius:7px;padding:22px 25px;margin-bottom:22px}.business-table{max-width:100%;overflow-x:auto}.section-heading{display:flex;justify-content:space-between;gap:20px;align-items:start;margin-bottom:16px}.section-heading h2{margin:0 0 4px;font-size:17px}.section-heading p{margin:0;color:#64737b;font-size:13px}.inline-form{display:flex;gap:8px;min-width:520px}.inline-form .el-input{max-width:170px}.heading{display:flex;align-items:end;justify-content:space-between;gap:20px;margin-bottom:35px}.eyebrow{color:#16675a;font-weight:700;font-size:12px;margin:0 0 12px}.heading h1{font-size:clamp(24px,4vw,32px);margin:0}.subheading{color:#64737b;margin:8px 0 0}.status-section{background:#fff;border:1px solid #e0e5e6;border-radius:7px;padding:22px 25px;display:flex;justify-content:space-between;align-items:center;gap:20px}.status-section h2,.scope h2{font-size:17px;margin:0 0 5px}.status-section p{margin:0;color:#64737b;font-size:13px}.status{font-size:13px;white-space:nowrap;border-radius:4px;padding:5px 11px}.status.online{background:#e5f5ec;color:#16734a}.status.offline{background:#fff0ea;color:#b44830}.status.checking{background:#f1f3f4;color:#64737b}.scope{margin-top:38px}.scope dl{border-top:1px solid #dfe5e7;margin:16px 0 0}.scope dl div{display:grid;grid-template-columns:180px 1fr;padding:17px 0;border-bottom:1px solid #dfe5e7;gap:12px}.scope dt{color:#64737b}.scope dd{margin:0;font-weight:500}.footnote{color:#64737b;font-size:13px;margin-top:30px}@media(max-width:700px){.section-heading{display:block}.inline-form{min-width:0;display:grid;grid-template-columns:1fr;margin-top:15px}.inline-form .el-input{max-width:none}.data-section{padding:16px}.login-panel{margin:5vh auto 0}} +.license-form{min-width:0;display:grid;grid-template-columns:repeat(2,minmax(150px,1fr));width:560px;max-width:100%}.license-form .el-select,.license-form .el-date-editor{width:100%;min-width:0}.license-form .el-button{grid-column:1/-1;justify-self:end}.el-pagination{margin-top:16px}.data-section:has(.license-form) .section-heading{align-items:start}@media(max-width:900px){.data-section:has(.license-form) .section-heading{display:block}.license-form{margin-top:16px;width:100%}}@media(max-width:600px){.license-form{grid-template-columns:minmax(0,1fr)}} +@media(max-width:600px){.heading{align-items:start}.status-section{align-items:start;flex-direction:column}.scope dl div{grid-template-columns:1fr;gap:4px}.environment{display:none}} +.integration-controls{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.integration-controls label{display:flex;align-items:center;gap:8px;font-size:14px}.integration-controls select{min-height:34px;padding:4px 10px;border:1px solid #d8e0e3;border-radius:4px;background:white;color:#263840}.integration-controls .el-form-item{margin-bottom:8px}.integration-controls .el-select{width:150px}.integration-meta{display:flex;gap:20px;flex-wrap:wrap;color:#64737b;font-size:13px;margin:16px 0}.integration-panel h3{font-size:15px;margin:24px 0 12px}.prompt-box{border:1px solid #e0e5e6;padding:16px;border-radius:6px;background:#fbfcfd}.prompt-box pre,.vector-box{white-space:pre-wrap;overflow-wrap:anywhere;font:13px/1.7 ui-monospace,monospace;margin:0 0 12px;max-width:100%}.vector-box{padding:16px;background:#f5f7fa;border:1px solid #e0e5e6;border-radius:6px}.integration-rules{padding-left:20px;font-size:14px;line-height:1.8}.integration-panel summary{cursor:pointer;margin-bottom:12px}@media(max-width:620px){.integration-controls{align-items:stretch;flex-direction:column}.integration-controls .el-form-item{display:block}.integration-controls .el-select{width:100%}.integration-controls a{margin-left:0!important;white-space:normal;height:auto;min-height:32px}.integration-meta{gap:8px}.integration-panel .section-heading{display:block}} +/* Demo-aligned administration shell */ +.admin-workspace{display:flex;min-height:100vh;background:#f6f8fb;color:#17202b}.admin-workspace .sidebar{width:242px;flex:0 0 242px;background:#14202e;color:#fff;padding:23px 14px;display:flex;flex-direction:column}.admin-workspace .brand{display:flex;gap:11px;align-items:center;padding:0 12px 31px;font-size:17px;font-weight:700}.admin-workspace .brand small{display:block;color:#96a5b6;font-size:11px;font-weight:400;margin-top:2px}.brand-mark{width:31px;height:31px;background:#2e83f1;border-radius:8px;display:grid;place-items:center;font-weight:800;color:#fff}.admin-workspace .nav{display:flex;flex-direction:column}.admin-workspace .nav-label{color:#617487;font-size:11px;letter-spacing:.08em;padding:0 13px;margin:13px 0 7px}.admin-workspace .nav a{width:100%;color:#96a5b6;text-decoration:none;text-align:left;padding:10px 13px;border-radius:7px;margin:2px 0;display:flex;gap:11px;align-items:center}.admin-workspace .nav a:hover,.admin-workspace .nav a.active{color:#fff;background:#213247}.admin-workspace .nav .ico{width:18px;text-align:center;font-size:16px}.admin-workspace .sidebar-footer{margin-top:auto;border-top:1px solid #2b3b4e;padding:15px 11px 0;color:#96a5b6;font-size:12px}.admin-workspace .main{flex:1;min-width:0}.admin-workspace .topbar{height:70px;padding:0 32px}.crumb{color:#687586}.crumb strong{color:#17202b;margin-left:7px}.admin-workspace .content{max-width:1440px;padding:30px 34px 46px}.admin-workspace .heading{margin-bottom:27px}.admin-workspace .heading h1{font-size:24px;letter-spacing:-.02em}.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:23px}.stat{background:#fff;border:1px solid #e5e9ef;border-radius:8px;padding:19px 20px;position:relative}.stat>span{display:block;color:#687586;font-size:13px}.stat strong{display:block;font-size:28px;margin-top:7px}.stat small{display:block;color:#16845b;font-size:12px;margin-top:7px}.stat i{position:absolute;right:18px;top:19px;width:36px;height:36px;border-radius:8px;display:grid;place-items:center;font-size:18px;font-style:normal}.i-blue{background:#eaf2ff;color:#1769e0}.i-green{background:#e9f8f1;color:#16845b}.i-amber{background:#fff5df;color:#ae6c00}.i-red{background:#fff0f0;color:#c23b3b}.dashboard-grid{display:grid;grid-template-columns:1.4fr 1fr;gap:18px;margin-bottom:23px}.panel{background:#fff;border:1px solid #e5e9ef;border-radius:8px;padding:20px}.panel-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}.panel h2{font-size:16px;margin:0}.panel-head a,.link,.action{color:#1769e0;text-decoration:none;background:none}.chart{height:182px;display:flex;align-items:end;gap:13px;padding:20px 8px 0;border-bottom:1px solid #e5e9ef}.bar-group{flex:1;height:100%;display:flex;align-items:end;justify-content:center;gap:3px;position:relative;min-width:22px}.bar{width:calc(50% - 2px);min-height:0;border-radius:4px 4px 0 0}.bar.issued{background:#4c96ed}.bar.expired{background:#b9d5fa}.bar-group>span{position:absolute;bottom:-25px;font-size:11px;color:#687586}.legend{display:flex;gap:18px;margin-top:26px;color:#687586;font-size:12px}.legend i{display:inline-block;width:8px;height:8px;background:#4c96ed;border-radius:2px;margin-right:5px}.legend i.expired{background:#b9d5fa}.deadline{display:flex;justify-content:space-between;padding:13px 0;border-bottom:1px solid #edf0f4}.deadline:last-of-type{border-bottom:0}.deadline-name{border:0;background:none;padding:0;text-align:left;font-weight:600;color:#17202b}.deadline-name small{display:block;color:#687586;margin-top:3px;font-weight:400}.tag{font-size:12px;border-radius:4px;padding:3px 8px;white-space:nowrap;height:max-content}.tag.green{color:#16845b;background:#e9f8f1}.tag.amber{color:#ae6c00;background:#fff5df}.tag.red{color:#c23b3b;background:#fff0f0}.table-panel{padding:0;overflow:hidden}.table-head{padding:20px 20px 15px;display:flex;justify-content:space-between;align-items:center}.table-head h2{font-size:16px;margin:0}.filters{display:flex;gap:8px;align-items:center}.filters input,.filters select,.search-button{border:1px solid #e5e9ef;border-radius:5px;padding:7px 10px;background:#fff;color:#17202b}.search-button{color:#1769e0;cursor:pointer}.table-scroll{overflow:auto}.table-panel table{width:100%;border-collapse:collapse}.table-panel th,.table-panel td{text-align:left;padding:13px 20px;border-top:1px solid #edf0f4;white-space:nowrap}.table-panel th{font-size:12px;color:#687586;font-weight:500;background:#fbfcfd}.table-panel td{font-size:13px}.avatar{display:inline-grid;place-items:center;width:28px;height:28px;margin-right:9px;border-radius:50%;background:#e6eefc;color:#356db7;font-size:11px;font-weight:700}.license-code{font-family:ui-monospace,monospace;font-size:12px}.empty-state,.muted{color:#687586;text-align:center;padding:24px}.footer-note{text-align:right;color:#8a96a5;font-size:12px;margin-top:13px}.license-detail{display:grid;grid-template-columns:120px 1fr;gap:12px;border-top:1px solid #e5e9ef;padding-top:16px}.license-detail dt{color:#687586}.license-detail dd{margin:0;font-weight:500} +@media(max-width:960px){.admin-workspace .sidebar{width:72px;flex-basis:72px;padding:20px 10px}.admin-workspace .brand{padding:0 10px 30px}.admin-workspace .brand>div:last-child,.admin-workspace .nav-label,.admin-workspace .nav a span:not(.ico),.admin-workspace .sidebar-footer>span:last-child{display:none}.admin-workspace .brand-mark{margin:auto}.admin-workspace .nav a{justify-content:center;padding:11px}.admin-workspace .sidebar-footer{text-align:center;padding-left:0;padding-right:0}.stats{grid-template-columns:repeat(2,1fr)}.dashboard-grid{grid-template-columns:1fr}.admin-workspace .content{padding:25px 20px}.admin-workspace .topbar{padding:0 20px}} +@media(max-width:620px){.admin-workspace .topbar{height:60px}.stats{gap:10px}.stat{padding:14px}.stat strong{font-size:22px}.table-head{display:block}.filters{margin-top:13px;flex-wrap:wrap}.filters input{width:150px}.admin-workspace .content{padding:20px 13px}.dashboard-grid{gap:12px}.panel{padding:16px}.admin-workspace .heading{display:block}.admin-workspace .heading .el-button{margin-top:15px}} diff --git a/frontend/src/views/AdminsPanel.test.ts b/frontend/src/views/AdminsPanel.test.ts new file mode 100644 index 0000000..4fadaf0 --- /dev/null +++ b/frontend/src/views/AdminsPanel.test.ts @@ -0,0 +1,26 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import ElementPlus from 'element-plus' +const calls=vi.hoisted(()=>({listAdmins:vi.fn(),createAdmin:vi.fn(),setAdminActive:vi.fn(),resetAdminPassword:vi.fn()})) +vi.mock('../admin-api',()=>calls) +import AdminsPanel from './AdminsPanel.vue' +beforeEach(()=>{vi.resetAllMocks();calls.listAdmins.mockResolvedValue({data:{data:[{id:1,username:'admin-1',email:'admin@example.test',active:true,created_at:'2026-10-09T00:00:00Z'}]}});calls.createAdmin.mockResolvedValue({data:{data:{id:2}}})}) +describe('AdminsPanel',()=>{ + it('validates confirmation and clears credentials after creation',async()=>{ + const wrapper=mount(AdminsPanel,{props:{currentUsername:'admin-1'},global:{plugins:[ElementPlus]}});await flushPromises() + expect(wrapper.text()).toContain('admin-1') + await wrapper.find('input[aria-label="管理员用户名"]').setValue('Team_2') + await wrapper.find('input[aria-label="管理员联系邮箱"]').setValue('team@example.test') + await wrapper.find('input[aria-label="管理员密码"]').setValue('New-Password') + await wrapper.find('input[aria-label="确认管理员密码"]').setValue('Wrong') + await wrapper.find('form').trigger('submit');await flushPromises();expect(calls.createAdmin).not.toHaveBeenCalled();expect(wrapper.text()).toContain('两次输入的密码不一致') + await wrapper.find('input[aria-label="确认管理员密码"]').setValue('New-Password');await wrapper.find('form').trigger('submit');await flushPromises() + expect(calls.createAdmin).toHaveBeenCalledWith({username:'team_2',email:'team@example.test',password:'New-Password'}) + expect((wrapper.find('input[aria-label="管理员密码"]').element as HTMLInputElement).value).toBe('');expect(wrapper.text()).toContain('管理员已创建');wrapper.unmount() + }) + it('prevents disabling the current account',async()=>{ + const wrapper=mount(AdminsPanel,{props:{currentUsername:'admin-1'},global:{plugins:[ElementPlus]}});await flushPromises() + const button=wrapper.findAll('button').find(x=>x.text()==='停用');expect(button).toBeDefined();await button!.trigger('click');await flushPromises() + expect(calls.setAdminActive).not.toHaveBeenCalled();expect(wrapper.text()).toContain('不能停用当前登录的管理员');wrapper.unmount() + }) +}) diff --git a/frontend/src/views/AdminsPanel.vue b/frontend/src/views/AdminsPanel.vue new file mode 100644 index 0000000..446f62c --- /dev/null +++ b/frontend/src/views/AdminsPanel.vue @@ -0,0 +1,16 @@ + + diff --git a/frontend/src/views/AuditPanel.test.ts b/frontend/src/views/AuditPanel.test.ts new file mode 100644 index 0000000..fdd3ffd --- /dev/null +++ b/frontend/src/views/AuditPanel.test.ts @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import ElementPlus from 'element-plus' +import { defineComponent, nextTick } from 'vue' +const calls = vi.hoisted(() => ({listAuditEvents:vi.fn()})) +vi.mock('../admin-api', async importOriginal => ({...await importOriginal(),...calls})) +import AuditPanel from './AuditPanel.vue' +const event = {id:1,actor_admin_id:2,actor_email:'admin@example.test',action:'settings.update',resource_type:'settings',resource_id:1,details:{password:'never-render',nested:{current_password:'also-secret',site_name:'Visible'}},created_at:'2026-10-09T00:00:00Z'} +const response = {data:{data:[event],meta:{page:1,page_size:20,total:60}}} +const PaginationStub = defineComponent({ + props: ['currentPage', 'pageSize', 'total', 'disabled'], + emits: ['update:currentPage', 'current-change'], + template: ``, +}) +const options = {global:{plugins:[ElementPlus],stubs:{teleport:true,ElPagination:PaginationStub}}} +beforeEach(() => {vi.resetAllMocks();calls.listAuditEvents.mockResolvedValue(response)}) +describe('AuditPanel', () => { + it('filters with UTC timestamps, paginates and renders redacted detail', async () => { + const wrapper = mount(AuditPanel,options); await flushPromises() + await wrapper.get('[aria-label="搜索审计日志"]').setValue('admin') + await wrapper.get('[aria-label="审计动作"]').setValue('settings.update') + await wrapper.get('[aria-label="资源类型"]').setValue('settings') + await wrapper.get('[aria-label="审计开始时间"]').setValue('2026-10-01T10:00') + await wrapper.get('form').trigger('submit'); await flushPromises() + expect(calls.listAuditEvents).toHaveBeenLastCalledWith({page:1,page_size:20,q:'admin',action:'settings.update',resource_type:'settings',from:new Date('2026-10-01T10:00').toISOString(),to:undefined}) + await wrapper.get('.btn-next').trigger('click'); await flushPromises() + expect(calls.listAuditEvents.mock.calls.at(-1)?.[0].page).toBe(2) + await wrapper.findAll('button').find(b => b.text() === '详情')!.trigger('click'); await flushPromises() + expect(wrapper.text()).toContain('Visible'); expect(wrapper.text()).not.toMatch(/never-render|also-secret/) + await wrapper.findAll('button').find(b => b.text() === '重置')!.trigger('click'); await flushPromises() + expect(calls.listAuditEvents.mock.calls.at(-1)?.[0]).toMatchObject({page:1,from:undefined,q:undefined}) + wrapper.unmount() + }) + it('shows loading, empty and retryable error states', async () => { + let resolve!: (value:typeof response) => void + calls.listAuditEvents.mockReturnValueOnce(new Promise(r => {resolve=r})) + const wrapper = mount(AuditPanel,options) + await nextTick() + expect(wrapper.get('[role="status"]').text()).toContain('正在加载') + resolve({data:{data:[],meta:{page:1,page_size:20,total:0}}}); await flushPromises() + expect(wrapper.text()).toContain('暂无符合条件') + calls.listAuditEvents.mockRejectedValueOnce(new Error('日志接口失败')) + await wrapper.findAll('button').find(b => b.text() === '刷新日志')!.trigger('click'); await flushPromises() + expect(wrapper.get('[role="alert"]').text()).toBe('日志接口失败') + await wrapper.findAll('button').find(b => b.text() === '刷新日志')!.trigger('click'); await flushPromises() + expect(wrapper.find('[role="alert"]').exists()).toBe(false); wrapper.unmount() + }) + it('rejects reversed dates and ignores stale responses', async () => { + let resolve!: (value:typeof response) => void + calls.listAuditEvents.mockReturnValueOnce(new Promise(r => {resolve=r})) + const wrapper = mount(AuditPanel,options) + await wrapper.get('[aria-label="审计开始时间"]').setValue('2026-10-09T10:00') + await wrapper.get('[aria-label="审计结束时间"]').setValue('2026-10-01T10:00') + await wrapper.get('form').trigger('submit'); expect(calls.listAuditEvents).toHaveBeenCalledTimes(1) + await wrapper.get('[aria-label="审计结束时间"]').setValue('2026-10-10T10:00') + calls.listAuditEvents.mockResolvedValueOnce({data:{data:[],meta:{page:1,page_size:20,total:0}}}) + await wrapper.get('form').trigger('submit'); await flushPromises(); resolve(response); await flushPromises() + expect(wrapper.text()).not.toContain('admin@example.test'); wrapper.unmount() + }) +}) diff --git a/frontend/src/views/AuditPanel.vue b/frontend/src/views/AuditPanel.vue new file mode 100644 index 0000000..c08bf30 --- /dev/null +++ b/frontend/src/views/AuditPanel.vue @@ -0,0 +1,64 @@ + + + diff --git a/frontend/src/views/CustomerPortal.test.ts b/frontend/src/views/CustomerPortal.test.ts new file mode 100644 index 0000000..8c0a9c0 --- /dev/null +++ b/frontend/src/views/CustomerPortal.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import CustomerPortal from './CustomerPortal.vue' + +const post = vi.fn() +vi.mock('axios', async () => { + const actual = await vi.importActual('axios') + return { ...actual, default: { ...actual.default, create: () => ({ post }) }, isAxiosError: () => true } +}) + +describe('CustomerPortal', () => { + afterEach(() => { post.mockReset(); vi.restoreAllMocks() }) + it('sends credentials, renders snapshot, and clears them on exit', async () => { + post.mockResolvedValueOnce({ data: { data: { customer:{id:1,name:'Acme'},product:{name:'App',code:'app'},license:{id:3,status:'active',expires_at:'2026-12-01'},instance:{instance_id:'i',status:'activated',freeze_state:'none'},lease:{current_state:'active',expires_at:null},releases:[] },meta:{total:0} } }) + const wrapper = mount(CustomerPortal) + await wrapper.get('input').setValue('instance-1'); await wrapper.get('input[type=password]').setValue('secret-value'); await wrapper.get('form').trigger('submit'); await flushPromises() + expect(post).toHaveBeenCalledWith('/portal/snapshot',{instance_id:'instance-1',secret:'secret-value'},{params:{page:1,page_size:20}}) + expect(wrapper.text()).toContain('Acme'); expect(wrapper.text()).toContain('App'); expect(wrapper.find('input').exists()).toBe(false) + await wrapper.get('button').trigger('click'); expect(wrapper.find('input').exists()).toBe(true); expect((wrapper.find('input[type=password]').element as HTMLInputElement).value).toBe('') + }) + it('shows generic denial and keeps no credential after cross-tenant refusal', async () => { + post.mockRejectedValueOnce({ response:{ data:{ error:{ message:'Invalid credentials' } } } }) + const wrapper=mount(CustomerPortal); await wrapper.get('input').setValue('other'); await wrapper.get('input[type=password]').setValue('bad'); await wrapper.get('form').trigger('submit'); await flushPromises() + expect(wrapper.get('[role=alert]').text()).toContain('请求失败'); expect((wrapper.find('input[type=password]').element as HTMLInputElement).value).toBe('') + }) + it('shows download failure without exposing secret', async () => { + post.mockResolvedValueOnce({ data:{ data:{ customer:{id:1,name:'Acme'},product:{name:'App',code:'app'},license:{id:3,status:'active',expires_at:'2026-12-01'},instance:{instance_id:'i',status:'activated',freeze_state:'none'},lease:{current_state:'active',expires_at:null},releases:[{id:4,version:'1.0',size_bytes:1,download_allowed:true}] },meta:{total:1} } }).mockRejectedValueOnce(new Error('download failed')) + const wrapper=mount(CustomerPortal); await wrapper.get('input').setValue('i'); await wrapper.get('input[type=password]').setValue('secret'); await wrapper.get('form').trigger('submit'); await flushPromises(); await wrapper.get('table button').trigger('click'); await flushPromises() + expect(wrapper.get('[role=alert]').text()).toContain('下载失败'); expect(wrapper.text()).not.toContain('secret') + }) +}) diff --git a/frontend/src/views/CustomerPortal.vue b/frontend/src/views/CustomerPortal.vue new file mode 100644 index 0000000..d925324 --- /dev/null +++ b/frontend/src/views/CustomerPortal.vue @@ -0,0 +1,50 @@ + + + diff --git a/frontend/src/views/DashboardPanel.test.ts b/frontend/src/views/DashboardPanel.test.ts new file mode 100644 index 0000000..40bdf6b --- /dev/null +++ b/frontend/src/views/DashboardPanel.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import DashboardPanel from './DashboardPanel.vue' +import { formatDateTime } from '../date-format' +const mocks=vi.hoisted(()=>({getDashboard:vi.fn(),listLicenses:vi.fn()})) +vi.mock('../dashboard-api',()=>({getDashboard:mocks.getDashboard})) +vi.mock('../api',()=>({listLicenses:mocks.listLicenses})) +const payload={active_licenses:12,new_customers:3,paid_revenue_cents:253400,currency:'CNY',expiring_licenses:2,generated_at:'2026-10-08T00:00:00Z',license_trend:[{month:'2026-10',issued:4,expired:1}],upcoming_expirations:[],recent_licenses:[]} +describe('DashboardPanel',()=>{afterEach(()=>vi.resetAllMocks()) +it('renders values supplied by the dashboard API, never demo defaults',async()=>{mocks.getDashboard.mockResolvedValue({data:{data:payload}});const wrapper=mount(DashboardPanel,{global:{stubs:{'el-button':{template:''}}}});await flushPromises();expect(wrapper.text()).toContain('12');expect(wrapper.text()).toContain('3');expect(wrapper.text()).toContain('¥2,534.00');expect(wrapper.text()).toContain('4');expect(wrapper.text()).toContain('未来 30 天暂无到期授权');expect(mocks.getDashboard).toHaveBeenCalledWith(6);wrapper.unmount()}) +it('renders searched licenses even when the summary is unavailable', async () => { + mocks.getDashboard.mockRejectedValue(new Error('暂时不可用')) + const expires = '2026-10-20T00:03:04Z' + mocks.listLicenses.mockResolvedValue({ data: { data: [{ id: 1, license_key: 'test-license', customer_name: '测试客户', product_name: '测试产品', status: 'active', expires_at: expires }] } }) + const wrapper = mount(DashboardPanel, { global: { stubs: { 'el-button': true, 'router-link': true }, directives: { loading: () => {} } } }) + await flushPromises() + await wrapper.get('form').trigger('submit') + await flushPromises() + expect(wrapper.get('tbody').text()).toContain('test-license') + expect(wrapper.get('tbody').text()).toContain(formatDateTime(expires)) + expect(wrapper.get('tbody').text()).not.toContain(expires) + wrapper.unmount() +}) +it('shows an explicit error when summary loading fails',async()=>{mocks.getDashboard.mockRejectedValue(new Error('暂时不可用'));const wrapper=mount(DashboardPanel,{global:{stubs:{'el-button':true}}});await flushPromises();expect(wrapper.get('[role="alert"]').text()).toContain('暂时不可用');wrapper.unmount()}) +}) diff --git a/frontend/src/views/DashboardPanel.vue b/frontend/src/views/DashboardPanel.vue new file mode 100644 index 0000000..5d6da9c --- /dev/null +++ b/frontend/src/views/DashboardPanel.vue @@ -0,0 +1,28 @@ + + diff --git a/frontend/src/views/IntegrationPanel.test.ts b/frontend/src/views/IntegrationPanel.test.ts new file mode 100644 index 0000000..afa36fe --- /dev/null +++ b/frontend/src/views/IntegrationPanel.test.ts @@ -0,0 +1,27 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import ElementPlus from 'element-plus' +const calls = vi.hoisted(() => ({getIntegrationKit:vi.fn()})) +vi.mock('../admin-api', async importOriginal => ({...await importOriginal(),...calls})) +import IntegrationPanel from './IntegrationPanel.vue' +const kit = {protocol_version:'license-v2 / lease-v2',platform_base_url:'https://license.yihuiyong.cn',language:'python',language_label:'Python 3.11+',mode:'service',mode_label:'常驻服务',endpoints:[{method:'POST',path:'/heartbeat',purpose:'刷新租约'}],security_rules:['不得泄露 secret'],prompt:'实现 LicenseClient',protocol:'DER signature',payload_example:{version:'lease-v2'}} +beforeEach(() => {vi.resetAllMocks();calls.getIntegrationKit.mockResolvedValue({data:{data:kit}})}) +describe('IntegrationPanel',()=>{ + it('loads generated materials and exposes both download formats',async()=>{ + const wrapper=mount(IntegrationPanel,{global:{plugins:[ElementPlus]}});await flushPromises() + expect(calls.getIntegrationKit).toHaveBeenCalledWith('python','service') + expect(wrapper.text()).toContain('实现 LicenseClient');expect(wrapper.text()).toContain('不得泄露 secret') + 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) + 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') + wrapper.unmount() + }) + 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() + }) +}) diff --git a/frontend/src/views/IntegrationPanel.vue b/frontend/src/views/IntegrationPanel.vue new file mode 100644 index 0000000..a294a6c --- /dev/null +++ b/frontend/src/views/IntegrationPanel.vue @@ -0,0 +1,62 @@ + + diff --git a/frontend/src/views/OrdersPanel.test.ts b/frontend/src/views/OrdersPanel.test.ts new file mode 100644 index 0000000..f420c1f --- /dev/null +++ b/frontend/src/views/OrdersPanel.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import type { Customer, Product } from '../api' +import ElementPlus from 'element-plus' +import { defineComponent } from 'vue' +const SelectStub = defineComponent({ name:'ElSelect', props:['modelValue'], emits:['update:modelValue'], template:'' }) +const calls = vi.hoisted(() => ({ listOrders:vi.fn(),getOrder:vi.fn(),createOrder:vi.fn(),confirmPayment:vi.fn(),issueOrder:vi.fn() })) +vi.mock('../orders-api', () => calls) +import OrdersPanel from './OrdersPanel.vue' +const order = {id:42,order_no:'test-order',customer_id:1,customer_name:'测试客户',product_id:2,product_name:'测试产品',amount_cents:100,currency:'CNY',status:'paid',payment_reference:'BANK-001',license_id:null} +const props: {customers: Customer[]; products: Product[]} = {customers:[{id:1,name:'测试客户',contact_email:'a@example.test',status:'active',created_at:'',updated_at:''}],products:[{id:2,code:'test',name:'测试产品',description:'',active:true,created_at:'',updated_at:''}]} +function button(wrapper:ReturnType,text:string) { return wrapper.findAll('button').find(item=>item.text()===text)! } +beforeEach(()=>{vi.resetAllMocks();calls.listOrders.mockResolvedValue({data:{data:[order],meta:{total:1}}});calls.getOrder.mockResolvedValue({data:{data:order}})}) +describe('OrdersPanel',()=>{ + it('loads persisted orders and retrieves detail',async()=>{ + const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus]}});await flushPromises() + expect(wrapper.text()).toContain('test-order');expect(calls.listOrders).toHaveBeenCalledWith(1) + await button(wrapper,'详情').trigger('click');await flushPromises();expect(calls.getOrder).toHaveBeenCalledWith(42) + wrapper.unmount() + }) + it('retains an unchanged create key after failure',async()=>{ + calls.createOrder.mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({}) + const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus],stubs:{teleport:true,ElSelect:SelectStub}}});await flushPromises() + await button(wrapper,'录入订单').trigger('click');await flushPromises() + const selects=wrapper.findAllComponents({name:'ElSelect'}) + selects[0]!.vm.$emit('update:modelValue',1);selects[1]!.vm.$emit('update:modelValue',2);await flushPromises() + await button(wrapper,'创建订单').trigger('click');await flushPromises() + await button(wrapper,'创建订单').trigger('click');await flushPromises() + expect(calls.createOrder).toHaveBeenCalledTimes(2) + expect(calls.createOrder.mock.calls[0]![1]).toBe(calls.createOrder.mock.calls[1]![1]) + expect(calls.createOrder.mock.calls[0]![0]).toEqual({customer_id:1,product_id:2,amount_cents:100,currency:'CNY'}) + wrapper.unmount() + }) + it('displays loading failures',async()=>{ + calls.listOrders.mockRejectedValue(new Error('订单接口失败')) + const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus]}});await flushPromises() + expect(wrapper.get('[role="alert"]').text()).toBe('订单接口失败');wrapper.unmount() + }) +}) diff --git a/frontend/src/views/OrdersPanel.vue b/frontend/src/views/OrdersPanel.vue new file mode 100644 index 0000000..77f799c --- /dev/null +++ b/frontend/src/views/OrdersPanel.vue @@ -0,0 +1,90 @@ + + diff --git a/frontend/src/views/Overview.test.ts b/frontend/src/views/Overview.test.ts new file mode 100644 index 0000000..9d6b4cd --- /dev/null +++ b/frontend/src/views/Overview.test.ts @@ -0,0 +1,138 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { defineComponent } from 'vue' + +const routeState = vi.hoisted(() => ({meta:{view:'licenses'},query:{}})) +const routerMock = vi.hoisted(() => ({push:vi.fn(),replace:vi.fn()})) +vi.mock('vue-router', () => ({useRoute:()=>routeState,useRouter:()=>routerMock})) +const health = vi.hoisted(() => ({ checkApiHealth: vi.fn() })) +vi.mock('../api-health', () => health) +const business = vi.hoisted(() => ({ me: vi.fn(), listCustomers: vi.fn(), listProducts: vi.fn(), listLicenses: vi.fn(), issueLicense: vi.fn(), renewLicense: vi.fn(), listLicenseInstances: vi.fn() })) +vi.mock('../api', () => business) +const settingsApi = vi.hoisted(() => ({ getSettings: vi.fn() })) +vi.mock('../admin-api', () => settingsApi) + +vi.mock('./OrdersPanel.vue', () => ({ default: defineComponent({ template: '
线下订单
' }) })) +import Overview from './Overview.vue' +import { formatDateTime } from '../date-format' + +const DrawerStub = defineComponent({ template: '' }) +const ColumnStub = defineComponent({ props: ['label'], template: '{{ label }}' }) +const TableStub = defineComponent({ template: '
' }) +const ButtonStub = defineComponent({ + emits: ['click'], + template: '', +}) + +describe('Overview API status', () => { + it('renews using a date picker, validates dates and reuses the key on retry', async () => { + routeState.meta.view = 'licenses' + health.checkApiHealth.mockResolvedValue('online') + business.me.mockResolvedValue({ data: { data: { email: 'admin@example.test' } } }) + business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } }) + business.listProducts.mockResolvedValue({ data: { data: [] } }) + const row = { id: 7, status: 'active', expires_at: '2027-01-02T00:03:04Z' } + business.listLicenses.mockResolvedValue({ data: { data: [row], meta: { total: 1 } } }) + const Actions = defineComponent({ props: ['label'], setup: () => ({ row }), template: '
' }) + const Dialog = defineComponent({ props: ['modelValue', 'title'], template: '
' }) + const Picker = defineComponent({ props: ['modelValue'], emits: ['update:modelValue'], template: '' }) + const wrapper = mount(Overview, { global: { stubs: { 'router-link': true, 'el-dialog': Dialog, 'el-drawer': true, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': TableStub, 'el-table-column': Actions, 'el-select': true, 'el-option': true, 'el-date-picker': Picker, 'el-pagination': true }, directives: { loading: () => {} } } }) + await flushPromises() + await wrapper.findAll('button').find(button => button.text() === '续期')!.trigger('click') + const dialog = wrapper.get('[data-title="续期授权"]') + const picker = dialog.getComponent(Picker) + expect(dialog.text()).toContain(formatDateTime(row.expires_at)) + picker.vm.$emit('update:modelValue', null) + await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click') + expect(business.renewLicense).not.toHaveBeenCalled() + picker.vm.$emit('update:modelValue', new Date(row.expires_at)) + await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click') + expect(dialog.text()).toContain('新的到期时间必须晚于当前到期时间') + const chosen = new Date('2028-03-04T12:34:56+08:00') + picker.vm.$emit('update:modelValue', chosen) + business.renewLicense.mockRejectedValueOnce(new Error('网络错误')).mockResolvedValueOnce({}) + await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click') + await flushPromises() + expect(dialog.text()).toContain('网络错误') + const key = business.renewLicense.mock.calls[0][2] + await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click') + await flushPromises() + expect(business.renewLicense).toHaveBeenLastCalledWith(7, chosen.toISOString(), key) + expect(wrapper.find('[data-title="续期授权"]').exists()).toBe(false) + wrapper.unmount() + }) + afterEach(() => vi.resetAllMocks()) + + it('checks on mount and supports manual retry', async () => { + routeState.meta.view='dashboard' + health.checkApiHealth.mockResolvedValueOnce('online').mockResolvedValueOnce('offline') + business.me.mockRejectedValue(new Error('unauthorized')) + const wrapper = mount(Overview, { global: { stubs: { 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-drawer': DrawerStub, 'el-table': true, 'el-table-column': true, 'el-select': true, 'el-option': true, 'el-date-picker': true, 'el-pagination': true }, directives: { loading: () => {} } } }) + expect(wrapper.get('[role="status"]').text()).toBe('检测中') + await flushPromises() + expect(wrapper.get('[role="status"]').text()).toBe('服务在线') + await wrapper.get('button').trigger('click') + await flushPromises() + expect(wrapper.get('[role="status"]').text()).toBe('服务未连接') + expect(health.checkApiHealth).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) + + it('displays persisted site settings after refresh and updates immediately on save', async () => { + routeState.meta.view = 'settings' + health.checkApiHealth.mockResolvedValue('online') + business.me.mockResolvedValue({ data: { data: { role: 'admin' } } }) + business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } }) + business.listProducts.mockResolvedValue({ data: { data: [] } }) + business.listLicenses.mockResolvedValue({ data: { data: [], meta: { total: 0 } } }) + settingsApi.getSettings.mockResolvedValue({ data: { data: { site_name: '已保存站点', announcement: '已保存公告', support_email: 'help@example.test', updated_at: null } } }) + const wrapper = mount(Overview, { global: { stubs: { SettingsPanel: true, 'router-link': true, 'el-dialog': true, 'el-drawer': true, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': true, 'el-table-column': true, 'el-pagination': true }, directives: { loading: () => {} } } }) + await flushPromises() + expect(settingsApi.getSettings).toHaveBeenCalledOnce() + expect(wrapper.get('.brand').text()).toContain('已保存站点') + expect(wrapper.get('[role="note"]').text()).toBe('已保存公告') + expect(wrapper.find('a[href="mailto:help@example.test"]').exists()).toBe(true) + wrapper.getComponent({ name: 'SettingsPanel' }).vm.$emit('saved', { site_name: '新站点', announcement: '新公告', support_email: '', updated_at: null }) + await flushPromises() + expect(wrapper.get('.brand').text()).toContain('新站点') + expect(wrapper.get('[role="note"]').text()).toBe('新公告') + expect(wrapper.find('a[href^="mailto:"]').exists()).toBe(false) + wrapper.unmount() + }) + + it('formats license start and end columns as local date times', async () => { + routeState.meta.view = 'licenses' + health.checkApiHealth.mockResolvedValue('online') + business.me.mockResolvedValue({ data: { data: { email: 'admin@example.test' } } }) + business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } }) + business.listProducts.mockResolvedValue({ data: { data: [] } }) + const row = { id: 1, starts_at: '2026-01-02T00:03:04Z', expires_at: '2027-01-02T00:03:04Z' } + business.listLicenses.mockResolvedValue({ data: { data: [row], meta: { total: 1 } } }) + const DateColumn = defineComponent({ props: ['label'], setup: () => ({ row }), template: '' }) + const wrapper = mount(Overview, { global: { stubs: { 'router-link': true, 'el-dialog': true, 'el-drawer': true, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': TableStub, 'el-table-column': DateColumn, 'el-select': true, 'el-option': true, 'el-date-picker': true, 'el-pagination': true }, directives: { loading: () => {} } } }) + await flushPromises() + expect(wrapper.text()).toContain(formatDateTime(row.starts_at)) + expect(wrapper.text()).toContain(formatDateTime(row.expires_at)) + expect(wrapper.text()).not.toContain(row.starts_at) + wrapper.unmount() + }) + + it('loads real license list contract after session recovery', async () => { + routeState.meta.view='licenses' + health.checkApiHealth.mockResolvedValue('online') + business.me.mockResolvedValue({ data: { data: { role: 'admin' } } }) + business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } }) + business.listProducts.mockResolvedValue({ data: { data: [] } }) + business.listLicenses.mockResolvedValue({ data: { data: [], meta: { total: 1 } } }) + const wrapper = mount(Overview, { global: { stubs: { 'el-drawer': DrawerStub, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': TableStub, 'el-table-column': ColumnStub, 'el-select': true, 'el-option': true, 'el-date-picker': true, 'el-pagination': true }, directives: { loading: () => {} } } }) + await flushPromises() + expect(wrapper.text()).toContain('期限授权') + expect(wrapper.text()).toContain('共 1 条') + expect(wrapper.text()).toContain('最后在线') + expect(wrapper.text()).toContain('租约到期') + expect(wrapper.text()).toContain('冻结状态') + expect(wrapper.text()).toContain('已传播状态') + expect(business.listLicenses).toHaveBeenCalledWith({ page: 1, q: '', status: '' }) + wrapper.unmount() + }) +}) diff --git a/frontend/src/views/Overview.vue b/frontend/src/views/Overview.vue index cc8a0f3..4b4216d 100644 --- a/frontend/src/views/Overview.vue +++ b/frontend/src/views/Overview.vue @@ -1,37 +1,126 @@ - diff --git a/frontend/src/views/ReleasesPanel.test.ts b/frontend/src/views/ReleasesPanel.test.ts new file mode 100644 index 0000000..bb2fc5c --- /dev/null +++ b/frontend/src/views/ReleasesPanel.test.ts @@ -0,0 +1,13 @@ +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import ReleasesPanel from './ReleasesPanel.vue' + +describe('ReleasesPanel', () => { + it('shows validation error without sending an invalid publication', async () => { + const wrapper = mount(ReleasesPanel, { props: { products: [] }, global: { stubs: { ElButton: { template: '' }, ElSelect: true, ElOption: true, ElInput: true, ElTable: true, ElTableColumn: true, ElPagination: true }, directives: { loading: () => {} } } }) + expect(wrapper.find('[role="alert"]').exists()).toBe(false) + await wrapper.findAll('button')[1]!.trigger('click') + expect(wrapper.find('[role="alert"]').text()).toContain('请选择产品') + expect(wrapper.find('input[type="file"]').attributes('aria-label')).toBe('版本文件') + }) +}) diff --git a/frontend/src/views/ReleasesPanel.vue b/frontend/src/views/ReleasesPanel.vue new file mode 100644 index 0000000..c7b7636 --- /dev/null +++ b/frontend/src/views/ReleasesPanel.vue @@ -0,0 +1,43 @@ + + diff --git a/frontend/src/views/SettingsPanel.test.ts b/frontend/src/views/SettingsPanel.test.ts new file mode 100644 index 0000000..a6be3b6 --- /dev/null +++ b/frontend/src/views/SettingsPanel.test.ts @@ -0,0 +1,53 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import ElementPlus, { ElMessageBox } from 'element-plus' +const calls = vi.hoisted(() => ({getSettings:vi.fn(),saveSettings:vi.fn(),changePassword:vi.fn()})) +vi.mock('../admin-api', async importOriginal => ({...await importOriginal(),...calls})) +import SettingsPanel from './SettingsPanel.vue' +const settings = {site_name:'Persisted Site',support_email:'help@example.test',announcement:'真实公告',updated_at:null} +const options = {global:{plugins:[ElementPlus]}} +beforeEach(() => {vi.restoreAllMocks();vi.resetAllMocks();calls.getSettings.mockResolvedValue({data:{data:settings}})}) +async function passwords(wrapper:ReturnType, next='a', confirm=next) { + await wrapper.get('[aria-label="当前密码"]').setValue('old') + await wrapper.get('[aria-label="新密码"]').setValue(next) + await wrapper.get('[aria-label="确认新密码"]').setValue(confirm) +} +describe('SettingsPanel', () => { + it('loads persisted settings, saves only editable fields and emits updated display data', async () => { + const wrapper = mount(SettingsPanel,options); await flushPromises() + expect((wrapper.get('[aria-label="站点名称"]').element as HTMLInputElement).value).toBe('Persisted Site') + await wrapper.get('[aria-label="站点名称"]').setValue('Changed') + calls.saveSettings.mockResolvedValue({data:{data:{...settings,site_name:'Changed',updated_at:'2026-10-09T00:00:00Z'}}}) + await wrapper.findAll('form')[0]!.trigger('submit'); await flushPromises() + expect(calls.saveSettings).toHaveBeenCalledWith({site_name:'Changed',support_email:'help@example.test',announcement:'真实公告'}) + expect(wrapper.text()).toContain('设置已保存'); expect(wrapper.emitted('saved')?.[0]?.[0]).toMatchObject({site_name:'Changed'}) + calls.saveSettings.mockRejectedValueOnce(new Error('保存接口失败')) + await wrapper.findAll('form')[0]!.trigger('submit'); await flushPromises() + expect(wrapper.text()).toContain('保存接口失败'); expect(wrapper.text()).not.toContain('设置已保存'); wrapper.unmount() + }) + it('blocks invalid settings and supports recovering from load failure', async () => { + calls.getSettings.mockRejectedValueOnce(new Error('加载失败')) + const wrapper = mount(SettingsPanel,options); await flushPromises() + expect(wrapper.text()).toContain('加载失败'); expect(wrapper.find('[aria-label="站点名称"]').exists()).toBe(false) + await wrapper.findAll('button').find(b=>b.text()==='重新加载设置')!.trigger('click'); await flushPromises() + await wrapper.get('[aria-label="站点名称"]').setValue('') + await wrapper.findAll('form')[0]!.trigger('submit'); await flushPromises() + expect(calls.saveSettings).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('站点名称须为'); wrapper.unmount() + }) + it('requires matching passwords and confirmation, handles errors and clears secrets on success', async () => { + const confirm = vi.spyOn(ElMessageBox,'confirm').mockRejectedValueOnce('cancel') + const wrapper = mount(SettingsPanel,options); await flushPromises() + await passwords(wrapper,'a','b'); await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises() + expect(wrapper.text()).toContain('不一致'); expect(confirm).not.toHaveBeenCalled() + await passwords(wrapper); await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises() + expect(calls.changePassword).not.toHaveBeenCalled() + confirm.mockResolvedValue('confirm' as Awaited>); calls.changePassword.mockRejectedValueOnce(new Error('当前密码错误')).mockResolvedValueOnce({status:204}) + await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises() + expect(wrapper.text()).toContain('当前密码错误') + await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises() + expect(calls.changePassword).toHaveBeenLastCalledWith({current_password:'old',new_password:'a'}) + expect(wrapper.text()).toContain('当前会话保留') + for (const label of ['当前密码','新密码','确认新密码']) expect((wrapper.get(`[aria-label="${label}"]`).element as HTMLInputElement).value).toBe('') + wrapper.unmount() + }) +}) diff --git a/frontend/src/views/SettingsPanel.vue b/frontend/src/views/SettingsPanel.vue new file mode 100644 index 0000000..abf1a75 --- /dev/null +++ b/frontend/src/views/SettingsPanel.vue @@ -0,0 +1,64 @@ + + diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 6b22e2d..7e87365 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -5,6 +5,17 @@ export default defineConfig({ plugins: [vue()], server: { port: 5173, - proxy: { '/api': 'http://127.0.0.1:18080' } - } + // Preserve the browser-facing Host so the API's same-origin guard can + // compare it with Origin. Vite's string shorthand enables changeOrigin. + proxy: { + '/api': { + target: 'http://127.0.0.1:18081', + changeOrigin: false, + }, + } + }, + test: { + environment: 'jsdom', + globals: true, + }, }) diff --git a/scripts/backup-delivery.sh b/scripts/backup-delivery.sh new file mode 100644 index 0000000..33e0e81 --- /dev/null +++ b/scripts/backup-delivery.sh @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu +# Run during an upload/admin-write maintenance window. This script never reads or copies the signing key. +: "${MYSQL_HOST:?set MYSQL_HOST}" +: "${MYSQL_USER:?set MYSQL_USER}" +: "${MYSQL_PASSWORD_FILE:?set protected MYSQL_PASSWORD_FILE}" +: "${MYSQL_DATABASE:?set MYSQL_DATABASE}" +: "${PACKAGE_STORAGE_ROOT:?set PACKAGE_STORAGE_ROOT to the private package directory}" +: "${BACKUP_DIR:?set BACKUP_DIR to a protected destination}" +case "$BACKUP_DIR" in /*) ;; *) echo 'BACKUP_DIR must be absolute' >&2; exit 1;; esac +case "$PACKAGE_STORAGE_ROOT" in /*) ;; *) echo 'PACKAGE_STORAGE_ROOT must be absolute' >&2; exit 1;; esac +mkdir -p "$BACKUP_DIR"; chmod 700 "$BACKUP_DIR" +name=$(date -u +%Y%m%dT%H%M%SZ); work="$BACKUP_DIR/.delivery-$name" +mkdir "$work"; trap 'unset MYSQL_PWD; rm -rf "$work"' EXIT HUP INT TERM +export MYSQL_PWD=$(cat "$MYSQL_PASSWORD_FILE") +mysqldump --host="$MYSQL_HOST" --port="${MYSQL_PORT:-3306}" --user="$MYSQL_USER" --single-transaction --no-tablespaces --routines --triggers "$MYSQL_DATABASE" > "$work/mysql.sql" +unset MYSQL_PWD +tar --sort=name --mtime='UTC 1970-01-01' --owner=0 --group=0 --numeric-owner -C "$PACKAGE_STORAGE_ROOT" -cf "$work/packages.tar" . +(cd "$work" && sha256sum mysql.sql packages.tar > SHA256SUMS) +printf '%s\n' 'Signing keys are intentionally excluded. Record migration version and quiescence window separately.' > "$work/METADATA.txt" +mv "$work" "$BACKUP_DIR/delivery-$name" +printf '%s\n' "$BACKUP_DIR/delivery-$name" diff --git a/scripts/check-delivery.sh b/scripts/check-delivery.sh new file mode 100644 index 0000000..df47853 --- /dev/null +++ b/scripts/check-delivery.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +expected=1 +for file in backend/migrations/*.up.sql; do + [ -s "$file" ] || { echo 'empty migration' >&2; exit 1; } + base=${file%.up.sql} + [ -s "$base.down.sql" ] || { echo 'missing down migration' >&2; exit 1; } + name=${base##*/} + version=${name%%_*} + [ "$version" = "$(printf '%06d' "$expected")" ] || { echo 'migration sequence must be contiguous and unique' >&2; exit 1; } + expected=$((expected + 1)) +done +[ "$expected" -gt 1 ] || { echo 'no migrations found' >&2; exit 1; } +for file in backend/migrations/*.down.sql; do + [ -s "${file%.down.sql}.up.sql" ] || { echo 'missing up migration' >&2; exit 1; } +done +for file in scripts/*.sh deploy/entrypoint.sh; do sh -n "$file"; done +printf '%s\n' 'Migration naming/pairs and shell syntax passed; this does not execute migrations or Compose.' diff --git a/scripts/restore-delivery.sh b/scripts/restore-delivery.sh new file mode 100644 index 0000000..ec69be5 --- /dev/null +++ b/scripts/restore-delivery.sh @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu +# Restore only into an explicitly empty isolated database/private directory. Never restores signing keys. +: "${MYSQL_HOST:?set MYSQL_HOST}"; : "${MYSQL_USER:?set MYSQL_USER}"; : "${MYSQL_PASSWORD_FILE:?set protected MYSQL_PASSWORD_FILE}"; : "${MYSQL_DATABASE:?set MYSQL_DATABASE}" +: "${PACKAGE_STORAGE_ROOT:?set PACKAGE_STORAGE_ROOT for the empty private target directory}"; : "${BACKUP_DIR:?set BACKUP_DIR containing delivery-*/mysql.sql and packages.tar}" +: "${CONFIRM_EMPTY_RESTORE:?set CONFIRM_EMPTY_RESTORE=YES after independently verifying isolation}" +[ "$CONFIRM_EMPTY_RESTORE" = YES ] || { echo 'CONFIRM_EMPTY_RESTORE must be YES' >&2; exit 1; } +case "$PACKAGE_STORAGE_ROOT" in /*) ;; *) echo 'PACKAGE_STORAGE_ROOT must be absolute' >&2; exit 1;; esac +[ -d "$PACKAGE_STORAGE_ROOT" ] || { echo 'target package directory must exist' >&2; exit 1; } +[ -z "$(find "$PACKAGE_STORAGE_ROOT" -mindepth 1 -print -quit)" ] || { echo 'target package directory must be empty' >&2; exit 1; } +backup=$(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d -name 'delivery-*' -exec test -f '{}/mysql.sql' \; -print | sort | tail -1) +[ -n "$backup" ] || { echo 'no backup found' >&2; exit 1; } +(cd "$backup" && sha256sum -c SHA256SUMS) +case "$MYSQL_DATABASE" in ''|*[!a-zA-Z0-9_]*) echo 'MYSQL_DATABASE must be an ASCII identifier' >&2; exit 1;; esac +export MYSQL_PWD=$(cat "$MYSQL_PASSWORD_FILE") +trap 'unset MYSQL_PWD' EXIT HUP INT TERM +count=$(mysql --host="$MYSQL_HOST" --port="${MYSQL_PORT:-3306}" --user="$MYSQL_USER" --batch --skip-column-names "$MYSQL_DATABASE" -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '$MYSQL_DATABASE'") +[ "$count" = 0 ] || { echo 'target database must exist and be empty' >&2; exit 1; } +mysql --host="$MYSQL_HOST" --port="${MYSQL_PORT:-3306}" --user="$MYSQL_USER" "$MYSQL_DATABASE" < "$backup/mysql.sql" +unset MYSQL_PWD +tar -C "$PACKAGE_STORAGE_ROOT" -xf "$backup/packages.tar" +printf '%s\n' 'Restore completed without restoring signing keys. Run explicit migrations/version checks and release/object checksum verification before traffic.' diff --git a/软件授权与统一管理平台-架构决策与MVP验收规格.md b/软件授权与统一管理平台-架构决策与MVP验收规格.md index 7c45cfa..72a67f7 100644 --- a/软件授权与统一管理平台-架构决策与MVP验收规格.md +++ b/软件授权与统一管理平台-架构决策与MVP验收规格.md @@ -1,20 +1,20 @@ # 软件授权与统一管理平台:架构决策与 MVP 验收规格(待签字) -依据:[原方案](./软件授权%20%26%20统一管理平台(服务端)详细开发方案.md)和[详细任务方案](./软件授权与统一管理平台-详细开发任务方案.md)。本文为实施前的**建议基线**,不是已获业务批准的最终需求。2026-09-30 用户已确认首发为 Web 服务器端软件、采用线下订单与本地存储并暂缓支付/OSS/站点并发、最长连续离线 14 天。其余带「建议值」的时限、容量和安全取舍仍需业务、接入方和运维负责人在 M0 签字。Web 服务实例标识/重建/扩容的具体规则尚未确认,旧桌面场景的工作量不能直接视为准确排期。 +依据:[原方案](./软件授权%20&%20统一管理平台(服务端)详细开发方案.md)和[详细任务方案](./软件授权与统一管理平台-详细开发任务方案.md)。本文为实施前的**建议基线**,不是已获业务批准的最终需求。2026-09-30 用户已确认首发为 Web 服务器端软件、采用线下订单与本地存储并暂缓支付/OSS/站点并发、最长连续离线 14 天。其余带「建议值」的时限、容量和安全取舍仍需业务、接入方和运维负责人在 M0 签字。Web 服务实例标识/重建/扩容的具体规则尚未确认,旧桌面场景的工作量不能直接视为准确排期。 -## 1. MVP 边界与签字角色 +## 1\. MVP 边界与签字角色 已确认首发接入**Web 服务器端软件**,通过服务实例/部署主体激活、在线心跳和最长 14 天的离线租约获取使用权;实现永久/订阅权益、可配置模块、线下订单、版本检查和鉴权下载,以及基本后台、门户、审计、备份。首发暂缓线上支付、OSS 和站点并发授权;试用是否首发仍待定。这里的“Web 服务器端软件”指**被授权的业务软件部署**,并非仅指本授权管理平台本身;具体产品名称、部署拓扑及接入技术栈仍需确认。首发不要求 C#/C++ 桌面 SDK;被授权 Web 软件的接入实现及负责人未指定,缺少真实接入方不能完成端到端 UAT。 -| 角色(待指派姓名) | 必须签字的内容 | -| --- | --- | -| 产品/销售负责人 | 许可类型、售卖权益、离线期限、续费/解绑/退款规则、首批产品、UAT | -| 后端技术负责人 | 证书与 API 契约、数据一致性、状态机、下载链路、性能基线 | -| 被授权 Web 软件接入负责人(待指定) | 实例身份持久化、证书验签、14 天离线边界、部署重建及错误提示 | -| 安全/运维负责人 | 密钥托管、外网入口、备份恢复目标、监控及发布回滚 | -| 财务负责人 | 线下订单审批、确认收款、开票/退款口径(如涉及) | +|角色(待指派姓名)|必须签字的内容| +|-|-| +|产品/销售负责人|许可类型、售卖权益、离线期限、续费/解绑/退款规则、首批产品、UAT| +|后端技术负责人|证书与 API 契约、数据一致性、状态机、下载链路、性能基线| +|被授权 Web 软件接入负责人(待指定)|实例身份持久化、证书验签、14 天离线边界、部署重建及错误提示| +|安全/运维负责人|密钥托管、外网入口、备份恢复目标、监控及发布回滚| +|财务负责人|线下订单审批、确认收款、开票/退款口径(如涉及)| -## 2. 架构决策记录(ADR 草案) +## 2\. 架构决策记录(ADR 草案) 每项决定以「建议 -> 验收依据 -> 待签字问题」写出,修改须记录责任人、日期和影响任务。拒绝建议时仍需指定可测试替代方案。 @@ -26,7 +26,7 @@ ### ADR-02 离线许可、冻结和时间 -**已确认**最长连续离线 **14 天**。**建议实现**:将 `entitlement_expires_at`(购买权益期限,永久授权可无期限)与 `lease_expires_at`(最近签发的离线使用截止)分开;被授权 Web 服务实例在租约内验签并检查模块/部署主体,联网心跳续发租约。每 24 小时尝试续租并退避为待签字建议。冻结在下次成功联网或既有租约到期时生效,不能承诺立即失效。若授权平台不可达,到租约截止则停止受控功能,不自动延长;故障宽限仍需业务决定。永久权益不代表永不过期的离线证书。 +**已确认**最长连续离线 **14 天**。**建议实现**:将 `entitlement\_expires\_at`(购买权益期限,永久授权可无期限)与 `lease\_expires\_at`(最近签发的离线使用截止)分开;被授权 Web 服务实例在租约内验签并检查模块/部署主体,联网心跳续发租约。每 24 小时尝试续租并退避为待签字建议。冻结在下次成功联网或既有租约到期时生效,不能承诺立即失效。若授权平台不可达,到租约截止则停止受控功能,不自动延长;故障宽限仍需业务决定。永久权益不代表永不过期的离线证书。 客户可控服务器的时钟和实例文件可被篡改或克隆;本地防回拨只提高攻击成本。服务实例可保存最近可信时间并检测显著回拨,但重建、快照恢复与多副本一致性须单独约定。若要求永久离线,则不能同时承诺远程冻结。 @@ -34,13 +34,13 @@ ### ADR-03 证书格式与签名密钥 -**建议**:P-256 ECDSA + SHA-256(由 Web 软件接入方确认加密库兼容性),签名对象采用版本化、无歧义字节编码,例如固定字段顺序的规范 JSON;证书中含 `schema_version`、`key_id`、授权/产品/客户标识、Web 部署/实例标识摘要、模块权益、签发时间、生效时间、租约截止及权益截止。所有时间统一 UTC,缺省字段与数字编码在测试向量中固定。私钥只在受控服务端读取,禁止 API 返回;证书公钥标识支持轮换,旧公钥至少保留到所有已签证书的最长租约到期及恢复窗口结束。若密钥失陷,启动应急换钥和补发,承认在离线窗口内不能立即让旧证书失效。 +**建议**:P-256 ECDSA + SHA-256(由 Web 软件接入方确认加密库兼容性),签名对象采用版本化、无歧义字节编码,例如固定字段顺序的规范 JSON;证书中含 `schema\_version`、`key\_id`、授权/产品/客户标识、Web 部署/实例标识摘要、模块权益、签发时间、生效时间、租约截止及权益截止。所有时间统一 UTC,缺省字段与数字编码在测试向量中固定。私钥只在受控服务端读取,禁止 API 返回;证书公钥标识支持轮换,旧公钥至少保留到所有已签证书的最长租约到期及恢复窗口结束。若密钥失陷,启动应急换钥和补发,承认在离线窗口内不能立即让旧证书失效。 -**验收**:平台与被授权 Web 软件接入方使用同一组成功/字段篡改/部署主体不符/过期/旧 key_id 向量得到相同结果。**待签字**:接入语言及加密库兼容性、轮换保留期、私钥托管方式与灾备负责人。 +**验收**:平台与被授权 Web 软件接入方使用同一组成功/字段篡改/部署主体不符/过期/旧 key\_id 向量得到相同结果。**待签字**:接入语言及加密库兼容性、轮换保留期、私钥托管方式与灾备负责人。 ### ADR-04 订单、权益与数据库真相源 -**建议**:MySQL 是订单、权益、设备绑定的权威数据;Redis 只用于缓存、限流和非关键协调。订单确认与发放使用事务,并以 `(order_id, grant_type)` 唯一键及显式状态防重复;若通知或外部动作在事务之外,使用 outbox + 幂等消费。授权码可独立生成但必须绑定具体权益与状态。模板/套餐变更不反向改变既有订单或权益快照。订单作废/退款后资格回收遵守 ADR-02 的离线窗口。 +**建议**:MySQL 是订单、权益、设备绑定的权威数据;Redis 只用于缓存、限流和非关键协调。订单确认与发放使用事务,并以 `(order\_id, grant\_type)` 唯一键及显式状态防重复;若通知或外部动作在事务之外,使用 outbox + 幂等消费。授权码可独立生成但必须绑定具体权益与状态。模板/套餐变更不反向改变既有订单或权益快照。订单作废/退款后资格回收遵守 ADR-02 的离线窗口。 **验收**:并发双击确认、任务重跑、服务重启和回调重复模拟均不产生双份权益/超额设备;冻结后旧缓存不继续放行在线校验。**待签字**:线下订单谁确认收款、谁可批准发放;续费从当前到期日还是付款日叠加;退款审批与历史凭证留存。 @@ -54,7 +54,7 @@ ### ADR-06 账号、审计与配置 -**建议**:内部与客户登录使用不同身份域与 token 受众,服务端按 customer_id 强制作用域。客户子账号仅拥有分配的查看/下载权限。审计业务关键事件与事务可靠关联,记录操作主体、租户、目标、结果和请求 ID,但不存完整授权码、token、私钥或手机号。敏感密钥由部署密钥系统/环境注入,不在网页提供查看和修改。 +**建议**:内部与客户登录使用不同身份域与 token 受众,服务端按 customer\_id 强制作用域。客户子账号仅拥有分配的查看/下载权限。审计业务关键事件与事务可靠关联,记录操作主体、租户、目标、结果和请求 ID,但不存完整授权码、token、私钥或手机号。敏感密钥由部署密钥系统/环境注入,不在网页提供查看和修改。 **验收**:用同角色两个客户账号交叉读写资源全部拒绝;禁用账号/撤权后敏感操作及时失败;审计可定位确认订单、发放、冻结和下载但不泄露凭证。**待签字**:角色权限矩阵、审计保留期、客服代客操作是否允许及其审批。 @@ -64,43 +64,43 @@ **验收**:同客户连续版本检查灰度命中一致,版本从 beta 切正式不影响错误渠道,强更和撤回按既定矩阵运行;签名/哈希不符包不可发布。**待签字**:Windows 安装包签名责任、更新失败回滚策略、是否允许旧版继续运行。 -## 3. MVP 可执行验收场景 +## 3\. MVP 可执行验收场景 下表为 T01 转成自动化测试和 UAT 的候选集合。最长连续离线 **14 天已确认**;其他数值与规则仍为建议或待确认,签字后再写进接口契约与测试数据。未指定容量和 SLA 时不承诺特定并发性能。 -| 编号 | 前置/操作 | 预期结果 | -| --- | --- | --- | -| U01 | 财务/授权人员录入并确认首发产品线下订单,连续或并发提交两次 | 只形成一份有效授权权益与一次发放记录;金额及套餐权益按下单快照保留,审计可追溯 | -| U02 | 客户主账号查看授权并创建只读子账号;子账号尝试冻结/跨客户查询 | 主账号看见本企业数据;子账号只能查看许可范围;跨客户接口与操作均被服务端拒绝 | -| U03 | 被授权 Web 软件实例用有效授权码首次联网激活匹配产品与部署身份,之后重启并重试 | 只绑定一次,签发接入方可验签的证书;重启/重试返回同一业务效果,证书包含生效/租约/权益截止 | -| U04 | 克隆实例至另一部署、并发激活,或篡改实例标识/证书模块列表 | 按签字后的实例规则拒绝超额/违规克隆且无脏绑定;篡改证书验签或主体检查失败 | -| U05 | 离线使用、恢复网络心跳;后台冻结后继续离线 | 租约内可用,冻结在下次联网/租约到期生效,后台可见最迟截止;边界时刻测试与 ADR-02 一致 | -| U06 | 延期/续费订阅,重复执行确认及到期提醒任务 | 新旧证书权益期限符合规则,只发放一次;30/15/7 天提醒按档位去重,延期后不误发 | -| U07 | 管理员分片上传几百 MB 的版本包,模拟丢片/重试/磁盘满 | 可断点续传;服务端摘要匹配后才可发布;失败文件不出现在下载列表,临时分片可回收 | -| U08 | 同客户多次版本检查,再以无权客户访问下载 URL/文件路径 | 灰度结果稳定;有权用户可断点下载且 SHA-256 一致;无权及路径猜测请求拒绝并记录必要审计 | -| U09 | 停用内部用户、撤销客户子账号权限,再用旧会话调用敏感接口 | 按签字确定的失效上限拒绝操作;后台按钮隐藏不能代替 API 鉴权 | -| U10 | 用备份在全新环境恢复数据库、文件与密钥;演练发布失败回滚 | RPO/RTO 达标,既有证书仍可验签,订单/授权/包元数据和物理文件一致,回滚步骤可重复 | -| U11 | 以约定负载压测激活/心跳/下载并注入 Redis 暂停及应用重启 | 业务关键数据不丢不超发;关键操作在降级策略下符合预期,测试报告记录 P95/错误率/资源占用 | +|编号|前置/操作|预期结果| +|-|-|-| +|U01|财务/授权人员录入并确认首发产品线下订单,连续或并发提交两次|只形成一份有效授权权益与一次发放记录;金额及套餐权益按下单快照保留,审计可追溯| +|U02|客户主账号查看授权并创建只读子账号;子账号尝试冻结/跨客户查询|主账号看见本企业数据;子账号只能查看许可范围;跨客户接口与操作均被服务端拒绝| +|U03|被授权 Web 软件实例用有效授权码首次联网激活匹配产品与部署身份,之后重启并重试|只绑定一次,签发接入方可验签的证书;重启/重试返回同一业务效果,证书包含生效/租约/权益截止| +|U04|克隆实例至另一部署、并发激活,或篡改实例标识/证书模块列表|按签字后的实例规则拒绝超额/违规克隆且无脏绑定;篡改证书验签或主体检查失败| +|U05|离线使用、恢复网络心跳;后台冻结后继续离线|租约内可用,冻结在下次联网/租约到期生效,后台可见最迟截止;边界时刻测试与 ADR-02 一致| +|U06|延期/续费订阅,重复执行确认及到期提醒任务|新旧证书权益期限符合规则,只发放一次;30/15/7 天提醒按档位去重,延期后不误发| +|U07|管理员分片上传几百 MB 的版本包,模拟丢片/重试/磁盘满|可断点续传;服务端摘要匹配后才可发布;失败文件不出现在下载列表,临时分片可回收| +|U08|同客户多次版本检查,再以无权客户访问下载 URL/文件路径|灰度结果稳定;有权用户可断点下载且 SHA-256 一致;无权及路径猜测请求拒绝并记录必要审计| +|U09|停用内部用户、撤销客户子账号权限,再用旧会话调用敏感接口|按签字确定的失效上限拒绝操作;后台按钮隐藏不能代替 API 鉴权| +|U10|用备份在全新环境恢复数据库、文件与密钥;演练发布失败回滚|RPO/RTO 达标,既有证书仍可验签,订单/授权/包元数据和物理文件一致,回滚步骤可重复| +|U11|以约定负载压测激活/心跳/下载并注入 Redis 暂停及应用重启|业务关键数据不丢不超发;关键操作在降级策略下符合预期,测试报告记录 P95/错误率/资源占用| **负载基线待定**:明确首年客户数、活跃设备数、心跳频率峰值、同时激活数、最大上传包、下载带宽和每月新增文件量,再定 CPU/磁盘/带宽预算及 P95/错误率门槛。没有容量数据时仅做功能和风险验收,不能宣称达到特定并发性能。 -## 4. 工作顺序与资源重排 +## 4\. 工作顺序与资源重排 下表沿用[详细任务方案](./软件授权与统一管理平台-详细开发任务方案.md)在**旧桌面场景**下的 T01-T30 累计工作量:不含 T16(站点)和 T24(OSS)为后端 106 人天、前端 76 人天;含二者为后端 113、前端 81。旧模型假设后端/前端各 1 人、每人每周约 3.5 个有效开发日。Web 服务实例身份、部署扩容和接入责任尚不明确,**表内窗口须重新估算后才可用作 Web 首发排期**。 -| 门禁 | 覆盖任务(不含条件项) | 累计 B/F 人天 | 后端理论下限* | 建议检查窗口 | 实际交付依据 | -| --- | --- | ---: | ---: | --- | --- | -| M0 规则与契约冻结 | T01-T02 | 5/4 | 1.4 周 | 第 2-3 周 | ADR 签字、用例及 API 草案确认 | -| M1 基线及主数据 | T01-T11(跳过 T16) | 38/27 | 10.9 周 | 第 12-14 周 | 可部署登录/RBAC、客户、产品与模板 | -| M2 Web 实例授权闭环 | T01-T15 | 58/39 | 16.6 周 | 第 18-21 周(旧假设) | 实例激活、14 天离线、冻结联调 | -| M3 商业/升级/门户 | T01-T26(跳过 T16/T24) | 92/66 | 26.3 周 | 第 28-32 周 | 订单、发放、通知、版本、门户及审计贯通 | -| M4 发布候选 | T01-T30(跳过 T16/T24) | 106/76 | 30.3 周 | 第 33-37 周 | 压测、安全检查、恢复演练、UAT 签字 | +|门禁|覆盖任务(不含条件项)|累计 B/F 人天|后端理论下限\*|建议检查窗口|实际交付依据| +|-|-|-:|-:|-|-| +|M0 规则与契约冻结|T01-T02|5/4|1.4 周|第 2-3 周|ADR 签字、用例及 API 草案确认| +|M1 基线及主数据|T01-T11(跳过 T16)|38/27|10.9 周|第 12-14 周|可部署登录/RBAC、客户、产品与模板| +|M2 Web 实例授权闭环|T01-T15|58/39|16.6 周|第 18-21 周(旧假设)|实例激活、14 天离线、冻结联调| +|M3 商业/升级/门户|T01-T26(跳过 T16/T24)|92/66|26.3 周|第 28-32 周|订单、发放、通知、版本、门户及审计贯通| +|M4 发布候选|T01-T30(跳过 T16/T24)|106/76|30.3 周|第 33-37 周|压测、安全检查、恢复演练、UAT 签字| -*理论下限仅用旧假设下累计后端工作量除以 3.5,未计等待外部签字、Web 软件接入实现、发现的问题或需求变化。若 5 天/周全部用于开发,最低纯编码时间约 21.2 周,但无法合理覆盖协作和返工。M1 所含 T07 的前端人天为上传/下载组件准备,具体成品仍以后续 T22/T23 验收。具体门禁窗口并非保证,重估前须先确认业务优先级、真实开发速度与可用环境。 +\*理论下限仅用旧假设下累计后端工作量除以 3.5,未计等待外部签字、Web 软件接入实现、发现的问题或需求变化。若 5 天/周全部用于开发,最低纯编码时间约 21.2 周,但无法合理覆盖协作和返工。M1 所含 T07 的前端人天为上传/下载组件准备,具体成品仍以后续 T22/T23 验收。具体门禁窗口并非保证,重估前须先确认业务优先级、真实开发速度与可用环境。 **迭代建议**:第一周完成 Web 软件产品和接入负责人指派;第二周按 ADR 形成实例身份、证书、状态机和 OpenAPI 样例;之后优先纵向贯通线下发放-Web 服务实例激活-14 天离线验证,再逐步补版本/门户。每两周复盘剩余工作量,不以原方案“73 天”作为考核基准。若首发加入 T16/T24、在线支付或正式双语言 SDK,单独增加依赖、人天和验收轮次;不要在既有窗口内暗含这些工作。 -## 5. 当前待签字清单 +## 5\. 当前待签字清单 1. 被授权 Web 软件的具体产品名称、接入语言、部署拓扑及接入负责人;试用是否首发(原清单保留,不代表已确认)。 2. 已确认 14 天离线期限;待确认心跳频率、故障宽限、永久授权维保权益及服务器时间回拨取舍。 @@ -112,3 +112,4 @@ 8. 后续站点授权、线上支付及 C#/C++ SDK 的独立负责人及排期;这些不阻塞本次 Web 服务端首发。 签字后先更新 ADR 的建议值与 U01-U11 预期,再同步调整任务方案中的范围、人天与里程碑。 + diff --git a/软件授权与统一管理平台-详细开发任务方案.md b/软件授权与统一管理平台-详细开发任务方案.md index 259c7f3..098d51c 100644 --- a/软件授权与统一管理平台-详细开发任务方案.md +++ b/软件授权与统一管理平台-详细开发任务方案.md @@ -1,22 +1,22 @@ # 软件授权与统一管理平台:详细开发任务方案 -依据:[原服务端方案](./软件授权%20%26%20统一管理平台(服务端)详细开发方案.md)。范围含 Go/Gin 服务端、Vue3/Vite/Element Plus 后台及客户门户、MySQL8/Redis、Local 文件存储和 Docker Compose 部署。首发授权对象为 Web 服务器端软件实例/部署主体;在线支付、OSS、站点并发授权暂缓。C#/C++ 客户端 SDK 不属于本首发范围,后续单独估算。 +依据:[原服务端方案](./软件授权%20&%20统一管理平台(服务端)详细开发方案.md)。范围含 Go/Gin 服务端、Vue3/Vite/Element Plus 后台及客户门户、MySQL8/Redis、Local 文件存储和 Docker Compose 部署。首发授权对象为 Web 服务器端软件实例/部署主体;在线支付、OSS、站点并发授权暂缓。C#/C++ 客户端 SDK 不属于本首发范围,后续单独估算。 ## 一、原方案评估与决策关口 原方案覆盖主要能力,但缺少能直接开发的协议、状态机、权限矩阵与验收口径。八阶段工期合计 **83 工作日**(10+10+18+10+12+8+10+5),而非原文 73 天;这是顺序阶段时间,不能当作两名开发者的实际排期。 -| 决策 | 问题 | 建议及必须确认的结果 | -| --- | --- | --- | -| D01 | Web 服务软件若部署在客户可控服务器,实例凭据也可能被复制 | 激活资格依靠授权码、实例/部署绑定规则及服务端权益;TLS、请求幂等与限流防滥用。HMAC 仅给能保护独立密钥的服务间调用方使用;确定克隆威胁模型。 | -| D02 | Web 服务实例离线运行与冻结后立即失效不可兼得 | 已确认最长连续离线期限为 **14 天**;建议证书租约按此上限实现。冻结最迟于下次联网或租约到期生效是技术边界,故障宽限及实际操作规则仍待确认。 | -| D03 | Nginx 直接暴露 `/files` 与安装包鉴权冲突 | 文件不直接公开;Go 鉴权后本地用 Nginx `internal` + `X-Accel-Redirect`,OSS 用短期签名 URL;试用包另设公开策略。 | -| D04 | 改配置切 OSS 不会自动迁移已存在的 Local 文件 | 文件元数据持久化 driver、key、大小、SHA-256;新旧驱动可共存,历史文件迁移另设校验与回滚。 | -| D05 | Web 服务实例/部署主体、账号/站点/模块权益未映射到完整数据模型 | 首发明确实例身份、容器重建、克隆与扩容策略;模块权益建关联表/快照。站点席位、续租和崩溃释放留给后续专项。 | -| D06 | 微信/支付宝接入条件及退款对账不明确 | 建议首发仅线下订单;线上支付作为条件扩展,等商户、回调验签、退款、对账规则确定后排期。 | -| D07 | 内部用户与客户账号、子账号权限边界不清 | 分离身份域;为所有客户资源强制加 customer_id 作用域;签字确认角色/接口权限矩阵。 | -| D08 | 后台“密钥配置”可能泄露私钥及 OSS 凭证 | 私钥与各类凭证通过密钥管理或环境注入,网页不提供明文查看或修改。 | -| D09 | 试用、解绑、续费、退款的行为含糊 | 冻结/解绑审批次数、续费起算点、到期时区、退款后的权益回收、试用反滥用写成规则表并确认。 | +|决策|问题|建议及必须确认的结果| +|-|-|-| +|D01|Web 服务软件若部署在客户可控服务器,实例凭据也可能被复制|激活资格依靠授权码、实例/部署绑定规则及服务端权益;TLS、请求幂等与限流防滥用。HMAC 仅给能保护独立密钥的服务间调用方使用;确定克隆威胁模型。| +|D02|Web 服务实例离线运行与冻结后立即失效不可兼得|已确认最长连续离线期限为 **14 天**;建议证书租约按此上限实现。冻结最迟于下次联网或租约到期生效是技术边界,故障宽限及实际操作规则仍待确认。| +|D03|Nginx 直接暴露 `/files` 与安装包鉴权冲突|文件不直接公开;Go 鉴权后本地用 Nginx `internal` + `X-Accel-Redirect`,OSS 用短期签名 URL;试用包另设公开策略。| +|D04|改配置切 OSS 不会自动迁移已存在的 Local 文件|文件元数据持久化 driver、key、大小、SHA-256;新旧驱动可共存,历史文件迁移另设校验与回滚。| +|D05|Web 服务实例/部署主体、账号/站点/模块权益未映射到完整数据模型|首发明确实例身份、容器重建、克隆与扩容策略;模块权益建关联表/快照。站点席位、续租和崩溃释放留给后续专项。| +|D06|微信/支付宝接入条件及退款对账不明确|建议首发仅线下订单;线上支付作为条件扩展,等商户、回调验签、退款、对账规则确定后排期。| +|D07|内部用户与客户账号、子账号权限边界不清|分离身份域;为所有客户资源强制加 customer\_id 作用域;签字确认角色/接口权限矩阵。| +|D08|后台“密钥配置”可能泄露私钥及 OSS 凭证|私钥与各类凭证通过密钥管理或环境注入,网页不提供明文查看或修改。| +|D09|试用、解绑、续费、退款的行为含糊|冻结/解绑审批次数、续费起算点、到期时区、退款后的权益回收、试用反滥用写成规则表并确认。| **M0 冻结产物**:首发 Web 产品与接入技术栈、部署/实例身份规则、D01-D09 决策记录、授权状态机、权限矩阵、接口与错误码草案、版本兼容规则、测试负载与验收环境。D01-D03 未确认之前不定稿接入协议及下载接口。 @@ -30,84 +30,124 @@ ## 三、任务清单 -| ID | 任务与交付物 | 前置 | B/F 人天 | -| --- | --- | --- | ---: | -| T01 | 需求规则定稿:D01-D09、MVP 边界、角色矩阵、状态机与验收用例 | 无 | 3/2 | -| T02 | OpenAPI、统一错误码、租户模型、证书规范及版本兼容契约 | T01 | 2/2 | -| T03 | Go/Vue 工程骨架、配置示例、迁移/测试/CI 与静态检查 | T01 | 3/2 | -| T04 | MySQL 表结构、约束、索引、迁移、初始角色/权限数据 | T02,T03 | 4/1 | -| T05 | Gin 中间件、双身份域鉴权、刷新/注销、限流、健康检查、Redis | T02,T03 | 4/1 | -| T06 | 前端登录、路由/权限、Axios 处理、分页、空态与错误态 | T02,T03,T05 | 3/3 | -| T07 | 存储抽象与 Local 流式存储、临时文件原子提交、路径校验 | T03,T04 | 4/3 | -| T08 | Compose/Nginx/TLS 测试环境、配置注入、日志与健康检查 | T03,T05 | 4/4 | -| T09 | 内部账号/角色/按钮权限及管理页面 | T04,T05,T06 | 4/3 | -| T10 | 客户档案、主子账号、租户隔离与重置密码页面 | T04,T05,T06 | 4/3 | -| T11 | 产品/模块/授权模板管理、禁用约束与页面 | T04,T09 | 3/3 | -| T12 | License 模型、权益、状态机、生成/冻结/解绑/延期事务 | T10,T11 | 4/1 | -| T13 | P-256 ECDSA 签发、证书版本、公钥 ID、规范序列化与 Web 接入测试向量 | T02,T12 | 5/3 | -| T14 | Web 服务实例标识/激活接口、重试幂等、并发绑定及激活记录页面 | T12,T13 | 6/4 | -| T15 | Web 服务实例心跳、14 天租约、冻结传播、缓存失效、异常激活监测 | T13,T14 | 5/4 | -| T16* | 账号/站点授权:席位占用/释放/续租与租户接入 | T12,T15 | 4/3 | -| T17 | 套餐、价格快照、订单号、线下录单及审批列表 | T10,T11,T12 | 3/3 | -| T18 | 订单确认、幂等发放、续费申请、作废/退款规则 | T12,T17 | 5/4 | -| T19 | 站内/邮件通知、30/15/7 天提醒去重与失败重试 | T12,T18 | 4/2 | -| T20 | 财务/到期报表统计口径、鉴权及受限 Excel 导出 | T17,T18 | 3/2 | -| T21 | 版本/兼容/发布状态、强更、灰度分组与管理页 | T11,T12 | 4/3 | -| T22 | 分片上传、断点续传、SHA-256、配额和残留清理 | T07,T21 | 5/4 | -| T23 | 版本检查、鉴权下载、Range、下载日志与前端入口 | T15,T21,T22 | 4/3 | -| T24* | OSS 驱动、短时签名 URL、Local 共存、迁移/回滚演练 | T07,T23 | 3/2 | -| T25 | 客户门户授权/到期/订单/续费/下载与账号页 | T10,T15,T18,T23 | 3/3 | -| T26 | 后台概览、审计分页/脱敏、筛选与保留策略 | T09,T14,T18,T23 | 3/3 | -| T27 | Web 服务端接入测试桩、证书验签向量、前后端闭环联调 | T15,T23,T25 | 4/3 | -| T28 | 并发/压力、越权、重放、路径穿越、故障注入与回归 | T27 | 4/3 | -| T29 | DB+binlog/文件/密钥备份恢复、监控告警、回滚手册 | T08,T28 | 3/2 | -| T30 | UAT 签字、发布演练、灰度上线、观察与问题关闭 | T29 | 3/2 | +### 执行状态(2026-10-01) -`*` 是条件项;T16/T24 已确认不纳入首发。原桌面假设下估算 **后端 113、前端 81、合计 194 人天**;不含 T16/T24 时为后端 106、前端 76。Web 服务实例身份、部署扩容和接入方未定,**这些人天及第 33-37 周窗口尚未重估,不可作为 Web 首发承诺**;每人每周约 3.5 个有效开发日仅是旧排期假设。具体前提、签字问题和验收场景见[架构决策与 MVP 验收规格](./软件授权与统一管理平台-架构决策与MVP验收规格.md)。 +状态定义:**未开始**=未实施;**进行中**=有实现但交付物未齐;**阻塞**=缺业务决定或接入条件;**待验收**=实现及本地检查完成,仍缺评审/环境验收;**已验收**=任务完成定义及验收记录均满足;**暂缓**=明确不纳入首发。不以创建文件或通过单元测试替代完整任务验收。每项实现、验证或阻塞变化后更新此表;此处状态是项目文档状态,不自动关闭 Craft Agent 看板任务。 + +|任务|状态|交付依据 / 剩余工作| +|-|-|-| +|T01|阻塞|已形成 ADR 与 U01-U11 草案;缺产品/接入负责人、实例规则、权限矩阵及业务签字| +|T02|阻塞|已记录DEV-LICENSE-v0.1签发开发假设;依赖T01,OpenAPI、错误码、租户与证书正式契约未冻结| +|T03|待验收|已加入 golang-migrate 执行器/显式 up-down-version-force 命令;专用 MySQL 8.0 空库 up/down 与非法 DDL dirty/force 恢复演练通过;Go 生命周期、test/vet、前端 5 用例/build、CI 配置已核对;业务迁移、真实部署、远端 CI 与评审仍缺,不能标已验收| +|T04|进行中|管理员/会话/客户/产品及licenses/audit_events迁移已完成专用MySQL真实up验证(version 2 clean);正式表结构、完整权益与种子权限验收仍依赖T02决策| +|T05|进行中|已实现单一内部管理员 bcrypt 登录、数据库会话、服务端角色控制和注销失效;已补Redis共享入口限流和fail-closed集成测试;双身份域、刷新策略及Redis生产TLS/ACL/HA仍未完成| +|T06|进行中|已实现 Vue 管理台登录/会话恢复/退出、Axios 统一错误处理、客户搜索空态和产品列表;正式权限路由、完整分页编辑体验仍待补齐| +|T07|进行中|Local对象存储、路径/符号链接校验及上传临时文件能力已实现;分片/断点续传/配额与残留回收未完成| +|T08|进行中|新增Compose/API与前端镜像、内部网络、只读Nginx包挂载、保护文件注入、readiness/schema gate、显式CIDR代理信任、Secure cookie开关和真实证书TLS样例;Compose校验/前端镜像/Nginx语法通过,Redis为可选cache profile;API镜像受Docker出站网络阻断,完整Compose smoke与真实TLS代理仍未完成;见docs/deployment-delivery.md| +|T09|进行中|已有单一 admin 初始化命令和服务端角色门禁;多账号、RBAC 管理页及审计待正式规则| +|T10|进行中|已实现客户档案真实 MySQL CRUD 的新增/列表搜索/删除;客户账号、租户隔离、编辑页面和正式唯一性规则未完成| +|T11|进行中|已实现产品编码/名称/说明真实 MySQL CRUD API及基础列表页;模块、模板、禁用约束和完整编辑页未完成| +|T12|进行中|已实现期限授权签发/详情/撤销/续期、version 3 操作幂等记录、事务审计、真实MySQL和并发验证;实例绑定、权益模型、正式状态机和契约验收仍依赖T01/T02| +|T13|进行中|license-v1/lease-v1 P-256签名、公钥端点及固定公开租约验签向量已实现;新增显式配置DEV v2签名key_id、当前key签发/旧key验证目录及Go→Node撤销/未知/篡改测试;真实业务轮换、生命周期批准、正式契约与验收待完成| +|T14|进行中|实例UUID/secret哈希、事务激活、并发幂等与脱敏实例抽屉已实现并通过MySQL测试;克隆/迁移/扩容阻塞| +|T15|进行中|006迁移、实例凭据心跳、60秒限频、14天独立签名租约、UTC回拨容差与冻结/撤销联网传播已实现;MySQL事务/并发验证通过,新增独立Node验签/租约高水位参考执行器;可信持久化、真实客户端接入、异常监测和UAT未完成| +|T16|暂缓|站点并发授权不纳入已确认首发范围| +|T17|进行中|已实现v4线下订单录入、列表、详情及客户/产品范围校验;套餐、价格快照、审批列表仍待正式规则| +|T18|进行中|已实现订单收款确认、一次性事务发放、幂等重放和并发验证;续费起始日、退款/撤销关系、审批角色仍为待确认规则| +|T19|未开始|通知、提醒去重与失败重试仍未实现;Redis可选部署及本地限流不代表通知能力| +|T20|未开始|订单金额/收款凭据已留存,可作为报表输入;财务口径、报表和受限导出待开发| +|T21|进行中|DEV版本列表、单体上传发布状态及管理页已实现;请求ID/观测有增量,兼容策略、强更、灰度和人工登录验收未完成| +|T22|进行中|DEV单体上传SHA-256、64MiB边界、事务回滚及重复digest并发测试通过;通用请求体上限与观测有增量,分片/断点续传/配额/崩溃残留回收仍未完成| +|T23|进行中|隔离MySQL/Nginx鉴权、真实字节/SHA-256、Range206、内部路径404及拒绝审计通过;版本检查、客户端入口及业务运行时升级未完成| +|T24|暂缓|OSS 与历史文件迁移不纳入已确认首发范围| +|T25|进行中|新增独立 `/customer` 实例凭据只读入口及 `/api/v1/portal/snapshot`,覆盖产品/授权/实例/租约/下载权限、分页、审计、错误态和越权拒绝;客户账号登录、租户/RBAC/重置及订单续费仍未定义,不能视为完整客户门户| +|T26|进行中|订单/授权/实例激活/心跳/冻结写事务审计;后台显示last_seen、租约、冻结和传播状态且不返回secret;审计分页、筛选、保留与完整覆盖未完成| +|T27|进行中|Web API客户端、同源/Cookie策略及本地下载入口已接入;新增独立client/verify.mjs及Go→Node v2跨语言验签测试;真实接入方完整联调及负责人确认未完成| +|T28|进行中|增加JSON日志脱敏、请求体/Origin/入口限流测试及四类入口前置保护;Redis共享登录配额/断连拒绝集成测试通过;TLS/ACL/HA、真实代理故障、压力/容量、依赖漏洞修复及正式安全验收未完成| +|T29|进行中|新增备份/恢复脚本、独立loopback ready/指标及临时受保护key两次API启动验签连续性演练;签名key排除、空目标保护和sha256校验、一次性隔离恢复演练通过;key_id/轮换、持久监控告警、真实生产密钥备份、binlog/一致性自动校验和回滚演练仍未完成,见docs/deployment-delivery.md与docs/operations-security.md| +|T30|阻塞|UAT签字、完整Compose、Linux race、真实TLS/Redis HA、压力恢复、灰度和生产批准均未完成;本次测试证据不构成发布授权| + +执行记录见 [任务执行记录](./docs/task-execution.md)。当前仅允许提前推进不固化业务规则的 T03 基础设施;不视为 T01/T02 已完成,也不承诺正式发布。 + +|ID|任务与交付物|前置|B/F 人天| +|-|-|-|-:| +|T01|需求规则定稿:D01-D09、MVP 边界、角色矩阵、状态机与验收用例|无|3/2| +|T02|OpenAPI、统一错误码、租户模型、证书规范及版本兼容契约|T01|2/2| +|T03|Go/Vue 工程骨架、配置示例、迁移/测试/CI 与静态检查|T01|3/2| +|T04|MySQL 表结构、约束、索引、迁移、初始角色/权限数据|T02,T03|4/1| +|T05|Gin 中间件、双身份域鉴权、刷新/注销、限流、健康检查、Redis|T02,T03|4/1| +|T06|前端登录、路由/权限、Axios 处理、分页、空态与错误态|T02,T03,T05|3/3| +|T07|存储抽象与 Local 流式存储、临时文件原子提交、路径校验|T03,T04|4/3| +|T08|Compose/Nginx/TLS 测试环境、配置注入、日志与健康检查|T03,T05|4/4| +|T09|内部账号/角色/按钮权限及管理页面|T04,T05,T06|4/3| +|T10|客户档案、主子账号、租户隔离与重置密码页面|T04,T05,T06|4/3| +|T11|产品/模块/授权模板管理、禁用约束与页面|T04,T09|3/3| +|T12|License 模型、权益、状态机、生成/冻结/解绑/延期事务|T10,T11|4/1| +|T13|P-256 ECDSA 签发、证书版本、公钥 ID、规范序列化与 Web 接入测试向量|T02,T12|5/3| +|T14|Web 服务实例标识/激活接口、重试幂等、并发绑定及激活记录页面|T12,T13|6/4| +|T15|Web 服务实例心跳、14 天租约、冻结传播、缓存失效、异常激活监测|T13,T14|5/4| +|T16\*|账号/站点授权:席位占用/释放/续租与租户接入|T12,T15|4/3| +|T17|套餐、价格快照、订单号、线下录单及审批列表|T10,T11,T12|3/3| +|T18|订单确认、幂等发放、续费申请、作废/退款规则|T12,T17|5/4| +|T19|站内/邮件通知、30/15/7 天提醒去重与失败重试|T12,T18|4/2| +|T20|财务/到期报表统计口径、鉴权及受限 Excel 导出|T17,T18|3/2| +|T21|版本/兼容/发布状态、强更、灰度分组与管理页|T11,T12|4/3| +|T22|分片上传、断点续传、SHA-256、配额和残留清理|T07,T21|5/4| +|T23|版本检查、鉴权下载、Range、下载日志与前端入口|T15,T21,T22|4/3| +|T24\*|OSS 驱动、短时签名 URL、Local 共存、迁移/回滚演练|T07,T23|3/2| +|T25|客户门户授权/到期/订单/续费/下载与账号页|T10,T15,T18,T23|3/3| +|T26|后台概览、审计分页/脱敏、筛选与保留策略|T09,T14,T18,T23|3/3| +|T27|Web 服务端接入测试桩、证书验签向量、前后端闭环联调|T15,T23,T25|4/3| +|T28|并发/压力、越权、重放、路径穿越、故障注入与回归|T27|4/3| +|T29|DB+binlog/文件/密钥备份恢复、监控告警、回滚手册|T08,T28|3/2| +|T30|UAT 签字、发布演练、灰度上线、观察与问题关闭|T29|3/2| + +`\*` 是条件项;T16/T24 已确认不纳入首发。原桌面假设下估算 **后端 113、前端 81、合计 194 人天**;不含 T16/T24 时为后端 106、前端 76。Web 服务实例身份、部署扩容和接入方未定,**这些人天及第 33-37 周窗口尚未重估,不可作为 Web 首发承诺**;每人每周约 3.5 个有效开发日仅是旧排期假设。具体前提、签字问题和验收场景见[架构决策与 MVP 验收规格](./软件授权与统一管理平台-架构决策与MVP验收规格.md)。 ## 四、分域验收标准 -### 1. 数据、身份及 RBAC(T04-T11) +### 1\. 数据、身份及 RBAC(T04-T11) -- 空库迁移成功并演练失败恢复;授权码、订单号、AppID 唯一;订单金额采用定点数,时间以 UTC 存储;模块权益/实例绑定/证书版本/通知/订单发放记录补齐。按 `(customer_id,status,expire_time)` 等查询建立复合索引并测量查询计划。 -- 内部与客户 token 的身份域/受众分离;用户停用和登出后敏感操作失效,刷新 token 轮换。客户接口服务端强制过滤 customer_id,验证同角色跨客户读取/修改均失败,不能只靠前端隐藏按钮。 -- 密码采用 bcrypt 或 Argon2id;手机号可按需加密并展示脱敏;日志禁止写入 token、授权码、私钥、完整手机号。菜单与接口权限有对应测试。 +* 空库迁移成功并演练失败恢复;授权码、订单号、AppID 唯一;订单金额采用定点数,时间以 UTC 存储;模块权益/实例绑定/证书版本/通知/订单发放记录补齐。按 `(customer\_id,status,expire\_time)` 等查询建立复合索引并测量查询计划。 +* 内部与客户 token 的身份域/受众分离;用户停用和登出后敏感操作失效,刷新 token 轮换。客户接口服务端强制过滤 customer\_id,验证同角色跨客户读取/修改均失败,不能只靠前端隐藏按钮。 +* 密码采用 bcrypt 或 Argon2id;手机号可按需加密并展示脱敏;日志禁止写入 token、授权码、私钥、完整手机号。菜单与接口权限有对应测试。 -### 2. 授权与 Web 接入协议(T12-T16) +### 2\. 授权与 Web 接入协议(T12-T16) -- 试用、永久、订阅、站点授权分别定义允许的状态迁移和解绑/重绑上限;首发重点定义 Web 服务实例授权。实例标识、绑定及后续重绑由数据库事务保障,并发重复激活只占用一次;Redis 只加速,不作唯一事实来源。 -- 证书包含 `schema_version`、`license_id`、`product_id`、Web 服务实例/账号主体、模块权益、`issued_at`、`not_before`、`expires_at`、`lease_expires_at`、`key_id`;规范签名字节/编码及算法,提供服务端接入测试向量。私钥不可从后台读取。 -- 明确激活请求 ID、时间戳/nonce、幂等返回、重试退避及错误码;Web 服务实例断网在 14 天租约内可用,过期不可用;冻结后按 D02 最迟失效时间验收。服务器时钟、实例标识持久化和容器重建行为必须纳入测试。 -- 站点授权作为后续专项:明确租户、用户/设备标识、席位 TTL、续租和异常断线回收;不得把 Web 部署实例标识直接复用为并发席位。 +* 试用、永久、订阅、站点授权分别定义允许的状态迁移和解绑/重绑上限;首发重点定义 Web 服务实例授权。实例标识、绑定及后续重绑由数据库事务保障,并发重复激活只占用一次;Redis 只加速,不作唯一事实来源。 +* 证书包含 `schema\_version`、`license\_id`、`product\_id`、Web 服务实例/账号主体、模块权益、`issued\_at`、`not\_before`、`expires\_at`、`lease\_expires\_at`、`key\_id`;规范签名字节/编码及算法,提供服务端接入测试向量。私钥不可从后台读取。 +* 明确激活请求 ID、时间戳/nonce、幂等返回、重试退避及错误码;Web 服务实例断网在 14 天租约内可用,过期不可用;冻结后按 D02 最迟失效时间验收。服务器时钟、实例标识持久化和容器重建行为必须纳入测试。 +* 站点授权作为后续专项:明确租户、用户/设备标识、席位 TTL、续租和异常断线回收;不得把 Web 部署实例标识直接复用为并发席位。 -### 3. 订单、通知、报表(T17-T20) +### 3\. 订单、通知、报表(T17-T20) -- 订单保存价格、套餐和权益快照;定义待确认、已确认、已发放、作废、退款的合法转移。一次订单最多发放一次;订单与发放主记录使用事务,跨系统副作用使用可靠事件/重试及唯一业务键。 -- 提醒按 license+提醒档位+到期日唯一去重;多实例定时任务也只能产生一条通知;发送失败可重试,延期后不再误发。财务报表定义币种、税额、退款及时区,只允许授权角色导出并限制规模。 -- **线上支付条件扩展**:另设商户沙箱、下单、回调原文验签与金额匹配、重复回调不重复发放、退款、对账、异常补偿、财务 UAT;未启用前页面不能展示可支付按钮。 +* 订单保存价格、套餐和权益快照;定义待确认、已确认、已发放、作废、退款的合法转移。一次订单最多发放一次;订单与发放主记录使用事务,跨系统副作用使用可靠事件/重试及唯一业务键。 +* 提醒按 license+提醒档位+到期日唯一去重;多实例定时任务也只能产生一条通知;发送失败可重试,延期后不再误发。财务报表定义币种、税额、退款及时区,只允许授权角色导出并限制规模。 +* **线上支付条件扩展**:另设商户沙箱、下单、回调原文验签与金额匹配、重复回调不重复发放、退款、对账、异常补偿、财务 UAT;未启用前页面不能展示可支付按钮。 -### 4. 版本、存储及下载(T07,T21-T24) +### 4\. 版本、存储及下载(T07,T21-T24) -- 存储接口支持流式 `Put/Open/Stat/Delete`、私有 key、上下文与文件元数据;不能仅返回公开 URL。上传逐片校验,最终校验 SHA-256;缺片、重复完成、超额、路径穿越、磁盘写满都有测试,分片定期清理。 -- 版本号比较规则(建议 SemVer 或产品专用)及强更门槛明确;按客户 ID 稳定分桶或名单灰度,重复查询结果稳定,并区分平台/架构/渠道。 -- Go 验证有效权益后以 Nginx internal 路径或短期 OSS 签名地址交付正式包;不得直接猜测 `/files/{key}` 访问。支持 Range 与下载审计;存储切换后旧文件仍可读取,迁移成功以数量与 SHA-256 校验,失败可回滚。 +* 存储接口支持流式 `Put/Open/Stat/Delete`、私有 key、上下文与文件元数据;不能仅返回公开 URL。上传逐片校验,最终校验 SHA-256;缺片、重复完成、超额、路径穿越、磁盘写满都有测试,分片定期清理。 +* 版本号比较规则(建议 SemVer 或产品专用)及强更门槛明确;按客户 ID 稳定分桶或名单灰度,重复查询结果稳定,并区分平台/架构/渠道。 +* Go 验证有效权益后以 Nginx internal 路径或短期 OSS 签名地址交付正式包;不得直接猜测 `/files/{key}` 访问。支持 Range 与下载审计;存储切换后旧文件仍可读取,迁移成功以数量与 SHA-256 校验,失败可回滚。 -### 5. 审计、质量及部署(T08,T26-T30) +### 5\. 审计、质量及部署(T08,T26-T30) -- 高风险审计记录 actor/身份域、租户、目标、动作、请求 ID、IP、结果、时间及脱敏前后摘要;业务事务或可靠事件确保重要记录不因异步丢失。分页筛选并限制访问范围。 -- 关键端到端用例:线下订单→确认发放→Web 服务实例激活→离线验签→心跳续租→版本灰度→授权下载→续费/冻结。压力阈值(并发心跳、安装包大小、P95、错误率)在 T01 定义,T28 出具实测报告。 -- Compose 使用非 root 应用用户、健康检查、凭证注入和持久卷;数据库全量+binlog、文件及签名私钥备份须形成一致恢复点,至少演练一次空环境恢复。准备监控告警、部署顺序和回滚责任人。 +* 高风险审计记录 actor/身份域、租户、目标、动作、请求 ID、IP、结果、时间及脱敏前后摘要;业务事务或可靠事件确保重要记录不因异步丢失。分页筛选并限制访问范围。 +* 关键端到端用例:线下订单→确认发放→Web 服务实例激活→离线验签→心跳续租→版本灰度→授权下载→续费/冻结。压力阈值(并发心跳、安装包大小、P95、错误率)在 T01 定义,T28 出具实测报告。 +* Compose 使用非 root 应用用户、健康检查、凭证注入和持久卷;数据库全量+binlog、文件及签名私钥备份须形成一致恢复点,至少演练一次空环境恢复。准备监控告警、部署顺序和回滚责任人。 ## 五、里程碑与发布门禁 -| 里程碑 | 粗排窗口 | 验收输出 | -| --- | --- | --- | -| M0 规则冻结 | 第 2-3 周 | T01-T02 评审通过,D01-D09 责任人/决定/日期齐备;累计 B/F 5/4 人天 | -| M1 可登录基线 | 第 12-14 周 | T03-T11 基础环境可部署,身份域、权限、客户与产品主数据贯通;累计 B/F 38/27 人天 | -| M2 授权闭环 | 第 18-21 周 | T12-T15 完成 Web 服务实例激活、14 天离线/冻结行为验证;累计 B/F 58/39 人天;T16 暂不纳入首发 | -| M3 商业与升级 | 第 28-32 周 | T17-T23、T25-T26 贯通订单发放、版本下载、运营后台及客户门户;累计 B/F 92/66 人天;T24 暂不纳入首发 | -| M4 发布候选 | 第 33-37 周 | T27-T30 联调、安全/压力/恢复演练通过,UAT 签字及回滚演练完成;累计 B/F 106/76 人天 | +|里程碑|粗排窗口|验收输出| +|-|-|-| +|M0 规则冻结|第 2-3 周|T01-T02 评审通过,D01-D09 责任人/决定/日期齐备;累计 B/F 5/4 人天| +|M1 可登录基线|第 12-14 周|T03-T11 基础环境可部署,身份域、权限、客户与产品主数据贯通;累计 B/F 38/27 人天| +|M2 授权闭环|第 18-21 周|T12-T15 完成 Web 服务实例激活、14 天离线/冻结行为验证;累计 B/F 58/39 人天;T16 暂不纳入首发| +|M3 商业与升级|第 28-32 周|T17-T23、T25-T26 贯通订单发放、版本下载、运营后台及客户门户;累计 B/F 92/66 人天;T24 暂不纳入首发| +|M4 发布候选|第 33-37 周|T27-T30 联调、安全/压力/恢复演练通过,UAT 签字及回滚演练完成;累计 B/F 106/76 人天| 上述窗口是旧桌面假设下的参考数据,**并非已确认的 Web 首发排期**;只有重新明确部署实例规则、接入方与功能裁剪并重估后,才能设置新窗口。累计人天不是精确关键路径。前端可在 T02 接口冻结后用 mock 并行开发,每两周演示可运行的端到端功能并重估。线上支付、OSS 存量迁移、站点授权和 C#/C++ 正式 SDK 若后续纳入,必须增加资源或重新定日期。 **发布门禁**:不得有未关闭的高危越权、私钥泄露或未授权下载问题;并发激活与发放无超额/重复;冻结和 14 天离线行为符合签字规则;文件完整性、备份恢复、监控告警、回滚演练及值班安排均通过。把 T01-T30 建为项目工作项,分别关联 PR、接口变更、测试报告及验收记录;先确认被授权 Web 软件的产品、接入负责人和实例身份规则,再重估并进行两周迭代排期。 +