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