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

http.ts

959 lines33.9 KB

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