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

Api.ts

1,367 lines51.0 KB

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