Files
archived-orca/src/shared/runtime-environments.ts
T
OrcaWinandm4air 99db2bfae4 feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2) (#24420)
* feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2)

Paired runtime environments gain a durable two-phase SSH access link
(prepare link, verified link, prepare unlink, complete unlink, cancel),
plus the reconciliation record type and the runtime identity verification
helper that T6 needs. Nothing calls the link store yet; T6's managed tunnel
and runtime SSH access are its first writers.

Why a sidecar: v1.4.217 and v1.4.218 parse orca-environments.json with plain
z.object schemas, which strip unknown keys, and rewrite the whole file on
routine use (markEnvironmentUsed). Storing the link there, as #16741 did, would
let a downgraded build keep the tunnel endpoint but drop sshAccess, stranding
the server unlinkable and losing its pinned host-key fingerprint. #16741's own
answer (bumping the store version) makes those builds reject the whole file.

So orca-environments.json keeps exactly its shipped shape (version 1, persisted
fields only), and all T5 state lives in orca-environment-sidecar.json beside
it: the link and its tunnel endpoint, the pending operation, the reconciliation
record, the verified runtime id and a monotonic pairing-revision floor. Reads
overlay the sidecar; each entry is bound to the environment's createdAt,
pairing revision and preferred endpoint, so a re-pair, removal or edit by an
older build makes it stale (ignored, pruned on the next sidecar write). An
unreadable sidecar fails closed, like the main file.

Porting note (source: #16741 a68b6f3531):
- Taken: the link-store behavior and messages, the access-link schemas and
  refinements, the reconciliation record, identity verification, and the
  store/schema tests.
- Adapted: link state moved from orca-environments.json to the sidecar;
  existing mutators write persisted fields only; removal, re-pairing and
  runtime identity changes refuse while SSH access is linked or pending.
- Left for later slices: orcadDeployment and restoreManagedOrcadEnvironmentLink
  (T6), reconciliation store, integrity, catalog and UI (T5-3 to T5-5), the 24
  renderer terminal-input files (T7), runtime-identity and the managed-tunnel
  resolver (T6).

* test(runtime): read SSH access from the known view of a persisted environment

---------

Co-authored-by: m4air <m4air@m4airs-Air.localdomain>
2026-10-01 11:45:59 -07:00

231 lines
7.9 KiB
TypeScript

import { z } from 'zod'
import { PAIRING_OFFER_VERSION, type PairingOffer } from './pairing'
import { classifyRemotePairingHostname } from './remote-pairing-address'
import { RuntimeEnvironmentReconciliationRecordSchema } from './runtime-environment-reconciliation-record'
export const RuntimeAccessEndpointSchema = z.object({
id: z.string().min(1),
kind: z.literal('websocket'),
label: z.string().min(1),
endpoint: z.string().min(1),
deviceToken: z.string().min(1),
publicKeyB64: z.string().min(1)
})
export const PublicRuntimeAccessEndpointSchema = RuntimeAccessEndpointSchema.omit({
deviceToken: true,
publicKeyB64: true
})
export type PublicRuntimeAccessEndpoint = z.infer<typeof PublicRuntimeAccessEndpointSchema>
export const RuntimeEnvironmentSourceSchema = z.enum(['manual', 'ephemeral-vm'])
export type RuntimeEnvironmentSource = z.infer<typeof RuntimeEnvironmentSourceSchema>
export const RuntimeSshTunnelLinkSchema = z.object({
sshTargetId: z.string().min(1),
sshTargetGeneration: z.number().int().positive(),
localPort: z.number().int().min(1).max(65_535),
remotePort: z.number().int().min(1).max(65_535)
})
export type RuntimeSshTunnelLink = z.infer<typeof RuntimeSshTunnelLinkSchema>
export const RuntimeSshAccessLinkSchema = RuntimeSshTunnelLinkSchema.extend({
requestId: z.string().min(1).optional(),
targetFingerprint: z.string().min(1).optional(),
endpointId: z.string().min(1),
previousPreferredEndpointId: z.string().min(1)
})
export type RuntimeSshAccessLink = z.infer<typeof RuntimeSshAccessLinkSchema>
export const RuntimeSshAccessOperationSchema = RuntimeSshTunnelLinkSchema.omit({ localPort: true })
.extend({
requestId: z.string().min(1),
operation: z.enum(['link', 'unlink']),
targetFingerprint: z.string().min(1).optional()
})
.refine((intent) => intent.operation !== 'link' || !!intent.targetFingerprint, {
message: 'Link intent requires a target fingerprint.'
})
export type RuntimeSshAccessOperation = z.infer<typeof RuntimeSshAccessOperationSchema>
/** The fields shipped builds read and rewrite in orca-environments.json. */
export const PersistedRuntimeEnvironmentSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
createdAt: z.number().finite(),
updatedAt: z.number().finite(),
pairingRevision: z.number().finite().optional(),
pairedDeviceId: z.string().min(1).optional(),
lastUsedAt: z.number().finite().nullable(),
runtimeId: z.string().min(1).nullable(),
source: RuntimeEnvironmentSourceSchema.optional(),
connectionDependency: z.literal('ssh-tunnel').optional(),
endpoints: z.array(RuntimeAccessEndpointSchema).min(1),
preferredEndpointId: z.string().min(1)
})
export type PersistedRuntimeEnvironment = z.infer<typeof PersistedRuntimeEnvironmentSchema>
/**
* A persisted environment with its sidecar state overlaid (runtime-environment-sidecar). These
* fields never enter orca-environments.json: shipped builds strip unknown keys when they rewrite it.
*/
export const KnownRuntimeEnvironmentSchema = PersistedRuntimeEnvironmentSchema.extend({
sshAccess: RuntimeSshAccessLinkSchema.optional(),
pendingSshAccessOperation: RuntimeSshAccessOperationSchema.optional(),
reconciliation: RuntimeEnvironmentReconciliationRecordSchema.optional()
})
.refine(
({ pendingSshAccessOperation, sshAccess, connectionDependency }) =>
!pendingSshAccessOperation || (!sshAccess && !connectionDependency),
{
message: 'Pending SSH access operations cannot coexist with active SSH access.',
path: ['pendingSshAccessOperation']
}
)
.refine(
(environment) => {
const access = environment.sshAccess
return (
!access ||
(environment.connectionDependency === 'ssh-tunnel' &&
environment.preferredEndpointId === access.endpointId &&
access.previousPreferredEndpointId !== access.endpointId &&
environment.endpoints.some(
(endpoint) => endpoint.id === access.previousPreferredEndpointId
) &&
getPreferredLoopbackRuntimePort(environment) === access.localPort)
)
},
{
message:
'Runtime SSH access must preserve its previous endpoint and prefer its loopback endpoint.',
path: ['sshAccess']
}
)
export type KnownRuntimeEnvironment = z.infer<typeof KnownRuntimeEnvironmentSchema>
export type PublicKnownRuntimeEnvironment = Omit<KnownRuntimeEnvironment, 'endpoints'> & {
endpoints: PublicRuntimeAccessEndpoint[]
}
export function redactRuntimeEnvironment(
environment: KnownRuntimeEnvironment
): PublicKnownRuntimeEnvironment {
return {
...environment,
endpoints: environment.endpoints.map(
({ deviceToken: _deviceToken, publicKeyB64: _key, ...rest }) => rest
)
}
}
// Why version 1 and the persisted schema: shipped builds accept only this shape, so every
// T5 field lives in the sidecar and a downgrade rewrite cannot lose or reject it.
export const RuntimeEnvironmentStoreSchema = z.object({
version: z.literal(1),
environments: z.array(PersistedRuntimeEnvironmentSchema)
})
export type RuntimeEnvironmentStore = z.infer<typeof RuntimeEnvironmentStoreSchema>
export function createEnvironmentFromPairingOffer(args: {
id: string
name: string
now: number
offer: PairingOffer
runtimeId?: string | null
source?: RuntimeEnvironmentSource
connectionDependency?: 'ssh-tunnel'
}): KnownRuntimeEnvironment {
const endpointId = `ws-${args.id}`
return KnownRuntimeEnvironmentSchema.parse({
id: args.id,
name: args.name,
createdAt: args.now,
updatedAt: args.now,
pairingRevision: args.now,
...(args.offer.pairedDeviceId ? { pairedDeviceId: args.offer.pairedDeviceId } : {}),
lastUsedAt: null,
runtimeId: args.runtimeId ?? null,
...(args.source ? { source: args.source } : {}),
...(args.connectionDependency ? { connectionDependency: args.connectionDependency } : {}),
endpoints: [
{
id: endpointId,
kind: 'websocket',
label: 'WebSocket',
endpoint: args.offer.endpoint,
deviceToken: args.offer.deviceToken,
publicKeyB64: args.offer.publicKeyB64
}
],
preferredEndpointId: endpointId
})
}
export function isEphemeralVmRuntimeEnvironment(
environment: Pick<PublicKnownRuntimeEnvironment, 'source'>
): boolean {
return environment.source === 'ephemeral-vm'
}
export function isUserManagedRuntimeEnvironment(
environment: Pick<PublicKnownRuntimeEnvironment, 'source'>
): boolean {
return !isEphemeralVmRuntimeEnvironment(environment)
}
export function getPreferredPairingOffer(environment: KnownRuntimeEnvironment): PairingOffer {
const endpoint =
environment.endpoints.find((entry) => entry.id === environment.preferredEndpointId) ??
environment.endpoints[0]
if (!endpoint) {
throw new Error(`Environment ${environment.name} has no access endpoints`)
}
return {
v: PAIRING_OFFER_VERSION,
endpoint: endpoint.endpoint,
deviceToken: endpoint.deviceToken,
publicKeyB64: endpoint.publicKeyB64,
...(environment.pairedDeviceId ? { pairedDeviceId: environment.pairedDeviceId } : {})
}
}
/** SSH is an access path for a paired server; managed lifecycle ownership is T6's deployment link. */
export function getRuntimeSshAccess(
environment: Pick<KnownRuntimeEnvironment, 'sshAccess'>
): RuntimeSshTunnelLink | undefined {
return environment.sshAccess
}
export function getPreferredLoopbackRuntimePort(environment: {
endpoints: { id: string; endpoint: string }[]
preferredEndpointId: string
}): number | null {
const endpoint = environment.endpoints.find(
(entry) => entry.id === environment.preferredEndpointId
)
if (!endpoint) {
return null
}
try {
const url = new URL(endpoint.endpoint)
const port = Number(url.port)
return (url.protocol === 'ws:' || url.protocol === 'wss:') &&
classifyRemotePairingHostname(url.hostname) === 'loopback' &&
Number.isInteger(port) &&
port >= 1 &&
port <= 65_535
? port
: null
} catch {
return null
}
}