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