The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 04:30 UTC
refactor: move HMAC, key, and random work to effect/crypto (#30501)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 4, 2026 at 10:35 UTC
fb99a5e4b026162812bf078ea37f161f6ae007c8
33 files changed
+541
-370
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+2
-2
@@ -262,10 +262,10 @@ describe("DesktopBackendConfiguration", () => {
262
);
263
assert.equal(
264
first.bootstrap.desktopBootstrapToken,
265
- currentDesktopBootstrapToken(
265
+ yield* currentDesktopBootstrapToken(
266
first.bootstrap.desktopBootstrapSecret ?? "",
267
yield* Clock.currentTimeMillis,
268
- ),
268
+ ).pipe(Effect.provide(NodeCrypto.layerMac)),
269
);
270
assert.equal(
271
yield* configuration.currentBootstrapToken,
apps/desktop/src/backend/DesktopBackendConfiguration.ts
+7
-3
@@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapTo
5
import * as Clock from "effect/Clock";
6
import * as Context from "effect/Context";
7
import * as SecureRandom from "effect/crypto/SecureRandom";
8
+import * as Mac from "effect/crypto/Mac";
9
import * as Effect from "effect/Effect";
10
import * as Hex from "effect/encoding/Hex";
11
import * as FileSystem from "effect/FileSystem";
@@ -723,6 +724,7 @@ export const make = Effect.gen(function* () {
724
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
725
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
726
const settings = yield* DesktopAppSettings.DesktopAppSettings;
727
+ const mac = yield* Mac.Mac;
728
const random = yield* SecureRandom.SecureRandom;
729
// Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets.
730
const secretRef = yield* SynchronizedRef.make(Option.none<string>());
@@ -741,10 +743,10 @@ export const make = Effect.gen(function* () {
743
744
const sharedInputs = Effect.gen(function* () {
745
const bootstrapSecret = yield* getOrCreateBootstrapSecret;
744
- const bootstrapToken = currentDesktopBootstrapToken(
746
+ const bootstrapToken = yield* currentDesktopBootstrapToken(
747
bootstrapSecret,
748
yield* Clock.currentTimeMillis,
747
- );
749
+ ).pipe(Effect.provideService(Mac.Mac, mac));
750
const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
751
Effect.provideService(FileSystem.FileSystem, fileSystem),
752
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
@@ -806,7 +808,9 @@ export const make = Effect.gen(function* () {
808
809
const currentBootstrapToken = Effect.gen(function* () {
810
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
+ );
814
});
815
816
return DesktopBackendConfiguration.of({
apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
+8
-4
@@ -1,3 +1,4 @@
1
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
import { assert, describe, it } from "@effect/vitest";
3
import * as Deferred from "effect/Deferred";
4
import * as Duration from "effect/Duration";
@@ -80,7 +81,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
81
]),
82
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
83
const layerTest = DesktopLocalEnvironmentAuth.layer.pipe(
83
- Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),
84
+ Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
85
);
86
87
const [first, second] = yield* Effect.gen(function* () {
@@ -151,14 +152,17 @@ describe("DesktopLocalEnvironmentAuth", () => {
152
}).pipe(
153
Effect.provide(
154
DesktopLocalEnvironmentAuth.layer.pipe(
154
- Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
155
+ Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer, NodeCrypto.layerMac)),
156
),
157
),
158
);
159
160
assert.strictEqual(
161
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)),
166
);
167
}).pipe(Effect.provide(TestClock.layer())),
168
);
@@ -205,7 +209,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
209
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
210
Effect.provide(
211
DesktopLocalEnvironmentAuth.layer.pipe(
208
- Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),
212
+ Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
213
),
214
),
215
);
apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
+5
-1
@@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapTo
5
import * as Clock from "effect/Clock";
6
import * as Context from "effect/Context";
7
import * as Duration from "effect/Duration";
8
+import * as Mac from "effect/crypto/Mac";
9
import * as Effect from "effect/Effect";
10
import * as Layer from "effect/Layer";
11
import * as Option from "effect/Option";
@@ -67,6 +68,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
68
export const make = Effect.gen(function* () {
69
const pool = yield* DesktopBackendPool.DesktopBackendPool;
70
const httpClient = yield* HttpClient.HttpClient;
71
+ const mac = yield* Mac.Mac;
72
const tokenRef = yield* Ref.make(Option.none<string>());
73
const mutex = yield* Semaphore.make(1);
74
@@ -93,7 +95,9 @@ export const make = Effect.gen(function* () {
95
const credential =
96
secret === undefined
97
? config.bootstrap.desktopBootstrapToken
96
- : currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
98
+ : yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(
99
+ Effect.provideService(Mac.Mac, mac),
100
+ );
101
if (!credential) {
102
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
103
}
apps/server/src/assets/AssetAccess.ts
+3
-3
@@ -51,7 +51,7 @@ import {
51
base64UrlDecodeUtf8,
52
base64UrlEncode,
53
signPayload,
54
- timingSafeEqualBase64Url,
54
+ verifyPayloadSignature,
55
} from "../auth/utils.ts";
56
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
57
import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
@@ -872,7 +872,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
872
claims = { ...claims, expiresAt };
873
}
874
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
875
- const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
875
+ const token = `${encodedPayload}.${yield* signPayload(encodedPayload, signingSecret)}`;
876
return {
877
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
878
expiresAt,
@@ -895,7 +895,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
895
Effect.orElseSucceed(() => null),
896
);
897
if (!signingSecret) return null;
898
- if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
898
+ if (!(yield* verifyPayloadSignature(encodedPayload, signature, signingSecret))) return null;
899
900
const claims = decodeClaims(encodedPayload);
901
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
apps/server/src/assets/AttachmentUpload.test.ts
+1
-1
@@ -165,7 +165,7 @@ describe("AttachmentUpload", () => {
165
expiresAt: issued.expiresAt,
166
}),
167
);
168
- const legacyToken = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
168
+ const legacyToken = `${encodedPayload}.${yield* signPayload(encodedPayload, secret)}`;
169
170
expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({
171
type: "image",
apps/server/src/assets/AttachmentUpload.ts
+4
-3
@@ -31,7 +31,7 @@ import {
31
base64UrlDecodeUtf8,
32
base64UrlEncode,
33
signPayload,
34
- timingSafeEqualBase64Url,
34
+ verifyPayloadSignature,
35
} from "../auth/utils.ts";
36
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
37
import * as ServerConfig from "../config.ts";
@@ -120,9 +120,10 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
120
}),
121
);
122
123
+ const signature = yield* signPayload(encodedPayload, secret);
124
return {
125
attachmentId,
125
- relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`,
126
+ relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signature}`,
127
expiresAt,
128
};
129
});
@@ -141,7 +142,7 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat
142
),
143
Effect.orElseSucceed(() => null),
144
);
144
- if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) {
145
+ if (!secret || !(yield* verifyPayloadSignature(encodedPayload, signature, secret))) {
146
return null;
147
}
148
apps/server/src/auth/McpOAuth.ts
+28
-18
@@ -23,6 +23,7 @@ import * as Clock from "effect/Clock";
23
import * as Context from "effect/Context";
24
import * as Digest from "effect/crypto/Digest";
25
import * as SecureRandom from "effect/crypto/SecureRandom";
26
+import * as Mac from "effect/crypto/Mac";
27
import * as Effect from "effect/Effect";
28
import * as Layer from "effect/Layer";
29
import * as Option from "effect/Option";
@@ -44,6 +45,7 @@ import {
45
deriveAuthClientMetadata,
46
signPayload,
47
timingSafeEqualBase64Url,
48
+ verifyPayloadSignature,
49
} from "./utils.ts";
50
import { requestUrl } from "../requestUrl.ts";
51
@@ -266,27 +268,33 @@ const make = Effect.gen(function* () {
268
.pipe(Effect.orDie);
269
const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
270
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));
274
275
const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
276
const body = base64UrlEncode(
277
JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),
278
);
275
- return `${body}.${sign("mcp-client-id", body)}`;
279
+ return sign("mcp-client-id", body).pipe(Effect.map((signature) => `${body}.${signature}`));
280
};
281
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> {
286
const [body, signature, extra] = clientId.split(".");
287
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;
296
return Option.getOrUndefined(
289
- decodeClientIdPayload(json).pipe(
297
+ decodeClientIdPayload(json.value).pipe(
298
Option.map((payload) => ({
299
clientId,
300
name: payload.n,
@@ -295,7 +303,7 @@ const make = Effect.gen(function* () {
303
})),
304
),
305
);
298
- };
306
+ });
307
308
const pkceVerifies = (verifier: string, challenge: string) =>
309
CODE_VERIFIER_PATTERN.test(verifier)
@@ -347,7 +355,7 @@ const make = Effect.gen(function* () {
355
});
356
}
357
return {
350
- clientId: signClientId(name, redirectUris, peerLink),
358
+ clientId: yield* signClientId(name, redirectUris, peerLink),
359
name,
360
redirectUris,
361
peerLink,
@@ -358,7 +366,7 @@ const make = Effect.gen(function* () {
366
const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn(
367
"McpOAuth.validateAuthorization",
368
)(function* ({ urls, request }) {
361
- const client = parseClientId(request.client_id ?? "");
369
+ const client = yield* parseClientId(request.client_id ?? "");
370
if (client === undefined) {
371
return yield* new McpOAuthPageError({
372
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* () {
418
authorization,
419
) =>
420
environmentAuth.authenticateBrowserSession(request).pipe(
413
- Effect.map((session) =>
421
+ Effect.flatMap((session) =>
422
// Approving manages access, and a session may only hand out scopes it holds.
423
session.scopes.includes(AuthAccessWriteScope) &&
424
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,
429
),
430
Effect.orElseSucceed(() => undefined),
431
);
@@ -507,7 +517,7 @@ const make = Effect.gen(function* () {
517
"code, redirect_uri, client_id and code_verifier are required.",
518
);
519
}
510
- if (parseClientId(clientId) === undefined) {
520
+ if ((yield* parseClientId(clientId)) === undefined) {
521
return yield* fail("invalid_client", "The client is unknown.");
522
}
523
// A presented code is spent even when a later check fails (RFC 6749 §4.1.2).
apps/server/src/auth/PairingGrantStore.test.ts
+8
-6
@@ -182,15 +182,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
182
yield* TestClock.adjust(Duration.days(5));
183
const now = 5 * 24 * 60 * 60 * 1000;
184
const current = yield* bootstrapCredentials.consume(
185
- currentDesktopBootstrapToken("desktop-secret", now),
185
+ yield* currentDesktopBootstrapToken("desktop-secret", now).pipe(
186
+ Effect.provide(NodeCrypto.layerMac),
187
+ ),
188
);
189
expect(current.method).toBe("desktop-bootstrap");
190
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));
196
expect(stale._tag).toBe("UnknownBootstrapCredentialError");
197
198
const launch = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
apps/server/src/auth/PairingGrantStore.ts
+8
-3
@@ -12,6 +12,7 @@ import * as Context from "effect/Context";
12
import * as SecureRandom from "effect/crypto/SecureRandom";
13
import * as DateTime from "effect/DateTime";
14
import * as Duration from "effect/Duration";
15
+import * as Mac from "effect/crypto/Mac";
16
import * as Effect from "effect/Effect";
17
import * as Layer from "effect/Layer";
18
import * as Option from "effect/Option";
@@ -312,9 +313,13 @@ const make = Effect.gen(function* () {
313
314
// Accept tokens derived from the rotating desktop secret; older desktops send only a token.
315
const desktopBootstrapSecret = config.desktopBootstrapSecret;
316
+ const mac = yield* Mac.Mac;
317
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
+ );
323
324
if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
325
const now = yield* DateTime.now;
@@ -438,7 +443,7 @@ const make = Effect.gen(function* () {
443
const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
444
function* (credential, input) {
445
const now = yield* DateTime.now;
441
- if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
446
+ if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
447
return {
448
method: "desktop-bootstrap",
449
scopes: AuthStandardClientScopes,
apps/server/src/auth/ReusableDevAuth.ts
+3
-2
@@ -1,6 +1,7 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no timingSafeEqual.
1
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Digest is effectful; this resolves the dev token synchronously at startup.
2
import * as NodeCrypto from "node:crypto";
3
import { AuthSessionId } from "@t3tools/contracts";
4
+import * as Mac from "effect/crypto/Mac";
5
import * as DateTime from "effect/DateTime";
6
import * as Redacted from "effect/Redacted";
7
@@ -27,6 +28,6 @@ export function resolveReusableDevAuth(
28
sessionId: AuthSessionId.make(`${REUSABLE_DEV_SESSION_PREFIX}${tokenId}`),
29
cookieName: `t3_dev_session_${tokenId}`,
30
matches: (credential: string) =>
30
- NodeCrypto.timingSafeEqual(hash, NodeCrypto.createHash("sha256").update(credential).digest()),
31
+ Mac.timingSafeEqual(hash, NodeCrypto.createHash("sha256").update(credential).digest()),
32
};
33
}
apps/server/src/auth/SessionStore.test.ts
+5
-3
@@ -370,10 +370,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("SessionStore.lay
370
const secret = yield* secrets.getOrCreateRandom("server-signing-key", 32);
371
const resign = (claims: string) => {
372
const payload = base64UrlEncode(claims);
373
- return `${payload}.${signPayload(payload, secret)}`;
373
+ return signPayload(payload, secret).pipe(
374
+ Effect.map((signature) => `${payload}.${signature}`),
375
+ );
376
};
375
- const legacyToken = resign(currentClaims.replace('"v":1', '"v":2'));
376
- const editedToken = resign(
377
+ const legacyToken = yield* resign(currentClaims.replace('"v":1', '"v":2'));
378
+ const editedToken = yield* resign(
379
currentClaims.replace(/"scopes":\[[^\]]*\]/, '"scopes":["access:write"]'),
380
);
381
apps/server/src/auth/SessionStore.ts
+13
-7
@@ -13,6 +13,7 @@ import * as Context from "effect/Context";
13
import * as SecureRandom from "effect/crypto/SecureRandom";
14
import * as DateTime from "effect/DateTime";
15
import * as Duration from "effect/Duration";
16
+import * as Mac from "effect/crypto/Mac";
17
import * as Effect from "effect/Effect";
18
import * as Layer from "effect/Layer";
19
import * as PubSub from "effect/PubSub";
@@ -36,7 +37,7 @@ import {
37
resolveLegacySessionCookieName,
38
resolveSessionCookieName,
39
signPayload,
39
- timingSafeEqualBase64Url,
40
+ verifyPayloadSignature,
41
} from "./utils.ts";
42
43
export interface IssuedSession {
@@ -497,6 +498,13 @@ const make = Effect.gen(function* () {
498
const secretStore = yield* ServerSecretStore.ServerSecretStore;
499
const authSessions = yield* AuthSessions.AuthSessionRepository;
500
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
501
+ const mac = yield* Mac.Mac;
502
+ const sign = (payload: string) =>
503
+ signPayload(payload, signingSecret).pipe(Effect.provideService(Mac.Mac, mac));
504
+ const verifySignature = (payload: string, signature: string) =>
505
+ verifyPayloadSignature(payload, signature, signingSecret).pipe(
506
+ Effect.provideService(Mac.Mac, mac),
507
+ );
508
const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
509
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
510
// Newest session per DPoP key. A live socket moves to it at expiry, so a
@@ -679,7 +687,7 @@ const make = Effect.gen(function* () {
687
}),
688
),
689
);
682
- const signature = signPayload(encodedPayload, signingSecret);
690
+ const signature = yield* sign(encodedPayload);
691
const client = input?.client ?? createDefaultClientMetadata();
692
const sessionRecord = {
693
sessionId,
@@ -791,8 +799,7 @@ const make = Effect.gen(function* () {
799
return yield* new MalformedSessionTokenError({});
800
}
801
794
- const expectedSignature = signPayload(encodedPayload, signingSecret);
795
- if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
802
+ if (!(yield* verifySignature(encodedPayload, signature))) {
803
return yield* new InvalidSessionTokenSignatureError({});
804
}
805
@@ -879,7 +886,7 @@ const make = Effect.gen(function* () {
886
}),
887
),
888
);
882
- const signature = signPayload(encodedPayload, signingSecret);
889
+ const signature = yield* sign(encodedPayload);
890
return {
891
token: `${encodedPayload}.${signature}`,
892
expiresAt,
@@ -894,8 +901,7 @@ const make = Effect.gen(function* () {
901
return yield* new MalformedWebSocketTokenError({});
902
}
903
897
- const expectedSignature = signPayload(encodedPayload, signingSecret);
898
- if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
904
+ if (!(yield* verifySignature(encodedPayload, signature))) {
905
return yield* new InvalidWebSocketTokenSignatureError({});
906
}
907
apps/server/src/auth/utils.ts
+33
-10
@@ -4,10 +4,12 @@ import type {
4
AuthClientPresentationMetadata,
5
} from "@t3tools/contracts";
6
import type * as HttpServerRequest from "effect/http/HttpServerRequest";
7
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
7
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Digest is effectful; the cookie name stays a plain function.
8
import * as NodeCrypto from "node:crypto";
9
import * as NodeNet from "node:net";
10
import { normalizeHostname } from "@t3tools/shared/hostClassification";
11
+import * as Mac from "effect/crypto/Mac";
12
+import * as Effect from "effect/Effect";
13
import * as Base64Url from "effect/encoding/Base64Url";
14
import * as Result from "effect/Result";
15
@@ -79,17 +81,38 @@ export function base64UrlDecodeUtf8(input: string): string {
81
return Result.getOrThrow(Base64Url.decodeString(input));
82
}
83
82
-export function signPayload(payload: string, secret: Uint8Array): string {
83
- return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
84
-}
84
+const hmacKey = (secret: Uint8Array) => Mac.key(Mac.hmacSha256, secret).pipe(Effect.orDie);
85
+
86
+// Untraced: every authenticated request signs or verifies at least one token.
87
+export const signPayload = Effect.fnUntraced(function* (payload: string, secret: Uint8Array) {
88
+ const mac = yield* Mac.Mac;
89
+ const tag = yield* mac
90
+ .sign(yield* hmacKey(secret), new TextEncoder().encode(payload))
91
+ .pipe(Effect.orDie);
92
+ return Base64Url.encode(tag);
93
+});
94
+
95
+export const verifyPayloadSignature = Effect.fnUntraced(function* (
96
+ payload: string,
97
+ signature: string,
98
+ secret: Uint8Array,
99
+) {
100
+ const tag = Base64Url.decode(signature);
101
+ if (Result.isFailure(tag)) return false;
102
+ const mac = yield* Mac.Mac;
103
+ return yield* mac
104
+ .verify(yield* hmacKey(secret), tag.success, new TextEncoder().encode(payload))
105
+ .pipe(Effect.orDie);
106
+});
107
108
export function timingSafeEqualBase64Url(left: string, right: string): boolean {
87
- const leftBuffer = Buffer.from(left, "base64url");
88
- const rightBuffer = Buffer.from(right, "base64url");
89
- if (leftBuffer.length !== rightBuffer.length) {
90
- return false;
91
- }
92
- return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
109
+ const leftBytes = Base64Url.decode(left);
110
+ const rightBytes = Base64Url.decode(right);
111
+ return (
112
+ Result.isSuccess(leftBytes) &&
113
+ Result.isSuccess(rightBytes) &&
114
+ Mac.timingSafeEqual(leftBytes.success, rightBytes.success)
115
+ );
116
}
117
118
function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
apps/server/src/cloud/CloudLink.ts
+16
-14
@@ -1,5 +1,3 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createPublicKey.
2
-import * as NodeCrypto from "node:crypto";
1
import {
2
AuthStandardClientScopes,
3
EnvironmentAuthenticatedPrincipal,
@@ -45,6 +43,7 @@ import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
43
import * as Context from "effect/Context";
44
import * as SecureRandom from "effect/crypto/SecureRandom";
45
import * as Signature from "effect/crypto/Signature";
46
+import * as Jwk from "effect/jose/Jwk";
47
import * as DateTime from "effect/DateTime";
48
import * as Duration from "effect/Duration";
49
import * as Effect from "effect/Effect";
@@ -339,14 +338,9 @@ export function consumeCloudReplayGuards(input: {
338
function validateCloudMintPublicKey(
339
publicKey: string,
340
): Effect.Effect<void, CloudLinkRelayConfigInvalidError> {
342
- const invalid = new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" });
343
- return Effect.try({
344
- try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
345
- catch: () => invalid,
346
- }).pipe(
347
- Effect.flatMap((key) =>
348
- key.asymmetricKeyType === "ed25519" ? Effect.void : Effect.fail(invalid),
349
- ),
341
+ return Jwk.importSpki(publicKey.replace(/\\n/g, "\n"), "EdDSA").pipe(
342
+ Effect.asVoid,
343
+ Effect.mapError(() => new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" })),
344
);
345
}
346
@@ -587,7 +581,9 @@ const make = Effect.gen(function* () {
581
requestUrl: string,
582
allowNonLoopbackRequestHost = false,
583
) {
590
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
584
+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
585
+ Effect.provideService(Signature.Signature, signature),
586
+ );
587
if (
588
!isSupportedLinkProviderKind(request) ||
589
!isAllowedEndpointOrigin({
@@ -929,7 +925,9 @@ const make = Effect.gen(function* () {
925
const makeManagedTunnelRecoveryProof = Effect.fn(
926
"environment.cloud.makeManagedTunnelRecoveryProof",
927
)(function* (input: ManagedTunnelRecoveryProofInput) {
932
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
928
+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
929
+ Effect.provideService(Signature.Signature, signature),
930
+ );
931
const configuredIssuer = yield* secrets.get(RELAY_ISSUER_SECRET);
932
const now = yield* DateTime.now;
933
const issuedAt = Math.floor(now.epochMilliseconds / 1_000);
@@ -1483,7 +1481,9 @@ const make = Effect.gen(function* () {
1481
return yield* new CloudLinkProofReplayedError({ request: "health" });
1482
}
1483
1486
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
1484
+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
1485
+ Effect.provideService(Signature.Signature, signature),
1486
+ );
1487
const descriptor = yield* environment.getDescriptor;
1488
const responseExpiresAt = DateTime.add(now, { minutes: 5 });
1489
const responsePayload = {
@@ -1587,7 +1587,9 @@ const make = Effect.gen(function* () {
1587
return yield* new CloudLinkProofReplayedError({ request: "mint" });
1588
}
1589
1590
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
1590
+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
1591
+ Effect.provideService(Signature.Signature, signature),
1592
+ );
1593
const issued = yield* environmentAuth.createPairingLink({
1594
scopes: AuthStandardClientScopes,
1595
subject: "cloud-connect",
apps/server/src/cloud/environmentKeys.ts
+17
-10
@@ -1,7 +1,7 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
2
-import * as NodeCrypto from "node:crypto";
1
import * as Effect from "effect/Effect";
2
+import * as Jwk from "effect/jose/Jwk";
3
import * as Option from "effect/Option";
4
+import * as Redacted from "effect/Redacted";
5
import * as Schema from "effect/Schema";
6
7
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -93,12 +93,19 @@ export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function*
93
});
94
}
95
96
- const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
97
- privateKeyEncoding: { format: "pem", type: "pkcs8" },
98
- publicKeyEncoding: { format: "pem", type: "spki" },
99
- });
100
- return yield* persistEnvironmentKeyPair(secrets, {
101
- privateKey: keyPair.privateKey,
102
- publicKey: keyPair.publicKey,
103
- });
96
+ const keyPair = yield* Jwk.generateKeyPair({ algorithm: "EdDSA" }).pipe(
97
+ Effect.flatMap((pair) =>
98
+ Effect.all({
99
+ privateKey: Jwk.importPrivate(pair.privateKey, "EdDSA").pipe(
100
+ Effect.flatMap((key) => Jwk.exportPkcs8(key, { format: "pem" })),
101
+ Effect.map(Redacted.value),
102
+ ),
103
+ publicKey: Jwk.importPublic(pair.publicKey, "EdDSA").pipe(
104
+ Effect.flatMap((key) => Jwk.exportSpki(key, { format: "pem" })),
105
+ ),
106
+ }),
107
+ ),
108
+ Effect.orDie,
109
+ );
110
+ return yield* persistEnvironmentKeyPair(secrets, keyPair);
111
});
apps/server/src/guest/GuestShareService.ts
+37
-20
@@ -26,6 +26,7 @@ import * as Context from "effect/Context";
26
import * as SecureRandom from "effect/crypto/SecureRandom";
27
import * as DateTime from "effect/DateTime";
28
import * as Duration from "effect/Duration";
29
+import * as Mac from "effect/crypto/Mac";
30
import * as Effect from "effect/Effect";
31
import * as FileSystem from "effect/FileSystem";
32
import * as Layer from "effect/Layer";
@@ -39,6 +40,7 @@ import {
40
base64UrlEncode,
41
signPayload,
42
timingSafeEqualBase64Url,
43
+ verifyPayloadSignature,
44
} from "../auth/utils.ts";
45
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
46
import {
@@ -143,10 +145,9 @@ const decodeSessionClaims = Schema.decodeUnknownOption(Schema.fromJsonString(Ses
145
146
/** A truncated HMAC keeps invite links short. 128 bits is still far beyond guessing range. */
147
const inviteSignature = (shareId: string, key: Uint8Array) =>
146
- base64UrlEncode(
147
- Buffer.from(signPayload(`guest-invite:${shareId}`, key), "base64url").subarray(
148
- 0,
149
- INVITE_SIGNATURE_BYTES,
148
+ signPayload(`guest-invite:${shareId}`, key).pipe(
149
+ Effect.map((signature) =>
150
+ base64UrlEncode(Buffer.from(signature, "base64url").subarray(0, INVITE_SIGNATURE_BYTES)),
151
),
152
);
153
@@ -242,6 +243,7 @@ const make = Effect.gen(function* () {
243
const random = yield* SecureRandom.SecureRandom;
244
const secretStore = yield* ServerSecretStore.ServerSecretStore;
245
const analytics = yield* AnalyticsService.AnalyticsService;
246
+ const mac = yield* Mac.Mac;
247
const signingKey = yield* Effect.cached(
248
secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),
249
);
@@ -251,12 +253,19 @@ const make = Effect.gen(function* () {
253
// `<shareId>.<signature>` and the thread is looked up by share id; a session token carries
254
// signed claims.
255
const signInvite = (shareId: GuestShareId) =>
254
- Effect.map(signingKey, (key) => `${shareId}.${inviteSignature(shareId, key)}`);
255
- const signSession = (claims: SessionClaims) =>
256
- Effect.map(signingKey, (key) => {
257
- const payload = base64UrlEncode(JSON.stringify(claims));
258
- return `${payload}.${signPayload(payload, key)}`;
259
- });
256
+ signingKey.pipe(
257
+ Effect.flatMap((key) => inviteSignature(shareId, key)),
258
+ Effect.map((signature) => `${shareId}.${signature}`),
259
+ Effect.provideService(Mac.Mac, mac),
260
+ );
261
+ const signSession = (claims: SessionClaims) => {
262
+ const payload = base64UrlEncode(JSON.stringify(claims));
263
+ return signingKey.pipe(
264
+ Effect.flatMap((key) => signPayload(payload, key)),
265
+ Effect.map((signature) => `${payload}.${signature}`),
266
+ Effect.provideService(Mac.Mac, mac),
267
+ );
268
+ };
269
const splitToken = (token: string) => {
270
const [payload, signature, extra] = token.split(".");
271
return payload && signature && extra === undefined ? { payload, signature } : null;
@@ -265,7 +274,10 @@ const make = Effect.gen(function* () {
274
const parts = splitToken(token);
275
if (parts === null) return Option.none<SessionClaims>();
276
const key = yield* signingKey;
268
- if (!timingSafeEqualBase64Url(parts.signature, inviteSignature(parts.payload, key))) {
277
+ const expected = yield* inviteSignature(parts.payload, key).pipe(
278
+ Effect.provideService(Mac.Mac, mac),
279
+ );
280
+ if (!timingSafeEqualBase64Url(parts.signature, expected)) {
281
return Option.none<SessionClaims>();
282
}
283
const shareId = GuestShareId.make(parts.payload);
@@ -276,15 +288,20 @@ const make = Effect.gen(function* () {
288
? Option.none<SessionClaims>()
289
: Option.some<SessionClaims>({ kind: "session", threadId, shareId });
290
});
279
- const verifySession = (token: string) =>
280
- Effect.map(signingKey, (key) => {
281
- const parts = splitToken(token);
282
- if (parts === null) return Option.none<SessionClaims>();
283
- if (!timingSafeEqualBase64Url(parts.signature, signPayload(parts.payload, key))) {
284
- return Option.none<SessionClaims>();
285
- }
286
- return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));
287
- });
291
+ // Untraced: runs on every guest request, like the Effect.map it replaced.
292
+ const verifySession = Effect.fnUntraced(function* (token: string) {
293
+ const key = yield* signingKey;
294
+ const parts = splitToken(token);
295
+ if (parts === null) return Option.none<SessionClaims>();
296
+ if (
297
+ !(yield* verifyPayloadSignature(parts.payload, parts.signature, key).pipe(
298
+ Effect.provideService(Mac.Mac, mac),
299
+ ))
300
+ ) {
301
+ return Option.none<SessionClaims>();
302
+ }
303
+ return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));
304
+ });
305
306
const connectHostname = managedEndpoint.inspectConnector.pipe(
307
Effect.map((facts) => facts?.hostname ?? null),
apps/server/src/mcp/toolkits/attachment/handlers.ts
+4
-1
@@ -5,6 +5,7 @@ import {
5
OrchestratorMcpFailure,
6
} from "@t3tools/contracts";
7
import * as Clock from "effect/Clock";
8
+import * as Mac from "effect/crypto/Mac";
9
import * as Effect from "effect/Effect";
10
import * as McpInvocationContext from "../../McpInvocationContext.ts";
11
import * as Upload from "../../../assets/AttachmentUpload.ts";
@@ -43,7 +44,8 @@ const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(
44
45
export const layer = McpToolAccess.toLayer(
46
AttachmentToolkit,
46
- Effect.sync(() => {
47
+ Effect.gen(function* () {
48
+ const mac = yield* Mac.Mac;
49
const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();
50
return {
51
// A pending upload belongs to its caller until a send claims it, so
@@ -52,6 +54,7 @@ export const layer = McpToolAccess.toLayer(
54
(input) =>
55
Effect.gen(function* () {
56
const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
57
+ Effect.provideService(Mac.Mac, mac),
58
Effect.mapError(unavailable),
59
);
60
const now = yield* Clock.currentTimeMillis;
apps/server/src/provider/CodexChatGptAuth.ts
+15
-8
@@ -1,5 +1,4 @@
1
-// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener and PKCE use Node APIs.
2
-import * as NodeCrypto from "node:crypto";
1
+// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener uses Node APIs.
2
import * as NodeHttp from "node:http";
3
import {
4
ProviderSetupError,
@@ -19,6 +18,7 @@ import * as Signature from "effect/crypto/Signature";
18
import * as JoseError from "effect/jose/JoseError";
19
import * as Jwks from "effect/jose/Jwks";
20
import * as Jwt from "effect/jose/Jwt";
21
+import * as Base64Url from "effect/encoding/Base64Url";
22
import * as Hex from "effect/encoding/Hex";
23
import * as Exit from "effect/Exit";
24
import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
@@ -527,12 +527,14 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
527
const selectedTokens = (yield* readSessions).sessions.find(
528
(session) => session.clientId === selectedClientId,
529
);
530
- const state = NodeCrypto.randomBytes(32).toString("base64url");
531
- const nonce = NodeCrypto.randomBytes(32).toString("base64url");
532
- const verifier = NodeCrypto.randomBytes(64).toString("base64url");
530
+ const randomToken = (size: number) =>
531
+ random.randomBytes(size).pipe(Effect.map(Base64Url.encode));
532
+ const state = yield* randomToken(32);
533
+ const nonce = yield* randomToken(32);
534
+ const verifier = yield* randomToken(64);
535
const returnUrl =
536
codexAuthReturnUrl(context.returnUrl) ?? codexAuthReturnUrl(options.defaultReturnUrl);
535
- const pageNonce = NodeCrypto.randomBytes(24).toString("base64url");
537
+ const pageNonce = yield* randomToken(24);
538
const callback = Promise.withResolvers<{ url: URL; response?: NodeHttp.ServerResponse }>();
539
const clientCallback = context.callbackMode === "client";
540
let used = false;
@@ -575,9 +577,14 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
577
return yield* failure("callback", "Could not start the local sign-in callback.");
578
// Only the port may vary between attempts; token exchange uses this exact URI.
579
const port =
578
- address && typeof address !== "string" ? address.port : NodeCrypto.randomInt(49_152, 65_536);
580
+ address && typeof address !== "string"
581
+ ? address.port
582
+ : yield* random.intBetween(49_152, 65_536, { halfOpen: true });
583
const redirectUri = `http://127.0.0.1:${port}/auth/callback`;
584
const idTokenHint = selectedTokens?.idToken ?? options.reconnectProfile?.idTokenHint;
585
+ const codeChallenge = Base64Url.encode(
586
+ yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)),
587
+ );
588
const url = new URL(endpoints.authorization_endpoint);
589
url.search = new URLSearchParams({
590
client_id: registeredClientId ?? "dynamic_agent_client",
@@ -599,7 +606,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
606
state,
607
nonce,
608
code_challenge_method: "S256",
602
- code_challenge: NodeCrypto.createHash("sha256").update(verifier).digest("base64url"),
609
+ code_challenge: codeChallenge,
610
}).toString();
611
yield* context.setInteraction(
612
{
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+9
-3
@@ -28,6 +28,8 @@ import {
28
} from "@t3tools/contracts";
29
import * as Cause from "effect/Cause";
30
import * as Context from "effect/Context";
31
+import * as Digest from "effect/crypto/Digest";
32
+import * as Mac from "effect/crypto/Mac";
33
import * as SecureRandom from "effect/crypto/SecureRandom";
34
import * as Data from "effect/Data";
35
import * as DateTime from "effect/DateTime";
@@ -436,6 +438,8 @@ export const layer = Layer.effect(
438
Effect.gen(function* () {
439
const sql = yield* SqlClient.SqlClient;
440
const random = yield* SecureRandom.SecureRandom;
441
+ const digest = yield* Digest.Digest;
442
+ const mac = yield* Mac.Mac;
443
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
444
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
445
const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
@@ -1927,7 +1931,9 @@ export const layer = Layer.effect(
1931
if (
1932
row === undefined ||
1933
row.webhook_token === null ||
1930
- !constantTimeEquals(request.token, row.webhook_token)
1934
+ !(yield* constantTimeEquals(request.token, row.webhook_token).pipe(
1935
+ Effect.provideService(Digest.Digest, digest),
1936
+ ))
1937
) {
1938
return yield* notFound;
1939
}
@@ -2042,12 +2048,12 @@ export const layer = Layer.effect(
2048
if (signature !== null) {
2049
const verified =
2050
row.webhook_secret !== null &&
2045
- verifyWebhookSignature({
2051
+ (yield* verifyWebhookSignature({
2052
signature,
2053
secret: row.webhook_secret,
2054
headers: request.headers,
2055
body: request.body,
2050
- });
2056
+ }).pipe(Effect.provideService(Mac.Mac, mac)));
2057
if (!verified) {
2058
yield* log("rejected_signature");
2059
yield* observe("rejected_signature");
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+2
@@ -182,6 +182,8 @@ const withService = <A, E>(
182
const launches = yield* Queue.unbounded<LaunchInput>();
183
const secretsByRef = new Map<string, string>();
184
const layerDependencies = Layer.mergeAll(
185
+ NodePlatformCrypto.layerDigest,
186
+ NodePlatformCrypto.layerMac,
187
options.frameGate === undefined && options.onFrame === undefined
188
? NodePlatformCrypto.layer
189
: Layer.effect(
apps/server/src/scheduledTasks/webhookVerification.test.ts
+56
-40
@@ -1,7 +1,9 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
1
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Node's HMAC is an independent oracle for the Effect implementation.
2
import * as NodeCrypto from "node:crypto";
3
4
+import * as PlatformNodeCrypto from "@effect/platform-node/NodeCrypto";
5
import { assert, describe, it } from "@effect/vitest";
6
+import * as Effect from "effect/Effect";
7
8
import { verifyWebhookSignature } from "./webhookVerification.ts";
9
@@ -12,44 +14,58 @@ const hmac = () => NodeCrypto.createHmac("sha256", secret).update(body);
14
describe("verifyWebhookSignature", () => {
15
const github = { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=" } as const;
16
15
- it("rejects a tampered body, a wrong secret, a missing header and a missing prefix", () => {
16
- const valid = `sha256=${hmac().digest("hex")}`;
17
- const tampered = new TextEncoder().encode('{"action":"closed"}');
18
- assert.isFalse(
19
- verifyWebhookSignature({
20
- signature: github,
21
- secret,
22
- headers: { "x-hub-signature-256": valid },
23
- body: tampered,
24
- }),
25
- );
26
- assert.isFalse(
27
- verifyWebhookSignature({
28
- signature: github,
29
- secret: "other",
30
- headers: { "x-hub-signature-256": valid },
31
- body,
32
- }),
33
- );
34
- assert.isFalse(verifyWebhookSignature({ signature: github, secret, headers: {}, body }));
35
- assert.isFalse(
36
- verifyWebhookSignature({
37
- signature: github,
38
- secret,
39
- headers: { "x-hub-signature-256": hmac().digest("hex") },
40
- body,
41
- }),
42
- );
43
- });
17
+ it.effect("rejects a tampered body, a wrong secret, a missing header and a missing prefix", () =>
18
+ Effect.gen(function* () {
19
+ const valid = `sha256=${hmac().digest("hex")}`;
20
+ const tampered = new TextEncoder().encode('{"action":"closed"}');
21
+ assert.isFalse(
22
+ yield* verifyWebhookSignature({
23
+ signature: github,
24
+ secret,
25
+ headers: { "x-hub-signature-256": valid },
26
+ body: tampered,
27
+ }),
28
+ );
29
+ assert.isFalse(
30
+ yield* verifyWebhookSignature({
31
+ signature: github,
32
+ secret: "other",
33
+ headers: { "x-hub-signature-256": valid },
34
+ body,
35
+ }),
36
+ );
37
+ assert.isFalse(
38
+ yield* verifyWebhookSignature({ signature: github, secret, headers: {}, body }),
39
+ );
40
+ assert.isFalse(
41
+ yield* verifyWebhookSignature({
42
+ signature: github,
43
+ secret,
44
+ headers: { "x-hub-signature-256": hmac().digest("hex") },
45
+ body,
46
+ }),
47
+ );
48
+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),
49
+ );
50
45
- it("accepts a base64 signature without prefix", () => {
46
- assert.isTrue(
47
- verifyWebhookSignature({
48
- signature: { header: "X-Signature", encoding: "base64", prefix: "" },
49
- secret,
50
- headers: { "x-signature": hmac().digest("base64") },
51
- body,
52
- }),
53
- );
54
- });
51
+ it.effect("accepts a hex signature with its prefix and a base64 signature without one", () =>
52
+ Effect.gen(function* () {
53
+ assert.isTrue(
54
+ yield* verifyWebhookSignature({
55
+ signature: github,
56
+ secret,
57
+ headers: { "x-hub-signature-256": `sha256=${hmac().digest("hex").toUpperCase()}` },
58
+ body,
59
+ }),
60
+ );
61
+ assert.isTrue(
62
+ yield* verifyWebhookSignature({
63
+ signature: { header: "X-Signature", encoding: "base64", prefix: "" },
64
+ secret,
65
+ headers: { "x-signature": hmac().digest("base64") },
66
+ body,
67
+ }),
68
+ );
69
+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),
70
+ );
71
});
apps/server/src/scheduledTasks/webhookVerification.ts
+45
-29
@@ -1,32 +1,48 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
2
-import * as NodeCrypto from "node:crypto";
3
-
1
import type { ScheduledTaskWebhookSignature } from "@t3tools/contracts";
2
+import * as Digest from "effect/crypto/Digest";
3
+import * as Mac from "effect/crypto/Mac";
4
+import * as Effect from "effect/Effect";
5
+import * as Base64 from "effect/encoding/Base64";
6
+import * as Hex from "effect/encoding/Hex";
7
+import * as Result from "effect/Result";
8
+
9
+const utf8 = (value: string) => new TextEncoder().encode(value);
10
6
-/** Constant-time string comparison that does not leak length through timing. */
7
-export function constantTimeEquals(a: string, b: string): boolean {
8
- const digestA = NodeCrypto.createHash("sha256").update(a).digest();
9
- const digestB = NodeCrypto.createHash("sha256").update(b).digest();
10
- return NodeCrypto.timingSafeEqual(digestA, digestB);
11
-}
11
+/** Compares hashes so the comparison does not leak either string's length. */
12
+export const constantTimeEquals = Effect.fn("webhookVerification.constantTimeEquals")(function* (
13
+ a: string,
14
+ b: string,
15
+) {
16
+ const digest = yield* Digest.Digest;
17
+ const [left, right] = yield* Effect.all([
18
+ digest.digest(Digest.sha256, utf8(a)),
19
+ digest.digest(Digest.sha256, utf8(b)),
20
+ ]);
21
+ return Mac.timingSafeEqual(left, right);
22
+});
23
13
-export function verifyWebhookSignature(input: {
14
- readonly signature: ScheduledTaskWebhookSignature;
15
- readonly secret: string;
16
- readonly headers: Readonly<Record<string, string>>;
17
- readonly body: Uint8Array;
18
-}): boolean {
19
- const received = input.headers[input.signature.header.toLowerCase()];
20
- if (received === undefined) return false;
21
- const value = received.trim();
22
- const prefix = input.signature.prefix;
23
- if (prefix !== "" && !value.toLowerCase().startsWith(prefix.toLowerCase())) return false;
24
- const digest = NodeCrypto.createHmac("sha256", input.secret).update(input.body).digest();
25
- const expected =
26
- input.signature.encoding === "hex" ? digest.toString("hex") : digest.toString("base64");
27
- const candidate = value.slice(prefix.length);
28
- return constantTimeEquals(
29
- input.signature.encoding === "hex" ? candidate.toLowerCase() : candidate,
30
- expected,
31
- );
32
-}
24
+export const verifyWebhookSignature = Effect.fn("webhookVerification.verifyWebhookSignature")(
25
+ function* (input: {
26
+ readonly signature: ScheduledTaskWebhookSignature;
27
+ readonly secret: string;
28
+ readonly headers: Readonly<Record<string, string>>;
29
+ readonly body: Uint8Array;
30
+ }) {
31
+ const received = input.headers[input.signature.header.toLowerCase()];
32
+ if (received === undefined) return false;
33
+ const value = received.trim();
34
+ const prefix = input.signature.prefix;
35
+ if (prefix !== "" && !value.toLowerCase().startsWith(prefix.toLowerCase())) return false;
36
+ const candidate = value.slice(prefix.length);
37
+ const tag =
38
+ input.signature.encoding === "hex"
39
+ ? Hex.decode(candidate.toLowerCase())
40
+ : Base64.decode(candidate);
41
+ if (Result.isFailure(tag)) return false;
42
+ const mac = yield* Mac.Mac;
43
+ return yield* Mac.key(Mac.hmacSha256, utf8(input.secret)).pipe(
44
+ Effect.flatMap((key) => mac.verify(key, tag.success, input.body)),
45
+ Effect.orElseSucceed(() => false),
46
+ );
47
+ },
48
+);
apps/server/src/secrets/SecretRequests.ts
+23
-21
@@ -2,7 +2,6 @@
2
// Consuming tools keep values out of transcripts, projections, clients and model context.
3
// A `file` request instead moves its value to an owner-only file for the agent's own shell.
4
// A secret the user pasted in chat goes straight to such a file, with no card.
5
-import { pipe } from "effect/Function";
5
import {
6
CommandId,
7
SecretRef,
@@ -11,12 +10,12 @@ import {
10
type SecretRequestAnswerInput,
11
type ThreadId,
12
} from "@t3tools/contracts";
14
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
15
-import * as NodeCrypto from "node:crypto";
13
14
import * as Clock from "effect/Clock";
15
import * as Context from "effect/Context";
16
+import * as Mac from "effect/crypto/Mac";
17
import * as Effect from "effect/Effect";
18
+import * as Hex from "effect/encoding/Hex";
19
import * as FileSystem from "effect/FileSystem";
20
import * as Layer from "effect/Layer";
21
import * as Option from "effect/Option";
@@ -36,14 +35,6 @@ const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
35
const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
36
const FILE_NAME_PATTERN = /^[0-9a-f]{32}(\.partial)?$/;
37
39
-const refFor = (salt: string, threadId: ThreadId, turnItemId: string) =>
40
- SecretRef.make(
41
- `${SECRET_REF_PREFIX}${NodeCrypto.createHmac("sha256", salt)
42
- .update(`${threadId}\u0000${turnItemId}`)
43
- .digest("hex")
44
- .slice(0, 32)}`,
45
- );
46
-
38
const StoredSecret = Schema.fromJsonString(
39
Schema.Struct({ projectId: Schema.String, value: Schema.String, savedAt: Schema.Number }),
40
);
@@ -86,9 +77,19 @@ const make = Effect.gen(function* () {
77
// Beside the store's own files so the same owner-only directory and cleanup rules apply.
78
const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files");
79
89
- const salt = Buffer.from(
90
- yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
91
- ).toString("hex");
80
+ const mac = yield* Mac.Mac;
81
+ // Keyed by the salt's hex text, as refs saved by earlier versions were.
82
+ const refKey = yield* Mac.key(
83
+ Mac.hmacSha256,
84
+ new TextEncoder().encode(
85
+ Hex.encode(yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie)),
86
+ ),
87
+ ).pipe(Effect.orDie);
88
+ const refFor = (threadId: ThreadId, turnItemId: string) =>
89
+ mac.sign(refKey, new TextEncoder().encode(`${threadId}\u0000${turnItemId}`)).pipe(
90
+ Effect.orDie,
91
+ Effect.map((tag) => SecretRef.make(`${SECRET_REF_PREFIX}${Hex.encode(tag).slice(0, 32)}`)),
92
+ );
93
94
const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(
95
function* (input) {
@@ -123,7 +124,7 @@ const make = Effect.gen(function* () {
124
}).pipe(Effect.orDie);
125
yield* store
126
.create(
126
- storeName(refFor(salt, input.threadId, item.id)),
127
+ storeName(yield* refFor(input.threadId, item.id)),
128
new TextEncoder().encode(encoded),
129
)
130
.pipe(
@@ -153,7 +154,9 @@ const make = Effect.gen(function* () {
154
// Clear failed saves so the pending card can be answered again.
155
Effect.tapError(() =>
156
input.answer.type === "save"
156
- ? pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged)
157
+ ? refFor(input.threadId, item.id).pipe(
158
+ Effect.flatMap((ref) => removeLogged(storeName(ref))),
159
+ )
160
: Effect.void,
161
),
162
);
@@ -169,7 +172,7 @@ const make = Effect.gen(function* () {
172
);
173
const card = recorded.turnItems.find((candidate) => candidate.id === item.id);
174
if (card?.type === "secret_request" && card.secretStatus !== "saved") {
172
- yield* pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged);
175
+ yield* removeLogged(storeName(yield* refFor(input.threadId, item.id)));
176
return yield* new SecretRequestError({ reason: "agent_stopped" });
177
}
178
},
@@ -177,7 +180,7 @@ const make = Effect.gen(function* () {
180
181
const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")(
182
function* (input) {
180
- const ref = refFor(salt, input.threadId, input.turnItemId);
183
+ const ref = yield* refFor(input.threadId, input.turnItemId);
184
const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));
185
return Option.map(stored, () => ref);
186
},
@@ -277,7 +280,7 @@ const make = Effect.gen(function* () {
280
return yield* new SecretRequestError({ reason: "not_a_file_request" });
281
}
282
if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
280
- const ref = refFor(salt, input.threadId, item.id);
283
+ const ref = yield* refFor(input.threadId, item.id);
284
const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));
285
return yield* Effect.gen(function* () {
286
// 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* () {
304
"SecretRequests.savePasted",
305
)(function* (input) {
306
if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
304
- const ref = refFor(
305
- salt,
307
+ const ref = yield* refFor(
308
input.threadId,
309
`pasted\u0000${input.requestNamespace}\u0000${input.requestKey}`,
310
);
infra/relay/src/agentActivity/ApnsDeliveries.test.ts
+10
-9
@@ -157,6 +157,7 @@ function layerFor(input: {
157
) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
158
}) {
159
return ApnsDeliveries.layer.pipe(
160
+ Layer.provideMerge(NodeCryptoLayer.layerMac),
161
Layer.provide(ApnsClient.layer),
162
Layer.provide(ApnsProviderTokens.layer),
163
Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
@@ -571,7 +572,7 @@ describe("ApnsDeliveries", () => {
572
});
573
return Effect.gen(function* () {
574
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
574
- const result = yield* deliveries.processSignedJob(signedEnd);
575
+ const result = yield* deliveries.processSignedJob(yield* signedEnd);
576
expect(result.ok).toBe(true);
577
expect(requests).toHaveLength(sends ? 1 : 0);
578
if (sends) {
@@ -633,7 +634,7 @@ describe("ApnsDeliveries", () => {
634
635
return Effect.gen(function* () {
636
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
636
- const result = yield* deliveries.processSignedJob(signed);
637
+ const result = yield* deliveries.processSignedJob(yield* signed);
638
639
expect(result.kind).toBe("push_notification");
640
expect(result.ok).toBe(true);
@@ -698,7 +699,7 @@ describe("ApnsDeliveries", () => {
699
700
return Effect.gen(function* () {
701
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
701
- const result = yield* deliveries.processSignedJob(signed);
702
+ const result = yield* deliveries.processSignedJob(yield* signed);
703
704
expect(result).toMatchObject({
705
kind: "push_notification",
@@ -745,7 +746,7 @@ describe("ApnsDeliveries", () => {
746
747
return Effect.gen(function* () {
748
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
748
- const result = yield* deliveries.processSignedJob(signed);
749
+ const result = yield* deliveries.processSignedJob(yield* signed);
750
751
expect(result).toMatchObject({
752
kind: "live_activity_update",
@@ -813,7 +814,7 @@ describe("ApnsDeliveries", () => {
814
815
return Effect.gen(function* () {
816
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
816
- const result = yield* deliveries.processSignedJob(signed);
817
+ const result = yield* deliveries.processSignedJob(yield* signed);
818
819
expect(result).toMatchObject({
820
kind: "live_activity_update",
@@ -879,7 +880,7 @@ describe("ApnsDeliveries", () => {
880
881
return Effect.gen(function* () {
882
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
882
- const result = yield* Effect.exit(deliveries.processSignedJob(signed));
883
+ const result = yield* Effect.exit(deliveries.processSignedJob(yield* signed));
884
885
expect(result._tag).toBe("Failure");
886
if (result._tag === "Failure") {
@@ -935,7 +936,7 @@ describe("ApnsDeliveries", () => {
936
937
return Effect.gen(function* () {
938
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
938
- const result = yield* deliveries.processSignedJob(signed);
939
+ const result = yield* deliveries.processSignedJob(yield* signed);
940
941
expect(result.kind).toBe("push_notification");
942
expect(result.ok).toBe(false);
@@ -995,7 +996,7 @@ describe("ApnsDeliveries", () => {
996
997
return Effect.gen(function* () {
998
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
998
- const result = yield* deliveries.processSignedJob(signed);
999
+ const result = yield* deliveries.processSignedJob(yield* signed);
1000
1001
expect(result.kind).toBe("live_activity_update");
1002
expect(result.ok).toBe(false);
@@ -1204,7 +1205,7 @@ describe("signed APNs registration metadata", () => {
1205
});
1206
return Effect.gen(function* () {
1207
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
1207
- const result = yield* deliveries.processSignedJob(signed);
1208
+ const result = yield* deliveries.processSignedJob(yield* signed);
1209
expect(result.ok).toBe(true);
1210
expect(requests).toHaveLength(1);
1211
expect(requests[0]?.url).toBe(
infra/relay/src/agentActivity/ApnsDeliveries.ts
+4
-6
@@ -11,6 +11,7 @@ import {
11
} from "@t3tools/contracts/relay";
12
import * as Context from "effect/Context";
13
import * as DateTime from "effect/DateTime";
14
+import * as Mac from "effect/crypto/Mac";
15
import * as Effect from "effect/Effect";
16
import * as Layer from "effect/Layer";
17
import * as Option from "effect/Option";
@@ -31,7 +32,6 @@ import {
32
type ApnsLiveActivityAlert,
33
type ApnsNotificationPayload,
34
SignedApnsDeliveryJob,
34
- isApnsDeliveryJobVerificationError,
35
verifySignedApnsDeliveryJob,
36
type ApnsDeliveryJobVerificationError,
37
} from "./apnsDeliveryJobs.ts";
@@ -511,6 +511,7 @@ const make = Effect.gen(function* () {
511
const liveActivities = yield* LiveActivities.LiveActivities;
512
const deliveryQueue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;
513
const config = yield* RelayConfiguration.RelayConfiguration;
514
+ const mac = yield* Mac.Mac;
515
const apns = yield* Apns.ApnsClient;
516
const activityRows = yield* AgentActivityRows.AgentActivityRows;
517
@@ -934,14 +935,11 @@ const make = Effect.gen(function* () {
935
),
936
);
937
const now = yield* DateTime.now;
937
- const payload = verifySignedApnsDeliveryJob({
938
+ const payload = yield* verifySignedApnsDeliveryJob({
939
secret: config.apnsDeliveryJobSigningSecret,
940
job: signedJob,
941
nowMs: now.epochMilliseconds,
941
- });
942
- if (isApnsDeliveryJobVerificationError(payload)) {
943
- return yield* payload;
944
- }
942
+ }).pipe(Effect.provideService(Mac.Mac, mac));
943
yield* Effect.annotateCurrentSpan({
944
"relay.mobile.device_id": payload.target.deviceId,
945
"relay.delivery.kind": payload.kind,
infra/relay/src/agentActivity/ApnsDeliveryQueue.ts
+6
-4
@@ -3,6 +3,7 @@ import * as Cloudflare from "@alchemy.run/cloudflare";
3
import * as SecureRandom from "effect/crypto/SecureRandom";
4
import * as Context from "effect/Context";
5
import * as DateTime from "effect/DateTime";
6
+import * as Mac from "effect/crypto/Mac";
7
import * as Effect from "effect/Effect";
8
import * as Layer from "effect/Layer";
9
import * as Schema from "effect/Schema";
@@ -80,6 +81,7 @@ const make = Effect.gen(function* () {
81
const sender = yield* ApnsDeliveryQueueSender;
82
const random = yield* SecureRandom.SecureRandom;
83
const config = yield* RelayConfiguration.RelayConfiguration;
84
+ const mac = yield* Mac.Mac;
85
86
return ApnsDeliveryQueue.of({
87
enqueueLiveActivity: Effect.fn("relay.apns_delivery_queue.enqueue_live_activity")(
@@ -111,10 +113,10 @@ const make = Effect.gen(function* () {
113
createdAt: DateTime.formatIso(now),
114
expiresAt: expiresAtForJob(now.epochMilliseconds),
115
});
114
- const signed = signApnsDeliveryJob({
116
+ const signed = yield* signApnsDeliveryJob({
117
secret: config.apnsDeliveryJobSigningSecret,
118
payload,
117
- });
119
+ }).pipe(Effect.provideService(Mac.Mac, mac));
120
yield* sender.send(signed).pipe(
121
Effect.mapError(
122
(cause) =>
@@ -175,10 +177,10 @@ const make = Effect.gen(function* () {
177
createdAt: DateTime.formatIso(now),
178
expiresAt: expiresAtForJob(now.epochMilliseconds),
179
});
178
- const signed = signApnsDeliveryJob({
180
+ const signed = yield* signApnsDeliveryJob({
181
secret: config.apnsDeliveryJobSigningSecret,
182
payload,
181
- });
183
+ }).pipe(Effect.provideService(Mac.Mac, mac));
184
yield* sender.send(signed).pipe(
185
Effect.mapError(
186
(cause) =>
infra/relay/src/agentActivity/MobileRegistrations.test.ts
+1
@@ -166,6 +166,7 @@ function layerRegistrationReplay(input: {
166
),
167
),
168
Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
169
+ Layer.provide(NodeCryptoLayer.layerMac),
170
Layer.provide(
171
Layer.mergeAll(
172
Layer.succeed(Devices.Devices, input.devices),
infra/relay/src/agentActivity/apnsDeliveryJobs.test.ts
+44
-35
@@ -1,4 +1,6 @@
1
+import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
2
import { describe, expect, it } from "@effect/vitest";
3
+import * as Effect from "effect/Effect";
4
import * as Redacted from "effect/Redacted";
5
6
import {
@@ -10,42 +12,49 @@ import {
12
const secret = Redacted.make("queue-signing-secret");
13
14
describe("apnsDeliveryJobs", () => {
13
- it("rejects tampered signed queue jobs", () => {
14
- const payload = makeApnsDeliveryJobPayload({
15
- kind: "live_activity_end",
16
- userId: "user-1",
17
- deviceId: "device-1",
18
- token: "token-1",
19
- aggregate: null,
20
- createdAt: "2026-05-25T00:00:00.000Z",
21
- expiresAt: "2026-05-25T00:05:00.000Z",
22
- jobId: "job-1",
23
- });
24
- const signed = signApnsDeliveryJob({ secret, payload });
25
- const tampered = {
26
- ...signed,
27
- payload: {
28
- ...signed.payload,
29
- target: {
30
- ...signed.payload.target,
31
- token: "attacker-token",
15
+ it.effect("rejects tampered signed queue jobs", () =>
16
+ Effect.gen(function* () {
17
+ const payload = makeApnsDeliveryJobPayload({
18
+ kind: "live_activity_end",
19
+ userId: "user-1",
20
+ deviceId: "device-1",
21
+ token: "token-1",
22
+ aggregate: null,
23
+ createdAt: "2026-05-25T00:00:00.000Z",
24
+ expiresAt: "2026-05-25T00:05:00.000Z",
25
+ jobId: "job-1",
26
+ });
27
+ const signed = yield* signApnsDeliveryJob({ secret, payload });
28
+ expect(yield* verifySignedApnsDeliveryJob({ secret, job: signed, nowMs: 0 })).toEqual(
29
+ payload,
30
+ );
31
+ const tampered = {
32
+ ...signed,
33
+ payload: {
34
+ ...signed.payload,
35
+ target: {
36
+ ...signed.payload.target,
37
+ token: "attacker-token",
38
+ },
39
},
33
- },
34
- };
40
+ };
41
36
- const result = verifySignedApnsDeliveryJob({
37
- secret,
38
- job: tampered,
39
- nowMs: 0,
40
- });
42
+ const result = yield* Effect.flip(
43
+ verifySignedApnsDeliveryJob({
44
+ secret,
45
+ job: tampered,
46
+ nowMs: 0,
47
+ }),
48
+ );
49
42
- expect(result).toMatchObject({
43
- _tag: "ApnsDeliveryJobSignatureInvalid",
44
- jobId: "job-1",
45
- kind: "live_activity_end",
46
- userId: "user-1",
47
- deviceId: "device-1",
48
- message: "Invalid signature for APNs delivery job job-1.",
49
- });
50
- });
50
+ expect(result).toMatchObject({
51
+ _tag: "ApnsDeliveryJobSignatureInvalid",
52
+ jobId: "job-1",
53
+ kind: "live_activity_end",
54
+ userId: "user-1",
55
+ deviceId: "device-1",
56
+ message: "Invalid signature for APNs delivery job job-1.",
57
+ });
58
+ }).pipe(Effect.provide(NodeCryptoLayer.layerMac)),
59
+ );
60
});
infra/relay/src/agentActivity/apnsDeliveryJobs.ts
+55
-46
@@ -1,14 +1,15 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
2
-import * as NodeCrypto from "node:crypto";
3
-
1
import {
2
RelayAgentActivityAggregateState,
3
RelayAgentAwarenessPhase,
4
} from "@t3tools/contracts/relay";
5
import { stableStringify } from "@t3tools/shared/relaySigning";
6
+import * as Mac from "effect/crypto/Mac";
7
import * as DateTime from "effect/DateTime";
8
+import * as Effect from "effect/Effect";
9
+import * as Base64Url from "effect/encoding/Base64Url";
10
import * as Option from "effect/Option";
11
import * as Redacted from "effect/Redacted";
12
+import * as Result from "effect/Result";
13
import * as Schema from "effect/Schema";
14
15
const MAX_JOB_AGE_MS = 10 * 60 * 1_000;
@@ -224,8 +225,6 @@ export const ApnsDeliveryJobVerificationError = Schema.Union([
225
]);
226
export type ApnsDeliveryJobVerificationError = typeof ApnsDeliveryJobVerificationError.Type;
227
227
-export const isApnsDeliveryJobVerificationError = Schema.is(ApnsDeliveryJobVerificationError);
228
-
228
export function makeApnsDeliveryJobPayload(input: {
229
readonly kind: ApnsDeliveryJobPayload["kind"];
230
readonly userId: string;
@@ -313,41 +312,63 @@ function validatePayloadShape(payload: ApnsDeliveryJobPayload): ApnsDeliveryJobI
312
}
313
}
314
316
-function signatureForPayload(input: {
317
- readonly secret: Redacted.Redacted<string>;
318
- readonly payload: ApnsDeliveryJobPayload;
319
-}): string {
320
- return NodeCrypto.createHmac("sha256", Redacted.value(input.secret))
321
- .update(stableStringify(input.payload))
322
- .digest("base64url");
323
-}
315
+const signingKey = (secret: Redacted.Redacted<string>) =>
316
+ Mac.key(Mac.hmacSha256, new TextEncoder().encode(Redacted.value(secret)));
317
325
-function timingSafeEqualBase64Url(left: string, right: string): boolean {
326
- const leftBuffer = Buffer.from(left, "base64url");
327
- const rightBuffer = Buffer.from(right, "base64url");
328
- if (leftBuffer.length !== rightBuffer.length) {
329
- return false;
330
- }
331
- return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
332
-}
318
+const payloadBytes = (payload: ApnsDeliveryJobPayload) =>
319
+ new TextEncoder().encode(stableStringify(payload));
320
334
-export function signApnsDeliveryJob(input: {
321
+export const signApnsDeliveryJob = Effect.fn("relay.apns_delivery_jobs.sign")(function* (input: {
322
readonly secret: Redacted.Redacted<string>;
323
readonly payload: ApnsDeliveryJobPayload;
337
-}): SignedApnsDeliveryJob {
324
+}) {
325
+ const mac = yield* Mac.Mac;
326
+ const signature = yield* signingKey(input.secret).pipe(
327
+ Effect.flatMap((key) => mac.sign(key, payloadBytes(input.payload))),
328
+ Effect.orDie,
329
+ );
330
return {
331
algorithm: APNS_DELIVERY_JOB_SIGNING_ALGORITHM,
332
payload: input.payload,
341
- signature: signatureForPayload(input),
342
- };
343
-}
333
+ signature: Base64Url.encode(signature),
334
+ } satisfies SignedApnsDeliveryJob;
335
+});
336
345
-export function verifySignedApnsDeliveryJob(input: {
346
- readonly secret: Redacted.Redacted<string>;
347
- readonly job: SignedApnsDeliveryJob;
348
- readonly nowMs: number;
349
-}): ApnsDeliveryJobPayload | ApnsDeliveryJobVerificationError {
350
- const payload = input.job.payload;
337
+export const verifySignedApnsDeliveryJob = Effect.fn("relay.apns_delivery_jobs.verify")(
338
+ function* (input: {
339
+ readonly secret: Redacted.Redacted<string>;
340
+ readonly job: SignedApnsDeliveryJob;
341
+ readonly nowMs: number;
342
+ }) {
343
+ const payload = input.job.payload;
344
+ const invalid = validateSignedJobWindow(payload, input.nowMs);
345
+ if (invalid !== null) {
346
+ return yield* invalid;
347
+ }
348
+ const tag = Base64Url.decode(input.job.signature);
349
+ const mac = yield* Mac.Mac;
350
+ const verified =
351
+ Result.isSuccess(tag) &&
352
+ (yield* signingKey(input.secret).pipe(
353
+ Effect.flatMap((key) => mac.verify(key, tag.success, payloadBytes(payload))),
354
+ Effect.orDie,
355
+ ));
356
+ if (!verified) {
357
+ return yield* new ApnsDeliveryJobSignatureInvalid({
358
+ jobId: payload.jobId,
359
+ kind: payload.kind,
360
+ userId: payload.target.userId,
361
+ deviceId: payload.target.deviceId,
362
+ });
363
+ }
364
+ return payload;
365
+ },
366
+);
367
+
368
+function validateSignedJobWindow(
369
+ payload: ApnsDeliveryJobPayload,
370
+ nowMs: number,
371
+): ApnsDeliveryJobVerificationError | null {
372
const invalidPayload = validatePayloadShape(payload);
373
if (invalidPayload !== null) {
374
return invalidPayload;
@@ -394,7 +415,7 @@ export function verifySignedApnsDeliveryJob(input: {
415
expiresAt: payload.expiresAt,
416
});
417
}
397
- if (expiresAtMs <= input.nowMs) {
418
+ if (expiresAtMs <= nowMs) {
419
return new ApnsDeliveryJobExpired({
420
jobId: payload.jobId,
421
kind: payload.kind,
@@ -403,17 +424,5 @@ export function verifySignedApnsDeliveryJob(input: {
424
expiresAt: payload.expiresAt,
425
});
426
}
406
- const expected = signatureForPayload({
407
- secret: input.secret,
408
- payload,
409
- });
410
- if (!timingSafeEqualBase64Url(input.job.signature, expected)) {
411
- return new ApnsDeliveryJobSignatureInvalid({
412
- jobId: payload.jobId,
413
- kind: payload.kind,
414
- userId: payload.target.userId,
415
- deviceId: payload.target.deviceId,
416
- });
417
- }
418
- return payload;
427
+ return null;
428
}
infra/relay/src/worker.ts
+6
-3
@@ -6,6 +6,7 @@ import * as Config from "effect/Config";
6
import * as Cause from "effect/Cause";
7
import * as DateTime from "effect/DateTime";
8
import * as Digest from "effect/crypto/Digest";
9
+import * as Mac from "effect/crypto/Mac";
10
import * as SecureRandom from "effect/crypto/SecureRandom";
11
import * as Signature from "effect/crypto/Signature";
12
import * as Effect from "effect/Effect";
@@ -74,9 +75,11 @@ import * as HookInbox from "./hooks/HookInbox.ts";
75
import * as HookInboxObject from "./hooks/HookInboxObject.ts";
76
import * as MobileTelemetry from "./mobileTelemetry/MobileTelemetry.ts";
77
77
-const layerWebcrypto = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(
78
- Layer.provideMerge(SecureRandom.layerWebCrypto),
79
-);
78
+const layerWebcrypto = Layer.mergeAll(
79
+ Digest.layerWebCrypto,
80
+ Mac.layerWebCrypto,
81
+ Signature.layerWebCrypto,
82
+).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto));
83
84
const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, {
85
platform: "web",
packages/shared/src/desktopBootstrapToken.test.ts
+41
-37
@@ -1,4 +1,9 @@
1
-import { describe, expect, it } from "vite-plus/test";
1
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Older desktops derive the token with Node's HMAC.
2
+import * as NodeCrypto from "node:crypto";
3
+
4
+import * as PlatformNodeCrypto from "@effect/platform-node/NodeCrypto";
5
+import { describe, expect, it } from "@effect/vitest";
6
+import * as Effect from "effect/Effect";
7
8
import {
9
DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
@@ -10,40 +15,39 @@ const SECRET = "desktop-secret";
15
const WINDOW = DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS;
16
17
describe("desktop bootstrap token", () => {
13
- it("rotates every window and stays accepted for one more", () => {
14
- const issuedAt = 10 * WINDOW + 1;
15
- const token = currentDesktopBootstrapToken(SECRET, issuedAt);
16
-
17
- expect(currentDesktopBootstrapToken(SECRET, issuedAt + WINDOW)).not.toBe(token);
18
- expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt)).toBe(true);
19
- expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt + WINDOW)).toBe(true);
20
- expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt + 2 * WINDOW)).toBe(false);
21
- });
22
-
23
- it("accepts a token from a desktop clock slightly ahead of the backend", () => {
24
- const desktopNow = 10 * WINDOW + 500;
25
- const backendNow = 10 * WINDOW - 500;
26
-
27
- expect(
28
- isValidDesktopBootstrapToken(
29
- SECRET,
30
- currentDesktopBootstrapToken(SECRET, desktopNow),
31
- backendNow,
32
- ),
33
- ).toBe(true);
34
- expect(
35
- isValidDesktopBootstrapToken(
36
- SECRET,
37
- currentDesktopBootstrapToken(SECRET, desktopNow + WINDOW),
38
- backendNow,
39
- ),
40
- ).toBe(false);
41
- });
42
-
43
- it("rejects tokens derived from another secret", () => {
44
- const token = currentDesktopBootstrapToken("other-secret", WINDOW);
45
-
46
- expect(isValidDesktopBootstrapToken(SECRET, token, WINDOW)).toBe(false);
47
- expect(isValidDesktopBootstrapToken(SECRET, "short", WINDOW)).toBe(false);
48
- });
18
+ it.effect("rotates every window and stays accepted for one more", () =>
19
+ Effect.gen(function* () {
20
+ const issuedAt = 10 * WINDOW + 1;
21
+ const token = yield* currentDesktopBootstrapToken(SECRET, issuedAt);
22
+
23
+ expect(token).toBe(
24
+ NodeCrypto.createHmac("sha256", SECRET).update("t3-desktop-bootstrap:10").digest("hex"),
25
+ );
26
+ expect(yield* currentDesktopBootstrapToken(SECRET, issuedAt + WINDOW)).not.toBe(token);
27
+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, issuedAt)).toBe(true);
28
+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, issuedAt + WINDOW)).toBe(true);
29
+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, issuedAt + 2 * WINDOW)).toBe(false);
30
+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),
31
+ );
32
+
33
+ it.effect("accepts a token from a desktop clock slightly ahead of the backend", () =>
34
+ Effect.gen(function* () {
35
+ const desktopNow = 10 * WINDOW + 500;
36
+ const backendNow = 10 * WINDOW - 500;
37
+ const ahead = yield* currentDesktopBootstrapToken(SECRET, desktopNow);
38
+ const tooFarAhead = yield* currentDesktopBootstrapToken(SECRET, desktopNow + WINDOW);
39
+
40
+ expect(yield* isValidDesktopBootstrapToken(SECRET, ahead, backendNow)).toBe(true);
41
+ expect(yield* isValidDesktopBootstrapToken(SECRET, tooFarAhead, backendNow)).toBe(false);
42
+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),
43
+ );
44
+
45
+ it.effect("rejects tokens derived from another secret", () =>
46
+ Effect.gen(function* () {
47
+ const token = yield* currentDesktopBootstrapToken("other-secret", WINDOW);
48
+
49
+ expect(yield* isValidDesktopBootstrapToken(SECRET, token, WINDOW)).toBe(false);
50
+ expect(yield* isValidDesktopBootstrapToken(SECRET, "short", WINDOW)).toBe(false);
51
+ }).pipe(Effect.provide(PlatformNodeCrypto.layerMac)),
52
+ );
53
});
packages/shared/src/desktopBootstrapToken.ts
+22
-18
@@ -1,32 +1,36 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
2
-import * as NodeCrypto from "node:crypto";
1
+import * as Mac from "effect/crypto/Mac";
2
+import * as Effect from "effect/Effect";
3
+import * as Hex from "effect/encoding/Hex";
4
5
/** Accept previous/current windows for token lifetime and the next window for WSL clock lag. */
6
export const DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS = 12 * 60 * 60 * 1000;
7
8
+const utf8 = (value: string) => new TextEncoder().encode(value);
9
+
10
function windowIndex(nowMs: number): number {
11
return Math.floor(nowMs / DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS);
12
}
13
11
-function deriveToken(secret: string, window: number): string {
12
- return NodeCrypto.createHmac("sha256", secret)
13
- .update(`t3-desktop-bootstrap:${window}`)
14
- .digest("hex");
15
-}
14
+// Untraced: an inner step of the named callers below, run up to three times per check.
15
+const deriveToken = Effect.fnUntraced(function* (secret: string, window: number) {
16
+ const mac = yield* Mac.Mac;
17
+ const key = yield* Mac.key(Mac.hmacSha256, utf8(secret));
18
+ return Hex.encode(yield* mac.sign(key, utf8(`t3-desktop-bootstrap:${window}`)));
19
+}, Effect.orDie);
20
17
-export function currentDesktopBootstrapToken(secret: string, nowMs: number): string {
18
- return deriveToken(secret, windowIndex(nowMs));
19
-}
21
+export const currentDesktopBootstrapToken = Effect.fn("desktopBootstrapToken.current")(
22
+ (secret: string, nowMs: number) => deriveToken(secret, windowIndex(nowMs)),
23
+);
24
21
-export function isValidDesktopBootstrapToken(
25
+export const isValidDesktopBootstrapToken = Effect.fn("desktopBootstrapToken.isValid")(function* (
26
secret: string,
27
token: string,
28
nowMs: number,
25
-): boolean {
26
- const presented = Buffer.from(token);
29
+) {
30
+ const presented = utf8(token);
31
const current = windowIndex(nowMs);
28
- return [current - 1, current, current + 1].some((window) => {
29
- const expected = Buffer.from(deriveToken(secret, window));
30
- return expected.length === presented.length && NodeCrypto.timingSafeEqual(expected, presented);
31
- });
32
-}
32
+ for (const window of [current - 1, current, current + 1]) {
33
+ if (Mac.timingSafeEqual(utf8(yield* deriveToken(secret, window)), presented)) return true;
34
+ }
35
+ return false;
36
+});