Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix(relay): mint server-owned mobile access tokens
rcourtman3b6e48d5ce56
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 7e720d05e4..c37ea6fefe 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -122,6 +122,7 @@ management, and fleet control surfaces.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.+8. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows reuse the canonical mobile token route instead of reintroducing wildcard or browser-authored runtime token bundles.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 8ff3cb87df..61a9274d53 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -131,6 +131,7 @@ Own canonical runtime payload shapes between backend and frontend.10. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `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`, and `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`11. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.12. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.+13. Keep Pulse Mobile relay credential minting on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator, but browser callers must only consume that route and must not define the mobile runtime scope bundle or token-purpose metadata locally.## Forbidden Paths@@ -1530,4 +1531,8 @@ reads. `internal/api/security_tokens.go`,`frontend-modern/src/types/api.ts` own the canonical `record.lastUsedAt` and`record.expiresAt` lookup shape for one token, and relay pairing surfaces mustconsume that same contract when deciding whether a displayed QR token can be-revoked or must be preserved as an already-used device credential.+revoked or must be preserved as an already-used device credential. That same+contract now also owns backend-minted Pulse Mobile relay access tokens: the+server route, not the browser, defines the canonical mobile runtime scope+bundle and token-purpose metadata, and the pairing UI only consumes that+server-owned credential when requesting the onboarding payload.diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 2cc4419fcb..10ac629d28 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -482,11 +482,11 @@ dashboard shell, whileowns license readiness, relay status polling, snooze state, and trial startruntime. Future onboarding changes must extend that split instead of pullinglicense and relay runtime back into the card shell.-That relay pairing boundary now also includes ephemeral device-token lifecycle:-when the settings surface generates a mobile pairing QR, it must mint a fresh-scoped API token for that pairing attempt, fetch the onboarding payload through-that token context, and tear down superseded or failed pairing tokens instead-of accumulating long-lived hidden credentials.+That relay pairing boundary now also includes backend-owned mobile credential+lifecycle: when the settings surface generates a mobile pairing QR, it must ask+the server for a fresh scoped Pulse Mobile relay access token, fetch the+onboarding payload through that token context, and tear down superseded or+failed unused tokens instead of accumulating hidden credentials.That same pairing fetch path must stay token-bound instead of ambient-sessionbound: the onboarding QR request must carry the freshly minted relay pairingtoken explicitly so the returned payload reflects the exact credential that the@@ -496,15 +496,16 @@ The same flow must fail closed if the pairing payload omits the authenticatedrelay token state needed by the mobile deep link; pairing UI cannot silentlyrender a QR that bypasses governed auth ownership.Relay pairing token presentation is part of that same contract as well: the-settings surface must label those transient credentials distinctly from-long-lived automation tokens so operators can identify and revoke stale mobile-pairing attempts without guessing which credential was created for device-bootstrap.+settings surface must label those Pulse Mobile relay access credentials+distinctly from long-lived automation tokens so operators can identify and+revoke stale mobile devices or abandoned pairing attempts without guessing+which credential was created for mobile runtime access.Relay pairing refresh behavior is part of that lifecycle contract too: a-successful QR refresh must revoke the superseded pairing token once the new-token-backed payload is ready, while a failed refresh must revoke only the new-failed token and keep the previously valid QR visible instead of collapsing the-operator back to an empty pairing state.+successful QR refresh must revoke the superseded token once the new token-backed+payload is ready only if the superseded token still shows no device use, while+a failed refresh must revoke only the new failed token and keep the previously+valid QR visible instead of collapsing the operator back to an empty pairing+state.Hosted signup provisioning now follows the same rule. Changes to`internal/api/public_signup_handlers.go` and `internal/hosted/provisioner.go`must carry this contract and the dedicated hosted-signup provisioning proofdiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 7c075d700c..571239800f 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -279,6 +279,7 @@ That same shared token-settings boundary now also governs relay pairing tokenlifecycle. `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.+reads, expose the backend-owned Pulse Mobile relay access token creator, 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.mdindex 890e2698da..f98ca2091d 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -71,6 +71,7 @@ querying, and the operator-facing storage health presentation layer.14. Preserve canonical /api/auto-register DHCP continuity in those shared helpers so a PVE or PBS node that reruns registration from a new IP with the same canonical node name and deterministic Pulse-managed token identity updates in place instead of duplicating the inventory record.15. Preserve the governed root-or-sudo Unix wrapper in shared backend install-command helpers so storage- and recovery-adjacent transport surfaces do not inherit a stale raw `| bash -s --` install payload shape from the canonical agent-install-command API and hosted Proxmox install responses.16. Preserve optional-auth tokenless behavior in those same shared backend install-command helpers so adjacent transport surfaces do not implicitly persist API tokens and flip auth-configured state when an operator only requested a Proxmox install command on a token-optional Pulse instance.+17. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so storage- and recovery-adjacent transport surfaces do not inherit browser-authored wildcard token bundles when they depend on the canonical security helper layer.## Forbidden Pathsdiff --git a/frontend-modern/src/api/__tests__/security.test.ts b/frontend-modern/src/api/__tests__/security.test.tsindex 7d97b7aff2..4b26509480 100644--- a/frontend-modern/src/api/__tests__/security.test.ts+++ b/frontend-modern/src/api/__tests__/security.test.ts@@ -154,6 +154,35 @@ describe('SecurityAPI', () => {});});+ describe('createRelayMobileAccessToken', () => {+ it('creates a server-owned relay mobile runtime token', async () => {+ const mockResponse: CreateAPITokenResponse = {+ token: 'pmp_mobile',+ record: {+ id: 'relay-mobile-1',+ name: 'Pulse Mobile relay access 2026-03-24T23:30:00Z',+ prefix: 'pmp_',+ suffix: 'bile',+ createdAt: '',+ scopes: ['ai:chat', 'ai:execute'],+ ownerUserId: '[email protected]',+ },+ };+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockResponse);++ const result = await SecurityAPI.createRelayMobileAccessToken();++ expect(apiFetchJSON).toHaveBeenCalledWith(+ '/api/security/tokens/relay-mobile',+ expect.objectContaining({+ method: 'POST',+ body: JSON.stringify({}),+ }),+ );+ expect(result).toEqual(mockResponse);+ });+ });+describe('deleteToken', () => {it('deletes a token', async () => {vi.mocked(apiFetchJSON).mockResolvedValueOnce(undefined);diff --git a/frontend-modern/src/api/security.ts b/frontend-modern/src/api/security.tsindex f9f4b041f6..fa35cc630a 100644--- a/frontend-modern/src/api/security.ts+++ b/frontend-modern/src/api/security.ts@@ -42,6 +42,13 @@ export class SecurityAPI {});}+ static async createRelayMobileAccessToken(): Promise<CreateAPITokenResponse> {+ return apiFetchJSON<CreateAPITokenResponse>('/api/security/tokens/relay-mobile', {+ method: 'POST',+ body: JSON.stringify({}),+ });+ }+static async deleteToken(id: string): Promise<void> {await apiFetchJSON(`/api/security/tokens/${encodeURIComponent(id)}`, {method: 'DELETE',diff --git a/frontend-modern/src/components/Settings/RelayPairingSection.tsx b/frontend-modern/src/components/Settings/RelayPairingSection.tsxindex a08c803580..5441816188 100644--- a/frontend-modern/src/components/Settings/RelayPairingSection.tsx+++ b/frontend-modern/src/components/Settings/RelayPairingSection.tsx@@ -62,7 +62,7 @@ export const RelayPairingSection: Component<RelayPairingSectionProps> = (props)</div><p class={formHelpText}>- Generate a QR code for pairing during staged mobile beta rollout.+ Generate a QR code that provisions a dedicated Pulse Mobile relay access credential.</p><Show when={props.showPairing}>diff --git a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsxindex d03c5cf0ec..d048ef97f9 100644--- a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx@@ -44,7 +44,7 @@ vi.mock('@/api/onboarding', () => ({vi.mock('@/api/security', () => ({SecurityAPI: {- createToken: (...args: unknown[]) => createTokenMock(...args),+ createRelayMobileAccessToken: (...args: unknown[]) => createTokenMock(...args),deleteToken: (...args: unknown[]) => deleteTokenMock(...args),getToken: (...args: unknown[]) => getTokenMock(...args),},@@ -106,19 +106,21 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-123',record: {id: 'relay-token-1',- name: 'Relay mobile device 2026-03-12T00:00:00Z',+ name: 'Pulse Mobile relay access 2026-03-12T00:00:00Z',prefix: 'pmp_',suffix: '1234',createdAt: '',+ scopes: ['ai:chat', 'ai:execute'],},});deleteTokenMock.mockResolvedValue(undefined);getTokenMock.mockResolvedValue({id: 'relay-token-1',- name: 'Relay mobile device 2026-03-12T00:00:00Z',+ name: 'Pulse Mobile relay access 2026-03-12T00:00:00Z',prefix: 'pmp_',suffix: '1234',createdAt: '',+ scopes: ['ai:chat', 'ai:execute'],});getQRPayloadMock.mockResolvedValue({schema: 'pulse-onboarding/v1',@@ -159,6 +161,7 @@ describe('RelaySettingsPanel runtime', () => {await waitFor(() => {expect(createTokenMock).toHaveBeenCalledTimes(1);+ expect(createTokenMock).toHaveBeenCalledWith();expect(getQRPayloadMock).toHaveBeenCalledTimes(1);expect(getQRPayloadMock).toHaveBeenCalledWith('token-123');expect(qrToDataUrlMock).toHaveBeenCalledWith('pulse://connect?instance_id=instance-local', {@@ -224,7 +227,7 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-123',record: {id: 'relay-token-1',- name: 'Relay mobile device first',+ name: 'Pulse Mobile relay access first',prefix: 'pmp_',suffix: '1234',createdAt: '',@@ -234,7 +237,7 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-456',record: {id: 'relay-token-2',- name: 'Relay mobile device second',+ name: 'Pulse Mobile relay access second',prefix: 'pmp_',suffix: '5678',createdAt: '',@@ -289,7 +292,7 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-123',record: {id: 'relay-token-1',- name: 'Relay mobile device first',+ name: 'Pulse Mobile relay access first',prefix: 'pmp_',suffix: '1234',createdAt: '',@@ -299,7 +302,7 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-456',record: {id: 'relay-token-2',- name: 'Relay mobile device second',+ name: 'Pulse Mobile relay access second',prefix: 'pmp_',suffix: '5678',createdAt: '',@@ -329,7 +332,7 @@ describe('RelaySettingsPanel runtime', () => {getTokenMock.mockResolvedValueOnce({id: 'relay-token-1',- name: 'Relay mobile device first',+ name: 'Pulse Mobile relay access first',prefix: 'pmp_',suffix: '1234',createdAt: '',@@ -387,7 +390,7 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-123',record: {id: 'relay-token-1',- name: 'Relay mobile device first',+ name: 'Pulse Mobile relay access first',prefix: 'pmp_',suffix: '1234',createdAt: '',@@ -397,7 +400,7 @@ describe('RelaySettingsPanel runtime', () => {token: 'token-456',record: {id: 'relay-token-2',- name: 'Relay mobile device second',+ name: 'Pulse Mobile relay access second',prefix: 'pmp_',suffix: '5678',createdAt: '',diff --git a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.tsindex 91169f4dea..8d713e1a64 100644--- a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts+++ b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts@@ -20,10 +20,6 @@ export interface RelaySettingsPanelProps {canManage?: boolean;}-function buildRelayPairingTokenName(now: Date): string {- return `Relay mobile device ${now.toISOString()}`;-}-export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {const [config, setConfig] = createSignal<RelayConfig | null>(null);const [status, setStatus] = createSignal<RelayStatus | null>(null);@@ -226,7 +222,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {let createdTokenId: string | null = null;try {- const createdToken = await SecurityAPI.createToken(buildRelayPairingTokenName(new Date()));+ const createdToken = await SecurityAPI.createRelayMobileAccessToken();if (!createdToken.token) {throw new Error('Failed to generate relay device token');}diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex d81a066f02..a1282abba1 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -458,6 +458,7 @@ var allRouteAllowlist = []string{"/api/security/sso/providers/metadata/preview","/api/security/sso/providers","/api/security/sso/providers/",+ "/api/security/tokens/relay-mobile","/api/security/tokens","/api/security/tokens/","/api/security/status",diff --git a/internal/api/router_routes_auth_security.go b/internal/api/router_routes_auth_security.goindex 2cf3b7eeba..8cba45db50 100644--- a/internal/api/router_routes_auth_security.go+++ b/internal/api/router_routes_auth_security.go@@ -123,6 +123,12 @@ func (r *Router) registerAuthSecurityInstallRoutes() {}}))+ r.mux.HandleFunc("/api/security/tokens/relay-mobile", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {+ if !ensureSettingsWriteScope(r.config, w, req) {+ return+ }+ r.handleCreateRelayMobileAccessToken(w, req)+ }))r.mux.HandleFunc("/api/security/tokens", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {switch req.Method {case http.MethodGet:diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex c7c9861a32..449fd11931 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -2181,6 +2181,7 @@ func TestProxyAuthNonAdminDeniedAdminEndpoints(t *testing.T) {{method: http.MethodPost, path: "/api/system/settings/update", body: `{}`},{method: http.MethodPost, path: "/api/security/reset-lockout", body: `{}`},{method: http.MethodPost, path: "/api/security/apply-restart", body: `{}`},+ {method: http.MethodPost, path: "/api/security/tokens/relay-mobile", body: `{}`},{method: http.MethodGet, path: "/api/security/tokens", body: ``},{method: http.MethodDelete, path: "/api/security/tokens/token-1", body: ``},{method: http.MethodPost, path: "/api/security/regenerate-token", body: `{}`},@@ -2927,6 +2928,7 @@ func TestSecurityTokensWriteRequiresSettingsWriteScope(t *testing.T) {router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")paths := []string{+ "/api/security/tokens/relay-mobile","/api/security/tokens","/api/security/tokens/token-1",}@@ -3079,6 +3081,7 @@ func TestPermissionProtectedEndpointsDenyWhenAuthorizerBlocks(t *testing.T) {{method: http.MethodGet, path: "/api/admin/reports/generate", body: ""},{method: http.MethodPost, path: "/api/admin/reports/generate-multi", body: `{}`},{method: http.MethodGet, path: "/api/admin/webhooks/audit", body: ""},+ {method: http.MethodPost, path: "/api/security/tokens/relay-mobile", body: `{}`},{method: http.MethodGet, path: "/api/security/tokens", body: ""},{method: http.MethodDelete, path: "/api/security/tokens/token-1", body: ""},{method: http.MethodGet, path: "/api/settings/ai", body: ""},@@ -3216,6 +3219,7 @@ func TestPrivilegedSecurityEndpointsRejectNonAdminSession(t *testing.T) {{method: http.MethodPut, path: "/api/settings/relay", body: `{}`},{method: http.MethodGet, path: "/api/settings/ai", body: ``},{method: http.MethodGet, path: "/api/ai/cost/summary", body: ``},+ {method: http.MethodPost, path: "/api/security/tokens/relay-mobile", body: `{}`},{method: http.MethodGet, path: "/api/security/tokens", body: ``},{method: http.MethodDelete, path: "/api/security/tokens/token-1", body: ``},{method: http.MethodGet, path: "/api/security/sso/providers", body: ``},diff --git a/internal/api/security_tokens.go b/internal/api/security_tokens.goindex 2dab69592f..77061024ec 100644--- a/internal/api/security_tokens.go+++ b/internal/api/security_tokens.go@@ -27,6 +27,8 @@ type apiTokenDTO struct {}const apiTokenMetadataOwnerUserID = "owner_user_id"+const apiTokenMetadataPurpose = "purpose"+const apiTokenPurposeRelayMobileAccess = "relay_mobile_access"func apiTokenOwnerUserID(record config.APITokenRecord) string {if record.Metadata == nil {@@ -129,6 +131,88 @@ func canonicalizeRequestedScope(scope string) string {}}+func relayMobileAccessTokenScopes() []string {+ return []string{+ config.ScopeAIChat,+ config.ScopeAIExecute,+ }+}++func defaultRelayMobileAccessTokenName(now time.Time) string {+ return fmt.Sprintf("Pulse Mobile relay access %s", now.UTC().Format(time.RFC3339))+}++func (r *Router) createAPITokenRecord(+ req *http.Request,+ name string,+ scopes []string,+ expiresIn *string,+ metadata map[string]string,+) (string, *config.APITokenRecord, error) {+ if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {+ for _, requested := range scopes {+ if !callerToken.HasScope(requested) {+ return "", nil, fmt.Errorf("Cannot grant scope %q: your token does not have this scope", requested)+ }+ }+ }++ rawToken, err := internalauth.GenerateAPIToken()+ if err != nil {+ return "", nil, fmt.Errorf("generate raw token: %w", err)+ }++ record, err := config.NewAPITokenRecord(rawToken, name, scopes)+ if err != nil {+ return "", nil, fmt.Errorf("construct token record: %w", err)+ }+ record.OrgID = strings.TrimSpace(GetOrgID(req.Context()))+ if record.OrgID == "" {+ record.OrgID = "default"+ }+ if ownerUserID := apiTokenOwnerUserIDForRequest(r.config, req); ownerUserID != "" {+ if record.Metadata == nil {+ record.Metadata = make(map[string]string)+ }+ record.Metadata[apiTokenMetadataOwnerUserID] = ownerUserID+ }+ if len(metadata) > 0 {+ if record.Metadata == nil {+ record.Metadata = make(map[string]string)+ }+ for key, value := range metadata {+ record.Metadata[key] = value+ }+ }++ if expiresIn != nil && *expiresIn != "" {+ dur, err := time.ParseDuration(*expiresIn)+ if err != nil {+ return "", nil, fmt.Errorf("invalid expiresIn duration: %w", err)+ }+ if dur < time.Minute {+ return "", nil, fmt.Errorf("Token expiration must be at least 1 minute")+ }+ exp := time.Now().UTC().Add(dur)+ record.ExpiresAt = &exp+ }++ config.Mu.Lock()+ defer config.Mu.Unlock()++ r.config.APITokens = append(r.config.APITokens, *record)+ r.config.SortAPITokens()++ if r.persistence != nil {+ if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {+ r.config.APITokens = r.config.APITokens[:len(r.config.APITokens)-1]+ return "", nil, fmt.Errorf("persist token: %w", err)+ }+ }++ return rawToken, record, nil+}+// handleListAPITokens returns all configured API tokens (metadata only).func (r *Router) handleListAPITokens(w http.ResponseWriter, req *http.Request) {if req.Method != http.MethodGet {@@ -222,77 +306,28 @@ func (r *Router) handleCreateAPIToken(w http.ResponseWriter, req *http.Request)return}- // Scope escalation prevention: if the caller is an API token, the new token's- // scopes must be a subset of the caller's scopes. Session-based (browser) requests- // bypass this check since sessions have implicit full access.- if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {- for _, requested := range scopes {- if !callerToken.HasScope(requested) {- r.auditTokenEvent(req, "token_created", false,- fmt.Sprintf("Scope escalation denied: caller missing scope %q", requested))- http.Error(w, fmt.Sprintf("Cannot grant scope %q: your token does not have this scope", requested), http.StatusForbidden)- return- }- }- }-- rawToken, err := internalauth.GenerateAPIToken()+ rawToken, record, err := r.createAPITokenRecord(req, name, scopes, payload.ExpiresIn, nil)if err != nil {- r.auditTokenEvent(req, "token_created", false, "Failed to generate API token")- log.Error().Err(err).Msg("Failed to generate API token")- http.Error(w, "Failed to generate token", http.StatusInternalServerError)- return- }-- record, err := config.NewAPITokenRecord(rawToken, name, scopes)- if err != nil {- r.auditTokenEvent(req, "token_created", false, "Failed to construct API token record")- log.Error().Err(err).Str("token_name", name).Msg("Failed to construct API token record")- http.Error(w, "Failed to generate token", http.StatusInternalServerError)- return- }- record.OrgID = strings.TrimSpace(GetOrgID(req.Context()))- if record.OrgID == "" {- record.OrgID = "default"- }- if ownerUserID := apiTokenOwnerUserIDForRequest(r.config, req); ownerUserID != "" {- if record.Metadata == nil {- record.Metadata = make(map[string]string)- }- record.Metadata[apiTokenMetadataOwnerUserID] = ownerUserID- }-- if payload.ExpiresIn != nil && *payload.ExpiresIn != "" {- dur, err := time.ParseDuration(*payload.ExpiresIn)- if err != nil {+ switch {+ case strings.HasPrefix(err.Error(), "Cannot grant scope "):+ r.auditTokenEvent(req, "token_created", false, "Scope escalation denied for token creation")+ http.Error(w, err.Error(), http.StatusForbidden)+ case strings.HasPrefix(err.Error(), "invalid expiresIn duration: "):r.auditTokenEvent(req, "token_created", false, "Invalid token expiration duration")- http.Error(w, "Invalid expiresIn duration: "+err.Error(), http.StatusBadRequest)- return- }- if dur < time.Minute {+ http.Error(w, "Invalid expiresIn duration: "+strings.TrimPrefix(err.Error(), "invalid expiresIn duration: "), http.StatusBadRequest)+ case err.Error() == "Token expiration must be at least 1 minute":r.auditTokenEvent(req, "token_created", false, "Token expiration duration below minimum")- http.Error(w, "Token expiration must be at least 1 minute", http.StatusBadRequest)- return- }- exp := time.Now().UTC().Add(dur)- record.ExpiresAt = &exp- }-- config.Mu.Lock()- defer config.Mu.Unlock()-- r.config.APITokens = append(r.config.APITokens, *record)- r.config.SortAPITokens()-- if r.persistence != nil {- if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {- // Rollback the in-memory addition- r.config.APITokens = r.config.APITokens[:len(r.config.APITokens)-1]+ http.Error(w, err.Error(), http.StatusBadRequest)+ case strings.HasPrefix(err.Error(), "persist token: "):r.auditTokenEvent(req, "token_created", false, "Failed to persist API token")log.Error().Err(err).Msg("Failed to persist API tokens after creation")http.Error(w, "Failed to save token", http.StatusInternalServerError)- return+ default:+ r.auditTokenEvent(req, "token_created", false, "Failed to generate API token")+ log.Error().Err(err).Str("token_name", name).Msg("Failed to construct API token record")+ http.Error(w, "Failed to generate token", http.StatusInternalServerError)}+ return}r.auditTokenEvent(req, "token_created", true, fmt.Sprintf("Created API token id=%s scopes=%s", record.ID, strings.Join(record.Scopes, ",")))@@ -311,6 +346,53 @@ func (r *Router) handleCreateAPIToken(w http.ResponseWriter, req *http.Request)})}+// handleCreateRelayMobileAccessToken generates the canonical Pulse Mobile relay runtime token.+func (r *Router) handleCreateRelayMobileAccessToken(w http.ResponseWriter, req *http.Request) {+ if req.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ rawToken, record, err := r.createAPITokenRecord(+ req,+ defaultRelayMobileAccessTokenName(time.Now().UTC()),+ relayMobileAccessTokenScopes(),+ nil,+ map[string]string{apiTokenMetadataPurpose: apiTokenPurposeRelayMobileAccess},+ )+ if err != nil {+ switch {+ case strings.HasPrefix(err.Error(), "Cannot grant scope "):+ r.auditTokenEvent(req, "token_created", false, "Relay mobile scope escalation denied")+ http.Error(w, err.Error(), http.StatusForbidden)+ case strings.HasPrefix(err.Error(), "persist token: "):+ r.auditTokenEvent(req, "token_created", false, "Failed to persist relay mobile access token")+ log.Error().Err(err).Msg("Failed to persist relay mobile access token")+ http.Error(w, "Failed to save token", http.StatusInternalServerError)+ default:+ r.auditTokenEvent(req, "token_created", false, "Failed to generate relay mobile access token")+ log.Error().Err(err).Msg("Failed to generate relay mobile access token")+ http.Error(w, "Failed to generate token", http.StatusInternalServerError)+ }+ return+ }++ r.auditTokenEvent(req, "token_created", true, fmt.Sprintf("Created relay mobile access token id=%s scopes=%s", record.ID, strings.Join(record.Scopes, ",")))++ log.Info().+ Str("audit_event", "token_created").+ Str("token_id", record.ID).+ Str("token_name", record.Name).+ Str("client_ip", req.RemoteAddr).+ Msg("Relay mobile access token created")++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "token": rawToken,+ "record": toAPITokenDTO(*record),+ })+}+// handleDeleteAPIToken removes an API token by ID.func (r *Router) handleDeleteAPIToken(w http.ResponseWriter, req *http.Request) {if req.Method != http.MethodDelete {diff --git a/internal/api/security_tokens_handlers_test.go b/internal/api/security_tokens_handlers_test.goindex b837a8d7e9..c0e07d48b0 100644--- a/internal/api/security_tokens_handlers_test.go+++ b/internal/api/security_tokens_handlers_test.go@@ -239,6 +239,53 @@ func TestSecurityTokens_Create_WithInvalidExpiresIn(t *testing.T) {}}+func TestSecurityTokens_CreateRelayMobileAccessToken(t *testing.T) {+ cfg := &config.Config{}+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{+ config: cfg,+ persistence: persistence,+ }++ req := httptest.NewRequest(http.MethodPost, "/api/security/tokens/relay-mobile", nil)+ req = req.WithContext(authpkg.WithUser(req.Context(), "alice"))+ rr := httptest.NewRecorder()+ router.handleCreateRelayMobileAccessToken(rr, req)++ if rr.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)+ }++ var createResp struct {+ Token string `json:"token"`+ Record apiTokenDTO `json:"record"`+ }+ if err := json.NewDecoder(rr.Body).Decode(&createResp); err != nil {+ t.Fatalf("decode create response: %v", err)+ }+ if createResp.Token == "" {+ t.Fatal("expected raw token in response")+ }+ if !strings.HasPrefix(createResp.Record.Name, "Pulse Mobile relay access ") {+ t.Fatalf("unexpected relay mobile token name %q", createResp.Record.Name)+ }+ wantScopes := []string{config.ScopeAIChat, config.ScopeAIExecute}+ if len(createResp.Record.Scopes) != len(wantScopes) {+ t.Fatalf("relay mobile scopes length = %d, want %d", len(createResp.Record.Scopes), len(wantScopes))+ }+ for i, scope := range wantScopes {+ if createResp.Record.Scopes[i] != scope {+ t.Fatalf("relay mobile scope[%d] = %q, want %q", i, createResp.Record.Scopes[i], scope)+ }+ }+ if got := cfg.APITokens[0].Metadata[apiTokenMetadataPurpose]; got != apiTokenPurposeRelayMobileAccess {+ t.Fatalf("relay mobile token purpose metadata = %q, want %q", got, apiTokenPurposeRelayMobileAccess)+ }+ if got := cfg.APITokens[0].Metadata[apiTokenMetadataOwnerUserID]; got != "alice" {+ t.Fatalf("relay mobile owner user metadata = %q, want alice", got)+ }+}+func TestSecurityTokens_Create_BindsTokenToRequestOrg(t *testing.T) {cfg := &config.Config{}persistence := config.NewConfigPersistence(t.TempDir())