TypeScript
refactor: replace jose with effect/jose (#30474)
Julius Marminge14e8f393faeb
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 6fcab874325..53484dfc12c 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -63,7 +63,6 @@"diff": "8.0.3","effect": "catalog:","ffi-rs": "1.3.2",- "jose": "catalog:","node-pty": "^1.2.0-beta.15","playwright-core": "1.60.0","proper-lockfile": "4.1.2",diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.tsindex 3d8d9650b22..7092292666e 100644--- a/apps/server/src/cloud/CloudLink.ts+++ b/apps/server/src/cloud/CloudLink.ts@@ -44,6 +44,7 @@ import {import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -374,9 +375,6 @@ function normalizePemForSignedPayload(value: string): string {return value.trim();}-const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);-const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);-type ManagedTunnelRecoveryProofInput = {readonly environmentId: RelayManagedEndpointRecoveryProofPayload["environmentId"];readonly cloudUserId: string;@@ -532,6 +530,7 @@ const make = Effect.gen(function* () {const httpServer = yield* HttpServer.HttpServer;const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;const random = yield* SecureRandom.SecureRandom;+ const signature = yield* Signature.Signature;const config = yield* ServerConfig.ServerConfig;const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;@@ -623,6 +622,7 @@ const make = Effect.gen(function* () {typ: RELAY_LINK_PROOF_TYP,payload,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({@@ -960,6 +960,7 @@ const make = Effect.gen(function* () {typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,payload,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),),@@ -1453,14 +1454,13 @@ const make = Effect.gen(function* () {const linkedCloudUserId = yield* readInstalledCloudUserId;const now = yield* DateTime.now;const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const proofOption = yield* verifyRelayJwt({+ const proofOption = yield* verifyRelayJwt(RelayCloudEnvironmentHealthProofPayload, {publicKey: cloudMintPublicKey,token: request.proof,typ: RELAY_HEALTH_REQUEST_TYP,issuer: normalizeRelayIssuer(relayIssuer),audience: `t3-env:${environmentId}`,- nowEpochSeconds: nowSeconds,- }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);+ }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);if (Option.isNone(proofOption) ||proofOption.value.environmentId !== environmentId ||@@ -1504,6 +1504,7 @@ const make = Effect.gen(function* () {typ: RELAY_HEALTH_RESPONSE_TYP,payload: responsePayload,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({@@ -1556,14 +1557,13 @@ const make = Effect.gen(function* () {const linkedCloudUserId = yield* readInstalledCloudUserId;const now = yield* DateTime.now;const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const proofOption = yield* verifyRelayJwt({+ const proofOption = yield* verifyRelayJwt(RelayCloudMintCredentialProofPayload, {publicKey: cloudMintPublicKey,token: request.proof,typ: RELAY_MINT_REQUEST_TYP,issuer: normalizeRelayIssuer(relayIssuer),audience: `t3-env:${environmentId}`,- nowEpochSeconds: nowSeconds,- }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);+ }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);if (Option.isNone(proofOption) ||proofOption.value.environmentId !== environmentId ||@@ -1612,6 +1612,7 @@ const make = Effect.gen(function* () {typ: RELAY_MINT_RESPONSE_TYP,payload: responsePayload,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.tsindex 176ebd2ee33..ddbf46fdfb3 100644--- a/apps/server/src/cloud/http.test.ts+++ b/apps/server/src/cloud/http.test.ts@@ -13,6 +13,7 @@ import {type RelayLinkProofRequest,} from "@t3tools/contracts/relay";import * as Effect from "effect/Effect";+import * as TestClock from "effect/testing/TestClock";import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";import { HttpClient, HttpServer } from "effect/http";@@ -22,8 +23,7 @@ import * as HttpRouter from "effect/http/HttpRouter";import * as HttpApi from "effect/http-api/HttpApi";import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";import * as NetAddress from "effect/net/NetAddress";-import { decodeJwt, importSPKI, jwtVerify } from "jose";-import { RELAY_LINK_PROOF_TYP } from "@t3tools/shared/relayJwt";+import { decodeRelayJwt, RELAY_LINK_PROOF_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";import * as AuthHttp from "../auth/http.ts";@@ -52,7 +52,7 @@ const proofRequest: RelayLinkProofRequest = {},origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },};-const decodeLinkProofPayload = Schema.decodeUnknownSync(RelayEnvironmentLinkProofPayload);+const decodeLinkProofPayload = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);class LinkProofTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.auth,@@ -112,119 +112,123 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),);-const withLinkProofClient = async (- body: (client: {- post: (- path: string,- payload: unknown,- headers?: Record<string, string>,- origin?: string,- ) => Promise<Response>;- exchange: (credential: string, scope?: string) => Promise<string>;- }) => Promise<void>,-) => {- const { handler, dispose } = HttpRouter.toWebHandler(layerLinkProofRoutes, {- disableLogger: true,- });+const responseJson = (response: Response) => Effect.promise(() => response.json());++// Scoped: the web handler and its layer are disposed when the test's scope closes.+const linkProofClient = Effect.gen(function* () {+ const { handler } = yield* Effect.acquireRelease(+ Effect.sync(() => HttpRouter.toWebHandler(layerLinkProofRoutes, { disableLogger: true })),+ (web) => Effect.promise(() => web.dispose()),+ );const post = (path: string,payload: unknown,headers?: Record<string, string>,origin = NON_LOOPBACK_ORIGIN,) =>- handler(- new Request(`${origin}${path}`, {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: JSON.stringify(payload),- }),+ Effect.promise(() =>+ handler(+ new Request(`${origin}${path}`, {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify(payload),+ }),+ ),);- const exchange = async (credential: string, scope?: string) => {- const response = await handler(- new Request(`${NON_LOOPBACK_ORIGIN}/oauth/token`, {- method: "POST",- body: new URLSearchParams({- grant_type: AuthTokenExchangeGrantType,- subject_token: credential,- subject_token_type: AuthEnvironmentBootstrapTokenType,- requested_token_type: AuthAccessTokenType,- ...(scope ? { scope } : {}),+ const exchange = Effect.fnUntraced(function* (credential: string, scope?: string) {+ const response = yield* Effect.promise(() =>+ handler(+ new Request(`${NON_LOOPBACK_ORIGIN}/oauth/token`, {+ method: "POST",+ body: new URLSearchParams({+ grant_type: AuthTokenExchangeGrantType,+ subject_token: credential,+ subject_token_type: AuthEnvironmentBootstrapTokenType,+ requested_token_type: AuthAccessTokenType,+ ...(scope ? { scope } : {}),+ }),}),- }),+ ),);expect(response.status).toBe(200);- const payload = (await response.json()) as { access_token: string };+ const payload = (yield* responseJson(response)) as { access_token: string };return payload.access_token;- };- try {- await body({ post, exchange });- } finally {- await dispose();- }-};+ });+ return { post, exchange };+});describe("link proof over a non-loopback desktop transport", () => {- it("signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host", () =>- withLinkProofClient(async ({ post, exchange }) => {- const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);- const response = await post("/api/connect/link-proof", proofRequest, {- authorization: `Bearer ${token}`,- });- expect(response.status).toBe(200);- const proof = (await response.json()) as string;- const payload = decodeLinkProofPayload(decodeJwt(proof));- const verified = await jwtVerify(- proof,- await importSPKI(payload.environmentPublicKey, "EdDSA"),- {- algorithms: ["EdDSA"],+ it.effect(+ "signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host",+ () =>+ Effect.gen(function* () {+ const { post, exchange } = yield* linkProofClient;+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);+ const response = yield* post("/api/connect/link-proof", proofRequest, {+ authorization: `Bearer ${token}`,+ });+ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ const proof = (yield* responseJson(response)) as string;+ const unverified = yield* decodeRelayJwt(proof).pipe(+ Effect.flatMap(decodeLinkProofPayload),+ );+ yield* TestClock.setTime(unverified.iat * 1_000);+ const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, {+ publicKey: unverified.environmentPublicKey,+ token: proof,typ: RELAY_LINK_PROOF_TYP,issuer: "t3-env:wsl-environment",audience: proofRequest.relayIssuer,- },- );- expect(verified.payload).toMatchObject({- origin: proofRequest.origin,- endpoint: proofRequest.endpoint,- challenge: proofRequest.challenge,- });- expect(response.headers.get("cache-control")).toBe("no-store");- }));+ });+ expect(verified).toMatchObject({+ origin: proofRequest.origin,+ endpoint: proofRequest.endpoint,+ challenge: proofRequest.challenge,+ });+ }).pipe(Effect.provide(NodeCrypto.layerSignature)),+ );- it("does not pass desktop trust to a paired client or accept client-supplied provenance", () =>- withLinkProofClient(async ({ post, exchange }) => {- const desktop = await exchange(DESKTOP_BOOTSTRAP_TOKEN);- const paired = await post(- "/api/auth/pairing-token",- {- scopes: ["relay:write"],- label: "desktop-bootstrap",+ it.effect(+ "does not pass desktop trust to a paired client or accept client-supplied provenance",+ () =>+ Effect.gen(function* () {+ const { post, exchange } = yield* linkProofClient;+ const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);+ const paired = yield* post(+ "/api/auth/pairing-token",+ {+ scopes: ["relay:write"],+ label: "desktop-bootstrap",+ subject: "desktop-bootstrap",+ },+ { authorization: `Bearer ${desktop}` },+ );+ expect(paired.status).toBe(200);+ const { credential } = (yield* responseJson(paired)) as { credential: string };+ const token = yield* exchange(credential);+ const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };+ const payload = {+ ...proofRequest,+ allowNonLoopbackRequestHost: true,subject: "desktop-bootstrap",- },- { authorization: `Bearer ${desktop}` },- );- expect(paired.status).toBe(200);- const { credential } = (await paired.json()) as { credential: string };- const token = await exchange(credential);- const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };- const payload = {- ...proofRequest,- allowNonLoopbackRequestHost: true,- subject: "desktop-bootstrap",- };- const rejected = await post("/api/connect/link-proof", payload, headers);- expect(rejected.status).toBe(400);- expect(await rejected.json()).toMatchObject({ message: "Invalid managed endpoint origin." });- const loopback = await post(- "/api/connect/link-proof",- proofRequest,- headers,- LOOPBACK_ORIGIN,- );- expect(loopback.status).toBe(200);- }));+ };+ const rejected = yield* post("/api/connect/link-proof", payload, headers);+ expect(rejected.status).toBe(400);+ expect(yield* responseJson(rejected)).toMatchObject({+ message: "Invalid managed endpoint origin.",+ });+ const loopback = yield* post(+ "/api/connect/link-proof",+ proofRequest,+ headers,+ LOOPBACK_ORIGIN,+ );+ expect(loopback.status).toBe(200);+ }),+ );- it.each([+ it.effect.each([{name: "non-loopback tunnel origin",origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 },@@ -246,34 +250,41 @@ describe("link proof over a non-loopback desktop transport", () => {headers: { "x-forwarded-proto": "http" },},])("rejects $name even for desktop bootstrap", ({ origin, headers }) =>- withLinkProofClient(async ({ post, exchange }) => {- const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);- const response = await post(+ Effect.gen(function* () {+ const { post, exchange } = yield* linkProofClient;+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);+ const response = yield* post("/api/connect/link-proof",{ ...proofRequest, origin },{ ...headers, authorization: `Bearer ${token}` },);expect(response.status).toBe(400);- expect(await response.json()).toMatchObject({ message: "Invalid managed endpoint origin." });+ expect(yield* responseJson(response)).toMatchObject({+ message: "Invalid managed endpoint origin.",+ });}),);- it("requires relay-write scope even for desktop bootstrap", () =>- withLinkProofClient(async ({ post, exchange }) => {- const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");- const response = await post("/api/connect/link-proof", proofRequest, {+ it.effect("requires relay-write scope even for desktop bootstrap", () =>+ Effect.gen(function* () {+ const { post, exchange } = yield* linkProofClient;+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");+ const response = yield* post("/api/connect/link-proof", proofRequest, {authorization: `Bearer ${token}`,});expect(response.status).toBe(403);- expect(await response.json()).toMatchObject({+ expect(yield* responseJson(response)).toMatchObject({code: "insufficient_scope",requiredScope: "relay:write",});- }));+ }),+ );- it("rejects unauthenticated requests", () =>- withLinkProofClient(async ({ post }) => {- const response = await post("/api/connect/link-proof", proofRequest);+ it.effect("rejects unauthenticated requests", () =>+ Effect.gen(function* () {+ const { post } = yield* linkProofClient;+ const response = yield* post("/api/connect/link-proof", proofRequest);expect(response.status).toBe(401);- }));+ }),+ );});diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.tsindex f6291112642..1c23f395935 100644--- a/apps/server/src/provider/CodexChatGptAuth.test.ts+++ b/apps/server/src/provider/CodexChatGptAuth.test.ts@@ -14,11 +14,11 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import * as Fiber from "effect/Fiber";import * as Deferred from "effect/Deferred";import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts";import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";-import { exportJWK, generateKeyPair, SignJWT } from "jose";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as ServerEnvironment from "../environment/ServerEnvironment.ts";import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";@@ -44,9 +44,23 @@ const makeHarnessFor = Effect.fnUntraced(function* (const environment = ServerEnvironment.ServerEnvironmentIdentity.of({getEnvironmentId: Effect.succeed(environmentId),});- const keys = yield* Effect.promise(() => generateKeyPair("RS256"));- const jwk = yield* Effect.promise(() => exportJWK(keys.publicKey));- const untrustedKeys = yield* Effect.promise(() => generateKeyPair("RS256"));+ const signingKeyFor = (kid: string) => {+ const pair = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });+ return {+ kid,+ privateKey: pair.privateKey,+ publicJwk: { ...pair.publicKey.export({ format: "jwk" }), kid, alg: "RS256", use: "sig" },+ };+ };+ let signingKey = signingKeyFor("test");+ let jwksRequests = 0;+ const untrustedKeys = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });+ const signIdToken = (claims: Record<string, unknown>, privateKey: NodeCrypto.KeyObject) => {+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");+ const signingInput = `${encode({ alg: "RS256", kid: signingKey.kid })}.${encode(claims)}`;+ const signature = NodeCrypto.sign("sha256", Buffer.from(signingInput), privateKey);+ return `${signingInput}.${signature.toString("base64url")}`;+ };const secrets = ServerSecretStore.ServerSecretStore.of({get: (name) => Effect.sync(() => Option.fromUndefinedOr(bytes.get(name))),set: (name, value) =>@@ -99,9 +113,8 @@ const makeHarnessFor = Effect.fnUntraced(function* (return;}if (request.url === "/jwks") {- response.end(- JSON.stringify({ keys: [{ ...jwk, kid: "test", alg: "RS256", use: "sig" }] }),- );+ jwksRequests += 1;+ response.end(JSON.stringify({ keys: [signingKey.publicJwk] }));return;}if (request.url === "/revoke") {@@ -167,21 +180,20 @@ const makeHarnessFor = Effect.fnUntraced(function* (.digest("base64url"),authorize.searchParams.get("code_challenge"),);- const token = await new SignJWT({- nonce: invalidNonce ? "incorrect" : authorize.searchParams.get("nonce"),- email,- })- .setProtectedHeader({ alg: "RS256", kid: "test" })- .setIssuer(identityFailure === "issuer" ? "https://untrusted-issuer.test" : origin)- .setAudience(- identityFailure === "audience"- ? "oaiapp_untrusted_audience"- : body.get("client_id")!,- )- .setSubject(subject)- .setIssuedAt()- .setExpirationTime("1h")- .sign(identityFailure === "signature" ? untrustedKeys.privateKey : keys.privateKey);+ const token = signIdToken(+ {+ nonce: invalidNonce ? "incorrect" : authorize.searchParams.get("nonce"),+ email,+ iss: identityFailure === "issuer" ? "https://untrusted-issuer.test" : origin,+ aud:+ identityFailure === "audience"+ ? "oaiapp_untrusted_audience"+ : body.get("client_id")!,+ sub: subject,+ exp: 4_102_444_800,+ },+ identityFailure === "signature" ? untrustedKeys.privateKey : signingKey.privateKey,+ );response.end(JSON.stringify({access_token: "initial-access",@@ -283,6 +295,10 @@ const makeHarnessFor = Effect.fnUntraced(function* (});return {auth,+ jwksRequests: () => jwksRequests,+ rotateSigningKey: () => {+ signingKey = signingKeyFor("rotated");+ },analyticsEvents,secrets,environmentId,@@ -649,6 +665,17 @@ it.effect(h.exchanges[2]!.get("redirect_uri"),reconnect.searchParams.get("redirect_uri"),);+ assert.strictEqual(h.jwksRequests(), 1);+ h.rotateSigningKey();+ yield* h.auth.controller.logout(Effect.void);+ yield* h.signIn;+ yield* h.phase("succeeded");+ assert.strictEqual(h.jwksRequests(), 2);+ yield* TestClock.adjust("10 minutes");+ yield* h.auth.controller.logout(Effect.void);+ yield* h.signIn;+ yield* h.phase("succeeded");+ assert.strictEqual(h.jwksRequests(), 3);}),),);diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.tsindex 457e85791b6..0758593488f 100644--- a/apps/server/src/provider/CodexChatGptAuth.ts+++ b/apps/server/src/provider/CodexChatGptAuth.ts@@ -1,7 +1,6 @@// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener and PKCE use Node APIs.import * as NodeCrypto from "node:crypto";import * as NodeHttp from "node:http";-import { createRemoteJWKSet, jwtVerify } from "jose";import {ProviderSetupError,type ChatGptReconnectProfile,@@ -16,6 +15,10 @@ import * as AnalyticsService from "../telemetry/AnalyticsService.ts";import { openAiUserId } from "../telemetry/Identify.ts";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";+import * as JoseError from "effect/jose/JoseError";+import * as Jwks from "effect/jose/Jwks";+import * as Jwt from "effect/jose/Jwt";import * as Hex from "effect/encoding/Hex";import * as Exit from "effect/Exit";import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";@@ -95,6 +98,13 @@ const Discovery = Schema.Struct({revocation_endpoint: Schema.optionalKey(Schema.String),});const OAuthError = Schema.Struct({ error: Schema.String });+const JWKS_CACHE_TTL_MS = 10 * 60 * 1000;+const IdTokenClaims = Schema.Struct({+ sub: Schema.String,+ nonce: Schema.optionalKey(Schema.Unknown),+ email: Schema.optionalKey(Schema.Unknown),+});+const decodeKeySet = Schema.decodeUnknownEffect(Jwks.KeySet);const decodeSessions = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Union([Sessions, Record])),);@@ -165,6 +175,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*const secrets = yield* ServerSecretStore.ServerSecretStore;const random = yield* SecureRandom.SecureRandom;const digest = yield* Digest.Digest;+ const signature = yield* Signature.Signature;const environmentLocks = sessionLocks.get(secrets) ?? new Map<string, Semaphore.Semaphore>();sessionLocks.set(secrets, environmentLocks);const lock = environmentLocks.get(store.binding.key) ?? (yield* Semaphore.make(1));@@ -177,7 +188,6 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*const failure = (operation: string, detail: string) =>new ProviderSetupError({ instanceId: options.instanceId, operation, detail });let metadata: typeof Discovery.Type | undefined;- let jwks: ReturnType<typeof createRemoteJWKSet> | undefined;const discover = Effect.gen(function* () {if (metadata) return metadata;const result = yield* http.get(options.discoveryUrl ?? DISCOVERY).pipe(@@ -203,9 +213,58 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*)return yield* failure("discover", "ChatGPT sign-in configuration could not be verified.");metadata = result;- jwks = createRemoteJWKSet(new URL(result.jwks_uri));return result;});+ // Reused for 10 minutes like jose's remote set; an unknown kid refetches once for rotation.+ let keySet: { readonly keys: Jwks.KeySet; readonly expiresAt: number } | undefined;+ const fetchKeySet = Effect.fn("CodexChatGptAuth.fetchKeySet")(function* (jwksUri: string) {+ return yield* http.get(jwksUri).pipe(+ Effect.filterOrFail(+ (response) => response.status === 200,+ () => failure("verify", "Could not reach ChatGPT sign-in. Try again."),+ ),+ Effect.flatMap((response) => response.json),+ Effect.flatMap(decodeKeySet),+ // Bounds the body read too, as jose's remote set did; a stalled endpoint fails the sign-in.+ Effect.timeoutOrElse({+ duration: "5 seconds",+ orElse: () => Effect.fail(failure("verify", "Could not reach ChatGPT sign-in. Try again.")),+ }),+ Effect.tap((fetched) =>+ Effect.map(Clock.currentTimeMillis, (now) => {+ keySet = { keys: fetched, expiresAt: now + JWKS_CACHE_TTL_MS };+ }),+ ),+ );+ });+ const verifyIdToken = Effect.fn("CodexChatGptAuth.verifyIdToken")(+ function* (token: string, audience: string) {+ const endpoints = yield* discover;+ const verifyWith = (keys: Jwks.KeySet) =>+ Jwks.makeLocal(keys).pipe(+ Effect.flatMap((jwks) =>+ Jwt.verifyWithKeySet(IdTokenClaims, token, {+ issuer: endpoints.issuer,+ audience,+ algorithms: ["RS256", "ES256"],+ clockTolerance: "5 seconds",+ requiredClaims: ["exp"],+ }).pipe(Effect.provideService(Jwks.Jwks, jwks)),+ ),+ );+ const fresh = fetchKeySet(endpoints.jwks_uri).pipe(Effect.flatMap(verifyWith));+ const cached = keySet;+ return yield* cached === undefined || cached.expiresAt <= (yield* Clock.currentTimeMillis)+ ? fresh+ : verifyWith(cached.keys).pipe(+ Effect.catchIf(+ (error) => JoseError.isJoseError(error) && error.reason._tag === "KeyNotFound",+ () => fresh,+ ),+ );+ },+ Effect.provideService(Signature.Signature, signature),+ );const readSessions = store.get.pipe(Effect.mapError(() => failure("read", "Could not read the saved ChatGPT connection.")),Effect.flatMap((bytes) =>@@ -622,22 +681,19 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*"verify","ChatGPT did not return a verified identity. Sign in again.",);- const identity = yield* Effect.tryPromise({- try: async () => {- const { payload } = await jwtVerify(tokens.id_token!, jwks!, {- issuer: endpoints.issuer,- audience: clientId,- algorithms: ["RS256", "ES256"],- clockTolerance: 5,- });- if (payload.nonce !== nonce || !payload.sub || !payload.exp) throw new Error("identity");- return {- subject: payload.sub,- email: typeof payload.email === "string" ? payload.email : null,- };- },- catch: () => failure("verify", "ChatGPT sign-in could not be verified. Start again."),- });+ const identity = yield* verifyIdToken(tokens.id_token, clientId).pipe(+ Effect.flatMap(({ claims }) =>+ claims.nonce === nonce+ ? Effect.succeed({+ subject: claims.sub,+ email: typeof claims.email === "string" ? claims.email : null,+ })+ : Effect.fail(failure("verify", "identity")),+ ),+ Effect.mapError(() =>+ failure("verify", "ChatGPT sign-in could not be verified. Start again."),+ ),+ );const expectedSubject =savedRegistration?.subject ??(previous?.clientId === registeredClientId ? previous?.subject : undefined);@@ -951,20 +1007,15 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*"import","The transferred ChatGPT connection is invalid or expired.",);- const identity = yield* Effect.tryPromise({- try: () =>- jwtVerify(credentials.idToken, jwks!, {- issuer: endpoints.issuer,- audience: credentials.clientId,- algorithms: ["RS256", "ES256"],- clockTolerance: 5,- }),- catch: () => failure("import", "The transferred ChatGPT identity could not be verified."),- });+ const identity = yield* verifyIdToken(credentials.idToken, credentials.clientId).pipe(+ Effect.mapError(() =>+ failure("import", "The transferred ChatGPT identity could not be verified."),+ ),+ );if (- identity.payload.sub !== credentials.subject ||+ identity.claims.sub !== credentials.subject ||profile.registration.subject !== credentials.subject ||- (identity.payload.email ?? null) !== credentials.email ||+ (identity.claims.email ?? null) !== credentials.email ||(profile.registration.email !== undefined &&profile.registration.email !== credentials.email))diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.tsindex c34aa00a196..871ce9ed6e8 100644--- a/apps/server/src/provider/Drivers/CodexDriver.ts+++ b/apps/server/src/provider/Drivers/CodexDriver.ts@@ -1,6 +1,7 @@import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";+import type * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";@@ -101,6 +102,7 @@ export type CodexDriverEnv =| ResetCreditCoordinator.ResetCreditCoordinator| Digest.Digest| SecureRandom.SecureRandom+ | Signature.Signature| FileSystem.FileSystem| HttpClient.HttpClient| ProviderLatestVersions.ProviderLatestVersionsdiff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsindex 6e9175862e4..286c95cf7f1 100644--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.ts@@ -24,6 +24,7 @@ import {import * as Cause from "effect/Cause";import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";@@ -247,17 +248,6 @@ function deliveryStats(};}-function signRelayAgentActivityPublishProof(input: {- readonly privateKey: string;- readonly payload: RelayAgentActivityPublishProofPayload;-}) {- return signRelayJwt({- privateKey: input.privateKey,- typ: RELAY_ACTIVITY_PUBLISH_TYP,- payload: input.payload,- });-}-const makePublishProof = Effect.fn("makePublishProof")(function* (input: {readonly privateKey: string;readonly relayIssuer: string;@@ -279,7 +269,11 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: {threadId: input.threadId,state: input.state,} satisfies RelayAgentActivityPublishProofPayload;- return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });+ return yield* signRelayJwt({+ privateKey: input.privateKey,+ typ: RELAY_ACTIVITY_PUBLISH_TYP,+ payload,+ });});function describeThreadShellForAwareness(@@ -378,6 +372,7 @@ export const make = Effect.gen(function* () {const threads = yield* ThreadManagement.ThreadManagementService;const projects = yield* ProjectService.ProjectService;const random = yield* SecureRandom.SecureRandom;+ const signature = yield* Signature.Signature;const scope = yield* Effect.scope;const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);const startedAt = (yield* DateTime.now).epochMilliseconds;@@ -491,7 +486,7 @@ export const make = Effect.gen(function* () {threadId,state: input.state,jti: yield* random.uuidV4(),- });+ }).pipe(Effect.provideService(Signature.Signature, signature));yield* Effect.logInfo("publishing agent activity for thread", {environmentId,diff --git a/apps/server/src/scheduledTasks/RelayDeliveryProof.ts b/apps/server/src/scheduledTasks/RelayDeliveryProof.tsindex 0f33869c387..4cc7ff2b237 100644--- a/apps/server/src/scheduledTasks/RelayDeliveryProof.ts+++ b/apps/server/src/scheduledTasks/RelayDeliveryProof.ts@@ -6,21 +6,19 @@ import {RELAY_HOOK_DELIVERY_TYP,verifyRelayJwt,} from "@t3tools/shared/relayJwt";-import * as Clock from "effect/Clock";import * as Context from "effect/Context";+import * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";-import * as Schema from "effect/Schema";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import { CLOUD_MINT_PUBLIC_KEY, RELAY_ISSUER_SECRET, RELAY_URL_SECRET } from "../cloud/config.ts";import * as ServerEnvironment from "../environment/ServerEnvironment.ts";/** Covers the relay's 24-hour hold plus a margin. */-const MAX_PROOF_AGE_SECONDS = 25 * 60 * 60;+const MAX_PROOF_AGE = "25 hours";-const decodePayload = Schema.decodeUnknownOption(RelayHookDeliveryProofPayload);const text = (bytes: Option.Option<Uint8Array>) =>Option.map(bytes, (value) => new TextDecoder().decode(value));@@ -39,6 +37,7 @@ export class RelayDeliveryProof extends Context.Service<const make = Effect.gen(function* () {const secrets = yield* ServerSecretStore.ServerSecretStore;const environment = yield* ServerEnvironment.ServerEnvironment;+ const signature = yield* Signature.Signature;const verify: RelayDeliveryProof["Service"]["verify"] = Effect.fn("webhook.verifyRelayDelivery")(function* (input) {const proof = input.headers[RELAY_HOOK_DELIVERY_HEADER];@@ -55,15 +54,14 @@ const make = Effect.gen(function* () {const relayIssuer = Option.isSome(issuer) ? issuer : relayUrl;if (Option.isNone(publicKey) || Option.isNone(relayIssuer)) return Option.none();const environmentId = yield* environment.getEnvironmentId;- const payload = yield* verifyRelayJwt({+ const payload = yield* verifyRelayJwt(RelayHookDeliveryProofPayload, {publicKey: publicKey.value,token: proof,typ: RELAY_HOOK_DELIVERY_TYP,issuer: normalizeRelayIssuer(relayIssuer.value),audience: `t3-env:${environmentId}`,- nowEpochSeconds: Math.floor((yield* Clock.currentTimeMillis) / 1_000),- maxTokenAge: MAX_PROOF_AGE_SECONDS,- }).pipe(Effect.map(decodePayload), Effect.orElseSucceed(Option.none));+ maxTokenAge: MAX_PROOF_AGE,+ }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);// The proof must name exactly this delivery, so it cannot be lifted onto another one.if (Option.isNone(payload) ||diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.tsindex d920840c700..ace3d93b9ac 100644--- a/apps/server/src/scheduledTasks/webhookRoute.test.ts+++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts@@ -1,3 +1,4 @@+import * as PlatformNodeCrypto from "@effect/platform-node/NodeCrypto";import { describe, expect, it } from "@effect/vitest";// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.import * as NodeCrypto from "node:crypto";@@ -66,7 +67,7 @@ const relayProof = Effect.fn("relayProof")(function* (claims: {receivedAt: claims.receivedAt,hookId: claims.hookId,},- });+ }).pipe(Effect.provide(PlatformNodeCrypto.layerSignature));});const handlerFor = (@@ -101,7 +102,7 @@ const handlerFor = (Layer.provideMerge(Etag.layerWeak),),),- Layer.provide(NodeServices.layer),+ Layer.provide([NodeServices.layer, PlatformNodeCrypto.layerSignature]),),{ disableLogger: true },);diff --git a/apps/web/package.json b/apps/web/package.jsonindex 3421f42d394..57ed8f275f0 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -65,7 +65,6 @@"hast-util-to-jsx-runtime": "^2.3.6","heic-to": "^1.5.2","html-url-attributes": "^3.0.1",- "jose": "catalog:","jsonc-parser": "3.3.1","jszip": "3.10.1","katex": "^0.16.47",diff --git a/apps/web/src/cloud/dpop.test.ts b/apps/web/src/cloud/dpop.test.tsindex b0aecbbf474..da869e08522 100644--- a/apps/web/src/cloud/dpop.test.ts+++ b/apps/web/src/cloud/dpop.test.ts@@ -1,7 +1,7 @@import { verifyDpopProof } from "@t3tools/shared/dpop";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";-import { decodeJwt } from "jose";+import * as TestClock from "effect/testing/TestClock";import { vi } from "vite-plus/test";import { createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";@@ -11,6 +11,7 @@ describe("browser DPoP proofs", () => {it.effect("signs relay resource proofs with an access-token hash", () =>Effect.gen(function* () {vi.stubGlobal("indexedDB", undefined);+ yield* TestClock.setTime(1_700_000_000_000);const proofKey = yield* generateBrowserDpopKey;const proof = yield* createBrowserDpopProof({method: "POST",@@ -18,8 +19,6 @@ describe("browser DPoP proofs", () => {accessToken: "relay-access-token",proofKey,}).pipe(Effect.provide(Dpop.layer));- const issuedAt = decodeJwt(proof.proof).iat;- expect(issuedAt).toBeTypeOf("number");expect(verifyDpopProof({@@ -28,7 +27,7 @@ describe("browser DPoP proofs", () => {url: "https://relay.example.test/v1/environments/env-1/connect",expectedThumbprint: proof.thumbprint,expectedAccessToken: "relay-access-token",- nowEpochSeconds: issuedAt!,+ nowEpochSeconds: 1_700_000_000,}),).toMatchObject({ ok: true });}),diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.tsindex 758d14b1aba..203222303e8 100644--- a/apps/web/src/cloud/dpop.ts+++ b/apps/web/src/cloud/dpop.ts@@ -5,11 +5,14 @@ import {} from "@t3tools/shared/dpop";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";+import * as Clock from "effect/Clock";import * as Data from "effect/Data";import * as Effect from "effect/Effect";+import * as Jwt from "effect/jose/Jwt";import * as Layer from "effect/Layer";+import * as Redacted from "effect/Redacted";import * as Schema from "effect/Schema";-import { importJWK, SignJWT, type JWK } from "jose";export interface BrowserDpopKey {readonly privateKey: CryptoKey;@@ -28,7 +31,9 @@ const DPOP_KEY_STORE_NAME = "keys";const DPOP_KEY_ID = "relay-dpop-proof-key";const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk);-export const layer = Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto);+export const layer = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(+ Layer.provideMerge(SecureRandom.layerWebCrypto),+);function dpopError(message: string, cause?: unknown) {return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });@@ -122,7 +127,10 @@ export const generateBrowserDpopKey = Effect.gen(function* () {),);const privateKey = yield* Effect.tryPromise({- try: () => importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise<CryptoKey>,+ try: () =>+ crypto.subtle.importKey("jwk", privateJwk, { name: "ECDSA", namedCurve: "P-256" }, false, [+ "sign",+ ]),catch: (cause) => dpopError("Could not import DPoP private key.", cause),});return {@@ -140,7 +148,7 @@ export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(f}): Effect.fn.Return<{ readonly proof: string; readonly thumbprint: string },BrowserDpopError,- SecureRandom.SecureRandom+ SecureRandom.SecureRandom | Signature.Signature> {const normalizedUrl = yield* Effect.try({try: () => new URL(input.url),@@ -149,22 +157,24 @@ export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(fnormalizedUrl.search = "";normalizedUrl.hash = "";const jti = yield* SecureRandom.SecureRandom.pipe(Effect.flatMap((random) => random.uuidV4()));- const proof = yield* Effect.tryPromise({- try: () =>- new SignJWT({- htm: input.method.toUpperCase(),- htu: normalizedUrl.toString(),- jti,- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),- })- .setProtectedHeader({- typ: "dpop+jwt",- alg: "ES256",- jwk: input.proofKey.publicJwk,- })- .setIssuedAt()- .sign(input.proofKey.privateKey),- catch: (cause) => dpopError("Could not sign DPoP proof.", cause),- });+ const key = yield* Signature.privateKeyFromCryptoKey(+ Signature.ecdsaP256,+ input.proofKey.privateKey,+ ).pipe(Effect.mapError((cause) => dpopError("Could not load DPoP proof key.", cause)));+ const proof = yield* Jwt.sign(+ Schema.Json,+ {+ htm: input.method.toUpperCase(),+ htu: normalizedUrl.toString(),+ jti,+ iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000),+ ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),+ },+ { _tag: "PrivateKey", algorithm: "ES256", kid: undefined, key },+ { typ: "dpop+jwt", jwk: input.proofKey.publicJwk },+ ).pipe(+ Effect.map(Redacted.value),+ Effect.mapError((cause) => dpopError("Could not sign DPoP proof.", cause)),+ );return { proof, thumbprint: input.proofKey.thumbprint };});diff --git a/apps/web/src/cloud/managedRelayLayer.ts b/apps/web/src/cloud/managedRelayLayer.tsindex 0d293d03a42..9d20528728f 100644--- a/apps/web/src/cloud/managedRelayLayer.ts+++ b/apps/web/src/cloud/managedRelayLayer.ts@@ -1,6 +1,7 @@import { ManagedRelay } from "@t3tools/client-runtime/relay";import { RelayWebClientId } from "@t3tools/contracts/relay";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Semaphore from "effect/Semaphore";@@ -17,6 +18,7 @@ const layerRelayDpopSigner = Layer.effect(ManagedRelay.ManagedRelayDpopSigner,Effect.gen(function* () {const random = yield* SecureRandom.SecureRandom;+ const signature = yield* Signature.Signature;const keyLoadSemaphore = yield* Semaphore.make(1);let loadedKey: BrowserDpopKey | null = null;const loadOrCreateBrowserDpopKey = keyLoadSemaphore.withPermit(@@ -61,6 +63,7 @@ const layerRelayDpopSigner = Layer.effect();return yield* createBrowserDpopProof({ ...input, proofKey }).pipe(Effect.provideService(SecureRandom.SecureRandom, random),+ Effect.provideService(Signature.Signature, signature),Effect.map((proof) => proof.proof),Effect.mapError((error) =>diff --git a/infra/relay/src/auth/RelayTokens.test.ts b/infra/relay/src/auth/RelayTokens.test.tsindex 502f7b9a48e..fc6e35fec03 100644--- a/infra/relay/src/auth/RelayTokens.test.ts+++ b/infra/relay/src/auth/RelayTokens.test.ts@@ -3,9 +3,12 @@ import * as NodeCrypto from "node:crypto";import { describe, expect, it } from "@effect/vitest";import { signRelayJwt } from "@t3tools/shared/relayJwt";+import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Redacted from "effect/Redacted";+import * as TestClock from "effect/testing/TestClock";import * as RelayConfiguration from "../Config.ts";import * as RelayTokens from "./RelayTokens.ts";@@ -34,7 +37,11 @@ const config = RelayConfiguration.RelayConfiguration.of({managedEndpointNamespace: undefined,});-const layer = RelayTokens.layer.pipe(Layer.provide(RelayConfiguration.layer(config)));+const layer = RelayTokens.layer.pipe(+ Layer.provide(RelayConfiguration.layer(config)),+ Layer.provideMerge(Signature.layerWebCrypto),+ Layer.provide(SecureRandom.layerWebCrypto),+);describe("RelayTokens", () => {it.effect("issues a user-bound environment link challenge", () =>@@ -51,6 +58,7 @@ describe("RelayTokens", () => {issuedAtEpochSeconds: 100,expiresAtEpochSeconds: 200,});+ yield* TestClock.setTime(150_000);expect(yield* relayTokens.verifyLinkChallenge({@@ -61,7 +69,6 @@ describe("RelayTokens", () => {liveActivitiesEnabled: true,managedTunnelsEnabled: true,},- nowEpochSeconds: 150,}),).toMatchObject({ sub: "user_123", jti: "challenge-1" });expect(@@ -73,7 +80,6 @@ describe("RelayTokens", () => {liveActivitiesEnabled: true,managedTunnelsEnabled: true,},- nowEpochSeconds: 150,}),).toBeNull();}).pipe(Effect.provide(layer)),@@ -92,17 +98,15 @@ describe("RelayTokens", () => {scopes: ["environment:connect", "environment:status", "mobile:registration"],});- expect(- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 700 }),- ).toMatchObject({+ yield* TestClock.setTime(700_000);+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toMatchObject({sub: "user_123",cnf: { jkt: "proof-key-thumbprint" },client_id: "t3-mobile",scope: ["environment:connect", "environment:status", "mobile:registration"],});- expect(- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 1_961 }),- ).toBeNull();+ yield* TestClock.setTime(1_961_000);+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toBeNull();}).pipe(Effect.provide(layer)),);@@ -119,9 +123,8 @@ describe("RelayTokens", () => {scopes: ["environment:connect", "environment:status"],});- expect(- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 }),- ).toMatchObject({+ yield* TestClock.setTime(150_000);+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toMatchObject({client_id: "t3-web",scope: ["environment:connect", "environment:status"],cnf: { jkt: "web-proof-key-thumbprint" },@@ -148,7 +151,8 @@ describe("RelayTokens", () => {},});- expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();+ yield* TestClock.setTime(150_000);+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toBeNull();}).pipe(Effect.provide(layer)),);@@ -171,7 +175,8 @@ describe("RelayTokens", () => {},});- expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();+ yield* TestClock.setTime(150_000);+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toBeNull();}).pipe(Effect.provide(layer)),);});diff --git a/infra/relay/src/auth/RelayTokens.ts b/infra/relay/src/auth/RelayTokens.tsindex bf48980907a..9d6014b8d72 100644--- a/infra/relay/src/auth/RelayTokens.ts+++ b/infra/relay/src/auth/RelayTokens.ts@@ -16,6 +16,7 @@ import {verifyRelayJwt,} from "@t3tools/shared/relayJwt";import * as Context from "effect/Context";+import * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Redacted from "effect/Redacted";@@ -57,9 +58,6 @@ export type RelayDpopAccessTokenClaims = Omit<typeof RelayDpopAccessTokenClaims.readonly scope: ReadonlyArray<RelayDpopAccessTokenScope>;};-const decodeLinkChallengeClaims = Schema.decodeUnknownEffect(LinkChallengeClaims);-const decodeDpopAccessTokenClaims = Schema.decodeUnknownEffect(RelayDpopAccessTokenClaims);-const allowedScopesByClientId: Record<RelayPublicClientId,ReadonlySet<RelayDpopAccessTokenScope>@@ -97,7 +95,6 @@ export class RelayTokens extends Context.Service<readonly token: string;readonly userId: string;readonly request: RelayEnvironmentLinkChallengeRequest;- readonly nowEpochSeconds: number;}) => Effect.Effect<LinkChallengeClaims | null>;readonly issueDpopAccessToken: (input: {readonly userId: string;@@ -110,7 +107,6 @@ export class RelayTokens extends Context.Service<}) => Effect.Effect<string, RelayJwtError>;readonly verifyDpopAccessToken: (input: {readonly token: string;- readonly nowEpochSeconds: number;}) => Effect.Effect<RelayDpopAccessTokenClaims | null>;}>()("t3code-relay/auth/RelayTokens") {}@@ -118,6 +114,7 @@ export class RelayTokens extends Context.Service<const make = Effect.gen(function* () {const config = yield* RelayConfiguration.RelayConfiguration;const issuer = normalizeRelayIssuer(config.relayIssuer);+ const signature = yield* Signature.Signature;const issueLinkChallenge: RelayTokens["Service"]["issueLinkChallenge"] = Effect.fn("relay.tokens.issue_link_challenge",@@ -135,21 +132,20 @@ const make = Effect.gen(function* () {exp: input.expiresAtEpochSeconds,...input.request,},- });+ }).pipe(Effect.provideService(Signature.Signature, signature));});const verifyLinkChallenge: RelayTokens["Service"]["verifyLinkChallenge"] = Effect.fn("relay.tokens.verify_link_challenge",)((input) =>- verifyRelayJwt({+ verifyRelayJwt(LinkChallengeClaims, {publicKey: config.cloudMintPublicKey,token: input.token,typ: LINK_CHALLENGE_TYP,issuer,audience: issuer,- nowEpochSeconds: input.nowEpochSeconds,}).pipe(- Effect.flatMap(decodeLinkChallengeClaims),+ Effect.provideService(Signature.Signature, signature),Effect.map((claims) => {if (claims.sub !== input.userId ||@@ -182,28 +178,27 @@ const make = Effect.gen(function* () {scope: encodeOAuthScope(input.scopes),cnf: { jkt: input.proofKeyThumbprint },},- });+ }).pipe(Effect.provideService(Signature.Signature, signature));});const verifyDpopAccessToken: RelayTokens["Service"]["verifyDpopAccessToken"] = Effect.fn("relay.tokens.verify_dpop_access_token",)((input) =>- verifyRelayJwt({+ verifyRelayJwt(RelayDpopAccessTokenClaims, {publicKey: config.cloudMintPublicKey,token: input.token,typ: ACCESS_TOKEN_TYP,issuer,audience: issuer,- nowEpochSeconds: input.nowEpochSeconds,maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.tapError((error) =>Effect.annotateCurrentSpan("relay.tokens.verification_failure",RelayJwtError.diagnosticCode(error),),),- Effect.flatMap(decodeDpopAccessTokenClaims),Effect.map((claims): RelayDpopAccessTokenClaims | null => {const scopes = resolveDpopAccessTokenScopes({clientId: claims.client_id,diff --git a/infra/relay/src/environments/EnvironmentConnector.ts b/infra/relay/src/environments/EnvironmentConnector.tsindex ad22b54f9ae..00841b8731f 100644--- a/infra/relay/src/environments/EnvironmentConnector.ts+++ b/infra/relay/src/environments/EnvironmentConnector.ts@@ -31,6 +31,7 @@ import {import { stableStringify } from "@t3tools/shared/relaySigning";import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -151,12 +152,6 @@ export class EnvironmentConnector extends Context.Service<}>()("t3code-relay/environments/EnvironmentConnector") {}-const decodeMintResponseProof = Schema.decodeUnknownEffect(- RelayEnvironmentMintResponseProofPayload,-);-const decodeHealthResponseProof = Schema.decodeUnknownEffect(- RelayEnvironmentHealthResponseProofPayload,-);const isEnvironmentHealthError = Schema.is(Schema.Union([EnvironmentHttpBadRequestError,@@ -200,21 +195,17 @@ const currentTraceId = Effect.currentSpan.pipe(export const withoutRedirects = <A, E, R>(effect: Effect.Effect<A, E, R>) =>effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));-const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A, E>(input: {+const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A>(input: {readonly token: string;readonly typ: string;readonly issuer: string;readonly audience: string;- readonly nowEpochSeconds: number;readonly environmentPublicKeys: ReadonlyArray<string>;- readonly decodePayload: (input: unknown) => Effect.Effect<A, E>;+ readonly schema: Schema.ConstraintDecoder<A>;}) {- const { decodePayload, ...rest } = input;+ const { schema, environmentPublicKeys: _keys, ...rest } = input;for (const publicKey of input.environmentPublicKeys) {- const proof = yield* verifyRelayJwt({ ...rest, publicKey }).pipe(- Effect.flatMap(decodePayload),- Effect.option,- );+ const proof = yield* verifyRelayJwt(schema, { ...rest, publicKey }).pipe(Effect.option);if (Option.isSome(proof)) {return proof.value;}@@ -230,16 +221,14 @@ function verifyEnvironmentResponse(input: {readonly clientProofKeyThumbprint: string;readonly environmentPublicKeys: ReadonlyArray<string>;readonly relayIssuer: string;- readonly nowEpochSeconds: number;}) {return verifyWithEnvironmentKeys({token: input.response.proof,typ: RELAY_MINT_RESPONSE_TYP,issuer: `t3-env:${input.environmentId}`,audience: normalizeRelayIssuer(input.relayIssuer),- nowEpochSeconds: input.nowEpochSeconds,environmentPublicKeys: input.environmentPublicKeys,- decodePayload: decodeMintResponseProof,+ schema: RelayEnvironmentMintResponseProofPayload,}).pipe(Effect.map((proof) =>@@ -270,9 +259,8 @@ function verifyEnvironmentHealthResponse(input: {typ: RELAY_HEALTH_RESPONSE_TYP,issuer: `t3-env:${input.environmentId}`,audience: normalizeRelayIssuer(input.relayIssuer),- nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000),environmentPublicKeys: input.environmentPublicKeys,- decodePayload: decodeHealthResponseProof,+ schema: RelayEnvironmentHealthResponseProofPayload,}).pipe(Effect.map((proof) => {if (@@ -387,6 +375,7 @@ const make = Effect.gen(function* () {const settings = yield* RelayConfiguration.RelayConfiguration;const httpClient = yield* HttpClient.HttpClient;const random = yield* SecureRandom.SecureRandom;+ const signature = yield* Signature.Signature;const relayIssuer = normalizeRelayIssuer(settings.relayIssuer);const makeEnvironmentClient = (httpBaseUrl: string) =>makeEnvironmentHttpApiClient(httpBaseUrl).pipe(@@ -479,6 +468,7 @@ const make = Effect.gen(function* () {typ: RELAY_HEALTH_REQUEST_TYP,payload,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentMintRequestFailed({@@ -556,7 +546,7 @@ const make = Effect.gen(function* () {environmentPublicKeys: [link.environmentPublicKey],relayIssuer,now: yield* DateTime.now,- });+ }).pipe(Effect.provideService(Signature.Signature, signature));if (!verified) {return yield* new EnvironmentMintResponseInvalid({environmentId: input.environmentId,@@ -644,6 +634,7 @@ const make = Effect.gen(function* () {typ: RELAY_MINT_REQUEST_TYP,payload,}).pipe(+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentMintRequestFailed({@@ -693,8 +684,7 @@ const make = Effect.gen(function* () {clientProofKeyThumbprint: input.clientProofKeyThumbprint,environmentPublicKeys: [link.environmentPublicKey],relayIssuer,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- });+ }).pipe(Effect.provideService(Signature.Signature, signature));if (!verified) {return yield* new EnvironmentMintResponseInvalid({environmentId: input.environmentId,diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.tsindex 81fbafc55e9..bab85ffb722 100644--- a/infra/relay/src/environments/EnvironmentLinker.test.ts+++ b/infra/relay/src/environments/EnvironmentLinker.test.ts@@ -1,5 +1,6 @@// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.import * as NodeCrypto from "node:crypto";+import * as EffectNodeCrypto from "@effect/platform-node/NodeCrypto";import type {RelayEnvironmentLinkProofPayload,RelayEnvironmentLinkRequest,@@ -153,6 +154,7 @@ function layerTest(input?: {}),),),+ Layer.provideMerge(EffectNodeCrypto.layerSignature),);}diff --git a/infra/relay/src/environments/EnvironmentLinker.ts b/infra/relay/src/environments/EnvironmentLinker.tsindex f4789b94290..6a58f6ab4f3 100644--- a/infra/relay/src/environments/EnvironmentLinker.ts+++ b/infra/relay/src/environments/EnvironmentLinker.ts@@ -10,6 +10,7 @@ import {verifyRelayJwt,} from "@t3tools/shared/relayJwt";import * as Context from "effect/Context";+import * as Signature from "effect/crypto/Signature";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -142,22 +143,24 @@ const make = Effect.gen(function* () {const proofReplay = yield* DpopProofs.DpopProofReplay;const relayTokens = yield* RelayTokens.RelayTokens;const config = yield* RelayConfiguration.RelayConfiguration;+ const signature = yield* Signature.Signature;return EnvironmentLinker.of({link: Effect.fn("relay.environment_linker.link")(function* (input) {const now = yield* DateTime.now;const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const unverified = yield* Effect.try({- try: () => decodeRelayJwt(input.request.proof),- catch: (cause) =>- new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: "unknown",- reason: "invalid_signature_or_scope",- stage: "decode_token",- cause,- }),- });+ const unverified = yield* decodeRelayJwt(input.request.proof).pipe(+ Effect.mapError(+ (cause) =>+ new EnvironmentLinkProofInvalid({+ userId: input.userId,+ environmentId: "unknown",+ reason: "invalid_signature_or_scope",+ stage: "decode_token",+ cause,+ }),+ ),+ );const candidate = yield* decodeProof(unverified).pipe(Effect.mapError((cause) =>@@ -185,15 +188,14 @@ const make = Effect.gen(function* () {}const issuer = `t3-env:${candidate.environmentId}`;const relayIssuer = normalizeRelayIssuer(config.relayIssuer);- const verified = yield* verifyRelayJwt({+ const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, {publicKey: candidate.environmentPublicKey,token: input.request.proof,typ: RELAY_LINK_PROOF_TYP,issuer,audience: relayIssuer,- nowEpochSeconds: nowSeconds,}).pipe(- Effect.flatMap(decodeProof),+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentLinkProofInvalid({@@ -232,7 +234,6 @@ const make = Effect.gen(function* () {liveActivitiesEnabled: input.request.liveActivitiesEnabled,managedTunnelsEnabled: input.request.managedTunnelsEnabled,},- nowEpochSeconds: nowSeconds,});if (challenge === null) {return yield* new EnvironmentLinkProofInvalid({diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.tsindex 5206f6f482a..625ce46ce4d 100644--- a/infra/relay/src/environments/EnvironmentPublishSignatures.ts+++ b/infra/relay/src/environments/EnvironmentPublishSignatures.ts@@ -12,6 +12,7 @@ import {import { stableStringify } from "@t3tools/shared/relaySigning";import * as Context from "effect/Context";import * as Digest from "effect/crypto/Digest";+import * as Signature from "effect/crypto/Signature";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Base64Url from "effect/encoding/Base64Url";@@ -73,8 +74,6 @@ export class EnvironmentPublishSignatures extends Context.Service<}>()("t3code-relay/environments/EnvironmentPublishSignatures") {}-const decodeProof = Schema.decodeUnknownEffect(RelayAgentActivityPublishProofPayload);-function environmentPublishReplayThumbprintData(input: {readonly environmentId: string;readonly environmentPublicKey: string;@@ -94,6 +93,7 @@ const make = Effect.gen(function* () {const proofReplay = yield* DpopProofs.DpopProofReplay;const config = yield* RelayConfiguration.RelayConfiguration;const crypto = yield* Digest.Digest;+ const signature = yield* Signature.Signature;return EnvironmentPublishSignatures.of({verify: Effect.fn("relay.environment_publish_signatures.verify")(function* (input) {@@ -102,17 +102,18 @@ const make = Effect.gen(function* () {"relay.thread_id": input.threadId,});const now = yield* DateTime.now;- const decoded = yield* Effect.try({- try: () => decodeRelayJwt(input.request.proof),- catch: (cause) =>- new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "invalid_signature_or_payload",- stage: "decode_token",- cause,- }),- });+ const decoded = yield* decodeRelayJwt(input.request.proof).pipe(+ Effect.mapError(+ (cause) =>+ new EnvironmentPublishSignatureInvalid({+ environmentId: input.environmentId,+ threadId: input.threadId,+ reason: "invalid_signature_or_payload",+ stage: "decode_token",+ cause,+ }),+ ),+ );if (typeof decoded.exp === "number" &&decoded.exp <= Math.floor(now.epochMilliseconds / 1_000)@@ -123,15 +124,14 @@ const make = Effect.gen(function* () {expiresAt: DateTime.formatIso(DateTime.makeUnsafe(decoded.exp * 1_000)),});}- const proof = yield* verifyRelayJwt({+ const proof = yield* verifyRelayJwt(RelayAgentActivityPublishProofPayload, {publicKey: input.environmentPublicKey,token: input.request.proof,typ: RELAY_ACTIVITY_PUBLISH_TYP,issuer: `t3-env:${input.environmentId}`,audience: normalizeRelayIssuer(config.relayIssuer),- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),}).pipe(- Effect.flatMap(decodeProof),+ Effect.provideService(Signature.Signature, signature),Effect.mapError((cause) =>new EnvironmentPublishSignatureInvalid({diff --git a/infra/relay/src/hooks/HookForwarder.test.ts b/infra/relay/src/hooks/HookForwarder.test.tsindex a146ced9c10..0ecdee43617 100644--- a/infra/relay/src/hooks/HookForwarder.test.ts+++ b/infra/relay/src/hooks/HookForwarder.test.ts@@ -4,9 +4,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import * as NodeCrypto from "node:crypto";import * as EffectNodeCrypto from "@effect/platform-node/NodeCrypto";import { describe, expect, it } from "@effect/vitest";-import { RelayApi } from "@t3tools/contracts/relay";+import { RelayApi, RelayHookDeliveryProofPayload } from "@t3tools/contracts/relay";import * as Deferred from "effect/Deferred";-import * as Clock from "effect/Clock";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Redacted from "effect/Redacted";@@ -256,14 +255,13 @@ describe("HookForwarder", () => {}),);const sent = harness.sent[0]!;- const payload = yield* verifyRelayJwt({+ const payload = yield* verifyRelayJwt(RelayHookDeliveryProofPayload, {publicKey: mintKeys.publicKey,token: sent.headers["x-t3-relay-delivery"]!,typ: RELAY_HOOK_DELIVERY_TYP,issuer: settings.relayIssuer,audience: `t3-env:${environmentId}`,- nowEpochSeconds: Math.floor((yield* Clock.currentTimeMillis) / 1_000),- });+ }).pipe(Effect.provide(EffectNodeCrypto.layerSignature));expect(payload).toMatchObject({environmentId,hookId: "hook-1",diff --git a/infra/relay/src/hooks/HookForwarder.ts b/infra/relay/src/hooks/HookForwarder.tsindex d93c6b40746..037a851409c 100644--- a/infra/relay/src/hooks/HookForwarder.ts+++ b/infra/relay/src/hooks/HookForwarder.ts@@ -1,6 +1,7 @@import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -220,6 +221,7 @@ const make = Effect.gen(function* () {const rateLimiter = yield* HookRateLimiter;const inbox = yield* HookInbox.HookInbox;const random = yield* SecureRandom.SecureRandom;+ const signature = yield* Signature.Signature;const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(function* (input: {@@ -245,7 +247,7 @@ const make = Effect.gen(function* () {receivedAt: input.receivedAt,hookId: input.hookId,} satisfies RelayHookDeliveryProofPayload,- });+ }).pipe(Effect.provideService(Signature.Signature, signature));},(effect, _input) => effect.pipe(Effect.orDie),);diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.tsindex e6db7fc8b7a..0ed73648e78 100644--- a/infra/relay/src/http/Api.test.ts+++ b/infra/relay/src/http/Api.test.ts@@ -637,7 +637,10 @@ describe("relay managed tunnel recovery", () => {}),);expect(wrongAction).toMatchObject({ _tag: "Unauthorized" });- }).pipe(Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings)),+ }).pipe(+ Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings),+ Effect.provide(NodeCryptoLayer.layerSignature),+ ),);it.effect("rejects a signed registration proof for a different origin", () =>@@ -679,7 +682,10 @@ describe("relay managed tunnel recovery", () => {);expect(error).toMatchObject({ _tag: "Unauthorized" });- }).pipe(Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings)),+ }).pipe(+ Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings),+ Effect.provide(NodeCryptoLayer.layerSignature),+ ),);it.effect("registers recovery for an existing tunnel without provisioning it", () => {@@ -1458,7 +1464,7 @@ describe("relay routing fallback", () => {})),);expect(verified.map((input) => input.threadId)).toEqual(threadIds);- }).pipe(Effect.scoped),+ }).pipe(Effect.scoped, Effect.provide(NodeCryptoLayer.layerSignature)),);});diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.tsindex 902ace8c56d..f06d441c12c 100644--- a/infra/relay/src/http/Api.ts+++ b/infra/relay/src/http/Api.ts@@ -88,10 +88,6 @@ export const RELAY_HTTP_ROUTER_CONFIG = {maxParamLength: 512,} as const;-const decodeManagedTunnelRecoveryProof = Schema.decodeUnknownEffect(- RelayManagedEndpointRecoveryProofPayload,-);-const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>Effect.succeed(@@ -397,11 +393,7 @@ export const layerDpopClientAuth = Layer.effect(return yield* relayAuthInvalidError("invalid_bearer");}const token = readHttpAuthorizationCredential(credential);- const now = yield* DateTime.now;- const verified = yield* relayTokens.verifyDpopAccessToken({- token,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- });+ const verified = yield* relayTokens.verifyDpopAccessToken({ token });if (!verified) {return yield* relayAuthInvalidError("invalid_bearer");}@@ -588,18 +580,13 @@ export const verifyEnvironmentTunnelRecoveryProof = Effect.fn("relay.api.server.verifyEnvironmentTunnelRecoveryProof",)(function* (input: EnvironmentTunnelRecoveryProofInput) {const config = yield* RelayConfiguration.RelayConfiguration;- const now = yield* DateTime.now;- const verified = yield* verifyRelayJwt({+ const verified = yield* verifyRelayJwt(RelayManagedEndpointRecoveryProofPayload, {publicKey: input.environmentPublicKey,token: input.proof,typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,issuer: `t3-env:${input.environmentId}`,audience: normalizeRelayIssuer(config.relayIssuer),- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- }).pipe(- Effect.flatMap(decodeManagedTunnelRecoveryProof),- Effect.mapError(() => new HttpApiError.Unauthorized({})),- );+ }).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));if (verified.environmentId !== input.environmentId ||diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.tsindex 08b5cf1f7ab..fb6b926bd74 100644--- a/infra/relay/src/worker.ts+++ b/infra/relay/src/worker.ts@@ -7,6 +7,7 @@ import * as Cause from "effect/Cause";import * as DateTime from "effect/DateTime";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -73,7 +74,9 @@ import * as HookInbox from "./hooks/HookInbox.ts";import * as HookInboxObject from "./hooks/HookInboxObject.ts";import * as MobileTelemetry from "./mobileTelemetry/MobileTelemetry.ts";-const layerWebcrypto = Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto);+const layerWebcrypto = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(+ Layer.provideMerge(SecureRandom.layerWebCrypto),+);const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, {platform: "web",diff --git a/packages/client-runtime/src/relay/discovery.ts b/packages/client-runtime/src/relay/discovery.tsindex ce5e708829d..63dadc6cadf 100644--- a/packages/client-runtime/src/relay/discovery.ts+++ b/packages/client-runtime/src/relay/discovery.ts@@ -105,15 +105,13 @@ function validateStatus(return Effect.succeed(status);}-function relayAccountId(clerkToken: string): Option.Option<string> {- try {- return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(- Option.filter((subject) => subject.length > 0),- );- } catch {- return Option.none();- }-}+const relayAccountId = Effect.fn("clientRuntime.discovery.relayAccountId")(function* (+ clerkToken: string,+) {+ const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option);+ const sub = Option.isSome(claims) ? claims.value.sub : undefined;+ return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none<string>();+});/** @public */export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {@@ -258,7 +256,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {if ((yield* Ref.get(accountGeneration)) !== generation) {return;}- const accountId = relayAccountId(clerkToken);+ const accountId = yield* relayAccountId(clerkToken);const previousAccountId = yield* Ref.get(activeAccountId);if (Option.isSome(previousAccountId) &&diff --git a/packages/client-runtime/src/relay/managedRelay.test.ts b/packages/client-runtime/src/relay/managedRelay.test.tsindex 0506609229a..76c6cb905a7 100644--- a/packages/client-runtime/src/relay/managedRelay.test.ts+++ b/packages/client-runtime/src/relay/managedRelay.test.ts@@ -36,7 +36,7 @@ function layerManagedRelayTest(function clerkToken(subject: string, nonce: string): string {const encode = (value: unknown) =>btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");- return `${encode({ alg: "none" })}.${encode({ sub: subject, nonce })}.signature`;+ return `${encode({ alg: "RS256" })}.${encode({ sub: subject, nonce })}.c2lnbmF0dXJl`;}describe("ManagedRelayClient", () => {diff --git a/packages/client-runtime/src/relay/managedRelay.ts b/packages/client-runtime/src/relay/managedRelay.tsindex 7c30ff640fb..a99e090314a 100644--- a/packages/client-runtime/src/relay/managedRelay.ts+++ b/packages/client-runtime/src/relay/managedRelay.ts@@ -408,15 +408,13 @@ function tokenMatches();}-function relayAccountId(clerkToken: string): Option.Option<string> {- try {- return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(- Option.filter((subject) => subject.length > 0),- );- } catch {- return Option.none();- }-}+const relayAccountId = Effect.fn("clientRuntime.managedRelay.relayAccountId")(function* (+ clerkToken: string,+) {+ const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option);+ const sub = Option.isSome(claims) ? claims.value.sub : undefined;+ return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none<string>();+});function bearerHeaders(clerkToken: string) {return { authorization: `Bearer ${clerkToken}` };@@ -564,7 +562,7 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* ("relay.scopes": input.scopes.join(" "),});const nowMillis = yield* Clock.currentTimeMillis;- const accountId = relayAccountId(input.clerkToken);+ const accountId = yield* relayAccountId(input.clerkToken);if (Option.isNone(accountId)) {yield* Effect.annotateCurrentSpan({"relay.token_cache.result": "bypass",diff --git a/packages/client-runtime/src/relay/managedRelayState.test.ts b/packages/client-runtime/src/relay/managedRelayState.test.tsindex 113de2e40bf..6b91a2213bb 100644--- a/packages/client-runtime/src/relay/managedRelayState.test.ts+++ b/packages/client-runtime/src/relay/managedRelayState.test.ts@@ -96,7 +96,7 @@ function setSession() {function clerkToken(expiresAtSeconds: number): string {const encode = (value: unknown) =>btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");- return `${encode({ alg: "none" })}.${encode({ exp: expiresAtSeconds })}.signature`;+ return `${encode({ alg: "RS256" })}.${encode({ exp: expiresAtSeconds })}.c2lnbmF0dXJl`;}describe("createManagedRelayQueryManager", () => {diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.tsindex c949faf2c32..983ccc87ffa 100644--- a/packages/client-runtime/src/relay/managedRelayState.ts+++ b/packages/client-runtime/src/relay/managedRelayState.ts@@ -85,15 +85,16 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): ManacachedToken = null;return null;}- try {- const expiresAtSeconds = decodeRelayJwt(token).exp;- cachedToken =- typeof expiresAtSeconds === "number"- ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }- : null;- } catch {- cachedToken = null;- }+ const expiresAtSeconds = Effect.runSync(+ decodeRelayJwt(token).pipe(+ Effect.map((claims) => claims.exp),+ Effect.orElseSucceed(() => undefined),+ ),+ );+ cachedToken =+ typeof expiresAtSeconds === "number"+ ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }+ : null;return token;});pendingToken = operation;diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 8835c6918c3..72c53671a1e 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -534,7 +534,6 @@"@t3tools/contracts": "workspace:*","effect": "catalog:","ffi-rs": "1.3.2",- "jose": "catalog:","mdast-util-directive": "catalog:","mdast-util-to-hast": "^13.2.1","micromark-extension-directive": "catalog:",diff --git a/packages/shared/src/relayJwt.test.ts b/packages/shared/src/relayJwt.test.tsindex f0557bfe505..0e41fb3a717 100644--- a/packages/shared/src/relayJwt.test.ts+++ b/packages/shared/src/relayJwt.test.ts@@ -1,16 +1,51 @@+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";import { describe, expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Jwk from "effect/jose/Jwk";+import * as Redacted from "effect/Redacted";+import * as Schema from "effect/Schema";+import * as TestClock from "effect/testing/TestClock";-import { RelayJwtError } from "./relayJwt.ts";+import { decodeRelayJwt, RelayJwtError, signRelayJwt, verifyRelayJwt } from "./relayJwt.ts";++const Claims = Schema.Struct({ sub: Schema.String });++const keyPair = Effect.gen(function* () {+ const pair = yield* Jwk.generateKeyPair({ algorithm: "EdDSA" });+ const publicKey = yield* Jwk.importPublic(pair.publicKey, "EdDSA").pipe(+ Effect.flatMap((key) => Jwk.exportSpki(key, { format: "pem" })),+ );+ const privateKey = yield* Jwk.importPrivate(pair.privateKey, "EdDSA").pipe(+ Effect.flatMap((key) => Jwk.exportPkcs8(key, { format: "pem" })),+ );+ return { publicKey, privateKey: Redacted.value(privateKey) };+});describe("relayJwt", () => {- it("extracts stable diagnostic codes without copying cause text into the error message", () => {- const error = new RelayJwtError({- operation: "verify",- typ: "test+jwt",- cause: { code: "ERR_JWT_EXPIRED", message: "sensitive library detail" },- });+ it.effect("verifies against the ambient clock and reports claim diagnostics", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(1_000_000);+ const keys = yield* keyPair;+ const token = yield* signRelayJwt({+ privateKey: keys.privateKey,+ typ: "test+jwt",+ payload: { sub: "user", iss: "relay", aud: "env", iat: 1_000, exp: 1_100 },+ });+ const verify = verifyRelayJwt(Claims, {+ publicKey: keys.publicKey,+ token,+ typ: "test+jwt",+ issuer: "relay",+ audience: "env",+ });++ expect(yield* verify).toEqual({ sub: "user" });+ expect((yield* decodeRelayJwt(token)).sub).toBe("user");- expect(RelayJwtError.diagnosticCode(error)).toBe("ERR_JWT_EXPIRED");- expect(error.message).not.toContain("sensitive library detail");- });+ yield* TestClock.adjust("161 seconds");+ const error = yield* Effect.flip(verify);+ expect(RelayJwtError.diagnosticCode(error)).toBe("ClaimValidationFailed.exp.expired");+ expect(error.message).toBe('Failed to verify relay JWT of type "test+jwt".');+ }).pipe(Effect.provide(NodeCrypto.layerSignature)),+ );});diff --git a/packages/shared/src/relayJwt.ts b/packages/shared/src/relayJwt.tsindex ba309b028e3..f21a532bd0b 100644--- a/packages/shared/src/relayJwt.ts+++ b/packages/shared/src/relayJwt.ts@@ -1,7 +1,11 @@-import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";-import * as DateTime from "effect/DateTime";+import type * as Signature from "effect/crypto/Signature";+import type * as Duration from "effect/Duration";import * as Effect from "effect/Effect";-import * as Predicate from "effect/Predicate";+import * as JoseError from "effect/jose/JoseError";+import * as Jwk from "effect/jose/Jwk";+import * as Jws from "effect/jose/Jws";+import * as Jwt from "effect/jose/Jwt";+import * as Redacted from "effect/Redacted";import * as Schema from "effect/Schema";export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";@@ -15,88 +19,95 @@ export const RELAY_HOOK_DELIVERY_TYP = "t3-relay-hook-delivery+jwt";export const RELAY_HOOK_DELIVERY_HEADER = "x-t3-relay-delivery";export class RelayJwtError extends Schema.TaggedError<RelayJwtError>()("RelayJwtError", {- operation: Schema.Literals(["sign", "verify"]),- typ: Schema.String,+ operation: Schema.Literals(["sign", "verify", "decode"]),+ typ: Schema.optional(Schema.String),issuer: Schema.optional(Schema.String),audience: Schema.optional(Schema.String),cause: Schema.Defect(),}) {override get message(): string {- return `Failed to ${this.operation} relay JWT of type "${this.typ}".`;+ return this.typ === undefined+ ? `Failed to ${this.operation} relay JWT.`+ : `Failed to ${this.operation} relay JWT of type "${this.typ}".`;}static diagnosticCode(error: RelayJwtError): string {- if (- Predicate.isObject(error.cause) &&- Predicate.hasProperty(error.cause, "code") &&- Predicate.isString(error.cause.code) &&- error.cause.code.length > 0- ) {- return error.cause.code;+ if (JoseError.isJoseError(error.cause)) {+ const reason = error.cause.reason;+ return reason._tag === "ClaimValidationFailed"+ ? `${reason._tag}.${reason.claim}.${reason.reason}`+ : reason._tag;}-- return error.cause instanceof Error && error.cause.name ? error.cause.name : "unknown";+ return Schema.isSchemaError(error.cause) ? "SchemaError" : "unknown";}}+export type RelayJwtClaims = Readonly<Record<string, Schema.Json>>;+export function normalizeRelayIssuer(value: string): string {return value.trim().replace(/\/+$/gu, "");}-export function decodeRelayJwt(token: string): JWTPayload {- return decodeJwt(token);-}+/** Reads claims without verifying them. Never authorize on the result. */+export const decodeRelayJwt = Effect.fn("relayJwt.decode")(function* (+ token: string,+): Effect.fn.Return<RelayJwtClaims, RelayJwtError> {+ const unverified = yield* Jwt.decodeUnverified(token).pipe(+ Effect.mapError((cause) => new RelayJwtError({ operation: "decode", cause })),+ );+ return unverified.claims;+});function normalizePem(value: string): string {return value.replace(/\\n/gu, "\n").trim();}-export function signRelayJwt(input: {+export const signRelayJwt = Effect.fn("relayJwt.sign")(function* (input: {readonly privateKey: string;readonly typ: string;- readonly payload: JWTPayload;-}): Effect.Effect<string, RelayJwtError> {- return Effect.tryPromise({- try: async () => {- const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA");- return new SignJWT(input.payload)- .setProtectedHeader({ alg: "EdDSA", typ: input.typ })- .sign(key);- },- catch: (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),- });-}+ readonly payload: Readonly<Record<string, unknown>>;+}): Effect.fn.Return<string, RelayJwtError, Signature.Signature> {+ const token = yield* Jwk.importPkcs8(Redacted.make(normalizePem(input.privateKey)), "EdDSA").pipe(+ Effect.flatMap((key) =>+ Jws.sign(new TextEncoder().encode(JSON.stringify(input.payload)), key, { typ: input.typ }),+ ),+ Effect.mapError((cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause })),+ );+ return Redacted.value(token);+});-export function verifyRelayJwt(input: {- readonly publicKey: string;- readonly token: string;- readonly typ: string;- readonly issuer: string;- readonly audience: string;- readonly nowEpochSeconds: number;- readonly maxTokenAge?: string | number;-}): Effect.Effect<JWTPayload, RelayJwtError> {- return Effect.tryPromise({- try: async () => {- const key = await importSPKI(normalizePem(input.publicKey), "EdDSA");- const verified = await jwtVerify(input.token, key, {- algorithms: ["EdDSA"],+/** Verifies an EdDSA relay JWT against the ambient `Clock` and decodes its claims. */+export const verifyRelayJwt = Effect.fn("relayJwt.verify")(function* <A>(+ schema: Schema.ConstraintDecoder<A>,+ input: {+ readonly publicKey: string;+ readonly token: string;+ readonly typ: string;+ readonly issuer: string;+ readonly audience: string;+ readonly maxTokenAge?: Duration.Input;+ },+): Effect.fn.Return<A, RelayJwtError, Signature.Signature> {+ const verified = yield* Jwk.importSpki(normalizePem(input.publicKey), "EdDSA").pipe(+ Effect.flatMap((key) =>+ Jwt.verify(schema, input.token, key, {typ: input.typ,issuer: input.issuer,audience: input.audience,maxTokenAge: input.maxTokenAge ?? "5 minutes",- clockTolerance: 60,- currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),- });- return verified.payload;- },- catch: (cause) =>- new RelayJwtError({- operation: "verify",- typ: input.typ,- issuer: input.issuer,- audience: input.audience,- cause,+ clockTolerance: "60 seconds",}),- });-}+ ),+ Effect.mapError(+ (cause) =>+ new RelayJwtError({+ operation: "verify",+ typ: input.typ,+ issuer: input.issuer,+ audience: input.audience,+ cause,+ }),+ ),+ );+ return verified.claims;+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bc0372629cf..4f5985a40bc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -909,9 +909,6 @@ importers:ffi-rs:specifier: 1.3.2version: 1.3.2- jose:- specifier: 'catalog:'- version: 6.2.2node-pty:specifier: 1.2.0-beta.15version: 1.2.0-beta.15(patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651)@@ -1165,9 +1162,6 @@ importers:html-url-attributes:specifier: ^3.0.1version: 3.0.1- jose:- specifier: 'catalog:'- version: 6.2.2jsonc-parser:specifier: 3.3.1version: 3.3.1@@ -2048,9 +2042,6 @@ importers:ffi-rs:specifier: 1.3.2version: 1.3.2- jose:- specifier: 'catalog:'- version: 6.2.2mdast-util-directive:specifier: 'catalog:'version: 3.1.0([email protected])