TypeScript
refactor: move HMAC, key, and random work to effect/crypto (#30501)
Julius Marmingefb99a5e4b026
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.tsindex aabc374798f..b0c042c05f5 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts@@ -262,10 +262,10 @@ describe("DesktopBackendConfiguration", () => {);assert.equal(first.bootstrap.desktopBootstrapToken,- currentDesktopBootstrapToken(+ yield* currentDesktopBootstrapToken(first.bootstrap.desktopBootstrapSecret ?? "",yield* Clock.currentTimeMillis,- ),+ ).pipe(Effect.provide(NodeCrypto.layerMac)),);assert.equal(yield* configuration.currentBootstrapToken,diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.tsindex 69a70b68a4b..1789c31eb40 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts@@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToimport * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Hex from "effect/encoding/Hex";import * as FileSystem from "effect/FileSystem";@@ -723,6 +724,7 @@ export const make = Effect.gen(function* () {const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;const settings = yield* DesktopAppSettings.DesktopAppSettings;+ const mac = yield* Mac.Mac;const random = yield* SecureRandom.SecureRandom;// Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets.const secretRef = yield* SynchronizedRef.make(Option.none<string>());@@ -741,10 +743,10 @@ export const make = Effect.gen(function* () {const sharedInputs = Effect.gen(function* () {const bootstrapSecret = yield* getOrCreateBootstrapSecret;- const bootstrapToken = currentDesktopBootstrapToken(+ const bootstrapToken = yield* currentDesktopBootstrapToken(bootstrapSecret,yield* Clock.currentTimeMillis,- );+ ).pipe(Effect.provideService(Mac.Mac, mac));const observabilitySettings = yield* readBackendObservabilitySettings.pipe(Effect.provideService(FileSystem.FileSystem, fileSystem),Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),@@ -806,7 +808,9 @@ export const make = Effect.gen(function* () {const currentBootstrapToken = Effect.gen(function* () {const secret = yield* getOrCreateBootstrapSecret;- return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);+ return yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(+ Effect.provideService(Mac.Mac, mac),+ );});return DesktopBackendConfiguration.of({diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.tsindex be16c4ecc43..e82e3afea73 100644--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts@@ -1,3 +1,4 @@+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";import { assert, describe, it } from "@effect/vitest";import * as Deferred from "effect/Deferred";import * as Duration from "effect/Duration";@@ -80,7 +81,7 @@ describe("DesktopLocalEnvironmentAuth", () => {]),} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);const layerTest = DesktopLocalEnvironmentAuth.layer.pipe(- Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),+ Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),);const [first, second] = yield* Effect.gen(function* () {@@ -151,14 +152,17 @@ describe("DesktopLocalEnvironmentAuth", () => {}).pipe(Effect.provide(DesktopLocalEnvironmentAuth.layer.pipe(- Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),+ Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer, NodeCrypto.layerMac)),),),);assert.strictEqual(yield* Ref.get(presented),- currentDesktopBootstrapToken("desktop-secret", DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS * 2 + 1),+ yield* currentDesktopBootstrapToken(+ "desktop-secret",+ DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS * 2 + 1,+ ).pipe(Effect.provide(NodeCrypto.layerMac)),);}).pipe(Effect.provide(TestClock.layer())),);@@ -205,7 +209,7 @@ describe("DesktopLocalEnvironmentAuth", () => {const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(Effect.provide(DesktopLocalEnvironmentAuth.layer.pipe(- Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),+ Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),),),);diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.tsindex e916b35053e..6c7d24623d4 100644--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts@@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToimport * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as Duration from "effect/Duration";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -67,6 +68,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<export const make = Effect.gen(function* () {const pool = yield* DesktopBackendPool.DesktopBackendPool;const httpClient = yield* HttpClient.HttpClient;+ const mac = yield* Mac.Mac;const tokenRef = yield* Ref.make(Option.none<string>());const mutex = yield* Semaphore.make(1);@@ -93,7 +95,9 @@ export const make = Effect.gen(function* () {const credential =secret === undefined? config.bootstrap.desktopBootstrapToken- : currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);+ : yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(+ Effect.provideService(Mac.Mac, mac),+ );if (!credential) {return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();}diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.tsindex c4c0b3f7e93..47f4b75f832 100644--- a/apps/server/src/assets/AssetAccess.ts+++ b/apps/server/src/assets/AssetAccess.ts@@ -51,7 +51,7 @@ import {base64UrlDecodeUtf8,base64UrlEncode,signPayload,- timingSafeEqualBase64Url,+ verifyPayloadSignature,} from "../auth/utils.ts";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";@@ -872,7 +872,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (iclaims = { ...claims, expiresAt };}const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));- const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;+ const token = `${encodedPayload}.${yield* signPayload(encodedPayload, signingSecret)}`;return {relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,expiresAt,@@ -895,7 +895,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (Effect.orElseSucceed(() => null),);if (!signingSecret) return null;- if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;+ if (!(yield* verifyPayloadSignature(encodedPayload, signature, signingSecret))) return null;const claims = decodeClaims(encodedPayload);if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;diff --git a/apps/server/src/assets/AttachmentUpload.test.ts b/apps/server/src/assets/AttachmentUpload.test.tsindex 0aea7a412ac..ac59683688b 100644--- a/apps/server/src/assets/AttachmentUpload.test.ts+++ b/apps/server/src/assets/AttachmentUpload.test.ts@@ -165,7 +165,7 @@ describe("AttachmentUpload", () => {expiresAt: issued.expiresAt,}),);- const legacyToken = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;+ const legacyToken = `${encodedPayload}.${yield* signPayload(encodedPayload, secret)}`;expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({type: "image",diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.tsindex 4865dbf82ee..de1be7eacd2 100644--- a/apps/server/src/assets/AttachmentUpload.ts+++ b/apps/server/src/assets/AttachmentUpload.ts@@ -31,7 +31,7 @@ import {base64UrlDecodeUtf8,base64UrlEncode,signPayload,- timingSafeEqualBase64Url,+ verifyPayloadSignature,} from "../auth/utils.ts";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as ServerConfig from "../config.ts";@@ -120,9 +120,10 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f}),);+ const signature = yield* signPayload(encodedPayload, secret);return {attachmentId,- relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`,+ relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signature}`,expiresAt,};});@@ -141,7 +142,7 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat),Effect.orElseSucceed(() => null),);- if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) {+ if (!secret || !(yield* verifyPayloadSignature(encodedPayload, signature, secret))) {return null;}diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.tsindex 3f4d7ff51f8..9c7d05b7dfa 100644--- a/apps/server/src/auth/McpOAuth.ts+++ b/apps/server/src/auth/McpOAuth.ts@@ -23,6 +23,7 @@ import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -44,6 +45,7 @@ import {deriveAuthClientMetadata,signPayload,timingSafeEqualBase64Url,+ verifyPayloadSignature,} from "./utils.ts";import { requestUrl } from "../requestUrl.ts";@@ -266,27 +268,33 @@ const make = Effect.gen(function* () {.pipe(Effect.orDie);const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());- const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);+ const mac = yield* Mac.Mac;+ const sign = (domain: string, payload: string) =>+ signPayload(`${domain}.${payload}`, signingKey).pipe(Effect.provideService(Mac.Mac, mac));const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),);- return `${body}.${sign("mcp-client-id", body)}`;+ return sign("mcp-client-id", body).pipe(Effect.map((signature) => `${body}.${signature}`));};- const parseClientId = (clientId: string): McpOAuthClient | undefined => {+ // Untraced: only called inside the traced McpOAuth methods below.+ const parseClientId = Effect.fnUntraced(function* (+ clientId: string,+ ): Effect.fn.Return<McpOAuthClient | undefined> {const [body, signature, extra] = clientId.split(".");if (!body || !signature || extra !== undefined) return undefined;- if (!timingSafeEqualBase64Url(signature, sign("mcp-client-id", body))) return undefined;- let json: string;- try {- json = base64UrlDecodeUtf8(body);- } catch {- return undefined;- }+ const verified = yield* verifyPayloadSignature(+ `mcp-client-id.${body}`,+ signature,+ signingKey,+ ).pipe(Effect.provideService(Mac.Mac, mac));+ if (!verified) return undefined;+ const json = yield* Effect.try(() => base64UrlDecodeUtf8(body)).pipe(Effect.option);+ if (Option.isNone(json)) return undefined;return Option.getOrUndefined(- decodeClientIdPayload(json).pipe(+ decodeClientIdPayload(json.value).pipe(Option.map((payload) => ({clientId,name: payload.n,@@ -295,7 +303,7 @@ const make = Effect.gen(function* () {})),),);- };+ });const pkceVerifies = (verifier: string, challenge: string) =>CODE_VERIFIER_PATTERN.test(verifier)@@ -347,7 +355,7 @@ const make = Effect.gen(function* () {});}return {- clientId: signClientId(name, redirectUris, peerLink),+ clientId: yield* signClientId(name, redirectUris, peerLink),name,redirectUris,peerLink,@@ -358,7 +366,7 @@ const make = Effect.gen(function* () {const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn("McpOAuth.validateAuthorization",)(function* ({ urls, request }) {- const client = parseClientId(request.client_id ?? "");+ const client = yield* parseClientId(request.client_id ?? "");if (client === undefined) {return yield* new McpOAuthPageError({description: "This sign-in link names an unknown app. Start the sign-in again from it.",@@ -410,12 +418,14 @@ const make = Effect.gen(function* () {authorization,) =>environmentAuth.authenticateBrowserSession(request).pipe(- Effect.map((session) =>+ Effect.flatMap((session) =>// Approving manages access, and a session may only hand out scopes it holds.session.scopes.includes(AuthAccessWriteScope) &&session.scopes.includes(AuthOrchestrationReadScope)- ? { csrfToken: csrfToken(session.sessionId, authorization), scopes: session.scopes }- : undefined,+ ? csrfToken(session.sessionId, authorization).pipe(+ Effect.map((token) => ({ csrfToken: token, scopes: session.scopes })),+ )+ : Effect.undefined,),Effect.orElseSucceed(() => undefined),);@@ -507,7 +517,7 @@ const make = Effect.gen(function* () {"code, redirect_uri, client_id and code_verifier are required.",);}- if (parseClientId(clientId) === undefined) {+ if ((yield* parseClientId(clientId)) === undefined) {return yield* fail("invalid_client", "The client is unknown.");}// A presented code is spent even when a later check fails (RFC 6749 §4.1.2).diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.tsindex 4a9b277b554..baa7f388f2b 100644--- a/apps/server/src/auth/PairingGrantStore.test.ts+++ b/apps/server/src/auth/PairingGrantStore.test.ts@@ -182,15 +182,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStoryield* TestClock.adjust(Duration.days(5));const now = 5 * 24 * 60 * 60 * 1000;const current = yield* bootstrapCredentials.consume(- currentDesktopBootstrapToken("desktop-secret", now),+ yield* currentDesktopBootstrapToken("desktop-secret", now).pipe(+ Effect.provide(NodeCrypto.layerMac),+ ),);expect(current.method).toBe("desktop-bootstrap");- const stale = yield* Effect.flip(- bootstrapCredentials.consume(- currentDesktopBootstrapToken("desktop-secret", now - 2 * window),- ),- );+ const staleToken = yield* currentDesktopBootstrapToken(+ "desktop-secret",+ now - 2 * window,+ ).pipe(Effect.provide(NodeCrypto.layerMac));+ const stale = yield* Effect.flip(bootstrapCredentials.consume(staleToken));expect(stale._tag).toBe("UnknownBootstrapCredentialError");const launch = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.tsindex 3df0f6a3ea2..add1c7990f1 100644--- a/apps/server/src/auth/PairingGrantStore.ts+++ b/apps/server/src/auth/PairingGrantStore.ts@@ -12,6 +12,7 @@ import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -312,9 +313,13 @@ const make = Effect.gen(function* () {// Accept tokens derived from the rotating desktop secret; older desktops send only a token.const desktopBootstrapSecret = config.desktopBootstrapSecret;+ const mac = yield* Mac.Mac;const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>- desktopBootstrapSecret !== undefined &&- isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs);+ desktopBootstrapSecret === undefined+ ? Effect.succeed(false)+ : isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs).pipe(+ Effect.provideService(Mac.Mac, mac),+ );if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {const now = yield* DateTime.now;@@ -438,7 +443,7 @@ const make = Effect.gen(function* () {const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(function* (credential, input) {const now = yield* DateTime.now;- if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {+ if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {return {method: "desktop-bootstrap",scopes: AuthStandardClientScopes,diff --git a/apps/server/src/auth/ReusableDevAuth.ts b/apps/server/src/auth/ReusableDevAuth.tsindex 5d8da9a0f45..a9c0b5c3e0f 100644--- a/apps/server/src/auth/ReusableDevAuth.ts+++ b/apps/server/src/auth/ReusableDevAuth.ts@@ -1,6 +1,7 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no timingSafeEqual.+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Digest is effectful; this resolves the dev token synchronously at startup.import * as NodeCrypto from "node:crypto";import { AuthSessionId } from "@t3tools/contracts";+import * as Mac from "effect/crypto/Mac";import * as DateTime from "effect/DateTime";import * as Redacted from "effect/Redacted";@@ -27,6 +28,6 @@ export function resolveReusableDevAuth(sessionId: AuthSessionId.make(`${REUSABLE_DEV_SESSION_PREFIX}${tokenId}`),cookieName: `t3_dev_session_${tokenId}`,matches: (credential: string) =>- NodeCrypto.timingSafeEqual(hash, NodeCrypto.createHash("sha256").update(credential).digest()),+ Mac.timingSafeEqual(hash, NodeCrypto.createHash("sha256").update(credential).digest()),};}diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.tsindex 78f231e021a..919fcb118e1 100644--- a/apps/server/src/auth/SessionStore.test.ts+++ b/apps/server/src/auth/SessionStore.test.ts@@ -370,10 +370,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("SessionStore.layconst secret = yield* secrets.getOrCreateRandom("server-signing-key", 32);const resign = (claims: string) => {const payload = base64UrlEncode(claims);- return `${payload}.${signPayload(payload, secret)}`;+ return signPayload(payload, secret).pipe(+ Effect.map((signature) => `${payload}.${signature}`),+ );};- const legacyToken = resign(currentClaims.replace('"v":1', '"v":2'));- const editedToken = resign(+ const legacyToken = yield* resign(currentClaims.replace('"v":1', '"v":2'));+ const editedToken = yield* resign(currentClaims.replace(/"scopes":\[[^\]]*\]/, '"scopes":["access:write"]'),);diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.tsindex 12979242d2b..61d4355d920 100644--- a/apps/server/src/auth/SessionStore.ts+++ b/apps/server/src/auth/SessionStore.ts@@ -13,6 +13,7 @@ import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as PubSub from "effect/PubSub";@@ -36,7 +37,7 @@ import {resolveLegacySessionCookieName,resolveSessionCookieName,signPayload,- timingSafeEqualBase64Url,+ verifyPayloadSignature,} from "./utils.ts";export interface IssuedSession {@@ -497,6 +498,13 @@ const make = Effect.gen(function* () {const secretStore = yield* ServerSecretStore.ServerSecretStore;const authSessions = yield* AuthSessions.AuthSessionRepository;const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);+ const mac = yield* Mac.Mac;+ const sign = (payload: string) =>+ signPayload(payload, signingSecret).pipe(Effect.provideService(Mac.Mac, mac));+ const verifySignature = (payload: string, signature: string) =>+ verifyPayloadSignature(payload, signature, signingSecret).pipe(+ Effect.provideService(Mac.Mac, mac),+ );const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();// Newest session per DPoP key. A live socket moves to it at expiry, so a@@ -679,7 +687,7 @@ const make = Effect.gen(function* () {}),),);- const signature = signPayload(encodedPayload, signingSecret);+ const signature = yield* sign(encodedPayload);const client = input?.client ?? createDefaultClientMetadata();const sessionRecord = {sessionId,@@ -791,8 +799,7 @@ const make = Effect.gen(function* () {return yield* new MalformedSessionTokenError({});}- const expectedSignature = signPayload(encodedPayload, signingSecret);- if (!timingSafeEqualBase64Url(signature, expectedSignature)) {+ if (!(yield* verifySignature(encodedPayload, signature))) {return yield* new InvalidSessionTokenSignatureError({});}@@ -879,7 +886,7 @@ const make = Effect.gen(function* () {}),),);- const signature = signPayload(encodedPayload, signingSecret);+ const signature = yield* sign(encodedPayload);return {token: `${encodedPayload}.${signature}`,expiresAt,@@ -894,8 +901,7 @@ const make = Effect.gen(function* () {return yield* new MalformedWebSocketTokenError({});}- const expectedSignature = signPayload(encodedPayload, signingSecret);- if (!timingSafeEqualBase64Url(signature, expectedSignature)) {+ if (!(yield* verifySignature(encodedPayload, signature))) {return yield* new InvalidWebSocketTokenSignatureError({});}diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.tsindex 77235946ca7..986baff06dd 100644--- a/apps/server/src/auth/utils.ts+++ b/apps/server/src/auth/utils.ts@@ -4,10 +4,12 @@ import type {AuthClientPresentationMetadata,} from "@t3tools/contracts";import type * as HttpServerRequest from "effect/http/HttpServerRequest";-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Digest is effectful; the cookie name stays a plain function.import * as NodeCrypto from "node:crypto";import * as NodeNet from "node:net";import { normalizeHostname } from "@t3tools/shared/hostClassification";+import * as Mac from "effect/crypto/Mac";+import * as Effect from "effect/Effect";import * as Base64Url from "effect/encoding/Base64Url";import * as Result from "effect/Result";@@ -79,17 +81,38 @@ export function base64UrlDecodeUtf8(input: string): string {return Result.getOrThrow(Base64Url.decodeString(input));}-export function signPayload(payload: string, secret: Uint8Array): string {- return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");-}+const hmacKey = (secret: Uint8Array) => Mac.key(Mac.hmacSha256, secret).pipe(Effect.orDie);++// Untraced: every authenticated request signs or verifies at least one token.+export const signPayload = Effect.fnUntraced(function* (payload: string, secret: Uint8Array) {+ const mac = yield* Mac.Mac;+ const tag = yield* mac+ .sign(yield* hmacKey(secret), new TextEncoder().encode(payload))+ .pipe(Effect.orDie);+ return Base64Url.encode(tag);+});++export const verifyPayloadSignature = Effect.fnUntraced(function* (+ payload: string,+ signature: string,+ secret: Uint8Array,+) {+ const tag = Base64Url.decode(signature);+ if (Result.isFailure(tag)) return false;+ const mac = yield* Mac.Mac;+ return yield* mac+ .verify(yield* hmacKey(secret), tag.success, new TextEncoder().encode(payload))+ .pipe(Effect.orDie);+});export function timingSafeEqualBase64Url(left: string, right: string): boolean {- const leftBuffer = Buffer.from(left, "base64url");- const rightBuffer = Buffer.from(right, "base64url");- if (leftBuffer.length !== rightBuffer.length) {- return false;- }- return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);+ const leftBytes = Base64Url.decode(left);+ const rightBytes = Base64Url.decode(right);+ return (+ Result.isSuccess(leftBytes) &&+ Result.isSuccess(rightBytes) &&+ Mac.timingSafeEqual(leftBytes.success, rightBytes.success)+ );}function normalizeNonEmptyString(value: string | null | undefined): string | undefined {diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.tsindex 7092292666e..1dd2f23bdbd 100644--- a/apps/server/src/cloud/CloudLink.ts+++ b/apps/server/src/cloud/CloudLink.ts@@ -1,5 +1,3 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createPublicKey.-import * as NodeCrypto from "node:crypto";import {AuthStandardClientScopes,EnvironmentAuthenticatedPrincipal,@@ -45,6 +43,7 @@ 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 Jwk from "effect/jose/Jwk";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -339,14 +338,9 @@ export function consumeCloudReplayGuards(input: {function validateCloudMintPublicKey(publicKey: string,): Effect.Effect<void, CloudLinkRelayConfigInvalidError> {- const invalid = new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" });- return Effect.try({- try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),- catch: () => invalid,- }).pipe(- Effect.flatMap((key) =>- key.asymmetricKeyType === "ed25519" ? Effect.void : Effect.fail(invalid),- ),+ return Jwk.importSpki(publicKey.replace(/\\n/g, "\n"), "EdDSA").pipe(+ Effect.asVoid,+ Effect.mapError(() => new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" })),);}@@ -587,7 +581,9 @@ const make = Effect.gen(function* () {requestUrl: string,allowNonLoopbackRequestHost = false,) {- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(+ Effect.provideService(Signature.Signature, signature),+ );if (!isSupportedLinkProviderKind(request) ||!isAllowedEndpointOrigin({@@ -929,7 +925,9 @@ const make = Effect.gen(function* () {const makeManagedTunnelRecoveryProof = Effect.fn("environment.cloud.makeManagedTunnelRecoveryProof",)(function* (input: ManagedTunnelRecoveryProofInput) {- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(+ Effect.provideService(Signature.Signature, signature),+ );const configuredIssuer = yield* secrets.get(RELAY_ISSUER_SECRET);const now = yield* DateTime.now;const issuedAt = Math.floor(now.epochMilliseconds / 1_000);@@ -1483,7 +1481,9 @@ const make = Effect.gen(function* () {return yield* new CloudLinkProofReplayedError({ request: "health" });}- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(+ Effect.provideService(Signature.Signature, signature),+ );const descriptor = yield* environment.getDescriptor;const responseExpiresAt = DateTime.add(now, { minutes: 5 });const responsePayload = {@@ -1587,7 +1587,9 @@ const make = Effect.gen(function* () {return yield* new CloudLinkProofReplayedError({ request: "mint" });}- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(+ Effect.provideService(Signature.Signature, signature),+ );const issued = yield* environmentAuth.createPairingLink({scopes: AuthStandardClientScopes,subject: "cloud-connect",diff --git a/apps/server/src/cloud/environmentKeys.ts b/apps/server/src/cloud/environmentKeys.tsindex f829f93e802..79715885956 100644--- a/apps/server/src/cloud/environmentKeys.ts+++ b/apps/server/src/cloud/environmentKeys.ts@@ -1,7 +1,7 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.-import * as NodeCrypto from "node:crypto";import * as Effect from "effect/Effect";+import * as Jwk from "effect/jose/Jwk";import * as Option from "effect/Option";+import * as Redacted from "effect/Redacted";import * as Schema from "effect/Schema";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";@@ -93,12 +93,19 @@ export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function*});}- const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- return yield* persistEnvironmentKeyPair(secrets, {- privateKey: keyPair.privateKey,- publicKey: keyPair.publicKey,- });+ const keyPair = yield* Jwk.generateKeyPair({ algorithm: "EdDSA" }).pipe(+ Effect.flatMap((pair) =>+ Effect.all({+ privateKey: Jwk.importPrivate(pair.privateKey, "EdDSA").pipe(+ Effect.flatMap((key) => Jwk.exportPkcs8(key, { format: "pem" })),+ Effect.map(Redacted.value),+ ),+ publicKey: Jwk.importPublic(pair.publicKey, "EdDSA").pipe(+ Effect.flatMap((key) => Jwk.exportSpki(key, { format: "pem" })),+ ),+ }),+ ),+ Effect.orDie,+ );+ return yield* persistEnvironmentKeyPair(secrets, keyPair);});diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.tsindex fd9a0efc3b6..637b19a9ac9 100644--- a/apps/server/src/guest/GuestShareService.ts+++ b/apps/server/src/guest/GuestShareService.ts@@ -26,6 +26,7 @@ import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";@@ -39,6 +40,7 @@ import {base64UrlEncode,signPayload,timingSafeEqualBase64Url,+ verifyPayloadSignature,} from "../auth/utils.ts";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import {@@ -143,10 +145,9 @@ const decodeSessionClaims = Schema.decodeUnknownOption(Schema.fromJsonString(Ses/** A truncated HMAC keeps invite links short. 128 bits is still far beyond guessing range. */const inviteSignature = (shareId: string, key: Uint8Array) =>- base64UrlEncode(- Buffer.from(signPayload(`guest-invite:${shareId}`, key), "base64url").subarray(- 0,- INVITE_SIGNATURE_BYTES,+ signPayload(`guest-invite:${shareId}`, key).pipe(+ Effect.map((signature) =>+ base64UrlEncode(Buffer.from(signature, "base64url").subarray(0, INVITE_SIGNATURE_BYTES)),),);@@ -242,6 +243,7 @@ const make = Effect.gen(function* () {const random = yield* SecureRandom.SecureRandom;const secretStore = yield* ServerSecretStore.ServerSecretStore;const analytics = yield* AnalyticsService.AnalyticsService;+ const mac = yield* Mac.Mac;const signingKey = yield* Effect.cached(secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),);@@ -251,12 +253,19 @@ const make = Effect.gen(function* () {// `<shareId>.<signature>` and the thread is looked up by share id; a session token carries// signed claims.const signInvite = (shareId: GuestShareId) =>- Effect.map(signingKey, (key) => `${shareId}.${inviteSignature(shareId, key)}`);- const signSession = (claims: SessionClaims) =>- Effect.map(signingKey, (key) => {- const payload = base64UrlEncode(JSON.stringify(claims));- return `${payload}.${signPayload(payload, key)}`;- });+ signingKey.pipe(+ Effect.flatMap((key) => inviteSignature(shareId, key)),+ Effect.map((signature) => `${shareId}.${signature}`),+ Effect.provideService(Mac.Mac, mac),+ );+ const signSession = (claims: SessionClaims) => {+ const payload = base64UrlEncode(JSON.stringify(claims));+ return signingKey.pipe(+ Effect.flatMap((key) => signPayload(payload, key)),+ Effect.map((signature) => `${payload}.${signature}`),+ Effect.provideService(Mac.Mac, mac),+ );+ };const splitToken = (token: string) => {const [payload, signature, extra] = token.split(".");return payload && signature && extra === undefined ? { payload, signature } : null;@@ -265,7 +274,10 @@ const make = Effect.gen(function* () {const parts = splitToken(token);if (parts === null) return Option.none<SessionClaims>();const key = yield* signingKey;- if (!timingSafeEqualBase64Url(parts.signature, inviteSignature(parts.payload, key))) {+ const expected = yield* inviteSignature(parts.payload, key).pipe(+ Effect.provideService(Mac.Mac, mac),+ );+ if (!timingSafeEqualBase64Url(parts.signature, expected)) {return Option.none<SessionClaims>();}const shareId = GuestShareId.make(parts.payload);@@ -276,15 +288,20 @@ const make = Effect.gen(function* () {? Option.none<SessionClaims>(): Option.some<SessionClaims>({ kind: "session", threadId, shareId });});- const verifySession = (token: string) =>- Effect.map(signingKey, (key) => {- const parts = splitToken(token);- if (parts === null) return Option.none<SessionClaims>();- if (!timingSafeEqualBase64Url(parts.signature, signPayload(parts.payload, key))) {- return Option.none<SessionClaims>();- }- return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));- });+ // Untraced: runs on every guest request, like the Effect.map it replaced.+ const verifySession = Effect.fnUntraced(function* (token: string) {+ const key = yield* signingKey;+ const parts = splitToken(token);+ if (parts === null) return Option.none<SessionClaims>();+ if (+ !(yield* verifyPayloadSignature(parts.payload, parts.signature, key).pipe(+ Effect.provideService(Mac.Mac, mac),+ ))+ ) {+ return Option.none<SessionClaims>();+ }+ return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));+ });const connectHostname = managedEndpoint.inspectConnector.pipe(Effect.map((facts) => facts?.hostname ?? null),diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.tsindex b2248976235..df451763a8e 100644--- a/apps/server/src/mcp/toolkits/attachment/handlers.ts+++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts@@ -5,6 +5,7 @@ import {OrchestratorMcpFailure,} from "@t3tools/contracts";import * as Clock from "effect/Clock";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as McpInvocationContext from "../../McpInvocationContext.ts";import * as Upload from "../../../assets/AttachmentUpload.ts";@@ -43,7 +44,8 @@ const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(export const layer = McpToolAccess.toLayer(AttachmentToolkit,- Effect.sync(() => {+ Effect.gen(function* () {+ const mac = yield* Mac.Mac;const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();return {// A pending upload belongs to its caller until a send claims it, so@@ -52,6 +54,7 @@ export const layer = McpToolAccess.toLayer((input) =>Effect.gen(function* () {const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(+ Effect.provideService(Mac.Mac, mac),Effect.mapError(unavailable),);const now = yield* Clock.currentTimeMillis;diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.tsindex 0758593488f..470c845d9c9 100644--- a/apps/server/src/provider/CodexChatGptAuth.ts+++ b/apps/server/src/provider/CodexChatGptAuth.ts@@ -1,5 +1,4 @@-// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener and PKCE use Node APIs.-import * as NodeCrypto from "node:crypto";+// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener uses Node APIs.import * as NodeHttp from "node:http";import {ProviderSetupError,@@ -19,6 +18,7 @@ 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 Base64Url from "effect/encoding/Base64Url";import * as Hex from "effect/encoding/Hex";import * as Exit from "effect/Exit";import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";@@ -527,12 +527,14 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*const selectedTokens = (yield* readSessions).sessions.find((session) => session.clientId === selectedClientId,);- const state = NodeCrypto.randomBytes(32).toString("base64url");- const nonce = NodeCrypto.randomBytes(32).toString("base64url");- const verifier = NodeCrypto.randomBytes(64).toString("base64url");+ const randomToken = (size: number) =>+ random.randomBytes(size).pipe(Effect.map(Base64Url.encode));+ const state = yield* randomToken(32);+ const nonce = yield* randomToken(32);+ const verifier = yield* randomToken(64);const returnUrl =codexAuthReturnUrl(context.returnUrl) ?? codexAuthReturnUrl(options.defaultReturnUrl);- const pageNonce = NodeCrypto.randomBytes(24).toString("base64url");+ const pageNonce = yield* randomToken(24);const callback = Promise.withResolvers<{ url: URL; response?: NodeHttp.ServerResponse }>();const clientCallback = context.callbackMode === "client";let used = false;@@ -575,9 +577,14 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*return yield* failure("callback", "Could not start the local sign-in callback.");// Only the port may vary between attempts; token exchange uses this exact URI.const port =- address && typeof address !== "string" ? address.port : NodeCrypto.randomInt(49_152, 65_536);+ address && typeof address !== "string"+ ? address.port+ : yield* random.intBetween(49_152, 65_536, { halfOpen: true });const redirectUri = `http://127.0.0.1:${port}/auth/callback`;const idTokenHint = selectedTokens?.idToken ?? options.reconnectProfile?.idTokenHint;+ const codeChallenge = Base64Url.encode(+ yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)),+ );const url = new URL(endpoints.authorization_endpoint);url.search = new URLSearchParams({client_id: registeredClientId ?? "dynamic_agent_client",@@ -599,7 +606,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*state,nonce,code_challenge_method: "S256",- code_challenge: NodeCrypto.createHash("sha256").update(verifier).digest("base64url"),+ code_challenge: codeChallenge,}).toString();yield* context.setInteraction({diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.tsindex 6f220fc58c5..6d5e4484860 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts@@ -28,6 +28,8 @@ import {} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Context from "effect/Context";+import * as Digest from "effect/crypto/Digest";+import * as Mac from "effect/crypto/Mac";import * as SecureRandom from "effect/crypto/SecureRandom";import * as Data from "effect/Data";import * as DateTime from "effect/DateTime";@@ -436,6 +438,8 @@ export const layer = Layer.effect(Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;const random = yield* SecureRandom.SecureRandom;+ const digest = yield* Digest.Digest;+ const mac = yield* Mac.Mac;const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;const threadManagement = yield* ThreadManagementService.ThreadManagementService;const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;@@ -1927,7 +1931,9 @@ export const layer = Layer.effect(if (row === undefined ||row.webhook_token === null ||- !constantTimeEquals(request.token, row.webhook_token)+ !(yield* constantTimeEquals(request.token, row.webhook_token).pipe(+ Effect.provideService(Digest.Digest, digest),+ ))) {return yield* notFound;}@@ -2042,12 +2048,12 @@ export const layer = Layer.effect(if (signature !== null) {const verified =row.webhook_secret !== null &&- verifyWebhookSignature({+ (yield* verifyWebhookSignature({signature,secret: row.webhook_secret,headers: request.headers,body: request.body,- });+ }).pipe(Effect.provideService(Mac.Mac, mac)));if (!verified) {yield* log("rejected_signature");yield* observe("rejected_signature");diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.tsindex 90d2ccc329c..e06ed817ac4 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts@@ -182,6 +182,8 @@ const withService = <A, E>(const launches = yield* Queue.unbounded<LaunchInput>();const secretsByRef = new Map<string, string>();const layerDependencies = Layer.mergeAll(+ NodePlatformCrypto.layerDigest,+ NodePlatformCrypto.layerMac,options.frameGate === undefined && options.onFrame === undefined? NodePlatformCrypto.layer: Layer.effect(diff --git a/apps/server/src/scheduledTasks/webhookVerification.test.ts b/apps/server/src/scheduledTasks/webhookVerification.test.tsindex 330128bfb1a..05b7bf3510b 100644--- a/apps/server/src/scheduledTasks/webhookVerification.test.ts+++ b/apps/server/src/scheduledTasks/webhookVerification.test.ts@@ -1,7 +1,9 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Node's HMAC is an independent oracle for the Effect implementation.import * as NodeCrypto from "node:crypto";+import * as PlatformNodeCrypto from "@effect/platform-node/NodeCrypto";import { assert, describe, it } from "@effect/vitest";+import * as Effect from "effect/Effect";import { verifyWebhookSignature } from "./webhookVerification.ts";@@ -12,44 +14,58 @@ const hmac = () => NodeCrypto.createHmac("sha256", secret).update(body);describe("verifyWebhookSignature", () => {const github = { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=" } as const;- it("rejects a tampered body, a wrong secret, a missing header and a missing prefix", () => {- const valid = `sha256=${hmac().digest("hex")}`;- const tampered = new TextEncoder().encode('{"action":"closed"}');- assert.isFalse(- verifyWebhookSignature({- signature: github,- secret,- headers: { "x-hub-signature-256": valid },- body: tampered,- }),- );- assert.isFalse(- verifyWebhookSignature({- signature: github,- secret: "other",- headers: { "x-hub-signature-256": valid },- body,- }),- );- assert.isFalse(verifyWebhookSignature({ signature: github, secret, headers: {}, body }));- assert.isFalse(- verifyWebhookSignature({- signature: github,- secret,- headers: { "x-hub-signature-256": hmac().digest("hex") },- body,- }),- );- });+ it.effect("rejects a tampered body, a wrong secret, a missing header and a missing prefix", () =>+ Effect.gen(function* () {+ const valid = `sha256=${hmac().digest("hex")}`;+ const tampered = new TextEncoder().encode('{"action":"closed"}');+ assert.isFalse(+ yield* verifyWebhookSignature({+ signature: github,+ secret,+ headers: { "x-hub-signature-256": valid },+ body: tampered,+ }),+ );+ assert.isFalse(+ yield* verifyWebhookSignature({+ signature: github,+ secret: "other",+ headers: { "x-hub-signature-256": valid },+ body,+ }),+ );+ assert.isFalse(+ yield* verifyWebhookSignature({ signature: github, secret, headers: {}, body }),+ );+ assert.isFalse(+ yield* verifyWebhookSignature({+ signature: github,+ secret,+ headers: { "x-hub-signature-256": hmac().digest("hex") },+ body,+ }),+ );+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),+ );- it("accepts a base64 signature without prefix", () => {- assert.isTrue(- verifyWebhookSignature({- signature: { header: "X-Signature", encoding: "base64", prefix: "" },- secret,- headers: { "x-signature": hmac().digest("base64") },- body,- }),- );- });+ it.effect("accepts a hex signature with its prefix and a base64 signature without one", () =>+ Effect.gen(function* () {+ assert.isTrue(+ yield* verifyWebhookSignature({+ signature: github,+ secret,+ headers: { "x-hub-signature-256": `sha256=${hmac().digest("hex").toUpperCase()}` },+ body,+ }),+ );+ assert.isTrue(+ yield* verifyWebhookSignature({+ signature: { header: "X-Signature", encoding: "base64", prefix: "" },+ secret,+ headers: { "x-signature": hmac().digest("base64") },+ body,+ }),+ );+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),+ );});diff --git a/apps/server/src/scheduledTasks/webhookVerification.ts b/apps/server/src/scheduledTasks/webhookVerification.tsindex 292c8e97a2e..d0c75ed9e43 100644--- a/apps/server/src/scheduledTasks/webhookVerification.ts+++ b/apps/server/src/scheduledTasks/webhookVerification.ts@@ -1,32 +1,48 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.-import * as NodeCrypto from "node:crypto";-import type { ScheduledTaskWebhookSignature } from "@t3tools/contracts";+import * as Digest from "effect/crypto/Digest";+import * as Mac from "effect/crypto/Mac";+import * as Effect from "effect/Effect";+import * as Base64 from "effect/encoding/Base64";+import * as Hex from "effect/encoding/Hex";+import * as Result from "effect/Result";++const utf8 = (value: string) => new TextEncoder().encode(value);-/** Constant-time string comparison that does not leak length through timing. */-export function constantTimeEquals(a: string, b: string): boolean {- const digestA = NodeCrypto.createHash("sha256").update(a).digest();- const digestB = NodeCrypto.createHash("sha256").update(b).digest();- return NodeCrypto.timingSafeEqual(digestA, digestB);-}+/** Compares hashes so the comparison does not leak either string's length. */+export const constantTimeEquals = Effect.fn("webhookVerification.constantTimeEquals")(function* (+ a: string,+ b: string,+) {+ const digest = yield* Digest.Digest;+ const [left, right] = yield* Effect.all([+ digest.digest(Digest.sha256, utf8(a)),+ digest.digest(Digest.sha256, utf8(b)),+ ]);+ return Mac.timingSafeEqual(left, right);+});-export function verifyWebhookSignature(input: {- readonly signature: ScheduledTaskWebhookSignature;- readonly secret: string;- readonly headers: Readonly<Record<string, string>>;- readonly body: Uint8Array;-}): boolean {- const received = input.headers[input.signature.header.toLowerCase()];- if (received === undefined) return false;- const value = received.trim();- const prefix = input.signature.prefix;- if (prefix !== "" && !value.toLowerCase().startsWith(prefix.toLowerCase())) return false;- const digest = NodeCrypto.createHmac("sha256", input.secret).update(input.body).digest();- const expected =- input.signature.encoding === "hex" ? digest.toString("hex") : digest.toString("base64");- const candidate = value.slice(prefix.length);- return constantTimeEquals(- input.signature.encoding === "hex" ? candidate.toLowerCase() : candidate,- expected,- );-}+export const verifyWebhookSignature = Effect.fn("webhookVerification.verifyWebhookSignature")(+ function* (input: {+ readonly signature: ScheduledTaskWebhookSignature;+ readonly secret: string;+ readonly headers: Readonly<Record<string, string>>;+ readonly body: Uint8Array;+ }) {+ const received = input.headers[input.signature.header.toLowerCase()];+ if (received === undefined) return false;+ const value = received.trim();+ const prefix = input.signature.prefix;+ if (prefix !== "" && !value.toLowerCase().startsWith(prefix.toLowerCase())) return false;+ const candidate = value.slice(prefix.length);+ const tag =+ input.signature.encoding === "hex"+ ? Hex.decode(candidate.toLowerCase())+ : Base64.decode(candidate);+ if (Result.isFailure(tag)) return false;+ const mac = yield* Mac.Mac;+ return yield* Mac.key(Mac.hmacSha256, utf8(input.secret)).pipe(+ Effect.flatMap((key) => mac.verify(key, tag.success, input.body)),+ Effect.orElseSucceed(() => false),+ );+ },+);diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.tsindex 4d713f9bf7e..af216a746c0 100644--- a/apps/server/src/secrets/SecretRequests.ts+++ b/apps/server/src/secrets/SecretRequests.ts@@ -2,7 +2,6 @@// Consuming tools keep values out of transcripts, projections, clients and model context.// A `file` request instead moves its value to an owner-only file for the agent's own shell.// A secret the user pasted in chat goes straight to such a file, with no card.-import { pipe } from "effect/Function";import {CommandId,SecretRef,@@ -11,12 +10,12 @@ import {type SecretRequestAnswerInput,type ThreadId,} from "@t3tools/contracts";-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.-import * as NodeCrypto from "node:crypto";import * as Clock from "effect/Clock";import * as Context from "effect/Context";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";+import * as Hex from "effect/encoding/Hex";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -36,14 +35,6 @@ const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;const FILE_NAME_PATTERN = /^[0-9a-f]{32}(\.partial)?$/;-const refFor = (salt: string, threadId: ThreadId, turnItemId: string) =>- SecretRef.make(- `${SECRET_REF_PREFIX}${NodeCrypto.createHmac("sha256", salt)- .update(`${threadId}\u0000${turnItemId}`)- .digest("hex")- .slice(0, 32)}`,- );-const StoredSecret = Schema.fromJsonString(Schema.Struct({ projectId: Schema.String, value: Schema.String, savedAt: Schema.Number }),);@@ -86,9 +77,19 @@ const make = Effect.gen(function* () {// Beside the store's own files so the same owner-only directory and cleanup rules apply.const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files");- const salt = Buffer.from(- yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),- ).toString("hex");+ const mac = yield* Mac.Mac;+ // Keyed by the salt's hex text, as refs saved by earlier versions were.+ const refKey = yield* Mac.key(+ Mac.hmacSha256,+ new TextEncoder().encode(+ Hex.encode(yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie)),+ ),+ ).pipe(Effect.orDie);+ const refFor = (threadId: ThreadId, turnItemId: string) =>+ mac.sign(refKey, new TextEncoder().encode(`${threadId}\u0000${turnItemId}`)).pipe(+ Effect.orDie,+ Effect.map((tag) => SecretRef.make(`${SECRET_REF_PREFIX}${Hex.encode(tag).slice(0, 32)}`)),+ );const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(function* (input) {@@ -123,7 +124,7 @@ const make = Effect.gen(function* () {}).pipe(Effect.orDie);yield* store.create(- storeName(refFor(salt, input.threadId, item.id)),+ storeName(yield* refFor(input.threadId, item.id)),new TextEncoder().encode(encoded),).pipe(@@ -153,7 +154,9 @@ const make = Effect.gen(function* () {// Clear failed saves so the pending card can be answered again.Effect.tapError(() =>input.answer.type === "save"- ? pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged)+ ? refFor(input.threadId, item.id).pipe(+ Effect.flatMap((ref) => removeLogged(storeName(ref))),+ ): Effect.void,),);@@ -169,7 +172,7 @@ const make = Effect.gen(function* () {);const card = recorded.turnItems.find((candidate) => candidate.id === item.id);if (card?.type === "secret_request" && card.secretStatus !== "saved") {- yield* pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged);+ yield* removeLogged(storeName(yield* refFor(input.threadId, item.id)));return yield* new SecretRequestError({ reason: "agent_stopped" });}},@@ -177,7 +180,7 @@ const make = Effect.gen(function* () {const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")(function* (input) {- const ref = refFor(salt, input.threadId, input.turnItemId);+ const ref = yield* refFor(input.threadId, input.turnItemId);const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));return Option.map(stored, () => ref);},@@ -277,7 +280,7 @@ const make = Effect.gen(function* () {return yield* new SecretRequestError({ reason: "not_a_file_request" });}if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });- const ref = refFor(salt, input.threadId, item.id);+ const ref = yield* refFor(input.threadId, item.id);const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));return yield* Effect.gen(function* () {// One use: the file counts as delivered only once the stored copy is gone. A retry with the@@ -301,8 +304,7 @@ const make = Effect.gen(function* () {"SecretRequests.savePasted",)(function* (input) {if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });- const ref = refFor(- salt,+ const ref = yield* refFor(input.threadId,`pasted\u0000${input.requestNamespace}\u0000${input.requestKey}`,);diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.tsindex b2445b0ab4c..64823f49735 100644--- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts+++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts@@ -157,6 +157,7 @@ function layerFor(input: {) => Effect.Effect<HttpClientResponse.HttpClientResponse>;}) {return ApnsDeliveries.layer.pipe(+ Layer.provideMerge(NodeCryptoLayer.layerMac),Layer.provide(ApnsClient.layer),Layer.provide(ApnsProviderTokens.layer),Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),@@ -571,7 +572,7 @@ describe("ApnsDeliveries", () => {});return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signedEnd);+ const result = yield* deliveries.processSignedJob(yield* signedEnd);expect(result.ok).toBe(true);expect(requests).toHaveLength(sends ? 1 : 0);if (sends) {@@ -633,7 +634,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result.kind).toBe("push_notification");expect(result.ok).toBe(true);@@ -698,7 +699,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result).toMatchObject({kind: "push_notification",@@ -745,7 +746,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result).toMatchObject({kind: "live_activity_update",@@ -813,7 +814,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result).toMatchObject({kind: "live_activity_update",@@ -879,7 +880,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* Effect.exit(deliveries.processSignedJob(signed));+ const result = yield* Effect.exit(deliveries.processSignedJob(yield* signed));expect(result._tag).toBe("Failure");if (result._tag === "Failure") {@@ -935,7 +936,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result.kind).toBe("push_notification");expect(result.ok).toBe(false);@@ -995,7 +996,7 @@ describe("ApnsDeliveries", () => {return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result.kind).toBe("live_activity_update");expect(result.ok).toBe(false);@@ -1204,7 +1205,7 @@ describe("signed APNs registration metadata", () => {});return Effect.gen(function* () {const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);+ const result = yield* deliveries.processSignedJob(yield* signed);expect(result.ok).toBe(true);expect(requests).toHaveLength(1);expect(requests[0]?.url).toBe(diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.ts b/infra/relay/src/agentActivity/ApnsDeliveries.tsindex 6e0e4bdc6e2..8913bdd1f8c 100644--- a/infra/relay/src/agentActivity/ApnsDeliveries.ts+++ b/infra/relay/src/agentActivity/ApnsDeliveries.ts@@ -11,6 +11,7 @@ import {} from "@t3tools/contracts/relay";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -31,7 +32,6 @@ import {type ApnsLiveActivityAlert,type ApnsNotificationPayload,SignedApnsDeliveryJob,- isApnsDeliveryJobVerificationError,verifySignedApnsDeliveryJob,type ApnsDeliveryJobVerificationError,} from "./apnsDeliveryJobs.ts";@@ -511,6 +511,7 @@ const make = Effect.gen(function* () {const liveActivities = yield* LiveActivities.LiveActivities;const deliveryQueue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;const config = yield* RelayConfiguration.RelayConfiguration;+ const mac = yield* Mac.Mac;const apns = yield* Apns.ApnsClient;const activityRows = yield* AgentActivityRows.AgentActivityRows;@@ -934,14 +935,11 @@ const make = Effect.gen(function* () {),);const now = yield* DateTime.now;- const payload = verifySignedApnsDeliveryJob({+ const payload = yield* verifySignedApnsDeliveryJob({secret: config.apnsDeliveryJobSigningSecret,job: signedJob,nowMs: now.epochMilliseconds,- });- if (isApnsDeliveryJobVerificationError(payload)) {- return yield* payload;- }+ }).pipe(Effect.provideService(Mac.Mac, mac));yield* Effect.annotateCurrentSpan({"relay.mobile.device_id": payload.target.deviceId,"relay.delivery.kind": payload.kind,diff --git a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts b/infra/relay/src/agentActivity/ApnsDeliveryQueue.tsindex 5b633b0c4e6..09cff5184b0 100644--- a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts+++ b/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts@@ -3,6 +3,7 @@ import * as Cloudflare from "@alchemy.run/cloudflare";import * as SecureRandom from "effect/crypto/SecureRandom";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";+import * as Mac from "effect/crypto/Mac";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";@@ -80,6 +81,7 @@ const make = Effect.gen(function* () {const sender = yield* ApnsDeliveryQueueSender;const random = yield* SecureRandom.SecureRandom;const config = yield* RelayConfiguration.RelayConfiguration;+ const mac = yield* Mac.Mac;return ApnsDeliveryQueue.of({enqueueLiveActivity: Effect.fn("relay.apns_delivery_queue.enqueue_live_activity")(@@ -111,10 +113,10 @@ const make = Effect.gen(function* () {createdAt: DateTime.formatIso(now),expiresAt: expiresAtForJob(now.epochMilliseconds),});- const signed = signApnsDeliveryJob({+ const signed = yield* signApnsDeliveryJob({secret: config.apnsDeliveryJobSigningSecret,payload,- });+ }).pipe(Effect.provideService(Mac.Mac, mac));yield* sender.send(signed).pipe(Effect.mapError((cause) =>@@ -175,10 +177,10 @@ const make = Effect.gen(function* () {createdAt: DateTime.formatIso(now),expiresAt: expiresAtForJob(now.epochMilliseconds),});- const signed = signApnsDeliveryJob({+ const signed = yield* signApnsDeliveryJob({secret: config.apnsDeliveryJobSigningSecret,payload,- });+ }).pipe(Effect.provideService(Mac.Mac, mac));yield* sender.send(signed).pipe(Effect.mapError((cause) =>diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.tsindex 6f5997c931b..1865a633d57 100644--- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts+++ b/infra/relay/src/agentActivity/MobileRegistrations.test.ts@@ -166,6 +166,7 @@ function layerRegistrationReplay(input: {),),Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),+ Layer.provide(NodeCryptoLayer.layerMac),Layer.provide(Layer.mergeAll(Layer.succeed(Devices.Devices, input.devices),diff --git a/infra/relay/src/agentActivity/apnsDeliveryJobs.test.ts b/infra/relay/src/agentActivity/apnsDeliveryJobs.test.tsindex 291722338b8..a9b7fa61129 100644--- a/infra/relay/src/agentActivity/apnsDeliveryJobs.test.ts+++ b/infra/relay/src/agentActivity/apnsDeliveryJobs.test.ts@@ -1,4 +1,6 @@+import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";import { describe, expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";import * as Redacted from "effect/Redacted";import {@@ -10,42 +12,49 @@ import {const secret = Redacted.make("queue-signing-secret");describe("apnsDeliveryJobs", () => {- it("rejects tampered signed queue jobs", () => {- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate: null,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:05:00.000Z",- jobId: "job-1",- });- const signed = signApnsDeliveryJob({ secret, payload });- const tampered = {- ...signed,- payload: {- ...signed.payload,- target: {- ...signed.payload.target,- token: "attacker-token",+ it.effect("rejects tampered signed queue jobs", () =>+ Effect.gen(function* () {+ const payload = makeApnsDeliveryJobPayload({+ kind: "live_activity_end",+ userId: "user-1",+ deviceId: "device-1",+ token: "token-1",+ aggregate: null,+ createdAt: "2026-05-25T00:00:00.000Z",+ expiresAt: "2026-05-25T00:05:00.000Z",+ jobId: "job-1",+ });+ const signed = yield* signApnsDeliveryJob({ secret, payload });+ expect(yield* verifySignedApnsDeliveryJob({ secret, job: signed, nowMs: 0 })).toEqual(+ payload,+ );+ const tampered = {+ ...signed,+ payload: {+ ...signed.payload,+ target: {+ ...signed.payload.target,+ token: "attacker-token",+ },},- },- };+ };- const result = verifySignedApnsDeliveryJob({- secret,- job: tampered,- nowMs: 0,- });+ const result = yield* Effect.flip(+ verifySignedApnsDeliveryJob({+ secret,+ job: tampered,+ nowMs: 0,+ }),+ );- expect(result).toMatchObject({- _tag: "ApnsDeliveryJobSignatureInvalid",- jobId: "job-1",- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- message: "Invalid signature for APNs delivery job job-1.",- });- });+ expect(result).toMatchObject({+ _tag: "ApnsDeliveryJobSignatureInvalid",+ jobId: "job-1",+ kind: "live_activity_end",+ userId: "user-1",+ deviceId: "device-1",+ message: "Invalid signature for APNs delivery job job-1.",+ });+ }).pipe(Effect.provide(NodeCryptoLayer.layerMac)),+ );});diff --git a/infra/relay/src/agentActivity/apnsDeliveryJobs.ts b/infra/relay/src/agentActivity/apnsDeliveryJobs.tsindex a1fe2aa0bce..b732507a731 100644--- a/infra/relay/src/agentActivity/apnsDeliveryJobs.ts+++ b/infra/relay/src/agentActivity/apnsDeliveryJobs.ts@@ -1,14 +1,15 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.-import * as NodeCrypto from "node:crypto";-import {RelayAgentActivityAggregateState,RelayAgentAwarenessPhase,} from "@t3tools/contracts/relay";import { stableStringify } from "@t3tools/shared/relaySigning";+import * as Mac from "effect/crypto/Mac";import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Base64Url from "effect/encoding/Base64Url";import * as Option from "effect/Option";import * as Redacted from "effect/Redacted";+import * as Result from "effect/Result";import * as Schema from "effect/Schema";const MAX_JOB_AGE_MS = 10 * 60 * 1_000;@@ -224,8 +225,6 @@ export const ApnsDeliveryJobVerificationError = Schema.Union([]);export type ApnsDeliveryJobVerificationError = typeof ApnsDeliveryJobVerificationError.Type;-export const isApnsDeliveryJobVerificationError = Schema.is(ApnsDeliveryJobVerificationError);-export function makeApnsDeliveryJobPayload(input: {readonly kind: ApnsDeliveryJobPayload["kind"];readonly userId: string;@@ -313,41 +312,63 @@ function validatePayloadShape(payload: ApnsDeliveryJobPayload): ApnsDeliveryJobI}}-function signatureForPayload(input: {- readonly secret: Redacted.Redacted<string>;- readonly payload: ApnsDeliveryJobPayload;-}): string {- return NodeCrypto.createHmac("sha256", Redacted.value(input.secret))- .update(stableStringify(input.payload))- .digest("base64url");-}+const signingKey = (secret: Redacted.Redacted<string>) =>+ Mac.key(Mac.hmacSha256, new TextEncoder().encode(Redacted.value(secret)));-function timingSafeEqualBase64Url(left: string, right: string): boolean {- const leftBuffer = Buffer.from(left, "base64url");- const rightBuffer = Buffer.from(right, "base64url");- if (leftBuffer.length !== rightBuffer.length) {- return false;- }- return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);-}+const payloadBytes = (payload: ApnsDeliveryJobPayload) =>+ new TextEncoder().encode(stableStringify(payload));-export function signApnsDeliveryJob(input: {+export const signApnsDeliveryJob = Effect.fn("relay.apns_delivery_jobs.sign")(function* (input: {readonly secret: Redacted.Redacted<string>;readonly payload: ApnsDeliveryJobPayload;-}): SignedApnsDeliveryJob {+}) {+ const mac = yield* Mac.Mac;+ const signature = yield* signingKey(input.secret).pipe(+ Effect.flatMap((key) => mac.sign(key, payloadBytes(input.payload))),+ Effect.orDie,+ );return {algorithm: APNS_DELIVERY_JOB_SIGNING_ALGORITHM,payload: input.payload,- signature: signatureForPayload(input),- };-}+ signature: Base64Url.encode(signature),+ } satisfies SignedApnsDeliveryJob;+});-export function verifySignedApnsDeliveryJob(input: {- readonly secret: Redacted.Redacted<string>;- readonly job: SignedApnsDeliveryJob;- readonly nowMs: number;-}): ApnsDeliveryJobPayload | ApnsDeliveryJobVerificationError {- const payload = input.job.payload;+export const verifySignedApnsDeliveryJob = Effect.fn("relay.apns_delivery_jobs.verify")(+ function* (input: {+ readonly secret: Redacted.Redacted<string>;+ readonly job: SignedApnsDeliveryJob;+ readonly nowMs: number;+ }) {+ const payload = input.job.payload;+ const invalid = validateSignedJobWindow(payload, input.nowMs);+ if (invalid !== null) {+ return yield* invalid;+ }+ const tag = Base64Url.decode(input.job.signature);+ const mac = yield* Mac.Mac;+ const verified =+ Result.isSuccess(tag) &&+ (yield* signingKey(input.secret).pipe(+ Effect.flatMap((key) => mac.verify(key, tag.success, payloadBytes(payload))),+ Effect.orDie,+ ));+ if (!verified) {+ return yield* new ApnsDeliveryJobSignatureInvalid({+ jobId: payload.jobId,+ kind: payload.kind,+ userId: payload.target.userId,+ deviceId: payload.target.deviceId,+ });+ }+ return payload;+ },+);++function validateSignedJobWindow(+ payload: ApnsDeliveryJobPayload,+ nowMs: number,+): ApnsDeliveryJobVerificationError | null {const invalidPayload = validatePayloadShape(payload);if (invalidPayload !== null) {return invalidPayload;@@ -394,7 +415,7 @@ export function verifySignedApnsDeliveryJob(input: {expiresAt: payload.expiresAt,});}- if (expiresAtMs <= input.nowMs) {+ if (expiresAtMs <= nowMs) {return new ApnsDeliveryJobExpired({jobId: payload.jobId,kind: payload.kind,@@ -403,17 +424,5 @@ export function verifySignedApnsDeliveryJob(input: {expiresAt: payload.expiresAt,});}- const expected = signatureForPayload({- secret: input.secret,- payload,- });- if (!timingSafeEqualBase64Url(input.job.signature, expected)) {- return new ApnsDeliveryJobSignatureInvalid({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- return payload;+ return null;}diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.tsindex fb6b926bd74..dbece02354c 100644--- a/infra/relay/src/worker.ts+++ b/infra/relay/src/worker.ts@@ -6,6 +6,7 @@ import * as Config from "effect/Config";import * as Cause from "effect/Cause";import * as DateTime from "effect/DateTime";import * as Digest from "effect/crypto/Digest";+import * as Mac from "effect/crypto/Mac";import * as SecureRandom from "effect/crypto/SecureRandom";import * as Signature from "effect/crypto/Signature";import * as Effect from "effect/Effect";@@ -74,9 +75,11 @@ 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(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(- Layer.provideMerge(SecureRandom.layerWebCrypto),-);+const layerWebcrypto = Layer.mergeAll(+ Digest.layerWebCrypto,+ Mac.layerWebCrypto,+ Signature.layerWebCrypto,+).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto));const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, {platform: "web",diff --git a/packages/shared/src/desktopBootstrapToken.test.ts b/packages/shared/src/desktopBootstrapToken.test.tsindex c097e43ed52..5150dada63c 100644--- a/packages/shared/src/desktopBootstrapToken.test.ts+++ b/packages/shared/src/desktopBootstrapToken.test.ts@@ -1,4 +1,9 @@-import { describe, expect, it } from "vite-plus/test";+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Older desktops derive the token with Node's HMAC.+import * as NodeCrypto from "node:crypto";++import * as PlatformNodeCrypto from "@effect/platform-node/NodeCrypto";+import { describe, expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";import {DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,@@ -10,40 +15,39 @@ const SECRET = "desktop-secret";const WINDOW = DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS;describe("desktop bootstrap token", () => {- it("rotates every window and stays accepted for one more", () => {- const issuedAt = 10 * WINDOW + 1;- const token = currentDesktopBootstrapToken(SECRET, issuedAt);-- expect(currentDesktopBootstrapToken(SECRET, issuedAt + WINDOW)).not.toBe(token);- expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt)).toBe(true);- expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt + WINDOW)).toBe(true);- expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt + 2 * WINDOW)).toBe(false);- });-- it("accepts a token from a desktop clock slightly ahead of the backend", () => {- const desktopNow = 10 * WINDOW + 500;- const backendNow = 10 * WINDOW - 500;-- expect(- isValidDesktopBootstrapToken(- SECRET,- currentDesktopBootstrapToken(SECRET, desktopNow),- backendNow,- ),- ).toBe(true);- expect(- isValidDesktopBootstrapToken(- SECRET,- currentDesktopBootstrapToken(SECRET, desktopNow + WINDOW),- backendNow,- ),- ).toBe(false);- });-- it("rejects tokens derived from another secret", () => {- const token = currentDesktopBootstrapToken("other-secret", WINDOW);-- expect(isValidDesktopBootstrapToken(SECRET, token, WINDOW)).toBe(false);- expect(isValidDesktopBootstrapToken(SECRET, "short", WINDOW)).toBe(false);- });+ it.effect("rotates every window and stays accepted for one more", () =>+ Effect.gen(function* () {+ const issuedAt = 10 * WINDOW + 1;+ const token = yield* currentDesktopBootstrapToken(SECRET, issuedAt);++ expect(token).toBe(+ NodeCrypto.createHmac("sha256", SECRET).update("t3-desktop-bootstrap:10").digest("hex"),+ );+ expect(yield* currentDesktopBootstrapToken(SECRET, issuedAt + WINDOW)).not.toBe(token);+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, issuedAt)).toBe(true);+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, issuedAt + WINDOW)).toBe(true);+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, issuedAt + 2 * WINDOW)).toBe(false);+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),+ );++ it.effect("accepts a token from a desktop clock slightly ahead of the backend", () =>+ Effect.gen(function* () {+ const desktopNow = 10 * WINDOW + 500;+ const backendNow = 10 * WINDOW - 500;+ const ahead = yield* currentDesktopBootstrapToken(SECRET, desktopNow);+ const tooFarAhead = yield* currentDesktopBootstrapToken(SECRET, desktopNow + WINDOW);++ expect(yield* isValidDesktopBootstrapToken(SECRET, ahead, backendNow)).toBe(true);+ expect(yield* isValidDesktopBootstrapToken(SECRET, tooFarAhead, backendNow)).toBe(false);+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),+ );++ it.effect("rejects tokens derived from another secret", () =>+ Effect.gen(function* () {+ const token = yield* currentDesktopBootstrapToken("other-secret", WINDOW);++ expect(yield* isValidDesktopBootstrapToken(SECRET, token, WINDOW)).toBe(false);+ expect(yield* isValidDesktopBootstrapToken(SECRET, "short", WINDOW)).toBe(false);+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),+ );});diff --git a/packages/shared/src/desktopBootstrapToken.ts b/packages/shared/src/desktopBootstrapToken.tsindex 5f1082634ab..76e9d0b86de 100644--- a/packages/shared/src/desktopBootstrapToken.ts+++ b/packages/shared/src/desktopBootstrapToken.ts@@ -1,32 +1,36 @@-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.-import * as NodeCrypto from "node:crypto";+import * as Mac from "effect/crypto/Mac";+import * as Effect from "effect/Effect";+import * as Hex from "effect/encoding/Hex";/** Accept previous/current windows for token lifetime and the next window for WSL clock lag. */export const DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS = 12 * 60 * 60 * 1000;+const utf8 = (value: string) => new TextEncoder().encode(value);+function windowIndex(nowMs: number): number {return Math.floor(nowMs / DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS);}-function deriveToken(secret: string, window: number): string {- return NodeCrypto.createHmac("sha256", secret)- .update(`t3-desktop-bootstrap:${window}`)- .digest("hex");-}+// Untraced: an inner step of the named callers below, run up to three times per check.+const deriveToken = Effect.fnUntraced(function* (secret: string, window: number) {+ const mac = yield* Mac.Mac;+ const key = yield* Mac.key(Mac.hmacSha256, utf8(secret));+ return Hex.encode(yield* mac.sign(key, utf8(`t3-desktop-bootstrap:${window}`)));+}, Effect.orDie);-export function currentDesktopBootstrapToken(secret: string, nowMs: number): string {- return deriveToken(secret, windowIndex(nowMs));-}+export const currentDesktopBootstrapToken = Effect.fn("desktopBootstrapToken.current")(+ (secret: string, nowMs: number) => deriveToken(secret, windowIndex(nowMs)),+);-export function isValidDesktopBootstrapToken(+export const isValidDesktopBootstrapToken = Effect.fn("desktopBootstrapToken.isValid")(function* (secret: string,token: string,nowMs: number,-): boolean {- const presented = Buffer.from(token);+) {+ const presented = utf8(token);const current = windowIndex(nowMs);- return [current - 1, current, current + 1].some((window) => {- const expected = Buffer.from(deriveToken(secret, window));- return expected.length === presented.length && NodeCrypto.timingSafeEqual(expected, presented);- });-}+ for (const window of [current - 1, current, current + 1]) {+ if (Mac.timingSafeEqual(utf8(yield* deriveToken(secret, window)), presented)) return true;+ }+ return false;+});