The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { describe, expect, it } from "@effect/vitest"; |
| 4 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as FileSystem from "effect/FileSystem"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Path from "effect/Path"; |
| 10 | import * as PlatformError from "effect/PlatformError"; |
| 11 | import * as Schema from "effect/Schema"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import * as TestClock from "effect/testing/TestClock"; |
| 14 | import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http"; |
| 15 | import { RELAY_LINK_PROOF_TYP, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt"; |
| 16 | import * as NetAddress from "effect/net/NetAddress"; |
| 17 | |
| 18 | import { EnvironmentId } from "@t3tools/contracts"; |
| 19 | import * as EnvironmentKeys from "./environmentKeys.ts"; |
| 20 | import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; |
| 21 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 22 | import * as ServerConfigModule from "../config.ts"; |
| 23 | import { writeServiceState } from "../serviceLauncher.ts"; |
| 24 | import { |
| 25 | SERVICE_LAUNCHER_PROTOCOL, |
| 26 | SERVICE_STATE_FILE, |
| 27 | SERVICE_STOP_MARKER_FILE, |
| 28 | type ServiceUpdateRecord, |
| 29 | } from "./serviceProtocol.ts"; |
| 30 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 31 | import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; |
| 32 | import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts"; |
| 33 | import * as CliTokenManager from "./CliTokenManager.ts"; |
| 34 | import { |
| 35 | RelayEnvironmentLinkProofPayload, |
| 36 | RelayManagedEndpointRecoveryRegistrationRequest, |
| 37 | } from "@t3tools/contracts/relay"; |
| 38 | import { |
| 39 | CLOUD_ENDPOINT_CONFIRMED_ORIGIN, |
| 40 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 41 | CLOUD_LINK_REVOKED, |
| 42 | CLOUD_LINKED_USER_ID, |
| 43 | decodeRuntimeConfig, |
| 44 | RELAY_ENVIRONMENT_CREDENTIAL_SECRET, |
| 45 | RELAY_ISSUER_SECRET, |
| 46 | RELAY_URL_SECRET, |
| 47 | } from "./config.ts"; |
| 48 | import * as CloudLink from "./CloudLink.ts"; |
| 49 | import * as ConnectReachability from "./ConnectReachability.ts"; |
| 50 | import { consumeCloudReplayGuards } from "./CloudLink.ts"; |
| 51 | import { pendingServiceUpdateExists } from "./updateHandoff.ts"; |
| 52 | import { managedTunnelStartupAction } from "./managedTunnelStartup.ts"; |
| 53 | import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts"; |
| 54 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 55 | import * as ServerSettings from "../serverSettings.ts"; |
| 56 | |
| 57 | const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") => |
| 58 | new ServerSecretStore.SecretStorePersistError({ |
| 59 | resource: "cloud replay guard", |
| 60 | cause: PlatformError.systemError({ |
| 61 | _tag: tag, |
| 62 | module: "FileSystem", |
| 63 | method: "open", |
| 64 | pathOrDescriptor: "cloud-replay-guard.bin", |
| 65 | }), |
| 66 | }); |
| 67 | |
| 68 | const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation"); |
| 69 | |
| 70 | const idleAwarenessRelay = AgentAwarenessRelay.AgentAwarenessRelay.of({ |
| 71 | publishThread: () => Effect.void, |
| 72 | drain: Effect.void, |
| 73 | requestCatchUp: () => Effect.void, |
| 74 | start: () => Effect.void, |
| 75 | }); |
| 76 | |
| 77 | const idleHttpServer = HttpServer.HttpServer.of({ |
| 78 | address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), |
| 79 | serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"], |
| 80 | }); |
| 81 | |
| 82 | const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect( |
| 83 | Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest), |
| 84 | ); |
| 85 | |
| 86 | function makeSecretStore( |
| 87 | create: ServerSecretStore.ServerSecretStore["Service"]["create"], |
| 88 | ): ServerSecretStore.ServerSecretStore["Service"] { |
| 89 | return { |
| 90 | get: unusedSecretStoreOperation, |
| 91 | set: unusedSecretStoreOperation, |
| 92 | create, |
| 93 | getOrCreateRandom: unusedSecretStoreOperation, |
| 94 | remove: unusedSecretStoreOperation, |
| 95 | }; |
| 96 | } |
| 97 | |
| 98 | describe("consumeCloudReplayGuards", () => { |
| 99 | it.effect("reports already-created guards as replay conflicts", () => |
| 100 | Effect.gen(function* () { |
| 101 | const consumed = yield* consumeCloudReplayGuards({ |
| 102 | secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))), |
| 103 | names: ["cloud-jti", "cloud-nonce"], |
| 104 | value: new Uint8Array(), |
| 105 | }); |
| 106 | |
| 107 | expect(consumed).toBe(false); |
| 108 | }), |
| 109 | ); |
| 110 | }); |
| 111 | |
| 112 | describe("releaseManagedTunnelOnShutdown", () => { |
| 113 | const cliToken: CliTokenManager.PersistedToken = { |
| 114 | accessToken: "cli-access-token", |
| 115 | refreshToken: "cli-refresh-token", |
| 116 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 117 | }; |
| 118 | |
| 119 | function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) { |
| 120 | const values = new Map<string, Uint8Array>( |
| 121 | Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const), |
| 122 | ); |
| 123 | const store: ServerSecretStore.ServerSecretStore["Service"] = { |
| 124 | get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))), |
| 125 | set: (name, value) => |
| 126 | Effect.sync(() => { |
| 127 | values.set(name, value); |
| 128 | }), |
| 129 | create: (name, value) => |
| 130 | Effect.sync(() => { |
| 131 | values.set(name, value); |
| 132 | }), |
| 133 | getOrCreateRandom: unusedSecretStoreOperation, |
| 134 | remove: (name) => |
| 135 | Effect.sync(() => { |
| 136 | values.delete(name); |
| 137 | }), |
| 138 | }; |
| 139 | return { store, values }; |
| 140 | } |
| 141 | |
| 142 | interface ReleaseHarness { |
| 143 | readonly store: ServerSecretStore.ServerSecretStore["Service"]; |
| 144 | readonly applyConfigCalls: Array<unknown>; |
| 145 | readonly requests: Array<HttpClientRequest.HttpClientRequest>; |
| 146 | readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>; |
| 147 | readonly respond?: () => Response; |
| 148 | readonly address?: HttpServer.HttpServer["Service"]["address"]; |
| 149 | readonly respondEffect?: Effect.Effect<Response>; |
| 150 | readonly getExisting?: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"]; |
| 151 | readonly latestReachability?: ConnectReachability.ConnectReachability["Service"]["latest"]; |
| 152 | readonly connector?: ManagedEndpointRuntime.ConnectorFacts; |
| 153 | } |
| 154 | |
| 155 | const writeLauncherState = (update: ServiceUpdateRecord) => |
| 156 | Effect.gen(function* () { |
| 157 | const path = yield* Path.Path; |
| 158 | const config = yield* ServerConfigModule.ServerConfig; |
| 159 | const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE); |
| 160 | yield* Effect.promise(() => |
| 161 | writeServiceState(statePath, { |
| 162 | protocol: SERVICE_LAUNCHER_PROTOCOL, |
| 163 | activeVersion: "0.0.30", |
| 164 | update, |
| 165 | }), |
| 166 | ); |
| 167 | }); |
| 168 | |
| 169 | const provideReleaseHarness = |
| 170 | (harness: ReleaseHarness) => |
| 171 | <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 172 | effect.pipe( |
| 173 | Effect.provide( |
| 174 | CloudLink.layer.pipe( |
| 175 | Layer.provide(EnvironmentKeys.layer), |
| 176 | Layer.provide(ManagedPolicy.layerTest()), |
| 177 | Layer.provide(ServerSettings.ServerSettingsService.layerTest()), |
| 178 | ), |
| 179 | ), |
| 180 | Effect.provideService( |
| 181 | ConnectReachability.ConnectReachability, |
| 182 | ConnectReachability.ConnectReachability.of({ |
| 183 | check: Effect.die("unused"), |
| 184 | latest: harness.latestReachability ?? Effect.succeedNone, |
| 185 | }), |
| 186 | ), |
| 187 | Effect.provideService(HttpServer.HttpServer, { |
| 188 | ...idleHttpServer, |
| 189 | address: harness.address ?? idleHttpServer.address, |
| 190 | }), |
| 191 | Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store), |
| 192 | Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay), |
| 193 | Effect.provideService( |
| 194 | ServerEnvironment.ServerEnvironment, |
| 195 | ServerEnvironment.ServerEnvironment.of({ |
| 196 | getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")), |
| 197 | getDescriptor: Effect.succeed({ |
| 198 | environmentId: EnvironmentId.make("env_123"), |
| 199 | label: "Test environment", |
| 200 | platform: { os: "linux", arch: "x64" }, |
| 201 | serverVersion: "0.0.0-test", |
| 202 | capabilities: { repositoryIdentity: true }, |
| 203 | }), |
| 204 | }), |
| 205 | ), |
| 206 | Effect.provideService( |
| 207 | ManagedEndpointRuntime.CloudManagedEndpointRuntime, |
| 208 | ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({ |
| 209 | applyConfig: (config) => |
| 210 | Effect.sync(() => { |
| 211 | harness.applyConfigCalls.push(config); |
| 212 | return config === null |
| 213 | ? ({ |
| 214 | status: "disabled", |
| 215 | } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus) |
| 216 | : ({ |
| 217 | status: "running", |
| 218 | providerKind: "cloudflare_tunnel", |
| 219 | pid: 123, |
| 220 | } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus); |
| 221 | }), |
| 222 | recoveryRequests: Stream.empty, |
| 223 | requestRecovery: () => Effect.void, |
| 224 | restartConnector: () => Effect.succeed(false), |
| 225 | tunnelConnected: Stream.empty, |
| 226 | inspectConnector: Effect.succeed(harness.connector ?? null), |
| 227 | readinessChanged: Stream.empty, |
| 228 | withLinkStateLock: (effect) => effect, |
| 229 | }), |
| 230 | ), |
| 231 | Effect.provideService( |
| 232 | EnvironmentAuth.EnvironmentAuth, |
| 233 | EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]), |
| 234 | ), |
| 235 | Effect.provideService( |
| 236 | CliTokenManager.CloudCliTokenManager, |
| 237 | CliTokenManager.CloudCliTokenManager.of({ |
| 238 | get: unusedSecretStoreOperation(), |
| 239 | getExisting: harness.getExisting ?? Effect.succeedSome(cliToken), |
| 240 | hasCredential: unusedSecretStoreOperation(), |
| 241 | store: () => unusedSecretStoreOperation(), |
| 242 | clear: unusedSecretStoreOperation(), |
| 243 | }), |
| 244 | ), |
| 245 | Effect.provideService( |
| 246 | HttpClient.HttpClient, |
| 247 | HttpClient.make((request) => |
| 248 | Effect.sync(() => { |
| 249 | harness.requests.push(request); |
| 250 | }).pipe( |
| 251 | Effect.andThen(harness.onRequest?.(request) ?? Effect.void), |
| 252 | Effect.andThen( |
| 253 | harness.respondEffect ?? |
| 254 | Effect.sync(() => (harness.respond ?? (() => Response.json({ ok: true })))()), |
| 255 | ), |
| 256 | Effect.map((response) => HttpClientResponse.fromWeb(request, response)), |
| 257 | ), |
| 258 | ), |
| 259 | ), |
| 260 | |
| 261 | Effect.provide([ |
| 262 | ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe( |
| 263 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 264 | ), |
| 265 | ConfigProvider.layer( |
| 266 | ConfigProvider.fromEnv({ env: { T3CODE_RELAY_URL: "https://relay.example.test" } }), |
| 267 | ), |
| 268 | ]), |
| 269 | Effect.scoped, |
| 270 | ); |
| 271 | |
| 272 | it.effect.each([ |
| 273 | { direction: "ahead", skewSeconds: 600 }, |
| 274 | { direction: "behind", skewSeconds: -600 }, |
| 275 | ])( |
| 276 | "signs a link proof accepted at relay time when the host clock is $direction", |
| 277 | ({ skewSeconds }) => { |
| 278 | const { store } = makeMemorySecretStore(); |
| 279 | |
| 280 | return Effect.gen(function* () { |
| 281 | const relayNow = 1_800_000_000; |
| 282 | const relayIssuer = "https://relay.example.test"; |
| 283 | const relayKeys = yield* EnvironmentKeys.getOrCreateEnvironmentKeyPairFromSecretStore( |
| 284 | makeMemorySecretStore().store, |
| 285 | ); |
| 286 | const challenge = yield* signRelayJwt({ |
| 287 | privateKey: relayKeys.privateKey, |
| 288 | typ: "t3-link-challenge+jwt", |
| 289 | payload: { |
| 290 | kind: "environment_link_challenge", |
| 291 | iss: relayIssuer, |
| 292 | aud: relayIssuer, |
| 293 | sub: "user-123", |
| 294 | jti: "challenge-jti", |
| 295 | iat: relayNow, |
| 296 | exp: relayNow + 300, |
| 297 | notificationsEnabled: true, |
| 298 | liveActivitiesEnabled: false, |
| 299 | managedTunnelsEnabled: false, |
| 300 | }, |
| 301 | }); |
| 302 | yield* TestClock.setTime((relayNow + skewSeconds) * 1_000); |
| 303 | const link = yield* CloudLink.CloudLink; |
| 304 | const proof = yield* link.linkProof({ |
| 305 | challenge, |
| 306 | relayIssuer, |
| 307 | endpoint: { |
| 308 | httpBaseUrl: "http://127.0.0.1:3773", |
| 309 | wsBaseUrl: "ws://127.0.0.1:3773", |
| 310 | providerKind: "manual", |
| 311 | }, |
| 312 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 313 | }); |
| 314 | const environmentKeys = |
| 315 | yield* EnvironmentKeys.getOrCreateEnvironmentKeyPairFromSecretStore(store); |
| 316 | yield* TestClock.setTime(relayNow * 1_000); |
| 317 | const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, { |
| 318 | publicKey: environmentKeys.publicKey, |
| 319 | token: proof, |
| 320 | typ: RELAY_LINK_PROOF_TYP, |
| 321 | issuer: "t3-env:env_123", |
| 322 | audience: relayIssuer, |
| 323 | }); |
| 324 | |
| 325 | expect(verified).toMatchObject({ |
| 326 | iat: relayNow, |
| 327 | exp: relayNow + 300, |
| 328 | challenge, |
| 329 | environmentId: "env_123", |
| 330 | scopes: ["agent_activity_notifications"], |
| 331 | }); |
| 332 | }).pipe(provideReleaseHarness({ store, applyConfigCalls: [], requests: [] })); |
| 333 | }, |
| 334 | ); |
| 335 | |
| 336 | const managedLinkSecrets = [ |
| 337 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"], |
| 338 | [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"], |
| 339 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 340 | [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"], |
| 341 | ] as const; |
| 342 | |
| 343 | it.effect("does not recreate a link that was unlinked while startup registration retried", () => { |
| 344 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 345 | const applyConfigCalls: Array<unknown> = []; |
| 346 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 347 | |
| 348 | return Effect.gen(function* () { |
| 349 | const link = yield* CloudLink.CloudLink; |
| 350 | |
| 351 | values.delete(CLOUD_CLI_DESIRED_LINK_SECRET); |
| 352 | |
| 353 | expect(yield* link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull(); |
| 354 | expect(requests).toEqual([]); |
| 355 | expect(applyConfigCalls).toEqual([]); |
| 356 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 357 | }); |
| 358 | |
| 359 | it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => { |
| 360 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 361 | const applyConfigCalls: Array<unknown> = []; |
| 362 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 363 | |
| 364 | return Effect.gen(function* () { |
| 365 | const link = yield* CloudLink.CloudLink; |
| 366 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 367 | |
| 368 | expect(released).toBe(true); |
| 369 | expect(applyConfigCalls).toEqual([null]); |
| 370 | expect(requests).toHaveLength(1); |
| 371 | const request = requests[0]!; |
| 372 | expect(request.method).toBe("DELETE"); |
| 373 | expect(request.url).toBe( |
| 374 | "https://relay.example.test/v1/client/environment-links/env_123/tunnel", |
| 375 | ); |
| 376 | expect(request.headers.authorization).toBe("Bearer cli-access-token"); |
| 377 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false); |
| 378 | expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false); |
| 379 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 380 | }); |
| 381 | |
| 382 | it.effect("releases a tunnel only through the configured relay", () => { |
| 383 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 384 | values.set(RELAY_URL_SECRET, new TextEncoder().encode("https://old-relay.example.test")); |
| 385 | const applyConfigCalls: Array<unknown> = []; |
| 386 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 387 | |
| 388 | return Effect.gen(function* () { |
| 389 | const link = yield* CloudLink.CloudLink; |
| 390 | expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(false); |
| 391 | expect(applyConfigCalls).toEqual([]); |
| 392 | expect(requests).toEqual([]); |
| 393 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 394 | }); |
| 395 | |
| 396 | it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => { |
| 397 | const { store, values } = makeMemorySecretStore([ |
| 398 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"], |
| 399 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 400 | ]); |
| 401 | const applyConfigCalls: Array<unknown> = []; |
| 402 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 403 | |
| 404 | return Effect.gen(function* () { |
| 405 | const link = yield* CloudLink.CloudLink; |
| 406 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 407 | |
| 408 | expect(released).toBe(false); |
| 409 | expect(applyConfigCalls).toEqual([]); |
| 410 | expect(requests).toEqual([]); |
| 411 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true); |
| 412 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 413 | }); |
| 414 | |
| 415 | it.effect("keeps the tunnel when shutdown hands off to a pending update", () => { |
| 416 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 417 | const applyConfigCalls: Array<unknown> = []; |
| 418 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 419 | |
| 420 | return Effect.gen(function* () { |
| 421 | const link = yield* CloudLink.CloudLink; |
| 422 | yield* writeLauncherState({ |
| 423 | id: "update-1", |
| 424 | fromVersion: "0.0.30", |
| 425 | targetVersion: "0.0.31", |
| 426 | dbPath: "/tmp/state.sqlite", |
| 427 | status: "pending", |
| 428 | }); |
| 429 | |
| 430 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 431 | |
| 432 | expect(released).toBe(false); |
| 433 | expect(applyConfigCalls).toEqual([]); |
| 434 | expect(requests).toEqual([]); |
| 435 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true); |
| 436 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 437 | }); |
| 438 | |
| 439 | it.effect("still releases a pending update when the launcher is stopping", () => { |
| 440 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 441 | const applyConfigCalls: Array<unknown> = []; |
| 442 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 443 | |
| 444 | return Effect.gen(function* () { |
| 445 | const link = yield* CloudLink.CloudLink; |
| 446 | yield* writeLauncherState({ |
| 447 | id: "update-1", |
| 448 | fromVersion: "0.0.30", |
| 449 | targetVersion: "0.0.31", |
| 450 | dbPath: "/tmp/state.sqlite", |
| 451 | status: "pending", |
| 452 | }); |
| 453 | const fs = yield* FileSystem.FileSystem; |
| 454 | const path = yield* Path.Path; |
| 455 | const config = yield* ServerConfigModule.ServerConfig; |
| 456 | yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), ""); |
| 457 | |
| 458 | expect(yield* pendingServiceUpdateExists).toBe(true); |
| 459 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 460 | |
| 461 | expect(released).toBe(true); |
| 462 | expect(requests).toHaveLength(1); |
| 463 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false); |
| 464 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 465 | }); |
| 466 | |
| 467 | // regression: 808d6853555 keep the managed tunnel across remote update restarts |
| 468 | it.effect("still releases when the recorded update already settled", () => { |
| 469 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 470 | const applyConfigCalls: Array<unknown> = []; |
| 471 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 472 | |
| 473 | return Effect.gen(function* () { |
| 474 | const link = yield* CloudLink.CloudLink; |
| 475 | yield* writeLauncherState({ |
| 476 | id: "update-1", |
| 477 | fromVersion: "0.0.30", |
| 478 | targetVersion: "0.0.31", |
| 479 | status: "committed", |
| 480 | }); |
| 481 | |
| 482 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 483 | |
| 484 | expect(released).toBe(true); |
| 485 | expect(requests).toHaveLength(1); |
| 486 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false); |
| 487 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 488 | }); |
| 489 | |
| 490 | it.effect("keeps a runtime config that a fast restart replaced mid-release", () => { |
| 491 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 492 | const applyConfigCalls: Array<unknown> = []; |
| 493 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 494 | const freshConfig = new TextEncoder().encode("fresh-runtime-config"); |
| 495 | |
| 496 | return Effect.gen(function* () { |
| 497 | const link = yield* CloudLink.CloudLink; |
| 498 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 499 | |
| 500 | expect(released).toBe(true); |
| 501 | |
| 502 | expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig); |
| 503 | }).pipe( |
| 504 | provideReleaseHarness({ |
| 505 | store, |
| 506 | applyConfigCalls, |
| 507 | requests, |
| 508 | respond: () => { |
| 509 | values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig); |
| 510 | return Response.json({ ok: true }); |
| 511 | }, |
| 512 | }), |
| 513 | ); |
| 514 | }); |
| 515 | |
| 516 | it.effect("keeps the stored connector token when the relay skipped the release", () => { |
| 517 | const { store, values } = makeMemorySecretStore(managedLinkSecrets); |
| 518 | const applyConfigCalls: Array<unknown> = []; |
| 519 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 520 | |
| 521 | return Effect.gen(function* () { |
| 522 | const link = yield* CloudLink.CloudLink; |
| 523 | const released = yield* link.releaseManagedTunnelOnShutdown(); |
| 524 | |
| 525 | expect(released).toBe(false); |
| 526 | expect(requests).toHaveLength(1); |
| 527 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true); |
| 528 | }).pipe( |
| 529 | provideReleaseHarness({ |
| 530 | store, |
| 531 | applyConfigCalls, |
| 532 | requests, |
| 533 | respond: () => Response.json({ ok: false }), |
| 534 | }), |
| 535 | ); |
| 536 | }); |
| 537 | |
| 538 | it.effect("registers an existing tunnel and starts the confirmed connector", () => { |
| 539 | const { store } = makeMemorySecretStore([ |
| 540 | [ |
| 541 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 542 | '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}', |
| 543 | ], |
| 544 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 545 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 546 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 547 | ]); |
| 548 | const applyConfigCalls: Array<unknown> = []; |
| 549 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 550 | |
| 551 | return Effect.gen(function* () { |
| 552 | const link = yield* CloudLink.CloudLink; |
| 553 | expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({ |
| 554 | status: "ready", |
| 555 | }); |
| 556 | expect(requests).toHaveLength(1); |
| 557 | expect(requests[0]?.method).toBe("POST"); |
| 558 | expect(requests[0]?.url).toBe( |
| 559 | "https://relay.example.test/v1/environments/env_123/tunnel/recovery", |
| 560 | ); |
| 561 | expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential"); |
| 562 | const body = requests[0]?.body; |
| 563 | expect(body?._tag).toBe("Uint8Array"); |
| 564 | if (body?._tag === "Uint8Array") { |
| 565 | expect( |
| 566 | yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)), |
| 567 | ).toMatchObject({ |
| 568 | cloudUserId: "user-123", |
| 569 | tunnelId: "existing-tunnel", |
| 570 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 571 | }); |
| 572 | } |
| 573 | expect(applyConfigCalls).toHaveLength(1); |
| 574 | }).pipe( |
| 575 | provideReleaseHarness({ |
| 576 | store, |
| 577 | applyConfigCalls, |
| 578 | requests, |
| 579 | respond: () => Response.json({ status: "ready" }), |
| 580 | }), |
| 581 | ); |
| 582 | }); |
| 583 | |
| 584 | it.effect("registers and starts a managed tunnel at the bound IPv6 loopback address", () => { |
| 585 | const { store } = makeMemorySecretStore(); |
| 586 | const config = { |
| 587 | providerKind: "cloudflare_tunnel" as const, |
| 588 | connectorToken: "existing-token", |
| 589 | tunnelId: "existing-tunnel", |
| 590 | }; |
| 591 | const applyConfigCalls: Array<unknown> = []; |
| 592 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 593 | |
| 594 | return Effect.gen(function* () { |
| 595 | const link = yield* CloudLink.CloudLink; |
| 596 | expect( |
| 597 | yield* link.applyRelayConfig({ |
| 598 | relayUrl: "https://relay.example.test", |
| 599 | cloudUserId: "user-123", |
| 600 | environmentCredential: "environment-credential", |
| 601 | cloudMintPublicKey: |
| 602 | "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----", |
| 603 | endpointRuntime: config, |
| 604 | }), |
| 605 | ).toMatchObject({ ok: true, endpointRuntimeStatus: { status: "running" } }); |
| 606 | expect(requests).toHaveLength(1); |
| 607 | const body = requests[0]!.body; |
| 608 | if (body._tag !== "Uint8Array") throw new Error("Expected a JSON recovery request"); |
| 609 | expect( |
| 610 | yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)), |
| 611 | ).toMatchObject({ |
| 612 | origin: { localHttpHost: "[::1]", localHttpPort: 4884 }, |
| 613 | }); |
| 614 | expect(applyConfigCalls).toEqual([null, config]); |
| 615 | }).pipe( |
| 616 | provideReleaseHarness({ |
| 617 | store, |
| 618 | applyConfigCalls, |
| 619 | requests, |
| 620 | address: NetAddress.inetAddressFromIpStringUnsafe("::1", 4884), |
| 621 | respond: () => Response.json({ status: "ready" }), |
| 622 | }), |
| 623 | ); |
| 624 | }); |
| 625 | |
| 626 | it.effect("marks a link the relay rejects as revoked without dropping or replacing it", () => { |
| 627 | const { store, values } = makeMemorySecretStore([ |
| 628 | [ |
| 629 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 630 | '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}', |
| 631 | ], |
| 632 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 633 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 634 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 635 | [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"], |
| 636 | ]); |
| 637 | const applyConfigCalls: Array<unknown> = []; |
| 638 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 639 | |
| 640 | return Effect.gen(function* () { |
| 641 | const link = yield* CloudLink.CloudLink; |
| 642 | expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({ |
| 643 | status: "revoked", |
| 644 | }); |
| 645 | expect((yield* link.linkState()).linkRevoked).toBe(true); |
| 646 | |
| 647 | expect(requests).toHaveLength(1); |
| 648 | expect(applyConfigCalls).toEqual([]); |
| 649 | expect(values.has(RELAY_ENVIRONMENT_CREDENTIAL_SECRET)).toBe(true); |
| 650 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true); |
| 651 | }).pipe( |
| 652 | provideReleaseHarness({ |
| 653 | store, |
| 654 | applyConfigCalls, |
| 655 | requests, |
| 656 | respond: () => |
| 657 | Response.json( |
| 658 | { |
| 659 | _tag: "RelayAuthInvalidError", |
| 660 | code: "auth_invalid", |
| 661 | reason: "not_authorized", |
| 662 | traceId: "trace-revoked", |
| 663 | }, |
| 664 | { status: 401 }, |
| 665 | ), |
| 666 | }), |
| 667 | ); |
| 668 | }); |
| 669 | |
| 670 | it.effect("does not mark a link that was replaced while its rejection was in flight", () => { |
| 671 | const { store, values } = makeMemorySecretStore([ |
| 672 | [ |
| 673 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 674 | '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}', |
| 675 | ], |
| 676 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 677 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 678 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "old-credential"], |
| 679 | ]); |
| 680 | |
| 681 | return Effect.gen(function* () { |
| 682 | const link = yield* CloudLink.CloudLink; |
| 683 | expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({ |
| 684 | status: "superseded", |
| 685 | }); |
| 686 | expect(values.has(CLOUD_LINK_REVOKED)).toBe(false); |
| 687 | }).pipe( |
| 688 | provideReleaseHarness({ |
| 689 | store, |
| 690 | applyConfigCalls: [], |
| 691 | requests: [], |
| 692 | respond: () => { |
| 693 | values.set( |
| 694 | RELAY_ENVIRONMENT_CREDENTIAL_SECRET, |
| 695 | new TextEncoder().encode("replacement-credential"), |
| 696 | ); |
| 697 | return Response.json( |
| 698 | { |
| 699 | _tag: "RelayAuthInvalidError", |
| 700 | code: "auth_invalid", |
| 701 | reason: "not_authorized", |
| 702 | traceId: "trace-stale", |
| 703 | }, |
| 704 | { status: 401 }, |
| 705 | ); |
| 706 | }, |
| 707 | }), |
| 708 | ); |
| 709 | }); |
| 710 | |
| 711 | it.effect.each([ |
| 712 | { |
| 713 | name: "replaces a revoked link to another account", |
| 714 | revoked: true, |
| 715 | startup: false, |
| 716 | cloudUserId: "user-456", |
| 717 | }, |
| 718 | { |
| 719 | name: "replaces a revoked link to the same account", |
| 720 | revoked: true, |
| 721 | startup: false, |
| 722 | cloudUserId: "user-123", |
| 723 | }, |
| 724 | { |
| 725 | name: "replaces a revoked link after a partial drop removed its user id", |
| 726 | revoked: true, |
| 727 | startup: false, |
| 728 | cloudUserId: "user-456", |
| 729 | partialDrop: true, |
| 730 | }, |
| 731 | { |
| 732 | name: "rejects switching an active link to another account", |
| 733 | revoked: false, |
| 734 | startup: false, |
| 735 | cloudUserId: "user-456", |
| 736 | }, |
| 737 | { |
| 738 | name: "keeps a revoked link when startup links another account", |
| 739 | revoked: true, |
| 740 | startup: true, |
| 741 | cloudUserId: "user-456", |
| 742 | }, |
| 743 | ])("$name", ({ revoked, startup, cloudUserId, partialDrop }) => { |
| 744 | const { store, values } = makeMemorySecretStore([ |
| 745 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 746 | ...(partialDrop ? [] : [[CLOUD_LINKED_USER_ID, "user-123"] as const]), |
| 747 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "old-credential"], |
| 748 | ...(revoked ? [[CLOUD_LINK_REVOKED, "true"] as const] : []), |
| 749 | [CLOUD_CLI_DESIRED_LINK_SECRET, startup ? "publish_only" : "managed"], |
| 750 | ]); |
| 751 | const cloudMintPublicKey = |
| 752 | "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----"; |
| 753 | |
| 754 | return Effect.gen(function* () { |
| 755 | const link = yield* CloudLink.CloudLink; |
| 756 | expect((yield* link.linkState()).linkRevoked).toBe(revoked && !partialDrop); |
| 757 | const relink = Effect.gen(function* () { |
| 758 | if (startup) { |
| 759 | yield* link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773"); |
| 760 | } else { |
| 761 | yield* link.applyRelayConfig({ |
| 762 | relayUrl: "https://relay.example.test", |
| 763 | cloudUserId, |
| 764 | environmentCredential: "fresh-credential", |
| 765 | cloudMintPublicKey, |
| 766 | endpointRuntime: null, |
| 767 | }); |
| 768 | } |
| 769 | }); |
| 770 | const result = yield* relink.pipe( |
| 771 | Effect.provide( |
| 772 | ConfigProvider.layer( |
| 773 | ConfigProvider.fromEnv({ env: { T3CODE_RELAY_URL: "https://relay.example.test" } }), |
| 774 | ), |
| 775 | ), |
| 776 | Effect.flip, |
| 777 | Effect.option, |
| 778 | ); |
| 779 | if (revoked && !startup) { |
| 780 | expect(result).toEqual(Option.none()); |
| 781 | expect(yield* link.linkState()).toMatchObject({ |
| 782 | linked: true, |
| 783 | linkRevoked: false, |
| 784 | cloudUserId, |
| 785 | }); |
| 786 | expect(new TextDecoder().decode(values.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET))).toBe( |
| 787 | "fresh-credential", |
| 788 | ); |
| 789 | expect(values.has(CLOUD_CLI_DESIRED_LINK_SECRET)).toBe(cloudUserId === "user-123"); |
| 790 | } else { |
| 791 | expect(Option.getOrThrow(result)).toBeInstanceOf(CloudLink.CloudLinkAccountMismatchError); |
| 792 | expect(yield* link.linkState()).toMatchObject({ |
| 793 | cloudUserId: "user-123", |
| 794 | linkRevoked: revoked, |
| 795 | }); |
| 796 | expect(values.has(CLOUD_CLI_DESIRED_LINK_SECRET)).toBe(true); |
| 797 | } |
| 798 | }).pipe( |
| 799 | provideReleaseHarness({ |
| 800 | store, |
| 801 | applyConfigCalls: [], |
| 802 | requests: [], |
| 803 | respond: () => |
| 804 | Response.json({ |
| 805 | challenge: "challenge-1", |
| 806 | expiresAt: "2099-01-01T00:00:00.000Z", |
| 807 | ok: true, |
| 808 | cloudUserId: "user-456", |
| 809 | environmentId: "env_123", |
| 810 | endpoint: { |
| 811 | httpBaseUrl: "http://127.0.0.1:3773", |
| 812 | wsBaseUrl: "ws://127.0.0.1:3773", |
| 813 | providerKind: "manual", |
| 814 | }, |
| 815 | endpointRuntime: null, |
| 816 | relayIssuer: "https://relay.example.test", |
| 817 | environmentCredential: "fresh-credential", |
| 818 | cloudMintPublicKey, |
| 819 | }), |
| 820 | }), |
| 821 | ); |
| 822 | }); |
| 823 | |
| 824 | it.effect( |
| 825 | "starts a connector with a marker for the current origin without contacting relay", |
| 826 | () => { |
| 827 | const configJson = |
| 828 | '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}'; |
| 829 | const config = { |
| 830 | providerKind: "cloudflare_tunnel" as const, |
| 831 | connectorToken: "existing-token", |
| 832 | tunnelId: "existing-tunnel", |
| 833 | }; |
| 834 | const { store } = makeMemorySecretStore([ |
| 835 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, configJson], |
| 836 | [ |
| 837 | CLOUD_ENDPOINT_CONFIRMED_ORIGIN, |
| 838 | `{"config":${configJson},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}`, |
| 839 | ], |
| 840 | ]); |
| 841 | const applyConfigCalls: Array<unknown> = []; |
| 842 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 843 | |
| 844 | return Effect.gen(function* () { |
| 845 | const link = yield* CloudLink.CloudLink; |
| 846 | expect(yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true); |
| 847 | expect(applyConfigCalls).toEqual([config]); |
| 848 | expect(requests).toEqual([]); |
| 849 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 850 | }, |
| 851 | ); |
| 852 | |
| 853 | it.effect.each([ |
| 854 | { name: "missing", marker: undefined, origin: "http://127.0.0.1:3773" }, |
| 855 | { |
| 856 | name: "stale", |
| 857 | marker: |
| 858 | '{"config":{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}', |
| 859 | origin: "http://127.0.0.1:4884", |
| 860 | }, |
| 861 | ])("does not start a connector with a $name origin marker", ({ marker, origin }) => { |
| 862 | const entries: Array<readonly [string, string]> = [ |
| 863 | [ |
| 864 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 865 | '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}', |
| 866 | ], |
| 867 | ]; |
| 868 | if (marker !== undefined) entries.push([CLOUD_ENDPOINT_CONFIRMED_ORIGIN, marker]); |
| 869 | const { store } = makeMemorySecretStore(entries); |
| 870 | const applyConfigCalls: Array<unknown> = []; |
| 871 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 872 | |
| 873 | return Effect.gen(function* () { |
| 874 | const link = yield* CloudLink.CloudLink; |
| 875 | expect(yield* link.startManagedTunnelIfOriginConfirmed(origin)).toBe(false); |
| 876 | expect(applyConfigCalls).toEqual([]); |
| 877 | expect(requests).toEqual([]); |
| 878 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 879 | }); |
| 880 | |
| 881 | // regression: #9386 remove tunnels after hosts go offline |
| 882 | it.effect( |
| 883 | "starts the stored connector without a marker when confirmation is not required", |
| 884 | () => { |
| 885 | const config = { |
| 886 | providerKind: "cloudflare_tunnel" as const, |
| 887 | connectorToken: "existing-token", |
| 888 | tunnelId: "existing-tunnel", |
| 889 | }; |
| 890 | const { store } = makeMemorySecretStore([ |
| 891 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)], |
| 892 | ]); |
| 893 | const applyConfigCalls: Array<unknown> = []; |
| 894 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 895 | |
| 896 | return Effect.gen(function* () { |
| 897 | const link = yield* CloudLink.CloudLink; |
| 898 | expect( |
| 899 | yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773", { |
| 900 | requireConfirmedOrigin: false, |
| 901 | }), |
| 902 | ).toBe(true); |
| 903 | expect(applyConfigCalls).toEqual([config]); |
| 904 | expect(requests).toEqual([]); |
| 905 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 906 | }, |
| 907 | ); |
| 908 | |
| 909 | it.effect.each(["replaced", "removed"] as const)( |
| 910 | "does not activate a tunnel when its runtime config is %s during registration", |
| 911 | (mutation) => { |
| 912 | const originalConfig = |
| 913 | '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}'; |
| 914 | const { store, values } = makeMemorySecretStore([ |
| 915 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, originalConfig], |
| 916 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 917 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 918 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 919 | ]); |
| 920 | const applyConfigCalls: Array<unknown> = []; |
| 921 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 922 | |
| 923 | return Effect.gen(function* () { |
| 924 | const link = yield* CloudLink.CloudLink; |
| 925 | expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({ |
| 926 | status: "superseded", |
| 927 | }); |
| 928 | expect(applyConfigCalls).toEqual([]); |
| 929 | expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false); |
| 930 | }).pipe( |
| 931 | provideReleaseHarness({ |
| 932 | store, |
| 933 | applyConfigCalls, |
| 934 | requests, |
| 935 | respond: () => { |
| 936 | if (mutation === "replaced") { |
| 937 | values.set( |
| 938 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 939 | new TextEncoder().encode( |
| 940 | '{"providerKind":"cloudflare_tunnel","connectorToken":"fresh-token","tunnelId":"fresh-tunnel"}', |
| 941 | ), |
| 942 | ); |
| 943 | } else { |
| 944 | values.delete(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 945 | } |
| 946 | return Response.json({ status: "ready" }); |
| 947 | }, |
| 948 | }), |
| 949 | ); |
| 950 | }, |
| 951 | ); |
| 952 | |
| 953 | it.effect("requests startup recovery for a legacy config without a recorded tunnel ID", () => { |
| 954 | const { store } = makeMemorySecretStore([ |
| 955 | [ |
| 956 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 957 | '{"providerKind":"cloudflare_tunnel","connectorToken":"token"}', |
| 958 | ], |
| 959 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 960 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 961 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 962 | ]); |
| 963 | const applyConfigCalls: Array<unknown> = []; |
| 964 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 965 | |
| 966 | return Effect.gen(function* () { |
| 967 | const link = yield* CloudLink.CloudLink; |
| 968 | const registration = yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773"); |
| 969 | expect(registration).toEqual({ |
| 970 | status: "recovery_required", |
| 971 | config: { providerKind: "cloudflare_tunnel", connectorToken: "token" }, |
| 972 | }); |
| 973 | expect( |
| 974 | managedTunnelStartupAction({ |
| 975 | wantsCliLink: false, |
| 976 | registration, |
| 977 | }), |
| 978 | ).toEqual({ |
| 979 | action: "request_recovery", |
| 980 | config: { providerKind: "cloudflare_tunnel", connectorToken: "token" }, |
| 981 | }); |
| 982 | expect(requests).toEqual([]); |
| 983 | expect(applyConfigCalls).toEqual([]); |
| 984 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 985 | }); |
| 986 | |
| 987 | it.effect("recovers a web-linked tunnel and clears its revoked mark", () => { |
| 988 | const oldConfig = |
| 989 | '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}'; |
| 990 | const nextConfig = { |
| 991 | providerKind: "cloudflare_tunnel", |
| 992 | connectorToken: "new-token", |
| 993 | tunnelId: "new-tunnel", |
| 994 | } as const; |
| 995 | const { store, values } = makeMemorySecretStore([ |
| 996 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig], |
| 997 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 998 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 999 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 1000 | [CLOUD_LINK_REVOKED, "true"], |
| 1001 | ]); |
| 1002 | const applyConfigCalls: Array<unknown> = []; |
| 1003 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1004 | |
| 1005 | return Effect.gen(function* () { |
| 1006 | const link = yield* CloudLink.CloudLink; |
| 1007 | expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(true); |
| 1008 | expect(requests).toHaveLength(1); |
| 1009 | expect(requests[0]?.method).toBe("POST"); |
| 1010 | expect(requests[0]?.url).toBe("https://relay.example.test/v1/environments/env_123/tunnel"); |
| 1011 | expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential"); |
| 1012 | expect(applyConfigCalls).toEqual([nextConfig]); |
| 1013 | expect( |
| 1014 | Option.getOrNull( |
| 1015 | decodeRuntimeConfig(new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG))), |
| 1016 | ), |
| 1017 | ).toEqual(nextConfig); |
| 1018 | expect(values.has(CLOUD_LINK_REVOKED)).toBe(false); |
| 1019 | }).pipe( |
| 1020 | provideReleaseHarness({ |
| 1021 | store, |
| 1022 | applyConfigCalls, |
| 1023 | requests, |
| 1024 | respond: () => |
| 1025 | Response.json({ |
| 1026 | endpoint: { |
| 1027 | httpBaseUrl: "https://environment.example.test/", |
| 1028 | wsBaseUrl: "wss://environment.example.test/ws", |
| 1029 | providerKind: "cloudflare_tunnel", |
| 1030 | }, |
| 1031 | endpointRuntime: nextConfig, |
| 1032 | }), |
| 1033 | }), |
| 1034 | ); |
| 1035 | }); |
| 1036 | |
| 1037 | it.effect("does not recover an environment without a managed tunnel credential", () => { |
| 1038 | const { store } = makeMemorySecretStore([ |
| 1039 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"], |
| 1040 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 1041 | ]); |
| 1042 | const applyConfigCalls: Array<unknown> = []; |
| 1043 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1044 | |
| 1045 | return Effect.gen(function* () { |
| 1046 | const link = yield* CloudLink.CloudLink; |
| 1047 | expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false); |
| 1048 | expect(applyConfigCalls).toEqual([]); |
| 1049 | expect(requests).toEqual([]); |
| 1050 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 1051 | }); |
| 1052 | |
| 1053 | it.effect("ignores recovery requests for a tunnel that has already been replaced", () => { |
| 1054 | const { store } = makeMemorySecretStore([ |
| 1055 | [ |
| 1056 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 1057 | '{"providerKind":"cloudflare_tunnel","connectorToken":"current-token","tunnelId":"current-tunnel"}', |
| 1058 | ], |
| 1059 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 1060 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 1061 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 1062 | ]); |
| 1063 | const applyConfigCalls: Array<unknown> = []; |
| 1064 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1065 | |
| 1066 | return Effect.gen(function* () { |
| 1067 | const link = yield* CloudLink.CloudLink; |
| 1068 | expect( |
| 1069 | yield* link.recoverManagedTunnel("http://127.0.0.1:3773", { |
| 1070 | providerKind: "cloudflare_tunnel", |
| 1071 | connectorToken: "old-token", |
| 1072 | tunnelId: "old-tunnel", |
| 1073 | }), |
| 1074 | ).toBe(false); |
| 1075 | expect(requests).toEqual([]); |
| 1076 | expect(applyConfigCalls).toEqual([]); |
| 1077 | }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); |
| 1078 | }); |
| 1079 | |
| 1080 | it.effect.each([ |
| 1081 | { |
| 1082 | status: 401, |
| 1083 | body: { |
| 1084 | _tag: "RelayAuthInvalidError", |
| 1085 | code: "auth_invalid", |
| 1086 | reason: "invalid_bearer", |
| 1087 | traceId: "trace-revoked", |
| 1088 | }, |
| 1089 | rejection: "unauthorized", |
| 1090 | }, |
| 1091 | { status: 403, body: {}, rejection: "forbidden" }, |
| 1092 | { status: 409, body: {}, rejection: "rejected" }, |
| 1093 | ])("preserves a permanent $status relay recovery failure", ({ status, body, rejection }) => { |
| 1094 | const { store } = makeMemorySecretStore([ |
| 1095 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"], |
| 1096 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 1097 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 1098 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 1099 | ]); |
| 1100 | const applyConfigCalls: Array<unknown> = []; |
| 1101 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1102 | |
| 1103 | return Effect.gen(function* () { |
| 1104 | const link = yield* CloudLink.CloudLink; |
| 1105 | const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773")); |
| 1106 | |
| 1107 | expect(error).toMatchObject({ _tag: "RelayRequestError", rejection }); |
| 1108 | expect(CloudLink.shouldRetryCloudLink(error)).toBe(false); |
| 1109 | expect(requests).toHaveLength(1); |
| 1110 | expect(applyConfigCalls).toEqual([]); |
| 1111 | }).pipe( |
| 1112 | provideReleaseHarness({ |
| 1113 | store, |
| 1114 | applyConfigCalls, |
| 1115 | requests, |
| 1116 | respond: () => Response.json(body, { status }), |
| 1117 | }), |
| 1118 | ); |
| 1119 | }); |
| 1120 | |
| 1121 | it.effect("retries a relay link proof rejected as expired", () => { |
| 1122 | const { store } = makeMemorySecretStore([ |
| 1123 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"], |
| 1124 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 1125 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 1126 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 1127 | ]); |
| 1128 | const applyConfigCalls: Array<unknown> = []; |
| 1129 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1130 | |
| 1131 | return Effect.gen(function* () { |
| 1132 | const link = yield* CloudLink.CloudLink; |
| 1133 | const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773")); |
| 1134 | |
| 1135 | expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "unavailable" }); |
| 1136 | expect(error.message).toContain("Trace ID: trace-expired"); |
| 1137 | expect(CloudLink.shouldRetryCloudLink(error)).toBe(true); |
| 1138 | }).pipe( |
| 1139 | provideReleaseHarness({ |
| 1140 | store, |
| 1141 | applyConfigCalls, |
| 1142 | requests, |
| 1143 | respond: () => |
| 1144 | Response.json( |
| 1145 | { |
| 1146 | _tag: "RelayEnvironmentLinkProofExpiredError", |
| 1147 | code: "environment_link_proof_expired", |
| 1148 | traceId: "trace-expired", |
| 1149 | }, |
| 1150 | { status: 401 }, |
| 1151 | ), |
| 1152 | }), |
| 1153 | ); |
| 1154 | }); |
| 1155 | |
| 1156 | it.effect("keeps a tunnel configuration replaced during recovery", () => { |
| 1157 | const { store, values } = makeMemorySecretStore([ |
| 1158 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"], |
| 1159 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 1160 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 1161 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], |
| 1162 | ]); |
| 1163 | const applyConfigCalls: Array<unknown> = []; |
| 1164 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1165 | const freshConfig = new TextEncoder().encode("fresh-config"); |
| 1166 | |
| 1167 | return Effect.gen(function* () { |
| 1168 | const link = yield* CloudLink.CloudLink; |
| 1169 | expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false); |
| 1170 | expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig); |
| 1171 | expect(applyConfigCalls).toEqual([]); |
| 1172 | }).pipe( |
| 1173 | provideReleaseHarness({ |
| 1174 | store, |
| 1175 | applyConfigCalls, |
| 1176 | requests, |
| 1177 | respond: () => { |
| 1178 | values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig); |
| 1179 | return Response.json({ |
| 1180 | endpoint: { |
| 1181 | httpBaseUrl: "https://environment.example.test/", |
| 1182 | wsBaseUrl: "wss://environment.example.test/ws", |
| 1183 | providerKind: "cloudflare_tunnel", |
| 1184 | }, |
| 1185 | endpointRuntime: { |
| 1186 | providerKind: "cloudflare_tunnel", |
| 1187 | connectorToken: "replacement-token", |
| 1188 | }, |
| 1189 | }); |
| 1190 | }, |
| 1191 | }), |
| 1192 | ); |
| 1193 | }); |
| 1194 | |
| 1195 | it.effect("does not report a managed tunnel after a relay config write fails part-way", () => { |
| 1196 | const { store, values } = makeMemorySecretStore([ |
| 1197 | [CLOUD_ENDPOINT_RUNTIME_CONFIG, "managed-config"], |
| 1198 | [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"], |
| 1199 | [RELAY_URL_SECRET, "https://relay.example.test"], |
| 1200 | [CLOUD_LINKED_USER_ID, "user-123"], |
| 1201 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "old-credential"], |
| 1202 | ]); |
| 1203 | const failingStore: ServerSecretStore.ServerSecretStore["Service"] = { |
| 1204 | ...store, |
| 1205 | set: (name, value) => |
| 1206 | name === RELAY_ISSUER_SECRET |
| 1207 | ? Effect.fail( |
| 1208 | new ServerSecretStore.SecretStorePersistError({ |
| 1209 | resource: name, |
| 1210 | cause: PlatformError.systemError({ |
| 1211 | _tag: "PermissionDenied", |
| 1212 | module: "FileSystem", |
| 1213 | method: "rename", |
| 1214 | pathOrDescriptor: `${name}.bin`, |
| 1215 | }), |
| 1216 | }), |
| 1217 | ) |
| 1218 | : store.set(name, value), |
| 1219 | }; |
| 1220 | const applyConfigCalls: Array<unknown> = []; |
| 1221 | const requests: Array<HttpClientRequest.HttpClientRequest> = []; |
| 1222 | const cloudMintPublicKey = |
| 1223 | "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAMY09Vo5CzEA6aEkhB/0h27t4Qs71SHS1fTSI4K0KvZQ=\n-----END PUBLIC KEY-----\n"; |
| 1224 | |
| 1225 | return Effect.gen(function* () { |
| 1226 | const link = yield* CloudLink.CloudLink; |
| 1227 | const error = yield* Effect.flip( |
| 1228 | link.applyRelayConfig({ |
| 1229 | relayUrl: "https://relay.example.test", |
| 1230 | cloudUserId: "user-123", |
| 1231 | environmentCredential: "new-credential", |
| 1232 | cloudMintPublicKey, |
| 1233 | endpointRuntime: null, |
| 1234 | }), |
| 1235 | ); |
| 1236 | |
| 1237 | expect(error._tag).toBe("CloudLinkInternalError"); |
| 1238 | expect(yield* link.linkState()).toMatchObject({ |
| 1239 | linked: true, |
| 1240 | cloudUserId: "user-123", |
| 1241 | managedTunnelActive: false, |
| 1242 | }); |
| 1243 | expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false); |
| 1244 | }).pipe(provideReleaseHarness({ store: failingStore, applyConfigCalls, requests })); |
| 1245 | }); |
| 1246 | |
| 1247 | it.effect("does not report a not-linked check once the managed tunnel config is stored", () => { |
| 1248 | const { store } = makeMemorySecretStore(managedLinkSecrets); |
| 1249 | const notLinked = ConnectReachability.classifyReachability( |
| 1250 | { |
| 1251 | managedTunnelConfigured: false, |
| 1252 | connector: null, |
| 1253 | endpoint: null, |
| 1254 | edgeReachable: null, |
| 1255 | exitNode: null, |
| 1256 | }, |
| 1257 | "2026-10-29T00:00:00.000Z", |
| 1258 | ); |
| 1259 | |
| 1260 | return Effect.gen(function* () { |
| 1261 | const state = yield* (yield* CloudLink.CloudLink).linkState(); |
| 1262 | |
| 1263 | expect(state.managedTunnelActive).toBe(true); |
| 1264 | expect(state.reachability?.status === "unreachable" && state.reachability.cause).not.toBe( |
| 1265 | "not_linked", |
| 1266 | ); |
| 1267 | // The address shows before any check passes. |
| 1268 | expect(state.tunnelHostname).toBe("prod-abc.t3coderelay.com"); |
| 1269 | }).pipe( |
| 1270 | provideReleaseHarness({ |
| 1271 | store, |
| 1272 | applyConfigCalls: [], |
| 1273 | requests: [], |
| 1274 | latestReachability: Effect.succeedSome(notLinked), |
| 1275 | connector: { |
| 1276 | pid: 123, |
| 1277 | readyConnections: 0, |
| 1278 | hostname: "prod-abc.t3coderelay.com", |
| 1279 | origin: null, |
| 1280 | protocol: null, |
| 1281 | }, |
| 1282 | }), |
| 1283 | ); |
| 1284 | }); |
| 1285 | |
| 1286 | it.effect("reports a check that ran after the managed tunnel config was stored", () => { |
| 1287 | const { store } = makeMemorySecretStore(managedLinkSecrets); |
| 1288 | const reachable = { |
| 1289 | status: "reachable" as const, |
| 1290 | checkedAt: "2026-10-29T00:00:00.000Z", |
| 1291 | readyConnections: 4, |
| 1292 | protocol: "quic", |
| 1293 | }; |
| 1294 | |
| 1295 | return Effect.gen(function* () { |
| 1296 | const state = yield* (yield* CloudLink.CloudLink).linkState(); |
| 1297 | |
| 1298 | expect(state.reachability).toEqual(reachable); |
| 1299 | }).pipe( |
| 1300 | provideReleaseHarness({ |
| 1301 | store, |
| 1302 | applyConfigCalls: [], |
| 1303 | requests: [], |
| 1304 | latestReachability: Effect.succeedSome(reachable), |
| 1305 | }), |
| 1306 | ); |
| 1307 | }); |
| 1308 | }); |