Skip to content

The agent that grows with you

fix(desktop): enforce exact route identity authority

Andrex Ibiza, MBA38ce2d7553c4
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index d357597a019..4b215bfeda3 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -82,11 +82,21 @@ test('resolvedConnectionId identifies local and migrated remote descriptors', ()
resolvedConnectionId(registry, {
baseUrl: 'http://127.0.0.1:49152',
mode: 'remote',
- remoteHost: 'root@work-host',
+ remoteHost: 'ROOT@WORK-HOST',
remoteKind: 'ssh'
}),
work?.id
)
+
+ const ambiguousLocal: ConnectionRegistry = {
+ ...registry,
+ connections: [
+ ...registry.connections,
+ { id: 'local-copy', kind: 'local', label: 'Local copy' }
+ ]
+ }
+
+ assert.equal(resolvedConnectionId(ambiguousLocal, { mode: 'local' }), null)
})
test('resolvedConnectionId does not guess an unregistered remote', () => {
@@ -107,6 +117,297 @@ test('agentHandle bare when unique, @name-device shape when duplicated', () => {
assert.equal(agentHandle('', 'Homelab', false), 'default')
})
+test('resolvedConnectionId accepts only a current exact descriptor id and never falls back', () => {
+ const registry: ConnectionRegistry = {
+ version: REGISTRY_VERSION,
+ primary: 'remote-a',
+ launchMode: 'primary',
+ lastUsed: 'remote-a',
+ connections: [
+ { id: LOCAL_CONNECTION_ID, kind: 'local', label: 'This device' },
+ {
+ id: 'remote-a',
+ kind: 'remote',
+ label: 'Remote A',
+ url: 'https://shared.example',
+ authMode: 'token',
+ token: { encoding: 'safeStorage', value: 'token-a' },
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-a' } }
+ },
+ {
+ id: 'remote-b',
+ kind: 'remote',
+ label: 'Remote B',
+ url: 'https://shared.example',
+ authMode: 'oauth',
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-b' } }
+ }
+ ]
+ }
+
+ assert.equal(
+ resolvedConnectionId(registry, {
+ authMode: 'token',
+ baseUrl: 'https://shared.example',
+ connectionId: 'remote-b',
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-a' } },
+ mode: 'remote',
+ remoteKind: 'url',
+ token: { encoding: 'safeStorage', value: 'token-a' }
+ }),
+ 'remote-b'
+ )
+
+ const inferableRemoteA = {
+ authMode: 'token',
+ baseUrl: 'https://shared.example',
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-a' } },
+ mode: 'remote' as const,
+ remoteKind: 'url' as const,
+ token: { encoding: 'safeStorage', value: 'token-a' }
+ }
+
+ // Only true absence enters compatibility inference. Every explicitly
+ // present invalid value remains unresolved even though the remaining
+ // envelope uniquely identifies remote-a.
+ assert.equal(resolvedConnectionId(registry, inferableRemoteA), 'remote-a')
+
+ for (const connectionId of ['', ' ', null, undefined, 42, {}, 'unknown-source', 'retired-source']) {
+ assert.equal(resolvedConnectionId(registry, { ...inferableRemoteA, connectionId }), null)
+ }
+
+ // Registry order is never authority for either an exact current id or a
+ // rejected explicit claim.
+ const reordered = { ...registry, connections: [...registry.connections].reverse() }
+
+ assert.equal(
+ resolvedConnectionId(reordered, {
+ ...inferableRemoteA,
+ connectionId: 'remote-b'
+ }),
+ 'remote-b'
+ )
+ assert.equal(resolvedConnectionId(reordered, { ...inferableRemoteA, connectionId: 'retired-source' }), null)
+})
+
+test('resolvedConnectionId reuses the exact URL envelope and rejects weak or duplicate matches', () => {
+ const sharedUrl = 'https://shared.example/gateway'
+
+ const registry: ConnectionRegistry = {
+ version: REGISTRY_VERSION,
+ primary: 'remote-token',
+ launchMode: 'primary',
+ lastUsed: 'remote-token',
+ connections: [
+ { id: LOCAL_CONNECTION_ID, kind: 'local', label: 'This device' },
+ {
+ id: 'remote-token',
+ kind: 'remote',
+ label: 'Token remote',
+ url: sharedUrl,
+ authMode: 'token',
+ token: { encoding: 'safeStorage', value: 'token-a' },
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-a' } }
+ },
+ {
+ id: 'remote-oauth',
+ kind: 'remote',
+ label: 'OAuth remote',
+ url: `${sharedUrl}/`,
+ authMode: 'oauth',
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-b' } }
+ },
+ {
+ id: 'cloud-nous',
+ kind: 'cloud',
+ label: 'Nous cloud',
+ url: sharedUrl,
+ authMode: 'oauth',
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-cloud' } },
+ org: 'nous'
+ },
+ {
+ id: 'cloud-labs',
+ kind: 'cloud',
+ label: 'Labs cloud',
+ url: sharedUrl,
+ authMode: 'oauth',
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-cloud' } },
+ org: 'labs'
+ }
+ ]
+ }
+
+ assert.equal(
+ resolvedConnectionId(registry, {
+ authMode: 'token',
+ baseUrl: sharedUrl,
+ headers: { 'cf-access-client-id': { encoding: 'safeStorage', value: 'header-a' } },
+ mode: 'remote',
+ remoteKind: 'url',
+ token: { encoding: 'safeStorage', value: 'token-a' }
+ }),
+ 'remote-token'
+ )
+ assert.equal(
+ resolvedConnectionId(registry, {
+ authMode: 'oauth',
+ baseUrl: sharedUrl,
+ headers: { 'CF-ACCESS-CLIENT-ID': { encoding: 'safeStorage', value: 'header-b' } },
+ mode: 'remote',
+ remoteKind: 'url'
+ }),
+ 'remote-oauth'
+ )
+ assert.equal(
+ resolvedConnectionId(registry, {
+ authMode: 'oauth',
+ baseUrl: sharedUrl,
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-cloud' } },
+ mode: 'remote',
+ org: 'nous',
+ remoteKind: 'cloud'
+ }),
+ 'cloud-nous'
+ )
+ assert.equal(
+ resolvedConnectionId(registry, {
+ authMode: 'oauth',
+ baseUrl: sharedUrl,
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-cloud' } },
+ mode: 'remote',
+ org: 'labs',
+ remoteKind: 'cloud'
+ }),
+ 'cloud-labs'
+ )
+
+ // Post-dial URL-only shapes do not contain enough proof to choose a source.
+ assert.equal(
+ resolvedConnectionId(registry, { baseUrl: sharedUrl, mode: 'remote', remoteKind: 'url' }),
+ null
+ )
+ assert.equal(
+ resolvedConnectionId(registry, { baseUrl: sharedUrl, mode: 'remote', remoteKind: 'cloud' }),
+ null
+ )
+
+ // Even a complete envelope fails closed when two registrations are exact twins.
+ const duplicate: ConnectionRegistry = {
+ ...registry,
+ connections: [
+ ...registry.connections,
+ { ...registry.connections.find(connection => connection.id === 'remote-token')!, id: 'remote-token-copy' }
+ ]
+ }
+
+ assert.equal(
+ resolvedConnectionId(duplicate, {
+ authMode: 'token',
+ baseUrl: sharedUrl,
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-a' } },
+ mode: 'remote',
+ remoteKind: 'url',
+ token: { encoding: 'safeStorage', value: 'token-a' }
+ }),
+ null
+ )
+ assert.equal(
+ resolvedConnectionId(
+ { ...duplicate, connections: [...duplicate.connections].reverse() },
+ {
+ authMode: 'token',
+ baseUrl: sharedUrl,
+ headers: { 'CF-Access-Client-Id': { encoding: 'safeStorage', value: 'header-a' } },
+ mode: 'remote',
+ remoteKind: 'url',
+ token: { encoding: 'safeStorage', value: 'token-a' }
+ }
+ ),
+ null
+ )
+})
+
+test('resolvedConnectionId keeps same-host SSH routes distinct by port, key, path, and profile', () => {
+ const base = {
+ host: 'work-host',
+ keyPath: '/keys/a',
+ kind: 'ssh' as const,
+ remoteHermesPath: '/srv/hermes',
+ remoteProfile: 'alpha',
+ user: 'root'
+ }
+
+ const registry: ConnectionRegistry = {
+ version: REGISTRY_VERSION,
+ primary: 'ssh-base',
+ launchMode: 'primary',
+ lastUsed: 'ssh-base',
+ connections: [
+ { id: LOCAL_CONNECTION_ID, kind: 'local', label: 'This device' },
+ { ...base, id: 'ssh-base', label: 'SSH base' },
+ { ...base, id: 'ssh-port', label: 'SSH port', port: 2222 },
+ { ...base, id: 'ssh-key', keyPath: '/keys/b', label: 'SSH key' },
+ { ...base, id: 'ssh-path', label: 'SSH path', remoteHermesPath: '/opt/hermes' },
+ { ...base, id: 'ssh-profile', label: 'SSH profile', remoteProfile: 'beta' }
+ ]
+ }
+
+ const resolve = (ssh: NonNullable<Parameters<typeof resolvedConnectionId>[1]['ssh']>) =>
+ resolvedConnectionId(registry, { mode: 'remote', remoteKind: 'ssh', ssh })
+
+ assert.equal(resolve(base), 'ssh-base')
+ assert.equal(resolve({ ...base, port: 2222 }), 'ssh-port')
+ assert.equal(resolve({ ...base, keyPath: '/keys/b' }), 'ssh-key')
+ assert.equal(resolve({ ...base, remoteHermesPath: '/opt/hermes' }), 'ssh-path')
+ assert.equal(resolve({ ...base, remoteProfile: 'beta' }), 'ssh-profile')
+ assert.equal(
+ resolvedConnectionId(registry, {
+ connectionId: 'ssh-port',
+ mode: 'remote',
+ remoteKind: 'ssh',
+ ssh: { ...base, port: 9999 }
+ }),
+ 'ssh-port'
+ )
+
+ // user@host is a transport hint, not a registry identity, when variants coexist.
+ assert.equal(
+ resolvedConnectionId(registry, {
+ mode: 'remote',
+ remoteHost: 'ROOT@WORK-HOST',
+ remoteKind: 'ssh'
+ }),
+ null
+ )
+ assert.equal(
+ resolvedConnectionId(registry, {
+ mode: 'remote',
+ remoteHost: 'ROOT@WORK-HOST',
+ remoteKind: 'ssh',
+ ssh: undefined
+ }),
+ null
+ )
+
+ const duplicate: ConnectionRegistry = {
+ ...registry,
+ connections: [...registry.connections, { ...base, id: 'ssh-base-copy', label: 'SSH base copy' }]
+ }
+
+ assert.equal(
+ resolvedConnectionId(duplicate, { mode: 'remote', remoteKind: 'ssh', ssh: base }),
+ null
+ )
+ assert.equal(
+ resolvedConnectionId(
+ { ...duplicate, connections: [...duplicate.connections].reverse() },
+ { mode: 'remote', remoteKind: 'ssh', ssh: base }
+ ),
+ null
+ )
+})
+
test('connectionIdForLabel suffixes on collision and never mints "local"', () => {
assert.equal(connectionIdForLabel('Homelab', []), 'homelab')
assert.equal(connectionIdForLabel('Homelab', ['homelab']), 'homelab-2')
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index cec23fea90c..c2e8edd672d 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -35,6 +35,7 @@ import {
normalizeSshConfig,
normAuthMode
} from './connection-config'
+import { matchingConnectionId, type StoredRoute } from './connection-route-identity'
export const REGISTRY_VERSION = 2
@@ -183,24 +184,63 @@ export interface RegistryLocalRoute {
poolKey: string
}
+export interface ResolvedConnectionSshDescriptor {
+ host?: string
+ keyPath?: string
+ port?: number
+ remoteHermesPath?: string
+ remoteProfile?: string
+ user?: string
+}
+
export interface ResolvedConnectionDescriptor {
+ authMode?: unknown
baseUrl?: string
+ /** Property presence means this descriptor claims registry qualification.
+ * Invalid or retired claims fail closed; only descriptors with no such
+ * property may enter the legacy compatibility resolver. */
+ connectionId?: unknown
+ headers?: Record<string, unknown>
mode?: 'local' | 'remote'
+ org?: unknown
remoteHost?: string
remoteKind?: 'cloud' | 'ssh' | 'url'
+ ssh?: ResolvedConnectionSshDescriptor
+ token?: unknown
}
/**
* Recover registry identity for a descriptor resolved through the legacy v1
- * profile path. Registry-scoped routes already carry `connectionId`; this
- * bridge keeps migrated per-profile remotes truthful until v1 is retired.
+ * profile path. Registry-scoped routes already carry `connectionId`; that
+ * exact identity is authoritative only while it names a current registry
+ * entry. Only genuinely unqualified descriptors may use compatibility
+ * inference, which keeps migrated per-profile remotes truthful until v1 is
+ * retired without letting malformed qualification fall through to a weaker
+ * endpoint-shaped identity.
*/
export function resolvedConnectionId(
registry: ConnectionRegistry,
descriptor: ResolvedConnectionDescriptor
): null | string {
+ if (Object.prototype.hasOwnProperty.call(descriptor, 'connectionId')) {
+ const explicitConnectionId = descriptor.connectionId
+
+ // Presence is authoritative even when the value is unusable. Never turn
+ // a malformed, blank, unknown, or retired registry claim into permission
+ // to infer a different source from mutable endpoint metadata.
+ if (typeof explicitConnectionId !== 'string' || !explicitConnectionId.trim()) {
+ return null
+ }
+
+ return registry.connections.some(connection => connection.id === explicitConnectionId)
+ ? explicitConnectionId
+ : null
+ }
+
if (descriptor.mode === 'local') {
- return registry.connections.find(connection => connection.kind === 'local')?.id ?? null
+ const localConnections = registry.connections.filter(connection => connection.kind === 'local')
+
+ return localConnections.length === 1 ? localConnections[0].id : null
}
if (descriptor.mode !== 'remote') {
@@ -208,52 +248,113 @@ export function resolvedConnectionId(
}
if (descriptor.remoteKind === 'ssh') {
- const remoteHost = String(descriptor.remoteHost || '')
- .trim()
- .toLowerCase()
+ if (Object.prototype.hasOwnProperty.call(descriptor, 'ssh')) {
+ if (!descriptor.ssh || typeof descriptor.ssh !== 'object') {
+ return null
+ }
- if (!remoteHost) {
- return null
+ return matchingConnectionId(registry, { ...descriptor.ssh, kind: 'ssh' }, 'unique') ?? null
}
- return (
- registry.connections.find(connection => {
- if (connection.kind !== 'ssh') {
- return false
- }
+ // Old descriptors expose only user@host after the tunnel has discarded
+ // port/key/path/profile. That weak shape is compatible only when exactly
+ // one registered SSH source even shares the target, and the defaulted
+ // route still satisfies the canonical #88922 full-envelope matcher.
+ const ssh = normalizeSshConfig({ mode: 'ssh', host: descriptor.remoteHost })
- const host = String(connection.host || '')
- .trim()
- .toLowerCase()
+ if (!ssh) {
+ return null
+ }
- const target = connection.user ? `${String(connection.user).trim().toLowerCase()}@${host}` : host
+ const target = normalizedSshTarget(ssh)
- return target === remoteHost
- })?.id ?? null
+ const coarseMatches = registry.connections.filter(
+ connection => connection.kind === 'ssh' && normalizedSshTarget(connection) === target
)
+
+ if (!target || coarseMatches.length !== 1) {
+ return null
+ }
+
+ return matchingConnectionId(registry, { kind: 'ssh', ...ssh }, 'unique') ?? null
}
- let baseUrl = ''
+ const kind = descriptor.remoteKind === 'cloud' ? 'cloud' : descriptor.remoteKind === 'url' ? 'remote' : null
+
+ if (!kind) {
+ return null
+ }
+
+ let url = ''
try {
- baseUrl = normalizeRemoteBaseUrl(descriptor.baseUrl)
+ url = normalizeRemoteBaseUrl(descriptor.baseUrl)
} catch {
return null
}
- return (
- registry.connections.find(connection => {
- if (connection.kind !== 'cloud' && connection.kind !== 'remote') {
+ const authMode = normAuthMode(descriptor.authMode)
+
+ const route: StoredRoute = {
+ authMode,
+ headers: descriptor.headers,
+ kind,
+ org: descriptor.org,
+ token: descriptor.token,
+ url
+ }
+
+ const hasExactEnvelope =
+ Object.prototype.hasOwnProperty.call(descriptor, 'authMode') &&
+ Object.prototype.hasOwnProperty.call(descriptor, 'headers') &&
+ (authMode === 'oauth' || Object.prototype.hasOwnProperty.call(descriptor, 'token')) &&
+ (kind === 'remote' || Object.prototype.hasOwnProperty.call(descriptor, 'org'))
+
+ if (!hasExactEnvelope) {
+ // A URL alone cannot choose among legal registrations that differ by auth,
+ // headers, Cloud organization, or account. Require one coarse candidate
+ // before the same full-envelope matcher is allowed to accept the legacy
+ // defaults; otherwise zero/multiple candidates fail closed.
+ const coarseMatches = registry.connections.filter(connection => {
+ if (connection.kind !== kind) {
return false
}
try {
- return normalizeRemoteBaseUrl(connection.url) === baseUrl
+ return normalizeRemoteBaseUrl(connection.url) === url
} catch {
return false
}
- })?.id ?? null
- )
+ })
+
+ if (coarseMatches.length !== 1) {
+ return null
+ }
+ }
+
+ return matchingConnectionId(registry, route, 'unique') ?? null
+}
+
+function normalizedSshTarget(route: {
+ host?: unknown
+ port?: unknown
+ user?: unknown
+}): null | string {
+ const ssh = normalizeSshConfig({ ...route, mode: 'ssh' })
+
+ if (!ssh) {
+ return null
+ }
+
+ const host = String(ssh.host || '')
+ .trim()
+ .toLowerCase()
+
+ const user = String(ssh.user || '')
+ .trim()
+ .toLowerCase()
+
+ return user ? `${user}@${host}` : host
}
/**
diff --git a/apps/desktop/electron/connection-route-identity.ts b/apps/desktop/electron/connection-route-identity.ts
new file mode 100644
index 00000000000..b95e59f2963
--- /dev/null
+++ b/apps/desktop/electron/connection-route-identity.ts
@@ -0,0 +1,136 @@
+/**
+ * Canonical registry route identity for Desktop.
+ *
+ * Identity is frozen before dialing, while the complete auth/transport
+ * envelope still exists. Compatibility callers may reuse the same contract,
+ * but must never reconstruct a stronger identity from post-dial metadata.
+ */
+
+import {
+ normalizeRemoteBaseUrl,
+ normalizeRemoteHeaders,
+ normalizeSshConfig,
+ normAuthMode
+} from './connection-config'
+import type { ConnectionRegistry, RegistryConnection } from './connection-registry'
+
+interface SshRouteConfig {
+ host: string
+ keyPath?: string
+ mode: 'ssh'
+ port?: number
+ remoteHermesPath?: string
+ remoteProfile?: string
+ user?: string
+}
+
+export type StoredRoute =
+ | {
+ authMode?: unknown
+ headers?: Record<string, unknown>
+ kind: 'cloud' | 'remote'
+ org?: unknown
+ token?: unknown
+ url?: unknown
+ }
+ | ({ kind: 'ssh' } & Partial<SshRouteConfig>)
+
+function stableValue(value: unknown): string {
+ if (!value || typeof value !== 'object') {
+ return JSON.stringify(value ?? null)
+ }
+
+ if (Array.isArray(value)) {
+ return `[${value.map(stableValue).join(',')}]`
+ }
+
+ return `{${Object.entries(value)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, item]) => `${JSON.stringify(key)}:${stableValue(item)}`)
+ .join(',')}}`
+}
+
+function canonicalHeaders(headers: unknown): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(normalizeRemoteHeaders(headers))
+ .map(([name, value]): [string, unknown] => [name.toLowerCase(), value])
+ .sort(([left], [right]) => left.localeCompare(right))
+ )
+}
+
+function routeIdentity(route: StoredRoute): null | string {
+ if (route.kind === 'ssh') {
+ const ssh = normalizeSshConfig({ ...route, mode: 'ssh' })
+
+ if (!ssh) {
+ return null
+ }
+
+ return stableValue({
+ host: ssh.host.trim().toLowerCase(),
+ keyPath: ssh.keyPath || '',
+ kind: 'ssh',
+ port: ssh.port || 22,
+ remoteHermesPath: ssh.remoteHermesPath || '',
+ remoteProfile: ssh.remoteProfile || '',
+ user: (ssh.user || '').trim().toLowerCase()
+ })
+ }
+
+ try {
+ const authMode = normAuthMode(route.authMode)
+
+ return stableValue({
+ authMode,
+ headers: canonicalHeaders(route.headers),
+ kind: route.kind,
+ org: route.kind === 'cloud' ? String(route.org || '').trim() : '',
+ token: authMode === 'token' ? (route.token ?? null) : null,
+ url: normalizeRemoteBaseUrl(route.url)
+ })
+ } catch {
+ return null
+ }
+}
+
+function registryRoute(connection: RegistryConnection): null | StoredRoute {
+ if (connection.kind === 'local') {
+ return null
+ }
+
+ return connection as StoredRoute
+}
+
+/**
+ * Match the complete pre-dial route identity used by #88922.
+ *
+ * `primary` accepts only the configured primary when its full envelope is
+ * equal. `unique` accepts exactly one full-envelope match. Zero and multiple
+ * matches deliberately remain unresolved.
+ */
+export function matchingConnectionId(
+ registry: ConnectionRegistry,
+ route: StoredRoute,
+ strategy: 'primary' | 'unique'
+): undefined | string {
+ const identity = routeIdentity(route)
+
+ if (!identity) {
+ return undefined
+ }
+
+ if (strategy === 'primary') {
+ const primary = registry.connections.find(connection => connection.id === registry.primary)
+ const candidate = primary && registryRoute(primary)
+
+ return candidate && routeIdentity(candidate) === identity ? primary.id : undefined
+ }
+
+ const matches = registry.connections.filter(connection => {
+ const candidate = registryRoute(connection)
+
+ return candidate ? routeIdentity(candidate) === identity : false
+ })
+
+ return matches.length === 1 ? matches[0].id : undefined
+}
diff --git a/apps/desktop/electron/desktop-remote-route.ts b/apps/desktop/electron/desktop-remote-route.ts
index 16f44d05ef2..c7c8a5cbc68 100644
--- a/apps/desktop/electron/desktop-remote-route.ts
+++ b/apps/desktop/electron/desktop-remote-route.ts
@@ -1,20 +1,13 @@
-/**
- * Pure route planner for Desktop's legacy v1 connection config. It preserves
- * v2 registry provenance before URL normalization, OAuth, or SSH tunnelling
- * discard dial details. Environment routes deliberately remain unregistered.
- */
-
import {
connectionScopeKey,
modeIsRemoteLike,
- normalizeRemoteBaseUrl,
- normalizeRemoteHeaders,
normalizeSshConfig,
normAuthMode,
profileRemoteOverride,
profileSshOverride
} from './connection-config'
-import type { ConnectionRegistry, RegistryConnection } from './connection-registry'
+import type { ConnectionRegistry } from './connection-registry'
+import { matchingConnectionId, type StoredRoute } from './connection-route-identity'
type RouteSource = 'env' | 'profile' | 'settings'
@@ -54,110 +47,6 @@ export interface DesktopRemoteRouteInput {
registry: ConnectionRegistry
}
-type StoredRoute =
- | {
- authMode?: unknown
- headers?: Record<string, unknown>
- kind: 'cloud' | 'remote'
- org?: unknown
- token?: unknown
- url?: unknown
- }
- | ({ kind: 'ssh' } & Partial<SshRouteConfig>)
-
-function stableValue(value: unknown): string {
- if (!value || typeof value !== 'object') {
- return JSON.stringify(value ?? null)
- }
-
- if (Array.isArray(value)) {
- return `[${value.map(stableValue).join(',')}]`
- }
-
- return `{${Object.entries(value)
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([key, item]) => `${JSON.stringify(key)}:${stableValue(item)}`)
- .join(',')}}`
-}
-
-function canonicalHeaders(headers: unknown): Record<string, unknown> {
- return Object.fromEntries(
- Object.entries(normalizeRemoteHeaders(headers))
- .map(([name, value]): [string, unknown] => [name.toLowerCase(), value])
- .sort(([left], [right]) => left.localeCompare(right))
- )
-}
-
-function routeIdentity(route: StoredRoute): null | string {
- if (route.kind === 'ssh') {
- const ssh = normalizeSshConfig({ ...route, mode: 'ssh' })
-
- if (!ssh) {
- return null
- }
-
- return stableValue({
- host: ssh.host,
- keyPath: ssh.keyPath || '',
- kind: 'ssh',
- port: ssh.port || 22,
- remoteHermesPath: ssh.remoteHermesPath || '',
- remoteProfile: ssh.remoteProfile || '',
- user: ssh.user || ''
- })
- }
-
- try {
- const authMode = normAuthMode(route.authMode)
-
- return stableValue({
- authMode,
- headers: canonicalHeaders(route.headers),
- kind: route.kind,
- org: route.kind === 'cloud' ? String(route.org || '').trim() : '',
- token: authMode === 'token' ? (route.token ?? null) : null,
- url: normalizeRemoteBaseUrl(route.url)
- })
- } catch {
- return null
- }
-}
-
-function registryRoute(connection: RegistryConnection): null | StoredRoute {
- if (connection.kind === 'local') {
- return null
- }
-
- return connection as StoredRoute
-}
-
-function matchingConnectionId(
- registry: ConnectionRegistry,
- route: StoredRoute,
- strategy: 'primary' | 'unique'
-): undefined | string {
- const identity = routeIdentity(route)
-
- if (!identity) {
- return undefined
- }
-
- if (strategy === 'primary') {
- const primary = registry.connections.find(connection => connection.id === registry.primary)
- const candidate = primary && registryRoute(primary)
-
- return candidate && routeIdentity(candidate) === identity ? primary.id : undefined
- }
-
- const matches = registry.connections.filter(connection => {
- const candidate = registryRoute(connection)
-
- return candidate ? routeIdentity(candidate) === identity : false
- })
-
- return matches.length === 1 ? matches[0].id : undefined
-}
-
function withConnectionId<T extends object>(route: T, connectionId?: string): T & { connectionId?: string } {
return connectionId ? { ...route, connectionId } : route
}
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index ec92be722a5..b483fec3919 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -113,6 +113,17 @@ describe('connection registry cache', () => {
expect(ensureGatewayAgent).not.toHaveBeenCalled()
})
+ it('restores a remote registry primary through its exact connection id', async () => {
+ list.mockResolvedValueOnce({ ...registry, primary: 'homelab', launchMode: 'primary' })
+ $connection.set({ connectionId: 'local', mode: 'local' })
+
+ await initializeConnectionsRegistry()
+
+ expect(ensureGatewayAgent).toHaveBeenCalledTimes(1)
+ expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default')
+ expect(setLastUsed).toHaveBeenCalledWith('homelab')
+ })
+
it('uses only the resolved descriptor identity for the active gateway', () => {
setConnectionsRegistry({ ...registry, primary: 'homelab' })
$connection.set({ connectionId: 'work-vps', mode: 'remote' })