feat: export client activation files and add Windows local launcher
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -12,6 +12,18 @@
|
||||
|
||||
已有实例丢失 secret 时不能从列表读取;当前没有重置/轮换接口。由管理员冻结旧实例并撤销旧授权,再签发新授权、创建新实例并交付。旧离线租约不会立即失效,最长按现有租约策略持续 14 天。创建超时后先刷新实例列表核实结果,不能盲目反复创建。
|
||||
|
||||
### 授权文件导入(交付格式 v1)
|
||||
|
||||
创建实例成功后,管理员可在当前凭据窗口点击“导出授权文件”,下载 UTF-8 JSON(文件名 license-{instance_id}.license.json)。仅首次展示期间可导出;已有实例无法恢复 secret 或重新导出。文件包含明文实例凭据,须经安全渠道交付,导入后移入受保护存储并妥善处理原下载文件。
|
||||
|
||||
```json
|
||||
{"format":"yhy-license-activation","version":1,"api_base_url":"https://license.yihuiyong.cn","instance_id":"实例UUID","license_key":"授权密钥","secret":"实例激活密钥"}
|
||||
```
|
||||
|
||||
客户端需实现导入入口:限制文件大小(建议 16 KiB),严格验证 JSON 对象及上述字段、类型、format/version、UUID 和非空凭据,拒绝未知版本和额外字段。api_base_url 必须是 HTTPS 根地址,无用户信息、查询、片段或路径;仅受控本机开发允许 HTTP 回环地址。文件来自不可信输入,导入前展示实例及目标授权中心,请用户确认,并校验开发团队预置的允许地址;不得将文件中的 secret 自动发送到任意地址、重定向目标或探测接口。导入不能覆盖已有不同实例身份或清除租约时间高水位;切换身份需显式受控流程。导入错误不得记录文件内容或 secret。
|
||||
|
||||
本文件未签名,不包含可信公钥、激活证书或运行租约,不能单凭导入启用业务;不代表完全离线授权。确认后,使用既有在线激活接口及幂等键,再通过预置可信公钥验证证书和心跳租约;只在既有运行策略允许时启用。公钥信任不能从本文件或 api_base_url 自动建立。
|
||||
|
||||
POST /api/v1/activation/instances/{instance_id}
|
||||
|
||||
头部:Content-Type: application/json,Idempotency-Key: 唯一业务操作标识。
|
||||
|
||||
@@ -118,7 +118,7 @@ func integrationPrompt(language, mode string) string {
|
||||
|
||||
默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。
|
||||
|
||||
首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 仅首次展示但持续用于心跳和下载。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,丢失 secret 没有找回接口。
|
||||
首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 仅首次展示但持续用于心跳和下载。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,丢失 secret 没有找回接口。
|
||||
|
||||
实现激活 POST /api/v1/activation/instances/{instance_id},提交 license_key、secret 和 Idempotency-Key;实现心跳 POST /api/v1/instances/{instance_id}/heartbeat,提交 secret、RFC3339 UTC client_time 和 Idempotency-Key。
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 本地基础管理台运行
|
||||
|
||||
Windows 用户可在项目根目录双击 `start-local.bat`,详见 [Windows 本机一键启动](windows-local-start.md)。该入口使用隔离开发数据库,复用正在运行的服务,不重置既有管理员密码。
|
||||
|
||||
开发阶段需本机 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`
|
||||
|
||||
@@ -37,4 +37,10 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
|
||||
|
||||
管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。secret 只在创建响应及当前窗口展示,数据库保存哈希,关闭后无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。
|
||||
|
||||
## 授权文件导出与导入
|
||||
|
||||
实例创建成功后,在当前凭据窗口填写实际授权中心根地址,点击“导出授权文件”,下载 `license-{instance_id}.license.json`。默认地址为 `https://license.yihuiyong.cn`。文件是 UTF-8 JSON,包含 `format: yhy-license-activation`、`version: 1`、`api_base_url`、`instance_id`、`license_key`、`secret`。前端仅从当前内存凭据生成下载,不新增接口或数据库表,不写浏览器持久化存储。文件含明文密钥,需安全交付;关闭窗口后不能重新取得 secret 或补导出。
|
||||
|
||||
客户端需按 protocol.md 的“授权文件导入”实现导入入口。接入中心生成的工程提示已包含这一要求,但目前不提供各语言已实现的导入 SDK。客户端应限制文件大小、校验字段及版本、核对受控授权中心允许列表并让用户确认,随后安全保存凭据、在线激活、验签证书和心跳租约。导入不能清空既有时间高水位或静默切换实例。文件本身未签名,不包含可信公钥,不构成离线运行凭证。
|
||||
|
||||
升级方案随 JSON、Markdown 和 ZIP 导出,ZIP 新增 upgrade.md(共六个文件)。实例创建响应设置 Cache-Control: no-store;前端不将 secret 写入日志或浏览器持久化存储。
|
||||
|
||||
39
docs/windows-local-start.md
Normal file
39
docs/windows-local-start.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Windows 本机一键启动
|
||||
|
||||
在项目根目录双击 `start-local.bat`。也可在 CMD 中执行:
|
||||
|
||||
```bat
|
||||
cd /d E:\webroot\YHY-MAGER
|
||||
start-local.bat
|
||||
```
|
||||
|
||||
需要安装 Go 1.23+、Node.js 20+(含 npm)、Docker Desktop,且先启动 Docker Desktop。Windows 自带的 Windows PowerShell 5.1 即可运行。首次启动需联网下载 MySQL 镜像、Go 模块和前端依赖。
|
||||
|
||||
脚本调用 `scripts/start-local.ps1`,使用以下地址:
|
||||
|
||||
| 服务 | 地址 |
|
||||
| --- | --- |
|
||||
| 管理台 | http://127.0.0.1:15173/ |
|
||||
| API 存活检查 | http://127.0.0.1:18081/api/v1/health/live |
|
||||
| 本地 MySQL | 127.0.0.1:13307 |
|
||||
|
||||
后端已运行时,脚本只检查存活并复用,不重启、不迁移。后端未运行时,脚本复用或创建 `license-platform-mysql-app` 容器,只创建/迁移隔离数据库 `license_platform_local_261009`,不会迁移原数据库 `license_platform`。新容器随机生成本地数据库密码,后续从容器配置读取,不在终端打印或写入脚本。Docker 管理权限用户可以读取该开发密码。
|
||||
|
||||
数据库没有管理员时,会提示输入用户名、邮箱、隐藏输入的密码。已有账户不会重置。历史 schema 10 迁移后的既有用户名为 `admin-{id}`,本机已知账户为 `admin-1`,使用原密码登录。管理员初始化工具目前通过进程参数接收密码,短时间内可能被本机有权限的用户查看,适用于受控开发机器。
|
||||
|
||||
脚本分别打开 API 和 Web PowerShell 窗口,等待两端启动成功后打开浏览器。重复运行会复用存活 API 和符合前端入口特征的已有页面;存活检查不代表已验证数据库或版本,更新后需先关闭旧窗口再启动。端口被其他服务占用时,先解决冲突,不要结束不明进程。
|
||||
|
||||
关闭 API/Web 窗口即可停止相应服务;MySQL 容器保持运行、数据保留。需要停止 MySQL 时执行 `docker stop license-platform-mysql-app`。不要删除容器:当前脚本使用 Docker 容器的数据卷,删除容器会影响后续数据复用。
|
||||
|
||||
本机启动默认显式使用 `ENTRY_LIMIT_MODE=local-dev`,无需 Redis;该模式只适合本机开发。程序包默认目录为 `sessions/260930-calm-falcon/data/local-packages`,可通过 `PACKAGE_STORAGE_ROOT` 环境变量指定其他绝对目录。
|
||||
|
||||
激活和心跳签名需要持久 P-256 私钥。脚本不会生成、替换或自动选择历史私钥,也不会将私钥写入仓库。需要完整激活功能时,先在 CMD 设置受保护 PEM 文件的绝对路径,再启动:
|
||||
|
||||
```bat
|
||||
set "LICENSE_SIGNING_PRIVATE_KEY_FILE=C:\protected\license-signing.pem"
|
||||
start-local.bat
|
||||
```
|
||||
|
||||
如果使用 v2 keyring,还需设置 `LICENSE_KEYRING_FILE` 为对应受保护公钥环文件绝对路径;两者必须匹配。不要同时设置私钥文件和 `LICENSE_SIGNING_PRIVATE_KEY_PEM`,不要随意替换现有签名密钥。未配置密钥时可使用基础管理功能,但签名接口会返回不可用。
|
||||
|
||||
本脚本启动开发服务,不用于线上部署。新脚本尚未提交或推送 Git。
|
||||
27
frontend/src/license-file.test.ts
Normal file
27
frontend/src/license-file.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { buildLicenseFile, downloadLicenseFile } from './license-file'
|
||||
const credentials = { instance_id: 'test-instance', license_key: 'test-license', secret: 'test-secret' }
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.useRealTimers() })
|
||||
it('exports versioned activation credentials with normalized deployment root', () => {
|
||||
expect(buildLicenseFile(credentials, ' https://license.yihuiyong.cn/ ')).toEqual({
|
||||
format: 'yhy-license-activation', version: 1, api_base_url: 'https://license.yihuiyong.cn', ...credentials,
|
||||
})
|
||||
expect(buildLicenseFile(credentials, 'http://127.0.0.1:18081').api_base_url).toBe('http://127.0.0.1:18081')
|
||||
})
|
||||
it.each(['http://example.com', 'https://user:pass@example.com', 'https://example.com/api', 'https://example.com/?secret=x', 'https://example.com/#x', 'javascript:alert(1)', 'invalid'])('rejects invalid center %s', address => {
|
||||
expect(() => buildLicenseFile(credentials, address)).toThrow()
|
||||
})
|
||||
it('downloads JSON and releases the temporary object URL', () => {
|
||||
vi.useFakeTimers()
|
||||
const create = vi.fn(() => 'blob:test'), revoke = vi.fn()
|
||||
// Preserve URL parsing while stubbing browser download APIs absent in jsdom.
|
||||
vi.stubGlobal('URL', class extends URL { static createObjectURL = create; static revokeObjectURL = revoke })
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function(this: HTMLAnchorElement) {
|
||||
expect(this.download).toBe('license-test-instance.license.json')
|
||||
expect(this.href).toBe('blob:test')
|
||||
})
|
||||
downloadLicenseFile(credentials, 'https://license.yihuiyong.cn')
|
||||
expect(create).toHaveBeenCalledWith(expect.any(Blob)); expect(click).toHaveBeenCalledOnce()
|
||||
expect(document.querySelector('a')).toBeNull()
|
||||
vi.runAllTimers(); expect(revoke).toHaveBeenCalledWith('blob:test')
|
||||
})
|
||||
34
frontend/src/license-file.ts
Normal file
34
frontend/src/license-file.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
export type ActivationCredentials = { instance_id: string; license_key: string; secret: string }
|
||||
|
||||
// This is a credential delivery file, not a signed license certificate or lease.
|
||||
export function buildLicenseFile(credentials: ActivationCredentials, baseURL: string) {
|
||||
const url = new URL(baseURL.trim())
|
||||
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
|
||||
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
|
||||
url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
||||
throw new Error('授权中心必须是 HTTPS 根地址;仅本机开发允许 HTTP 回环地址。')
|
||||
}
|
||||
return {
|
||||
format: 'yhy-license-activation',
|
||||
version: 1,
|
||||
api_base_url: url.origin,
|
||||
instance_id: credentials.instance_id,
|
||||
license_key: credentials.license_key,
|
||||
secret: credentials.secret,
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadLicenseFile(credentials: ActivationCredentials, baseURL: string) {
|
||||
const content = JSON.stringify(buildLicenseFile(credentials, baseURL), null, 2) + '\n'
|
||||
const blob = new Blob([content], { type: 'application/json;charset=utf-8' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = `license-${credentials.instance_id}.license.json`
|
||||
document.body.appendChild(anchor)
|
||||
try { anchor.click() } finally {
|
||||
anchor.remove()
|
||||
// Release only after the browser has processed the download navigation.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ it('creates and displays first-return credentials, without another creation entr
|
||||
await w.get('button').trigger('click');await flushPromises()
|
||||
expect(api.provisionLicenseInstance).toHaveBeenCalledWith(7)
|
||||
expect(w.text()).toContain('test-license');expect(w.text()).toContain('test-instance');expect(w.text()).toContain('test-secret');expect(w.emitted('created')).toHaveLength(1)
|
||||
expect(w.find('button').exists()).toBe(false);w.unmount()
|
||||
expect(w.findAll('button').map(b=>b.text())).toEqual(['导出授权文件']);w.unmount()
|
||||
const reopened=mount(Panel,{props:{licenseId:7,hasInstance:true,ready:true},global:{plugins:[ElementPlus]}})
|
||||
expect(reopened.get('button').attributes('disabled')).toBeDefined();expect(reopened.text()).not.toContain('test-secret');reopened.unmount()
|
||||
})
|
||||
|
||||
@@ -2,9 +2,17 @@
|
||||
import { ref } from 'vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { getLicense, provisionLicenseInstance } from '../api'
|
||||
import { downloadLicenseFile } from '../license-file'
|
||||
const props = defineProps<{licenseId:number;hasInstance:boolean;ready:boolean}>()
|
||||
const emit = defineEmits<{created:[]}>()
|
||||
const busy = ref(false), error = ref('')
|
||||
const exportError = ref(''), baseURL = ref('https://license.yihuiyong.cn')
|
||||
function exportFile() {
|
||||
if (!credentials.value) return
|
||||
exportError.value = ''
|
||||
try { downloadLicenseFile(credentials.value, baseURL.value) }
|
||||
catch (e) { exportError.value = e instanceof Error ? e.message : '导出失败,请重试' }
|
||||
}
|
||||
const credentials = ref<{instance_id:string;license_key:string;secret:string}|null>(null)
|
||||
async function create() {
|
||||
if(busy.value || props.hasInstance || !props.ready || credentials.value || error.value) return
|
||||
@@ -29,6 +37,11 @@ async function create() {
|
||||
<template v-if="credentials">
|
||||
<p role="status">实例已创建。请立即安全保存下列凭据,关闭窗口后不再显示激活密钥。</p>
|
||||
<dl class="license-detail"><dt>实例 ID(instance_id)</dt><dd class="license-code">{{credentials.instance_id}}</dd><dt>授权码(license_key)</dt><dd class="license-code">{{credentials.license_key}}</dd><dt>激活密钥(secret)</dt><dd class="license-code">{{credentials.secret}}</dd></dl>
|
||||
<label for="license-export-base-url">授权文件中的授权中心地址</label>
|
||||
<el-input id="license-export-base-url" v-model="baseURL" placeholder="https://license.yihuiyong.cn" />
|
||||
<el-button type="primary" @click="exportFile">导出授权文件</el-button>
|
||||
<p v-if="exportError" class="error" role="alert">{{ exportError }}</p>
|
||||
<p>导出的 .license.json 含激活密钥,请安全交付。客户端需支持本文件格式,导入后在线激活并获取运行租约;文件本身不代表授权有效。关闭此窗口后无法再次导出包含密钥的文件。</p>
|
||||
<p>默认授权中心:https://license.yihuiyong.cn;私有部署填写实际 HTTPS 根地址。密钥仅首次展示,但客户端激活后仍需安全保存用于心跳和下载;不要放入日志、截图或普通工单。生产验签公钥应由开发团队预置。</p>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
152
scripts/start-local.ps1
Normal file
152
scripts/start-local.ps1
Normal file
@@ -0,0 +1,152 @@
|
||||
param([ValidateSet('Start','Api','Web')][string]$Mode = 'Start')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path $PSScriptRoot -Parent
|
||||
Set-Location $root
|
||||
|
||||
if ($Mode -eq 'Api') {
|
||||
Set-Location (Join-Path $root 'backend')
|
||||
& go run ./cmd/server
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
if ($Mode -eq 'Web') {
|
||||
Set-Location (Join-Path $root 'frontend')
|
||||
& npm.cmd run dev -- --port 15173 --strictPort
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
function Invoke-Checked([scriptblock]$Action) {
|
||||
& $Action
|
||||
if ($LASTEXITCODE -ne 0) { throw "Command failed (exit $LASTEXITCODE)." }
|
||||
}
|
||||
function Test-Port([int]$Port) {
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try { return $client.ConnectAsync('127.0.0.1', $Port).Wait(500) -and $client.Connected }
|
||||
catch { return $false }
|
||||
finally { $client.Dispose() }
|
||||
}
|
||||
function Wait-Http([string]$Url, [int]$Seconds = 90) {
|
||||
$deadline = (Get-Date).AddSeconds($Seconds)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -Uri $Url -TimeoutSec 2
|
||||
if ($response.StatusCode -eq 200) { return }
|
||||
} catch { }
|
||||
Start-Sleep -Milliseconds 1000
|
||||
}
|
||||
throw "Service did not become ready: $Url. Check its command window."
|
||||
}
|
||||
function Start-ServiceWindow([string]$ServiceMode) {
|
||||
$script = Join-Path $PSScriptRoot 'start-local.ps1'
|
||||
Start-Process powershell.exe -WorkingDirectory $root -ArgumentList @('-NoProfile', '-NoExit', '-ExecutionPolicy', 'Bypass', '-File', ('"' + $script + '"'), '-Mode', $ServiceMode) | Out-Null
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($command in @('go', 'node', 'npm.cmd', 'docker')) {
|
||||
if (-not (Get-Command $command -ErrorAction SilentlyContinue)) { throw "Missing $command. Install Go 1.23+, Node.js 20+ and Docker Desktop, then reopen this window." }
|
||||
}
|
||||
Write-Host 'License Platform - local development startup'
|
||||
Write-Host 'Web: http://127.0.0.1:15173/ API: http://127.0.0.1:18081/'
|
||||
|
||||
if (Test-Port 18081) {
|
||||
# Never terminate or migrate underneath an existing backend.
|
||||
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:18081/api/v1/health/live' -TimeoutSec 3
|
||||
if ($health.status -ne 'ok') { throw 'Port 18081 is occupied by another service.' }
|
||||
Write-Host 'API already running; reusing it without migration or restart.'
|
||||
} else {
|
||||
Invoke-Checked { docker info --format '{{.ServerVersion}}' | Out-Null }
|
||||
$container = 'license-platform-mysql-app'
|
||||
$database = 'license_platform_local_261009'
|
||||
$names = & docker ps -a --format '{{.Names}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot query Docker. Start Docker Desktop first.' }
|
||||
if ($names -notcontains $container) {
|
||||
if (Test-Port 13307) { throw 'Port 13307 is occupied. No container or data was changed.' }
|
||||
$random = New-Object byte[] 32
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
try { $rng.GetBytes($random) } finally { $rng.Dispose() }
|
||||
$env:MYSQL_ROOT_PASSWORD = -join ($random | ForEach-Object { $_.ToString('x2') })
|
||||
Write-Host 'Creating isolated local MySQL container (first startup may pull mysql:8.0)...'
|
||||
Invoke-Checked { docker run -d --name $container -e MYSQL_ROOT_PASSWORD -p 127.0.0.1:13307:3306 mysql:8.0 | Out-Null }
|
||||
Remove-Item Env:MYSQL_ROOT_PASSWORD
|
||||
} else {
|
||||
Invoke-Checked { docker start $container | Out-Null }
|
||||
}
|
||||
$info = (& docker inspect $container | ConvertFrom-Json)[0]
|
||||
$passwordEntry = @($info.Config.Env | Where-Object { $_ -like 'MYSQL_ROOT_PASSWORD=*' })
|
||||
if ($passwordEntry.Count -ne 1) { throw 'Local MySQL root password is not available in the container configuration.' }
|
||||
$password = $passwordEntry[0].Substring('MYSQL_ROOT_PASSWORD='.Length)
|
||||
$ports = @($info.NetworkSettings.Ports.'3306/tcp')
|
||||
if (-not ($ports | Where-Object { $_.HostPort -eq '13307' })) { throw 'MySQL container must expose port 13307.' }
|
||||
$env:MYSQL_PWD = $password
|
||||
Write-Host 'Waiting for local MySQL (up to 120 seconds)...'
|
||||
$ready = $false
|
||||
for ($i = 0; $i -lt 60; $i++) {
|
||||
& docker exec -e MYSQL_PWD $container mysql -uroot -N -e 'SELECT 1' 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { $ready = $true; break }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
if (-not $ready) { throw 'MySQL did not become ready. Check Docker container logs.' }
|
||||
Invoke-Checked { docker exec -e MYSQL_PWD $container mysql -uroot -e "CREATE DATABASE IF NOT EXISTS $database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" }
|
||||
$env:MYSQL_DSN = "root:${password}@tcp(127.0.0.1:13307)/${database}?parseTime=true"
|
||||
$escaped = [Uri]::EscapeDataString($password)
|
||||
$env:MIGRATION_DSN = "mysql://root:${escaped}@tcp(127.0.0.1:13307)/${database}?multiStatements=true"
|
||||
Set-Location (Join-Path $root 'backend')
|
||||
Write-Host "Applying migrations to $database only (original license_platform is untouched)..."
|
||||
Invoke-Checked { go run ./cmd/migrate -dir ./migrations up }
|
||||
$adminCount = & docker exec -e MYSQL_PWD $container mysql -uroot -N -e "SELECT COUNT(*) FROM ${database}.admins"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot check administrator accounts.' }
|
||||
if ([int]$adminCount -eq 0) {
|
||||
$username = Read-Host 'First administrator username (3-32 lowercase letters/digits/_/-)'
|
||||
$email = Read-Host 'Administrator email'
|
||||
$secure = Read-Host 'Administrator password (nonempty, maximum 72 UTF-8 bytes)' -AsSecureString
|
||||
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
|
||||
try {
|
||||
$plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)
|
||||
# admin-init currently accepts password only via CLI; never print it.
|
||||
Invoke-Checked { go run ./cmd/admin-init -username $username -email $email -password $plain }
|
||||
} finally {
|
||||
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer)
|
||||
$plain = $null
|
||||
$secure.Dispose()
|
||||
}
|
||||
}
|
||||
Remove-Item Env:MYSQL_PWD
|
||||
Remove-Item Env:MIGRATION_DSN
|
||||
$password = $null
|
||||
$env:HTTP_ADDR = '127.0.0.1:18081'
|
||||
$env:SESSION_COOKIE_SECURE = 'false'
|
||||
$env:ENTRY_LIMIT_MODE = 'local-dev'
|
||||
$env:METRICS_ADDR = ''
|
||||
# Preserve explicitly supplied protected signing key and keyring paths.
|
||||
if (-not $env:LICENSE_SIGNING_PRIVATE_KEY_FILE -and -not $env:LICENSE_SIGNING_PRIVATE_KEY_PEM) {
|
||||
Write-Warning 'No signing key configured. Management UI works, but activation/heartbeat signing requires LICENSE_SIGNING_PRIVATE_KEY_FILE (protected P-256 PEM).'
|
||||
}
|
||||
if (-not $env:PACKAGE_STORAGE_ROOT) {
|
||||
$env:PACKAGE_STORAGE_ROOT = Join-Path $root 'sessions/260930-calm-falcon/data/local-packages'
|
||||
New-Item -ItemType Directory -Force -Path $env:PACKAGE_STORAGE_ROOT | Out-Null
|
||||
}
|
||||
Start-ServiceWindow 'Api'
|
||||
Remove-Item Env:MYSQL_DSN
|
||||
Wait-Http 'http://127.0.0.1:18081/api/v1/health/live'
|
||||
}
|
||||
if (Test-Port 15173) {
|
||||
$page = Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:15173/' -TimeoutSec 3
|
||||
if ($page.Content -notmatch '/src/main.ts') { throw 'Port 15173 is occupied by an unrecognized frontend. Close it and rerun.' }
|
||||
Write-Host 'Frontend already running; opening the existing page.'
|
||||
Start-Process 'http://127.0.0.1:15173/'
|
||||
exit 0
|
||||
}
|
||||
Set-Location (Join-Path $root 'frontend')
|
||||
if (-not (Test-Path 'node_modules/.bin/vite.cmd')) {
|
||||
Write-Host 'Installing frontend dependencies...'
|
||||
Invoke-Checked { npm.cmd ci }
|
||||
}
|
||||
Start-ServiceWindow 'Web'
|
||||
Wait-Http 'http://127.0.0.1:15173/'
|
||||
Start-Process 'http://127.0.0.1:15173/'
|
||||
Write-Host 'Ready. Close API/Web windows to stop those services; MySQL data is retained.'
|
||||
} catch {
|
||||
Write-Host ('Startup failed: ' + $_.Exception.Message) -ForegroundColor Red
|
||||
exit 1
|
||||
} finally {
|
||||
Set-Location $root
|
||||
}
|
||||
11
start-local.bat
Normal file
11
start-local.bat
Normal file
@@ -0,0 +1,11 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\start-local.ps1"
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo Startup failed. See the error above.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
endlocal
|
||||
Reference in New Issue
Block a user