Skip to content
TypeScript

refactor: Effect code gets UUIDs and SHA-256 from Effect's Crypto (#16377)

Erik Thorelli83b982a85c87
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index f731424e021..5211d59804f 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -1,4 +1,5 @@
import * as NodeVM from "node:vm";
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { it as effectIt } from "@effect/vitest";
import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
import type {
@@ -279,6 +280,7 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(layerEnvironment),
Layer.provideMerge(layerFileSystem),
Layer.provideMerge(Path.layer),
+ Layer.provideMerge(NodeCrypto.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "darwin")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 3593ae5f5df..bc34daee4ad 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -5,7 +5,6 @@
* elements live in the renderer; we only attach listeners and forward state
* here). Single layer-scoped browser session partition.
*/
-import * as NodeCrypto from "node:crypto";
import {
DesktopPreviewRecordingInputSchema,
DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER,
@@ -49,6 +48,7 @@ import {
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -643,6 +643,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
const hostPlatform = yield* HostProcessPlatform;
const path = yield* Path.Path;
+ const crypto = yield* Crypto.Crypto;
const parentScope = yield* Scope.Scope;
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
@@ -1657,9 +1658,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
returnByValue: boolean,
awaitPromise = true,
): Effect.Effect<A, PreviewManagerError> =>
- Effect.suspend(() => {
- const objectGroup = `t3-evaluation-${NodeCrypto.randomUUID()}`;
- return send("Runtime.evaluate", {
+ Effect.gen(function* () {
+ const objectGroup = `t3-evaluation-${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}`;
+ return yield* send("Runtime.evaluate", {
expression,
awaitPromise,
returnByValue,
@@ -4186,10 +4187,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const context = { operation: "automationPress.awaitNativeKey", tabId, webContentsId: wc.id };
const evaluate = (frame: Electron.WebFrameMain, expression: string) =>
attemptPromise(context, () => frame.executeJavaScript(expression));
+ const receiptId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const { frames, receiptKey } = yield* Effect.acquireRelease(
attempt(context, () => ({
frames: wc.mainFrame.framesInSubtree,
- receiptKey: JSON.stringify(`__t3NativeKey_${NodeCrypto.randomUUID()}`),
+ receiptKey: JSON.stringify(`__t3NativeKey_${receiptId}`),
})),
({ frames, receiptKey }) =>
Effect.forEach(
@@ -4445,10 +4447,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
keySequence,
clipboardData,
);
- const selectionKey = yield* encodeJson(
- context,
- `__t3EditingSelection_${NodeCrypto.randomUUID()}`,
- );
+ const selectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
+ const selectionKey = yield* encodeJson(context, `__t3EditingSelection_${selectionId}`);
// Editing requires an active document. Preserve the target
// and selection across focus handlers without focusing the desktop.
yield* Effect.acquireUseRelease(
diff --git a/apps/server/scripts/measure-pr-preview.ts b/apps/server/scripts/measure-pr-preview.ts
index 1221fb7ff39..f967d1f26a8 100644
--- a/apps/server/scripts/measure-pr-preview.ts
+++ b/apps/server/scripts/measure-pr-preview.ts
@@ -50,6 +50,7 @@ const layerMeasuredProcess = Layer.effect(
const layerServices = GitHubPullRequestCli.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provideMerge(layerMeasuredProcess),
+ Layer.provide(NodeServices.layer),
);
const decodeJson = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown));
diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts
index a6e83d8853c..071f6313b68 100644
--- a/apps/server/src/assets/AttachmentUpload.ts
+++ b/apps/server/src/assets/AttachmentUpload.ts
@@ -1,11 +1,10 @@
-import * as NodeCrypto from "node:crypto";
-
import {
ATTACHMENT_UPLOAD_URL_TTL_MS,
type AttachmentCreateUploadUrlInput,
AttachmentUploadSigningKeyError,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -170,9 +169,11 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio
attachmentsDir: config.attachmentsDir,
relativePath,
});
+ const crypto = yield* Crypto.Crypto;
+ const partId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const partPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
- relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
+ relativePath: `${relativePath}.${partId}.part`,
});
if (!finalPath || !partPath) {
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
diff --git a/apps/server/src/assets/NativeAppIconResolver.ts b/apps/server/src/assets/NativeAppIconResolver.ts
index b883f625d33..df5c8a03f67 100644
--- a/apps/server/src/assets/NativeAppIconResolver.ts
+++ b/apps/server/src/assets/NativeAppIconResolver.ts
@@ -1,7 +1,7 @@
-import * as NodeCrypto from "node:crypto";
import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
@@ -13,6 +13,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Semaphore from "effect/Semaphore";
+import * as Hex from "effect/encoding/Hex";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
@@ -175,9 +176,13 @@ const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUnc
const appVersion =
(yield* plistValue(infoPlistPath, "CFBundleVersion")) ||
(yield* plistValue(infoPlistPath, "CFBundleShortVersionString"));
- const cacheKey = NodeCrypto.createHash("sha256")
- .update(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`)
- .digest("hex");
+ const crypto = yield* Crypto.Crypto;
+ const cacheKey = yield* crypto
+ .digest(
+ "SHA-256",
+ new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`),
+ )
+ .pipe(Effect.map(Hex.encode), Effect.orDie);
const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
if (yield* existingFile(cachePath)) return cachePath;
@@ -185,7 +190,7 @@ const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUnc
yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
const temporaryPath = path.join(
cacheDirectory,
- `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID()}.png`,
+ `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}.png`,
);
yield* commandOutput("/usr/bin/sips", [
"-z",
diff --git a/apps/server/src/cli/app.ts b/apps/server/src/cli/app.ts
index 35fe0489f52..d9ad57f5127 100644
--- a/apps/server/src/cli/app.ts
+++ b/apps/server/src/cli/app.ts
@@ -1,5 +1,4 @@
// @effect-diagnostics globalTimers:off -- The Node socket client owns its response deadline and clears it on every completion path.
-import * as NodeCrypto from "node:crypto";
import * as NodeNet from "node:net";
import * as NodeOS from "node:os";
@@ -18,6 +17,7 @@ import {
} from "@t3tools/shared/hostProcess";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
@@ -212,9 +212,11 @@ const runAppCommand = Effect.fn("cli.app")(function* (flags: {
userId,
joinPath: path.join,
}).address;
+ const crypto = yield* Crypto.Crypto;
+ const requestId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const request: DesktopAppActivationRequest = {
version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
- requestId: NodeCrypto.randomUUID(),
+ requestId,
type: "open-workspace",
workspaceRoot,
platform: hostPlatform,
diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts
index f9ad91087c3..e1ac55edc3f 100644
--- a/apps/server/src/device/SshDeviceHost.ts
+++ b/apps/server/src/device/SshDeviceHost.ts
@@ -1,4 +1,3 @@
-import * as NodeCrypto from "node:crypto";
import {
type DeviceHostSummary,
DevicePlatformAvailability,
@@ -9,6 +8,7 @@ import {
import { runSshCommand, baseSshArgs, resolveSshCommand } from "@t3tools/ssh/command";
import * as NetService from "@t3tools/shared/Net";
import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
+import * as Crypto from "effect/Crypto";
import * as Exit from "effect/Exit";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -17,6 +17,7 @@ import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
+import * as Hex from "effect/encoding/Hex";
import * as HttpClient from "effect/http/HttpClient";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
@@ -79,10 +80,11 @@ const ownerFor = Effect.fn("SshDeviceHost.ownerFor")(function* (hostId: string)
const environmentId = yield* fs
.readFileString(server.environmentIdPath)
.pipe(Effect.orElseSucceed(() => server.stateDir));
- return NodeCrypto.createHash("sha256")
- .update(`${environmentId}\0${server.stateDir}\0${hostId}`)
- .digest("hex")
- .slice(0, 24);
+ const crypto = yield* Crypto.Crypto;
+ const owner = yield* crypto
+ .digest("SHA-256", new TextEncoder().encode(`${environmentId}\0${server.stateDir}\0${hostId}`))
+ .pipe(Effect.map(Hex.encode), Effect.orDie);
+ return owner.slice(0, 24);
});
export const probe = Effect.fn("SshDeviceHost.probe")(function* (
@@ -125,6 +127,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
const net = yield* NetService.NetService;
const http = yield* HttpClient.HttpClient;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const crypto = yield* Crypto.Crypto;
const parentScope = yield* Scope.Scope;
const ssh = yield* resolveSshCommand;
const owner = yield* ownerFor(config.id);
@@ -135,6 +138,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
| FileSystem.FileSystem
| Path.Path
| ChildProcessSpawner.ChildProcessSpawner
+ | Crypto.Crypto
| ServerConfig.ServerConfig
>,
) =>
@@ -143,6 +147,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig.ServerConfig, server),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ Effect.provideService(Crypto.Crypto, crypto),
);
const lock = yield* Semaphore.make(1);
let stopped = false;
diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts
index 377956eb620..1ff48ab7eb5 100644
--- a/apps/server/src/mcp/McpHttpServer.ts
+++ b/apps/server/src/mcp/McpHttpServer.ts
@@ -1,7 +1,7 @@
-import * as NodeCrypto from "node:crypto";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -334,8 +334,10 @@ const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const millis = yield* Clock.currentTimeMillis;
+ const crypto = yield* Crypto.Crypto;
// Two saves in the same millisecond must not overwrite each other.
- const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
+ const unique = (yield* crypto.randomUUIDv4.pipe(Effect.orDie)).slice(0, 8);
+ const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${unique}.png`;
const screenshotPath = path.join(config.browserArtifactsDir, fileName);
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(
Effect.andThen(fileSystem.writeFile(screenshotPath, data)),
@@ -387,7 +389,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
// The MCP tool runner only supplies the client, so hand the save path its services here.
const saveServices = yield* Effect.context<
- ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path
+ ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path | Crypto.Crypto
>();
const built = yield* PreviewSnapshotToolkit;
const tool = PreviewSnapshotTool;
diff --git a/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts b/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts
index 83b6fb3d556..838c25efa2b 100644
--- a/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts
@@ -1,3 +1,4 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { expect, it } from "@effect/vitest";
import {
DEFAULT_SERVER_SETTINGS,
@@ -45,7 +46,7 @@ it.effect.each([
capabilities: new Set(effective.enableAgentBrowserAccess ? ["preview"] : []),
issuedAt: 0,
};
- const manager = yield* Preview.make;
+ const manager = yield* Preview.make.pipe(Effect.provide(NodeCrypto.layer));
const tab = yield* manager.open({ threadId, url: "http://localhost:3000" });
const layerDependencies = Layer.mergeAll(
Layer.succeed(Preview.PreviewManager, manager),
diff --git a/apps/server/src/preview/Manager.test.ts b/apps/server/src/preview/Manager.test.ts
index d1fc142502d..cdf4a5af828 100644
--- a/apps/server/src/preview/Manager.test.ts
+++ b/apps/server/src/preview/Manager.test.ts
@@ -1,7 +1,10 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { it } from "@effect/vitest";
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
import { PreviewUrlNormalizationError } from "@t3tools/shared/preview";
-import { Effect, PubSub } from "effect";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as PubSub from "effect/PubSub";
import { expect } from "vite-plus/test";
import * as PreviewManager from "./Manager.ts";
@@ -35,7 +38,7 @@ const collectEvents = Effect.gen(function* () {
return collector;
}).pipe(Effect.withSpan("preview.test.collectEvents"));
-it.layer(PreviewManager.layer)("PreviewManager", (it) => {
+it.layer(PreviewManager.layer.pipe(Layer.provide(NodeCrypto.layer)))("PreviewManager", (it) => {
it.effect("opens a session and emits opened with normalized URL", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
diff --git a/apps/server/src/preview/Manager.ts b/apps/server/src/preview/Manager.ts
index a5f5cba9ccd..3a1f870e390 100644
--- a/apps/server/src/preview/Manager.ts
+++ b/apps/server/src/preview/Manager.ts
@@ -31,8 +31,8 @@ import {
newPreviewTabId,
normalizePreviewUrl,
} from "@t3tools/shared/preview";
-import * as NodeCrypto from "node:crypto";
import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -155,7 +155,8 @@ const buildIdleSnapshot = (input: {
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* PreviewManagerMake() {
- const serverEpoch = NodeCrypto.randomUUID();
+ const crypto = yield* Crypto.Crypto;
+ const serverEpoch = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
// Unbounded PubSub is fine here — events are tiny and we don't want to
// block publishers if a subscriber is slow. WS clients backpressure on
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
index 85af1b3e343..01976a17359 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
@@ -1,3 +1,4 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it, vi } from "@effect/vitest";
import { ProjectId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -64,6 +65,7 @@ it.effect("resolves setup scripts through the standalone project service", () =>
}),
Layer.mock(TerminalManager.TerminalManager)({ open, write, subscribe }),
ServerSettings.layerTest(),
+ NodeCrypto.layer,
),
),
);
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts
index 956733ba850..7b101226d5d 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts
@@ -5,10 +5,10 @@ import {
resolveProjectScripts,
setupProjectScript,
} from "@t3tools/shared/projectScripts";
-import * as NodeCrypto from "node:crypto";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -201,6 +201,7 @@ export const make = Effect.gen(function* () {
const projects = yield* ProjectService.ProjectService;
const terminalManager = yield* TerminalManager.TerminalManager;
const serverSettings = yield* ServerSettings.ServerSettingsService;
+ const crypto = yield* Crypto.Crypto;
const completionShell = resolveCompletionShell(
yield* HostProcessPlatform,
yield* HostProcessEnvironment,
@@ -367,7 +368,9 @@ export const make = Effect.gen(function* () {
COLORTERM: "",
};
const observe = input.observeCompletion;
- const completionToken = observe ? NodeCrypto.randomUUID().replaceAll("-", "") : null;
+ const completionToken = observe
+ ? (yield* crypto.randomUUIDv4.pipe(Effect.orDie)).replaceAll("-", "")
+ : null;
const commandLine =
observe && completionToken
? wrapCommandForCompletion(
diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.ts
index 5b06bf70209..b5f30c2e54f 100644
--- a/apps/server/src/provider/CodexChatGptAuth.ts
+++ b/apps/server/src/provider/CodexChatGptAuth.ts
@@ -12,6 +12,7 @@ import { codexCallbackUrl } from "@t3tools/shared/codexAuthHandoff";
import * as Clock from "effect/Clock";
import * as Cause from "effect/Cause";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
+import * as Crypto from "effect/Crypto";
import * as Exit from "effect/Exit";
import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
import * as Effect from "effect/Effect";
@@ -158,6 +159,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
options.instanceId,
);
const secrets = yield* ServerSecretStore.ServerSecretStore;
+ const crypto = yield* Crypto.Crypto;
const environmentLocks = sessionLocks.get(secrets) ?? new Map<string, Semaphore.Semaphore>();
sessionLocks.set(secrets, environmentLocks);
const lock = environmentLocks.get(store.binding.key) ?? (yield* Semaphore.make(1));
@@ -306,7 +308,10 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
savedConnectionCount: savedConnections.size,
unidentifiedConnectedConnectionCount,
};
- }).pipe(Effect.provideService(ServerSecretStore.ServerSecretStore, secrets));
+ }).pipe(
+ Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
+ Effect.provideService(Crypto.Crypto, crypto),
+ );
const saveRegistration = Effect.fnUntraced(function* (profile: typeof Registration.Type) {
const saved = yield* readRegistrations;
profile = {
diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts
index e84e265b8c5..688ac83db42 100644
--- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts
+++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts
@@ -199,6 +199,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
const serverConfig = yield* ServerConfig.ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
+ const crypto = yield* Crypto.Crypto;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
@@ -388,6 +389,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, pathService),
Effect.provideService(HttpClient.HttpClient, httpClient),
+ Effect.provideService(Crypto.Crypto, crypto),
Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
);
diff --git a/apps/server/src/provider/ProviderCredentialStore.test.ts b/apps/server/src/provider/ProviderCredentialStore.test.ts
index 780d39c777f..2833eca65d2 100644
--- a/apps/server/src/provider/ProviderCredentialStore.test.ts
+++ b/apps/server/src/provider/ProviderCredentialStore.test.ts
@@ -1,3 +1,4 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -35,6 +36,11 @@ it.effect("isolates provider bindings and preserves opaque credentials", () =>
assert.isTrue(Option.isNone(yield* b.get));
assert.isTrue(Option.isNone(yield* c.get));
assert.isFalse(a.binding.key.includes("/"));
+ // Stored credentials are found by this name, so it must not change between releases.
+ assert.strictEqual(
+ a.binding.key,
+ "provider-auth-db3cc9436c8272847fe0c152ba8b0d4695af90acd916f555649e17ba6efe6094",
+ );
const long = yield* ProviderCredentialStore.make("a".repeat(64), "b".repeat(64)).pipe(
Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
);
@@ -45,5 +51,5 @@ it.effect("isolates provider bindings and preserves opaque credentials", () =>
assert.notStrictEqual(delimiter.binding.key, a.binding.key);
yield* a.remove;
assert.isTrue(Option.isNone(yield* a.get));
- }),
+ }).pipe(Effect.provide(NodeCrypto.layer)),
);
diff --git a/apps/server/src/provider/ProviderCredentialStore.ts b/apps/server/src/provider/ProviderCredentialStore.ts
index 259b441654c..a71cffd35df 100644
--- a/apps/server/src/provider/ProviderCredentialStore.ts
+++ b/apps/server/src/provider/ProviderCredentialStore.ts
@@ -1,5 +1,6 @@
-import * as NodeCrypto from "node:crypto";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
+import * as Hex from "effect/encoding/Hex";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
/** A provider binding stores opaque bytes; only its adapter decodes or refreshes them. */
@@ -8,10 +9,12 @@ export const make = Effect.fn("ProviderCredentialStore.make")(function* (
bindingId: string,
) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
+ const crypto = yield* Crypto.Crypto;
// Hash the tuple so arbitrary bindings cannot escape or exceed a filename.
- const key = `provider-auth-${NodeCrypto.createHash("sha256")
- .update(`${driver.length}:${driver}${bindingId}`)
- .digest("hex")}`;
+ const bindingHash = yield* crypto
+ .digest("SHA-256", new TextEncoder().encode(`${driver.length}:${driver}${bindingId}`))
+ .pipe(Effect.map(Hex.encode), Effect.orDie);
+ const key = `provider-auth-${bindingHash}`;
return {
binding: { owner: "t3" as const, key },
get: secrets.get(key),
diff --git a/apps/server/src/provider/openCodeUsageLimits.ts b/apps/server/src/provider/openCodeUsageLimits.ts
index 194f7be5c2f..80a44821ac8 100644
--- a/apps/server/src/provider/openCodeUsageLimits.ts
+++ b/apps/server/src/provider/openCodeUsageLimits.ts
@@ -1,13 +1,14 @@
import * as NodeOS from "node:os";
-import * as NodeCrypto from "node:crypto";
import type { ServerProviderUsageWindow } from "@t3tools/contracts";
+import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import * as Hex from "effect/encoding/Hex";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import {
@@ -96,15 +97,16 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
},
];
+ const crypto = yield* Crypto.Crypto;
+ // Go's usage response has no account ID. An unkeyed hash matches across
+ // environments without a shared secret. It permits offline guesses, but
+ // Go keys are randomly generated.
+ const credentialFingerprint = yield* crypto
+ .digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
+ .pipe(Effect.map(Hex.encode), Effect.orDie);
return {
...makeUsageLimits({ checkedAt, windows }),
- // Go's usage response has no account ID. An unkeyed hash matches across
- // environments without a shared secret. It permits offline guesses, but
- // Go keys are randomly generated.
- credentialFingerprint: NodeCrypto.createHash("sha256")
- .update("opencode-go\0")
- .update(apiKey)
- .digest("hex"),
+ credentialFingerprint,
};
}).pipe(
Effect.timeout("5 seconds"),
diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
index b614cbd4ee7..44730cf1335 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
@@ -1,3 +1,4 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { afterEach, assert, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Clock from "effect/Clock";
@@ -65,6 +66,7 @@ const layer = it.layer(
}),
),
Layer.provideMerge(GitHubGraphQlBudget.layer),
+ Layer.provide(NodeCrypto.layer),
),
);
@@ -247,7 +249,7 @@ it.effect(
);
const cli = yield* GitHubPullRequestCli.make.pipe(
Effect.provideService(GitHubCli.GitHubCli, github),
- Effect.provide(GitHubGraphQlBudget.layer),
+ Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, NodeCrypto.layer)),
);
const input = { cwd: "/repo", host: "github.com" };
const first = yield* cli.withVerifiedCredential(input, (identity) =>
diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.ts
index 25c37922845..a860ccdc047 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts
@@ -4,7 +4,7 @@ import { runGitHubStackAction, type GitHubStackActionError } from "./githubStack
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Clock from "effect/Clock";
-import * as NodeCrypto from "node:crypto";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Exit from "effect/Exit";
@@ -15,6 +15,7 @@ import * as RequestResolver from "effect/RequestResolver";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
+import * as Hex from "effect/encoding/Hex";
import {
resolvePullRequestAuthorFilter,
PositiveInt,
@@ -1148,6 +1149,7 @@ function actionArgs(
export const make = Effect.gen(function* () {
const github = yield* GitHubCli.GitHubCli;
const graphQlBudget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
+ const crypto = yield* Crypto.Crypto;
const revalidateChecks = yield* makeChecksRevalidator;
const routingIdentities = new Map<
string,
@@ -1184,7 +1186,10 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(unavailable))).stdout.trim();
if (!token) return yield* unavailable();
- const key = `${host}:${NodeCrypto.createHash("sha256").update(token).digest("hex")}`;
+ const tokenHash = yield* crypto
+ .digest("SHA-256", new TextEncoder().encode(token))
+ .pipe(Effect.map(Hex.encode), Effect.orDie);
+ const key = `${host}:${tokenHash}`;
const credential = { host, token: Redacted.make(token), credentialFingerprint: key };
// A cold page may ask several times. Wait per credential and check again after the
// first verification; cancellation releases the next waiter without losing its request.
diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts
index 4d9390b159f..92d8e98313f 100644
--- a/apps/server/src/vcs/GitVcsDriver.ts
+++ b/apps/server/src/vcs/GitVcsDriver.ts
@@ -1,7 +1,7 @@
-import * as NodeCrypto from "node:crypto";
import * as NodeBuffer from "node:buffer";
import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -536,6 +536,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsProcess = yield* VcsProcess.VcsProcess;
+ const crypto = yield* Crypto.Crypto;
const capabilities = {
kind: "git" as const,
supportsWorktrees: true,
@@ -811,10 +812,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
"sparse.expectFilesOutsideOfPatterns=false",
];
const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
- const tempIndexPath = path.join(
- gitCommonDir,
- `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
- );
+ const indexId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
+ const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 3f94cb72aa7..c98daa92042 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1,7 +1,6 @@
import { OrchestrationDispatchCommandError } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
-import * as NodeCrypto from "node:crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -1469,7 +1468,7 @@ const layerWsRpc = (
provider?.models.find((candidate) => candidate.isDefault)?.slug ??
provider?.models[0]?.slug ??
"default";
- const commandId = CommandId.make(NodeCrypto.randomUUID());
+ const commandId = CommandId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie));
const launched = yield* Effect.result(
startup.enqueueCommand(
threadLaunch.launch({