Skip to content

Commit 18207c4

Browse files
refactor: move HMAC, key, and random work to effect/crypto
Effect 4.1's crypto modules cover what these node:crypto call sites need: Mac for HMAC signing and constant-time verification, Jwk for Ed25519 key generation and SPKI checks, SecureRandom and Digest for Codex PKCE. The stale "Effect's Crypto has no X" suppressions go with them. Derivations stay byte-compatible with existing tokens, secret refs, and older desktops. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 135173e commit 18207c4

33 files changed

Lines changed: 538 additions & 368 deletions

‎apps/desktop/src/backend/DesktopBackendConfiguration.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,10 @@ describe("DesktopBackendConfiguration", () => {
262262
);
263263
assert.equal(
264264
first.bootstrap.desktopBootstrapToken,
265-
currentDesktopBootstrapToken(
265+
yield* currentDesktopBootstrapToken(
266266
first.bootstrap.desktopBootstrapSecret ?? "",
267267
yield* Clock.currentTimeMillis,
268-
),
268+
).pipe(Effect.provide(NodeCrypto.layerMac)),
269269
);
270270
assert.equal(
271271
yield* configuration.currentBootstrapToken,

‎apps/desktop/src/backend/DesktopBackendConfiguration.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapTo
55
import * as Clock from "effect/Clock";
66
import * as Context from "effect/Context";
77
import * as SecureRandom from "effect/crypto/SecureRandom";
8+
import * as Mac from "effect/crypto/Mac";
89
import * as Effect from "effect/Effect";
910
import * as Hex from "effect/encoding/Hex";
1011
import * as FileSystem from "effect/FileSystem";
@@ -723,6 +724,7 @@ export const make = Effect.gen(function* () {
723724
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
724725
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
725726
const settings = yield* DesktopAppSettings.DesktopAppSettings;
727+
const mac = yield* Mac.Mac;
726728
const random = yield* SecureRandom.SecureRandom;
727729
// Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets.
728730
const secretRef = yield* SynchronizedRef.make(Option.none<string>());
@@ -741,10 +743,10 @@ export const make = Effect.gen(function* () {
741743

742744
const sharedInputs = Effect.gen(function* () {
743745
const bootstrapSecret = yield* getOrCreateBootstrapSecret;
744-
const bootstrapToken = currentDesktopBootstrapToken(
746+
const bootstrapToken = yield* currentDesktopBootstrapToken(
745747
bootstrapSecret,
746748
yield* Clock.currentTimeMillis,
747-
);
749+
).pipe(Effect.provideService(Mac.Mac, mac));
748750
const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
749751
Effect.provideService(FileSystem.FileSystem, fileSystem),
750752
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
@@ -806,7 +808,9 @@ export const make = Effect.gen(function* () {
806808

807809
const currentBootstrapToken = Effect.gen(function* () {
808810
const secret = yield* getOrCreateBootstrapSecret;
809-
return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
811+
return yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(
812+
Effect.provideService(Mac.Mac, mac),
813+
);
810814
});
811815

812816
return DesktopBackendConfiguration.of({

‎apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
12
import { assert, describe, it } from "@effect/vitest";
23
import * as Deferred from "effect/Deferred";
34
import * as Duration from "effect/Duration";
@@ -80,7 +81,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
8081
]),
8182
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
8283
const layerTest = DesktopLocalEnvironmentAuth.layer.pipe(
83-
Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),
84+
Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
8485
);
8586

8687
const [first, second] = yield* Effect.gen(function* () {
@@ -151,14 +152,17 @@ describe("DesktopLocalEnvironmentAuth", () => {
151152
}).pipe(
152153
Effect.provide(
153154
DesktopLocalEnvironmentAuth.layer.pipe(
154-
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
155+
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer, NodeCrypto.layerMac)),
155156
),
156157
),
157158
);
158159

159160
assert.strictEqual(
160161
yield* Ref.get(presented),
161-
currentDesktopBootstrapToken("desktop-secret", DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS * 2 + 1),
162+
yield* currentDesktopBootstrapToken(
163+
"desktop-secret",
164+
DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS * 2 + 1,
165+
).pipe(Effect.provide(NodeCrypto.layerMac)),
162166
);
163167
}).pipe(Effect.provide(TestClock.layer())),
164168
);
@@ -205,7 +209,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
205209
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
206210
Effect.provide(
207211
DesktopLocalEnvironmentAuth.layer.pipe(
208-
Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),
212+
Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
209213
),
210214
),
211215
);

‎apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapTo
55
import * as Clock from "effect/Clock";
66
import * as Context from "effect/Context";
77
import * as Duration from "effect/Duration";
8+
import * as Mac from "effect/crypto/Mac";
89
import * as Effect from "effect/Effect";
910
import * as Layer from "effect/Layer";
1011
import * as Option from "effect/Option";
@@ -67,6 +68,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
6768
export const make = Effect.gen(function* () {
6869
const pool = yield* DesktopBackendPool.DesktopBackendPool;
6970
const httpClient = yield* HttpClient.HttpClient;
71+
const mac = yield* Mac.Mac;
7072
const tokenRef = yield* Ref.make(Option.none<string>());
7173
const mutex = yield* Semaphore.make(1);
7274

@@ -93,7 +95,9 @@ export const make = Effect.gen(function* () {
9395
const credential =
9496
secret === undefined
9597
? config.bootstrap.desktopBootstrapToken
96-
: currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
98+
: yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(
99+
Effect.provideService(Mac.Mac, mac),
100+
);
97101
if (!credential) {
98102
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
99103
}

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ import {
5151
base64UrlDecodeUtf8,
5252
base64UrlEncode,
5353
signPayload,
54-
timingSafeEqualBase64Url,
54+
verifyPayloadSignature,
5555
} from "../auth/utils.ts";
5656
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
5757
import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
@@ -872,7 +872,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
872872
claims = { ...claims, expiresAt };
873873
}
874874
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
875-
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
875+
const token = `${encodedPayload}.${yield* signPayload(encodedPayload, signingSecret)}`;
876876
return {
877877
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
878878
expiresAt,
@@ -895,7 +895,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
895895
Effect.orElseSucceed(() => null),
896896
);
897897
if (!signingSecret) return null;
898-
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
898+
if (!(yield* verifyPayloadSignature(encodedPayload, signature, signingSecret))) return null;
899899

900900
const claims = decodeClaims(encodedPayload);
901901
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;

‎apps/server/src/assets/AttachmentUpload.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ describe("AttachmentUpload", () => {
165165
expiresAt: issued.expiresAt,
166166
}),
167167
);
168-
const legacyToken = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
168+
const legacyToken = `${encodedPayload}.${yield* signPayload(encodedPayload, secret)}`;
169169

170170
expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({
171171
type: "image",

‎apps/server/src/assets/AttachmentUpload.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import {
3131
base64UrlDecodeUtf8,
3232
base64UrlEncode,
3333
signPayload,
34-
timingSafeEqualBase64Url,
34+
verifyPayloadSignature,
3535
} from "../auth/utils.ts";
3636
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
3737
import * as ServerConfig from "../config.ts";
@@ -120,9 +120,10 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
120120
}),
121121
);
122122

123+
const signature = yield* signPayload(encodedPayload, secret);
123124
return {
124125
attachmentId,
125-
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`,
126+
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signature}`,
126127
expiresAt,
127128
};
128129
});
@@ -141,7 +142,7 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat
141142
),
142143
Effect.orElseSucceed(() => null),
143144
);
144-
if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) {
145+
if (!secret || !(yield* verifyPayloadSignature(encodedPayload, signature, secret))) {
145146
return null;
146147
}
147148

‎apps/server/src/auth/McpOAuth.ts‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import * as Clock from "effect/Clock";
2323
import * as Context from "effect/Context";
2424
import * as Digest from "effect/crypto/Digest";
2525
import * as SecureRandom from "effect/crypto/SecureRandom";
26+
import * as Mac from "effect/crypto/Mac";
2627
import * as Effect from "effect/Effect";
2728
import * as Layer from "effect/Layer";
2829
import * as Option from "effect/Option";
@@ -44,6 +45,7 @@ import {
4445
deriveAuthClientMetadata,
4546
signPayload,
4647
timingSafeEqualBase64Url,
48+
verifyPayloadSignature,
4749
} from "./utils.ts";
4850
import { requestUrl } from "../requestUrl.ts";
4951

@@ -266,27 +268,33 @@ const make = Effect.gen(function* () {
266268
.pipe(Effect.orDie);
267269
const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
268270

269-
const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
271+
const mac = yield* Mac.Mac;
272+
const sign = (domain: string, payload: string) =>
273+
signPayload(`${domain}.${payload}`, signingKey).pipe(Effect.provideService(Mac.Mac, mac));
270274

271275
const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
272276
const body = base64UrlEncode(
273277
JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),
274278
);
275-
return `${body}.${sign("mcp-client-id", body)}`;
279+
return sign("mcp-client-id", body).pipe(Effect.map((signature) => `${body}.${signature}`));
276280
};
277281

278-
const parseClientId = (clientId: string): McpOAuthClient | undefined => {
282+
// Untraced: only called inside the traced McpOAuth methods below.
283+
const parseClientId = Effect.fnUntraced(function* (
284+
clientId: string,
285+
): Effect.fn.Return<McpOAuthClient | undefined> {
279286
const [body, signature, extra] = clientId.split(".");
280287
if (!body || !signature || extra !== undefined) return undefined;
281-
if (!timingSafeEqualBase64Url(signature, sign("mcp-client-id", body))) return undefined;
282-
let json: string;
283-
try {
284-
json = base64UrlDecodeUtf8(body);
285-
} catch {
286-
return undefined;
287-
}
288+
const verified = yield* verifyPayloadSignature(
289+
`mcp-client-id.${body}`,
290+
signature,
291+
signingKey,
292+
).pipe(Effect.provideService(Mac.Mac, mac));
293+
if (!verified) return undefined;
294+
const json = yield* Effect.try(() => base64UrlDecodeUtf8(body)).pipe(Effect.option);
295+
if (Option.isNone(json)) return undefined;
288296
return Option.getOrUndefined(
289-
decodeClientIdPayload(json).pipe(
297+
decodeClientIdPayload(json.value).pipe(
290298
Option.map((payload) => ({
291299
clientId,
292300
name: payload.n,
@@ -295,7 +303,7 @@ const make = Effect.gen(function* () {
295303
})),
296304
),
297305
);
298-
};
306+
});
299307

300308
const pkceVerifies = (verifier: string, challenge: string) =>
301309
CODE_VERIFIER_PATTERN.test(verifier)
@@ -347,7 +355,7 @@ const make = Effect.gen(function* () {
347355
});
348356
}
349357
return {
350-
clientId: signClientId(name, redirectUris, peerLink),
358+
clientId: yield* signClientId(name, redirectUris, peerLink),
351359
name,
352360
redirectUris,
353361
peerLink,
@@ -358,7 +366,7 @@ const make = Effect.gen(function* () {
358366
const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn(
359367
"McpOAuth.validateAuthorization",
360368
)(function* ({ urls, request }) {
361-
const client = parseClientId(request.client_id ?? "");
369+
const client = yield* parseClientId(request.client_id ?? "");
362370
if (client === undefined) {
363371
return yield* new McpOAuthPageError({
364372
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* () {
410418
authorization,
411419
) =>
412420
environmentAuth.authenticateBrowserSession(request).pipe(
413-
Effect.map((session) =>
421+
Effect.flatMap((session) =>
414422
// Approving manages access, and a session may only hand out scopes it holds.
415423
session.scopes.includes(AuthAccessWriteScope) &&
416424
session.scopes.includes(AuthOrchestrationReadScope)
417-
? { csrfToken: csrfToken(session.sessionId, authorization), scopes: session.scopes }
418-
: undefined,
425+
? csrfToken(session.sessionId, authorization).pipe(
426+
Effect.map((token) => ({ csrfToken: token, scopes: session.scopes })),
427+
)
428+
: Effect.undefined,
419429
),
420430
Effect.orElseSucceed(() => undefined),
421431
);
@@ -507,7 +517,7 @@ const make = Effect.gen(function* () {
507517
"code, redirect_uri, client_id and code_verifier are required.",
508518
);
509519
}
510-
if (parseClientId(clientId) === undefined) {
520+
if ((yield* parseClientId(clientId)) === undefined) {
511521
return yield* fail("invalid_client", "The client is unknown.");
512522
}
513523
// A presented code is spent even when a later check fails (RFC 6749 §4.1.2).

‎apps/server/src/auth/PairingGrantStore.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -182,15 +182,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
182182
yield* TestClock.adjust(Duration.days(5));
183183
const now = 5 * 24 * 60 * 60 * 1000;
184184
const current = yield* bootstrapCredentials.consume(
185-
currentDesktopBootstrapToken("desktop-secret", now),
185+
yield* currentDesktopBootstrapToken("desktop-secret", now).pipe(
186+
Effect.provide(NodeCrypto.layerMac),
187+
),
186188
);
187189
expect(current.method).toBe("desktop-bootstrap");
188190

189-
const stale = yield* Effect.flip(
190-
bootstrapCredentials.consume(
191-
currentDesktopBootstrapToken("desktop-secret", now - 2 * window),
192-
),
193-
);
191+
const staleToken = yield* currentDesktopBootstrapToken(
192+
"desktop-secret",
193+
now - 2 * window,
194+
).pipe(Effect.provide(NodeCrypto.layerMac));
195+
const stale = yield* Effect.flip(bootstrapCredentials.consume(staleToken));
194196
expect(stale._tag).toBe("UnknownBootstrapCredentialError");
195197

196198
const launch = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));

‎apps/server/src/auth/PairingGrantStore.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as Context from "effect/Context";
1212
import * as SecureRandom from "effect/crypto/SecureRandom";
1313
import * as DateTime from "effect/DateTime";
1414
import * as Duration from "effect/Duration";
15+
import * as Mac from "effect/crypto/Mac";
1516
import * as Effect from "effect/Effect";
1617
import * as Layer from "effect/Layer";
1718
import * as Option from "effect/Option";
@@ -312,9 +313,13 @@ const make = Effect.gen(function* () {
312313

313314
// Accept tokens derived from the rotating desktop secret; older desktops send only a token.
314315
const desktopBootstrapSecret = config.desktopBootstrapSecret;
316+
const mac = yield* Mac.Mac;
315317
const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
316-
desktopBootstrapSecret !== undefined &&
317-
isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs);
318+
desktopBootstrapSecret === undefined
319+
? Effect.succeed(false)
320+
: isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs).pipe(
321+
Effect.provideService(Mac.Mac, mac),
322+
);
318323

319324
if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
320325
const now = yield* DateTime.now;
@@ -438,7 +443,7 @@ const make = Effect.gen(function* () {
438443
const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
439444
function* (credential, input) {
440445
const now = yield* DateTime.now;
441-
if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
446+
if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
442447
return {
443448
method: "desktop-bootstrap",
444449
scopes: AuthStandardClientScopes,

0 commit comments

Comments
 (0)