Open History to see the last commit
1import { createClerkClient, verifyToken } from "@clerk/backend";
2import { sql as drizzleSql } from "drizzle-orm";
3import * as Crypto from "effect/Crypto";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Record from "effect/Record";
10import * as Redacted from "effect/Redacted";
11import * as Schema from "effect/Schema";
12import * as Tracer from "effect/Tracer";
13import * as HttpEffect from "effect/unstable/http/HttpEffect";
14import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware";
15import * as HttpRouter from "effect/unstable/http/HttpRouter";
16import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
17import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
18import * as HttpTraceContext from "effect/unstable/http/HttpTraceContext";
19import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
20import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
21import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
22import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
23
24import {
25 RelayApi,
26 RelayAgentActivityPublishProofExpiredError,
27 RelayAgentActivityPublishProofInvalidError,
28 RelayClientAuth,
29 RelayClientPrincipal,
30 RelayAccessTokenType,
31 RelayDpopClientAuth,
32 RelayEnvironmentConnectScope,
33 RelayEnvironmentStatusScope,
34 RelayMobileRegistrationScope,
35 RelayAuthInvalidError,
36 type RelayAuthInvalidReason,
37 RelayEnvironmentAuth,
38 RelayEnvironmentConnectNotAuthorizedError,
39 RelayEnvironmentEndpointTimedOutError,
40 RelayEnvironmentEndpointUnavailableError,
41 RelayEnvironmentLinkFailedError,
42 RelayEnvironmentLinkProofExpiredError,
43 RelayEnvironmentLinkProofInvalidError,
44 RelayEnvironmentLinkUnavailableError,
45 RelayEnvironmentPrincipal,
46 type RelayEnvironmentConnectRequest,
47 type RelayDpopAccessTokenScope,
48 RelayInternalError,
49} from "@t3tools/contracts/relay";
50import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";
51
52import * as DeliveryAttempts from "../agentActivity/DeliveryAttempts.ts";
53import * as AgentActivityRows from "../agentActivity/AgentActivityRows.ts";
54import * as Devices from "../agentActivity/Devices.ts";
55import * as DpopProofs from "../auth/DpopProofs.ts";
56import * as RelayTokens from "../auth/RelayTokens.ts";
57import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";
58import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
59import * as LiveActivities from "../agentActivity/LiveActivities.ts";
60import * as RelayConfiguration from "../Config.ts";
61import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";
62import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";
63import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";
64import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
65import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
66import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
67import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
68import { withSpanAttributes } from "../observability.ts";
69import * as RelayDb from "../db.ts";
70
71const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;
72const relayCorsAllowedHeaders = [
73 "authorization",
74 "b3",
75 "traceparent",
76 "content-type",
77 "dpop",
78] as const;
79const relayCorsExposedHeaders = ["traceparent", "www-authenticate"] as const;
80
81const relayCorsHeaders = {
82 "access-control-allow-origin": "*",
83 "access-control-expose-headers": relayCorsExposedHeaders.join(","),
84} as const;
85
86const relayCorsPreflightHeaders = {
87 ...relayCorsHeaders,
88 "access-control-allow-methods": relayCorsAllowedMethods.join(","),
89 "access-control-allow-headers": relayCorsAllowedHeaders.join(","),
90 "access-control-max-age": "86400",
91} as const;
92
93const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
94 (_request, response) =>
95 Effect.succeed(
96 HttpServerResponse.setHeaders(response, {
97 "cache-control": "no-store",
98 pragma: "no-cache",
99 }),
100 ),
101);
102
103const appendRelayDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>
104 Effect.succeed(
105 response.status === 401
106 ? HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")
107 : response,
108 ),
109);
110
111const appendRelayTraceContextResponseHeader = Effect.gen(function* () {
112 const span = yield* Effect.currentParentSpan;
113 if (span._tag !== "Span") {
114 return;
115 }
116 const traceparent = HttpTraceContext.toHeaders(span).traceparent;
117 if (traceparent === undefined) {
118 return;
119 }
120 yield* HttpEffect.appendPreResponseHandler((_request, response) =>
121 Effect.succeed(HttpServerResponse.setHeader(response, "traceparent", traceparent)),
122 );
123}).pipe(Effect.ignore);
124
125export const relayCors = HttpRouter.middleware(
126 Effect.fnUntraced(function* <E, R>(
127 httpEffect: Effect.Effect<
128 HttpServerResponse.HttpServerResponse,
129 E,
130 HttpServerRequest.HttpServerRequest | R
131 >,
132 ) {
133 const request = yield* HttpServerRequest.HttpServerRequest;
134 if (request.method === "OPTIONS") {
135 return HttpServerResponse.empty({
136 status: 204,
137 headers: relayCorsPreflightHeaders,
138 });
139 }
140 const response = yield* httpEffect;
141 return HttpServerResponse.setHeaders(response, relayCorsHeaders);
142 }),
143 { global: true },
144);
145
146export const relayNotFoundRoute = HttpRouter.add(
147 "*",
148 "/*",
149 HttpServerResponse.empty({ status: 404 }),
150);
151
152export const relayDocsRedirectRoute = HttpRouter.add(
153 "GET",
154 "/",
155 HttpServerResponse.redirect("/docs"),
156);
157
158export const traceRelayHttpRequest = <E, R>(
159 httpEffect: Effect.Effect<
160 HttpServerResponse.HttpServerResponse,
161 E,
162 HttpServerRequest.HttpServerRequest | R
163 >,
164) =>
165 // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first.
166 HttpMiddleware.tracer(
167 appendRelayTraceContextResponseHeader.pipe(Effect.andThen(httpEffect)),
168 ).pipe(Effect.ensuring(Effect.yieldNow));
169
170export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(
171 httpEffect: Effect.Effect<
172 HttpServerResponse.HttpServerResponse,
173 E,
174 HttpServerRequest.HttpServerRequest | R
175 >,
176 tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>,
177) =>
178 traceRelayHttpRequest(httpEffect).pipe(
179 Effect.provide(Layer.merge(tracerLayer, httpHeaderRedactionLayer)),
180 );
181
182export const withoutCapturedParentSpan = <A, E, R>(
183 effect: Effect.Effect<A, E, R>,
184): Effect.Effect<A, E, R> =>
185 Effect.withFiber((fiber) => {
186 const context = fiber.context;
187 // HttpApiBuilder captures its build context for route handlers; an event parent would outlive export.
188 fiber.setContext(Context.omit(Tracer.ParentSpan)(context));
189 return effect.pipe(Effect.ensuring(Effect.sync(() => fiber.setContext(context))));
190 });
191
192export const relayClientAuthLayer = Layer.effect(
193 RelayClientAuth,
194 Effect.gen(function* () {
195 const config = yield* RelayConfiguration.RelayConfiguration;
196 return {
197 clientBearer: Effect.fn("relay.auth.client.bearer")(function* (httpEffect, { credential }) {
198 const token = readHttpAuthorizationCredential(credential);
199 const verified = yield* verifyRelayClientBearerToken(config, token).pipe(
200 Effect.tapError((error) =>
201 Effect.annotateCurrentSpan(
202 "relay.auth.clerk_verification_failure",
203 clerkVerificationFailureReason(error.cause),
204 ),
205 ),
206 Effect.catch(() => relayAuthInvalidError("invalid_bearer")),
207 );
208 if (!verified.sub) {
209 yield* Effect.annotateCurrentSpan({
210 "relay.auth.clerk_verification_failure": "missing_subject",
211 });
212 return yield* relayAuthInvalidError("invalid_bearer");
213 }
214 yield* Effect.annotateCurrentSpan({
215 "relay.auth.mode": verified.mode,
216 "relay.auth.subject": verified.sub,
217 });
218
219 return yield* httpEffect.pipe(
220 withSpanAttributes({ "user.id": verified.sub }),
221 Effect.provideService(RelayClientPrincipal, {
222 userId: verified.sub,
223 token,
224 }),
225 );
226 }),
227 };
228 }),
229);
230
231export const relayEnvironmentAuthLayer = Layer.effect(
232 RelayEnvironmentAuth,
233 Effect.gen(function* () {
234 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
235 return {
236 environmentBearer: Effect.fn("relay.auth.environment.bearer")(function* (
237 httpEffect,
238 { credential },
239 ) {
240 const token = readHttpAuthorizationCredential(credential);
241 const principal = yield* credentials.authenticate(token).pipe(
242 Effect.catchTags({
243 EnvironmentCredentialAuthenticatePersistenceError: () =>
244 relayInternalErrorResponse("persistence_failed"),
245 }),
246 );
247 if (principal._tag === "None") {
248 return yield* relayAuthInvalidError("not_authorized");
249 }
250 yield* Effect.annotateCurrentSpan({
251 "relay.auth.mode": "environment_credential",
252 });
253 return yield* httpEffect.pipe(
254 withSpanAttributes({
255 "relay.environment_id": principal.value.environmentId,
256 }),
257 Effect.provideService(RelayEnvironmentPrincipal, principal.value),
258 );
259 }),
260 };
261 }),
262);
263
264export const relayDpopClientAuthLayer = Layer.effect(
265 RelayDpopClientAuth,
266 Effect.gen(function* () {
267 const relayTokens = yield* RelayTokens.RelayTokens;
268 return {
269 relayDpop: Effect.fn("relay.auth.dpop_client")(function* (httpEffect, { credential }) {
270 yield* appendRelayDpopChallengeHeader;
271 const request = yield* HttpServerRequest.HttpServerRequest;
272 if (!isDpopAuthorizationHeader(request.headers.authorization)) {
273 return yield* relayAuthInvalidError("invalid_bearer");
274 }
275 const token = readHttpAuthorizationCredential(credential);
276 const now = yield* DateTime.now;
277 const verified = yield* relayTokens.verifyDpopAccessToken({
278 token,
279 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
280 });
281 if (!verified) {
282 return yield* relayAuthInvalidError("invalid_bearer");
283 }
284 yield* Effect.annotateCurrentSpan({
285 "relay.auth.mode": "dpop",
286 "relay.auth.subject": verified.sub,
287 });
288 return yield* httpEffect.pipe(
289 withSpanAttributes({ "user.id": verified.sub }),
290 Effect.provideService(RelayClientPrincipal, {
291 userId: verified.sub,
292 token,
293 proofKeyThumbprint: verified.cnf.jkt,
294 dpopScopes: verified.scope,
295 }),
296 );
297 }),
298 };
299 }),
300);
301
302function isDpopAuthorizationHeader(value: string | undefined): boolean {
303 return /^DPoP +/iu.test(value ?? "");
304}
305
306function readHttpAuthorizationCredential(credential: Redacted.Redacted<string>): string {
307 // Effect beta.73 leaves the scheme separator in decoded HTTP credentials.
308 return Redacted.value(credential).trimStart();
309}
310
311export const metadataApi = HttpApiBuilder.group(
312 RelayApi,
313 "metadata",
314 Effect.fnUntraced(function* (handlers) {
315 const settings = yield* RelayConfiguration.RelayConfiguration;
316 const issuer = normalizeRelayIssuer(settings.relayIssuer);
317 const scopes = [
318 RelayEnvironmentConnectScope,
319 RelayEnvironmentStatusScope,
320 RelayMobileRegistrationScope,
321 ] as const;
322 return handlers
323 .handle("authorizationServer", () =>
324 Effect.succeed({
325 issuer,
326 token_endpoint: `${issuer}/v1/client/dpop-token`,
327 grant_types_supported: ["urn:ietf:params:oauth:grant-type:token-exchange"],
328 token_endpoint_auth_methods_supported: ["none"],
329 dpop_signing_alg_values_supported: ["ES256"],
330 scopes_supported: scopes,
331 }),
332 )
333 .handle("protectedResource", () =>
334 Effect.succeed({
335 resource: issuer,
336 authorization_servers: [issuer],
337 scopes_supported: scopes,
338 dpop_bound_access_tokens_required: true,
339 dpop_signing_alg_values_supported: ["ES256"],
340 }),
341 );
342 }),
343);
344
345export const healthApi = HttpApiBuilder.group(
346 RelayApi,
347 "health",
348 Effect.fnUntraced(function* (handlers) {
349 const db = yield* RelayDb.RelayDb;
350 return handlers.handle(
351 "health",
352 Effect.fn("relay.api.health")(
353 function* () {
354 yield* db.execute(drizzleSql`SELECT 1`);
355 return { ok: true, service: "relay" as const };
356 },
357 Effect.catch(() => relayInternalErrorResponse("database_unavailable")),
358 ),
359 );
360 }),
361);
362
363export const mobileApi = HttpApiBuilder.group(
364 RelayApi,
365 "mobile",
366 Effect.fnUntraced(function* (handlers) {
367 const registrations = yield* MobileRegistrations.MobileRegistrations;
368 const dpopProofs = yield* DpopProofs.DpopProofReplay;
369 return handlers
370 .handle(
371 "registerDevice",
372 Effect.fn("relay.api.mobile.registerDevice")(function* (args) {
373 const { payload } = args;
374 const { userId, token } = yield* RelayClientPrincipal;
375 const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");
376 yield* requireDpopThumbprint(proofKeyThumbprint, {
377 expectedAccessToken: token,
378 }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
379 return yield* registrations.registerDevice({ userId, payload });
380 }, mapRelayCommonApiErrors("invalid_dpop")),
381 )
382 .handle(
383 "registerLiveActivity",
384 Effect.fn("relay.api.mobile.registerLiveActivity")(function* (args) {
385 const { payload } = args;
386 const { userId, token } = yield* RelayClientPrincipal;
387 const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");
388 yield* requireDpopThumbprint(proofKeyThumbprint, {
389 expectedAccessToken: token,
390 }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
391 return yield* registrations.registerLiveActivity({ userId, payload });
392 }, mapRelayCommonApiErrors("invalid_dpop")),
393 )
394 .handle(
395 "unregisterDevice",
396 Effect.fn("relay.api.mobile.unregisterDevice")(function* (args) {
397 const { params } = args;
398 const { userId, token } = yield* RelayClientPrincipal;
399 const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");
400 yield* requireDpopThumbprint(proofKeyThumbprint, {
401 expectedAccessToken: token,
402 }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
403 return yield* registrations.unregisterDevice({ userId, deviceId: params.deviceId });
404 }, mapRelayCommonApiErrors("invalid_dpop")),
405 );
406 }),
407);
408
409export const clientApi = HttpApiBuilder.group(
410 RelayApi,
411 "client",
412 Effect.fnUntraced(function* (handlers) {
413 const config = yield* RelayConfiguration.RelayConfiguration;
414 const crypto = yield* Crypto.Crypto;
415 const relayTokens = yield* RelayTokens.RelayTokens;
416 const linker = yield* EnvironmentLinker.EnvironmentLinker;
417 const links = yield* EnvironmentLinks.EnvironmentLinks;
418 const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
419 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
420 const devices = yield* Devices.Devices;
421 return handlers
422 .handle(
423 "listEnvironments",
424 Effect.fn("relay.api.client.listEnvironments")(function* () {
425 const { userId } = yield* RelayClientPrincipal;
426 const environments = yield* links.listForUser({ userId });
427 return { environments };
428 }, mapRelayCommonApiErrors("not_authorized")),
429 )
430 .handle(
431 "listDevices",
432 Effect.fn("relay.api.client.listDevices")(function* () {
433 const { userId } = yield* RelayClientPrincipal;
434 return { devices: yield* devices.listForUser({ userId }) };
435 }, mapRelayCommonApiErrors("not_authorized")),
436 )
437 .handle(
438 "linkEnvironment",
439 Effect.fn("relay.api.client.linkEnvironment")(
440 function* (args) {
441 const { payload } = args;
442 yield* appendRelayCredentialResponseHeaders;
443 const { userId } = yield* RelayClientPrincipal;
444 const result = yield* linker.link({ userId, request: payload });
445 return {
446 ok: true,
447 cloudUserId: userId,
448 environmentId: result.environmentId,
449 endpoint: result.endpoint,
450 endpointRuntime: result.endpointRuntime,
451 relayIssuer: config.relayIssuer,
452 environmentCredential: result.environmentCredential,
453 cloudMintPublicKey: config.cloudMintPublicKey,
454 };
455 },
456 mapErrorTags({
457 EnvironmentLinkProofExpired: (_error, traceId) =>
458 new RelayEnvironmentLinkProofExpiredError({
459 code: "environment_link_proof_expired",
460 traceId,
461 }),
462 EnvironmentLinkProofInvalid: (linkError, traceId) =>
463 new RelayEnvironmentLinkProofInvalidError({
464 code: "environment_link_proof_invalid",
465 reason: linkError.reason,
466 traceId,
467 }),
468 ManagedEndpointProvisioningNotConfigured: (_error, traceId) =>
469 new RelayEnvironmentLinkUnavailableError({
470 code: "environment_link_unavailable",
471 reason: "managed_endpoint_not_configured",
472 traceId,
473 }),
474 ManagedEndpointProvisioningFailed: (_error, traceId) =>
475 new RelayEnvironmentLinkUnavailableError({
476 code: "environment_link_unavailable",
477 reason: "managed_endpoint_provisioning_failed",
478 traceId,
479 }),
480 ManagedEndpointOriginNotAllowed: (_error, traceId) =>
481 new RelayEnvironmentLinkProofInvalidError({
482 code: "environment_link_proof_invalid",
483 reason: "origin_not_allowed",
484 traceId,
485 }),
486 EnvironmentLinkUpsertPersistenceError: (_error, traceId) =>
487 new RelayEnvironmentLinkFailedError({
488 code: "environment_link_failed",
489 reason: "link_persistence_failed",
490 traceId,
491 }),
492 EnvironmentCredentialCreatePersistenceError: (_error, traceId) =>
493 new RelayEnvironmentLinkFailedError({
494 code: "environment_link_failed",
495 reason: "credential_persistence_failed",
496 traceId,
497 }),
498 DpopProofReplayPersistenceError: (_error, traceId) =>
499 new RelayEnvironmentLinkFailedError({
500 code: "environment_link_failed",
501 reason: "replay_persistence_failed",
502 traceId,
503 }),
504 }),
505 mapRelayCommonApiErrors("not_authorized"),
506 ),
507 )
508 .handle(
509 "createEnvironmentLinkChallenge",
510 Effect.fn("relay.api.client.createEnvironmentLinkChallenge")(function* (args) {
511 yield* appendRelayCredentialResponseHeaders;
512 const { userId } = yield* RelayClientPrincipal;
513 const now = yield* DateTime.now;
514 const expiresAt = DateTime.add(now, { minutes: 5 });
515 const jti = yield* crypto.randomUUIDv4.pipe(
516 Effect.catch(() => relayInternalErrorResponse("internal_error")),
517 );
518 const challenge = yield* relayTokens
519 .issueLinkChallenge({
520 userId,
521 request: args.payload,
522 jti,
523 issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
524 expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),
525 })
526 .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
527 return { challenge, expiresAt: DateTime.formatIso(expiresAt) };
528 }, mapRelayCommonApiErrors("not_authorized")),
529 )
530 .handle(
531 "unlinkEnvironment",
532 Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) {
533 const { params } = args;
534 const { userId } = yield* RelayClientPrincipal;
535 yield* managedEndpointProvider
536 .deprovision({
537 userId,
538 environmentId: params.environmentId,
539 })
540 .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
541 const link = yield* links.getForUser({
542 userId,
543 environmentId: params.environmentId,
544 });
545 if (link === null) {
546 return { ok: false };
547 }
548 const unlinked = yield* links.revokeForUser({
549 userId,
550 environmentId: params.environmentId,
551 });
552 if (unlinked) {
553 yield* credentials.revokeForEnvironmentPublicKey({
554 environmentId: link.environmentId,
555 environmentPublicKey: link.environmentPublicKey,
556 });
557 }
558 return { ok: unlinked };
559 }, mapRelayCommonApiErrors("not_authorized")),
560 );
561 }),
562);
563
564export const tokenApi = HttpApiBuilder.group(
565 RelayApi,
566 "token",
567 Effect.fnUntraced(function* (handlers) {
568 const config = yield* RelayConfiguration.RelayConfiguration;
569 const crypto = yield* Crypto.Crypto;
570 const dpopProofs = yield* DpopProofs.DpopProofReplay;
571 const relayTokens = yield* RelayTokens.RelayTokens;
572 return handlers.handle(
573 "exchangeDpopAccessToken",
574 Effect.fn("relay.api.token.exchangeDpopAccessToken")(function* (args) {
575 yield* appendRelayCredentialResponseHeaders;
576 const issuer = normalizeRelayIssuer(config.relayIssuer);
577 const requestedScopes = relayTokens.resolveDpopAccessTokenScopes({
578 clientId: args.payload.client_id,
579 scope: args.payload.scope,
580 });
581 yield* Effect.annotateCurrentSpan({
582 "relay.auth.mode": "clerk_bearer_token_exchange",
583 "relay.oauth.client_id": args.payload.client_id,
584 "relay.oauth.scopes": args.payload.scope,
585 });
586 if (args.payload.resource !== issuer || requestedScopes === null) {
587 return yield* new HttpApiError.Unauthorized({});
588 }
589
590 const verified = yield* verifyClerkBearerToken(config, args.payload.subject_token).pipe(
591 Effect.catch(() => relayAuthInvalidError("invalid_bearer")),
592 );
593 if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)) {
594 return yield* relayAuthInvalidError("invalid_bearer");
595 }
596 const proofKeyThumbprint = yield* requireDpopProof().pipe(
597 Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
598 );
599 const now = yield* DateTime.now;
600 const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL);
601 const jti = yield* crypto.randomUUIDv4.pipe(
602 Effect.catch(() => relayInternalErrorResponse("internal_error")),
603 );
604 return {
605 access_token: yield* relayTokens
606 .issueDpopAccessToken({
607 userId: verified.sub,
608 proofKeyThumbprint,
609 jti,
610 issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
611 expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),
612 clientId: args.payload.client_id,
613 scopes: requestedScopes,
614 })
615 .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
616 issued_token_type: RelayAccessTokenType,
617 token_type: "DPoP" as const,
618 expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL),
619 scope: encodeOAuthScope(requestedScopes),
620 };
621 }, mapRelayCommonApiErrors("invalid_dpop")),
622 );
623 }),
624);
625
626export const dpopClientApi = HttpApiBuilder.group(
627 RelayApi,
628 "dpopClient",
629 Effect.fnUntraced(function* (handlers) {
630 const connector = yield* EnvironmentConnector.EnvironmentConnector;
631 const dpopProofs = yield* DpopProofs.DpopProofReplay;
632 return handlers
633 .handle(
634 "connectEnvironment",
635 Effect.fn("relay.api.dpopClient.connectEnvironment")(
636 function* (args) {
637 const { params, payload } = args;
638 yield* appendRelayCredentialResponseHeaders;
639 const { userId, token } = yield* RelayClientPrincipal;
640 const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:connect");
641 const requestedThumbprint = resolveConnectClientKeyThumbprint(payload);
642 if (!requestedThumbprint || requestedThumbprint !== proofKeyThumbprint) {
643 return yield* new HttpApiError.Unauthorized({});
644 }
645 const clientProofKeyThumbprint = yield* requireDpopThumbprint(proofKeyThumbprint, {
646 expectedAccessToken: token,
647 }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
648 return yield* connector.connect({
649 userId,
650 environmentId: params.environmentId,
651 clientProofKeyThumbprint,
652 ...(payload.deviceId ? { deviceId: payload.deviceId } : {}),
653 });
654 },
655 mapRelayCommonApiErrors("invalid_dpop"),
656 mapErrorTags({
657 EnvironmentConnectNotAuthorized: (_error, traceId) =>
658 new RelayEnvironmentConnectNotAuthorizedError({
659 code: "environment_connect_not_authorized",
660 traceId,
661 }),
662 EnvironmentMintRequestFailed: (_error, traceId) =>
663 new RelayEnvironmentEndpointUnavailableError({
664 code: "environment_endpoint_unavailable",
665 reason: "endpoint_request_failed",
666 traceId,
667 }),
668 EnvironmentMintRequestTimedOut: (_error, traceId) =>
669 new RelayEnvironmentEndpointTimedOutError({
670 code: "environment_endpoint_timed_out",
671 traceId,
672 }),
673 EnvironmentMintResponseInvalid: (_error, traceId) =>
674 new RelayEnvironmentEndpointUnavailableError({
675 code: "environment_endpoint_unavailable",
676 reason: "endpoint_response_invalid",
677 traceId,
678 }),
679 }),
680 ),
681 )
682 .handle(
683 "getEnvironmentStatus",
684 Effect.fn("relay.api.dpopClient.getEnvironmentStatus")(
685 function* (args) {
686 const { params } = args;
687 const { userId, token } = yield* RelayClientPrincipal;
688 const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:status");
689 yield* requireDpopThumbprint(proofKeyThumbprint, {
690 expectedAccessToken: token,
691 }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
692 return yield* connector.status({
693 userId,
694 environmentId: params.environmentId,
695 });
696 },
697 mapRelayCommonApiErrors("invalid_dpop"),
698 mapErrorTags({
699 EnvironmentConnectNotAuthorized: (_error, traceId) =>
700 new RelayEnvironmentConnectNotAuthorizedError({
701 code: "environment_connect_not_authorized",
702 traceId,
703 }),
704 EnvironmentMintRequestFailed: (_error, traceId) =>
705 new RelayEnvironmentEndpointUnavailableError({
706 code: "environment_endpoint_unavailable",
707 reason: "endpoint_request_failed",
708 traceId,
709 }),
710 EnvironmentMintRequestTimedOut: (_error, traceId) =>
711 new RelayEnvironmentEndpointTimedOutError({
712 code: "environment_endpoint_timed_out",
713 traceId,
714 }),
715 EnvironmentMintResponseInvalid: (_error, traceId) =>
716 new RelayEnvironmentEndpointUnavailableError({
717 code: "environment_endpoint_unavailable",
718 reason: "endpoint_response_invalid",
719 traceId,
720 }),
721 }),
722 ),
723 );
724 }),
725);
726
727export const serverApi = HttpApiBuilder.group(
728 RelayApi,
729 "server",
730 Effect.fnUntraced(function* (handlers) {
731 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
732 const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;
733 return handlers.handle(
734 "publishAgentActivity",
735 Effect.fn("relay.api.server.publishAgentActivity")(
736 function* (args) {
737 const { params, payload } = args;
738 const principal = yield* RelayEnvironmentPrincipal;
739 if (principal.environmentId !== params.environmentId) {
740 return yield* new HttpApiError.Unauthorized({});
741 }
742 yield* publishSignatures.verify({
743 environmentId: params.environmentId,
744 environmentPublicKey: principal.environmentPublicKey,
745 threadId: params.threadId,
746 request: payload,
747 });
748 return yield* publisher.publish({
749 environmentId: params.environmentId,
750 environmentPublicKey: principal.environmentPublicKey,
751 threadId: params.threadId,
752 state: payload.state,
753 });
754 },
755 mapErrorTags({
756 EnvironmentPublishPublicKeyMissing: (_error, traceId) =>
757 new RelayAuthInvalidError({
758 code: "auth_invalid",
759 reason: "not_authorized",
760 traceId,
761 }),
762 EnvironmentPublishSignatureExpired: (_error, traceId) =>
763 new RelayAgentActivityPublishProofExpiredError({
764 code: "agent_activity_publish_proof_expired",
765 traceId,
766 }),
767 EnvironmentPublishSignatureInvalid: (_error, traceId) =>
768 new RelayAgentActivityPublishProofInvalidError({
769 code: "agent_activity_publish_proof_invalid",
770 reason: "invalid_signature_or_payload",
771 traceId,
772 }),
773 DpopProofReplayPersistenceError: (_error, traceId) =>
774 new RelayInternalError({
775 code: "internal_error",
776 reason: "persistence_failed",
777 traceId,
778 }),
779 ApnsDeliveryJobQueuePayloadInvalid: (_error, traceId) =>
780 new RelayInternalError({
781 code: "internal_error",
782 reason: "internal_error",
783 traceId,
784 }),
785 ApnsDeliveryJobLiveActivityAggregateMissing: (_error, traceId) =>
786 new RelayInternalError({
787 code: "internal_error",
788 reason: "internal_error",
789 traceId,
790 }),
791 ApnsDeliveryJobLiveActivityNotificationUnexpected: (_error, traceId) =>
792 new RelayInternalError({
793 code: "internal_error",
794 reason: "internal_error",
795 traceId,
796 }),
797 ApnsDeliveryJobPushNotificationMissing: (_error, traceId) =>
798 new RelayInternalError({
799 code: "internal_error",
800 reason: "internal_error",
801 traceId,
802 }),
803 ApnsDeliveryJobPushNotificationAggregateUnexpected: (_error, traceId) =>
804 new RelayInternalError({
805 code: "internal_error",
806 reason: "internal_error",
807 traceId,
808 }),
809 ApnsDeliveryJobCreatedAtInvalid: (_error, traceId) =>
810 new RelayInternalError({
811 code: "internal_error",
812 reason: "internal_error",
813 traceId,
814 }),
815 ApnsDeliveryJobExpiresAtInvalid: (_error, traceId) =>
816 new RelayInternalError({
817 code: "internal_error",
818 reason: "internal_error",
819 traceId,
820 }),
821 ApnsDeliveryJobTimeWindowInvalid: (_error, traceId) =>
822 new RelayInternalError({
823 code: "internal_error",
824 reason: "internal_error",
825 traceId,
826 }),
827 ApnsDeliveryJobTimeWindowTooLong: (_error, traceId) =>
828 new RelayInternalError({
829 code: "internal_error",
830 reason: "internal_error",
831 traceId,
832 }),
833 ApnsDeliveryJobSignatureInvalid: (_error, traceId) =>
834 new RelayInternalError({
835 code: "internal_error",
836 reason: "internal_error",
837 traceId,
838 }),
839 ApnsDeliveryJobExpired: (_error, traceId) =>
840 new RelayInternalError({
841 code: "internal_error",
842 reason: "internal_error",
843 traceId,
844 }),
845 ApnsDeliveryJobClaimInFlight: (_error, traceId) =>
846 new RelayInternalError({
847 code: "internal_error",
848 reason: "internal_error",
849 traceId,
850 }),
851 ApnsDeliveryQueueSendError: (_error, traceId) =>
852 new RelayInternalError({
853 code: "internal_error",
854 reason: "upstream_unavailable",
855 traceId,
856 }),
857 }),
858 mapRelayCommonApiErrors("not_authorized"),
859 ),
860 );
861 }),
862);
863
864class ClerkTokenVerificationFailed extends Schema.TaggedErrorClass<ClerkTokenVerificationFailed>()(
865 "ClerkTokenVerificationFailed",
866 {
867 cause: Schema.Defect(),
868 },
869) {
870 override get message(): string {
871 return "Clerk token verification failed";
872 }
873}
874
875const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized);
876
877const currentTraceId = Effect.currentParentSpan.pipe(
878 Effect.map((span) => span.traceId),
879 Effect.orElseSucceed(() => "unavailable"),
880);
881
882const RelayCommonPersistenceError = Schema.Union([
883 Devices.DeviceRegistrationPersistenceError,
884 Devices.DeviceUnregistrationPersistenceError,
885 Devices.DeviceListPersistenceError,
886 LiveActivities.LiveActivityRegistrationPersistenceError,
887 EnvironmentLinks.EnvironmentLinkUserListPersistenceError,
888 EnvironmentLinks.EnvironmentPublicKeyListPersistenceError,
889 EnvironmentLinks.EnvironmentLinkListPersistenceError,
890 EnvironmentLinks.EnvironmentLinkLookupPersistenceError,
891 EnvironmentLinks.EnvironmentLinkRevokePersistenceError,
892 ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError,
893 EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError,
894 EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError,
895 DpopProofs.DpopProofReplayPersistenceError,
896 LiveActivities.LiveActivityTargetListPersistenceError,
897 AgentActivityRows.AgentActivityRowUpsertPersistenceError,
898 AgentActivityRows.AgentActivityRowDeletePersistenceError,
899 AgentActivityRows.AgentActivityRowListPersistenceError,
900 LiveActivities.LiveActivityDeliveryMarkPersistenceError,
901 DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
902]);
903type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
904const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
905
906type MapRelayCommonApiError<E> =
907 | Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>
908 | (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)
909 | (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
910
911function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {
912 return currentTraceId.pipe(
913 Effect.flatMap((traceId) =>
914 Effect.fail(new RelayInternalError({ code: "internal_error", reason, traceId })),
915 ),
916 );
917}
918
919function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) {
920 const mapError = Effect.fnUntraced(function* <E>(error: E) {
921 const traceId = yield* currentTraceId;
922 if (isHttpUnauthorized(error)) {
923 return yield* Effect.fail(
924 new RelayAuthInvalidError({
925 code: "auth_invalid",
926 reason: authReason,
927 traceId,
928 }) as MapRelayCommonApiError<E>,
929 );
930 }
931 if (isRelayCommonPersistenceError(error)) {
932 return yield* Effect.fail(
933 new RelayInternalError({
934 code: "internal_error",
935 reason: "persistence_failed",
936 traceId,
937 }) as MapRelayCommonApiError<E>,
938 );
939 }
940
941 return yield* Effect.fail(error as MapRelayCommonApiError<E>);
942 });
943
944 return <A, E, R>(
945 effect: Effect.Effect<A, E, R>,
946 ): Effect.Effect<A, MapRelayCommonApiError<E>, R> => effect.pipe(Effect.catch(mapError));
947}
948
949type TaggedErrorTag<E> = Extract<E, { readonly _tag: string }>["_tag"];
950
951type MapErrorTagCases<E> = {
952 readonly [K in TaggedErrorTag<E>]+?: (
953 error: Extract<E, { readonly _tag: K }>,
954 traceId: string,
955 ) => unknown;
956};
957
958type MappedTagError<Cases> = Cases[keyof Cases] extends (
959 ...args: ReadonlyArray<never>
960) => infer Error
961 ? Error
962 : never;
963
964type CatchTagCases<E, Cases> = {
965 readonly [K in TaggedErrorTag<E>]+?: (
966 error: Extract<E, { readonly _tag: K }>,
967 ) => Effect.Effect<never, MappedTagError<Cases>>;
968} & (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never });
969
970function mapErrorTags<
971 E,
972 Cases extends MapErrorTagCases<E> &
973 (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }),
974>(cases: Cases) {
975 const catchCases = Record.map(
976 cases as Record.ReadonlyRecord<
977 string,
978 (error: never, traceId: string) => MappedTagError<Cases>
979 >,
980 (makeError) => (error: never) =>
981 currentTraceId.pipe(Effect.flatMap((traceId) => Effect.fail(makeError(error, traceId)))),
982 ) as CatchTagCases<E, Cases>;
983
984 return <A, R>(
985 self: Effect.Effect<A, E, R>,
986 ): Effect.Effect<A, Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>, R> =>
987 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off
988 Effect.catchTags(self, catchCases) as Effect.Effect<
989 A,
990 Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>,
991 R
992 >;
993}
994
995function resolveConnectClientKeyThumbprint(payload: RelayEnvironmentConnectRequest): string | null {
996 const requestedThumbprint = payload.clientKeyThumbprint ?? payload.clientProofKeyThumbprint;
997 if (!requestedThumbprint) {
998 return null;
999 }
1000 if (
1001 payload.clientKeyThumbprint &&
1002 payload.clientProofKeyThumbprint &&
1003 payload.clientKeyThumbprint !== payload.clientProofKeyThumbprint
1004 ) {
1005 return null;
1006 }
1007 return requestedThumbprint;
1008}
1009
1010function safeAuthFailureReason(value: string): string {
1011 return /^[a-z0-9._-]+$/i.test(value) ? value : "unknown";
1012}
1013
1014function clerkVerificationFailureReason(cause: unknown): string {
1015 if (
1016 cause instanceof Error &&
1017 (cause.message.startsWith("Invalid JWT audience claim ") ||
1018 cause.message.startsWith("Invalid JWT audience claim array "))
1019 ) {
1020 return "audience_mismatch";
1021 }
1022 if (typeof cause === "object" && cause !== null && "reason" in cause) {
1023 const reason = (cause as { readonly reason?: unknown }).reason;
1024 if (typeof reason === "string" && reason.length > 0) {
1025 return safeAuthFailureReason(reason);
1026 }
1027 }
1028 if (cause instanceof Error && cause.name) {
1029 return safeAuthFailureReason(cause.name);
1030 }
1031 return "unknown";
1032}
1033
1034function hasExpectedClerkAudience(audience: unknown, expectedAudience: string): boolean {
1035 return typeof audience === "string"
1036 ? audience === expectedAudience
1037 : Array.isArray(audience) &&
1038 audience.some((entry) => typeof entry === "string" && entry === expectedAudience);
1039}
1040
1041function verifyClerkBearerToken(
1042 config: RelayConfiguration.RelayConfiguration["Service"],
1043 token: string,
1044) {
1045 return Effect.tryPromise({
1046 try: () =>
1047 verifyToken(token, {
1048 secretKey: Redacted.value(config.clerkSecretKey),
1049 audience: config.clerkJwtAudience,
1050 }),
1051 catch: (cause) => new ClerkTokenVerificationFailed({ cause }),
1052 }).pipe(
1053 Effect.withSpan("verify_clerk_bearer_token", {
1054 attributes: { "relay.auth.token_length": token.length },
1055 }),
1056 );
1057}
1058
1059function verifyClerkOAuthBearerToken(
1060 config: RelayConfiguration.RelayConfiguration["Service"],
1061 token: string,
1062) {
1063 return Effect.tryPromise({
1064 try: async () => {
1065 const client = createClerkClient({
1066 secretKey: Redacted.value(config.clerkSecretKey),
1067 publishableKey: config.clerkPublishableKey,
1068 });
1069 const state = await client.authenticateRequest(
1070 new Request(config.relayIssuer, {
1071 headers: { authorization: `Bearer ${token}` },
1072 }),
1073 { acceptsToken: "oauth_token" },
1074 );
1075 const auth = state.toAuth();
1076 if (!state.isAuthenticated || !auth.userId) {
1077 throw new Error("Clerk OAuth token is not authenticated.");
1078 }
1079 return { sub: auth.userId };
1080 },
1081 catch: (cause) => new ClerkTokenVerificationFailed({ cause }),
1082 });
1083}
1084
1085export function verifyRelayClientBearerToken(
1086 config: RelayConfiguration.RelayConfiguration["Service"],
1087 token: string,
1088) {
1089 return verifyClerkBearerToken(config, token).pipe(
1090 Effect.flatMap((verified) =>
1091 verified.sub && hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)
1092 ? Effect.succeed({ sub: verified.sub, mode: "clerk_session_bearer" as const })
1093 : Effect.fail(new ClerkTokenVerificationFailed({ cause: "missing_relay_audience" })),
1094 ),
1095 Effect.catch(() =>
1096 verifyClerkOAuthBearerToken(config, token).pipe(
1097 Effect.map((verified) => ({ ...verified, mode: "clerk_oauth_bearer" as const })),
1098 ),
1099 ),
1100 );
1101}
1102
1103const requireDpopPrincipalScope = Effect.fn("relay.api.require_dpop_principal_scope")(function* (
1104 scope: RelayDpopAccessTokenScope,
1105) {
1106 yield* Effect.annotateCurrentSpan({ "relay.dpop.required_scope": scope });
1107 const principal = yield* RelayClientPrincipal;
1108 if (!principal.proofKeyThumbprint || !principal.dpopScopes?.includes(scope)) {
1109 return yield* new HttpApiError.Unauthorized({});
1110 }
1111 return principal.proofKeyThumbprint;
1112});
1113
1114const requireDpopThumbprint = Effect.fn("relay.api.require_dpop_thumbprint")(function* (
1115 expectedThumbprint: string,
1116 options?: {
1117 readonly expectedAccessToken?: string;
1118 },
1119) {
1120 const request = yield* HttpServerRequest.HttpServerRequest;
1121 const now = yield* DateTime.now;
1122 const url = HttpServerRequest.toURL(request);
1123 if (url._tag === "None") {
1124 return yield* new HttpApiError.Unauthorized({});
1125 }
1126 const dpopProofs = yield* DpopProofs.DpopProofReplay;
1127 return yield* dpopProofs.verifyAndConsume({
1128 proof: request.headers.dpop,
1129 method: request.method,
1130 url: url.value.href,
1131 now,
1132 expectedThumbprint,
1133 ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}),
1134 });
1135});
1136
1137const requireDpopProof = Effect.fn("relay.api.require_dpop_proof")(function* (options?: {
1138 readonly expectedAccessToken?: string;
1139}) {
1140 const request = yield* HttpServerRequest.HttpServerRequest;
1141 const now = yield* DateTime.now;
1142 const url = HttpServerRequest.toURL(request);
1143 if (url._tag === "None") {
1144 return yield* new HttpApiError.Unauthorized({});
1145 }
1146 const dpopProofs = yield* DpopProofs.DpopProofReplay;
1147 return yield* dpopProofs.verifyAndConsume({
1148 proof: request.headers.dpop,
1149 method: request.method,
1150 url: url.value.href,
1151 now,
1152 ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}),
1153 });
1154});
1155
1156const relayAuthInvalidError = Effect.fnUntraced(function* (reason: RelayAuthInvalidReason) {
1157 const traceId = yield* currentTraceId;
1158 yield* Effect.annotateCurrentSpan({
1159 "relay.trace_id": traceId,
1160 "relay.error.outbound_tag": "RelayAuthInvalidError",
1161 "relay.error.outbound_reason": reason,
1162 });
1163 return yield* new RelayAuthInvalidError({ code: "auth_invalid", reason, traceId });
1164});