Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

test(first-session): prove deterministic setup handoff

rcourtmand8f106de1d33
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f957b3131f..6d923d3048 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -548,6 +548,11 @@ That same shared `internal/api/` boundary also assumes manual auth env writes
and first-session status reads resolve the `.env` path through the shared
auth-path helper, so lifecycle-adjacent setup and password flows do not each
reconstruct their own `/etc/pulse/.env` fallback logic.
+The same proof boundary also owns deterministic first-run re-entry for the
+managed local backend: integration helpers may use the seeded runtime-state
+primary API token to call the dev-only `/api/security/dev/reset-first-run`
+route, but they may not recreate auth teardown by deleting files or rebuilding
+bootstrap state outside the canonical backend path.
That same shared `internal/api/` boundary also assumes generated developer
warnings do not mis-teach the local runtime split: the embedded frontend notice
under `internal/api/DO_NOT_EDIT_FRONTEND_HERE.md` may point operators to the
@@ -984,6 +989,11 @@ the active onboarding contract. The primary install guidance text in the wizard
must switch with that mode as well: tokenless onboarding may not keep
advertising automatic token rotation after each copy once the active transport
is explicitly tokenless.
+The same first-session contract now also owns the landing handoff after secure
+setup: RC-proof and helpers must treat direct navigation into
+`/settings/infrastructure/install` as the canonical completion path, rather
+than assuming the legacy dashboard-only landing still defines successful
+wizard completion.
That same `SetupCompletionPanel` boundary must also stay on the direct
`setup-completion-install-surface` proof path, rather than relying only on shared
helper coverage or downstream install tests to catch lifecycle drift in the
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 9a39ac6cd8..0d8dd17650 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -751,6 +751,12 @@ through the supported `pulse bootstrap-token` command, but `.bootstrap_token`
may not remain a raw plaintext secret file on disk. Canonical runtime
persistence must encrypt that token at rest and rewrite any legacy plaintext
bootstrap-token file immediately into the encrypted canonical format on load.
+That same first-session contract also owns the dev/test reset response used by
+managed-backend proof: `/api/security/dev/reset-first-run` may exist only for
+development verification, must require authenticated `settings:write`, must
+clear persisted auth state through the shared auth-env and token-persistence
+helpers, and must return the regenerated `bootstrapToken` together with the
+canonical `bootstrapTokenPath` needed to re-enter first-run deterministically.
That same setup-token-only contract must also keep missing-token failures
specific: `/api/auto-register` may not answer a missing `authToken` request
with a generic authentication error after the route has been narrowed to the
@@ -1445,6 +1451,11 @@ both sides instead of relying only on broad settings-surface coverage on the
security side: token settings changes must continue to carry the direct
`api-token-management-surface` API-contract proof together with the
security-side surface proof.
+That same boundary must also keep token scope presets lazily derived from the
+canonical scope constants: `apiTokenManagerModel.ts` may expose
+`getAPITokenScopePresets()`, but it must not publish an eagerly evaluated
+top-level preset array that can reintroduce settings-chunk initialization-order
+failures in production bundles.
That same boundary now also includes
`frontend-modern/src/utils/apiTokenPresentation.ts`, so token load/create/
revoke errors keep one governed customer-facing message source instead of
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 740d682d85..c5882861ce 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -240,6 +240,10 @@ plaintext secret file on disk. Canonical runtime persistence must keep the
token encrypted at rest, and any legacy plaintext bootstrap-token file must be
treated only as migration input that is rewritten immediately into the
encrypted canonical format on load.
+Managed first-session proof may reset that boundary only through the dev-only
+`/api/security/dev/reset-first-run` route under authenticated
+`settings:write`; harnesses may not scrape `.env`, delete persisted token
+state, or recreate bootstrap material through lane-local teardown logic.
That same trust rule also applies to persisted relay client secrets:
`internal/config/persistence_relay.go` may only accept plaintext `relay.enc`
files as migration input. Once relay config can be read, canonical runtime
@@ -277,6 +281,11 @@ stale `pulse-hot-dev` service name or any lane-local restart folklore.
continue to carry the direct `security-settings-surfaces` proof path together
with the API-contract token-management proof instead of borrowing coverage only
from broader settings-shell or API ownership.
+That same token-settings surface must also derive presets lazily from the
+canonical scope constants. `apiTokenManagerModel.ts` may expose a
+`getAPITokenScopePresets()` factory, but it must not freeze preset scope data
+at module-load time in a way that can break security settings initialization in
+production chunks.
That same governed AI trust boundary also covers unified-resource context
posture derivation: `internal/ai/resource_context_policy_model.go` is now the
canonical owner for the policy-posture summary, local-only count, and
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d40792aa8d..c2c1ab6b98 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -458,6 +458,10 @@ That same shared boundary also assumes manual auth env writes and auth-status
reads resolve `.env` through the shared auth-path helper, so storage-adjacent
recovery and setup flows do not keep neighboring `/etc/pulse/.env` fallback
logic alive after the runtime data-dir authority has been centralized.
+The same boundary also owns first-session reset cleanup during managed-backend
+proof: the dev-only `/api/security/dev/reset-first-run` route must clear auth
+env and persisted API-token state through the shared helpers, and adjacent test
+or recovery tooling may not delete those files directly.
That same shared `internal/api/` dependency also assumes generated developer
warnings keep the local browser/runtime split accurate: the embedded frontend
notice under `internal/api/DO_NOT_EDIT_FRONTEND_HERE.md` may describe `:7655`
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 1358468dc0..e9a6ea6c4a 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -910,9 +910,13 @@ describe('Settings architecture guardrails', () => {
expect(apiTokenManagerStateSource).toContain('const [tokens, setTokens] = createSignal<APITokenRecord[]>([])');
expect(apiTokenManagerStateSource).toContain('const loadTokens = async () =>');
expect(apiTokenManagerStateSource).toContain('SecurityAPI.listTokens()');
+ expect(apiTokenManagerStateSource).toContain('const scopePresets = getAPITokenScopePresets();');
+ expect(apiTokenManagerStateSource).not.toContain('const scopePresets = API_TOKEN_SCOPE_PRESETS;');
expect(apiTokenManagerModelSource).toContain('export const hasAgentScopeResource =');
expect(apiTokenManagerModelSource).toContain('export const buildDockerTokenUsage =');
expect(apiTokenManagerModelSource).toContain('export const buildAgentTokenUsage =');
+ expect(apiTokenManagerModelSource).toContain('export const getAPITokenScopePresets = (): APITokenPreset[] => [');
+ expect(apiTokenManagerModelSource).not.toContain('export const API_TOKEN_SCOPE_PRESETS = [');
});
it('keeps the node setup modal shell behind extracted state and model owners', () => {
diff --git a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
index 154be1a27a..bcc633c983 100644
--- a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
+++ b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
@@ -38,7 +38,7 @@ type ScopeOption = (typeof API_SCOPE_OPTIONS)[number];
const API_TOKEN_SCOPE_GROUP_ORDER: ScopeGroup[] = ['Monitoring', 'Agents', 'Settings'];
-export const API_TOKEN_SCOPE_PRESETS: APITokenPreset[] = [
+export const getAPITokenScopePresets = (): APITokenPreset[] => [
{
label: 'Kiosk / Dashboard',
scopes: [MONITORING_READ_SCOPE],
diff --git a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
index afd34060a8..291a2bd272 100644
--- a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
+++ b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
@@ -23,13 +23,13 @@ import { logger } from '@/utils/logger';
import { getPulseBaseUrl } from '@/utils/url';
import {
API_TOKEN_SCOPES_DOC_URL,
- API_TOKEN_SCOPE_PRESETS,
API_TOKEN_WILDCARD_SCOPE,
agentActionIdForResource,
buildAgentTokenUsage,
buildDockerTokenUsage,
countWildcardTokens,
dockerActionIdForResource,
+ getAPITokenScopePresets,
getAPITokenDialogName,
getAPITokenHint,
groupAPITokenScopes,
@@ -77,6 +77,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const scopedTokenCount = createMemo(() => totalTokens() - wildcardCount());
const hasWildcardTokens = createMemo(() => wildcardCount() > 0);
const scopeGroups = createMemo(() => groupAPITokenScopes());
+ const scopePresets = getAPITokenScopePresets();
const isFullAccessSelected = () =>
selectedScopes().length === 0 || selectedScopes().includes(API_TOKEN_WILDCARD_SCOPE);
@@ -340,7 +341,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
reopenTokenDialog,
scopedTokenCount,
scopeGroups,
- scopePresets: API_TOKEN_SCOPE_PRESETS,
+ scopePresets,
selectedScopes,
setCreateSectionRef,
setNameInput,
diff --git a/internal/api/auth_env_path.go b/internal/api/auth_env_path.go
index 425a7bdbe1..47f3acb620 100644
--- a/internal/api/auth_env_path.go
+++ b/internal/api/auth_env_path.go
@@ -40,3 +40,14 @@ func writeAuthEnvFile(configPath string, dataPath string, content []byte) (strin
}
return "", lastErr
}
+
+func removeAuthEnvFiles(configPath string, dataPath string) error {
+ paths := resolveAuthEnvWritePaths(configPath, dataPath)
+ var lastErr error
+ for _, envPath := range paths {
+ if err := os.Remove(envPath); err != nil && !os.IsNotExist(err) {
+ lastErr = err
+ }
+ }
+ return lastErr
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 0bd0202dca..e18fcdaa24 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2499,6 +2499,61 @@ func TestContract_QuickSecuritySetupBootstrapRetrievalGuidance(t *testing.T) {
}
}
+func TestContract_ResetFirstRunSecurityResponseJSONSnapshot(t *testing.T) {
+ t.Setenv("PULSE_DEV", "true")
+ t.Setenv("NODE_ENV", "")
+
+ record := newTokenRecord(t, "contract-reset-first-run-token-123.12345678", []string{config.ScopeSettingsWrite}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ cfg.AuthUser = "admin"
+ cfg.AuthPass = "hashed-password"
+
+ envPath, err := writeAuthEnvFile(cfg.ConfigPath, cfg.DataPath, []byte("PULSE_AUTH_USER='admin'\n"))
+ if err != nil {
+ t.Fatalf("writeAuthEnvFile: %v", err)
+ }
+
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+ req := httptest.NewRequest(http.MethodPost, "/api/security/dev/reset-first-run", nil)
+ req.Header.Set("X-API-Token", "contract-reset-first-run-token-123.12345678")
+ rec := httptest.NewRecorder()
+
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("reset-first-run status = %d, want 200 (%s)", rec.Code, rec.Body.String())
+ }
+
+ var payload firstRunResetResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode reset-first-run response: %v", err)
+ }
+ if strings.TrimSpace(payload.BootstrapToken) == "" {
+ t.Fatal("reset-first-run response missing bootstrapToken")
+ }
+ if got, want := payload.BootstrapTokenPath, filepath.Join(cfg.DataPath, bootstrapTokenFilename); got != want {
+ t.Fatalf("reset-first-run bootstrapTokenPath = %q, want %q", got, want)
+ }
+ if _, err := os.Stat(envPath); !os.IsNotExist(err) {
+ t.Fatalf("reset-first-run should remove auth env file, stat err = %v", err)
+ }
+
+ got, err := json.Marshal(firstRunResetResponse{
+ BootstrapToken: "bootstrap-token-placeholder",
+ BootstrapTokenPath: "bootstrap-token-path-placeholder",
+ })
+ if err != nil {
+ t.Fatalf("marshal reset-first-run response snapshot: %v", err)
+ }
+
+ const want = `{
+ "bootstrapToken":"bootstrap-token-placeholder",
+ "bootstrapTokenPath":"bootstrap-token-path-placeholder"
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_SetupScriptURLResponseJSONSnapshot(t *testing.T) {
payload := map[string]any{
"type": "pve",
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index a1282abba1..92bbe3ce8a 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -272,6 +272,7 @@ var bareRouteAllowlist = []string{
"/api/oidc/",
"/api/security/apply-restart",
"/api/security/change-password",
+ "/api/security/dev/reset-first-run",
"/api/security/quick-setup",
"/api/security/recovery",
"/api/security/regenerate-token",
@@ -450,6 +451,7 @@ var allRouteAllowlist = []string{
"/api/admin/reports/generate-multi",
"/api/admin/webhooks/audit",
"/api/security/change-password",
+ "/api/security/dev/reset-first-run",
"/api/logout",
"/api/login",
"/api/security/reset-lockout",
diff --git a/internal/api/router_routes_auth_security.go b/internal/api/router_routes_auth_security.go
index 8cba45db50..171bab150b 100644
--- a/internal/api/router_routes_auth_security.go
+++ b/internal/api/router_routes_auth_security.go
@@ -366,6 +366,7 @@ func (r *Router) registerAuthSecurityInstallRoutes() {
// Quick security setup route - using fixed version
r.mux.HandleFunc("/api/security/quick-setup", handleQuickSecuritySetupFixed(r))
+ r.mux.HandleFunc("/api/security/dev/reset-first-run", r.handleResetFirstRunSecurity)
// API token regeneration endpoint
r.mux.HandleFunc("/api/security/regenerate-token", r.HandleRegenerateAPIToken)
diff --git a/internal/api/security_first_run_reset.go b/internal/api/security_first_run_reset.go
new file mode 100644
index 0000000000..eeb45e0ff8
--- /dev/null
+++ b/internal/api/security_first_run_reset.go
@@ -0,0 +1,80 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "os"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
+ "github.com/rs/zerolog/log"
+)
+
+type firstRunResetResponse struct {
+ BootstrapToken string `json:"bootstrapToken"`
+ BootstrapTokenPath string `json:"bootstrapTokenPath,omitempty"`
+}
+
+func devModeEnabled() bool {
+ return os.Getenv("PULSE_DEV") == "true" || strings.EqualFold(os.Getenv("NODE_ENV"), "development")
+}
+
+func (r *Router) handleResetFirstRunSecurity(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if !devModeEnabled() {
+ http.Error(w, "Development mode required", http.StatusForbidden)
+ return
+ }
+ if !CheckAuth(r.config, w, req) {
+ return
+ }
+ if !ensureSettingsWriteScope(r.config, w, req) {
+ return
+ }
+
+ config.Mu.Lock()
+ previousAuthUser := strings.TrimSpace(r.config.AuthUser)
+ r.config.AuthUser = ""
+ r.config.AuthPass = ""
+ r.config.APIToken = ""
+ r.config.APITokens = nil
+ config.Mu.Unlock()
+
+ if previousAuthUser != "" {
+ InvalidateUserSessions(previousAuthUser)
+ }
+ r.clearSession(w, req)
+ r.clearBootstrapToken()
+
+ if err := removeAuthEnvFiles(r.config.ConfigPath, r.config.DataPath); err != nil {
+ log.Warn().Err(err).Msg("Failed to remove auth env files during first-run reset")
+ http.Error(w, "Failed to remove persisted auth configuration", http.StatusInternalServerError)
+ return
+ }
+ if r.persistence != nil {
+ if err := r.persistence.SaveAPITokens([]config.APITokenRecord{}); err != nil {
+ log.Warn().Err(err).Msg("Failed to clear persisted API tokens during first-run reset")
+ http.Error(w, "Failed to clear persisted API tokens", http.StatusInternalServerError)
+ return
+ }
+ }
+
+ token, _, path, err := loadOrCreateBootstrapToken(r.config.DataPath)
+ if err != nil {
+ log.Error().Err(err).Msg("Failed to recreate bootstrap token during first-run reset")
+ http.Error(w, "Failed to recreate bootstrap token", http.StatusInternalServerError)
+ return
+ }
+ r.bootstrapTokenHash = internalauth.HashAPIToken(token)
+ r.bootstrapTokenPath = path
+
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(firstRunResetResponse{
+ BootstrapToken: token,
+ BootstrapTokenPath: path,
+ })
+}
diff --git a/internal/api/security_first_run_reset_test.go b/internal/api/security_first_run_reset_test.go
new file mode 100644
index 0000000000..a6c5e64134
--- /dev/null
+++ b/internal/api/security_first_run_reset_test.go
@@ -0,0 +1,91 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func TestResetFirstRunSecurityRequiresDevMode(t *testing.T) {
+ t.Setenv("PULSE_DEV", "")
+ t.Setenv("NODE_ENV", "production")
+
+ record := newTokenRecord(t, "reset-first-run-token-123.12345678", []string{config.ScopeSettingsWrite}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/dev/reset-first-run", nil)
+ req.Header.Set("X-API-Token", "reset-first-run-token-123.12345678")
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("expected 403 outside dev mode, got %d", rec.Code)
+ }
+}
+
+func TestResetFirstRunSecurityClearsAuthAndReturnsBootstrapToken(t *testing.T) {
+ t.Setenv("PULSE_DEV", "true")
+ t.Setenv("NODE_ENV", "")
+
+ record := newTokenRecord(t, "reset-first-run-token-234.12345678", []string{config.ScopeSettingsWrite}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ cfg.AuthUser = "admin"
+ cfg.AuthPass = "hashed-password"
+
+ envPath, err := writeAuthEnvFile(cfg.ConfigPath, cfg.DataPath, []byte("PULSE_AUTH_USER='admin'\n"))
+ if err != nil {
+ t.Fatalf("writeAuthEnvFile: %v", err)
+ }
+
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+ req := httptest.NewRequest(http.MethodPost, "/api/security/dev/reset-first-run", nil)
+ req.Header.Set("X-API-Token", "reset-first-run-token-234.12345678")
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d (%s)", rec.Code, rec.Body.String())
+ }
+
+ var payload firstRunResetResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if strings.TrimSpace(payload.BootstrapToken) == "" {
+ t.Fatal("expected bootstrapToken in response")
+ }
+ if strings.TrimSpace(payload.BootstrapTokenPath) == "" {
+ t.Fatal("expected bootstrapTokenPath in response")
+ }
+ if router.bootstrapTokenHash == "" || !router.bootstrapTokenValid(payload.BootstrapToken) {
+ t.Fatal("expected router to accept returned bootstrap token")
+ }
+ if cfg.AuthUser != "" || cfg.AuthPass != "" {
+ t.Fatalf("expected auth credentials cleared, got user=%q pass=%q", cfg.AuthUser, cfg.AuthPass)
+ }
+ if cfg.HasAPITokens() || cfg.APIToken != "" {
+ t.Fatalf("expected API tokens cleared, got %d tokens", len(cfg.APITokens))
+ }
+ if _, err := os.Stat(envPath); !os.IsNotExist(err) {
+ t.Fatalf("expected auth env file removed, stat err=%v", err)
+ }
+
+ persistence := config.NewConfigPersistence(cfg.DataPath)
+ tokens, err := persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("LoadAPITokens: %v", err)
+ }
+ if len(tokens) != 0 {
+ t.Fatalf("expected persisted API tokens cleared, got %d", len(tokens))
+ }
+
+ tokenPath := filepath.Join(cfg.DataPath, bootstrapTokenFilename)
+ if payload.BootstrapTokenPath != tokenPath {
+ t.Fatalf("bootstrap token path = %q, want %q", payload.BootstrapTokenPath, tokenPath)
+ }
+}
diff --git a/tests/integration/scripts/managed-local-backend.mjs b/tests/integration/scripts/managed-local-backend.mjs
index a4a6a6360c..6beae19307 100644
--- a/tests/integration/scripts/managed-local-backend.mjs
+++ b/tests/integration/scripts/managed-local-backend.mjs
@@ -90,6 +90,7 @@ export function buildManagedLocalBackendEnv(state, env = process.env) {
PULSE_DEV: 'true',
PULSE_E2E_BILLING_STATE_PATH: state.billingStatePath,
PULSE_E2E_BOOTSTRAP_TOKEN: trim(env.PULSE_E2E_BOOTSTRAP_TOKEN) || DEFAULT_E2E_BOOTSTRAP_TOKEN,
+ PULSE_E2E_PRIMARY_API_TOKEN: trim(env.PULSE_E2E_PRIMARY_API_TOKEN) || DEFAULT_E2E_PRIMARY_API_TOKEN,
ALLOWED_ORIGINS: trim(env.ALLOWED_ORIGINS) || allowedOrigins.join(','),
};
@@ -480,6 +481,7 @@ export async function startManagedLocalBackend({
dataDir: state.dataDir,
logPath: state.logPath,
billingStatePath: state.billingStatePath,
+ primaryAPIToken: backendEnv.PULSE_E2E_PRIMARY_API_TOKEN,
};
await writeRuntimeState(runtimeState, env);
logger.log(`[integration] Started managed local backend at ${state.baseURL} (pid ${child.pid})`);
diff --git a/tests/integration/scripts/managed-local-backend.test.mjs b/tests/integration/scripts/managed-local-backend.test.mjs
index b490506e3a..7d874c6840 100644
--- a/tests/integration/scripts/managed-local-backend.test.mjs
+++ b/tests/integration/scripts/managed-local-backend.test.mjs
@@ -50,6 +50,7 @@ test('buildManagedLocalBackendEnv seeds auth, bootstrap token, and billing path'
assert.equal(env.PULSE_DATA_DIR, state.dataDir);
assert.equal(env.PULSE_E2E_BILLING_STATE_PATH, state.billingStatePath);
assert.equal(env.PULSE_E2E_BOOTSTRAP_TOKEN.length > 0, true);
+ assert.equal(env.PULSE_E2E_PRIMARY_API_TOKEN.length > 0, true);
assert.equal(env.PULSE_METRICS_PORT, '0');
assert.equal('ALLOW_ADMIN_BYPASS' in env, false);
assert.equal(env.PULSE_MULTI_TENANT_ENABLED, 'true');
diff --git a/tests/integration/tests/11-first-session.spec.ts b/tests/integration/tests/11-first-session.spec.ts
index dbf4f162f1..e59155fe9b 100644
--- a/tests/integration/tests/11-first-session.spec.ts
+++ b/tests/integration/tests/11-first-session.spec.ts
@@ -1,19 +1,17 @@
import { test, expect } from '@playwright/test';
-import { ensureAuthenticated, navigateToSettings, apiRequest } from './helpers';
+import { ensureAuthenticated, ensureFirstRunExperience, navigateToSettings, apiRequest } from './helpers';
/**
* Dedicated first-session E2E test covering the full journey:
- * wizard → dashboard → settings discovery → gated panel guards
+ * wizard → infrastructure operations handoff → settings discovery → gated panel guards
*
* This satisfies L8 score-8 criteria: "Dedicated first-session E2E test
- * (wizard → dashboard → settings discovery)."
+ * (wizard → settings discovery)" with the current canonical first-run handoff
+ * landing in Infrastructure Operations install rather than the legacy dashboard.
*
- * NOTE: The wizard step is handled by `ensureAuthenticated()` which calls
- * `maybeCompleteSetupWizard()` only when security is not yet configured.
- * In full-suite runs (file 11), prior tests will have already bootstrapped,
- * so the wizard step is a no-op. This is correct — the test validates the
- * post-wizard first-session UX regardless of whether this run performed
- * the actual wizard flow.
+ * The opening test in this file forces the backend into deterministic
+ * first-run state through the dev/test reset route, then completes the real
+ * setup wizard before the rest of the suite continues through normal auth.
*/
type EntitlementPayload = {
@@ -28,13 +26,16 @@ type EntitlementPayload = {
const SETTINGS_SIDEBAR = '[aria-label="Settings navigation"]';
test.describe.serial('First-session experience', () => {
- test('wizard completes and lands on dashboard', async ({ page }, testInfo) => {
+ test('wizard completes and lands on infrastructure operations', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');
- await ensureAuthenticated(page);
+ await ensureFirstRunExperience(page);
- // After setup wizard + login the app must land on the infrastructure dashboard.
- await expect(page).toHaveURL(/\/(infrastructure|proxmox\/overview|dashboard|nodes)/);
+ // First-run security now hands off directly into the Infrastructure Operations install flow.
+ await expect(page).toHaveURL(/\/settings\/infrastructure\/install/);
+ await expect(
+ page.getByRole('heading', { name: 'Infrastructure Operations', exact: true }).first(),
+ ).toBeVisible();
await expect(page.locator('#root')).toBeVisible();
// The main content area should be rendered (not stuck on a spinner/blank).
diff --git a/tests/integration/tests/helpers.ts b/tests/integration/tests/helpers.ts
index 1e54facc66..43e8924f37 100644
--- a/tests/integration/tests/helpers.ts
+++ b/tests/integration/tests/helpers.ts
@@ -19,18 +19,32 @@ const runtimeStatePath = (() => {
: path.resolve(__dirname, '..', '..', '..', configuredPath);
})();
-const runtimeBaseURL = (): string | null => {
+type RuntimeState = {
+ baseURL?: string;
+ primaryAPIToken?: string;
+};
+
+const readRuntimeState = (): RuntimeState | null => {
try {
const raw = fs.readFileSync(runtimeStatePath, 'utf8');
- const parsed = JSON.parse(raw) as { baseURL?: string };
- return typeof parsed.baseURL === 'string' && parsed.baseURL.trim() !== ''
- ? parsed.baseURL.trim()
- : null;
+ return JSON.parse(raw) as RuntimeState;
} catch {
return null;
}
};
+const runtimeBaseURL = (): string | null => {
+ const parsed = readRuntimeState();
+ return typeof parsed?.baseURL === 'string' && parsed.baseURL.trim() !== ''
+ ? parsed.baseURL.trim()
+ : null;
+};
+
+const runtimePrimaryAPIToken = (): string => {
+ const parsed = readRuntimeState();
+ return typeof parsed?.primaryAPIToken === 'string' ? parsed.primaryAPIToken.trim() : '';
+};
+
/**
* Default admin credentials for testing
*/
@@ -44,10 +58,26 @@ const DEFAULT_E2E_BOOTSTRAP_TOKEN = '0123456789abcdef0123456789abcdef0123456789a
export const E2E_CREDENTIALS = {
bootstrapToken: process.env.PULSE_E2E_BOOTSTRAP_TOKEN || DEFAULT_E2E_BOOTSTRAP_TOKEN,
+ primaryApiToken: process.env.PULSE_E2E_PRIMARY_API_TOKEN || runtimePrimaryAPIToken(),
username: process.env.PULSE_E2E_USERNAME || ADMIN_CREDENTIALS.username,
password: process.env.PULSE_E2E_PASSWORD || ADMIN_CREDENTIALS.password,
};
+async function waitForAppShell(page: Page, timeoutMs = 20_000) {
+ await page.waitForLoadState('domcontentloaded');
+
+ // The raw HTML shell contains a noscript fallback. Wait for the SPA to
+ // mount before making route-specific assertions against wizard/login UI.
+ await page.waitForFunction(
+ () => {
+ const root = document.getElementById('root');
+ return root !== null && root.children.length > 0;
+ },
+ undefined,
+ { timeout: timeoutMs },
+ );
+}
+
export async function waitForPulseReady(page: Page, timeoutMs = 120_000) {
const startedAt = Date.now();
let lastError: unknown = null;
@@ -70,27 +100,17 @@ type SecurityStatus = {
hasAuthentication?: boolean;
};
-export async function getSecurityStatus(page: Page): Promise<SecurityStatus> {
- const res = await page.request.get('/api/security/status');
- if (!res.ok()) {
- throw new Error(`Failed to fetch security status: ${res.status()}`);
- }
- return (await res.json()) as SecurityStatus;
-}
-
-export async function maybeCompleteSetupWizard(page: Page) {
- const security = await getSecurityStatus(page);
- if (security.hasAuthentication !== false) {
- return;
- }
+type ResetFirstRunResponse = {
+ bootstrapToken?: string;
+};
- if (!E2E_CREDENTIALS.bootstrapToken) {
- throw new Error(
- 'Pulse requires first-run setup but PULSE_E2E_BOOTSTRAP_TOKEN is not set (or is empty)',
- );
+async function completeSetupWizard(page: Page, bootstrapToken: string) {
+ if (!bootstrapToken) {
+ throw new Error('Pulse requires first-run setup but no bootstrap token is available');
}
await page.goto('/');
+ await waitForAppShell(page);
const wizard = page.getByRole('main', { name: 'Pulse Setup Wizard' });
await expect(wizard).toBeVisible();
@@ -100,7 +120,7 @@ export async function maybeCompleteSetupWizard(page: Page) {
const continueButton = wizard.getByRole('button', { name: /continue to setup|continue/i });
const finishButton = wizard.getByRole('button', { name: /go to dashboard|skip for now/i });
- await page.getByPlaceholder('Paste your bootstrap token').fill(E2E_CREDENTIALS.bootstrapToken);
+ await page.getByPlaceholder('Paste your bootstrap token').fill(bootstrapToken);
// Welcome step auto-submits pasted tokens; only click Continue if no transition happened.
let onSecurityStep = false;
@@ -134,7 +154,6 @@ export async function maybeCompleteSetupWizard(page: Page) {
clickedCustomPassword = true;
break;
} catch (error) {
- // The step can transition to complete while waiting; handle that as success.
if (await securityConfigured.isVisible({ timeout: 250 }).catch(() => false)) {
onCompleteStep = true;
break;
@@ -152,7 +171,17 @@ export async function maybeCompleteSetupWizard(page: Page) {
await wizard.locator('input[type="password"]').nth(1).fill(E2E_CREDENTIALS.password);
await wizard.getByRole('button', { name: /create account/i }).click();
- await expect(securityConfigured).toBeVisible();
+ await expect
+ .poll(async () => {
+ if (await securityConfigured.isVisible({ timeout: 250 }).catch(() => false)) {
+ return 'complete';
+ }
+ if (/\/settings\/infrastructure\/install/.test(page.url())) {
+ return 'handoff';
+ }
+ return 'pending';
+ })
+ .not.toBe('pending');
onCompleteStep = true;
}
} else {
@@ -162,13 +191,88 @@ export async function maybeCompleteSetupWizard(page: Page) {
}
if (onCompleteStep) {
- await finishButton.scrollIntoViewIfNeeded();
- await finishButton.click({ timeout: 10_000 });
+ const finishVisible = await finishButton.isVisible({ timeout: 500 }).catch(() => false);
+ if (finishVisible) {
+ await finishButton.scrollIntoViewIfNeeded();
+ await finishButton.click({ timeout: 10_000 });
+ }
}
await page.waitForLoadState('domcontentloaded');
}
+export async function getSecurityStatus(page: Page): Promise<SecurityStatus> {
+ const res = await page.request.get('/api/security/status');
+ if (!res.ok()) {
+ throw new Error(`Failed to fetch security status: ${res.status()}`);
+ }
+ return (await res.json()) as SecurityStatus;
+}
+
+export async function maybeCompleteSetupWizard(page: Page) {
+ const security = await getSecurityStatus(page);
+ if (security.hasAuthentication !== false) {
+ return;
+ }
+
+ await completeSetupWizard(page, E2E_CREDENTIALS.bootstrapToken);
+}
+
+export async function ensureFirstRunExperience(page: Page) {
+ await page.addInitScript(() => {
+ localStorage.setItem('pulse_whats_new_v2_shown', 'true');
+ });
+ await waitForPulseReady(page);
+
+ let bootstrapToken = E2E_CREDENTIALS.bootstrapToken;
+ const security = await getSecurityStatus(page);
+ if (security.hasAuthentication !== false) {
+ let resetRes = await apiRequest(page, '/api/security/dev/reset-first-run', {
+ method: 'POST',
+ headers: E2E_CREDENTIALS.primaryApiToken
+ ? { 'X-API-Token': E2E_CREDENTIALS.primaryApiToken }
+ : undefined,
+ });
+ if (resetRes.status() === 401 && !E2E_CREDENTIALS.primaryApiToken) {
+ await login(page);
+ resetRes = await apiRequest(page, '/api/security/dev/reset-first-run', {
+ method: 'POST',
+ });
+ }
+ if (!resetRes.ok()) {
+ throw new Error(`Failed to reset first-run state: ${resetRes.status()} ${await resetRes.text()}`);
+ }
+
+ const payload = (await resetRes.json()) as ResetFirstRunResponse;
+ bootstrapToken = String(payload.bootstrapToken || '').trim();
+ if (bootstrapToken === '') {
+ throw new Error('First-run reset response did not include a bootstrap token');
+ }
+
+ await expect
+ .poll(async () => {
+ const current = await getSecurityStatus(page);
+ return current.hasAuthentication === false;
+ })
+ .toBe(true);
+
+ await page.goto('/', { waitUntil: 'domcontentloaded' });
+ await page.evaluate(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ });
+ await page.context().clearCookies();
+ }
+
+ await completeSetupWizard(page, bootstrapToken);
+ const firstRunLandingPattern =
+ /\/(settings\/infrastructure\/install|proxmox|dashboard|nodes|hosts|docker|infrastructure)/;
+ if (!firstRunLandingPattern.test(page.url())) {
+ await login(page);
+ }
+ await expect(page).toHaveURL(firstRunLandingPattern);
+}
+
/**
* Login as admin user
*/
@@ -185,20 +289,7 @@ export async function loginAsAdmin(page: Page) {
export async function login(page: Page, credentials = E2E_CREDENTIALS) {
await page.goto('/');
- await page.waitForLoadState('domcontentloaded');
-
- // Wait for SPA JavaScript to execute. The raw HTML shell contains a
- // "You need to enable JavaScript" noscript message. Under load (e.g.
- // running the full journey suite sequentially), Vite can take several
- // seconds to serve the JS bundle. Wait for #root to have meaningful
- // child content before looking for login form or authenticated route.
- await page.waitForFunction(
- () => {
- const root = document.getElementById('root');
- return root !== null && root.children.length > 0;
- },
- { timeout: 20_000 },
- );
+ await waitForAppShell(page);
const authenticatedURL = /\/(proxmox|dashboard|nodes|hosts|docker|infrastructure)/;
const usernameInput = page.locator('input[name="username"]');