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

http.ts

161 lines6.0 KB

1import {
2 AuthRelayReadScope,
3 AuthRelayWriteScope,
4 EnvironmentCloudEndpointUnavailableError,
5 EnvironmentHttpApi,
6 EnvironmentHttpBadRequestError,
7 EnvironmentHttpConflictError,
8 EnvironmentHttpForbiddenError,
9 EnvironmentHttpInternalServerError,
10 EnvironmentHttpUnauthorizedError,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as HttpEffect from "effect/http/HttpEffect";
14import { HttpServerRequest, HttpServerResponse } from "effect/http";
15import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
16​
17import { requireEnvironmentScope } from "../auth/http.ts";
18import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
19import * as CloudLink from "./CloudLink.ts";
20import type { RelayRequestError } from "./relayResponse.ts";
21import { traceRelayRequest } from "./traceRelayRequest.ts";
22​
23const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
24 "cache-control": "no-store",
25 pragma: "no-cache",
26} as const;
27​
28const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
29 (_request, response) =>
30 Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
31);
32​
33const internalServerError = (error: { readonly message: string }, cause: unknown) =>
34 Effect.logError(error.message, { cause }).pipe(
35 Effect.andThen(Effect.fail(new EnvironmentHttpInternalServerError({ message: error.message }))),
36 );
37​
38const relayFailure = (error: RelayRequestError) => {
39 const message = error.message;
40 switch (error.rejection) {
41 case "unauthorized":
42 return Effect.fail(new EnvironmentHttpUnauthorizedError({ message }));
43 case "forbidden":
44 return Effect.fail(new EnvironmentHttpForbiddenError({ message }));
45 case "rejected":
46 return Effect.fail(new EnvironmentHttpBadRequestError({ message }));
47 case "unavailable":
48 return Effect.fail(new EnvironmentHttpInternalServerError({ message }));
49 }
50};
51​
52const badRequest = (error: { readonly message: string }) =>
53 Effect.fail(new EnvironmentHttpBadRequestError({ message: error.message }));
54const unauthorized = (error: { readonly message: string }) =>
55 Effect.fail(new EnvironmentHttpUnauthorizedError({ message: error.message }));
56const conflict = (error: { readonly message: string }) =>
57 Effect.fail(new EnvironmentHttpConflictError({ message: error.message }));
58​
59/** How a connect route answers each CloudLink failure. Messages carry through unchanged. */
60const connectErrorCases = {
61 CloudLinkRelayConfigInvalidError: badRequest,
62 CloudLinkOriginInvalidError: badRequest,
63 CloudLinkNotLinkedError: badRequest,
64 CloudLinkAccountMismatchError: conflict,
65 CloudLinkAuthorizationMissingError: unauthorized,
66 CloudLinkProofRejectedError: unauthorized,
67 CloudLinkProofReplayedError: conflict,
68 CloudLinkTunnelSupersededError: conflict,
69 CloudLinkInternalError: (error: CloudLink.CloudLinkInternalError) =>
70 internalServerError(error, error.cause),
71 RelayRequestError: relayFailure,
72} as const;
73​
74type ConnectFailure =
75 | Exclude<CloudLink.CloudLinkError, CloudLink.CloudLinkEndpointUnavailableError>
76 | EnvironmentAuth.ServerAuthInternalError
77 | RelayRequestError;
78​
79/** Internal failures are logged with their cause before the route answers 500. */
80const toHttpError = <A, R>(effect: Effect.Effect<A, ConnectFailure, R>) =>
81 effect.pipe(
82 Effect.catchTags(connectErrorCases),
83 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
84 internalServerError(error, error),
85 ),
86 );
87​
88/** Relay configuration is the one route that answers 503 when the tunnel cannot serve. */
89const toHttpErrorOrUnavailable = <A, R>(
90 effect: Effect.Effect<A, ConnectFailure | CloudLink.CloudLinkEndpointUnavailableError, R>,
91) =>
92 effect.pipe(
93 Effect.catchTags({
94 ...connectErrorCases,
95 CloudLinkEndpointUnavailableError: (error) =>
96 Effect.fail(
97 new EnvironmentCloudEndpointUnavailableError({
98 message: error.message,
99 endpointRuntimeStatus: error.endpointRuntimeStatus,
100 }),
101 ),
102 }),
103 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
104 internalServerError(error, error),
105 ),
106 );
107​
108export const layer = HttpApiBuilder.group(
109 EnvironmentHttpApi,
110 "connect",
111 Effect.fnUntraced(function* (handlers) {
112 const cloudLink = yield* CloudLink.CloudLink;
113 return handlers
114 .handle("linkProof", ({ payload }) =>
115 Effect.gen(function* () {
116 yield* requireEnvironmentScope(AuthRelayWriteScope);
117 const request = yield* HttpServerRequest.HttpServerRequest;
118 const proof = yield* toHttpError(cloudLink.linkProof(payload, request));
119 yield* appendCloudCredentialResponseHeaders;
120 return proof;
121 }),
122 )
123 .handle("relayConfig", ({ payload }) =>
124 requireEnvironmentScope(AuthRelayWriteScope).pipe(
125 Effect.andThen(toHttpErrorOrUnavailable(cloudLink.applyRelayConfig(payload))),
126 ),
127 )
128 .handle("linkState", () =>
129 requireEnvironmentScope(AuthRelayReadScope).pipe(
130 Effect.andThen(toHttpError(cloudLink.linkState())),
131 ),
132 )
133 .handle("unlink", () =>
134 requireEnvironmentScope(AuthRelayWriteScope).pipe(
135 Effect.andThen(toHttpError(cloudLink.unlink())),
136 ),
137 )
138 .handle("preferences", ({ payload }) =>
139 requireEnvironmentScope(AuthRelayWriteScope).pipe(
140 Effect.andThen(toHttpError(cloudLink.updatePreferences(payload))),
141 ),
142 )
143 .handle("health", ({ payload }) =>
144 toHttpError(cloudLink.answerHealthRequest(payload)).pipe(
145 Effect.tap(() => appendCloudCredentialResponseHeaders),
146 ),
147 )
148 .handle("mintCredential", ({ payload }) =>
149 toHttpError(cloudLink.mintCredential(payload)).pipe(
150 Effect.tap(() => appendCloudCredentialResponseHeaders),
151 ),
152 )
153 .handle("t3MintCredential", ({ payload }) =>
154 traceRelayRequest(
155 toHttpError(cloudLink.mintCredential(payload)).pipe(
156 Effect.tap(() => appendCloudCredentialResponseHeaders),
157 ),
158 ),
159 );
160 }),
161);