Refactor shared and SSH Effect services

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-20 20:17:07 -07:00
1 parent 761be9497d
commit 7e85f7b6ec
17 files changed
+1277 -524

No files matched your search

@@ -10,7 +10,9 @@ import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import {
DesktopSshEnvironmentRequestError,
@@ -24,6 +26,8 @@ const decodeDesktopSshEnvironmentEnsureResult = Schema.decodeUnknownEffect(
DesktopSshEnvironmentEnsureResultSchema,
);
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
return HttpClientResponse.fromWeb(
request,
@@ -133,7 +137,7 @@ describe("SSH environment IPC", () => {
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
assert.equal(error.operation, "fetch-environment-descriptor");
assert.equal(error.cause instanceof SshHttpBridgeError, false);
assert.equal(isSshHttpBridgeError(error.cause), false);
}).pipe(Effect.provide(layer));
});
@@ -158,7 +162,7 @@ describe("SSH environment IPC", () => {
const error = failure.value;
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
assert.instanceOf(error.cause, SshHttpBridgeError);
assert.equal(isSshHttpBridgeError(error.cause), true);
assert.equal(requestCount, 0);
}).pipe(Effect.provide(layer));
});
@@ -57,11 +57,13 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || cause instanceof SshHttpBridgeError) {
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause)) {
return cause.status ?? null;
}
if (isSshHttpBridgeError(cause)) return null;
if (isEnvironmentRequestInvalidError(cause)) {
return 400;
}
@@ -2,7 +2,7 @@ import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as NetService from "@t3tools/shared/Net";
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
import { SshPasswordPromptRequestError } from "@t3tools/ssh/errors";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -35,18 +35,17 @@ describe("sshEnvironment", () => {
});
it("treats password prompt timeouts as cancellable authentication prompts", () => {
assert.equal(
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(
new SshPasswordPromptError({
message: "SSH authentication timed out for devbox.",
cause: new DesktopSshPasswordPrompts.DesktopSshPromptTimedOutError({
requestId: "prompt-1",
destination: "devbox",
}),
}),
),
true,
);
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptTimedOutError({
requestId: "prompt-1",
destination: "devbox",
});
const error = new SshPasswordPromptRequestError({
destination: "devbox",
cause,
});
assert.strictEqual(error.cause, cause);
assert(DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error));
assert.equal(error.cause.message, "SSH authentication timed out for devbox.");
});
it.effect("wires desktop host discovery through the ssh package runtime", () =>
+48 -26
View File
@@ -7,13 +7,19 @@ import * as NetService from "@t3tools/shared/Net";
import * as SshAuth from "@t3tools/ssh/auth";
import { discoverSshHosts } from "@t3tools/ssh/config";
import {
SshCommandError,
SshHostDiscoveryError,
SshInvalidTargetError,
SshLaunchError,
SshPairingError,
type SshCommandError,
type SshHostDiscoveryError,
type SshInvalidTargetError,
type SshLaunchError,
type SshPairingError,
SshPasswordPromptCancelledError,
SshPasswordPromptError,
SshReadinessError,
SshPasswordPromptSecureRandomnessError,
SshPasswordPromptServiceStoppedError,
SshPasswordPromptTimedOutError,
SshPasswordPromptWindowClosedError,
SshPasswordPromptWindowUnavailableError,
type SshReadinessError,
} from "@t3tools/ssh/errors";
import * as SshTunnel from "@t3tools/ssh/tunnel";
import * as Context from "effect/Context";
@@ -21,11 +27,14 @@ 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 * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
export type DesktopSshEnvironmentRuntimeServices =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
@@ -69,17 +78,20 @@ export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>;
}
type DesktopSshPasswordPromptCancellationError = SshPasswordPromptError & {
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
};
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
return discoverSshHosts(input ?? {});
}
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is SshPasswordPromptError & {
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
} {
): error is DesktopSshPasswordPromptCancellationError {
return (
error instanceof SshPasswordPromptError &&
isSshPasswordPromptError(error) &&
"cause" in error &&
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
);
}
@@ -91,31 +103,41 @@ function unexpectedPasswordPromptError(error: never): never {
export function toSshPasswordPromptError(
cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptRequestError,
): SshPasswordPromptError {
let message: string;
switch (cause._tag) {
case "DesktopSshPromptRequestIdGenerationError":
message = "Secure randomness is unavailable.";
break;
return new SshPasswordPromptSecureRandomnessError({
destination: cause.destination,
cause,
});
case "DesktopSshPromptWindowUnavailableError":
case "DesktopSshPromptPresentationError":
message = "T3 Code window is not available for SSH authentication.";
break;
return new SshPasswordPromptWindowUnavailableError({
destination: cause.destination,
cause,
});
case "DesktopSshPromptTimedOutError":
message = `SSH authentication timed out for ${cause.destination}.`;
break;
return new SshPasswordPromptTimedOutError({
destination: cause.destination,
cause,
});
case "DesktopSshPromptCancelledError":
message = `SSH authentication cancelled for ${cause.destination}.`;
break;
return new SshPasswordPromptCancelledError({
destination: cause.destination,
cause,
});
case "DesktopSshPromptWindowClosedError":
message = "SSH authentication was cancelled because the app window closed.";
break;
return new SshPasswordPromptWindowClosedError({
destination: cause.destination,
cause,
});
case "DesktopSshPromptServiceStoppedError":
message = "SSH password prompt service stopped.";
break;
return new SshPasswordPromptServiceStoppedError({
destination: cause.destination,
cause,
});
default:
return unexpectedPasswordPromptError(cause);
}
return new SshPasswordPromptError({ message, cause });
}
const makePasswordPrompt = (
@@ -130,7 +152,7 @@ export const make = Effect.gen(function* () {
const manager = yield* SshTunnel.SshEnvironmentManager;
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));
const passwordPrompt = SshAuth.make(makePasswordPrompt(prompts));
return DesktopSshEnvironment.of({
discoverHosts: (input) =>
@@ -160,7 +182,7 @@ export const make = Effect.gen(function* () {
export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
Layer.effect(DesktopSshEnvironment, make).pipe(
Layer.provide(
SshTunnel.SshEnvironmentManager.layer({
SshTunnel.layer({
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
+40 -10
View File
@@ -42,6 +42,7 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
RelayClientInstallFailedError,
type RelayClientInstallFailureReason,
type RelayClientInstallProgressEvent,
OrchestrationReplayEventsError,
type FilesystemBrowseFailure,
@@ -114,6 +115,36 @@ import { catchEnvironmentAuthenticationErrors } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
function relayClientInstallFailureReason(
error: RelayClient.RelayClientInstallError,
): RelayClientInstallFailureReason {
switch (error._tag) {
case "RelayClientDownloadError":
case "RelayClientDownloadReadError":
return "download_failed";
case "RelayClientChecksumMismatchError":
return "invalid_checksum";
case "RelayClientInstallLockedError":
return "install_locked";
case "RelayClientOverrideMissingError":
return "override_missing";
case "RelayClientUnsupportedPlatformError":
return "unsupported_platform";
case "RelayClientChecksumVerificationError":
case "RelayClientExecutableValidationError":
return "validation_failed";
case "RelayClientDirectoryCreateError":
case "RelayClientInstallLockAcquireError":
case "RelayClientDownloadWriteError":
case "RelayClientArchiveExtractError":
case "RelayClientExecutablePermissionError":
case "RelayClientStageError":
case "RelayClientActivationError":
case "RelayClientInstallWriteError":
return "write_failed";
}
}
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
function unexpectedCompatibilityError(error: never): never {
@@ -1289,16 +1320,15 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
status,
}),
),
Effect.catchTags({
RelayClientInstallError: (error) =>
Queue.fail(
queue,
new RelayClientInstallFailedError({
reason: error.reason,
message: error.message,
}),
),
}),
Effect.catchIf(RelayClient.isRelayClientInstallError, (error) =>
Queue.fail(
queue,
new RelayClientInstallFailedError({
reason: relayClientInstallFailureReason(error),
message: error.message,
}),
),
),
Effect.andThen(Queue.end(queue)),
Effect.forkScoped,
),
+1 -3
View File
@@ -31,9 +31,7 @@ const openServer = (host?: string): Effect.Effect<NodeNet.Server, NetService.Net
};
server.once("error", (cause) => {
settle(
Effect.fail(new NetService.NetError({ message: "Failed to open test server", cause })),
);
settle(Effect.fail(new NetService.NetError({ host: host ?? "localhost", cause })));
});
if (host) {
+38 -35
View File
@@ -1,15 +1,19 @@
import * as NodeNet from "node:net";
import * as Data from "effect/Data";
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 Predicate from "effect/Predicate";
import * as Schema from "effect/Schema";
export class NetError extends Data.TaggedError("NetError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class NetError extends Schema.TaggedErrorClass<NetError>()("NetError", {
host: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `Failed to reserve loopback port on ${this.host}.`;
}
}
const isErrnoExceptionWithCode = (
cause: unknown,
@@ -28,34 +32,33 @@ const closeServer = (server: NodeNet.Server) => {
}
};
export interface NetServiceShape {
/**
* Returns true when a TCP server can bind to {host, port}.
*/
readonly canListenOnHost: (port: number, host: string) => Effect.Effect<boolean>;
/**
* Checks loopback availability on both IPv4 and IPv6 localhost addresses.
*/
readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;
/**
* Reserve an ephemeral loopback port and release it immediately.
*/
readonly reserveLoopbackPort: (host?: string) => Effect.Effect<number, NetError>;
/**
* Resolve an available listening port, preferring the provided port first.
*/
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
}
/**
* NetService - Service tag for startup networking helpers.
*/
export class NetService extends Context.Service<NetService, NetServiceShape>()(
"@t3tools/shared/Net/NetService",
) {}
export class NetService extends Context.Service<
NetService,
{
/**
* Returns true when a TCP server can bind to {host, port}.
*/
readonly canListenOnHost: (port: number, host: string) => Effect.Effect<boolean>;
/**
* Checks loopback availability on both IPv4 and IPv6 localhost addresses.
*/
readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;
/**
* Reserve an ephemeral loopback port and release it immediately.
*/
readonly reserveLoopbackPort: (host?: string) => Effect.Effect<number, NetError>;
/**
* Resolve an available listening port, preferring the provided port first.
*/
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
}
>()("@t3tools/shared/Net/NetService") {}
export const make = () => {
/**
@@ -160,7 +163,7 @@ export const make = () => {
};
probe.once("error", (cause) => {
settle(Effect.fail(new NetError({ message: "Failed to reserve loopback port", cause })));
settle(Effect.fail(new NetError({ host, cause })));
});
probe.listen(0, host, () => {
@@ -171,7 +174,7 @@ export const make = () => {
settle(Effect.succeed(port));
return;
}
settle(Effect.fail(new NetError({ message: "Failed to reserve loopback port" })));
settle(Effect.fail(new NetError({ host })));
});
});
@@ -180,7 +183,7 @@ export const make = () => {
});
});
return {
return NetService.of({
canListenOnHost,
isPortAvailableOnLoopback,
reserveLoopbackPort,
@@ -191,7 +194,7 @@ export const make = () => {
}
return yield* reserveLoopbackPort();
}),
} satisfies NetServiceShape;
});
};
export const layer = Layer.sync(NetService, make);
+24 -19
View File
@@ -8,15 +8,14 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";
import {
RelayClientInstallError,
CLOUDFLARED_VERSION,
makeCloudflaredRelayClient,
} from "./relayClient.ts";
import * as RelayClient from "./relayClient.ts";
const hostRuntimeLayer = (env: Record<string, string> = {}) =>
Layer.mergeAll(
@@ -72,7 +71,7 @@ describe("RelayClient", () => {
const overridePath = `${baseDir}/override-cloudflared`;
yield* fileSystem.writeFileString(overridePath, "override");
yield* fileSystem.chmod(overridePath, 0o755);
const manager = yield* makeCloudflaredRelayClient({
const manager = yield* RelayClient.makeCloudflaredRelayClient({
baseDir,
});
@@ -89,7 +88,7 @@ describe("RelayClient", () => {
status: "available",
executablePath: overridePath,
source: "override",
version: CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
});
}).pipe(
Effect.scoped,
@@ -111,7 +110,7 @@ describe("RelayClient", () => {
prefix: "t3-cloudflared-test-",
});
const bytes = new TextEncoder().encode("test-cloudflared-binary");
const manager = yield* makeCloudflaredRelayClient({
const manager = yield* RelayClient.makeCloudflaredRelayClient({
baseDir,
releaseAsset: {
url: "https://example.test/cloudflared",
@@ -128,12 +127,12 @@ describe("RelayClient", () => {
}
}),
);
const managedPath = `${baseDir}/tools/cloudflared/${CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
const managedPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
expect(installed).toEqual({
status: "available",
executablePath: managedPath,
source: "managed",
version: CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
});
expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
"test-cloudflared-binary",
@@ -167,7 +166,7 @@ describe("RelayClient", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-cloudflared-test-",
});
const manager = yield* makeCloudflaredRelayClient({
const manager = yield* RelayClient.makeCloudflaredRelayClient({
baseDir,
releaseAsset: {
url: "https://example.test/cloudflared",
@@ -177,8 +176,14 @@ describe("RelayClient", () => {
});
const error = yield* manager.install.pipe(Effect.flip);
expect(error).toBeInstanceOf(RelayClientInstallError);
expect(error.reason).toBe("invalid_checksum");
expect(error).toBeInstanceOf(RelayClient.RelayClientChecksumMismatchError);
expect(error).toMatchObject({
expectedChecksum: Encoding.encodeHex(sha256(new TextEncoder().encode("expected"))),
actualChecksum: Encoding.encodeHex(sha256(new TextEncoder().encode("tampered"))),
});
expect(error.message).toBe(
"Downloaded relay client checksum did not match the pinned release.",
);
}).pipe(
Effect.scoped,
Effect.provide(
@@ -200,7 +205,7 @@ describe("RelayClient", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-cloudflared-test-",
});
const manager = yield* makeCloudflaredRelayClient({
const manager = yield* RelayClient.makeCloudflaredRelayClient({
baseDir,
releaseAsset: {
url: "https://example.test/cloudflared",
@@ -236,13 +241,13 @@ describe("RelayClient", () => {
});
const binDir = `${baseDir}/bin`;
const executablePath = `${binDir}/cloudflared`;
const manager = yield* makeCloudflaredRelayClient({
const manager = yield* RelayClient.makeCloudflaredRelayClient({
baseDir,
});
expect(yield* manager.resolve).toEqual({
status: "missing",
version: CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
});
yield* fileSystem.makeDirectory(binDir);
@@ -254,7 +259,7 @@ describe("RelayClient", () => {
status: "available",
executablePath,
source: "path",
version: CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
});
}).pipe(
Effect.scoped,
+335 -96
View File
@@ -6,7 +6,6 @@ import type {
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
@@ -14,9 +13,14 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";
export const CLOUDFLARED_VERSION = "2026.5.2";
@@ -44,23 +48,233 @@ export type RelayClientStatus =
export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
readonly reason:
| "download_failed"
| "invalid_checksum"
| "install_locked"
| "override_missing"
| "unsupported_platform"
| "validation_failed"
| "write_failed";
readonly message: string;
readonly cause?: unknown;
}> {}
export class RelayClientDownloadError extends Schema.TaggedErrorClass<RelayClientDownloadError>()(
"RelayClientDownloadError",
{
url: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not download the relay client.";
}
}
class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
readonly command: string;
readonly exitCode: number;
}> {}
export class RelayClientDownloadReadError extends Schema.TaggedErrorClass<RelayClientDownloadReadError>()(
"RelayClientDownloadReadError",
{
url: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not read the downloaded relay client binary.";
}
}
export class RelayClientChecksumMismatchError extends Schema.TaggedErrorClass<RelayClientChecksumMismatchError>()(
"RelayClientChecksumMismatchError",
{
expectedChecksum: Schema.String,
actualChecksum: Schema.String,
},
) {
override get message(): string {
return "Downloaded relay client checksum did not match the pinned release.";
}
}
export class RelayClientInstallLockedError extends Schema.TaggedErrorClass<RelayClientInstallLockedError>()(
"RelayClientInstallLockedError",
{
lockPath: Schema.String,
},
) {
override get message(): string {
return "Another relay client installation is still in progress.";
}
}
export class RelayClientOverrideMissingError extends Schema.TaggedErrorClass<RelayClientOverrideMissingError>()(
"RelayClientOverrideMissingError",
{
executablePath: Schema.String,
},
) {
override get message(): string {
return `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`;
}
}
export class RelayClientUnsupportedPlatformError extends Schema.TaggedErrorClass<RelayClientUnsupportedPlatformError>()(
"RelayClientUnsupportedPlatformError",
{
platform: Schema.String,
arch: Schema.String,
},
) {
override get message(): string {
return `T3 Code does not provide a managed relay client binary for ${this.platform}-${this.arch}.`;
}
}
export class RelayClientChecksumVerificationError extends Schema.TaggedErrorClass<RelayClientChecksumVerificationError>()(
"RelayClientChecksumVerificationError",
{
url: Schema.String,
expectedChecksum: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not verify the downloaded relay client checksum.";
}
}
export class RelayClientExecutableValidationError extends Schema.TaggedErrorClass<RelayClientExecutableValidationError>()(
"RelayClientExecutableValidationError",
{
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "The downloaded relay client binary did not run.";
}
}
export class RelayClientDirectoryCreateError extends Schema.TaggedErrorClass<RelayClientDirectoryCreateError>()(
"RelayClientDirectoryCreateError",
{
directoryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not create the relay client tool directory.";
}
}
export class RelayClientInstallLockAcquireError extends Schema.TaggedErrorClass<RelayClientInstallLockAcquireError>()(
"RelayClientInstallLockAcquireError",
{
lockPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not acquire the relay client installation lock.";
}
}
export class RelayClientDownloadWriteError extends Schema.TaggedErrorClass<RelayClientDownloadWriteError>()(
"RelayClientDownloadWriteError",
{
archivePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not write the relay client download.";
}
}
export class RelayClientArchiveExtractError extends Schema.TaggedErrorClass<RelayClientArchiveExtractError>()(
"RelayClientArchiveExtractError",
{
archivePath: Schema.String,
destinationDirectory: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not extract the relay client.";
}
}
export class RelayClientExecutablePermissionError extends Schema.TaggedErrorClass<RelayClientExecutablePermissionError>()(
"RelayClientExecutablePermissionError",
{
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not make the relay client executable.";
}
}
export class RelayClientStageError extends Schema.TaggedErrorClass<RelayClientStageError>()(
"RelayClientStageError",
{
sourcePath: Schema.String,
destinationPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not stage the relay client.";
}
}
export class RelayClientActivationError extends Schema.TaggedErrorClass<RelayClientActivationError>()(
"RelayClientActivationError",
{
sourcePath: Schema.String,
destinationPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not activate the relay client.";
}
}
export class RelayClientInstallWriteError extends Schema.TaggedErrorClass<RelayClientInstallWriteError>()(
"RelayClientInstallWriteError",
{
managedPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not install the relay client.";
}
}
export const RelayClientInstallError = Schema.Union([
RelayClientDownloadError,
RelayClientDownloadReadError,
RelayClientChecksumMismatchError,
RelayClientInstallLockedError,
RelayClientOverrideMissingError,
RelayClientUnsupportedPlatformError,
RelayClientChecksumVerificationError,
RelayClientExecutableValidationError,
RelayClientDirectoryCreateError,
RelayClientInstallLockAcquireError,
RelayClientDownloadWriteError,
RelayClientArchiveExtractError,
RelayClientExecutablePermissionError,
RelayClientStageError,
RelayClientActivationError,
RelayClientInstallWriteError,
]);
export type RelayClientInstallError = typeof RelayClientInstallError.Type;
class CloudflaredCommandError extends Schema.TaggedErrorClass<CloudflaredCommandError>()(
"CloudflaredCommandError",
{
command: Schema.String,
exitCode: Schema.Number,
},
) {
override get message(): string {
return `${this.command} exited with code ${this.exitCode}.`;
}
}
export const isRelayClientInstallError = Schema.is(RelayClientInstallError);
export interface CloudflaredReleaseAsset {
readonly url: string;
@@ -123,17 +337,16 @@ export interface CloudflaredRelayClientOptions {
readonly releaseAsset?: CloudflaredReleaseAsset;
}
export interface RelayClientShape {
readonly resolve: Effect.Effect<RelayClientStatus>;
readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
readonly installWithProgress: (
report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
}
export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
"@t3tools/shared/relayClient",
) {}
export class RelayClient extends Context.Service<
RelayClient,
{
readonly resolve: Effect.Effect<RelayClientStatus>;
readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
readonly installWithProgress: (
report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
}
>()("@t3tools/shared/relayClient") {}
function executableFileName(platform: NodeJS.Platform): string {
return platform === "win32" ? "cloudflared.exe" : "cloudflared";
@@ -152,27 +365,17 @@ function isAlreadyExists(error: PlatformError.PlatformError): boolean {
const wrapInstallFailure =
(
reason: RelayClientInstallError["reason"],
message: string,
makeError: (cause: unknown) => RelayClientInstallError,
): (<E, R>(
effect: Effect.Effect<void, E, R>,
) => Effect.Effect<void, RelayClientInstallError, R>) =>
(effect) =>
effect.pipe(
Effect.mapError(
(cause) =>
new RelayClientInstallError({
reason,
message,
cause,
}),
),
);
effect.pipe(Effect.mapError(makeError));
export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
options: CloudflaredRelayClientOptions,
): Effect.fn.Return<
RelayClientShape,
RelayClient["Service"],
never,
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
@@ -221,7 +424,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
return null;
});
const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
const resolve: RelayClient["Service"]["resolve"] = Effect.gen(function* () {
const config = yield* loadCloudflaredConfig;
if (Option.isSome(config.executableOverride)) {
return (yield* isExecutableFile(config.executableOverride.value))
@@ -286,9 +489,8 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.mapError(
(cause) =>
new RelayClientInstallError({
reason: "download_failed",
message: "Could not download the relay client.",
new RelayClientDownloadError({
url: asset.url,
cause,
}),
),
@@ -297,9 +499,8 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
yield* response.arrayBuffer.pipe(
Effect.mapError(
(cause) =>
new RelayClientInstallError({
reason: "download_failed",
message: "Could not read the downloaded relay client binary.",
new RelayClientDownloadReadError({
url: asset.url,
cause,
}),
),
@@ -309,17 +510,18 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
Effect.mapError(
(cause) =>
new RelayClientInstallError({
reason: "validation_failed",
message: "Could not verify the downloaded relay client checksum.",
new RelayClientChecksumVerificationError({
url: asset.url,
expectedChecksum: asset.sha256,
cause,
}),
),
);
if (Encoding.encodeHex(checksum) !== asset.sha256) {
return yield* new RelayClientInstallError({
reason: "invalid_checksum",
message: "Downloaded relay client checksum did not match the pinned release.",
const actualChecksum = Encoding.encodeHex(checksum);
if (actualChecksum !== asset.sha256) {
return yield* new RelayClientChecksumMismatchError({
expectedChecksum: asset.sha256,
actualChecksum,
});
}
return bytes;
@@ -346,9 +548,8 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
}
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
}
return yield* new RelayClientInstallError({
reason: "install_locked",
message: "Another relay client installation is still in progress.",
return yield* new RelayClientInstallLockedError({
lockPath,
});
});
@@ -360,32 +561,34 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
if (existing.status === "available") return existing;
const config = yield* loadCloudflaredConfig;
if (Option.isSome(config.executableOverride)) {
return yield* new RelayClientInstallError({
reason: "override_missing",
message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,
return yield* new RelayClientOverrideMissingError({
executablePath: config.executableOverride.value,
});
}
if (!releaseAsset) {
return yield* new RelayClientInstallError({
reason: "unsupported_platform",
message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
return yield* new RelayClientUnsupportedPlatformError({
platform,
arch,
});
}
const managedDirectory = path.dirname(managedPath);
const lockPath = `${managedPath}.lock`;
yield* fileSystem
.makeDirectory(managedDirectory, { recursive: true })
.pipe(
wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
);
yield* fileSystem.makeDirectory(managedDirectory, { recursive: true }).pipe(
wrapInstallFailure(
(cause) =>
new RelayClientDirectoryCreateError({
directoryPath: managedDirectory,
cause,
}),
),
);
yield* report("waiting_for_lock");
yield* acquireInstallLock(lockPath).pipe(
Effect.catchTag("PlatformError", (cause) =>
Effect.fail(
new RelayClientInstallError({
reason: "write_failed",
message: "Could not acquire the relay client installation lock.",
new RelayClientInstallLockAcquireError({
lockPath,
cause,
}),
),
@@ -405,37 +608,74 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
);
const download = yield* downloadAsset(releaseAsset, report);
yield* report("installing");
yield* fileSystem
.writeFile(archivePath, download)
.pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
yield* fileSystem.writeFile(archivePath, download).pipe(
wrapInstallFailure(
(cause) =>
new RelayClientDownloadWriteError({
archivePath,
cause,
}),
),
);
const executablePath = path.join(tempDirectory, executableFileName(platform));
if (releaseAsset.archive === "tgz") {
yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
wrapInstallFailure("write_failed", "Could not extract the relay client."),
wrapInstallFailure(
(cause) =>
new RelayClientArchiveExtractError({
archivePath,
destinationDirectory: tempDirectory,
cause,
}),
),
);
}
if (platform !== "win32") {
yield* fileSystem
.chmod(executablePath, 0o755)
.pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
yield* fileSystem.chmod(executablePath, 0o755).pipe(
wrapInstallFailure(
(cause) =>
new RelayClientExecutablePermissionError({
executablePath,
cause,
}),
),
);
}
yield* report("validating");
yield* runCommand(executablePath, ["--version"]).pipe(
wrapInstallFailure("validation_failed", "The downloaded relay client binary did not run."),
wrapInstallFailure(
(cause) =>
new RelayClientExecutableValidationError({
executablePath,
cause,
}),
),
);
const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;
yield* report("activating");
yield* fileSystem
.rename(executablePath, stagedPath)
.pipe(wrapInstallFailure("write_failed", "Could not stage the relay client."));
yield* fileSystem
.rename(stagedPath, managedPath)
.pipe(
wrapInstallFailure("write_failed", "Could not activate the relay client."),
Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
);
yield* fileSystem.rename(executablePath, stagedPath).pipe(
wrapInstallFailure(
(cause) =>
new RelayClientStageError({
sourcePath: executablePath,
destinationPath: stagedPath,
cause,
}),
),
);
yield* fileSystem.rename(stagedPath, managedPath).pipe(
wrapInstallFailure(
(cause) =>
new RelayClientActivationError({
sourcePath: stagedPath,
destinationPath: managedPath,
cause,
}),
),
Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
);
return {
status: "available",
executablePath: managedPath,
@@ -446,19 +686,18 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
Effect.scoped,
Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
Effect.catch((cause) =>
cause instanceof RelayClientInstallError
isRelayClientInstallError(cause)
? Effect.fail(cause)
: Effect.fail(
new RelayClientInstallError({
reason: "write_failed",
message: "Could not install the relay client.",
new RelayClientInstallWriteError({
managedPath,
cause,
}),
),
),
);
});
const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
const installWithProgress: RelayClient["Service"]["installWithProgress"] = (report) =>
installSemaphore.withPermit(
installUnlocked((stage) =>
report({
+19 -18
View File
@@ -8,7 +8,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import { SshPasswordPromptError } from "./errors.ts";
import type { SshPasswordPromptError } from "./errors.ts";
export interface SshPasswordRequest {
readonly destination: string;
@@ -34,24 +34,25 @@ export interface SshAuthOptions {
readonly interactiveAuth?: boolean;
}
export interface SshPasswordPromptShape {
readonly isAvailable: boolean;
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string | null, SshPasswordPromptError>;
}
export class SshPasswordPrompt extends Context.Service<
SshPasswordPrompt,
{
readonly isAvailable: boolean;
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string | null, SshPasswordPromptError>;
}
>()("@t3tools/ssh/auth/SshPasswordPrompt") {}
export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPasswordPromptShape>()(
"@t3tools/ssh/auth/SshPasswordPrompt",
) {
static readonly disabledLayer = Layer.succeed(
SshPasswordPrompt,
SshPasswordPrompt.of({
isAvailable: false,
request: () => Effect.succeed(null),
}),
);
}
export const make = (service: SshPasswordPrompt["Service"]) => SshPasswordPrompt.of(service);
export const layer = (service: SshPasswordPrompt["Service"]) =>
Layer.succeed(SshPasswordPrompt, make(service));
export const disabledLayer = layer({
isAvailable: false,
request: () => Effect.succeed(null),
});
export interface SshChildEnvironmentOptions {
readonly interactiveAuth?: boolean;
+36 -4
View File
@@ -8,7 +8,7 @@ import * as Result from "effect/Result";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
baseSshArgs,
@@ -17,7 +17,7 @@ import {
resolveRemoteT3CliPackageSpec,
runSshCommand,
} from "./command.ts";
import { SshCommandError } from "./errors.ts";
import { SshCommandExitError, SshCommandSpawnError, SshTunnelExitError } from "./errors.ts";
const encoder = new TextEncoder();
@@ -167,11 +167,43 @@ describe("ssh command", () => {
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.instanceOf(result.failure, SshCommandError);
assert.instanceOf(result.failure, SshCommandExitError);
assert.equal(result.failure.message, "Pairing token creation failed");
assert.equal(result.failure.stdout, "Pairing token creation failed\n");
assert.equal(result.failure.stderr, "");
}
assert.equal(
new SshCommandExitError({
command: ["ssh"],
exitCode: 1,
stderr: "",
stdout: "",
target: "devbox",
}).message,
"SSH command failed for devbox (exit 1).",
);
assert.equal(
new SshTunnelExitError({
command: ["ssh"],
exitCode: 1,
stderr: "",
target: "devbox",
}).message,
"SSH tunnel exited unexpectedly for devbox (exit 1).",
);
const spawnCause = new Error("ssh executable path included sensitive diagnostics");
const spawnError = new SshCommandSpawnError({
command: ["ssh"],
exitCode: null,
stderr: "",
target: "devbox",
cause: spawnCause,
});
assert.strictEqual(spawnError.cause, spawnCause);
assert.equal(spawnError.message, "Failed to spawn SSH command for devbox.");
assert.notInclude(spawnError.message, spawnCause.message);
}).pipe(Effect.provide(processLayer));
});
@@ -197,7 +229,7 @@ describe("ssh command", () => {
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.instanceOf(result.failure, SshCommandError);
assert.instanceOf(result.failure, SshCommandExitError);
assert.equal(result.failure.message, '{"credential":"[redacted]"}');
assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n');
}
+30 -41
View File
@@ -9,10 +9,21 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
import * as SshAuth from "./auth.ts";
import {
SshAuthenticationHelperError,
type SshCommandError,
SshCommandExecutionError,
SshCommandExitError,
SshCommandSpawnError,
SshCommandTimeoutError,
SshHostAliasRequiredError,
type SshInvalidTargetError,
SshTargetDestinationMissingError,
} from "./errors.ts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
@@ -35,7 +46,7 @@ export interface SshCommandResult {
readonly stderr: string;
}
export interface RunSshCommandOptions extends SshAuthOptions {
export interface RunSshCommandOptions extends SshAuth.SshAuthOptions {
readonly preHostArgs?: ReadonlyArray<string>;
readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string;
@@ -93,9 +104,10 @@ export const buildSshHostSpecEffect = (
): Effect.Effect<string, SshInvalidTargetError> =>
Effect.try({
try: () => buildSshHostSpec(target),
catch: (cause) =>
new SshInvalidTargetError({
message: cause instanceof Error ? cause.message : "SSH target is invalid.",
catch: () =>
new SshTargetDestinationMissingError({
alias: target.alias,
hostname: target.hostname,
}),
});
@@ -143,20 +155,6 @@ function redactSshErrorOutput(output: string): string {
: redacted;
}
function normalizeSshErrorMessage(input: {
readonly stdout?: string;
readonly stderr: string;
readonly fallbackMessage: string;
}): string {
const cleanedStderr = input.stderr.trim();
if (cleanedStderr.length > 0) {
return cleanedStderr;
}
const cleanedStdout = input.stdout?.trim() ?? "";
return cleanedStdout.length > 0 ? cleanedStdout : input.fallbackMessage;
}
function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
return {
alias: target.alias,
@@ -180,17 +178,16 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const hostSpec = yield* buildSshHostSpecEffect(target);
const environment = yield* buildSshChildEnvironment({
const environment = yield* SshAuth.buildSshChildEnvironment({
...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
}).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
new SshAuthenticationHelperError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: "Failed to prepare SSH authentication helpers.",
cause,
}),
),
@@ -226,14 +223,11 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
Effect.provideService(Scope.Scope, commandScope),
Effect.mapError(
(cause) =>
new SshCommandError({
new SshCommandSpawnError({
command: [sshCommand, ...args],
exitCode: null,
stderr: "",
message:
cause instanceof Error
? cause.message
: `Failed to spawn SSH command for ${hostSpec}.`,
target: hostSpec,
cause,
}),
),
@@ -249,12 +243,11 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
new SshCommandExecutionError({
command: ["ssh", ...args],
exitCode: null,
stderr: "",
message:
cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
target: hostSpec,
cause,
}),
),
@@ -269,16 +262,12 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
stdout: diagnosticStdout,
stderr,
});
return yield* new SshCommandError({
return yield* new SshCommandExitError({
command: ["ssh", ...args],
exitCode,
stdout: diagnosticStdout,
stderr,
message: normalizeSshErrorMessage({
stdout: diagnosticStdout,
stderr,
fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
}),
target: hostSpec,
});
}
@@ -313,11 +302,11 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
preHostArgs: input.preHostArgs ?? [],
hasStdin: input.stdin !== undefined,
});
return yield* new SshCommandError({
return yield* new SshCommandTimeoutError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
});
}),
}),
@@ -334,7 +323,7 @@ export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(functi
> {
const trimmedAlias = alias.trim();
if (trimmedAlias.length === 0) {
return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
return yield* new SshHostAliasRequiredError({ alias });
}
yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
+10
View File
@@ -9,6 +9,7 @@ import {
parseKnownHostsHostnames,
resolveSshConfigIncludePattern,
} from "./config.ts";
import { SshHostDiscoveryError } from "./errors.ts";
function makeTempHomeDir() {
return Effect.gen(function* () {
@@ -18,6 +19,15 @@ function makeTempHomeDir() {
}
describe("ssh config", () => {
it("keeps host discovery causes separate from stable operation messages", () => {
const cause = new Error("home directory included sensitive diagnostics");
const error = new SshHostDiscoveryError({ homeDir: "/home/test", cause });
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "SSH host discovery failed for /home/test.");
assert.notInclude(error.message, cause.message);
});
it.effect("discovers ssh config hosts across included files", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+33 -24
View File
@@ -207,22 +207,30 @@ const readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) {
return parseKnownHostsHostnames(yield* fs.readFileString(filePath));
});
export const discoverSshHosts = Effect.fnUntraced(
function* (input: { readonly homeDir?: string }) {
const path = yield* Path.Path;
const env = yield* Config.all({
home: Config.string("HOME").pipe(Config.option),
userProfile: Config.string("USERPROFILE").pipe(Config.option),
});
const homeDir =
input?.homeDir ??
Option.getOrUndefined(env.home) ??
Option.getOrUndefined(env.userProfile) ??
"";
if (homeDir.trim().length === 0) {
return [];
}
export const discoverSshHosts = Effect.fnUntraced(function* (input: { readonly homeDir?: string }) {
const path = yield* Path.Path;
const env = yield* Config.all({
home: Config.string("HOME").pipe(Config.option),
userProfile: Config.string("USERPROFILE").pipe(Config.option),
}).pipe(
Effect.mapError(
(cause) =>
new SshHostDiscoveryError({
homeDir: input.homeDir ?? null,
cause,
}),
),
);
const homeDir =
input?.homeDir ??
Option.getOrUndefined(env.home) ??
Option.getOrUndefined(env.userProfile) ??
"";
if (homeDir.trim().length === 0) {
return [];
}
return yield* Effect.gen(function* () {
const sshDirectory = path.join(homeDir, ".ssh");
const configAliases = yield* collectSshConfigAliasesFromFile(
path.join(sshDirectory, "config"),
@@ -258,12 +266,13 @@ export const discoverSshHosts = Effect.fnUntraced(
return [...discovered.values()].toSorted((left, right) =>
left.alias.localeCompare(right.alias),
);
},
Effect.mapError(
(cause) =>
new SshHostDiscoveryError({
message: "Failed to discover SSH hosts.",
cause,
}),
),
);
}).pipe(
Effect.mapError(
(cause) =>
new SshHostDiscoveryError({
homeDir,
cause,
}),
),
);
});
+441 -39
View File
@@ -1,47 +1,449 @@
import * as Data from "effect/Data";
import * as Schema from "effect/Schema";
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
readonly message: string;
readonly cause: unknown;
}> {}
export class SshHostDiscoveryError extends Schema.TaggedErrorClass<SshHostDiscoveryError>()(
"SshHostDiscoveryError",
{
homeDir: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `SSH host discovery failed${this.homeDir === null ? "" : ` for ${this.homeDir}`}.`;
}
}
export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
readonly message: string;
}> {}
export class SshHostAliasRequiredError extends Schema.TaggedErrorClass<SshHostAliasRequiredError>()(
"SshHostAliasRequiredError",
{
alias: Schema.String,
},
) {
override get message(): string {
return "SSH host alias is required.";
}
}
export class SshCommandError extends Data.TaggedError("SshCommandError")<{
readonly message: string;
readonly command: readonly string[];
readonly exitCode: number | null;
readonly stderr: string;
readonly stdout?: string;
readonly cause?: unknown;
}> {}
export class SshTargetDestinationMissingError extends Schema.TaggedErrorClass<SshTargetDestinationMissingError>()(
"SshTargetDestinationMissingError",
{
alias: Schema.String,
hostname: Schema.String,
},
) {
override get message(): string {
return "SSH target is missing its alias/hostname.";
}
}
export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
readonly message: string;
readonly stdout: string;
readonly cause?: unknown;
}> {}
export const SshInvalidTargetError = Schema.Union([
SshHostAliasRequiredError,
SshTargetDestinationMissingError,
]);
export type SshInvalidTargetError = typeof SshInvalidTargetError.Type;
export class SshPairingError extends Data.TaggedError("SshPairingError")<{
readonly message: string;
readonly stdout: string;
readonly cause?: unknown;
}> {}
const SshCommandErrorFields = {
command: Schema.Array(Schema.String),
exitCode: Schema.NullOr(Schema.Number),
stderr: Schema.String,
stdout: Schema.optional(Schema.String),
target: Schema.optional(Schema.String),
timeoutMs: Schema.optional(Schema.Number),
};
export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
readonly message: string;
readonly status?: number;
readonly cause?: unknown;
}> {}
const SshCommandFailureFields = {
...SshCommandErrorFields,
cause: Schema.Defect(),
};
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SshAuthenticationHelperError extends Schema.TaggedErrorClass<SshAuthenticationHelperError>()(
"SshAuthenticationHelperError",
{
...SshCommandFailureFields,
},
) {
override get message(): string {
return `Failed to prepare SSH authentication helpers${targetSuffix(this.target)}.`;
}
}
export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SshCommandSpawnError extends Schema.TaggedErrorClass<SshCommandSpawnError>()(
"SshCommandSpawnError",
{
...SshCommandFailureFields,
},
) {
override get message(): string {
return `Failed to spawn SSH command${targetSuffix(this.target)}.`;
}
}
export class SshCommandExecutionError extends Schema.TaggedErrorClass<SshCommandExecutionError>()(
"SshCommandExecutionError",
{
...SshCommandFailureFields,
},
) {
override get message(): string {
return `Failed to run SSH command${targetSuffix(this.target)}.`;
}
}
export class SshCommandExitError extends Schema.TaggedErrorClass<SshCommandExitError>()(
"SshCommandExitError",
{
...SshCommandErrorFields,
},
) {
override get message(): string {
return (
this.stderr.trim() ||
this.stdout?.trim() ||
`SSH command failed${targetSuffix(this.target)}${exitCodeSuffix(this.exitCode)}.`
);
}
}
export class SshCommandTimeoutError extends Schema.TaggedErrorClass<SshCommandTimeoutError>()(
"SshCommandTimeoutError",
{
...SshCommandErrorFields,
},
) {
override get message(): string {
return `SSH command timed out after ${this.timeoutMs ?? 0}ms.`;
}
}
export class SshCommandCancelledError extends Schema.TaggedErrorClass<SshCommandCancelledError>()(
"SshCommandCancelledError",
{
...SshCommandErrorFields,
},
) {
override get message(): string {
return `SSH environment connection was cancelled${targetSuffix(this.target)}.`;
}
}
export class SshTunnelSpawnError extends Schema.TaggedErrorClass<SshTunnelSpawnError>()(
"SshTunnelSpawnError",
{
...SshCommandFailureFields,
},
) {
override get message(): string {
return `Failed to spawn SSH tunnel${targetSuffix(this.target)}.`;
}
}
export class SshTunnelMonitorError extends Schema.TaggedErrorClass<SshTunnelMonitorError>()(
"SshTunnelMonitorError",
{
...SshCommandFailureFields,
},
) {
override get message(): string {
return `Failed to monitor SSH tunnel${targetSuffix(this.target)}.`;
}
}
export class SshTunnelExitError extends Schema.TaggedErrorClass<SshTunnelExitError>()(
"SshTunnelExitError",
{
...SshCommandErrorFields,
},
) {
override get message(): string {
return (
this.stderr.trim() ||
this.stdout?.trim() ||
`SSH tunnel exited unexpectedly${targetSuffix(this.target)}${exitCodeSuffix(this.exitCode)}.`
);
}
}
export const SshCommandError = Schema.Union([
SshAuthenticationHelperError,
SshCommandSpawnError,
SshCommandExecutionError,
SshCommandExitError,
SshCommandTimeoutError,
SshCommandCancelledError,
SshTunnelSpawnError,
SshTunnelMonitorError,
SshTunnelExitError,
]);
export type SshCommandError = typeof SshCommandError.Type;
export class SshLaunchPortMissingError extends Schema.TaggedErrorClass<SshLaunchPortMissingError>()(
"SshLaunchPortMissingError",
{
stdout: Schema.String,
},
) {
override get message(): string {
return "SSH launch did not return a remote port.";
}
}
export class SshLaunchOutputParseError extends Schema.TaggedErrorClass<SshLaunchOutputParseError>()(
"SshLaunchOutputParseError",
{
stdout: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "SSH launch returned unparseable output.";
}
}
export class SshLaunchInvalidPortError extends Schema.TaggedErrorClass<SshLaunchInvalidPortError>()(
"SshLaunchInvalidPortError",
{
stdout: Schema.String,
remotePort: Schema.optional(Schema.Number),
},
) {
override get message(): string {
return `SSH launch returned an invalid remote port: ${String(this.remotePort)}.`;
}
}
export const SshLaunchError = Schema.Union([
SshLaunchPortMissingError,
SshLaunchOutputParseError,
SshLaunchInvalidPortError,
]);
export type SshLaunchError = typeof SshLaunchError.Type;
export class SshPairingCredentialMissingError extends Schema.TaggedErrorClass<SshPairingCredentialMissingError>()(
"SshPairingCredentialMissingError",
{
stdout: Schema.String,
},
) {
override get message(): string {
return "SSH pairing did not return a credential.";
}
}
export class SshPairingOutputParseError extends Schema.TaggedErrorClass<SshPairingOutputParseError>()(
"SshPairingOutputParseError",
{
stdout: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "SSH pairing returned unparseable output.";
}
}
export class SshPairingInvalidCredentialError extends Schema.TaggedErrorClass<SshPairingInvalidCredentialError>()(
"SshPairingInvalidCredentialError",
{
stdout: Schema.String,
},
) {
override get message(): string {
return "SSH pairing command returned an invalid credential.";
}
}
export const SshPairingError = Schema.Union([
SshPairingCredentialMissingError,
SshPairingOutputParseError,
SshPairingInvalidCredentialError,
]);
export type SshPairingError = typeof SshPairingError.Type;
export class SshHttpBridgeInvalidUrlError extends Schema.TaggedErrorClass<SshHttpBridgeInvalidUrlError>()(
"SshHttpBridgeInvalidUrlError",
{
reason: Schema.Literals(["missing_url", "invalid_url"]),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return "Invalid SSH forwarded HTTP base URL.";
}
}
export class SshHttpBridgeNonLoopbackUrlError extends Schema.TaggedErrorClass<SshHttpBridgeNonLoopbackUrlError>()(
"SshHttpBridgeNonLoopbackUrlError",
{
hostname: Schema.String,
},
) {
override get message(): string {
return `SSH desktop bridge only supports loopback forwarded URLs${targetSuffix(this.hostname)}.`;
}
}
export const SshHttpBridgeError = Schema.Union([
SshHttpBridgeInvalidUrlError,
SshHttpBridgeNonLoopbackUrlError,
]);
export type SshHttpBridgeError = typeof SshHttpBridgeError.Type;
export class SshReadinessProbeError extends Schema.TaggedErrorClass<SshReadinessProbeError>()(
"SshReadinessProbeError",
{
requestUrl: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Backend readiness probe failed at ${this.requestUrl}.`;
}
}
export class SshReadinessProbeTimeoutError extends Schema.TaggedErrorClass<SshReadinessProbeTimeoutError>()(
"SshReadinessProbeTimeoutError",
{
requestUrl: Schema.String,
timeoutMs: Schema.Number,
attempt: Schema.Number,
},
) {
override get message(): string {
return `Backend readiness probe exceeded ${this.timeoutMs}ms at ${this.requestUrl}.`;
}
}
export class SshReadinessTimeoutError extends Schema.TaggedErrorClass<SshReadinessTimeoutError>()(
"SshReadinessTimeoutError",
{
requestUrl: Schema.String,
timeoutMs: Schema.Number,
attempts: Schema.Number,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Timed out waiting ${this.timeoutMs}ms for backend readiness at ${this.requestUrl}.`;
}
}
export const SshReadinessError = Schema.Union([
SshReadinessProbeError,
SshReadinessProbeTimeoutError,
SshReadinessTimeoutError,
]);
export type SshReadinessError = typeof SshReadinessError.Type;
export class SshPasswordPromptUnavailableError extends Schema.TaggedErrorClass<SshPasswordPromptUnavailableError>()(
"SshPasswordPromptUnavailableError",
{
destination: Schema.String,
},
) {
override get message(): string {
return `SSH authentication failed for ${this.destination}.`;
}
}
export class SshPasswordPromptCancelledError extends Schema.TaggedErrorClass<SshPasswordPromptCancelledError>()(
"SshPasswordPromptCancelledError",
{
destination: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `SSH authentication cancelled for ${this.destination}.`;
}
}
export class SshPasswordPromptSecureRandomnessError extends Schema.TaggedErrorClass<SshPasswordPromptSecureRandomnessError>()(
"SshPasswordPromptSecureRandomnessError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Secure randomness is unavailable.";
}
}
export class SshPasswordPromptWindowUnavailableError extends Schema.TaggedErrorClass<SshPasswordPromptWindowUnavailableError>()(
"SshPasswordPromptWindowUnavailableError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "T3 Code window is not available for SSH authentication.";
}
}
export class SshPasswordPromptTimedOutError extends Schema.TaggedErrorClass<SshPasswordPromptTimedOutError>()(
"SshPasswordPromptTimedOutError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `SSH authentication timed out for ${this.destination}.`;
}
}
export class SshPasswordPromptWindowClosedError extends Schema.TaggedErrorClass<SshPasswordPromptWindowClosedError>()(
"SshPasswordPromptWindowClosedError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "SSH authentication was cancelled because the app window closed.";
}
}
export class SshPasswordPromptServiceStoppedError extends Schema.TaggedErrorClass<SshPasswordPromptServiceStoppedError>()(
"SshPasswordPromptServiceStoppedError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "SSH password prompt service stopped.";
}
}
export class SshPasswordPromptRequestError extends Schema.TaggedErrorClass<SshPasswordPromptRequestError>()(
"SshPasswordPromptRequestError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `SSH authentication failed for ${this.destination}.`;
}
}
export const SshPasswordPromptError = Schema.Union([
SshPasswordPromptUnavailableError,
SshPasswordPromptCancelledError,
SshPasswordPromptSecureRandomnessError,
SshPasswordPromptWindowUnavailableError,
SshPasswordPromptTimedOutError,
SshPasswordPromptWindowClosedError,
SshPasswordPromptServiceStoppedError,
SshPasswordPromptRequestError,
]);
export type SshPasswordPromptError = typeof SshPasswordPromptError.Type;
function targetSuffix(target: string | undefined): string {
return target ? ` for ${target}` : "";
}
function exitCodeSuffix(exitCode: number | null): string {
return exitCode === null ? "" : ` (exit ${exitCode})`;
}
+81 -63
View File
@@ -8,23 +8,15 @@ import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as TestClock from "effect/testing/TestClock";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { SshPasswordPrompt } from "./auth.ts";
import {
buildRemoteLaunchScript,
buildRemotePairingScript,
buildRemoteStopScript,
buildRemoteT3RunnerScript,
describeReadinessCause,
issueRemotePairingToken,
launchOrReuseRemoteServer,
REMOTE_PICK_PORT_SCRIPT,
SshEnvironmentManager,
waitForHttpReady,
} from "./tunnel.ts";
import * as SshAuth from "./auth.ts";
import { SshReadinessProbeTimeoutError, SshReadinessTimeoutError } from "./errors.ts";
import * as SshTunnel from "./tunnel.ts";
const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
@@ -90,7 +82,7 @@ function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
describe("ssh tunnel scripts", () => {
it("builds the remote t3 runner with npx and npm fallbacks", () => {
const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
const script = SshTunnel.buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
assert.include(script, "T3_NODE_SCRIPT_PATH=''");
assert.include(script, 'exec t3 "$@"');
@@ -116,14 +108,14 @@ describe("ssh tunnel scripts", () => {
});
it("does not hard-code a remote node engine range", () => {
const script = buildRemoteT3RunnerScript();
const script = SshTunnel.buildRemoteT3RunnerScript();
assert.include(script, "T3_NODE_ENGINE_RANGE=''");
assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
});
it("shell-quotes package specs in the remote t3 runner", () => {
const script = buildRemoteT3RunnerScript({
const script = SshTunnel.buildRemoteT3RunnerScript({
packageSpec: "t3@nightly; touch /tmp/t3-owned",
});
@@ -133,7 +125,7 @@ describe("ssh tunnel scripts", () => {
});
it("builds the remote t3 runner with a node script override", () => {
const script = buildRemoteT3RunnerScript({
const script = SshTunnel.buildRemoteT3RunnerScript({
nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
});
@@ -153,65 +145,82 @@ describe("ssh tunnel scripts", () => {
} as const;
assert.include(
buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
SshTunnel.buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
'[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
);
assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
assert.include(buildRemoteLaunchScript(), "ensure_remote_node_path()");
assert.include(buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
assert.include(SshTunnel.buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
assert.include(SshTunnel.buildRemoteLaunchScript(), "ensure_remote_node_path()");
assert.include(SshTunnel.buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
assert.include(
buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
SshTunnel.buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
`T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`,
);
assert.include(
buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
SshTunnel.buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
"does not satisfy required range ",
);
assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
assert.include(buildRemoteLaunchScript(), "wait_ready");
assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
assert.include(buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
assert.notInclude(buildRemoteLaunchScript(), "server-home");
assert.include(buildRemoteLaunchScript(), "Remote T3 server did not become ready");
assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
assert.include(SshTunnel.buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
assert.include(SshTunnel.buildRemoteLaunchScript(), "wait_ready");
assert.include(SshTunnel.buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
assert.include(SshTunnel.buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
assert.notInclude(SshTunnel.buildRemoteLaunchScript(), "server-home");
assert.include(SshTunnel.buildRemoteLaunchScript(), "Remote T3 server did not become ready");
assert.include(SshTunnel.buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
assert.include(
buildRemotePairingScript(target),
SshTunnel.buildRemotePairingScript(target),
'"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
);
assert.include(buildRemotePairingScript(target), 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"');
assert.notInclude(buildRemotePairingScript(target), "server-home");
assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
assert.include(
buildRemoteStopScript(target),
SshTunnel.buildRemotePairingScript(target),
'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"',
);
assert.notInclude(SshTunnel.buildRemotePairingScript(target), "server-home");
assert.include(
SshTunnel.buildRemotePairingScript(target, { packageSpec: "t3@nightly" }),
"t3@nightly",
);
assert.include(
SshTunnel.buildRemoteStopScript(target),
'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
);
assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
assert.include(
buildRemoteLaunchScript(),
SshTunnel.buildRemoteStopScript(target),
'kill "$REMOTE_PID" 2>/dev/null || true',
);
assert.include(
SshTunnel.buildRemoteStopScript(target),
'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"',
);
assert.include(
SshTunnel.buildRemoteLaunchScript(),
'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
);
assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
assert.include(SshTunnel.buildRemoteLaunchScript(), "resolve_default_runtime_port()");
assert.include(
buildRemoteLaunchScript(),
SshTunnel.buildRemoteLaunchScript(),
'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
);
assert.include(
buildRemoteLaunchScript(),
SshTunnel.buildRemoteLaunchScript(),
"if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))",
);
assert.include(buildRemoteLaunchScript(), 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
assert.include(buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
assert.include(buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
assert.include(buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
assert.include(
SshTunnel.buildRemoteLaunchScript(),
'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"',
);
assert.include(SshTunnel.buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
assert.include(SshTunnel.buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
assert.include(SshTunnel.buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
assert.include(SshTunnel.buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
assert.isBelow(
buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
SshTunnel.buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
SshTunnel.buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
);
assert.isBelow(
buildRemoteLaunchScript().indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
SshTunnel.buildRemoteLaunchScript().indexOf(
'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
),
SshTunnel.buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
);
});
@@ -229,21 +238,22 @@ describe("ssh tunnel scripts", () => {
const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
return Effect.gen(function* () {
const result = yield* launchOrReuseRemoteServer(target);
const result = yield* SshTunnel.launchOrReuseRemoteServer(target);
assert.equal(result.remotePort, 3774);
}).pipe(Effect.provide(processLayer));
});
it("allows the remote port picker to run without a state file path", () => {
assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
assert.include(SshTunnel.REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
});
it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
Effect.gen(function* () {
const fiber = yield* Effect.forkChild(
Effect.result(
waitForHttpReady({
SshTunnel.waitForHttpReady({
baseUrl: "http://127.0.0.1:41773/",
path: "/ready",
timeoutMs: 1_000,
intervalMs: 100,
probeTimeoutMs: 250,
@@ -257,7 +267,15 @@ describe("ssh tunnel scripts", () => {
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.include(result.failure.message, "Timed out waiting 1000ms");
assert.instanceOf(result.failure, SshReadinessTimeoutError);
const timeoutError = result.failure as SshReadinessTimeoutError;
assert.equal(timeoutError.requestUrl, "http://127.0.0.1:41773/ready");
assert.include(timeoutError.message, "Timed out waiting 1000ms");
assert.isAbove(timeoutError.attempts, 0);
assert.instanceOf(timeoutError.cause, SshReadinessProbeTimeoutError);
const probeTimeout = timeoutError.cause as SshReadinessProbeTimeoutError;
assert.equal(probeTimeout.attempt, timeoutError.attempts);
assert.isFalse("cause" in probeTimeout);
}
}).pipe(
Effect.provide(
@@ -268,7 +286,7 @@ describe("ssh tunnel scripts", () => {
it("preserves primitive readiness reason values in diagnostic output", () => {
assert.deepEqual(
describeReadinessCause({
SshTunnel.describeReadinessCause({
_tag: "HttpClientError",
message: "Backend readiness probe failed.",
reason: "authentication failed",
@@ -305,7 +323,7 @@ describe("ssh tunnel scripts", () => {
const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
return Effect.gen(function* () {
const result = yield* issueRemotePairingToken(target);
const result = yield* SshTunnel.issueRemotePairingToken(target);
assert.equal(result.credential, "LCL4R2TPHDKQ");
}).pipe(Effect.provide(processLayer));
});
@@ -333,7 +351,7 @@ describe("ssh tunnel scripts", () => {
const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
return Effect.gen(function* () {
const result = yield* issueRemotePairingToken(target);
const result = yield* SshTunnel.issueRemotePairingToken(target);
assert.equal(result.credential, "LCL4R2TPHDKQ");
}).pipe(Effect.provide(processLayer));
});
@@ -366,8 +384,8 @@ describe("ssh tunnel scripts", () => {
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, testHttpClient),
Layer.succeed(NetService.NetService, testNetService),
SshPasswordPrompt.disabledLayer,
SshEnvironmentManager.layer(),
SshAuth.disabledLayer,
SshTunnel.layer(),
);
const target = {
alias: "devbox",
@@ -377,7 +395,7 @@ describe("ssh tunnel scripts", () => {
} as const;
return Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const manager = yield* SshTunnel.SshEnvironmentManager;
const first = yield* manager.ensureEnvironment(target);
assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
+119 -129
View File
@@ -19,15 +19,12 @@ import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
buildSshChildEnvironment,
type SshAuthOptions,
SshPasswordPrompt,
isSshAuthFailure,
} from "./auth.ts";
import * as SshAuth from "./auth.ts";
import {
baseSshArgs,
buildSshHostSpecEffect,
@@ -40,15 +37,35 @@ import {
targetConnectionKey,
} from "./command.ts";
import {
SshAuthenticationHelperError,
SshCommandCancelledError,
SshCommandError,
SshHttpBridgeInvalidUrlError,
SshHttpBridgeNonLoopbackUrlError,
SshHttpBridgeError,
SshInvalidTargetError,
SshLaunchInvalidPortError,
SshLaunchOutputParseError,
SshLaunchPortMissingError,
SshLaunchError,
SshPairingCredentialMissingError,
SshPairingInvalidCredentialError,
SshPairingOutputParseError,
SshPairingError,
SshPasswordPromptCancelledError,
SshPasswordPromptUnavailableError,
SshPasswordPromptError,
SshReadinessProbeError,
SshReadinessProbeTimeoutError,
SshReadinessTimeoutError,
SshReadinessError,
SshTunnelExitError,
SshTunnelMonitorError,
SshTunnelSpawnError,
} from "./errors.ts";
const isSshReadinessError = Schema.is(SshReadinessError);
export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT_MS = 20_000;
@@ -86,7 +103,7 @@ type SshEnvironmentEffectContext =
| Path.Path
| HttpClient.HttpClient
| NetService.NetService
| SshPasswordPrompt;
| SshAuth.SshPasswordPrompt;
type SshEnvironmentEffectError =
| SshCommandError
@@ -98,11 +115,11 @@ type SshEnvironmentEffectError =
| NetService.NetError;
function makeSshTunnelCancelledError(target: DesktopSshEnvironmentTarget): SshCommandError {
return new SshCommandError({
return new SshCommandCancelledError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH environment connection was cancelled for ${target.alias || target.hostname}.`,
target: target.alias || target.hostname,
});
}
@@ -129,7 +146,7 @@ interface SshAuthOperationInput<T> {
readonly key: string;
readonly target: DesktopSshEnvironmentTarget;
readonly operation: (
authOptions: SshAuthOptions,
authOptions: SshAuth.SshAuthOptions,
) => Effect.Effect<T, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
}
@@ -138,19 +155,25 @@ interface SshAuthAttemptInput<T> extends SshAuthOperationInput<T> {
readonly authSecret: string | null;
}
export interface SshEnvironmentManagerShape {
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<
DesktopSshEnvironmentBootstrap,
SshEnvironmentEffectError,
SshEnvironmentEffectContext
>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
}
/**
* @effect-expect-leaking ChildProcessSpawner | FileSystem | HttpClient | NetService | Path | SshAuth.SshPasswordPrompt
*/
export class SshEnvironmentManager extends Context.Service<
SshEnvironmentManager,
{
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<
DesktopSshEnvironmentBootstrap,
SshEnvironmentEffectError,
SshEnvironmentEffectContext
>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
}
>()("@t3tools/ssh/tunnel/SshEnvironmentManager") {}
const RemoteLaunchResult = Schema.Struct({
remotePort: Schema.Number,
@@ -208,11 +231,6 @@ function buildRemoteNodeEngineCheckScript(): string {
(${remoteNodeEngineCheckMain.toString()})();`;
}
export function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {
const cleaned = stderr.trim();
return cleaned.length > 0 ? cleaned : fallbackMessage;
}
function stripTrailingNewlines(value: string): string {
return value.replace(/\n+$/u, "");
}
@@ -233,11 +251,12 @@ function applyScriptPlaceholders(
}
export function describeReadinessCause(cause: unknown): unknown {
if (cause instanceof SshReadinessError) {
if (isSshReadinessError(cause)) {
const nestedCause = "cause" in cause ? cause.cause : undefined;
return {
_tag: cause._tag,
message: cause.message,
...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
...(nestedCause === undefined ? {} : { cause: describeReadinessCause(nestedCause) }),
};
}
if (cause instanceof Error) {
@@ -714,7 +733,7 @@ function buildRemoteLogTailScript(target: DesktopSshEnvironmentTarget): string {
export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemoteServer")(
function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
input?: SshAuth.SshAuthOptions,
runner?: RemoteT3RunnerOptions,
): Effect.fn.Return<
{ readonly remotePort: number; readonly remoteServerKind: "external" | "managed" | null },
@@ -734,25 +753,23 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
if (!getLastNonEmptyOutputLine(result.stdout)) {
return yield* new SshLaunchError({
message: "SSH launch did not return a remote port.",
return yield* new SshLaunchPortMissingError({
stdout: result.stdout,
});
}
const parsed = yield* decodeRemoteLaunchOutput(result.stdout).pipe(
Effect.mapError(
(cause) =>
new SshLaunchError({
message: "SSH launch returned unparseable output.",
new SshLaunchOutputParseError({
stdout: result.stdout,
cause,
}),
),
);
if (!Number.isInteger(parsed.remotePort)) {
return yield* new SshLaunchError({
message: `SSH launch returned an invalid remote port: ${String(parsed.remotePort)}.`,
return yield* new SshLaunchInvalidPortError({
stdout: result.stdout,
remotePort: parsed.remotePort,
});
}
yield* Effect.logInfo("ssh.remoteServer.launch.ready", {
@@ -770,7 +787,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingToken")(function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
input?: SshAuth.SshAuthOptions,
runner?: RemoteT3RunnerOptions,
): Effect.fn.Return<
{
@@ -791,24 +808,21 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
if (!getLastNonEmptyOutputLine(result.stdout)) {
return yield* new SshPairingError({
message: "SSH pairing did not return a credential.",
return yield* new SshPairingCredentialMissingError({
stdout: result.stdout,
});
}
const parsed = yield* decodeRemotePairingOutput(result.stdout).pipe(
Effect.mapError(
(cause) =>
new SshPairingError({
message: "SSH pairing returned unparseable output.",
new SshPairingOutputParseError({
stdout: result.stdout,
cause,
}),
),
);
if (parsed.credential.trim().length === 0) {
return yield* new SshPairingError({
message: "SSH pairing command returned an invalid credential.",
return yield* new SshPairingInvalidCredentialError({
stdout: result.stdout,
});
}
@@ -823,7 +837,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT
export const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
input?: SshAuth.SshAuthOptions,
): Effect.fn.Return<
void,
SshCommandError | SshInvalidTargetError,
@@ -848,7 +862,7 @@ export const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(functio
const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
input?: SshAuth.SshAuthOptions,
): Effect.fn.Return<
string,
SshCommandError | SshInvalidTargetError,
@@ -900,8 +914,8 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
Effect.mapError(
(cause) =>
new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
new SshReadinessProbeError({
requestUrl,
cause,
}),
),
@@ -910,31 +924,23 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SshReadinessError({
message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
cause: {
kind: "probe-timeout",
attempt,
probeTimeoutMs,
},
new SshReadinessProbeTimeoutError({
requestUrl,
timeoutMs: probeTimeoutMs,
attempt,
}),
),
});
}).pipe(
Effect.mapError((cause) =>
cause instanceof SshReadinessError
isSshReadinessError(cause)
? cause
: new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
: new SshReadinessProbeError({
requestUrl,
cause,
}),
),
Effect.tapError((cause) =>
Ref.set(lastProbeFailure, {
attempt,
cause: describeReadinessCause(cause),
}),
),
Effect.tapError((cause) => Ref.set(lastProbeFailure, cause)),
),
),
HttpClient.tap((response) => response.text.pipe(Effect.ignore)),
@@ -943,10 +949,10 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
Effect.mapError((cause) =>
cause instanceof SshReadinessError
isSshReadinessError(cause)
? cause
: new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
: new SshReadinessProbeError({
requestUrl,
cause,
}),
),
@@ -970,11 +976,13 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
intervalMs,
probeTimeoutMs,
attempts: attempt,
lastFailure,
lastFailure: describeReadinessCause(lastFailure),
});
return yield* new SshReadinessError({
message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`,
cause: lastFailure,
return yield* new SshReadinessTimeoutError({
requestUrl,
timeoutMs,
attempts: attempt,
...(lastFailure === null ? {} : { cause: lastFailure }),
});
}),
});
@@ -990,23 +998,19 @@ function isLoopbackHostname(hostname: string): boolean {
export const resolveLoopbackSshHttpBaseUrl = Effect.fn("ssh/tunnel.resolveLoopbackSshHttpBaseUrl")(
function* (rawHttpBaseUrl: unknown): Effect.fn.Return<string, SshHttpBridgeError> {
return yield* Effect.try({
try: () => {
if (typeof rawHttpBaseUrl !== "string" || rawHttpBaseUrl.trim().length === 0) {
throw new Error("Invalid SSH forwarded http base URL.");
}
const baseUrl = new URL(rawHttpBaseUrl);
if (!isLoopbackHostname(baseUrl.hostname)) {
throw new Error("SSH desktop bridge only supports loopback forwarded URLs.");
}
return baseUrl.toString();
},
catch: (cause) =>
new SshHttpBridgeError({
message: cause instanceof Error ? cause.message : "Invalid SSH forwarded http base URL.",
cause,
}),
if (typeof rawHttpBaseUrl !== "string" || rawHttpBaseUrl.trim().length === 0) {
return yield* new SshHttpBridgeInvalidUrlError({ reason: "missing_url" });
}
const baseUrl = yield* Effect.try({
try: () => new URL(rawHttpBaseUrl),
catch: (cause) => new SshHttpBridgeInvalidUrlError({ reason: "invalid_url", cause }),
});
if (!isLoopbackHostname(baseUrl.hostname)) {
return yield* new SshHttpBridgeNonLoopbackUrlError({
hostname: baseUrl.hostname,
});
}
return baseUrl.toString();
},
);
@@ -1022,7 +1026,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
readonly localPort: number;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly authOptions: SshAuthOptions;
readonly authOptions: SshAuth.SshAuthOptions;
readonly remoteServerKind: "external" | "managed" | null;
}): Effect.fn.Return<
SshTunnelEntry,
@@ -1035,7 +1039,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
| Scope.Scope
> {
const hostSpec = yield* buildSshHostSpecEffect(input.resolvedTarget);
const childEnvironment = yield* buildSshChildEnvironment({
const childEnvironment = yield* SshAuth.buildSshChildEnvironment({
...(input.authOptions.authSecret === undefined
? {}
: { authSecret: input.authOptions.authSecret }),
@@ -1045,11 +1049,10 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
}).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
new SshAuthenticationHelperError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: "Failed to prepare SSH authentication helpers.",
cause,
}),
),
@@ -1096,14 +1099,11 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
.pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
new SshTunnelSpawnError({
command: tunnelCommand,
exitCode: null,
stderr: "",
message:
cause instanceof Error
? cause.message
: `Failed to spawn SSH tunnel for ${input.resolvedTarget.alias}.`,
target: input.resolvedTarget.alias,
cause,
}),
),
@@ -1133,26 +1133,20 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
new SshTunnelMonitorError({
command: tunnelCommand,
exitCode: null,
stderr: "",
message:
cause instanceof Error
? cause.message
: `Failed to monitor SSH tunnel for ${input.resolvedTarget.alias}.`,
target: input.resolvedTarget.alias,
cause,
}),
),
Effect.flatMap(([stderr, exitCode]) => {
const error = new SshCommandError({
const error = new SshTunnelExitError({
command: tunnelCommand,
exitCode,
stderr,
message: normalizeSshErrorMessage(
stderr,
`SSH tunnel exited unexpectedly for ${input.resolvedTarget.alias} (exit ${exitCode}).`,
),
target: input.resolvedTarget.alias,
});
return Effect.logWarning("ssh.tunnel.process.exited", {
...sshTargetLogFields(input.resolvedTarget),
@@ -1237,9 +1231,9 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
return tunnelEntry;
});
const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.make")(function* (
export const make = Effect.fn("ssh/tunnel.SshEnvironmentManager.make")(function* (
options: SshEnvironmentManagerOptions = {},
): Effect.fn.Return<SshEnvironmentManagerShape, never, Scope.Scope> {
): Effect.fn.Return<SshEnvironmentManager["Service"], never, Scope.Scope> {
const managerScope = yield* Scope.Scope;
const tunnels = new Map<string, SshTunnelEntry>();
const pendingTunnelEntries = new Map<
@@ -1291,16 +1285,20 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
const promptForPassword = Effect.fn("ssh/tunnel.promptForPassword")(function* (
target: DesktopSshEnvironmentTarget,
attempt: number,
): Effect.fn.Return<string, SshInvalidTargetError | SshPasswordPromptError, SshPasswordPrompt> {
const promptService = yield* SshPasswordPrompt;
): Effect.fn.Return<
string,
SshInvalidTargetError | SshPasswordPromptError,
SshAuth.SshPasswordPrompt
> {
const promptService = yield* SshAuth.SshPasswordPrompt;
const hostSpec = yield* buildSshHostSpecEffect(target);
if (!promptService.isAvailable) {
yield* Effect.logWarning("ssh.auth.passwordPrompt.unavailable", {
...sshTargetLogFields(target),
attempt,
});
return yield* new SshPasswordPromptError({
message: `SSH authentication failed for ${hostSpec}.`,
return yield* new SshPasswordPromptUnavailableError({
destination: hostSpec,
});
}
@@ -1319,8 +1317,8 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
...sshTargetLogFields(target),
attempt,
});
return yield* new SshPasswordPromptError({
message: `SSH authentication cancelled for ${hostSpec}.`,
return yield* new SshPasswordPromptCancelledError({
destination: hostSpec,
});
}
yield* Effect.logInfo("ssh.auth.passwordPrompt.received", {
@@ -1336,7 +1334,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
readonly error: SshEnvironmentEffectError;
},
): Effect.fn.Return<T, SshEnvironmentEffectError, SshEnvironmentEffectContext> {
if (!isSshAuthFailure(input.error)) {
if (!SshAuth.isSshAuthFailure(input.error)) {
return yield* input.error;
}
@@ -1346,7 +1344,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
promptCount: input.promptCount,
cause: input.error,
});
const promptService = yield* SshPasswordPrompt;
const promptService = yield* SshAuth.SshPasswordPrompt;
if (!promptService.isAvailable) {
return yield* input.error;
}
@@ -1371,7 +1369,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
const runWithSshAuthAttempt = Effect.fn("ssh/tunnel.runWithSshAuthAttempt")(function* <T>(
input: SshAuthAttemptInput<T>,
): Effect.fn.Return<T, SshEnvironmentEffectError, SshEnvironmentEffectContext> {
const promptService = yield* SshPasswordPrompt;
const promptService = yield* SshAuth.SshPasswordPrompt;
const authOptions =
input.authSecret === null
? {
@@ -1686,13 +1684,5 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
return SshEnvironmentManager.of({ ensureEnvironment, disconnectEnvironment });
});
/**
* @effect-expect-leaking ChildProcessSpawner | FileSystem | HttpClient | NetService | Path | SshPasswordPrompt
*/
export class SshEnvironmentManager extends Context.Service<
SshEnvironmentManager,
SshEnvironmentManagerShape
>()("@t3tools/ssh/tunnel/SshEnvironmentManager") {
static readonly layer = (options: SshEnvironmentManagerOptions = {}) =>
Layer.effect(SshEnvironmentManager, makeSshEnvironmentManager(options));
}
export const layer = (options: SshEnvironmentManagerOptions = {}) =>
Layer.effect(SshEnvironmentManager, make(options));