Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add local portal preview dev loop
rcourtman35c7aea985ba
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 9a9582e5b4..5a1f81021e 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -251,6 +251,14 @@ The top-level authenticated shell is part of that same customer-facingboundary: cloud-paid trial prompts may appear in owned commercial surfaces, butthe app shell must not force a global, persistent Pro trial nudge thatoverrides the primary runtime chrome for every signed-in user.+The maintained Pulse Account portal frontend is part of that same boundary for+local development as well as runtime delivery. Styling or interaction work on+`internal/cloudcp/portal/frontend/` must have a local preview path that uses+the same frontend build pipeline as the embedded production bundle, while+serving scenario-backed local portal APIs without requiring a live cloud deploy+for every iteration. Final verification still belongs on a real control-plane+instance, but local portal design work must not depend on redeploying+`cloud.pulserelay.pro` just to see each frontend change.That same shell framing also owns user-facing prerelease labeling forrc-channel builds. `frontend-modern/src/AppLayout.tsx` may still key off thecanonical `rc` channel metadata internally, but the visible badge must framediff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.jsonindex ee97d1579d..6938951327 100644--- a/internal/cloudcp/portal/dist/build_manifest.json+++ b/internal/cloudcp/portal/dist/build_manifest.json@@ -1,9 +1,10 @@{- "source_hash": "e610c850356380a4b964ccafee42ab51270cd73bd456f7acf2ae51fb49ef09cf",+ "source_hash": "cf3bd31fad5b412fe2628e9fe834b1d693d86fbb4c34160ff53ad349b7d7fad0","build_inputs": ["package.json","tsconfig.json","build.mjs",+ "build_config.mjs","src/account_controller.test.ts","src/account_controller.ts","src/account_roles.test.ts",diff --git a/internal/cloudcp/portal/frontend/README.md b/internal/cloudcp/portal/frontend/README.mdnew file mode 100644index 0000000000..82a3eb9fe7--- /dev/null+++ b/internal/cloudcp/portal/frontend/README.md@@ -0,0 +1,55 @@+# Pulse Account Frontend Dev Loop++The production portal is embedded into the control-plane binary, so styling changes do not appear on `cloud.pulserelay.pro` until the frontend bundle is rebuilt and the control-plane is redeployed.++For local UI work, use the preview server instead of production.++## Commands++```bash+npm --prefix internal/cloudcp/portal/frontend run dev+```++This does three things:++- builds the current portal frontend with the same esbuild pipeline used for production+- watches `internal/cloudcp/portal/frontend/src`+- serves a local preview at `http://127.0.0.1:8765`++## Preview URLs++- Managed hosted account: `http://127.0.0.1:8765/?scenario=managed`+- Read-only hosted account: `http://127.0.0.1:8765/?scenario=readonly`+- Self-hosted commercial account: `http://127.0.0.1:8765/?scenario=selfhosted`+- Empty hosted account: `http://127.0.0.1:8765/?scenario=empty`++Append `&reset=1` to reset a scenario back to its seed state.++The preview server keeps scenario state in memory and stubs the main portal APIs so you can exercise:++- workspace create/suspend/delete+- access invite/change-role/remove+- hosted billing handoff+- self-hosted billing/license/privacy flows++The preview server is intentionally local-only. It is for design and interaction iteration, not for validating production credentials or external services.++## Production Build++When the UI is ready to ship, rebuild the embedded bundle:++```bash+npm --prefix internal/cloudcp/portal/frontend run build+```++That updates:++- `internal/cloudcp/portal/dist/portal_app.js`+- `internal/cloudcp/portal/dist/portal_app.css`+- `internal/cloudcp/portal/dist/build_manifest.json`++After that, rebuild and deploy the control-plane binary/image to see the change on the live portal.++## Functional Caveat++The preview harness is good for local front-end iteration, but it is still a harness. Final verification for auth, live account state, Stripe, and production data should happen against a real control-plane instance before shipping.diff --git a/internal/cloudcp/portal/frontend/build.mjs b/internal/cloudcp/portal/frontend/build.mjsindex 9d4d2149a6..e34c4968cf 100644--- a/internal/cloudcp/portal/frontend/build.mjs+++ b/internal/cloudcp/portal/frontend/build.mjs@@ -1,18 +1,12 @@import fs from 'node:fs/promises';import path from 'node:path';import crypto from 'node:crypto';-import { fileURLToPath } from 'node:url';import { build } from 'esbuild';import { withExclusiveLock } from '../../../../scripts/exclusive-lock.mjs';+import { createPortalBuildOptions, distRoot, frontendRoot, manifestPath, repoRoot } from './build_config.mjs';-const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);-const frontendRoot = __dirname;-const repoRoot = path.resolve(frontendRoot, '../../../../');-const distRoot = path.resolve(frontendRoot, '../dist');const lockPath = path.join(repoRoot, 'tmp', 'locks', 'pulse-account-frontend-build.lock');-const manifestPath = path.join(distRoot, 'build_manifest.json');async function listSourceInputs(relativeDir) {const absoluteDir = path.join(frontendRoot, relativeDir);@@ -38,6 +32,7 @@ async function getBuildInputs() {'package.json','tsconfig.json','build.mjs',+ 'build_config.mjs',...sourceInputs,];}@@ -63,25 +58,7 @@ await withExclusiveLock(await fs.rm(path.join(distRoot, 'portal_app.css'), { force: true });await fs.rm(manifestPath, { force: true });- await build({- absWorkingDir: frontendRoot,- entryPoints: ['src/index.ts'],- outfile: path.join(distRoot, 'portal_app.js'),- bundle: true,- loader: {- '.woff2': 'dataurl',- '.woff': 'dataurl',- '.ttf': 'dataurl',- '.otf': 'dataurl',- },- format: 'iife',- platform: 'browser',- target: ['es2020'],- legalComments: 'none',- sourcemap: false,- minify: false,- logLevel: 'info',- });+ await build(createPortalBuildOptions());await fs.writeFile(manifestPath,diff --git a/internal/cloudcp/portal/frontend/build_config.mjs b/internal/cloudcp/portal/frontend/build_config.mjsnew file mode 100644index 0000000000..a77796f5c2--- /dev/null+++ b/internal/cloudcp/portal/frontend/build_config.mjs@@ -0,0 +1,43 @@+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);++export const frontendRoot = __dirname;+export const repoRoot = path.resolve(frontendRoot, '../../../../');+export const distRoot = path.resolve(frontendRoot, '../dist');+export const manifestPath = path.join(distRoot, 'build_manifest.json');++export function createPortalBuildOptions(overrides = {}) {+ const {+ outfile = path.join(distRoot, 'portal_app.js'),+ plugins = [],+ write = true,+ logLevel = 'info',+ sourcemap = false,+ minify = false,+ } = overrides;++ return {+ absWorkingDir: frontendRoot,+ entryPoints: ['src/index.ts'],+ outfile,+ bundle: true,+ loader: {+ '.woff2': 'dataurl',+ '.woff': 'dataurl',+ '.ttf': 'dataurl',+ '.otf': 'dataurl',+ },+ format: 'iife',+ platform: 'browser',+ target: ['es2020'],+ legalComments: 'none',+ sourcemap,+ minify,+ logLevel,+ write,+ plugins,+ };+}diff --git a/internal/cloudcp/portal/frontend/dev.mjs b/internal/cloudcp/portal/frontend/dev.mjsnew file mode 100644index 0000000000..7dbfcd3b5e--- /dev/null+++ b/internal/cloudcp/portal/frontend/dev.mjs@@ -0,0 +1,654 @@+import http from 'node:http';+import path from 'node:path';+import { context } from 'esbuild';++import { createPortalBuildOptions, frontendRoot } from './build_config.mjs';++const scenarioCookieName = 'pulse_portal_preview_scenario';+const previewHost = process.env.PULSE_PORTAL_PREVIEW_HOST || '127.0.0.1';+const previewPort = Number(process.env.PULSE_PORTAL_PREVIEW_PORT || '8765');+const previewScenarios = ['managed', 'readonly', 'selfhosted', 'empty'];++function iso(value) {+ return new Date(value).toISOString();+}++function deepClone(value) {+ return JSON.parse(JSON.stringify(value));+}++function buildScenarioTemplate(name) {+ const base = {+ authenticated: true,+ email: '[email protected]',+ has_self_hosted_commercial: false,+ public_site_url: 'https://pulserelay.pro',+ support_email: '[email protected]',+ commercial_api_base_url: '/__portal_preview/commercial',+ portal_path: '/portal',+ bootstrap_path: '/api/portal/bootstrap',+ magic_link_request_path: '/api/public/magic-link/request',+ signup_path: '/signup',+ logout_path: '/auth/logout',+ account_api_base_path: '/api/accounts',+ portal_api_base_path: '/api/portal',+ accounts: [],+ };++ if (name === 'readonly') {+ return {+ ...base,+ accounts: [{+ id: 'acct_readonly',+ name: 'Pulse',+ kind: 'msp',+ kind_label: 'MSP',+ role: 'read_only',+ can_manage: false,+ has_billing: true,+ workspaces: [+ {+ id: 'ws_alpha',+ display_name: 'MSP Test Workspace A',+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ created_at: iso('2026-03-20T10:00:00Z'),+ },+ {+ id: 'ws_beta',+ display_name: 'MSP Test Workspace B',+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ created_at: iso('2026-03-21T10:00:00Z'),+ },+ ],+ members: [+ { email: '[email protected]', role: 'owner', user_id: 'u_owner' },+ { email: '[email protected]', role: 'tech', user_id: 'u_ops' },+ { email: '[email protected]', role: 'read_only', user_id: 'u_view' },+ ],+ }],+ };+ }++ if (name === 'selfhosted') {+ return {+ ...base,+ email: '[email protected]',+ has_self_hosted_commercial: true,+ accounts: [],+ };+ }++ if (name === 'empty') {+ return {+ ...base,+ accounts: [{+ id: 'acct_empty',+ name: 'Pulse',+ kind: 'msp',+ kind_label: 'MSP',+ role: 'owner',+ can_manage: true,+ has_billing: true,+ workspaces: [],+ members: [+ { email: '[email protected]', role: 'owner', user_id: 'u_owner' },+ ],+ }],+ };+ }++ return {+ ...base,+ accounts: [{+ id: 'acct_managed',+ name: 'Pulse',+ kind: 'msp',+ kind_label: 'MSP',+ role: 'owner',+ can_manage: true,+ has_billing: true,+ workspaces: [+ {+ id: 'ws_alpha',+ display_name: 'MSP Test Workspace A',+ state: 'suspended',+ healthy: false,+ health_status: 'unhealthy',+ created_at: iso('2026-03-20T10:00:00Z'),+ },+ {+ id: 'ws_beta',+ display_name: 'MSP Test Workspace B',+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ created_at: iso('2026-03-21T10:00:00Z'),+ },+ ],+ members: [+ { email: '[email protected]', role: 'owner', user_id: 'u_owner' },+ { email: '[email protected]', role: 'admin', user_id: 'u_admin' },+ { email: '[email protected]', role: 'tech', user_id: 'u_ops' },+ ],+ }],+ };+}++const scenarioTemplates = Object.fromEntries(+ previewScenarios.map(function(name) {+ return [name, buildScenarioTemplate(name)];+ }),+);++const scenarioState = new Map();+const sseClients = new Set();++function resetScenario(name) {+ const scenario = previewScenarios.includes(name) ? name : 'managed';+ const nextState = deepClone(scenarioTemplates[scenario]);+ scenarioState.set(scenario, nextState);+ return nextState;+}++function getScenarioState(name) {+ const scenario = previewScenarios.includes(name) ? name : 'managed';+ if (!scenarioState.has(scenario)) {+ resetScenario(scenario);+ }+ return scenarioState.get(scenario);+}++function parseCookies(headerValue) {+ const cookies = {};+ for (const part of String(headerValue || '').split(';')) {+ const index = part.indexOf('=');+ if (index === -1) continue;+ const key = part.slice(0, index).trim();+ const value = part.slice(index + 1).trim();+ if (!key) continue;+ cookies[key] = decodeURIComponent(value);+ }+ return cookies;+}++function resolveScenario(url, request) {+ const requestedScenario = String(url.searchParams.get('scenario') || '').trim();+ if (previewScenarios.includes(requestedScenario)) {+ return requestedScenario;+ }+ const cookies = parseCookies(request.headers.cookie || '');+ if (previewScenarios.includes(cookies[scenarioCookieName])) {+ return cookies[scenarioCookieName];+ }+ return 'managed';+}++function readRequestBody(request) {+ return new Promise(function(resolve, reject) {+ let body = '';+ request.setEncoding('utf8');+ request.on('data', function(chunk) {+ body += chunk;+ });+ request.on('end', function() {+ resolve(body);+ });+ request.on('error', reject);+ });+}++async function readJSONBody(request) {+ const body = await readRequestBody(request);+ if (!body.trim()) return {};+ return JSON.parse(body);+}++function sendJSON(response, statusCode, payload, extraHeaders = {}) {+ response.writeHead(statusCode, {+ 'Content-Type': 'application/json; charset=utf-8',+ 'Cache-Control': 'no-store',+ ...extraHeaders,+ });+ response.end(JSON.stringify(payload));+}++function sendText(response, statusCode, payload, extraHeaders = {}) {+ response.writeHead(statusCode, {+ 'Content-Type': 'text/plain; charset=utf-8',+ 'Cache-Control': 'no-store',+ ...extraHeaders,+ });+ response.end(payload);+}++function escapeHTML(value) {+ return String(value || '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}++function previewReturnURL(request, scenario, toastMessage) {+ const origin = 'http://' + previewHost + ':' + String(previewPort);+ const url = new URL('/', origin);+ url.searchParams.set('scenario', scenario);+ if (toastMessage) {+ url.searchParams.set('preview_toast', toastMessage);+ }+ return url.toString();+}++function buildPreviewHTML(assets, bootstrap, previewToast) {+ const bootstrapJSON = JSON.stringify(bootstrap).replace(/</g, '\\u003c');+ const safeToast = previewToast ? JSON.stringify(String(previewToast)) : 'null';+ return '<!DOCTYPE html>' ++ '<html lang="en">' ++ '<head>' ++ '<meta charset="utf-8">' ++ '<meta name="viewport" content="width=device-width, initial-scale=1">' ++ '<title>Pulse Account Preview</title>' ++ '<style>' + assets.css + '</style>' ++ '</head>' ++ '<body>' ++ '<header>' ++ '<span class="brand">Pulse Account</span>' ++ '<div class="user-info" id="portal-user-info"></div>' ++ '</header>' ++ '<script id="pulse-account-bootstrap" type="application/json">' + bootstrapJSON + '</script>' ++ '<main class="main"><div id="portal-app-root"></div></main>' ++ '<div class="toast" id="toast"></div>' ++ '<script>' + assets.js + '</script>' ++ '<script>' ++ '(function(){' ++ 'var source=new EventSource("/__portal_preview/events");' ++ 'source.addEventListener("reload",function(){window.location.reload();});' ++ 'var previewToast=' + safeToast + ';' ++ 'if(previewToast){' ++ 'var toast=document.getElementById("toast");' ++ 'if(toast){toast.textContent=previewToast;toast.className="toast visible";setTimeout(function(){toast.className="toast";},3200);}' ++ '}' ++ '})();' ++ '</script>' ++ '</body>' ++ '</html>';+}++const buildState = {+ assets: {+ css: '',+ js: '',+ },+ errors: [],+ version: 0,+};++function notifyReload() {+ const payload = JSON.stringify({ version: buildState.version });+ for (const response of sseClients) {+ response.write('event: reload\n');+ response.write('data: ' + payload + '\n\n');+ }+}++function buildErrorText(errors) {+ return errors.map(function(error) {+ const location = error.location+ ? error.location.file + ':' + error.location.line + ':' + error.location.column+ : 'unknown';+ return location + '\n' + error.text;+ }).join('\n\n');+}++const previewAssetsPlugin = {+ name: 'pulse-account-preview-assets',+ setup(build) {+ build.onEnd(function(result) {+ if (result.errors.length > 0) {+ buildState.errors = result.errors.slice();+ console.error('[portal-preview] build failed\n' + buildErrorText(result.errors));+ return;+ }+ const jsOutput = result.outputFiles.find(function(file) {+ return file.path.endsWith('portal_app.js');+ });+ const cssOutput = result.outputFiles.find(function(file) {+ return file.path.endsWith('portal_app.css');+ });+ if (!jsOutput || !cssOutput) {+ buildState.errors = [{+ text: 'Preview build did not produce both portal_app.js and portal_app.css.',+ location: null,+ }];+ console.error('[portal-preview] build failed\nPreview build did not produce both portal_app.js and portal_app.css.');+ return;+ }+ buildState.assets.js = jsOutput.text;+ buildState.assets.css = cssOutput.text;+ buildState.errors = [];+ buildState.version += 1;+ console.log('[portal-preview] build ' + String(buildState.version) + ' ready');+ notifyReload();+ });+ },+};++function findAccount(bootstrap, accountID) {+ return (bootstrap.accounts || []).find(function(account) {+ return account.id === accountID;+ }) || null;+}++function routeAccountAPI(request, response, url, bootstrap, scenario) {+ const match = url.pathname.match(/^\/api\/accounts\/([^/]+)\/(tenants|members)(?:\/([^/]+))?$/);+ if (!match) {+ sendText(response, 404, 'Not found');+ return;+ }++ const accountID = decodeURIComponent(match[1]);+ const resource = match[2];+ const resourceID = match[3] ? decodeURIComponent(match[3]) : '';+ const account = findAccount(bootstrap, accountID);+ if (!account) {+ sendJSON(response, 404, { error: 'Account not found.' });+ return;+ }++ if (resource === 'members') {+ if (request.method === 'GET' && !resourceID) {+ sendJSON(response, 200, account.members || []);+ return;+ }+ if (request.method === 'POST' && !resourceID) {+ readJSONBody(request).then(function(body) {+ const email = String(body.email || '').trim().toLowerCase();+ const role = String(body.role || 'read_only').trim() || 'read_only';+ const members = account.members || [];+ if (!email) {+ sendJSON(response, 400, { error: 'Email is required.' });+ return;+ }+ if (members.some(function(member) { return String(member.email || '').toLowerCase() === email; })) {+ sendJSON(response, 409, { error: 'Member already exists.' });+ return;+ }+ members.push({+ email,+ role,+ user_id: 'u_' + Math.random().toString(36).slice(2, 10),+ created_at: iso(new Date()),+ });+ account.members = members;+ sendJSON(response, 200, { ok: true });+ }).catch(function() {+ sendJSON(response, 400, { error: 'Invalid JSON.' });+ });+ return;+ }+ if (request.method === 'PATCH' && resourceID) {+ readJSONBody(request).then(function(body) {+ const nextRole = String(body.role || '').trim();+ const member = (account.members || []).find(function(item) {+ return item.user_id === resourceID;+ });+ if (!member) {+ sendJSON(response, 404, { error: 'Member not found.' });+ return;+ }+ member.role = nextRole || member.role;+ sendJSON(response, 200, { ok: true });+ }).catch(function() {+ sendJSON(response, 400, { error: 'Invalid JSON.' });+ });+ return;+ }+ if (request.method === 'DELETE' && resourceID) {+ account.members = (account.members || []).filter(function(member) {+ return member.user_id !== resourceID;+ });+ sendJSON(response, 200, { ok: true });+ return;+ }+ }++ if (resource === 'tenants') {+ if (request.method === 'POST' && !resourceID) {+ readJSONBody(request).then(function(body) {+ const displayName = String(body.display_name || '').trim();+ if (!displayName) {+ sendJSON(response, 400, { error: 'Workspace name is required.' });+ return;+ }+ account.workspaces = account.workspaces || [];+ account.workspaces.push({+ id: 'ws_' + Math.random().toString(36).slice(2, 10),+ display_name: displayName,+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ created_at: iso(new Date()),+ });+ sendJSON(response, 200, { ok: true });+ }).catch(function() {+ sendJSON(response, 400, { error: 'Invalid JSON.' });+ });+ return;+ }+ if (request.method === 'PATCH' && resourceID) {+ readJSONBody(request).then(function(body) {+ const workspace = (account.workspaces || []).find(function(item) {+ return item.id === resourceID;+ });+ if (!workspace) {+ sendJSON(response, 404, { error: 'Workspace not found.' });+ return;+ }+ if (String(body.state || '').trim() === 'suspended') {+ workspace.state = 'suspended';+ workspace.healthy = false;+ workspace.health_status = 'unhealthy';+ }+ sendJSON(response, 200, { ok: true });+ }).catch(function() {+ sendJSON(response, 400, { error: 'Invalid JSON.' });+ });+ return;+ }+ if (request.method === 'DELETE' && resourceID) {+ account.workspaces = (account.workspaces || []).filter(function(workspace) {+ return workspace.id !== resourceID;+ });+ sendJSON(response, 200, { ok: true });+ return;+ }+ }++ sendText(response, 405, 'Method not allowed');+}++function routeCommercialAPI(request, response, url, scenario) {+ if (request.method !== 'POST') {+ sendText(response, 405, 'Method not allowed');+ return;+ }++ const successRedirect = previewReturnURL(request, scenario, 'Preview mode: external billing or email verification would complete here.');+ const route = url.pathname.replace('/__portal_preview/commercial', '');++ if (+ route === '/v1/manage/request' ||+ route === '/v1/retrieve-license/request' ||+ route === '/v1/gdpr/request-export' ||+ route === '/v1/gdpr/request-delete'+ ) {+ sendJSON(response, 200, { message: 'Preview code sent.' });+ return;+ }++ if (route === '/v1/manage') {+ sendJSON(response, 200, { url: successRedirect });+ return;+ }++ if (route === '/v1/retrieve-license') {+ sendJSON(response, 200, {+ license: {+ token: 'pulse_preview_1234567890',+ tier: 'Cloud Starter',+ issued_at: iso('2026-03-20T10:00:00Z'),+ expires_at: null,+ email: '[email protected]',+ invoice_url: 'https://pulserelay.pro',+ },+ });+ return;+ }++ if (route === '/v1/gdpr/export') {+ sendJSON(response, 200, {+ email: '[email protected]',+ export_generated_at: iso(new Date()),+ records: [+ { type: 'license', id: 'lic_preview' },+ { type: 'billing_profile', id: 'bill_preview' },+ ],+ });+ return;+ }++ if (route === '/v1/gdpr/confirm-delete') {+ sendJSON(response, 200, {+ deleted_count: 2,+ message: 'Preview deletion completed.',+ stripe_reminder: 'Stripe-managed payment data still requires provider-side deletion.',+ });+ return;+ }++ if (route === '/v1/self-refund') {+ sendJSON(response, 200, { ok: true });+ return;+ }++ sendText(response, 404, 'Not found');+}++const server = http.createServer(function(request, response) {+ const url = new URL(request.url || '/', 'http://' + previewHost + ':' + String(previewPort));+ const scenario = resolveScenario(url, request);++ if (url.pathname === '/healthz') {+ sendText(response, 200, 'ok');+ return;+ }++ if (url.pathname === '/__portal_preview/events') {+ response.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-store',+ Connection: 'keep-alive',+ });+ response.write('event: ready\n');+ response.write('data: {"ok":true}\n\n');+ sseClients.add(response);+ request.on('close', function() {+ sseClients.delete(response);+ });+ return;+ }++ if (url.pathname === '/api/portal/bootstrap') {+ sendJSON(response, 200, getScenarioState(scenario));+ return;+ }++ if (url.pathname === '/api/public/magic-link/request') {+ sendJSON(response, 200, { message: 'Preview mode: magic link skipped.' });+ return;+ }++ if (url.pathname === '/auth/logout') {+ sendJSON(response, 200, { ok: true });+ return;+ }++ if (url.pathname === '/api/portal/billing') {+ sendJSON(response, 200, {+ url: previewReturnURL(request, scenario, 'Preview mode: hosted billing portal would open here.'),+ });+ return;+ }++ if (url.pathname.startsWith('/api/accounts/')) {+ routeAccountAPI(request, response, url, getScenarioState(scenario), scenario);+ return;+ }++ if (url.pathname.startsWith('/__portal_preview/commercial/')) {+ routeCommercialAPI(request, response, url, scenario);+ return;+ }++ if (url.pathname === '/' || url.pathname === '/portal') {+ if (url.searchParams.get('reset') === '1') {+ resetScenario(scenario);+ }+ if (buildState.errors.length > 0 && !buildState.assets.js) {+ response.writeHead(500, {+ 'Content-Type': 'text/html; charset=utf-8',+ 'Cache-Control': 'no-store',+ 'Set-Cookie': scenarioCookieName + '=' + encodeURIComponent(scenario) + '; Path=/; SameSite=Lax',+ });+ response.end('<!DOCTYPE html><html><body><pre>' + escapeHTML(buildErrorText(buildState.errors)) + '</pre></body></html>');+ return;+ }+ response.writeHead(200, {+ 'Content-Type': 'text/html; charset=utf-8',+ 'Cache-Control': 'no-store',+ 'Set-Cookie': scenarioCookieName + '=' + encodeURIComponent(scenario) + '; Path=/; SameSite=Lax',+ });+ response.end(buildPreviewHTML(buildState.assets, getScenarioState(scenario), url.searchParams.get('preview_toast') || ''));+ return;+ }++ sendText(response, 404, 'Not found');+});++const buildContext = await context(createPortalBuildOptions({+ outfile: path.join(frontendRoot, '.portal-preview', 'portal_app.js'),+ write: false,+ logLevel: 'silent',+ plugins: [previewAssetsPlugin],+}));++await buildContext.rebuild();+await buildContext.watch();++server.listen(previewPort, previewHost, function() {+ console.log('[portal-preview] http://' + previewHost + ':' + String(previewPort));+ console.log('[portal-preview] managed -> http://' + previewHost + ':' + String(previewPort) + '/?scenario=managed');+ console.log('[portal-preview] readonly -> http://' + previewHost + ':' + String(previewPort) + '/?scenario=readonly');+ console.log('[portal-preview] selfhosted -> http://' + previewHost + ':' + String(previewPort) + '/?scenario=selfhosted');+ console.log('[portal-preview] empty -> http://' + previewHost + ':' + String(previewPort) + '/?scenario=empty');+});++async function shutdown(signal) {+ console.log('[portal-preview] shutting down (' + signal + ')');+ for (const response of sseClients) {+ response.end();+ }+ server.close(function() {});+ await buildContext.dispose();+ process.exit(0);+}++process.on('SIGINT', function() {+ void shutdown('SIGINT');+});+process.on('SIGTERM', function() {+ void shutdown('SIGTERM');+});diff --git a/internal/cloudcp/portal/frontend/package.json b/internal/cloudcp/portal/frontend/package.jsonindex beba3c776f..87969a9261 100644--- a/internal/cloudcp/portal/frontend/package.json+++ b/internal/cloudcp/portal/frontend/package.json@@ -4,6 +4,7 @@"type": "module","scripts": {"build": "node build.mjs",+ "dev": "node dev.mjs","test": "vitest run","typecheck": "tsc --noEmit -p tsconfig.json"},diff --git a/internal/cloudcp/portal/frontend/src/runtime.test.ts b/internal/cloudcp/portal/frontend/src/runtime.test.tsindex c96c342121..41b46874a2 100644--- a/internal/cloudcp/portal/frontend/src/runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/runtime.test.ts@@ -25,6 +25,21 @@ describe('portal runtime', function() {expect(defaults.bootstrap_path).toBe('/api/account/bootstrap');});+ it('keeps local preview API roots intact for harness-driven development', function() {+ var defaults = createBootstrapDefaults({+ has_self_hosted_commercial: false,+ commercial_api_base_url: '/__portal_preview/commercial',+ bootstrap_path: '/api/portal/bootstrap',+ account_api_base_path: '/api/accounts',+ portal_api_base_path: '/api/portal',+ });++ expect(defaults.commercial_api_base_url).toBe('/__portal_preview/commercial');+ expect(defaults.bootstrap_path).toBe('/api/portal/bootstrap');+ expect(defaults.account_api_base_path).toBe('/api/accounts');+ expect(defaults.portal_api_base_path).toBe('/api/portal');+ });+it('creates a store from runtime bootstrap input', function() {var runtime = createPortalRuntime({authenticated: true,