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

http.ts

1,086 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`) during
653// the pending window also tears this server down. The launcher marks that case
654// just before it signals the child, so pending + no marker is the handoff.
655const pendingUpdateHandoffExists = Effect.gen(function* () {
656 if (!(yield* pendingServiceUpdateExists)) {
657 return false;
658 }
659 const config = yield* ServerConfig.ServerConfig;
660 const fs = yield* FileSystem.FileSystem;
661 const path = yield* Path.Path;
662 const runtimeDir = path.join(config.baseDir, "runtime");
663 const stopping = yield* fs
664 .exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
665 .pipe(Effect.orElseSucceed(() => false));
666 return !stopping;
667});
668​
669// Cloudflare bills per provisioned tunnel, so an environment that goes offline
670// must not leave its tunnel behind. Releasing deletes only the tunnel — the
671// relay keeps the link and its hostname reservation, and the next startup's
672// link reconcile provisions a replacement tunnel under the same URL.
673export const releaseManagedTunnelOnShutdown = Effect.fn(
674 "environment.cloud.releaseManagedTunnelOnShutdown",
675)(function* () {
676 const dependencies = yield* cloudHttpDependencies;
677 // Only a managed link stores a runtime config; publish-only links have no
678 // tunnel to release.
679 const runtimeConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
680 if (Option.isNone(runtimeConfig)) {
681 return false;
682 }
683 // Only CLI-desired managed links release on shutdown, because the startup
684 // reconcile that provisions the replacement tunnel only runs for them. A
685 // link installed by a web/mobile client comes back after a restart by
686 // reapplying the stored connector token — it has no boot-time re-provision
687 // path — so its tunnel must survive the restart. (Unlink still deletes it.)
688 if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
689 return false;
690 }
691 // A shutdown that hands off to a pending remote update is not the
692 // environment going offline: the launcher immediately brings a server back
693 // (the new version, or the old one after a rollback). Deleting the tunnel
694 // here forces that server to provision a replacement UUID, and the public
695 // hostname's route to the new tunnel takes 1-2 minutes to propagate — the
696 // dominant cost of an update restart. Keep the tunnel instead: the next
697 // boot respawns the connector from the stored config and is reachable as
698 // soon as it connects, and the reconcile confirms the still-live tunnel
699 // without replacing it.
700 if (yield* pendingUpdateHandoffExists) {
701 yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
702 return false;
703 }
704 const token = yield* dependencies.cliTokenManager.getExisting;
705 if (Option.isNone(token)) {
706 return false;
707 }
708 // The link belongs to the relay it was installed against, so target the
709 // persisted URL: T3CODE_RELAY_URL may have changed since the link was made.
710 const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);
711 if (Option.isNone(relayUrl)) {
712 return false;
713 }
714 const environmentId = yield* dependencies.environment.getEnvironmentId;
715 // Stop the local connector before the relay deletes the tunnel it serves.
716 yield* dependencies.endpointRuntime.applyConfig(null);
717 const response = yield* HttpClientRequest.delete(
718 `${bytesToString(relayUrl.value)}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,
719 ).pipe(
720 HttpClientRequest.bearerToken(token.value.accessToken),
721 dependencies.httpClient.execute,
722 Effect.flatMap(HttpClientResponse.filterStatusOk),
723 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
724 withRelayClientTracing,
725 );
726 // ok:false means the relay skipped deletion because a concurrent provision
727 // owns the recorded tunnel now — leave the stored config alone.
728 if (!response.ok) {
729 return false;
730 }
731 // The connector token died with the tunnel. Drop the stored config so the
732 // next start waits for the link reconcile instead of respawning the relay
733 // client with a dead token. Kept when the release request fails: the tunnel
734 // still exists, so the stored token keeps working across the restart.
735 // Only dropped while it is still the config this shutdown released — a fast
736 // restart may already have reconciled and stored a fresh config for its
737 // replacement tunnel, and that one must survive this finalizer.
738 const storedConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
739 if (
740 Option.isSome(storedConfig) &&
741 bytesToString(storedConfig.value) === bytesToString(runtimeConfig.value)
742 ) {
743 yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
744 }
745 return true;
746});
747​
748const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
749 dependencies: CloudHttpDependencies,
750) {
751 const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] =
752 yield* Effect.all(
753 [
754 dependencies.secrets.get(CLOUD_LINKED_USER_ID),
755 dependencies.secrets.get(RELAY_URL_SECRET),
756 dependencies.secrets.get(RELAY_ISSUER_SECRET),
757 dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
758 dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
759 ],
760 { concurrency: 5 },
761 );
762 return {
763 linked: Option.isSome(cloudUserId),
764 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
765 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
766 relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,
767 // The managed tunnel runtime config is only stored for managed links; a
768 // publish-only link leaves it absent.
769 managedTunnelActive: Option.isSome(endpointRuntimeConfig),
770 publishAgentActivity: Option.isSome(publishAgentActivity)
771 ? bytesToString(publishAgentActivity.value) === "true"
772 : false,
773 } satisfies EnvironmentCloudLinkStateResult;
774});
775​
776const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
777 function* (dependencies: CloudHttpDependencies) {
778 yield* requireEnvironmentScope(AuthRelayReadScope);
779 return yield* readCloudLinkState(dependencies);
780 },
781 Effect.catchIf(
782 ServerSecretStore.isSecretStoreError,
783 failEnvironmentCloudInternalError("Could not read environment relay configuration."),
784 ),
785);
786​
787const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
788 function* (dependencies: CloudHttpDependencies) {
789 yield* requireEnvironmentScope(AuthRelayWriteScope);
790 const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null);
791 yield* Effect.all(
792 [
793 dependencies.secrets.remove(CLOUD_LINKED_USER_ID),
794 dependencies.secrets.remove(RELAY_URL_SECRET),
795 dependencies.secrets.remove(RELAY_ISSUER_SECRET),
796 dependencies.secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
797 dependencies.secrets.remove(CLOUD_MINT_PUBLIC_KEY),
798 dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),
799 dependencies.secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),
800 ],
801 { concurrency: 7 },
802 );
803 yield* setCliDesiredCloudLink(false);
804 return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
805 },
806 Effect.catchIf(
807 ServerSecretStore.isSecretStoreError,
808 failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
809 ),
810);
811​
812const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
813 function* (
814 dependencies: CloudHttpDependencies,
815 payload: { readonly publishAgentActivity: boolean },
816 ) {
817 yield* requireEnvironmentScope(AuthRelayWriteScope);
818 yield* dependencies.secrets.set(
819 PUBLISH_AGENT_ACTIVITY_SECRET,
820 stringToBytes(String(payload.publishAgentActivity)),
821 );
822 return yield* readCloudLinkState(dependencies);
823 },
824 Effect.catchIf(
825 ServerSecretStore.isSecretStoreError,
826 failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
827 ),
828);
829​
830const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
831 function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {
832 const cloudMintPublicKey = yield* dependencies.secrets
833 .get(CLOUD_MINT_PUBLIC_KEY)
834 .pipe(
835 Effect.flatMap((bytes) =>
836 Option.isSome(bytes)
837 ? Effect.succeed(bytesToString(bytes.value))
838 : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
839 ),
840 );
841 const relayIssuer = yield* dependencies.secrets
842 .get(RELAY_ISSUER_SECRET)
843 .pipe(
844 Effect.flatMap((bytes) =>
845 Option.isSome(bytes)
846 ? Effect.succeed(bytesToString(bytes.value))
847 : dependencies.secrets
848 .get(RELAY_URL_SECRET)
849 .pipe(
850 Effect.flatMap((fallbackBytes) =>
851 Option.isSome(fallbackBytes)
852 ? Effect.succeed(bytesToString(fallbackBytes.value))
853 : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
854 ),
855 ),
856 ),
857 );
858 const environmentId = yield* dependencies.environment.getEnvironmentId;
859 const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
860 const now = yield* DateTime.now;
861 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
862 const proofOption = yield* verifyRelayJwt({
863 publicKey: cloudMintPublicKey,
864 token: request.proof,
865 typ: RELAY_HEALTH_REQUEST_TYP,
866 issuer: normalizeRelayIssuer(relayIssuer),
867 audience: `t3-env:${environmentId}`,
868 nowEpochSeconds: nowSeconds,
869 }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);
870 if (
871 Option.isNone(proofOption) ||
872 proofOption.value.environmentId !== environmentId ||
873 proofOption.value.sub !== linkedCloudUserId ||
874 !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
875 !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
876 ) {
877 return yield* new EnvironmentHttpUnauthorizedError({
878 message: "Invalid cloud health request.",
879 });
880 }
881 const proof = proofOption.value;
882​
883 const jtiSecretName = `${CLOUD_HEALTH_JTI_PREFIX}${proof.jti}`;
884 const nonceSecretName = `${CLOUD_HEALTH_NONCE_PREFIX}${proof.nonce}`;
885 const consumedReplayGuards = yield* consumeCloudReplayGuards({
886 secrets: dependencies.secrets,
887 names: [jtiSecretName, nonceSecretName],
888 value: stringToBytes(DateTime.formatIso(now)),
889 });
890 if (!consumedReplayGuards) {
891 return yield* new EnvironmentHttpConflictError({
892 message: "Cloud health request was already consumed.",
893 });
894 }
895​
896 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
897 const descriptor = yield* dependencies.environment.getDescriptor;
898 const responseExpiresAt = DateTime.add(now, { minutes: 5 });
899 const responsePayload = {
900 iss: `t3-env:${environmentId}`,
901 aud: normalizeRelayIssuer(relayIssuer),
902 sub: environmentId,
903 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
904 iat: nowSeconds,
905 exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),
906 environmentId,
907 requestNonce: proof.nonce,
908 status: "online",
909 descriptor,
910 checkedAt: DateTime.formatIso(now),
911 } satisfies RelayEnvironmentHealthResponseProofPayload;
912 const responseProof = yield* signRelayJwt({
913 privateKey: keyPair.privateKey,
914 typ: RELAY_HEALTH_RESPONSE_TYP,
915 payload: responsePayload,
916 }).pipe(
917 Effect.mapError(
918 (cause) =>
919 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
920 cause,
921 }),
922 ),
923 );
924 const response = {
925 environmentId,
926 status: "online",
927 descriptor,
928 checkedAt: responsePayload.checkedAt,
929 proof: responseProof,
930 } satisfies RelayEnvironmentHealthResponseShape;
931​
932 yield* appendCloudCredentialResponseHeaders;
933 return response;
934 },
935 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
936 failEnvironmentCloudInternalError(error.message)(error),
937 ),
938 Effect.catchIf(
939 ServerSecretStore.isSecretStoreError,
940 failEnvironmentCloudInternalError("Could not answer cloud health request."),
941 ),
942 Effect.catchTag(
943 "PlatformError",
944 failEnvironmentCloudInternalError("Could not answer cloud health request."),
945 ),
946);
947​
948const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
949 function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {
950 const cloudMintPublicKey = yield* dependencies.secrets
951 .get(CLOUD_MINT_PUBLIC_KEY)
952 .pipe(
953 Effect.flatMap((bytes) =>
954 Option.isSome(bytes)
955 ? Effect.succeed(bytesToString(bytes.value))
956 : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
957 ),
958 );
959 const relayIssuer = yield* dependencies.secrets
960 .get(RELAY_ISSUER_SECRET)
961 .pipe(
962 Effect.flatMap((bytes) =>
963 Option.isSome(bytes)
964 ? Effect.succeed(bytesToString(bytes.value))
965 : dependencies.secrets
966 .get(RELAY_URL_SECRET)
967 .pipe(
968 Effect.flatMap((fallbackBytes) =>
969 Option.isSome(fallbackBytes)
970 ? Effect.succeed(bytesToString(fallbackBytes.value))
971 : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
972 ),
973 ),
974 ),
975 );
976 const environmentId = yield* dependencies.environment.getEnvironmentId;
977 const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
978 const now = yield* DateTime.now;
979 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
980 const proofOption = yield* verifyRelayJwt({
981 publicKey: cloudMintPublicKey,
982 token: request.proof,
983 typ: RELAY_MINT_REQUEST_TYP,
984 issuer: normalizeRelayIssuer(relayIssuer),
985 audience: `t3-env:${environmentId}`,
986 nowEpochSeconds: nowSeconds,
987 }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);
988 if (
989 Option.isNone(proofOption) ||
990 proofOption.value.environmentId !== environmentId ||
991 proofOption.value.sub !== linkedCloudUserId ||
992 proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint ||
993 !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
994 !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
995 ) {
996 return yield* new EnvironmentHttpUnauthorizedError({
997 message: "Invalid cloud mint request.",
998 });
999 }
1000 const proof = proofOption.value;
1001​
1002 const jtiSecretName = `${CLOUD_MINT_JTI_PREFIX}${proof.jti}`;
1003 const nonceSecretName = `${CLOUD_MINT_NONCE_PREFIX}${proof.nonce}`;
1004 const consumedReplayGuards = yield* consumeCloudReplayGuards({
1005 secrets: dependencies.secrets,
1006 names: [jtiSecretName, nonceSecretName],
1007 value: stringToBytes(DateTime.formatIso(now)),
1008 });
1009 if (!consumedReplayGuards) {
1010 return yield* new EnvironmentHttpConflictError({
1011 message: "Cloud mint request was already consumed.",
1012 });
1014​
1015 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
1016 const issued = yield* dependencies.environmentAuth.createPairingLink({
1017 scopes: AuthStandardClientScopes,
1018 subject: "cloud-connect",
1019 ttl: Duration.minutes(2),
1020 label: "T3 Connect connect",
1021 proofKeyThumbprint: proof.clientProofKeyThumbprint,
1022 });
1023 const responsePayload = {
1024 iss: `t3-env:${environmentId}`,
1025 aud: normalizeRelayIssuer(relayIssuer),
1026 sub: environmentId,
1027 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
1028 iat: nowSeconds,
1029 exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000),
1030 environmentId,
1031 clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
1032 requestNonce: proof.nonce,
1033 credential: issued.credential,
1034 } satisfies RelayEnvironmentMintResponseProofPayload;
1035 const responseProof = yield* signRelayJwt({
1036 privateKey: keyPair.privateKey,
1037 typ: RELAY_MINT_RESPONSE_TYP,
1038 payload: responsePayload,
1039 }).pipe(
1040 Effect.mapError(
1041 (cause) =>
1042 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
1043 cause,
1044 }),
1045 ),
1046 );
1047 const response = {
1048 credential: issued.credential,
1049 expiresAt: DateTime.formatIso(issued.expiresAt),
1050 proof: responseProof,
1051 } satisfies RelayEnvironmentMintResponseShape;
1052​
1053 yield* appendCloudCredentialResponseHeaders;
1054 return response;
1055 },
1056 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
1057 failEnvironmentCloudInternalError(error.message)(error),
1058 ),
1059 Effect.catchIf(
1060 ServerSecretStore.isSecretStoreError,
1061 failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
1062 ),
1063 Effect.catchTag(
1064 "PlatformError",
1065 failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
1066 ),
1068​
1069export const connectHttpApiLayer = HttpApiBuilder.group(
1070 EnvironmentHttpApi,
1071 "connect",
1072 Effect.fnUntraced(function* (handlers) {
1073 const dependencies = yield* cloudHttpDependencies;
1074 return handlers
1075 .handle("linkProof", ({ payload }) => cloudLinkProofHandler(dependencies, payload))
1076 .handle("relayConfig", ({ payload }) => cloudRelayConfigHandler(dependencies, payload))
1077 .handle("linkState", () => cloudLinkStateHandler(dependencies))
1078 .handle("unlink", () => cloudUnlinkHandler(dependencies))
1079 .handle("preferences", ({ payload }) => cloudPreferencesHandler(dependencies, payload))
1080 .handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))
1081 .handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))
1082 .handle("t3MintCredential", ({ payload }) =>
1083 traceRelayRequest(cloudMintCredentialHandler(dependencies, payload)),
1084 );
1085 }),