param([ValidateSet('Start','Api','Web')][string]$Mode = 'Start') $ErrorActionPreference = 'Stop' $root = Split-Path $PSScriptRoot -Parent Set-Location $root $localPaymentKey = Join-Path $root 'secrets/payment-config.key' if (-not $env:PAYMENT_CONFIG_ENCRYPTION_KEY_FILE) { if (-not (Test-Path -LiteralPath $localPaymentKey)) { throw "Missing local payment config key: $localPaymentKey" } $env:PAYMENT_CONFIG_ENCRYPTION_KEY_FILE = $localPaymentKey } 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:PAYMENT_CONFIG_ENCRYPTION_KEY_FILE = $localPaymentKey $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 }