The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { createClerkClient, verifyToken } from "@clerk/backend"; |
| 2 | import { sql as drizzleSql } from "drizzle-orm"; |
| 3 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 4 | import * as Context from "effect/Context"; |
| 5 | import * as DateTime from "effect/DateTime"; |
| 6 | import * as Duration from "effect/Duration"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Option from "effect/Option"; |
| 10 | import * as Record from "effect/Record"; |
| 11 | import * as Redacted from "effect/Redacted"; |
| 12 | import * as Schema from "effect/Schema"; |
| 13 | import * as Tracer from "effect/Tracer"; |
| 14 | import * as Headers from "effect/http/Headers"; |
| 15 | import * as HttpEffect from "effect/http/HttpEffect"; |
| 16 | import * as HttpMiddleware from "effect/http/HttpMiddleware"; |
| 17 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 18 | import * as HttpServerRequest from "effect/http/HttpServerRequest"; |
| 19 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 20 | import * as HttpTraceContext from "effect/http/HttpTraceContext"; |
| 21 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 22 | import * as HttpApiError from "effect/http-api/HttpApiError"; |
| 23 | import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; |
| 24 | import * as HttpObservability from "@t3tools/shared/httpObservability"; |
| 25 | |
| 26 | import { |
| 27 | RelayApi, |
| 28 | RelayAgentActivityPublishProofExpiredError, |
| 29 | RelayAgentActivityPublishProofInvalidError, |
| 30 | RelayClientAuth, |
| 31 | RelayClientPrincipal, |
| 32 | RelayAccessTokenType, |
| 33 | RelayDpopClientAuth, |
| 34 | RelayEnvironmentConnectScope, |
| 35 | RelayEnvironmentStatusScope, |
| 36 | RelayMobileRegistrationScope, |
| 37 | RelayAuthInvalidError, |
| 38 | type RelayAuthInvalidReason, |
| 39 | type RelayDpopFailureReason, |
| 40 | RelayEnvironmentAuth, |
| 41 | RelayEnvironmentConnectNotAuthorizedError, |
| 42 | RelayEnvironmentEndpointTimedOutError, |
| 43 | RelayEnvironmentEndpointUnavailableError, |
| 44 | RelayEnvironmentLinkFailedError, |
| 45 | RelayEnvironmentLinkProofExpiredError, |
| 46 | RelayEnvironmentLinkProofInvalidError, |
| 47 | RelayEnvironmentLinkUnavailableError, |
| 48 | RelayEnvironmentLinkLimitExceededError, |
| 49 | RelayEnvironmentPrincipal, |
| 50 | type RelayEnvironmentConnectRequest, |
| 51 | type RelayManagedEndpointOrigin, |
| 52 | RelayManagedEndpointRecoveryProofPayload, |
| 53 | type RelayDpopAccessTokenScope, |
| 54 | RelayInternalError, |
| 55 | } from "@t3tools/contracts/relay"; |
| 56 | import { |
| 57 | normalizeRelayIssuer, |
| 58 | RELAY_MANAGED_TUNNEL_RECOVERY_TYP, |
| 59 | verifyRelayJwt, |
| 60 | } from "@t3tools/shared/relayJwt"; |
| 61 | |
| 62 | import * as DeliveryAttempts from "../agentActivity/DeliveryAttempts.ts"; |
| 63 | import * as AgentActivityRows from "../agentActivity/AgentActivityRows.ts"; |
| 64 | import * as Devices from "../agentActivity/Devices.ts"; |
| 65 | import * as DpopProofs from "../auth/DpopProofs.ts"; |
| 66 | import * as RelayTokens from "../auth/RelayTokens.ts"; |
| 67 | import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts"; |
| 68 | import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts"; |
| 69 | import * as HeldHooks from "../hooks/HeldHooks.ts"; |
| 70 | import * as HookInbox from "../hooks/HookInbox.ts"; |
| 71 | import * as LiveActivities from "../agentActivity/LiveActivities.ts"; |
| 72 | import * as RelayConfiguration from "../Config.ts"; |
| 73 | import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts"; |
| 74 | import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts"; |
| 75 | import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts"; |
| 76 | import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts"; |
| 77 | import * as ManagedTunnelLimits from "../environments/ManagedTunnelLimits.ts"; |
| 78 | import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts"; |
| 79 | import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts"; |
| 80 | import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts"; |
| 81 | import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts"; |
| 82 | import { withSpanAttributes } from "../observability.ts"; |
| 83 | import { isRelayHookPath, redactRelayHookUrl } from "../hooks/HookForwarder.ts"; |
| 84 | import * as RelayDb from "../db.ts"; |
| 85 | |
| 86 | // Delegated IDs exceed the router's default 100-character limit; match the environment server. |
| 87 | export const RELAY_HTTP_ROUTER_CONFIG = { |
| 88 | maxParamLength: 512, |
| 89 | } as const; |
| 90 | |
| 91 | const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler( |
| 92 | (_request, response) => |
| 93 | Effect.succeed( |
| 94 | HttpServerResponse.setHeaders(response, { |
| 95 | "cache-control": "no-store", |
| 96 | pragma: "no-cache", |
| 97 | }), |
| 98 | ), |
| 99 | ); |
| 100 | |
| 101 | // T3 Code hosts never retry sooner than Retry-After, so during a Cloudflare |
| 102 | // rate limit they wait out the pause instead of retrying into it. |
| 103 | const appendCloudflareRetryAfter = (error: unknown) => { |
| 104 | const retryAfterMillis = ManagedEndpointProvider.cloudflareRetryAfterMillis(error); |
| 105 | if (retryAfterMillis === undefined) return Effect.void; |
| 106 | const seconds = String(Math.max(1, Math.ceil(retryAfterMillis / 1000))); |
| 107 | return HttpEffect.appendPreResponseHandler((_request, response) => |
| 108 | Effect.succeed(HttpServerResponse.setHeader(response, "retry-after", seconds)), |
| 109 | ); |
| 110 | }; |
| 111 | |
| 112 | const appendRelayDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) => |
| 113 | Effect.succeed( |
| 114 | response.status === 401 |
| 115 | ? HttpServerResponse.setHeader(response, "www-authenticate", "DPoP") |
| 116 | : response, |
| 117 | ), |
| 118 | ); |
| 119 | |
| 120 | const 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 | |
| 134 | const relayCorsMiddleware = HttpMiddleware.cors({ |
| 135 | allowedMethods: ["GET", "POST", "DELETE", "OPTIONS"], |
| 136 | allowedHeaders: ["authorization", "b3", "traceparent", "content-type", "dpop"], |
| 137 | exposedHeaders: ["traceparent", "www-authenticate"], |
| 138 | maxAge: 86_400, |
| 139 | }); |
| 140 | |
| 141 | export const layerCors = HttpRouter.middleware( |
| 142 | Effect.fnUntraced(function* <E, R>( |
| 143 | httpEffect: Effect.Effect< |
| 144 | HttpServerResponse.HttpServerResponse, |
| 145 | E, |
| 146 | HttpServerRequest.HttpServerRequest | R |
| 147 | >, |
| 148 | ) { |
| 149 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 150 | if (isRelayHookPath(request.url)) { |
| 151 | return yield* httpEffect; |
| 152 | } |
| 153 | return yield* relayCorsMiddleware(httpEffect); |
| 154 | }), |
| 155 | { global: true }, |
| 156 | ); |
| 157 | |
| 158 | export const layerNotFoundRoute = HttpRouter.add( |
| 159 | "*", |
| 160 | "/*", |
| 161 | HttpServerResponse.empty({ status: 404 }), |
| 162 | ); |
| 163 | |
| 164 | export const layerDocsRedirectRoute = HttpRouter.add( |
| 165 | "GET", |
| 166 | "/", |
| 167 | HttpServerResponse.redirect("/docs"), |
| 168 | ); |
| 169 | |
| 170 | // Finish before the mobile client's 10 s timeout so request cancellation cannot discard unexported spans. |
| 171 | const RELAY_REQUEST_DEADLINE_MS = 9_000; |
| 172 | /** Allow body reading, upstream wait, and inbox hold; an API-sized deadline would drop held webhooks. */ |
| 173 | const RELAY_HOOK_REQUEST_DEADLINE_MS = 25_000; |
| 174 | |
| 175 | const relayRequestDeadline = <E, R>( |
| 176 | httpEffect: Effect.Effect< |
| 177 | HttpServerResponse.HttpServerResponse, |
| 178 | E, |
| 179 | HttpServerRequest.HttpServerRequest | R |
| 180 | >, |
| 181 | deadlineMs = RELAY_REQUEST_DEADLINE_MS, |
| 182 | ) => |
| 183 | httpEffect.pipe( |
| 184 | Effect.timeoutOption(Duration.millis(deadlineMs)), |
| 185 | Effect.flatMap( |
| 186 | Option.match({ |
| 187 | // The enclosing operation owns the span for this inline handler. |
| 188 | onNone: Effect.fnUntraced(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": deadlineMs, |
| 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 | |
| 208 | const SENDER_TRACE_HEADER = /^(traceparent|tracestate|b3|x-b3-.*)$/i; |
| 209 | |
| 210 | // Where the request entered Cloudflare's network. The Worker runs near its |
| 211 | // database, not at this edge, so these are the only way to split relay |
| 212 | // latency by where users are. |
| 213 | const annotateRelayEdgeLocation = Effect.gen(function* () { |
| 214 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 215 | const cf: unknown = request.source instanceof Request ? Reflect.get(request.source, "cf") : null; |
| 216 | if (typeof cf !== "object" || cf === null) return; |
| 217 | const attributes: Record<string, string> = {}; |
| 218 | for (const key of ["colo", "country", "continent"] as const) { |
| 219 | const value: unknown = Reflect.get(cf, key); |
| 220 | if (typeof value === "string" && value) attributes[`relay.edge.${key}`] = value; |
| 221 | } |
| 222 | yield* Effect.annotateCurrentSpan(attributes); |
| 223 | }); |
| 224 | |
| 225 | // The method-named server span is created below; this wrapper must not add another span. |
| 226 | const traceRelayHttpRequest = Effect.fnUntraced(function* <E, R>( |
| 227 | httpEffect: Effect.Effect< |
| 228 | HttpServerResponse.HttpServerResponse, |
| 229 | E, |
| 230 | HttpServerRequest.HttpServerRequest | R |
| 231 | >, |
| 232 | ) { |
| 233 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 234 | const traced = annotateRelayEdgeLocation.pipe( |
| 235 | Effect.andThen(appendRelayTraceContextResponseHeader), |
| 236 | Effect.andThen(relayRequestDeadline(httpEffect)), |
| 237 | ); |
| 238 | if (!isRelayHookPath(request.url)) { |
| 239 | return yield* HttpMiddleware.tracer(traced).pipe( |
| 240 | Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false), |
| 241 | // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first. |
| 242 | Effect.ensuring(Effect.yieldNow), |
| 243 | ); |
| 244 | } |
| 245 | // Hook URLs carry a secret token: the tracer and deadline log see a redacted |
| 246 | // request, while the route itself still receives the original. A webhook |
| 247 | // sender's trace context is dropped, so it cannot pick the trace our relay |
| 248 | // and environment spans land in. |
| 249 | const redacted = request.modify({ |
| 250 | url: redactRelayHookUrl(request.url), |
| 251 | headers: Headers.removeMany( |
| 252 | request.headers, |
| 253 | Object.keys(request.headers).filter((name) => SENDER_TRACE_HEADER.test(name)), |
| 254 | ), |
| 255 | }); |
| 256 | return yield* HttpMiddleware.tracer( |
| 257 | annotateRelayEdgeLocation.pipe( |
| 258 | Effect.andThen(appendRelayTraceContextResponseHeader), |
| 259 | Effect.andThen( |
| 260 | relayRequestDeadline( |
| 261 | httpEffect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)), |
| 262 | RELAY_HOOK_REQUEST_DEADLINE_MS, |
| 263 | ), |
| 264 | ), |
| 265 | ), |
| 266 | ).pipe( |
| 267 | Effect.provideService(HttpServerRequest.HttpServerRequest, redacted), |
| 268 | Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false), |
| 269 | Effect.ensuring(Effect.yieldNow), |
| 270 | ); |
| 271 | }); |
| 272 | |
| 273 | const layerWebhookHeaderRedaction = Layer.effect( |
| 274 | Headers.CurrentRedactedNames, |
| 275 | Effect.map(Headers.CurrentRedactedNames, (names) => [ |
| 276 | ...names, |
| 277 | /signature/i, |
| 278 | /token/i, |
| 279 | /secret/i, |
| 280 | /key/i, |
| 281 | /auth/i, |
| 282 | ]), |
| 283 | ); |
| 284 | |
| 285 | export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>( |
| 286 | httpEffect: Effect.Effect< |
| 287 | HttpServerResponse.HttpServerResponse, |
| 288 | E, |
| 289 | HttpServerRequest.HttpServerRequest | R |
| 290 | >, |
| 291 | tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>, |
| 292 | ) => |
| 293 | traceRelayHttpRequest(httpEffect).pipe( |
| 294 | Effect.provide( |
| 295 | Layer.merge( |
| 296 | tracerLayer, |
| 297 | layerWebhookHeaderRedaction.pipe(Layer.provide(HttpObservability.layer)), |
| 298 | ), |
| 299 | ), |
| 300 | ); |
| 301 | |
| 302 | export const withoutCapturedParentSpan = <A, E, R>( |
| 303 | effect: Effect.Effect<A, E, R>, |
| 304 | ): Effect.Effect<A, E, R> => |
| 305 | Effect.withFiber((fiber) => { |
| 306 | const context = fiber.context; |
| 307 | // HttpApiBuilder captures its build context for route handlers; an event parent would outlive export. |
| 308 | fiber.setContext(Context.omit(Tracer.ParentSpan)(context)); |
| 309 | return effect.pipe(Effect.ensuring(Effect.sync(() => fiber.setContext(context)))); |
| 310 | }); |
| 311 | |
| 312 | export const layerClientAuth = Layer.effect( |
| 313 | RelayClientAuth, |
| 314 | Effect.gen(function* () { |
| 315 | const config = yield* RelayConfiguration.RelayConfiguration; |
| 316 | return { |
| 317 | clientBearer: Effect.fn("relay.auth.client.bearer")(function* (httpEffect, { credential }) { |
| 318 | const token = readHttpAuthorizationCredential(credential); |
| 319 | const verified = yield* verifyRelayClientBearerToken(config, token).pipe( |
| 320 | Effect.tapError((error) => |
| 321 | Effect.annotateCurrentSpan( |
| 322 | "relay.auth.clerk_verification_failure", |
| 323 | clerkVerificationFailureReason(error.cause), |
| 324 | ), |
| 325 | ), |
| 326 | Effect.catch(() => relayAuthInvalidError("invalid_bearer")), |
| 327 | ); |
| 328 | if (!verified.sub) { |
| 329 | yield* Effect.annotateCurrentSpan({ |
| 330 | "relay.auth.clerk_verification_failure": "missing_subject", |
| 331 | }); |
| 332 | return yield* relayAuthInvalidError("invalid_bearer"); |
| 333 | } |
| 334 | yield* Effect.annotateCurrentSpan({ |
| 335 | "relay.auth.mode": verified.mode, |
| 336 | "relay.auth.subject": verified.sub, |
| 337 | }); |
| 338 | |
| 339 | return yield* httpEffect.pipe( |
| 340 | withSpanAttributes({ "user.id": verified.sub }), |
| 341 | Effect.provideService(RelayClientPrincipal, { |
| 342 | userId: verified.sub, |
| 343 | token, |
| 344 | }), |
| 345 | ); |
| 346 | }), |
| 347 | }; |
| 348 | }), |
| 349 | ); |
| 350 | |
| 351 | export const layerEnvironmentAuth = Layer.effect( |
| 352 | RelayEnvironmentAuth, |
| 353 | Effect.gen(function* () { |
| 354 | const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; |
| 355 | return { |
| 356 | environmentBearer: Effect.fn("relay.auth.environment.bearer")(function* ( |
| 357 | httpEffect, |
| 358 | { credential }, |
| 359 | ) { |
| 360 | const token = readHttpAuthorizationCredential(credential); |
| 361 | const principal = yield* credentials.authenticate(token).pipe( |
| 362 | Effect.catchTags({ |
| 363 | EnvironmentCredentialAuthenticatePersistenceError: () => |
| 364 | relayInternalErrorResponse("persistence_failed"), |
| 365 | }), |
| 366 | ); |
| 367 | if (principal._tag === "None") { |
| 368 | return yield* relayAuthInvalidError("not_authorized"); |
| 369 | } |
| 370 | yield* Effect.annotateCurrentSpan({ |
| 371 | "relay.auth.mode": "environment_credential", |
| 372 | }); |
| 373 | return yield* httpEffect.pipe( |
| 374 | withSpanAttributes({ |
| 375 | "relay.environment_id": principal.value.environmentId, |
| 376 | }), |
| 377 | Effect.provideService(RelayEnvironmentPrincipal, principal.value), |
| 378 | ); |
| 379 | }), |
| 380 | }; |
| 381 | }), |
| 382 | ); |
| 383 | |
| 384 | export const layerDpopClientAuth = Layer.effect( |
| 385 | RelayDpopClientAuth, |
| 386 | Effect.gen(function* () { |
| 387 | const relayTokens = yield* RelayTokens.RelayTokens; |
| 388 | return { |
| 389 | relayDpop: Effect.fn("relay.auth.dpop_client")(function* (httpEffect, { credential }) { |
| 390 | yield* appendRelayDpopChallengeHeader; |
| 391 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 392 | if (!isDpopAuthorizationHeader(request.headers.authorization)) { |
| 393 | return yield* relayAuthInvalidError("invalid_bearer"); |
| 394 | } |
| 395 | const token = readHttpAuthorizationCredential(credential); |
| 396 | const verified = yield* relayTokens.verifyDpopAccessToken({ token }); |
| 397 | if (!verified) { |
| 398 | return yield* relayAuthInvalidError("invalid_bearer"); |
| 399 | } |
| 400 | yield* Effect.annotateCurrentSpan({ |
| 401 | "relay.auth.mode": "dpop", |
| 402 | "relay.auth.subject": verified.sub, |
| 403 | }); |
| 404 | return yield* httpEffect.pipe( |
| 405 | withSpanAttributes({ "user.id": verified.sub }), |
| 406 | Effect.provideService(RelayClientPrincipal, { |
| 407 | userId: verified.sub, |
| 408 | token, |
| 409 | proofKeyThumbprint: verified.cnf.jkt, |
| 410 | dpopScopes: verified.scope, |
| 411 | }), |
| 412 | ); |
| 413 | }), |
| 414 | }; |
| 415 | }), |
| 416 | ); |
| 417 | |
| 418 | function isDpopAuthorizationHeader(value: string | undefined): boolean { |
| 419 | return /^DPoP +/iu.test(value ?? ""); |
| 420 | } |
| 421 | |
| 422 | function readHttpAuthorizationCredential(credential: Redacted.Redacted<string>): string { |
| 423 | // Effect beta.73 leaves the scheme separator in decoded HTTP credentials. |
| 424 | return Redacted.value(credential).trimStart(); |
| 425 | } |
| 426 | |
| 427 | export const layerMetadataApi = HttpApiBuilder.group( |
| 428 | RelayApi, |
| 429 | "metadata", |
| 430 | Effect.fnUntraced(function* (handlers) { |
| 431 | const settings = yield* RelayConfiguration.RelayConfiguration; |
| 432 | const issuer = normalizeRelayIssuer(settings.relayIssuer); |
| 433 | const scopes = [ |
| 434 | RelayEnvironmentConnectScope, |
| 435 | RelayEnvironmentStatusScope, |
| 436 | RelayMobileRegistrationScope, |
| 437 | ] as const; |
| 438 | return handlers |
| 439 | .handle("authorizationServer", () => |
| 440 | Effect.succeed({ |
| 441 | issuer, |
| 442 | token_endpoint: `${issuer}/v1/client/dpop-token`, |
| 443 | grant_types_supported: ["urn:ietf:params:oauth:grant-type:token-exchange"], |
| 444 | token_endpoint_auth_methods_supported: ["none"], |
| 445 | dpop_signing_alg_values_supported: ["ES256"], |
| 446 | scopes_supported: scopes, |
| 447 | }), |
| 448 | ) |
| 449 | .handle("protectedResource", () => |
| 450 | Effect.succeed({ |
| 451 | resource: issuer, |
| 452 | authorization_servers: [issuer], |
| 453 | scopes_supported: scopes, |
| 454 | dpop_bound_access_tokens_required: true, |
| 455 | dpop_signing_alg_values_supported: ["ES256"], |
| 456 | }), |
| 457 | ); |
| 458 | }), |
| 459 | ); |
| 460 | |
| 461 | export const layerHealthApi = HttpApiBuilder.group( |
| 462 | RelayApi, |
| 463 | "health", |
| 464 | Effect.fnUntraced(function* (handlers) { |
| 465 | const db = yield* RelayDb.RelayDb; |
| 466 | return handlers.handle( |
| 467 | "health", |
| 468 | Effect.fn("relay.api.health")( |
| 469 | function* () { |
| 470 | yield* db.execute(drizzleSql`SELECT 1`); |
| 471 | return { ok: true, service: "relay" as const }; |
| 472 | }, |
| 473 | Effect.catch(() => relayInternalErrorResponse("database_unavailable")), |
| 474 | ), |
| 475 | ); |
| 476 | }), |
| 477 | ); |
| 478 | |
| 479 | const revokeEnvironmentLinkRecord = Effect.fn("relay.api.client.revokeEnvironmentLinkRecord")( |
| 480 | function* (input: { |
| 481 | readonly userId: string; |
| 482 | readonly environmentId: string; |
| 483 | readonly environmentPublicKey: string; |
| 484 | }) { |
| 485 | const transactions = yield* RelayDb.RelayTransactions; |
| 486 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 487 | const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; |
| 488 | return yield* transactions.withTransaction( |
| 489 | Effect.gen(function* () { |
| 490 | const revoked = yield* links.revokeForUser({ |
| 491 | userId: input.userId, |
| 492 | environmentId: input.environmentId, |
| 493 | }); |
| 494 | if (revoked) { |
| 495 | yield* credentials.revokeForEnvironmentPublicKey({ |
| 496 | environmentId: input.environmentId, |
| 497 | environmentPublicKey: input.environmentPublicKey, |
| 498 | }); |
| 499 | } |
| 500 | return revoked; |
| 501 | }), |
| 502 | ); |
| 503 | }, |
| 504 | ); |
| 505 | |
| 506 | export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnvironmentRecord")( |
| 507 | function* (input: { |
| 508 | readonly userId: string; |
| 509 | readonly environmentId: string; |
| 510 | readonly managedEndpointNamespace?: string | undefined; |
| 511 | }) { |
| 512 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 513 | const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; |
| 514 | const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision({ |
| 515 | userId: input.userId, |
| 516 | environmentId: input.environmentId, |
| 517 | }); |
| 518 | const link = yield* links.getForUser({ |
| 519 | userId: input.userId, |
| 520 | environmentId: input.environmentId, |
| 521 | }); |
| 522 | const unlinked = |
| 523 | link === null |
| 524 | ? false |
| 525 | : yield* revokeEnvironmentLinkRecord({ |
| 526 | userId: input.userId, |
| 527 | environmentId: link.environmentId, |
| 528 | environmentPublicKey: link.environmentPublicKey, |
| 529 | }); |
| 530 | // Cleared before teardown, which can fail: a later link under another key shares this inbox. |
| 531 | const endpointKey = |
| 532 | deprovisionTarget && input.managedEndpointNamespace |
| 533 | ? HeldHooks.endpointKeyForTunnelName( |
| 534 | input.managedEndpointNamespace, |
| 535 | deprovisionTarget.tunnelName, |
| 536 | ) |
| 537 | : null; |
| 538 | if (endpointKey !== null) { |
| 539 | const inbox = yield* HookInbox.HookInbox; |
| 540 | yield* inbox.clear({ endpointKey }).pipe( |
| 541 | Effect.catch((error) => |
| 542 | Effect.logWarning("Could not clear held webhook requests", { |
| 543 | environmentId: input.environmentId, |
| 544 | errorTag: error._tag, |
| 545 | }), |
| 546 | ), |
| 547 | ); |
| 548 | } |
| 549 | // Deprovision after revocation commits; retry even if already revoked to finish failed Cloudflare cleanup. |
| 550 | const deprovisioned = yield* managedEndpointProvider.deprovision({ |
| 551 | userId: input.userId, |
| 552 | environmentId: input.environmentId, |
| 553 | target: deprovisionTarget, |
| 554 | }); |
| 555 | if (!deprovisioned) { |
| 556 | const key = { userId: input.userId, environmentId: input.environmentId }; |
| 557 | const retryTarget = yield* managedEndpointProvider.prepareDeprovision(key); |
| 558 | if (retryTarget !== null && (yield* links.getForUser(key)) === null) { |
| 559 | yield* managedEndpointProvider.deprovision({ ...key, target: retryTarget }); |
| 560 | } |
| 561 | } |
| 562 | return unlinked; |
| 563 | }, |
| 564 | ); |
| 565 | |
| 566 | type EnvironmentTunnelRecoveryProofInput = { |
| 567 | readonly proof: string; |
| 568 | readonly userId: string; |
| 569 | readonly environmentId: string; |
| 570 | readonly environmentPublicKey: string; |
| 571 | } & ( |
| 572 | | { |
| 573 | readonly action: "register"; |
| 574 | readonly tunnelId: string; |
| 575 | readonly origin: RelayManagedEndpointOrigin; |
| 576 | } |
| 577 | | { readonly action: "recover"; readonly origin: RelayManagedEndpointOrigin } |
| 578 | ); |
| 579 | |
| 580 | export const verifyEnvironmentTunnelRecoveryProof = Effect.fn( |
| 581 | "relay.api.server.verifyEnvironmentTunnelRecoveryProof", |
| 582 | )(function* (input: EnvironmentTunnelRecoveryProofInput) { |
| 583 | const config = yield* RelayConfiguration.RelayConfiguration; |
| 584 | const verified = yield* verifyRelayJwt(RelayManagedEndpointRecoveryProofPayload, { |
| 585 | publicKey: input.environmentPublicKey, |
| 586 | token: input.proof, |
| 587 | typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP, |
| 588 | issuer: `t3-env:${input.environmentId}`, |
| 589 | audience: normalizeRelayIssuer(config.relayIssuer), |
| 590 | }).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({}))); |
| 591 | |
| 592 | if ( |
| 593 | verified.environmentId !== input.environmentId || |
| 594 | verified.sub !== input.environmentId || |
| 595 | verified.cloudUserId !== input.userId || |
| 596 | verified.action !== input.action |
| 597 | ) { |
| 598 | return yield* new HttpApiError.Unauthorized({}); |
| 599 | } |
| 600 | if (input.action === "register") { |
| 601 | if ( |
| 602 | verified.action !== "register" || |
| 603 | verified.tunnelId !== input.tunnelId || |
| 604 | verified.origin.localHttpHost !== input.origin.localHttpHost || |
| 605 | verified.origin.localHttpPort !== input.origin.localHttpPort |
| 606 | ) { |
| 607 | return yield* new HttpApiError.Unauthorized({}); |
| 608 | } |
| 609 | return; |
| 610 | } |
| 611 | if ( |
| 612 | verified.action !== "recover" || |
| 613 | verified.origin.localHttpHost !== input.origin.localHttpHost || |
| 614 | verified.origin.localHttpPort !== input.origin.localHttpPort |
| 615 | ) { |
| 616 | return yield* new HttpApiError.Unauthorized({}); |
| 617 | } |
| 618 | }); |
| 619 | |
| 620 | export const registerEnvironmentTunnelRecovery = Effect.fn( |
| 621 | "relay.api.server.registerEnvironmentTunnelRecovery", |
| 622 | )(function* (input: { |
| 623 | readonly userId: string; |
| 624 | readonly environmentId: string; |
| 625 | readonly environmentPublicKey: string; |
| 626 | readonly tunnelId: string; |
| 627 | readonly origin: RelayManagedEndpointOrigin; |
| 628 | }) { |
| 629 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 630 | const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; |
| 631 | const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; |
| 632 | const link = yield* links.getForUser({ |
| 633 | userId: input.userId, |
| 634 | environmentId: input.environmentId, |
| 635 | }); |
| 636 | if ( |
| 637 | link === null || |
| 638 | link.environmentPublicKey !== input.environmentPublicKey || |
| 639 | link.endpoint.providerKind !== "cloudflare_tunnel" |
| 640 | ) { |
| 641 | return yield* new HttpApiError.Unauthorized({}); |
| 642 | } |
| 643 | const status = yield* managedEndpointProvider.reconcileOrigin({ |
| 644 | userId: input.userId, |
| 645 | environmentId: input.environmentId, |
| 646 | tunnelId: input.tunnelId, |
| 647 | origin: input.origin, |
| 648 | endpoint: link.endpoint, |
| 649 | }); |
| 650 | if (status === "recovery_required") { |
| 651 | return { status }; |
| 652 | } |
| 653 | if (!(yield* allocations.enableRecovery(input))) { |
| 654 | return yield* new HttpApiError.Unauthorized({}); |
| 655 | } |
| 656 | return { status }; |
| 657 | }); |
| 658 | |
| 659 | export const recoverEnvironmentTunnelRecord = Effect.fn( |
| 660 | "relay.api.server.recoverEnvironmentTunnelRecord", |
| 661 | )(function* (input: { |
| 662 | readonly userId: string; |
| 663 | readonly environmentId: string; |
| 664 | readonly environmentPublicKey: string; |
| 665 | readonly origin: RelayManagedEndpointOrigin; |
| 666 | }) { |
| 667 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 668 | const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; |
| 669 | const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; |
| 670 | const link = yield* links.getForUser({ |
| 671 | userId: input.userId, |
| 672 | environmentId: input.environmentId, |
| 673 | }); |
| 674 | if ( |
| 675 | link === null || |
| 676 | link.environmentPublicKey !== input.environmentPublicKey || |
| 677 | link.endpoint.providerKind !== "cloudflare_tunnel" |
| 678 | ) { |
| 679 | return yield* new HttpApiError.Unauthorized({}); |
| 680 | } |
| 681 | |
| 682 | const recovered = yield* managedEndpointProvider.provision({ |
| 683 | userId: input.userId, |
| 684 | environmentId: input.environmentId, |
| 685 | origin: input.origin, |
| 686 | reuseReadyTunnel: true, |
| 687 | }); |
| 688 | const recoveredTunnelId = recovered.runtime.tunnelId; |
| 689 | if ( |
| 690 | recoveredTunnelId === undefined || |
| 691 | recovered.endpoint.httpBaseUrl !== link.endpoint.httpBaseUrl || |
| 692 | recovered.endpoint.wsBaseUrl !== link.endpoint.wsBaseUrl |
| 693 | ) { |
| 694 | if (recoveredTunnelId !== undefined) { |
| 695 | yield* managedEndpointProvider |
| 696 | .release({ |
| 697 | userId: input.userId, |
| 698 | environmentId: input.environmentId, |
| 699 | expectedTunnelId: recoveredTunnelId, |
| 700 | }) |
| 701 | .pipe( |
| 702 | Effect.catch((cause) => |
| 703 | Effect.logWarning("Failed to clean up a tunnel with a mismatched endpoint", { |
| 704 | userId: input.userId, |
| 705 | environmentId: input.environmentId, |
| 706 | tunnelId: recoveredTunnelId, |
| 707 | cause, |
| 708 | }), |
| 709 | ), |
| 710 | ); |
| 711 | } |
| 712 | return yield* new HttpApiError.Unauthorized({}); |
| 713 | } |
| 714 | |
| 715 | const enabled = yield* allocations.enableRecovery({ |
| 716 | userId: input.userId, |
| 717 | environmentId: input.environmentId, |
| 718 | tunnelId: recoveredTunnelId, |
| 719 | environmentPublicKey: input.environmentPublicKey, |
| 720 | origin: input.origin, |
| 721 | }); |
| 722 | if (!enabled) { |
| 723 | const owner = { userId: input.userId, environmentId: input.environmentId }; |
| 724 | const target = yield* managedEndpointProvider.prepareDeprovision(owner); |
| 725 | const currentLink = target === null ? null : yield* links.getForUser(input); |
| 726 | if ( |
| 727 | target !== null && |
| 728 | (currentLink === null || currentLink.endpoint.providerKind !== "cloudflare_tunnel") |
| 729 | ) { |
| 730 | yield* managedEndpointProvider.deprovision({ ...owner, target }).pipe( |
| 731 | Effect.catch((cause) => |
| 732 | Effect.logWarning("Failed to clean up a tunnel after its managed link was removed", { |
| 733 | userId: input.userId, |
| 734 | environmentId: input.environmentId, |
| 735 | cause, |
| 736 | }), |
| 737 | ), |
| 738 | ); |
| 739 | } |
| 740 | return yield* new HttpApiError.Unauthorized({}); |
| 741 | } |
| 742 | return { |
| 743 | endpoint: recovered.endpoint, |
| 744 | endpointRuntime: recovered.runtime, |
| 745 | }; |
| 746 | }); |
| 747 | |
| 748 | export const layerMobileApi = HttpApiBuilder.group( |
| 749 | RelayApi, |
| 750 | "mobile", |
| 751 | Effect.fnUntraced(function* (handlers) { |
| 752 | const registrations = yield* MobileRegistrations.MobileRegistrations; |
| 753 | const dpopProofs = yield* DpopProofs.DpopProofReplay; |
| 754 | return handlers |
| 755 | .handle( |
| 756 | "registerDevice", |
| 757 | Effect.fn("relay.api.mobile.registerDevice")(function* (args) { |
| 758 | const { payload } = args; |
| 759 | const { userId, token } = yield* RelayClientPrincipal; |
| 760 | const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); |
| 761 | yield* requireDpopThumbprint(proofKeyThumbprint, { |
| 762 | expectedAccessToken: token, |
| 763 | }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); |
| 764 | return yield* registrations.registerDevice({ userId, payload }); |
| 765 | }, mapRelayCommonApiErrors("invalid_dpop")), |
| 766 | ) |
| 767 | .handle( |
| 768 | "registerLiveActivity", |
| 769 | Effect.fn("relay.api.mobile.registerLiveActivity")(function* (args) { |
| 770 | const { payload } = args; |
| 771 | const { userId, token } = yield* RelayClientPrincipal; |
| 772 | const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); |
| 773 | yield* requireDpopThumbprint(proofKeyThumbprint, { |
| 774 | expectedAccessToken: token, |
| 775 | }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); |
| 776 | return yield* registrations.registerLiveActivity({ userId, payload }); |
| 777 | }, mapRelayCommonApiErrors("invalid_dpop")), |
| 778 | ) |
| 779 | .handle( |
| 780 | "getAgentActivitySnapshot", |
| 781 | Effect.fn("relay.api.mobile.getAgentActivitySnapshot")(function* () { |
| 782 | const { userId, token } = yield* RelayClientPrincipal; |
| 783 | const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); |
| 784 | yield* requireDpopThumbprint(proofKeyThumbprint, { |
| 785 | expectedAccessToken: token, |
| 786 | }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); |
| 787 | return yield* registrations.getAgentActivitySnapshot({ userId }); |
| 788 | }, mapRelayCommonApiErrors("invalid_dpop")), |
| 789 | ) |
| 790 | .handle( |
| 791 | "unregisterDevice", |
| 792 | Effect.fn("relay.api.mobile.unregisterDevice")(function* (args) { |
| 793 | const { params } = args; |
| 794 | const { userId, token } = yield* RelayClientPrincipal; |
| 795 | const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); |
| 796 | yield* requireDpopThumbprint(proofKeyThumbprint, { |
| 797 | expectedAccessToken: token, |
| 798 | }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); |
| 799 | return yield* registrations.unregisterDevice({ userId, deviceId: params.deviceId }); |
| 800 | }, mapRelayCommonApiErrors("invalid_dpop")), |
| 801 | ); |
| 802 | }), |
| 803 | ); |
| 804 | |
| 805 | export const layerClientApi = HttpApiBuilder.group( |
| 806 | RelayApi, |
| 807 | "client", |
| 808 | Effect.fnUntraced(function* (handlers) { |
| 809 | const config = yield* RelayConfiguration.RelayConfiguration; |
| 810 | const random = yield* SecureRandom.SecureRandom; |
| 811 | const relayTokens = yield* RelayTokens.RelayTokens; |
| 812 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 813 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 814 | const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; |
| 815 | const devices = yield* Devices.Devices; |
| 816 | const t3Chat = yield* T3ChatAccounts.T3ChatAccounts; |
| 817 | const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits; |
| 818 | return handlers |
| 819 | .handle( |
| 820 | "listEnvironments", |
| 821 | Effect.fn("relay.api.client.listEnvironments")(function* () { |
| 822 | const { userId } = yield* RelayClientPrincipal; |
| 823 | const environments = yield* links.listForUser({ userId }); |
| 824 | return { environments }; |
| 825 | }, mapRelayCommonApiErrors("not_authorized")), |
| 826 | ) |
| 827 | .handle( |
| 828 | "listDevices", |
| 829 | Effect.fn("relay.api.client.listDevices")(function* () { |
| 830 | yield* appendRelayCredentialResponseHeaders; |
| 831 | const { userId } = yield* RelayClientPrincipal; |
| 832 | const registered = yield* devices.listForUser({ userId }); |
| 833 | return { |
| 834 | devices: registered.flatMap((device) => |
| 835 | device.platform === "ios" && device.iosMajorVersion !== null |
| 836 | ? [{ ...device, platform: "ios" as const, iosMajorVersion: device.iosMajorVersion }] |
| 837 | : [], |
| 838 | ), |
| 839 | }; |
| 840 | }, mapRelayCommonApiErrors("not_authorized")), |
| 841 | ) |
| 842 | .handle( |
| 843 | "listDevicesV2", |
| 844 | Effect.fn("relay.api.client.listDevicesV2")(function* () { |
| 845 | yield* appendRelayCredentialResponseHeaders; |
| 846 | const { userId } = yield* RelayClientPrincipal; |
| 847 | return { devices: yield* devices.listForUser({ userId }) }; |
| 848 | }, mapRelayCommonApiErrors("not_authorized")), |
| 849 | ) |
| 850 | .handle( |
| 851 | "linkEnvironment", |
| 852 | Effect.fn("relay.api.client.linkEnvironment")( |
| 853 | function* (args) { |
| 854 | const { payload } = args; |
| 855 | yield* appendRelayCredentialResponseHeaders; |
| 856 | const { userId } = yield* RelayClientPrincipal; |
| 857 | const result = yield* linker.link({ userId, request: payload }); |
| 858 | return { |
| 859 | ok: true, |
| 860 | cloudUserId: userId, |
| 861 | environmentId: result.environmentId, |
| 862 | endpoint: result.endpoint, |
| 863 | endpointRuntime: result.endpointRuntime, |
| 864 | relayIssuer: config.relayIssuer, |
| 865 | environmentCredential: result.environmentCredential, |
| 866 | cloudMintPublicKey: config.cloudMintPublicKey, |
| 867 | }; |
| 868 | }, |
| 869 | Effect.tapError(appendCloudflareRetryAfter), |
| 870 | mapErrorTags({ |
| 871 | EnvironmentLinkProofExpired: (_error, traceId) => |
| 872 | new RelayEnvironmentLinkProofExpiredError({ |
| 873 | code: "environment_link_proof_expired", |
| 874 | traceId, |
| 875 | }), |
| 876 | EnvironmentLinkProofInvalid: (linkError, traceId) => |
| 877 | new RelayEnvironmentLinkProofInvalidError({ |
| 878 | code: "environment_link_proof_invalid", |
| 879 | reason: linkError.reason, |
| 880 | traceId, |
| 881 | }), |
| 882 | ManagedEndpointProvisioningNotConfigured: (_error, traceId) => |
| 883 | new RelayEnvironmentLinkUnavailableError({ |
| 884 | code: "environment_link_unavailable", |
| 885 | reason: "managed_endpoint_not_configured", |
| 886 | traceId, |
| 887 | }), |
| 888 | ManagedEndpointProvisioningFailed: (error, traceId) => |
| 889 | new RelayEnvironmentLinkUnavailableError({ |
| 890 | code: "environment_link_unavailable", |
| 891 | reason: "managed_endpoint_provisioning_failed", |
| 892 | provisioningStage: error.stage, |
| 893 | traceId, |
| 894 | }), |
| 895 | ManagedEndpointOriginNotAllowed: (_error, traceId) => |
| 896 | new RelayEnvironmentLinkProofInvalidError({ |
| 897 | code: "environment_link_proof_invalid", |
| 898 | reason: "origin_not_allowed", |
| 899 | traceId, |
| 900 | }), |
| 901 | ManagedEndpointDeprovisioningFailed: (_error, traceId) => |
| 902 | new RelayEnvironmentLinkUnavailableError({ |
| 903 | code: "environment_link_unavailable", |
| 904 | reason: "managed_endpoint_provisioning_failed", |
| 905 | traceId, |
| 906 | }), |
| 907 | ManagedTunnelLimitExceeded: (limitError, traceId) => |
| 908 | new RelayEnvironmentLinkLimitExceededError({ |
| 909 | code: "environment_link_limit_exceeded", |
| 910 | maxTunnels: limitError.maxTunnels, |
| 911 | traceId, |
| 912 | }), |
| 913 | EnvironmentLinkUpsertPersistenceError: (_error, traceId) => |
| 914 | new RelayEnvironmentLinkFailedError({ |
| 915 | code: "environment_link_failed", |
| 916 | reason: "link_persistence_failed", |
| 917 | traceId, |
| 918 | }), |
| 919 | EnvironmentCredentialCreatePersistenceError: (_error, traceId) => |
| 920 | new RelayEnvironmentLinkFailedError({ |
| 921 | code: "environment_link_failed", |
| 922 | reason: "credential_persistence_failed", |
| 923 | traceId, |
| 924 | }), |
| 925 | DpopProofReplayPersistenceError: (_error, traceId) => |
| 926 | new RelayEnvironmentLinkFailedError({ |
| 927 | code: "environment_link_failed", |
| 928 | reason: "replay_persistence_failed", |
| 929 | traceId, |
| 930 | }), |
| 931 | }), |
| 932 | mapRelayCommonApiErrors("not_authorized"), |
| 933 | ), |
| 934 | ) |
| 935 | .handle( |
| 936 | "createEnvironmentLinkChallenge", |
| 937 | Effect.fn("relay.api.client.createEnvironmentLinkChallenge")(function* (args) { |
| 938 | yield* appendRelayCredentialResponseHeaders; |
| 939 | const { userId } = yield* RelayClientPrincipal; |
| 940 | const now = yield* DateTime.now; |
| 941 | const expiresAt = DateTime.add(now, { minutes: 5 }); |
| 942 | const jti = yield* random.uuidV4(); |
| 943 | const challenge = yield* relayTokens |
| 944 | .issueLinkChallenge({ |
| 945 | userId, |
| 946 | request: args.payload, |
| 947 | jti, |
| 948 | issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), |
| 949 | expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 950 | }) |
| 951 | .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); |
| 952 | return { challenge, expiresAt: DateTime.formatIso(expiresAt) }; |
| 953 | }, mapRelayCommonApiErrors("not_authorized")), |
| 954 | ) |
| 955 | .handle( |
| 956 | "unlinkEnvironment", |
| 957 | Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) { |
| 958 | const { params } = args; |
| 959 | const { userId } = yield* RelayClientPrincipal; |
| 960 | const unlinked = yield* unlinkEnvironmentRecord({ |
| 961 | userId, |
| 962 | environmentId: params.environmentId, |
| 963 | managedEndpointNamespace: config.managedEndpointNamespace, |
| 964 | }).pipe( |
| 965 | Effect.catchTags({ |
| 966 | SqlError: () => relayInternalErrorResponse("internal_error"), |
| 967 | ManagedEndpointDeprovisioningFailed: () => |
| 968 | relayInternalErrorResponse("upstream_unavailable"), |
| 969 | }), |
| 970 | ); |
| 971 | return { ok: unlinked }; |
| 972 | }, mapRelayCommonApiErrors("not_authorized")), |
| 973 | ) |
| 974 | .handle( |
| 975 | "releaseEnvironmentTunnel", |
| 976 | Effect.fn("relay.api.client.releaseEnvironmentTunnel")(function* (args) { |
| 977 | const { params } = args; |
| 978 | const { userId } = yield* RelayClientPrincipal; |
| 979 | // False means concurrent provisioning retained the tunnel; the caller must keep its runtime config. |
| 980 | const released = yield* managedEndpointProvider |
| 981 | .release({ |
| 982 | userId, |
| 983 | environmentId: params.environmentId, |
| 984 | }) |
| 985 | .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))); |
| 986 | return { ok: released }; |
| 987 | }, mapRelayCommonApiErrors("not_authorized")), |
| 988 | ) |
| 989 | .handle( |
| 990 | "getT3ChatLink", |
| 991 | Effect.fn("relay.api.client.getT3ChatLink")(function* () { |
| 992 | yield* appendRelayCredentialResponseHeaders; |
| 993 | const { userId } = yield* RelayClientPrincipal; |
| 994 | const link = t3Chat.available |
| 995 | ? yield* t3Chat |
| 996 | .getLink({ userId }) |
| 997 | .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))) |
| 998 | : null; |
| 999 | const maxTunnelsOverride = yield* tunnelLimits |
| 1000 | .getOverride({ userId }) |
| 1001 | .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); |
| 1002 | return { |
| 1003 | available: t3Chat.available, |
| 1004 | link, |
| 1005 | ...(maxTunnelsOverride === null ? {} : { maxTunnelsOverride }), |
| 1006 | }; |
| 1007 | }, mapRelayCommonApiErrors("not_authorized")), |
| 1008 | ) |
| 1009 | .handle( |
| 1010 | "createT3ChatLinkRequest", |
| 1011 | Effect.fn("relay.api.client.createT3ChatLinkRequest")(function* () { |
| 1012 | const { userId } = yield* RelayClientPrincipal; |
| 1013 | const url = yield* t3Chat.createLinkUrl({ userId }).pipe( |
| 1014 | Effect.catchTags({ |
| 1015 | T3ChatNotConfigured: () => relayInternalErrorResponse("internal_error"), |
| 1016 | ClerkUserLookupFailed: () => relayInternalErrorResponse("upstream_unavailable"), |
| 1017 | }), |
| 1018 | ); |
| 1019 | return { url }; |
| 1020 | }, mapRelayCommonApiErrors("not_authorized")), |
| 1021 | ) |
| 1022 | .handle( |
| 1023 | "unlinkT3Chat", |
| 1024 | Effect.fn("relay.api.client.unlinkT3Chat")(function* () { |
| 1025 | const { userId } = yield* RelayClientPrincipal; |
| 1026 | yield* t3Chat |
| 1027 | .unlink({ userId }) |
| 1028 | .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))); |
| 1029 | return { ok: true }; |
| 1030 | }, mapRelayCommonApiErrors("not_authorized")), |
| 1031 | ); |
| 1032 | }), |
| 1033 | ); |
| 1034 | |
| 1035 | export const layerTokenApi = HttpApiBuilder.group( |
| 1036 | RelayApi, |
| 1037 | "token", |
| 1038 | Effect.fnUntraced(function* (handlers) { |
| 1039 | const config = yield* RelayConfiguration.RelayConfiguration; |
| 1040 | const random = yield* SecureRandom.SecureRandom; |
| 1041 | const dpopProofs = yield* DpopProofs.DpopProofReplay; |
| 1042 | const relayTokens = yield* RelayTokens.RelayTokens; |
| 1043 | return handlers.handle( |
| 1044 | "exchangeDpopAccessToken", |
| 1045 | Effect.fn("relay.api.token.exchangeDpopAccessToken")(function* (args) { |
| 1046 | yield* appendRelayCredentialResponseHeaders; |
| 1047 | const issuer = normalizeRelayIssuer(config.relayIssuer); |
| 1048 | const requestedScopes = relayTokens.resolveDpopAccessTokenScopes({ |
| 1049 | clientId: args.payload.client_id, |
| 1050 | scope: args.payload.scope, |
| 1051 | }); |
| 1052 | yield* Effect.annotateCurrentSpan({ |
| 1053 | "relay.auth.mode": "clerk_bearer_token_exchange", |
| 1054 | "relay.oauth.client_id": args.payload.client_id, |
| 1055 | "relay.oauth.scopes": args.payload.scope, |
| 1056 | }); |
| 1057 | if (args.payload.resource !== issuer || requestedScopes === null) { |
| 1058 | return yield* new HttpApiError.Unauthorized({}); |
| 1059 | } |
| 1060 | |
| 1061 | const verified = yield* verifyClerkBearerToken(config, args.payload.subject_token).pipe( |
| 1062 | Effect.catch(() => relayAuthInvalidError("invalid_bearer")), |
| 1063 | ); |
| 1064 | if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)) { |
| 1065 | return yield* relayAuthInvalidError("invalid_bearer"); |
| 1066 | } |
| 1067 | const proofKeyThumbprint = yield* requireDpopProof().pipe( |
| 1068 | Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs), |
| 1069 | ); |
| 1070 | const now = yield* DateTime.now; |
| 1071 | const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL); |
| 1072 | const jti = yield* random.uuidV4(); |
| 1073 | return { |
| 1074 | access_token: yield* relayTokens |
| 1075 | .issueDpopAccessToken({ |
| 1076 | userId: verified.sub, |
| 1077 | proofKeyThumbprint, |
| 1078 | jti, |
| 1079 | issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), |
| 1080 | expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 1081 | clientId: args.payload.client_id, |
| 1082 | scopes: requestedScopes, |
| 1083 | }) |
| 1084 | .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))), |
| 1085 | issued_token_type: RelayAccessTokenType, |
| 1086 | token_type: "DPoP" as const, |
| 1087 | expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL), |
| 1088 | scope: encodeOAuthScope(requestedScopes), |
| 1089 | }; |
| 1090 | }, mapRelayCommonApiErrors("invalid_dpop")), |
| 1091 | ); |
| 1092 | }), |
| 1093 | ); |
| 1094 | |
| 1095 | export const layerDpopClientApi = HttpApiBuilder.group( |
| 1096 | RelayApi, |
| 1097 | "dpopClient", |
| 1098 | Effect.fnUntraced(function* (handlers) { |
| 1099 | const connector = yield* EnvironmentConnector.EnvironmentConnector; |
| 1100 | const dpopProofs = yield* DpopProofs.DpopProofReplay; |
| 1101 | return handlers |
| 1102 | .handle( |
| 1103 | "connectEnvironment", |
| 1104 | Effect.fn("relay.api.dpopClient.connectEnvironment")( |
| 1105 | function* (args) { |
| 1106 | const { params, payload } = args; |
| 1107 | yield* appendRelayCredentialResponseHeaders; |
| 1108 | const { userId, token } = yield* RelayClientPrincipal; |
| 1109 | const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:connect"); |
| 1110 | const requestedThumbprint = resolveConnectClientKeyThumbprint(payload); |
| 1111 | if (!requestedThumbprint || requestedThumbprint !== proofKeyThumbprint) { |
| 1112 | return yield* new HttpApiError.Unauthorized({}); |
| 1113 | } |
| 1114 | const clientProofKeyThumbprint = yield* requireDpopThumbprint(proofKeyThumbprint, { |
| 1115 | expectedAccessToken: token, |
| 1116 | }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); |
| 1117 | return yield* connector.connect({ |
| 1118 | userId, |
| 1119 | environmentId: params.environmentId, |
| 1120 | clientProofKeyThumbprint, |
| 1121 | ...(payload.deviceId ? { deviceId: payload.deviceId } : {}), |
| 1122 | }); |
| 1123 | }, |
| 1124 | mapRelayCommonApiErrors("invalid_dpop"), |
| 1125 | mapErrorTags({ |
| 1126 | EnvironmentConnectNotAuthorized: (error, traceId) => |
| 1127 | new RelayEnvironmentConnectNotAuthorizedError({ |
| 1128 | code: "environment_connect_not_authorized", |
| 1129 | reason: error.reason, |
| 1130 | traceId, |
| 1131 | }), |
| 1132 | EnvironmentMintRequestFailed: (error, traceId) => |
| 1133 | new RelayEnvironmentEndpointUnavailableError({ |
| 1134 | code: "environment_endpoint_unavailable", |
| 1135 | reason: "endpoint_request_failed", |
| 1136 | ...(error.endpointFailure ? { endpointFailure: error.endpointFailure } : {}), |
| 1137 | ...(error.endpointStatus ? { endpointStatus: error.endpointStatus } : {}), |
| 1138 | traceId, |
| 1139 | }), |
| 1140 | EnvironmentMintRequestTimedOut: (_error, traceId) => |
| 1141 | new RelayEnvironmentEndpointTimedOutError({ |
| 1142 | code: "environment_endpoint_timed_out", |
| 1143 | traceId, |
| 1144 | }), |
| 1145 | EnvironmentMintResponseInvalid: (_error, traceId) => |
| 1146 | new RelayEnvironmentEndpointUnavailableError({ |
| 1147 | code: "environment_endpoint_unavailable", |
| 1148 | reason: "endpoint_response_invalid", |
| 1149 | traceId, |
| 1150 | }), |
| 1151 | }), |
| 1152 | ), |
| 1153 | ) |
| 1154 | .handle( |
| 1155 | "getEnvironmentStatus", |
| 1156 | Effect.fn("relay.api.dpopClient.getEnvironmentStatus")( |
| 1157 | function* (args) { |
| 1158 | const { params } = args; |
| 1159 | const { userId, token } = yield* RelayClientPrincipal; |
| 1160 | const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:status"); |
| 1161 | yield* requireDpopThumbprint(proofKeyThumbprint, { |
| 1162 | expectedAccessToken: token, |
| 1163 | }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); |
| 1164 | return yield* connector.status({ |
| 1165 | userId, |
| 1166 | environmentId: params.environmentId, |
| 1167 | }); |
| 1168 | }, |
| 1169 | mapRelayCommonApiErrors("invalid_dpop"), |
| 1170 | mapErrorTags({ |
| 1171 | EnvironmentConnectNotAuthorized: (error, traceId) => |
| 1172 | new RelayEnvironmentConnectNotAuthorizedError({ |
| 1173 | code: "environment_connect_not_authorized", |
| 1174 | reason: error.reason, |
| 1175 | traceId, |
| 1176 | }), |
| 1177 | EnvironmentMintRequestFailed: (error, traceId) => |
| 1178 | new RelayEnvironmentEndpointUnavailableError({ |
| 1179 | code: "environment_endpoint_unavailable", |
| 1180 | reason: "endpoint_request_failed", |
| 1181 | ...(error.endpointFailure ? { endpointFailure: error.endpointFailure } : {}), |
| 1182 | ...(error.endpointStatus ? { endpointStatus: error.endpointStatus } : {}), |
| 1183 | traceId, |
| 1184 | }), |
| 1185 | EnvironmentMintRequestTimedOut: (_error, traceId) => |
| 1186 | new RelayEnvironmentEndpointTimedOutError({ |
| 1187 | code: "environment_endpoint_timed_out", |
| 1188 | traceId, |
| 1189 | }), |
| 1190 | EnvironmentMintResponseInvalid: (_error, traceId) => |
| 1191 | new RelayEnvironmentEndpointUnavailableError({ |
| 1192 | code: "environment_endpoint_unavailable", |
| 1193 | reason: "endpoint_response_invalid", |
| 1194 | traceId, |
| 1195 | }), |
| 1196 | }), |
| 1197 | ), |
| 1198 | ); |
| 1199 | }), |
| 1200 | ); |
| 1201 | |
| 1202 | export const layerServerApi = HttpApiBuilder.group( |
| 1203 | RelayApi, |
| 1204 | "server", |
| 1205 | Effect.fnUntraced(function* (handlers) { |
| 1206 | const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; |
| 1207 | const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; |
| 1208 | const heldHooks = yield* HeldHooks.HeldHooks; |
| 1209 | const requireOwnEnvironment = |
| 1210 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 1211 | Effect.fnUntraced(function* (environmentId: string) { |
| 1212 | const principal = yield* RelayEnvironmentPrincipal; |
| 1213 | if (principal.environmentId !== environmentId) { |
| 1214 | return yield* new HttpApiError.Unauthorized({}); |
| 1215 | } |
| 1216 | }); |
| 1217 | const activityHandlers = handlers.handle( |
| 1218 | "publishAgentActivity", |
| 1219 | Effect.fn("relay.api.server.publishAgentActivity")( |
| 1220 | function* (args) { |
| 1221 | const { params, payload } = args; |
| 1222 | const principal = yield* RelayEnvironmentPrincipal; |
| 1223 | if (principal.environmentId !== params.environmentId) { |
| 1224 | return yield* new HttpApiError.Unauthorized({}); |
| 1225 | } |
| 1226 | yield* publishSignatures.verify({ |
| 1227 | environmentId: params.environmentId, |
| 1228 | environmentPublicKey: principal.environmentPublicKey, |
| 1229 | threadId: params.threadId, |
| 1230 | request: payload, |
| 1231 | }); |
| 1232 | return yield* publisher.publish({ |
| 1233 | environmentId: params.environmentId, |
| 1234 | environmentPublicKey: principal.environmentPublicKey, |
| 1235 | threadId: params.threadId, |
| 1236 | state: payload.state, |
| 1237 | }); |
| 1238 | }, |
| 1239 | mapErrorTags({ |
| 1240 | EnvironmentPublishSignatureExpired: (_error, traceId) => |
| 1241 | new RelayAgentActivityPublishProofExpiredError({ |
| 1242 | code: "agent_activity_publish_proof_expired", |
| 1243 | traceId, |
| 1244 | }), |
| 1245 | EnvironmentPublishSignatureInvalid: (_error, traceId) => |
| 1246 | new RelayAgentActivityPublishProofInvalidError({ |
| 1247 | code: "agent_activity_publish_proof_invalid", |
| 1248 | reason: "invalid_signature_or_payload", |
| 1249 | traceId, |
| 1250 | }), |
| 1251 | DpopProofReplayPersistenceError: (_error, traceId) => |
| 1252 | new RelayInternalError({ |
| 1253 | code: "internal_error", |
| 1254 | reason: "persistence_failed", |
| 1255 | traceId, |
| 1256 | }), |
| 1257 | ApnsDeliveryJobQueuePayloadInvalid: (_error, traceId) => |
| 1258 | new RelayInternalError({ |
| 1259 | code: "internal_error", |
| 1260 | reason: "internal_error", |
| 1261 | traceId, |
| 1262 | }), |
| 1263 | ApnsDeliveryJobLiveActivityAggregateMissing: (_error, traceId) => |
| 1264 | new RelayInternalError({ |
| 1265 | code: "internal_error", |
| 1266 | reason: "internal_error", |
| 1267 | traceId, |
| 1268 | }), |
| 1269 | ApnsDeliveryJobLiveActivityNotificationUnexpected: (_error, traceId) => |
| 1270 | new RelayInternalError({ |
| 1271 | code: "internal_error", |
| 1272 | reason: "internal_error", |
| 1273 | traceId, |
| 1274 | }), |
| 1275 | ApnsDeliveryJobPushNotificationMissing: (_error, traceId) => |
| 1276 | new RelayInternalError({ |
| 1277 | code: "internal_error", |
| 1278 | reason: "internal_error", |
| 1279 | traceId, |
| 1280 | }), |
| 1281 | ApnsDeliveryJobPushNotificationAggregateUnexpected: (_error, traceId) => |
| 1282 | new RelayInternalError({ |
| 1283 | code: "internal_error", |
| 1284 | reason: "internal_error", |
| 1285 | traceId, |
| 1286 | }), |
| 1287 | ApnsDeliveryJobCreatedAtInvalid: (_error, traceId) => |
| 1288 | new RelayInternalError({ |
| 1289 | code: "internal_error", |
| 1290 | reason: "internal_error", |
| 1291 | traceId, |
| 1292 | }), |
| 1293 | ApnsDeliveryJobExpiresAtInvalid: (_error, traceId) => |
| 1294 | new RelayInternalError({ |
| 1295 | code: "internal_error", |
| 1296 | reason: "internal_error", |
| 1297 | traceId, |
| 1298 | }), |
| 1299 | ApnsDeliveryJobTimeWindowInvalid: (_error, traceId) => |
| 1300 | new RelayInternalError({ |
| 1301 | code: "internal_error", |
| 1302 | reason: "internal_error", |
| 1303 | traceId, |
| 1304 | }), |
| 1305 | ApnsDeliveryJobTimeWindowTooLong: (_error, traceId) => |
| 1306 | new RelayInternalError({ |
| 1307 | code: "internal_error", |
| 1308 | reason: "internal_error", |
| 1309 | traceId, |
| 1310 | }), |
| 1311 | ApnsDeliveryJobSignatureInvalid: (_error, traceId) => |
| 1312 | new RelayInternalError({ |
| 1313 | code: "internal_error", |
| 1314 | reason: "internal_error", |
| 1315 | traceId, |
| 1316 | }), |
| 1317 | ApnsDeliveryJobExpired: (_error, traceId) => |
| 1318 | new RelayInternalError({ |
| 1319 | code: "internal_error", |
| 1320 | reason: "internal_error", |
| 1321 | traceId, |
| 1322 | }), |
| 1323 | ApnsDeliveryJobClaimInFlight: (_error, traceId) => |
| 1324 | new RelayInternalError({ |
| 1325 | code: "internal_error", |
| 1326 | reason: "internal_error", |
| 1327 | traceId, |
| 1328 | }), |
| 1329 | ApnsDeliveryQueueSendError: (_error, traceId) => |
| 1330 | new RelayInternalError({ |
| 1331 | code: "internal_error", |
| 1332 | reason: "upstream_unavailable", |
| 1333 | traceId, |
| 1334 | }), |
| 1335 | FcmDeliveryError: (_error, traceId) => |
| 1336 | new RelayInternalError({ |
| 1337 | code: "internal_error", |
| 1338 | reason: "upstream_unavailable", |
| 1339 | traceId, |
| 1340 | }), |
| 1341 | }), |
| 1342 | mapRelayCommonApiErrors("not_authorized"), |
| 1343 | ), |
| 1344 | ); |
| 1345 | |
| 1346 | return activityHandlers |
| 1347 | .handle( |
| 1348 | "registerManagedEndpointRecovery", |
| 1349 | Effect.fn("relay.api.server.registerManagedEndpointRecovery")( |
| 1350 | function* ({ params, payload }) { |
| 1351 | const principal = yield* RelayEnvironmentPrincipal; |
| 1352 | if (principal.environmentId !== params.environmentId) { |
| 1353 | return yield* new HttpApiError.Unauthorized({}); |
| 1354 | } |
| 1355 | yield* verifyEnvironmentTunnelRecoveryProof({ |
| 1356 | action: "register", |
| 1357 | proof: payload.proof, |
| 1358 | userId: payload.cloudUserId, |
| 1359 | environmentId: params.environmentId, |
| 1360 | environmentPublicKey: principal.environmentPublicKey, |
| 1361 | tunnelId: payload.tunnelId, |
| 1362 | origin: payload.origin, |
| 1363 | }); |
| 1364 | yield* appendRelayCredentialResponseHeaders; |
| 1365 | return yield* registerEnvironmentTunnelRecovery({ |
| 1366 | userId: payload.cloudUserId, |
| 1367 | environmentId: params.environmentId, |
| 1368 | environmentPublicKey: principal.environmentPublicKey, |
| 1369 | tunnelId: payload.tunnelId, |
| 1370 | origin: payload.origin, |
| 1371 | }); |
| 1372 | }, |
| 1373 | Effect.tapError(appendCloudflareRetryAfter), |
| 1374 | Effect.catchTags({ |
| 1375 | ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})), |
| 1376 | ManagedEndpointProvisioningNotConfigured: () => |
| 1377 | relayInternalErrorResponse("upstream_unavailable"), |
| 1378 | ManagedEndpointProvisioningFailed: () => |
| 1379 | relayInternalErrorResponse("upstream_unavailable"), |
| 1380 | ManagedTunnelLimitExceeded: () => relayInternalErrorResponse("upstream_unavailable"), |
| 1381 | }), |
| 1382 | mapRelayCommonApiErrors("not_authorized"), |
| 1383 | ), |
| 1384 | ) |
| 1385 | .handle( |
| 1386 | "recoverManagedEndpoint", |
| 1387 | Effect.fn("relay.api.server.recoverManagedEndpoint")( |
| 1388 | function* ({ params, payload }) { |
| 1389 | const principal = yield* RelayEnvironmentPrincipal; |
| 1390 | if (principal.environmentId !== params.environmentId) { |
| 1391 | return yield* new HttpApiError.Unauthorized({}); |
| 1392 | } |
| 1393 | yield* verifyEnvironmentTunnelRecoveryProof({ |
| 1394 | action: "recover", |
| 1395 | proof: payload.proof, |
| 1396 | userId: payload.cloudUserId, |
| 1397 | environmentId: params.environmentId, |
| 1398 | environmentPublicKey: principal.environmentPublicKey, |
| 1399 | origin: payload.origin, |
| 1400 | }); |
| 1401 | yield* appendRelayCredentialResponseHeaders; |
| 1402 | return yield* recoverEnvironmentTunnelRecord({ |
| 1403 | userId: payload.cloudUserId, |
| 1404 | environmentId: params.environmentId, |
| 1405 | environmentPublicKey: principal.environmentPublicKey, |
| 1406 | origin: payload.origin, |
| 1407 | }); |
| 1408 | }, |
| 1409 | Effect.tapError(appendCloudflareRetryAfter), |
| 1410 | Effect.catchTags({ |
| 1411 | ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})), |
| 1412 | ManagedEndpointProvisioningNotConfigured: () => |
| 1413 | relayInternalErrorResponse("upstream_unavailable"), |
| 1414 | ManagedEndpointProvisioningFailed: () => |
| 1415 | relayInternalErrorResponse("upstream_unavailable"), |
| 1416 | ManagedEndpointDeprovisioningFailed: () => |
| 1417 | relayInternalErrorResponse("upstream_unavailable"), |
| 1418 | ManagedTunnelLimitExceeded: () => relayInternalErrorResponse("upstream_unavailable"), |
| 1419 | }), |
| 1420 | mapRelayCommonApiErrors("not_authorized"), |
| 1421 | ), |
| 1422 | ) |
| 1423 | .handle( |
| 1424 | "updateLinkPreferences", |
| 1425 | Effect.fn("relay.api.server.updateLinkPreferences")(function* ({ params, payload }) { |
| 1426 | yield* requireOwnEnvironment(params.environmentId); |
| 1427 | const principal = yield* RelayEnvironmentPrincipal; |
| 1428 | yield* heldHooks.setHoldWhileOffline({ |
| 1429 | environmentId: params.environmentId, |
| 1430 | environmentPublicKey: principal.environmentPublicKey, |
| 1431 | holdWebhooksWhileOffline: payload.holdWebhooksWhileOffline, |
| 1432 | }); |
| 1433 | return payload; |
| 1434 | }, mapRelayCommonApiErrors("not_authorized")), |
| 1435 | ) |
| 1436 | .handle( |
| 1437 | "updateLiveActivityPreference", |
| 1438 | Effect.fn("relay.api.server.updateLiveActivityPreference")(function* ({ params, payload }) { |
| 1439 | yield* requireOwnEnvironment(params.environmentId); |
| 1440 | const principal = yield* RelayEnvironmentPrincipal; |
| 1441 | const links = yield* EnvironmentLinks.EnvironmentLinks; |
| 1442 | const ok = yield* links.updateLiveActivityPreference({ |
| 1443 | userId: payload.cloudUserId, |
| 1444 | environmentId: params.environmentId, |
| 1445 | environmentPublicKey: principal.environmentPublicKey, |
| 1446 | liveActivitiesEnabled: payload.liveActivitiesEnabled, |
| 1447 | }); |
| 1448 | return { ok }; |
| 1449 | }, mapRelayCommonApiErrors("not_authorized")), |
| 1450 | ) |
| 1451 | .handle( |
| 1452 | "wakeHeldHooks", |
| 1453 | Effect.fn("relay.api.server.wakeHeldHooks")(function* ({ params }) { |
| 1454 | yield* requireOwnEnvironment(params.environmentId); |
| 1455 | const principal = yield* RelayEnvironmentPrincipal; |
| 1456 | const pending = yield* heldHooks.wake({ |
| 1457 | environmentId: params.environmentId, |
| 1458 | environmentPublicKey: principal.environmentPublicKey, |
| 1459 | }); |
| 1460 | return { pending }; |
| 1461 | }, mapRelayCommonApiErrors("not_authorized")), |
| 1462 | ); |
| 1463 | }), |
| 1464 | ); |
| 1465 | |
| 1466 | class ClerkTokenVerificationFailed extends Schema.TaggedError<ClerkTokenVerificationFailed>()( |
| 1467 | "ClerkTokenVerificationFailed", |
| 1468 | { |
| 1469 | cause: Schema.Defect(), |
| 1470 | }, |
| 1471 | ) { |
| 1472 | override get message(): string { |
| 1473 | return "Clerk token verification failed"; |
| 1474 | } |
| 1475 | } |
| 1476 | |
| 1477 | const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized); |
| 1478 | const isDpopProofRejected = Schema.is(DpopProofs.DpopProofRejected); |
| 1479 | |
| 1480 | const currentTraceId = Effect.currentParentSpan.pipe( |
| 1481 | Effect.map((span) => span.traceId), |
| 1482 | Effect.orElseSucceed(() => "unavailable"), |
| 1483 | ); |
| 1484 | |
| 1485 | const RelayCommonPersistenceError = Schema.Union([ |
| 1486 | Devices.DeviceRegistrationPersistenceError, |
| 1487 | Devices.DeviceUnregistrationPersistenceError, |
| 1488 | Devices.DeviceListPersistenceError, |
| 1489 | LiveActivities.LiveActivityRegistrationPersistenceError, |
| 1490 | EnvironmentLinks.EnvironmentLinkUserListPersistenceError, |
| 1491 | EnvironmentLinks.EnvironmentLinkListPersistenceError, |
| 1492 | EnvironmentLinks.EnvironmentLinkLookupPersistenceError, |
| 1493 | EnvironmentLinks.EnvironmentLinkRevokePersistenceError, |
| 1494 | ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError, |
| 1495 | EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError, |
| 1496 | EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError, |
| 1497 | DpopProofs.DpopProofReplayPersistenceError, |
| 1498 | LiveActivities.LiveActivityTargetListPersistenceError, |
| 1499 | AgentActivityRows.AgentActivityRowUpsertPersistenceError, |
| 1500 | AgentActivityRows.AgentActivityRowDeletePersistenceError, |
| 1501 | AgentActivityRows.AgentActivityRowListPersistenceError, |
| 1502 | LiveActivities.LiveActivityDeliveryMarkPersistenceError, |
| 1503 | DeliveryAttempts.DeliveryAttemptRecordPersistenceError, |
| 1504 | EnvironmentLinks.EnvironmentLinkEnvironmentLookupPersistenceError, |
| 1505 | HookInbox.HookInboxError, |
| 1506 | ]); |
| 1507 | type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type; |
| 1508 | const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError); |
| 1509 | |
| 1510 | type MapRelayCommonApiError<E> = |
| 1511 | | Exclude< |
| 1512 | E, |
| 1513 | HttpApiError.Unauthorized | DpopProofs.DpopProofRejected | RelayCommonPersistenceError |
| 1514 | > |
| 1515 | | (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError) |
| 1516 | | (Extract<E, DpopProofs.DpopProofRejected> extends never ? never : RelayAuthInvalidError) |
| 1517 | | (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError); |
| 1518 | |
| 1519 | export function relayDpopFailureReason( |
| 1520 | code: DpopProofs.DpopProofFailureCode, |
| 1521 | ): RelayDpopFailureReason { |
| 1522 | switch (code) { |
| 1523 | case "time_window": |
| 1524 | return "time_window"; |
| 1525 | case "key_mismatch": |
| 1526 | return "key_mismatch"; |
| 1527 | case "method_mismatch": |
| 1528 | case "url_mismatch": |
| 1529 | return "request_mismatch"; |
| 1530 | case "access_token_hash_mismatch": |
| 1531 | return "token_mismatch"; |
| 1532 | case "replayed": |
| 1533 | return "replay"; |
| 1534 | case "missing_proof": |
| 1535 | case "malformed_proof": |
| 1536 | case "invalid_signature": |
| 1537 | case "invalid_proof": |
| 1538 | return "invalid_proof"; |
| 1539 | } |
| 1540 | } |
| 1541 | |
| 1542 | function relayInternalErrorResponse(reason: RelayInternalError["reason"]) { |
| 1543 | return currentTraceId.pipe( |
| 1544 | Effect.flatMap((traceId) => |
| 1545 | Effect.fail(new RelayInternalError({ code: "internal_error", reason, traceId })), |
| 1546 | ), |
| 1547 | ); |
| 1548 | } |
| 1549 | |
| 1550 | function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { |
| 1551 | const mapError = Effect.fnUntraced(function* <E>(error: E) { |
| 1552 | const traceId = yield* currentTraceId; |
| 1553 | if (isDpopProofRejected(error)) { |
| 1554 | yield* Effect.annotateCurrentSpan({ |
| 1555 | "relay.dpop.failure_code": error.code, |
| 1556 | }); |
| 1557 | return yield* Effect.fail( |
| 1558 | new RelayAuthInvalidError({ |
| 1559 | code: "auth_invalid", |
| 1560 | reason: authReason, |
| 1561 | ...(authReason === "invalid_dpop" |
| 1562 | ? { dpopFailureReason: relayDpopFailureReason(error.code) } |
| 1563 | : {}), |
| 1564 | traceId, |
| 1565 | }) as MapRelayCommonApiError<E>, |
| 1566 | ); |
| 1567 | } |
| 1568 | if (isHttpUnauthorized(error)) { |
| 1569 | if (authReason === "invalid_dpop") { |
| 1570 | yield* Effect.annotateCurrentSpan({ |
| 1571 | "relay.dpop.failure_code": "invalid_proof", |
| 1572 | }); |
| 1573 | } |
| 1574 | return yield* Effect.fail( |
| 1575 | new RelayAuthInvalidError({ |
| 1576 | code: "auth_invalid", |
| 1577 | reason: authReason, |
| 1578 | ...(authReason === "invalid_dpop" ? { dpopFailureReason: "invalid_proof" } : {}), |
| 1579 | traceId, |
| 1580 | }) as MapRelayCommonApiError<E>, |
| 1581 | ); |
| 1582 | } |
| 1583 | if (isRelayCommonPersistenceError(error)) { |
| 1584 | return yield* Effect.fail( |
| 1585 | new RelayInternalError({ |
| 1586 | code: "internal_error", |
| 1587 | reason: "persistence_failed", |
| 1588 | traceId, |
| 1589 | }) as MapRelayCommonApiError<E>, |
| 1590 | ); |
| 1591 | } |
| 1592 | |
| 1593 | return yield* Effect.fail(error as MapRelayCommonApiError<E>); |
| 1594 | }); |
| 1595 | |
| 1596 | return <A, E, R>( |
| 1597 | effect: Effect.Effect<A, E, R>, |
| 1598 | ): Effect.Effect<A, MapRelayCommonApiError<E>, R> => effect.pipe(Effect.catch(mapError)); |
| 1599 | } |
| 1600 | |
| 1601 | type TaggedErrorTag<E> = Extract<E, { readonly _tag: string }>["_tag"]; |
| 1602 | |
| 1603 | type MapErrorTagCases<E> = { |
| 1604 | readonly [K in TaggedErrorTag<E>]+?: ( |
| 1605 | error: Extract<E, { readonly _tag: K }>, |
| 1606 | traceId: string, |
| 1607 | ) => unknown; |
| 1608 | }; |
| 1609 | |
| 1610 | type MappedTagError<Cases> = Cases[keyof Cases] extends ( |
| 1611 | ...args: ReadonlyArray<never> |
| 1612 | ) => infer Error |
| 1613 | ? Error |
| 1614 | : never; |
| 1615 | |
| 1616 | type CatchTagCases<E, Cases> = { |
| 1617 | readonly [K in TaggedErrorTag<E>]+?: ( |
| 1618 | error: Extract<E, { readonly _tag: K }>, |
| 1619 | ) => Effect.Effect<never, MappedTagError<Cases>>; |
| 1620 | } & (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }); |
| 1621 | |
| 1622 | function mapErrorTags< |
| 1623 | E, |
| 1624 | Cases extends MapErrorTagCases<E> & |
| 1625 | (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }), |
| 1626 | >(cases: Cases) { |
| 1627 | const catchCases = Record.map( |
| 1628 | cases as Record.ReadonlyRecord< |
| 1629 | string, |
| 1630 | (error: never, traceId: string) => MappedTagError<Cases> |
| 1631 | >, |
| 1632 | (makeError) => (error: never) => |
| 1633 | currentTraceId.pipe(Effect.flatMap((traceId) => Effect.fail(makeError(error, traceId)))), |
| 1634 | ) as CatchTagCases<E, Cases>; |
| 1635 | |
| 1636 | return <A, R>( |
| 1637 | self: Effect.Effect<A, E, R>, |
| 1638 | ): Effect.Effect<A, Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>, R> => |
| 1639 | // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off |
| 1640 | Effect.catchTags(self, catchCases) as Effect.Effect< |
| 1641 | A, |
| 1642 | Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>, |
| 1643 | R |
| 1644 | >; |
| 1645 | } |
| 1646 | |
| 1647 | function resolveConnectClientKeyThumbprint(payload: RelayEnvironmentConnectRequest): string | null { |
| 1648 | const requestedThumbprint = payload.clientKeyThumbprint ?? payload.clientProofKeyThumbprint; |
| 1649 | if (!requestedThumbprint) { |
| 1650 | return null; |
| 1651 | } |
| 1652 | if ( |
| 1653 | payload.clientKeyThumbprint && |
| 1654 | payload.clientProofKeyThumbprint && |
| 1655 | payload.clientKeyThumbprint !== payload.clientProofKeyThumbprint |
| 1656 | ) { |
| 1657 | return null; |
| 1658 | } |
| 1659 | return requestedThumbprint; |
| 1660 | } |
| 1661 | |
| 1662 | function safeAuthFailureReason(value: string): string { |
| 1663 | return /^[a-z0-9._-]+$/i.test(value) ? value : "unknown"; |
| 1664 | } |
| 1665 | |
| 1666 | function clerkVerificationFailureReason(cause: unknown): string { |
| 1667 | if ( |
| 1668 | cause instanceof Error && |
| 1669 | (cause.message.startsWith("Invalid JWT audience claim ") || |
| 1670 | cause.message.startsWith("Invalid JWT audience claim array ")) |
| 1671 | ) { |
| 1672 | return "audience_mismatch"; |
| 1673 | } |
| 1674 | if (typeof cause === "object" && cause !== null && "reason" in cause) { |
| 1675 | const reason = (cause as { readonly reason?: unknown }).reason; |
| 1676 | if (typeof reason === "string" && reason.length > 0) { |
| 1677 | return safeAuthFailureReason(reason); |
| 1678 | } |
| 1679 | } |
| 1680 | if (cause instanceof Error && cause.name) { |
| 1681 | return safeAuthFailureReason(cause.name); |
| 1682 | } |
| 1683 | return "unknown"; |
| 1684 | } |
| 1685 | |
| 1686 | function hasExpectedClerkAudience(audience: unknown, expectedAudience: string): boolean { |
| 1687 | return typeof audience === "string" |
| 1688 | ? audience === expectedAudience |
| 1689 | : Array.isArray(audience) && |
| 1690 | audience.some((entry) => typeof entry === "string" && entry === expectedAudience); |
| 1691 | } |
| 1692 | |
| 1693 | function verifyClerkBearerToken( |
| 1694 | config: RelayConfiguration.RelayConfiguration["Service"], |
| 1695 | token: string, |
| 1696 | ) { |
| 1697 | return Effect.tryPromise({ |
| 1698 | try: () => |
| 1699 | verifyToken(token, { |
| 1700 | secretKey: Redacted.value(config.clerkSecretKey), |
| 1701 | audience: config.clerkJwtAudience, |
| 1702 | }), |
| 1703 | catch: (cause) => new ClerkTokenVerificationFailed({ cause }), |
| 1704 | }).pipe( |
| 1705 | Effect.withSpan("verify_clerk_bearer_token", { |
| 1706 | attributes: { "relay.auth.token_length": token.length }, |
| 1707 | }), |
| 1708 | ); |
| 1709 | } |
| 1710 | |
| 1711 | function verifyClerkOAuthBearerToken( |
| 1712 | config: RelayConfiguration.RelayConfiguration["Service"], |
| 1713 | token: string, |
| 1714 | ) { |
| 1715 | return Effect.tryPromise({ |
| 1716 | try: async () => { |
| 1717 | const client = createClerkClient({ |
| 1718 | secretKey: Redacted.value(config.clerkSecretKey), |
| 1719 | publishableKey: config.clerkPublishableKey, |
| 1720 | }); |
| 1721 | const state = await client.authenticateRequest( |
| 1722 | new Request(config.relayIssuer, { |
| 1723 | headers: { authorization: `Bearer ${token}` }, |
| 1724 | }), |
| 1725 | { acceptsToken: "oauth_token" }, |
| 1726 | ); |
| 1727 | const auth = state.toAuth(); |
| 1728 | if (!state.isAuthenticated || !auth.userId) { |
| 1729 | throw new Error("Clerk OAuth token is not authenticated."); |
| 1730 | } |
| 1731 | return { sub: auth.userId }; |
| 1732 | }, |
| 1733 | catch: (cause) => new ClerkTokenVerificationFailed({ cause }), |
| 1734 | }); |
| 1735 | } |
| 1736 | |
| 1737 | export function verifyRelayClientBearerToken( |
| 1738 | config: RelayConfiguration.RelayConfiguration["Service"], |
| 1739 | token: string, |
| 1740 | ) { |
| 1741 | return verifyClerkBearerToken(config, token).pipe( |
| 1742 | Effect.flatMap((verified) => |
| 1743 | verified.sub && hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience) |
| 1744 | ? Effect.succeed({ sub: verified.sub, mode: "clerk_session_bearer" as const }) |
| 1745 | : Effect.fail(new ClerkTokenVerificationFailed({ cause: "missing_relay_audience" })), |
| 1746 | ), |
| 1747 | Effect.catch(() => |
| 1748 | verifyClerkOAuthBearerToken(config, token).pipe( |
| 1749 | Effect.map((verified) => ({ ...verified, mode: "clerk_oauth_bearer" as const })), |
| 1750 | ), |
| 1751 | ), |
| 1752 | ); |
| 1753 | } |
| 1754 | |
| 1755 | const requireDpopPrincipalScope = Effect.fn("relay.api.require_dpop_principal_scope")(function* ( |
| 1756 | scope: RelayDpopAccessTokenScope, |
| 1757 | ) { |
| 1758 | yield* Effect.annotateCurrentSpan({ "relay.dpop.required_scope": scope }); |
| 1759 | const principal = yield* RelayClientPrincipal; |
| 1760 | if (!principal.proofKeyThumbprint || !principal.dpopScopes?.includes(scope)) { |
| 1761 | return yield* new HttpApiError.Unauthorized({}); |
| 1762 | } |
| 1763 | return principal.proofKeyThumbprint; |
| 1764 | }); |
| 1765 | |
| 1766 | const requireDpopThumbprint = Effect.fn("relay.api.require_dpop_thumbprint")(function* ( |
| 1767 | expectedThumbprint: string, |
| 1768 | options?: { |
| 1769 | readonly expectedAccessToken?: string; |
| 1770 | }, |
| 1771 | ) { |
| 1772 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 1773 | const now = yield* DateTime.now; |
| 1774 | const url = HttpServerRequest.toURL(request); |
| 1775 | if (url._tag === "None") { |
| 1776 | return yield* new HttpApiError.Unauthorized({}); |
| 1777 | } |
| 1778 | const dpopProofs = yield* DpopProofs.DpopProofReplay; |
| 1779 | return yield* dpopProofs.verifyAndConsume({ |
| 1780 | proof: request.headers.dpop, |
| 1781 | method: request.method, |
| 1782 | url: url.value.href, |
| 1783 | now, |
| 1784 | expectedThumbprint, |
| 1785 | ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}), |
| 1786 | }); |
| 1787 | }); |
| 1788 | |
| 1789 | const requireDpopProof = Effect.fn("relay.api.require_dpop_proof")(function* (options?: { |
| 1790 | readonly expectedAccessToken?: string; |
| 1791 | }) { |
| 1792 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 1793 | const now = yield* DateTime.now; |
| 1794 | const url = HttpServerRequest.toURL(request); |
| 1795 | if (url._tag === "None") { |
| 1796 | return yield* new HttpApiError.Unauthorized({}); |
| 1797 | } |
| 1798 | const dpopProofs = yield* DpopProofs.DpopProofReplay; |
| 1799 | return yield* dpopProofs.verifyAndConsume({ |
| 1800 | proof: request.headers.dpop, |
| 1801 | method: request.method, |
| 1802 | url: url.value.href, |
| 1803 | now, |
| 1804 | ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}), |
| 1805 | }); |
| 1806 | }); |
| 1807 | |
| 1808 | const relayAuthInvalidError = Effect.fnUntraced(function* (reason: RelayAuthInvalidReason) { |
| 1809 | const traceId = yield* currentTraceId; |
| 1810 | yield* Effect.annotateCurrentSpan({ |
| 1811 | "relay.trace_id": traceId, |
| 1812 | "relay.error.outbound_tag": "RelayAuthInvalidError", |
| 1813 | "relay.error.outbound_reason": reason, |
| 1814 | }); |
| 1815 | return yield* new RelayAuthInvalidError({ code: "auth_invalid", reason, traceId }); |
| 1816 | }); |