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.

Use saved credentials in copied agent removal commands

pulse-triage[bot]35bb23bebf30
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 55ac477663..4c7323798f 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1071,6 +1071,33 @@ Unified Agent installer command. The choice must remain off by default, be
visible at the point where the command is generated, and affect both the
installer download and the agent's subsequent Pulse TLS connection.
+### Copied removal uses the installed credential, not installation input
+
+Every existing uninstall copy surface (installer, source management and removed
+Agent Doctor handoff) must work without minting or revealing an install token.
+Unix `--uninstall` skips preflight, private token input and token-file bootstrap;
+it clears inherited lifecycle credentials/identity/trust in its child only and
+lets the installed connection recover its own server, credential and pin.
+Explicit canonical identity and selected CA/insecure settings remain supported;
+an HTTP download alone must not weaken the saved HTTPS connection.
+
+Windows removal invokes the downloaded script with typed uninstall and empty
+credential/connection parameters, so ambient install variables cannot shadow
+saved state. Its download uses only selected trust, restores the TLS callback
+and does not assign shell environment variables. Identity and paths are quoted
+as literals. Installation's private-input/preflight path remains separate.
+`agentInstallCommand.test.ts` executes a terminal-free Unix recorder and retains
+its success/failure exit and inherited-state boundaries; the real composed hook
+and Doctor model prove all token/platform/identity branches. The parent/final
+`agent-uninstall.cjs` browser matrix checks real copy callers, displayed/copy
+parity, no issuance on removal and unchanged install gating.
+
+These are command-generation/controlled-browser proofs, not native uninstall.
+Unix's existing durable authenticated deregistration-before-teardown boundary
+is unchanged. Windows installer confirmation/failure retention remains owned
+by Delivery: its current suppressed unregister failure is not made safe by a
+token-free command. No copy receipt establishes installed removal or a release.
+
## Canonical Files
- `internal/agentexec/guest_exec_safety.go`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5e67417ac2..78c0e83e83 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -657,6 +657,19 @@ report request and response shapes are unchanged.
`TestContractDeployEnrolledCollectorReducesItsAuthorityAfterItsFirstReport`
in `internal/api/contract_test.go` pins report, then reduction.
+### Saved-credential uninstall copy handoffs
+
+Existing installer, source-manager and removed Agent Doctor copy actions do not
+request an install token for removal. The composed operations hook carries
+canonical ID/hostname into the appropriate saved-state command family; no
+endpoint, payload, API-token scope, server removal authentication or identity
+matching changes. `infrastructureAgentDoctorModel.test.ts` composes every
+removed-platform handoff with the real command closure, preserving exact
+identity and keeping installation credentials out. The shared command proof
+executes a terminal-free Unix recorder and inspects explicit Windows parameter
+binding. Browser evidence is UI-only; server/native deregistration and Windows
+failure retention require their own owner result, not source acceptance.
+
## Canonical Files
1a. `docs/API.md`
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 863262db0c..0da0a9c995 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -1344,6 +1344,19 @@ layouts, scoped filtering, day selection and later inventory replacement.
Compact Coverage age cells use the existing metadata-size text and reclaim numeric-age gutters so the full Unknown word stays visible even beside a Job column at 320px; text-range checks account for cell padding, not only the outer box.
+### Removal copy actions are independent of install unlock state
+
+The existing Infrastructure installer, source-manager and removed Agent Doctor
+controls copy removal commands before or after installation-token generation,
+without minting, displaying or embedding another credential. Displayed command
+and copied text must agree. Guidance describes saved host connection/credentials
+and does not present the saved Unix helper as an offline authentication bypass.
+The `agent-uninstall.cjs` parent/final desktop and touch-phone matrix exercises
+these production components with synthetic API data, including selected trust,
+canonical identity, optional authentication and installation's separate token
+gate. No route, navigation entry or remote-execution surface is added; native
+removal/failure retention and containing publication remain separate evidence.
+
## Canonical Files
1. `frontend-modern/src/components/shared/`
diff --git a/frontend-modern/browser-tests/agent-uninstall.cjs b/frontend-modern/browser-tests/agent-uninstall.cjs
new file mode 100644
index 0000000000..3140908ebc
--- /dev/null
+++ b/frontend-modern/browser-tests/agent-uninstall.cjs
@@ -0,0 +1,398 @@
+// Actual operations/install/Doctor/workspace components with synthetic local API data.
+// Copied commands are observed, not executed; no host, credential or service changes.
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const crypto = require('node:crypto');
+const { chromium, webkit } = require('playwright');
+const hash = (p) => crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
+const origin = 'http://127.0.0.1:5361';
+const token = 'synthetic-browser-install-token';
+const binding = JSON.parse(fs.readFileSync('/workspace/tmp/uninstall-browser-binding.json'));
+const output = '/workspace/tmp/agent-uninstall-browser';
+fs.mkdirSync(output, { recursive: true });
+const result = {
+ binding,
+ playwright: require('playwright/package.json').version,
+ cases: [],
+ captures: [],
+ completed: false,
+ cleanup: [],
+ limits:
+ 'Synthetic production UI components and API doubles; no PowerShell execution, physical device, native removal, publication or release.',
+};
+assert.equal(
+ result.playwright,
+ JSON.parse(fs.readFileSync('/workspace/tests/integration/package-lock.json')).packages[
+ 'node_modules/@playwright/test'
+ ].version,
+);
+(async () => {
+ for (const [mode, source] of Object.entries(binding.scenarios)) {
+ const root = '/workspace/' + source.root;
+ for (const [p, h] of Object.entries(source.content_sha256))
+ assert.equal(hash(root + '/' + p.replace('frontend-modern/', '')), h, p);
+ const { createServer } = await import(root + '/node_modules/vite/dist/node/index.js');
+ const server = await createServer({
+ root,
+ configFile: root + '/vite.config.ts',
+ cacheDir: output + '/' + mode + '-cache',
+ server: { host: '127.0.0.1', port: 5361, strictPort: true, watch: null },
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ let browser;
+ try {
+ await server.listen();
+ for (const [engine, width, dark] of [
+ [chromium, 1280, false],
+ [webkit, 390, true],
+ ]) {
+ browser = await engine.launch(
+ engine === chromium
+ ? { headless: true, channel: 'chromium', args: ['--no-sandbox'] }
+ : { headless: true },
+ );
+ const page = await browser.newPage({
+ viewport: { width, height: 900 },
+ isMobile: width < 500,
+ hasTouch: width < 500,
+ locale: 'en-GB',
+ });
+ page.setDefaultTimeout(9000);
+ const record = {
+ mode,
+ width,
+ dark,
+ browser: browser.version(),
+ reads: [],
+ writes: [],
+ unexpected: [],
+ offOrigin: [],
+ errors: [],
+ commands: [],
+ screenshots: [],
+ minted: 0,
+ };
+ result.cases.push(record);
+ let optional = false;
+ page.on('pageerror', (e) => record.errors.push(e.message));
+ page.on('console', (m) => {
+ if (m.type() === 'error') record.errors.push(m.text().slice(0, 500));
+ });
+ await page.addInitScript((dark) => {
+ window.__copies = [];
+ Object.defineProperty(navigator, 'clipboard', {
+ value: { writeText: async (text) => window.__copies.push(text) },
+ });
+ document.addEventListener(
+ 'DOMContentLoaded',
+ () => document.documentElement.classList.toggle('dark', dark),
+ { once: true },
+ );
+ }, dark);
+ await page.route('**/*', async (route) => {
+ const req = route.request(),
+ url = new URL(req.url()),
+ p = url.pathname;
+ if (url.origin !== origin) {
+ record.offOrigin.push(url.origin);
+ return route.abort();
+ }
+ if (!p.startsWith('/api/')) return route.continue();
+ if (req.method() !== 'GET') {
+ record.writes.push({ p, method: req.method() });
+ if (p === '/api/agent-install-command') {
+ assert.equal(req.postDataJSON().type, 'host');
+ record.minted++;
+ return route.fulfill({
+ json: {
+ token,
+ record: {
+ id: 'synthetic-install-record',
+ name: 'Synthetic installer',
+ prefix: 'synthetic',
+ suffix: 'test',
+ createdAt: new Date().toISOString(),
+ },
+ },
+ });
+ }
+ return route.fulfill({ status: 403, json: { error: 'Fixture refuses mutation' } });
+ }
+ record.reads.push(p);
+ let data;
+ if (p === '/api/security/status')
+ data = {
+ requiresAuth: !optional,
+ hasAuthentication: !optional,
+ apiTokenConfigured: !optional,
+ agentUrl: 'https://download.invalid/base',
+ };
+ else if (p === '/api/state') data = { connectedInfrastructure: [] };
+ else if (p === '/api/connections')
+ data = {
+ systems: [],
+ connections: [
+ {
+ id: 'agent:workspace-agent',
+ type: 'agent',
+ name: 'workspace-host',
+ address: 'workspace.example',
+ state: 'active',
+ stateReason: '',
+ enabled: true,
+ surfaces: ['host'],
+ scope: { host: true },
+ lastSeen: new Date().toISOString(),
+ lastError: null,
+ source: 'agent',
+ agentVersion: '6.5.0',
+ agentIdentity: { hostname: 'workspace.example', platform: 'debian' },
+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
+ },
+ ],
+ };
+ else if (p === '/api/license/runtime-capabilities')
+ data = {
+ capabilities: [],
+ limits: [],
+ hosted_mode: false,
+ blocked_capabilities: [],
+ runtime: { build: 'community' },
+ };
+ else if (p === '/api/health') data = { status: 'ok' };
+ else {
+ record.unexpected.push(p);
+ return route.fulfill({ status: 404, json: { error: 'Unexpected fixture read' } });
+ }
+ return route.fulfill({ json: data });
+ });
+ const capture = async (name, locator) => {
+ await locator.scrollIntoViewIfNeeded();
+ await page.waitForTimeout(180);
+ const path = `${output}/${mode}-${width}-${name}.png`;
+ await page.screenshot({ path, animations: 'disabled' });
+ const item = { path: path.replace('/workspace/', ''), sha256: hash(path) };
+ result.captures.push(item);
+ record.screenshots.push(item);
+ assert.ok(
+ await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1),
+ 'page overflow',
+ );
+ };
+ const copy = async (name, platform, stage, scope = page) => {
+ const button = scope.getByRole('button', { name, exact: true });
+ await button.focus();
+ await page.keyboard.press('Enter');
+ const command = await page.evaluate(() => window.__copies.at(-1));
+ assert.equal(typeof command, 'string');
+ const safe =
+ platform === 'windows'
+ ? !command.includes('PULSE_TOKEN') &&
+ !command.includes(token) &&
+ command.includes("-Url '' -Token '' -TokenFile ''")
+ : !command.includes('Pulse agent token') &&
+ !command.includes('--token') &&
+ !command.includes(token) &&
+ !command.includes('--url');
+ assert.ok(command.includes(platform === 'windows' ? 'install.ps1' : '--uninstall'));
+ assert.ok(!command.includes('\n'));
+ record.commands.push({ name, platform, stage, safe, command });
+ if (mode === 'final') assert.ok(safe, name + ' ' + stage);
+ return command;
+ };
+ await page.goto(origin + '/browser-tests/agent-uninstall.html', {
+ waitUntil: 'domcontentloaded',
+ timeout: 60000,
+ });
+ await page
+ .getByRole('heading', { name: 'Saved-credential agent removal', exact: true })
+ .waitFor();
+ const summary = page.locator('summary').filter({ hasText: 'Uninstall agent' });
+ await summary.click();
+ const checkInstaller = async (stage) => {
+ for (const [name, platform] of [
+ ['Copy Linux macOS FreeBSD uninstall command', 'unix'],
+ ['Copy Windows uninstall command', 'windows'],
+ ]) {
+ const cmd = await copy(name, platform, stage);
+ const shown = page
+ .getByRole('button', { name, exact: true })
+ .locator('..')
+ .locator('code');
+ assert.equal(await shown.textContent(), cmd, 'render/copy parity');
+ }
+ assert.equal(record.minted, stage === 'minted' ? 1 : 0);
+ await capture(stage, summary);
+ };
+ await checkInstaller('unminted');
+ if (binding.installer_only) {
+ assert.ok(
+ (await page.locator('body').innerText()).includes(
+ 'If a Unix install has saved credentials, its server must confirm removal',
+ ),
+ );
+ assert.deepEqual(record.writes, []);
+ assert.deepEqual(record.errors, []);
+ assert.deepEqual(record.unexpected, []);
+ assert.deepEqual(record.offOrigin, []);
+ await browser.close();
+ browser = undefined;
+ console.log(
+ JSON.stringify({
+ mode,
+ width,
+ installer_only: true,
+ copies: record.commands.length,
+ minted: record.minted,
+ }),
+ );
+ continue;
+ }
+ for (const target of ['removed-fixture', 'removed-windows']) {
+ await page
+ .getByRole('button', { name: 'Show details for ' + target, exact: true })
+ .click();
+ }
+ for (const [name, platform, id] of [
+ [
+ 'Copy Linux / macOS / FreeBSD uninstall command for removed-fixture',
+ 'unix',
+ 'removed-agent-42',
+ ],
+ [
+ 'Copy Windows PowerShell uninstall command for removed-windows',
+ 'windows',
+ 'removed-windows-42',
+ ],
+ ]) {
+ const cmd = await copy(name, platform, 'doctor-unminted');
+ assert.ok(cmd.includes(id));
+ }
+ await capture(
+ 'doctor',
+ page.getByRole('button', {
+ name: 'Copy Windows PowerShell uninstall command for removed-windows',
+ exact: true,
+ }),
+ );
+ await page.getByRole('button', { name: 'Generate token', exact: true }).first().click();
+ const dialog = page.getByRole('dialog', { name: 'API token ready' });
+ await dialog.waitFor();
+ await dialog.getByRole('button', { name: 'Dismiss', exact: true }).click();
+ await checkInstaller('minted');
+ await page
+ .getByRole('button', {
+ name: 'Show advanced connection and install options',
+ exact: true,
+ })
+ .click();
+ await page
+ .getByLabel('Connection URL (Agent → Pulse)', { exact: true })
+ .fill('https://download.invalid/custom/');
+ await page
+ .getByLabel('Custom CA certificate path (optional)', { exact: true })
+ .fill('/explicit/ca.pem');
+ const identityCopy = await copy('Copy Unix uninstall', 'unix', 'identity-ca');
+ assert.ok(
+ identityCopy.includes('agent-fixture-42') &&
+ identityCopy.includes('node.example') &&
+ identityCopy.includes('--cacert'),
+ );
+ const winCopy = await copy('Copy Windows uninstall command', 'windows', 'custom-ca');
+ assert.ok(winCopy.includes('/explicit/ca.pem'));
+ await capture('custom-ca', summary);
+ // Installation remains credential-gated/private; removal never unlocks it.
+ const installCommand = await page
+ .locator('code')
+ .filter({ hasText: 'Pulse agent token' })
+ .first()
+ .textContent();
+ assert.ok(installCommand.includes('--token-file') && !installCommand.includes(token));
+ optional = true;
+ await page.goto(origin + '/browser-tests/agent-uninstall.html?optional=1', {
+ waitUntil: 'domcontentloaded',
+ timeout: 60000,
+ });
+ await summary.waitFor();
+ await summary.click();
+ await copy('Copy Linux macOS FreeBSD uninstall command', 'unix', 'optional-auth');
+ await copy('Copy Windows uninstall command', 'windows', 'optional-auth');
+ assert.equal(record.minted, 1);
+ optional = false;
+ await page.goto(origin + '/browser-tests/agent-uninstall.html?workspace=1', {
+ waitUntil: 'domcontentloaded',
+ timeout: 60000,
+ });
+ await page
+ .getByRole('button', { name: /^Manage/ })
+ .first()
+ .click();
+ const section = page
+ .getByText('Uninstall commands', { exact: true })
+ .locator('..')
+ .locator('..');
+ const buttons = section.getByRole('button', {
+ name: 'Copy uninstall command',
+ exact: true,
+ });
+ assert.equal(await buttons.count(), 2);
+ for (let i = 0; i < 2; i++) {
+ await buttons.nth(i).click();
+ const command = await page.evaluate(() => window.__copies.at(-1));
+ const platform = i === 0 ? 'unix' : 'windows';
+ const safe =
+ !command.includes(token) &&
+ !command.includes('Pulse agent token') &&
+ !command.includes('--token') &&
+ (platform !== 'windows' || !command.includes('PULSE_TOKEN'));
+ record.commands.push({
+ name: 'Workspace copy ' + platform,
+ stage: 'workspace',
+ platform,
+ safe,
+ command,
+ });
+ if (mode === 'final') assert.ok(safe);
+ }
+ await capture('workspace', section);
+ assert.equal(record.minted, 1, 'removal minted a token');
+ assert.deepEqual(record.writes, [{ p: '/api/agent-install-command', method: 'POST' }]);
+ assert.deepEqual(record.unexpected, []);
+ assert.deepEqual(record.offOrigin, []);
+ assert.deepEqual(record.errors, []);
+ if (mode === 'parent') {
+ assert.equal(
+ record.commands.find((x) => x.stage === 'unminted' && x.platform === 'unix').safe,
+ false,
+ );
+ assert.equal(
+ record.commands.find((x) => x.stage === 'unminted' && x.platform === 'windows').safe,
+ false,
+ );
+ }
+ await browser.close();
+ browser = undefined;
+ console.log(
+ JSON.stringify({
+ mode,
+ width,
+ copies: record.commands.length,
+ minted: record.minted,
+ errors: record.errors,
+ }),
+ );
+ }
+ } finally {
+ if (browser) await browser.close();
+ await server.close();
+ result.cleanup.push({ mode, browserClosed: true, serverClosed: true });
+ fs.writeFileSync(output + '/result.json', JSON.stringify(result, null, 2) + '\n');
+ }
+ }
+ result.completed = true;
+ fs.writeFileSync(output + '/result.json', JSON.stringify(result, null, 2) + '\n');
+ console.log('PASS copied removal controls for every supplied source scenario');
+})().catch((e) => {
+ console.error(e);
+ process.exitCode = 1;
+});
diff --git a/frontend-modern/browser-tests/agent-uninstall.html b/frontend-modern/browser-tests/agent-uninstall.html
new file mode 100644
index 0000000000..e3bf6ee356
--- /dev/null
+++ b/frontend-modern/browser-tests/agent-uninstall.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Saved-credential agent removal</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./agent-uninstall.tsx"></script>
+ </body>
+</html>
diff --git a/frontend-modern/browser-tests/agent-uninstall.tsx b/frontend-modern/browser-tests/agent-uninstall.tsx
new file mode 100644
index 0000000000..15b515ed5b
--- /dev/null
+++ b/frontend-modern/browser-tests/agent-uninstall.tsx
@@ -0,0 +1,203 @@
+// Production settings state, installer and token dialog; synthetic API data only.
+import { Route, Router } from '@solidjs/router';
+import { render } from 'solid-js/web';
+import {
+ InfrastructureOperationsStateProvider,
+ useInfrastructureOperationsContext,
+} from '../src/components/Settings/useInfrastructureOperationsState';
+import { InfrastructureInstallerSection } from '../src/components/Settings/InfrastructureInstallerSection';
+import { InfrastructureAgentDoctorPage } from '../src/components/Settings/InfrastructureAgentDoctorPage';
+import type { InfrastructureAgentDoctorTarget } from '../src/components/Settings/infrastructureAgentUpdateCommandsModel';
+import { InfrastructureWorkspace } from '../src/components/Settings/InfrastructureWorkspace';
+import { TokenRevealDialog } from '../src/components/TokenRevealDialog';
+import '../src/index.css';
+
+const Operations = () => {
+ const state = useInfrastructureOperationsContext();
+ const identity = {
+ agentActionId: 'agent-fixture-42',
+ agentId: 'unused-alias',
+ hostname: 'node.example',
+ };
+ const connection = {
+ id: 'agent:agent-fixture-42',
+ type: 'agent',
+ name: 'node.example',
+ address: 'node.example',
+ state: 'unauthorized',
+ agentIdentity: { hostname: 'node.example', commandsEnabled: false },
+ } as Parameters<typeof state.getAgentConnectionUpgradeCommand>[0];
+ return (
+ <section class="space-y-2 p-4 border border-border" aria-label="Lifecycle command fixture">
+ <p>Actual operations state: identity and trust options must survive.</p>
+ <button onClick={() => navigator.clipboard.writeText(state.getUninstallCommand(identity))}>
+ Copy Unix uninstall
+ </button>
+ <button
+ onClick={() =>
+ navigator.clipboard.writeText(
+ state.getAgentConnectionUpgradeCommand(connection, ['--enable-docker'], 'linux', true),
+ )
+ }
+ >
+ Copy Unix credential repair
+ </button>
+ <button
+ onClick={() =>
+ navigator.clipboard.writeText(
+ state.getAgentConnectionUpgradeCommand(connection, ['--enable-docker'], 'linux', false),
+ )
+ }
+ >
+ Copy Unix saved-state update
+ </button>
+ </section>
+ );
+};
+const Fixture = () =>
+ new URLSearchParams(location.search).has('workspace') ? (
+ <Workspace />
+ ) : (
+ <InfrastructureOperationsStateProvider embedded>
+ <main class="mx-auto max-w-5xl p-4 bg-base text-base-content">
+ <h1 class="text-xl mb-4">Saved-credential agent removal</h1>
+ <InfrastructureInstallerSection />
+ <Operations />
+ <Doctor />
+ <TokenRevealDialog />
+ </main>
+ </InfrastructureOperationsStateProvider>
+ );
+const Doctor = () => {
+ const target = {
+ key: 'agent:doctor-fixture',
+ connectionId: 'agent:doctor-fixture',
+ displayName: 'doctor-fixture',
+ contextLabel: 'Machine',
+ currentVersion: '6.4.5',
+ installFlags: ['--enable-docker'],
+ status: 'critical',
+ reasons: [],
+ evidence: [],
+ needsUpdate: false,
+ needsCredentialRepair: true,
+ commandPlatform: 'linux',
+ safeCollector: false,
+ actionRunnerPosture: [],
+ actionRunnerCredentialEligible: false,
+ source: 'ledger',
+ connection: {
+ id: 'agent:doctor-fixture',
+ type: 'agent',
+ name: 'doctor-fixture',
+ address: 'doctor.example',
+ state: 'unauthorized',
+ agentIdentity: { hostname: 'doctor.example', commandsEnabled: false },
+ },
+ } as InfrastructureAgentDoctorTarget;
+ const removedTarget = {
+ ...target,
+ key: 'agent:removed-fixture',
+ connectionId: 'agent:removed-fixture',
+ displayName: 'removed-fixture',
+ status: 'removed',
+ needsCredentialRepair: false,
+ connection: undefined,
+ diagnostic: { agentId: 'removed-agent-42', hostname: 'removed.example' },
+ } as InfrastructureAgentDoctorTarget;
+ const removedWindows = {
+ ...removedTarget,
+ key: 'agent:removed-windows',
+ connectionId: 'agent:removed-windows',
+ displayName: 'removed-windows',
+ commandPlatform: 'windows',
+ diagnostic: { agentId: 'removed-windows-42', hostname: 'removed-windows.example' },
+ } as InfrastructureAgentDoctorTarget;
+ return <InfrastructureAgentDoctorPage targets={[target, removedTarget, removedWindows]} />;
+};
+const baseProps = () =>
+ ({
+ selectedAgent: () => 'pve',
+ onSelectAgent: () => {},
+ initialLoadComplete: () => true,
+ discoveryEnabled: () => false,
+ discoveryMode: () => 'auto',
+ discoverySubnetDraft: () => '',
+ discoverySubnetError: () => undefined,
+ discoveryScanStatus: () => ({ scanning: false }),
+ discoveredNodes: () => [],
+ savingDiscoverySettings: () => false,
+ envOverrides: () => ({}),
+ agentStateResources: () => [],
+ pbsInstances: () => [],
+ pmgInstances: () => [],
+ pveNodes: () => [],
+ pbsNodes: () => [],
+ pmgNodes: () => [],
+ trueNASSettings: {
+ closeDialog: () => {},
+ connections: () => [],
+ } as any,
+ vmwareSettings: {
+ closeDialog: () => {},
+ connections: () => [],
+ } as any,
+ temperatureMonitoringEnabled: () => false,
+ triggerDiscoveryScan: () => {},
+ loadDiscoveredNodes: () => {},
+ handleDiscoveryEnabledChange: () => {},
+ handleDiscoveryModeChange: () => {},
+ setDiscoveryMode: () => {},
+ setDiscoverySubnetDraft: () => {},
+ setDiscoverySubnetError: () => {},
+ setLastCustomSubnet: () => {},
+ commitDiscoverySubnet: () => {},
+ parseSubnetList: () => [],
+ normalizeSubnetList: (value: string) => value,
+ isValidCIDR: () => true,
+ currentDraftSubnetValue: () => '',
+ discoverySubnetInputRef: () => {},
+ testNodeConnection: () => {},
+ requestDeleteNode: () => {},
+ refreshClusterNodes: () => {},
+ setShowNodeModal: () => {},
+ editingNode: () => null,
+ setEditingNode: () => {},
+ setCurrentNodeType: () => {},
+ modalResetKey: () => 0,
+ setModalResetKey: () => {},
+ isNodeModalVisible: () => false,
+ securityStatus: () => null,
+ resolveTemperatureMonitoringEnabled: () => false,
+ temperatureMonitoringLocked: () => false,
+ savingTemperatureSetting: () => false,
+ handleTemperatureMonitoringChange: () => {},
+ disableDockerUpdateActions: () => false,
+ disableDockerUpdateActionsLocked: () => false,
+ savingDockerUpdateActions: () => false,
+ handleDisableDockerUpdateActionsChange: () => {},
+ handleNodeTemperatureMonitoringChange: () => {},
+ saveNode: () => {},
+ showDeleteNodeModal: () => false,
+ cancelDeleteNode: () => {},
+ deleteNode: () => {},
+ deleteNodeLoading: () => false,
+ nodePendingDeleteLabel: () => '',
+ nodePendingDeleteHost: () => '',
+ nodePendingDeleteType: () => '',
+ nodePendingDeleteTypeLabel: () => '',
+ }) as any;
+
+const Workspace = () => (
+ <main class="mx-auto max-w-5xl p-4">
+ <InfrastructureWorkspace {...baseProps()} />
+ </main>
+);
+render(
+ () => (
+ <Router>
+ <Route path="*" component={Fixture} />
+ </Router>
+ ),
+ document.getElementById('root')!,
+);
diff --git a/frontend-modern/browser-verification/59aba77c4d2f53f6.json b/frontend-modern/browser-verification/59aba77c4d2f53f6.json
new file mode 100644
index 0000000000..2e66361b4f
--- /dev/null
+++ b/frontend-modern/browser-verification/59aba77c4d2f53f6.json
@@ -0,0 +1,46 @@
+{
+ "version": 1,
+ "base_sha": "9ef92f0ccf2d914b0f54b21124ff9292bf2e4925",
+ "verified_at": "2026-10-11T21:19:06.076269Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/utils/agentInstallCommand.ts",
+ "frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx",
+ "frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx",
+ "frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx",
+ "frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/utils/agentInstallCommand.ts": "a8fca39fd0a21eb22601d827e8e8189ceadf852bf27c694049adff06a2ee1231",
+ "frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx": "0ad6e29ec582e1e1af099d53ff25afd508fa76e8c40c1f4779e7ef91bd7f0e97",
+ "frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx": "ee5554185fd1adfc740d0bd4b8c94f2f650c2c4b8f5ac138df5d5b20fddcd86e",
+ "frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx": "c494f0758e8b8c65bce9c2ee26074ba73b7517cd495c5d8ac194a5abf0badd77",
+ "frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx": "69597f5def093a847663126667a81c9fc9b5caae85c507858ba1ba6fc39def00"
+ },
+ "routes": [
+ "Existing Infrastructure installer, source management and removed Agent Doctor handoffs in /browser-tests/agent-uninstall.html; synthetic production component/router fixtures, not an application route"
+ ],
+ "viewports": [
+ {
+ "width": 1280,
+ "height": 900
+ },
+ {
+ "width": 390,
+ "height": 900
+ }
+ ],
+ "states": [
+ "Playwright 1.56.1 matches the integration lock. Chromium 141.0.7390.37 desktop light and touch-phone WebKit 26.0 dark. Exact base and final runtime hashes checked; all twenty matrix screenshots and two final conditional-guidance screenshots inspected.",
+ "The retained complete parent cohorts reproduce Unix private-input prompting and Windows placeholder/new installation-token injection on both viewports. Final cohorts pass twelve copied-command observations each across installer, removed Doctor and source manager before/after token generation, custom CA/identity and optional authentication. Copy/display parity, keyboard activation, no removal issuance, install gate/private-input separation and no page overflow hold.",
+ "An initial load timeout, unexpanded Doctor copy timeout and colliding synthetic Doctor connection IDs were retained. A fourth-run checker incorrectly treated the Unix child-only unset PULSE_TOKEN as credential injection; the complete parents remain valid but that run exited one. Corrected final-only cohorts passed, with no source-runtime correction hidden in the checker change.",
+ "A later wording-only qualification limits Unix confirmation-before-erasure guidance to installs with saved credentials. Its exact final InstallerSection hash and both fresh desktop/phone renders/copies pass separately; the four other runtime hashes match the full final matrix unchanged.",
+ "Only explicit synthetic installation generation posts once per full cohort; removal posts/mints nothing. No unexpected read, off-origin request, page or console error. Browser/server close. No commands, native uninstall, physical device, installed recovery, publication or release acceptance is claimed."
+ ],
+ "interactions": [
+ "Expand Uninstall agent without unlocking installation, focus each copy button and use Enter; compare displayed/copy text.",
+ "Expand removed Linux and Windows Doctor rows and copy canonical host-local handoffs.",
+ "Explicitly generate a synthetic install token, dismiss reveal and copy uninstall again; set explicit download URL/CA and observe token-free canonical output.",
+ "Reload optional-auth controls without minting; open actual source manager Manage dialog and copy both uninstall families."
+ ]
+}
diff --git a/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx b/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx
index 329edd39a5..b7fb34275b 100644
--- a/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx
+++ b/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx
@@ -941,9 +941,8 @@ export const InfrastructureAgentDoctorPage: Component<InfrastructureAgentDoctorP
This agent was removed from Pulse, but the agent software may
still be installed on its host. Finish detaching it by running
the uninstall command on the affected host itself. Pulse does
- not run commands remotely. For Unix commands that require a
- token, run the command first, then paste the separately revealed
- token at its silent prompt. Never insert it into the command.
+ not run commands remotely. Removal uses the host's saved
+ connection and credentials; do not generate a new token.
</p>
<For each={handoff().commands}>
{(entry) => (
diff --git a/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx b/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx
index a44b51fb27..e2088fa648 100644
--- a/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx
+++ b/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx
@@ -907,7 +907,8 @@ export const InfrastructureInstallerSection: Component<InfrastructureInstallerSe
</summary>
<div class="mt-3 space-y-3">
<p class="text-xs text-muted">
- Run the appropriate command on your machine to remove the Pulse agent:
+ Run the appropriate command on the agent's host. Removal uses its saved connection and
+ credentials; you do not need to generate another token.
</p>
<div class="space-y-1">
<span class="text-xs font-medium text-muted">Linux / macOS / FreeBSD</span>
@@ -930,7 +931,7 @@ export const InfrastructureInstallerSection: Component<InfrastructureInstallerSe
</div>
</div>
<p class="text-xs italic text-muted">
- If the agent can't reach this server, run directly on the machine:{' '}
+ To use the installer saved on a Unix host, run:{' '}
<code class="rounded-sm bg-surface-hover px-1 not-italic">
sudo bash /var/lib/pulse-agent/install.sh --uninstall
</code>{' '}
@@ -944,6 +945,11 @@ export const InfrastructureInstallerSection: Component<InfrastructureInstallerSe
</code>
)
</p>
+ <p class="text-xs text-muted">
+ If a Unix install has saved credentials, its server must confirm removal before local
+ credentials and services are deleted. If it is refused, restore trusted connectivity
+ before retrying.
+ </p>
<div class="space-y-1">
<span class="text-xs font-medium text-muted">
Windows (PowerShell as Administrator)
diff --git a/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx b/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx
index 52a99f1c0a..afdc957ccb 100644
--- a/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx
+++ b/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx
@@ -550,7 +550,8 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
<div class="text-sm font-semibold text-base-content">Uninstall commands</div>
<p class="text-xs text-muted">
Removing the source forgets it from Pulse. Uninstall the agent on the host as well
- if you want to detach it completely.
+ if you want to detach it completely. The commands use the host's saved connection
+ and credentials, not a new installation token.
</p>
</div>
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
index 72260c3b27..1a22f01a62 100644
--- a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
@@ -1138,7 +1138,6 @@ describe('Agent Doctor Unix credential handoffs', () => {
expect(command).not.toContain(privateInstallState.token);
expect(command).not.toContain('old-alias');
expect(command).not.toContain('| bash');
- expect(command).toContain('--token-file "$token_file"');
expect(command).toContain('--agent-id');
expect(command).toContain('canonical-id-42');
expect(command).toContain('--hostname');
@@ -1148,6 +1147,9 @@ describe('Agent Doctor Unix credential handoffs', () => {
expect(command).not.toContain('--enable-commands');
execFileSync('sh', ['-n', '-c', command]);
}
+ expect(repair).toContain('--token-file "$token_file"');
+ expect(uninstall).not.toContain('--token');
+ expect(uninstall).not.toContain('Pulse agent token');
expect(repair).toContain('--update');
expect(repair).toContain('--enable-docker');
expect(repair).toContain('--preflight-only');
@@ -1173,3 +1175,45 @@ describe('Agent Doctor Unix credential handoffs', () => {
).toBe(false);
});
});
+
+describe('removed-agent handoff uses saved credentials, not installation state', () => {
+ it.each(['debian', 'Windows Server 2022', undefined])(
+ 'carries canonical identity into every offered %s command',
+ (platform) => {
+ const [target] = collectInfrastructureAgentDoctorTargets({
+ rows: [],
+ diagnosticsAvailable: true,
+ diagnostics: [
+ diagnosticFixture({
+ connectionId: 'agent:removed-host',
+ rowKey: 'removed-host',
+ id: 'removed-host',
+ agentId: 'canonical-removed',
+ name: 'removed-host',
+ hostname: 'removed.example',
+ status: 'removed',
+ platform,
+ }),
+ ],
+ });
+ const handoff = getInfrastructureAgentDoctorUninstallHandoff(target)!;
+ const operations = useInfrastructureOperationsState();
+ for (const entry of handoff.commands) {
+ const command = operations.getPlatformUninstallCommand(entry.platform, handoff.identity);
+ expect(command).toContain('canonical-removed');
+ expect(command).toContain('removed.example');
+ expect(command).not.toContain(operations.currentToken());
+ expect(command).not.toContain('<api-token>');
+ expect(command).not.toContain('Pulse agent token');
+ if (entry.platform === 'windows') {
+ expect(command).toContain("-Uninstall $true -Url '' -Token '' -TokenFile ''");
+ expect(command).not.toContain('$env:');
+ } else {
+ expect(command).toContain('--uninstall');
+ expect(command).not.toContain('--url');
+ expect(command).not.toContain('--token');
+ }
+ }
+ },
+ );
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index e8015c4f0e..a33bd1cdd1 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -2218,3 +2218,22 @@ describe('node import preview authority boundary', () => {
expect(nodeCredentialSlotSource).toContain('if (saveBlockedByImportPlan())');
});
});
+
+describe('ordinary uninstall copy surfaces', () => {
+ it('keeps both installer families reachable without an installation token and uses the shared state', () => {
+ const removal = infrastructureInstallerSectionSource.slice(
+ infrastructureInstallerSectionSource.indexOf('Uninstall agent'),
+ );
+ expect(removal).toContain('copyToClipboard(state.getUninstallCommand())');
+ expect(removal).toContain('copyToClipboard(state.getWindowsUninstallCommand())');
+ expect(removal).not.toContain('commandsUnlocked');
+ expect(removal).not.toContain('requiresToken');
+ expect(removal).not.toContain('handleGenerateToken');
+ expect(removal).toContain('saved connection');
+ expect(removal).not.toContain("If the agent can't reach this server");
+ expect(infrastructureWorkspaceSource).toContain('linux: operations.getUninstallCommand()');
+ expect(infrastructureWorkspaceSource).toContain(
+ 'windows: operations.getWindowsUninstallCommand()',
+ );
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx b/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx
index bde07dcf74..18254c397a 100644
--- a/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx
@@ -175,13 +175,14 @@ describe('useInfrastructureOperationsState command-building closures', () => {
});
});
- describe('resolvedCommandToken (via getUninstallCommand)', () => {
- it('requests private input without copying a placeholder when a token is required', async () => {
+ describe('saved-credential removal independent of install token', () => {
+ it('uses saved credentials without prompting when an installation token is required', async () => {
const { state, dispose } = mountHook();
await flushAsync();
state.setCustomAgentUrl(HTTPS_URL);
- expect(state.getUninstallCommand()).toContain('--token-file "$token_file"');
+ expect(state.getUninstallCommand()).not.toContain('--token');
+ expect(state.getUninstallCommand()).not.toContain('Pulse agent token');
expect(state.getUninstallCommand()).not.toContain('<api-token>');
dispose();
});
@@ -193,7 +194,8 @@ describe('useInfrastructureOperationsState command-building closures', () => {
await state.handleGenerateToken();
const cmd = state.getUninstallCommand();
- expect(cmd).toContain('--token-file "$token_file"');
+ expect(cmd).not.toContain('--token');
+ expect(cmd).not.toContain('Pulse agent token');
expect(cmd).not.toContain('tok-1');
expect(cmd).not.toContain('<api-token>');
expect(mocks.showTokenReveal).toHaveBeenCalledWith({
@@ -237,7 +239,7 @@ describe('useInfrastructureOperationsState command-building closures', () => {
expect(cmd).not.toContain('--token');
expect(cmd).not.toContain('<api-token>');
expect(cmd).toContain('--uninstall');
- expect(cmd).toContain('--url');
+ expect(cmd).not.toContain('--url');
expect(cmd).toContain('https://pulse.test');
dispose();
});
@@ -268,15 +270,15 @@ describe('useInfrastructureOperationsState command-building closures', () => {
dispose();
});
- it('appends --insecure for an http:// url even in secure mode (url-driven arm)', async () => {
+ it('does not weaken saved server trust because the download URL is HTTP', async () => {
const { state, dispose } = mountHook();
await flushAsync();
state.setCustomAgentUrl(HTTP_URL);
const cmd = state.getUninstallCommand();
- // insecureMode is off, so curl stays -fsSL, but the http url forces --insecure.
+ // The download endpoint is not the saved credential-bearing server.
expect(cmd).toContain('curl -fsSL ');
- expect(cmd).toContain(' --insecure');
+ expect(cmd).not.toContain(' --insecure');
expect(cmd).toContain("'http://pulse.test/install.sh'");
dispose();
});
@@ -339,72 +341,53 @@ describe('useInfrastructureOperationsState command-building closures', () => {
});
});
- describe('getPowerShellTransportEnv (via getWindowsUninstallCommand)', () => {
- it('produces no transport prefix when insecure mode is off and no CA is set', async () => {
- const { state, dispose } = mountHook();
- await flushAsync();
- state.setCustomAgentUrl(HTTPS_URL);
-
- const cmd = state.getWindowsUninstallCommand();
- expect(cmd.startsWith('$env:PULSE_URL=')).toBe(true);
- dispose();
- });
-
- it('emits only the insecure-skip-verify env when insecure mode is on', async () => {
- const { state, dispose } = mountHook();
- await flushAsync();
- state.setCustomAgentUrl(HTTPS_URL);
- state.setInsecureMode(true);
-
- const cmd = state.getWindowsUninstallCommand();
- expect(cmd).toContain('$env:PULSE_INSECURE_SKIP_VERIFY="true"; $env:PULSE_URL=');
- // The bootstrap always references $env:PULSE_CACERT in a guard, so assert
- // the assignment form (`="`) is absent — only transportEnv produces that.
- expect(cmd).not.toContain('$env:PULSE_CACERT="');
- dispose();
- });
-
- it('emits only the CA cert env when a custom CA path is set', async () => {
- const { state, dispose } = mountHook();
- await flushAsync();
- state.setCustomAgentUrl(HTTPS_URL);
- state.setCustomCaPath('/etc/ssl/ca.pem');
-
- const cmd = state.getWindowsUninstallCommand();
- expect(cmd).toContain('$env:PULSE_CACERT="/etc/ssl/ca.pem"; $env:PULSE_URL=');
- dispose();
- });
+ describe('Windows saved-state uninstall invocation', () => {
+ it.each([false, true])(
+ 'does not read or mint an installation token (minted=%s)',
+ async (minted) => {
+ const { state, dispose } = mountHook();
+ await flushAsync();
+ state.setCustomAgentUrl(HTTPS_URL);
+ if (minted) await state.handleGenerateToken();
+ const issuanceCalls = mocks.createHostAgentInstallToken.mock.calls.length;
+ const cmd = state.getWindowsUninstallCommand();
+ expect(cmd).toContain("-Url '' -Token '' -TokenFile ''");
+ expect(cmd).toContain('-Uninstall $true');
+ expect(cmd).toContain("-AgentId '' -Hostname ''");
+ expect(cmd).not.toContain('PULSE_TOKEN');
+ expect(cmd).not.toContain('tok-1');
+ expect(cmd).not.toContain('<api-token>');
+ expect(cmd).not.toContain('$env:');
+ expect(mocks.createHostAgentInstallToken).toHaveBeenCalledTimes(issuanceCalls);
+ dispose();
+ },
+ );
- it('emits both env assignments when insecure mode and a CA path are set', async () => {
+ it('uses only explicit download trust, leaving saved runtime trust available', async () => {
const { state, dispose } = mountHook();
await flushAsync();
state.setCustomAgentUrl(HTTPS_URL);
- state.setInsecureMode(true);
- state.setCustomCaPath('/etc/ssl/ca.pem');
-
- const cmd = state.getWindowsUninstallCommand();
- expect(cmd).toContain(
- '$env:PULSE_INSECURE_SKIP_VERIFY="true"; $env:PULSE_CACERT="/etc/ssl/ca.pem"; ',
- );
- dispose();
- });
-
- it('omits PULSE_TOKEN when no token resolves, and includes it after one is minted', async () => {
- // resolvedCommandToken only yields a falsy value (no PULSE_TOKEN line)
- // when no token is required and none has been minted; the placeholder arm
- // is covered in the resolvedCommandToken group above.
- mocks.securityGetStatus.mockResolvedValue({
- requiresAuth: false,
- hasAuthentication: false,
- apiTokenConfigured: false,
+ const command = state.getWindowsUninstallCommand({
+ agentActionId: ' canonical ',
+ agentId: 'alias',
+ hostname: " host's-name ",
});
- const { state, dispose } = mountHook();
- await flushAsync();
- state.setCustomAgentUrl(HTTPS_URL);
-
- expect(state.getWindowsUninstallCommand()).not.toContain('PULSE_TOKEN');
- await state.handleGenerateToken();
- expect(state.getWindowsUninstallCommand()).toContain('$env:PULSE_TOKEN="tok-1"');
+ expect(command).toContain("-Insecure $false -CACertPath '' -ServerFingerprint ''");
+ expect(command).toContain("-AgentId 'canonical' -Hostname 'host''s-name'");
+ expect(command).toContain('if ($false -or');
+ expect(command).toContain(
+ 'finally { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $pulsePrev;',
+ );
+ state.setCustomCaPath("C:\\trust\\host's-ca.pem");
+ expect(state.getWindowsUninstallCommand()).toContain(
+ "-CACertPath 'C:\\trust\\host''s-ca.pem'",
+ );
+ expect(state.getWindowsUninstallCommand()).toContain(
+ "LoadCertificate('C:\\trust\\host''s-ca.pem')",
+ );
+ state.setInsecureMode(true);
+ expect(state.getWindowsUninstallCommand()).toContain('-Insecure $true');
+ expect(state.getWindowsUninstallCommand()).toContain('if ($true -or');
dispose();
});
});
diff --git a/frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx b/frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx
index 8bf285278d..7892f7541a 100644
--- a/frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx
+++ b/frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx
@@ -1,9 +1,9 @@
import { createContext, useContext, type ParentComponent } from 'solid-js';
import type { Connection } from '@/api/connections';
import {
- buildPowerShellInstallScriptBootstrap,
buildUnixAgentInstallCommand,
buildWindowsAgentInstallCommand,
+ buildWindowsAgentUninstallCommand,
powerShellQuote,
resolveAgentCommandPlatform,
} from '@/utils/agentInstallCommand';
@@ -79,12 +79,10 @@ export const useInfrastructureOperationsState = (
const getUninstallCommand = (row?: AgentUninstallIdentity) => {
const url = installState.selectedAgentUrl();
- const token = resolvedCommandToken();
const agentId = getCanonicalUninstallAgentId(row);
const hostname = getCanonicalUninstallHostname(row);
return buildUnixAgentInstallCommand({
baseUrl: url,
- token,
insecure: installState.insecureMode(),
caCertPath: selectedCustomCaPath(),
extraArgs: [
@@ -96,24 +94,13 @@ export const useInfrastructureOperationsState = (
};
const getWindowsUninstallCommand = (row?: AgentUninstallIdentity) => {
- const url = installState.selectedAgentUrl();
- const token = resolvedCommandToken();
- const transportEnv = getPowerShellTransportEnv();
- const agentId = getCanonicalUninstallAgentId(row);
- const hostname = getCanonicalUninstallHostname(row);
- const identityEnv: string[] = [];
- if (agentId) {
- identityEnv.push(`$env:PULSE_AGENT_ID="${powerShellQuote(agentId)}"`);
- }
- if (hostname) {
- identityEnv.push(`$env:PULSE_HOSTNAME="${powerShellQuote(hostname)}"`);
- }
- const prefixParts = [...transportEnv, ...identityEnv];
- const prefix = prefixParts.length > 0 ? `${prefixParts.join('; ')}; ` : '';
- if (token) {
- return `${prefix}$env:PULSE_URL="${powerShellQuote(url)}"; $env:PULSE_TOKEN="${powerShellQuote(token)}"; $env:PULSE_UNINSTALL="true"; ${buildPowerShellInstallScriptBootstrap(url)}`;
- }
- return `${prefix}$env:PULSE_URL="${powerShellQuote(url)}"; $env:PULSE_UNINSTALL="true"; ${buildPowerShellInstallScriptBootstrap(url)}`;
+ return buildWindowsAgentUninstallCommand({
+ baseUrl: installState.selectedAgentUrl(),
+ insecure: installState.insecureMode(),
+ caCertPath: selectedCustomCaPath(),
+ agentId: getCanonicalUninstallAgentId(row),
+ hostname: getCanonicalUninstallHostname(row),
+ });
};
const getPlatformUninstallCommand = (platform: AgentPlatform, row?: AgentUninstallIdentity) => {
diff --git a/frontend-modern/src/utils/__tests__/agentInstallCommand.test.ts b/frontend-modern/src/utils/__tests__/agentInstallCommand.test.ts
index d1c9b53a88..843dbb0c26 100644
--- a/frontend-modern/src/utils/__tests__/agentInstallCommand.test.ts
+++ b/frontend-modern/src/utils/__tests__/agentInstallCommand.test.ts
@@ -12,9 +12,11 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
+import { unixBootstrapTestSource } from './unixBootstrapTestSource';
import {
buildUnixAgentInstallCommand,
buildWindowsAgentInstallCommand,
+ buildWindowsAgentUninstallCommand,
normalizeInstallerBaseUrl,
resolveAgentCommandPlatform,
resolveInstallerBaseUrl,
@@ -750,3 +752,149 @@ describe('credential-free Unix lifecycle execution', { timeout: 25_000 }, () =>
},
);
});
+
+describe('saved-credential uninstall commands', () => {
+ it.each(['unused-new-install-token', null])(
+ 'never asks for installation credentials (%s)',
+ (token) => {
+ const command = buildUnixAgentInstallCommand({
+ baseUrl: 'https://download.invalid',
+ token,
+ tokenFilePath: 'unused-relative-file',
+ extraArgs: ['--uninstall'],
+ });
+ const child = unixBootstrapTestSource(command);
+ expect(command).not.toContain('unused-new-install-token');
+ expect(command).not.toContain('unused-relative-file');
+ expect(command).not.toContain('Pulse agent token');
+ expect(command).not.toContain('--token');
+ expect(command).not.toContain('--url');
+ expect(command).not.toContain('--preflight-only');
+ expect(child).toContain(
+ 'unset PULSE_TOKEN PULSE_TOKEN_FILE PULSE_URL PULSE_AGENT_ID PULSE_HOSTNAME',
+ );
+ expect(command).toContain('https://download.invalid/install.sh');
+ },
+ );
+
+ it.each([0, 17])(
+ 'executes the actual Unix command without a terminal and retains installer exit %s',
+ (exit) => {
+ const dir = mkdtempSync(join(tmpdir(), 'pulse-uninstall-command-'));
+ const bin = join(dir, 'bin');
+ mkdirSync(bin);
+ try {
+ writeFileSync(join(bin, 'id'), '#!/bin/sh\nprintf 0\n', { mode: 0o700 });
+ writeFileSync(
+ join(bin, 'curl'),
+ `#!/bin/sh
+while [ "$#" -gt 0 ]; do
+ if [ "$1" = -o ]; then cp "$RECORDER" "$2"; exit 0; fi
+ shift
+done
+exit 31
+`,
+ { mode: 0o700 },
+ );
+ // Only a recorder is downloaded. No production installer or sudo runs.
+ const recorder = join(dir, 'recorder');
+ writeFileSync(
+ recorder,
+ `#!/bin/bash
+printf '%s\\n' "$@" > "$ARGV"
+printf '%s:%s:%s:%s:%s:%s:%s:%s' "\${PULSE_TOKEN-}" "\${PULSE_TOKEN_FILE-}" "\${PULSE_URL-}" "\${PULSE_AGENT_ID-}" "\${PULSE_HOSTNAME-}" "\${PULSE_INSECURE_SKIP_VERIFY-}" "\${PULSE_CACERT-}" "\${PULSE_SERVER_FINGERPRINT-}" > "$ENV_CAPTURE"
+exit "$EXPECTED_EXIT"
+`,
+ );
+ const command = buildUnixAgentInstallCommand({
+ baseUrl: 'https://download.invalid',
+ token: 'not-an-uninstall-credential',
+ caCertPath: '/explicit/ca.pem',
+ extraArgs: ['--uninstall', "--agent-id 'saved-id'", "--hostname 'saved.example'"],
+ });
+ const result = spawnSync('bash', ['-c', command], {
+ encoding: 'utf8',
+ timeout: 5000,
+ env: {
+ ...process.env,
+ PATH: `${bin}:${process.env.PATH}`,
+ RECORDER: recorder,
+ ARGV: join(dir, 'argv'),
+ ENV_CAPTURE: join(dir, 'environment'),
+ EXPECTED_EXIT: String(exit),
+ PULSE_TOKEN: 'ambient-install-secret',
+ PULSE_TOKEN_FILE: '/wrong/file',
+ PULSE_URL: 'https://wrong.invalid',
+ PULSE_AGENT_ID: 'wrong-id',
+ PULSE_HOSTNAME: 'wrong-host',
+ PULSE_INSECURE_SKIP_VERIFY: 'true',
+ PULSE_CACERT: '/wrong/ca',
+ PULSE_SERVER_FINGERPRINT: 'wrong-pin',
+ },
+ });
+ expect(result.status, result.stdout + result.stderr).toBe(exit);
+ expect(result.stdout + result.stderr).not.toContain('ambient-install-secret');
+ expect(readFileSync(join(dir, 'environment'), 'utf8')).toBe(':::::::');
+ expect(readFileSync(join(dir, 'argv'), 'utf8').trim().split('\n')).toEqual([
+ '--uninstall',
+ '--agent-id',
+ 'saved-id',
+ '--hostname',
+ 'saved.example',
+ '--non-interactive',
+ '--cacert',
+ '/explicit/ca.pem',
+ ]);
+ // The parent shell retains its inherited value; clearing is child-only.
+ const sentinel = execFileSync('bash', ['-c', command + '; printf %s "$PULSE_TOKEN"'], {
+ env: {
+ ...process.env,
+ PATH: `${bin}:${process.env.PATH}`,
+ RECORDER: recorder,
+ ARGV: join(dir, 'argv'),
+ ENV_CAPTURE: join(dir, 'environment'),
+ EXPECTED_EXIT: '0',
+ PULSE_TOKEN: 'parent-sentinel',
+ },
+ encoding: 'utf8',
+ timeout: 5000,
+ });
+ expect(sentinel).toBe('parent-sentinel');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it('Windows binds empty credential parameters and escaped identity without mutating environment', () => {
+ const command = buildWindowsAgentUninstallCommand({
+ baseUrl: 'https://download.invalid/',
+ agentId: "agent'$()",
+ hostname: "host'$name",
+ caCertPath: "C:\\trust\\host's.pem",
+ });
+ expect(command).toContain('https://download.invalid/install.ps1');
+ expect(command).toContain("-Uninstall $true -Url '' -Token '' -TokenFile ''");
+ expect(command).toContain("-AgentId 'agent''$()' -Hostname 'host''$name'");
+ expect(command).toContain(
+ "-Insecure $false -CACertPath 'C:\\trust\\host''s.pem' -ServerFingerprint ''",
+ );
+ expect(command).toContain("LoadCertificate('C:\\trust\\host''s.pem')");
+ expect(command).toContain('-PreflightOnly $false');
+ expect(command).not.toContain('$env:');
+ expect(command).not.toContain('\n');
+ expect(command).toContain('ForEach-Object { & ([scriptblock]::Create($_))');
+ });
+
+ it('HTTP download does not grant an insecure saved-server uninstall', () => {
+ expect(
+ buildUnixAgentInstallCommand({
+ baseUrl: 'http://download.invalid',
+ extraArgs: ['--uninstall'],
+ }),
+ ).not.toContain(' --insecure');
+ expect(buildWindowsAgentUninstallCommand({ baseUrl: 'http://download.invalid' })).toContain(
+ '-Insecure $false',
+ );
+ });
+});
diff --git a/frontend-modern/src/utils/agentInstallCommand.ts b/frontend-modern/src/utils/agentInstallCommand.ts
index e7a181c79e..c82158b381 100644
--- a/frontend-modern/src/utils/agentInstallCommand.ts
+++ b/frontend-modern/src/utils/agentInstallCommand.ts
@@ -147,13 +147,17 @@ export const buildUnixAgentInstallCommand = ({
throw new Error('Pulse install endpoint URL is required.');
}
const normalizedCaCertPath = (caCertPath || '').trim();
- const needsToken = Boolean((token || '').trim() || tokenFilePath?.trim());
- const normalizedTokenFilePath = (tokenFilePath || '').trim();
+ const normalizedExtraArgs = extraArgs.map((arg) => arg.trim()).filter((arg) => arg.length > 0);
+ const uninstall = normalizedExtraArgs.includes('--uninstall');
+ // Removal authenticates with the installed host's saved credential, never
+ // with a newly generated installation token (or its private-input prompt).
+ const needsToken = !uninstall && Boolean((token || '').trim() || tokenFilePath?.trim());
+ const normalizedTokenFilePath = uninstall ? '' : (tokenFilePath || '').trim();
if (normalizedTokenFilePath && !normalizedTokenFilePath.startsWith('/')) {
throw new Error('Pulse token file path must be absolute.');
}
- const normalizedExtraArgs = extraArgs.map((arg) => arg.trim()).filter((arg) => arg.length > 0);
- const installRequiresInsecure = insecure || normalizedBaseUrl.startsWith('http://');
+ const installRequiresInsecure =
+ insecure || (!uninstall && normalizedBaseUrl.startsWith('http://'));
const curlFlags = insecure ? '-kfsSL' : '-fsSL';
// Build shell grammar explicitly: command fields such as pfSense's remove
// pasted newlines. Never flatten a multiline script (or quoted user data).
@@ -173,7 +177,7 @@ export const buildUnixAgentInstallCommand = ({
'--non-interactive',
].join(' ');
const installArgs = [
- `--url ${shellQuoteArg(normalizedBaseUrl)}`,
+ ...(!uninstall ? [`--url ${shellQuoteArg(normalizedBaseUrl)}`] : []),
...(needsToken ? ['--token-file "$token_file"'] : []),
...normalizedExtraArgs,
'--non-interactive',
@@ -183,6 +187,13 @@ export const buildUnixAgentInstallCommand = ({
// the silent bounded read in the privileged child, not the caller's shell or
// sudo argv. A canonical line read silently truncates long pasted tokens.
const privileged = ['set +xv;', 'set -eu;', 'umask 077;'];
+ if (uninstall) {
+ // A previous pasted install must not shadow saved state. This runs only
+ // in the privileged child; the caller's environment is left unchanged.
+ privileged.push(
+ 'unset PULSE_TOKEN PULSE_TOKEN_FILE PULSE_URL PULSE_AGENT_ID PULSE_HOSTNAME PULSE_INSECURE_SKIP_VERIFY PULSE_CACERT PULSE_SERVER_FINGERPRINT;',
+ );
+ }
if (normalizedTokenFilePath) {
privileged.push(
`token_file=${shellQuoteArg(normalizedTokenFilePath)};`,
@@ -221,15 +232,17 @@ export const buildUnixAgentInstallCommand = ({
"trap cleanup EXIT; trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM;",
`curl ${curlFlags}${caCertArg} ${shellQuoteArg(`${normalizedBaseUrl}/install.sh`)} -o "$install_script";`,
// Detachment must not require a downloadable new agent binary.
- ...(!normalizedExtraArgs.includes('--uninstall')
- ? [`bash "$install_script" ${preflightArgs}${caCertArg}${insecureArg};`]
- : []),
+ ...(!uninstall ? [`bash "$install_script" ${preflightArgs}${caCertArg}${insecureArg};`] : []),
`if [ "$(id -u)" -eq 0 ]; then ${child} else sudo ${child} fi;`,
')',
].join(' ');
};
-export const buildPowerShellInstallScriptBootstrap = (baseUrl: string) => {
+const buildPowerShellInstallerDownload = (
+ baseUrl: string,
+ insecure = '$env:PULSE_INSECURE_SKIP_VERIFY -eq "true"',
+ caCertPath = '$env:PULSE_CACERT',
+) => {
const normalizedBaseUrl = normalizeInstallerBaseUrl(baseUrl);
if (!normalizedBaseUrl.trim()) {
throw new Error('Pulse install endpoint URL is required.');
@@ -237,25 +250,57 @@ export const buildPowerShellInstallScriptBootstrap = (baseUrl: string) => {
const scriptUrl = powerShellQuote(`${normalizedBaseUrl}/install.ps1`);
return (
`& { $pulseScriptUrl="${scriptUrl}"; ` +
- `if ($env:PULSE_INSECURE_SKIP_VERIFY -eq "true" -or -not [string]::IsNullOrWhiteSpace($env:PULSE_CACERT)) { ` +
+ `if (${insecure} -or -not [string]::IsNullOrWhiteSpace(${caCertPath})) { ` +
`${powerShellTlsValidatorBootstrap}` +
`$pulseCustomCa = $null; ` +
- `if (-not [string]::IsNullOrWhiteSpace($env:PULSE_CACERT)) { ` +
- `${powerShellLoadCustomCa('$env:PULSE_CACERT')}` +
+ `if (-not [string]::IsNullOrWhiteSpace(${caCertPath})) { ` +
+ `${powerShellLoadCustomCa(caCertPath)}` +
`}; ` +
`$pulsePrev = [System.Net.ServicePointManager]::ServerCertificateValidationCallback; ` +
`try { ` +
- `if ($env:PULSE_INSECURE_SKIP_VERIFY -eq "true") { ` +
+ `if (${insecure}) { ` +
`[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [PulseInstallerCertificateValidator]::AcceptAnyCallback ` +
`} else { ` +
`[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [PulseInstallerCertificateValidator]::ValidateCustomCaCallback ` +
`}; ` +
`irm $pulseScriptUrl ` +
`} finally { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $pulsePrev; [PulseInstallerCertificateValidator]::CustomCa = $null } ` +
- `} else { irm $pulseScriptUrl } } | iex`
+ `} else { irm $pulseScriptUrl } }`
);
};
+export const buildPowerShellInstallScriptBootstrap = (baseUrl: string) =>
+ `${buildPowerShellInstallerDownload(baseUrl)} | iex`;
+
+export const buildWindowsAgentUninstallCommand = ({
+ baseUrl,
+ insecure = false,
+ caCertPath,
+ agentId = '',
+ hostname = '',
+}: {
+ baseUrl: string;
+ insecure?: boolean;
+ caCertPath?: string | null;
+ agentId?: string;
+ hostname?: string;
+}) => {
+ const ca = powerShellSingleQuotedLiteral((caCertPath || '').trim());
+ const allowInsecure = insecure ? '$true' : '$false';
+ // Explicit empty parameters bypass ambient install credentials/identity and
+ // let install.ps1 recover its saved connection, token and trust. Download
+ // trust is separately bound to the selected endpoint, without changing env.
+ const args = [
+ '-Uninstall $true',
+ "-Url '' -Token '' -TokenFile ''",
+ `-AgentId ${powerShellSingleQuotedLiteral(agentId)}`,
+ `-Hostname ${powerShellSingleQuotedLiteral(hostname)}`,
+ `-Insecure ${allowInsecure} -CACertPath ${ca} -ServerFingerprint ''`,
+ "-PreflightOnly $false -Output '' -NonInteractive $true",
+ ];
+ return `${buildPowerShellInstallerDownload(baseUrl, allowInsecure, ca)} | ForEach-Object { & ([scriptblock]::Create($_)) ${args.join(' ')} }`;
+};
+
export const buildWindowsAgentInstallCommand = ({
baseUrl,
token,