diff --git a/apps/mobile/src/features/cloud/publicConfig.test.ts b/apps/mobile/src/features/cloud/publicConfig.test.ts index 26c1561bf0..df9aefdc43 100644 --- a/apps/mobile/src/features/cloud/publicConfig.test.ts +++ b/apps/mobile/src/features/cloud/publicConfig.test.ts @@ -31,4 +31,17 @@ describe("resolveCloudPublicConfig", () => { relayUrl: "https://relay.example.test", }); }); + + it("rejects an insecure relay URL", () => { + expect( + resolveCloudPublicConfig({ + clerk: { publishableKey: "pk_test_example", jwtTemplate: "t3-relay" }, + relay: { url: "http://relay.example.test" }, + }), + ).toEqual({ + clerkPublishableKey: "pk_test_example", + clerkJwtTemplate: "t3-relay", + relayUrl: null, + }); + }); }); diff --git a/apps/mobile/src/features/cloud/publicConfig.ts b/apps/mobile/src/features/cloud/publicConfig.ts index d775f06101..fcd0ceb272 100644 --- a/apps/mobile/src/features/cloud/publicConfig.ts +++ b/apps/mobile/src/features/cloud/publicConfig.ts @@ -1,5 +1,6 @@ import Constants from "expo-constants"; import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth"; +import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl"; type ExpoExtra = Readonly> | undefined; @@ -22,7 +23,7 @@ export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig return { clerkPublishableKey: trimNonEmpty(clerk?.publishableKey), clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate), - relayUrl: trimNonEmpty(relay?.url)?.replace(/\/+$/u, "") ?? null, + relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""), } satisfies CloudPublicConfig; } diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index 3c27410741..1df23d6859 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -37,6 +37,7 @@ import { signRelayJwt, verifyRelayJwt, } from "@t3tools/shared/relayJwt"; +import { isSecureRelayUrl } from "@t3tools/shared/relayUrl"; import * as DateTime from "effect/DateTime"; import * as Crypto from "effect/Crypto"; import * as Duration from "effect/Duration"; @@ -155,20 +156,6 @@ function validateCloudMintPublicKey( ); } -function isSecureRelayUrl(value: string): boolean { - try { - const url = new URL(value); - return ( - url.protocol === "https:" && - url.username.length === 0 && - url.password.length === 0 && - url.hash.length === 0 - ); - } catch { - return false; - } -} - function validateRelayConfigPayload( payload: RelayEnvironmentConfigRequest, ): Effect.Effect { diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 29f103a50e..8b1f997231 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -2127,6 +2127,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => { relayIssuer: "http://relay.example.test", environmentCredential: "t3env_test_credential", }); + const nonOriginRelayUrl = yield* postRelayConfig({ + relayUrl: "https://relay.example.test/path", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + }); const emptyCredential = yield* postRelayConfig({ relayUrl: "https://relay.example.test", cloudUserId: "user_123", @@ -2138,6 +2143,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const insecureRelayIssuerBody = yield* responseJsonEffect<{ readonly message?: string }>( insecureRelayIssuer, ); + const nonOriginRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>( + nonOriginRelayUrl, + ); const emptyCredentialBody = yield* responseJsonEffect<{ readonly message?: string }>( emptyCredential, ); @@ -2149,6 +2157,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { insecureRelayIssuerBody.message, "Relay issuer must be a secure absolute HTTPS URL.", ); + assert.equal(nonOriginRelayUrl.status, 400); + assert.equal(nonOriginRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL."); assert.equal(emptyCredential.status, 400); assert.equal(emptyCredentialBody.message, "Relay environment credential is required."); }).pipe(Effect.provide(NodeHttpServer.layerTest)), diff --git a/apps/web/src/cloud/publicConfig.test.ts b/apps/web/src/cloud/publicConfig.test.ts index 32a902c47e..a19814beb3 100644 --- a/apps/web/src/cloud/publicConfig.test.ts +++ b/apps/web/src/cloud/publicConfig.test.ts @@ -22,4 +22,12 @@ describe("hasCloudPublicConfig", () => { vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test"); expect(hasCloudPublicConfig()).toBe(true); }); + + it("rejects an insecure relay URL", () => { + vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_example"); + vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay"); + vi.stubEnv("VITE_T3CODE_RELAY_URL", "http://relay.example.test"); + + expect(hasCloudPublicConfig()).toBe(false); + }); }); diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.ts index fe3d5b5e63..291f1830ca 100644 --- a/apps/web/src/cloud/publicConfig.ts +++ b/apps/web/src/cloud/publicConfig.ts @@ -1,4 +1,5 @@ import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth"; +import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl"; export interface CloudPublicConfig { readonly clerkPublishableKey: string | null; @@ -16,11 +17,9 @@ export function resolveCloudPublicConfig(): CloudPublicConfig { import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined, ), clerkJwtTemplate: trimNonEmpty(import.meta.env.VITE_CLERK_JWT_TEMPLATE as string | undefined), - relayUrl: - trimNonEmpty(import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined)?.replace( - /\/+$/u, - "", - ) ?? null, + relayUrl: normalizeSecureRelayUrl( + (import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined) ?? "", + ), }; } diff --git a/packages/client-runtime/src/managedRelay.test.ts b/packages/client-runtime/src/managedRelay.test.ts index 412981d958..e340f12f62 100644 --- a/packages/client-runtime/src/managedRelay.test.ts +++ b/packages/client-runtime/src/managedRelay.test.ts @@ -16,7 +16,10 @@ import { } from "./managedRelay.ts"; import { remoteHttpClientLayer } from "./remote.ts"; -function managedRelayTestLayer(fetchFn: typeof globalThis.fetch) { +function managedRelayTestLayer( + fetchFn: typeof globalThis.fetch, + relayUrl = "https://relay.example.test", +) { const httpClientLayer = remoteHttpClientLayer(fetchFn); const signerLayer = Layer.succeed( ManagedRelayDpopSigner, @@ -26,12 +29,33 @@ function managedRelayTestLayer(fetchFn: typeof globalThis.fetch) { }), ); return managedRelayClientLayer({ - relayUrl: "https://relay.example.test", + relayUrl, clientId: "t3-mobile", }).pipe(Layer.provide(signerLayer), Layer.provide(httpClientLayer)); } describe("ManagedRelayClient", () => { + it.effect("rejects unsafe relay URLs before sending credentials", () => { + let requestCount = 0; + const fetchFn = (() => { + requestCount += 1; + return Promise.resolve(Response.json({})); + }) satisfies typeof globalThis.fetch; + + return Effect.gen(function* () { + const relayClient = yield* ManagedRelayClient; + const error = yield* relayClient + .listEnvironments({ clerkToken: "clerk-token" }) + .pipe(Effect.flip); + + expect(error).toMatchObject({ + _tag: "ManagedRelayClientError", + message: "Relay URL must be a secure absolute HTTPS origin.", + }); + expect(requestCount).toBe(0); + }).pipe(Effect.provide(managedRelayTestLayer(fetchFn, "http://relay.example.test"))); + }); + it.effect("reuses usable DPoP tokens and refreshes cleared or expiring cache entries", () => { let tokenExchangeCount = 0; const fetchFn = ((input) => { diff --git a/packages/client-runtime/src/managedRelay.ts b/packages/client-runtime/src/managedRelay.ts index 4ac2d34a62..a3bc973c64 100644 --- a/packages/client-runtime/src/managedRelay.ts +++ b/packages/client-runtime/src/managedRelay.ts @@ -26,6 +26,7 @@ import { RelayUnregisterDeviceEndpoint, } from "@t3tools/contracts/relay"; import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope"; +import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -183,14 +184,37 @@ function dpopHeaders(authorization: ManagedRelayAuthorization) { }; } +function disabledManagedRelayClient(relayUrl: string): ManagedRelayClientShape { + const unavailable = () => + Effect.fail(relayClientError("Relay URL must be a secure absolute HTTPS origin.")); + return ManagedRelayClient.of({ + relayUrl, + listEnvironments: unavailable, + listDevices: unavailable, + createEnvironmentLinkChallenge: unavailable, + linkEnvironment: unavailable, + unlinkEnvironment: unavailable, + getEnvironmentStatus: unavailable, + connectEnvironment: unavailable, + registerDevice: unavailable, + unregisterDevice: unavailable, + registerLiveActivity: unavailable, + resetTokenCache: Effect.void, + }); +} + export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) { return Layer.effect( ManagedRelayClient, Effect.gen(function* () { + const relayUrl = normalizeSecureRelayUrl(options.relayUrl); + if (relayUrl === null) { + return disabledManagedRelayClient(options.relayUrl); + } const signer = yield* ManagedRelayDpopSigner; - const client = yield* HttpApiClient.make(RelayApi, { baseUrl: options.relayUrl }); + const client = yield* HttpApiClient.make(RelayApi, { baseUrl: relayUrl }); const cachedTokens = yield* SynchronizedRef.make>([]); - const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: options.relayUrl }); + const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: relayUrl }); type DpopProofTarget = Pick; const dpopProofTargets = { @@ -257,7 +281,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) subject_token: input.clerkToken, subject_token_type: RelayJwtSubjectTokenType, requested_token_type: RelayAccessTokenType, - resource: options.relayUrl, + resource: relayUrl, scope: encodeOAuthScope(input.scopes), client_id: options.clientId, }, @@ -325,7 +349,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) }); return ManagedRelayClient.of({ - relayUrl: options.relayUrl, + relayUrl, listEnvironments: (input) => client.client.listEnvironments({ headers: bearerHeaders(input.clerkToken) }).pipe( Effect.map((response) => response.environments), diff --git a/packages/shared/package.json b/packages/shared/package.json index 2f825f9166..f5407e2709 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -103,6 +103,10 @@ "types": "./src/relayAuth.ts", "import": "./src/relayAuth.ts" }, + "./relayUrl": { + "types": "./src/relayUrl.ts", + "import": "./src/relayUrl.ts" + }, "./relayJwt": { "types": "./src/relayJwt.ts", "import": "./src/relayJwt.ts" diff --git a/packages/shared/src/relayUrl.test.ts b/packages/shared/src/relayUrl.test.ts new file mode 100644 index 0000000000..23b8568669 --- /dev/null +++ b/packages/shared/src/relayUrl.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { isSecureRelayUrl, normalizeSecureRelayUrl } from "./relayUrl.ts"; + +describe("normalizeSecureRelayUrl", () => { + it("normalizes secure relay origins", () => { + expect(normalizeSecureRelayUrl(" https://relay.example.test/// ")).toBe( + "https://relay.example.test", + ); + expect(normalizeSecureRelayUrl("https://relay.example.test:8443/")).toBe( + "https://relay.example.test:8443", + ); + }); + + it.each([ + "http://relay.example.test", + "https://user:password@relay.example.test", + "https://relay.example.test/path", + "https://relay.example.test?query=value", + "https://relay.example.test#fragment", + "not a url", + ])("rejects unsafe relay URL %s", (value) => { + expect(normalizeSecureRelayUrl(value)).toBeNull(); + expect(isSecureRelayUrl(value)).toBe(false); + }); +}); diff --git a/packages/shared/src/relayUrl.ts b/packages/shared/src/relayUrl.ts new file mode 100644 index 0000000000..4e5f397702 --- /dev/null +++ b/packages/shared/src/relayUrl.ts @@ -0,0 +1,22 @@ +export function normalizeSecureRelayUrl(value: string): string | null { + try { + const url = new URL(value.trim()); + if ( + url.protocol !== "https:" || + url.username.length > 0 || + url.password.length > 0 || + url.search.length > 0 || + url.hash.length > 0 || + !/^\/+$/u.test(url.pathname) + ) { + return null; + } + return url.origin; + } catch { + return null; + } +} + +export function isSecureRelayUrl(value: string): boolean { + return normalizeSecureRelayUrl(value) !== null; +}