fix(relay): make desktop control lifecycle provable and self-healing (#12076)
- RelayControlOrigin.activate rejects controls whose socket closed before activation (hello-ack and close in one ws parser turn previously published a dead control with no recovery path) - RelayControlClient gains a 75s inbound-silence watchdog mirroring the relay's ping contract, so dead or server-side-unindexed sockets terminate and trigger origin recovery - RelayAuthCoordinator only republishes 'registered' when the owned broker proves a live control, and logs reconcile failures instead of swallowing them; the origin pool logs recovery-attempt failures - Host-proof validation reports the failing check by name (never values), keeping main's 30s skew bounds - isLive() plumbed client -> origin -> pool -> broker Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
@@ -274,4 +274,32 @@ describe('RelayAuthCoordinator', () => {
|
||||
await vi.waitFor(() => expect(coordinator.getActiveBroker()).toBe(brokers[2]))
|
||||
expect(brokers[1]!.closeNow).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('reopens instead of republishing registered for a dead broker', async () => {
|
||||
// Why: a broker that lost its control without recovering must not keep
|
||||
// reporting registered on every reconcile while phones get HOST_OFFLINE.
|
||||
let firstBrokerLive = true
|
||||
const brokers = [
|
||||
{ closeNow: vi.fn(), isLive: () => firstBrokerLive },
|
||||
{ closeNow: vi.fn(), isLive: () => true }
|
||||
]
|
||||
const openBroker = vi.fn().mockResolvedValueOnce(brokers[0]).mockResolvedValueOnce(brokers[1])
|
||||
const statuses: string[] = []
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: (status) => statuses.push(status)
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(coordinator.getActiveBroker()).toBe(brokers[0]))
|
||||
expect(statuses.at(-1)).toBe('registered')
|
||||
|
||||
firstBrokerLive = false
|
||||
coordinator.reconcile()
|
||||
|
||||
await vi.waitFor(() => expect(coordinator.getActiveBroker()).toBe(brokers[1]))
|
||||
expect(brokers[0]!.closeNow).toHaveBeenCalledOnce()
|
||||
expect(statuses.at(-1)).toBe('registered')
|
||||
expect(statuses.filter((status) => status === 'connecting')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ export type RelayAuthContext = {
|
||||
|
||||
export type CoordinatedRelayBroker = {
|
||||
closeNow(): void
|
||||
isLive?(): boolean
|
||||
}
|
||||
|
||||
type RelayAuthCoordinatorOptions = {
|
||||
@@ -143,7 +144,13 @@ export class RelayAuthCoordinator {
|
||||
return
|
||||
}
|
||||
this.cancelLinger()
|
||||
if (this.ownership?.valid && this.ownership.identityKey === nextIdentityKey) {
|
||||
if (
|
||||
this.ownership?.valid &&
|
||||
this.ownership.identityKey === nextIdentityKey &&
|
||||
// Why: registered must be provable; a broker whose control died without
|
||||
// recovering falls through and is replaced instead of republished.
|
||||
(this.ownership.broker?.isLive?.() ?? true)
|
||||
) {
|
||||
this.retryAttempt = 0
|
||||
this.options.onStatus('registered')
|
||||
return
|
||||
@@ -181,6 +188,12 @@ export class RelayAuthCoordinator {
|
||||
this.options.onStatus('registered')
|
||||
} catch (error) {
|
||||
if (this.isEpochCurrent(epoch)) {
|
||||
// Why: silent broker-open failures made a dead relay look like standby
|
||||
// during incident diagnosis; the message carries operation + status.
|
||||
console.warn(
|
||||
'[relay] broker reconcile failed:',
|
||||
error instanceof Error ? error.message : String(error)
|
||||
)
|
||||
this.options.onStatus('offline')
|
||||
if (shouldRetryRelayConnectionError(error)) {
|
||||
const retryAfterMs = error instanceof RelayHttpError ? (error.retryAfterMs ?? 0) : 0
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createHash, createHmac, randomBytes } from 'node:crypto'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
@@ -378,3 +379,174 @@ describe('RelayControlClient', () => {
|
||||
await vi.waitFor(() => expect(onDrain).toHaveBeenCalledOnce())
|
||||
})
|
||||
})
|
||||
|
||||
class FakeControlSocket extends EventEmitter {
|
||||
readonly OPEN = 1
|
||||
readyState = 1
|
||||
script: ((message: Record<string, unknown>, socket: FakeControlSocket) => void) | null = null
|
||||
|
||||
send(payload: string): void {
|
||||
this.script?.(JSON.parse(payload) as Record<string, unknown>, this)
|
||||
}
|
||||
|
||||
close(code = 1000): void {
|
||||
if (this.readyState !== 1) {
|
||||
return
|
||||
}
|
||||
this.readyState = 3
|
||||
this.emit('close', code)
|
||||
}
|
||||
|
||||
terminate(): void {
|
||||
this.close(1006)
|
||||
}
|
||||
|
||||
deliver(message: object): void {
|
||||
this.emit('message', JSON.stringify(message), false)
|
||||
}
|
||||
}
|
||||
|
||||
function scriptedControl(options: { closeWithAck?: boolean; issuedAtOffsetMs?: number } = {}): {
|
||||
client: RelayControlClient
|
||||
socket: FakeControlSocket
|
||||
onClose: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const hostKeys = nacl.box.keyPair()
|
||||
const keypair: E2EEKeypair = {
|
||||
publicKey: hostKeys.publicKey,
|
||||
secretKey: hostKeys.secretKey,
|
||||
publicKeyB64: Buffer.from(hostKeys.publicKey).toString('base64')
|
||||
}
|
||||
const origin = 'http://relay.test'
|
||||
const relayHostId = createHash('sha256')
|
||||
.update(hostKeys.publicKey)
|
||||
.digest('base64url')
|
||||
.slice(0, 16)
|
||||
const socket = new FakeControlSocket()
|
||||
socket.script = (message, ws) => {
|
||||
if (message.type === 'host-hello') {
|
||||
const relayKeys = nacl.box.keyPair()
|
||||
const nonce = randomBytes(24)
|
||||
const secret = randomBytes(32)
|
||||
const issuedAt = Date.now() + (options.issuedAtOffsetMs ?? 0)
|
||||
const expiresAt = issuedAt + 10_000
|
||||
const transcript = buildTranscript({
|
||||
origin,
|
||||
relayKey: relayKeys.publicKey,
|
||||
nonce,
|
||||
challengeId: 'challenge-1',
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
relayHostId,
|
||||
hostKey: hostKeys.publicKey
|
||||
})
|
||||
const plaintext = concat([
|
||||
text(`${CHALLENGE_DOMAIN}\0`),
|
||||
uint32(transcript.byteLength),
|
||||
transcript,
|
||||
secret
|
||||
])
|
||||
ws.deliver({
|
||||
type: 'host-challenge',
|
||||
challengeId: 'challenge-1',
|
||||
relayEphemeralPublicKeyB64: Buffer.from(relayKeys.publicKey).toString('base64'),
|
||||
nonceB64: nonce.toString('base64'),
|
||||
ciphertextB64: Buffer.from(
|
||||
nacl.box(plaintext, nonce, hostKeys.publicKey, relayKeys.secretKey)
|
||||
).toString('base64'),
|
||||
expiresAt
|
||||
})
|
||||
return
|
||||
}
|
||||
if (message.type === 'host-challenge-ack') {
|
||||
ws.deliver({
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 4,
|
||||
controlResumeSecret: randomBytes(32).toString('base64url'),
|
||||
leaseExpiresAt: Date.now() + 3_600_000,
|
||||
activeConnIds: [],
|
||||
pendingConns: []
|
||||
})
|
||||
// Same ws parser turn: the close event fires before any awaiting caller
|
||||
// of connect() gets to run.
|
||||
if (options.closeWithAck) {
|
||||
ws.close(1006)
|
||||
}
|
||||
}
|
||||
}
|
||||
const onClose = vi.fn()
|
||||
const client = new RelayControlClient({
|
||||
cellUrl: origin,
|
||||
relayJwt: 'scoped-token',
|
||||
relayHostId,
|
||||
assignmentEpoch: 3,
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
keypair,
|
||||
appVersion: '1.2.3',
|
||||
onConnectionOpen: vi.fn(),
|
||||
onDrain: vi.fn(),
|
||||
onClose,
|
||||
createSocket: () => socket as unknown as WebSocket
|
||||
})
|
||||
queueMicrotask(() => socket.emit('open'))
|
||||
return { client, socket, onClose }
|
||||
}
|
||||
|
||||
describe('RelayControlClient scripted-socket lifecycle', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('resolves connect when close lands in the ack parser turn, but reports not live', async () => {
|
||||
const { client, onClose } = scriptedControl({ closeWithAck: true })
|
||||
|
||||
await expect(client.connect()).resolves.toMatchObject({ generation: 4 })
|
||||
|
||||
expect(onClose).toHaveBeenCalledWith(1006)
|
||||
expect(client.isLive()).toBe(false)
|
||||
})
|
||||
|
||||
it('tolerates a cell clock slightly ahead when validating the challenge', async () => {
|
||||
// A relay whose clock runs ~100ms-2s ahead is normal NTP drift, not replay.
|
||||
const { client } = scriptedControl({ issuedAtOffsetMs: 1_500 })
|
||||
|
||||
await expect(client.connect()).resolves.toMatchObject({ generation: 4 })
|
||||
expect(client.isLive()).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a challenge issued beyond the clock tolerance', async () => {
|
||||
const { client } = scriptedControl({ issuedAtOffsetMs: 45_000 })
|
||||
|
||||
await expect(client.connect()).rejects.toThrow('invalid host challenge')
|
||||
expect(client.isLive()).toBe(false)
|
||||
})
|
||||
|
||||
it('terminates a silent control after the silence limit and reports closure', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { client, socket, onClose } = scriptedControl()
|
||||
await expect(client.connect()).resolves.toMatchObject({ generation: 4 })
|
||||
expect(client.isLive()).toBe(true)
|
||||
|
||||
vi.advanceTimersByTime(91_000)
|
||||
|
||||
expect(socket.readyState).toBe(3)
|
||||
expect(onClose).toHaveBeenCalledWith(1006)
|
||||
expect(client.isLive()).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a control live while server pings keep arriving', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { client, socket } = scriptedControl()
|
||||
await client.connect()
|
||||
|
||||
for (let round = 0; round < 6; round++) {
|
||||
vi.advanceTimersByTime(60_000)
|
||||
socket.deliver({ type: 'ping', t: Date.now() })
|
||||
}
|
||||
expect(client.isLive()).toBe(true)
|
||||
|
||||
vi.advanceTimersByTime(91_000)
|
||||
expect(client.isLive()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -17,6 +17,11 @@ import {
|
||||
import { RelayControlRequests } from './relay-control-requests'
|
||||
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
|
||||
import { answerRelayHostChallenge } from './relay-host-proof'
|
||||
import {
|
||||
RELAY_CONTROL_SILENCE_LIMIT_MS,
|
||||
RelayControlSilenceWatchdog
|
||||
} from './relay-control-silence-watchdog'
|
||||
import { controlWebSocketUrl } from './relay-control-url'
|
||||
|
||||
type RelayControlState = 'idle' | 'opening' | 'proving' | 'active' | 'draining' | 'closed'
|
||||
|
||||
@@ -35,26 +40,11 @@ type RelayControlClientOptions = {
|
||||
onClose: (code: number) => void
|
||||
createSocket?: (url: string, relayJwt: string) => WebSocket
|
||||
connectDeadlineMs?: number
|
||||
silenceLimitMs?: number
|
||||
}
|
||||
|
||||
const RELAY_CONTROL_CONNECT_DEADLINE_MS = 15_000
|
||||
|
||||
function controlWebSocketUrl(cellUrl: string): { origin: string; url: string } {
|
||||
const parsed = new URL(cellUrl)
|
||||
if (parsed.pathname !== '/' || parsed.search || parsed.hash) {
|
||||
throw new Error('relay_cell_url_must_be_an_origin')
|
||||
}
|
||||
const origin = parsed.origin
|
||||
if (parsed.protocol === 'https:') {
|
||||
parsed.protocol = 'wss:'
|
||||
} else if (parsed.protocol === 'http:') {
|
||||
parsed.protocol = 'ws:'
|
||||
} else {
|
||||
throw new Error('relay_cell_url_must_use_http')
|
||||
}
|
||||
return { origin, url: `${parsed.origin}/v1/host/control` }
|
||||
}
|
||||
|
||||
export class RelayControlClient {
|
||||
private readonly options: RelayControlClientOptions
|
||||
private readonly relayOrigin: string
|
||||
@@ -66,12 +56,17 @@ export class RelayControlClient {
|
||||
private connectResolve: ((ack: RelayHostHelloAckMessage) => void) | null = null
|
||||
private connectReject: ((error: Error) => void) | null = null
|
||||
private connectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly silenceWatchdog: RelayControlSilenceWatchdog
|
||||
|
||||
constructor(options: RelayControlClientOptions) {
|
||||
this.options = options
|
||||
const endpoint = controlWebSocketUrl(options.cellUrl)
|
||||
this.relayOrigin = endpoint.origin
|
||||
this.controlUrl = endpoint.url
|
||||
this.silenceWatchdog = new RelayControlSilenceWatchdog(
|
||||
options.silenceLimitMs ?? RELAY_CONTROL_SILENCE_LIMIT_MS,
|
||||
() => this.socket?.terminate()
|
||||
)
|
||||
this.createSocket =
|
||||
options.createSocket ??
|
||||
((url, token) =>
|
||||
@@ -91,6 +86,7 @@ export class RelayControlClient {
|
||||
this.socket = socket
|
||||
socket.once('open', () => this.sendHostHello())
|
||||
socket.on('message', (raw, isBinary) => {
|
||||
this.silenceWatchdog.noteInbound()
|
||||
if (isBinary) {
|
||||
this.failProtocol('binary control message')
|
||||
return
|
||||
@@ -120,6 +116,14 @@ export class RelayControlClient {
|
||||
return this.requests.size
|
||||
}
|
||||
|
||||
isLive(): boolean {
|
||||
return (
|
||||
(this.state === 'active' || this.state === 'draining') &&
|
||||
this.socket !== null &&
|
||||
this.socket.readyState === WebSocket.OPEN
|
||||
)
|
||||
}
|
||||
|
||||
refreshAuthorization(relayJwt: string): void {
|
||||
this.sendActive({ type: 'auth-refresh', relayJwt })
|
||||
}
|
||||
@@ -165,6 +169,7 @@ export class RelayControlClient {
|
||||
closeNow(): void {
|
||||
const wasConnecting = this.state === 'opening' || this.state === 'proving'
|
||||
this.state = 'closed'
|
||||
this.silenceWatchdog.stop()
|
||||
if (wasConnecting) {
|
||||
this.connectReject?.(new Error('relay_control_closed'))
|
||||
this.clearConnectPromise()
|
||||
@@ -235,6 +240,7 @@ export class RelayControlClient {
|
||||
private handleProofMessage(message: Record<string, unknown>): void {
|
||||
const challenge = RelayHostChallengeMessageSchema.safeParse(message)
|
||||
if (challenge.success) {
|
||||
let invalidReason = 'unknown'
|
||||
const proofB64 = answerRelayHostChallenge(challenge.data, {
|
||||
relayOrigin: this.relayOrigin,
|
||||
...this.options.identity,
|
||||
@@ -243,10 +249,14 @@ export class RelayControlClient {
|
||||
hostSecretKey: this.options.keypair.secretKey,
|
||||
assignmentEpoch: this.options.assignmentEpoch,
|
||||
previousGeneration: this.options.previousGeneration,
|
||||
resumeRequested: Boolean(this.options.controlResumeSecret)
|
||||
resumeRequested: Boolean(this.options.controlResumeSecret),
|
||||
onInvalid: (reason) => {
|
||||
invalidReason = reason
|
||||
}
|
||||
})
|
||||
if (!proofB64) {
|
||||
this.failProtocol('invalid host challenge')
|
||||
// Reason names the failing check only; field values never surface here.
|
||||
this.failProtocol(`invalid host challenge: ${invalidReason} origin=${this.relayOrigin}`)
|
||||
return
|
||||
}
|
||||
this.socket?.send(
|
||||
@@ -264,6 +274,7 @@ export class RelayControlClient {
|
||||
return
|
||||
}
|
||||
this.state = 'active'
|
||||
this.silenceWatchdog.start()
|
||||
this.connectResolve?.(ack.data)
|
||||
this.clearConnectPromise()
|
||||
}
|
||||
@@ -284,6 +295,7 @@ export class RelayControlClient {
|
||||
private handleClose(code: number): void {
|
||||
const wasConnecting = this.state === 'opening' || this.state === 'proving'
|
||||
this.state = 'closed'
|
||||
this.silenceWatchdog.stop()
|
||||
if (wasConnecting) {
|
||||
this.connectReject?.(new Error(`relay_control_closed_${code}`))
|
||||
this.clearConnectPromise()
|
||||
|
||||
@@ -71,6 +71,10 @@ export class RelayControlOrigin {
|
||||
return this.activeControl
|
||||
}
|
||||
|
||||
hasLiveControl(): boolean {
|
||||
return this.activeControl?.isLive() ?? false
|
||||
}
|
||||
|
||||
get cellUrl(): string {
|
||||
return this.assignment.cellUrl
|
||||
}
|
||||
@@ -225,6 +229,13 @@ export class RelayControlOrigin {
|
||||
}
|
||||
|
||||
private activate(control: RelayControlClient, ack: RelayHostHelloAckMessage): void {
|
||||
// Why: a socket can deliver hello-ack and close in the same ws parser turn.
|
||||
// That close already ran onClose (removing the control) before this
|
||||
// continuation, so promoting it would publish a dead control that no close
|
||||
// event will ever recover.
|
||||
if (!this.controls.has(control) || !control.isLive()) {
|
||||
throw new Error('relay_control_closed_before_activation')
|
||||
}
|
||||
if (ack.generation <= 0) {
|
||||
throw new Error('invalid_relay_generation')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// The relay pings every 15s and closes a control after 75s of silence; mirror
|
||||
// that bound so a dead or server-side-unindexed socket cannot stay "active".
|
||||
export const RELAY_CONTROL_SILENCE_LIMIT_MS = 75_000
|
||||
|
||||
const CHECK_INTERVAL_MS = 15_000
|
||||
|
||||
export class RelayControlSilenceWatchdog {
|
||||
private timer: ReturnType<typeof setInterval> | null = null
|
||||
private lastInboundAt = 0
|
||||
|
||||
constructor(
|
||||
private readonly limitMs: number,
|
||||
private readonly onSilence: () => void
|
||||
) {}
|
||||
|
||||
noteInbound(): void {
|
||||
this.lastInboundAt = Date.now()
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.lastInboundAt = Date.now()
|
||||
this.timer = setInterval(() => {
|
||||
if (Date.now() - this.lastInboundAt > this.limitMs) {
|
||||
this.stop()
|
||||
this.onSilence()
|
||||
}
|
||||
}, CHECK_INTERVAL_MS)
|
||||
this.timer.unref?.()
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export function controlWebSocketUrl(cellUrl: string): { origin: string; url: string } {
|
||||
const parsed = new URL(cellUrl)
|
||||
if (parsed.pathname !== '/' || parsed.search || parsed.hash) {
|
||||
throw new Error('relay_cell_url_must_be_an_origin')
|
||||
}
|
||||
const origin = parsed.origin
|
||||
if (parsed.protocol === 'https:') {
|
||||
parsed.protocol = 'wss:'
|
||||
} else if (parsed.protocol === 'http:') {
|
||||
parsed.protocol = 'ws:'
|
||||
} else {
|
||||
throw new Error('relay_cell_url_must_use_http')
|
||||
}
|
||||
return { origin, url: `${parsed.origin}/v1/host/control` }
|
||||
}
|
||||
@@ -29,6 +29,8 @@ export type RelayHostProofContext = {
|
||||
previousGeneration?: number
|
||||
resumeRequested: boolean
|
||||
now?: () => number
|
||||
/** Reports the failing check by name only; never receives field values. */
|
||||
onInvalid?: (reason: string) => void
|
||||
}
|
||||
|
||||
function decodeCanonicalBase64(value: string, expectedBytes: number): Uint8Array | null {
|
||||
@@ -95,6 +97,7 @@ function validateTranscript(
|
||||
): boolean {
|
||||
const fields = parseTranscript(transcript)
|
||||
if (!fields || fields.size !== 16) {
|
||||
context.onInvalid?.('transcript-structure')
|
||||
return false
|
||||
}
|
||||
const now = (context.now ?? Date.now)()
|
||||
@@ -103,28 +106,51 @@ function validateTranscript(
|
||||
const previousGeneration = fields.get('previousGeneration')
|
||||
const expectedPrevious =
|
||||
context.previousGeneration === undefined ? new Uint8Array() : uint64(context.previousGeneration)
|
||||
return (
|
||||
issuedAt !== null &&
|
||||
issuedAt - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= now &&
|
||||
now - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= challenge.expiresAt &&
|
||||
issuedAt <= challenge.expiresAt &&
|
||||
challenge.expiresAt - issuedAt <= MAX_HOST_PROOF_CHALLENGE_WINDOW_MS &&
|
||||
expiresAt === challenge.expiresAt &&
|
||||
equal(fields.get('protocol'), textEncoder.encode(HOST_PROOF_TRANSCRIPT_DOMAIN)) &&
|
||||
equal(fields.get('version'), new Uint8Array([1])) &&
|
||||
equal(fields.get('relayOrigin'), textEncoder.encode(context.relayOrigin)) &&
|
||||
equal(fields.get('relayEphemeralPublicKey'), relayKey) &&
|
||||
equal(fields.get('challengeNonce'), nonce) &&
|
||||
equal(fields.get('challengeId'), textEncoder.encode(challenge.challengeId)) &&
|
||||
equal(fields.get('userId'), textEncoder.encode(context.userId)) &&
|
||||
equal(fields.get('profileId'), textEncoder.encode(context.profileId)) &&
|
||||
equal(fields.get('organizationId'), textEncoder.encode(context.organizationId)) &&
|
||||
equal(fields.get('relayHostId'), textEncoder.encode(context.relayHostId)) &&
|
||||
equal(fields.get('hostPublicKey'), context.hostPublicKey) &&
|
||||
equal(fields.get('assignmentEpoch'), uint64(context.assignmentEpoch)) &&
|
||||
equal(previousGeneration, expectedPrevious) &&
|
||||
equal(fields.get('resumeRequested'), new Uint8Array([context.resumeRequested ? 1 : 0]))
|
||||
)
|
||||
// Main's 30s skew bounds with named-check reporting kept from the incident
|
||||
// instrumentation; deltas are relative offsets only, never absolute values.
|
||||
const checks: [string, boolean][] = [
|
||||
['issuedAt-readable', issuedAt !== null],
|
||||
[
|
||||
`issuedAt-not-future(d=${issuedAt === null ? 'n/a' : issuedAt - now}ms)`,
|
||||
issuedAt === null || issuedAt - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= now
|
||||
],
|
||||
[
|
||||
`not-expired(d=${challenge.expiresAt - now}ms)`,
|
||||
now - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= challenge.expiresAt
|
||||
],
|
||||
['issuedAt-before-expiry', issuedAt === null || issuedAt <= challenge.expiresAt],
|
||||
[
|
||||
`window(w=${issuedAt === null ? 'n/a' : challenge.expiresAt - issuedAt}ms)`,
|
||||
issuedAt === null || challenge.expiresAt - issuedAt <= MAX_HOST_PROOF_CHALLENGE_WINDOW_MS
|
||||
],
|
||||
['expiry-consistent', expiresAt === challenge.expiresAt],
|
||||
['protocol', equal(fields.get('protocol'), textEncoder.encode(HOST_PROOF_TRANSCRIPT_DOMAIN))],
|
||||
['version', equal(fields.get('version'), new Uint8Array([1]))],
|
||||
['relayOrigin', equal(fields.get('relayOrigin'), textEncoder.encode(context.relayOrigin))],
|
||||
['relayEphemeralPublicKey', equal(fields.get('relayEphemeralPublicKey'), relayKey)],
|
||||
['challengeNonce', equal(fields.get('challengeNonce'), nonce)],
|
||||
['challengeId', equal(fields.get('challengeId'), textEncoder.encode(challenge.challengeId))],
|
||||
['userId', equal(fields.get('userId'), textEncoder.encode(context.userId))],
|
||||
['profileId', equal(fields.get('profileId'), textEncoder.encode(context.profileId))],
|
||||
[
|
||||
'organizationId',
|
||||
equal(fields.get('organizationId'), textEncoder.encode(context.organizationId))
|
||||
],
|
||||
['relayHostId', equal(fields.get('relayHostId'), textEncoder.encode(context.relayHostId))],
|
||||
['hostPublicKey', equal(fields.get('hostPublicKey'), context.hostPublicKey)],
|
||||
['assignmentEpoch', equal(fields.get('assignmentEpoch'), uint64(context.assignmentEpoch))],
|
||||
['previousGeneration', equal(previousGeneration, expectedPrevious)],
|
||||
[
|
||||
'resumeRequested',
|
||||
equal(fields.get('resumeRequested'), new Uint8Array([context.resumeRequested ? 1 : 0]))
|
||||
]
|
||||
]
|
||||
const failed = checks.filter(([, ok]) => !ok).map(([name]) => name)
|
||||
if (failed.length > 0) {
|
||||
context.onInvalid?.(`transcript:${failed.join('+')}`)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export function answerRelayHostChallenge(
|
||||
@@ -139,6 +165,7 @@ export function answerRelayHostChallenge(
|
||||
}
|
||||
const plaintext = nacl.box.open(ciphertext, nonce, relayKey, context.hostSecretKey)
|
||||
if (!plaintext) {
|
||||
context.onInvalid?.('challenge-box-open')
|
||||
return null
|
||||
}
|
||||
const domain = textEncoder.encode(`${HOST_CHALLENGE_PLAINTEXT_DOMAIN}\0`)
|
||||
|
||||
@@ -55,6 +55,10 @@ export class RelayOriginPool {
|
||||
return this.basisOrigins.get(basisConnId)?.availableControl ?? null
|
||||
}
|
||||
|
||||
hasLiveControl(): boolean {
|
||||
return this.activeOrigin?.hasLiveControl() ?? false
|
||||
}
|
||||
|
||||
async openInitial(assignment: RelayAssignment, relayJwt: string): Promise<void> {
|
||||
this.assignment = assignment
|
||||
this.relayJwt = relayJwt
|
||||
@@ -186,6 +190,12 @@ export class RelayOriginPool {
|
||||
this.scheduleControlRotation()
|
||||
} catch (error) {
|
||||
if (this.isCurrent() && origin === this.activeOrigin) {
|
||||
// Why: this retry loop ran silently during the 2026-08 incident while
|
||||
// Director 503 throttling stretched recovery to minutes.
|
||||
console.warn(
|
||||
'[relay] control recovery attempt failed:',
|
||||
error instanceof Error ? error.message : String(error)
|
||||
)
|
||||
const retryAfterMs = error instanceof RelayHttpError ? (error.retryAfterMs ?? 0) : 0
|
||||
this.drainRetry.schedule(retryAfterMs, () => this.handleDrain(origin, message))
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ vi.mock('./relay-control-client', () => ({
|
||||
RelayControlClient: class {
|
||||
connect = fakes.controlConnect
|
||||
closeNow = vi.fn()
|
||||
isLive = vi.fn(() => true)
|
||||
confirmResume = vi.fn().mockResolvedValue({
|
||||
type: 'device-resume-confirmed',
|
||||
v: 1,
|
||||
@@ -157,6 +158,33 @@ describe('RelaySessionBroker lifecycle ownership', () => {
|
||||
expect(statuses).toEqual(['connecting'])
|
||||
})
|
||||
|
||||
it('fails connect when the control closes before origin activation', async () => {
|
||||
// Why: a socket can deliver hello-ack and close in the same ws parser turn;
|
||||
// onClose then fires before the connect promise settles, so nothing may
|
||||
// publish this control as active.
|
||||
fakes.controlConnect.mockImplementationOnce(async () => {
|
||||
fakes.controls[0]!.options.onClose(1006)
|
||||
return {
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 1,
|
||||
controlResumeSecret: 'A'.repeat(43),
|
||||
leaseExpiresAt: 1_000_000,
|
||||
activeConnIds: [],
|
||||
pendingConns: []
|
||||
} satisfies RelayHostHelloAckMessage
|
||||
})
|
||||
const statuses: string[] = []
|
||||
|
||||
await expect(
|
||||
RelaySessionBroker.connect(brokerOptions({ onStatus: (status) => statuses.push(status) }))
|
||||
).rejects.toThrow('relay_control_closed_before_activation')
|
||||
|
||||
expect(statuses).not.toContain('registered')
|
||||
expect(statuses.at(-1)).toBe('offline')
|
||||
await vi.waitFor(() => expect(fakes.transports[0]!.stop).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('activates a new origin while keeping basis-bound work on the drained origin', async () => {
|
||||
const firstAck: RelayHostHelloAckMessage = {
|
||||
type: 'host-hello-ack',
|
||||
|
||||
@@ -77,6 +77,10 @@ export class RelaySessionBroker {
|
||||
return `${identity.userId}\0${identity.profileId}\0${identity.organizationId}`
|
||||
}
|
||||
|
||||
isLive(): boolean {
|
||||
return !this.closed && this.originPool.hasLiveControl()
|
||||
}
|
||||
|
||||
get endpoint(): MobileRelayEndpoint | null {
|
||||
const assignment = this.originPool.activeAssignment
|
||||
if (!assignment) {
|
||||
|
||||
Reference in New Issue
Block a user