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 { 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
302function providerKindMatchesRequestedLinkScopes(request: RelayLinkProofRequest): boolean {
303 return request.endpoint.providerKind === "cloudflare_tunnel";
304}
305
306function hasExactScope(input: {
307 readonly scopes: ReadonlyArray<string>;
308 readonly expected: string;
309}): boolean {
310 return input.scopes.length === 1 && input.scopes[0] === input.expected;
311}
312
313function hasBoundedCloudProofLifetime(input: {
314 readonly iat: number;
315 readonly exp: number;
316 readonly nowSeconds: number;
317}): boolean {
318 return (
319 input.exp > input.iat &&
320 input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS &&
321 input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS
322 );
323}
324
325const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);
326const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
327
328interface CloudHttpDependencies {
329 readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
330 readonly environment: ServerEnvironment.ServerEnvironment["Service"];
331 readonly endpointRuntime: ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"];
332 readonly environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"];
333 readonly cliTokenManager: CliTokenManager.CloudCliTokenManager["Service"];
334 readonly httpClient: HttpClient.HttpClient;
335}
336
337const cloudHttpDependencies = Effect.gen(function* () {
338 return {
339 secrets: yield* ServerSecretStore.ServerSecretStore,
340 environment: yield* ServerEnvironment.ServerEnvironment,
341 endpointRuntime: yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime,
342 environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,
343 cliTokenManager: yield* CliTokenManager.CloudCliTokenManager,
344 httpClient: yield* HttpClient.HttpClient,
345 } satisfies CloudHttpDependencies;
346});
347
348const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
349 dependencies: CloudHttpDependencies,
350 request: RelayLinkProofRequest,
351 requestUrl: string,
352) {
353 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
354 if (
355 !providerKindMatchesRequestedLinkScopes(request) ||
356 !isAllowedEndpointOrigin({
357 origin: request.origin,
358 requestUrl,
359 })
360 ) {
361 return yield* new EnvironmentHttpBadRequestError({
362 message: "Invalid managed endpoint origin.",
363 });
364 }
365 const now = yield* DateTime.now;
366 const expiresAt = DateTime.add(now, { minutes: 5 });
367 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
368 const descriptor = yield* dependencies.environment.getDescriptor;
369 const payload = {
370 iss: `t3-env:${descriptor.environmentId}`,
371 aud: normalizeRelayIssuer(request.relayIssuer),
372 sub: descriptor.environmentId,
373 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
374 iat: nowSeconds,
375 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
376 challenge: request.challenge,
377 descriptor,
378 environmentId: descriptor.environmentId,
379 environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
380 endpoint: request.endpoint,
381 origin: request.origin,
382 scopes: ["agent_activity_notifications", "managed_tunnels"],
383 } satisfies RelayEnvironmentLinkProofPayload;
384 return yield* signRelayJwt({
385 privateKey: keyPair.privateKey,
386 typ: RELAY_LINK_PROOF_TYP,
387 payload,
388 }).pipe(
389 Effect.mapError(
390 (cause) =>
391 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
392 cause,
393 }),
394 ),
395 );
396});
397
398const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
399 function* (dependencies: CloudHttpDependencies, request: RelayLinkProofRequest) {
400 yield* requireEnvironmentScope(AuthRelayWriteScope);
401 const httpRequest = yield* HttpServerRequest.HttpServerRequest;
402 const requestUrl = requestAbsoluteUrl(httpRequest);
403 if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
404 return yield* new EnvironmentHttpBadRequestError({
405 message: "Invalid managed endpoint origin.",
406 });
407 }
408 const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
409 yield* appendCloudCredentialResponseHeaders;
410 return proof satisfies RelayEnvironmentLinkProof;
411 },
412 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
413 failEnvironmentCloudInternalError(error.message)(error),
414 ),
415 Effect.catchIf(
416 ServerSecretStore.isSecretStoreError,
417 failEnvironmentCloudInternalError("Could not generate environment link proof."),
418 ),
419 Effect.catchTag(
420 "PlatformError",
421 failEnvironmentCloudInternalError("Could not generate environment link proof."),
422 ),
423);
424
425const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
426 dependencies: CloudHttpDependencies,
427 payload: RelayEnvironmentConfigRequest,
428) {
429 yield* validateRelayConfigPayload(payload);
430 yield* validateLinkedCloudUser({
431 secrets: dependencies.secrets,
432 cloudUserId: payload.cloudUserId,
433 });
434 yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
435 const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(
436 payload.endpointRuntime,
437 );
438 const ok =
439 endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
440 if (!ok) {
441 return yield* new EnvironmentCloudEndpointUnavailableError({
442 message: "Managed endpoint runtime could not be started.",
443 endpointRuntimeStatus,
444 });
445 }
446
447 yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));
448 yield* dependencies.secrets.set(
449 RELAY_ISSUER_SECRET,
450 stringToBytes(payload.relayIssuer ?? payload.relayUrl),
451 );
452 yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));
453 yield* dependencies.secrets.set(
454 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
455 stringToBytes(payload.environmentCredential),
456 );
457 yield* dependencies.secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey));
458 if (payload.endpointRuntime) {
459 const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime);
460 yield* dependencies.secrets.set(
461 CLOUD_ENDPOINT_RUNTIME_CONFIG,
462 stringToBytes(endpointRuntimeJson),
463 );
464 } else {
465 yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
466 }
467 return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
468});
469
470const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
471 function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) {
472 yield* requireEnvironmentScope(AuthRelayWriteScope);
473 return yield* applyCloudRelayConfig(dependencies, payload);
474 },
475 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
476 failEnvironmentCloudInternalError(error.message)(error),
477 ),
478 Effect.catchIf(
479 ServerSecretStore.isSecretStoreError,
480 failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
481 ),
482 Effect.catchTag(
483 "SchemaError",
484 failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
485 ),
486);
487
488const relayClientRequest = <A>(
489 dependencies: CloudHttpDependencies,
490 input: {
491 readonly url: string;
492 readonly token: string;
493 readonly payload: unknown;
494 readonly schema: Schema.Decoder<A>;
495 },
496) =>
497 HttpClientRequest.post(input.url).pipe(
498 HttpClientRequest.bearerToken(input.token),
499 HttpClientRequest.bodyJson(input.payload),
500 Effect.flatMap(dependencies.httpClient.execute),
501 Effect.flatMap(HttpClientResponse.filterStatusOk),
502 Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
503 Effect.mapError(
504 (cause) =>
505 new EnvironmentHttpInternalServerError({
506 message: `T3 Connect relay request failed: ${String(cause)}`,
507 }),
508 ),
509 withRelayClientTracing,
510 );
511
512const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")(
513 function* (dependencies: CloudHttpDependencies, localOrigin: string) {
514 const localUrl = yield* Effect.try({
515 try: () => new URL(localOrigin),
516 catch: () =>
517 new EnvironmentHttpBadRequestError({
518 message: "Could not resolve local environment origin.",
519 }),
520 });
521 if (localUrl.origin !== localOrigin) {
522 return yield* new EnvironmentHttpBadRequestError({
523 message: "Could not resolve local environment origin.",
524 });
525 }
526 const localWsOrigin = localOrigin.replace(/^http/u, "ws");
527 const token = yield* dependencies.cliTokenManager.getExisting.pipe(
528 Effect.flatMap(
529 Option.match({
530 onNone: () =>
531 Effect.fail(
532 new EnvironmentHttpUnauthorizedError({
533 message: "Run `t3 connect link` to authorize this environment.",
534 }),
535 ),
536 onSome: Effect.succeed,
537 }),
538 ),
539 );
540 const relayUrl = yield* requireRelayUrl;
541 const challenge = yield* relayClientRequest(dependencies, {
542 url: `${relayUrl}/v1/client/environment-link-challenges`,
543 token: token.accessToken,
544 payload: {
545 notificationsEnabled: true,
546 liveActivitiesEnabled: true,
547 managedTunnelsEnabled: true,
548 },
549 schema: RelayEnvironmentLinkChallengeResponse,
550 });
551 const proof = yield* makeCloudLinkProof(
552 dependencies,
553 {
554 challenge: challenge.challenge,
555 relayIssuer: relayUrl,
556 endpoint: {
557 httpBaseUrl: localOrigin,
558 wsBaseUrl: localWsOrigin,
559 providerKind: "cloudflare_tunnel",
560 },
561 origin: {
562 localHttpHost: localUrl.hostname,
563 localHttpPort: endpointRequestPort(localUrl),
564 },
565 },
566 localOrigin,
567 );
568 const link = yield* relayClientRequest(dependencies, {
569 url: `${relayUrl}/v1/client/environment-links`,
570 token: token.accessToken,
571 payload: {
572 proof,
573 notificationsEnabled: true,
574 liveActivitiesEnabled: true,
575 managedTunnelsEnabled: true,
576 },
577 schema: RelayEnvironmentLinkResponse,
578 });
579 yield* setCliDesiredCloudLink(true);
580 return yield* applyCloudRelayConfig(dependencies, {
581 relayUrl,
582 relayIssuer: link.relayIssuer,
583 cloudUserId: link.cloudUserId,
584 environmentCredential: link.environmentCredential,
585 cloudMintPublicKey: link.cloudMintPublicKey,
586 endpointRuntime: link.endpointRuntime,
587 });
588 },
589 Effect.catchIf(
590 ServerSecretStore.isSecretStoreError,
591 failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
592 ),
593 Effect.catchTags({
594 CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
595 CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
596 CloudCliCredentialReadError: failCloudCliTokenManagerError,
597 CloudCliAuthorizationError: failCloudCliTokenManagerError,
598 CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
599 }),
600);
601
602export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileDesiredLink")(
603 function* (localOrigin: string) {
604 return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);
605 },
606);
607
608const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
609 dependencies: CloudHttpDependencies,
610) {
611 const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all(
612 [
613 dependencies.secrets.get(CLOUD_LINKED_USER_ID),
614 dependencies.secrets.get(RELAY_URL_SECRET),
615 dependencies.secrets.get(RELAY_ISSUER_SECRET),
616 dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
617 ],
618 { concurrency: 4 },
619 );
620 return {
621 linked: Option.isSome(cloudUserId),
622 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
623 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
624 relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,
625 publishAgentActivity: Option.isSome(publishAgentActivity)
626 ? bytesToString(publishAgentActivity.value) === "true"
627 : false,
628 } satisfies EnvironmentCloudLinkStateResult;
629});
630
631const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
632 function* (dependencies: CloudHttpDependencies) {
633 yield* requireEnvironmentScope(AuthRelayReadScope);
634 return yield* readCloudLinkState(dependencies);
635 },
636 Effect.catchIf(
637 ServerSecretStore.isSecretStoreError,
638 failEnvironmentCloudInternalError("Could not read environment relay configuration."),
639 ),
640);
641
642const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
643 function* (dependencies: CloudHttpDependencies) {
644 yield* requireEnvironmentScope(AuthRelayWriteScope);
645 const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null);
646 yield* Effect.all(
647 [
648 dependencies.secrets.remove(CLOUD_LINKED_USER_ID),
649 dependencies.secrets.remove(RELAY_URL_SECRET),
650 dependencies.secrets.remove(RELAY_ISSUER_SECRET),
651 dependencies.secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
652 dependencies.secrets.remove(CLOUD_MINT_PUBLIC_KEY),
653 dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),
654 dependencies.secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),
655 ],
656 { concurrency: 7 },
657 );
658 yield* setCliDesiredCloudLink(false);
659 return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
660 },
661 Effect.catchIf(
662 ServerSecretStore.isSecretStoreError,
663 failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
664 ),
665);
666
667const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
668 function* (
669 dependencies: CloudHttpDependencies,
670 payload: { readonly publishAgentActivity: boolean },
671 ) {
672 yield* requireEnvironmentScope(AuthRelayWriteScope);
673 yield* dependencies.secrets.set(
674 PUBLISH_AGENT_ACTIVITY_SECRET,
675 stringToBytes(String(payload.publishAgentActivity)),
676 );
677 return yield* readCloudLinkState(dependencies);
678 },
679 Effect.catchIf(
680 ServerSecretStore.isSecretStoreError,
681 failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
682 ),
683);
684
685const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
686 function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {
687 const cloudMintPublicKey = yield* dependencies.secrets
688 .get(CLOUD_MINT_PUBLIC_KEY)
689 .pipe(
690 Effect.flatMap((bytes) =>
691 Option.isSome(bytes)
692 ? Effect.succeed(bytesToString(bytes.value))
693 : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
694 ),
695 );
696 const relayIssuer = yield* dependencies.secrets
697 .get(RELAY_ISSUER_SECRET)
698 .pipe(
699 Effect.flatMap((bytes) =>
700 Option.isSome(bytes)
701 ? Effect.succeed(bytesToString(bytes.value))
702 : dependencies.secrets
703 .get(RELAY_URL_SECRET)
704 .pipe(
705 Effect.flatMap((fallbackBytes) =>
706 Option.isSome(fallbackBytes)
707 ? Effect.succeed(bytesToString(fallbackBytes.value))
708 : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
709 ),
710 ),
711 ),
712 );
713 const environmentId = yield* dependencies.environment.getEnvironmentId;
714 const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
715 const now = yield* DateTime.now;
716 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
717 const proofOption = yield* verifyRelayJwt({
718 publicKey: cloudMintPublicKey,
719 token: request.proof,
720 typ: RELAY_HEALTH_REQUEST_TYP,
721 issuer: normalizeRelayIssuer(relayIssuer),
722 audience: `t3-env:${environmentId}`,
723 nowEpochSeconds: nowSeconds,
724 }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);
725 if (
726 Option.isNone(proofOption) ||
727 proofOption.value.environmentId !== environmentId ||
728 proofOption.value.sub !== linkedCloudUserId ||
729 !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
730 !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
731 ) {
732 return yield* new EnvironmentHttpUnauthorizedError({
733 message: "Invalid cloud health request.",
734 });
735 }
736 const proof = proofOption.value;
737
738 const jtiSecretName = `${CLOUD_HEALTH_JTI_PREFIX}${proof.jti}`;
739 const nonceSecretName = `${CLOUD_HEALTH_NONCE_PREFIX}${proof.nonce}`;
740 const consumedReplayGuards = yield* consumeCloudReplayGuards({
741 secrets: dependencies.secrets,
742 names: [jtiSecretName, nonceSecretName],
743 value: stringToBytes(DateTime.formatIso(now)),
744 });
745 if (!consumedReplayGuards) {
746 return yield* new EnvironmentHttpConflictError({
747 message: "Cloud health request was already consumed.",
748 });
749 }
750
751 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
752 const descriptor = yield* dependencies.environment.getDescriptor;
753 const responseExpiresAt = DateTime.add(now, { minutes: 5 });
754 const responsePayload = {
755 iss: `t3-env:${environmentId}`,
756 aud: normalizeRelayIssuer(relayIssuer),
757 sub: environmentId,
758 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
759 iat: nowSeconds,
760 exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),
761 environmentId,
762 requestNonce: proof.nonce,
763 status: "online",
764 descriptor,
765 checkedAt: DateTime.formatIso(now),
766 } satisfies RelayEnvironmentHealthResponseProofPayload;
767 const responseProof = yield* signRelayJwt({
768 privateKey: keyPair.privateKey,
769 typ: RELAY_HEALTH_RESPONSE_TYP,
770 payload: responsePayload,
771 }).pipe(
772 Effect.mapError(
773 (cause) =>
774 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
775 cause,
776 }),
777 ),
778 );
779 const response = {
780 environmentId,
781 status: "online",
782 descriptor,
783 checkedAt: responsePayload.checkedAt,
784 proof: responseProof,
785 } satisfies RelayEnvironmentHealthResponseShape;
786
787 yield* appendCloudCredentialResponseHeaders;
788 return response;
789 },
790 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
791 failEnvironmentCloudInternalError(error.message)(error),
792 ),
793 Effect.catchIf(
794 ServerSecretStore.isSecretStoreError,
795 failEnvironmentCloudInternalError("Could not answer cloud health request."),
796 ),
797 Effect.catchTag(
798 "PlatformError",
799 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
806 .get(CLOUD_MINT_PUBLIC_KEY)
807 .pipe(
808 Effect.flatMap((bytes) =>
809 Option.isSome(bytes)
810 ? Effect.succeed(bytesToString(bytes.value))
811 : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
812 ),
813 );
814 const relayIssuer = yield* dependencies.secrets
815 .get(RELAY_ISSUER_SECRET)
816 .pipe(
817 Effect.flatMap((bytes) =>
818 Option.isSome(bytes)
819 ? Effect.succeed(bytesToString(bytes.value))
820 : dependencies.secrets
821 .get(RELAY_URL_SECRET)
822 .pipe(
823 Effect.flatMap((fallbackBytes) =>
824 Option.isSome(fallbackBytes)
825 ? Effect.succeed(bytesToString(fallbackBytes.value))
826 : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
827 ),
828 ),
829 ),
830 );
831 const environmentId = yield* dependencies.environment.getEnvironmentId;
832 const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
833 const now = yield* DateTime.now;
834 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
835 const proofOption = yield* verifyRelayJwt({
836 publicKey: cloudMintPublicKey,
837 token: request.proof,
838 typ: RELAY_MINT_REQUEST_TYP,
839 issuer: normalizeRelayIssuer(relayIssuer),
840 audience: `t3-env:${environmentId}`,
841 nowEpochSeconds: nowSeconds,
842 }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);
843 if (
844 Option.isNone(proofOption) ||
845 proofOption.value.environmentId !== environmentId ||
846 proofOption.value.sub !== linkedCloudUserId ||
847 proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint ||
848 !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
849 !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
850 ) {
851 return yield* new EnvironmentHttpUnauthorizedError({
852 message: "Invalid cloud mint request.",
853 });
854 }
855 const proof = proofOption.value;
856
857 const jtiSecretName = `${CLOUD_MINT_JTI_PREFIX}${proof.jti}`;
858 const nonceSecretName = `${CLOUD_MINT_NONCE_PREFIX}${proof.nonce}`;
859 const consumedReplayGuards = yield* consumeCloudReplayGuards({
860 secrets: dependencies.secrets,
861 names: [jtiSecretName, nonceSecretName],
862 value: stringToBytes(DateTime.formatIso(now)),
863 });
864 if (!consumedReplayGuards) {
865 return yield* new EnvironmentHttpConflictError({
866 message: "Cloud mint request was already consumed.",
867 });
868 }
869
870 const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
871 const issued = yield* dependencies.environmentAuth.createPairingLink({
872 scopes: AuthStandardClientScopes,
873 subject: "cloud-connect",
874 ttl: Duration.minutes(2),
875 label: "T3 Connect connect",
876 proofKeyThumbprint: proof.clientProofKeyThumbprint,
877 });
878 const responsePayload = {
879 iss: `t3-env:${environmentId}`,
880 aud: normalizeRelayIssuer(relayIssuer),
881 sub: environmentId,
882 jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
883 iat: nowSeconds,
884 exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000),
885 environmentId,
886 clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
887 requestNonce: proof.nonce,
888 credential: issued.credential,
889 } satisfies RelayEnvironmentMintResponseProofPayload;
890 const responseProof = yield* signRelayJwt({
891 privateKey: keyPair.privateKey,
892 typ: RELAY_MINT_RESPONSE_TYP,
893 payload: responsePayload,
894 }).pipe(
895 Effect.mapError(
896 (cause) =>
897 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
898 cause,
899 }),
900 ),
901 );
902 const response = {
903 credential: issued.credential,
904 expiresAt: DateTime.formatIso(issued.expiresAt),
905 proof: responseProof,
906 } satisfies RelayEnvironmentMintResponseShape;
907
908 yield* appendCloudCredentialResponseHeaders;
909 return response;
910 },
911 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
912 failEnvironmentCloudInternalError(error.message)(error),
913 ),
914 Effect.catchIf(
915 ServerSecretStore.isSecretStoreError,
916 failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
917 ),
918 Effect.catchTag(
919 "PlatformError",
920 failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
921 ),
922);
923
924export const connectHttpApiLayer = HttpApiBuilder.group(
925 EnvironmentHttpApi,
926 "connect",
927 Effect.fnUntraced(function* (handlers) {
928 const dependencies = yield* cloudHttpDependencies;
929 return handlers
930 .handle("linkProof", ({ payload }) => cloudLinkProofHandler(dependencies, payload))
931 .handle("relayConfig", ({ payload }) => cloudRelayConfigHandler(dependencies, payload))
932 .handle("linkState", () => cloudLinkStateHandler(dependencies))
933 .handle("unlink", () => cloudUnlinkHandler(dependencies))
934 .handle("preferences", ({ payload }) => cloudPreferencesHandler(dependencies, payload))
935 .handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))
936 .handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))
937 .handle("t3MintCredential", ({ payload }) =>
938 traceRelayRequest(cloudMintCredentialHandler(dependencies, payload)),
939 );
940 }),
941);