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

http.ts

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