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

EnvironmentLinker.ts

360 lines12.5 KB

1import {
2 RelayEnvironmentLinkProofPayload,
3 RelayEnvironmentLinkProofInvalidReason,
4 type RelayEnvironmentLinkRequest,
5} from "@t3tools/contracts/relay";
6import {
7 decodeRelayJwt,
8 normalizeRelayIssuer,
9 RELAY_LINK_PROOF_TYP,
10 verifyRelayJwt,
11} from "@t3tools/shared/relayJwt";
12import * as Context from "effect/Context";
13import * as Signature from "effect/crypto/Signature";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Schema from "effect/Schema";
18import * as SqlError from "effect/sql/SqlError";
19​
20import * as DpopProofs from "../auth/DpopProofs.ts";
21import * as RelayTokens from "../auth/RelayTokens.ts";
22import * as RelayDb from "../db.ts";
23import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
24import * as EnvironmentLinks from "./EnvironmentLinks.ts";
25import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
26import * as RelayConfiguration from "../Config.ts";
27​
28export class EnvironmentLinkProofExpired extends Schema.TaggedError<EnvironmentLinkProofExpired>()(
29 "EnvironmentLinkProofExpired",
30 {
31 userId: Schema.String,
32 environmentId: Schema.String,
33 expiresAt: Schema.String,
34 },
35) {
36 override get message(): string {
37 return `Environment '${this.environmentId}' link proof expired at ${this.expiresAt}`;
38 }
40​
41export class EnvironmentLinkProofInvalid extends Schema.TaggedError<EnvironmentLinkProofInvalid>()(
42 "EnvironmentLinkProofInvalid",
43 {
44 userId: Schema.String,
45 environmentId: Schema.String,
46 reason: RelayEnvironmentLinkProofInvalidReason,
47 stage: Schema.Literals([
48 "decode_token",
49 "decode_payload",
50 "verify_proof",
51 "authorize_capabilities",
52 "validate_descriptor",
53 "verify_challenge",
54 "validate_expiration",
55 "consume_proof_nonce",
56 "consume_challenge_nonce",
57 "validate_origin",
58 "validate_endpoint",
59 ]),
60 cause: Schema.optional(Schema.Defect()),
61 },
62) {
63 override get message(): string {
64 return `Environment '${this.environmentId}' link proof is invalid during ${this.stage}: ${this.reason}`;
65 }
67​
68export type EnvironmentLinkError =
69 | EnvironmentLinkProofExpired
70 | EnvironmentLinkProofInvalid
71 | DpopProofs.DpopProofReplayPersistenceError
72 | EnvironmentLinks.EnvironmentLinkUpsertPersistenceError
73 | EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError
74 | ManagedEndpointProvider.ManagedEndpointProviderError;
75​
76export class EnvironmentLinker extends Context.Service<
77 EnvironmentLinker,
78 {
79 readonly link: (input: {
80 readonly userId: string;
81 readonly request: RelayEnvironmentLinkRequest;
82 }) => Effect.Effect<
83 {
84 readonly environmentId: RelayEnvironmentLinkProofPayload["environmentId"];
85 readonly endpoint: RelayEnvironmentLinkProofPayload["endpoint"];
86 readonly endpointRuntime:
87 | ManagedEndpointProvider.ManagedEndpointProvisioningResult["runtime"]
88 | null;
89 readonly environmentCredential: string;
90 },
91 EnvironmentLinkError
92 >;
93 }
94>()("t3code-relay/environments/EnvironmentLinker") {}
95​
96const decodeProof = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);
97​
98function proofAuthorizesRequestedCapabilities(
99 proof: RelayEnvironmentLinkProofPayload,
100 request: RelayEnvironmentLinkRequest,
101): boolean {
102 const scopes = new Set(proof.scopes);
103 if (request.managedTunnelsEnabled && !scopes.has("managed_tunnels")) {
104 return false;
105 }
106 return !(
107 (request.notificationsEnabled || request.liveActivitiesEnabled) &&
108 !scopes.has("agent_activity_notifications")
109 );
111​
112function isSecureManagedEndpoint(endpoint: RelayEnvironmentLinkProofPayload["endpoint"]): boolean {
113 try {
114 const httpUrl = new URL(endpoint.httpBaseUrl);
115 const wsUrl = new URL(endpoint.wsBaseUrl);
116 return httpUrl.protocol === "https:" && wsUrl.protocol === "wss:";
117 } catch {
118 return false;
119 }
121​
122function normalizeHostname(hostname: string): string {
123 return hostname
124 .trim()
125 .toLowerCase()
126 .replace(/^\[(.*)\]$/u, "$1");
128​
129function isLoopbackManagedTunnelOrigin(
130 origin: RelayEnvironmentLinkProofPayload["origin"],
131): boolean {
132 const hostname = normalizeHostname(origin.localHttpHost);
133 return (
134 (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
135 Number.isInteger(origin.localHttpPort) &&
136 origin.localHttpPort > 0 &&
137 origin.localHttpPort <= 65_535
138 );
140​
141const make = Effect.gen(function* () {
142 const links = yield* EnvironmentLinks.EnvironmentLinks;
143 const transactions = yield* RelayDb.RelayTransactions;
144 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
145 const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
146 const proofReplay = yield* DpopProofs.DpopProofReplay;
147 const relayTokens = yield* RelayTokens.RelayTokens;
148 const config = yield* RelayConfiguration.RelayConfiguration;
149 const signature = yield* Signature.Signature;
150​
151 return EnvironmentLinker.of({
152 link: Effect.fn("relay.environment_linker.link")(function* (input) {
153 const now = yield* DateTime.now;
154 const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
155 const unverified = yield* decodeRelayJwt(input.request.proof).pipe(
156 Effect.mapError(
157 (cause) =>
158 new EnvironmentLinkProofInvalid({
159 userId: input.userId,
160 environmentId: "unknown",
161 reason: "invalid_signature_or_scope",
162 stage: "decode_token",
163 cause,
164 }),
165 ),
166 );
167 const candidate = yield* decodeProof(unverified).pipe(
168 Effect.mapError(
169 (cause) =>
170 new EnvironmentLinkProofInvalid({
171 userId: input.userId,
172 environmentId: "unknown",
173 reason: "invalid_signature_or_scope",
174 stage: "decode_payload",
175 cause,
176 }),
177 ),
178 );
179 yield* Effect.annotateCurrentSpan({
180 "relay.environment_id": candidate.environmentId,
181 "relay.link.notifications_enabled": input.request.notificationsEnabled,
182 "relay.link.live_activities_enabled": input.request.liveActivitiesEnabled,
183 "relay.link.managed_tunnels_enabled": input.request.managedTunnelsEnabled,
184 });
185 if (candidate.exp <= nowSeconds) {
186 return yield* new EnvironmentLinkProofExpired({
187 userId: input.userId,
188 environmentId: candidate.environmentId,
189 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(candidate.exp * 1_000)),
190 });
191 }
192 const issuer = `t3-env:${candidate.environmentId}`;
193 const relayIssuer = normalizeRelayIssuer(config.relayIssuer);
194 const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, {
195 publicKey: candidate.environmentPublicKey,
196 token: input.request.proof,
197 typ: RELAY_LINK_PROOF_TYP,
198 issuer,
199 audience: relayIssuer,
200 }).pipe(
201 Effect.provideService(Signature.Signature, signature),
202 Effect.mapError(
203 (cause) =>
204 new EnvironmentLinkProofInvalid({
205 userId: input.userId,
206 environmentId: candidate.environmentId,
207 reason: "invalid_signature_or_scope",
208 stage: "verify_proof",
209 cause,
210 }),
211 ),
212 );
213 if (
214 verified.sub !== verified.environmentId ||
215 !proofAuthorizesRequestedCapabilities(verified, input.request)
216 ) {
217 return yield* new EnvironmentLinkProofInvalid({
218 userId: input.userId,
219 environmentId: candidate.environmentId,
220 reason: "invalid_signature_or_scope",
221 stage: "authorize_capabilities",
222 });
223 }
224 if (verified.descriptor.environmentId !== verified.environmentId) {
225 return yield* new EnvironmentLinkProofInvalid({
226 userId: input.userId,
227 environmentId: verified.environmentId,
228 reason: "descriptor_mismatch",
229 stage: "validate_descriptor",
230 });
231 }
232 const challenge = yield* relayTokens.verifyLinkChallenge({
233 token: verified.challenge,
234 userId: input.userId,
235 request: {
236 notificationsEnabled: input.request.notificationsEnabled,
237 liveActivitiesEnabled: input.request.liveActivitiesEnabled,
238 managedTunnelsEnabled: input.request.managedTunnelsEnabled,
239 },
240 });
241 if (challenge === null) {
242 return yield* new EnvironmentLinkProofInvalid({
243 userId: input.userId,
244 environmentId: verified.environmentId,
245 reason: "challenge_invalid",
246 stage: "verify_challenge",
247 });
248 }
249 const expiresAt = DateTime.make(verified.exp * 1_000);
250 if (expiresAt._tag === "None") {
251 return yield* new EnvironmentLinkProofInvalid({
252 userId: input.userId,
253 environmentId: verified.environmentId,
254 reason: "invalid_signature_or_scope",
255 stage: "validate_expiration",
256 });
257 }
258 const consumedNonce = yield* proofReplay.consume({
259 thumbprint: verified.environmentPublicKey,
260 jti: verified.jti,
261 iat: verified.iat,
262 expiresAt: expiresAt.value,
263 });
264 if (!consumedNonce) {
265 return yield* new EnvironmentLinkProofInvalid({
266 userId: input.userId,
267 environmentId: verified.environmentId,
268 reason: "replayed_nonce",
269 stage: "consume_proof_nonce",
270 });
271 }
272 const consumedChallenge = yield* proofReplay.consume({
273 thumbprint: "relay-environment-link-challenge",
274 jti: challenge.jti,
275 iat: challenge.iat,
276 expiresAt: expiresAt.value,
277 });
278 if (!consumedChallenge) {
279 return yield* new EnvironmentLinkProofInvalid({
280 userId: input.userId,
281 environmentId: verified.environmentId,
282 reason: "challenge_invalid",
283 stage: "consume_challenge_nonce",
284 });
285 }
286 if (input.request.managedTunnelsEnabled && !isLoopbackManagedTunnelOrigin(verified.origin)) {
287 return yield* new EnvironmentLinkProofInvalid({
288 userId: input.userId,
289 environmentId: verified.environmentId,
290 reason: "origin_not_allowed",
291 stage: "validate_origin",
292 });
293 }
294 // Non-tunnel links must release provisioned tunnel/DNS resources; best-effort deprovision is idempotent.
295 if (!input.request.managedTunnelsEnabled) {
296 yield* managedEndpointProvider
297 .deprovision({
298 userId: input.userId,
299 environmentId: verified.environmentId,
300 })
301 .pipe(
302 Effect.tapError((error) =>
303 Effect.logWarning("managed endpoint deprovision on publish-only link failed", {
304 environmentId: verified.environmentId,
305 errorTag: error._tag,
306 }),
307 ),
308 Effect.ignore,
309 );
310 }
311 const provisioned = input.request.managedTunnelsEnabled
312 ? yield* managedEndpointProvider.provision({
313 userId: input.userId,
314 environmentId: verified.environmentId,
315 origin: verified.origin,
316 })
317 : null;
318 const endpoint = provisioned?.endpoint ?? verified.endpoint;
319 // Only advertised managed endpoints need secure URLs; publish-only links route out of band.
320 if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) {
321 return yield* new EnvironmentLinkProofInvalid({
322 userId: input.userId,
323 environmentId: verified.environmentId,
324 reason: "endpoint_not_secure",
325 stage: "validate_endpoint",
326 });
327 }
328 const environmentCredential = yield* transactions
329 .withTransaction(
330 links.upsert({ ...input, proof: verified, endpoint }).pipe(
331 Effect.andThen(
332 credentials.create({
333 environmentId: verified.environmentId,
334 environmentPublicKey: verified.environmentPublicKey,
335 }),
336 ),
337 ),
338 )
339 .pipe(
340 Effect.mapError((cause) =>
341 SqlError.isSqlError(cause)
342 ? new EnvironmentLinks.EnvironmentLinkUpsertPersistenceError({
343 userId: input.userId,
344 environmentId: verified.environmentId,
345 cause,
346 })
347 : cause,
348 ),
349 );
350 return {
351 environmentId: verified.environmentId,
352 endpoint,
353 endpointRuntime: provisioned?.runtime ?? null,
354 environmentCredential,
355 };
356 }),
357 });
358});
359​
360export const layer = Layer.effect(EnvironmentLinker, make);