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

http.ts

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