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

Api.ts

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