Skip to content

Commit 2e0501f

Browse files
committed
refactor: Effect code gets UUIDs and SHA-256 from Effect's Crypto
Thirteen files made UUIDs or SHA-256 digests with node:crypto from inside Effect code. They now use the Crypto service, captured where each service is built. Node's calls threw on failure, which became defects, so Effect.orDie keeps that behavior. Every hash keeps its exact input bytes and hex output, so stored credential names and cache keys do not change.
1 parent 8f75697 commit 2e0501f

22 files changed

Lines changed: 109 additions & 58 deletions

‎apps/desktop/src/preview/Manager.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeVM from "node:vm";
2+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
23
import { it as effectIt } from "@effect/vitest";
34
import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
45
import type {
@@ -279,6 +280,7 @@ const layer = PreviewManager.layer.pipe(
279280
Layer.provideMerge(layerEnvironment),
280281
Layer.provideMerge(layerFileSystem),
281282
Layer.provideMerge(Path.layer),
283+
Layer.provideMerge(NodeCrypto.layer),
282284
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "darwin")),
283285
);
284286
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);

‎apps/desktop/src/preview/Manager.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
* elements live in the renderer; we only attach listeners and forward state
66
* here). Single layer-scoped browser session partition.
77
*/
8-
import * as NodeCrypto from "node:crypto";
98
import {
109
DesktopPreviewRecordingInputSchema,
1110
DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER,
@@ -49,6 +48,7 @@ import {
4948
import * as Cause from "effect/Cause";
5049
import * as Clock from "effect/Clock";
5150
import * as Context from "effect/Context";
51+
import * as Crypto from "effect/Crypto";
5252
import * as DateTime from "effect/DateTime";
5353
import * as Deferred from "effect/Deferred";
5454
import * as Effect from "effect/Effect";
@@ -643,6 +643,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
643643
const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
644644
const hostPlatform = yield* HostProcessPlatform;
645645
const path = yield* Path.Path;
646+
const crypto = yield* Crypto.Crypto;
646647
const parentScope = yield* Scope.Scope;
647648
const context = yield* Effect.context<never>();
648649
const runFork = Effect.runForkWith(context);
@@ -1657,9 +1658,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
16571658
returnByValue: boolean,
16581659
awaitPromise = true,
16591660
): Effect.Effect<A, PreviewManagerError> =>
1660-
Effect.suspend(() => {
1661-
const objectGroup = `t3-evaluation-${NodeCrypto.randomUUID()}`;
1662-
return send("Runtime.evaluate", {
1661+
Effect.gen(function* () {
1662+
const objectGroup = `t3-evaluation-${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}`;
1663+
return yield* send("Runtime.evaluate", {
16631664
expression,
16641665
awaitPromise,
16651666
returnByValue,
@@ -4186,10 +4187,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
41864187
const context = { operation: "automationPress.awaitNativeKey", tabId, webContentsId: wc.id };
41874188
const evaluate = (frame: Electron.WebFrameMain, expression: string) =>
41884189
attemptPromise(context, () => frame.executeJavaScript(expression));
4190+
const receiptId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
41894191
const { frames, receiptKey } = yield* Effect.acquireRelease(
41904192
attempt(context, () => ({
41914193
frames: wc.mainFrame.framesInSubtree,
4192-
receiptKey: JSON.stringify(`__t3NativeKey_${NodeCrypto.randomUUID()}`),
4194+
receiptKey: JSON.stringify(`__t3NativeKey_${receiptId}`),
41934195
})),
41944196
({ frames, receiptKey }) =>
41954197
Effect.forEach(
@@ -4445,10 +4447,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
44454447
keySequence,
44464448
clipboardData,
44474449
);
4448-
const selectionKey = yield* encodeJson(
4449-
context,
4450-
`__t3EditingSelection_${NodeCrypto.randomUUID()}`,
4451-
);
4450+
const selectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
4451+
const selectionKey = yield* encodeJson(context, `__t3EditingSelection_${selectionId}`);
44524452
// Editing requires an active document. Preserve the target
44534453
// and selection across focus handlers without focusing the desktop.
44544454
yield* Effect.acquireUseRelease(

‎apps/server/scripts/measure-pr-preview.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ const layerMeasuredProcess = Layer.effect(
5050
const layerServices = GitHubPullRequestCli.layer.pipe(
5151
Layer.provide(GitHubCli.layer),
5252
Layer.provideMerge(layerMeasuredProcess),
53+
Layer.provide(NodeServices.layer),
5354
);
5455

5556
const decodeJson = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown));

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
import * as NodeCrypto from "node:crypto";
2-
31
import {
42
ATTACHMENT_UPLOAD_URL_TTL_MS,
53
type AttachmentCreateUploadUrlInput,
64
AttachmentUploadSigningKeyError,
75
} from "@t3tools/contracts";
86
import * as Clock from "effect/Clock";
7+
import * as Crypto from "effect/Crypto";
98
import * as Effect from "effect/Effect";
109
import * as FileSystem from "effect/FileSystem";
1110
import * as Option from "effect/Option";
@@ -170,9 +169,11 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio
170169
attachmentsDir: config.attachmentsDir,
171170
relativePath,
172171
});
172+
const crypto = yield* Crypto.Crypto;
173+
const partId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
173174
const partPath = resolveAttachmentRelativePath({
174175
attachmentsDir: config.attachmentsDir,
175-
relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
176+
relativePath: `${relativePath}.${partId}.part`,
176177
});
177178
if (!finalPath || !partPath) {
178179
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import * as NodeCrypto from "node:crypto";
21
import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
32
import * as Cache from "effect/Cache";
43
import * as Cause from "effect/Cause";
4+
import * as Crypto from "effect/Crypto";
55
import * as Effect from "effect/Effect";
66
import * as Clock from "effect/Clock";
77
import * as Context from "effect/Context";
@@ -13,6 +13,7 @@ import * as Option from "effect/Option";
1313
import * as Path from "effect/Path";
1414
import * as PlatformError from "effect/PlatformError";
1515
import * as Semaphore from "effect/Semaphore";
16+
import * as Hex from "effect/encoding/Hex";
1617
import { ChildProcess, ChildProcessSpawner } from "effect/process";
1718
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
1819

@@ -175,17 +176,21 @@ const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUnc
175176
const appVersion =
176177
(yield* plistValue(infoPlistPath, "CFBundleVersion")) ||
177178
(yield* plistValue(infoPlistPath, "CFBundleShortVersionString"));
178-
const cacheKey = NodeCrypto.createHash("sha256")
179-
.update(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`)
180-
.digest("hex");
179+
const crypto = yield* Crypto.Crypto;
180+
const cacheKey = yield* crypto
181+
.digest(
182+
"SHA-256",
183+
new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`),
184+
)
185+
.pipe(Effect.map(Hex.encode), Effect.orDie);
181186
const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
182187
const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
183188
if (yield* existingFile(cachePath)) return cachePath;
184189

185190
yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
186191
const temporaryPath = path.join(
187192
cacheDirectory,
188-
`.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID()}.png`,
193+
`.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}.png`,
189194
);
190195
yield* commandOutput("/usr/bin/sips", [
191196
"-z",

‎apps/server/src/cli/app.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// @effect-diagnostics globalTimers:off -- The Node socket client owns its response deadline and clears it on every completion path.
2-
import * as NodeCrypto from "node:crypto";
32
import * as NodeNet from "node:net";
43
import * as NodeOS from "node:os";
54

@@ -18,6 +17,7 @@ import {
1817
} from "@t3tools/shared/hostProcess";
1918
import * as Config from "effect/Config";
2019
import * as Console from "effect/Console";
20+
import * as Crypto from "effect/Crypto";
2121
import * as Effect from "effect/Effect";
2222
import * as Option from "effect/Option";
2323
import * as Path from "effect/Path";
@@ -212,9 +212,11 @@ const runAppCommand = Effect.fn("cli.app")(function* (flags: {
212212
userId,
213213
joinPath: path.join,
214214
}).address;
215+
const crypto = yield* Crypto.Crypto;
216+
const requestId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
215217
const request: DesktopAppActivationRequest = {
216218
version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
217-
requestId: NodeCrypto.randomUUID(),
219+
requestId,
218220
type: "open-workspace",
219221
workspaceRoot,
220222
platform: hostPlatform,

‎apps/server/src/device/SshDeviceHost.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as NodeCrypto from "node:crypto";
21
import {
32
type DeviceHostSummary,
43
DevicePlatformAvailability,
@@ -9,6 +8,7 @@ import {
98
import { runSshCommand, baseSshArgs, resolveSshCommand } from "@t3tools/ssh/command";
109
import * as NetService from "@t3tools/shared/Net";
1110
import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
11+
import * as Crypto from "effect/Crypto";
1212
import * as Exit from "effect/Exit";
1313
import * as Effect from "effect/Effect";
1414
import * as FileSystem from "effect/FileSystem";
@@ -17,6 +17,7 @@ import * as Scope from "effect/Scope";
1717
import * as Semaphore from "effect/Semaphore";
1818
import * as Schema from "effect/Schema";
1919
import * as Stream from "effect/Stream";
20+
import * as Hex from "effect/encoding/Hex";
2021
import * as HttpClient from "effect/http/HttpClient";
2122
import * as ChildProcess from "effect/process/ChildProcess";
2223
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
@@ -79,10 +80,11 @@ const ownerFor = Effect.fn("SshDeviceHost.ownerFor")(function* (hostId: string)
7980
const environmentId = yield* fs
8081
.readFileString(server.environmentIdPath)
8182
.pipe(Effect.orElseSucceed(() => server.stateDir));
82-
return NodeCrypto.createHash("sha256")
83-
.update(`${environmentId}\0${server.stateDir}\0${hostId}`)
84-
.digest("hex")
85-
.slice(0, 24);
83+
const crypto = yield* Crypto.Crypto;
84+
const owner = yield* crypto
85+
.digest("SHA-256", new TextEncoder().encode(`${environmentId}\0${server.stateDir}\0${hostId}`))
86+
.pipe(Effect.map(Hex.encode), Effect.orDie);
87+
return owner.slice(0, 24);
8688
});
8789

8890
export const probe = Effect.fn("SshDeviceHost.probe")(function* (
@@ -125,6 +127,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
125127
const net = yield* NetService.NetService;
126128
const http = yield* HttpClient.HttpClient;
127129
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
130+
const crypto = yield* Crypto.Crypto;
128131
const parentScope = yield* Scope.Scope;
129132
const ssh = yield* resolveSshCommand;
130133
const owner = yield* ownerFor(config.id);
@@ -135,6 +138,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
135138
| FileSystem.FileSystem
136139
| Path.Path
137140
| ChildProcessSpawner.ChildProcessSpawner
141+
| Crypto.Crypto
138142
| ServerConfig.ServerConfig
139143
>,
140144
) =>
@@ -143,6 +147,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
143147
Effect.provideService(Path.Path, path),
144148
Effect.provideService(ServerConfig.ServerConfig, server),
145149
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
150+
Effect.provideService(Crypto.Crypto, crypto),
146151
);
147152
const lock = yield* Semaphore.make(1);
148153
let stopped = false;

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import * as NodeCrypto from "node:crypto";
21
import * as Cause from "effect/Cause";
32
import * as Clock from "effect/Clock";
43
import * as Context from "effect/Context";
4+
import * as Crypto from "effect/Crypto";
55
import * as Effect from "effect/Effect";
66
import * as FileSystem from "effect/FileSystem";
77
import * as Layer from "effect/Layer";
@@ -334,8 +334,10 @@ const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (
334334
const fileSystem = yield* FileSystem.FileSystem;
335335
const path = yield* Path.Path;
336336
const millis = yield* Clock.currentTimeMillis;
337+
const crypto = yield* Crypto.Crypto;
337338
// Two saves in the same millisecond must not overwrite each other.
338-
const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
339+
const unique = (yield* crypto.randomUUIDv4.pipe(Effect.orDie)).slice(0, 8);
340+
const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${unique}.png`;
339341
const screenshotPath = path.join(config.browserArtifactsDir, fileName);
340342
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(
341343
Effect.andThen(fileSystem.writeFile(screenshotPath, data)),
@@ -387,7 +389,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
387389
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
388390
// The MCP tool runner only supplies the client, so hand the save path its services here.
389391
const saveServices = yield* Effect.context<
390-
ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path
392+
ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path | Crypto.Crypto
391393
>();
392394
const built = yield* PreviewSnapshotToolkit;
393395
const tool = PreviewSnapshotTool;

‎apps/server/src/mcp/toolkits/previewControls/handlers.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
12
import { expect, it } from "@effect/vitest";
23
import {
34
DEFAULT_SERVER_SETTINGS,
@@ -45,7 +46,7 @@ it.effect.each([
4546
capabilities: new Set(effective.enableAgentBrowserAccess ? ["preview"] : []),
4647
issuedAt: 0,
4748
};
48-
const manager = yield* Preview.make;
49+
const manager = yield* Preview.make.pipe(Effect.provide(NodeCrypto.layer));
4950
const tab = yield* manager.open({ threadId, url: "http://localhost:3000" });
5051
const layerDependencies = Layer.mergeAll(
5152
Layer.succeed(Preview.PreviewManager, manager),

‎apps/server/src/preview/Manager.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
12
import { it } from "@effect/vitest";
23
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
34
import { PreviewUrlNormalizationError } from "@t3tools/shared/preview";
4-
import { Effect, PubSub } from "effect";
5+
import * as Effect from "effect/Effect";
6+
import * as Layer from "effect/Layer";
7+
import * as PubSub from "effect/PubSub";
58
import { expect } from "vite-plus/test";
69

710
import * as PreviewManager from "./Manager.ts";
@@ -35,7 +38,7 @@ const collectEvents = Effect.gen(function* () {
3538
return collector;
3639
}).pipe(Effect.withSpan("preview.test.collectEvents"));
3740

38-
it.layer(PreviewManager.layer)("PreviewManager", (it) => {
41+
it.layer(PreviewManager.layer.pipe(Layer.provide(NodeCrypto.layer)))("PreviewManager", (it) => {
3942
it.effect("opens a session and emits opened with normalized URL", () =>
4043
Effect.gen(function* () {
4144
const threadId = freshThreadId();

0 commit comments

Comments
 (0)