Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 1cb9811e93 test(mobile): retain false prefetch coverage
Co-authored-by: codex <[email protected]>
2026-06-20 08:25:47 -07:00
Julius Marmingeandcodex a2b6fd8274 Structure mobile file rendering errors
Co-authored-by: codex <[email protected]>
2026-06-20 08:17:23 -07:00
Julius Marmingeandcodex 97e5cd3bf7 [codex] align server auth Effect services (#3180)
Co-authored-by: codex <[email protected]>
2026-06-20 01:34:52 -07:00
Julius Marmingeandcodex b19fc1b87b [codex] refactor desktop Electron Effect services (#3178)
Co-authored-by: codex <[email protected]>
2026-06-20 01:24:04 -07:00
Julius Marmingeandcodex 2fa37ec183 [codex] Enforce canonical Node namespace imports (#3238)
Co-authored-by: codex <[email protected]>
2026-06-20 01:06:37 -07:00
ss db27502aff [fix/feat:ui] Capitalize Work Log heading (#3228) 2026-06-20 00:52:38 -07:00
ss 6c5fb7930d [fix/feat:ui] Use shared button for model favorites (#3223) 2026-06-20 00:40:57 -07:00
ss 30acfa9c51 [fix/feat:ui] Fix clipped chatbar provider badge (#3224) 2026-06-20 00:39:54 -07:00
Julius Marmingeandcodex f58b6da230 [codex] Preserve workspace RPC error messages (#3222)
Co-authored-by: codex <[email protected]>
2026-06-20 00:39:04 -07:00
Julius Marmingeandcodex 9a1c4875a3 [codex] Remove redundant Effect type annotations (#3229)
Co-authored-by: codex <[email protected]>
2026-06-20 00:37:47 -07:00
Julius Marmingeandcodex 7eda6ba5fc [codex] Migrate desktop shell and SSH Effect services (#3194)
Co-authored-by: codex <[email protected]>
2026-06-20 00:36:41 -07:00
Julius Marmingeandcodex c00e721c04 [codex] Refactor client runtime Effect services (#3200)
Co-authored-by: codex <[email protected]>
2026-06-20 07:17:29 +00:00
Julius Marmingeandcodex b0a3a50448 [codex] Refactor project and workspace Effect services (#3190)
Co-authored-by: codex <[email protected]>
2026-06-20 00:12:46 -07:00
Julius MarmingeandJulius Marminge 79c57170c7 [codex] Make settings environment-scoped by default (#3216)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-20 00:08:32 -07:00
Julius Marmingeandcodex 3900c45f25 Preserve observable Effect error semantics (#3220)
Co-authored-by: codex <[email protected]>
2026-06-19 23:49:51 -07:00
Wout StiensandCodex 8d61172f8b Cosmetic fix: Sync web title with nightly server branding (#3219)
Co-authored-by: Codex <[email protected]>
2026-06-19 23:49:33 -07:00
Julius MarmingeandJulius Marminge dc82f792c3 [codex] Close right panel when its last tab closes (#3221)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-19 23:48:41 -07:00
Julius MarmingeandJulius Marminge 335e0b59ea Fix PR creation from origin-based worktrees (#3218)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-19 23:38:54 -07:00
Julius Marmingeandcodex 2fbbe68c24 Clarify Effect error discriminator modeling (#3217)
Co-authored-by: codex <[email protected]>
2026-06-19 23:27:15 -07:00
236 changed files with 6118 additions and 4521 deletions

No files matched your search

@@ -27,7 +27,7 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts` and `electron`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
@@ -46,10 +46,12 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling an error. Flag error classes whose only meaningful field is `cause`, or whose `message` merely stringifies an opaque cause.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
@@ -1,23 +1,23 @@
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { compile } from "tailwindcss";
const directory = dirname(fileURLToPath(import.meta.url));
const appRoot = join(directory, "..");
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = createRequire(import.meta.url);
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const appRoot = NodePath.join(directory, "..");
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = NodeModule.createRequire(import.meta.url);
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
readFile(sourcePath, "utf8"),
readFile(preloadPath, "utf8"),
readFile(join(tailwindRoot, "theme.css"), "utf8"),
readFile(join(tailwindRoot, "preflight.css"), "utf8"),
NodeFSP.readFile(sourcePath, "utf8"),
NodeFSP.readFile(preloadPath, "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
]);
const candidates = new Set(
@@ -37,4 +37,4 @@ const encodedCss = `'${css
.replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
await writeFile(outputPath, moduleSource);
await NodeFSP.writeFile(outputPath, moduleSource);
+13 -9
View File
@@ -1,7 +1,7 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import { join } from "node:path";
import * as NodePath from "node:path";
import {
desktopDir,
@@ -64,7 +64,7 @@ function killChildTreeByPid(pid, signal) {
return;
}
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
@@ -72,7 +72,9 @@ function cleanupStaleDevApps() {
return;
}
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
stdio: "ignore",
});
}
function startApp() {
@@ -87,7 +89,7 @@ function startApp() {
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = spawn(electronCommand.electronPath, electronCommand.args, {
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -180,8 +182,8 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(
join(desktopDir, directory),
const watcher = NodeFS.watch(
NodePath.join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
@@ -202,7 +204,9 @@ function killChildTree(signal) {
}
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
stdio: "ignore",
});
}
async function shutdown(exitCode) {
+89 -73
View File
@@ -1,29 +1,18 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import { spawnSync } from "node:child_process";
import {
copyFileSync,
chmodSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const devBundleIdSuffix = basename(repoRoot)
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
export const desktopDir = NodePath.resolve(__dirname, "..");
const repoRoot = NodePath.resolve(desktopDir, "..", "..");
const devBundleIdSuffix = NodePath.basename(repoRoot)
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "");
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
@@ -32,22 +21,35 @@ export const APP_BUNDLE_ID = isDevelopment
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
"assets",
"dev",
"blueprint-macos-1024.png",
);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
});
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
encoding: "utf8",
});
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (insertResult.status === 0) {
return;
}
@@ -58,16 +60,24 @@ function setPlistString(plistPath, key, value) {
function setPlistJson(plistPath, key, value) {
const serialized = JSON.stringify(value);
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
if (insertResult.status === 0) {
return;
}
@@ -77,7 +87,7 @@ function setPlistJson(plistPath, key, value) {
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
@@ -91,7 +101,7 @@ function shellSingleQuote(value) {
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
const envEntries = [
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
@@ -101,7 +111,7 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
writeFileSync(
NodeFS.writeFileSync(
targetBinaryPath,
[
"#!/bin/sh",
@@ -110,7 +120,7 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
"",
].join("\n"),
);
chmodSync(targetBinaryPath, 0o755);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
function registerMacLauncherBundle(appBundlePath) {
@@ -140,21 +150,24 @@ function registerMacLauncherBundle(appBundlePath) {
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
if (
NodeFS.existsSync(generatedIconPath) &&
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
NodeFS.mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
@@ -164,7 +177,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
@@ -174,7 +187,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
@@ -187,12 +200,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
@@ -204,9 +217,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
},
]);
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
@@ -218,7 +231,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
];
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
const infoPlistPath = join(
const infoPlistPath = NodePath.join(
appBundlePath,
"Contents",
"Frameworks",
@@ -226,7 +239,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
"Contents",
"Info.plist",
);
if (!existsSync(infoPlistPath)) {
if (!NodeFS.existsSync(infoPlistPath)) {
continue;
}
@@ -242,34 +255,34 @@ function patchHelperBundleInfoPlists(appBundlePath) {
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = join(runtimeDir, "metadata.json");
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
NodeFS.mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
appBundleId: APP_BUNDLE_ID,
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
};
const currentMetadata = readJson(metadataPath);
if (
existsSync(targetBinaryPath) &&
NodeFS.existsSync(targetBinaryPath) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
@@ -277,18 +290,21 @@ function buildMacLauncher(electronBinaryPath) {
return targetBinaryPath;
}
rmSync(targetAppBundlePath, { recursive: true, force: true });
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
// verbatimSymlinks keeps the framework's relative symlinks intact
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
// rewrites them to absolute paths into node_modules, which escape the
// bundle and crash sandboxed helper processes (icudtl.dat not found).
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
recursive: true,
verbatimSymlinks: true,
});
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
@@ -299,9 +315,9 @@ function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
return true;
}
const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
try {
const sandboxStat = statSync(sandboxPath);
const sandboxStat = NodeFS.statSync(sandboxPath);
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
} catch {
return false;
@@ -322,7 +338,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
export function resolveElectronPath() {
ensureElectronRuntime();
const require = createRequire(import.meta.url);
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (hostPlatform !== "darwin") {
@@ -345,11 +361,11 @@ export function resolveDevProtocolClient() {
return null;
}
const require = createRequire(import.meta.url);
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
appBundleId: APP_BUNDLE_ID,
};
}
@@ -1,14 +1,14 @@
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { arch, platform, tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
const require = createRequire(import.meta.url);
const require = NodeModule.createRequire(import.meta.url);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostPlatform = platform();
const hostPlatform = NodeOS.platform();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostArch = arch();
const hostArch = NodeOS.arch();
function getPlatformPath() {
switch (hostPlatform) {
@@ -27,26 +27,28 @@ function getPlatformPath() {
function ensureExecutable(filePath) {
if (hostPlatform !== "win32") {
chmodSync(filePath, 0o755);
NodeFS.chmodSync(filePath, 0o755);
}
}
function repairPathFile(electronDir, platformPath) {
const pathFile = join(electronDir, "path.txt");
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
const pathFile = NodePath.join(electronDir, "path.txt");
const currentPath = NodeFS.existsSync(pathFile)
? NodeFS.readFileSync(pathFile, "utf8")
: undefined;
if (currentPath !== platformPath) {
writeFileSync(pathFile, platformPath);
NodeFS.writeFileSync(pathFile, platformPath);
}
}
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [join(electronDir, "dist", platformPath)];
const paths = [NodePath.join(electronDir, "dist", platformPath)];
if (hostPlatform === "darwin") {
paths.push(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
NodePath.join(
electronDir,
"dist",
"Electron.app",
@@ -66,7 +68,7 @@ function isMachO(filePath) {
return true;
}
const result = spawnSync("file", ["-b", filePath], {
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
encoding: "utf8",
});
@@ -75,7 +77,7 @@ function isMachO(filePath) {
function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !existsSync(runtimePath);
return !NodeFS.existsSync(runtimePath);
});
}
@@ -85,8 +87,8 @@ function invalidRuntimePaths(electronDir, platformPath) {
}
return [
join(electronDir, "dist", platformPath),
join(
NodePath.join(electronDir, "dist", platformPath),
NodePath.join(
electronDir,
"dist",
"Electron.app",
@@ -95,11 +97,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
"Electron Framework.framework",
"Electron Framework",
),
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
}
function runChecked(command, args) {
const result = spawnSync(command, args, {
const result = NodeChildProcess.spawnSync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
@@ -114,8 +116,8 @@ function runChecked(command, args) {
}
function installElectronRuntime(electronDir, version) {
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
try {
runChecked("curl", [
@@ -125,34 +127,34 @@ function installElectronRuntime(electronDir, version) {
zipPath,
]);
if (hostPlatform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]);
} else {
runChecked("python3", [
"-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath,
join(electronDir, "dist"),
NodePath.join(electronDir, "dist"),
]);
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}
export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = dirname(electronPackageJsonPath);
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = NodePath.dirname(electronPackageJsonPath);
const platformPath = getPlatformPath();
const electronPath = join(electronDir, "dist", platformPath);
const electronPath = NodePath.join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (existsSync(join(electronDir, "dist"))) {
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
}
rmSync(join(electronDir, "path.txt"), { force: true });
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
installElectronRuntime(electronDir, electronPackageJson.version);
}
+7 -7
View File
@@ -1,16 +1,16 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodeChildProcess from "node:child_process";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const desktopDir = NodePath.resolve(__dirname, "..");
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+2 -2
View File
@@ -1,4 +1,4 @@
import { spawn } from "node:child_process";
import * as NodeChildProcess from "node:child_process";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
@@ -6,7 +6,7 @@ const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+8 -8
View File
@@ -1,13 +1,13 @@
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodePath from "node:path";
import * as NodeTimersPromises from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await FileSystem.access(filePath);
await NodeFSP.access(filePath);
return true;
} catch {
return false;
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = Net.createConnection({ host, port });
const socket = NodeNet.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
@@ -114,6 +114,6 @@ export async function waitForResources({
);
}
await Timers.setTimeout(intervalMs);
await NodeTimersPromises.setTimeout(intervalMs);
}
}
@@ -237,7 +237,6 @@ describe("DesktopConnectionCatalogStore", () => {
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
);
assert.equal(error.operation, "decode-catalog-document");
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
@@ -272,7 +271,6 @@ describe("DesktopConnectionCatalogStore", () => {
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.operation, "read-catalog");
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
@@ -368,7 +366,6 @@ describe("DesktopConnectionCatalogStore", () => {
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
);
assert.equal(error.operation, "decode-encrypted-catalog");
assert.equal(error.resource, "encryptedCatalog");
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
@@ -92,7 +92,6 @@ const writeError = (
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
"DesktopConnectionCatalogStoreDecodeError",
{
operation: Schema.Literal("decode-encrypted-catalog"),
resource: Schema.Literal("encryptedCatalog"),
catalogPath: Schema.String,
cause: Schema.Defect(),
@@ -106,7 +105,6 @@ export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedError
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
"DesktopConnectionCatalogStoreReadError",
{
operation: Schema.Literal("read-catalog"),
catalogPath: Schema.String,
cause: Schema.Defect(),
},
@@ -119,7 +117,6 @@ export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorCl
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
"DesktopConnectionCatalogStoreDocumentDecodeError",
{
operation: Schema.Literal("decode-catalog-document"),
catalogPath: Schema.String,
cause: Schema.Defect(),
},
@@ -167,16 +164,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
| ElectronSafeStorage.ElectronSafeStorageError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
| DesktopConnectionCatalogStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
>;
readonly clear: Effect.Effect<void>;
}
@@ -190,7 +184,6 @@ function decodeSecretBytes(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDecodeError({
operation: "decode-encrypted-catalog",
resource: "encryptedCatalog",
catalogPath,
cause,
@@ -212,7 +205,6 @@ const readDocument = (
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopConnectionCatalogStoreReadError({
operation: "read-catalog",
catalogPath,
cause: error,
}),
@@ -226,7 +218,6 @@ const readDocument = (
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDocumentDecodeError({
operation: "decode-catalog-document",
catalogPath,
cause,
}),
+3 -3
View File
@@ -8,7 +8,7 @@ import * as Scope from "effect/Scope";
import type * as Electron from "electron";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -37,7 +37,7 @@ export class DesktopLifecycle extends Context.Service<
>()("@t3tools/desktop/app/DesktopLifecycle") {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
DesktopObservability.makeComponentLogger("desktop-lifecycle");
makeComponentLogger("desktop-lifecycle");
function addScopedListener<Args extends ReadonlyArray<unknown>>(
target: unknown,
@@ -122,7 +122,7 @@ function quitFromSignal(
);
}
const make = DesktopLifecycle.of({
export const make = DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
+1 -5
View File
@@ -50,11 +50,7 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
const readPersistedOtlpTracesUrl: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
@@ -54,11 +54,7 @@ const { logWarning: logBackendConfigurationWarning } = DesktopObservability.make
"desktop-backend-configuration",
);
const readPersistedBackendObservabilitySettings: Effect.Effect<
BackendObservabilitySettings,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const exists = yield* fileSystem
@@ -1,4 +1,4 @@
import { networkInterfaces } from "node:os";
import * as NodeOS from "node:os";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -27,7 +27,7 @@ export class DesktopNetworkInterfaces extends Context.Service<
export const make = (): DesktopNetworkInterfaces["Service"] =>
DesktopNetworkInterfaces.of({
read: Effect.sync(() => networkInterfaces()),
read: Effect.sync(() => NodeOS.networkInterfaces()),
});
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
+35 -36
View File
@@ -13,41 +13,40 @@ export interface ElectronAppMetadata {
readonly runningUnderArm64Translation: boolean;
}
export interface ElectronAppShape {
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"@t3tools/desktop/electron/ElectronApp",
) {}
export class ElectronApp extends Context.Service<
ElectronApp,
{
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronApp") {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
eventName: string,
@@ -63,7 +62,7 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
}),
).pipe(Effect.asVoid);
const make = ElectronApp.of({
export const make = ElectronApp.of({
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
+14 -15
View File
@@ -17,22 +17,21 @@ export interface ElectronDialogConfirmInput {
readonly message: string;
}
export interface ElectronDialogShape {
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
export class ElectronDialog extends Context.Service<
ElectronDialog,
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"@t3tools/desktop/electron/ElectronDialog",
) {}
const make = ElectronDialog.of({
export const make = ElectronDialog.of({
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({
+110 -112
View File
@@ -1,11 +1,11 @@
import type { ContextMenuItem } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
export interface ElectronMenuPosition {
readonly x: number;
@@ -23,19 +23,18 @@ export interface ElectronMenuTemplateInput {
readonly template: readonly Electron.MenuItemConstructorOptions[];
}
export interface ElectronMenuShape {
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"@t3tools/desktop/electron/ElectronMenu",
) {}
export class ElectronMenu extends Context.Service<
ElectronMenu,
{
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronMenu") {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
@@ -80,114 +79,113 @@ const normalizePosition = (
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
export const layer = Layer.effect(
ElectronMenu,
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
}
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
};
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return destructiveMenuIconCache;
};
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
template.push(itemOption);
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return template;
};
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
template.push(itemOption);
}
return template;
};
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
return;
}
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
});
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
}),
);
export const layer = Layer.effect(ElectronMenu, make);
+17 -17
View File
@@ -1,8 +1,8 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
@@ -23,13 +23,14 @@ export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export class ElectronProtocolRegistrationError extends Data.TaggedError(
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
"ElectronProtocolRegistrationError",
)<{
readonly scheme: string;
readonly cause: unknown;
}> {
override get message() {
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register ${this.scheme}: protocol.`;
}
}
@@ -41,15 +42,14 @@ export interface DesktopProtocolRegistrationInput {
readonly clerkFrontendApiHostname: string | undefined;
}
export interface ElectronProtocolShape {
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export class ElectronProtocol extends Context.Service<
ElectronProtocol,
{
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronProtocol") {}
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
const clerkOrigin = input.clerkFrontendApiHostname
@@ -114,7 +114,7 @@ async function proxyRequest(
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
@@ -1,56 +1,69 @@
import * as Electron from "electron";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Schema from "effect/Schema";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
import * as Electron from "electron";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
};
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
"ElectronSafeStorageAvailabilityError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
return "Electron safe storage failed to check encryption availability.";
}
}
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
"ElectronSafeStorageEncryptError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
return "Electron safe storage failed to encrypt a string.";
}
}
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
"ElectronSafeStorageDecryptError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
return "Electron safe storage failed to decrypt a string.";
}
}
export interface ElectronSafeStorageShape {
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
export const ElectronSafeStorageError = Schema.Union([
ElectronSafeStorageAvailabilityError,
ElectronSafeStorageEncryptError,
ElectronSafeStorageDecryptError,
]);
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
ElectronSafeStorageShape
{
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
const make = ElectronSafeStorage.of({
export const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
+8 -9
View File
@@ -20,16 +20,15 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
}
}
export interface ElectronShellShape {
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
export const make = ElectronShell.of({
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false),
+9 -10
View File
@@ -6,17 +6,16 @@ import * as Scope from "effect/Scope";
import * as Electron from "electron";
export interface ElectronThemeShape {
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronTheme extends Context.Service<
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
) {}
const make = ElectronTheme.of({
export const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.suspend(() => {
@@ -73,6 +73,7 @@ describe("ElectronUpdater", () => {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates.");
}
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
+57 -46
View File
@@ -1,7 +1,7 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { autoUpdater } from "electron-updater";
@@ -10,67 +10,76 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
const electronUpdaterErrorFields = {
cause: Schema.Defect(),
};
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
"ElectronUpdaterCheckForUpdatesError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return "Electron updater failed to check for updates.";
}
}
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
"ElectronUpdaterDownloadUpdateError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return "Electron updater failed to download the update.";
}
}
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
"ElectronUpdaterQuitAndInstallError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return "Electron updater failed to quit and install the update.";
}
}
export type ElectronUpdaterError =
| ElectronUpdaterCheckForUpdatesError
| ElectronUpdaterDownloadUpdateError
| ElectronUpdaterQuitAndInstallError;
export const ElectronUpdaterError = Schema.Union([
ElectronUpdaterCheckForUpdatesError,
ElectronUpdaterDownloadUpdateError,
ElectronUpdaterQuitAndInstallError,
]);
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
export interface ElectronUpdaterShape {
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronUpdater extends Context.Service<
ElectronUpdater,
{
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronUpdater") {}
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"@t3tools/desktop/electron/ElectronUpdater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
export const make = ElectronUpdater.of({
setFeedURL: (options) =>
Effect.suspend(() => {
autoUpdater.setFeedURL(options);
@@ -136,4 +145,6 @@ export const layer = Layer.succeed(ElectronUpdater, {
}),
).pipe(Effect.asVoid);
},
} satisfies ElectronUpdaterShape);
});
export const layer = Layer.succeed(ElectronUpdater, make);
+29 -27
View File
@@ -1,43 +1,45 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
readonly cause: unknown;
}> {
override get message() {
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
"ElectronWindowCreateError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to create Electron BrowserWindow.";
}
}
export interface ElectronWindowShape {
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
export class ElectronWindow extends Context.Service<
ElectronWindow,
{
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
>()("@t3tools/desktop/electron/ElectronWindow") {}
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"@t3tools/desktop/electron/ElectronWindow",
) {}
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+2 -2
View File
@@ -22,7 +22,7 @@ import {
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { pathToFileURL } from "node:url";
import * as NodeURL from "node:url";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
@@ -196,7 +196,7 @@ export const getPreviewConfig = DesktopIpc.makeIpcMethod({
return {
partition: yield* manager.getBrowserPartition(environmentId),
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
};
}),
});
+2 -2
View File
@@ -19,7 +19,7 @@ import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts";
import * as ElectronMenu from "./electron/ElectronMenu.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
import * as DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
import * as ElectronTheme from "./electron/ElectronTheme.ts";
import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
@@ -106,7 +106,7 @@ const electronLayer = Layer.mergeAll(
ElectronDialog.layer,
ElectronMenu.layer,
ElectronProtocol.layer,
DesktopSecretStorage.layer,
ElectronSafeStorage.layer,
ElectronShell.layer,
ElectronTheme.layer,
ElectronUpdater.layer,
@@ -1,14 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { runInNewContext } from "node:vm";
import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeVM from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = createRequire(import.meta.url);
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
@@ -32,7 +32,11 @@ export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRunt
catch: (cause) => fail("resolvePackage", cause),
});
const coreBundle = yield* Effect.tryPromise({
try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
try: () =>
NodeFSP.readFile(
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
"utf8",
),
catch: (cause) => fail("readCoreBundle", cause),
});
const marker = "source3 = ";
@@ -53,7 +57,7 @@ export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRunt
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
@@ -241,7 +241,6 @@ describe("DesktopSavedEnvironments", () => {
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentSecretDecodeError);
assert.equal(error.operation, "decode-secret");
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
assert.equal(error.field, "encryptedBearerToken");
@@ -363,7 +362,6 @@ describe("DesktopSavedEnvironments", () => {
registryError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
assert.equal(registryError.operation, "decode-registry");
assert.equal(registryError.registryPath, environment.savedEnvironmentRegistryPath);
assert.exists(registryError.cause);
const secretError = yield* savedEnvironments
@@ -409,7 +407,6 @@ describe("DesktopSavedEnvironments", () => {
const error = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
assert.equal(error.operation, "read-registry");
assert.equal(error.registryPath, registryPath);
assert.strictEqual(error.cause, permissionError);
assert.equal(error.message, `Failed to read desktop saved environments at ${registryPath}.`);
@@ -106,7 +106,6 @@ const writeError = (
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
"DesktopSavedEnvironmentsReadError",
{
operation: Schema.Literal("read-registry"),
registryPath: Schema.String,
cause: Schema.Defect(),
},
@@ -119,7 +118,6 @@ export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<D
export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsDocumentDecodeError>()(
"DesktopSavedEnvironmentsDocumentDecodeError",
{
operation: Schema.Literal("decode-registry"),
registryPath: Schema.String,
cause: Schema.Defect(),
},
@@ -132,7 +130,6 @@ export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedEr
export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretDecodeError>()(
"DesktopSavedEnvironmentSecretDecodeError",
{
operation: Schema.Literal("decode-secret"),
environmentId: Schema.String,
registryPath: Schema.String,
field: Schema.Literal("encryptedBearerToken"),
@@ -155,13 +152,11 @@ export type DesktopSavedEnvironmentsMutationError =
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
| ElectronSafeStorage.ElectronSafeStorageError;
export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsMutationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
| ElectronSafeStorage.ElectronSafeStorageError;
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
@@ -248,7 +243,6 @@ function readRegistryDocument(
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopSavedEnvironmentsReadError({
operation: "read-registry",
registryPath,
cause: error,
}),
@@ -262,7 +256,6 @@ function readRegistryDocument(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsDocumentDecodeError({
operation: "decode-registry",
registryPath,
cause,
}),
@@ -329,7 +322,6 @@ function decodeSecretBytes(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretDecodeError({
operation: "decode-secret",
environmentId,
registryPath,
field: "encryptedBearerToken",
@@ -3,7 +3,8 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -19,13 +20,11 @@ interface WindowsProbeOptions {
readonly loadProfile: boolean;
}
export interface DesktopShellEnvironmentShape {
readonly installIntoProcess: Effect.Effect<void, never>;
}
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
DesktopShellEnvironmentShape
{
readonly installIntoProcess: Effect.Effect<void>;
}
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
const LOGIN_SHELL_ENV_NAMES = [
@@ -212,11 +211,7 @@ const readLoginShellEnvironment = (
timeout: LOGIN_SHELL_TIMEOUT,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath: Effect.Effect<
Option.Option<string>,
never,
ChildProcessSpawner.ChildProcessSpawner
> = runCommandOutput({
const readLaunchctlPath = runCommandOutput({
command: "/bin/launchctl",
args: ["getenv", "PATH"],
timeout: LAUNCHCTL_TIMEOUT,
@@ -336,20 +331,20 @@ const installShellEnvironment = (
return Effect.void;
};
export const layer = Layer.effect(
DesktopShellEnvironment,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return DesktopShellEnvironment.of({
installIntoProcess: installShellEnvironment({
env: process.env,
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
),
});
}),
);
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
installShellEnvironment({
env: process.env,
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
);
return DesktopShellEnvironment.of({ installIntoProcess });
});
export const layer = Layer.effect(DesktopShellEnvironment, make);
@@ -19,6 +19,20 @@ function makeTempHomeDir() {
}
describe("sshEnvironment", () => {
it("keeps prompt presentation diagnostics distinct from the legacy wrapper message", () => {
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
requestId: "prompt-1",
destination: "devbox",
cause: new Error("renderer send failed"),
});
assert.equal(cause.message, "Failed to present SSH password prompt for devbox.");
assert.equal(
DesktopSshEnvironment.toSshPasswordPromptError(cause).message,
"T3 Code window is not available for SSH authentication.",
);
});
it("treats password prompt timeouts as cancellable authentication prompts", () => {
assert.equal(
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(
@@ -104,7 +118,6 @@ describe("sshEnvironment", () => {
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
request: () => Effect.die("unexpected password prompt request"),
resolve: () => Effect.die("unexpected password prompt resolution"),
cancelPending: () => Effect.void,
}),
),
Layer.provideMerge(NodeServices.layer),
+61 -41
View File
@@ -4,11 +4,7 @@ import type {
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import {
SshPasswordPrompt,
type SshPasswordPromptShape,
type SshPasswordRequest,
} from "@t3tools/ssh/auth";
import * as SshAuth from "@t3tools/ssh/auth";
import { discoverSshHosts } from "@t3tools/ssh/config";
import {
SshCommandError,
@@ -19,14 +15,14 @@ import {
SshPasswordPromptError,
SshReadinessError,
} from "@t3tools/ssh/errors";
import { SshEnvironmentManager, type RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import * as SshTunnel from "@t3tools/ssh/tunnel";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
@@ -52,27 +48,25 @@ export type DesktopSshEnvironmentError =
| DesktopSshEnvironmentDiscoverError
| DesktopSshEnvironmentOperationError;
export interface DesktopSshEnvironmentShape {
readonly discoverHosts: (input?: {
readonly homeDir?: string;
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
}
export class DesktopSshEnvironment extends Context.Service<
DesktopSshEnvironment,
DesktopSshEnvironmentShape
{
readonly discoverHosts: (input?: {
readonly homeDir?: string;
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
}
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>;
}
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
@@ -88,27 +82,53 @@ export function isDesktopSshPasswordPromptCancellation(
);
}
function unexpectedPasswordPromptError(error: never): never {
throw new Error(`Unhandled desktop SSH password prompt error: ${String(error)}`);
}
export function toSshPasswordPromptError(
cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptRequestError,
): SshPasswordPromptError {
let message: string;
switch (cause._tag) {
case "DesktopSshPromptRequestIdGenerationError":
message = "Secure randomness is unavailable.";
break;
case "DesktopSshPromptWindowUnavailableError":
case "DesktopSshPromptPresentationError":
message = "T3 Code window is not available for SSH authentication.";
break;
case "DesktopSshPromptTimedOutError":
message = `SSH authentication timed out for ${cause.destination}.`;
break;
case "DesktopSshPromptCancelledError":
message = `SSH authentication cancelled for ${cause.destination}.`;
break;
case "DesktopSshPromptWindowClosedError":
message = "SSH authentication was cancelled because the app window closed.";
break;
case "DesktopSshPromptServiceStoppedError":
message = "SSH password prompt service stopped.";
break;
default:
return unexpectedPasswordPromptError(cause);
}
return new SshPasswordPromptError({ message, cause });
}
const makePasswordPrompt = (
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPromptsShape,
): SshPasswordPromptShape => ({
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPrompts["Service"],
): SshAuth.SshPasswordPrompt["Service"] => ({
isAvailable: true,
request: (request: SshPasswordRequest) =>
prompts.request(request).pipe(
Effect.mapError(
(cause) =>
new SshPasswordPromptError({
message: cause.message,
cause,
}),
),
),
request: (request: SshAuth.SshPasswordRequest) =>
prompts.request(request).pipe(Effect.mapError(toSshPasswordPromptError)),
});
const make = Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
export const make = Effect.gen(function* () {
const manager = yield* SshTunnel.SshEnvironmentManager;
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
const passwordPrompt = SshPasswordPrompt.of(makePasswordPrompt(prompts));
const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));
return DesktopSshEnvironment.of({
discoverHosts: (input) =>
@@ -120,7 +140,7 @@ const make = Effect.gen(function* () {
manager
.ensureEnvironment(target, ensureOptions)
.pipe(
Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.ensureEnvironment"),
),
@@ -128,7 +148,7 @@ const make = Effect.gen(function* () {
manager
.disconnectEnvironment(target)
.pipe(
Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
),
@@ -138,7 +158,7 @@ const make = Effect.gen(function* () {
export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
Layer.effect(DesktopSshEnvironment, make).pipe(
Layer.provide(
SshEnvironmentManager.layer({
SshTunnel.SshEnvironmentManager.layer({
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
@@ -9,7 +9,7 @@ import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
interface SentMessage {
@@ -111,7 +111,7 @@ describe("DesktopSshPasswordPrompts", () => {
assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0];
assert.ok(sent);
assert.equal(sent.channel, IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL);
assert.equal(sent.channel, SSH_PASSWORD_PROMPT_CHANNEL);
const request = sent.args[0] as { readonly requestId: string; readonly destination: string };
assert.equal(request.destination, "devbox");
assert.equal(testWindow.isRestored(), true);
+143 -95
View File
@@ -3,7 +3,6 @@ import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contract
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -11,93 +10,134 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../ipc/channels.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
export class DesktopSshPromptUnavailableError extends Data.TaggedError(
"DesktopSshPromptUnavailableError",
)<{
readonly reason: string;
}> {
override get message() {
return this.reason;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
"DesktopSshPromptRequestIdGenerationError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Secure randomness is unavailable.";
}
}
export class DesktopSshPromptWindowUnavailableError extends Data.TaggedError(
export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorClass<DesktopSshPromptWindowUnavailableError>()(
"DesktopSshPromptWindowUnavailableError",
)<{
readonly destination: string;
}> {
override get message() {
{
destination: Schema.String,
},
) {
override get message(): string {
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
export class DesktopSshPromptSendError extends Data.TaggedError("DesktopSshPromptSendError")<{
readonly requestId: string;
readonly destination: string;
readonly cause: unknown;
}> {
override get message() {
return WINDOW_UNAVAILABLE_MESSAGE;
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
"DesktopSshPromptPresentationError",
{
requestId: Schema.String,
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to present SSH password prompt for ${this.destination}.`;
}
}
export class DesktopSshPromptTimedOutError extends Data.TaggedError(
export class DesktopSshPromptTimedOutError extends Schema.TaggedErrorClass<DesktopSshPromptTimedOutError>()(
"DesktopSshPromptTimedOutError",
)<{
readonly requestId: string;
readonly destination: string;
}> {
override get message() {
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return `SSH authentication timed out for ${this.destination}.`;
}
}
export class DesktopSshPromptCancelledError extends Data.TaggedError(
export class DesktopSshPromptCancelledError extends Schema.TaggedErrorClass<DesktopSshPromptCancelledError>()(
"DesktopSshPromptCancelledError",
)<{
readonly requestId: string;
readonly destination: string;
readonly reason: string;
}> {
override get message() {
return this.reason;
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return `SSH authentication cancelled for ${this.destination}.`;
}
}
export class DesktopSshPromptInvalidRequestIdError extends Data.TaggedError(
export class DesktopSshPromptWindowClosedError extends Schema.TaggedErrorClass<DesktopSshPromptWindowClosedError>()(
"DesktopSshPromptWindowClosedError",
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return "SSH authentication was cancelled because the app window closed.";
}
}
export class DesktopSshPromptServiceStoppedError extends Schema.TaggedErrorClass<DesktopSshPromptServiceStoppedError>()(
"DesktopSshPromptServiceStoppedError",
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return "SSH password prompt service stopped.";
}
}
export class DesktopSshPromptInvalidRequestIdError extends Schema.TaggedErrorClass<DesktopSshPromptInvalidRequestIdError>()(
"DesktopSshPromptInvalidRequestIdError",
)<{
readonly requestId: string;
}> {
override get message() {
{
requestId: Schema.String,
},
) {
override get message(): string {
return "Invalid SSH password prompt id.";
}
}
export class DesktopSshPromptExpiredError extends Data.TaggedError("DesktopSshPromptExpiredError")<{
readonly requestId: string;
}> {
override get message() {
export class DesktopSshPromptExpiredError extends Schema.TaggedErrorClass<DesktopSshPromptExpiredError>()(
"DesktopSshPromptExpiredError",
{
requestId: Schema.String,
},
) {
override get message(): string {
return "SSH password prompt expired. Try connecting again.";
}
}
export type DesktopSshPasswordPromptRequestError =
| DesktopSshPromptUnavailableError
| DesktopSshPromptRequestIdGenerationError
| DesktopSshPromptWindowUnavailableError
| DesktopSshPromptSendError
| DesktopSshPromptPresentationError
| DesktopSshPromptTimedOutError
| DesktopSshPromptCancelledError;
| DesktopSshPromptCancelledError
| DesktopSshPromptWindowClosedError
| DesktopSshPromptServiceStoppedError;
export type DesktopSshPasswordPromptResolveError =
| DesktopSshPromptInvalidRequestIdError
@@ -107,28 +147,28 @@ export type DesktopSshPasswordPromptError =
| DesktopSshPasswordPromptRequestError
| DesktopSshPasswordPromptResolveError;
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is DesktopSshPromptCancelledError | DesktopSshPromptTimedOutError {
return (
error instanceof DesktopSshPromptCancelledError ||
error instanceof DesktopSshPromptTimedOutError
);
}
export const DesktopSshPasswordPromptCancellation = Schema.Union([
DesktopSshPromptCancelledError,
DesktopSshPromptWindowClosedError,
DesktopSshPromptServiceStoppedError,
DesktopSshPromptTimedOutError,
]);
export type DesktopSshPasswordPromptCancellation = typeof DesktopSshPasswordPromptCancellation.Type;
export interface DesktopSshPasswordPromptsShape {
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
readonly resolve: (
input: DesktopSshPasswordPromptResolutionInput,
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
readonly cancelPending: (reason: string) => Effect.Effect<void>;
}
export const isDesktopSshPasswordPromptCancellation = Schema.is(
DesktopSshPasswordPromptCancellation,
);
export class DesktopSshPasswordPrompts extends Context.Service<
DesktopSshPasswordPrompts,
DesktopSshPasswordPromptsShape
{
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
readonly resolve: (
input: DesktopSshPasswordPromptResolutionInput,
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
}
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
interface PendingSshPasswordPrompt {
@@ -137,7 +177,7 @@ interface PendingSshPasswordPrompt {
readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
}
interface LayerOptions {
export interface DesktopSshPasswordPromptsOptions {
readonly passwordPromptTimeoutMs?: number;
}
@@ -161,14 +201,16 @@ const failPending = (
error: DesktopSshPasswordPromptRequestError,
) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
options: DesktopSshPasswordPromptsOptions = {},
) {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
const cancelPending = (reason: string): Effect.Effect<void> =>
const cancelPending = () =>
Ref.getAndSet(pendingRef, new Map()).pipe(
Effect.flatMap((pending) =>
Effect.forEach(
@@ -176,10 +218,9 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
(entry) =>
failPending(
entry,
new DesktopSshPromptCancelledError({
new DesktopSshPromptServiceStoppedError({
requestId: entry.requestId,
destination: entry.destination,
reason,
}),
),
{ discard: true },
@@ -188,13 +229,11 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
Effect.asVoid,
);
yield* Effect.addFinalizer(() =>
cancelPending("SSH password prompt service stopped.").pipe(Effect.ignore),
);
yield* Effect.addFinalizer(() => cancelPending().pipe(Effect.ignore));
const resolve = Effect.fn("desktop.sshPasswordPrompts.resolve")(function* (
input: DesktopSshPasswordPromptResolutionInput,
): Effect.fn.Return<void, DesktopSshPasswordPromptResolveError> {
const resolve: DesktopSshPasswordPrompts["Service"]["resolve"] = Effect.fn(
"desktop.sshPasswordPrompts.resolve",
)(function* (input) {
const requestId = input.requestId.trim();
if (requestId.length === 0) {
return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
@@ -212,7 +251,6 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
new DesktopSshPromptCancelledError({
requestId,
destination: entry.destination,
reason: `SSH authentication cancelled for ${entry.destination}.`,
}),
);
return;
@@ -221,9 +259,9 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
});
const request = Effect.fn("desktop.sshPasswordPrompts.request")(function* (
input: SshPasswordRequest,
): Effect.fn.Return<string, DesktopSshPasswordPromptRequestError> {
const request: DesktopSshPasswordPrompts["Service"]["request"] = Effect.fn(
"desktop.sshPasswordPrompts.request",
)(function* (input) {
const window = yield* electronWindow.main;
if (Option.isNone(window) || window.value.isDestroyed()) {
return yield* new DesktopSshPromptWindowUnavailableError({
@@ -233,7 +271,11 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
(cause) =>
new DesktopSshPromptRequestIdGenerationError({
destination: input.destination,
cause,
}),
),
);
const now = yield* DateTime.now;
@@ -267,10 +309,9 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
onSome: (pending) =>
failPending(
pending,
new DesktopSshPromptCancelledError({
new DesktopSshPromptWindowClosedError({
requestId,
destination: input.destination,
reason: "SSH authentication was cancelled because the app window closed.",
}),
),
}),
@@ -302,36 +343,43 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
return yield* Effect.try({
try: () => {
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
}
window.value.once("closed", cancelOnWindowClosed);
window.value.webContents.send(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
}
if (window.value.isMinimized()) {
window.value.restore();
}
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
}
window.value.focus();
},
catch: (cause) =>
new DesktopSshPromptSendError({
requestId,
destination: input.destination,
cause,
}),
isDesktopSshPromptWindowUnavailableError(cause)
? cause
: new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
cause,
}),
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
});
return DesktopSshPasswordPrompts.of({
request,
resolve,
cancelPending,
});
});
export const layer = (options: LayerOptions = {}) =>
export const layer = (options: DesktopSshPasswordPromptsOptions = {}) =>
Layer.effect(DesktopSshPasswordPrompts, make(options));
@@ -83,7 +83,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
}),
).pipe(Effect.asVoid),
} satisfies ElectronUpdater.ElectronUpdaterShape);
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: () => Effect.die("unexpected BrowserWindow creation"),
@@ -99,7 +99,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
} satisfies ElectronWindow.ElectronWindowShape);
} satisfies ElectronWindow.ElectronWindow["Service"]);
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
@@ -46,14 +46,14 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronAppShape);
} satisfies ElectronApp.ElectronApp["Service"]);
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialogShape);
} satisfies ElectronDialog.ElectronDialog["Service"]);
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
getState: Effect.die("unexpected getState"),
@@ -86,7 +86,7 @@ const makeElectronMenuLayer = (
Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid),
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenuShape);
} satisfies ElectronMenu.ElectronMenu["Service"]);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import type * as Electron from "electron";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
@@ -26,9 +26,9 @@ type DesktopApplicationMenuRuntimeServices =
| DesktopWindow.DesktopWindow
| ElectronDialog.ElectronDialog;
const { logInfo: logUpdaterInfo } = DesktopObservability.makeComponentLogger("desktop-updater");
const { logInfo: logUpdaterInfo } = makeComponentLogger("desktop-updater");
const { logError: logMenuError } = DesktopObservability.makeComponentLogger("desktop-menu");
const { logError: logMenuError } = makeComponentLogger("desktop-menu");
const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function* (
action: string,
@@ -37,11 +37,7 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const checkForUpdatesFromMenu: Effect.Effect<
void,
never,
DesktopUpdates.DesktopUpdates | ElectronDialog.ElectronDialog
> = Effect.gen(function* () {
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const result = yield* updates.check("menu");
@@ -65,11 +61,7 @@ const checkForUpdatesFromMenu: Effect.Effect<
}
}).pipe(Effect.withSpan("desktop.menu.checkForUpdates"));
const handleCheckForUpdatesMenuClick: Effect.Effect<
void,
DesktopWindow.DesktopWindowError,
DesktopUpdates.DesktopUpdates | ElectronDialog.ElectronDialog | DesktopWindow.DesktopWindow
> = Effect.gen(function* () {
const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const disabledReason = yield* updates.disabledReason;
+6 -6
View File
@@ -8,15 +8,15 @@ import type * as Electron from "electron";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as IpcChannels from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
@@ -57,7 +57,7 @@ export class DesktopWindow extends Context.Service<
>()("@t3tools/desktop/window/DesktopWindow") {}
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
DesktopObservability.makeComponentLogger("desktop-window");
makeComponentLogger("desktop-window");
function getIconOption(
iconPaths: DesktopAssets.DesktopIconPaths,
@@ -380,7 +380,7 @@ export const make = Effect.gen(function* () {
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(IpcChannels.MENU_ACTION_CHANNEL, action);
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
void runPromise(electronWindow.reveal(targetWindow));
};
@@ -1,16 +1,19 @@
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { getBuiltInSpriteSheet } from "@pierre/trees";
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const moduleDirectory = resolve(scriptDirectory, "..");
const repositoryRoot = resolve(moduleDirectory, "../../../..");
const outputDirectory = join(moduleDirectory, "assets/file-icons");
const generatedModulePath = join(moduleDirectory, "src/markdownFileIcons.generated.ts");
const webIconSource = readFileSync(join(repositoryRoot, "apps/web/src/pierre-icons.ts"), "utf8");
const scriptDirectory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const moduleDirectory = NodePath.resolve(scriptDirectory, "..");
const repositoryRoot = NodePath.resolve(moduleDirectory, "../../../..");
const outputDirectory = NodePath.join(moduleDirectory, "assets/file-icons");
const generatedModulePath = NodePath.join(moduleDirectory, "src/markdownFileIcons.generated.ts");
const webIconSource = NodeFS.readFileSync(
NodePath.join(repositoryRoot, "apps/web/src/pierre-icons.ts"),
"utf8",
);
const customSprite = webIconSource.match(/const T3_FILE_ICON_SPRITE = `([\s\S]*?)`;/)?.[1];
if (!customSprite) {
@@ -95,20 +98,20 @@ function symbolFromSprite(sprite, id) {
}
function renderIcon(token, symbol, color) {
const svgPath = join(outputDirectory, `.pierre-${token}.svg`);
const pngPath = join(outputDirectory, `pierre_${token}.png`);
writeFileSync(
const svgPath = NodePath.join(outputDirectory, `.pierre-${token}.svg`);
const pngPath = NodePath.join(outputDirectory, `pierre_${token}.png`);
NodeFS.writeFileSync(
svgPath,
`<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="${symbol.viewBox}" style="color:${color}">${symbol.body}</svg>`,
);
execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
NodeChildProcess.execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
stdio: "ignore",
});
rmSync(svgPath);
NodeFS.rmSync(svgPath);
}
rmSync(outputDirectory, { recursive: true, force: true });
mkdirSync(outputDirectory, { recursive: true });
NodeFS.rmSync(outputDirectory, { recursive: true, force: true });
NodeFS.mkdirSync(outputDirectory, { recursive: true });
const builtInSprite = getBuiltInSpriteSheet("complete");
const builtInTokens = [...builtInSprite.matchAll(/<symbol id="file-tree-builtin-([^"]+)"/g)]
@@ -130,4 +133,4 @@ const tokens = [...new Set([...builtInTokens, ...Object.keys(customIcons)])].sor
const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const MARKDOWN_FILE_ICON_SOURCES = {\n${tokens
.map((token) => ` ${token}: require("../assets/file-icons/pierre_${token}.png"),`)
.join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;
writeFileSync(generatedModulePath, generatedSource);
NodeFS.writeFileSync(generatedModulePath, generatedSource);
+7 -11
View File
@@ -5,24 +5,20 @@ import { Atom } from "effect/unstable/reactivity";
import { runtimeContextLayer } from "../lib/runtime";
import { connectionPlatformLayer } from "./platform";
const providedConnectionPlatformLayer: Layer.Layer<
Layer.Success<typeof connectionPlatformLayer>,
Layer.Error<typeof connectionPlatformLayer>
> = connectionPlatformLayer.pipe(Layer.provide(runtimeContextLayer));
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
type ConnectionLayerSource =
| typeof Connection.layer
| typeof runtimeContextLayer
| typeof providedConnectionPlatformLayer;
| typeof connectionPlatformLayer;
export const connectionLayer: Layer.Layer<
Layer.Success<ConnectionLayerSource>,
Layer.Error<ConnectionLayerSource>
> = Connection.layer.pipe(
const connectionLayer = Connection.layer.pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
export const connectionAtomRuntime: Atom.AtomRuntime<
Layer.Success<typeof connectionLayer>,
Layer.Error<typeof connectionLayer>
Layer.Success<ConnectionLayerSource>,
Layer.Error<ConnectionLayerSource>
> = Atom.runtime(connectionLayer);
@@ -2,7 +2,7 @@ import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import * as Layer from "effect/Layer";
import { HttpClient } from "effect/unstable/http";
@@ -35,7 +35,7 @@ const connection: SavedRemoteConnection = {
};
const testLayer = Layer.mergeAll(
Layer.succeed(ManagedRelayClient, null as never),
Layer.succeed(ManagedRelay.ManagedRelayClient, null as never),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
@@ -1,6 +1,6 @@
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
@@ -11,7 +11,7 @@ export function setLiveActivityUpdatesEnabled(input: {
readonly enabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelayClient> {
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
yield* Effect.tryPromise({
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
@@ -9,7 +9,7 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { type ManagedRelayClient } from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import { verifyDpopProof } from "@t3tools/shared/dpop";
@@ -158,7 +158,7 @@ const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundO
}
idlePasses = 0;
const exit = yield* Effect.exit(
pending.operation as Effect.Effect<unknown, unknown, ManagedRelayClient>,
pending.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
);
yield* Effect.sync(() => {
pending.resolve(exit);
@@ -9,7 +9,7 @@ import {
type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import {
isAtomCommandInterrupted,
settleAsyncResult,
@@ -175,7 +175,7 @@ const relayToken = Effect.gen(function* () {
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
): Effect.Effect<void, unknown, ManagedRelayClient> {
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled before relay request", {
@@ -198,7 +198,7 @@ function registerDeviceWithRelay(
return;
}
const client = yield* ManagedRelayClient;
const client = yield* ManagedRelay.ManagedRelayClient;
logRegistrationDebug("relay device registration request started", {
expectedGeneration,
});
@@ -215,7 +215,7 @@ function registerDeviceWithRelay(
function unregisterDeviceWithRelay(input: {
readonly deviceId: string;
readonly tokenProvider: () => Promise<string | null>;
}): Effect.Effect<void, unknown, ManagedRelayClient> {
}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return;
const token = yield* Effect.tryPromise({
@@ -227,7 +227,7 @@ function unregisterDeviceWithRelay(input: {
return;
}
const client = yield* ManagedRelayClient;
const client = yield* ManagedRelay.ManagedRelayClient;
yield* client.unregisterDevice({
clerkToken: token,
deviceId: input.deviceId,
@@ -237,7 +237,7 @@ function unregisterDeviceWithRelay(input: {
function registerLiveActivityWithRelay(
body: RelayLiveActivityRegistrationRequest,
): Effect.Effect<boolean, unknown, ManagedRelayClient> {
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return false;
const token = yield* relayToken;
@@ -246,7 +246,7 @@ function registerLiveActivityWithRelay(
return false;
}
const client = yield* ManagedRelayClient;
const client = yield* ManagedRelay.ManagedRelayClient;
yield* client.registerLiveActivity({
clerkToken: token,
payload: body,
@@ -274,7 +274,7 @@ function logRegistrationDebug(context: string, details?: unknown): void {
}
function runRegistrationInBackground(
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
operation: Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
context: string,
): void {
void (async () => {
@@ -370,7 +370,7 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
function registerDevice(
input: DeviceRegistrationInput = {},
expectedGeneration = deviceRegistrationGeneration,
): Effect.Effect<void, unknown, ManagedRelayClient> {
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
logRegistrationDebug("device registration skipped; platform does not support it");
@@ -411,7 +411,7 @@ function registerDevice(
function registerDeviceForCurrentUser(
pushToStartToken?: string,
): Effect.Effect<void, unknown, ManagedRelayClient> {
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
}
@@ -485,7 +485,7 @@ export function unregisterAllAgentAwarenessConnections(): void {
export function refreshAgentAwarenessRegistration(): Effect.Effect<
void,
never,
ManagedRelayClient
ManagedRelay.ManagedRelayClient
> {
return registerDeviceForCurrentUser().pipe(
Effect.catch((error) =>
@@ -515,7 +515,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
export function unregisterAgentAwarenessDeviceForCurrentUser(
tokenProvider: () => Promise<string | null>,
): Effect.Effect<void, never, ManagedRelayClient> {
): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadAgentAwarenessDeviceId(),
@@ -536,7 +536,7 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
export function registerLiveActivityPushToken(input: {
readonly activity: LiveActivity<AgentActivityProps>;
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
return false;
@@ -588,7 +588,7 @@ export function registerLiveActivityPushToken(input: {
function registerLiveActivityPushTokenValue(input: {
readonly activityPushToken: string;
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
@@ -624,7 +624,7 @@ function scheduleActiveLiveActivityRegistrationRetry(): void {
export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
void,
never,
ManagedRelayClient
ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
@@ -1,6 +1,6 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { ManagedRelayClient, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
@@ -22,7 +22,7 @@ import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publi
function resetManagedRelayTokenCache() {
return settleAsyncResult(() =>
runtime.runPromiseExit(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
),
);
}
@@ -4,11 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { EnvironmentId } from "@t3tools/contracts";
import { RelayMobileClientId } from "@t3tools/contracts/relay";
import {
managedRelayClientLayer,
ManagedRelayClient,
ManagedRelayDpopSigner,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/unstable/http";
@@ -62,8 +58,8 @@ const createProofMock = vi.fn(
Effect.succeed(`dpop:${input.method}:${input.url}`),
);
const testDpopSignerLayer = Layer.succeed(
ManagedRelayDpopSigner,
ManagedRelayDpopSigner.of({
ManagedRelay.ManagedRelayDpopSigner,
ManagedRelay.ManagedRelayDpopSigner.of({
thumbprint: Effect.succeed("client-proof-key-thumbprint"),
createProof: (input) => createProofMock(input),
}),
@@ -73,7 +69,7 @@ function cloudClientLayer() {
const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));
return Layer.mergeAll(
httpClientLayer,
managedRelayClientLayer({
ManagedRelay.layer({
relayUrl: "https://relay.example.test",
clientId: RelayMobileClientId,
}).pipe(Layer.provideMerge(testDpopSignerLayer), Layer.provide(httpClientLayer)),
@@ -81,7 +77,11 @@ function cloudClientLayer() {
}
const withCloudServices = <A, E>(
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner>,
effect: Effect.Effect<
A,
E,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
>,
) => effect.pipe(Effect.provide(cloudClientLayer()));
function validLinkProof() {
@@ -25,11 +25,7 @@ import {
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
ManagedRelayClient,
type ManagedRelayClientError,
ManagedRelayDpopSigner,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
import { authClientMetadata } from "../../lib/authClientMetadata";
@@ -156,13 +152,15 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
}
function decodedRelayClientError(message: string) {
return (cause: ManagedRelayClientError) => {
const relayError = cause.relayError;
return (cause: ManagedRelay.ManagedRelayClientError) => {
const relayError =
cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
return new CloudEnvironmentLinkError({
message: detail ? `${message}: ${detail}` : message,
cause,
...(cause.traceId ? { traceId: cause.traceId } : {}),
...(traceId ? { traceId } : {}),
});
};
}
@@ -261,7 +259,11 @@ function ensureConnectEndpointMatchesEnvironment(input: {
export function linkEnvironmentToCloud(input: {
readonly connection: SavedRemoteConnection;
readonly clerkToken: string;
}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
}): Effect.Effect<
void,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
if (!input.connection.bearerToken) {
return yield* new CloudEnvironmentLinkError({
@@ -270,7 +272,7 @@ export function linkEnvironmentToCloud(input: {
}
const localBearerToken = input.connection.bearerToken;
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
@@ -353,11 +355,11 @@ export function listCloudEnvironments(input: {
}): Effect.Effect<
ReadonlyArray<RelayClientEnvironmentRecord>,
CloudEnvironmentLinkError,
ManagedRelayClient
ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const relayClient = yield* ManagedRelay.ManagedRelayClient;
return yield* relayClient
.listEnvironments({
@@ -374,11 +376,11 @@ export function getCloudEnvironmentStatus(input: {
}): Effect.Effect<
RelayEnvironmentStatusResponseType,
CloudEnvironmentLinkError,
ManagedRelayClient
ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const status = yield* relayClient
.getEnvironmentStatus({
clerkToken: input.clerkToken,
@@ -413,7 +415,7 @@ export function loadCloudEnvironmentStatuses(input: {
}): Effect.Effect<
ReadonlyArray<CloudEnvironmentRecordWithStatus>,
CloudEnvironmentLinkError,
ManagedRelayClient
ManagedRelay.ManagedRelayClient
> {
return Effect.forEach(
input.environments,
@@ -445,7 +447,7 @@ export function listCloudEnvironmentsWithStatus(input: {
}): Effect.Effect<
ReadonlyArray<CloudEnvironmentRecordWithStatus>,
CloudEnvironmentLinkError,
ManagedRelayClient
ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
const environments = yield* listCloudEnvironments(input);
@@ -473,7 +475,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
}) {
yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const deviceId = yield* loadAgentAwarenessDeviceId();
const connect = yield* relayClient
@@ -514,7 +516,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
message: "Connected endpoint descriptor does not match the selected environment.",
});
}
const signer = yield* ManagedRelayDpopSigner;
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
const bootstrapDpop = yield* signer
.createProof({
method: "POST",
@@ -555,7 +557,7 @@ export function connectCloudEnvironment(input: {
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
@@ -570,7 +572,7 @@ export function refreshCloudEnvironmentConnection(input: {
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
@@ -1,8 +1,4 @@
import {
managedRelayClientLayer as makeManagedRelayClientLayer,
ManagedRelayDpopSigner,
ManagedRelayDpopSignerError,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { RelayMobileClientId } from "@t3tools/contracts/relay";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
@@ -12,34 +8,54 @@ import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
const relayDpopSignerLayer = Layer.effect(
ManagedRelayDpopSigner,
ManagedRelay.ManagedRelayDpopSigner,
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const loadProofKey = yield* Effect.cached(
loadOrCreateDpopProofKeyPair().pipe(Effect.provideService(Crypto.Crypto, crypto)),
);
return ManagedRelayDpopSigner.of({
return ManagedRelay.ManagedRelayDpopSigner.of({
thumbprint: loadProofKey.pipe(
Effect.map((proofKey) => proofKey.thumbprint),
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
Effect.mapError(
(error) =>
new ManagedRelay.ManagedRelayDpopKeyLoadError({
keyStore: "expo-secure-store",
cause: error,
}),
),
Effect.withSpan("mobile.managedRelayDpopSigner.loadThumbprint"),
),
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(
function* (input) {
const proofKey = yield* loadProofKey;
return yield* createDpopProof({ ...input, proofKey }).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proof) => proof.proof),
);
},
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
),
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {
const proofKey = yield* loadProofKey.pipe(
Effect.mapError(
(error) =>
new ManagedRelay.ManagedRelayDpopProofCreationError({
method: input.method,
url: input.url,
cause: error,
}),
),
);
return yield* createDpopProof({ ...input, proofKey }).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proof) => proof.proof),
Effect.mapError(
(error) =>
new ManagedRelay.ManagedRelayDpopProofCreationError({
method: input.method,
url: input.url,
cause: error,
}),
),
);
}),
});
}),
);
export const managedRelayClientLayer = (relayUrl: string) =>
makeManagedRelayClientLayer({
ManagedRelay.layer({
relayUrl,
clientId: RelayMobileClientId,
accessTokenStore: managedRelayAccessTokenStore,
@@ -1,7 +1,4 @@
import {
type ManagedRelayAccessTokenCacheEntry,
type ManagedRelayAccessTokenStore,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
@@ -60,7 +57,7 @@ const loadManagedRelayAccessTokens = Effect.tryPromise({
}).pipe(
Effect.flatMap((encoded) =>
encoded === null
? Effect.succeed<ReadonlyArray<ManagedRelayAccessTokenCacheEntry>>([])
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
: decodeManagedRelayAccessTokenCache(encoded).pipe(
Effect.map((cache) => cache.entries),
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
@@ -68,7 +65,9 @@ const loadManagedRelayAccessTokens = Effect.tryPromise({
),
);
const saveManagedRelayAccessTokens = (entries: ReadonlyArray<ManagedRelayAccessTokenCacheEntry>) =>
const saveManagedRelayAccessTokens = (
entries: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>,
) =>
encodeManagedRelayAccessTokenCache({
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
entries,
@@ -87,7 +86,7 @@ const clearManagedRelayAccessTokens = Effect.tryPromise({
catch: storeError("Could not clear persisted relay access tokens."),
});
export const managedRelayAccessTokenStore: ManagedRelayAccessTokenStore = {
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
load: loadManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("load")),
Effect.orElseSucceed(() => []),
@@ -1,9 +1,12 @@
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
createSourceHighlightAtomFamily,
isSourceHighlightError,
type SourceHighlightTokens,
} from "./sourceHighlightingState";
@@ -101,8 +104,9 @@ describe("sourceHighlightingState", () => {
});
it("exposes highlighter errors as a failed async result", async () => {
const cause = new Error("highlight failed");
const highlight = vi.fn(async () => {
throw new Error("highlight failed");
throw cause;
});
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
const registry = AtomRegistry.make();
@@ -113,8 +117,17 @@ describe("sourceHighlightingState", () => {
});
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
const result = registry.get(atom);
const error = AsyncResult.isFailure(result)
? Option.getOrUndefined(Cause.findErrorOption(result.cause))
: undefined;
expect(isSourceHighlightError(error)).toBe(true);
expect(error).toMatchObject({
path: "src/example.ts",
theme: "light",
cause,
});
unmount();
@@ -1,5 +1,6 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Atom } from "effect/unstable/reactivity";
import {
@@ -22,9 +23,20 @@ type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighligh
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
readonly cause: unknown;
}> {}
export class SourceHighlightError extends Schema.TaggedErrorClass<SourceHighlightError>()(
"SourceHighlightError",
{
path: Schema.String,
theme: Schema.Literals(["light", "dark"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to highlight ${this.path} with the ${this.theme} theme.`;
}
}
export const isSourceHighlightError = Schema.is(SourceHighlightError);
export function createSourceHighlightAtomFamily(options?: {
readonly highlight?: SourceHighlighter;
@@ -36,7 +48,8 @@ export function createSourceHighlightAtomFamily(options?: {
Atom.make(
Effect.tryPromise({
try: () => highlight(request),
catch: (cause) => new SourceHighlightError({ cause }),
catch: (cause) =>
new SourceHighlightError({ path: request.path, theme: request.theme, cause }),
}),
).pipe(
Atom.setIdleTTL(idleTtlMs),
@@ -1,8 +1,13 @@
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { describe, expect, it, vi } from "vite-plus/test";
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
import {
createWorkspaceFileImageAtomFamily,
isWorkspaceImagePrefetchError,
} from "./workspace-file-image-cache";
describe("workspaceFileImageAtom", () => {
it("reuses a prefetched image across route remounts", async () => {
@@ -48,14 +53,47 @@ describe("workspaceFileImageAtom", () => {
registry.dispose();
});
it("exposes prefetch failures", async () => {
it("exposes a false native prefetch result", async () => {
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
const registry = AtomRegistry.make();
const atom = imageAtom("https://example.test/missing.png");
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
const result = registry.get(atom);
const error = AsyncResult.isFailure(result)
? Option.getOrUndefined(Cause.findErrorOption(result.cause))
: undefined;
expect(isWorkspaceImagePrefetchError(error)).toBe(true);
expect(error).toMatchObject({ uri: "https://example.test/missing.png" });
expect(error).not.toHaveProperty("cause");
unmount();
registry.dispose();
});
it("preserves thrown prefetch causes", async () => {
const cause = new Error("native image prefetch failed");
const imageAtom = createWorkspaceFileImageAtomFamily({
prefetch: async () => {
throw cause;
},
});
const registry = AtomRegistry.make();
const atom = imageAtom("https://example.test/missing.png");
const unmount = registry.mount(atom);
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
const result = registry.get(atom);
const error = AsyncResult.isFailure(result)
? Option.getOrUndefined(Cause.findErrorOption(result.cause))
: undefined;
expect(isWorkspaceImagePrefetchError(error)).toBe(true);
expect(error).toMatchObject({
uri: "https://example.test/missing.png",
cause,
});
unmount();
@@ -1,5 +1,6 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Atom } from "effect/unstable/reactivity";
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
@@ -8,10 +9,19 @@ type ImagePrefetch = (uri: string) => Promise<boolean>;
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
readonly cause?: unknown;
readonly uri: string;
}> {}
export class WorkspaceImagePrefetchError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchError>()(
"WorkspaceImagePrefetchError",
{
uri: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to prefetch workspace image ${this.uri}.`;
}
}
export const isWorkspaceImagePrefetchError = Schema.is(WorkspaceImagePrefetchError);
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
const { Image } = await import("react-native");
@@ -35,7 +45,7 @@ export function createWorkspaceFileImageAtomFamily(options?: {
return key.uri;
},
catch: (cause) =>
cause instanceof WorkspaceImagePrefetchError
isWorkspaceImagePrefetchError(cause)
? cause
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
}),
+16 -3
View File
@@ -15,7 +15,14 @@ function configuredRelayUrl(): string {
const httpClientLayer = remoteHttpClientLayer(fetch);
export const runtimeLayer = Layer.merge(
type RuntimeLayerSource =
| ReturnType<typeof managedRelayClientLayer>
| typeof Socket.layerWebSocketConstructorGlobal
| typeof cryptoLayer
| typeof httpClientLayer
| typeof tracingLayer;
const runtimeLayer = Layer.merge(
managedRelayClientLayer(configuredRelayUrl()),
Socket.layerWebSocketConstructorGlobal,
).pipe(
@@ -24,6 +31,12 @@ export const runtimeLayer = Layer.merge(
Layer.provideMerge(tracingLayer.pipe(Layer.provide(httpClientLayer))),
);
export const runtime = ManagedRuntime.make(runtimeLayer);
export const runtime: ManagedRuntime.ManagedRuntime<
Layer.Success<RuntimeLayerSource>,
Layer.Error<RuntimeLayerSource>
> = ManagedRuntime.make(runtimeLayer);
export const runtimeContextLayer = Layer.effectContext(runtime.contextEffect);
export const runtimeContextLayer: Layer.Layer<
Layer.Success<RuntimeLayerSource>,
Layer.Error<RuntimeLayerSource>
> = Layer.effectContext(runtime.contextEffect);
+2 -3
View File
@@ -12,8 +12,7 @@ import type {
import { Atom } from "effect/unstable/reactivity";
import { environmentProjects } from "./projects";
import { environmentServerConfigsAtom } from "./server";
import { environmentSession } from "./session";
import { environmentServerConfigsAtom, serverEnvironment } from "./server";
import { environmentThreadShells } from "./threads";
const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
@@ -50,7 +49,7 @@ export function useEnvironmentServerConfig(
return useAtomValue(
environmentId === null
? EMPTY_SERVER_CONFIG_ATOM
: environmentSession.configValueAtom(environmentId),
: serverEnvironment.configValueAtom(environmentId),
);
}
+2 -2
View File
@@ -5,12 +5,12 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { environmentCatalog } from "../connection/catalog";
import { environmentSession } from "./session";
import { serverEnvironment } from "./server";
export const environmentPresentations = createEnvironmentPresentationAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
stateAtom: environmentCatalog.stateAtom,
configValueAtom: environmentSession.configValueAtom,
serverConfigValueAtom: serverEnvironment.configValueAtom,
});
const EMPTY_ENVIRONMENT_PRESENTATION_ATOM = Atom.make<EnvironmentPresentation | null>(null).pipe(
+2 -2
View File
@@ -6,9 +6,9 @@ import { connectionAtomRuntime } from "../connection/runtime";
import { environmentSession } from "./session";
export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
initialConfigValueAtom: environmentSession.configValueAtom,
initialConfigValueAtom: environmentSession.initialConfigValueAtom,
});
export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
catalogValueAtom: environmentCatalog.catalogValueAtom,
configValueAtom: serverEnvironment.configValueAtom,
serverConfigValueAtom: serverEnvironment.configValueAtom,
});
@@ -1,5 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import { execFileSync } from "node:child_process";
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
@@ -46,7 +46,7 @@ import {
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
@@ -72,7 +72,7 @@ import {
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import * as WorkspaceEntries from "../src/workspace/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as WorkspacePaths from "../src/workspace/WorkspacePaths.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
@@ -82,7 +82,7 @@ import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";
const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
return NodeChildProcess.execFileSync("git", args, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
@@ -348,12 +348,12 @@ export const makeOrchestrationIntegrationHarness = (
),
Layer.provideMerge(
WorkspaceEntries.layer.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provide(WorkspacePaths.layer),
Layer.provideMerge(VcsDriverRegistry.layer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(WorkspacePaths.layer),
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
@@ -378,7 +378,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(orchestrationReactorLayer),
Layer.provideMerge(providerRegistryLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
@@ -1,6 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import path from "node:path";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import {
ApprovalRequestId,
@@ -409,7 +409,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
@@ -456,7 +456,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
@@ -752,7 +752,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
@@ -811,7 +811,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
@@ -869,7 +869,10 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
),
true,
);
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
assert.equal(
NodeFS.readFileSync(NodePath.join(harness.workspaceDir, "README.md"), "utf8"),
"v2\n",
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
@@ -1332,7 +1335,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
@@ -1390,7 +1393,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
+3 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off
import { appendFileSync } from "node:fs";
import * as NodeFS from "node:fs";
import * as Effect from "effect/Effect";
@@ -42,7 +42,7 @@ function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
process.once("SIGTERM", () => {
@@ -693,7 +693,7 @@ const program = Effect.gen(function* () {
}
const payload = event.payload;
return Effect.sync(() => {
appendFileSync(
NodeFS.appendFileSync(
requestLogPath,
payload.endsWith("\n") ? payload : `${payload}\n`,
"utf8",
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import process from "node:process";
import readline from "node:readline";
import * as NodeChildProcess from "node:child_process";
import * as NodeProcess from "node:process";
import * as NodeReadline from "node:readline";
import * as NodeTimers from "node:timers";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Effect from "effect/Effect";
@@ -56,19 +56,19 @@ type PendingRequest = {
reject: (error: Error) => void;
};
const targetCwd = process.argv[2] ?? process.cwd();
const targetModel = process.argv[3] ?? "gpt-5.4";
const promptText = process.argv[4] ?? "helo";
const targetReasoning = process.env.CURSOR_REASONING ?? "";
const targetContext = process.env.CURSOR_CONTEXT ?? "";
const targetFast = process.env.CURSOR_FAST ?? "";
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
const targetCwd = NodeProcess.argv[2] ?? NodeProcess.cwd();
const targetModel = NodeProcess.argv[3] ?? "gpt-5.4";
const promptText = NodeProcess.argv[4] ?? "helo";
const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? "";
const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? "";
const targetFast = NodeProcess.env.CURSOR_FAST ?? "";
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "agent";
const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
function logSection(title: string, value: unknown) {
process.stdout.write(`\n=== ${title} ===\n`);
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
NodeProcess.stdout.write(`\n=== ${title} ===\n`);
NodeProcess.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function fail(message: string): never {
@@ -124,18 +124,18 @@ function sleep(ms: number) {
}
class JsonRpcChild {
readonly child: ChildProcessWithoutNullStreams;
readonly child: NodeChildProcess.ChildProcessWithoutNullStreams;
readonly pending = new Map<JsonRpcId, PendingRequest>();
nextId = 1;
closed = false;
constructor(bin: string, args: string[], cwd: string) {
const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args));
this.child = spawn(spawnCommand.command, spawnCommand.args, {
this.child = NodeChildProcess.spawn(spawnCommand.command, spawnCommand.args, {
cwd,
shell: spawnCommand.shell,
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
env: NodeProcess.env,
});
this.child.on("exit", (code, signal) => {
@@ -155,14 +155,14 @@ class JsonRpcChild {
this.pending.clear();
});
const stdout = readline.createInterface({ input: this.child.stdout });
const stdout = NodeReadline.createInterface({ input: this.child.stdout });
stdout.on("line", (line) => {
void this.handleStdoutLine(line);
});
const stderr = readline.createInterface({ input: this.child.stderr });
const stderr = NodeReadline.createInterface({ input: this.child.stderr });
stderr.on("line", (line) => {
process.stdout.write(`[stderr] ${line}\n`);
NodeProcess.stdout.write(`[stderr] ${line}\n`);
});
}
@@ -175,7 +175,7 @@ class JsonRpcChild {
headers: [],
...message,
});
process.stdout.write(`>>> ${payload}\n`);
NodeProcess.stdout.write(`>>> ${payload}\n`);
this.child.stdin.write(`${payload}\n`);
}
@@ -240,13 +240,13 @@ class JsonRpcChild {
return;
}
process.stdout.write(`<<< ${line}\n`);
NodeProcess.stdout.write(`<<< ${line}\n`);
let message: JsonRpcMessage;
try {
message = JSON.parse(line) as JsonRpcMessage;
} catch (error) {
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
NodeProcess.stdout.write(`[parse-error] ${(error as Error).message}\n`);
return;
}
@@ -435,7 +435,7 @@ async function main() {
}
void main().catch((error: unknown) => {
process.stderr.write(
NodeProcess.stderr.write(
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
);
process.exitCode = 1;
+7 -7
View File
@@ -7,18 +7,18 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
import { ProjectFaviconResolverLive } from "../project/Layers/ProjectFaviconResolver.ts";
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
const configLayer = ServerConfig.layerTest(process.cwd(), {
const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-asset-access-test-",
});
const testLayer = Layer.mergeAll(
configLayer,
WorkspacePathsLive,
ProjectFaviconResolverLive.pipe(Layer.provide(WorkspacePathsLive)),
WorkspacePaths.layer,
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
).pipe(Layer.provideMerge(NodeServices.layer));
@@ -127,7 +127,7 @@ describe("AssetAccess", () => {
it.effect("issues exact attachment capabilities by attachment id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
+11 -11
View File
@@ -19,11 +19,11 @@ import {
signPayload,
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import { ServerSecretStore } from "../auth/ServerSecretStore.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { ProjectFaviconResolver } from "../project/Services/ProjectFaviconResolver.ts";
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
@@ -103,7 +103,7 @@ const failAccess = (message: string, cause?: unknown) =>
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
const fileSystem = yield* FileSystem.FileSystem;
const workspacePaths = yield* WorkspacePaths;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot(input)
.pipe(Effect.orElseSucceed(() => null));
@@ -130,7 +130,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
let claims: AssetClaims;
let fileName: string;
@@ -181,7 +181,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
break;
}
case "attachment": {
const config = yield* ServerConfig;
const config = yield* ServerConfig.ServerConfig;
const attachmentPath = resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: input.resource.attachmentId,
@@ -202,7 +202,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
const workspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.resource.cwd)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const faviconResolver = yield* ProjectFaviconResolver;
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot);
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
if (
@@ -225,7 +225,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}
}
const secretStore = yield* ServerSecretStore;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const signingSecret = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
@@ -244,7 +244,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
const secretStore = yield* ServerSecretStore;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const signingSecret = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.orElseSucceed(() => null));
@@ -255,7 +255,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
if (claims.kind === "attachment") {
const config = yield* ServerConfig;
const config = yield* ServerConfig.ServerConfig;
const attachmentPath = resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: claims.attachmentId,
+1 -1
View File
@@ -1,5 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import NodePath from "node:path";
import * as NodePath from "node:path";
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\]+/, "");
+13 -9
View File
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
@@ -45,11 +45,13 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
try {
const attachmentId = "thread-1-attachment";
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
@@ -57,12 +59,14 @@ describe("attachmentStore", () => {
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
try {
const resolved = resolveAttachmentPathById({
attachmentsDir,
@@ -70,7 +74,7 @@ describe("attachmentStore", () => {
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
+4 -4
View File
@@ -1,6 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import type { ChatAttachment } from "@t3tools/contracts";
@@ -39,7 +39,7 @@ export function createAttachmentId(threadId: string): string | null {
if (!threadSegment) {
return null;
}
return `${threadSegment}-${randomUUID()}`;
return `${threadSegment}-${NodeCrypto.randomUUID()}`;
}
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
@@ -89,7 +89,7 @@ export function resolveAttachmentPathById(input: {
attachmentsDir: input.attachmentsDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
if (maybePath && NodeFS.existsSync(maybePath)) {
return maybePath;
}
}
+10 -17
View File
@@ -53,29 +53,25 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
it.effect("classifies invalid bootstrap credential failures for the HTTP boundary", () =>
Effect.sync(() => {
const error = EnvironmentAuth.toBootstrapExchangeError(
new PairingGrantStore.BootstrapCredentialInvalidError({
message: "Unknown bootstrap credential.",
}),
new PairingGrantStore.UnknownBootstrapCredentialError({}),
);
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
if (error._tag === "ServerAuthInvalidCredentialError") {
expect(error.reason).toBe("invalid_credential");
}
}),
);
it.effect("maps unexpected bootstrap failures to 500", () =>
Effect.sync(() => {
const error = EnvironmentAuth.toBootstrapExchangeError(
new PairingGrantStore.BootstrapCredentialInternalError({
message: "Failed to consume bootstrap credential.",
cause: new Error("sqlite is unavailable"),
}),
);
const cause = new PairingGrantStore.BootstrapCredentialConsumeError({
cause: new Error("sqlite is unavailable"),
});
const error = EnvironmentAuth.toBootstrapExchangeError(cause);
expect(error._tag).toBe("ServerAuthInternalError");
expect(error._tag).toBe("ServerAuthBootstrapCredentialValidationError");
expect(error.message).toBe("Failed to validate bootstrap credential.");
if (error._tag === "ServerAuthBootstrapCredentialValidationError") {
expect(error.cause).toBe(cause);
}
}),
);
@@ -117,10 +113,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
)
.pipe(Effect.flip);
expect(error._tag).toBe("ServerAuthInvalidRequestError");
if (error._tag === "ServerAuthInvalidRequestError") {
expect(error.reason).toBe("scope_not_granted");
}
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
+494 -224
View File
@@ -20,12 +20,12 @@ import {
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
@@ -67,123 +67,429 @@ export interface AuthenticatedSession {
readonly expiresAt?: DateTime.DateTime;
}
export class ServerAuthInternalError extends Data.TaggedError("ServerAuthInternalError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const serverAuthInternalErrorContext = {
cause: Schema.Defect(),
};
export class ServerAuthInvalidCredentialError extends Data.TaggedError(
"ServerAuthInvalidCredentialError",
)<{
readonly reason: "missing_credential" | "invalid_credential";
readonly cause?: unknown;
}> {}
export class ServerAuthInvalidRequestError extends Data.TaggedError(
"ServerAuthInvalidRequestError",
)<{
readonly reason: "invalid_scope" | "scope_not_granted";
}> {}
export class ServerAuthForbiddenOperationError extends Data.TaggedError(
"ServerAuthForbiddenOperationError",
)<{
readonly reason: "current_session_revoke_not_allowed";
}> {}
export interface EnvironmentAuthShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
readonly getSessionState: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
readonly createBrowserSession: (
credential: string,
requestMetadata: AuthClientMetadata,
) => Effect.Effect<
{
readonly response: AuthBrowserSessionResult;
readonly sessionToken: string;
},
ServerAuthInvalidCredentialError | ServerAuthInternalError
>;
readonly exchangeBootstrapCredentialForAccessToken: (
credential: string,
requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
requestMetadata: AuthClientMetadata,
input?: {
readonly proofKeyThumbprint?: string;
},
) => Effect.Effect<
AuthAccessTokenResult,
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
>;
readonly createPairingLink: (input?: {
readonly ttl?: Duration.Duration;
readonly label?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
readonly issueStartupPairingCredential: () => Effect.Effect<
AuthPairingCredentialResult,
ServerAuthInternalError
>;
readonly listPairingLinks: (input?: {
readonly excludeSubjects?: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly issueSession: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
ServerAuthInternalError
>;
readonly revokeSession: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly revokeOtherSessionsExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthInternalError>;
readonly listClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
readonly revokeClientSession: (
currentSessionId: AuthSessionId,
targetSessionId: AuthSessionId,
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthInternalError>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<
AuthenticatedSession,
ServerAuthInvalidCredentialError | ServerAuthInternalError
>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<
AuthenticatedSession,
ServerAuthInvalidCredentialError | ServerAuthInternalError
>;
readonly issueWebSocketTicket: (
session: Pick<AuthenticatedSession, "sessionId">,
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
readonly issueStartupPairingUrl: (
baseUrl: string,
) => Effect.Effect<string, ServerAuthInternalError>;
export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthBootstrapCredentialValidationError>()(
"ServerAuthBootstrapCredentialValidationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to validate bootstrap credential.";
}
}
export class EnvironmentAuth extends Context.Service<EnvironmentAuth, EnvironmentAuthShape>()(
"t3/auth/EnvironmentAuth",
) {}
export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
"ServerAuthSessionCredentialValidationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to validate session credential.";
}
}
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
"ServerAuthAuthenticatedSessionIssueError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to issue authenticated session.";
}
}
export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
"ServerAuthAuthenticatedAccessTokenIssueError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to issue authenticated access token.";
}
}
export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
"ServerAuthPairingLinkCreationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to create pairing link.";
}
}
export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<ServerAuthPairingLinksListError>()(
"ServerAuthPairingLinksListError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to list pairing links.";
}
}
export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
"ServerAuthPairingLinkRevocationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke pairing link.";
}
}
export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
"ServerAuthSessionTokenIssueError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to issue session token.";
}
}
export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerAuthSessionsListError>()(
"ServerAuthSessionsListError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to list sessions.";
}
}
export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
"ServerAuthSessionRevocationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke session.";
}
}
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
"ServerAuthOtherSessionsRevocationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke other sessions.";
}
}
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
"ServerAuthWebSocketTokenIssueError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to issue websocket token.";
}
}
export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
"ServerAuthDpopReplayStateRecordError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to record DPoP proof replay state.";
}
}
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
"ServerAuthDpopReplayKeyCalculationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to calculate DPoP replay key.";
}
}
export class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountVerificationError>()(
"ServerAuthLinkedCloudAccountVerificationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Could not verify the linked cloud account.";
}
}
export class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountReadError>()(
"ServerAuthLinkedCloudAccountReadError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Could not read the linked cloud account.";
}
}
export class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountMissingError>()(
"ServerAuthLinkedCloudAccountMissingError",
{},
) {
override get message(): string {
return "Cloud linked user is not installed for this environment.";
}
}
export class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudLinkJwtSigningError>()(
"ServerAuthCloudLinkJwtSigningError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to sign cloud link JWT.";
}
}
export class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedErrorClass<ServerAuthCloudMintPublicKeyMissingError>()(
"ServerAuthCloudMintPublicKeyMissingError",
{},
) {
override get message(): string {
return "Cloud mint public key is not installed for this environment.";
}
}
export class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedErrorClass<ServerAuthCloudRelayIssuerMissingError>()(
"ServerAuthCloudRelayIssuerMissingError",
{},
) {
override get message(): string {
return "Cloud relay issuer is not installed for this environment.";
}
}
export class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudHealthJwtSigningError>()(
"ServerAuthCloudHealthJwtSigningError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to sign cloud health JWT.";
}
}
export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudMintJwtSigningError>()(
"ServerAuthCloudMintJwtSigningError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to sign cloud mint JWT.";
}
}
export const ServerAuthInternalError = Schema.Union([
ServerAuthBootstrapCredentialValidationError,
ServerAuthSessionCredentialValidationError,
ServerAuthAuthenticatedSessionIssueError,
ServerAuthAuthenticatedAccessTokenIssueError,
ServerAuthPairingLinkCreationError,
ServerAuthPairingLinksListError,
ServerAuthPairingLinkRevocationError,
ServerAuthSessionTokenIssueError,
ServerAuthSessionsListError,
ServerAuthSessionRevocationError,
ServerAuthOtherSessionsRevocationError,
ServerAuthWebSocketTokenIssueError,
ServerAuthDpopReplayStateRecordError,
ServerAuthDpopReplayKeyCalculationError,
ServerAuthLinkedCloudAccountVerificationError,
ServerAuthLinkedCloudAccountReadError,
ServerAuthLinkedCloudAccountMissingError,
ServerAuthCloudLinkJwtSigningError,
ServerAuthCloudMintPublicKeyMissingError,
ServerAuthCloudRelayIssuerMissingError,
ServerAuthCloudHealthJwtSigningError,
ServerAuthCloudMintJwtSigningError,
]);
export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
export class ServerAuthMissingCredentialError extends Schema.TaggedErrorClass<ServerAuthMissingCredentialError>()(
"ServerAuthMissingCredentialError",
{},
) {
override get message(): string {
return "Server authentication credential is missing.";
}
}
export class ServerAuthInvalidCredentialError extends Schema.TaggedErrorClass<ServerAuthInvalidCredentialError>()(
"ServerAuthInvalidCredentialError",
{
diagnostic: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return "Server authentication credential is invalid.";
}
}
export const ServerAuthCredentialError = Schema.Union([
ServerAuthMissingCredentialError,
ServerAuthInvalidCredentialError,
]);
export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
export const serverAuthCredentialReason = (
error: ServerAuthCredentialError,
): "missing_credential" | "invalid_credential" =>
error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
"ServerAuthInvalidScopeError",
{},
) {
override get message(): string {
return "The requested authentication scope is invalid.";
}
}
export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
"ServerAuthScopeNotGrantedError",
{},
) {
override get message(): string {
return "The requested authentication scope was not granted.";
}
}
export const ServerAuthInvalidRequestError = Schema.Union([
ServerAuthInvalidScopeError,
ServerAuthScopeNotGrantedError,
]);
export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
export const serverAuthInvalidRequestReason = (
error: ServerAuthInvalidRequestError,
): "invalid_scope" | "scope_not_granted" =>
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
"ServerAuthForbiddenOperationError",
{},
) {
override get message(): string {
return "The current authentication session cannot revoke itself.";
}
}
export class EnvironmentAuth extends Context.Service<
EnvironmentAuth,
{
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
readonly getSessionState: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
readonly createBrowserSession: (
credential: string,
requestMetadata: AuthClientMetadata,
) => Effect.Effect<
{
readonly response: AuthBrowserSessionResult;
readonly sessionToken: string;
},
ServerAuthInvalidCredentialError | ServerAuthInternalError
>;
readonly exchangeBootstrapCredentialForAccessToken: (
credential: string,
requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
requestMetadata: AuthClientMetadata,
input?: {
readonly proofKeyThumbprint?: string;
},
) => Effect.Effect<
AuthAccessTokenResult,
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
>;
readonly createPairingLink: (input?: {
readonly ttl?: Duration.Duration;
readonly label?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
readonly issueStartupPairingCredential: () => Effect.Effect<
AuthPairingCredentialResult,
ServerAuthInternalError
>;
readonly listPairingLinks: (input?: {
readonly excludeSubjects?: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly issueSession: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
ServerAuthInternalError
>;
readonly revokeSession: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly revokeOtherSessionsExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthInternalError>;
readonly listClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
readonly revokeClientSession: (
currentSessionId: AuthSessionId,
targetSessionId: AuthSessionId,
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthInternalError>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly issueWebSocketTicket: (
session: Pick<AuthenticatedSession, "sessionId">,
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
readonly issueStartupPairingUrl: (
baseUrl: string,
) => Effect.Effect<string, ServerAuthInternalError>;
}
>()("t3/auth/EnvironmentAuth") {}
type BootstrapExchangeResult = {
readonly response: AuthBrowserSessionResult;
@@ -206,23 +512,14 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
};
const toInternalError =
(message: string) =>
(cause: unknown): ServerAuthInternalError =>
new ServerAuthInternalError({ message, cause });
export function toBootstrapExchangeError(
cause: PairingGrantStore.BootstrapCredentialError,
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
if (cause._tag === "BootstrapCredentialInternalError") {
return new ServerAuthInternalError({
message: "Failed to validate bootstrap credential.",
cause,
});
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
return new ServerAuthBootstrapCredentialValidationError({ cause });
}
return new ServerAuthInvalidCredentialError({
reason: "invalid_credential",
cause,
});
}
@@ -231,17 +528,11 @@ const mapSessionVerificationErrors = <A, R>(
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
effect.pipe(
Effect.catchTags({
SessionCredentialInvalidError: (cause) =>
Effect.fail(new ServerAuthInvalidCredentialError({ reason: "invalid_credential", cause })),
SessionCredentialInternalError: (cause) =>
Effect.fail(
new ServerAuthInternalError({
message: "Failed to validate session credential.",
cause,
}),
),
}),
Effect.mapError((cause) =>
SessionStore.isSessionCredentialInvalidError(cause)
? new ServerAuthInvalidCredentialError({ cause })
: new ServerAuthSessionCredentialValidationError({ cause }),
),
);
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
@@ -262,7 +553,7 @@ function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string |
return token.length > 0 ? token : null;
}
export const make = Effect.fn("makeEnvironmentAuth")(function* () {
export const make = Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const sessions = yield* SessionStore.SessionStore;
@@ -277,12 +568,14 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
ServerAuthInvalidCredentialError | ServerAuthInternalError
> =>
sessions.verify(token).pipe(
Effect.tapErrorTag("SessionCredentialInvalidError", (cause) =>
Effect.logWarning("Rejected authenticated session credential.").pipe(
Effect.annotateLogs({
reason: cause.message,
}),
),
Effect.tapError((cause) =>
SessionStore.isSessionCredentialInvalidError(cause)
? Effect.logWarning("Rejected authenticated session credential.").pipe(
Effect.annotateLogs({
reason: cause.message,
}),
)
: Effect.void,
),
Effect.map((session) => ({
sessionId: session.sessionId,
@@ -295,13 +588,15 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
mapSessionVerificationErrors,
);
const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
const authenticateRequest = (
request: HttpServerRequest.HttpServerRequest,
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
const cookieToken = request.cookies[sessions.cookieName];
const bearerToken = parseBearerToken(request);
const dpopToken = parseDpopToken(request);
const credential = cookieToken ?? bearerToken ?? dpopToken;
if (!credential) {
return Effect.fail(new ServerAuthInvalidCredentialError({ reason: "missing_credential" }));
return Effect.fail(new ServerAuthMissingCredentialError({}));
}
return authenticateToken(credential).pipe(
Effect.flatMap((session) => {
@@ -309,8 +604,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
if (!dpopToken || dpopToken !== credential) {
return Effect.fail(
new ServerAuthInvalidCredentialError({
reason: "invalid_credential",
cause: "DPoP-bound access token requires DPoP authorization.",
diagnostic: "DPoP-bound access token requires DPoP authorization.",
}),
);
}
@@ -327,8 +621,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
if (dpopToken) {
return Effect.fail(
new ServerAuthInvalidCredentialError({
reason: "invalid_credential",
cause: "DPoP authorization requires a proof-bound access token.",
diagnostic: "DPoP authorization requires a proof-bound access token.",
}),
);
}
@@ -337,7 +630,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
);
};
const getSessionState: EnvironmentAuthShape["getSessionState"] = (request) =>
const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
authenticateRequest(request).pipe(
Effect.map(
(session) =>
@@ -349,7 +642,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
}) satisfies AuthSessionState,
),
Effect.catchTag("ServerAuthInvalidCredentialError", () =>
Effect.catchIf(isServerAuthCredentialError, () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
@@ -358,7 +651,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
Effect.withSpan("EnvironmentAuth.getSessionState"),
);
const createBrowserSession: EnvironmentAuthShape["createBrowserSession"] = (
const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = (
credential,
requestMetadata,
) =>
@@ -376,13 +669,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
},
})
.pipe(
Effect.mapError(
(cause) =>
new ServerAuthInternalError({
message: "Failed to issue authenticated session.",
cause,
}),
),
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
),
),
Effect.map(
@@ -400,7 +687,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
Effect.withSpan("EnvironmentAuth.createBrowserSession"),
);
const exchangeBootstrapCredentialForAccessToken: EnvironmentAuthShape["exchangeBootstrapCredentialForAccessToken"] =
const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
(credential, requestedScopes, requestMetadata, input) =>
bootstrapCredentials.consume(credential, input).pipe(
Effect.mapError(toBootstrapExchangeError),
@@ -408,9 +695,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
Effect.gen(function* () {
const grantedScopes = requestedScopes ?? grant.scopes;
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
return yield* new ServerAuthInvalidRequestError({
reason: "scope_not_granted",
});
return yield* new ServerAuthScopeNotGrantedError({});
}
return yield* sessions
.issue({
@@ -430,11 +715,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
})
.pipe(
Effect.mapError(
(cause) =>
new ServerAuthInternalError({
message: "Failed to issue authenticated access token.",
cause,
}),
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
),
);
}),
@@ -482,7 +763,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
),
);
const createPairingLink: EnvironmentAuthShape["createPairingLink"] = Effect.fn(
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
"EnvironmentAuth.createPairingLink",
)(
function* (input) {
@@ -504,10 +785,10 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
},
Effect.mapError(toInternalError("Failed to create pairing link.")),
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
);
const listPairingLinks: EnvironmentAuthShape["listPairingLinks"] = (input) =>
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
Effect.map((pairingLinks) => {
const excludedSubjects = input?.excludeSubjects ?? [
@@ -519,19 +800,17 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
);
}),
Effect.mapError(toInternalError("Failed to list pairing links.")),
Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
Effect.withSpan("EnvironmentAuth.listPairingLinks"),
);
const revokePairingLink: EnvironmentAuthShape["revokePairingLink"] = (id) =>
bootstrapCredentials
.revoke(id)
.pipe(
Effect.mapError(toInternalError("Failed to revoke pairing link.")),
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
);
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
bootstrapCredentials.revoke(id).pipe(
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
);
const issueSession: EnvironmentAuthShape["issueSession"] = (input) =>
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
sessions
.issue({
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
@@ -556,49 +835,46 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
expiresAt: DateTime.toUtc(issued.expiresAt),
}) satisfies IssuedBearerSession,
),
Effect.mapError(toInternalError("Failed to issue session token.")),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueSession"),
);
const listSessions: EnvironmentAuthShape["listSessions"] = () =>
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
sessions.listActive().pipe(
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
Effect.mapError(toInternalError("Failed to list sessions.")),
Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
Effect.withSpan("EnvironmentAuth.listSessions"),
);
const revokeSession: EnvironmentAuthShape["revokeSession"] = (sessionId) =>
sessions
.revoke(sessionId)
.pipe(
Effect.mapError(toInternalError("Failed to revoke session.")),
Effect.withSpan("EnvironmentAuth.revokeSession"),
);
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
sessions.revoke(sessionId).pipe(
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeSession"),
);
const revokeOtherSessionsExcept: EnvironmentAuthShape["revokeOtherSessionsExcept"] = (
const revokeOtherSessionsExcept: EnvironmentAuth["Service"]["revokeOtherSessionsExcept"] = (
sessionId,
) =>
sessions
.revokeAllExcept(sessionId)
.pipe(
Effect.mapError(toInternalError("Failed to revoke other sessions.")),
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
);
sessions.revokeAllExcept(sessionId).pipe(
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
);
const issuePairingCredential: EnvironmentAuthShape["issuePairingCredential"] = (input) =>
const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
issuePairingCredentialForSubject({
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: "one-time-token",
...(input?.label ? { label: input.label } : {}),
}).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
const issueStartupPairingCredential: EnvironmentAuthShape["issueStartupPairingCredential"] = () =>
issuePairingCredentialForSubject({
scopes: AuthAdministrativeScopes,
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
() =>
issuePairingCredentialForSubject({
scopes: AuthAdministrativeScopes,
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
const listClientSessions: EnvironmentAuthShape["listClientSessions"] = (currentSessionId) =>
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
listSessions().pipe(
Effect.map((clientSessions) =>
clientSessions.map(
@@ -611,25 +887,23 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
Effect.withSpan("EnvironmentAuth.listClientSessions"),
);
const revokeClientSession: EnvironmentAuthShape["revokeClientSession"] = Effect.fn(
const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
"EnvironmentAuth.revokeClientSession",
)(function* (currentSessionId, targetSessionId) {
if (currentSessionId === targetSessionId) {
return yield* new ServerAuthForbiddenOperationError({
reason: "current_session_revoke_not_allowed",
});
return yield* new ServerAuthForbiddenOperationError({});
}
return yield* revokeSession(targetSessionId);
});
const revokeOtherClientSessions: EnvironmentAuthShape["revokeOtherClientSessions"] = (
const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
currentSessionId,
) =>
revokeOtherSessionsExcept(currentSessionId).pipe(
Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
);
const issueStartupPairingUrl: EnvironmentAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
issueStartupPairingCredential().pipe(
Effect.map((issued) => {
const url = new URL(baseUrl);
@@ -641,15 +915,9 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
);
const issueWebSocketTicket: EnvironmentAuthShape["issueWebSocketTicket"] = (session) =>
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
sessions.issueWebSocketToken(session.sessionId).pipe(
Effect.mapError(
(cause) =>
new ServerAuthInternalError({
message: "Failed to issue websocket token.",
cause,
}),
),
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
Effect.map(
(issued) =>
({
@@ -660,10 +928,12 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
);
const authenticateHttpRequest: EnvironmentAuthShape["authenticateHttpRequest"] = (request) =>
const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
request,
) =>
authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
const authenticateWebSocketUpgrade: EnvironmentAuthShape["authenticateWebSocketUpgrade"] =
const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
const requestUrl = HttpServerRequest.toURL(request);
if (Option.isSome(requestUrl)) {
@@ -685,7 +955,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
return yield* authenticateRequest(request);
});
return {
return EnvironmentAuth.of({
getDescriptor: () =>
Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
getSessionState,
@@ -707,10 +977,10 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
authenticateWebSocketUpgrade,
issueWebSocketTicket,
issueStartupPairingUrl,
} satisfies EnvironmentAuthShape;
});
});
export const layer = Layer.effect(EnvironmentAuth, make()).pipe(
export const layer = Layer.effect(EnvironmentAuth, make).pipe(
Layer.provideMerge(PairingGrantStore.layer),
Layer.provideMerge(SessionStore.layer),
Layer.provideMerge(EnvironmentAuthPolicy.layer),
@@ -22,7 +22,11 @@ const makeServerConfigLayer = (
} satisfies ServerConfig.ServerConfig["Service"];
}),
).pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-auth-control-plane-test-",
}),
),
);
const makeEnvironmentAuthLayer = (
+9 -11
View File
@@ -3,21 +3,19 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
import { resolveSessionCookieName } from "./utils.ts";
import { isLoopbackHost, isWildcardHost } from "../startupAccess.ts";
export interface EnvironmentAuthPolicyShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
}
export class EnvironmentAuthPolicy extends Context.Service<
EnvironmentAuthPolicy,
EnvironmentAuthPolicyShape
{
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
}
>()("t3/auth/EnvironmentAuthPolicy") {}
export const make = Effect.fn("makeEnvironmentAuthPolicy")(function* () {
const config = yield* ServerConfig;
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
const policy =
@@ -46,10 +44,10 @@ export const make = Effect.fn("makeEnvironmentAuthPolicy")(function* () {
}),
};
return {
return EnvironmentAuthPolicy.of({
getDescriptor: () =>
Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuthPolicy.getDescriptor")),
} satisfies EnvironmentAuthPolicyShape;
});
});
export const layer = Layer.effect(EnvironmentAuthPolicy, make());
export const layer = Layer.effect(EnvironmentAuthPolicy, make);
@@ -61,7 +61,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
expect(first.subject).toBe("one-time-token");
expect(first.label).toBe("Julius iPhone");
expect(issued.label).toBe("Julius iPhone");
expect(second._tag).toBe("BootstrapCredentialInvalidError");
expect(second._tag).toBe("UnknownBootstrapCredentialError");
expect(second.message).toContain("Unknown bootstrap credential");
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
);
@@ -85,7 +85,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
expect(successes).toHaveLength(1);
expect(failures).toHaveLength(7);
for (const failure of failures) {
expect(failure.failure._tag).toBe("BootstrapCredentialInvalidError");
expect(failure.failure._tag).toBe("UnknownBootstrapCredentialError");
expect(failure.failure.message).toContain("Unknown bootstrap credential");
}
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
@@ -132,7 +132,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
"relay:write",
]);
expect(first.subject).toBe("desktop-bootstrap");
expect(second._tag).toBe("BootstrapCredentialInvalidError");
expect(second._tag).toBe("UnknownBootstrapCredentialError");
}).pipe(
Effect.provide(
makePairingGrantStoreLayer({
@@ -149,7 +149,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
yield* TestClock.adjust(Duration.minutes(6));
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
expect(expired._tag).toBe("BootstrapCredentialInvalidError");
expect(expired._tag).toBe("ExpiredBootstrapCredentialError");
expect(expired.message).toContain("Bootstrap credential expired");
}).pipe(
Effect.provide(
@@ -183,7 +183,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
expect(revokedConsume.message).toContain("no longer available");
expect(revokedConsume._tag).toBe("BootstrapCredentialInvalidError");
expect(revokedConsume._tag).toBe("UnavailableBootstrapCredentialError");
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
);
});
+150 -82
View File
@@ -7,17 +7,17 @@ import {
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
export interface BootstrapGrant {
@@ -29,22 +29,110 @@ export interface BootstrapGrant {
readonly expiresAt: DateTime.DateTime;
}
export class BootstrapCredentialInvalidError extends Data.TaggedError(
"BootstrapCredentialInvalidError",
)<{
readonly message: string;
}> {}
export class UnknownBootstrapCredentialError extends Schema.TaggedErrorClass<UnknownBootstrapCredentialError>()(
"UnknownBootstrapCredentialError",
{},
) {
override get message(): string {
return "Unknown bootstrap credential.";
}
}
export class BootstrapCredentialInternalError extends Data.TaggedError(
"BootstrapCredentialInternalError",
)<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<ExpiredBootstrapCredentialError>()(
"ExpiredBootstrapCredentialError",
{},
) {
override get message(): string {
return "Bootstrap credential expired.";
}
}
export type BootstrapCredentialError =
| BootstrapCredentialInvalidError
| BootstrapCredentialInternalError;
export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedErrorClass<BootstrapCredentialProofKeyMismatchError>()(
"BootstrapCredentialProofKeyMismatchError",
{},
) {
override get message(): string {
return "Bootstrap credential proof key mismatch.";
}
}
export class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClass<UnavailableBootstrapCredentialError>()(
"UnavailableBootstrapCredentialError",
{},
) {
override get message(): string {
return "Bootstrap credential is no longer available.";
}
}
export const BootstrapCredentialInvalidError = Schema.Union([
UnknownBootstrapCredentialError,
ExpiredBootstrapCredentialError,
BootstrapCredentialProofKeyMismatchError,
UnavailableBootstrapCredentialError,
]);
export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
export const isBootstrapCredentialInvalidError = Schema.is(BootstrapCredentialInvalidError);
export class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActivePairingLinksLoadError>()(
"ActivePairingLinksLoadError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to load active pairing links.";
}
}
export class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(
"PairingLinkRevokeError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to revoke pairing link.";
}
}
export class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(
"PairingCredentialIssueError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to issue pairing credential.";
}
}
export class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeError>()(
"BootstrapCredentialConsumeError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to consume bootstrap credential.";
}
}
export const BootstrapCredentialInternalError = Schema.Union([
ActivePairingLinksLoadError,
PairingLinkRevokeError,
PairingCredentialIssueError,
BootstrapCredentialConsumeError,
]);
export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
export const BootstrapCredentialError = Schema.Union([
BootstrapCredentialInvalidError,
BootstrapCredentialInternalError,
]);
export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
export const isBootstrapCredentialError = Schema.is(BootstrapCredentialError);
export interface IssuedBootstrapCredential {
readonly id: string;
@@ -64,31 +152,30 @@ export type BootstrapCredentialChange =
readonly id: string;
};
export interface PairingGrantStoreShape {
readonly issueOneTimeToken: (input?: {
readonly ttl?: Duration.Duration;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly label?: string;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthPairingLink>,
BootstrapCredentialInternalError
>;
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
readonly consume: (
credential: string,
input?: {
export class PairingGrantStore extends Context.Service<
PairingGrantStore,
{
readonly issueOneTimeToken: (input?: {
readonly ttl?: Duration.Duration;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly label?: string;
readonly proofKeyThumbprint?: string;
},
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
}
export class PairingGrantStore extends Context.Service<PairingGrantStore, PairingGrantStoreShape>()(
"t3/auth/PairingGrantStore",
) {}
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthPairingLink>,
BootstrapCredentialInternalError
>;
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
readonly consume: (
credential: string,
input?: {
readonly proofKeyThumbprint?: string;
},
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
}
>()("t3/auth/PairingGrantStore") {}
interface StoredBootstrapGrant extends BootstrapGrant {
readonly remainingUses: number | "unbounded";
@@ -111,20 +198,9 @@ const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
const invalidBootstrapCredentialError = (message: string) =>
new BootstrapCredentialInvalidError({
message,
});
const internalBootstrapCredentialError = (message: string, cause: unknown) =>
new BootstrapCredentialInternalError({
message,
cause,
});
export const make = Effect.fn("makePairingGrantStore")(function* () {
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const config = yield* ServerConfig;
const config = yield* ServerConfig.ServerConfig;
const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
@@ -177,10 +253,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
});
}
const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
internalBootstrapCredentialError(message, cause);
const listActive: PairingGrantStoreShape["listActive"] = Effect.fn(
const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
"PairingGrantStore.listActive",
)(
function* () {
@@ -208,10 +281,10 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
} satisfies AuthPairingLink),
);
},
Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")),
Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
);
const revoke: PairingGrantStoreShape["revoke"] = Effect.fn("PairingGrantStore.revoke")(
const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
function* (id) {
const revokedAt = yield* DateTime.now;
const revoked = yield* pairingLinks.revoke({
@@ -223,10 +296,10 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
}
return revoked;
},
Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")),
Effect.mapError((cause) => new PairingLinkRevokeError({ cause })),
);
const issueOneTimeToken: PairingGrantStoreShape["issueOneTimeToken"] = Effect.fn(
const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
"PairingGrantStore.issueOneTimeToken",
)(
function* (input) {
@@ -264,10 +337,10 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
});
return issued;
},
Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")),
Effect.mapError((cause) => new PairingCredentialIssueError({ cause })),
);
const consume: PairingGrantStoreShape["consume"] = Effect.fn("PairingGrantStore.consume")(
const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
function* (credential, input) {
const now = yield* DateTime.now;
const seededResult: ConsumeResult = yield* Ref.modify(
@@ -279,7 +352,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
{
_tag: "error",
reason: "not-found",
error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
error: new UnknownBootstrapCredentialError({}),
},
current,
];
@@ -292,7 +365,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
{
_tag: "error",
reason: "expired",
error: invalidBootstrapCredentialError("Bootstrap credential expired."),
error: new ExpiredBootstrapCredentialError({}),
},
next,
];
@@ -303,7 +376,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
{
_tag: "error",
reason: "not-found",
error: invalidBootstrapCredentialError("Bootstrap credential proof key mismatch."),
error: new BootstrapCredentialProofKeyMismatchError({}),
},
next,
];
@@ -370,41 +443,36 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
const matching = yield* pairingLinks.getByCredential({ credential });
if (Option.isNone(matching)) {
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
return yield* new UnknownBootstrapCredentialError({});
}
if (matching.value.revokedAt !== null) {
return yield* invalidBootstrapCredentialError(
"Bootstrap credential is no longer available.",
);
return yield* new UnavailableBootstrapCredentialError({});
}
if (matching.value.consumedAt !== null) {
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
return yield* new UnknownBootstrapCredentialError({});
}
if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
return yield* new ExpiredBootstrapCredentialError({});
}
if (
matching.value.proofKeyThumbprint !== null &&
matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
) {
return yield* invalidBootstrapCredentialError("Bootstrap credential proof key mismatch.");
return yield* new BootstrapCredentialProofKeyMismatchError({});
}
return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
return yield* new UnavailableBootstrapCredentialError({});
},
Effect.mapError((cause) =>
cause._tag === "BootstrapCredentialInvalidError" ||
cause._tag === "BootstrapCredentialInternalError"
? cause
: internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
isBootstrapCredentialError(cause) ? cause : new BootstrapCredentialConsumeError({ cause }),
),
);
return {
return PairingGrantStore.of({
issueOneTimeToken,
listActive,
get streamChanges() {
@@ -412,9 +480,9 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
},
revoke,
consume,
} satisfies PairingGrantStoreShape;
});
});
export const layer = Layer.effect(PairingGrantStore, make()).pipe(
export const layer = Layer.effect(PairingGrantStore, make).pipe(
Layer.provideMerge(AuthPairingLinks.layer),
);
@@ -9,7 +9,7 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
const makeServerConfigLayer = () =>
@@ -231,7 +231,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
assert.include(error.message, "Failed to read secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
@@ -246,7 +246,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
);
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
assert.include(error.message, "Failed to persist secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
@@ -259,7 +259,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
assert.include(error.message, "Failed to remove secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
+157 -48
View File
@@ -9,49 +9,158 @@ import * as Predicate from "effect/Predicate";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
export class SecretStoreError extends Schema.TaggedErrorClass<SecretStoreError>()(
"SecretStoreError",
const secretStoreErrorContext = {
resource: Schema.String,
cause: Schema.Defect(),
};
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
"SecretStoreSecureError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
...secretStoreErrorContext,
},
) {}
) {
override get message(): string {
return `Failed to secure ${this.resource}.`;
}
}
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
"SecretStoreReadError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to read ${this.resource}.`;
}
}
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
"SecretStoreTemporaryPathError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to create temporary path for ${this.resource}.`;
}
}
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
"SecretStorePersistError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to persist ${this.resource}.`;
}
}
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
"SecretStoreRandomGenerationError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to generate random bytes for ${this.resource}.`;
}
}
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
"SecretStoreConcurrentReadError",
{
resource: Schema.String,
},
) {
override get message(): string {
return `Failed to read ${this.resource} after concurrent creation.`;
}
}
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
"SecretStoreRemoveError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to remove ${this.resource}.`;
}
}
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
"SecretStoreDecodeError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to decode ${this.resource}.`;
}
}
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
"SecretStoreEncodeError",
{
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to encode ${this.resource}.`;
}
}
export const SecretStoreError = Schema.Union([
SecretStoreSecureError,
SecretStoreReadError,
SecretStoreTemporaryPathError,
SecretStorePersistError,
SecretStoreRandomGenerationError,
SecretStoreConcurrentReadError,
SecretStoreRemoveError,
SecretStoreDecodeError,
SecretStoreEncodeError,
]);
export type SecretStoreError = typeof SecretStoreError.Type;
export const isSecretStoreError = Schema.is(SecretStoreError);
const isPlatformError = (value: unknown): value is PlatformError.PlatformError =>
Predicate.isTagged(value, "PlatformError");
export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists";
"cause" in error && isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists";
export interface ServerSecretStoreShape {
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
name: string,
bytes: number,
) => Effect.Effect<Uint8Array, SecretStoreError>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
export class ServerSecretStore extends Context.Service<
ServerSecretStore,
{
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
name: string,
bytes: number,
) => Effect.Effect<Uint8Array, SecretStoreError>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
>()("t3/auth/ServerSecretStore") {}
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
"t3/auth/ServerSecretStore",
) {}
export const make = Effect.fn("makeServerSecretStore")(function* () {
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const serverConfig = yield* ServerConfig.ServerConfig;
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
new SecretStoreSecureError({
resource: `secrets directory ${serverConfig.secretsDir}`,
cause,
}),
),
@@ -59,15 +168,15 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
const get: ServerSecretStoreShape["get"] = (name) =>
const get: ServerSecretStore["Service"]["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name}.`,
new SecretStoreReadError({
resource: `secret ${name}`,
cause,
}),
),
@@ -75,13 +184,13 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
Effect.withSpan("ServerSecretStore.get"),
);
const set: ServerSecretStoreShape["set"] = (name, value) => {
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
const secretPath = resolveSecretPath(name);
return crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to create temporary path for secret ${name}.`,
new SecretStoreTemporaryPathError({
resource: `secret ${name}`,
cause,
}),
),
@@ -98,8 +207,8 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
Effect.ignore,
Effect.flatMap(() =>
Effect.fail(
new SecretStoreError({
message: `Failed to persist secret ${name}.`,
new SecretStorePersistError({
resource: `secret ${name}`,
cause,
}),
),
@@ -112,7 +221,7 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
);
};
const create: ServerSecretStoreShape["create"] = (name, value) => {
const create: ServerSecretStore["Service"]["create"] = (name, value) => {
const secretPath = resolveSecretPath(name);
return Effect.scoped(
Effect.gen(function* () {
@@ -127,15 +236,15 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to persist secret ${name}.`,
new SecretStorePersistError({
resource: `secret ${name}`,
cause,
}),
),
);
};
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
const getOrCreateRandom: ServerSecretStore["Service"]["getOrCreateRandom"] = (name, bytes) =>
get(name).pipe(
Effect.flatMap(
Option.match({
@@ -144,15 +253,15 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
crypto.randomBytes(bytes).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate random bytes for secret ${name}.`,
new SecretStoreRandomGenerationError({
resource: `secret ${name}`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
Effect.catchIf(isSecretStoreError, (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
@@ -160,8 +269,8 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
new SecretStoreConcurrentReadError({
resource: `secret ${name}`,
}),
),
}),
@@ -177,14 +286,14 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
);
const remove: ServerSecretStoreShape["remove"] = (name) =>
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
fileSystem.remove(resolveSecretPath(name)).pipe(
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.void
: Effect.fail(
new SecretStoreError({
message: `Failed to remove secret ${name}.`,
new SecretStoreRemoveError({
resource: `secret ${name}`,
cause,
}),
),
@@ -192,13 +301,13 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
Effect.withSpan("ServerSecretStore.remove"),
);
return {
return ServerSecretStore.of({
get,
set,
create,
getOrCreateRandom,
remove,
} satisfies ServerSecretStoreShape;
});
});
export const layer = Layer.effect(ServerSecretStore, make());
export const layer = Layer.effect(ServerSecretStore, make);
+4 -4
View File
@@ -51,7 +51,7 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
const failingSessionLookupCredentialLayer = Layer.effect(
SessionStore.SessionStore,
SessionStore.make(),
SessionStore.make,
).pipe(
Layer.provide(failingSessionLookupRepositoryLayer),
Layer.provide(ServerSecretStore.layer),
@@ -89,7 +89,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
const sessions = yield* SessionStore.SessionStore;
const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
expect(error._tag).toBe("SessionCredentialInvalidError");
expect(error._tag).toBe("MalformedSessionTokenError");
expect(error.message).toContain("Malformed session token");
}).pipe(Effect.provide(makeSessionStoreLayer())),
);
@@ -105,8 +105,8 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(sessionError._tag).toBe("SessionCredentialInternalError");
expect(websocketError._tag).toBe("SessionCredentialInternalError");
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
expect(sessionError.cause).toBe(repositoryFailure);
expect(websocketError.cause).toBe(repositoryFailure);
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
+343 -150
View File
@@ -10,7 +10,6 @@ import {
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -21,7 +20,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
import * as AuthSessions from "../persistence/AuthSessions.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import {
@@ -63,66 +62,311 @@ export type SessionCredentialChange =
readonly sessionId: AuthSessionId;
};
export class SessionCredentialInvalidError extends Data.TaggedError(
"SessionCredentialInvalidError",
)<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SessionCredentialInternalError extends Data.TaggedError(
"SessionCredentialInternalError",
)<{
readonly message: string;
readonly cause?: unknown;
}> {}
export type SessionCredentialError = SessionCredentialInvalidError | SessionCredentialInternalError;
export interface SessionStoreShape {
readonly cookieName: string;
readonly issue: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly method?: ServerAuthSessionMethod;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly client?: AuthClientMetadata;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
readonly issueWebSocketToken: (
sessionId: AuthSessionId,
input?: {
readonly ttl?: Duration.Duration;
},
) => Effect.Effect<
{
readonly token: string;
readonly expiresAt: DateTime.DateTime;
},
SessionCredentialInternalError
>;
readonly verifyWebSocketToken: (
token: string,
) => Effect.Effect<VerifiedSession, SessionCredentialError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
SessionCredentialInternalError
>;
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
readonly revoke: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, SessionCredentialInternalError>;
readonly revokeAllExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, SessionCredentialInternalError>;
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
export class MalformedSessionTokenError extends Schema.TaggedErrorClass<MalformedSessionTokenError>()(
"MalformedSessionTokenError",
{},
) {
override get message(): string {
return "Malformed session token.";
}
}
export class SessionStore extends Context.Service<SessionStore, SessionStoreShape>()(
"t3/auth/SessionStore",
) {}
export class InvalidSessionTokenSignatureError extends Schema.TaggedErrorClass<InvalidSessionTokenSignatureError>()(
"InvalidSessionTokenSignatureError",
{},
) {
override get message(): string {
return "Invalid session token signature.";
}
}
export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<InvalidSessionTokenPayloadError>()(
"InvalidSessionTokenPayloadError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Invalid session token payload.";
}
}
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
"SessionTokenExpiredError",
{},
) {
override get message(): string {
return "Session token expired.";
}
}
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
"UnknownSessionTokenError",
{},
) {
override get message(): string {
return "Unknown session token.";
}
}
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
"SessionTokenRevokedError",
{},
) {
override get message(): string {
return "Session token revoked.";
}
}
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
"InvalidSessionExpirationClaimError",
{},
) {
override get message(): string {
return "Invalid `exp` claim";
}
}
export class MalformedWebSocketTokenError extends Schema.TaggedErrorClass<MalformedWebSocketTokenError>()(
"MalformedWebSocketTokenError",
{},
) {
override get message(): string {
return "Malformed websocket token.";
}
}
export class InvalidWebSocketTokenSignatureError extends Schema.TaggedErrorClass<InvalidWebSocketTokenSignatureError>()(
"InvalidWebSocketTokenSignatureError",
{},
) {
override get message(): string {
return "Invalid websocket token signature.";
}
}
export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<InvalidWebSocketTokenPayloadError>()(
"InvalidWebSocketTokenPayloadError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Invalid websocket token payload.";
}
}
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
"WebSocketTokenExpiredError",
{},
) {
override get message(): string {
return "Websocket token expired.";
}
}
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
"UnknownWebSocketSessionError",
{},
) {
override get message(): string {
return "Unknown websocket session.";
}
}
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
"WebSocketSessionExpiredError",
{},
) {
override get message(): string {
return "Websocket session expired.";
}
}
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
"WebSocketSessionRevokedError",
{},
) {
override get message(): string {
return "Websocket session revoked.";
}
}
export const SessionCredentialInvalidError = Schema.Union([
MalformedSessionTokenError,
InvalidSessionTokenSignatureError,
InvalidSessionTokenPayloadError,
SessionTokenExpiredError,
UnknownSessionTokenError,
SessionTokenRevokedError,
InvalidSessionExpirationClaimError,
MalformedWebSocketTokenError,
InvalidWebSocketTokenSignatureError,
InvalidWebSocketTokenPayloadError,
WebSocketTokenExpiredError,
UnknownWebSocketSessionError,
WebSocketSessionExpiredError,
WebSocketSessionRevokedError,
]);
export type SessionCredentialInvalidError = typeof SessionCredentialInvalidError.Type;
export const isSessionCredentialInvalidError = Schema.is(SessionCredentialInvalidError);
const sessionCredentialInternalErrorContext = {
cause: Schema.Defect(),
};
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
"SessionClaimsEncodingError",
{
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to encode claims";
}
}
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
"SessionCredentialIssueError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to issue session credential.";
}
}
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
"SessionCredentialVerificationError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to verify session credential.";
}
}
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
"WebSocketTokenIssueError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to issue websocket token.";
}
}
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
"WebSocketTokenVerificationError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to verify websocket token.";
}
}
export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessionsListError>()(
"ActiveSessionsListError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to list active sessions.";
}
}
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
"SessionRevocationError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke session.";
}
}
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
"OtherSessionsRevocationError",
{
...sessionCredentialInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke other sessions.";
}
}
export const SessionCredentialInternalError = Schema.Union([
SessionClaimsEncodingError,
SessionCredentialIssueError,
SessionCredentialVerificationError,
WebSocketTokenIssueError,
WebSocketTokenVerificationError,
ActiveSessionsListError,
SessionRevocationError,
OtherSessionsRevocationError,
]);
export type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type;
export const isSessionCredentialInternalError = Schema.is(SessionCredentialInternalError);
export const SessionCredentialError = Schema.Union([
SessionCredentialInvalidError,
SessionCredentialInternalError,
]);
export type SessionCredentialError = typeof SessionCredentialError.Type;
export const isSessionCredentialError = Schema.is(SessionCredentialError);
export class SessionStore extends Context.Service<
SessionStore,
{
readonly cookieName: string;
readonly issue: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly method?: ServerAuthSessionMethod;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly client?: AuthClientMetadata;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
readonly issueWebSocketToken: (
sessionId: AuthSessionId,
input?: {
readonly ttl?: Duration.Duration;
},
) => Effect.Effect<
{
readonly token: string;
readonly expiresAt: DateTime.DateTime;
},
SessionCredentialInternalError
>;
readonly verifyWebSocketToken: (
token: string,
) => Effect.Effect<VerifiedSession, SessionCredentialError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
SessionCredentialInternalError
>;
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
readonly revoke: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, SessionCredentialInternalError>;
readonly revokeAllExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, SessionCredentialInternalError>;
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
}
>()("t3/auth/SessionStore") {}
const SIGNING_SECRET_NAME = "server-signing-key";
const DEFAULT_SESSION_TTL = Duration.days(30);
@@ -184,15 +428,9 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
};
}
const toSessionCredentialInternalError = (message: string) => (cause: unknown) =>
new SessionCredentialInternalError({
message,
cause,
});
export const make = Effect.fn("makeSessionStore")(function* () {
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* ServerConfig;
const serverConfig = yield* ServerConfig.ServerConfig;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const authSessions = yield* AuthSessions.AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
@@ -238,7 +476,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
);
});
const markConnected: SessionStoreShape["markConnected"] = (sessionId) =>
const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
Ref.modify(connectedSessionsRef, (current) => {
const next = new Map(current);
const wasDisconnected = !next.has(sessionId);
@@ -272,7 +510,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
Effect.withSpan("SessionStore.markConnected"),
);
const markDisconnected: SessionStoreShape["markDisconnected"] = (sessionId) =>
const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
const remaining = (next.get(sessionId) ?? 0) - 1;
@@ -299,7 +537,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
);
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionStoreShape["issue"] = Effect.fn("SessionStore.issue")(
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
function* (input) {
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
const issuedAt = yield* DateTime.now;
@@ -321,8 +559,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
const encodedPayload = yield* encodeClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new SessionCredentialInternalError({ message: "Failed to encode claims", cause }),
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
@@ -367,59 +604,41 @@ export const make = Effect.fn("makeSessionStore")(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies IssuedSession;
},
Effect.mapError(toSessionCredentialInternalError("Failed to issue session credential.")),
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
);
const verify: SessionStoreShape["verify"] = Effect.fn("SessionStore.verify")(
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new SessionCredentialInvalidError({
message: "Malformed session token.",
});
return yield* new MalformedSessionTokenError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new SessionCredentialInvalidError({
message: "Invalid session token signature.",
});
return yield* new InvalidSessionTokenSignatureError({});
}
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError(
(cause) =>
new SessionCredentialInvalidError({
message: "Invalid session token payload.",
cause,
}),
),
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionCredentialInvalidError({
message: "Session token expired.",
});
return yield* new SessionTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new SessionCredentialInvalidError({
message: "Unknown session token.",
});
return yield* new UnknownSessionTokenError({});
}
if (row.value.revokedAt !== null) {
return yield* new SessionCredentialInvalidError({
message: "Session token revoked.",
});
return yield* new SessionTokenRevokedError({});
}
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new SessionCredentialInvalidError({
message: "Invalid `exp` claim",
});
return yield* new InvalidSessionExpirationClaimError({});
}
return {
@@ -434,17 +653,14 @@ export const make = Effect.fn("makeSessionStore")(function* () {
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
cause._tag === "SessionCredentialInvalidError"
isSessionCredentialInvalidError(cause)
? cause
: new SessionCredentialInternalError({
message: "Failed to verify session credential.",
cause,
}),
: new SessionCredentialVerificationError({ cause }),
),
);
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
const issueWebSocketToken: SessionStoreShape["issueWebSocketToken"] = Effect.fn(
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
"SessionStore.issueWebSocketToken",
)(
function* (sessionId, input) {
@@ -463,7 +679,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new SessionCredentialInternalError({ message: "Failed to encode claims", cause }),
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
@@ -472,59 +688,41 @@ export const make = Effect.fn("makeSessionStore")(function* () {
expiresAt,
};
},
Effect.mapError(toSessionCredentialInternalError("Failed to issue websocket token.")),
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
);
const verifyWebSocketToken: SessionStoreShape["verifyWebSocketToken"] = Effect.fn(
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
"SessionStore.verifyWebSocketToken",
)(
function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new SessionCredentialInvalidError({
message: "Malformed websocket token.",
});
return yield* new MalformedWebSocketTokenError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new SessionCredentialInvalidError({
message: "Invalid websocket token signature.",
});
return yield* new InvalidWebSocketTokenSignatureError({});
}
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError(
(cause) =>
new SessionCredentialInvalidError({
message: "Invalid websocket token payload.",
cause,
}),
),
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionCredentialInvalidError({
message: "Websocket token expired.",
});
return yield* new WebSocketTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new SessionCredentialInvalidError({
message: "Unknown websocket session.",
});
return yield* new UnknownWebSocketSessionError({});
}
if (row.value.expiresAt.epochMilliseconds <= now) {
return yield* new SessionCredentialInvalidError({
message: "Websocket session expired.",
});
return yield* new WebSocketSessionExpiredError({});
}
if (row.value.revokedAt !== null) {
return yield* new SessionCredentialInvalidError({
message: "Websocket session revoked.",
});
return yield* new WebSocketSessionRevokedError({});
}
return {
@@ -538,16 +736,13 @@ export const make = Effect.fn("makeSessionStore")(function* () {
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
cause._tag === "SessionCredentialInvalidError"
isSessionCredentialInvalidError(cause)
? cause
: new SessionCredentialInternalError({
message: "Failed to verify websocket token.",
cause,
}),
: new WebSocketTokenVerificationError({ cause }),
),
);
const listActive: SessionStoreShape["listActive"] = Effect.fn("SessionStore.listActive")(
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
function* () {
const now = yield* DateTime.now;
const connectedSessions = yield* Ref.get(connectedSessionsRef);
@@ -567,10 +762,10 @@ export const make = Effect.fn("makeSessionStore")(function* () {
}),
);
},
Effect.mapError(toSessionCredentialInternalError("Failed to list active sessions.")),
Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
);
const revoke: SessionStoreShape["revoke"] = Effect.fn("SessionStore.revoke")(
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revoked = yield* authSessions.revoke({
@@ -587,10 +782,10 @@ export const make = Effect.fn("makeSessionStore")(function* () {
}
return revoked;
},
Effect.mapError(toSessionCredentialInternalError("Failed to revoke session.")),
Effect.mapError((cause) => new SessionRevocationError({ cause })),
);
const revokeAllExcept: SessionStoreShape["revokeAllExcept"] = Effect.fn(
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
"SessionStore.revokeAllExcept",
)(
function* (sessionId) {
@@ -618,10 +813,10 @@ export const make = Effect.fn("makeSessionStore")(function* () {
}
return revokedSessionIds.length;
},
Effect.mapError(toSessionCredentialInternalError("Failed to revoke other sessions.")),
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
);
return {
return SessionStore.of({
cookieName,
issue,
verify,
@@ -635,9 +830,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
revokeAllExcept,
markConnected,
markDisconnected,
} satisfies SessionStoreShape;
});
});
export const layer = Layer.effect(SessionStore, make()).pipe(
Layer.provideMerge(AuthSessions.layer),
);
export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));
+10 -6
View File
@@ -1,12 +1,12 @@
import { describe, expect, it } from "vite-plus/test";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import { SecretStorePersistError } from "./ServerSecretStore.ts";
import { mapDpopReplayStoreError } from "./dpop.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStoreError({
message: "Failed to persist DPoP proof.",
new SecretStorePersistError({
resource: "DPoP proof",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -17,16 +17,20 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
describe("mapDpopReplayStoreError", () => {
it("reports replay conflicts as invalid credentials", () => {
const error = mapDpopReplayStoreError(storeFailure("AlreadyExists"));
const cause = storeFailure("AlreadyExists");
const error = mapDpopReplayStoreError(cause);
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
if (error._tag === "ServerAuthInvalidCredentialError") {
expect(error.cause).toBe(cause);
}
});
it("reports replay-store availability failures as internal errors", () => {
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
expect(error._tag).toBe("ServerAuthInternalError");
if (error._tag === "ServerAuthInternalError") {
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
expect(error.message).toBe("Failed to record DPoP proof replay state.");
}
});
+17 -13
View File
@@ -5,7 +5,12 @@ import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import {
ServerAuthDpopReplayKeyCalculationError,
ServerAuthDpopReplayStateRecordError,
ServerAuthInvalidCredentialError,
type ServerAuthInternalError,
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
function firstHeaderValue(value: string | undefined): string | undefined {
@@ -26,14 +31,13 @@ export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest)
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
): EnvironmentAuth.ServerAuthInvalidCredentialError | EnvironmentAuth.ServerAuthInternalError =>
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? new EnvironmentAuth.ServerAuthInvalidCredentialError({
reason: "invalid_credential",
cause: "DPoP proof replayed.",
? new ServerAuthInvalidCredentialError({
diagnostic: "DPoP proof replayed.",
cause: error,
})
: new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to record DPoP proof replay state.",
: new ServerAuthDpopReplayStateRecordError({
cause: error,
});
@@ -54,9 +58,8 @@ export const verifyRequestDpopProof = (input: {
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
});
if (!result.ok) {
return yield* new EnvironmentAuth.ServerAuthInvalidCredentialError({
reason: "invalid_credential",
cause: result.reason,
return yield* new ServerAuthInvalidCredentialError({
diagnostic: result.reason,
});
}
const secretStore = yield* ServerSecretStore.ServerSecretStore;
@@ -67,8 +70,7 @@ export const verifyRequestDpopProof = (input: {
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to calculate DPoP replay key.",
new ServerAuthDpopReplayKeyCalculationError({
cause,
}),
),
@@ -86,7 +88,9 @@ export const verifyRequestDpopProof = (input: {
),
)
.pipe(
Effect.catchTag("SecretStoreError", (error) => Effect.fail(mapDpopReplayStoreError(error))),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
Effect.fail(mapDpopReplayStoreError(error)),
),
);
return result.thumbprint;
});
+42 -36
View File
@@ -169,10 +169,12 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
return yield* httpEffect.pipe(
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
@@ -201,7 +203,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const request = yield* HttpServerRequest.HttpServerRequest;
return yield* serverAuth.getSessionState(request);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
),
@@ -231,11 +233,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* appendCredentialResponseHeaders;
return result.response;
},
Effect.catchTags({
ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
ServerAuthInternalError: (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
),
),
)
.handle(
@@ -265,14 +268,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
}
const proofKeyThumbprint = args.headers.dpop
? yield* verifyRequestDpopProof({ request }).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
appendDpopChallengeHeader.pipe(
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
),
ServerAuthInternalError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
appendDpopChallengeHeader.pipe(
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
),
)
: undefined;
yield* appendCredentialResponseHeaders;
@@ -293,12 +296,15 @@ export const authHttpApiLayer = HttpApiBuilder.group(
);
},
traceRelayRequest,
Effect.catchTags({
ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
ServerAuthInvalidRequestError: (error) => failEnvironmentInvalidRequest(error.reason),
ServerAuthInternalError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
),
),
)
.handle(
@@ -310,7 +316,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* appendCredentialResponseHeaders;
return yield* serverAuth.issueWebSocketTicket(session);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
),
),
@@ -335,7 +341,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
}
return yield* serverAuth.issuePairingCredential(args.payload);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_credential_issuance_failed", error),
),
),
@@ -348,7 +354,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listPairingLinks();
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_links_load_failed", error),
),
),
@@ -362,7 +368,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
return { revoked };
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_link_revoke_failed", error),
),
),
@@ -375,7 +381,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listClientSessions(session.sessionId);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_sessions_load_failed", error),
),
),
@@ -392,12 +398,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
);
return { revoked };
},
Effect.catchTags({
ServerAuthForbiddenOperationError: (error) =>
failEnvironmentOperationForbidden(error.reason),
ServerAuthInternalError: (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
}),
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
)
.handle(
@@ -409,7 +415,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
return { revokedCount };
},
Effect.catchTag("ServerAuthInternalError", (error) =>
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
+3 -3
View File
@@ -4,7 +4,7 @@ import type {
AuthClientPresentationMetadata,
} from "@t3tools/contracts";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Crypto from "node:crypto";
import * as NodeCrypto from "node:crypto";
import * as Encoding from "effect/Encoding";
import * as Result from "effect/Result";
@@ -32,7 +32,7 @@ export function base64UrlDecodeUtf8(input: string): string {
}
export function signPayload(payload: string, secret: Uint8Array): string {
return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
}
export function timingSafeEqualBase64Url(left: string, right: string): boolean {
@@ -41,7 +41,7 @@ export function timingSafeEqualBase64Url(left: string, right: string): boolean {
if (leftBuffer.length !== rightBuffer.length) {
return false;
}
return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
}
function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
+49 -27
View File
@@ -1,8 +1,8 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
import * as NodeHttp from "node:http";
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -25,12 +25,12 @@ import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSna
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
} from "./serverRuntimeState.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
@@ -90,10 +90,10 @@ const makeCliTestServerConfig = (baseDir: string) =>
const makeProjectPersistenceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
Layer.mergeAll(
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
),
WorkspacePathsLive,
WorkspacePaths.layer,
).pipe(Layer.provideMerge(NodeServices.layer), Layer.provide(ServerConfig.layer(config)));
const readPersistedSnapshot = (baseDir: string) =>
@@ -197,7 +197,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("reports fresh headless connect state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-test-"),
);
const { output } = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
@@ -220,7 +222,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("reports actionable human-readable headless connect state", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-human-test-"),
);
const { output } = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir]),
);
@@ -234,11 +238,13 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("logs in to headless connect without enabling access", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),
);
const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
mkdirSync(secretsDir, { recursive: true });
writeFileSync(
join(secretsDir, "cloud-cli-oauth-token.bin"),
NodeFS.mkdirSync(secretsDir, { recursive: true });
NodeFS.writeFileSync(
NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"),
// @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
JSON.stringify({
accessToken: "access-token",
@@ -267,7 +273,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("disables headless connect without a running server", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-unlink-test-"),
);
const { output } = yield* captureStdout(
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
);
@@ -278,24 +286,28 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-logout-test-"),
);
const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
const tokenPath = join(secretsDir, "cloud-cli-oauth-token.bin");
mkdirSync(secretsDir, { recursive: true });
writeFileSync(tokenPath, "invalid persisted token");
const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin");
NodeFS.mkdirSync(secretsDir, { recursive: true });
NodeFS.writeFileSync(tokenPath, "invalid persisted token");
const { output } = yield* captureStdout(
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
);
assert.equal(output, "Signed out of T3 Connect locally.");
assert.isFalse(existsSync(tokenPath));
assert.isFalse(NodeFS.existsSync(tokenPath));
}),
);
it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-pairing-test-"),
);
const createdOutput = yield* captureStdout(
runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
@@ -325,7 +337,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("executes auth session subcommands and redacts secrets from list output", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-session-test-"),
);
const issuedOutput = yield* captureStdout(
runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
@@ -400,8 +414,12 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-offline-test-"),
);
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-workspace-"),
);
yield* runCliWithRuntime([
"project",
@@ -444,8 +462,12 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("routes project commands through a running server when runtime state is present", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-test-"),
);
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-workspace-"),
);
yield* withLiveProjectCliServer(baseDir, () =>
Effect.gen(function* () {
@@ -472,8 +494,8 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("rejects dev-url on project commands", () =>
Effect.gen(function* () {
const workspaceRoot = mkdtempSync(
join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
);
const error = yield* runCliWithRuntime([
"project",
+13 -13
View File
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NFS from "node:fs";
import * as path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as FileSystem from "effect/FileSystem";
@@ -53,8 +53,8 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NFS.closeSync(fd)),
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
@@ -78,7 +78,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
// so the stream owns the fd lifecycle and closes it asynchronously on end.
// Attempting to also close it synchronously in a finalizer races with the
// stream's async close and produces an uncaught EBADF.
const fd = NFS.openSync(filePath, "r");
const fd = NodeFS.openSync(filePath, "r");
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
@@ -96,8 +96,8 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
it.effect("returns none when the fd is unavailable", () =>
Effect.gen(function* () {
const fd = NFS.openSync("/dev/null", "r");
NFS.closeSync(fd);
const fd = NodeFS.openSync("/dev/null", "r");
NodeFS.closeSync(fd);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertNone(payload);
@@ -108,13 +108,13 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
const fifoPath = path.join(tempDir, "bootstrap.pipe");
const fifoPath = NodePath.join(tempDir, "bootstrap.pipe");
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
yield* Effect.sync(() => NodeChildProcess.execFileSync("mkfifo", [fifoPath]));
const _writer = yield* Effect.acquireRelease(
Effect.sync(() =>
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
NodeChildProcess.spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
stdio: ["ignore", "ignore", "ignore"],
}),
),
@@ -125,8 +125,8 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NFS.openSync(fifoPath, "r")),
(fd) => Effect.sync(() => NFS.closeSync(fd)),
Effect.sync(() => NodeFS.openSync(fifoPath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
+13 -13
View File
@@ -1,8 +1,8 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NFS from "node:fs";
import * as Net from "node:net";
import * as readline from "node:readline";
import type { Readable } from "node:stream";
import * as NodeFS from "node:fs";
import * as NodeNet from "node:net";
import * as NodeReadline from "node:readline";
import type * as NodeStream from "node:stream";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
@@ -33,7 +33,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
const timeoutMs = options?.timeoutMs ?? 1000;
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
const input = readline.createInterface({
const input = NodeReadline.createInterface({
input: stream,
crlfDelay: Infinity,
});
@@ -96,7 +96,7 @@ const isUnavailableBootstrapFdError = Predicate.compose(
const isFdReady = (fd: number) =>
Effect.try({
try: () => NFS.fstatSync(fd),
try: () => NodeFS.fstatSync(fd),
catch: (error) =>
new BootstrapError({
message: "Failed to stat bootstrap fd.",
@@ -113,7 +113,7 @@ const isFdReady = (fd: number) =>
const makeBootstrapInputStream = (fd: number) =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.try<Readable, BootstrapError>({
return yield* Effect.try<NodeStream.Readable, BootstrapError>({
try: () => {
const fdPath = resolveFdPath(fd, platform);
if (fdPath === undefined) {
@@ -122,8 +122,8 @@ const makeBootstrapInputStream = (fd: number) =>
let streamFd: number | undefined;
try {
streamFd = NFS.openSync(fdPath, "r");
return NFS.createReadStream("", {
streamFd = NodeFS.openSync(fdPath, "r");
return NodeFS.createReadStream("", {
fd: streamFd,
encoding: "utf8",
autoClose: true,
@@ -131,7 +131,7 @@ const makeBootstrapInputStream = (fd: number) =>
} catch (error) {
if (isBootstrapFdPathDuplicationError(error)) {
if (streamFd !== undefined) {
NFS.closeSync(streamFd);
NodeFS.closeSync(streamFd);
}
return makeDirectBootstrapStream(fd);
}
@@ -146,15 +146,15 @@ const makeBootstrapInputStream = (fd: number) =>
});
});
const makeDirectBootstrapStream = (fd: number): Readable => {
const makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {
try {
return NFS.createReadStream("", {
return NodeFS.createReadStream("", {
fd,
encoding: "utf8",
autoClose: true,
});
} catch {
const stream = new Net.Socket({
const stream = new NodeNet.Socket({
fd,
readable: true,
writable: false,
@@ -1,5 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import path from "node:path";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
@@ -80,7 +80,7 @@ function initRepoWithCommit(
yield* git(cwd, ["init"]);
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* writeTextFile(NodePath.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
});
@@ -107,7 +107,7 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
cwd: tmp,
checkpointRef: fromCheckpointRef,
});
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
yield* writeTextFile(NodePath.join(tmp, "README.md"), buildLargeText());
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: toCheckpointRef,
@@ -135,7 +135,7 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const componentPath = path.join(tmp, "Component.tsx");
const componentPath = NodePath.join(tmp, "Component.tsx");
yield* writeTextFile(
componentPath,
[
+2 -3
View File
@@ -32,8 +32,7 @@ import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts";
import { relayUrlConfig } from "../cloud/publicConfig.ts";
import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
import * as ServerConfig from "../config.ts";
import { ServerEnvironmentLive } from "../environment/Layers/ServerEnvironment.ts";
import * as ServerEnvironment from "../environment/Services/ServerEnvironment.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -301,7 +300,7 @@ const runCloudCommand = <A, E>(
CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironmentLive,
ServerEnvironment.layer,
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
+5 -6
View File
@@ -31,14 +31,13 @@ import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEng
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
import * as WorkspacePaths from "../workspace/Services/WorkspacePaths.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
type ProjectMutationTarget = {
@@ -68,9 +67,9 @@ const projectCommandUuid = Crypto.Crypto.pipe(
);
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
WorkspacePaths.layer,
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
),
);
@@ -301,7 +300,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
}).pipe(Effect.provide(offlineRuntimeLayer));
}).pipe(
Effect.provide(
Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePathsLive).pipe(
Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
+2 -2
View File
@@ -1,5 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off - The CLI loopback OAuth callback is a Node HTTP boundary.
import { createServer } from "node:http";
import * as NodeHttp from "node:http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as Clock from "effect/Clock";
@@ -206,7 +206,7 @@ export const make = Effect.gen(function* () {
disableLogger: true,
}).pipe(
Layer.provide(
NodeHttpServer.layer(createServer, {
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: 34338,
disablePreemptiveShutdown: true,
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
const makeServerSecretStoreLayer = () =>
@@ -65,8 +65,8 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
}).pipe(
Effect.flatMap(() =>
Effect.fail(
new ServerSecretStore.SecretStoreError({
message: "Concurrent keypair creation won.",
new ServerSecretStore.SecretStorePersistError({
resource: "environment signing key pair",
cause: PlatformError.systemError({
_tag: "AlreadyExists",
module: "FileSystem",
@@ -79,7 +79,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
),
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
} satisfies ServerSecretStore.ServerSecretStoreShape;
} satisfies ServerSecretStore.ServerSecretStore["Service"];
assert.deepEqual(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore), {
privateKey: "winner-private",
+17 -18
View File
@@ -27,47 +27,46 @@ function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
const keyPairPersistenceError = (message: string, cause?: unknown) =>
new ServerSecretStore.SecretStoreError({ message, cause });
const KEY_PAIR_RESOURCE = "environment signing key pair";
const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>
new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });
const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>
new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });
const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>
new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });
const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
secrets: ServerSecretStore.ServerSecretStoreShape,
secrets: ServerSecretStore.ServerSecretStore["Service"],
) {
const encoded = yield* secrets.get(CLOUD_LINK_KEY_PAIR);
if (Option.isNone(encoded)) {
return Option.none<EnvironmentKeyPair>();
}
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
Effect.mapError((cause) =>
keyPairPersistenceError("Failed to decode environment signing key pair.", cause),
),
Effect.mapError(keyPairDecodeError),
);
return Option.some(decoded);
});
const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(function* (
secrets: ServerSecretStore.ServerSecretStoreShape,
secrets: ServerSecretStore.ServerSecretStore["Service"],
keyPair: EnvironmentKeyPair,
) {
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
Effect.mapError((cause) =>
keyPairPersistenceError("Failed to encode environment signing key pair.", cause),
),
Effect.mapError(keyPairEncodeError),
);
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
Effect.as(keyPair),
Effect.catchTag("SecretStoreError", (error) =>
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
keyPairPersistenceError(
"Failed to read environment signing key pair after concurrent creation.",
),
),
onNone: () => Effect.fail(keyPairConcurrentReadError()),
}),
),
)
@@ -77,7 +76,7 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
});
export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function* (
secrets: ServerSecretStore.ServerSecretStoreShape,
secrets: ServerSecretStore.ServerSecretStore["Service"],
) {
const existing = yield* readEnvironmentKeyPair(secrets);
if (Option.isSome(existing)) {
+27 -3
View File
@@ -9,15 +9,15 @@ import { HttpClient, HttpServerRequest } from "effect/unstable/http";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerEnvironment from "../environment/Services/ServerEnvironment.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStoreError({
message: "Failed to persist cloud replay guard.",
new ServerSecretStore.SecretStorePersistError({
resource: "cloud replay guard",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -40,6 +40,30 @@ function makeSecretStore(
};
}
it("preserves messages surfaced by cloud 500 responses", () => {
const cause = new Error("cloud operation failed");
expect([
new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
]).toEqual([
"Could not verify the linked cloud account.",
"Could not read the linked cloud account.",
"Cloud linked user is not installed for this environment.",
"Failed to sign cloud link JWT.",
"Cloud mint public key is not installed for this environment.",
"Cloud relay issuer is not installed for this environment.",
"Failed to sign cloud health JWT.",
"Failed to sign cloud mint JWT.",
]);
});
describe("consumeCloudReplayGuards", () => {
it.effect("reports already-created guards as replay conflicts", () =>
Effect.gen(function* () {
+114 -120
View File
@@ -55,7 +55,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { requireEnvironmentScope } from "../auth/http.ts";
import * as ServerEnvironment from "../environment/Services/ServerEnvironment.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
@@ -68,7 +68,7 @@ import {
RELAY_URL_SECRET,
} from "./config.ts";
import { relayUrlConfig } from "./publicConfig.ts";
import * as CliState from "./CliState.ts";
import { setCliDesiredCloudLink } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
import { traceRelayRequest } from "./traceRelayRequest.ts";
@@ -98,7 +98,7 @@ const failEnvironmentCloudInternalError =
);
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
failEnvironmentCloudInternalError(error.message)(error.cause);
failEnvironmentCloudInternalError(error.message)(error);
const requireRelayUrl = relayUrlConfig.pipe(
Effect.mapError(
@@ -126,7 +126,7 @@ export function consumeCloudReplayGuards(input: {
input.names.map((name) =>
input.secrets.create(name, input.value).pipe(
Effect.as(true),
Effect.catchTag("SecretStoreError", (error) =>
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
@@ -211,8 +211,7 @@ function validateLinkedCloudUser(input: {
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Could not verify the linked cloud account.",
new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({
cause,
}),
),
@@ -239,19 +238,14 @@ function readInstalledCloudUserId(
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Could not read the linked cloud account.",
new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({
cause,
}),
),
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud linked user is not installed for this environment.",
}),
),
: Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})),
),
);
}
@@ -394,8 +388,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud link JWT.",
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
cause,
}),
),
@@ -416,15 +409,17 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
yield* appendCloudCredentialResponseHeaders;
return proof satisfies RelayEnvironmentLinkProof;
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not generate environment link proof."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not generate environment link proof."),
),
Effect.catchTags({
PlatformError: failEnvironmentCloudInternalError("Could not generate environment link proof."),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
}),
);
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
@@ -477,17 +472,17 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
yield* requireEnvironmentScope(AuthRelayWriteScope);
return yield* applyCloudRelayConfig(dependencies, payload);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
),
Effect.catchTag(
"SchemaError",
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
),
Effect.catchTags({
SchemaError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
}),
);
const relayClientRequest = <A>(
@@ -581,7 +576,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
},
schema: RelayEnvironmentLinkResponse,
});
yield* CliState.setCliDesiredCloudLink(true);
yield* setCliDesiredCloudLink(true);
return yield* applyCloudRelayConfig(dependencies, {
relayUrl,
relayIssuer: link.relayIssuer,
@@ -591,15 +586,16 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
endpointRuntime: link.endpointRuntime,
});
},
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
),
Effect.catchTags({
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
CloudCliCredentialReadError: failCloudCliTokenManagerError,
CloudCliAuthorizationError: failCloudCliTokenManagerError,
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
}),
);
@@ -637,8 +633,8 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
yield* requireEnvironmentScope(AuthRelayReadScope);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTag(
"SecretStoreError",
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
),
);
@@ -659,11 +655,11 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
],
{ concurrency: 7 },
);
yield* CliState.setCliDesiredCloudLink(false);
yield* setCliDesiredCloudLink(false);
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
},
Effect.catchTag(
"SecretStoreError",
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
),
);
@@ -680,42 +676,40 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTag(
"SecretStoreError",
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
),
);
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {
const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud mint public key is not installed for this environment.",
}),
),
),
);
const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets.get(RELAY_URL_SECRET).pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud relay issuer is not installed for this environment.",
}),
),
),
),
),
);
const cloudMintPublicKey = yield* dependencies.secrets
.get(CLOUD_MINT_PUBLIC_KEY)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
),
);
const relayIssuer = yield* dependencies.secrets
.get(RELAY_ISSUER_SECRET)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets
.get(RELAY_URL_SECRET)
.pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
),
),
),
);
const environmentId = yield* dependencies.environment.getEnvironmentId;
const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
const now = yield* DateTime.now;
@@ -777,8 +771,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud health JWT.",
new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
cause,
}),
),
@@ -794,45 +787,47 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not answer cloud health request."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not answer cloud health request."),
),
Effect.catchTags({
PlatformError: failEnvironmentCloudInternalError("Could not answer cloud health request."),
SecretStoreError: failEnvironmentCloudInternalError("Could not answer cloud health request."),
}),
);
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {
const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud mint public key is not installed for this environment.",
}),
),
),
);
const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets.get(RELAY_URL_SECRET).pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud relay issuer is not installed for this environment.",
}),
),
),
),
),
);
const cloudMintPublicKey = yield* dependencies.secrets
.get(CLOUD_MINT_PUBLIC_KEY)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
),
);
const relayIssuer = yield* dependencies.secrets
.get(RELAY_ISSUER_SECRET)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets
.get(RELAY_URL_SECRET)
.pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
),
),
),
);
const environmentId = yield* dependencies.environment.getEnvironmentId;
const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
const now = yield* DateTime.now;
@@ -899,8 +894,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud mint JWT.",
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
cause,
}),
),
@@ -914,17 +908,17 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
),
Effect.catchTags({
PlatformError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
}),
);
export const connectHttpApiLayer = HttpApiBuilder.group(
@@ -1,5 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as nodePath from "node:path";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -8,12 +8,11 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../../config.ts";
import * as ServerEnvironment from "../Services/ServerEnvironment.ts";
import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "./ServerEnvironment.ts";
const makeServerEnvironmentLayer = (baseDir: string) =>
ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
ServerEnvironment.layer.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
const makeServerConfig = Effect.fn(function* (baseDir: string) {
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
@@ -77,7 +76,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
});
const serverConfig = yield* makeServerConfig(baseDir);
const environmentIdPath = serverConfig.environmentIdPath;
yield* fileSystem.makeDirectory(nodePath.dirname(environmentIdPath), { recursive: true });
yield* fileSystem.makeDirectory(NodePath.dirname(environmentIdPath), { recursive: true });
yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
const writeAttempts: string[] = [];
const failingFileSystemLayer = FileSystem.layerNoop({
@@ -113,7 +112,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
return yield* serverEnvironment.getDescriptor;
}).pipe(
Effect.provide(
ServerEnvironmentLive.pipe(
ServerEnvironment.layer.pipe(
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
),
),
@@ -1,17 +1,25 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
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";
import * as Path from "effect/Path";
import { ServerConfig } from "../../config.ts";
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import packageJson from "../../../package.json" with { type: "json" };
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
export class ServerEnvironment extends Context.Service<
ServerEnvironment,
{
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
}
>()("t3/environment/ServerEnvironment") {}
function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
switch (platform) {
case "darwin":
@@ -38,10 +46,10 @@ function platformArch(
}
}
export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const serverConfig = yield* ServerConfig.ServerConfig;
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
@@ -77,9 +85,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
const environmentId = EnvironmentId.make(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({
cwdBaseName,
});
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
const descriptor: ExecutionEnvironmentDescriptor = {
environmentId,
@@ -94,12 +100,15 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
},
};
return {
return ServerEnvironment.of({
getEnvironmentId: Effect.succeed(environmentId),
getDescriptor: Effect.succeed(descriptor),
} satisfies ServerEnvironmentShape;
});
});
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()).pipe(
Layer.provide(ProcessRunnerLive),
);
/**
* ServerEnvironment is acquired from persisted filesystem and host-process
* state. It intentionally has no fallback Layer.succeed value: callers must
* provide the external platform services and a ServerConfig.
*/
export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));
@@ -2,12 +2,12 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { vi } from "vite-plus/test";
import * as ProcessRunner from "../../processRunner.ts";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
import { ChildProcessSpawner } from "effect/unstable/process";
const runMock = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
@@ -3,7 +3,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import { ProcessRunner } from "../../processRunner.ts";
import * as ProcessRunner from "../processRunner.ts";
interface ResolveServerEnvironmentLabelInput {
readonly cwdBaseName: string;
@@ -50,7 +50,7 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const processRunner = yield* ProcessRunner;
const processRunner = yield* ProcessRunner.ProcessRunner;
const result = yield* processRunner
.run({
command,
@@ -1,12 +0,0 @@
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
export interface ServerEnvironmentShape {
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
}
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
"t3/environment/Services/ServerEnvironment",
) {}
+126 -59
View File
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
@@ -20,7 +20,6 @@ import type {
} from "@t3tools/contracts";
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
import * as GitManager from "./GitManager.ts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
@@ -28,8 +27,9 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as ProjectSetupScriptRunner from "../project/Services/ProjectSetupScriptRunner.ts";
import * as GitManager from "./GitManager.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -164,7 +164,7 @@ function normalizeFakePullRequestSummary(raw: unknown): GitHubCli.GitHubPullRequ
}
function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
const result = spawnSync("git", args, {
const result = NodeChildProcess.spawnSync("git", args, {
cwd,
encoding: "utf8",
});
@@ -254,7 +254,7 @@ function initRepo(
yield* runGit(cwd, ["init", "--initial-branch=main"]);
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
yield* runGit(cwd, ["config", "user.name", "Test User"]);
yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n");
yield* fs.writeFileString(NodePath.join(cwd, "README.md"), "hello\n");
yield* runGit(cwd, ["add", "README.md"]);
yield* runGit(cwd, ["commit", "-m", "Initial commit"]);
});
@@ -459,7 +459,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
try: () => {
const headBranch = scenario.pullRequest?.headRefName;
if (headBranch) {
const existingBranch = spawnSync(
const existingBranch = NodeChildProcess.spawnSync(
"git",
["show-ref", "--verify", "--quiet", `refs/heads/${headBranch}`],
{
@@ -916,7 +916,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status returns an explicit non-repo result for deleted directories", () =>
Effect.gen(function* () {
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
const cwd = path.join(rootDir, "deleted-repo");
const cwd = NodePath.join(rootDir, "deleted-repo");
yield* makeDirectory(cwd);
yield* removePath(cwd);
const { manager } = yield* makeManager();
@@ -1026,7 +1026,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
fs.writeFileSync(path.join(repoDir, "fork-pr.txt"), "fork pr\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "fork-pr.txt"), "fork pr\n");
yield* runGit(repoDir, ["add", "fork-pr.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
@@ -1348,7 +1348,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
@@ -1383,7 +1383,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\ncustom\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
@@ -1426,8 +1426,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "a.txt"), "file a\n");
fs.writeFileSync(path.join(repoDir, "b.txt"), "file b\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "a.txt"), "file a\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "b.txt"), "file b\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
@@ -1454,7 +1454,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nfeature-branch\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
@@ -1514,7 +1514,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\ncustom-feature\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
@@ -1597,7 +1597,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
@@ -1626,7 +1626,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n");
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
@@ -1697,7 +1697,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/push-only"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "push-only.txt"), "push only\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "push-only.txt"), "push only\n");
yield* runGit(repoDir, ["add", "push-only.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Push only branch"]);
@@ -1725,11 +1725,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "push-dirty.txt"), "push dirty\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "push-dirty.txt"), "push dirty\n");
yield* runGit(repoDir, ["add", "push-dirty.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]);
fs.mkdirSync(path.join(repoDir, ".vercel"));
fs.writeFileSync(path.join(repoDir, ".vercel", "project.json"), "{}\n");
NodeFS.mkdirSync(NodePath.join(repoDir, ".vercel"));
NodeFS.writeFileSync(NodePath.join(repoDir, ".vercel", "project.json"), "{}\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
@@ -1760,7 +1760,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/create-pr-only"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "create-pr-only.txt"), "create pr\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "create-pr-only.txt"), "create pr\n");
yield* runGit(repoDir, ["add", "create-pr-only.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Create PR only branch"]);
@@ -1805,7 +1805,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]);
fs.writeFileSync(path.join(repoDir, "provider-fallback.txt"), "fallback\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "provider-fallback.txt"), "fallback\n");
yield* runGit(repoDir, ["add", "provider-fallback.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]);
const remoteDir = yield* createBareRemote();
@@ -1982,7 +1982,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
@@ -2200,7 +2200,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
@@ -2239,6 +2239,62 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("generates PR content against the remote base when the local base is stale", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(remoteDir, ["symbolic-ref", "HEAD", "refs/heads/main"]);
const peerDir = yield* makeTempDir("t3code-git-peer-");
yield* runGit(peerDir, ["clone", remoteDir, "."]);
yield* runGit(peerDir, ["config", "user.email", "[email protected]"]);
yield* runGit(peerDir, ["config", "user.name", "Peer User"]);
NodeFS.writeFileSync(NodePath.join(peerDir, "remote.txt"), "remote\n");
yield* runGit(peerDir, ["add", "remote.txt"]);
yield* runGit(peerDir, ["commit", "-m", "Remote base commit"]);
yield* runGit(peerDir, ["push", "origin", "main"]);
yield* runGit(repoDir, ["fetch", "origin"]);
yield* runGit(repoDir, [
"checkout",
"--no-track",
"-b",
"feature/remote-base",
"origin/main",
]);
NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n");
yield* runGit(repoDir, ["add", "feature.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/remote-base"]);
yield* runGit(repoDir, ["config", "branch.feature/remote-base.gh-merge-base", "main"]);
let generatedCommitSummary = "";
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: ["[]", "[]"],
},
textGeneration: {
generatePrContent: (input) => {
generatedCommitSummary = input.commitSummary;
return Effect.succeed({ title: "Feature PR", body: "Feature body" });
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "create_pr",
});
expect(result.pr.status).toBe("created");
expect(generatedCommitSummary).toContain("Feature commit");
expect(generatedCommitSummary).not.toContain("Remote base commit");
}),
);
it.effect(
"creates a new PR instead of reusing an unrelated fork PR with the same head branch",
() =>
@@ -2248,7 +2304,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
@@ -2320,7 +2376,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
@@ -2500,7 +2556,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local"]);
fs.writeFileSync(path.join(repoDir, "local.txt"), "local\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "local.txt"), "local\n");
yield* runGit(repoDir, ["add", "local.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local PR branch"]);
@@ -2541,7 +2597,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-upstream"]);
fs.writeFileSync(path.join(repoDir, "upstream.txt"), "upstream\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "upstream.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "upstream.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]);
@@ -2599,7 +2655,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-no-head-repo"]);
fs.writeFileSync(path.join(repoDir, "no-head-repo.txt"), "upstream\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "no-head-repo.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "no-head-repo.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]);
@@ -2646,7 +2702,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree"]);
fs.writeFileSync(path.join(repoDir, "worktree.txt"), "worktree\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "worktree.txt"), "worktree\n");
yield* runGit(repoDir, ["add", "worktree.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR worktree branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree"]);
@@ -2674,7 +2730,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.branch).toBe("feature/pr-worktree");
expect(result.worktreePath).not.toBeNull();
expect(fs.existsSync(result.worktreePath as string)).toBe(true);
expect(NodeFS.existsSync(result.worktreePath as string)).toBe(true);
const worktreeBranch = (yield* runGit(result.worktreePath as string, [
"branch",
"--show-current",
@@ -2691,7 +2747,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree-setup"]);
fs.writeFileSync(path.join(repoDir, "setup.txt"), "setup\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "setup.txt"), "setup\n");
yield* runGit(repoDir, ["add", "setup.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR worktree setup branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree-setup"]);
@@ -2746,7 +2802,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-fork"]);
fs.writeFileSync(path.join(repoDir, "fork.txt"), "fork\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "fork.txt"), "fork\n");
yield* runGit(repoDir, ["add", "fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-fork"]);
@@ -2808,7 +2864,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-fork"]);
fs.writeFileSync(path.join(repoDir, "local-fork.txt"), "local fork\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "local-fork.txt"), "local fork\n");
yield* runGit(repoDir, ["add", "local-fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-local-fork"]);
@@ -2861,7 +2917,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "binbandit-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fix/git-action-default-without-origin"]);
fs.writeFileSync(path.join(repoDir, "derived-fork.txt"), "derived fork\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "derived-fork.txt"), "derived fork\n");
yield* runGit(repoDir, ["add", "derived-fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Derived fork PR branch"]);
yield* runGit(repoDir, [
@@ -2913,11 +2969,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing-worktree"]);
fs.writeFileSync(path.join(repoDir, "existing.txt"), "existing\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "existing.txt"), "existing\n");
yield* runGit(repoDir, ["add", "existing.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Existing worktree branch"]);
yield* runGit(repoDir, ["checkout", "main"]);
const worktreePath = path.join(repoDir, "..", `pr-existing-${path.basename(repoDir)}`);
const worktreePath = NodePath.join(
repoDir,
"..",
`pr-existing-${NodePath.basename(repoDir)}`,
);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
@@ -2948,8 +3008,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
threadId: asThreadId("thread-pr-existing-worktree"),
});
expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
fs.realpathSync.native(worktreePath),
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
NodeFS.realpathSync.native(worktreePath),
);
expect(result.branch).toBe("feature/pr-existing-worktree");
expect(setupCalls).toHaveLength(0);
@@ -2968,7 +3028,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
fs.writeFileSync(path.join(repoDir, "fork-main.txt"), "fork main\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "fork-main.txt"), "fork main\n");
yield* runGit(repoDir, ["add", "fork-main.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork main branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
@@ -3028,7 +3088,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "fork-main-second.txt"), "fork main second\n");
yield* runGit(repoDir, ["add", "fork-main-second.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
@@ -3086,12 +3146,16 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-fork"]);
fs.writeFileSync(path.join(repoDir, "reused-fork.txt"), "reused fork\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-fork.txt"), "reused fork\n");
yield* runGit(repoDir, ["add", "reused-fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Reused fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-reused-fork"]);
yield* runGit(repoDir, ["checkout", "main"]);
const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${path.basename(repoDir)}`);
const worktreePath = NodePath.join(
repoDir,
"..",
`pr-reused-fork-${NodePath.basename(repoDir)}`,
);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-fork"]);
yield* runGit(worktreePath, ["branch", "--unset-upstream"], true);
@@ -3123,8 +3187,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
mode: "worktree",
});
expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
fs.realpathSync.native(worktreePath),
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
NodeFS.realpathSync.native(worktreePath),
);
expect(
(yield* runGit(worktreePath, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
@@ -3140,7 +3204,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-setup-failure"]);
fs.writeFileSync(path.join(repoDir, "setup-failure.txt"), "setup failure\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "setup-failure.txt"), "setup failure\n");
yield* runGit(repoDir, ["add", "setup-failure.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR setup failure branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-setup-failure"]);
@@ -3159,10 +3223,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
},
},
setupScriptRunner: {
runForThread: () =>
runForThread: (input) =>
Effect.fail(
new ProjectSetupScriptRunner.ProjectSetupScriptRunnerError({
message: "terminal start failed",
new ProjectSetupScriptRunner.ProjectSetupScriptOperationError({
threadId: input.threadId,
worktreePath: input.worktreePath,
operation: "openTerminal",
cause: new Error("terminal start failed"),
}),
),
},
@@ -3177,7 +3244,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.branch).toBe("feature/pr-setup-failure");
expect(result.worktreePath).not.toBeNull();
expect(fs.existsSync(result.worktreePath as string)).toBe(true);
expect(NodeFS.existsSync(result.worktreePath as string)).toBe(true);
}),
);
@@ -3217,9 +3284,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
NodeFS.writeFileSync(NodePath.join(repoDir, "hooked.txt"), "hooked\n");
NodeFS.writeFileSync(
NodePath.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: start" >&2\nsleep 0.05\necho "hook: end" >&2\n',
{ mode: 0o755 },
);
@@ -3280,9 +3347,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
NodeFS.writeFileSync(NodePath.join(repoDir, "hook-failure.txt"), "broken\n");
NodeFS.writeFileSync(
NodePath.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
{ mode: 0o755 },
);
@@ -3333,7 +3400,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-only-follow-up"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "pr-only.txt"), "pr only\n");
NodeFS.writeFileSync(NodePath.join(repoDir, "pr-only.txt"), "pr only\n");
yield* runGit(repoDir, ["add", "pr-only.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR only branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-only-follow-up"]);
+24 -2
View File
@@ -43,7 +43,7 @@ import {
import { GitManagerError } from "@t3tools/contracts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as ProjectSetupScriptRunner from "../project/Services/ProjectSetupScriptRunner.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import * as ServerSettings from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
@@ -1092,6 +1092,27 @@ export const make = Effect.gen(function* () {
return "main";
});
const resolveBaseRangeRef = Effect.fn("resolveBaseRangeRef")(function* (
cwd: string,
baseBranch: string,
) {
const remoteName = yield* gitCore
.resolvePrimaryRemoteName(cwd)
.pipe(Effect.orElseSucceed(() => null));
if (!remoteName) return baseBranch;
return yield* gitCore
.resolveRemoteTrackingCommit({
cwd,
refName: baseBranch,
fallbackRemoteName: remoteName,
})
.pipe(
Effect.map((resolved) => resolved.commitSha),
Effect.orElseSucceed(() => baseBranch),
);
});
const resolveCommitAndBranchSuggestion = Effect.fn("resolveCommitAndBranchSuggestion")(
function* (input: {
cwd: string;
@@ -1298,7 +1319,8 @@ export const make = Effect.gen(function* () {
phase: "pr",
label: `Generating ${terms.shortLabel} content...`,
});
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseBranch);
const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
const generated = yield* textGeneration.generatePrContent({
cwd,
+3 -3
View File
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import { existsSync } from "node:fs";
import { join } from "node:path";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
return NodeFS.existsSync(NodePath.join(cwd, ".git"));
}
+7 -5
View File
@@ -39,7 +39,7 @@ import {
failEnvironmentAuthInvalid,
failEnvironmentInternal,
} from "./auth/http.ts";
import * as ServerEnvironment from "./environment/Services/ServerEnvironment.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
@@ -81,10 +81,12 @@ const authenticateRawRouteWithScope = (
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
if (!session.scopes.includes(scope)) {
return yield* failEnvironmentScopeRequired(scope);
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff. Show more