Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

1,087 lines40.5 KB

1import * as NodeCrypto from "node:crypto";
2import {
3 AuthRelayReadScope,
4 AuthRelayWriteScope,
5 AuthStandardClientScopes,
6 EnvironmentCloudEndpointUnavailableError,
7 EnvironmentCloudLinkStateResult,
8 EnvironmentCloudRelayConfigResult,
9 EnvironmentHttpApi,
10 EnvironmentHttpBadRequestError,
11 EnvironmentHttpConflictError,
12 EnvironmentHttpInternalServerError,
13 EnvironmentHttpUnauthorizedError,
14} from "@t3tools/contracts";
15import {
16 RelayCloudEnvironmentHealthProofPayload,
17 RelayCloudEnvironmentHealthRequest,
18 RelayCloudMintCredentialProofPayload,
19 RelayCloudMintCredentialRequest,
20 RelayEnvironmentHealthResponseProofPayload,
21 type RelayEnvironmentHealthResponse as RelayEnvironmentHealthResponseShape,
22 RelayEnvironmentConfigRequest,
23 RelayEnvironmentLinkChallengeResponse,
24 RelayEnvironmentLinkResponse,
25 RelayEnvironmentMintResponseProofPayload,
26 type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,
27 RelayEnvironmentLinkProof,
28 RelayEnvironmentLinkProofPayload,
29 RelayLinkProofRequest,
30 RelayManagedEndpointOrigin,
31 RelayOkResponse,
32} from "@t3tools/contracts/relay";
33import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
34import {
35 normalizeRelayIssuer,
36 RELAY_HEALTH_REQUEST_TYP,
37 RELAY_HEALTH_RESPONSE_TYP,
38 RELAY_LINK_PROOF_TYP,
39 RELAY_MINT_REQUEST_TYP,
40 RELAY_MINT_RESPONSE_TYP,
41 signRelayJwt,
42 verifyRelayJwt,
43} from "@t3tools/shared/relayJwt";
44import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
45import * as DateTime from "effect/DateTime";
46import * as Crypto from "effect/Crypto";
47import * as Duration from "effect/Duration";
48import * as Effect from "effect/Effect";
49import * as FileSystem from "effect/FileSystem";
50import * as Option from "effect/Option";
51import * as Path from "effect/Path";
52import * as Schema from "effect/Schema";
53import * as HttpEffect from "effect/unstable/http/HttpEffect";
54import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
55import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
56import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
57​
58import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
59import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
60import { requireEnvironmentScope } from "../auth/http.ts";
61import * as ServerConfig from "../config.ts";
62import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
63import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
64import {
65 SERVICE_STATE_FILE,
66 SERVICE_STOP_MARKER_FILE,
67 serviceStateHasPendingUpdate,
68} from "./serviceProtocol.ts";
69import {
70 CLOUD_ENDPOINT_RUNTIME_CONFIG,
71 CLOUD_LINKED_USER_ID,
72 CLOUD_MINT_PUBLIC_KEY,
73 encodeEndpointRuntimeConfigJson,
74 PUBLISH_AGENT_ACTIVITY_SECRET,
75 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
76 RELAY_ISSUER_SECRET,
77 RELAY_URL_SECRET,
78} from "./config.ts";
79import { relayUrlConfig } from "./publicConfig.ts";
80import {
81 readCliDesiredCloudLink,
82 readCliDesiredLinkMode,
83 setCliDesiredCloudLink,
84} from "./CliState.ts";
85import * as CliTokenManager from "./CliTokenManager.ts";
86import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
87import { traceRelayRequest } from "./traceRelayRequest.ts";
88​
89const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";
90const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-";
91const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-";
92const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-";
93const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;
94const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;
95const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
96const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
97 "cache-control": "no-store",
98 pragma: "no-cache",
99} as const;
100​
101const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
102 (_request, response) =>
103 Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
104);
105​
106const failEnvironmentCloudInternalError =
107 (message: string) =>
108 (cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
109 Effect.logError(message, { cause }).pipe(
110 Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
111 );
112​
113const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
114 failEnvironmentCloudInternalError(error.message)(error);
115​
116const requireRelayUrl = relayUrlConfig.pipe(
117 Effect.mapError(
118 () =>
119 new EnvironmentHttpInternalServerError({
120 message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
121 }),
122 ),
123);
124​
125function bytesToString(bytes: Uint8Array): string {
126 return new TextDecoder().decode(bytes);
128​
129function stringToBytes(value: string): Uint8Array {
130 return new TextEncoder().encode(value);
132​
133export function consumeCloudReplayGuards(input: {
134 readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
135 readonly names: ReadonlyArray<string>;
136 readonly value: Uint8Array;
137}) {
138 return Effect.all(
139 input.names.map((name) =>
140 input.secrets.create(name, input.value).pipe(
141 Effect.as(true),
142 Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
143 ServerSecretStore.isSecretAlreadyExistsError(error)
144 ? Effect.succeed(false)
145 : Effect.fail(error),
146 ),
147 ),
148 ),
149 { concurrency: input.names.length },
150 ).pipe(Effect.map((created) => created.every(Boolean)));
152​
153function normalizePemForSignedPayload(value: string): string {
154 return value.trim();
156​
157function normalizeHostname(hostname: string): string {
158 return hostname
159 .trim()
160 .toLowerCase()
161 .replace(/^\[(.*)\]$/, "$1");
163​
164function validateCloudMintPublicKey(
165 publicKey: string,
166): Effect.Effect<void, EnvironmentHttpBadRequestError> {
167 return Effect.try({
168 try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
169 catch: () =>
170 new EnvironmentHttpBadRequestError({
171 message: "Cloud mint public key must be a valid Ed25519 public key.",
172 }),
173 }).pipe(
174 Effect.flatMap((key) =>
175 key.asymmetricKeyType === "ed25519"
176 ? Effect.void
177 : Effect.fail(
178 new EnvironmentHttpBadRequestError({
179 message: "Cloud mint public key must be a valid Ed25519 public key.",
180 }),
181 ),
182 ),
183 );
185​
186function validateRelayConfigPayload(
187 payload: RelayEnvironmentConfigRequest,
188): Effect.Effect<void, EnvironmentHttpBadRequestError> {
189 if (!isSecureRelayUrl(payload.relayUrl)) {
190 return Effect.fail(
191 new EnvironmentHttpBadRequestError({
192 message: "Relay URL must be a secure absolute HTTPS URL.",
193 }),
194 );
195 }
196 if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
197 return Effect.fail(
198 new EnvironmentHttpBadRequestError({
199 message: "Relay issuer must be a secure absolute HTTPS URL.",
200 }),
201 );
202 }
203 if (payload.environmentCredential.trim().length === 0) {
204 return Effect.fail(
205 new EnvironmentHttpBadRequestError({
206 message: "Relay environment credential is required.",
207 }),
208 );
209 }
210 if (payload.cloudUserId.trim().length === 0) {
211 return Effect.fail(
212 new EnvironmentHttpBadRequestError({
213 message: "Cloud user id is required.",
214 }),
215 );
216 }
217 return Effect.void;
219​
220function validateLinkedCloudUser(input: {
221 readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
222 readonly cloudUserId: string;
223}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
224 return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
225 Effect.mapError(
226 (cause) =>
227 new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({
228 cause,
229 }),
230 ),
231 Effect.flatMap((existing) => {
232 if (Option.isNone(existing)) {
233 return Effect.void;
234 }
235 const existingCloudUserId = bytesToString(existing.value);
236 return existingCloudUserId === input.cloudUserId
237 ? Effect.void
238 : Effect.fail(
239 new EnvironmentHttpConflictError({
240 message:
241 "This environment is already linked to a different cloud account. Unlink it before switching accounts.",
242 }),
243 );
244 }),
245 );
247​
248function readInstalledCloudUserId(
249 secrets: ServerSecretStore.ServerSecretStore["Service"],
250): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
251 return secrets.get(CLOUD_LINKED_USER_ID).pipe(
252 Effect.mapError(
253 (cause) =>
254 new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({
255 cause,
256 }),
257 ),
258 Effect.flatMap((bytes) =>
259 Option.isSome(bytes)
260 ? Effect.succeed(bytesToString(bytes.value))
261 : Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})),
262 ),
263 );
265​
266function isLoopbackHostname(hostname: string): boolean {
267 return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
269​
270function firstForwardedHeaderValue(value: string | undefined): string | undefined {
271 const first = value?.split(",")[0]?.trim();
272 return first && first.length > 0 ? first : undefined;
274​
275function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {
276 try {
277 return new URL(request.originalUrl).href;
278 } catch {
279 const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1";
280 try {
281 return new URL(request.originalUrl, `http://${host}`).href;
282 } catch {
283 return null;
284 }
285 }
287​
288function hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean {
289 return (
290 firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined ||
291 firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined
292 );
294​
295function endpointRequestPort(url: URL): number {
296 return Number(url.port || (url.protocol === "https:" ? 443 : 80));
298​
299function isAllowedEndpointOrigin(input: {
300 readonly origin: RelayManagedEndpointOrigin;
301 readonly requestUrl: string;
302}): boolean {
303 if (!isLoopbackHostname(input.origin.localHttpHost)) {
304 return false;
305 }
306​
307 const url = new URL(input.requestUrl);
308 if (!isLoopbackHostname(url.hostname)) {
309 return false;
310 }
311​
312 return input.origin.localHttpPort === endpointRequestPort(url);
314​
315// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must
316// point at a loopback origin. A manual endpoint is reached out of band (e.g.
317// Tailscale) or not advertised at all for publish-only links, so it is not
318// tied to the managed-tunnel scope.
319export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
320 return (
321 request.endpoint.providerKind === "cloudflare_tunnel" ||
322 request.endpoint.providerKind === "manual"
323 );
325​
326export function linkProofScopes(
327 request: RelayLinkProofRequest,
328): RelayEnvironmentLinkProofPayload["scopes"] {
329 return request.endpoint.providerKind === "cloudflare_tunnel"
330 ? ["agent_activity_notifications", "managed_tunnels"]
331 : ["agent_activity_notifications"];
333​
334function hasExactScope(input: {
335 readonly scopes: ReadonlyArray<string>;
336 readonly expected: string;
337}): boolean {
338 return input.scopes.length === 1 && input.scopes[0] === input.expected;
340​
341function hasBoundedCloudProofLifetime(input: {
342 readonly iat: number;
343 readonly exp: number;
344 readonly nowSeconds: number;
345}): boolean {
346 return (
347 input.exp > input.iat &&
348 input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS &&
349 input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS
350 );
352​
353const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);
354const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
355​
356interface CloudHttpDependencies {
357 readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
358 readonly environment: ServerEnvironment.ServerEnvironment["Service"];
359 readonly endpointRuntime: ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"];
360 readonly environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"];
361 readonly cliTokenManager: CliTokenManager.CloudCliTokenManager["Service"];
362 readonly httpClient: HttpClient.HttpClient;
364​
365const cloudHttpDependencies = Effect.gen(function* () {
366 return {
367 secrets: yield* ServerSecretStore.ServerSecretStore,
368 environment: yield* ServerEnvironment.ServerEnvironment,
369 endpointRuntime: yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime,
370 environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,
371 cliTokenManager: yield* CliTokenManager.CloudCliTokenManager,
372 httpClient: yield* HttpClient.HttpClient,
373 } satisfies CloudHttpDependencies;
374});
375​
376const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
377 dependencies: CloudHttpDependencies,
378 request: RelayLinkProofRequest,
379 requestUrl: string,
380) {
381 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
382 if (
383 !isSupportedLinkProviderKind(request) ||
384 !isAllowedEndpointOrigin({
385 origin: request.origin,
386 requestUrl,
387 })
388 ) {
389 return yield* new EnvironmentHttpBadRequestError({
390 message: "Invalid managed endpoint origin.",
391 });
392 }
393 const now = yield* DateTime.now;
394 const expiresAt = DateTime.add(now, { minutes: 5 });
395 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
396 const descriptor = yield* dependencies.environment.getDescriptor;
397 const payload = {
398 iss: `t3-env:${descriptor.environmentId}`,
399 aud: normalizeRelayIssuer(request.relayIssuer),
400 sub: descriptor.environmentId,
401 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
402 iat: nowSeconds,
403 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
404 challenge: request.challenge,
405 descriptor,
406 environmentId: descriptor.environmentId,
407 environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
408 endpoint: request.endpoint,
409 origin: request.origin,
410 scopes: linkProofScopes(request),
411 } satisfies RelayEnvironmentLinkProofPayload;
412 return yield* signRelayJwt({
413 privateKey: keyPair.privateKey,
414 typ: RELAY_LINK_PROOF_TYP,
415 payload,
416 }).pipe(
417 Effect.mapError(
418 (cause) =>
419 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
420 cause,
421 }),
422 ),
423 );
424});
425​
426const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
427 function* (dependencies: CloudHttpDependencies, request: RelayLinkProofRequest) {
428 yield* requireEnvironmentScope(AuthRelayWriteScope);
429 const httpRequest = yield* HttpServerRequest.HttpServerRequest;
430 const requestUrl = requestAbsoluteUrl(httpRequest);
431 if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
432 return yield* new EnvironmentHttpBadRequestError({
433 message: "Invalid managed endpoint origin.",
434 });
435 }
436 const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
437 yield* appendCloudCredentialResponseHeaders;
438 return proof satisfies RelayEnvironmentLinkProof;
439 },
440 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
441 failEnvironmentCloudInternalError(error.message)(error),
442 ),
443 Effect.catchIf(
444 ServerSecretStore.isSecretStoreError,
445 failEnvironmentCloudInternalError("Could not generate environment link proof."),
446 ),
447 Effect.catchTag(
448 "PlatformError",
449 failEnvironmentCloudInternalError("Could not generate environment link proof."),
450 ),
451);
452​
453const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
454 dependencies: CloudHttpDependencies,
455 payload: RelayEnvironmentConfigRequest,
456) {
457 yield* validateRelayConfigPayload(payload);
458 yield* validateLinkedCloudUser({
459 secrets: dependencies.secrets,
460 cloudUserId: payload.cloudUserId,
461 });
462 yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
463 const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(
464 payload.endpointRuntime,
465 );
466 const ok =
467 endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
468 if (!ok) {
469 return yield* new EnvironmentCloudEndpointUnavailableError({
470 message: "Managed endpoint runtime could not be started.",
471 endpointRuntimeStatus,
472 });
473 }
474​
475 yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));
476 yield* dependencies.secrets.set(
477 RELAY_ISSUER_SECRET,
478 stringToBytes(payload.relayIssuer ?? payload.relayUrl),
479 );
480 yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));
481 yield* dependencies.secrets.set(
482 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
483 stringToBytes(payload.environmentCredential),
484 );
485 yield* dependencies.secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey));
486 if (payload.endpointRuntime) {
487 const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime);
488 yield* dependencies.secrets.set(
489 CLOUD_ENDPOINT_RUNTIME_CONFIG,
490 stringToBytes(endpointRuntimeJson),
491 );
492 } else {
493 yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
494 }
495 return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
496});
497​
498const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
499 function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) {
500 yield* requireEnvironmentScope(AuthRelayWriteScope);
501 return yield* applyCloudRelayConfig(dependencies, payload);
502 },
503 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
504 failEnvironmentCloudInternalError(error.message)(error),
505 ),
506 Effect.catchIf(
507 ServerSecretStore.isSecretStoreError,
508 failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
509 ),
510 Effect.catchTag(
511 "SchemaError",
512 failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
513 ),
514);
515​
516const relayClientRequest = <A>(
517 dependencies: CloudHttpDependencies,
518 input: {
519 readonly url: string;
520 readonly token: string;
521 readonly payload: unknown;
522 readonly schema: Schema.Decoder<A>;
523 },
524) =>
525 HttpClientRequest.post(input.url).pipe(
526 HttpClientRequest.bearerToken(input.token),
527 HttpClientRequest.bodyJson(input.payload),
528 Effect.flatMap(dependencies.httpClient.execute),
529 Effect.flatMap(HttpClientResponse.filterStatusOk),
530 Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
531 Effect.mapError(
532 (cause) =>
533 new EnvironmentHttpInternalServerError({
534 message: `T3 Connect relay request failed: ${String(cause)}`,
535 }),
536 ),
537 withRelayClientTracing,
538 );
539​
540const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")(
541 function* (dependencies: CloudHttpDependencies, localOrigin: string) {
542 const localUrl = yield* Effect.try({
543 try: () => new URL(localOrigin),
544 catch: () =>
545 new EnvironmentHttpBadRequestError({
546 message: "Could not resolve local environment origin.",
547 }),
548 });
549 if (localUrl.origin !== localOrigin) {
550 return yield* new EnvironmentHttpBadRequestError({
551 message: "Could not resolve local environment origin.",
552 });
553 }
554 const localWsOrigin = localOrigin.replace(/^http/u, "ws");
555 const token = yield* dependencies.cliTokenManager.getExisting.pipe(
556 Effect.flatMap(
557 Option.match({
558 onNone: () =>
559 Effect.fail(
560 new EnvironmentHttpUnauthorizedError({
561 message: "Run `t3 connect link` to authorize this environment.",
562 }),
563 ),
564 onSome: Effect.succeed,
565 }),
566 ),
567 );
568 const mode = yield* readCliDesiredLinkMode;
569 const managedTunnelsEnabled = mode !== "publish_only";
570 const relayUrl = yield* requireRelayUrl;
571 const challenge = yield* relayClientRequest(dependencies, {
572 url: `${relayUrl}/v1/client/environment-link-challenges`,
573 token: token.accessToken,
574 payload: {
575 notificationsEnabled: true,
576 liveActivitiesEnabled: true,
577 managedTunnelsEnabled,
578 },
579 schema: RelayEnvironmentLinkChallengeResponse,
580 });
581 const proof = yield* makeCloudLinkProof(
582 dependencies,
583 {
584 challenge: challenge.challenge,
585 relayIssuer: relayUrl,
586 endpoint: {
587 httpBaseUrl: localOrigin,
588 wsBaseUrl: localWsOrigin,
589 providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
590 },
591 origin: {
592 localHttpHost: localUrl.hostname,
593 localHttpPort: endpointRequestPort(localUrl),
594 },
595 },
596 localOrigin,
597 );
598 const link = yield* relayClientRequest(dependencies, {
599 url: `${relayUrl}/v1/client/environment-links`,
600 token: token.accessToken,
601 payload: {
602 proof,
603 notificationsEnabled: true,
604 liveActivitiesEnabled: true,
605 managedTunnelsEnabled,
606 },
607 schema: RelayEnvironmentLinkResponse,
608 });
609 yield* setCliDesiredCloudLink(true, mode);
610 return yield* applyCloudRelayConfig(dependencies, {
611 relayUrl,
612 relayIssuer: link.relayIssuer,
613 cloudUserId: link.cloudUserId,
614 environmentCredential: link.environmentCredential,
615 cloudMintPublicKey: link.cloudMintPublicKey,
616 endpointRuntime: link.endpointRuntime,
617 });
618 },
619 Effect.catchIf(
620 ServerSecretStore.isSecretStoreError,
621 failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
622 ),
623 Effect.catchTags({
624 CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
625 CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
626 CloudCliCredentialReadError: failCloudCliTokenManagerError,
627 CloudCliAuthorizationError: failCloudCliTokenManagerError,
628 CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
629 }),
630);
631​
632export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileDesiredLink")(
633 function* (localOrigin: string) {
634 return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);
635 },
636);
637​
638// The launcher owns this durable state, so read it directly both when a trial
639// decides whether it owns pre-activation cleanup and while a server tears down.
640export const pendingServiceUpdateExists = Effect.gen(function* () {
641 const config = yield* ServerConfig.ServerConfig;
642 const fs = yield* FileSystem.FileSystem;
643 const path = yield* Path.Path;
644 const runtimeDir = path.join(config.baseDir, "runtime");
645 const stateText = yield* fs
646 .readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
647 .pipe(Effect.option);
648 return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
649});
650​
651// A pending update alone is not proof a replacement server is coming: an
652// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
653// `launchctl bootout`) during
654// the pending window also tears this server down. The launcher marks that case
655// just before it signals the child, so pending + no marker is the handoff.
656const pendingUpdateHandoffExists = Effect.gen(function* () {
657 if (!(yield* pendingServiceUpdateExists)) {
658 return false;
659 }
660 const config = yield* ServerConfig.ServerConfig;
661 const fs = yield* FileSystem.FileSystem;
662 const path = yield* Path.Path;
663 const runtimeDir = path.join(config.baseDir, "runtime");
664 const stopping = yield* fs
665 .exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
666 .pipe(Effect.orElseSucceed(() => false));
667 return !stopping;
668});
669​
670// Cloudflare bills per provisioned tunnel, so an environment that goes offline
671// must not leave its tunnel behind. Releasing deletes only the tunnel — the
672// relay keeps the link and its hostname reservation, and the next startup's
673// link reconcile provisions a replacement tunnel under the same URL.
674export const releaseManagedTunnelOnShutdown = Effect.fn(
675 "environment.cloud.releaseManagedTunnelOnShutdown",
676)(function* () {
677 const dependencies = yield* cloudHttpDependencies;
678 // Only a managed link stores a runtime config; publish-only links have no
679 // tunnel to release.
680 const runtimeConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
681 if (Option.isNone(runtimeConfig)) {
682 return false;
683 }
684 // Only CLI-desired managed links release on shutdown, because the startup
685 // reconcile that provisions the replacement tunnel only runs for them. A
686 // link installed by a web/mobile client comes back after a restart by
687 // reapplying the stored connector token — it has no boot-time re-provision
688 // path — so its tunnel must survive the restart. (Unlink still deletes it.)
689 if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
690 return false;
691 }
692 // A shutdown that hands off to a pending remote update is not the
693 // environment going offline: the launcher immediately brings a server back
694 // (the new version, or the old one after a rollback). Deleting the tunnel
695 // here forces that server to provision a replacement UUID, and the public
696 // hostname's route to the new tunnel takes 1-2 minutes to propagate — the
697 // dominant cost of an update restart. Keep the tunnel instead: the next
698 // boot respawns the connector from the stored config and is reachable as
699 // soon as it connects, and the reconcile confirms the still-live tunnel
700 // without replacing it.
701 if (yield* pendingUpdateHandoffExists) {
702 yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
703 return false;
704 }
705 const token = yield* dependencies.cliTokenManager.getExisting;
706 if (Option.isNone(token)) {
707 return false;
708 }
709 // The link belongs to the relay it was installed against, so target the
710 // persisted URL: T3CODE_RELAY_URL may have changed since the link was made.
711 const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);
712 if (Option.isNone(relayUrl)) {
713 return false;
714 }
715 const environmentId = yield* dependencies.environment.getEnvironmentId;
716 // Stop the local connector before the relay deletes the tunnel it serves.
717 yield* dependencies.endpointRuntime.applyConfig(null);
718 const response = yield* HttpClientRequest.delete(
719 `${bytesToString(relayUrl.value)}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,
720 ).pipe(
721 HttpClientRequest.bearerToken(token.value.accessToken),
722 dependencies.httpClient.execute,
723 Effect.flatMap(HttpClientResponse.filterStatusOk),
724 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
725 withRelayClientTracing,
726 );
727 // ok:false means the relay skipped deletion because a concurrent provision
728 // owns the recorded tunnel now — leave the stored config alone.
729 if (!response.ok) {
730 return false;
731 }
732 // The connector token died with the tunnel. Drop the stored config so the
733 // next start waits for the link reconcile instead of respawning the relay
734 // client with a dead token. Kept when the release request fails: the tunnel
735 // still exists, so the stored token keeps working across the restart.
736 // Only dropped while it is still the config this shutdown released — a fast
737 // restart may already have reconciled and stored a fresh config for its
738 // replacement tunnel, and that one must survive this finalizer.
739 const storedConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
740 if (
741 Option.isSome(storedConfig) &&
742 bytesToString(storedConfig.value) === bytesToString(runtimeConfig.value)
743 ) {
744 yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
745 }
746 return true;
747});
748​
749const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
750 dependencies: CloudHttpDependencies,
751) {
752 const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] =
753 yield* Effect.all(
754 [
755 dependencies.secrets.get(CLOUD_LINKED_USER_ID),
756 dependencies.secrets.get(RELAY_URL_SECRET),
757 dependencies.secrets.get(RELAY_ISSUER_SECRET),
758 dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
759 dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
760 ],
761 { concurrency: 5 },
762 );
763 return {
764 linked: Option.isSome(cloudUserId),
765 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
766 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
767 relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,
768 // The managed tunnel runtime config is only stored for managed links; a
769 // publish-only link leaves it absent.
770 managedTunnelActive: Option.isSome(endpointRuntimeConfig),
771 publishAgentActivity: Option.isSome(publishAgentActivity)
772 ? bytesToString(publishAgentActivity.value) === "true"
773 : false,
774 } satisfies EnvironmentCloudLinkStateResult;
775});
776​
777const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
778 function* (dependencies: CloudHttpDependencies) {
779 yield* requireEnvironmentScope(AuthRelayReadScope);
780 return yield* readCloudLinkState(dependencies);
781 },
782 Effect.catchIf(
783 ServerSecretStore.isSecretStoreError,
784 failEnvironmentCloudInternalError("Could not read environment relay configuration."),
785 ),
786);
787​
788const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
789 function* (dependencies: CloudHttpDependencies) {
790 yield* requireEnvironmentScope(AuthRelayWriteScope);
791 const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null);
792 yield* Effect.all(
793 [
794 dependencies.secrets.remove(CLOUD_LINKED_USER_ID),
795 dependencies.secrets.remove(RELAY_URL_SECRET),
796 dependencies.secrets.remove(RELAY_ISSUER_SECRET),
797 dependencies.secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
798 dependencies.secrets.remove(CLOUD_MINT_PUBLIC_KEY),
799 dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),
800 dependencies.secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),
801 ],
802 { concurrency: 7 },
803 );
804 yield* setCliDesiredCloudLink(false);
805 return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
806 },
807 Effect.catchIf(
808 ServerSecretStore.isSecretStoreError,
809 failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
810 ),
811);
812​
813const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
814 function* (
815 dependencies: CloudHttpDependencies,
816 payload: { readonly publishAgentActivity: boolean },
817 ) {
818 yield* requireEnvironmentScope(AuthRelayWriteScope);
819 yield* dependencies.secrets.set(
820 PUBLISH_AGENT_ACTIVITY_SECRET,
821 stringToBytes(String(payload.publishAgentActivity)),
822 );
823 return yield* readCloudLinkState(dependencies);
824 },
825 Effect.catchIf(
826 ServerSecretStore.isSecretStoreError,
827 failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
828 ),
829);
830​
831const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
832 function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {
833 const cloudMintPublicKey = yield* dependencies.secrets
834 .get(CLOUD_MINT_PUBLIC_KEY)
835 .pipe(
836 Effect.flatMap((bytes) =>
837 Option.isSome(bytes)
838 ? Effect.succeed(bytesToString(bytes.value))
839 : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
840 ),
841 );
842 const relayIssuer = yield* dependencies.secrets
843 .get(RELAY_ISSUER_SECRET)
844 .pipe(
845 Effect.flatMap((bytes) =>
846 Option.isSome(bytes)
847 ? Effect.succeed(bytesToString(bytes.value))
848 : dependencies.secrets
849 .get(RELAY_URL_SECRET)
850 .pipe(
851 Effect.flatMap((fallbackBytes) =>
852 Option.isSome(fallbackBytes)
853 ? Effect.succeed(bytesToString(fallbackBytes.value))
854 : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
855 ),
856 ),
857 ),
858 );
859 const environmentId = yield* dependencies.environment.getEnvironmentId;
860 const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
861 const now = yield* DateTime.now;
862 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
863 const proofOption = yield* verifyRelayJwt({
864 publicKey: cloudMintPublicKey,
865 token: request.proof,
866 typ: RELAY_HEALTH_REQUEST_TYP,
867 issuer: normalizeRelayIssuer(relayIssuer),
868 audience: `t3-env:${environmentId}`,
869 nowEpochSeconds: nowSeconds,
870 }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);
871 if (
872 Option.isNone(proofOption) ||
873 proofOption.value.environmentId !== environmentId ||
874 proofOption.value.sub !== linkedCloudUserId ||
875 !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
876 !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
877 ) {
878 return yield* new EnvironmentHttpUnauthorizedError({
879 message: "Invalid cloud health request.",
880 });
881 }
882 const proof = proofOption.value;
883​
884 const jtiSecretName = `${CLOUD_HEALTH_JTI_PREFIX}${proof.jti}`;
885 const nonceSecretName = `${CLOUD_HEALTH_NONCE_PREFIX}${proof.nonce}`;
886 const consumedReplayGuards = yield* consumeCloudReplayGuards({
887 secrets: dependencies.secrets,
888 names: [jtiSecretName, nonceSecretName],
889 value: stringToBytes(DateTime.formatIso(now)),
890 });
891 if (!consumedReplayGuards) {
892 return yield* new EnvironmentHttpConflictError({
893 message: "Cloud health request was already consumed.",
894 });
895 }
896​
897 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
898 const descriptor = yield* dependencies.environment.getDescriptor;
899 const responseExpiresAt = DateTime.add(now, { minutes: 5 });
900 const responsePayload = {
901 iss: `t3-env:${environmentId}`,
902 aud: normalizeRelayIssuer(relayIssuer),
903 sub: environmentId,
904 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
905 iat: nowSeconds,
906 exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),
907 environmentId,
908 requestNonce: proof.nonce,
909 status: "online",
910 descriptor,
911 checkedAt: DateTime.formatIso(now),
912 } satisfies RelayEnvironmentHealthResponseProofPayload;
913 const responseProof = yield* signRelayJwt({
914 privateKey: keyPair.privateKey,
915 typ: RELAY_HEALTH_RESPONSE_TYP,
916 payload: responsePayload,
917 }).pipe(
918 Effect.mapError(
919 (cause) =>
920 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
921 cause,
922 }),
923 ),
924 );
925 const response = {
926 environmentId,
927 status: "online",
928 descriptor,
929 checkedAt: responsePayload.checkedAt,
930 proof: responseProof,
931 } satisfies RelayEnvironmentHealthResponseShape;
932​
933 yield* appendCloudCredentialResponseHeaders;
934 return response;
935 },
936 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
937 failEnvironmentCloudInternalError(error.message)(error),
938 ),
939 Effect.catchIf(
940 ServerSecretStore.isSecretStoreError,
941 failEnvironmentCloudInternalError("Could not answer cloud health request."),
942 ),
943 Effect.catchTag(
944 "PlatformError",
945 failEnvironmentCloudInternalError("Could not answer cloud health request."),
946 ),
947);
948​
949const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
950 function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {
951 const cloudMintPublicKey = yield* dependencies.secrets
952 .get(CLOUD_MINT_PUBLIC_KEY)
953 .pipe(
954 Effect.flatMap((bytes) =>
955 Option.isSome(bytes)
956 ? Effect.succeed(bytesToString(bytes.value))
957 : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
958 ),
959 );
960 const relayIssuer = yield* dependencies.secrets
961 .get(RELAY_ISSUER_SECRET)
962 .pipe(
963 Effect.flatMap((bytes) =>
964 Option.isSome(bytes)
965 ? Effect.succeed(bytesToString(bytes.value))
966 : dependencies.secrets
967 .get(RELAY_URL_SECRET)
968 .pipe(
969 Effect.flatMap((fallbackBytes) =>
970 Option.isSome(fallbackBytes)
971 ? Effect.succeed(bytesToString(fallbackBytes.value))
972 : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
973 ),
974 ),
975 ),
976 );
977 const environmentId = yield* dependencies.environment.getEnvironmentId;
978 const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
979 const now = yield* DateTime.now;
980 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
981 const proofOption = yield* verifyRelayJwt({
982 publicKey: cloudMintPublicKey,
983 token: request.proof,
984 typ: RELAY_MINT_REQUEST_TYP,
985 issuer: normalizeRelayIssuer(relayIssuer),
986 audience: `t3-env:${environmentId}`,
987 nowEpochSeconds: nowSeconds,
988 }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);
989 if (
990 Option.isNone(proofOption) ||
991 proofOption.value.environmentId !== environmentId ||
992 proofOption.value.sub !== linkedCloudUserId ||
993 proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint ||
994 !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
995 !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
996 ) {
997 return yield* new EnvironmentHttpUnauthorizedError({
998 message: "Invalid cloud mint request.",
999 });
1001 const proof = proofOption.value;
1002​
1003 const jtiSecretName = `${CLOUD_MINT_JTI_PREFIX}${proof.jti}`;
1004 const nonceSecretName = `${CLOUD_MINT_NONCE_PREFIX}${proof.nonce}`;
1005 const consumedReplayGuards = yield* consumeCloudReplayGuards({
1006 secrets: dependencies.secrets,
1007 names: [jtiSecretName, nonceSecretName],
1008 value: stringToBytes(DateTime.formatIso(now)),
1009 });
1010 if (!consumedReplayGuards) {
1011 return yield* new EnvironmentHttpConflictError({
1012 message: "Cloud mint request was already consumed.",
1013 });
1015​
1016 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
1017 const issued = yield* dependencies.environmentAuth.createPairingLink({
1018 scopes: AuthStandardClientScopes,
1019 subject: "cloud-connect",
1020 ttl: Duration.minutes(2),
1021 label: "T3 Connect connect",
1022 proofKeyThumbprint: proof.clientProofKeyThumbprint,
1023 });
1024 const responsePayload = {
1025 iss: `t3-env:${environmentId}`,
1026 aud: normalizeRelayIssuer(relayIssuer),
1027 sub: environmentId,
1028 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
1029 iat: nowSeconds,
1030 exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000),
1031 environmentId,
1032 clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
1033 requestNonce: proof.nonce,
1034 credential: issued.credential,
1035 } satisfies RelayEnvironmentMintResponseProofPayload;
1036 const responseProof = yield* signRelayJwt({
1037 privateKey: keyPair.privateKey,
1038 typ: RELAY_MINT_RESPONSE_TYP,
1039 payload: responsePayload,
1040 }).pipe(
1041 Effect.mapError(
1042 (cause) =>
1043 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
1044 cause,
1045 }),
1046 ),
1047 );
1048 const response = {
1049 credential: issued.credential,
1050 expiresAt: DateTime.formatIso(issued.expiresAt),
1051 proof: responseProof,
1052 } satisfies RelayEnvironmentMintResponseShape;
1053​
1054 yield* appendCloudCredentialResponseHeaders;
1055 return response;
1056 },
1057 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
1058 failEnvironmentCloudInternalError(error.message)(error),
1059 ),
1060 Effect.catchIf(
1061 ServerSecretStore.isSecretStoreError,
1062 failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
1063 ),
1064 Effect.catchTag(
1065 "PlatformError",
1066 failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
1067 ),
1069​
1070export const connectHttpApiLayer = HttpApiBuilder.group(
1071 EnvironmentHttpApi,
1072 "connect",
1073 Effect.fnUntraced(function* (handlers) {
1074 const dependencies = yield* cloudHttpDependencies;
1075 return handlers
1076 .handle("linkProof", ({ payload }) => cloudLinkProofHandler(dependencies, payload))
1077 .handle("relayConfig", ({ payload }) => cloudRelayConfigHandler(dependencies, payload))
1078 .handle("linkState", () => cloudLinkStateHandler(dependencies))
1079 .handle("unlink", () => cloudUnlinkHandler(dependencies))
1080 .handle("preferences", ({ payload }) => cloudPreferencesHandler(dependencies, payload))
1081 .handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))
1082 .handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))
1083 .handle("t3MintCredential", ({ payload }) =>
1084 traceRelayRequest(cloudMintCredentialHandler(dependencies, payload)),
1085 );
1086 }),