mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
refactor: organize mobile cloud relay by lifecycle owner
This commit is contained in:
@@ -221,8 +221,8 @@ jobs:
|
||||
pnpm-lock.yaml
|
||||
cloud/pnpm-lock.yaml
|
||||
|
||||
# These two tests import the cloud relay workspace directly. Keeping them in one job
|
||||
# avoids installing and building the same workspace once per unit-test shard.
|
||||
# This test imports the cloud relay workspace directly. Its dedicated job avoids
|
||||
# installing and building the same workspace once per unit-test shard.
|
||||
- name: Install relay integration dependencies
|
||||
id: relay_dependencies
|
||||
if: ${{ !cancelled() && steps.root_dependencies.outcome == 'success' }}
|
||||
@@ -237,5 +237,4 @@ jobs:
|
||||
ORCA_BACKGROUND_LAUNCH: '1'
|
||||
run: >-
|
||||
pnpm exec vitest run --config config/vitest.config.ts
|
||||
tests/e2e/relay-region-compatibility.unit.test.ts
|
||||
tests/e2e/relay-region-correction.unit.test.ts
|
||||
|
||||
@@ -5,7 +5,7 @@ import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs
|
||||
import { SignJWT, exportJWK, generateKeyPair, importJWK, type JWK } from 'jose'
|
||||
import nacl from 'tweetnacl'
|
||||
import WebSocket from 'ws'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client'
|
||||
import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport'
|
||||
|
||||
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// client wrapper, the echo service, phone sockets and workerd memory sampling.
|
||||
import { execSync } from 'node:child_process'
|
||||
import WebSocket from 'ws'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client'
|
||||
import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport'
|
||||
|
||||
export const PORT = 8787
|
||||
|
||||
@@ -39,7 +39,7 @@ export async function runLifecycleChecks(ctx: Ctx, main: Control, mainAck: Ack):
|
||||
mute.on('close', (c) => (muteClose = c))
|
||||
await new Promise((res) => mute.on('open', res))
|
||||
// Complete the handshake by hand with the shipped proof answerer, then never pong.
|
||||
const { answerRelayHostChallenge } = await import('../../../../src/main/runtime/mobile-cloud-relay/relay-host-proof')
|
||||
const { answerRelayHostChallenge } = await import('../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof')
|
||||
mute.send(JSON.stringify({ type: 'host-hello', v: 1, relayHostId: ctx.relayHostId, assignmentEpoch: 7,
|
||||
hostPublicKeyB64: ctx.keypair.publicKeyB64, appVersion: 'spike' }))
|
||||
mute.on('message', (raw) => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'
|
||||
import { SignJWT, type KeyLike } from 'jose'
|
||||
import nacl from 'tweetnacl'
|
||||
import WebSocket from 'ws'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client'
|
||||
import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport'
|
||||
|
||||
export const PORT = 8789
|
||||
|
||||
@@ -8,7 +8,7 @@ import { join } from 'node:path'
|
||||
import { SignJWT, type KeyLike } from 'jose'
|
||||
import nacl from 'tweetnacl'
|
||||
import WebSocket from 'ws'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client'
|
||||
import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport'
|
||||
import { RelayPhoneHelloSchema } from '../../../../src/shared/remote-runtime/relay/mobile-relay-phone-protocol'
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { SignJWT, exportJWK, generateKeyPair, type KeyLike } from 'jose'
|
||||
import nacl from 'tweetnacl'
|
||||
import pg from 'pg'
|
||||
import WebSocket from 'ws'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client'
|
||||
import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client'
|
||||
import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport'
|
||||
import { RelayPhoneHelloSchema } from '../../../../src/shared/remote-runtime/relay/mobile-relay-phone-protocol'
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
Exact relay contract snapshots from `027acb4efa2e6b226d40df266b86367423946d62`, `cloud/packages/relay-contract/src/`. Used to exercise the pre-correction strict wire parsers. Do not format or edit these baseline sources.
|
||||
|
||||
```text
|
||||
aba94e108a5cd0f1af8b38875429ad8636d24c43a728273e3df60d9a1a1d1b6d director-messages.ts
|
||||
bd13b5a694a5d683a5b680c14e46ab33f4ef4a5bfedf040d046b09d540cb4c17 wire-scalars.ts
|
||||
bc89116f884a2f20a6588f9b91219aa596bc2410d28b499a93a78350def109d5 relay-regions.ts
|
||||
8fcae470a5fc72f2fcdde9d2f09cd20289c256356dd490484ac1cfa53839fbe4 control-messages.ts
|
||||
```
|
||||
@@ -1,146 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
Base6432ByteSchema,
|
||||
Base64Raw24ByteSchema,
|
||||
Base64Url32ByteSchema,
|
||||
EpochMsSchema,
|
||||
GenerationSchema,
|
||||
OpaqueIdSchema,
|
||||
PositiveDurationMsSchema,
|
||||
RelayHostIdSchema
|
||||
} from './wire-scalars.js'
|
||||
|
||||
const AppVersionSchema = z.string().min(1).max(128)
|
||||
const BoundedCiphertextSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16 * 1024)
|
||||
.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)
|
||||
const ConnectionKindSchema = z.enum(['invite', 'resume'])
|
||||
|
||||
export const HostHelloSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
relayHostId: RelayHostIdSchema,
|
||||
assignmentEpoch: GenerationSchema,
|
||||
hostPublicKeyB64: Base6432ByteSchema,
|
||||
appVersion: AppVersionSchema,
|
||||
previousGeneration: GenerationSchema.optional(),
|
||||
controlResumeSecret: Base64Url32ByteSchema.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const HostChallengeSchema = z
|
||||
.object({
|
||||
challengeId: OpaqueIdSchema,
|
||||
relayEphemeralPublicKeyB64: Base6432ByteSchema,
|
||||
nonceB64: Base64Raw24ByteSchema,
|
||||
ciphertextB64: BoundedCiphertextSchema,
|
||||
expiresAt: EpochMsSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const HostChallengeAckSchema = z
|
||||
.object({ challengeId: OpaqueIdSchema, proofB64: Base6432ByteSchema })
|
||||
.strict()
|
||||
|
||||
// Advertised on the control upgrade rather than in host-hello: HostHelloSchema
|
||||
// is strict, so a new hello key is refused by every already-deployed cell.
|
||||
export const RELAY_HOST_CAPABILITIES_HEADER = 'x-orca-host-capabilities'
|
||||
// The host accepts kind/relayDeviceId on a pendingConns entry. A host that does
|
||||
// not advertise this parses those entries strictly and would drop the whole ack.
|
||||
export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details'
|
||||
|
||||
export function parseRelayHostCapabilities(
|
||||
header: string | string[] | undefined
|
||||
): ReadonlySet<string> {
|
||||
const raw = Array.isArray(header) ? header.join(',') : (header ?? '')
|
||||
return new Set(
|
||||
raw
|
||||
.split(',')
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token.length > 0 && token.length <= 64)
|
||||
.slice(0, 16)
|
||||
)
|
||||
}
|
||||
|
||||
// kind/relayDeviceId are optional so an entry stays readable by a host that
|
||||
// predates them; the cell only emits them to a host that advertised support.
|
||||
const PendingConnectionSchema = z
|
||||
.object({
|
||||
connId: OpaqueIdSchema,
|
||||
connTicket: Base64Url32ByteSchema,
|
||||
kind: ConnectionKindSchema.optional(),
|
||||
relayDeviceId: OpaqueIdSchema.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const HostHelloAckSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
generation: GenerationSchema,
|
||||
controlResumeSecret: Base64Url32ByteSchema,
|
||||
leaseExpiresAt: EpochMsSchema,
|
||||
activeConnIds: z.array(OpaqueIdSchema).max(8),
|
||||
pendingConns: z.array(PendingConnectionSchema).max(8)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const ConnectionOpenSchema = z
|
||||
.object({
|
||||
connId: OpaqueIdSchema,
|
||||
connTicket: Base64Url32ByteSchema,
|
||||
kind: ConnectionKindSchema,
|
||||
relayDeviceId: OpaqueIdSchema,
|
||||
attachDeadlineMs: PositiveDurationMsSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const HostDataAuthSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
connTicket: Base64Url32ByteSchema,
|
||||
generation: GenerationSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const InviteCreateSchema = z
|
||||
.object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema })
|
||||
.strict()
|
||||
|
||||
export const InviteCreatedSchema = z
|
||||
.object({
|
||||
reqId: OpaqueIdSchema,
|
||||
inviteToken: Base64Url32ByteSchema,
|
||||
expiresAt: EpochMsSchema,
|
||||
maxAttempts: z.number().int().positive().max(16)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const DeviceRevokeSchema = z
|
||||
.object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema })
|
||||
.strict()
|
||||
|
||||
export const AuthRefreshSchema = z.object({ relayJwt: z.string().min(1).max(8 * 1024) }).strict()
|
||||
|
||||
export const DrainSchema = z
|
||||
.object({
|
||||
graceMs: z.number().int().nonnegative().max(60 * 60 * 1000),
|
||||
recovery: z.literal('resolve-director')
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const HeartbeatSchema = z.object({ t: EpochMsSchema }).strict()
|
||||
|
||||
export type HostHello = z.infer<typeof HostHelloSchema>
|
||||
export type HostChallenge = z.infer<typeof HostChallengeSchema>
|
||||
export type HostChallengeAck = z.infer<typeof HostChallengeAckSchema>
|
||||
export type HostHelloAck = z.infer<typeof HostHelloAckSchema>
|
||||
export type ConnectionOpen = z.infer<typeof ConnectionOpenSchema>
|
||||
export type HostDataAuth = z.infer<typeof HostDataAuthSchema>
|
||||
export type InviteCreate = z.infer<typeof InviteCreateSchema>
|
||||
export type InviteCreated = z.infer<typeof InviteCreatedSchema>
|
||||
export type DeviceRevoke = z.infer<typeof DeviceRevokeSchema>
|
||||
export type AuthRefresh = z.infer<typeof AuthRefreshSchema>
|
||||
export type Drain = z.infer<typeof DrainSchema>
|
||||
export type Heartbeat = z.infer<typeof HeartbeatSchema>
|
||||
@@ -1,75 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
Base64Url32ByteSchema,
|
||||
CanonicalHttpsOriginSchema,
|
||||
EpochMsSchema,
|
||||
GenerationSchema,
|
||||
RelayHostIdSchema
|
||||
} from './wire-scalars.js'
|
||||
import { RelayRegionSchema } from './relay-regions.js'
|
||||
|
||||
const SignedAssignmentLeaseSchema = z.string().min(1).max(8 * 1024)
|
||||
|
||||
export const AssignmentRequestSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
relayHostId: RelayHostIdSchema,
|
||||
// Client-declared reconnection; the director verifies it against the
|
||||
// durable assignment before granting fast-lane admission.
|
||||
reconnect: z.boolean().optional(),
|
||||
preferredRegion: RelayRegionSchema.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const AssignmentResponseSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
cellUrl: CanonicalHttpsOriginSchema,
|
||||
assignmentEpoch: GenerationSchema,
|
||||
lease: SignedAssignmentLeaseSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const ResolveRequestSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
relayHostId: RelayHostIdSchema,
|
||||
resumeToken: Base64Url32ByteSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const ResolveResponseSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
cellUrl: CanonicalHttpsOriginSchema,
|
||||
assignmentEpoch: GenerationSchema,
|
||||
leaseExpiresAt: EpochMsSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const RelayMovedSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
cellUrl: CanonicalHttpsOriginSchema,
|
||||
assignmentEpoch: GenerationSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
export function isTrustedNewerMove(input: {
|
||||
sourceOrigin: string
|
||||
configuredDirectorOrigin: string
|
||||
currentAssignmentEpoch: number
|
||||
move: z.infer<typeof RelayMovedSchema>
|
||||
}): boolean {
|
||||
// Why: cells and stale director responses must never redirect a credential-bearing client.
|
||||
return (
|
||||
input.sourceOrigin === input.configuredDirectorOrigin &&
|
||||
input.move.assignmentEpoch > input.currentAssignmentEpoch
|
||||
)
|
||||
}
|
||||
|
||||
export type AssignmentRequest = z.infer<typeof AssignmentRequestSchema>
|
||||
export type AssignmentResponse = z.infer<typeof AssignmentResponseSchema>
|
||||
export type ResolveRequest = z.infer<typeof ResolveRequestSchema>
|
||||
export type ResolveResponse = z.infer<typeof ResolveResponseSchema>
|
||||
export type RelayMoved = z.infer<typeof RelayMovedSchema>
|
||||
@@ -1,71 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const
|
||||
|
||||
export const RelayRegionSchema = z.enum(RELAY_REGIONS)
|
||||
|
||||
export type RelayRegion = z.infer<typeof RelayRegionSchema>
|
||||
|
||||
export const RELAY_DEFAULT_REGION: RelayRegion = 'us-central1'
|
||||
|
||||
// Field-name segment for the flat per-region runtime counters, spelled out rather than derived so
|
||||
// the Terraform side can hold the same literal and a test can compare the two. `satisfies` makes a
|
||||
// new region a compile error here, which is the point: a region with no segment would silently
|
||||
// drop out of the region-skew alert's denominators.
|
||||
export const RELAY_REGION_METRIC_SEGMENTS = {
|
||||
'us-central1': 'UsCentral1',
|
||||
'asia-east2': 'AsiaEast2'
|
||||
} as const satisfies Record<RelayRegion, string>
|
||||
|
||||
const RelayProbeOriginSchema = z.string().url().max(2_048).refine(isCanonicalHttpsOrigin)
|
||||
|
||||
export const RelayRegionCatalogResponseSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
regions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
region: RelayRegionSchema,
|
||||
probeOrigins: z.array(RelayProbeOriginSchema).min(1).max(2)
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.max(RELAY_REGIONS.length)
|
||||
})
|
||||
.strict()
|
||||
.superRefine((catalog, context) => {
|
||||
const regions = new Set<RelayRegion>()
|
||||
const origins = new Set<string>()
|
||||
for (const [regionIndex, entry] of catalog.regions.entries()) {
|
||||
if (regions.has(entry.region)) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
message: 'duplicate relay region',
|
||||
path: ['regions', regionIndex, 'region']
|
||||
})
|
||||
}
|
||||
regions.add(entry.region)
|
||||
for (const [originIndex, origin] of entry.probeOrigins.entries()) {
|
||||
if (origins.has(origin)) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
message: 'duplicate relay probe origin',
|
||||
path: ['regions', regionIndex, 'probeOrigins', originIndex]
|
||||
})
|
||||
}
|
||||
origins.add(origin)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export type RelayRegionCatalogResponse = z.infer<typeof RelayRegionCatalogResponseSchema>
|
||||
|
||||
function isCanonicalHttpsOrigin(value: string): boolean {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return url.protocol === 'https:' && url.origin === value
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/)
|
||||
export const Base64Url24ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{32}$/)
|
||||
export const Base6432ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){10}[A-Za-z0-9+/]{3}=$/)
|
||||
export const Base64Raw24ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){8}$/)
|
||||
export const RelayHostIdSchema = z.string().regex(/^[A-Za-z0-9_-]{16}$/)
|
||||
export const OpaqueIdSchema = z.string().min(1).max(128)
|
||||
export const EpochMsSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
|
||||
export const GenerationSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
|
||||
export const PositiveDurationMsSchema = z.number().int().positive().max(24 * 60 * 60 * 1000)
|
||||
|
||||
export const CanonicalHttpsOriginSchema = z.string().max(2048).refine((value) => {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return url.protocol === 'https:' && url.origin === value && url.pathname === '/'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}, 'must be a canonical HTTPS origin')
|
||||
@@ -475,7 +475,7 @@
|
||||
1 test-no-wall-clock:src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts
|
||||
2 test-no-wall-clock:src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/agent-session/structured-child-records-switch.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts
|
||||
2 test-no-wall-clock:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/push/push-device-registration-persistence.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/push/push-registration-rpc.test.ts
|
||||
@@ -614,7 +614,7 @@
|
||||
1 test-timeout-needs-reason:src/main/providers/local-pty/local-pty-child-process-verdict.test.ts
|
||||
2 test-timeout-needs-reason:src/main/providers/startup-line-typed-length.live-shell.test.ts
|
||||
5 test-timeout-needs-reason:src/main/pty/process-retirement/node-pty-master-fd-retirement.test.ts
|
||||
1 test-timeout-needs-reason:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts
|
||||
1 test-timeout-needs-reason:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts
|
||||
1 test-timeout-needs-reason:src/main/runtime/rpc/server/orchestration-cli-subprocess.test.ts
|
||||
2 test-timeout-needs-reason:src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts
|
||||
1 test-timeout-needs-reason:src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts
|
||||
|
||||
@@ -476,8 +476,8 @@
|
||||
1 src/main/runtime/client/navigation/desktop-chat-creation-history.ts
|
||||
9 src/main/runtime/host-instance-identity.ts
|
||||
4 src/main/runtime/hosts/platform-probe/host-descriptor.ts
|
||||
5 src/main/runtime/mobile-cloud-relay/relay-region-preference.ts
|
||||
2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts
|
||||
5 src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts
|
||||
2 src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts
|
||||
1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts
|
||||
2 src/main/runtime/push/push-unregister-outbox.ts
|
||||
1 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
1 src/main/rate-limits/service/service-polling.ts
|
||||
1 src/main/runtime/agent-state-rules/agent-state-rules-live-update.ts
|
||||
1 src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts
|
||||
3 src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts
|
||||
3 src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts
|
||||
1 src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts
|
||||
1 src/main/runtime/rpc/mobile/mobile-socket-wiring.ts
|
||||
1 src/main/runtime/rpc/transports/websocket/remote-runtime-server-heartbeat.ts
|
||||
|
||||
@@ -3000,19 +3000,17 @@
|
||||
"src/main/runtime/workspaces/creation/managed-worktree-create-registry.test.ts": 4143,
|
||||
"src/main/runtime/workspaces/creation/managed-worktree-create-telemetry.test.ts": 4152,
|
||||
"src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.test.ts": 432,
|
||||
"src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts": 48,
|
||||
"src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts": 408,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts": 580,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts": 161,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts": 1013,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts": 701,
|
||||
"src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts": 48,
|
||||
"src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts": 408,
|
||||
"src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts": 580,
|
||||
"src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts": 1013,
|
||||
"src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts": 701,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts": 147,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts": 122,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts": 175,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts": 196,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts": 253,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts": 127,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts": 73,
|
||||
"src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts": 122,
|
||||
"src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts": 175,
|
||||
"src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts": 196,
|
||||
"src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts": 253,
|
||||
"src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts": 73,
|
||||
"src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts": 804,
|
||||
"src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.integration.test.ts": 11377,
|
||||
"src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.test.ts": 1185,
|
||||
@@ -3509,7 +3507,6 @@
|
||||
"src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts": 4402,
|
||||
"src/main/runtime/rpc/server/runtime-rpc-delegated-device-sync.test.ts": 4986,
|
||||
"src/main/runtime/rpc/server/runtime-rpc-device-key-dispatch.test.ts": 3597,
|
||||
"src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts": 5350,
|
||||
"src/main/runtime/rpc/server/runtime-rpc-local-disconnect-forwarding.test.ts": 5138,
|
||||
"src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts": 30838,
|
||||
"src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts": 4652,
|
||||
|
||||
@@ -45,7 +45,6 @@ export const UNIT_EXCLUDE = [
|
||||
'src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts',
|
||||
'src/shared/startup-shell-portability.live-shell.test.ts',
|
||||
'src/shared/posix-command-path-lookup.test.ts',
|
||||
'tests/e2e/relay-region-compatibility.unit.test.ts',
|
||||
'tests/e2e/relay-region-correction.unit.test.ts',
|
||||
'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts',
|
||||
// Electron probes with in-process deadlines; the package job runs them serially.
|
||||
|
||||
@@ -141,7 +141,7 @@ const NODE_RUNTIME_INCLUDE = [
|
||||
'src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts',
|
||||
'src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts',
|
||||
'src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts',
|
||||
'src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts',
|
||||
'src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts',
|
||||
'src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts',
|
||||
'src/main/ipc/runtime-environments/runtime-environment-preference.test.ts',
|
||||
'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx',
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
setOrcaCloudSignInLink,
|
||||
startOrcaCloudSignInProgress
|
||||
} from './profile-cloud-sign-in-progress'
|
||||
import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/relay-region-preference'
|
||||
import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/region-selection/relay-region-preference'
|
||||
|
||||
import './profile-cloud-capability-refresh'
|
||||
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config'
|
||||
import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store'
|
||||
import { readFreshOrcaCloudSession } from '../../orca-profiles/cloud-session/profile-cloud-session-refresh'
|
||||
import type { OrcaCloudAuthConfig } from '../../../orca-profiles/cloud-auth/profile-cloud-auth-config'
|
||||
import { ensureActiveOrcaProfile } from '../../../orca-profiles/profile-index-store'
|
||||
import { readFreshOrcaCloudSession } from '../../../orca-profiles/cloud-session/profile-cloud-session-refresh'
|
||||
import type { RelayAuthContext } from './relay-auth-identity'
|
||||
|
||||
export async function readRelayAuthContext(
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import '../desktop-relay-service'
|
||||
import { RelayAuthCoordinator } from './relay-auth-coordinator'
|
||||
import type { RelayAuthContext } from './relay-auth-identity'
|
||||
import { RelayHttpError } from '../director/relay-http-client'
|
||||
|
||||
import '../session-lifecycle/relay-session-broker'
|
||||
|
||||
const context: RelayAuthContext = {
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
accessToken: 'access-1',
|
||||
relayEntitled: true
|
||||
}
|
||||
|
||||
describe('relay readiness', () => {
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('stops waiting when a fence cancels the scheduled retry', async () => {
|
||||
vi.useFakeTimers()
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker: async () => {
|
||||
throw new RelayHttpError('token-exchange', 502)
|
||||
},
|
||||
onStatus: () => {},
|
||||
random: () => 1
|
||||
})
|
||||
coordinator.reconcile()
|
||||
const waiting = coordinator.waitForReadiness(20_000)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
coordinator.fenceAndCloseNow()
|
||||
await expect(waiting).resolves.toEqual({
|
||||
ready: false,
|
||||
reason: 'control_not_active',
|
||||
retryAt: null
|
||||
})
|
||||
})
|
||||
|
||||
function coldStartWithHungRetry(): RelayAuthCoordinator {
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new RelayHttpError('assignment', 503))
|
||||
.mockImplementationOnce(() => new Promise(() => {}))
|
||||
return new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: () => {},
|
||||
random: () => 0.5
|
||||
})
|
||||
}
|
||||
|
||||
it('returns at its deadline while the retry it followed is still opening', async () => {
|
||||
vi.useFakeTimers()
|
||||
const coordinator = coldStartWithHungRetry()
|
||||
coordinator.reconcile()
|
||||
let settled: unknown = null
|
||||
void coordinator.waitForReadiness(10_000).then((readiness) => (settled = readiness))
|
||||
await vi.advanceTimersByTimeAsync(9_999)
|
||||
expect(settled).toBeNull()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(settled).toMatchObject({ ready: false, reason: 'director_assignment_503' })
|
||||
coordinator.stop()
|
||||
})
|
||||
})
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RelayAuthCoordinator } from './relay-auth-coordinator'
|
||||
import type { RelayAuthContext } from './relay-auth-identity'
|
||||
import type { RelayAccessTokenRefresh } from './relay-session-broker-contract'
|
||||
import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
+5
-5
@@ -1,12 +1,12 @@
|
||||
import {
|
||||
RELAY_HOST_CLOSE_REASON,
|
||||
type RelayHostCloseReason
|
||||
} from '../../../shared/relay-host-close-reason'
|
||||
import { relayStatusCellUrl } from '../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type * as RelayStatus from '../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { RelayAccessTokenRefresh } from './relay-session-broker-contract'
|
||||
} from '../../../../shared/relay-host-close-reason'
|
||||
import { relayStatusCellUrl } from '../../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type * as RelayStatus from '../../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract'
|
||||
|
||||
import { shouldRetryRelayConnectionError } from './relay-http-client'
|
||||
import { shouldRetryRelayConnectionError } from '../director/relay-http-client'
|
||||
import {
|
||||
RelayReadinessWaiters,
|
||||
relayRetryFloorMs,
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { RelayIdentity } from './relay-session-broker-contract'
|
||||
import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract'
|
||||
|
||||
export type RelayAuthContext = {
|
||||
identity: RelayIdentity
|
||||
@@ -0,0 +1,24 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters'
|
||||
import { RelayReadinessWaiters } from './relay-readiness'
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
describe('relay readiness wait lifetime', () => {
|
||||
it('releases callers without cancelling shared work and permits a later wait', async () => {
|
||||
vi.useFakeTimers()
|
||||
let finish = (): void => {}
|
||||
const work = new Promise<void>((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
const waiters = new RelayReadinessWaiters()
|
||||
const first = waiters.until(work, Date.now() + 10_000)
|
||||
waiters.releaseAll()
|
||||
await expect(first).resolves.toBe(false)
|
||||
expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0)
|
||||
const next = waiters.until(work, Date.now() + 10_000)
|
||||
finish()
|
||||
await expect(next).resolves.toBe(true)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
import { RelayHttpError } from './relay-http-client'
|
||||
import { RelayHostProofClockSkewError } from './relay-host-proof'
|
||||
import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason'
|
||||
import { RelayHttpError } from '../director/relay-http-client'
|
||||
import { RelayHostProofClockSkewError } from '../control-channel/relay-host-proof'
|
||||
import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason'
|
||||
|
||||
// Lowercase reason tokens must form valid relay_<reason> mint-failure codes.
|
||||
export type RelayUnavailableReason =
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair'
|
||||
import type { RelayConnectionOpenMessage, RelayDrainMessage } from './relay-control-protocol'
|
||||
|
||||
export type RelayControlClientOptions = {
|
||||
+1
-1
@@ -4,7 +4,7 @@ import type { Server, Socket } from 'node:net'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair'
|
||||
|
||||
import { RelayControlClient } from './relay-control-client'
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import type { RelayControlClientOptions } from './relay-control-client-options'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import WebSocket, { type RawData } from 'ws'
|
||||
import { MOBILE_RELAY_CLOSE_CODE } from '../../../shared/remote-runtime/relay/mobile-relay-close-codes'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import { MOBILE_RELAY_CLOSE_CODE } from '../../../../shared/remote-runtime/relay/mobile-relay-close-codes'
|
||||
import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason'
|
||||
import {
|
||||
RelayConnectionOpenMessageSchema,
|
||||
RelayControlErrorMessageSchema,
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type { RelayControlRequestTimeout } from './relay-control-requests'
|
||||
import { RELAY_RENEWAL_JITTER_RATIO } from './relay-renewal-jitter'
|
||||
import { RELAY_RENEWAL_JITTER_RATIO } from '../session-lifecycle/relay-renewal-jitter'
|
||||
import {
|
||||
RELAY_CLIENT_KEEPALIVE_FRAME,
|
||||
RelayKeepaliveAckMessageSchema,
|
||||
+1
-1
@@ -3,7 +3,7 @@ import type { RawData } from 'ws'
|
||||
import {
|
||||
DeviceCredentialInstalledSchema,
|
||||
DeviceResumeConfirmedSchema
|
||||
} from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract'
|
||||
} from '../../../../shared/remote-runtime/relay/mobile-relay-credential-contract'
|
||||
|
||||
const OpaqueIdSchema = z.string().min(1).max(128)
|
||||
const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/)
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason'
|
||||
|
||||
const NORMAL_CLOSE_CODE = 1000
|
||||
const REASONED_CLOSE_FLUSH_MS = 1_000
|
||||
+3
-20
@@ -1,4 +1,4 @@
|
||||
import { createHmac, randomBytes } from 'node:crypto'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import {
|
||||
@@ -84,7 +84,6 @@ function buildChallengeFixture(options: {
|
||||
}): {
|
||||
challenge: RelayHostChallenge
|
||||
context: RelayHostProofContext
|
||||
expectedProof: string
|
||||
} {
|
||||
const hostKeys = nacl.box.keyPair()
|
||||
const relayKeys = nacl.box.keyPair()
|
||||
@@ -130,27 +129,11 @@ function buildChallengeFixture(options: {
|
||||
resumeRequested: false,
|
||||
now: () => options.localNow
|
||||
}
|
||||
const expectedProof = createHmac('sha256', secret)
|
||||
.update(text(`${HOST_PROOF_DOMAIN}\0ack\0`))
|
||||
.update(transcript)
|
||||
.digest('base64')
|
||||
return { challenge, context, expectedProof }
|
||||
|
||||
return { challenge, context }
|
||||
}
|
||||
|
||||
describe('answerRelayHostChallenge clock skew (#10401)', () => {
|
||||
it('accepts challenges at the clock-skew boundaries', () => {
|
||||
const issuedAt = 1_700_000_000_000
|
||||
const expiresAt = issuedAt + 10_000
|
||||
for (const localNow of [issuedAt - CLOCK_SKEW_MS, expiresAt + CLOCK_SKEW_MS]) {
|
||||
const { challenge, context, expectedProof } = buildChallengeFixture({
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
localNow
|
||||
})
|
||||
expect(answerRelayHostChallenge(challenge, context)).toBe(expectedProof)
|
||||
}
|
||||
})
|
||||
|
||||
it('still rejects challenges outside the allowed skew window', () => {
|
||||
const serverNow = 1_700_000_000_000
|
||||
const issuedAt = serverNow
|
||||
+1
-1
@@ -6,7 +6,7 @@ import {
|
||||
openHostChallengeEnvelope,
|
||||
parseHostChallengeTranscript,
|
||||
readTranscriptUint64
|
||||
} from '../hosts/identity/host-challenge-envelope'
|
||||
} from '../../hosts/identity/host-challenge-envelope'
|
||||
|
||||
const HOST_PROOF_TRANSCRIPT_DOMAIN = 'orca-relay-host-proof/v1'
|
||||
const HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-relay-host-challenge/v1'
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import type { DeviceRegistry } from '../rpc/server/pairing/device-registry'
|
||||
import type { RelayRevokeOutbox } from './relay-revoke-outbox'
|
||||
import type { DeviceRegistry } from '../../rpc/server/pairing/device-registry'
|
||||
import type { RelayRevokeOutbox } from '../pairing/relay-revoke-outbox'
|
||||
|
||||
type RelayDemandLedgerOptions = {
|
||||
deviceRegistry: DeviceRegistry
|
||||
@@ -8,22 +8,22 @@ import type {
|
||||
PairingProvisionRelayParams
|
||||
} from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import { readRelayAuthContext } from './relay-auth-context'
|
||||
import { relayIdentityKey } from './relay-auth-identity'
|
||||
import { RelayAuthCoordinator } from './relay-auth-coordinator'
|
||||
import { RelayUnavailableError } from './relay-readiness'
|
||||
import { RelaySessionBroker } from './relay-session-broker'
|
||||
import { readRelayAuthContext } from './authentication/relay-auth-context'
|
||||
import { relayIdentityKey } from './authentication/relay-auth-identity'
|
||||
import { RelayAuthCoordinator } from './authentication/relay-auth-coordinator'
|
||||
import { RelayUnavailableError } from './authentication/relay-readiness'
|
||||
import { RelaySessionBroker } from './session-lifecycle/relay-session-broker'
|
||||
import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { PairingRelay } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
|
||||
import type {
|
||||
RelayRevokeOutbox,
|
||||
RelayDeviceBinding,
|
||||
RelayRevokeOutboxItem
|
||||
} from './relay-revoke-outbox'
|
||||
import { pairingAuthorizationForContext } from './relay-pairing-authorization'
|
||||
import { deriveRelayHostId } from './relay-http-client'
|
||||
import { RelayDemandLedger } from './relay-demand-ledger'
|
||||
import { createRelayRegionPreferenceReader } from './relay-region-preference-reader'
|
||||
} from './pairing/relay-revoke-outbox'
|
||||
import { pairingAuthorizationForContext } from './pairing/relay-pairing-authorization'
|
||||
import { deriveRelayHostId } from './director/relay-http-client'
|
||||
import { RelayDemandLedger } from './demand/relay-demand-ledger'
|
||||
import { createRelayRegionPreferenceReader } from './region-selection/relay-region-preference-reader'
|
||||
|
||||
type DesktopRelayServiceOptions = {
|
||||
authConfig: OrcaCloudAuthConfig
|
||||
|
||||
+5
-5
@@ -1,8 +1,8 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import { cancelUnreadResponseBody } from '../../lib/unread-response-body'
|
||||
import { parseRetryAfterHeaderMs } from '../../../shared/retry-after-header'
|
||||
import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair'
|
||||
import { cancelUnreadResponseBody } from '../../../lib/unread-response-body'
|
||||
import { parseRetryAfterHeaderMs } from '../../../../shared/retry-after-header'
|
||||
import {
|
||||
RelayAssignAbortedError,
|
||||
RelayAssignRateLimitedError,
|
||||
@@ -10,11 +10,11 @@ import {
|
||||
sharedRelayAssignRateGate,
|
||||
type RelayAssignRateGate
|
||||
} from './relay-assign-rate-gate'
|
||||
import type { RelayRegion } from './relay-region-probe'
|
||||
import type { RelayRegion } from '../region-selection/relay-region-probe'
|
||||
import {
|
||||
RelayRegionCorrectionResponseSchema,
|
||||
type RelayRegionCorrectionRequest
|
||||
} from './relay-region-correction-protocol'
|
||||
} from '../region-selection/relay-region-correction-protocol'
|
||||
|
||||
const RELAY_HTTP_REQUEST_DEADLINE_MS = 15_000
|
||||
const RELAY_RETRY_AFTER_MAX_MS = 5 * 60_000
|
||||
+5
-5
@@ -1,10 +1,10 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring'
|
||||
import type { RelayIdentity } from './relay-session-broker-contract'
|
||||
import type { RelayAssignment } from './relay-http-client'
|
||||
import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring'
|
||||
import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract'
|
||||
import type { RelayAssignment } from '../director/relay-http-client'
|
||||
import type { RelayControlOrigin } from './relay-control-origin'
|
||||
import type { RelayDrainMessage } from './relay-control-protocol'
|
||||
import type { RelayDrainMessage } from '../control-channel/relay-control-protocol'
|
||||
|
||||
export type RelayControlOriginOptions = {
|
||||
assignment: RelayAssignment
|
||||
+6
-6
@@ -1,14 +1,14 @@
|
||||
import type { RelayControlOriginOptions } from './relay-control-origin-options'
|
||||
import { CloudRelayTransport } from '../rpc/transports/relay-transport'
|
||||
import { RelayControlClient } from './relay-control-client'
|
||||
import { RELAY_HOST_ATTACH_DEADLINE_MS } from './relay-control-protocol'
|
||||
import { CloudRelayTransport } from '../../rpc/transports/relay-transport'
|
||||
import { RelayControlClient } from '../control-channel/relay-control-client'
|
||||
import { RELAY_HOST_ATTACH_DEADLINE_MS } from '../control-channel/relay-control-protocol'
|
||||
import type {
|
||||
RelayConnectionOpenMessage,
|
||||
RelayHostHelloAckMessage,
|
||||
RelayPendingConnection
|
||||
} from './relay-control-protocol'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import type { RelayAssignment } from './relay-http-client'
|
||||
} from '../control-channel/relay-control-protocol'
|
||||
import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason'
|
||||
import type { RelayAssignment } from '../director/relay-http-client'
|
||||
|
||||
const OBSERVED_OPEN_LIMIT = 16
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import type { RelayControlOrigin } from './relay-control-origin'
|
||||
import type { RelayAssignment } from './relay-http-client'
|
||||
import { relayRenewalDelayMs } from './relay-renewal-jitter'
|
||||
import type { RelayAssignment } from '../director/relay-http-client'
|
||||
import { relayRenewalDelayMs } from '../session-lifecycle/relay-renewal-jitter'
|
||||
|
||||
type RotationOptions = {
|
||||
current: () => RelayControlOrigin | null
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring'
|
||||
import type { RelayIdentity } from './relay-session-broker-contract'
|
||||
import type { MobileRelayStatus as RelayBrokerStatus } from '../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { RelayRegion } from './relay-region-probe'
|
||||
import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring'
|
||||
import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract'
|
||||
import type { MobileRelayStatus as RelayBrokerStatus } from '../../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { RelayRegion } from '../region-selection/relay-region-probe'
|
||||
|
||||
export type RelayOriginPoolOptions = {
|
||||
directorUrl: string
|
||||
+9
-5
@@ -1,11 +1,15 @@
|
||||
import { RelayOriginRetirement } from './relay-origin-retirement'
|
||||
import type { RelayOriginPoolOptions } from './relay-origin-pool-options'
|
||||
import { RelayControlOrigin } from './relay-control-origin'
|
||||
import type { RelayControlClient } from './relay-control-client'
|
||||
import type { RelayDrainMessage } from './relay-control-protocol'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import { RelayRetrySchedule } from './relay-retry-schedule'
|
||||
import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client'
|
||||
import type { RelayControlClient } from '../control-channel/relay-control-client'
|
||||
import type { RelayDrainMessage } from '../control-channel/relay-control-protocol'
|
||||
import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason'
|
||||
import { RelayRetrySchedule } from '../authentication/relay-retry-schedule'
|
||||
import {
|
||||
RelayHttpError,
|
||||
requestRelayAssignment,
|
||||
type RelayAssignment
|
||||
} from '../director/relay-http-client'
|
||||
import { RelayControlRotation } from './relay-control-rotation'
|
||||
|
||||
export class RelayOriginPool {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { RelayDrainMessage } from './relay-control-protocol'
|
||||
import type { RelayDrainMessage } from '../control-channel/relay-control-protocol'
|
||||
import type { RelayControlOrigin } from './relay-control-origin'
|
||||
|
||||
export class RelayOriginRetirement {
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import type { MobilePairingConnectionContext } from '../rpc/server/runtime-rpc-pairing-types'
|
||||
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
|
||||
import type { MobilePairingConnectionContext } from '../../rpc/server/runtime-rpc-pairing-types'
|
||||
import type { DeviceCredentialInstallAuthorization } from '../control-channel/relay-control-requests'
|
||||
|
||||
// Derives install authorization only from immutable connection metadata, never from request params.
|
||||
export function pairingAuthorizationForContext(
|
||||
@@ -0,0 +1,33 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { RelayRevokeOutbox } from './relay-revoke-outbox'
|
||||
|
||||
describe('RelayRevokeOutbox', () => {
|
||||
const paths: string[] = []
|
||||
afterEach(() => {
|
||||
for (const path of paths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('durably retains an idempotent account-scoped revoke after local deletion', () => {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-'))
|
||||
paths.push(path)
|
||||
const binding = {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'device-1',
|
||||
ownerIdentityKey: 'user-1\0profile-1\0org-1'
|
||||
}
|
||||
const first = new RelayRevokeOutbox(path).enqueue(binding)
|
||||
const reloaded = new RelayRevokeOutbox(path)
|
||||
expect(reloaded.enqueue(binding).reqId).toBe(first.reqId)
|
||||
expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first])
|
||||
reloaded.remove(first.reqId)
|
||||
expect(
|
||||
new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId)
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
+1
-1
@@ -5,7 +5,7 @@ import {
|
||||
hardenExistingSecureFile,
|
||||
isUnreadableError,
|
||||
writeSecureJsonFile
|
||||
} from '../../../shared/secure-storage/secure-file'
|
||||
} from '../../../../shared/secure-storage/secure-file'
|
||||
|
||||
export type RelayDeviceBinding = {
|
||||
relayHostId: string
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import { cancelUnreadResponseBody } from '../../lib/unread-response-body'
|
||||
import { readFetchResponseJsonWithinLimit } from '../../../shared/fetch-response-body'
|
||||
import { cancelUnreadResponseBody } from '../../../lib/unread-response-body'
|
||||
import { readFetchResponseJsonWithinLimit } from '../../../../shared/fetch-response-body'
|
||||
import { RelayRegionCatalogSchema, type RelayRegionCatalog } from './relay-region-probe'
|
||||
|
||||
const CATALOG_MAX_BYTES = 16 * 1024
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { z } from 'zod'
|
||||
import {
|
||||
hardenExistingSecureFile,
|
||||
writeSecureJsonFile
|
||||
} from '../../../shared/secure-storage/secure-file'
|
||||
} from '../../../../shared/secure-storage/secure-file'
|
||||
import { fetchRelayRegionCatalog, relayDirectorHost } from './relay-region-catalog-fetch'
|
||||
import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol'
|
||||
import {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { performance } from 'node:perf_hooks'
|
||||
import { z } from 'zod'
|
||||
import { cancelUnreadResponseBody } from '../../lib/unread-response-body'
|
||||
import { cancelUnreadResponseBody } from '../../../lib/unread-response-body'
|
||||
|
||||
export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const
|
||||
export type RelayRegion = (typeof RELAY_REGIONS)[number]
|
||||
+5
-1
@@ -1,4 +1,8 @@
|
||||
import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client'
|
||||
import {
|
||||
RelayHttpError,
|
||||
requestRelayAssignment,
|
||||
type RelayAssignment
|
||||
} from '../director/relay-http-client'
|
||||
import type {
|
||||
RelayRegionCorrectionRequest,
|
||||
RelayRegionDecision,
|
||||
@@ -1,131 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { DesktopRelayService } from './desktop-relay-service'
|
||||
import { RelayAuthCoordinator } from './relay-auth-coordinator'
|
||||
import type { RelayAuthContext } from './relay-auth-identity'
|
||||
import { RelayHttpError } from './relay-http-client'
|
||||
|
||||
import { RelaySessionBroker } from './relay-session-broker'
|
||||
|
||||
const context: RelayAuthContext = {
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
accessToken: 'access-1',
|
||||
relayEntitled: true
|
||||
}
|
||||
|
||||
function fakeSessionBroker(): RelaySessionBroker {
|
||||
const broker = Object.create(RelaySessionBroker.prototype)
|
||||
Object.defineProperties(broker, {
|
||||
closeNow: { value: vi.fn() },
|
||||
isLive: { value: () => true },
|
||||
createPairingRelay: { value: vi.fn(async () => ({ inviteExpiresAt: 1 })) },
|
||||
endpoint: { value: null },
|
||||
hostId: { value: 'host-1' },
|
||||
ownerIdentityKey: { value: 'owner-1' }
|
||||
})
|
||||
return broker
|
||||
}
|
||||
|
||||
function serviceWith(coordinator: RelayAuthCoordinator): DesktopRelayService {
|
||||
const service = Object.create(DesktopRelayService.prototype)
|
||||
return Object.assign(service, {
|
||||
coordinator,
|
||||
stopped: false,
|
||||
livenessTimer: null,
|
||||
demandExpiryTimer: null,
|
||||
demandLedger: { acquireTransient: () => () => {}, nextPendingExpiry: () => null }
|
||||
})
|
||||
}
|
||||
|
||||
describe('relay readiness', () => {
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('waits through the retry a cold-start failure scheduled instead of failing the mint', async () => {
|
||||
vi.useFakeTimers()
|
||||
const broker = fakeSessionBroker()
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new RelayHttpError('assignment', 503))
|
||||
.mockResolvedValueOnce(broker)
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: () => {},
|
||||
random: () => 1
|
||||
})
|
||||
const service = serviceWith(coordinator)
|
||||
const mint = service.createPairingRelay('device-1')
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
await expect(mint).resolves.toMatchObject({ binding: { relayHostId: 'host-1' } })
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
service.stop()
|
||||
})
|
||||
|
||||
it('stops waiting when a fence cancels the scheduled retry', async () => {
|
||||
vi.useFakeTimers()
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker: async () => {
|
||||
throw new RelayHttpError('token-exchange', 502)
|
||||
},
|
||||
onStatus: () => {},
|
||||
random: () => 1
|
||||
})
|
||||
coordinator.reconcile()
|
||||
const waiting = coordinator.waitForReadiness(20_000)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
coordinator.fenceAndCloseNow()
|
||||
await expect(waiting).resolves.toEqual({
|
||||
ready: false,
|
||||
reason: 'control_not_active',
|
||||
retryAt: null
|
||||
})
|
||||
})
|
||||
|
||||
function coldStartWithHungRetry(): RelayAuthCoordinator {
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new RelayHttpError('assignment', 503))
|
||||
.mockImplementationOnce(() => new Promise(() => {}))
|
||||
return new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: () => {},
|
||||
random: () => 0.5
|
||||
})
|
||||
}
|
||||
|
||||
it('returns at its deadline while the retry it followed is still opening', async () => {
|
||||
vi.useFakeTimers()
|
||||
const coordinator = coldStartWithHungRetry()
|
||||
coordinator.reconcile()
|
||||
let settled: unknown = null
|
||||
void coordinator.waitForReadiness(10_000).then((readiness) => (settled = readiness))
|
||||
await vi.advanceTimersByTimeAsync(9_999)
|
||||
expect(settled).toBeNull()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(settled).toMatchObject({ ready: false, reason: 'director_assignment_503' })
|
||||
coordinator.stop()
|
||||
})
|
||||
|
||||
it.each(['fence', 'stop'] as const)(
|
||||
'a %s releases a waiter whose followed retry is still opening',
|
||||
async (action) => {
|
||||
vi.useFakeTimers()
|
||||
const coordinator = coldStartWithHungRetry()
|
||||
coordinator.reconcile()
|
||||
let settled: unknown = null
|
||||
void coordinator.waitForReadiness(20_000).then((readiness) => (settled = readiness))
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(settled).toBeNull()
|
||||
if (action === 'fence') {
|
||||
coordinator.fenceAndCloseNow()
|
||||
} else {
|
||||
coordinator.stop()
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(settled).toMatchObject({ ready: false, retryAt: null })
|
||||
coordinator.stop()
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -1,118 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RelayAuthCoordinator } from './relay-auth-coordinator'
|
||||
import type { RelayAuthContext } from './relay-auth-identity'
|
||||
import { RelayHttpError } from './relay-http-client'
|
||||
|
||||
const context: RelayAuthContext = {
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
accessToken: 'access-1',
|
||||
relayEntitled: true
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('RelayAuthCoordinator transient recovery', () => {
|
||||
it('does not carry a pending retry across an identity switch', async () => {
|
||||
vi.useFakeTimers()
|
||||
let current = context
|
||||
const broker = { closeNow: vi.fn() }
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('temporary control open failure'))
|
||||
.mockResolvedValueOnce(broker)
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => current,
|
||||
openBroker,
|
||||
onStatus: vi.fn(),
|
||||
random: () => 0.75
|
||||
})
|
||||
|
||||
coordinator.reconcile()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledOnce()
|
||||
|
||||
current = {
|
||||
...context,
|
||||
identity: { ...context.identity, profileId: 'profile-2' }
|
||||
}
|
||||
coordinator.reconcile()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
expect(coordinator.getActiveBroker()).toBe(broker)
|
||||
await vi.advanceTimersByTimeAsync(120_000)
|
||||
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('RelayAuthCoordinator liveness safety net', () => {
|
||||
it('reopens a broker that died leaving no retry timer behind', async () => {
|
||||
// Expired-token refresh failure leaves no retry; ensureLive must revive it.
|
||||
vi.useFakeTimers()
|
||||
const dead = { closeNow: vi.fn(), isLive: () => false }
|
||||
const live = { closeNow: vi.fn(), isLive: () => true }
|
||||
const openBroker = vi.fn().mockResolvedValueOnce(dead).mockResolvedValueOnce(live)
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: vi.fn(),
|
||||
random: () => 0.5
|
||||
})
|
||||
|
||||
coordinator.reconcile()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(coordinator.getActiveBroker()).toBe(dead)
|
||||
await vi.advanceTimersByTimeAsync(600_000)
|
||||
expect(openBroker).toHaveBeenCalledOnce()
|
||||
|
||||
coordinator.ensureLive()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
expect(dead.closeNow).toHaveBeenCalled()
|
||||
expect(coordinator.getActiveBroker()).toBe(live)
|
||||
})
|
||||
|
||||
it('does not disturb a live broker, a scheduled retry, or an open in flight', async () => {
|
||||
vi.useFakeTimers()
|
||||
const broker = { closeNow: vi.fn(), isLive: () => true }
|
||||
let releaseOpen: ((value: typeof broker) => void) | undefined
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new RelayHttpError('assignment', 503, 30_000))
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releaseOpen = resolve
|
||||
})
|
||||
)
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: vi.fn(),
|
||||
random: () => 0.5
|
||||
})
|
||||
|
||||
coordinator.reconcile()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledOnce()
|
||||
|
||||
coordinator.ensureLive()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledOnce()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000)
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
coordinator.ensureLive()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
releaseOpen?.(broker)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(coordinator.getActiveBroker()).toBe(broker)
|
||||
|
||||
coordinator.ensureLive()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(openBroker).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,62 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { RelayControlLiveness } from './relay-control-liveness'
|
||||
|
||||
describe('RelayControlLiveness keepalive', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function liveness(live = { value: true }) {
|
||||
const terminate = vi.fn()
|
||||
// The relay's ack is an inbound frame.
|
||||
const sendKeepalive = vi.fn((frame: string) => {
|
||||
expect(frame).toBe('{"type":"keepalive"}')
|
||||
instance.noteInbound()
|
||||
})
|
||||
const instance: RelayControlLiveness = new RelayControlLiveness({
|
||||
cellUrl: 'https://relay.test',
|
||||
ping: vi.fn(),
|
||||
isLive: () => live.value,
|
||||
terminate,
|
||||
send: sendKeepalive
|
||||
})
|
||||
return { instance, sendKeepalive, terminate, live }
|
||||
}
|
||||
|
||||
it('sends a keepalive instead of tearing down when its own timers were held back', () => {
|
||||
vi.useFakeTimers()
|
||||
const terminate = vi.fn()
|
||||
const send = vi.fn()
|
||||
const instance = new RelayControlLiveness({
|
||||
cellUrl: 'https://relay.test',
|
||||
ping: vi.fn(),
|
||||
isLive: () => true,
|
||||
terminate,
|
||||
send
|
||||
})
|
||||
instance.start()
|
||||
instance.startKeepalive(25_000)
|
||||
// A throttled app: no timer ran for 100 s, then the silence check runs before the keepalive.
|
||||
vi.setSystemTime(Date.now() + 100_000)
|
||||
vi.advanceTimersToNextTimer()
|
||||
expect(terminate).not.toHaveBeenCalled()
|
||||
expect(send).toHaveBeenCalledWith('{"type":"keepalive"}')
|
||||
// Still unanswered at a later check: the link is judged dead as before.
|
||||
vi.advanceTimersByTime(80_000)
|
||||
expect(terminate).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('ignores an offer before the control is active and stops with the control', () => {
|
||||
vi.useFakeTimers()
|
||||
const { instance, sendKeepalive } = liveness()
|
||||
instance.startKeepalive(25_000)
|
||||
vi.advanceTimersByTime(50_000)
|
||||
expect(sendKeepalive).not.toHaveBeenCalled()
|
||||
instance.start()
|
||||
instance.startKeepalive(25_000)
|
||||
instance.stop()
|
||||
vi.advanceTimersByTime(100_000)
|
||||
expect(sendKeepalive).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,45 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { sharedPromiseSettlementWaiters } from '../../../shared/promise-settlement-waiters'
|
||||
import { RelayReadinessWaiters } from './relay-readiness'
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
describe('relay readiness wait lifetime', () => {
|
||||
it('detaches expired mint callers while shared reconnect work remains pending', async () => {
|
||||
vi.useFakeTimers()
|
||||
let finish = (): void => {}
|
||||
const work = new Promise<void>((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
const observed = vi.spyOn(work, 'then')
|
||||
const waiters = new RelayReadinessWaiters()
|
||||
const anchor = waiters.until(work, Date.now() + 10_000)
|
||||
for (let index = 0; index < 100; index += 1) {
|
||||
const waiting = waiters.until(work, Date.now() + 1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
await expect(waiting).resolves.toBe(false)
|
||||
}
|
||||
expect(observed).toHaveBeenCalledOnce()
|
||||
expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(1)
|
||||
finish()
|
||||
await expect(anchor).resolves.toBe(true)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('releases callers without cancelling shared work and permits a later wait', async () => {
|
||||
vi.useFakeTimers()
|
||||
let finish = (): void => {}
|
||||
const work = new Promise<void>((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
const waiters = new RelayReadinessWaiters()
|
||||
const first = waiters.until(work, Date.now() + 10_000)
|
||||
waiters.releaseAll()
|
||||
await expect(first).resolves.toBe(false)
|
||||
expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0)
|
||||
const next = waiters.until(work, Date.now() + 10_000)
|
||||
finish()
|
||||
await expect(next).resolves.toBe(true)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,99 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RelayAssignment } from './relay-http-client'
|
||||
import type * as RelayHttpClientModule from './relay-http-client'
|
||||
import type { RelayRegionWindow } from './relay-region-correction-protocol'
|
||||
const fake = vi.hoisted(() => ({ assign: vi.fn() }))
|
||||
vi.mock('./relay-http-client', async (original) => ({
|
||||
...(await original<typeof RelayHttpClientModule>()),
|
||||
requestRelayAssignment: fake.assign
|
||||
}))
|
||||
import { RelayRegionRefresh } from './relay-region-refresh'
|
||||
const HOUR = 60 * 60_000
|
||||
const window: RelayRegionWindow = {
|
||||
generation: 1,
|
||||
assignmentEpoch: 1,
|
||||
incumbentRegion: 'asia-east2',
|
||||
expiresAt: 24 * HOUR,
|
||||
policyVersion: 1
|
||||
}
|
||||
const assignment: RelayAssignment = {
|
||||
v: 1,
|
||||
cellUrl: 'https://source.example.test',
|
||||
assignmentEpoch: 1,
|
||||
lease: 'test',
|
||||
regionCorrection: { v: 1, window }
|
||||
}
|
||||
let scheduler: RelayRegionRefresh
|
||||
function setup(random = 0.5) {
|
||||
const measure = vi.fn().mockResolvedValue({
|
||||
outcome: 'conclusive',
|
||||
measurements: { 'us-central1': 30, 'asia-east2': 200 }
|
||||
})
|
||||
const applyAssignment = vi.fn(() => true)
|
||||
const isOnline = vi.fn(() => true)
|
||||
scheduler = new RelayRegionRefresh({
|
||||
directorUrl: 'https://director.example.test',
|
||||
relayHostId: 'test-host',
|
||||
token: () => 'test-token',
|
||||
assignment: () => assignment,
|
||||
isCurrent: () => true,
|
||||
isOnline,
|
||||
applyAssignment,
|
||||
measure,
|
||||
random: () => random,
|
||||
now: () => Date.now()
|
||||
})
|
||||
return { measure, applyAssignment, isOnline }
|
||||
}
|
||||
describe('broker-owned region decision refresh', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(0)
|
||||
fake.assign.mockReset()
|
||||
})
|
||||
afterEach(() => {
|
||||
scheduler?.close()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('retries exactly the same report without probing or extending its window', async () => {
|
||||
const { measure } = setup()
|
||||
fake.assign
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.mockResolvedValue({ ...assignment, regionCorrection: { v: 1, reportStatus: 'accepted' } })
|
||||
scheduler.start(assignment)
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(measure).toHaveBeenCalledOnce()
|
||||
expect(fake.assign).toHaveBeenCalledTimes(2)
|
||||
expect(fake.assign.mock.calls[0]![0].regionCorrection).toEqual(
|
||||
fake.assign.mock.calls[1]![0].regionCorrection
|
||||
)
|
||||
})
|
||||
|
||||
it('does not report a measurement that completed after broker close', async () => {
|
||||
const { measure } = setup()
|
||||
let resolve!: (value: unknown) => void
|
||||
measure.mockReturnValue(
|
||||
new Promise((done) => {
|
||||
resolve = done
|
||||
})
|
||||
)
|
||||
scheduler.start(assignment)
|
||||
scheduler.close()
|
||||
resolve({ outcome: 'inconclusive', reason: 'incomplete-measurement' })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fake.assign).not.toHaveBeenCalled()
|
||||
})
|
||||
it('uses a successor window after an expired report retry', async () => {
|
||||
setup()
|
||||
fake.assign.mockRejectedValueOnce(new Error('offline')).mockResolvedValue({
|
||||
...assignment,
|
||||
regionCorrection: { v: 1, window: { ...window, generation: 2, expiresAt: 48 * HOUR } }
|
||||
})
|
||||
scheduler.start(assignment)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
vi.setSystemTime(25 * HOUR)
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(fake.assign.mock.calls[1]![0].regionCorrection).toEqual({ v: 1, action: 'issue-window' })
|
||||
})
|
||||
})
|
||||
@@ -1,85 +0,0 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as SecureFileModule from '../../../shared/secure-storage/secure-file'
|
||||
import { RelayRevokeOutbox } from './relay-revoke-outbox'
|
||||
|
||||
const secureFileMocks = vi.hoisted(() => ({ failWrites: false }))
|
||||
|
||||
vi.mock('../../../shared/secure-storage/secure-file', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof SecureFileModule>()
|
||||
return {
|
||||
...actual,
|
||||
writeSecureJsonFile: (targetPath: string, value: unknown) => {
|
||||
if (secureFileMocks.failWrites) {
|
||||
throw new Error('disk full')
|
||||
}
|
||||
actual.writeSecureJsonFile(targetPath, value)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
describe('RelayRevokeOutbox', () => {
|
||||
const paths: string[] = []
|
||||
afterEach(() => {
|
||||
secureFileMocks.failWrites = false
|
||||
for (const path of paths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('durably retains an idempotent account-scoped revoke after local deletion', () => {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-'))
|
||||
paths.push(path)
|
||||
const binding = {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'device-1',
|
||||
ownerIdentityKey: 'user-1\0profile-1\0org-1'
|
||||
}
|
||||
const first = new RelayRevokeOutbox(path).enqueue(binding)
|
||||
const reloaded = new RelayRevokeOutbox(path)
|
||||
expect(reloaded.enqueue(binding).reqId).toBe(first.reqId)
|
||||
expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first])
|
||||
reloaded.remove(first.reqId)
|
||||
expect(
|
||||
new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId)
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('does not retain an enqueue that failed to reach disk', () => {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-'))
|
||||
paths.push(path)
|
||||
const binding = {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'device-1',
|
||||
ownerIdentityKey: 'user-1\0profile-1\0org-1'
|
||||
}
|
||||
const outbox = new RelayRevokeOutbox(path)
|
||||
secureFileMocks.failWrites = true
|
||||
expect(() => outbox.enqueue(binding)).toThrow('disk full')
|
||||
|
||||
secureFileMocks.failWrites = false
|
||||
const persisted = outbox.enqueue(binding)
|
||||
expect(
|
||||
new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId)
|
||||
).toEqual([persisted])
|
||||
})
|
||||
|
||||
it('does not remove an item in memory when the durable removal fails', () => {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-'))
|
||||
paths.push(path)
|
||||
const binding = {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'device-1',
|
||||
ownerIdentityKey: 'user-1\0profile-1\0org-1'
|
||||
}
|
||||
const outbox = new RelayRevokeOutbox(path)
|
||||
const item = outbox.enqueue(binding)
|
||||
secureFileMocks.failWrites = true
|
||||
expect(() => outbox.remove(item.reqId)).toThrow('disk full')
|
||||
|
||||
secureFileMocks.failWrites = false
|
||||
expect(outbox.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([item])
|
||||
})
|
||||
})
|
||||
@@ -1,45 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RelayWallClockTimer } from './relay-wall-clock-timer'
|
||||
|
||||
function resumeSource(): {
|
||||
subscribe: (onResume: () => void) => () => void
|
||||
resume: () => void
|
||||
count: () => number
|
||||
} {
|
||||
const listeners = new Set<() => void>()
|
||||
return {
|
||||
subscribe: (onResume) => {
|
||||
listeners.add(onResume)
|
||||
onResume()
|
||||
return () => listeners.delete(onResume)
|
||||
},
|
||||
resume: () => {
|
||||
for (const listener of Array.from(listeners)) {
|
||||
listener()
|
||||
}
|
||||
},
|
||||
count: () => listeners.size
|
||||
}
|
||||
}
|
||||
|
||||
describe('RelayWallClockTimer', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('runs a task that fell due during a sleep as soon as the machine resumes', () => {
|
||||
vi.useFakeTimers()
|
||||
let wall = 1_000_000
|
||||
const source = resumeSource()
|
||||
const timer = new RelayWallClockTimer(() => wall, source.subscribe)
|
||||
const task = vi.fn()
|
||||
timer.schedule(180_000, task)
|
||||
// Asleep: the wall clock moves, the timer clock does not.
|
||||
wall += 200_000
|
||||
source.resume()
|
||||
expect(task).toHaveBeenCalledTimes(1)
|
||||
vi.advanceTimersByTime(180_000)
|
||||
expect(task).toHaveBeenCalledTimes(1)
|
||||
expect(source.count()).toBe(0)
|
||||
})
|
||||
})
|
||||
+10
-7
@@ -1,11 +1,14 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config'
|
||||
import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import type { RelayRegion } from './relay-region-probe'
|
||||
import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol'
|
||||
import type { OrcaCloudAuthConfig } from '../../../orca-profiles/cloud-auth/profile-cloud-auth-config'
|
||||
import type { MobileRelayStatusPublisher } from '../../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring'
|
||||
import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason'
|
||||
import type { RelayRegion } from '../region-selection/relay-region-probe'
|
||||
import type {
|
||||
RelayRegionDecision,
|
||||
RelayRegionWindow
|
||||
} from '../region-selection/relay-region-correction-protocol'
|
||||
|
||||
export type RelayIdentity = {
|
||||
userId: string
|
||||
+9
-9
@@ -3,21 +3,21 @@ import type { RelaySessionBrokerOptions } from './relay-session-broker-contract'
|
||||
import {
|
||||
relayStatusCellUrl,
|
||||
type MobileRelayStatus as RelayBrokerStatus
|
||||
} from '../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { PairingRelay } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
|
||||
import type * as RelayCredentials from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract'
|
||||
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
|
||||
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
|
||||
} from '../../../../shared/remote-runtime/relay/mobile-relay-status'
|
||||
import type { PairingRelay } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
|
||||
import type * as RelayCredentials from '../../../../shared/remote-runtime/relay/mobile-relay-credential-contract'
|
||||
import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason'
|
||||
import type { DeviceCredentialInstallAuthorization } from '../control-channel/relay-control-requests'
|
||||
import {
|
||||
deriveRelayHostId,
|
||||
exchangeRelayAuthorization,
|
||||
requestRelayAssignment,
|
||||
type RelayAuthorization,
|
||||
type RelayAssignment
|
||||
} from './relay-http-client'
|
||||
import { relayIdentityKey } from './relay-auth-identity'
|
||||
import { RelayOriginPool } from './relay-origin-pool'
|
||||
import { RelayRegionRefresh } from './relay-region-refresh'
|
||||
} from '../director/relay-http-client'
|
||||
import { relayIdentityKey } from '../authentication/relay-auth-identity'
|
||||
import { RelayOriginPool } from '../origin-lifecycle/relay-origin-pool'
|
||||
import { RelayRegionRefresh } from '../region-selection/relay-region-refresh'
|
||||
import { relayRenewalDelayMs } from './relay-renewal-jitter'
|
||||
import { RelayWallClockTimer } from './relay-wall-clock-timer'
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { subscribeSystemPowerLifecycle } from '../../power/system-power-lifecycle'
|
||||
import { subscribeSystemPowerLifecycle } from '../../../power/system-power-lifecycle'
|
||||
|
||||
type SubscribeResume = (onResume: () => void) => () => void
|
||||
|
||||
+2
-17
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { DesktopRelayService } from './desktop-relay-service'
|
||||
import { createDesktopRelayServiceInstaller } from './desktop-relay-service-installer'
|
||||
import type { DesktopRelayService } from '../desktop-relay-service'
|
||||
import { createDesktopRelayServiceInstaller } from '../desktop-relay-service-installer'
|
||||
|
||||
function fakeService(): DesktopRelayService {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installer only calls start() and wraps the provider methods.
|
||||
@@ -25,21 +25,6 @@ function installerWith(overrides: {
|
||||
}
|
||||
|
||||
describe('createDesktopRelayServiceInstaller', () => {
|
||||
it('holds the first install until the network is ready and shares one in-flight install', async () => {
|
||||
let ready!: () => void
|
||||
const whenNetworkReady = new Promise<void>((resolve) => (ready = resolve))
|
||||
const create = vi.fn(() => fakeService())
|
||||
const { installer } = installerWith({ create, whenNetworkReady })
|
||||
|
||||
const first = installer.ensure()
|
||||
const second = installer.ensure()
|
||||
await Promise.resolve()
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
ready()
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([true, true])
|
||||
expect(create).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('refuses installs after sign-out, including one already waiting, until the next auth change', async () => {
|
||||
let ready!: () => void
|
||||
const whenNetworkReady = new Promise<void>((resolve) => (ready = resolve))
|
||||
+4
-4
@@ -4,10 +4,10 @@ import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import WebSocketClient, { WebSocketServer, type RawData, type WebSocket } from 'ws'
|
||||
import { DeviceRegistry } from '../rpc/server/pairing/device-registry'
|
||||
import { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring'
|
||||
import { CloudRelayTransport } from '../rpc/transports/relay-transport'
|
||||
import { deriveRelayHostId } from './relay-http-client'
|
||||
import { DeviceRegistry } from '../../rpc/server/pairing/device-registry'
|
||||
import { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring'
|
||||
import { CloudRelayTransport } from '../../rpc/transports/relay-transport'
|
||||
import { deriveRelayHostId } from '../director/relay-http-client'
|
||||
import { SimulatedMobileE2EEV2Peer } from './simulated-mobile-e2ee-v2-peer'
|
||||
|
||||
function deferred<T>() {
|
||||
+4
-4
@@ -4,13 +4,13 @@ import {
|
||||
validateMobileE2EEV2Handshake,
|
||||
type MobileE2EEPayloadKind,
|
||||
type MobileE2EEV2Hello
|
||||
} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract'
|
||||
} from '../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract'
|
||||
import {
|
||||
openMobileE2EEV2Frame,
|
||||
sealMobileE2EEV2Frame
|
||||
} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing'
|
||||
import { deriveSharedKey } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto'
|
||||
import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule'
|
||||
} from '../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing'
|
||||
import { deriveSharedKey } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto'
|
||||
import { deriveMobileE2EEV2KeySchedule } from '../../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule'
|
||||
|
||||
// Independent mobile wire peer for desktop tests, avoiding Expo imports.
|
||||
export class SimulatedMobileE2EEV2Peer {
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from 'zod'
|
||||
import { cancelUnreadResponseBody } from '../../lib/unread-response-body'
|
||||
import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair'
|
||||
import { deriveRelayHostId } from '../mobile-cloud-relay/relay-http-client'
|
||||
import { deriveRelayHostId } from '../mobile-cloud-relay/director/relay-http-client'
|
||||
import { answerPushHostChallenge } from './push-host-proof'
|
||||
import {
|
||||
postPushGatewayJson,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from '../../../../shared/remote-runtime/pairing/device-key-proof'
|
||||
import { DeviceRegistry } from '../server/pairing/device-registry'
|
||||
import { DEVICE_REGISTRY_FILENAME } from '../server/pairing/mobile-pairing-files'
|
||||
import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer'
|
||||
import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer'
|
||||
import { registerSocketDeviceKey } from '../server/runtime-rpc-device-key-registration'
|
||||
import { generateKeyPair } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto'
|
||||
import {
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { DeviceScope } from '../../../../../shared/runtime-session-contract
|
||||
import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode'
|
||||
import type { MobilePushRegistration } from '../../../../../shared/mobile-push-contract'
|
||||
import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach'
|
||||
import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission'
|
||||
import type { NetworkSourceClass } from '../../transports/websocket/source-admission/network-source-class'
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { DeviceScope } from '../../../../../shared/runtime-session-contracts'
|
||||
import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
import type { DeviceEntry } from './device-entry'
|
||||
import { parseMobilePushRegistration } from '../../../../../shared/mobile-push-contract'
|
||||
import { isDevicePublicKeyB64 } from '../../../../../shared/remote-runtime/pairing/device-key-proof'
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from './pairing-ticket-exchange'
|
||||
import { planIdleEphemeralPrune } from './ephemeral-device-rows'
|
||||
import { DeviceRegistrySightings } from './device-registry-sightings'
|
||||
import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode'
|
||||
import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach'
|
||||
import type { DelegatedPhone } from '../../../../../shared/delegated-mobile-device-contract'
|
||||
|
||||
+3
-48
@@ -1,7 +1,7 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync, type Stats } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
loadWindowsSecurity,
|
||||
type WindowsSecurity
|
||||
@@ -131,54 +131,9 @@ describeOnWindows('a secure store that exists but cannot be read', () => {
|
||||
expectUntouched(filePath, locked)
|
||||
})
|
||||
|
||||
it('does not blank the plugin secret vault on write', async () => {
|
||||
vi.doMock('electron', () => ({
|
||||
safeStorage: {
|
||||
isEncryptionAvailable: () => true,
|
||||
encryptString: (value: string) => Buffer.from(`enc:${value}`),
|
||||
decryptString: (buffer: Buffer) => buffer.toString().replace(/^enc:/, '')
|
||||
}
|
||||
}))
|
||||
const { PluginSecretsStore } = await import('../../../../plugins/plugin-secrets-store')
|
||||
const dir = join(root, 'plugin-secrets')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const store = new PluginSecretsStore(dir, 'publisher.plugin')
|
||||
// Reach the path the store computes rather than restating its layout here.
|
||||
const filePath = (store as unknown as { filePath: string }).filePath
|
||||
mkdirSync(join(filePath, '..'), { recursive: true })
|
||||
const original = JSON.stringify({
|
||||
version: 1,
|
||||
format: 'electron-safe-storage-v1',
|
||||
ciphertexts: { existing: Buffer.from('enc:keep-me').toString('base64') }
|
||||
})
|
||||
writeFileSync(filePath, original)
|
||||
const locked = makeUnreadable(filePath)
|
||||
|
||||
expect(store.set('added', 'value')).toEqual({ ok: false, error: expect.any(String) })
|
||||
store.delete('existing')
|
||||
|
||||
expectUntouched(filePath, locked)
|
||||
vi.doUnmock('electron')
|
||||
})
|
||||
it('does not blank the plugin KV store on write', async () => {
|
||||
const { PluginKvStore } = await import('../../../../plugins/plugin-storage-store')
|
||||
const dir = join(root, 'plugin-kv')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const store = new PluginKvStore(dir, 'publisher.plugin', 'storage.json')
|
||||
const filePath = (store as unknown as { filePath: string }).filePath
|
||||
mkdirSync(join(filePath, '..'), { recursive: true })
|
||||
const original = JSON.stringify({ keep: 'me' })
|
||||
writeFileSync(filePath, original)
|
||||
const locked = makeUnreadable(filePath)
|
||||
|
||||
expect(store.set('added', 'value')).toEqual({ ok: false, error: expect.any(String) })
|
||||
store.delete('keep')
|
||||
|
||||
expectUntouched(filePath, locked)
|
||||
})
|
||||
|
||||
it('does not drop pending relay revocations', async () => {
|
||||
const { RelayRevokeOutbox } = await import('../../../mobile-cloud-relay/relay-revoke-outbox')
|
||||
const { RelayRevokeOutbox } =
|
||||
await import('../../../mobile-cloud-relay/pairing/relay-revoke-outbox')
|
||||
const dir = join(root, 'relay')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const filePath = join(dir, 'mobile-relay-revoke-outbox.json')
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache'
|
||||
import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import { encodeDeviceProofMessage } from '../../../../shared/remote-runtime/pairing/device-key-proof'
|
||||
import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { DeviceRegistry } from './pairing/device-registry'
|
||||
import { DEVICE_REGISTRY_FILENAME } from './pairing/mobile-pairing-files'
|
||||
import { makeStore } from './runtime-rpc-worktree-store-fixtures'
|
||||
import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture'
|
||||
import {
|
||||
TerminalStreamOpcode,
|
||||
encodeTerminalStreamFrame,
|
||||
encodeTerminalStreamText
|
||||
} from '../../../../shared/terminal/stream/terminal-stream-protocol'
|
||||
import { OrcaRuntimeRpcServer } from './runtime-rpc'
|
||||
import {
|
||||
encodePairingOffer,
|
||||
parsePairingCode
|
||||
} from '../../../../shared/remote-runtime/pairing/pairing'
|
||||
import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
|
||||
import '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto'
|
||||
import { waitFor } from './runtime-rpc-test-harness'
|
||||
import {
|
||||
connectWs,
|
||||
nextWsMessage,
|
||||
waitForWsClose,
|
||||
authenticateMobileWs
|
||||
} from './runtime-rpc-mobile-ws-test-harness'
|
||||
|
||||
vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => {
|
||||
const listings = getWorktreeListingMocks()
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeScanCacheModule>()),
|
||||
listWorktrees: listings.listWorktrees
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => {
|
||||
const listings = getWorktreeListingMocks()
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeListingModule>()),
|
||||
listWorktreesStrict: listings.listWorktreesStrict
|
||||
}
|
||||
})
|
||||
|
||||
const { getWorktreeListingMocks } = vi.hoisted(() => {
|
||||
function createWorktreeListingMocks() {
|
||||
const worktrees = [
|
||||
{
|
||||
path: '/tmp/worktree-a',
|
||||
head: 'abc',
|
||||
branch: 'feature/foo',
|
||||
isBare: false,
|
||||
isMainWorktree: false
|
||||
}
|
||||
]
|
||||
return {
|
||||
listWorktrees: vi.fn().mockResolvedValue(worktrees),
|
||||
listWorktreesStrict: vi.fn().mockResolvedValue(worktrees)
|
||||
}
|
||||
}
|
||||
let listings: ReturnType<typeof createWorktreeListingMocks> | undefined
|
||||
return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) }
|
||||
})
|
||||
|
||||
async function authenticateKeyedWs(offer: PairingOffer, deviceId: string, key: nacl.SignKeyPair) {
|
||||
const ws = await connectWs(offer.endpoint)
|
||||
const peer = new SimulatedMobileE2EEV2Peer(
|
||||
nacl.box.keyPair(),
|
||||
Uint8Array.from(Buffer.from(offer.publicKeyB64, 'base64')),
|
||||
null
|
||||
)
|
||||
ws.send(JSON.stringify(peer.hello))
|
||||
expect(peer.acceptReady(JSON.parse(await nextWsMessage(ws)))).toBe(true)
|
||||
const transcriptHashB64 = peer.transcriptHashB64
|
||||
const proof = nacl.sign.detached(
|
||||
encodeDeviceProofMessage('auth', Buffer.from(transcriptHashB64, 'base64')),
|
||||
key.secretKey
|
||||
)
|
||||
ws.send(
|
||||
peer.sealText(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64,
|
||||
deviceId,
|
||||
deviceProofB64: Buffer.from(proof).toString('base64')
|
||||
})
|
||||
)
|
||||
)
|
||||
expect(JSON.parse(peer.openText(await nextWsMessage(ws))!)).toMatchObject({
|
||||
type: 'e2ee_authenticated'
|
||||
})
|
||||
return { ws, peer }
|
||||
}
|
||||
|
||||
describe('OrcaRuntimeRpcServer', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['mobile', false],
|
||||
['runtime', false],
|
||||
['mobile', true]
|
||||
] as const)(
|
||||
'revoking a %s bearer, removed on disk %s, removes descendants and closes their sockets',
|
||||
async (scope, removedOnDisk) => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-revoke-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
await server.start()
|
||||
try {
|
||||
const offer = server.createPairingOffer({ address: '127.0.0.1', name: 'Parent', scope })
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
const parsed = parsePairingCode(offer.pairingUrl)!
|
||||
const parentSocket = await authenticateMobileWs(offer.pairingUrl)
|
||||
const registry = server.getDeviceRegistry()!
|
||||
const key = nacl.sign.keyPair()
|
||||
const fork = registry.forkDeviceKey(
|
||||
offer.deviceId,
|
||||
Buffer.from(key.publicKey).toString('base64'),
|
||||
'Fork'
|
||||
)
|
||||
const idleFork = registry.forkDeviceKey(
|
||||
offer.deviceId,
|
||||
Buffer.alloc(32, 9).toString('base64'),
|
||||
'Offline fork'
|
||||
)
|
||||
const { ws: forkSocket } = await authenticateKeyedWs(parsed, fork.deviceId, key)
|
||||
const children =
|
||||
scope === 'runtime'
|
||||
? registry.upsertDelegatedMobileDevices(fork, [{ phoneKey: 'p', name: 'Pixel' }])
|
||||
: []
|
||||
const sockets = [parentSocket, forkSocket]
|
||||
for (const child of children) {
|
||||
sockets.push(
|
||||
await authenticateMobileWs(
|
||||
encodePairingOffer({
|
||||
...parsed,
|
||||
deviceToken: child.token,
|
||||
pairedDeviceId: child.deviceId,
|
||||
scope: 'mobile'
|
||||
})
|
||||
)
|
||||
)
|
||||
}
|
||||
const unrelated = registry.addDevice('Unrelated', scope)
|
||||
const unrelatedSocket = await authenticateMobileWs(
|
||||
encodePairingOffer({
|
||||
...parsed,
|
||||
deviceToken: unrelated.token,
|
||||
pairedDeviceId: unrelated.deviceId
|
||||
})
|
||||
)
|
||||
const closed = sockets.map(waitForWsClose)
|
||||
if (removedOnDisk) {
|
||||
const path = join(userDataPath, DEVICE_REGISTRY_FILENAME)
|
||||
const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8'))
|
||||
writeFileSync(path, JSON.stringify(rows.filter((row) => row.deviceId !== offer.deviceId)))
|
||||
}
|
||||
|
||||
const revoked =
|
||||
scope === 'mobile'
|
||||
? await server.revokeMobileDevice(offer.deviceId)
|
||||
: server.revokeRuntimeAccess(offer.deviceId)
|
||||
|
||||
expect(revoked).toBe(true)
|
||||
for (const device of [fork, idleFork, ...children]) {
|
||||
expect(registry.getDevice(device.deviceId)).toBeNull()
|
||||
expect(new DeviceRegistry(userDataPath).getDevice(device.deviceId)).toBeNull()
|
||||
}
|
||||
await Promise.all(closed)
|
||||
expect(registry.validateToken(unrelated.token)?.deviceId).toBe(unrelated.deviceId)
|
||||
expect(unrelatedSocket.readyState).toBe(unrelatedSocket.OPEN)
|
||||
unrelatedSocket.close()
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
},
|
||||
15_000
|
||||
)
|
||||
|
||||
it.each(['binary', 'text', 'sibling-cascade'] as const)(
|
||||
'retires an established keyed terminal subscription through %s revocation',
|
||||
async (kind) => {
|
||||
vi.useFakeTimers({ toFake: ['performance'] })
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-stream-revoke-'))
|
||||
const runtime = new OrcaRuntimeService(partialRuntimeStore(makeStore()))
|
||||
const write = vi.fn(() => true)
|
||||
runtime.setPtyController({
|
||||
spawn: vi.fn().mockResolvedValue({ id: 'fork-stream-pty' }),
|
||||
write,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
const cleanup = vi.spyOn(runtime, 'cleanupSubscriptionsForConnection')
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime,
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
await server.start()
|
||||
try {
|
||||
const terminal = await runtime.createTerminal('id:repo-1::/tmp/worktree-a')
|
||||
const offer = server.createPairingOffer({
|
||||
address: '127.0.0.1',
|
||||
name: 'Parent',
|
||||
scope: kind === 'sibling-cascade' ? 'mobile' : 'runtime'
|
||||
})
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
const registry = server.getDeviceRegistry()!
|
||||
const key = nacl.sign.keyPair()
|
||||
const earlier =
|
||||
kind === 'sibling-cascade'
|
||||
? registry.forkDeviceKey(
|
||||
offer.deviceId,
|
||||
Buffer.alloc(32, 7).toString('base64'),
|
||||
'Earlier'
|
||||
)
|
||||
: null
|
||||
const fork = registry.forkDeviceKey(
|
||||
offer.deviceId,
|
||||
Buffer.from(key.publicKey).toString('base64'),
|
||||
'Fork'
|
||||
)
|
||||
const later =
|
||||
kind === 'sibling-cascade'
|
||||
? registry.forkDeviceKey(
|
||||
offer.deviceId,
|
||||
Buffer.alloc(32, 8).toString('base64'),
|
||||
'Later'
|
||||
)
|
||||
: null
|
||||
if (kind === 'sibling-cascade') {
|
||||
server.setMobileRelayBinding(fork.deviceId, {
|
||||
relayHostId: 'host',
|
||||
relayDeviceId: fork.deviceId,
|
||||
ownerIdentityKey: 'owner'
|
||||
})
|
||||
registry.setPushRegistration(fork.deviceId, {
|
||||
registrationId: 'fork-push',
|
||||
filter: {},
|
||||
expiresAt: 4_000_000_000_000
|
||||
})
|
||||
}
|
||||
const { ws, peer } = await authenticateKeyedWs(
|
||||
parsePairingCode(offer.pairingUrl)!,
|
||||
fork.deviceId,
|
||||
key
|
||||
)
|
||||
const responses: { result?: { type?: string; streamId?: number } }[] = []
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary && Buffer.isBuffer(data)) {
|
||||
peer.openBinary(data)
|
||||
} else if (!isBinary) {
|
||||
responses.push(JSON.parse(peer.openText(data.toString())!))
|
||||
}
|
||||
})
|
||||
ws.send(
|
||||
peer.sealText(
|
||||
JSON.stringify({
|
||||
id: 'subscribe',
|
||||
method: 'terminal.subscribe',
|
||||
params: { terminal: terminal.handle, capabilities: { terminalBinaryStream: 1 } }
|
||||
})
|
||||
)
|
||||
)
|
||||
await waitFor(() => responses.some((response) => response.result?.type === 'subscribed'))
|
||||
const streamId = responses.find((response) => response.result?.type === 'subscribed')
|
||||
?.result?.streamId
|
||||
if (streamId === undefined) {
|
||||
throw new Error('Expected binary terminal subscription')
|
||||
}
|
||||
const sendInput = (text: string) =>
|
||||
ws.send(
|
||||
peer.sealBinary(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Input,
|
||||
streamId,
|
||||
seq: 1,
|
||||
payload: encodeTerminalStreamText(text)
|
||||
})
|
||||
)
|
||||
)
|
||||
sendInput('before')
|
||||
await waitFor(() => write.mock.calls.length === 1)
|
||||
const path = join(userDataPath, DEVICE_REGISTRY_FILENAME)
|
||||
const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8'))
|
||||
writeFileSync(
|
||||
path,
|
||||
JSON.stringify(
|
||||
rows.filter(
|
||||
(row) =>
|
||||
row.deviceId !== (kind === 'sibling-cascade' ? fork.deviceId : offer.deviceId)
|
||||
)
|
||||
)
|
||||
)
|
||||
// The registry sees another process's edit once its one-second stat window has passed.
|
||||
vi.advanceTimersByTime(1000)
|
||||
const closed = waitForWsClose(ws)
|
||||
|
||||
if (kind === 'sibling-cascade') {
|
||||
expect(await server.revokeMobileDevice(offer.deviceId)).toBe(true)
|
||||
for (const device of [earlier, fork, later]) {
|
||||
if (device) {
|
||||
expect(registry.getDevice(device.deviceId)).toBeNull()
|
||||
}
|
||||
}
|
||||
expect(registry.getDevice(offer.deviceId)).toBeNull()
|
||||
expect(server.getRelayRevokeOutbox().pendingFor('owner', 'host')).toMatchObject([
|
||||
{ relayDeviceId: fork.deviceId }
|
||||
])
|
||||
expect(server.getPushUnregisterOutbox().pending()).toMatchObject([
|
||||
{ deviceId: fork.deviceId, registrationId: 'fork-push' }
|
||||
])
|
||||
} else if (kind === 'binary') {
|
||||
sendInput('after')
|
||||
} else {
|
||||
ws.send(peer.sealText(JSON.stringify({ id: 'denied', method: 'status.get' })))
|
||||
}
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
cleanup.mock.calls.length > 0 ||
|
||||
write.mock.calls.length > 1 ||
|
||||
responses.some((response) => 'error' in response)
|
||||
)
|
||||
expect(write).toHaveBeenCalledTimes(1)
|
||||
expect(cleanup).toHaveBeenCalledOnce()
|
||||
await closed
|
||||
expect(server['mobileSocketWiring']?.channelCount).toBe(0)
|
||||
expect(server['mobileSocketWiring']?.connectionCount).toBe(0)
|
||||
} finally {
|
||||
cleanup.mockRestore()
|
||||
await server.stop()
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
RelayDeviceBinding,
|
||||
RelayRevokeOutboxItem
|
||||
} from '../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
import type {
|
||||
DelegatedPhone,
|
||||
DelegatedMobileDeviceSyncResult
|
||||
|
||||
@@ -16,7 +16,7 @@ import type {
|
||||
import type {
|
||||
RelayDeviceBinding,
|
||||
RelayRevokeOutboxItem
|
||||
} from '../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
|
||||
export const DEFAULT_WS_PORT = 6768
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { MobileSocketWiring } from '../mobile/mobile-socket-wiring'
|
||||
import type {
|
||||
RelayDeviceBinding,
|
||||
RelayRevokeOutbox
|
||||
} from '../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
import type { PushUnregisterOutbox } from '../../push/push-unregister-outbox'
|
||||
import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing'
|
||||
import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { UnpairedDeviceAuthThrottle } from '../mobile/unpaired-device-auth-
|
||||
import type { MobileSocketWiring } from '../mobile/mobile-socket-wiring'
|
||||
import type { MobileDesktopRelay } from '../../mobile-desktop-relay/mobile-desktop-relay'
|
||||
import type { MobileRelayHostCatalog } from '../../mobile-desktop-relay/mobile-relay-host-catalog'
|
||||
import { RelayRevokeOutbox } from '../../mobile-cloud-relay/relay-revoke-outbox'
|
||||
import { RelayRevokeOutbox } from '../../mobile-cloud-relay/pairing/relay-revoke-outbox'
|
||||
import { PushUnregisterOutbox } from '../../push/push-unregister-outbox'
|
||||
import { RuntimeBinaryMessageRouter } from './runtime-binary-message-router'
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import nacl from 'tweetnacl'
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { encodeDeviceProofMessage } from '../../../src/shared/remote-runtime/pairing/device-key-proof'
|
||||
import { DeviceRegistry } from '../../../src/main/runtime/rpc/server/pairing/device-registry'
|
||||
import { SimulatedMobileE2EEV2Peer } from '../../../src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer'
|
||||
import { SimulatedMobileE2EEV2Peer } from '../../../src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer'
|
||||
import {
|
||||
importReleaseCheckoutModule,
|
||||
materializeReleaseCheckout,
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
AssignmentRequestSchema as BaselineRequest,
|
||||
AssignmentResponseSchema as BaselineResponse
|
||||
} from '../../cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages'
|
||||
import { HostHelloSchema as BaselineHello } from '../../cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages'
|
||||
import { AssignmentRequestSchema } from '../../cloud/packages/relay-contract/src/director-messages'
|
||||
import { HostHelloSchema } from '../../cloud/packages/relay-contract/src/control-messages'
|
||||
import { requestRelayAssignment } from '../../src/main/runtime/mobile-cloud-relay/relay-http-client'
|
||||
import { RelayAssignRateGate } from '../../src/main/runtime/mobile-cloud-relay/relay-assign-rate-gate'
|
||||
|
||||
const assignment = {
|
||||
v: 1,
|
||||
cellUrl: 'https://asia.example.test',
|
||||
assignmentEpoch: 3,
|
||||
lease: 'synthetic-assignment'
|
||||
}
|
||||
const window = {
|
||||
generation: 1,
|
||||
assignmentEpoch: 3,
|
||||
incumbentRegion: 'asia-east2',
|
||||
expiresAt: 100_000_000,
|
||||
policyVersion: 1
|
||||
}
|
||||
function request(fetch: typeof globalThis.fetch) {
|
||||
return requestRelayAssignment({
|
||||
directorUrl: 'https://director.example.test',
|
||||
relayHostId: 'abcdefghijklmnop',
|
||||
relayToken: 'synthetic-authorization',
|
||||
preferredRegion: 'asia-east2',
|
||||
reconnect: true,
|
||||
regionCorrection: { v: 1, action: 'issue-window' },
|
||||
fetch,
|
||||
assignRateGate: new RelayAssignRateGate()
|
||||
})
|
||||
}
|
||||
|
||||
describe('relay correction mixed-version wire contracts', () => {
|
||||
it('new desktop falls back against the actual pinned old director parser', async () => {
|
||||
const bodies: unknown[] = []
|
||||
const fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const body: unknown = JSON.parse(String(init?.body))
|
||||
bodies.push(body)
|
||||
return BaselineRequest.safeParse(body).success
|
||||
? Response.json(BaselineResponse.parse(assignment))
|
||||
: new Response(null, { status: 400 })
|
||||
})
|
||||
expect(await request(fetch)).toEqual(assignment)
|
||||
expect(bodies).toHaveLength(2)
|
||||
expect(AssignmentRequestSchema.safeParse(bodies[0]).success).toBe(true)
|
||||
expect(BaselineRequest.safeParse(bodies[0]).success).toBe(false)
|
||||
expect(bodies[1]).toEqual({
|
||||
v: 1,
|
||||
relayHostId: 'abcdefghijklmnop',
|
||||
preferredRegion: 'asia-east2',
|
||||
reconnect: true
|
||||
})
|
||||
})
|
||||
|
||||
it('the old desktop assignment shape remains accepted by the new director', () => {
|
||||
const request = BaselineRequest.parse({ v: 1, relayHostId: 'abcdefghijklmnop' })
|
||||
expect(AssignmentRequestSchema.parse(request)).toEqual(request)
|
||||
expect(BaselineResponse.parse(assignment)).toEqual(assignment)
|
||||
})
|
||||
|
||||
it('the negotiated capability requires no change to the strict old host hello', () => {
|
||||
const hello = {
|
||||
v: 1,
|
||||
relayHostId: 'abcdefghijklmnop',
|
||||
assignmentEpoch: 3,
|
||||
hostPublicKeyB64: Buffer.alloc(32).toString('base64'),
|
||||
appVersion: 'test'
|
||||
}
|
||||
expect(BaselineHello.parse(HostHelloSchema.parse(hello))).toEqual(hello)
|
||||
expect(BaselineHello.safeParse({ ...hello, idleRegionalRehome: true }).success).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ v: 1, window: { ...window, policyVersion: 2 } },
|
||||
{ v: 2, window },
|
||||
{ v: 1, window: { ...window, expiresAt: -1 } },
|
||||
{ v: 1, window: { ...window, unexpectedField: true } }
|
||||
])(
|
||||
'defers unsupported or malformed optional correction without losing placement: %j',
|
||||
async (regionCorrection) => {
|
||||
const result = await request(async () => Response.json({ ...assignment, regionCorrection }))
|
||||
expect(result).toMatchObject(assignment)
|
||||
expect(result.regionCorrection).toBeUndefined()
|
||||
}
|
||||
)
|
||||
|
||||
it('still accepts supported correction metadata', async () => {
|
||||
const regionCorrection = { v: 1, window }
|
||||
expect(await request(async () => Response.json({ ...assignment, regionCorrection }))).toEqual({
|
||||
...assignment,
|
||||
regionCorrection
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ cellUrl: 'http://untrusted.example.test' },
|
||||
{ assignmentEpoch: -1 },
|
||||
{ lease: '' },
|
||||
{ unexpectedField: true }
|
||||
])('keeps the core assignment strict: %j', async (invalid) => {
|
||||
await expect(request(async () => Response.json({ ...assignment, ...invalid }))).rejects.toThrow(
|
||||
'relay_assignment_failed_502'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -13,8 +13,8 @@ import { IDLE_REHOME_MIN_CONTROL_AGE_MS } from '../../cloud/apps/relay/src/conne
|
||||
import { CONTROL_RENEWAL_BATCH_INTERVAL_MS } from '../../cloud/apps/relay/src/control-leases/control-renewal-batch'
|
||||
import { RELAY_PROTOCOL_LIMITS } from '../../cloud/packages/relay-contract/src/protocol-limits'
|
||||
import type * as AdminTokenVerifier from '../../cloud/apps/relay/src/authentication/admin-token-verifier'
|
||||
import { RelayOriginPool } from '../../src/main/runtime/mobile-cloud-relay/relay-origin-pool'
|
||||
import { RELAY_HOST_CAPABILITY_HEADERS } from '../../src/main/runtime/mobile-cloud-relay/relay-control-protocol'
|
||||
import { RelayOriginPool } from '../../src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool'
|
||||
import { RELAY_HOST_CAPABILITY_HEADERS } from '../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol'
|
||||
import type { MobileSocketTransport } from '../../src/main/runtime/rpc/mobile/mobile-socket-wiring'
|
||||
import { createRelayExecutionProcess } from './helpers/relay-execution-process'
|
||||
|
||||
|
||||
Reference in New Issue
Block a user