The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | RelayEnvironmentLinkProofPayload, |
| 3 | RelayEnvironmentLinkProofInvalidReason, |
| 4 | type RelayEnvironmentLinkRequest, |
| 5 | } from "@t3tools/contracts/relay"; |
| 6 | import { |
| 7 | decodeRelayJwt, |
| 8 | normalizeRelayIssuer, |
| 9 | RELAY_LINK_PROOF_TYP, |
| 10 | verifyRelayJwt, |
| 11 | } from "@t3tools/shared/relayJwt"; |
| 12 | import * as Context from "effect/Context"; |
| 13 | import * as Signature from "effect/crypto/Signature"; |
| 14 | import * as DateTime from "effect/DateTime"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Layer from "effect/Layer"; |
| 17 | import * as Schema from "effect/Schema"; |
| 18 | import * as SqlError from "effect/sql/SqlError"; |
| 19 | |
| 20 | import * as DpopProofs from "../auth/DpopProofs.ts"; |
| 21 | import * as RelayTokens from "../auth/RelayTokens.ts"; |
| 22 | import * as RelayDb from "../db.ts"; |
| 23 | import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; |
| 24 | import * as EnvironmentLinks from "./EnvironmentLinks.ts"; |
| 25 | import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; |
| 26 | import * as RelayConfiguration from "../Config.ts"; |
| 27 | |
| 28 | export class EnvironmentLinkProofExpired extends Schema.TaggedError<EnvironmentLinkProofExpired>()( |
| 29 | "EnvironmentLinkProofExpired", |
| 30 | { |
| 31 | userId: Schema.String, |
| 32 | environmentId: Schema.String, |
| 33 | expiresAt: Schema.String, |
| 34 | }, |
| 35 | ) { |
| 36 | override get message(): string { |
| 37 | return `Environment '${this.environmentId}' link proof expired at ${this.expiresAt}`; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export class EnvironmentLinkProofInvalid extends Schema.TaggedError<EnvironmentLinkProofInvalid>()( |
| 42 | "EnvironmentLinkProofInvalid", |
| 43 | { |
| 44 | userId: Schema.String, |
| 45 | environmentId: Schema.String, |
| 46 | reason: RelayEnvironmentLinkProofInvalidReason, |
| 47 | stage: Schema.Literals([ |
| 48 | "decode_token", |
| 49 | "decode_payload", |
| 50 | "verify_proof", |
| 51 | "authorize_capabilities", |
| 52 | "validate_descriptor", |
| 53 | "verify_challenge", |
| 54 | "validate_expiration", |
| 55 | "consume_proof_nonce", |
| 56 | "consume_challenge_nonce", |
| 57 | "validate_origin", |
| 58 | "validate_existing_link", |
| 59 | "validate_endpoint", |
| 60 | ]), |
| 61 | cause: Schema.optional(Schema.Defect()), |
| 62 | }, |
| 63 | ) { |
| 64 | override get message(): string { |
| 65 | return `Environment '${this.environmentId}' link proof is invalid during ${this.stage}: ${this.reason}`; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | export type EnvironmentLinkError = |
| 70 | | EnvironmentLinkProofExpired |
| 71 | | EnvironmentLinkProofInvalid |
| 72 | | DpopProofs.DpopProofReplayPersistenceError |
| 73 | | EnvironmentLinks.EnvironmentLinkUpsertPersistenceError |
| 74 | | EnvironmentLinks.EnvironmentLinkLookupPersistenceError |
| 75 | | ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed |
| 76 | | EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError |
| 77 | | ManagedEndpointProvider.ManagedEndpointProviderError; |
| 78 | |
| 79 | export class EnvironmentLinker extends Context.Service< |
| 80 | EnvironmentLinker, |
| 81 | { |
| 82 | readonly link: (input: { |
| 83 | readonly userId: string; |
| 84 | readonly request: RelayEnvironmentLinkRequest; |
| 85 | }) => Effect.Effect< |
| 86 | { |
| 87 | readonly environmentId: RelayEnvironmentLinkProofPayload["environmentId"]; |
| 88 | readonly endpoint: RelayEnvironmentLinkProofPayload["endpoint"]; |
| 89 | readonly endpointRuntime: |
| 90 | | ManagedEndpointProvider.ManagedEndpointProvisioningResult["runtime"] |
| 91 | | null; |
| 92 | readonly environmentCredential: string; |
| 93 | }, |
| 94 | EnvironmentLinkError |
| 95 | >; |
| 96 | } |
| 97 | >()("t3code-relay/environments/EnvironmentLinker") {} |
| 98 | |
| 99 | const decodeProof = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload); |
| 100 | |
| 101 | function proofAuthorizesRequestedCapabilities( |
| 102 | proof: RelayEnvironmentLinkProofPayload, |
| 103 | request: RelayEnvironmentLinkRequest, |
| 104 | ): boolean { |
| 105 | const scopes = new Set(proof.scopes); |
| 106 | if (request.managedTunnelsEnabled && !scopes.has("managed_tunnels")) { |
| 107 | return false; |
| 108 | } |
| 109 | return !( |
| 110 | (request.notificationsEnabled || request.liveActivitiesEnabled) && |
| 111 | !scopes.has("agent_activity_notifications") |
| 112 | ); |
| 113 | } |
| 114 | |
| 115 | function isSecureManagedEndpoint(endpoint: RelayEnvironmentLinkProofPayload["endpoint"]): boolean { |
| 116 | try { |
| 117 | const httpUrl = new URL(endpoint.httpBaseUrl); |
| 118 | const wsUrl = new URL(endpoint.wsBaseUrl); |
| 119 | return httpUrl.protocol === "https:" && wsUrl.protocol === "wss:"; |
| 120 | } catch { |
| 121 | return false; |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | function normalizeHostname(hostname: string): string { |
| 126 | return hostname |
| 127 | .trim() |
| 128 | .toLowerCase() |
| 129 | .replace(/^\[(.*)\]$/u, "$1"); |
| 130 | } |
| 131 | |
| 132 | function isLoopbackManagedTunnelOrigin( |
| 133 | origin: RelayEnvironmentLinkProofPayload["origin"], |
| 134 | ): boolean { |
| 135 | const hostname = normalizeHostname(origin.localHttpHost); |
| 136 | return ( |
| 137 | (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") && |
| 138 | Number.isInteger(origin.localHttpPort) && |
| 139 | origin.localHttpPort > 0 && |
| 140 | origin.localHttpPort <= 65_535 |
| 141 | ); |
| 142 | } |
| 143 | |
| 144 | const make = Effect.gen(function* () { |
| 145 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 146 | const transactions = yield* RelayDb.RelayTransactions; |
| 147 | const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; |
| 148 | const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; |
| 149 | const proofReplay = yield* DpopProofs.DpopProofReplay; |
| 150 | const relayTokens = yield* RelayTokens.RelayTokens; |
| 151 | const config = yield* RelayConfiguration.RelayConfiguration; |
| 152 | const signature = yield* Signature.Signature; |
| 153 | |
| 154 | return EnvironmentLinker.of({ |
| 155 | link: Effect.fn("relay.environment_linker.link")(function* (input) { |
| 156 | const now = yield* DateTime.now; |
| 157 | const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); |
| 158 | const unverified = yield* decodeRelayJwt(input.request.proof).pipe( |
| 159 | Effect.mapError( |
| 160 | (cause) => |
| 161 | new EnvironmentLinkProofInvalid({ |
| 162 | userId: input.userId, |
| 163 | environmentId: "unknown", |
| 164 | reason: "invalid_signature_or_scope", |
| 165 | stage: "decode_token", |
| 166 | cause, |
| 167 | }), |
| 168 | ), |
| 169 | ); |
| 170 | const candidate = yield* decodeProof(unverified).pipe( |
| 171 | Effect.mapError( |
| 172 | (cause) => |
| 173 | new EnvironmentLinkProofInvalid({ |
| 174 | userId: input.userId, |
| 175 | environmentId: "unknown", |
| 176 | reason: "invalid_signature_or_scope", |
| 177 | stage: "decode_payload", |
| 178 | cause, |
| 179 | }), |
| 180 | ), |
| 181 | ); |
| 182 | yield* Effect.annotateCurrentSpan({ |
| 183 | "relay.environment_id": candidate.environmentId, |
| 184 | "relay.link.notifications_enabled": input.request.notificationsEnabled, |
| 185 | "relay.link.live_activities_enabled": input.request.liveActivitiesEnabled, |
| 186 | "relay.link.managed_tunnels_enabled": input.request.managedTunnelsEnabled, |
| 187 | }); |
| 188 | if (candidate.exp <= nowSeconds) { |
| 189 | return yield* new EnvironmentLinkProofExpired({ |
| 190 | userId: input.userId, |
| 191 | environmentId: candidate.environmentId, |
| 192 | expiresAt: DateTime.formatIso(DateTime.makeUnsafe(candidate.exp * 1_000)), |
| 193 | }); |
| 194 | } |
| 195 | const issuer = `t3-env:${candidate.environmentId}`; |
| 196 | const relayIssuer = normalizeRelayIssuer(config.relayIssuer); |
| 197 | const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, { |
| 198 | publicKey: candidate.environmentPublicKey, |
| 199 | token: input.request.proof, |
| 200 | typ: RELAY_LINK_PROOF_TYP, |
| 201 | issuer, |
| 202 | audience: relayIssuer, |
| 203 | }).pipe( |
| 204 | Effect.provideService(Signature.Signature, signature), |
| 205 | Effect.mapError( |
| 206 | (cause) => |
| 207 | new EnvironmentLinkProofInvalid({ |
| 208 | userId: input.userId, |
| 209 | environmentId: candidate.environmentId, |
| 210 | reason: "invalid_signature_or_scope", |
| 211 | stage: "verify_proof", |
| 212 | cause, |
| 213 | }), |
| 214 | ), |
| 215 | ); |
| 216 | if ( |
| 217 | verified.sub !== verified.environmentId || |
| 218 | !proofAuthorizesRequestedCapabilities(verified, input.request) |
| 219 | ) { |
| 220 | return yield* new EnvironmentLinkProofInvalid({ |
| 221 | userId: input.userId, |
| 222 | environmentId: candidate.environmentId, |
| 223 | reason: "invalid_signature_or_scope", |
| 224 | stage: "authorize_capabilities", |
| 225 | }); |
| 226 | } |
| 227 | if (verified.descriptor.environmentId !== verified.environmentId) { |
| 228 | return yield* new EnvironmentLinkProofInvalid({ |
| 229 | userId: input.userId, |
| 230 | environmentId: verified.environmentId, |
| 231 | reason: "descriptor_mismatch", |
| 232 | stage: "validate_descriptor", |
| 233 | }); |
| 234 | } |
| 235 | const challenge = yield* relayTokens.verifyLinkChallenge({ |
| 236 | token: verified.challenge, |
| 237 | userId: input.userId, |
| 238 | request: { |
| 239 | notificationsEnabled: input.request.notificationsEnabled, |
| 240 | liveActivitiesEnabled: input.request.liveActivitiesEnabled, |
| 241 | managedTunnelsEnabled: input.request.managedTunnelsEnabled, |
| 242 | }, |
| 243 | }); |
| 244 | if (challenge === null) { |
| 245 | return yield* new EnvironmentLinkProofInvalid({ |
| 246 | userId: input.userId, |
| 247 | environmentId: verified.environmentId, |
| 248 | reason: "challenge_invalid", |
| 249 | stage: "verify_challenge", |
| 250 | }); |
| 251 | } |
| 252 | const expiresAt = DateTime.make(verified.exp * 1_000); |
| 253 | if (expiresAt._tag === "None") { |
| 254 | return yield* new EnvironmentLinkProofInvalid({ |
| 255 | userId: input.userId, |
| 256 | environmentId: verified.environmentId, |
| 257 | reason: "invalid_signature_or_scope", |
| 258 | stage: "validate_expiration", |
| 259 | }); |
| 260 | } |
| 261 | const consumedNonce = yield* proofReplay.consume({ |
| 262 | thumbprint: verified.environmentPublicKey, |
| 263 | jti: verified.jti, |
| 264 | iat: verified.iat, |
| 265 | expiresAt: expiresAt.value, |
| 266 | }); |
| 267 | if (!consumedNonce) { |
| 268 | return yield* new EnvironmentLinkProofInvalid({ |
| 269 | userId: input.userId, |
| 270 | environmentId: verified.environmentId, |
| 271 | reason: "replayed_nonce", |
| 272 | stage: "consume_proof_nonce", |
| 273 | }); |
| 274 | } |
| 275 | const consumedChallenge = yield* proofReplay.consume({ |
| 276 | thumbprint: "relay-environment-link-challenge", |
| 277 | jti: challenge.jti, |
| 278 | iat: challenge.iat, |
| 279 | expiresAt: expiresAt.value, |
| 280 | }); |
| 281 | if (!consumedChallenge) { |
| 282 | return yield* new EnvironmentLinkProofInvalid({ |
| 283 | userId: input.userId, |
| 284 | environmentId: verified.environmentId, |
| 285 | reason: "challenge_invalid", |
| 286 | stage: "consume_challenge_nonce", |
| 287 | }); |
| 288 | } |
| 289 | if (input.request.managedTunnelsEnabled && !isLoopbackManagedTunnelOrigin(verified.origin)) { |
| 290 | return yield* new EnvironmentLinkProofInvalid({ |
| 291 | userId: input.userId, |
| 292 | environmentId: verified.environmentId, |
| 293 | reason: "origin_not_allowed", |
| 294 | stage: "validate_origin", |
| 295 | }); |
| 296 | } |
| 297 | // The account bearer alone must not move an active link, its tunnel and its trusted key to |
| 298 | // another key. Unlinking first releases the tunnel. |
| 299 | const existing = yield* links.getForUser({ |
| 300 | userId: input.userId, |
| 301 | environmentId: verified.environmentId, |
| 302 | }); |
| 303 | if (existing !== null && existing.environmentPublicKey !== verified.environmentPublicKey) { |
| 304 | return yield* new EnvironmentLinkProofInvalid({ |
| 305 | userId: input.userId, |
| 306 | environmentId: verified.environmentId, |
| 307 | reason: "environment_key_mismatch", |
| 308 | stage: "validate_existing_link", |
| 309 | }); |
| 310 | } |
| 311 | // An unlink whose teardown failed leaves its tunnel behind, and provisioning would reuse it by |
| 312 | // name. Finish the teardown before any new link, publish-only too: once that link is active |
| 313 | // it could turn tunnels on and inherit the old one. |
| 314 | if (existing === null) { |
| 315 | const key = { userId: input.userId, environmentId: verified.environmentId }; |
| 316 | const leftover = yield* managedEndpointProvider.prepareDeprovision(key); |
| 317 | if (!(yield* managedEndpointProvider.deprovision({ ...key, target: leftover }))) { |
| 318 | return yield* new ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed({ |
| 319 | ...key, |
| 320 | stage: "claim-deprovision", |
| 321 | cause: "an earlier tunnel for this environment is still being torn down", |
| 322 | }); |
| 323 | } |
| 324 | } |
| 325 | // An active link going publish-only releases its own tunnel/DNS; best-effort deprovision is idempotent. |
| 326 | if (existing !== null && !input.request.managedTunnelsEnabled) { |
| 327 | yield* managedEndpointProvider |
| 328 | .deprovision({ |
| 329 | userId: input.userId, |
| 330 | environmentId: verified.environmentId, |
| 331 | }) |
| 332 | .pipe( |
| 333 | Effect.tapError((error) => |
| 334 | Effect.logWarning("managed endpoint deprovision on publish-only link failed", { |
| 335 | environmentId: verified.environmentId, |
| 336 | errorTag: error._tag, |
| 337 | }), |
| 338 | ), |
| 339 | Effect.ignore, |
| 340 | ); |
| 341 | } |
| 342 | const provisioned = input.request.managedTunnelsEnabled |
| 343 | ? yield* managedEndpointProvider.provision({ |
| 344 | userId: input.userId, |
| 345 | environmentId: verified.environmentId, |
| 346 | origin: verified.origin, |
| 347 | }) |
| 348 | : null; |
| 349 | const endpoint = provisioned?.endpoint ?? verified.endpoint; |
| 350 | // Only advertised managed endpoints need secure URLs; publish-only links route out of band. |
| 351 | if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) { |
| 352 | return yield* new EnvironmentLinkProofInvalid({ |
| 353 | userId: input.userId, |
| 354 | environmentId: verified.environmentId, |
| 355 | reason: "endpoint_not_secure", |
| 356 | stage: "validate_endpoint", |
| 357 | }); |
| 358 | } |
| 359 | const environmentCredential = yield* transactions |
| 360 | .withTransaction( |
| 361 | links.upsert({ ...input, proof: verified, endpoint }).pipe( |
| 362 | Effect.andThen( |
| 363 | credentials.create({ |
| 364 | environmentId: verified.environmentId, |
| 365 | environmentPublicKey: verified.environmentPublicKey, |
| 366 | }), |
| 367 | ), |
| 368 | ), |
| 369 | ) |
| 370 | .pipe( |
| 371 | Effect.mapError((cause) => |
| 372 | SqlError.isSqlError(cause) |
| 373 | ? new EnvironmentLinks.EnvironmentLinkUpsertPersistenceError({ |
| 374 | userId: input.userId, |
| 375 | environmentId: verified.environmentId, |
| 376 | cause, |
| 377 | }) |
| 378 | : cause, |
| 379 | ), |
| 380 | ); |
| 381 | return { |
| 382 | environmentId: verified.environmentId, |
| 383 | endpoint, |
| 384 | endpointRuntime: provisioned?.runtime ?? null, |
| 385 | environmentCredential, |
| 386 | }; |
| 387 | }), |
| 388 | }); |
| 389 | }); |
| 390 | |
| 391 | export const layer = Layer.effect(EnvironmentLinker, make); |