The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | type EnvironmentCloudLinkStateResult, |
| 3 | type EnvironmentCloudPreferencesRequest, |
| 4 | type EnvironmentCloudRelayConfigResult, |
| 5 | } from "@t3tools/contracts"; |
| 6 | import { |
| 7 | RelayCloudEnvironmentHealthProofPayload, |
| 8 | type RelayCloudEnvironmentHealthRequest, |
| 9 | RelayCloudMintCredentialProofPayload, |
| 10 | type RelayCloudMintCredentialRequest, |
| 11 | type RelayEnvironmentConfigRequest, |
| 12 | type RelayEnvironmentHealthResponse, |
| 13 | type RelayEnvironmentHealthResponseProofPayload, |
| 14 | type RelayEnvironmentLinkProof, |
| 15 | type RelayEnvironmentLinkProofPayload, |
| 16 | RelayEnvironmentLinkChallengeResponse, |
| 17 | RelayEnvironmentLinkResponse, |
| 18 | type RelayEnvironmentMintResponse, |
| 19 | type RelayEnvironmentMintResponseProofPayload, |
| 20 | type RelayLinkProofRequest, |
| 21 | type RelayManagedEndpointOrigin, |
| 22 | type RelayManagedEndpointRecoveryProofPayload, |
| 23 | RelayManagedEndpointRecoveryRegistrationResponse, |
| 24 | RelayManagedEndpointRecoveryResponse, |
| 25 | type RelayManagedEndpointRuntimeConfig, |
| 26 | RelayOkResponse, |
| 27 | } from "@t3tools/contracts/relay"; |
| 28 | import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; |
| 29 | import { |
| 30 | decodeRelayJwt, |
| 31 | normalizeRelayIssuer, |
| 32 | RELAY_HEALTH_REQUEST_TYP, |
| 33 | RELAY_HEALTH_RESPONSE_TYP, |
| 34 | RELAY_LINK_PROOF_TYP, |
| 35 | RELAY_MANAGED_TUNNEL_RECOVERY_TYP, |
| 36 | RELAY_MINT_REQUEST_TYP, |
| 37 | RELAY_MINT_RESPONSE_TYP, |
| 38 | verifyRelayJwt, |
| 39 | } from "@t3tools/shared/relayJwt"; |
| 40 | import { isSecureRelayUrl, normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl"; |
| 41 | import * as Context from "effect/Context"; |
| 42 | import * as Digest from "effect/crypto/Digest"; |
| 43 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 44 | import * as Hex from "effect/encoding/Hex"; |
| 45 | import * as Signature from "effect/crypto/Signature"; |
| 46 | import * as Jwk from "effect/jose/Jwk"; |
| 47 | import * as DateTime from "effect/DateTime"; |
| 48 | import * as Duration from "effect/Duration"; |
| 49 | import * as Effect from "effect/Effect"; |
| 50 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 51 | import * as FileSystem from "effect/FileSystem"; |
| 52 | import * as Layer from "effect/Layer"; |
| 53 | import * as Option from "effect/Option"; |
| 54 | import * as Path from "effect/Path"; |
| 55 | import type * as PlatformError from "effect/PlatformError"; |
| 56 | import * as Schedule from "effect/Schedule"; |
| 57 | import * as Schema from "effect/Schema"; |
| 58 | import * as Semaphore from "effect/Semaphore"; |
| 59 | import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; |
| 60 | import type * as HttpClientError from "effect/http/HttpClientError"; |
| 61 | import * as HttpServer from "effect/http/HttpServer"; |
| 62 | |
| 63 | import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; |
| 64 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 65 | import * as ServerConfig from "../config.ts"; |
| 66 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 67 | import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; |
| 68 | import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts"; |
| 69 | import { loopbackUrlHostForAddress } from "../startupAccess.ts"; |
| 70 | import { |
| 71 | type CliDesiredLinkMode, |
| 72 | dropRevokedCloudLink, |
| 73 | readCliDesiredCloudLink, |
| 74 | readCliDesiredLinkMode, |
| 75 | setCliDesiredCloudLink, |
| 76 | } from "./CliState.ts"; |
| 77 | import * as CliTokenManager from "./CliTokenManager.ts"; |
| 78 | import { |
| 79 | CLOUD_ENDPOINT_CONFIRMED_ORIGIN, |
| 80 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 81 | CLOUD_LINK_REVOKED, |
| 82 | CLOUD_LINKED_USER_ID, |
| 83 | CLOUD_MINT_PUBLIC_KEY, |
| 84 | decodeConfirmedOrigin, |
| 85 | decodeRuntimeConfig, |
| 86 | encodeConfirmedOriginJson, |
| 87 | encodeEndpointRuntimeConfigJson, |
| 88 | HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, |
| 89 | PUBLISH_AGENT_ACTIVITY_SECRET, |
| 90 | readRelayConnection, |
| 91 | RELAY_ENVIRONMENT_CREDENTIAL_SECRET, |
| 92 | RELAY_ISSUER_SECRET, |
| 93 | RELAY_URL_SECRET, |
| 94 | } from "./config.ts"; |
| 95 | import { EnvironmentSigningKey } from "./environmentKeys.ts"; |
| 96 | import * as ConnectReachability from "./ConnectReachability.ts"; |
| 97 | import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts"; |
| 98 | import * as ManagedLimits from "../policy/managedLimits.ts"; |
| 99 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 100 | import * as ServerSettings from "../serverSettings.ts"; |
| 101 | import { relayUrlConfig } from "./publicConfig.ts"; |
| 102 | import { |
| 103 | filterRelayResponse, |
| 104 | relayRequestError, |
| 105 | type RelayRequestError, |
| 106 | shouldRetryRelayRequest, |
| 107 | } from "./relayResponse.ts"; |
| 108 | import { |
| 109 | hasBoundedCloudProofLifetime, |
| 110 | hasExactScope, |
| 111 | isLoopbackEndpointOrigin, |
| 112 | isSupportedLinkProviderKind, |
| 113 | linkProofScopes, |
| 114 | managedEndpointRuntimeConfigsMatch, |
| 115 | parseManagedEndpointLocalOrigin, |
| 116 | } from "./linkChecks.ts"; |
| 117 | import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts"; |
| 118 | |
| 119 | const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-"; |
| 120 | const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-"; |
| 121 | const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-"; |
| 122 | const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-"; |
| 123 | export const CLOUD_REPLAY_MARKER_PREFIXES = [ |
| 124 | CLOUD_MINT_NONCE_PREFIX, |
| 125 | CLOUD_MINT_JTI_PREFIX, |
| 126 | CLOUD_HEALTH_NONCE_PREFIX, |
| 127 | CLOUD_HEALTH_JTI_PREFIX, |
| 128 | ] as const; |
| 129 | const MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT = Duration.minutes(2); |
| 130 | const RELAY_CONFIG_FIELD_MESSAGES = { |
| 131 | relayUrl: "Relay URL must be a secure absolute HTTPS URL.", |
| 132 | relayIssuer: "Relay issuer must be a secure absolute HTTPS URL.", |
| 133 | environmentCredential: "Relay environment credential is required.", |
| 134 | cloudUserId: "Cloud user id is required.", |
| 135 | cloudMintPublicKey: "Cloud mint public key must be a valid Ed25519 public key.", |
| 136 | } as const; |
| 137 | |
| 138 | export class CloudLinkRelayConfigInvalidError extends Schema.TaggedError<CloudLinkRelayConfigInvalidError>()( |
| 139 | "CloudLinkRelayConfigInvalidError", |
| 140 | { |
| 141 | field: Schema.Literals([ |
| 142 | "relayUrl", |
| 143 | "relayIssuer", |
| 144 | "environmentCredential", |
| 145 | "cloudUserId", |
| 146 | "cloudMintPublicKey", |
| 147 | ]), |
| 148 | }, |
| 149 | ) { |
| 150 | override get message(): string { |
| 151 | return RELAY_CONFIG_FIELD_MESSAGES[this.field]; |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | export class CloudLinkOriginInvalidError extends Schema.TaggedError<CloudLinkOriginInvalidError>()( |
| 156 | "CloudLinkOriginInvalidError", |
| 157 | { origin: Schema.Literals(["endpoint", "local"]) }, |
| 158 | ) { |
| 159 | override get message(): string { |
| 160 | return this.origin === "endpoint" |
| 161 | ? "Invalid managed endpoint origin." |
| 162 | : "Could not resolve local environment origin."; |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | export class CloudLinkNotLinkedError extends Schema.TaggedError<CloudLinkNotLinkedError>()( |
| 167 | "CloudLinkNotLinkedError", |
| 168 | {}, |
| 169 | ) { |
| 170 | override get message(): string { |
| 171 | return "Link this environment to T3 Connect first."; |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | export class CloudLinkAccountMismatchError extends Schema.TaggedError<CloudLinkAccountMismatchError>()( |
| 176 | "CloudLinkAccountMismatchError", |
| 177 | {}, |
| 178 | ) { |
| 179 | override get message(): string { |
| 180 | return "This environment is already linked to a different cloud account. Unlink it before switching accounts."; |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | export class CloudLinkAuthorizationMissingError extends Schema.TaggedError<CloudLinkAuthorizationMissingError>()( |
| 185 | "CloudLinkAuthorizationMissingError", |
| 186 | {}, |
| 187 | ) { |
| 188 | override get message(): string { |
| 189 | return "Run `t3 connect link` to authorize this environment."; |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | const SignedRelayRequest = Schema.Literals(["health", "mint"]); |
| 194 | |
| 195 | export class CloudLinkProofRejectedError extends Schema.TaggedError<CloudLinkProofRejectedError>()( |
| 196 | "CloudLinkProofRejectedError", |
| 197 | { request: SignedRelayRequest }, |
| 198 | ) { |
| 199 | override get message(): string { |
| 200 | return `Invalid cloud ${this.request} request.`; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | export class CloudLinkProofReplayedError extends Schema.TaggedError<CloudLinkProofReplayedError>()( |
| 205 | "CloudLinkProofReplayedError", |
| 206 | { request: SignedRelayRequest }, |
| 207 | ) { |
| 208 | override get message(): string { |
| 209 | return `Cloud ${this.request} request was already consumed.`; |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | export class CloudLinkTunnelSupersededError extends Schema.TaggedError<CloudLinkTunnelSupersededError>()( |
| 214 | "CloudLinkTunnelSupersededError", |
| 215 | {}, |
| 216 | ) { |
| 217 | override get message(): string { |
| 218 | return "The managed tunnel configuration changed during registration."; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | export class CloudLinkEndpointUnavailableError extends Schema.TaggedError<CloudLinkEndpointUnavailableError>()( |
| 223 | "CloudLinkEndpointUnavailableError", |
| 224 | { |
| 225 | reason: Schema.Literals(["runtime-not-started", "origin-unconfirmed"]), |
| 226 | endpointRuntimeStatus: Schema.Unknown, |
| 227 | }, |
| 228 | ) { |
| 229 | override get message(): string { |
| 230 | return this.reason === "runtime-not-started" |
| 231 | ? "Managed endpoint runtime could not be started." |
| 232 | : "Managed endpoint origin could not be confirmed."; |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | const INTERNAL_OPERATION_MESSAGES = { |
| 237 | "relay-url-unconfigured": |
| 238 | "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.", |
| 239 | "generate-link-proof": "Could not generate environment link proof.", |
| 240 | "persist-relay-config": "Could not persist environment relay configuration.", |
| 241 | "register-endpoint-origin": "Could not register the managed endpoint origin.", |
| 242 | "resolve-server-origin": "Could not resolve the local server origin.", |
| 243 | "persist-desired-link": "Could not persist desired T3 Connect link state.", |
| 244 | "sign-recovery-proof": "Could not sign the managed tunnel recovery request.", |
| 245 | "unsupported-recovered-tunnel": |
| 246 | "T3 Connect returned an unsupported managed tunnel configuration.", |
| 247 | "persist-recovered-tunnel": "Could not persist the recovered managed tunnel configuration.", |
| 248 | "read-relay-config": "Could not read environment relay configuration.", |
| 249 | "remove-relay-config": "Could not remove environment relay configuration.", |
| 250 | "update-live-activity-preference": "Could not update T3 Connect Live Activity preferences.", |
| 251 | "update-webhook-settings": "Could not update T3 Connect webhook settings.", |
| 252 | "read-preferences": "Could not read environment cloud preferences.", |
| 253 | "persist-preferences": "Could not persist environment cloud preferences.", |
| 254 | "answer-health": "Could not answer cloud health request.", |
| 255 | "issue-credential": "Could not issue cloud connection credential.", |
| 256 | } as const; |
| 257 | |
| 258 | export class CloudLinkInternalError extends Schema.TaggedError<CloudLinkInternalError>()( |
| 259 | "CloudLinkInternalError", |
| 260 | { |
| 261 | operation: Schema.Literals( |
| 262 | Object.keys(INTERNAL_OPERATION_MESSAGES) as [ |
| 263 | keyof typeof INTERNAL_OPERATION_MESSAGES, |
| 264 | ...Array<keyof typeof INTERNAL_OPERATION_MESSAGES>, |
| 265 | ], |
| 266 | ), |
| 267 | cause: Schema.optional(Schema.Defect()), |
| 268 | }, |
| 269 | ) { |
| 270 | override get message(): string { |
| 271 | return INTERNAL_OPERATION_MESSAGES[this.operation]; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | const internalError = |
| 276 | (operation: CloudLinkInternalError["operation"]) => |
| 277 | (cause: unknown): Effect.Effect<never, CloudLinkInternalError> => |
| 278 | Effect.fail(new CloudLinkInternalError({ operation, cause })); |
| 279 | |
| 280 | const isPermanentLinkError = Schema.is( |
| 281 | Schema.Union([ |
| 282 | CloudLinkRelayConfigInvalidError, |
| 283 | CloudLinkOriginInvalidError, |
| 284 | CloudLinkNotLinkedError, |
| 285 | CloudLinkAccountMismatchError, |
| 286 | CloudLinkAuthorizationMissingError, |
| 287 | CloudLinkProofRejectedError, |
| 288 | CloudLinkProofReplayedError, |
| 289 | CloudLinkTunnelSupersededError, |
| 290 | ]), |
| 291 | ); |
| 292 | |
| 293 | export const shouldRetryCloudLink = (error: unknown): boolean => |
| 294 | shouldRetryRelayRequest(error) && |
| 295 | !isPermanentLinkError(error) && |
| 296 | !(CliTokenManager.isCloudCliCredentialRefreshError(error) && error.requiresLogin); |
| 297 | |
| 298 | const rollbackFailed = (cause: unknown) => |
| 299 | Effect.logWarning("Could not roll back a T3 Connect preference", { cause }); |
| 300 | |
| 301 | const requireRelayUrl = relayUrlConfig.pipe( |
| 302 | Effect.mapError( |
| 303 | (cause) => new CloudLinkInternalError({ operation: "relay-url-unconfigured", cause }), |
| 304 | ), |
| 305 | ); |
| 306 | |
| 307 | function bytesToString(bytes: Uint8Array): string { |
| 308 | return new TextDecoder().decode(bytes); |
| 309 | } |
| 310 | |
| 311 | function stringToBytes(value: string): Uint8Array { |
| 312 | return new TextEncoder().encode(value); |
| 313 | } |
| 314 | |
| 315 | export function consumeCloudReplayGuards(input: { |
| 316 | readonly secrets: ServerSecretStore.ServerSecretStore["Service"]; |
| 317 | readonly names: ReadonlyArray<string>; |
| 318 | readonly value: Uint8Array; |
| 319 | }) { |
| 320 | return Effect.forEach( |
| 321 | input.names, |
| 322 | (name) => |
| 323 | input.secrets.create(name, input.value).pipe( |
| 324 | Effect.as(true), |
| 325 | Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) => |
| 326 | ServerSecretStore.isSecretAlreadyExistsError(error) |
| 327 | ? Effect.succeed(false) |
| 328 | : Effect.fail(error), |
| 329 | ), |
| 330 | ), |
| 331 | { concurrency: input.names.length }, |
| 332 | ).pipe(Effect.map((created) => created.every(Boolean))); |
| 333 | } |
| 334 | |
| 335 | function validateCloudMintPublicKey( |
| 336 | publicKey: string, |
| 337 | ): Effect.Effect<void, CloudLinkRelayConfigInvalidError> { |
| 338 | return Jwk.importSpki(publicKey.replace(/\\n/g, "\n"), "EdDSA").pipe( |
| 339 | Effect.asVoid, |
| 340 | Effect.mapError(() => new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" })), |
| 341 | ); |
| 342 | } |
| 343 | |
| 344 | function invalidRelayConfigField( |
| 345 | payload: RelayEnvironmentConfigRequest, |
| 346 | ): CloudLinkRelayConfigInvalidError["field"] | null { |
| 347 | if (!isSecureRelayUrl(payload.relayUrl)) return "relayUrl"; |
| 348 | if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) { |
| 349 | return "relayIssuer"; |
| 350 | } |
| 351 | if (payload.environmentCredential.trim().length === 0) return "environmentCredential"; |
| 352 | if (payload.cloudUserId.trim().length === 0) return "cloudUserId"; |
| 353 | return null; |
| 354 | } |
| 355 | |
| 356 | function validateRelayConfigPayload( |
| 357 | payload: RelayEnvironmentConfigRequest, |
| 358 | ): Effect.Effect<void, CloudLinkRelayConfigInvalidError> { |
| 359 | const field = invalidRelayConfigField(payload); |
| 360 | return field === null |
| 361 | ? Effect.void |
| 362 | : Effect.fail(new CloudLinkRelayConfigInvalidError({ field })); |
| 363 | } |
| 364 | |
| 365 | function normalizePemForSignedPayload(value: string): string { |
| 366 | return value.trim(); |
| 367 | } |
| 368 | |
| 369 | type ManagedTunnelRecoveryProofInput = { |
| 370 | readonly environmentId: RelayManagedEndpointRecoveryProofPayload["environmentId"]; |
| 371 | readonly cloudUserId: string; |
| 372 | readonly relayUrl: string; |
| 373 | } & ( |
| 374 | | { |
| 375 | readonly action: "register"; |
| 376 | readonly tunnelId: string; |
| 377 | readonly origin: RelayManagedEndpointOrigin; |
| 378 | } |
| 379 | | { readonly action: "recover"; readonly origin: RelayManagedEndpointOrigin } |
| 380 | ); |
| 381 | |
| 382 | export type CloudLinkError = |
| 383 | | CloudLinkAccountMismatchError |
| 384 | | CloudLinkAuthorizationMissingError |
| 385 | | CloudLinkEndpointUnavailableError |
| 386 | | CloudLinkInternalError |
| 387 | | CloudLinkNotLinkedError |
| 388 | | CloudLinkOriginInvalidError |
| 389 | | CloudLinkProofRejectedError |
| 390 | | CloudLinkProofReplayedError |
| 391 | | CloudLinkRelayConfigInvalidError |
| 392 | | CloudLinkTunnelSupersededError; |
| 393 | |
| 394 | type CloudLinkBackgroundError = |
| 395 | | CloudLinkEndpointUnavailableError |
| 396 | | CloudLinkInternalError |
| 397 | | CloudLinkOriginInvalidError |
| 398 | | RelayRequestError |
| 399 | | ServerSecretStore.SecretStoreError |
| 400 | | Schema.SchemaError |
| 401 | | PlatformError.PlatformError; |
| 402 | |
| 403 | type ManagedTunnelRegistration = |
| 404 | | { readonly status: "not_linked" | "superseded" | "revoked" } |
| 405 | | { readonly status: "recovery_required"; readonly config: RelayManagedEndpointRuntimeConfig } |
| 406 | | { |
| 407 | readonly status: "ready"; |
| 408 | readonly endpointRuntimeStatus: ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus; |
| 409 | }; |
| 410 | |
| 411 | export class CloudLink extends Context.Service< |
| 412 | CloudLink, |
| 413 | { |
| 414 | /** Signs the proof the relay asks for to link this environment, for this server's own origin. */ |
| 415 | readonly linkProof: ( |
| 416 | request: RelayLinkProofRequest, |
| 417 | ) => Effect.Effect< |
| 418 | RelayEnvironmentLinkProof, |
| 419 | | CloudLinkOriginInvalidError |
| 420 | | CloudLinkInternalError |
| 421 | | EnvironmentAuth.ServerAuthInternalError |
| 422 | | ManagedLimits.ManagedPolicyRefusedError |
| 423 | >; |
| 424 | readonly applyRelayConfig: ( |
| 425 | payload: RelayEnvironmentConfigRequest, |
| 426 | ) => Effect.Effect< |
| 427 | EnvironmentCloudRelayConfigResult, |
| 428 | | CloudLinkAccountMismatchError |
| 429 | | CloudLinkEndpointUnavailableError |
| 430 | | CloudLinkInternalError |
| 431 | | CloudLinkOriginInvalidError |
| 432 | | CloudLinkRelayConfigInvalidError |
| 433 | | CloudLinkTunnelSupersededError |
| 434 | | EnvironmentAuth.ServerAuthInternalError |
| 435 | | ManagedLimits.ManagedPolicyRefusedError |
| 436 | | RelayRequestError |
| 437 | >; |
| 438 | readonly linkState: () => Effect.Effect< |
| 439 | EnvironmentCloudLinkStateResult, |
| 440 | CloudLinkInternalError |
| 441 | >; |
| 442 | readonly unlink: () => Effect.Effect<EnvironmentCloudRelayConfigResult, CloudLinkInternalError>; |
| 443 | readonly updatePreferences: ( |
| 444 | input: EnvironmentCloudPreferencesRequest, |
| 445 | ) => Effect.Effect< |
| 446 | EnvironmentCloudLinkStateResult, |
| 447 | CloudLinkNotLinkedError | CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError |
| 448 | >; |
| 449 | readonly updateLiveActivityPreference: ( |
| 450 | enabled: boolean, |
| 451 | ) => Effect.Effect< |
| 452 | RelayOkResponse, |
| 453 | CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError |
| 454 | >; |
| 455 | readonly answerHealthRequest: ( |
| 456 | request: RelayCloudEnvironmentHealthRequest, |
| 457 | ) => Effect.Effect< |
| 458 | RelayEnvironmentHealthResponse, |
| 459 | | CloudLinkProofRejectedError |
| 460 | | CloudLinkProofReplayedError |
| 461 | | CloudLinkInternalError |
| 462 | | EnvironmentAuth.ServerAuthInternalError |
| 463 | | ManagedLimits.ManagedPolicyRefusedError |
| 464 | >; |
| 465 | readonly mintCredential: ( |
| 466 | request: RelayCloudMintCredentialRequest, |
| 467 | ) => Effect.Effect< |
| 468 | RelayEnvironmentMintResponse, |
| 469 | | CloudLinkProofRejectedError |
| 470 | | CloudLinkProofReplayedError |
| 471 | | CloudLinkInternalError |
| 472 | | EnvironmentAuth.ServerAuthInternalError |
| 473 | | ManagedLimits.ManagedPolicyRefusedError |
| 474 | >; |
| 475 | readonly reconcileDesiredLinkIfStillDesired: ( |
| 476 | localOrigin: string, |
| 477 | ) => Effect.Effect< |
| 478 | CliDesiredLinkMode | null, |
| 479 | | CloudLinkBackgroundError |
| 480 | | CloudLinkAccountMismatchError |
| 481 | | CloudLinkAuthorizationMissingError |
| 482 | | CloudLinkRelayConfigInvalidError |
| 483 | | EnvironmentAuth.ServerAuthInternalError |
| 484 | | CliTokenManager.CloudCliTokenManagerError |
| 485 | >; |
| 486 | readonly registerManagedTunnelRecovery: ( |
| 487 | localOrigin: string, |
| 488 | options?: { readonly retryRuntimeFailures?: boolean }, |
| 489 | ) => Effect.Effect<ManagedTunnelRegistration, CloudLinkBackgroundError>; |
| 490 | readonly recoverManagedTunnel: ( |
| 491 | localOrigin: string, |
| 492 | expectedConfig?: RelayManagedEndpointRuntimeConfig, |
| 493 | options?: { readonly retryRuntimeFailures?: boolean }, |
| 494 | ) => Effect.Effect<boolean, CloudLinkBackgroundError>; |
| 495 | readonly startManagedTunnelIfOriginConfirmed: ( |
| 496 | localOrigin: string, |
| 497 | options?: { readonly requireConfirmedOrigin?: boolean }, |
| 498 | ) => Effect.Effect< |
| 499 | boolean, |
| 500 | | CloudLinkEndpointUnavailableError |
| 501 | | CloudLinkOriginInvalidError |
| 502 | | ServerSecretStore.SecretStoreError |
| 503 | >; |
| 504 | readonly releaseManagedTunnelOnShutdown: () => Effect.Effect< |
| 505 | boolean, |
| 506 | | CloudLinkBackgroundError |
| 507 | | CliTokenManager.CloudCliTokenManagerError |
| 508 | | HttpClientError.HttpClientError |
| 509 | >; |
| 510 | } |
| 511 | >()("t3/cloud/CloudLink") {} |
| 512 | |
| 513 | const make = Effect.gen(function* () { |
| 514 | const secrets = yield* ServerSecretStore.ServerSecretStore; |
| 515 | const environment = yield* ServerEnvironment.ServerEnvironment; |
| 516 | const endpointRuntime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime; |
| 517 | const reachability = yield* ConnectReachability.ConnectReachability; |
| 518 | const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 519 | const serverSettings = yield* ServerSettings.ServerSettingsService; |
| 520 | const cliTokenManager = yield* CliTokenManager.CloudCliTokenManager; |
| 521 | const httpClient = yield* HttpClient.HttpClient; |
| 522 | const httpServer = yield* HttpServer.HttpServer; |
| 523 | const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; |
| 524 | const random = yield* SecureRandom.SecureRandom; |
| 525 | const digest = yield* Digest.Digest; |
| 526 | const signature = yield* Signature.Signature; |
| 527 | const signingKey = yield* EnvironmentSigningKey; |
| 528 | const config = yield* ServerConfig.ServerConfig; |
| 529 | const fileSystem = yield* FileSystem.FileSystem; |
| 530 | const path = yield* Path.Path; |
| 531 | const managedPolicy = yield* ManagedPolicy.ManagedPolicy; |
| 532 | |
| 533 | // Relay-signed text must not name a file directly; a digest is also a fixed, safe length. |
| 534 | // Untraced: it runs twice per proof inside the health and mint spans. |
| 535 | const replayMarkerName = Effect.fnUntraced(function* (prefix: string, value: string) { |
| 536 | const hash = yield* digest.digest(Digest.sha256, stringToBytes(value)).pipe(Effect.orDie); |
| 537 | return `${prefix}${Hex.encode(hash)}`; |
| 538 | }); |
| 539 | |
| 540 | const withSecrets = Effect.provideService(ServerSecretStore.ServerSecretStore, secrets); |
| 541 | const withRuntimeFiles = <A, E>( |
| 542 | effect: Effect.Effect<A, E, ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path>, |
| 543 | ) => |
| 544 | effect.pipe( |
| 545 | Effect.provideService(ServerConfig.ServerConfig, config), |
| 546 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 547 | Effect.provideService(Path.Path, path), |
| 548 | ); |
| 549 | |
| 550 | const validateLinkedCloudUser = ( |
| 551 | cloudUserId: string, |
| 552 | ): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | CloudLinkAccountMismatchError> => |
| 553 | secrets.get(CLOUD_LINKED_USER_ID).pipe( |
| 554 | Effect.mapError( |
| 555 | (cause) => |
| 556 | new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ |
| 557 | cause, |
| 558 | }), |
| 559 | ), |
| 560 | Effect.flatMap((existing) => { |
| 561 | if (Option.isNone(existing)) { |
| 562 | return Effect.void; |
| 563 | } |
| 564 | const existingCloudUserId = bytesToString(existing.value); |
| 565 | return existingCloudUserId === cloudUserId |
| 566 | ? Effect.void |
| 567 | : Effect.fail(new CloudLinkAccountMismatchError({})); |
| 568 | }), |
| 569 | ); |
| 570 | |
| 571 | const readInstalledCloudUserId: Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> = |
| 572 | secrets.get(CLOUD_LINKED_USER_ID).pipe( |
| 573 | Effect.mapError( |
| 574 | (cause) => |
| 575 | new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ |
| 576 | cause, |
| 577 | }), |
| 578 | ), |
| 579 | Effect.flatMap((bytes) => |
| 580 | Option.isSome(bytes) |
| 581 | ? Effect.succeed(bytesToString(bytes.value)) |
| 582 | : Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})), |
| 583 | ), |
| 584 | ); |
| 585 | |
| 586 | // The tunnel must reach this server, so the signed origin is its own loopback address, never the caller's. |
| 587 | const serverLoopbackOrigin = Effect.gen(function* () { |
| 588 | const address = httpServer.address; |
| 589 | if (typeof address === "string" || !("port" in address)) { |
| 590 | return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" }); |
| 591 | } |
| 592 | const { origin } = parseManagedEndpointLocalOrigin( |
| 593 | `http://${loopbackUrlHostForAddress(address)}:${address.port}`, |
| 594 | ); |
| 595 | if (!isLoopbackEndpointOrigin(origin)) { |
| 596 | return yield* new CloudLinkOriginInvalidError({ origin: "local" }); |
| 597 | } |
| 598 | return origin; |
| 599 | }); |
| 600 | |
| 601 | const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* ( |
| 602 | request: RelayLinkProofRequest, |
| 603 | ) { |
| 604 | if (!isSupportedLinkProviderKind(request)) { |
| 605 | return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" }); |
| 606 | } |
| 607 | const origin = yield* serverLoopbackOrigin; |
| 608 | const now = yield* DateTime.now; |
| 609 | const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); |
| 610 | // Borrow only the relay clock; the relay still verifies and consumes the challenge. |
| 611 | const issuedAt = yield* decodeRelayJwt(request.challenge).pipe( |
| 612 | Effect.map(({ iat }) => |
| 613 | typeof iat === "number" && Number.isSafeInteger(iat) && iat > 0 ? iat : nowSeconds, |
| 614 | ), |
| 615 | Effect.orElseSucceed(() => nowSeconds), |
| 616 | ); |
| 617 | const descriptor = yield* environment.getDescriptor; |
| 618 | const payload = { |
| 619 | iss: `t3-env:${descriptor.environmentId}`, |
| 620 | aud: normalizeRelayIssuer(request.relayIssuer), |
| 621 | sub: descriptor.environmentId, |
| 622 | jti: yield* random.uuidV4(), |
| 623 | iat: issuedAt, |
| 624 | exp: issuedAt + 5 * 60, |
| 625 | challenge: request.challenge, |
| 626 | descriptor, |
| 627 | environmentId: descriptor.environmentId, |
| 628 | environmentPublicKey: normalizePemForSignedPayload(signingKey.publicKey), |
| 629 | endpoint: request.endpoint, |
| 630 | origin, |
| 631 | scopes: linkProofScopes(request), |
| 632 | } satisfies RelayEnvironmentLinkProofPayload; |
| 633 | return yield* signingKey |
| 634 | .sign({ |
| 635 | typ: RELAY_LINK_PROOF_TYP, |
| 636 | payload, |
| 637 | }) |
| 638 | .pipe( |
| 639 | Effect.mapError( |
| 640 | (cause) => |
| 641 | new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ |
| 642 | cause, |
| 643 | }), |
| 644 | ), |
| 645 | ); |
| 646 | }); |
| 647 | |
| 648 | const linkProof = Effect.fn("environment.cloud.linkProof")( |
| 649 | function* (request: RelayLinkProofRequest) { |
| 650 | return yield* makeCloudLinkProof(request); |
| 651 | }, |
| 652 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")), |
| 653 | ); |
| 654 | |
| 655 | const activateManagedTunnel = Effect.fn("environment.cloud.activateManagedTunnel")( |
| 656 | function* (input: { |
| 657 | readonly config: RelayManagedEndpointRuntimeConfig; |
| 658 | readonly configJson: string; |
| 659 | readonly origin: RelayManagedEndpointOrigin; |
| 660 | }) { |
| 661 | return yield* endpointRuntime.withLinkStateLock( |
| 662 | Effect.gen(function* () { |
| 663 | const currentConfig = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 664 | if ( |
| 665 | Option.isNone(currentConfig) || |
| 666 | bytesToString(currentConfig.value) !== input.configJson |
| 667 | ) { |
| 668 | return null; |
| 669 | } |
| 670 | const status = yield* endpointRuntime.applyConfig(input.config); |
| 671 | if (status.status !== "running") { |
| 672 | return yield* new CloudLinkEndpointUnavailableError({ |
| 673 | reason: "runtime-not-started", |
| 674 | endpointRuntimeStatus: status, |
| 675 | }); |
| 676 | } |
| 677 | const marker = yield* encodeConfirmedOriginJson({ |
| 678 | config: input.config, |
| 679 | origin: input.origin, |
| 680 | }); |
| 681 | yield* secrets.set(CLOUD_ENDPOINT_CONFIRMED_ORIGIN, stringToBytes(marker)); |
| 682 | return status; |
| 683 | }), |
| 684 | ); |
| 685 | }, |
| 686 | ); |
| 687 | |
| 688 | const activateManagedTunnelWithRetry = ( |
| 689 | input: { |
| 690 | readonly config: RelayManagedEndpointRuntimeConfig; |
| 691 | readonly configJson: string; |
| 692 | readonly origin: RelayManagedEndpointOrigin; |
| 693 | }, |
| 694 | retryRuntimeFailures: boolean, |
| 695 | ) => { |
| 696 | const activate = activateManagedTunnel(input); |
| 697 | return retryRuntimeFailures |
| 698 | ? activate.pipe( |
| 699 | Effect.retry({ |
| 700 | while: (error) => |
| 701 | error._tag === "CloudLinkEndpointUnavailableError" && |
| 702 | ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus( |
| 703 | error.endpointRuntimeStatus, |
| 704 | ), |
| 705 | schedule: Schedule.exponential("1 second").pipe( |
| 706 | Schedule.modifyDelay(({ duration }) => |
| 707 | Effect.succeed(Duration.min(duration, Duration.seconds(30))), |
| 708 | ), |
| 709 | Schedule.jittered, |
| 710 | ), |
| 711 | }), |
| 712 | ) |
| 713 | : activate; |
| 714 | }; |
| 715 | |
| 716 | const startManagedTunnelIfOriginConfirmed = Effect.fn( |
| 717 | "environment.cloud.startManagedCloudTunnelIfOriginConfirmed", |
| 718 | )(function* (localOrigin: string, options?: { readonly requireConfirmedOrigin?: boolean }) { |
| 719 | const requireConfirmedOrigin = options?.requireConfirmedOrigin ?? true; |
| 720 | const parsedOrigin = yield* Effect.try({ |
| 721 | try: () => parseManagedEndpointLocalOrigin(localOrigin), |
| 722 | catch: () => new CloudLinkOriginInvalidError({ origin: "local" }), |
| 723 | }); |
| 724 | return yield* endpointRuntime.withLinkStateLock( |
| 725 | Effect.gen(function* () { |
| 726 | const [runtimeBytes, markerBytes] = yield* Effect.all([ |
| 727 | secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG), |
| 728 | secrets.get(CLOUD_ENDPOINT_CONFIRMED_ORIGIN), |
| 729 | ]); |
| 730 | if (Option.isNone(runtimeBytes)) return false; |
| 731 | const config = Option.getOrNull(decodeRuntimeConfig(bytesToString(runtimeBytes.value))); |
| 732 | if (config === null || config.providerKind !== "cloudflare_tunnel") return false; |
| 733 | // Require the relay-confirmed port unless falling back after the relay stayed unreachable. |
| 734 | if (requireConfirmedOrigin) { |
| 735 | if (Option.isNone(markerBytes)) return false; |
| 736 | const marker = Option.getOrNull(decodeConfirmedOrigin(bytesToString(markerBytes.value))); |
| 737 | if ( |
| 738 | marker === null || |
| 739 | !managedEndpointRuntimeConfigsMatch(marker.config, config) || |
| 740 | marker.origin.localHttpHost !== parsedOrigin.origin.localHttpHost || |
| 741 | marker.origin.localHttpPort !== parsedOrigin.origin.localHttpPort |
| 742 | ) { |
| 743 | return false; |
| 744 | } |
| 745 | } |
| 746 | const status = yield* endpointRuntime.applyConfig(config); |
| 747 | if (status.status !== "running") { |
| 748 | return yield* new CloudLinkEndpointUnavailableError({ |
| 749 | reason: "runtime-not-started", |
| 750 | endpointRuntimeStatus: status, |
| 751 | }); |
| 752 | } |
| 753 | return true; |
| 754 | }), |
| 755 | ); |
| 756 | }); |
| 757 | |
| 758 | const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* ( |
| 759 | payload: RelayEnvironmentConfigRequest, |
| 760 | options?: { |
| 761 | readonly lockHeld?: boolean; |
| 762 | readonly confirmedOrigin?: RelayManagedEndpointOrigin; |
| 763 | readonly replaceRevokedLink?: boolean; |
| 764 | }, |
| 765 | ) { |
| 766 | const apply = Effect.gen(function* () { |
| 767 | yield* validateRelayConfigPayload(payload); |
| 768 | yield* validateCloudMintPublicKey(payload.cloudMintPublicKey); |
| 769 | // Reject unsupported runtimes before they can stop a healthy tunnel. |
| 770 | if ( |
| 771 | payload.endpointRuntime !== null && |
| 772 | payload.endpointRuntime.providerKind !== "cloudflare_tunnel" |
| 773 | ) { |
| 774 | return yield* new CloudLinkEndpointUnavailableError({ |
| 775 | reason: "runtime-not-started", |
| 776 | endpointRuntimeStatus: { |
| 777 | status: "unsupported", |
| 778 | providerKind: payload.endpointRuntime.providerKind, |
| 779 | }, |
| 780 | }); |
| 781 | } |
| 782 | // Only an explicit link replaces a revoked one: a clock-skew 401 can mark a live link revoked. |
| 783 | if (options?.replaceRevokedLink === true) { |
| 784 | const [revoked, previousUserId] = yield* Effect.all([ |
| 785 | secrets.get(CLOUD_LINK_REVOKED), |
| 786 | secrets.get(CLOUD_LINKED_USER_ID), |
| 787 | ]); |
| 788 | // The CLI token may belong to the old account. Release it before the drop so a failed |
| 789 | // write leaves the revoked mark for a retry; a partial drop can leave no user id. |
| 790 | if ( |
| 791 | Option.isSome(revoked) && |
| 792 | Option.match(previousUserId, { |
| 793 | onNone: () => true, |
| 794 | onSome: (userId) => bytesToString(userId) !== payload.cloudUserId, |
| 795 | }) |
| 796 | ) { |
| 797 | yield* setCliDesiredCloudLink(false).pipe(withSecrets); |
| 798 | } |
| 799 | yield* dropRevokedCloudLink.pipe(withSecrets); |
| 800 | } |
| 801 | yield* validateLinkedCloudUser(payload.cloudUserId); |
| 802 | const endpointRuntimeJson = payload.endpointRuntime |
| 803 | ? yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime) |
| 804 | : null; |
| 805 | yield* endpointRuntime.applyConfig(null); |
| 806 | yield* secrets.remove(CLOUD_ENDPOINT_CONFIRMED_ORIGIN); |
| 807 | // Store runtime config last so partial writes cannot appear managed or respawn a stale tunnel. |
| 808 | yield* secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 809 | |
| 810 | yield* secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl)); |
| 811 | yield* secrets.set( |
| 812 | RELAY_ISSUER_SECRET, |
| 813 | stringToBytes(payload.relayIssuer ?? payload.relayUrl), |
| 814 | ); |
| 815 | yield* secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId)); |
| 816 | yield* secrets.set( |
| 817 | RELAY_ENVIRONMENT_CREDENTIAL_SECRET, |
| 818 | stringToBytes(payload.environmentCredential), |
| 819 | ); |
| 820 | yield* secrets.remove(CLOUD_LINK_REVOKED); |
| 821 | yield* secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey)); |
| 822 | yield* awarenessRelay.requestCatchUp(); |
| 823 | if (endpointRuntimeJson !== null) { |
| 824 | yield* secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(endpointRuntimeJson)); |
| 825 | } |
| 826 | if (payload.endpointRuntime === null || options?.confirmedOrigin === undefined) { |
| 827 | return { |
| 828 | ok: true, |
| 829 | endpointRuntimeStatus: { status: "disabled" }, |
| 830 | } satisfies EnvironmentCloudRelayConfigResult; |
| 831 | } |
| 832 | const endpointRuntimeStatus = yield* endpointRuntime.applyConfig(payload.endpointRuntime); |
| 833 | if (endpointRuntimeStatus.status !== "running") { |
| 834 | return yield* new CloudLinkEndpointUnavailableError({ |
| 835 | reason: "runtime-not-started", |
| 836 | endpointRuntimeStatus, |
| 837 | }); |
| 838 | } |
| 839 | const marker = yield* encodeConfirmedOriginJson({ |
| 840 | config: payload.endpointRuntime, |
| 841 | origin: options.confirmedOrigin, |
| 842 | }); |
| 843 | yield* secrets.set(CLOUD_ENDPOINT_CONFIRMED_ORIGIN, stringToBytes(marker)); |
| 844 | return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult; |
| 845 | }); |
| 846 | return yield* options?.lockHeld ? apply : endpointRuntime.withLinkStateLock(apply); |
| 847 | }); |
| 848 | |
| 849 | const relayClientRequest = <A>(input: { |
| 850 | readonly url: string; |
| 851 | readonly token: string; |
| 852 | readonly payload: unknown; |
| 853 | readonly schema: Schema.Decoder<A>; |
| 854 | readonly timeout?: Duration.Input; |
| 855 | }) => |
| 856 | HttpClientRequest.post(input.url).pipe( |
| 857 | HttpClientRequest.bearerToken(input.token), |
| 858 | HttpClientRequest.bodyJson(input.payload), |
| 859 | Effect.flatMap(httpClient.execute), |
| 860 | Effect.flatMap(filterRelayResponse), |
| 861 | Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)), |
| 862 | Effect.timeout(input.timeout ?? "10 seconds"), |
| 863 | Effect.mapError(relayRequestError), |
| 864 | withRelayClientTracing, |
| 865 | ); |
| 866 | |
| 867 | const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")( |
| 868 | function* (localOrigin: string) { |
| 869 | const parsedOrigin = yield* Effect.try({ |
| 870 | try: () => parseManagedEndpointLocalOrigin(localOrigin), |
| 871 | catch: () => new CloudLinkOriginInvalidError({ origin: "local" }), |
| 872 | }); |
| 873 | const token = yield* cliTokenManager.getExisting.pipe( |
| 874 | Effect.flatMap( |
| 875 | Option.match({ |
| 876 | onNone: () => Effect.fail(new CloudLinkAuthorizationMissingError({})), |
| 877 | onSome: Effect.succeed, |
| 878 | }), |
| 879 | ), |
| 880 | ); |
| 881 | const mode = yield* readCliDesiredLinkMode.pipe(withSecrets); |
| 882 | const managedTunnelsEnabled = mode !== "publish_only"; |
| 883 | const relayUrl = yield* requireRelayUrl; |
| 884 | const challenge = yield* relayClientRequest({ |
| 885 | url: `${relayUrl}/v1/client/environment-link-challenges`, |
| 886 | token: token.accessToken, |
| 887 | payload: { |
| 888 | notificationsEnabled: true, |
| 889 | liveActivitiesEnabled: true, |
| 890 | managedTunnelsEnabled, |
| 891 | }, |
| 892 | schema: RelayEnvironmentLinkChallengeResponse, |
| 893 | }); |
| 894 | const proof = yield* makeCloudLinkProof({ |
| 895 | challenge: challenge.challenge, |
| 896 | relayIssuer: relayUrl, |
| 897 | endpoint: { |
| 898 | httpBaseUrl: parsedOrigin.httpBaseUrl, |
| 899 | wsBaseUrl: parsedOrigin.wsBaseUrl, |
| 900 | providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual", |
| 901 | }, |
| 902 | origin: parsedOrigin.origin, |
| 903 | }); |
| 904 | const link = yield* relayClientRequest({ |
| 905 | url: `${relayUrl}/v1/client/environment-links`, |
| 906 | token: token.accessToken, |
| 907 | payload: { |
| 908 | proof, |
| 909 | notificationsEnabled: true, |
| 910 | liveActivitiesEnabled: true, |
| 911 | managedTunnelsEnabled, |
| 912 | }, |
| 913 | schema: RelayEnvironmentLinkResponse, |
| 914 | timeout: MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT, |
| 915 | }); |
| 916 | yield* setCliDesiredCloudLink(true, mode).pipe(withSecrets); |
| 917 | yield* applyCloudRelayConfig( |
| 918 | { |
| 919 | relayUrl, |
| 920 | relayIssuer: link.relayIssuer, |
| 921 | cloudUserId: link.cloudUserId, |
| 922 | environmentCredential: link.environmentCredential, |
| 923 | cloudMintPublicKey: link.cloudMintPublicKey, |
| 924 | endpointRuntime: link.endpointRuntime, |
| 925 | }, |
| 926 | { |
| 927 | lockHeld: true, |
| 928 | confirmedOrigin: parsedOrigin.origin, |
| 929 | }, |
| 930 | ); |
| 931 | return mode; |
| 932 | }, |
| 933 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("persist-desired-link")), |
| 934 | ); |
| 935 | |
| 936 | const reconcileDesiredLinkIfStillDesired = Effect.fn( |
| 937 | "environment.cloud.reconcileDesiredLinkIfStillDesired", |
| 938 | )(function* (localOrigin: string) { |
| 939 | return yield* endpointRuntime.withLinkStateLock( |
| 940 | Effect.gen(function* () { |
| 941 | if (!(yield* readCliDesiredCloudLink.pipe(withSecrets))) { |
| 942 | return null; |
| 943 | } |
| 944 | return yield* reconcileDesiredCloudLinkWith(localOrigin); |
| 945 | }), |
| 946 | ); |
| 947 | }); |
| 948 | |
| 949 | const makeManagedTunnelRecoveryProof = Effect.fn( |
| 950 | "environment.cloud.makeManagedTunnelRecoveryProof", |
| 951 | )(function* (input: ManagedTunnelRecoveryProofInput) { |
| 952 | const configuredIssuer = yield* secrets.get(RELAY_ISSUER_SECRET); |
| 953 | const now = yield* DateTime.now; |
| 954 | const issuedAt = Math.floor(now.epochMilliseconds / 1_000); |
| 955 | const claims = { |
| 956 | iss: `t3-env:${input.environmentId}`, |
| 957 | aud: normalizeRelayIssuer( |
| 958 | Option.isSome(configuredIssuer) ? bytesToString(configuredIssuer.value) : input.relayUrl, |
| 959 | ), |
| 960 | sub: input.environmentId, |
| 961 | jti: yield* random.uuidV4(), |
| 962 | iat: issuedAt, |
| 963 | exp: issuedAt + 60, |
| 964 | environmentId: input.environmentId, |
| 965 | cloudUserId: input.cloudUserId, |
| 966 | }; |
| 967 | const payload = |
| 968 | input.action === "register" |
| 969 | ? { |
| 970 | ...claims, |
| 971 | action: "register" as const, |
| 972 | tunnelId: input.tunnelId, |
| 973 | origin: input.origin, |
| 974 | } |
| 975 | : { ...claims, action: "recover" as const, origin: input.origin }; |
| 976 | |
| 977 | return yield* signingKey |
| 978 | .sign({ |
| 979 | typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP, |
| 980 | payload, |
| 981 | }) |
| 982 | .pipe( |
| 983 | Effect.mapError( |
| 984 | (cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }), |
| 985 | ), |
| 986 | ); |
| 987 | }); |
| 988 | |
| 989 | /** Keep credentials: clock skew can cause 401s. A relink during the request returns false without marking; accepted registration clears the mark. */ |
| 990 | const markLinkRevoked = (credential: string, cause: RelayRequestError) => |
| 991 | endpointRuntime.withLinkStateLock( |
| 992 | Effect.gen(function* () { |
| 993 | const current = yield* secrets.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET); |
| 994 | if (Option.isNone(current) || bytesToString(current.value) !== credential) { |
| 995 | return false; |
| 996 | } |
| 997 | yield* Effect.logWarning( |
| 998 | "T3 Connect no longer accepts this environment's link. Link it again to restore remote access.", |
| 999 | { cause }, |
| 1000 | ); |
| 1001 | yield* secrets.set(CLOUD_LINK_REVOKED, stringToBytes("true")); |
| 1002 | return true; |
| 1003 | }), |
| 1004 | ); |
| 1005 | |
| 1006 | const registerManagedTunnelRecovery = Effect.fn( |
| 1007 | "environment.cloud.registerManagedCloudTunnelRecovery", |
| 1008 | )(function* (localOrigin: string, options?: { readonly retryRuntimeFailures?: boolean }) { |
| 1009 | const [runtimeConfig, relayUrl, cloudUserId, environmentCredential] = yield* Effect.all([ |
| 1010 | secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG), |
| 1011 | secrets.get(RELAY_URL_SECRET), |
| 1012 | secrets.get(CLOUD_LINKED_USER_ID), |
| 1013 | secrets.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET), |
| 1014 | ]); |
| 1015 | if ( |
| 1016 | Option.isNone(runtimeConfig) || |
| 1017 | Option.isNone(relayUrl) || |
| 1018 | Option.isNone(cloudUserId) || |
| 1019 | Option.isNone(environmentCredential) |
| 1020 | ) { |
| 1021 | return { status: "not_linked" as const }; |
| 1022 | } |
| 1023 | |
| 1024 | const config = Option.getOrNull(decodeRuntimeConfig(bytesToString(runtimeConfig.value))); |
| 1025 | if (config?.providerKind !== "cloudflare_tunnel") { |
| 1026 | return { status: "not_linked" as const }; |
| 1027 | } |
| 1028 | |
| 1029 | const parsedOrigin = yield* Effect.try({ |
| 1030 | try: () => parseManagedEndpointLocalOrigin(localOrigin), |
| 1031 | catch: () => new CloudLinkOriginInvalidError({ origin: "local" }), |
| 1032 | }); |
| 1033 | if (config.tunnelId === undefined) { |
| 1034 | return { status: "recovery_required" as const, config }; |
| 1035 | } |
| 1036 | const origin = parsedOrigin.origin; |
| 1037 | const environmentId = yield* environment.getEnvironmentId; |
| 1038 | const relayUrlValue = bytesToString(relayUrl.value); |
| 1039 | const cloudUserIdValue = bytesToString(cloudUserId.value); |
| 1040 | const proof = yield* makeManagedTunnelRecoveryProof({ |
| 1041 | action: "register", |
| 1042 | environmentId, |
| 1043 | cloudUserId: cloudUserIdValue, |
| 1044 | relayUrl: relayUrlValue, |
| 1045 | tunnelId: config.tunnelId, |
| 1046 | origin, |
| 1047 | }); |
| 1048 | const credential = bytesToString(environmentCredential.value); |
| 1049 | const registered = yield* relayClientRequest({ |
| 1050 | url: `${relayUrlValue}/v1/environments/${encodeURIComponent(environmentId)}/tunnel/recovery`, |
| 1051 | token: credential, |
| 1052 | payload: { |
| 1053 | cloudUserId: cloudUserIdValue, |
| 1054 | tunnelId: config.tunnelId, |
| 1055 | origin, |
| 1056 | proof, |
| 1057 | }, |
| 1058 | schema: RelayManagedEndpointRecoveryRegistrationResponse, |
| 1059 | }).pipe( |
| 1060 | Effect.catchTags({ |
| 1061 | RelayRequestError: (error) => |
| 1062 | error.rejection === "unauthorized" |
| 1063 | ? markLinkRevoked(credential, error).pipe( |
| 1064 | Effect.map((marked) => (marked ? ("revoked" as const) : ("superseded" as const))), |
| 1065 | ) |
| 1066 | : Effect.fail(error), |
| 1067 | }), |
| 1068 | ); |
| 1069 | if (registered === "revoked" || registered === "superseded") { |
| 1070 | return { status: registered }; |
| 1071 | } |
| 1072 | yield* secrets.remove(CLOUD_LINK_REVOKED); |
| 1073 | if (registered.status === "recovery_required") { |
| 1074 | return { status: registered.status, config }; |
| 1075 | } |
| 1076 | const endpointRuntimeStatus = yield* activateManagedTunnelWithRetry( |
| 1077 | { |
| 1078 | config, |
| 1079 | configJson: bytesToString(runtimeConfig.value), |
| 1080 | origin, |
| 1081 | }, |
| 1082 | options?.retryRuntimeFailures === true, |
| 1083 | ); |
| 1084 | return endpointRuntimeStatus === null |
| 1085 | ? { status: "superseded" as const } |
| 1086 | : { status: "ready" as const, endpointRuntimeStatus }; |
| 1087 | }); |
| 1088 | |
| 1089 | const recoverManagedTunnel = Effect.fn("environment.cloud.recoverManagedCloudTunnel")(function* ( |
| 1090 | localOrigin: string, |
| 1091 | expectedConfig?: RelayManagedEndpointRuntimeConfig, |
| 1092 | options?: { readonly retryRuntimeFailures?: boolean }, |
| 1093 | ) { |
| 1094 | const [runtimeConfig, relayUrl, cloudUserId, environmentCredential] = yield* Effect.all([ |
| 1095 | secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG), |
| 1096 | secrets.get(RELAY_URL_SECRET), |
| 1097 | secrets.get(CLOUD_LINKED_USER_ID), |
| 1098 | secrets.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET), |
| 1099 | ]); |
| 1100 | if ( |
| 1101 | Option.isNone(runtimeConfig) || |
| 1102 | Option.isNone(relayUrl) || |
| 1103 | Option.isNone(cloudUserId) || |
| 1104 | Option.isNone(environmentCredential) |
| 1105 | ) { |
| 1106 | return false; |
| 1107 | } |
| 1108 | if (expectedConfig !== undefined) { |
| 1109 | const current = Option.getOrNull(decodeRuntimeConfig(bytesToString(runtimeConfig.value))); |
| 1110 | if ( |
| 1111 | current === null || |
| 1112 | current.providerKind !== expectedConfig.providerKind || |
| 1113 | current.connectorToken !== expectedConfig.connectorToken || |
| 1114 | current.tunnelId !== expectedConfig.tunnelId || |
| 1115 | current.tunnelName !== expectedConfig.tunnelName |
| 1116 | ) { |
| 1117 | return false; |
| 1118 | } |
| 1119 | } |
| 1120 | |
| 1121 | const parsedOrigin = yield* Effect.try({ |
| 1122 | try: () => parseManagedEndpointLocalOrigin(localOrigin), |
| 1123 | catch: () => new CloudLinkOriginInvalidError({ origin: "local" }), |
| 1124 | }); |
| 1125 | |
| 1126 | const environmentId = yield* environment.getEnvironmentId; |
| 1127 | const relayUrlValue = bytesToString(relayUrl.value); |
| 1128 | const cloudUserIdValue = bytesToString(cloudUserId.value); |
| 1129 | const origin = parsedOrigin.origin; |
| 1130 | const proof = yield* makeManagedTunnelRecoveryProof({ |
| 1131 | action: "recover", |
| 1132 | environmentId, |
| 1133 | cloudUserId: cloudUserIdValue, |
| 1134 | relayUrl: relayUrlValue, |
| 1135 | origin, |
| 1136 | }); |
| 1137 | const credential = bytesToString(environmentCredential.value); |
| 1138 | const recovered = yield* relayClientRequest({ |
| 1139 | url: `${relayUrlValue}/v1/environments/${encodeURIComponent(environmentId)}/tunnel`, |
| 1140 | token: credential, |
| 1141 | payload: { |
| 1142 | cloudUserId: cloudUserIdValue, |
| 1143 | origin, |
| 1144 | proof, |
| 1145 | }, |
| 1146 | schema: RelayManagedEndpointRecoveryResponse, |
| 1147 | timeout: MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT, |
| 1148 | }).pipe( |
| 1149 | Effect.tapError((error) => |
| 1150 | error.rejection === "unauthorized" ? markLinkRevoked(credential, error) : Effect.void, |
| 1151 | ), |
| 1152 | ); |
| 1153 | if (recovered.endpointRuntime.providerKind !== "cloudflare_tunnel") { |
| 1154 | return yield* new CloudLinkInternalError({ operation: "unsupported-recovered-tunnel" }); |
| 1155 | } |
| 1156 | |
| 1157 | const encoded = yield* encodeEndpointRuntimeConfigJson(recovered.endpointRuntime).pipe( |
| 1158 | Effect.mapError( |
| 1159 | (cause) => new CloudLinkInternalError({ operation: "persist-recovered-tunnel", cause }), |
| 1160 | ), |
| 1161 | ); |
| 1162 | const stored = yield* endpointRuntime.withLinkStateLock( |
| 1163 | Effect.gen(function* () { |
| 1164 | const currentConfig = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 1165 | if ( |
| 1166 | Option.isNone(currentConfig) || |
| 1167 | bytesToString(currentConfig.value) !== bytesToString(runtimeConfig.value) |
| 1168 | ) { |
| 1169 | return false; |
| 1170 | } |
| 1171 | yield* secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(encoded)); |
| 1172 | yield* secrets.remove(CLOUD_ENDPOINT_CONFIRMED_ORIGIN); |
| 1173 | yield* secrets.remove(CLOUD_LINK_REVOKED); |
| 1174 | return true; |
| 1175 | }), |
| 1176 | ); |
| 1177 | if (!stored) return false; |
| 1178 | const status = yield* activateManagedTunnelWithRetry( |
| 1179 | { |
| 1180 | config: recovered.endpointRuntime, |
| 1181 | configJson: encoded, |
| 1182 | origin, |
| 1183 | }, |
| 1184 | options?.retryRuntimeFailures === true, |
| 1185 | ); |
| 1186 | return status !== null; |
| 1187 | }); |
| 1188 | |
| 1189 | const applyRelayConfig = Effect.fn("environment.cloud.relayConfig")( |
| 1190 | function* (payload: RelayEnvironmentConfigRequest) { |
| 1191 | const result = yield* applyCloudRelayConfig(payload, { replaceRevokedLink: true }); |
| 1192 | if (payload.endpointRuntime?.providerKind === "cloudflare_tunnel") { |
| 1193 | const address = httpServer.address; |
| 1194 | if (typeof address === "string" || !("port" in address)) { |
| 1195 | return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" }); |
| 1196 | } |
| 1197 | const registration = yield* registerManagedTunnelRecovery( |
| 1198 | `http://${loopbackUrlHostForAddress(address)}:${address.port}`, |
| 1199 | ).pipe( |
| 1200 | Effect.retry({ |
| 1201 | times: 2, |
| 1202 | while: (error) => |
| 1203 | shouldRetryCloudLink(error) && error._tag !== "CloudLinkEndpointUnavailableError", |
| 1204 | }), |
| 1205 | ); |
| 1206 | if (registration.status === "superseded") { |
| 1207 | return yield* new CloudLinkTunnelSupersededError({}); |
| 1208 | } |
| 1209 | if (registration.status === "recovery_required") { |
| 1210 | yield* endpointRuntime.requestRecovery(registration.config); |
| 1211 | } |
| 1212 | if (registration.status !== "ready") { |
| 1213 | return yield* new CloudLinkEndpointUnavailableError({ |
| 1214 | reason: "origin-unconfirmed", |
| 1215 | endpointRuntimeStatus: { status: "disabled" }, |
| 1216 | }); |
| 1217 | } |
| 1218 | return { |
| 1219 | ok: true, |
| 1220 | endpointRuntimeStatus: registration.endpointRuntimeStatus, |
| 1221 | } satisfies EnvironmentCloudRelayConfigResult; |
| 1222 | } |
| 1223 | return result; |
| 1224 | }, |
| 1225 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("persist-relay-config")), |
| 1226 | Effect.catchTags({ |
| 1227 | SchemaError: internalError("persist-relay-config"), |
| 1228 | }), |
| 1229 | ); |
| 1230 | |
| 1231 | // Cloudflare bills provisioned tunnels even while environments are offline. |
| 1232 | const releaseManagedTunnelOnShutdown = Effect.fn( |
| 1233 | "environment.cloud.releaseManagedTunnelOnShutdown", |
| 1234 | )(function* () { |
| 1235 | const runtimeConfig = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 1236 | if (Option.isNone(runtimeConfig)) { |
| 1237 | return false; |
| 1238 | } |
| 1239 | // CLI authorization releases only CLI-desired managed links; web/mobile links recover by credential and expire through the relay reaper. |
| 1240 | if ( |
| 1241 | !(yield* readCliDesiredCloudLink.pipe(withSecrets)) || |
| 1242 | (yield* readCliDesiredLinkMode.pipe(withSecrets)) !== "managed" |
| 1243 | ) { |
| 1244 | return false; |
| 1245 | } |
| 1246 | // Update handoffs reuse the tunnel: replacing it adds 1-2 minutes of hostname propagation. |
| 1247 | if ( |
| 1248 | (yield* withRuntimeFiles(desktopUpdateRestartPending)) || |
| 1249 | (yield* withRuntimeFiles(pendingUpdateHandoffExists)) |
| 1250 | ) { |
| 1251 | yield* Effect.logInfo("Keeping the managed tunnel across the update restart"); |
| 1252 | return false; |
| 1253 | } |
| 1254 | const relayUrl = yield* requireRelayUrl.pipe(Effect.option); |
| 1255 | const installedRelayUrl = yield* secrets.get(RELAY_URL_SECRET); |
| 1256 | if ( |
| 1257 | Option.isNone(relayUrl) || |
| 1258 | Option.isNone(installedRelayUrl) || |
| 1259 | normalizeSecureRelayUrl(bytesToString(installedRelayUrl.value)) !== relayUrl.value |
| 1260 | ) { |
| 1261 | return false; |
| 1262 | } |
| 1263 | const token = yield* cliTokenManager.getExisting; |
| 1264 | if (Option.isNone(token)) { |
| 1265 | return false; |
| 1266 | } |
| 1267 | const environmentId = yield* environment.getEnvironmentId; |
| 1268 | yield* endpointRuntime.applyConfig(null); |
| 1269 | const response = yield* HttpClientRequest.delete( |
| 1270 | `${relayUrl.value}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`, |
| 1271 | ).pipe( |
| 1272 | HttpClientRequest.bearerToken(token.value.accessToken), |
| 1273 | httpClient.execute, |
| 1274 | Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), |
| 1275 | Effect.flatMap(filterRelayResponse), |
| 1276 | Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)), |
| 1277 | withRelayClientTracing, |
| 1278 | ); |
| 1279 | // ok:false means concurrent provisioning owns the tunnel; preserve its config. |
| 1280 | if (!response.ok) { |
| 1281 | return false; |
| 1282 | } |
| 1283 | // Released tokens are dead; remove only this shutdown's config to preserve a fast restart's replacement. |
| 1284 | const storedConfig = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 1285 | if ( |
| 1286 | Option.isSome(storedConfig) && |
| 1287 | bytesToString(storedConfig.value) === bytesToString(runtimeConfig.value) |
| 1288 | ) { |
| 1289 | yield* secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG); |
| 1290 | yield* secrets.remove(CLOUD_ENDPOINT_CONFIRMED_ORIGIN); |
| 1291 | } |
| 1292 | return true; |
| 1293 | }); |
| 1294 | |
| 1295 | const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* () { |
| 1296 | const [ |
| 1297 | cloudUserId, |
| 1298 | relayUrl, |
| 1299 | relayIssuer, |
| 1300 | endpointRuntimeConfig, |
| 1301 | publishAgentActivity, |
| 1302 | holdWebhooks, |
| 1303 | revoked, |
| 1304 | latestReachability, |
| 1305 | ] = yield* Effect.all( |
| 1306 | [ |
| 1307 | secrets.get(CLOUD_LINKED_USER_ID), |
| 1308 | secrets.get(RELAY_URL_SECRET), |
| 1309 | secrets.get(RELAY_ISSUER_SECRET), |
| 1310 | secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG), |
| 1311 | secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET), |
| 1312 | secrets.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET), |
| 1313 | secrets.get(CLOUD_LINK_REVOKED), |
| 1314 | reachability.latest, |
| 1315 | ], |
| 1316 | { concurrency: 8 }, |
| 1317 | ); |
| 1318 | // The hostname arrives once cloudflared connects, before any check passes. |
| 1319 | const connector = Option.isSome(endpointRuntimeConfig) |
| 1320 | ? yield* endpointRuntime.inspectConnector |
| 1321 | : null; |
| 1322 | // A not-linked check predates the stored tunnel config; the next check replaces it. |
| 1323 | const currentReachability = Option.filter( |
| 1324 | latestReachability, |
| 1325 | (result) => |
| 1326 | Option.isNone(endpointRuntimeConfig) || |
| 1327 | !(result.status === "unreachable" && result.cause === "not_linked"), |
| 1328 | ); |
| 1329 | return { |
| 1330 | linked: Option.isSome(cloudUserId), |
| 1331 | linkRevoked: Option.isSome(cloudUserId) && Option.isSome(revoked), |
| 1332 | cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null, |
| 1333 | relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null, |
| 1334 | relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null, |
| 1335 | managedTunnelActive: Option.isSome(endpointRuntimeConfig), |
| 1336 | publishAgentActivity: Option.isSome(publishAgentActivity) |
| 1337 | ? bytesToString(publishAgentActivity.value) === "true" |
| 1338 | : false, |
| 1339 | holdWebhooksWhileOffline: |
| 1340 | Option.isSome(holdWebhooks) && bytesToString(holdWebhooks.value) === "true", |
| 1341 | ...(Option.isSome(currentReachability) ? { reachability: currentReachability.value } : {}), |
| 1342 | ...(connector?.hostname ? { tunnelHostname: connector.hostname } : {}), |
| 1343 | } satisfies EnvironmentCloudLinkStateResult; |
| 1344 | }); |
| 1345 | |
| 1346 | const linkState = Effect.fn("environment.cloud.linkState")( |
| 1347 | function* () { |
| 1348 | return yield* readCloudLinkState(); |
| 1349 | }, |
| 1350 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("read-relay-config")), |
| 1351 | ); |
| 1352 | |
| 1353 | const unlink = Effect.fn("environment.cloud.unlink")( |
| 1354 | function* () { |
| 1355 | return yield* endpointRuntime.withLinkStateLock( |
| 1356 | Effect.gen(function* () { |
| 1357 | const endpointRuntimeStatus = yield* endpointRuntime.applyConfig(null); |
| 1358 | yield* Effect.all( |
| 1359 | [ |
| 1360 | secrets.remove(CLOUD_LINKED_USER_ID), |
| 1361 | secrets.remove(RELAY_URL_SECRET), |
| 1362 | secrets.remove(RELAY_ISSUER_SECRET), |
| 1363 | secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET), |
| 1364 | secrets.remove(CLOUD_MINT_PUBLIC_KEY), |
| 1365 | secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG), |
| 1366 | secrets.remove(CLOUD_ENDPOINT_CONFIRMED_ORIGIN), |
| 1367 | secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET), |
| 1368 | secrets.remove(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET), |
| 1369 | secrets.remove(CLOUD_LINK_REVOKED), |
| 1370 | ], |
| 1371 | { concurrency: 10 }, |
| 1372 | ); |
| 1373 | yield* setCliDesiredCloudLink(false).pipe(withSecrets); |
| 1374 | return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult; |
| 1375 | }), |
| 1376 | ); |
| 1377 | }, |
| 1378 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("remove-relay-config")), |
| 1379 | ); |
| 1380 | |
| 1381 | const pushHoldWebhooksWhileOffline = Effect.fn("CloudPreferences.pushHoldWebhooksWhileOffline")( |
| 1382 | function* (holdWebhooksWhileOffline: boolean) { |
| 1383 | const connection = yield* readRelayConnection.pipe(withSecrets); |
| 1384 | if (connection === null) { |
| 1385 | return yield* new CloudLinkNotLinkedError({}); |
| 1386 | } |
| 1387 | const environmentId = yield* environment.getEnvironmentId; |
| 1388 | const client = yield* makeRelayEnvironmentClient(connection); |
| 1389 | yield* client.server |
| 1390 | .updateLinkPreferences({ |
| 1391 | params: { environmentId }, |
| 1392 | payload: { holdWebhooksWhileOffline }, |
| 1393 | }) |
| 1394 | .pipe(Effect.timeout("10 seconds"), Effect.catch(internalError("update-webhook-settings"))); |
| 1395 | }, |
| 1396 | ); |
| 1397 | |
| 1398 | const savePreference = (name: string, value: boolean) => |
| 1399 | secrets |
| 1400 | .set(name, stringToBytes(String(value))) |
| 1401 | .pipe(Effect.catch(internalError("persist-preferences"))); |
| 1402 | |
| 1403 | const preferencesLock = yield* Semaphore.make(1); |
| 1404 | |
| 1405 | const savePreferences = Effect.fn("CloudPreferences.update")( |
| 1406 | function* (input: EnvironmentCloudPreferencesRequest) { |
| 1407 | // Read rollback targets before changing anything; failed reads must abort. |
| 1408 | const readCurrent = (name: string) => |
| 1409 | secrets.get(name).pipe(Effect.catch(internalError("read-preferences"))); |
| 1410 | const previousActivity = yield* readCurrent(PUBLISH_AGENT_ACTIVITY_SECRET); |
| 1411 | const previousHold = yield* readCurrent(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET); |
| 1412 | yield* savePreference(PUBLISH_AGENT_ACTIVITY_SECRET, input.publishAgentActivity); |
| 1413 | if (input.holdWebhooksWhileOffline !== undefined) { |
| 1414 | const next = input.holdWebhooksWhileOffline; |
| 1415 | const previous = Option.match(previousHold, { |
| 1416 | onNone: () => false, |
| 1417 | onSome: (bytes) => bytesToString(bytes) === "true", |
| 1418 | }); |
| 1419 | yield* pushHoldWebhooksWhileOffline(next).pipe( |
| 1420 | Effect.andThen( |
| 1421 | savePreference(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, next).pipe( |
| 1422 | Effect.tapError(() => |
| 1423 | previous === next |
| 1424 | ? Effect.void |
| 1425 | : pushHoldWebhooksWhileOffline(previous).pipe(Effect.catch(rollbackFailed)), |
| 1426 | ), |
| 1427 | ), |
| 1428 | ), |
| 1429 | Effect.tapError(() => |
| 1430 | Option.match(previousActivity, { |
| 1431 | onNone: () => secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET), |
| 1432 | onSome: (bytes) => secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, bytes), |
| 1433 | }).pipe(Effect.catch(rollbackFailed)), |
| 1434 | ), |
| 1435 | ); |
| 1436 | } |
| 1437 | yield* awarenessRelay.requestCatchUp(); |
| 1438 | }, |
| 1439 | // Finish or roll back even if the client disconnects mid-update. |
| 1440 | Effect.uninterruptible, |
| 1441 | preferencesLock.withPermits(1), |
| 1442 | ); |
| 1443 | |
| 1444 | const updatePreferences = Effect.fn("environment.cloud.preferences")( |
| 1445 | function* (input: EnvironmentCloudPreferencesRequest) { |
| 1446 | yield* savePreferences(input); |
| 1447 | return yield* readCloudLinkState(); |
| 1448 | }, |
| 1449 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("read-preferences")), |
| 1450 | ); |
| 1451 | |
| 1452 | const updateLiveActivityPreference = Effect.fn("environment.cloud.updateLiveActivityPreference")( |
| 1453 | function* (liveActivitiesEnabled: boolean) { |
| 1454 | return yield* endpointRuntime.withLinkStateLock( |
| 1455 | Effect.gen(function* () { |
| 1456 | const connection = yield* readRelayConnection.pipe(withSecrets); |
| 1457 | const cloudUserId = yield* secrets.get(CLOUD_LINKED_USER_ID); |
| 1458 | const revoked = yield* secrets.get(CLOUD_LINK_REVOKED); |
| 1459 | if (connection === null || Option.isNone(cloudUserId) || Option.isSome(revoked)) { |
| 1460 | return { ok: false }; |
| 1461 | } |
| 1462 | const environmentId = yield* environment.getEnvironmentId; |
| 1463 | const client = yield* makeRelayEnvironmentClient(connection); |
| 1464 | return yield* client.server |
| 1465 | .updateLiveActivityPreference({ |
| 1466 | params: { environmentId }, |
| 1467 | payload: { cloudUserId: bytesToString(cloudUserId.value), liveActivitiesEnabled }, |
| 1468 | }) |
| 1469 | .pipe( |
| 1470 | Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), |
| 1471 | Effect.timeout("10 seconds"), |
| 1472 | Effect.catch(internalError("update-live-activity-preference")), |
| 1473 | ); |
| 1474 | }), |
| 1475 | ); |
| 1476 | }, |
| 1477 | Effect.catchIf( |
| 1478 | ServerSecretStore.isSecretStoreError, |
| 1479 | internalError("update-live-activity-preference"), |
| 1480 | ), |
| 1481 | ); |
| 1482 | |
| 1483 | const answerHealthRequest = Effect.fn("environment.cloud.health")( |
| 1484 | function* (request: RelayCloudEnvironmentHealthRequest) { |
| 1485 | const cloudMintPublicKey = yield* secrets |
| 1486 | .get(CLOUD_MINT_PUBLIC_KEY) |
| 1487 | .pipe( |
| 1488 | Effect.flatMap((bytes) => |
| 1489 | Option.isSome(bytes) |
| 1490 | ? Effect.succeed(bytesToString(bytes.value)) |
| 1491 | : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})), |
| 1492 | ), |
| 1493 | ); |
| 1494 | const relayIssuer = yield* secrets |
| 1495 | .get(RELAY_ISSUER_SECRET) |
| 1496 | .pipe( |
| 1497 | Effect.flatMap((bytes) => |
| 1498 | Option.isSome(bytes) |
| 1499 | ? Effect.succeed(bytesToString(bytes.value)) |
| 1500 | : secrets |
| 1501 | .get(RELAY_URL_SECRET) |
| 1502 | .pipe( |
| 1503 | Effect.flatMap((fallbackBytes) => |
| 1504 | Option.isSome(fallbackBytes) |
| 1505 | ? Effect.succeed(bytesToString(fallbackBytes.value)) |
| 1506 | : Effect.fail( |
| 1507 | new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}), |
| 1508 | ), |
| 1509 | ), |
| 1510 | ), |
| 1511 | ), |
| 1512 | ); |
| 1513 | const environmentId = yield* environment.getEnvironmentId; |
| 1514 | const linkedCloudUserId = yield* readInstalledCloudUserId; |
| 1515 | const now = yield* DateTime.now; |
| 1516 | const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); |
| 1517 | const proofOption = yield* verifyRelayJwt(RelayCloudEnvironmentHealthProofPayload, { |
| 1518 | publicKey: cloudMintPublicKey, |
| 1519 | token: request.proof, |
| 1520 | typ: RELAY_HEALTH_REQUEST_TYP, |
| 1521 | issuer: normalizeRelayIssuer(relayIssuer), |
| 1522 | audience: `t3-env:${environmentId}`, |
| 1523 | }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option); |
| 1524 | if ( |
| 1525 | Option.isNone(proofOption) || |
| 1526 | proofOption.value.environmentId !== environmentId || |
| 1527 | proofOption.value.sub !== linkedCloudUserId || |
| 1528 | !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) || |
| 1529 | !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" }) |
| 1530 | ) { |
| 1531 | return yield* new CloudLinkProofRejectedError({ request: "health" }); |
| 1532 | } |
| 1533 | const proof = proofOption.value; |
| 1534 | |
| 1535 | const jtiSecretName = yield* replayMarkerName(CLOUD_HEALTH_JTI_PREFIX, proof.jti); |
| 1536 | const nonceSecretName = yield* replayMarkerName(CLOUD_HEALTH_NONCE_PREFIX, proof.nonce); |
| 1537 | const consumedReplayGuards = yield* consumeCloudReplayGuards({ |
| 1538 | secrets, |
| 1539 | names: [jtiSecretName, nonceSecretName], |
| 1540 | value: stringToBytes(DateTime.formatIso(now)), |
| 1541 | }); |
| 1542 | if (!consumedReplayGuards) { |
| 1543 | return yield* new CloudLinkProofReplayedError({ request: "health" }); |
| 1544 | } |
| 1545 | |
| 1546 | const descriptor = yield* environment.getDescriptor; |
| 1547 | const responseExpiresAt = DateTime.add(now, { minutes: 5 }); |
| 1548 | const responsePayload = { |
| 1549 | iss: `t3-env:${environmentId}`, |
| 1550 | aud: normalizeRelayIssuer(relayIssuer), |
| 1551 | sub: environmentId, |
| 1552 | jti: yield* random.uuidV4(), |
| 1553 | iat: nowSeconds, |
| 1554 | exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000), |
| 1555 | environmentId, |
| 1556 | requestNonce: proof.nonce, |
| 1557 | status: "online", |
| 1558 | descriptor, |
| 1559 | checkedAt: DateTime.formatIso(now), |
| 1560 | } satisfies RelayEnvironmentHealthResponseProofPayload; |
| 1561 | const responseProof = yield* signingKey |
| 1562 | .sign({ |
| 1563 | typ: RELAY_HEALTH_RESPONSE_TYP, |
| 1564 | payload: responsePayload, |
| 1565 | }) |
| 1566 | .pipe( |
| 1567 | Effect.mapError( |
| 1568 | (cause) => |
| 1569 | new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ |
| 1570 | cause, |
| 1571 | }), |
| 1572 | ), |
| 1573 | ); |
| 1574 | return { |
| 1575 | environmentId, |
| 1576 | status: "online", |
| 1577 | descriptor, |
| 1578 | checkedAt: responsePayload.checkedAt, |
| 1579 | proof: responseProof, |
| 1580 | } satisfies RelayEnvironmentHealthResponse; |
| 1581 | }, |
| 1582 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("answer-health")), |
| 1583 | ); |
| 1584 | |
| 1585 | const mintCredential = Effect.fn("environment.cloud.mintCredential")( |
| 1586 | function* (request: RelayCloudMintCredentialRequest) { |
| 1587 | const cloudMintPublicKey = yield* secrets |
| 1588 | .get(CLOUD_MINT_PUBLIC_KEY) |
| 1589 | .pipe( |
| 1590 | Effect.flatMap((bytes) => |
| 1591 | Option.isSome(bytes) |
| 1592 | ? Effect.succeed(bytesToString(bytes.value)) |
| 1593 | : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})), |
| 1594 | ), |
| 1595 | ); |
| 1596 | const relayIssuer = yield* secrets |
| 1597 | .get(RELAY_ISSUER_SECRET) |
| 1598 | .pipe( |
| 1599 | Effect.flatMap((bytes) => |
| 1600 | Option.isSome(bytes) |
| 1601 | ? Effect.succeed(bytesToString(bytes.value)) |
| 1602 | : secrets |
| 1603 | .get(RELAY_URL_SECRET) |
| 1604 | .pipe( |
| 1605 | Effect.flatMap((fallbackBytes) => |
| 1606 | Option.isSome(fallbackBytes) |
| 1607 | ? Effect.succeed(bytesToString(fallbackBytes.value)) |
| 1608 | : Effect.fail( |
| 1609 | new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}), |
| 1610 | ), |
| 1611 | ), |
| 1612 | ), |
| 1613 | ), |
| 1614 | ); |
| 1615 | const environmentId = yield* environment.getEnvironmentId; |
| 1616 | const linkedCloudUserId = yield* readInstalledCloudUserId; |
| 1617 | const now = yield* DateTime.now; |
| 1618 | const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); |
| 1619 | const proofOption = yield* verifyRelayJwt(RelayCloudMintCredentialProofPayload, { |
| 1620 | publicKey: cloudMintPublicKey, |
| 1621 | token: request.proof, |
| 1622 | typ: RELAY_MINT_REQUEST_TYP, |
| 1623 | issuer: normalizeRelayIssuer(relayIssuer), |
| 1624 | audience: `t3-env:${environmentId}`, |
| 1625 | }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option); |
| 1626 | if ( |
| 1627 | Option.isNone(proofOption) || |
| 1628 | proofOption.value.environmentId !== environmentId || |
| 1629 | proofOption.value.sub !== linkedCloudUserId || |
| 1630 | proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint || |
| 1631 | !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) || |
| 1632 | !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" }) |
| 1633 | ) { |
| 1634 | return yield* new CloudLinkProofRejectedError({ request: "mint" }); |
| 1635 | } |
| 1636 | const proof = proofOption.value; |
| 1637 | |
| 1638 | const jtiSecretName = yield* replayMarkerName(CLOUD_MINT_JTI_PREFIX, proof.jti); |
| 1639 | const nonceSecretName = yield* replayMarkerName(CLOUD_MINT_NONCE_PREFIX, proof.nonce); |
| 1640 | const consumedReplayGuards = yield* consumeCloudReplayGuards({ |
| 1641 | secrets, |
| 1642 | names: [jtiSecretName, nonceSecretName], |
| 1643 | value: stringToBytes(DateTime.formatIso(now)), |
| 1644 | }); |
| 1645 | if (!consumedReplayGuards) { |
| 1646 | return yield* new CloudLinkProofReplayedError({ request: "mint" }); |
| 1647 | } |
| 1648 | |
| 1649 | const settings = yield* serverSettings.getSettings.pipe( |
| 1650 | Effect.catch(internalError("issue-credential")), |
| 1651 | ); |
| 1652 | const issued = yield* environmentAuth.issueConnectCredential({ |
| 1653 | proofKeyThumbprint: proof.clientProofKeyThumbprint, |
| 1654 | requireApproval: settings.requireConnectDeviceApproval, |
| 1655 | }); |
| 1656 | const responsePayload = { |
| 1657 | iss: `t3-env:${environmentId}`, |
| 1658 | aud: normalizeRelayIssuer(relayIssuer), |
| 1659 | sub: environmentId, |
| 1660 | jti: yield* random.uuidV4(), |
| 1661 | iat: nowSeconds, |
| 1662 | exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000), |
| 1663 | environmentId, |
| 1664 | clientProofKeyThumbprint: proof.clientProofKeyThumbprint, |
| 1665 | requestNonce: proof.nonce, |
| 1666 | credential: issued.credential, |
| 1667 | } satisfies RelayEnvironmentMintResponseProofPayload; |
| 1668 | const responseProof = yield* signingKey |
| 1669 | .sign({ |
| 1670 | typ: RELAY_MINT_RESPONSE_TYP, |
| 1671 | payload: responsePayload, |
| 1672 | }) |
| 1673 | .pipe( |
| 1674 | Effect.mapError( |
| 1675 | (cause) => |
| 1676 | new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ |
| 1677 | cause, |
| 1678 | }), |
| 1679 | ), |
| 1680 | ); |
| 1681 | return { |
| 1682 | credential: issued.credential, |
| 1683 | expiresAt: DateTime.formatIso(issued.expiresAt), |
| 1684 | proof: responseProof, |
| 1685 | } satisfies RelayEnvironmentMintResponse; |
| 1686 | }, |
| 1687 | Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("issue-credential")), |
| 1688 | ); |
| 1689 | |
| 1690 | if (!ManagedLimits.allowsConnect(managedPolicy)) { |
| 1691 | // Reading state and unlinking stay available so clients can show and leave the old link. |
| 1692 | yield* unlink().pipe( |
| 1693 | Effect.tap(() => Effect.logInfo("T3 Connect is off by managed policy; unlinked.")), |
| 1694 | Effect.catch((cause) => |
| 1695 | Effect.logWarning("Failed to unlink T3 Connect turned off by managed policy", { cause }), |
| 1696 | ), |
| 1697 | ); |
| 1698 | const refused = Effect.fn("CloudLink.refusedByPolicy")(function* () { |
| 1699 | return yield* ManagedLimits.refuseConnect(managedPolicy); |
| 1700 | }); |
| 1701 | const notLinked = Effect.fn("CloudLink.notLinkedByPolicy")(() => |
| 1702 | Effect.succeed({ status: "not_linked" as const }), |
| 1703 | ); |
| 1704 | const notDesired = Effect.fn("CloudLink.notDesiredByPolicy")(() => Effect.succeed(null)); |
| 1705 | const notStarted = Effect.fn("CloudLink.notStartedByPolicy")(() => Effect.succeed(false)); |
| 1706 | return CloudLink.of({ |
| 1707 | linkProof: refused, |
| 1708 | applyRelayConfig: refused, |
| 1709 | linkState, |
| 1710 | unlink, |
| 1711 | updatePreferences: refused, |
| 1712 | updateLiveActivityPreference: refused, |
| 1713 | answerHealthRequest: refused, |
| 1714 | mintCredential: refused, |
| 1715 | reconcileDesiredLinkIfStillDesired: notDesired, |
| 1716 | registerManagedTunnelRecovery: notLinked, |
| 1717 | recoverManagedTunnel: notStarted, |
| 1718 | startManagedTunnelIfOriginConfirmed: notStarted, |
| 1719 | releaseManagedTunnelOnShutdown, |
| 1720 | }); |
| 1721 | } |
| 1722 | |
| 1723 | return CloudLink.of({ |
| 1724 | linkProof, |
| 1725 | applyRelayConfig, |
| 1726 | linkState, |
| 1727 | unlink, |
| 1728 | updatePreferences, |
| 1729 | updateLiveActivityPreference, |
| 1730 | answerHealthRequest, |
| 1731 | mintCredential, |
| 1732 | reconcileDesiredLinkIfStillDesired, |
| 1733 | registerManagedTunnelRecovery, |
| 1734 | recoverManagedTunnel, |
| 1735 | startManagedTunnelIfOriginConfirmed, |
| 1736 | releaseManagedTunnelOnShutdown, |
| 1737 | }); |
| 1738 | }); |
| 1739 | |
| 1740 | export const layer = Layer.effect(CloudLink, make); |