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.

fix(relay): revoke only unused pairing tokens

rcourtmanf15c4be46b51
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d6a6a3c99b..7e720d05e4 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -121,6 +121,7 @@ management, and fleet control surfaces.
4. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
5. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
6. Add or change profile management, the extracted agent profiles runtime owner, the pure unified-agent inventory/install model, the direct Proxmox workspace shell, route model, reporting summary owner, shared install/inventory/dialog section owners, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners plus their shared model, shared frontend install-command assembly, Proxmox setup/install API transport, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureReportingPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInventorySection.tsx`, `frontend-modern/src/components/Settings/InfrastructureActiveRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureIgnoredRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx`, `frontend-modern/src/components/Settings/InfrastructureDirectConnectionsSummaryCard.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/ProxmoxSettingsPanel.tsx`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ProxmoxDirectWorkspace.tsx`, `frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx`, `frontend-modern/src/components/Settings/ProxmoxDirectConnectionsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDiscoveryResultsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDeleteNodeDialog.tsx`, `frontend-modern/src/components/Settings/ProxmoxNodeModalStack.tsx`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts`, `frontend-modern/src/components/Settings/NodeModal.tsx`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, `frontend-modern/src/components/Infrastructure/deploy/ResultsStep.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`.
+7. Preserve canonical token-lifecycle reads in shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows do not revoke a displayed relay pairing token after `lastUsedAt` proves that an already paired device is actively depending on that credential.
## Forbidden Paths
@@ -1230,3 +1231,10 @@ runtime boundary. The same shared resource boundary now also owns the bundled
facet history read path for timeline data, so fleet lifecycle surfaces that
open resource drawers must continue to consume the backend bundle instead of
reassembling a local multi-call summary.
+That same shared `internal/api/` extension-point boundary now also assumes
+canonical security-token lifecycle reads. Lifecycle-adjacent setup and install
+flows may inspect token metadata through the shared auth/security routes, but
+they must not assume a displayed relay pairing token is disposable once
+`lastUsedAt` is set. Shared helper changes that refresh, hide, or replace a
+pairing credential must preserve used-token continuity instead of deleting a
+credential that an already paired device still depends on.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2344d62b18..8ff3cb87df 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -54,6 +54,7 @@ Own canonical runtime payload shapes between backend and frontend.
31. `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`
32. `frontend-modern/src/utils/apiTokenPresentation.ts`
33. `frontend-modern/src/utils/infrastructureSettingsPresentation.ts`
+34. `internal/api/router_routes_auth_security.go`
## Shared Boundaries
@@ -1522,3 +1523,11 @@ when hosted auth handoff preserves a non-default tenant org like `t-...`,
instance-level hosted billing lease from `default` if that tenant org has no
org-local billing state of its own, rather than failing closed into
`subscription_required` on first entry.
+The shared security token contract now also includes single-record metadata
+reads. `internal/api/security_tokens.go`,
+`internal/api/router_routes_auth_security.go`,
+`frontend-modern/src/api/security.ts`, and
+`frontend-modern/src/types/api.ts` own the canonical `record.lastUsedAt` and
+`record.expiresAt` lookup shape for one token, and relay pairing surfaces must
+consume that same contract when deciding whether a displayed QR token can be
+revoked or must be preserved as an already-used device credential.
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 0af1e1cc68..2cc4419fcb 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -612,3 +612,10 @@ checkout provisioning: long-running `checkout.session.completed` tenant
provisioning must complete under an explicit background timeout instead of
depending on the inbound Stripe request context surviving long enough for first
boot and health polling.
+That same paid relay onboarding boundary now also owns QR-token lifecycle on
+the staged mobile rollout surface. `RelaySettingsPanel.tsx`,
+`RelayPairingSection.tsx`, and `useRelaySettingsPanelState.ts` may revoke a
+displayed pairing token only when canonical token metadata still shows no
+`lastUsedAt`; once a token has been used by a paired device, refreshing or
+hiding the QR must preserve that credential instead of treating it as
+disposable UI state.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 13ee5ff27a..7c075d700c 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -9,7 +9,9 @@
"contract_file": "docs/release-control/v6/internal/subsystems/security-privacy.md",
"status_file": "docs/release-control/v6/internal/status.json",
"registry_file": "docs/release-control/v6/internal/subsystems/registry.json",
- "dependency_subsystem_ids": []
+ "dependency_subsystem_ids": [
+ "api-contracts"
+ ]
}
```
@@ -43,6 +45,7 @@ token-management visibility, and privacy controls to operators.
20. `internal/api/security_tokens.go`
21. `internal/api/system_settings.go`
22. `internal/telemetry/telemetry.go`
+23. `internal/api/router_routes_auth_security.go`
## Shared Boundaries
@@ -272,3 +275,10 @@ posture derivation: `internal/ai/resource_context_policy_model.go` is now the
canonical owner for the policy-posture summary, local-only count, and
redaction-hint inputs that drive outbound AI context export decisions, so
`resource_context.go` does not duplicate trust-boundary policy assembly inline.
+That same shared token-settings boundary now also governs relay pairing token
+lifecycle. `internal/api/security_tokens.go`,
+`internal/api/router_routes_auth_security.go`, and
+`frontend-modern/src/api/security.ts` expose canonical single-token metadata
+reads, and the relay pairing UI may revoke a displayed token only when that
+metadata still shows no `lastUsedAt`. Refreshing or hiding a QR payload must
+not delete a token that an already paired device is actively depending on.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index e1774859f9..890e2698da 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -839,3 +839,10 @@ share the canonical trimmed-string utility instead of each surface rebuilding
route for timeline history and related change counts, so storage and recovery
surfaces must continue to consume the shared bundle rather than issuing
separate local resource-detail fetches.
+That same shared `internal/api/` dependency now also assumes canonical
+security-token lifecycle reads. Storage- and recovery-adjacent consumers of
+shared auth/security helpers may inspect token metadata, but they must not
+treat a displayed relay pairing token as disposable once canonical metadata
+shows `lastUsedAt`. Shared transport mutations must preserve used-token
+continuity instead of deleting a credential that an already paired device
+still depends on.
diff --git a/frontend-modern/src/api/__tests__/security.test.ts b/frontend-modern/src/api/__tests__/security.test.ts
index 8b09899140..7d97b7aff2 100644
--- a/frontend-modern/src/api/__tests__/security.test.ts
+++ b/frontend-modern/src/api/__tests__/security.test.ts
@@ -70,6 +70,27 @@ describe('SecurityAPI', () => {
});
});
+ describe('getToken', () => {
+ it('fetches a single token record', async () => {
+ const mockRecord: APITokenRecord = {
+ id: 't1',
+ name: 'Token 1',
+ prefix: 'pmp_',
+ suffix: 'abc',
+ createdAt: '',
+ lastUsedAt: '2026-03-24T12:00:00Z',
+ expiresAt: '2026-03-25T12:00:00Z',
+ ownerUserId: '[email protected]',
+ };
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({ record: mockRecord });
+
+ const result = await SecurityAPI.getToken('token/1');
+
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens/token%2F1');
+ expect(result).toEqual(mockRecord);
+ });
+ });
+
describe('createToken', () => {
it('creates token with name and scopes', async () => {
const mockResponse: CreateAPITokenResponse = {
diff --git a/frontend-modern/src/api/security.ts b/frontend-modern/src/api/security.ts
index 11e58d2bf7..f9f4b041f6 100644
--- a/frontend-modern/src/api/security.ts
+++ b/frontend-modern/src/api/security.ts
@@ -15,6 +15,13 @@ export class SecurityAPI {
return apiFetchJSON<SecurityStatus>('/api/security/status');
}
+ static async getToken(id: string): Promise<APITokenRecord> {
+ const response = await apiFetchJSON<{ record: APITokenRecord }>(
+ `/api/security/tokens/${encodeURIComponent(id)}`,
+ );
+ return response.record;
+ }
+
static async listTokens(): Promise<APITokenRecord[]> {
const response = await apiFetchJSON<{ tokens: APITokenRecord[] }>('/api/security/tokens');
return objectArrayFieldOrEmpty<APITokenRecord>(response, 'tokens');
diff --git a/frontend-modern/src/components/Settings/RelayPairingSection.tsx b/frontend-modern/src/components/Settings/RelayPairingSection.tsx
index ed6320a8f0..a08c803580 100644
--- a/frontend-modern/src/components/Settings/RelayPairingSection.tsx
+++ b/frontend-modern/src/components/Settings/RelayPairingSection.tsx
@@ -20,6 +20,7 @@ interface RelayPairingSectionProps {
saving: boolean;
showPairing: boolean;
onCopyPairingPayload: () => void;
+ onHidePairing: () => void;
onPairNewDevice: () => void;
}
@@ -41,13 +42,22 @@ export const RelayPairingSection: Component<RelayPairingSectionProps> = (props)
: 'Pair New Device'}
</button>
<Show when={props.showPairing && props.pairingPayload}>
- <button
- class={RELAY_SECONDARY_BUTTON_CLASS}
- onClick={props.onCopyPairingPayload}
- disabled={!props.canManage || props.pairingLoading}
- >
- Copy Payload
- </button>
+ <>
+ <button
+ class={RELAY_SECONDARY_BUTTON_CLASS}
+ onClick={props.onCopyPairingPayload}
+ disabled={!props.canManage || props.pairingLoading}
+ >
+ Copy Payload
+ </button>
+ <button
+ class={RELAY_SECONDARY_BUTTON_CLASS}
+ onClick={props.onHidePairing}
+ disabled={!props.canManage || props.pairingLoading}
+ >
+ Hide QR
+ </button>
+ </>
</Show>
</div>
diff --git a/frontend-modern/src/components/Settings/RelaySettingsPanel.tsx b/frontend-modern/src/components/Settings/RelaySettingsPanel.tsx
index b6cee12427..ecc578997a 100644
--- a/frontend-modern/src/components/Settings/RelaySettingsPanel.tsx
+++ b/frontend-modern/src/components/Settings/RelaySettingsPanel.tsx
@@ -199,6 +199,7 @@ export const RelaySettingsPanel: Component<RelaySettingsPanelProps> = (props) =>
saving={state.saving()}
showPairing={state.showPairing()}
onCopyPairingPayload={() => void state.handleCopyPairingPayload()}
+ onHidePairing={() => void state.handleHidePairing()}
onPairNewDevice={() => void state.handlePairNewDevice()}
/>
</Show>
diff --git a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx
index 12f628724a..d03c5cf0ec 100644
--- a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx
@@ -12,6 +12,7 @@ const updateRelayConfigMock = vi.fn();
const getQRPayloadMock = vi.fn();
const createTokenMock = vi.fn();
const deleteTokenMock = vi.fn();
+const getTokenMock = vi.fn();
const showSuccessMock = vi.fn();
const showErrorMock = vi.fn();
const loggerErrorMock = vi.fn();
@@ -45,6 +46,7 @@ vi.mock('@/api/security', () => ({
SecurityAPI: {
createToken: (...args: unknown[]) => createTokenMock(...args),
deleteToken: (...args: unknown[]) => deleteTokenMock(...args),
+ getToken: (...args: unknown[]) => getTokenMock(...args),
},
}));
@@ -80,6 +82,7 @@ describe('RelaySettingsPanel runtime', () => {
getQRPayloadMock.mockReset();
createTokenMock.mockReset();
deleteTokenMock.mockReset();
+ getTokenMock.mockReset();
showSuccessMock.mockReset();
showErrorMock.mockReset();
loggerErrorMock.mockReset();
@@ -110,6 +113,13 @@ describe('RelaySettingsPanel runtime', () => {
},
});
deleteTokenMock.mockResolvedValue(undefined);
+ getTokenMock.mockResolvedValue({
+ id: 'relay-token-1',
+ name: 'Relay mobile device 2026-03-12T00:00:00Z',
+ prefix: 'pmp_',
+ suffix: '1234',
+ createdAt: '',
+ });
getQRPayloadMock.mockResolvedValue({
schema: 'pulse-onboarding/v1',
instance_url: 'https://pulse.example.test',
@@ -268,8 +278,107 @@ describe('RelaySettingsPanel runtime', () => {
await waitFor(() => {
expect(screen.getByText('pulse://connect?instance_id=instance-local&auth_token=token-456')).toBeInTheDocument();
+ expect(getTokenMock).toHaveBeenCalledWith('relay-token-1');
+ expect(deleteTokenMock).toHaveBeenCalledWith('relay-token-1');
+ });
+ });
+
+ it('keeps a previously used pairing token when refreshing the QR code', async () => {
+ createTokenMock
+ .mockResolvedValueOnce({
+ token: 'token-123',
+ record: {
+ id: 'relay-token-1',
+ name: 'Relay mobile device first',
+ prefix: 'pmp_',
+ suffix: '1234',
+ createdAt: '',
+ },
+ })
+ .mockResolvedValueOnce({
+ token: 'token-456',
+ record: {
+ id: 'relay-token-2',
+ name: 'Relay mobile device second',
+ prefix: 'pmp_',
+ suffix: '5678',
+ createdAt: '',
+ },
+ });
+ getQRPayloadMock
+ .mockResolvedValueOnce({
+ schema: 'pulse-onboarding/v1',
+ instance_url: 'https://pulse.example.test',
+ relay: {
+ enabled: true,
+ url: 'wss://relay.example.test/ws/instance',
+ },
+ auth_token: 'token-123',
+ deep_link: 'pulse://connect?instance_id=instance-local&auth_token=token-123',
+ })
+ .mockResolvedValueOnce({
+ schema: 'pulse-onboarding/v1',
+ instance_url: 'https://pulse.example.test',
+ relay: {
+ enabled: true,
+ url: 'wss://relay.example.test/ws/instance',
+ },
+ auth_token: 'token-456',
+ deep_link: 'pulse://connect?instance_id=instance-local&auth_token=token-456',
+ });
+ getTokenMock
+ .mockResolvedValueOnce({
+ id: 'relay-token-1',
+ name: 'Relay mobile device first',
+ prefix: 'pmp_',
+ suffix: '1234',
+ createdAt: '',
+ lastUsedAt: '2026-03-24T12:00:00Z',
+ });
+
+ render(() => <RelaySettingsPanel canManage />);
+
+ await waitFor(() => {
+ expect(screen.getByDisplayValue('wss://relay.example.test/ws/instance')).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Pair New Device' }));
+
+ await waitFor(() => {
+ expect(screen.getByText('pulse://connect?instance_id=instance-local&auth_token=token-123')).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh QR Code' }));
+
+ await waitFor(() => {
+ expect(screen.getByText('pulse://connect?instance_id=instance-local&auth_token=token-456')).toBeInTheDocument();
+ expect(getTokenMock).toHaveBeenCalledWith('relay-token-1');
+ });
+
+ expect(deleteTokenMock).not.toHaveBeenCalledWith('relay-token-1');
+ });
+
+ it('hides the QR and deletes the displayed token only when it is still unused', async () => {
+ render(() => <RelaySettingsPanel canManage />);
+
+ await waitFor(() => {
+ expect(screen.getByDisplayValue('wss://relay.example.test/ws/instance')).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Pair New Device' }));
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Hide QR' })).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Hide QR' }));
+
+ await waitFor(() => {
+ expect(getTokenMock).toHaveBeenCalledWith('relay-token-1');
expect(deleteTokenMock).toHaveBeenCalledWith('relay-token-1');
});
+
+ expect(screen.queryByRole('button', { name: 'Hide QR' })).not.toBeInTheDocument();
});
it('keeps the previous QR code when refresh fails', async () => {
diff --git a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts
index 7fc8a871fe..91169f4dea 100644
--- a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts
+++ b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts
@@ -11,7 +11,7 @@ import { trackPaywallViewed } from '@/utils/upgradeMetrics';
import { showError, showSuccess } from '@/utils/toast';
import { RelayAPI, type RelayConfig, type RelayStatus } from '@/api/relay';
import { OnboardingAPI, type OnboardingQRResponse } from '@/api/onboarding';
-import { SecurityAPI } from '@/api/security';
+import { SecurityAPI, type APITokenRecord } from '@/api/security';
import { logger } from '@/utils/logger';
import { getRelayConnectionPresentation } from '@/utils/relayPresentation';
import QRCode from 'qrcode';
@@ -73,12 +73,38 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {
}
};
+ const getPairingTokenRecord = async (tokenID: string): Promise<APITokenRecord | null> => {
+ try {
+ return await SecurityAPI.getToken(tokenID);
+ } catch (error) {
+ const status = (error as { status?: number } | null)?.status;
+ if (status === 404) {
+ return null;
+ }
+ throw error;
+ }
+ };
+
+ const deletePairingTokenIfUnused = async (tokenID: string | null) => {
+ if (!tokenID) return;
+ try {
+ const record = await getPairingTokenRecord(tokenID);
+ if (!record || record.lastUsedAt) {
+ return;
+ }
+ await deletePairingToken(tokenID);
+ } catch (error) {
+ logger.warn('[RelaySettings] Failed to inspect relay pairing token lifecycle', error);
+ }
+ };
+
const loadConfig = async () => {
try {
const nextConfig = await RelayAPI.getConfig();
setConfig(nextConfig);
setServerUrl(nextConfig.server_url);
if (!nextConfig.enabled) {
+ await deletePairingTokenIfUnused(pairingTokenId());
resetPairingState();
}
} catch (error) {
@@ -124,6 +150,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {
onCleanup(() => {
stopStatusPolling();
+ void deletePairingTokenIfUnused(pairingTokenId());
});
const handleStartTrial = async () => {
@@ -160,6 +187,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {
} else {
stopStatusPolling();
setStatus(null);
+ await deletePairingTokenIfUnused(pairingTokenId());
resetPairingState();
showSuccess('Remote access disabled');
}
@@ -217,7 +245,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {
setPairingQRCode(qrCodeDataUrl);
setPairingTokenId(createdTokenId);
if (previousTokenId && previousTokenId !== createdTokenId) {
- await deletePairingToken(previousTokenId);
+ await deletePairingTokenIfUnused(previousTokenId);
}
} catch (error) {
await deletePairingToken(createdTokenId);
@@ -231,6 +259,11 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {
}
};
+ const handleHidePairing = async () => {
+ await deletePairingTokenIfUnused(pairingTokenId());
+ resetPairingState();
+ };
+
const handleCopyPairingPayload = async () => {
const payload = pairingPayload();
if (!payload) return;
@@ -251,6 +284,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {
config,
connectionPresentation,
handleCopyPairingPayload,
+ handleHidePairing,
handlePairNewDevice,
handleSaveServerUrl,
handleStartTrial,
diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.ts
index 0616f871c4..06003e1118 100644
--- a/frontend-modern/src/types/api.ts
+++ b/frontend-modern/src/types/api.ts
@@ -9,6 +9,7 @@ export interface APITokenRecord {
suffix: string;
createdAt: string;
lastUsedAt?: string;
+ expiresAt?: string;
scopes?: string[];
ownerUserId?: string;
}
diff --git a/internal/api/router_routes_auth_security.go b/internal/api/router_routes_auth_security.go
index cac5f11dae..2cf3b7eeba 100644
--- a/internal/api/router_routes_auth_security.go
+++ b/internal/api/router_routes_auth_security.go
@@ -140,6 +140,13 @@ func (r *Router) registerAuthSecurityInstallRoutes() {
}
}))
r.mux.HandleFunc("/api/security/tokens/", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {
+ if req.Method == http.MethodGet {
+ if !ensureSettingsReadScope(r.config, w, req) {
+ return
+ }
+ r.handleGetAPIToken(w, req)
+ return
+ }
if !ensureSettingsWriteScope(r.config, w, req) {
return
}
diff --git a/internal/api/security_tokens.go b/internal/api/security_tokens.go
index ee30f9ccd8..2dab69592f 100644
--- a/internal/api/security_tokens.go
+++ b/internal/api/security_tokens.go
@@ -150,6 +150,36 @@ func (r *Router) handleListAPITokens(w http.ResponseWriter, req *http.Request) {
})
}
+// handleGetAPIToken returns a single configured API token by ID (metadata only).
+func (r *Router) handleGetAPIToken(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ tokenID := strings.TrimSpace(strings.TrimPrefix(req.URL.Path, "/api/security/tokens/"))
+ if tokenID == "" || strings.Contains(tokenID, "/") {
+ http.Error(w, "Token ID required", http.StatusBadRequest)
+ return
+ }
+
+ config.Mu.RLock()
+ defer config.Mu.RUnlock()
+
+ for _, record := range r.config.APITokens {
+ if record.ID != tokenID {
+ continue
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "record": toAPITokenDTO(record),
+ })
+ return
+ }
+
+ http.Error(w, "Token not found", http.StatusNotFound)
+}
+
type createTokenRequest struct {
Name string `json:"name"`
Scopes *[]string `json:"scopes"`
diff --git a/internal/api/security_tokens_handlers_test.go b/internal/api/security_tokens_handlers_test.go
index 28a4e59d91..b837a8d7e9 100644
--- a/internal/api/security_tokens_handlers_test.go
+++ b/internal/api/security_tokens_handlers_test.go
@@ -91,6 +91,23 @@ func TestSecurityTokens_ListCreateDelete(t *testing.T) {
t.Fatalf("expected 1 token, got %d", len(listResp.Tokens))
}
+ req = httptest.NewRequest(http.MethodGet, "/api/security/tokens/"+createResp.Record.ID, nil)
+ rr = httptest.NewRecorder()
+ router.handleGetAPIToken(rr, req)
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)
+ }
+
+ var getResp struct {
+ Record apiTokenDTO `json:"record"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&getResp); err != nil {
+ t.Fatalf("decode get response: %v", err)
+ }
+ if getResp.Record.ID != createResp.Record.ID {
+ t.Fatalf("expected record id %q, got %q", createResp.Record.ID, getResp.Record.ID)
+ }
+
req = httptest.NewRequest(http.MethodDelete, "/api/security/tokens/", nil)
rr = httptest.NewRecorder()
router.handleDeleteAPIToken(rr, req)
@@ -105,6 +122,13 @@ func TestSecurityTokens_ListCreateDelete(t *testing.T) {
t.Fatalf("expected status %d, got %d", http.StatusNotFound, rr.Code)
}
+ req = httptest.NewRequest(http.MethodGet, "/api/security/tokens/missing", nil)
+ rr = httptest.NewRecorder()
+ router.handleGetAPIToken(rr, req)
+ if rr.Code != http.StatusNotFound {
+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rr.Code)
+ }
+
// Deleting an existing token should succeed.
record := config.APITokenRecord{
ID: "migrated",