Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfc32cd101 | ||
|
|
6c12fe1e6c | ||
|
|
47c042422c | ||
|
|
4ec16654a6 |
No files matched your search
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
@@ -106,7 +105,6 @@ const withIdentity = <A, E, R>(
|
||||
readonly calls?: ElectronAppCalls;
|
||||
readonly environment?: TestEnvironmentInput;
|
||||
readonly legacyPathExists?: boolean;
|
||||
readonly legacyPathProbeError?: PlatformError.PlatformError;
|
||||
readonly packageJson?: string;
|
||||
readonly pngIconPath?: Option.Option<string>;
|
||||
} = {},
|
||||
@@ -123,11 +121,7 @@ const withIdentity = <A, E, R>(
|
||||
Layer.provideMerge(
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) =>
|
||||
input.legacyPathProbeError
|
||||
? Effect.fail(input.legacyPathProbeError)
|
||||
: Effect.succeed(
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
|
||||
),
|
||||
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
|
||||
readFileString: () =>
|
||||
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
|
||||
}),
|
||||
@@ -153,33 +147,6 @@ describe("DesktopAppIdentity", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves failures while inspecting the legacy userData path", () => {
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: legacyPath,
|
||||
});
|
||||
|
||||
return withIdentity(
|
||||
Effect.gen(function* () {
|
||||
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
|
||||
assert.equal(error.legacyPath, legacyPath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
|
||||
);
|
||||
}),
|
||||
{ legacyPathProbeError: cause },
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("configures app identity from the environment commit override", () => {
|
||||
const calls: ElectronAppCalls = {
|
||||
setAboutPanelOptions: [],
|
||||
|
||||
@@ -18,22 +18,10 @@ const AppPackageMetadata = Schema.Struct({
|
||||
});
|
||||
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
|
||||
|
||||
export class DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()(
|
||||
"DesktopUserDataPathResolutionError",
|
||||
{
|
||||
legacyPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
{
|
||||
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
@@ -45,7 +33,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
: Option.none();
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -95,15 +83,9 @@ export const make = Effect.gen(function* () {
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem
|
||||
.exists(legacyPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopAssets from "./DesktopAssets.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
describe("DesktopAssets", () => {
|
||||
it.effect("preserves the failed asset candidate and filesystem cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileName = "custom.bin";
|
||||
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
pathOrDescriptor: candidatePath,
|
||||
description: "private filesystem diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
|
||||
});
|
||||
const assetsLayer = DesktopAssets.layer.pipe(
|
||||
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
|
||||
);
|
||||
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
|
||||
|
||||
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
|
||||
assert.equal(error.fileName, fileName);
|
||||
assert.equal(error.candidatePath, candidatePath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private filesystem diagnostic");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
@@ -13,26 +12,11 @@ export interface DesktopIconPaths {
|
||||
readonly png: Option.Option<string>;
|
||||
}
|
||||
|
||||
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()(
|
||||
"DesktopAssetProbeError",
|
||||
{
|
||||
fileName: Schema.String,
|
||||
candidatePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<
|
||||
DesktopAssets,
|
||||
{
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (
|
||||
fileName: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAssets") {}
|
||||
|
||||
@@ -40,20 +24,14 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
|
||||
fileName: string,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<string>,
|
||||
DesktopAssetProbeError,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const candidates = environment.resolveResourcePathCandidates(fileName);
|
||||
for (const candidate of candidates) {
|
||||
const exists = yield* fileSystem
|
||||
.exists(candidate)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
|
||||
),
|
||||
);
|
||||
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
|
||||
if (exists) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
@@ -65,23 +43,16 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
ext: keyof DesktopIconPaths,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<string>,
|
||||
DesktopAssetProbeError,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopAssetProbeError({
|
||||
fileName: "icon.png",
|
||||
candidatePath: developmentDockIconPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (developmentDockIconExists) {
|
||||
return Option.some(developmentDockIconPath);
|
||||
}
|
||||
@@ -90,7 +61,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
return yield* resolveResourcePath(`icon.${ext}`);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
>();
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
|
||||
createClerkBridgeMock: vi.fn(),
|
||||
@@ -25,23 +24,7 @@ vi.mock("@clerk/electron/storage", () => ({
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const makeDesktopClerkLayer = (isDevelopment = true) => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
return DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
);
|
||||
};
|
||||
|
||||
describe("DesktopClerk", () => {
|
||||
beforeEach(() => {
|
||||
createClerkBridgeMock.mockReset();
|
||||
storageMock.mockReset();
|
||||
});
|
||||
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
@@ -57,9 +40,19 @@ describe("DesktopClerk", () => {
|
||||
const cleanup = vi.fn();
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment: true,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
yield* Effect.scoped(
|
||||
Layer.build(
|
||||
DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
@@ -76,54 +69,6 @@ describe("DesktopClerk", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves bridge initialization failures", () => {
|
||||
const cause = new Error("bridge initialization failed");
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
|
||||
assert.equal(error.stateDir, "/tmp/t3-state");
|
||||
assert.equal(error.isDevelopment, true);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves bridge cleanup failures", () => {
|
||||
const cause = new Error("bridge cleanup failed");
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({
|
||||
cleanup: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
|
||||
assert.equal(error.stateDir, "/tmp/t3-state");
|
||||
assert.equal(error.isDevelopment, false);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
|
||||
@@ -4,7 +4,6 @@ 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 Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
@@ -15,32 +14,6 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
|
||||
"DesktopClerkBridgeInitializationError",
|
||||
{
|
||||
stateDir: Schema.String,
|
||||
isDevelopment: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
|
||||
"DesktopClerkBridgeCleanupError",
|
||||
{
|
||||
stateDir: Schema.String,
|
||||
isDevelopment: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopClerk extends Context.Service<
|
||||
DesktopClerk,
|
||||
{
|
||||
@@ -82,28 +55,11 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
|
||||
});
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
|
||||
catch: (cause) =>
|
||||
new DesktopClerkBridgeInitializationError({
|
||||
stateDir: environment.stateDir,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
(bridge) =>
|
||||
Effect.try({
|
||||
try: () => bridge.cleanup(),
|
||||
catch: (cause) =>
|
||||
new DesktopClerkBridgeCleanupError({
|
||||
stateDir: environment.stateDir,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
|
||||
(bridge) => Effect.sync(() => bridge.cleanup()),
|
||||
);
|
||||
|
||||
return DesktopClerk.of({
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
|
||||
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
|
||||
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
|
||||
|
||||
describe("desktop detached action errors", () => {
|
||||
it("preserves the complete relaunch failure cause and reason", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("shutdown failed")),
|
||||
Cause.die(new Error("relaunch defect")),
|
||||
);
|
||||
const error = new DesktopLifecycleRelaunchError({
|
||||
reason: "apply update",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.reason, "apply update");
|
||||
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
|
||||
});
|
||||
|
||||
it("preserves the complete menu action failure cause and action", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("window unavailable")),
|
||||
Cause.die(new Error("dispatch defect")),
|
||||
);
|
||||
const error = new DesktopApplicationMenuActionError({
|
||||
action: "open-settings",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.action, "open-settings");
|
||||
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
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 type * as Electron from "electron";
|
||||
@@ -15,18 +15,6 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
|
||||
"DesktopLifecycleRelaunchError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop relaunch failed for reason "${this.reason}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopLifecycleRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
@@ -154,10 +142,11 @@ export const make = DesktopLifecycle.of({
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
const error = new DesktopLifecycleRelaunchError({ reason, cause });
|
||||
return logLifecycleError(error.message, { error });
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
@@ -3,8 +3,6 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
@@ -23,10 +21,6 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
|
||||
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
|
||||
);
|
||||
|
||||
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
|
||||
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
|
||||
);
|
||||
|
||||
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
backendConfig: Effect.succeed({
|
||||
@@ -172,62 +166,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("logs structured context when persisted observability settings cannot be read", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = `${baseDir}/userdata/settings.json`;
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: settingsPath,
|
||||
});
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
const failingFileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(cause),
|
||||
}),
|
||||
);
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolve;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isUndefined(config.bootstrap.otlpTracesUrl);
|
||||
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
|
||||
|
||||
const error = messages
|
||||
.flatMap((message) => (Array.isArray(message) ? message : [message]))
|
||||
.find(isDesktopBackendObservabilitySettingsReadError);
|
||||
assert.isDefined(error);
|
||||
assert.equal(error.settingsPath, settingsPath);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read persisted backend observability settings at ${settingsPath}.`,
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("captures backend output in development so child process logs can be persisted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -8,24 +8,12 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
{
|
||||
settingsPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
{
|
||||
@@ -62,34 +50,25 @@ const DESKTOP_BACKEND_ENV_NAMES = [
|
||||
const backendChildEnvPatch = (): Record<string, string | undefined> =>
|
||||
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
|
||||
|
||||
const logBackendObservabilitySettingsReadFailure = (
|
||||
settingsPath: string,
|
||||
cause: PlatformError.PlatformError,
|
||||
) => {
|
||||
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
|
||||
return Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
component: "desktop-backend-configuration",
|
||||
error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
|
||||
"desktop-backend-configuration",
|
||||
);
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
|
||||
Effect.as(Option.none()),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const exists = yield* fileSystem
|
||||
.exists(environment.serverSettingsPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return emptyBackendObservabilitySettings;
|
||||
}
|
||||
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
if (Option.isNone(raw)) {
|
||||
yield* logBackendConfigurationWarning(
|
||||
"failed to read persisted backend observability settings",
|
||||
);
|
||||
return emptyBackendObservabilitySettings;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { networkInterfacesMock } = vi.hoisted(() => ({
|
||||
networkInterfacesMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:os", () => ({
|
||||
networkInterfaces: networkInterfacesMock,
|
||||
}));
|
||||
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
|
||||
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
describe("DesktopNetworkInterfaces", () => {
|
||||
beforeEach(() => {
|
||||
networkInterfacesMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("reads network interfaces through the service", () => {
|
||||
const interfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.10",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
networkInterfacesMock.mockReturnValueOnce(interfaces);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
assert.strictEqual(yield* service.read, interfaces);
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
});
|
||||
|
||||
it.effect("preserves network interface read failures as structured defects", () => {
|
||||
const cause = new Error("network interface probe failed");
|
||||
networkInterfacesMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const exit = yield* Effect.exit(service.read);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,8 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
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 Schema from "effect/Schema";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
@@ -20,18 +18,6 @@ export type NetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
export class DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
|
||||
"DesktopNetworkInterfacesReadError",
|
||||
{
|
||||
platform: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read desktop network interfaces on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopNetworkInterfaces extends Context.Service<
|
||||
DesktopNetworkInterfaces,
|
||||
{
|
||||
@@ -39,14 +25,9 @@ export class DesktopNetworkInterfaces extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return DesktopNetworkInterfaces.of({
|
||||
read: Effect.try({
|
||||
try: () => NodeOS.networkInterfaces(),
|
||||
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
export const make = (): DesktopNetworkInterfaces["Service"] =>
|
||||
DesktopNetworkInterfaces.of({
|
||||
read: Effect.sync(() => NodeOS.networkInterfaces()),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
|
||||
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
|
||||
@@ -91,7 +91,6 @@ function makeLayer(input: {
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
@@ -100,7 +99,7 @@ function makeLayer(input: {
|
||||
});
|
||||
|
||||
return DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(NodeFileSystem.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
|
||||
@@ -123,7 +122,6 @@ const withHarness = <A, E, R>(
|
||||
>,
|
||||
env: Record<string, string | undefined> = {},
|
||||
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -137,7 +135,6 @@ const withHarness = <A, E, R>(
|
||||
networkInterfaces,
|
||||
env,
|
||||
...(spawnerLayer ? { spawnerLayer } : {}),
|
||||
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -240,67 +237,6 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves persistence request context and the settings failure chain", () => {
|
||||
const diskFailure = new Error("disk exploded");
|
||||
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: "/tmp/desktop-settings.json",
|
||||
cause: diskFailure,
|
||||
});
|
||||
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setServerExposureMode: () => Effect.fail(settingsFailure),
|
||||
setTailscaleServe: () => Effect.fail(settingsFailure),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
|
||||
|
||||
return withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
|
||||
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
modeError,
|
||||
DesktopServerExposure.DesktopServerExposureModePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
|
||||
assert.equal(modeError.mode, "network-accessible");
|
||||
assert.strictEqual(modeError.cause, settingsFailure);
|
||||
assert.strictEqual(modeError.cause.cause, diskFailure);
|
||||
assert.equal(
|
||||
modeError.message,
|
||||
"Failed to persist desktop server exposure mode network-accessible.",
|
||||
);
|
||||
assert.notInclude(modeError.message, diskFailure.message);
|
||||
|
||||
const tailscaleError = yield* serverExposure
|
||||
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
tailscaleError,
|
||||
DesktopServerExposure.DesktopTailscaleServePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
|
||||
assert.equal(tailscaleError.enabled, true);
|
||||
assert.equal(tailscaleError.port, 8443);
|
||||
assert.strictEqual(tailscaleError.cause, settingsFailure);
|
||||
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
|
||||
assert.equal(
|
||||
tailscaleError.message,
|
||||
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
|
||||
);
|
||||
assert.notInclude(tailscaleError.message, diskFailure.message);
|
||||
}),
|
||||
{},
|
||||
undefined,
|
||||
settingsLayer,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
|
||||
withHarness(
|
||||
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
|
||||
|
||||
@@ -2,12 +2,11 @@ import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/shared/advertisedEndpoint";
|
||||
import {
|
||||
DesktopServerExposureModeSchema,
|
||||
type AdvertisedEndpoint,
|
||||
type AdvertisedEndpointProvider,
|
||||
type DesktopServerExposureMode,
|
||||
type DesktopServerExposureState,
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
} from "@t3tools/contracts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -214,45 +213,23 @@ export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErr
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
|
||||
"DesktopServerExposureModePersistenceError",
|
||||
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
|
||||
"DesktopServerExposurePersistenceError",
|
||||
{
|
||||
mode: DesktopServerExposureModeSchema,
|
||||
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop server exposure mode ${this.mode}.`;
|
||||
return `Failed to persist desktop ${this.operation} settings.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()(
|
||||
"DesktopTailscaleServePersistenceError",
|
||||
{
|
||||
enabled: Schema.Boolean,
|
||||
port: Schema.NullOr(Schema.Number),
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
|
||||
}
|
||||
}
|
||||
export type DesktopServerExposureSetModeError =
|
||||
| DesktopServerExposureNoNetworkAddressError
|
||||
| DesktopServerExposurePersistenceError;
|
||||
|
||||
export const DesktopServerExposureSetModeError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
DesktopServerExposureModePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
|
||||
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
|
||||
|
||||
export const DesktopServerExposureError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
DesktopServerExposureModePersistenceError,
|
||||
DesktopTailscaleServePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
|
||||
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
|
||||
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
|
||||
|
||||
export interface DesktopServerExposureBackendConfig {
|
||||
readonly port: number;
|
||||
@@ -281,7 +258,7 @@ export class DesktopServerExposure extends Context.Service<
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
@@ -472,8 +449,8 @@ export const make = Effect.gen(function* () {
|
||||
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopServerExposureModePersistenceError({
|
||||
mode,
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "server-exposure-mode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -500,9 +477,8 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopTailscaleServePersistenceError({
|
||||
enabled: input.enabled,
|
||||
port: input.port ?? null,
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "tailscale-serve",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -100,44 +100,6 @@ describe("ElectronApp", () => {
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports which app metadata property failed", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("version unavailable");
|
||||
getVersionMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const error = yield* electronApp.metadata.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
|
||||
assert.strictEqual(error.property, "app-version");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
'Failed to read Electron app metadata property "app-version".',
|
||||
);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves Electron readiness failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("ready failed");
|
||||
whenReadyMock.mockRejectedValueOnce(cause);
|
||||
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const error = yield* electronApp.whenReady.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
|
||||
assert.strictEqual(error.isPackaged, true);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Failed to wait for the Electron app to become ready (packaged: true).",
|
||||
);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes app event listeners", () =>
|
||||
Effect.gen(function* () {
|
||||
const listener = vi.fn();
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
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 * as Electron from "electron";
|
||||
@@ -14,36 +13,12 @@ export interface ElectronAppMetadata {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
export class ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()(
|
||||
"ElectronAppMetadataReadError",
|
||||
{
|
||||
property: Schema.Literals(["app-version", "app-path"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read Electron app metadata property "${this.property}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()(
|
||||
"ElectronAppWhenReadyError",
|
||||
{
|
||||
isPackaged: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<
|
||||
ElectronApp,
|
||||
{
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
|
||||
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>;
|
||||
@@ -88,40 +63,15 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
export const make = ElectronApp.of({
|
||||
metadata: Effect.gen(function* () {
|
||||
const appVersion = yield* Effect.try({
|
||||
try: () => Electron.app.getVersion(),
|
||||
catch: (cause) =>
|
||||
new ElectronAppMetadataReadError({
|
||||
property: "app-version",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const appPath = yield* Effect.try({
|
||||
try: () => Electron.app.getAppPath(),
|
||||
catch: (cause) =>
|
||||
new ElectronAppMetadataReadError({
|
||||
property: "app-path",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
appVersion,
|
||||
appPath,
|
||||
isPackaged: Electron.app.isPackaged,
|
||||
resourcesPath: process.resourcesPath,
|
||||
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
|
||||
};
|
||||
}),
|
||||
metadata: Effect.sync(() => ({
|
||||
appVersion: Electron.app.getVersion(),
|
||||
appPath: Electron.app.getAppPath(),
|
||||
isPackaged: Electron.app.isPackaged,
|
||||
resourcesPath: process.resourcesPath,
|
||||
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
|
||||
})),
|
||||
name: Effect.sync(() => Electron.app.name),
|
||||
whenReady: Effect.gen(function* () {
|
||||
const isPackaged = Electron.app.isPackaged;
|
||||
yield* Effect.tryPromise({
|
||||
try: () => Electron.app.whenReady(),
|
||||
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
|
||||
});
|
||||
}),
|
||||
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
|
||||
quit: Effect.sync(() => {
|
||||
Electron.app.quit();
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import type { BrowserWindow } from "electron";
|
||||
@@ -91,116 +90,4 @@ describe("ElectronDialog", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
const owner = { id: 7 } as BrowserWindow;
|
||||
showOpenDialogMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.pickFolder({
|
||||
owner: Option.some(owner),
|
||||
defaultPath: Option.some("/workspace"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
|
||||
assert.isTrue(ElectronDialog.isElectronDialogError(error));
|
||||
assert.strictEqual(error.ownerWindowId, 7);
|
||||
assert.strictEqual(error.defaultPath, "/workspace");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 7");
|
||||
assert.include(error.message, "/workspace");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves confirmation request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("confirmation failed");
|
||||
const owner = { id: 9 } as BrowserWindow;
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.confirm({
|
||||
owner: Option.some(owner),
|
||||
message: " Confirm removal? ",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
|
||||
assert.strictEqual(error.ownerWindowId, 9);
|
||||
assert.strictEqual(error.promptLength, "Confirm removal?".length);
|
||||
assert.notProperty(error, "promptMessage");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 9");
|
||||
assert.notInclude(error.message, "Confirm removal?");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message box request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("message box failed");
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.showMessageBox({
|
||||
type: "warning",
|
||||
title: "Unsaved changes",
|
||||
message: "Discard changes?",
|
||||
detail: "This cannot be undone.",
|
||||
buttons: ["Cancel", "Discard"],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
|
||||
assert.strictEqual(error.type, "warning");
|
||||
assert.strictEqual(error.titleLength, "Unsaved changes".length);
|
||||
assert.strictEqual(error.messageLength, "Discard changes?".length);
|
||||
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
|
||||
assert.strictEqual(error.buttonCount, 2);
|
||||
assert.notProperty(error, "title");
|
||||
assert.notProperty(error, "dialogMessage");
|
||||
assert.notProperty(error, "dialogDetail");
|
||||
assert.notProperty(error, "buttons");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "warning");
|
||||
assert.notInclude(error.message, "Unsaved changes");
|
||||
assert.notInclude(error.message, "Discard changes?");
|
||||
assert.notInclude(error.message, "This cannot be undone.");
|
||||
assert.notInclude(error.message, "Cancel");
|
||||
assert.notInclude(error.message, "Discard");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves error box request context and cause in the defect", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("error box failed");
|
||||
showErrorBoxMock.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
|
||||
|
||||
assert.isTrue(exit._tag === "Failure");
|
||||
if (exit._tag === "Success") return;
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
|
||||
assert.strictEqual(error.titleLength, "Startup failed".length);
|
||||
assert.strictEqual(error.contentLength, "Could not start.".length);
|
||||
assert.notProperty(error, "title");
|
||||
assert.notProperty(error, "content");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, "Startup failed");
|
||||
assert.notInclude(error.message, "Could not start.");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
});
|
||||
@@ -2,80 +2,11 @@ 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 Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
|
||||
"ElectronDialogShowMessageBoxError",
|
||||
{
|
||||
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
|
||||
titleLength: Schema.NullOr(Schema.Number),
|
||||
messageLength: Schema.Number,
|
||||
detailLength: Schema.NullOr(Schema.Number),
|
||||
buttonCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const type = this.type === null ? "untyped" : this.type;
|
||||
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
|
||||
"ElectronDialogShowErrorBoxError",
|
||||
{
|
||||
titleLength: Schema.Number,
|
||||
contentLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
export type ElectronDialogError = typeof ElectronDialogError.Type;
|
||||
export const isElectronDialogError = Schema.is(ElectronDialogError);
|
||||
|
||||
export interface ElectronDialogPickFolderInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
@@ -91,24 +22,17 @@ export class ElectronDialog extends Context.Service<
|
||||
{
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronDialog") {}
|
||||
|
||||
export const make = ElectronDialog.of({
|
||||
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
|
||||
onNone: () => ({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
@@ -118,18 +42,10 @@ export const make = ElectronDialog.of({
|
||||
defaultPath,
|
||||
}),
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogPickFolderError({
|
||||
ownerWindowId,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
const result = yield* Option.match(input.owner, {
|
||||
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
|
||||
onSome: (owner) =>
|
||||
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
|
||||
});
|
||||
|
||||
if (result.canceled) {
|
||||
@@ -151,48 +67,17 @@ export const make = ElectronDialog.of({
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
cause,
|
||||
}),
|
||||
const result = yield* Option.match(input.owner, {
|
||||
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
|
||||
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}),
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.dialog.showMessageBox(options),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogShowMessageBoxError({
|
||||
type: options.type ?? null,
|
||||
titleLength: options.title?.length ?? null,
|
||||
messageLength: options.message.length,
|
||||
detailLength: options.detail?.length ?? null,
|
||||
buttonCount: options.buttons?.length ?? 0,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
|
||||
showErrorBox: (title, content) =>
|
||||
Effect.try({
|
||||
try: () => Electron.dialog.showErrorBox(title, content),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogShowErrorBoxError({
|
||||
titleLength: title.length,
|
||||
contentLength: content.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
Effect.sync(() => {
|
||||
Electron.dialog.showErrorBox(title, content);
|
||||
}),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronDialog, make);
|
||||
@@ -1,8 +1,5 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
@@ -27,10 +24,6 @@ vi.mock("electron", () => ({
|
||||
|
||||
import * as ElectronMenu from "./ElectronMenu.ts";
|
||||
|
||||
const TestLayer = ElectronMenu.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
describe("ElectronMenu", () => {
|
||||
beforeEach(() => {
|
||||
buildFromTemplateMock.mockReset();
|
||||
@@ -49,7 +42,7 @@ describe("ElectronMenu", () => {
|
||||
|
||||
assert.isTrue(Option.isNone(selectedItemId));
|
||||
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolves with the clicked leaf item id", () =>
|
||||
@@ -76,7 +69,7 @@ describe("ElectronMenu", () => {
|
||||
});
|
||||
|
||||
assert.equal(Option.getOrNull(selectedItemId), "copy");
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolves with none when the menu closes without a click", () =>
|
||||
@@ -100,7 +93,7 @@ describe("ElectronMenu", () => {
|
||||
enabled: true,
|
||||
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
|
||||
});
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
);
|
||||
|
||||
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
|
||||
@@ -121,89 +114,6 @@ describe("ElectronMenu", () => {
|
||||
|
||||
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
|
||||
assert.equal(popupMock.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves application-menu failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("application menu build failed");
|
||||
buildFromTemplateMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const exit = yield* Effect.exit(
|
||||
electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
|
||||
assert.equal(error.operation, "set-application-menu");
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.isNull(error.windowId);
|
||||
assert.equal(error.itemCount, 2);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves popup-template failures with window context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("popup failed");
|
||||
buildFromTemplateMock.mockReturnValueOnce({
|
||||
popup: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const exit = yield* Effect.exit(
|
||||
electronMenu.popupTemplate({
|
||||
window: { id: 41 } as Electron.BrowserWindow,
|
||||
template: [{ label: "Copy" }],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
|
||||
assert.equal(error.operation, "popup-template");
|
||||
assert.equal(error.windowId, 41);
|
||||
assert.equal(error.itemCount, 1);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves context-menu failures with normalized item context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("context menu build failed");
|
||||
buildFromTemplateMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const exit = yield* Effect.exit(
|
||||
electronMenu.showContextMenu({
|
||||
window: { id: 42 } as Electron.BrowserWindow,
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.none(),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
|
||||
assert.equal(error.operation, "show-context-menu");
|
||||
assert.equal(error.windowId, 42);
|
||||
assert.equal(error.itemCount, 1);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
);
|
||||
});
|
||||
@@ -4,7 +4,6 @@ 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 Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
@@ -24,28 +23,6 @@ export interface ElectronMenuTemplateInput {
|
||||
readonly template: readonly Electron.MenuItemConstructorOptions[];
|
||||
}
|
||||
|
||||
const ElectronMenuOperation = Schema.Literals([
|
||||
"set-application-menu",
|
||||
"popup-template",
|
||||
"show-context-menu",
|
||||
]);
|
||||
|
||||
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
|
||||
"ElectronMenuOperationError",
|
||||
{
|
||||
operation: ElectronMenuOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
itemCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<
|
||||
ElectronMenu,
|
||||
{
|
||||
@@ -165,36 +142,16 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronMenuOperationError({
|
||||
operation: "set-application-menu",
|
||||
platform,
|
||||
windowId: null,
|
||||
itemCount: template.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
input.template.length === 0
|
||||
? Effect.void
|
||||
: Effect.try({
|
||||
try: () =>
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({
|
||||
window: input.window,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronMenuOperationError({
|
||||
operation: "popup-template",
|
||||
platform,
|
||||
windowId: input.window.id,
|
||||
itemCount: input.template.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
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);
|
||||
@@ -212,39 +169,21 @@ export const make = Effect.gen(function* () {
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
try {
|
||||
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);
|
||||
} catch (cause) {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(
|
||||
Effect.die(
|
||||
new ElectronMenuOperationError({
|
||||
operation: "show-context-menu",
|
||||
platform,
|
||||
windowId: input.window.id,
|
||||
itemCount: normalizedItems.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
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);
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
@@ -99,60 +98,6 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
handleMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const error = yield* Effect.scoped(
|
||||
protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
|
||||
assert.equal(error.scheme, "t3code-dev");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol unregistration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol unregistration failed");
|
||||
unhandleMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const exit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
|
||||
assert.equal(error.scheme, "t3code");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
|
||||
}
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
|
||||
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
|
||||
scheme: "t3code",
|
||||
|
||||
@@ -31,19 +31,7 @@ export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<E
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register Electron protocol scheme "${this.scheme}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
|
||||
"ElectronProtocolUnregistrationError",
|
||||
{
|
||||
scheme: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
|
||||
return `Failed to register ${this.scheme}: protocol.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,14 +133,9 @@ export const make = Effect.gen(function* () {
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => Electron.protocol.unhandle(input.scheme),
|
||||
catch: (cause) =>
|
||||
new ElectronProtocolUnregistrationError({
|
||||
scheme: input.scheme,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unhandle(input.scheme);
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false))),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -8,7 +8,6 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
|
||||
themeState: {
|
||||
shouldUseDarkColors: true,
|
||||
themeSource: "system",
|
||||
setSourceError: null as unknown,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -18,9 +17,6 @@ vi.mock("electron", () => ({
|
||||
return themeState.shouldUseDarkColors;
|
||||
},
|
||||
set themeSource(value: string) {
|
||||
if (themeState.setSourceError !== null) {
|
||||
throw themeState.setSourceError;
|
||||
}
|
||||
themeState.themeSource = value;
|
||||
},
|
||||
on: onMock,
|
||||
@@ -36,7 +32,6 @@ describe("ElectronTheme", () => {
|
||||
removeListenerMock.mockClear();
|
||||
themeState.shouldUseDarkColors = true;
|
||||
themeState.themeSource = "system";
|
||||
themeState.setSourceError = null;
|
||||
});
|
||||
|
||||
it.effect("scopes native theme update listeners", () =>
|
||||
@@ -54,21 +49,4 @@ describe("ElectronTheme", () => {
|
||||
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
|
||||
}).pipe(Effect.provide(ElectronTheme.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves the requested source and cause when setting the theme fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("theme source failed");
|
||||
themeState.setSourceError = cause;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
|
||||
const error = yield* Effect.flip(electronTheme.setSource("dark"));
|
||||
|
||||
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
|
||||
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
|
||||
assert.strictEqual(error.source, "dark");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "dark");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronTheme.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,31 +1,16 @@
|
||||
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
|
||||
import type { DesktopTheme } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
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 * as Electron from "electron";
|
||||
|
||||
export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()(
|
||||
"ElectronThemeSetSourceError",
|
||||
{
|
||||
source: DesktopThemeSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to set the Electron theme source to ${this.source}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
|
||||
|
||||
export class ElectronTheme extends Context.Service<
|
||||
ElectronTheme,
|
||||
{
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronTheme") {}
|
||||
@@ -33,11 +18,9 @@ export class ElectronTheme extends Context.Service<
|
||||
export const make = ElectronTheme.of({
|
||||
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
|
||||
setSource: (theme) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
Electron.nativeTheme.themeSource = theme;
|
||||
},
|
||||
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
|
||||
Effect.suspend(() => {
|
||||
Electron.nativeTheme.themeSource = theme;
|
||||
return Effect.void;
|
||||
}),
|
||||
onUpdated: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
@@ -64,65 +65,16 @@ describe("ElectronUpdater", () => {
|
||||
const cause = new Error("network unavailable");
|
||||
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "beta";
|
||||
|
||||
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
|
||||
const exit = yield* Effect.exit(updater.checkForUpdates);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "beta");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves the execution-time channel on download failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("download unavailable");
|
||||
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "nightly";
|
||||
|
||||
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Electron updater failed to download the update on channel nightly.",
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("quit and install failed");
|
||||
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "alpha";
|
||||
|
||||
const error = yield* updater
|
||||
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "alpha");
|
||||
assert.equal(error.isSilent, true);
|
||||
assert.equal(error.isForceRunAfter, false);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
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)),
|
||||
);
|
||||
});
|
||||
@@ -10,41 +10,40 @@ type AutoUpdater = typeof autoUpdater;
|
||||
|
||||
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
|
||||
|
||||
const electronUpdaterErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
|
||||
"ElectronUpdaterCheckForUpdatesError",
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
...electronUpdaterErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
|
||||
return "Electron updater failed to check for updates.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
|
||||
"ElectronUpdaterDownloadUpdateError",
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
...electronUpdaterErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
|
||||
return "Electron updater failed to download the update.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
|
||||
"ElectronUpdaterQuitAndInstallError",
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
isSilent: Schema.Boolean,
|
||||
isForceRunAfter: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
...electronUpdaterErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
|
||||
return "Electron updater failed to quit and install the update.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,33 +116,18 @@ export const make = ElectronUpdater.of({
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
checkForUpdates: Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.tryPromise({
|
||||
try: () => autoUpdater.checkForUpdates(),
|
||||
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
downloadUpdate: Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.tryPromise({
|
||||
try: () => autoUpdater.downloadUpdate(),
|
||||
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
checkForUpdates: Effect.tryPromise({
|
||||
try: () => autoUpdater.checkForUpdates(),
|
||||
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
|
||||
}).pipe(Effect.asVoid),
|
||||
downloadUpdate: Effect.tryPromise({
|
||||
try: () => autoUpdater.downloadUpdate(),
|
||||
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
|
||||
}).pipe(Effect.asVoid),
|
||||
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
|
||||
Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.try({
|
||||
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
|
||||
catch: (cause) =>
|
||||
new ElectronUpdaterQuitAndInstallError({
|
||||
channel,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
Effect.try({
|
||||
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
|
||||
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
|
||||
}),
|
||||
on: (eventName, listener) => {
|
||||
const eventTarget = autoUpdater as unknown as {
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
|
||||
const invokeMethod: DesktopIpc.DesktopIpcMethod<never, never> = {
|
||||
channel: "desktop.test.invoke",
|
||||
handler: () => Effect.void,
|
||||
};
|
||||
|
||||
const syncMethod: DesktopIpc.DesktopSyncIpcMethod<never, never> = {
|
||||
channel: "desktop.test.sync",
|
||||
handler: () => Effect.void,
|
||||
};
|
||||
|
||||
function makeIpcMain(
|
||||
overrides: Partial<DesktopIpc.DesktopIpcMain> = {},
|
||||
): DesktopIpc.DesktopIpcMain {
|
||||
return {
|
||||
removeHandler: vi.fn(),
|
||||
handle: vi.fn(),
|
||||
removeAllListeners: vi.fn(),
|
||||
on: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("DesktopIpc", () => {
|
||||
it.effect("preserves invoke registration context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("invoke registration failed");
|
||||
const ipcMain = makeIpcMain({
|
||||
handle: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
const ipc = DesktopIpc.make(ipcMain);
|
||||
|
||||
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
|
||||
|
||||
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
|
||||
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
|
||||
assert.strictEqual(error.handlerKind, "invoke");
|
||||
assert.strictEqual(error.channel, invokeMethod.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "invoke");
|
||||
assert.include(error.message, invokeMethod.channel);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("sync unregistration failed");
|
||||
let removeCount = 0;
|
||||
const ipcMain = makeIpcMain({
|
||||
removeAllListeners: () => {
|
||||
removeCount += 1;
|
||||
if (removeCount === 2) throw cause;
|
||||
},
|
||||
});
|
||||
const ipc = DesktopIpc.make(ipcMain);
|
||||
|
||||
const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod)));
|
||||
|
||||
assert.isTrue(exit._tag === "Failure");
|
||||
if (exit._tag === "Success") return;
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
|
||||
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
|
||||
assert.strictEqual(error.handlerKind, "sync");
|
||||
assert.strictEqual(error.channel, syncMethod.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -24,39 +24,6 @@ export interface DesktopIpcMain {
|
||||
on(channel: string, listener: DesktopIpcSyncListener): void;
|
||||
}
|
||||
|
||||
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
|
||||
"DesktopIpcRegistrationError",
|
||||
{
|
||||
handlerKind: Schema.Literals(["invoke", "sync"]),
|
||||
channel: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
|
||||
"DesktopIpcUnregistrationError",
|
||||
{
|
||||
handlerKind: Schema.Literals(["invoke", "sync"]),
|
||||
channel: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopIpcError = Schema.Union([
|
||||
DesktopIpcRegistrationError,
|
||||
DesktopIpcUnregistrationError,
|
||||
]);
|
||||
export type DesktopIpcError = typeof DesktopIpcError.Type;
|
||||
export const isDesktopIpcError = Schema.is(DesktopIpcError);
|
||||
|
||||
export interface DesktopIpcMethod<E, R> {
|
||||
readonly channel: string;
|
||||
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
|
||||
@@ -72,10 +39,10 @@ export class DesktopIpc extends Context.Service<
|
||||
{
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/ipc/DesktopIpc") {}
|
||||
|
||||
@@ -90,27 +57,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
ipcMain.removeHandler(channel);
|
||||
ipcMain.handle(channel, (_event, raw) =>
|
||||
runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler(raw);
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
|
||||
),
|
||||
);
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
|
||||
Effect.sync(() => {
|
||||
ipcMain.removeHandler(channel);
|
||||
ipcMain.handle(channel, (_event, raw) =>
|
||||
runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler(raw);
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
|
||||
),
|
||||
);
|
||||
}),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => ipcMain.removeHandler(channel),
|
||||
catch: (cause) =>
|
||||
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
() => Effect.sync(() => ipcMain.removeHandler(channel)),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -123,30 +81,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
const runSync = Effect.runSyncWith(context);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
ipcMain.on(channel, (event) => {
|
||||
event.returnValue = runSync(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler();
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ channel }),
|
||||
Effect.withSpan("desktop.ipc.invokeSync"),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
|
||||
Effect.sync(() => {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
ipcMain.on(channel, (event) => {
|
||||
event.returnValue = runSync(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler();
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
|
||||
);
|
||||
});
|
||||
}),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => ipcMain.removeAllListeners(channel),
|
||||
catch: (cause) =>
|
||||
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -7,10 +7,9 @@ import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { beforeEach, describe, expect, vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
@@ -18,7 +17,7 @@ import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
@@ -80,7 +79,6 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
const withManager = <A>(
|
||||
use: (
|
||||
@@ -239,20 +237,6 @@ describe("PreviewManager", () => {
|
||||
expect(artifact.path).toMatch(
|
||||
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
|
||||
);
|
||||
|
||||
const captureCause = new Error("capture failed");
|
||||
capturePage.mockRejectedValueOnce(captureCause);
|
||||
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewOperationError",
|
||||
operation: "captureScreenshot.capturePage",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause: captureCause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -318,12 +302,9 @@ describe("PreviewManager", () => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewArtifactPathOutsideDirectoryError",
|
||||
artifactPath: "/tmp/t3/dev/settings.json",
|
||||
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
|
||||
expect(error.cause).toMatchObject({
|
||||
message: "Preview artifact path is outside the configured artifact directory.",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -343,20 +324,8 @@ describe("PreviewManager", () => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewArtifactPathOutsideDirectoryError",
|
||||
artifactPath: "/tmp/t3/dev/settings.json",
|
||||
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
|
||||
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
|
||||
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
|
||||
expect(Exit.isFailure(invalidImageExit)).toBe(true);
|
||||
if (Exit.isSuccess(invalidImageExit)) return;
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
|
||||
_tag: "PreviewArtifactImageLoadError",
|
||||
artifactPath,
|
||||
expect(error.cause).toMatchObject({
|
||||
message: "Preview artifact path is outside the configured artifact directory.",
|
||||
});
|
||||
}),
|
||||
),
|
||||
@@ -497,174 +466,10 @@ describe("PreviewManager", () => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewAutomationControlInterruptedError",
|
||||
operation: "click",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
});
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
if (error instanceof Error) {
|
||||
expect(error.name).toBe("PreviewAutomationControlInterruptedError");
|
||||
}
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const text = "ReferenceError: fallbackDetail is not defined";
|
||||
const exceptionDetails = {
|
||||
text,
|
||||
exception: { description: "" },
|
||||
};
|
||||
const sendCommand = vi.fn(async (method: string) =>
|
||||
method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
|
||||
);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const exit = yield* Effect.exit(
|
||||
manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewAutomationEvaluationError",
|
||||
detailKind: "exception-text",
|
||||
detailLength: text.length,
|
||||
cause: exceptionDetails,
|
||||
expect(error.cause).toMatchObject({
|
||||
name: "PreviewAutomationControlInterruptedError",
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("PreviewOperationError", () => {
|
||||
it("keeps timeline detail separate from its structured message", () => {
|
||||
const cause = new Error("CDP command failed with an invalid node id");
|
||||
const error = new PreviewManager.PreviewOperationError({
|
||||
operation: "click.DOM.resolveNode",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Preview automation diagnostics", () => {
|
||||
it("keeps browser exception detail out of structural diagnostics", () => {
|
||||
const secret = "unrelated-browser-payload-secret";
|
||||
const detail = "ReferenceError: missingValue is not defined";
|
||||
const cause = {
|
||||
text: "Uncaught Error",
|
||||
exception: { description: detail },
|
||||
unsafePayload: secret,
|
||||
};
|
||||
const error = new PreviewManager.PreviewAutomationEvaluationError({
|
||||
tabId: "tab_1",
|
||||
detailKind: "exception-description",
|
||||
detailLength: detail.length,
|
||||
cause,
|
||||
});
|
||||
|
||||
const encoded = encodePreviewManagerError(error);
|
||||
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
|
||||
readonly cause?: unknown;
|
||||
};
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodedCause).toStrictEqual(cause);
|
||||
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
|
||||
expect("detail" in error).toBe(false);
|
||||
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
|
||||
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
|
||||
secret,
|
||||
);
|
||||
});
|
||||
|
||||
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
|
||||
const selector = "role=button[name='selector-secret']";
|
||||
const reason = "Unexpected token near reason-secret";
|
||||
const cause = { invalidSelector: true as const, message: reason };
|
||||
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
|
||||
operation: "click",
|
||||
tabId: "tab_1",
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
reasonLength: reason.length,
|
||||
cause,
|
||||
});
|
||||
|
||||
const encoded = encodePreviewManagerError(error);
|
||||
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
|
||||
readonly cause?: unknown;
|
||||
};
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodedCause).toStrictEqual(cause);
|
||||
expect(error).toMatchObject({
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
reasonLength: reason.length,
|
||||
});
|
||||
expect(error.detail).toEqual({
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
});
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
|
||||
expect("selector" in error).toBe(false);
|
||||
expect("reason" in error).toBe(false);
|
||||
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
|
||||
reason,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not retain a missing target locator", () => {
|
||||
const selector = "[data-token='target-secret']";
|
||||
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
|
||||
operation: "scroll",
|
||||
tabId: "tab_1",
|
||||
selectorKind: "selector",
|
||||
selectorLength: selector.length,
|
||||
});
|
||||
|
||||
expect(error.message).not.toContain(selector);
|
||||
expect(JSON.stringify(error)).not.toContain(selector);
|
||||
expect("locator" in error).toBe(false);
|
||||
});
|
||||
});
|
||||
+360
-765
File diff suppressed because it is too large.
Load diff
@@ -3,14 +3,10 @@ import * as Effect from "effect/Effect";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractPlaywrightInjectedRuntimeSource,
|
||||
playwrightInjectedRuntimeInstallExpression,
|
||||
playwrightInjectedRuntimeSource,
|
||||
} from "./PlaywrightInjectedRuntime.ts";
|
||||
|
||||
const bundleWithSourceLiteral = (literal: string): string =>
|
||||
`const source3 = ${literal};\n }\n});`;
|
||||
|
||||
describe("playwright injected runtime", () => {
|
||||
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -27,54 +23,4 @@ describe("playwright injected runtime", () => {
|
||||
expect(expression).toContain('testIdAttributeName":"data-testid');
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("reports a missing source marker without an artificial cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource("const source = 'missing';", "/tmp/coreBundle.js"),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceMarkerNotFoundError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
marker: "source3 = ",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps source validation metadata cause-free", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource(
|
||||
bundleWithSourceLiteral('"short"'),
|
||||
"/tmp/coreBundle.js",
|
||||
),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceValidationError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
actualType: "string",
|
||||
actualLength: 5,
|
||||
minimumLength: 100_000,
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves the source evaluation cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource(bundleWithSourceLiteral("("), "/tmp/coreBundle.js"),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceEvaluationError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
timeoutMs: 1_000,
|
||||
cause: expect.objectContaining({ name: "SyntaxError" }),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -4,180 +4,69 @@ 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 = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
|
||||
const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
|
||||
const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
|
||||
const PLAYWRIGHT_BROWSER_NAME = "chromium";
|
||||
|
||||
export class PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()(
|
||||
"PlaywrightPackageResolveError",
|
||||
{
|
||||
specifier: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to resolve Playwright package: ${this.specifier}`;
|
||||
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
|
||||
"PlaywrightInjectedRuntimeError",
|
||||
)<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Playwright injected runtime operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightCoreBundleReadError extends Schema.TaggedErrorClass<PlaywrightCoreBundleReadError>()(
|
||||
"PlaywrightCoreBundleReadError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read Playwright core bundle: ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceMarkerNotFoundError>()(
|
||||
"PlaywrightSourceMarkerNotFoundError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
marker: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceTerminatorNotFoundError>()(
|
||||
"PlaywrightSourceTerminatorNotFoundError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
terminator: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceEvaluationError extends Schema.TaggedErrorClass<PlaywrightSourceEvaluationError>()(
|
||||
"PlaywrightSourceEvaluationError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceValidationError extends Schema.TaggedErrorClass<PlaywrightSourceValidationError>()(
|
||||
"PlaywrightSourceValidationError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
actualType: Schema.String,
|
||||
actualLength: Schema.NullOr(Schema.Number),
|
||||
minimumLength: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const actual =
|
||||
this.actualLength === null
|
||||
? this.actualType
|
||||
: `${this.actualType} with ${this.actualLength} characters`;
|
||||
return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightOptionsEncodeError extends Schema.TaggedErrorClass<PlaywrightOptionsEncodeError>()(
|
||||
"PlaywrightOptionsEncodeError",
|
||||
{
|
||||
sdkLanguage: Schema.String,
|
||||
browserName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const PlaywrightInjectedRuntimeError = Schema.Union([
|
||||
PlaywrightPackageResolveError,
|
||||
PlaywrightCoreBundleReadError,
|
||||
PlaywrightSourceMarkerNotFoundError,
|
||||
PlaywrightSourceTerminatorNotFoundError,
|
||||
PlaywrightSourceEvaluationError,
|
||||
PlaywrightSourceValidationError,
|
||||
PlaywrightOptionsEncodeError,
|
||||
]);
|
||||
export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
|
||||
|
||||
export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
|
||||
"PlaywrightInjectedRuntime.extractSource",
|
||||
)(function* (coreBundle: string, bundlePath: string) {
|
||||
const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
|
||||
if (start < 0) {
|
||||
return yield* new PlaywrightSourceMarkerNotFoundError({
|
||||
bundlePath,
|
||||
marker: PLAYWRIGHT_SOURCE_MARKER,
|
||||
});
|
||||
}
|
||||
const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
|
||||
const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
|
||||
if (literalEnd < 0) {
|
||||
return yield* new PlaywrightSourceTerminatorNotFoundError({
|
||||
bundlePath,
|
||||
terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
|
||||
});
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () =>
|
||||
NodeVM.runInNewContext(literal, Object.create(null), {
|
||||
timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new PlaywrightSourceEvaluationError({
|
||||
bundlePath,
|
||||
timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
|
||||
return yield* new PlaywrightSourceValidationError({
|
||||
bundlePath,
|
||||
actualType: typeof source,
|
||||
actualLength: typeof source === "string" ? source.length : null,
|
||||
minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
|
||||
});
|
||||
}
|
||||
return source;
|
||||
});
|
||||
const fail = (operation: string, cause: unknown) =>
|
||||
new PlaywrightInjectedRuntimeError({ operation, cause });
|
||||
|
||||
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
|
||||
function* () {
|
||||
const packageJsonPath = yield* Effect.try({
|
||||
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
|
||||
catch: (cause) =>
|
||||
new PlaywrightPackageResolveError({
|
||||
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
|
||||
cause,
|
||||
}),
|
||||
try: () => require.resolve("playwright-core/package.json"),
|
||||
catch: (cause) => fail("resolvePackage", cause),
|
||||
});
|
||||
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
|
||||
const coreBundle = yield* Effect.tryPromise({
|
||||
try: () => NodeFSP.readFile(bundlePath, "utf8"),
|
||||
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
|
||||
try: () =>
|
||||
NodeFSP.readFile(
|
||||
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
|
||||
"utf8",
|
||||
),
|
||||
catch: (cause) => fail("readCoreBundle", cause),
|
||||
});
|
||||
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
|
||||
const marker = "source3 = ";
|
||||
const start = coreBundle.indexOf(marker);
|
||||
if (start < 0) {
|
||||
return yield* fail(
|
||||
"findSourceMarker",
|
||||
new Error("Playwright injected runtime marker was not found."),
|
||||
);
|
||||
}
|
||||
const literalStart = start + marker.length;
|
||||
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
|
||||
if (literalEnd < 0) {
|
||||
return yield* fail(
|
||||
"findSourceTerminator",
|
||||
new Error("Playwright injected runtime terminator was not found."),
|
||||
);
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
|
||||
catch: (cause) => fail("evaluateSourceLiteral", cause),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < 100_000) {
|
||||
return yield* fail(
|
||||
"validateSource",
|
||||
new Error("Playwright injected runtime extraction returned invalid source."),
|
||||
);
|
||||
}
|
||||
return source;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -187,23 +76,14 @@ export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
|
||||
const source = yield* playwrightInjectedRuntimeSource();
|
||||
const options = yield* encodeUnknownJson({
|
||||
isUnderTest: false,
|
||||
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
|
||||
sdkLanguage: "javascript",
|
||||
testIdAttributeName: "data-testid",
|
||||
stableRafCount: 1,
|
||||
browserName: PLAYWRIGHT_BROWSER_NAME,
|
||||
browserName: "chromium",
|
||||
shouldPrependErrorPrefix: false,
|
||||
isUtilityWorld: false,
|
||||
customEngines: [],
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PlaywrightOptionsEncodeError({
|
||||
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
|
||||
browserName: PLAYWRIGHT_BROWSER_NAME,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
|
||||
return `(() => {
|
||||
if (globalThis.__t3PlaywrightInjected) return true;
|
||||
const module = { exports: {} };
|
||||
|
||||
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -118,13 +117,11 @@ describe("DesktopClientSettings", () => {
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
|
||||
assert.equal(error.operation, "replace-settings-file");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.isString(error.cause.stack);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, error.cause.message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -25,9 +25,7 @@ const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
|
||||
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
|
||||
decodeLegacyClientSettingsDocumentJson(raw).pipe(
|
||||
Effect.map((document) => document.settings),
|
||||
Effect.catchTags({
|
||||
SchemaError: () => decodeClientSettingsJsonValue(raw),
|
||||
}),
|
||||
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
|
||||
);
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
@@ -38,6 +36,7 @@ const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-settings-file",
|
||||
]);
|
||||
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
|
||||
|
||||
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
|
||||
"DesktopClientSettingsWriteError",
|
||||
@@ -52,6 +51,13 @@ export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<Des
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopClientSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopClientSettingsWriteError =>
|
||||
new DesktopClientSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
{
|
||||
@@ -90,45 +96,19 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.settingsPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -144,13 +124,8 @@ export const make = Effect.gen(function* () {
|
||||
set: (settings) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.clientSettingsPath,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
const isDesktopShellEnvironmentCommandError = Schema.is(
|
||||
DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
|
||||
);
|
||||
|
||||
function envOutput(values: Readonly<Record<string, string>>): string {
|
||||
return Object.entries(values)
|
||||
.flatMap(([name, value]) => [
|
||||
@@ -67,7 +59,6 @@ function runShellEnvironment(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly handler: (command: ChildProcess.Command) => string;
|
||||
readonly failure?: PlatformError.PlatformError;
|
||||
}) {
|
||||
const environmentLayer = Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
@@ -77,11 +68,7 @@ function runShellEnvironment(input: {
|
||||
);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
input.failure === undefined
|
||||
? Effect.succeed(makeProcess(input.handler(command)))
|
||||
: Effect.fail(input.failure),
|
||||
),
|
||||
ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
|
||||
);
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
@@ -242,44 +229,4 @@ describe("DesktopShellEnvironment", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs command failures with safe probe context and the exact cause", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/bash",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: "/bin/bash",
|
||||
});
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
|
||||
return runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () => "",
|
||||
failure: cause,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
const errors = messages
|
||||
.flatMap((message) => (Array.isArray(message) ? message : [message]))
|
||||
.filter(isDesktopShellEnvironmentCommandError);
|
||||
assert.lengthOf(errors, 1);
|
||||
assert.equal(errors[0]?.probe, "login-shell");
|
||||
assert.equal(errors[0]?.executable, "bash");
|
||||
assert.equal(errors[0]?.argumentCount, 2);
|
||||
assert.notProperty(errors[0] ?? {}, "args");
|
||||
assert.equal(errors[0]?.cause, cause);
|
||||
assert.notInclude(errors[0]?.message ?? "", cause.message);
|
||||
}),
|
||||
),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,6 @@ 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 ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
@@ -21,44 +20,6 @@ interface WindowsProbeOptions {
|
||||
readonly loadProfile: boolean;
|
||||
}
|
||||
|
||||
const DesktopShellEnvironmentProbe = Schema.Literals([
|
||||
"login-shell",
|
||||
"launchctl-path",
|
||||
"powershell-profile",
|
||||
"powershell-no-profile",
|
||||
]);
|
||||
type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
|
||||
|
||||
const desktopShellEnvironmentCommandFields = {
|
||||
probe: DesktopShellEnvironmentProbe,
|
||||
executable: Schema.String,
|
||||
argumentCount: Schema.Number,
|
||||
};
|
||||
|
||||
export class DesktopShellEnvironmentCommandError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandError>()(
|
||||
"DesktopShellEnvironmentCommandError",
|
||||
{
|
||||
...desktopShellEnvironmentCommandFields,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandTimeoutError>()(
|
||||
"DesktopShellEnvironmentCommandTimeoutError",
|
||||
{
|
||||
...desktopShellEnvironmentCommandFields,
|
||||
timeoutMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopShellEnvironment extends Context.Service<
|
||||
DesktopShellEnvironment,
|
||||
{
|
||||
@@ -166,18 +127,6 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
|
||||
const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
|
||||
const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
|
||||
|
||||
const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
|
||||
|
||||
const logShellEnvironmentCommandError = (
|
||||
error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
|
||||
) =>
|
||||
Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
component: "desktop-shell-environment",
|
||||
error,
|
||||
}),
|
||||
);
|
||||
|
||||
const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
|
||||
names
|
||||
.map((name) => {
|
||||
@@ -226,14 +175,13 @@ const extractEnvironment = (output: string, names: ReadonlyArray<string>): Envir
|
||||
};
|
||||
|
||||
const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
|
||||
readonly probe: DesktopShellEnvironmentProbe;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeout: Duration.Duration;
|
||||
readonly shell?: boolean;
|
||||
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const output = yield* spawner
|
||||
return yield* spawner
|
||||
.string(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
shell: input.shell ?? false,
|
||||
@@ -245,33 +193,10 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopShellEnvironmentCommandError({
|
||||
probe: input.probe,
|
||||
executable: executableName(input.command),
|
||||
argumentCount: input.args.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.catchTags({
|
||||
DesktopShellEnvironmentCommandError: (error) =>
|
||||
logShellEnvironmentCommandError(error).pipe(Effect.as("")),
|
||||
}),
|
||||
Effect.timeoutOption(input.timeout),
|
||||
Effect.map(Option.getOrElse(() => "")),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (Option.isSome(output)) {
|
||||
return output.value;
|
||||
}
|
||||
|
||||
const error = new DesktopShellEnvironmentCommandTimeoutError({
|
||||
probe: input.probe,
|
||||
executable: executableName(input.command),
|
||||
argumentCount: input.args.length,
|
||||
timeoutMs: Duration.toMillis(input.timeout),
|
||||
});
|
||||
yield* logShellEnvironmentCommandError(error);
|
||||
return "";
|
||||
});
|
||||
|
||||
const readLoginShellEnvironment = (
|
||||
@@ -281,14 +206,12 @@ const readLoginShellEnvironment = (
|
||||
names.length === 0
|
||||
? Effect.succeed({})
|
||||
: runCommandOutput({
|
||||
probe: "login-shell",
|
||||
command: shell,
|
||||
args: ["-ilc", capturePosixEnvironmentCommand(names)],
|
||||
timeout: LOGIN_SHELL_TIMEOUT,
|
||||
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
|
||||
|
||||
const readLaunchctlPath = runCommandOutput({
|
||||
probe: "launchctl-path",
|
||||
command: "/bin/launchctl",
|
||||
args: ["getenv", "PATH"],
|
||||
timeout: LAUNCHCTL_TIMEOUT,
|
||||
@@ -311,7 +234,6 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
|
||||
|
||||
for (const command of WINDOWS_SHELL_CANDIDATES) {
|
||||
const output = yield* runCommandOutput({
|
||||
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
|
||||
command,
|
||||
args,
|
||||
timeout: LOGIN_SHELL_TIMEOUT,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
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 Schema from "effect/Schema";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
@@ -14,18 +14,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
|
||||
export class DesktopApplicationMenuActionError extends Schema.TaggedErrorClass<DesktopApplicationMenuActionError>()(
|
||||
"DesktopApplicationMenuActionError",
|
||||
{
|
||||
action: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop menu action "${this.action}" failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopApplicationMenu extends Context.Service<
|
||||
DesktopApplicationMenu,
|
||||
{
|
||||
@@ -112,10 +100,12 @@ export const make = Effect.gen(function* () {
|
||||
effect.pipe(
|
||||
Effect.annotateLogs({ action }),
|
||||
Effect.withSpan("desktop.menu.action"),
|
||||
Effect.catchCause((cause) => {
|
||||
const error = new DesktopApplicationMenuActionError({ action, cause });
|
||||
return logMenuError(error.message, { error });
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logMenuError("desktop menu action failed", {
|
||||
action,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
|
||||
@@ -8,18 +7,6 @@ import { savePreferencesPatch } from "../../lib/storage";
|
||||
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
|
||||
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
|
||||
|
||||
export class LiveActivityPreferenceSaveError extends Schema.TaggedErrorClass<LiveActivityPreferenceSaveError>()(
|
||||
"LiveActivityPreferenceSaveError",
|
||||
{
|
||||
enabled: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to save the Live Activity updates setting (enabled: ${this.enabled}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export function setLiveActivityUpdatesEnabled(input: {
|
||||
readonly enabled: boolean;
|
||||
readonly clerkToken: string | null;
|
||||
@@ -28,7 +15,7 @@ export function setLiveActivityUpdatesEnabled(input: {
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.tryPromise({
|
||||
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
|
||||
catch: (cause) => new LiveActivityPreferenceSaveError({ enabled: input.enabled, cause }),
|
||||
catch: (error) => error,
|
||||
});
|
||||
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Platform } from "react-native";
|
||||
|
||||
export type NotificationPermissionResult =
|
||||
@@ -8,31 +7,9 @@ export type NotificationPermissionResult =
|
||||
| { readonly type: "granted" }
|
||||
| { readonly type: "denied"; readonly canAskAgain: boolean };
|
||||
|
||||
export class NotificationPermissionReadError extends Schema.TaggedErrorClass<NotificationPermissionReadError>()(
|
||||
"NotificationPermissionReadError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to read notification permissions on iOS.";
|
||||
}
|
||||
}
|
||||
|
||||
export class NotificationPermissionRequestError extends Schema.TaggedErrorClass<NotificationPermissionRequestError>()(
|
||||
"NotificationPermissionRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to request notification permissions on iOS.";
|
||||
}
|
||||
}
|
||||
|
||||
export const requestAgentNotificationPermission: Effect.Effect<
|
||||
NotificationPermissionResult,
|
||||
NotificationPermissionReadError | NotificationPermissionRequestError
|
||||
unknown
|
||||
> = Effect.gen(function* () {
|
||||
if (Platform.OS !== "ios") {
|
||||
return { type: "unsupported" };
|
||||
@@ -40,7 +17,7 @@ export const requestAgentNotificationPermission: Effect.Effect<
|
||||
|
||||
const existing = yield* Effect.tryPromise({
|
||||
try: () => Notifications.getPermissionsAsync(),
|
||||
catch: (cause) => new NotificationPermissionReadError({ cause }),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (existing.granted) {
|
||||
return { type: "granted" };
|
||||
@@ -59,7 +36,7 @@ export const requestAgentNotificationPermission: Effect.Effect<
|
||||
allowSound: true,
|
||||
},
|
||||
}),
|
||||
catch: (cause) => new NotificationPermissionRequestError({ cause }),
|
||||
catch: (error) => error,
|
||||
});
|
||||
return requested.granted
|
||||
? { type: "granted" }
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
CloudPublicConfigMissingError,
|
||||
hasTracingPublicConfig,
|
||||
resolveCloudPublicConfig,
|
||||
resolveRelayClerkTokenOptions,
|
||||
} from "./publicConfig";
|
||||
import { hasTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -16,12 +11,6 @@ vi.mock("expo-constants", () => ({
|
||||
}));
|
||||
|
||||
describe("resolveCloudPublicConfig", () => {
|
||||
it("reports the missing Clerk JWT template as structured configuration", () => {
|
||||
expect(() => resolveRelayClerkTokenOptions()).toThrowError(
|
||||
new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns no cloud configuration for an unconfigured build", () => {
|
||||
expect(resolveCloudPublicConfig({})).toEqual({
|
||||
clerk: {
|
||||
|
||||
@@ -1,18 +1,6 @@
|
||||
import Constants from "expo-constants";
|
||||
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class CloudPublicConfigMissingError extends Schema.TaggedErrorClass<CloudPublicConfigMissingError>()(
|
||||
"CloudPublicConfigMissingError",
|
||||
{
|
||||
key: Schema.Literal("T3CODE_CLERK_JWT_TEMPLATE"),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.key} is not configured.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface CloudPublicConfig {
|
||||
readonly clerk: {
|
||||
@@ -99,7 +87,7 @@ export function hasTracingPublicConfig(
|
||||
export function resolveRelayClerkTokenOptions() {
|
||||
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
|
||||
if (!jwtTemplate) {
|
||||
throw new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" });
|
||||
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
|
||||
}
|
||||
return relayClerkTokenOptions(jwtTemplate);
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractPairingUrlFromQrPayload,
|
||||
PairingQrPayloadEmptyError,
|
||||
parsePairingUrl,
|
||||
} from "./pairing";
|
||||
import { extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
|
||||
|
||||
describe("extractPairingUrlFromQrPayload", () => {
|
||||
it("trims raw pairing urls from qr payloads", () => {
|
||||
@@ -22,8 +18,7 @@ describe("extractPairingUrlFromQrPayload", () => {
|
||||
});
|
||||
|
||||
it("rejects empty qr payloads", () => {
|
||||
expect(() => extractPairingUrlFromQrPayload(" ")).toThrowError(PairingQrPayloadEmptyError);
|
||||
expect(() => extractPairingUrlFromQrPayload(" ")).toThrowError(
|
||||
expect(() => extractPairingUrlFromQrPayload(" ")).toThrow(
|
||||
"Scanned QR code did not contain a pairing URL.",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
import { readHostedPairingRequest } from "@t3tools/shared/remote";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
|
||||
|
||||
export class PairingQrPayloadEmptyError extends Schema.TaggedErrorClass<PairingQrPayloadEmptyError>()(
|
||||
"PairingQrPayloadEmptyError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Scanned QR code did not contain a pairing URL.";
|
||||
}
|
||||
}
|
||||
|
||||
export function buildPairingUrl(host: string, code: string): string {
|
||||
const h = host.trim();
|
||||
const c = code.trim();
|
||||
@@ -58,7 +48,7 @@ export function parsePairingUrl(url: string): { host: string; code: string } {
|
||||
export function extractPairingUrlFromQrPayload(payload: string): string {
|
||||
const trimmed = payload.trim();
|
||||
if (!trimmed) {
|
||||
throw new PairingQrPayloadEmptyError({});
|
||||
throw new Error("Scanned QR code did not contain a pairing URL.");
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -58,23 +58,10 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
|
||||
it("returns null when the view manager cannot be required", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
const cause = new Error("boom");
|
||||
expoMocks.requireNativeView.mockImplementation(() => {
|
||||
throw cause;
|
||||
throw new Error("boom");
|
||||
});
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoMocks.requireNativeView).toHaveBeenCalledTimes(1);
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NativeViewResolutionError",
|
||||
nativeModuleName: "T3ReviewDiffSurface",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
expect(consoleError).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,6 @@ import type { ComponentType } from "react";
|
||||
import type { NativeSyntheticEvent, ViewProps } from "react-native";
|
||||
import { requireNativeView } from "expo";
|
||||
|
||||
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
|
||||
|
||||
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
|
||||
|
||||
interface ExpoGlobalWithViewConfig {
|
||||
@@ -130,7 +128,6 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
}
|
||||
|
||||
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
|
||||
let nativeReviewDiffViewResolutionFailed = false;
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
@@ -143,10 +140,6 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
return cachedNativeReviewDiffView;
|
||||
}
|
||||
|
||||
if (nativeReviewDiffViewResolutionFailed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -155,14 +148,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
|
||||
NATIVE_REVIEW_DIFF_MODULE_NAME,
|
||||
);
|
||||
} catch (cause) {
|
||||
nativeReviewDiffViewResolutionFailed = true;
|
||||
console.error(
|
||||
new NativeViewResolutionError({
|
||||
nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
type NodeStyleOverrides,
|
||||
type PartialMarkdownTheme,
|
||||
} from "react-native-nitro-markdown";
|
||||
import { ScrollView, Text as NativeText, View } from "react-native";
|
||||
import { Linking, ScrollView, Text as NativeText, View } from "react-native";
|
||||
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
@@ -39,7 +38,7 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
<NativeText
|
||||
onPress={() => {
|
||||
if (href) {
|
||||
void tryOpenExternalUrl(href, "markdown-link");
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
@@ -144,19 +143,12 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
|
||||
export function FileMarkdownPreview(props: { readonly markdown: string }) {
|
||||
const styles = useMarkdownPreviewStyles();
|
||||
const onLinkPress = useCallback((href: string) => {
|
||||
void tryOpenExternalUrl(href, "markdown-link");
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
|
||||
<View className="mx-auto w-full max-w-[760px]">
|
||||
{hasNativeSelectableMarkdownText() ? (
|
||||
<SelectableMarkdownText
|
||||
markdown={props.markdown}
|
||||
onLinkPress={onLinkPress}
|
||||
textStyle={styles.nativeTextStyle}
|
||||
/>
|
||||
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
|
||||
) : (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
|
||||
@@ -2,7 +2,14 @@ import Stack from "expo-router/stack";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Linking,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Text as RNText,
|
||||
View,
|
||||
} from "react-native";
|
||||
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
|
||||
import {
|
||||
EnvironmentId,
|
||||
@@ -16,7 +23,6 @@ import { CopyTextButton } from "../../components/CopyTextButton";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { buildThreadFilesNavigation } from "../../lib/routes";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -249,7 +255,7 @@ function FilePreviewHeader(props: {
|
||||
)}
|
||||
onPress={() => {
|
||||
if (typeof props.externalPreviewUri === "string") {
|
||||
void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
|
||||
void Linking.openURL(props.externalPreviewUri);
|
||||
}
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -43,23 +43,10 @@ describe("resolveNativeTerminalSurfaceView", () => {
|
||||
|
||||
it("returns null when the view manager cannot be required", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
const cause = new Error("boom");
|
||||
expoMocks.requireNativeView.mockImplementation(() => {
|
||||
throw cause;
|
||||
throw new Error("boom");
|
||||
});
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
|
||||
|
||||
expect(resolveNativeTerminalSurfaceView()).toBeNull();
|
||||
expect(resolveNativeTerminalSurfaceView()).toBeNull();
|
||||
expect(expoMocks.requireNativeView).toHaveBeenCalledTimes(1);
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NativeViewResolutionError",
|
||||
nativeModuleName: "T3TerminalSurface",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
expect(consoleError).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,6 @@ import type { ComponentType } from "react";
|
||||
import type { NativeSyntheticEvent, ViewProps } from "react-native";
|
||||
import { requireNativeView } from "expo";
|
||||
|
||||
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
|
||||
|
||||
const NATIVE_TERMINAL_MODULE_NAME = "T3TerminalSurface";
|
||||
|
||||
interface ExpoGlobalWithViewConfig {
|
||||
@@ -35,7 +33,6 @@ export interface NativeTerminalSurfaceProps extends ViewProps {
|
||||
}
|
||||
|
||||
let cachedNativeTerminalSurfaceView: ComponentType<NativeTerminalSurfaceProps> | undefined;
|
||||
let nativeTerminalSurfaceViewResolutionFailed = false;
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
@@ -48,10 +45,6 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
|
||||
return cachedNativeTerminalSurfaceView;
|
||||
}
|
||||
|
||||
if (nativeTerminalSurfaceViewResolutionFailed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (getExpoViewConfig(NATIVE_TERMINAL_MODULE_NAME) == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -60,14 +53,7 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
|
||||
cachedNativeTerminalSurfaceView = requireNativeView<NativeTerminalSurfaceProps>(
|
||||
NATIVE_TERMINAL_MODULE_NAME,
|
||||
);
|
||||
} catch (cause) {
|
||||
nativeTerminalSurfaceViewResolutionFailed = true;
|
||||
console.error(
|
||||
new NativeViewResolutionError({
|
||||
nativeModuleName: NATIVE_TERMINAL_MODULE_NAME,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { ActivityIndicator, Pressable, View } from "react-native";
|
||||
import { ActivityIndicator, Linking, Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { GitActionProgress } from "../../state/use-vcs-action-state";
|
||||
|
||||
@@ -31,7 +30,7 @@ export function GitActionProgressOverlay(props: {
|
||||
|
||||
const handlePress = useCallback(() => {
|
||||
if (progress.prUrl) {
|
||||
void tryOpenExternalUrl(progress.prUrl, "pull-request");
|
||||
void Linking.openURL(progress.prUrl);
|
||||
return;
|
||||
}
|
||||
if (progress.phase === "success" || progress.phase === "error") {
|
||||
|
||||
@@ -13,9 +13,8 @@ import {
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Alert } from "react-native";
|
||||
import { Alert, Linking } from "react-native";
|
||||
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import {
|
||||
basename,
|
||||
getTerminalStatusLabel,
|
||||
@@ -126,8 +125,13 @@ export function ThreadGitControls(props: {
|
||||
Alert.alert("No open PR", "This branch does not have an open pull request.");
|
||||
return;
|
||||
}
|
||||
if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
|
||||
Alert.alert("Unable to open PR", "The pull request could not be opened.");
|
||||
try {
|
||||
await Linking.openURL(prUrl);
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Unable to open PR",
|
||||
error instanceof Error ? error.message : "An error occurred.",
|
||||
);
|
||||
}
|
||||
}, [gitStatus]);
|
||||
|
||||
|
||||
@@ -8,12 +8,11 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { Alert, Pressable, ScrollView, View } from "react-native";
|
||||
import { Alert, Linking, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
|
||||
import { buildThreadReviewRoutePath } from "../../../lib/routes";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
import { useThreadSelection } from "../../../state/use-thread-selection";
|
||||
@@ -84,8 +83,13 @@ export function GitOverviewSheet() {
|
||||
Alert.alert("No open PR", "This branch does not have an open pull request.");
|
||||
return;
|
||||
}
|
||||
if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
|
||||
Alert.alert("Unable to open PR", "The pull request could not be opened.");
|
||||
try {
|
||||
await Linking.openURL(prUrl);
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Unable to open PR",
|
||||
error instanceof Error ? error.message : "An error occurred.",
|
||||
);
|
||||
}
|
||||
}, [gitStatus.data]);
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class ProjectThreadTaskRequiredError extends Schema.TaggedErrorClass<ProjectThreadTaskRequiredError>()(
|
||||
"ProjectThreadTaskRequiredError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
projectId: ProjectId,
|
||||
environmentMode: Schema.Literals(["local", "worktree"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Enter a task before starting the thread.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectThreadBaseBranchRequiredError extends Schema.TaggedErrorClass<ProjectThreadBaseBranchRequiredError>()(
|
||||
"ProjectThreadBaseBranchRequiredError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
projectId: ProjectId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Select a base branch before creating a worktree.";
|
||||
}
|
||||
}
|
||||
|
||||
export const ProjectThreadCreationValidationError = Schema.Union([
|
||||
ProjectThreadTaskRequiredError,
|
||||
ProjectThreadBaseBranchRequiredError,
|
||||
]);
|
||||
export type ProjectThreadCreationValidationError = typeof ProjectThreadCreationValidationError.Type;
|
||||
|
||||
export function validateProjectThreadCreation(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly environmentMode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly initialMessageText: string;
|
||||
}): ProjectThreadCreationValidationError | null {
|
||||
if (input.initialMessageText.trim().length === 0) {
|
||||
return new ProjectThreadTaskRequiredError({
|
||||
environmentId: input.environmentId,
|
||||
projectId: input.projectId,
|
||||
environmentMode: input.environmentMode,
|
||||
});
|
||||
}
|
||||
if (input.environmentMode === "worktree" && !input.branch) {
|
||||
return new ProjectThreadBaseBranchRequiredError({
|
||||
environmentId: input.environmentId,
|
||||
projectId: input.projectId,
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
|
||||
import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
|
||||
|
||||
function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
@@ -53,16 +52,15 @@ export function useCreateProjectThread() {
|
||||
const initialMessageText = input.initialMessageText.trim();
|
||||
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
|
||||
|
||||
const validationError = validateProjectThreadCreation({
|
||||
environmentId: input.project.environmentId,
|
||||
projectId: input.project.id,
|
||||
environmentMode: input.envMode,
|
||||
branch: input.branch,
|
||||
initialMessageText,
|
||||
});
|
||||
if (validationError !== null) {
|
||||
setPendingConnectionError(validationError.message);
|
||||
return AsyncResult.failure(Cause.fail(validationError));
|
||||
if (initialMessageText.length === 0) {
|
||||
const error = new Error("Enter a task before starting the thread.");
|
||||
setPendingConnectionError(error.message);
|
||||
return AsyncResult.failure(Cause.fail(error));
|
||||
}
|
||||
if (input.envMode === "worktree" && !input.branch) {
|
||||
const error = new Error("Select a base branch before creating a worktree.");
|
||||
setPendingConnectionError(error.message);
|
||||
return AsyncResult.failure(Cause.fail(error));
|
||||
}
|
||||
|
||||
const isWorktree = input.envMode === "worktree";
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { Linking } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { tryOpenExternalUrl } from "./openExternalUrl";
|
||||
|
||||
vi.mock("react-native", () => ({
|
||||
Linking: { openURL: vi.fn() },
|
||||
}));
|
||||
|
||||
const openURL = vi.mocked(Linking.openURL);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("tryOpenExternalUrl", () => {
|
||||
it("opens supported URLs", async () => {
|
||||
openURL.mockResolvedValue(undefined);
|
||||
|
||||
await expect(
|
||||
tryOpenExternalUrl("https://github.com/pingdotgg/t3code", "pull-request"),
|
||||
).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("logs stable URL context without exposing the opening failure", async () => {
|
||||
const cause = new Error("browser-unavailable-secret-sentinel");
|
||||
openURL.mockRejectedValue(cause);
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
await expect(
|
||||
tryOpenExternalUrl("https://github.com/pingdotgg/t3code/pull/1?token=secret", "pull-request"),
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(consoleError).toHaveBeenCalledTimes(1);
|
||||
const [message, attributes] = consoleError.mock.calls[0] ?? [];
|
||||
expect(message).toBe("Failed to open pull-request URL with the https scheme.");
|
||||
expect(attributes).toEqual(
|
||||
expect.objectContaining({
|
||||
_tag: "ExternalUrlOpenError",
|
||||
target: "pull-request",
|
||||
scheme: "https",
|
||||
host: "github.com",
|
||||
stack: expect.stringContaining("ExternalUrlOpenError"),
|
||||
}),
|
||||
);
|
||||
expect(attributes).not.toHaveProperty("url");
|
||||
expect(attributes).not.toHaveProperty("cause");
|
||||
const diagnosticText = [message, ...Object.values(attributes as Record<string, unknown>)]
|
||||
.map(String)
|
||||
.join("\n");
|
||||
expect(diagnosticText).not.toContain("token=secret");
|
||||
expect(diagnosticText).not.toContain("browser-unavailable-secret-sentinel");
|
||||
});
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Linking } from "react-native";
|
||||
|
||||
const ExternalUrlTarget = Schema.Literals(["file-preview", "markdown-link", "pull-request"]);
|
||||
|
||||
export type ExternalUrlTarget = typeof ExternalUrlTarget.Type;
|
||||
|
||||
export class ExternalUrlOpenError extends Schema.TaggedErrorClass<ExternalUrlOpenError>()(
|
||||
"ExternalUrlOpenError",
|
||||
{
|
||||
target: ExternalUrlTarget,
|
||||
scheme: Schema.String,
|
||||
host: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to open ${this.target} URL with the ${this.scheme} scheme.`;
|
||||
}
|
||||
}
|
||||
|
||||
function externalUrlMetadata(url: string): { readonly scheme: string; readonly host?: string } {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return {
|
||||
scheme: parsed.protocol.replace(/:$/, "") || "unknown",
|
||||
host: parsed.hostname || undefined,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
scheme: /^([a-z][a-z\d+.-]*):/i.exec(url)?.[1]?.toLowerCase() ?? "unknown",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function tryOpenExternalUrl(url: string, target: ExternalUrlTarget): Promise<boolean> {
|
||||
try {
|
||||
await Linking.openURL(url);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
const error = new ExternalUrlOpenError({ target, ...externalUrlMetadata(url), cause });
|
||||
console.error(error.message, {
|
||||
_tag: error._tag,
|
||||
target: error.target,
|
||||
scheme: error.scheme,
|
||||
host: error.host,
|
||||
stack: error.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -69,35 +69,4 @@ describe("mobile connection storage", () => {
|
||||
toStableSavedRemoteConnection(managedConnection),
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves secure-storage read failures with operation and key context", async () => {
|
||||
const cause = new Error("keychain unavailable");
|
||||
mocks.getItemAsync.mockRejectedValueOnce(cause);
|
||||
|
||||
await expect(loadSavedConnections()).rejects.toMatchObject({
|
||||
_tag: "MobileSecureStorageError",
|
||||
operation: "read",
|
||||
key: "t3code.connections",
|
||||
cause,
|
||||
message: "Mobile secure storage operation read failed for key t3code.connections.",
|
||||
});
|
||||
});
|
||||
|
||||
it("logs structured decode failures before using the empty fallback", async () => {
|
||||
await mocks.setItemAsync("t3code.connections", "{");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
|
||||
await expect(loadSavedConnections()).resolves.toEqual([]);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"[mobile-storage] ignored invalid JSON",
|
||||
expect.objectContaining({
|
||||
_tag: "MobileStorageDecodeError",
|
||||
key: "t3code.connections",
|
||||
cause: expect.any(SyntaxError),
|
||||
message: "Failed to decode mobile storage value for key t3code.connections.",
|
||||
}),
|
||||
);
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
@@ -13,72 +12,21 @@ import {
|
||||
const CONNECTIONS_KEY = "t3code.connections";
|
||||
const PREFERENCES_KEY = "t3code.preferences";
|
||||
const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
|
||||
const MobileStorageKey = Schema.Literals([
|
||||
CONNECTIONS_KEY,
|
||||
PREFERENCES_KEY,
|
||||
AGENT_AWARENESS_DEVICE_ID_KEY,
|
||||
]);
|
||||
type MobileStorageKeyValue = typeof MobileStorageKey.Type;
|
||||
|
||||
export class MobileSecureStorageError extends Schema.TaggedErrorClass<MobileSecureStorageError>()(
|
||||
"MobileSecureStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "write", "generate-device-id"]),
|
||||
key: MobileStorageKey,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MobileStorageDecodeError extends Schema.TaggedErrorClass<MobileStorageDecodeError>()(
|
||||
"MobileStorageDecodeError",
|
||||
{
|
||||
key: MobileStorageKey,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode mobile storage value for key ${this.key}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MobileStorageEncodeError extends Schema.TaggedErrorClass<MobileStorageEncodeError>()(
|
||||
"MobileStorageEncodeError",
|
||||
{
|
||||
key: MobileStorageKey,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode mobile storage value for key ${this.key}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface Preferences {
|
||||
readonly liveActivitiesEnabled?: boolean;
|
||||
readonly terminalFontSize?: number;
|
||||
}
|
||||
|
||||
async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
|
||||
try {
|
||||
return await SecureStore.getItemAsync(key);
|
||||
} catch (cause) {
|
||||
throw new MobileSecureStorageError({ operation: "read", key, cause });
|
||||
}
|
||||
async function readStorageItem(key: string): Promise<string | null> {
|
||||
return await SecureStore.getItemAsync(key);
|
||||
}
|
||||
|
||||
async function writeStorageItem(key: MobileStorageKeyValue, value: string): Promise<void> {
|
||||
try {
|
||||
await SecureStore.setItemAsync(key, value);
|
||||
} catch (cause) {
|
||||
throw new MobileSecureStorageError({ operation: "write", key, cause });
|
||||
}
|
||||
async function writeStorageItem(key: string, value: string): Promise<void> {
|
||||
await SecureStore.setItemAsync(key, value);
|
||||
}
|
||||
|
||||
async function readJsonStorageItem<T>(key: MobileStorageKeyValue): Promise<T | null> {
|
||||
async function readJsonStorageItem<T>(key: string): Promise<T | null> {
|
||||
const raw = (await readStorageItem(key)) ?? "";
|
||||
if (!raw.trim()) {
|
||||
return null;
|
||||
@@ -86,25 +34,11 @@ async function readJsonStorageItem<T>(key: MobileStorageKeyValue): Promise<T | n
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as T;
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[mobile-storage] ignored invalid JSON",
|
||||
new MobileStorageDecodeError({ key, cause }),
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeJsonStorageItem(key: MobileStorageKeyValue, value: unknown) {
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = JSON.stringify(value);
|
||||
} catch (cause) {
|
||||
throw new MobileStorageEncodeError({ key, cause });
|
||||
}
|
||||
await writeStorageItem(key, encoded);
|
||||
}
|
||||
|
||||
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
|
||||
const parsed = await readJsonStorageItem<{
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
@@ -133,7 +67,7 @@ export async function saveConnection(connection: SavedRemoteConnection): Promise
|
||||
)
|
||||
: pipe(current, Arr.append(stableConnection));
|
||||
|
||||
await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
|
||||
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
|
||||
}
|
||||
|
||||
export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
|
||||
@@ -142,7 +76,7 @@ export async function clearSavedConnection(environmentId: EnvironmentId): Promis
|
||||
current,
|
||||
Arr.filter((entry) => entry.environmentId !== environmentId),
|
||||
);
|
||||
await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
|
||||
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
|
||||
}
|
||||
|
||||
export async function loadPreferences(): Promise<Preferences> {
|
||||
@@ -172,7 +106,7 @@ export async function savePreferencesPatch(patch: Partial<Preferences>): Promise
|
||||
...current,
|
||||
...patch,
|
||||
};
|
||||
await writeJsonStorageItem(PREFERENCES_KEY, next);
|
||||
await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -182,15 +116,8 @@ export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const deviceId = await import("./uuid")
|
||||
.then(({ uuidv4 }) => uuidv4())
|
||||
.catch((cause) => {
|
||||
throw new MobileSecureStorageError({
|
||||
operation: "generate-device-id",
|
||||
key: AGENT_AWARENESS_DEVICE_ID_KEY,
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const { uuidv4 } = await import("./uuid");
|
||||
const deviceId = uuidv4();
|
||||
await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class NativeViewResolutionError extends Schema.TaggedErrorClass<NativeViewResolutionError>()(
|
||||
"NativeViewResolutionError",
|
||||
{
|
||||
nativeModuleName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to resolve native view ${this.nativeModuleName}.`;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -12,20 +11,6 @@ const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
|
||||
const COMPOSER_DRAFTS_FILE = "drafts.json";
|
||||
const PERSIST_DEBOUNCE_MS = 200;
|
||||
|
||||
export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<ComposerDraftPersistenceError>()(
|
||||
"ComposerDraftPersistenceError",
|
||||
{
|
||||
operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]),
|
||||
directory: Schema.String,
|
||||
fileName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
@@ -71,16 +56,12 @@ async function getComposerDraftsFile() {
|
||||
}
|
||||
|
||||
async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDraft>> {
|
||||
let operation: ComposerDraftPersistenceError["operation"] = "open";
|
||||
try {
|
||||
const file = await getComposerDraftsFile();
|
||||
if (!file.exists) {
|
||||
return {};
|
||||
}
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
operation = "decode";
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
|
||||
const parsed = JSON.parse(await file.text()) as Partial<PersistedComposerDrafts>;
|
||||
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
|
||||
return {};
|
||||
}
|
||||
@@ -94,53 +75,30 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
|
||||
);
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-drafts] ignored persisted draft failure",
|
||||
new ComposerDraftPersistenceError({
|
||||
operation,
|
||||
directory: COMPOSER_DRAFTS_DIRECTORY,
|
||||
fileName: COMPOSER_DRAFTS_FILE,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
|
||||
let operation: ComposerDraftPersistenceError["operation"] = "open";
|
||||
try {
|
||||
const file = await getComposerDraftsFile();
|
||||
operation = "encode";
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document: PersistedComposerDrafts = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
};
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(encoded);
|
||||
} catch (cause) {
|
||||
throw new ComposerDraftPersistenceError({
|
||||
operation,
|
||||
directory: COMPOSER_DRAFTS_DIRECTORY,
|
||||
fileName: COMPOSER_DRAFTS_FILE,
|
||||
cause,
|
||||
});
|
||||
const file = await getComposerDraftsFile();
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document: PersistedComposerDrafts = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
};
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(document));
|
||||
}
|
||||
|
||||
async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
|
||||
try {
|
||||
await writePersistedComposerDrafts(drafts);
|
||||
} catch (error) {
|
||||
console.warn("[composer-drafts] failed to persist drafts", error);
|
||||
} catch {
|
||||
// Draft persistence is best-effort; in-memory drafts still keep working.
|
||||
}
|
||||
}
|
||||
@@ -170,16 +128,7 @@ export function ensureComposerDraftsLoaded(): void {
|
||||
...current,
|
||||
});
|
||||
})
|
||||
.catch((cause) => {
|
||||
console.warn(
|
||||
"[composer-drafts] failed to hydrate drafts",
|
||||
new ComposerDraftPersistenceError({
|
||||
operation: "hydrate",
|
||||
directory: COMPOSER_DRAFTS_DIRECTORY,
|
||||
fileName: COMPOSER_DRAFTS_FILE,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
.catch(() => {
|
||||
// Draft loading is best-effort; in-memory drafts still keep working.
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
|
||||
@@ -232,12 +231,7 @@ export function useThreadComposerState() {
|
||||
appendComposerDraftAttachments(threadKey, images);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[native paste] error converting images", {
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
uriCount: uris.length,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
console.error("[native paste] error converting images", error);
|
||||
}
|
||||
},
|
||||
[composerDrafts, selectedThreadShell],
|
||||
|
||||
@@ -114,6 +114,16 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
|
||||
if (error._tag === "ServerAuthScopeNotGrantedError") {
|
||||
expect(error.requestedScopes).toEqual(["orchestration:read", "access:write"]);
|
||||
expect(error.grantedScopes).toEqual([
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
"relay:read",
|
||||
]);
|
||||
}
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
|
||||
@@ -252,4 +262,20 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains both session ids when rejecting self-revocation", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const issued = yield* serverAuth.issueSession();
|
||||
const error = yield* serverAuth
|
||||
.revokeClientSession(issued.sessionId, issued.sessionId)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthForbiddenOperationError");
|
||||
if (error._tag === "ServerAuthForbiddenOperationError") {
|
||||
expect(error.currentSessionId).toBe(issued.sessionId);
|
||||
expect(error.targetSessionId).toBe(issued.sessionId);
|
||||
}
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
});
|
||||
@@ -85,44 +85,50 @@ export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedE
|
||||
export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
|
||||
"ServerAuthSessionCredentialValidationError",
|
||||
{
|
||||
credentialKind: Schema.Literals(["session", "websocket-ticket"]),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to validate session credential.";
|
||||
return `Failed to validate ${this.credentialKind} credential.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
|
||||
"ServerAuthAuthenticatedSessionIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue authenticated session.";
|
||||
return `Failed to issue authenticated session for ${this.subject}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
|
||||
"ServerAuthAuthenticatedAccessTokenIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue authenticated access token.";
|
||||
return `Failed to issue authenticated access token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
|
||||
"ServerAuthPairingLinkCreationError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create pairing link.";
|
||||
return `Failed to create pairing link for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,22 +146,25 @@ export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<Ser
|
||||
export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
|
||||
"ServerAuthPairingLinkRevocationError",
|
||||
{
|
||||
pairingLinkId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke pairing link.";
|
||||
return `Failed to revoke pairing link ${this.pairingLinkId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
|
||||
"ServerAuthSessionTokenIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue session token.";
|
||||
return `Failed to issue session token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,55 +182,63 @@ export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerA
|
||||
export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
|
||||
"ServerAuthSessionRevocationError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke session.";
|
||||
return `Failed to revoke session ${this.sessionId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
|
||||
"ServerAuthOtherSessionsRevocationError",
|
||||
{
|
||||
excludedSessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke other sessions.";
|
||||
return `Failed to revoke sessions other than ${this.excludedSessionId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
|
||||
"ServerAuthWebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue websocket token.";
|
||||
return `Failed to issue websocket token for session ${this.sessionId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
|
||||
"ServerAuthDpopReplayStateRecordError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
replayKey: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to record DPoP proof replay state.";
|
||||
return `Failed to record replay state for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
|
||||
"ServerAuthDpopReplayKeyCalculationError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to calculate DPoP replay key.";
|
||||
return `Failed to calculate replay key for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,11 +377,6 @@ export const ServerAuthCredentialError = Schema.Union([
|
||||
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",
|
||||
@@ -377,10 +389,13 @@ export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerA
|
||||
|
||||
export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
|
||||
"ServerAuthScopeNotGrantedError",
|
||||
{},
|
||||
{
|
||||
requestedScopes: Schema.Array(Schema.String),
|
||||
grantedScopes: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The requested authentication scope was not granted.";
|
||||
return `Requested scopes [${this.requestedScopes.join(", ")}] exceed granted scopes [${this.grantedScopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,28 +404,35 @@ export const ServerAuthInvalidRequestError = Schema.Union([
|
||||
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",
|
||||
{},
|
||||
{
|
||||
currentSessionId: Schema.String,
|
||||
targetSessionId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The current authentication session cannot revoke itself.";
|
||||
return `Authentication session ${this.currentSessionId} cannot revoke itself.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ServerAuthAuthenticationInternalError =
|
||||
| ServerAuthSessionCredentialValidationError
|
||||
| ServerAuthDpopReplayStateRecordError
|
||||
| ServerAuthDpopReplayKeyCalculationError;
|
||||
|
||||
export type ServerAuthAuthenticationError =
|
||||
| ServerAuthCredentialError
|
||||
| ServerAuthAuthenticationInternalError;
|
||||
|
||||
export class EnvironmentAuth extends Context.Service<
|
||||
EnvironmentAuth,
|
||||
{
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
readonly getSessionState: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthAuthenticationInternalError>;
|
||||
readonly createBrowserSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
@@ -419,7 +441,9 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly response: AuthBrowserSessionResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedSessionIssueError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForAccessToken: (
|
||||
credential: string,
|
||||
@@ -430,7 +454,10 @@ export class EnvironmentAuth extends Context.Service<
|
||||
},
|
||||
) => Effect.Effect<
|
||||
AuthAccessTokenResult,
|
||||
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthScopeNotGrantedError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedAccessTokenIssueError
|
||||
>;
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
@@ -438,56 +465,61 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthPairingLinkCreationError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthPairingLinkCreationError>;
|
||||
readonly issueStartupPairingCredential: () => Effect.Effect<
|
||||
AuthPairingCredentialResult,
|
||||
ServerAuthInternalError
|
||||
ServerAuthPairingLinkCreationError
|
||||
>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthPairingLinksListError>;
|
||||
readonly revokePairingLink: (
|
||||
id: string,
|
||||
) => Effect.Effect<boolean, ServerAuthPairingLinkRevocationError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthSessionTokenIssueError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
ServerAuthInternalError
|
||||
ServerAuthSessionsListError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
) => Effect.Effect<boolean, ServerAuthSessionRevocationError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthSessionsListError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
ServerAuthForbiddenOperationError | ServerAuthSessionRevocationError
|
||||
>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
readonly issueWebSocketTicket: (
|
||||
session: Pick<AuthenticatedSession, "sessionId">,
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthWebSocketTokenIssueError>;
|
||||
readonly issueStartupPairingUrl: (
|
||||
baseUrl: string,
|
||||
) => Effect.Effect<string, ServerAuthInternalError>;
|
||||
) => Effect.Effect<string, ServerAuthPairingLinkCreationError>;
|
||||
}
|
||||
>()("t3/auth/EnvironmentAuth") {}
|
||||
|
||||
@@ -514,7 +546,7 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
|
||||
|
||||
export function toBootstrapExchangeError(
|
||||
cause: PairingGrantStore.BootstrapCredentialError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
|
||||
): ServerAuthInvalidCredentialError | ServerAuthBootstrapCredentialValidationError {
|
||||
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
|
||||
return new ServerAuthBootstrapCredentialValidationError({ cause });
|
||||
}
|
||||
@@ -526,12 +558,17 @@ export function toBootstrapExchangeError(
|
||||
|
||||
const mapSessionVerificationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
|
||||
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
|
||||
credentialKind: ServerAuthSessionCredentialValidationError["credentialKind"],
|
||||
): Effect.Effect<
|
||||
A,
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError,
|
||||
R
|
||||
> =>
|
||||
effect.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
SessionStore.isSessionCredentialInvalidError(cause)
|
||||
? new ServerAuthInvalidCredentialError({ cause })
|
||||
: new ServerAuthSessionCredentialValidationError({ cause }),
|
||||
: new ServerAuthSessionCredentialValidationError({ credentialKind, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -565,7 +602,7 @@ export const make = Effect.gen(function* () {
|
||||
token: string,
|
||||
): Effect.Effect<
|
||||
AuthenticatedSession,
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError
|
||||
> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
@@ -585,12 +622,12 @@ export const make = Effect.gen(function* () {
|
||||
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
mapSessionVerificationErrors,
|
||||
(effect) => mapSessionVerificationErrors(effect, "session"),
|
||||
);
|
||||
|
||||
const authenticateRequest = (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError> => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const dpopToken = parseDpopToken(request);
|
||||
@@ -642,12 +679,18 @@ export const make = Effect.gen(function* () {
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchIf(isServerAuthCredentialError, () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
}),
|
||||
Effect.withSpan("EnvironmentAuth.getSessionState"),
|
||||
);
|
||||
|
||||
@@ -669,7 +712,13 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedSessionIssueError({
|
||||
subject: grant.subject,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
@@ -695,7 +744,10 @@ export const make = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const grantedScopes = requestedScopes ?? grant.scopes;
|
||||
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
|
||||
return yield* new ServerAuthScopeNotGrantedError({});
|
||||
return yield* new ServerAuthScopeNotGrantedError({
|
||||
requestedScopes: grantedScopes,
|
||||
grantedScopes: grant.scopes,
|
||||
});
|
||||
}
|
||||
return yield* sessions
|
||||
.issue({
|
||||
@@ -715,7 +767,12 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedAccessTokenIssueError({
|
||||
subject: grant.subject,
|
||||
scopes: grantedScopes,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
@@ -765,28 +822,33 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
|
||||
"EnvironmentAuth.createPairingLink",
|
||||
)(
|
||||
function* (input) {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
)(function* (input) {
|
||||
const scopes = input?.scopes ?? AuthStandardClientScopes;
|
||||
const subject = input?.subject ?? "one-time-token";
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials
|
||||
.issueOneTimeToken({
|
||||
scopes,
|
||||
subject,
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
},
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
|
||||
);
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkCreationError({ subject, scopes, cause }),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
scopes,
|
||||
subject,
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
});
|
||||
|
||||
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
@@ -806,16 +868,20 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials.revoke(id).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkRevocationError({ pairingLinkId: id, cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
|
||||
);
|
||||
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
|
||||
sessions
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => {
|
||||
const subject = input?.subject ?? DEFAULT_SESSION_SUBJECT;
|
||||
const scopes = input?.scopes ?? AuthAdministrativeScopes;
|
||||
return sessions
|
||||
.issue({
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
subject,
|
||||
method: "bearer-access-token",
|
||||
scopes: input?.scopes ?? AuthAdministrativeScopes,
|
||||
scopes,
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
@@ -830,14 +896,17 @@ export const make = Effect.gen(function* () {
|
||||
token: issued.token,
|
||||
method: "bearer-access-token",
|
||||
scopes: issued.scopes,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
subject,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies IssuedBearerSession,
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthSessionTokenIssueError({ subject, scopes, cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.issueSession"),
|
||||
);
|
||||
};
|
||||
|
||||
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
@@ -848,7 +917,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
|
||||
sessions.revoke(sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ sessionId, cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeSession"),
|
||||
);
|
||||
|
||||
@@ -856,7 +925,10 @@ export const make = Effect.gen(function* () {
|
||||
sessionId,
|
||||
) =>
|
||||
sessions.revokeAllExcept(sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthOtherSessionsRevocationError({ excludedSessionId: sessionId, cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
|
||||
);
|
||||
|
||||
@@ -891,7 +963,10 @@ export const make = Effect.gen(function* () {
|
||||
"EnvironmentAuth.revokeClientSession",
|
||||
)(function* (currentSessionId, targetSessionId) {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new ServerAuthForbiddenOperationError({});
|
||||
return yield* new ServerAuthForbiddenOperationError({
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
});
|
||||
}
|
||||
return yield* revokeSession(targetSessionId);
|
||||
});
|
||||
@@ -917,7 +992,9 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthWebSocketTokenIssueError({ sessionId: session.sessionId, cause }),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
@@ -947,7 +1024,7 @@ export const make = Effect.gen(function* () {
|
||||
scopes: session.scopes,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
mapSessionVerificationErrors,
|
||||
(effect) => mapSessionVerificationErrors(effect, "websocket-ticket"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,9 @@ import { expect, it } from "@effect/vitest";
|
||||
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 TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
|
||||
import { PersistenceSqlError } from "../persistence/Errors.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
|
||||
@@ -36,26 +33,6 @@ const makePairingGrantStoreLayer = (
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
const makePairingGrantStoreTestLayer = (
|
||||
overrides: Partial<AuthPairingLinks.AuthPairingLinkRepository["Service"]>,
|
||||
) =>
|
||||
Layer.effect(PairingGrantStore.PairingGrantStore, PairingGrantStore.make).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
AuthPairingLinks.AuthPairingLinkRepository,
|
||||
AuthPairingLinks.AuthPairingLinkRepository.of({
|
||||
create: () => Effect.void,
|
||||
consumeAvailable: () => Effect.succeed(Option.none()),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.succeed(false),
|
||||
getByCredential: () => Effect.succeed(Option.none()),
|
||||
...overrides,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
|
||||
it.effect("issues pairing tokens in a short manual-entry format", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -209,28 +186,4 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
|
||||
expect(revokedConsume._tag).toBe("UnavailableBootstrapCredentialError");
|
||||
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("identifies consume-available failures and preserves their cause", () => {
|
||||
const repositoryFailure = new PersistenceSqlError({
|
||||
operation: "consume-pairing-link",
|
||||
detail: "Database unavailable",
|
||||
cause: new Error("database unavailable"),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const pairingGrants = yield* PairingGrantStore.PairingGrantStore;
|
||||
const error = yield* Effect.flip(pairingGrants.consume("credential"));
|
||||
|
||||
if (error._tag !== "BootstrapCredentialConsumeAvailableError") {
|
||||
return yield* Effect.die(error);
|
||||
}
|
||||
expect(error.cause).toBe(repositoryFailure);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makePairingGrantStoreTestLayer({
|
||||
consumeAvailable: () => Effect.fail(repositoryFailure),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -88,38 +88,22 @@ export class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActiveP
|
||||
export class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(
|
||||
"PairingLinkRevokeError",
|
||||
{
|
||||
pairingLinkId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
|
||||
return "Failed to revoke pairing link.";
|
||||
}
|
||||
}
|
||||
|
||||
export class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(
|
||||
"PairingCredentialIssueError",
|
||||
{
|
||||
pairingLinkId: Schema.String,
|
||||
subject: Schema.String,
|
||||
label: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PairingCredentialRandomGenerationError extends Schema.TaggedErrorClass<PairingCredentialRandomGenerationError>()(
|
||||
"PairingCredentialRandomGenerationError",
|
||||
{
|
||||
operation: Schema.Literals(["generate-id", "generate-token"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate pairing credential data during '${this.operation}'.`;
|
||||
return "Failed to issue pairing credential.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,36 +118,11 @@ export class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<Boo
|
||||
}
|
||||
}
|
||||
|
||||
export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeAvailableError>()(
|
||||
"BootstrapCredentialConsumeAvailableError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to atomically consume an available bootstrap credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class BootstrapCredentialLookupError extends Schema.TaggedErrorClass<BootstrapCredentialLookupError>()(
|
||||
"BootstrapCredentialLookupError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to look up bootstrap credential state.";
|
||||
}
|
||||
}
|
||||
|
||||
export const BootstrapCredentialInternalError = Schema.Union([
|
||||
ActivePairingLinksLoadError,
|
||||
PairingLinkRevokeError,
|
||||
PairingCredentialIssueError,
|
||||
PairingCredentialRandomGenerationError,
|
||||
BootstrapCredentialConsumeError,
|
||||
BootstrapCredentialConsumeAvailableError,
|
||||
BootstrapCredentialLookupError,
|
||||
]);
|
||||
export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
|
||||
export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
|
||||
@@ -248,14 +207,7 @@ export const make = Effect.gen(function* () {
|
||||
const generatePairingToken = Effect.gen(function* () {
|
||||
let credential = "";
|
||||
while (credential.length < PAIRING_TOKEN_LENGTH) {
|
||||
const bytes = yield* crypto
|
||||
.randomBytes(PAIRING_TOKEN_LENGTH)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
|
||||
),
|
||||
);
|
||||
const bytes = yield* crypto.randomBytes(PAIRING_TOKEN_LENGTH);
|
||||
for (const byte of bytes) {
|
||||
if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
|
||||
continue;
|
||||
@@ -335,73 +287,58 @@ export const make = Effect.gen(function* () {
|
||||
const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
|
||||
function* (id) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* pairingLinks
|
||||
.revoke({
|
||||
id,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
|
||||
const revoked = yield* pairingLinks.revoke({
|
||||
id,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* emitRemoved(id);
|
||||
}
|
||||
return revoked;
|
||||
},
|
||||
Effect.mapError((cause) => new PairingLinkRevokeError({ cause })),
|
||||
);
|
||||
|
||||
const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
|
||||
"PairingGrantStore.issueOneTimeToken",
|
||||
)(function* (input) {
|
||||
const id = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
id,
|
||||
credential,
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
expiresAt,
|
||||
};
|
||||
const subject = input?.subject ?? "one-time-token";
|
||||
yield* pairingLinks
|
||||
.create({
|
||||
)(
|
||||
function* (input) {
|
||||
const id = yield* crypto.randomUUIDv4;
|
||||
const credential = yield* generatePairingToken;
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
id,
|
||||
credential,
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
expiresAt,
|
||||
};
|
||||
yield* pairingLinks.create({
|
||||
id,
|
||||
credential,
|
||||
method: "one-time-token",
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
label: input?.label ?? null,
|
||||
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
|
||||
createdAt: now,
|
||||
expiresAt: expiresAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PairingCredentialIssueError({
|
||||
pairingLinkId: id,
|
||||
subject,
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* emitUpsert({
|
||||
id,
|
||||
credential,
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
createdAt: now,
|
||||
expiresAt,
|
||||
});
|
||||
return issued;
|
||||
});
|
||||
});
|
||||
yield* emitUpsert({
|
||||
id,
|
||||
credential,
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
createdAt: now,
|
||||
expiresAt,
|
||||
});
|
||||
return issued;
|
||||
},
|
||||
Effect.mapError((cause) => new PairingCredentialIssueError({ cause })),
|
||||
);
|
||||
|
||||
const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
|
||||
function* (credential, input) {
|
||||
@@ -483,14 +420,12 @@ export const make = Effect.gen(function* () {
|
||||
return yield* seededResult.error;
|
||||
}
|
||||
|
||||
const consumed = yield* pairingLinks
|
||||
.consumeAvailable({
|
||||
credential,
|
||||
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
|
||||
consumedAt: now,
|
||||
now,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
|
||||
const consumed = yield* pairingLinks.consumeAvailable({
|
||||
credential,
|
||||
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
|
||||
consumedAt: now,
|
||||
now,
|
||||
});
|
||||
|
||||
if (Option.isSome(consumed)) {
|
||||
yield* emitRemoved(consumed.value.id);
|
||||
@@ -506,9 +441,7 @@ export const make = Effect.gen(function* () {
|
||||
} satisfies BootstrapGrant;
|
||||
}
|
||||
|
||||
const matching = yield* pairingLinks
|
||||
.getByCredential({ credential })
|
||||
.pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
|
||||
const matching = yield* pairingLinks.getByCredential({ credential });
|
||||
if (Option.isNone(matching)) {
|
||||
return yield* new UnknownBootstrapCredentialError({});
|
||||
}
|
||||
@@ -534,6 +467,9 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return yield* new UnavailableBootstrapCredentialError({});
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isBootstrapCredentialError(cause) ? cause : new BootstrapCredentialConsumeError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
return PairingGrantStore.of({
|
||||
|
||||
@@ -45,6 +45,31 @@ const makePermissionDeniedSecretStoreLayer = () =>
|
||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
||||
);
|
||||
|
||||
const DirectoryCreateFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return {
|
||||
...fileSystem,
|
||||
makeDirectory: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: String(path),
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeDirectoryCreateFailureSecretStoreLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
ServerSecretStore.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig.ServerConfig, config)),
|
||||
Layer.provideMerge(DirectoryCreateFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const RenameFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
@@ -146,6 +171,20 @@ const makeConcurrentCreateSecretStoreLayer = () =>
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
it.effect("preserves directory context when secret-store initialization fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(makeServerConfigLayer()));
|
||||
const error = yield* Layer.build(makeDirectoryCreateFailureSecretStoreLayer(config)).pipe(
|
||||
Effect.scoped,
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreDirectoryCreateError);
|
||||
assert.match(error.directoryPath, /secrets$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns Option.none when a secret file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
@@ -232,7 +271,8 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
|
||||
assert.include(error.message, "Failed to read secret session-signing-key.");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
||||
@@ -247,7 +287,9 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
|
||||
assert.include(error.message, "Failed to persist secret session-signing-key.");
|
||||
assert.equal(error.operation, "set");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
||||
@@ -260,7 +302,8 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
|
||||
assert.include(error.message, "Failed to remove secret session-signing-key.");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
||||
|
||||
@@ -11,114 +11,136 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
const secretStoreErrorContext = {
|
||||
resource: Schema.String,
|
||||
const storedSecretErrorContext = {
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
|
||||
"SecretStoreSecureError",
|
||||
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
|
||||
"SecretStoreDirectoryCreateError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to secure ${this.resource}.`;
|
||||
return `Failed to create secret store directory ${this.directoryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDirectorySecureError extends Schema.TaggedErrorClass<SecretStoreDirectorySecureError>()(
|
||||
"SecretStoreDirectorySecureError",
|
||||
{
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to secure secret store directory ${this.directoryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
|
||||
"SecretStoreReadError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
...storedSecretErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.resource}.`;
|
||||
return `Failed to read secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
|
||||
"SecretStoreTemporaryPathError",
|
||||
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
|
||||
"SecretStoreTemporaryPathGenerationError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create temporary path for ${this.resource}.`;
|
||||
return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
|
||||
"SecretStorePersistError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
operation: Schema.Literals(["create", "set"]),
|
||||
...storedSecretErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist ${this.resource}.`;
|
||||
return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
|
||||
"SecretStoreRandomGenerationError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
byteCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate random bytes for ${this.resource}.`;
|
||||
return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
|
||||
"SecretStoreConcurrentReadError",
|
||||
{
|
||||
resource: Schema.String,
|
||||
secretName: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.resource} after concurrent creation.`;
|
||||
return `Failed to read secret ${this.secretName} after concurrent creation.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
|
||||
"SecretStoreRemoveError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
...storedSecretErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to remove ${this.resource}.`;
|
||||
return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
|
||||
"SecretStoreDecodeError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.resource}.`;
|
||||
return `Failed to decode secret ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
|
||||
"SecretStoreEncodeError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode ${this.resource}.`;
|
||||
return `Failed to encode secret ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const SecretStoreError = Schema.Union([
|
||||
SecretStoreSecureError,
|
||||
SecretStoreDirectoryCreateError,
|
||||
SecretStoreDirectorySecureError,
|
||||
SecretStoreReadError,
|
||||
SecretStoreTemporaryPathError,
|
||||
SecretStoreTemporaryPathGenerationError,
|
||||
SecretStorePersistError,
|
||||
SecretStoreRandomGenerationError,
|
||||
SecretStoreConcurrentReadError,
|
||||
@@ -138,14 +160,26 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
|
||||
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 get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreReadError>;
|
||||
readonly set: (
|
||||
name: string,
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<void, SecretStoreTemporaryPathGenerationError | SecretStorePersistError>;
|
||||
readonly create: (
|
||||
name: string,
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<void, SecretStorePersistError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
) => Effect.Effect<
|
||||
Uint8Array,
|
||||
| SecretStoreReadError
|
||||
| SecretStoreRandomGenerationError
|
||||
| SecretStorePersistError
|
||||
| SecretStoreConcurrentReadError
|
||||
>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
|
||||
}
|
||||
>()("t3/auth/ServerSecretStore") {}
|
||||
|
||||
@@ -155,12 +189,20 @@ export const make = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreDirectoryCreateError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreSecureError({
|
||||
resource: `secrets directory ${serverConfig.secretsDir}`,
|
||||
new SecretStoreDirectorySecureError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -168,29 +210,33 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.readFile(secretPath).pipe(
|
||||
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: Effect.fail(
|
||||
new SecretStoreReadError({
|
||||
resource: `secret ${name}`,
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.get"),
|
||||
);
|
||||
};
|
||||
|
||||
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreTemporaryPathError({
|
||||
resource: `secret ${name}`,
|
||||
new SecretStoreTemporaryPathGenerationError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -208,7 +254,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStorePersistError({
|
||||
resource: `secret ${name}`,
|
||||
operation: "set",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -237,7 +285,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStorePersistError({
|
||||
resource: `secret ${name}`,
|
||||
operation: "create",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -254,30 +304,32 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreRandomGenerationError({
|
||||
resource: `secret ${name}`,
|
||||
secretName: name,
|
||||
byteCount: bytes,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((generated) =>
|
||||
create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchIf(isSecretStoreError, (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
resource: `secret ${name}`,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
secretName: name,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -286,20 +338,23 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.remove(secretPath).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreRemoveError({
|
||||
resource: `secret ${name}`,
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.remove"),
|
||||
);
|
||||
};
|
||||
|
||||
return ServerSecretStore.of({
|
||||
get,
|
||||
|
||||
@@ -6,7 +6,9 @@ import { mapDpopReplayStoreError } from "./dpop.ts";
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new SecretStorePersistError({
|
||||
resource: "DPoP proof",
|
||||
operation: "create",
|
||||
secretName: "DPoP proof",
|
||||
secretPath: "dpop-proof.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -15,10 +17,16 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
}),
|
||||
});
|
||||
|
||||
const replayContext = {
|
||||
proofKeyThumbprint: "proof-key-thumbprint",
|
||||
proofId: "proof-id",
|
||||
replayKey: "replay-key",
|
||||
};
|
||||
|
||||
describe("mapDpopReplayStoreError", () => {
|
||||
it("reports replay conflicts as invalid credentials", () => {
|
||||
const cause = storeFailure("AlreadyExists");
|
||||
const error = mapDpopReplayStoreError(cause);
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
|
||||
if (error._tag === "ServerAuthInvalidCredentialError") {
|
||||
@@ -27,11 +35,18 @@ describe("mapDpopReplayStoreError", () => {
|
||||
});
|
||||
|
||||
it("reports replay-store availability failures as internal errors", () => {
|
||||
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
|
||||
const cause = storeFailure("PermissionDenied");
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
|
||||
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
|
||||
expect(error.message).toBe("Failed to record DPoP proof replay state.");
|
||||
expect(error.message).toBe(
|
||||
"Failed to record replay state for DPoP proof proof-id (proof-key-thumbprint).",
|
||||
);
|
||||
expect(error.proofKeyThumbprint).toBe(replayContext.proofKeyThumbprint);
|
||||
expect(error.proofId).toBe(replayContext.proofId);
|
||||
expect(error.replayKey).toBe(replayContext.replayKey);
|
||||
expect(error.cause).toBe(cause);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
ServerAuthDpopReplayStateRecordError,
|
||||
ServerAuthInvalidCredentialError,
|
||||
type ServerAuthInternalError,
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
@@ -31,13 +30,19 @@ export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest)
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
context: {
|
||||
readonly proofKeyThumbprint: string;
|
||||
readonly proofId: string;
|
||||
readonly replayKey: string;
|
||||
},
|
||||
): ServerAuthInvalidCredentialError | ServerAuthDpopReplayStateRecordError =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "DPoP proof replayed.",
|
||||
cause: error,
|
||||
})
|
||||
: new ServerAuthDpopReplayStateRecordError({
|
||||
...context,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
@@ -71,6 +76,8 @@ export const verifyRequestDpopProof = (input: {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthDpopReplayKeyCalculationError({
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -88,8 +95,12 @@ export const verifyRequestDpopProof = (input: {
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
Effect.fail(mapDpopReplayStoreError(error)),
|
||||
Effect.mapError((error) =>
|
||||
mapDpopReplayStoreError(error, {
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
replayKey,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return result.thumbprint;
|
||||
|
||||
@@ -151,6 +151,22 @@ export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason,
|
||||
});
|
||||
}
|
||||
|
||||
const failAuthenticationInternal = (error: EnvironmentAuth.ServerAuthAuthenticationInternalError) =>
|
||||
failEnvironmentInternal("internal_error", error);
|
||||
|
||||
export const catchEnvironmentAuthenticationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, EnvironmentAuth.ServerAuthAuthenticationError, R>,
|
||||
) =>
|
||||
effect.pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () => failEnvironmentAuthInvalid("missing_credential"),
|
||||
ServerAuthInvalidCredentialError: () => failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
);
|
||||
|
||||
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
|
||||
scope: AuthEnvironmentScope,
|
||||
) {
|
||||
@@ -168,13 +184,8 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
return (httpEffect) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
);
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
|
||||
@@ -183,7 +194,11 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
}),
|
||||
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
|
||||
);
|
||||
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -203,9 +218,11 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
return yield* serverAuth.getSessionState(request);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -233,12 +250,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return result.response;
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
ServerAuthAuthenticatedSessionIssueError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -268,14 +287,16 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
const proofKeyThumbprint = args.headers.dpop
|
||||
? yield* verifyRequestDpopProof({ request }).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
ServerAuthDpopReplayStateRecordError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthDpopReplayKeyCalculationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
)
|
||||
: undefined;
|
||||
yield* appendCredentialResponseHeaders;
|
||||
@@ -296,15 +317,16 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
},
|
||||
traceRelayRequest,
|
||||
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),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthScopeNotGrantedError: () =>
|
||||
failEnvironmentInvalidRequest("scope_not_granted"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthAuthenticatedAccessTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -316,9 +338,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return yield* serverAuth.issueWebSocketTicket(session);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthWebSocketTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -341,9 +364,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
return yield* serverAuth.issuePairingCredential(args.payload);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -354,9 +378,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listPairingLinks();
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinksListError: (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -368,9 +393,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkRevocationError: (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -381,9 +407,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listClientSessions(session.sessionId);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionsListError: (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -398,12 +425,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthForbiddenOperationError: () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
ServerAuthSessionRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -415,9 +442,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return { revokedCount };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthOtherSessionsRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { assert, it } from "@effect/vitest";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -13,19 +13,10 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import { vi } from "vite-plus/test";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import {
|
||||
BootstrapEnvelopeDecodeError,
|
||||
BootstrapFdStatError,
|
||||
BootstrapInputStreamOpenError,
|
||||
readBootstrapEnvelope,
|
||||
} from "./bootstrap.ts";
|
||||
import { readBootstrapEnvelope } from "./bootstrap.ts";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({
|
||||
failPath: null as string | null,
|
||||
errorCode: "ENXIO",
|
||||
}));
|
||||
const fstatSyncInterceptor = vi.hoisted(() => ({ failFd: null as number | null }));
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
vi.mock("node:fs", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs")>();
|
||||
@@ -38,20 +29,12 @@ vi.mock("node:fs", async (importOriginal) => {
|
||||
filePath === openSyncInterceptor.failPath &&
|
||||
flags === "r"
|
||||
) {
|
||||
const error = new Error(`open failed with ${openSyncInterceptor.errorCode}`);
|
||||
Object.assign(error, { code: openSyncInterceptor.errorCode });
|
||||
const error = new Error("no such device or address");
|
||||
Object.assign(error, { code: "ENXIO" });
|
||||
throw error;
|
||||
}
|
||||
return (actual.openSync as (...a: typeof args) => number)(...args);
|
||||
},
|
||||
fstatSync: (...args: Parameters<typeof actual.fstatSync>) => {
|
||||
if (args[0] === fstatSyncInterceptor.failFd) {
|
||||
const error = new Error("permission denied");
|
||||
Object.assign(error, { code: "EACCES" });
|
||||
throw error;
|
||||
}
|
||||
return (actual.fstatSync as (...a: typeof args) => NodeFS.Stats)(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -111,39 +94,6 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves fd path, platform, and cause when opening the input stream fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NodeFS.openSync(filePath, "r")),
|
||||
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
|
||||
);
|
||||
const fdPath = `/proc/self/fd/${fd}`;
|
||||
|
||||
openSyncInterceptor.failPath = fdPath;
|
||||
openSyncInterceptor.errorCode = "EIO";
|
||||
try {
|
||||
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BootstrapInputStreamOpenError);
|
||||
assert.equal(error.fd, fd);
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.equal(error.fdPath, fdPath);
|
||||
assert.equal((error.cause as NodeJS.ErrnoException).code, "EIO");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to open bootstrap input stream for file descriptor ${fd} via '${fdPath}' on 'linux'.`,
|
||||
);
|
||||
} finally {
|
||||
openSyncInterceptor.failPath = null;
|
||||
openSyncInterceptor.errorCode = "ENXIO";
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NodeFS.openSync("/dev/null", "r");
|
||||
@@ -154,53 +104,6 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves fd and cause when stat fails for a non-availability reason", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NodeFS.openSync("/dev/null", "r")),
|
||||
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
fstatSyncInterceptor.failFd = fd;
|
||||
try {
|
||||
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BootstrapFdStatError);
|
||||
assert.equal(error.fd, fd);
|
||||
assert.equal((error.cause as NodeJS.ErrnoException).code, "EACCES");
|
||||
assert.equal(error.message, `Failed to stat bootstrap file descriptor ${fd}.`);
|
||||
} finally {
|
||||
fstatSyncInterceptor.failFd = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves fd and schema cause when decoding the envelope fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
yield* fs.writeFileString(filePath, '{"mode":42}\n');
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NodeFS.openSync(filePath, "r")),
|
||||
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
|
||||
);
|
||||
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BootstrapEnvelopeDecodeError);
|
||||
assert.equal(error.fd, fd);
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode bootstrap envelope from file descriptor ${fd}.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
@@ -12,64 +13,10 @@ import * as Schema from "effect/Schema";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export class BootstrapFdStatError extends Schema.TaggedErrorClass<BootstrapFdStatError>()(
|
||||
"BootstrapFdStatError",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to stat bootstrap file descriptor ${this.fd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BootstrapInputStreamOpenError extends Schema.TaggedErrorClass<BootstrapInputStreamOpenError>()(
|
||||
"BootstrapInputStreamOpenError",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
platform: Schema.String,
|
||||
fdPath: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const path = this.fdPath === undefined ? "" : ` via '${this.fdPath}'`;
|
||||
return `Failed to open bootstrap input stream for file descriptor ${this.fd}${path} on '${this.platform}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BootstrapEnvelopeReadError extends Schema.TaggedErrorClass<BootstrapEnvelopeReadError>()(
|
||||
"BootstrapEnvelopeReadError",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read bootstrap envelope from file descriptor ${this.fd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BootstrapEnvelopeDecodeError extends Schema.TaggedErrorClass<BootstrapEnvelopeDecodeError>()(
|
||||
"BootstrapEnvelopeDecodeError",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode bootstrap envelope from file descriptor ${this.fd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BootstrapError = Schema.Union([
|
||||
BootstrapFdStatError,
|
||||
BootstrapInputStreamOpenError,
|
||||
BootstrapEnvelopeReadError,
|
||||
BootstrapEnvelopeDecodeError,
|
||||
]);
|
||||
export type BootstrapError = typeof BootstrapError.Type;
|
||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
|
||||
schema: Schema.Codec<A, I>,
|
||||
@@ -85,10 +32,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
|
||||
|
||||
const timeoutMs = options?.timeoutMs ?? 1000;
|
||||
|
||||
return yield* Effect.callback<
|
||||
Option.Option<A>,
|
||||
BootstrapEnvelopeReadError | BootstrapEnvelopeDecodeError
|
||||
>((resume) => {
|
||||
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
|
||||
const input = NodeReadline.createInterface({
|
||||
input: stream,
|
||||
crlfDelay: Infinity,
|
||||
@@ -109,8 +53,8 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
|
||||
}
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapEnvelopeReadError({
|
||||
fd,
|
||||
new BootstrapError({
|
||||
message: "Failed to read bootstrap envelope.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -124,8 +68,8 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
|
||||
} else {
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapEnvelopeDecodeError({
|
||||
fd,
|
||||
new BootstrapError({
|
||||
message: "Failed to decode bootstrap envelope.",
|
||||
cause: parsed.failure,
|
||||
}),
|
||||
),
|
||||
@@ -154,24 +98,24 @@ const isFdReady = (fd: number) =>
|
||||
Effect.try({
|
||||
try: () => NodeFS.fstatSync(fd),
|
||||
catch: (error) =>
|
||||
new BootstrapFdStatError({
|
||||
fd,
|
||||
new BootstrapError({
|
||||
message: "Failed to stat bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTags({
|
||||
BootstrapFdStatError: (error) =>
|
||||
isUnavailableBootstrapFdError(error.cause) ? Effect.succeed(false) : Effect.fail(error),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
(error) => isUnavailableBootstrapFdError(error.cause),
|
||||
() => Effect.succeed(false),
|
||||
),
|
||||
);
|
||||
|
||||
const makeBootstrapInputStream = (fd: number) =>
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const fdPath = resolveFdPath(fd, platform);
|
||||
return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({
|
||||
return yield* Effect.try<NodeStream.Readable, BootstrapError>({
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd, platform);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
@@ -195,10 +139,8 @@ const makeBootstrapInputStream = (fd: number) =>
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapInputStreamOpenError({
|
||||
fd,
|
||||
platform,
|
||||
...(fdPath === undefined ? {} : { fdPath }),
|
||||
new BootstrapError({
|
||||
message: "Failed to duplicate bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
|
||||
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
|
||||
|
||||
function makeSecretStore(
|
||||
overrides: Partial<ServerSecretStore.ServerSecretStore["Service"]>,
|
||||
): ServerSecretStore.ServerSecretStore["Service"] {
|
||||
return {
|
||||
get: unusedSecretStoreOperation,
|
||||
set: unusedSecretStoreOperation,
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTokenManager(secretStore: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
return CliTokenManager.make.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secretStore),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unused HTTP client")),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("CloudCliTokenManager", () => {
|
||||
it.effect("retains secret context and cause when credential removal fails", () => {
|
||||
const failure = new ServerSecretStore.SecretStoreRemoveError({
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "remove",
|
||||
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(
|
||||
makeSecretStore({ remove: () => Effect.fail(failure) }),
|
||||
);
|
||||
const error = yield* Effect.flip(tokens.clear);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialRemovalError",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not remove the stored T3 Connect CLI credential cloud-cli-oauth-token.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies credential read failures without replacing the cause", () => {
|
||||
const failure = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(makeSecretStore({ get: () => Effect.fail(failure) }));
|
||||
const error = yield* Effect.flip(tokens.hasCredential);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialReadError",
|
||||
stage: "read-credential",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not inspect the stored T3 Connect CLI credential cloud-cli-oauth-token during read-credential.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies malformed persisted credentials as refresh decode failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(
|
||||
makeSecretStore({
|
||||
get: () =>
|
||||
Effect.succeed(Option.some(new TextEncoder().encode("not valid credential JSON"))),
|
||||
}),
|
||||
);
|
||||
const error = yield* Effect.flip(tokens.getExisting);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialRefreshError",
|
||||
stage: "decode-credential",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: { _tag: "SchemaError" },
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not refresh the T3 Connect CLI credential cloud-cli-oauth-token during decode-credential.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -27,6 +27,8 @@ import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts
|
||||
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
|
||||
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_HOST = "127.0.0.1";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_PORT = 34338;
|
||||
|
||||
const PersistedToken = Schema.Struct({
|
||||
accessToken: Schema.String,
|
||||
@@ -46,48 +48,136 @@ const OAuthTokenResponse = Schema.Struct({
|
||||
token_type: Schema.String,
|
||||
});
|
||||
|
||||
type CredentialReadFailure = ServerSecretStore.SecretStoreReadError | Schema.SchemaError;
|
||||
|
||||
type CredentialPersistFailure =
|
||||
| Schema.SchemaError
|
||||
| ServerSecretStore.SecretStoreTemporaryPathGenerationError
|
||||
| ServerSecretStore.SecretStorePersistError;
|
||||
|
||||
const CloudCliCredentialRefreshStage = Schema.Literals([
|
||||
"read-credential",
|
||||
"decode-credential",
|
||||
"load-oauth-config",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
|
||||
const CloudCliAuthorizationStage = Schema.Literals([
|
||||
"load-oauth-config",
|
||||
"prepare-pkce",
|
||||
"start-callback-server",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
|
||||
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
|
||||
"CloudCliCredentialRemovalError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not remove the stored T3 Connect CLI credential.";
|
||||
return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
|
||||
"CloudCliCredentialRefreshError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: CloudCliCredentialRefreshStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpoint: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Could not refresh the T3 Connect CLI credential.";
|
||||
const tokenEndpoint = this.tokenEndpoint ? ` using ${this.tokenEndpoint}` : "";
|
||||
return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
|
||||
"CloudCliCredentialReadError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: Schema.Literals(["read-credential", "decode-credential"]),
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialReadError {
|
||||
return new CloudCliCredentialReadError({
|
||||
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Could not read the stored T3 Connect CLI credential.";
|
||||
return `Could not inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
|
||||
"CloudCliAuthorizationError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: CloudCliAuthorizationStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpoint: Schema.optional(Schema.String),
|
||||
redirectUri: Schema.optional(Schema.String),
|
||||
callbackHost: Schema.optional(Schema.String),
|
||||
callbackPort: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliAuthorizationError {
|
||||
return new CloudCliAuthorizationError({
|
||||
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Could not authorize the T3 Connect CLI.";
|
||||
const tokenEndpoint = this.tokenEndpoint ? ` using ${this.tokenEndpoint}` : "";
|
||||
const redirectUri = this.redirectUri ? ` with callback ${this.redirectUri}` : "";
|
||||
const callbackAddress =
|
||||
this.callbackHost && this.callbackPort !== undefined
|
||||
? ` on ${this.callbackHost}:${this.callbackPort}`
|
||||
: "";
|
||||
return `Could not authorize the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}${redirectUri}${callbackAddress}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
|
||||
"CloudCliAuthorizationTimeoutError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
redirectUri: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Timed out waiting for T3 Connect authorization.";
|
||||
return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization at ${this.redirectUri}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,18 +193,21 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
|
||||
export class CloudCliTokenManager extends Context.Service<
|
||||
CloudCliTokenManager,
|
||||
{
|
||||
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
|
||||
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
|
||||
readonly get: Effect.Effect<
|
||||
PersistedToken,
|
||||
| CloudCliCredentialRefreshError
|
||||
| CloudCliAuthorizationError
|
||||
| CloudCliAuthorizationTimeoutError
|
||||
>;
|
||||
readonly getExisting: Effect.Effect<
|
||||
Option.Option<PersistedToken>,
|
||||
CloudCliCredentialRefreshError
|
||||
>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliCredentialReadError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliCredentialRemovalError>;
|
||||
}
|
||||
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
|
||||
|
||||
const wrapError =
|
||||
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
|
||||
effect.pipe(Effect.mapError(makeError));
|
||||
|
||||
function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
@@ -134,9 +227,15 @@ export const make = Effect.gen(function* () {
|
||||
return token;
|
||||
});
|
||||
|
||||
const clear = secrets
|
||||
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
|
||||
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
|
||||
const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliCredentialRemovalError({
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const read = Effect.fn("cloud.cli_token.read")(function* () {
|
||||
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
|
||||
@@ -162,21 +261,62 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliCredentialRefreshError({
|
||||
stage: "load-oauth-config",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: token.refreshToken,
|
||||
client_id: metadata.clientId,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliCredentialRefreshError({
|
||||
stage: "exchange-token",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const login = Effect.fn("cloud.cli_token.login")(function* () {
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
|
||||
const challenge = Encoding.encodeBase64Url(
|
||||
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliAuthorizationError({
|
||||
stage: "load-oauth-config",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { challenge, state, verifier } = yield* Effect.gen(function* () {
|
||||
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
|
||||
const challenge = Encoding.encodeBase64Url(
|
||||
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
|
||||
);
|
||||
const state = yield* crypto.randomUUIDv4;
|
||||
return { challenge, state, verifier };
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliAuthorizationError({
|
||||
stage: "prepare-pkce",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const state = yield* crypto.randomUUIDv4;
|
||||
const callback = yield* Deferred.make<string>();
|
||||
const callbackRoute = HttpRouter.add(
|
||||
"GET",
|
||||
@@ -207,12 +347,23 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: "127.0.0.1",
|
||||
port: 34338,
|
||||
host: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
port: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
disablePreemptiveShutdown: true,
|
||||
}),
|
||||
),
|
||||
Layer.build,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliAuthorizationError({
|
||||
stage: "start-callback-server",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
redirectUri: metadata.redirectUri,
|
||||
callbackHost: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
callbackPort: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const authorizationUrl = new URL(metadata.authorizationEndpoint);
|
||||
authorizationUrl.searchParams.set("client_id", metadata.clientId);
|
||||
@@ -225,13 +376,16 @@ export const make = Effect.gen(function* () {
|
||||
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
|
||||
const code = yield* Deferred.await(callback).pipe(
|
||||
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
Effect.catchTag("TimeoutError", (cause) =>
|
||||
Effect.fail(
|
||||
new CloudCliAuthorizationTimeoutError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
TimeoutError: (cause) =>
|
||||
Effect.fail(
|
||||
new CloudCliAuthorizationTimeoutError({
|
||||
redirectUri: metadata.redirectUri,
|
||||
timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "authorization_code",
|
||||
@@ -239,26 +393,45 @@ export const make = Effect.gen(function* () {
|
||||
redirect_uri: metadata.redirectUri,
|
||||
client_id: metadata.clientId,
|
||||
code_verifier: verifier,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliAuthorizationError({
|
||||
stage: "exchange-token",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
|
||||
const token = yield* read();
|
||||
const token = yield* read().pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead),
|
||||
);
|
||||
if (Option.isNone(token)) return token;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
|
||||
return token;
|
||||
}
|
||||
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
|
||||
return Option.some(
|
||||
yield* refresh(token.value).pipe(
|
||||
Effect.flatMap((refreshed) =>
|
||||
persist(refreshed).pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getExisting = semaphore.withPermits(1)(
|
||||
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
|
||||
);
|
||||
const getExisting = semaphore.withPermits(1)(getExistingNoLock());
|
||||
const hasCredential = semaphore.withPermits(1)(
|
||||
read().pipe(
|
||||
Effect.map(Option.isSome),
|
||||
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
|
||||
Effect.mapError(CloudCliCredentialReadError.fromCredentialRead),
|
||||
),
|
||||
);
|
||||
const get = semaphore.withPermits(1)(
|
||||
@@ -266,8 +439,14 @@ export const make = Effect.gen(function* () {
|
||||
const token = yield* getExistingNoLock();
|
||||
return Option.isSome(token)
|
||||
? token.value
|
||||
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
|
||||
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
|
||||
: yield* Effect.scoped(login()).pipe(
|
||||
Effect.flatMap((authorized) =>
|
||||
persist(authorized).pipe(
|
||||
Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
|
||||
|
||||
@@ -66,7 +66,9 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
resource: "environment signing key pair",
|
||||
operation: "create",
|
||||
secretName: "cloud-link-ed25519-key-pair",
|
||||
secretPath: "cloud-link-ed25519-key-pair.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
@@ -87,4 +89,24 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains the secret name and decode cause for malformed keypairs", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = {
|
||||
get: () => Effect.succeed(Option.some(new TextEncoder().encode("not-json"))),
|
||||
set: unusedSecretStoreOperation,
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
} satisfies ServerSecretStore.ServerSecretStore["Service"];
|
||||
|
||||
const error = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreDecodeError);
|
||||
assert.equal(error.secretName, "cloud-link-ed25519-key-pair");
|
||||
assert.exists(error.cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -27,17 +27,6 @@ function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
|
||||
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.ServerSecretStore["Service"],
|
||||
) {
|
||||
@@ -46,7 +35,13 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
|
||||
return Option.none<EnvironmentKeyPair>();
|
||||
}
|
||||
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
|
||||
Effect.mapError(keyPairDecodeError),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreDecodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(decoded);
|
||||
});
|
||||
@@ -56,22 +51,34 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
|
||||
keyPair: EnvironmentKeyPair,
|
||||
) {
|
||||
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
|
||||
Effect.mapError(keyPairEncodeError),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreEncodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
|
||||
Effect.as(keyPair),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? readEnvironmentKeyPair(secrets).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () => Effect.fail(keyPairConcurrentReadError()),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? readEnvironmentKeyPair(secrets).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStoreConcurrentReadError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,23 +1,35 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
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/ServerEnvironment.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
|
||||
import {
|
||||
CloudRelayRequestError,
|
||||
consumeCloudReplayGuards,
|
||||
reconcileDesiredCloudLink,
|
||||
} from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
resource: "cloud replay guard",
|
||||
operation: "create",
|
||||
secretName: "cloud replay guard",
|
||||
secretPath: "cloud-replay-guard.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -40,6 +52,55 @@ function makeSecretStore(
|
||||
};
|
||||
}
|
||||
|
||||
function reconcileWith(input: {
|
||||
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
|
||||
readonly httpClient?: HttpClient.HttpClient;
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}) {
|
||||
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: input.getExisting,
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
input.httpClient ?? HttpClient.make(() => unusedSecretStoreOperation()),
|
||||
),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it("preserves messages surfaced by cloud 500 responses", () => {
|
||||
const cause = new Error("cloud operation failed");
|
||||
|
||||
@@ -93,6 +154,45 @@ describe("consumeCloudReplayGuards", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("CloudRelayRequestError", () => {
|
||||
it("classifies response failures without deriving its message from the cause", () => {
|
||||
const request = HttpClientRequest.post(
|
||||
"https://relay.example.test/v1/client/environment-links",
|
||||
);
|
||||
const response = HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response("sensitive upstream response", { status: 502 }),
|
||||
);
|
||||
const upstreamCause = new Error("sensitive upstream response details");
|
||||
const cause = new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.StatusCodeError({
|
||||
request,
|
||||
response,
|
||||
cause: upstreamCause,
|
||||
}),
|
||||
});
|
||||
|
||||
const error = CloudRelayRequestError.fromClientFailure({
|
||||
operation: "create-environment-link",
|
||||
url: request.url,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
operation: "create-environment-link",
|
||||
phase: "check-response-status",
|
||||
method: "POST",
|
||||
url: request.url,
|
||||
responseStatus: 502,
|
||||
cause,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"T3 Connect relay create-environment-link failed during check-response-status with response status 502.",
|
||||
);
|
||||
expect(error.message).not.toContain(upstreamCause.message);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay request tracing", () => {
|
||||
it.effect("does not accept an unauthenticated request trace parent", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -160,48 +260,47 @@ describe("relay request tracing", () => {
|
||||
describe("reconcileDesiredCloudLink", () => {
|
||||
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: Effect.succeed(Option.none()),
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => unusedSecretStoreOperation()),
|
||||
),
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("redacts relay transport failures behind a stable structural message", () => {
|
||||
const transportCause = new Error("upstream included a sensitive database password");
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.fail(
|
||||
new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.TransportError({ request, cause: transportCause }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({
|
||||
getExisting: Effect.succeed(
|
||||
Option.some({
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
),
|
||||
httpClient,
|
||||
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
message: "T3 Connect relay create-link-challenge failed during send-request.",
|
||||
});
|
||||
expect(error.message).not.toContain(transportCause.message);
|
||||
});
|
||||
});
|
||||
});
|
||||
+319
-90
@@ -48,8 +48,13 @@ import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import * as HttpBody from "effect/unstable/http/HttpBody";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
@@ -85,6 +90,104 @@ const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
const CloudRelayRequestOperation = Schema.Literals([
|
||||
"create-link-challenge",
|
||||
"create-environment-link",
|
||||
]);
|
||||
|
||||
const CloudRelayRequestPhase = Schema.Literals([
|
||||
"encode-request",
|
||||
"send-request",
|
||||
"check-response-status",
|
||||
"decode-response",
|
||||
]);
|
||||
|
||||
export class CloudRelayConfigurationError extends Schema.TaggedErrorClass<CloudRelayConfigurationError>()(
|
||||
"CloudRelayConfigurationError",
|
||||
{
|
||||
configKey: Schema.Literal("T3CODE_RELAY_URL"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.configKey} must be configured as a secure absolute HTTPS origin.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayRequestError extends Schema.TaggedErrorClass<CloudRelayRequestError>()(
|
||||
"CloudRelayRequestError",
|
||||
{
|
||||
operation: CloudRelayRequestOperation,
|
||||
phase: CloudRelayRequestPhase,
|
||||
method: Schema.Literal("POST"),
|
||||
url: Schema.String,
|
||||
responseStatus: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromClientFailure(input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly cause: HttpBody.HttpBodyError | HttpClientError.HttpClientError | Schema.SchemaError;
|
||||
readonly responseStatus?: number;
|
||||
}): CloudRelayRequestError {
|
||||
if (input.cause._tag === "SchemaError") {
|
||||
return new CloudRelayRequestError({
|
||||
operation: input.operation,
|
||||
phase: "decode-response",
|
||||
method: "POST",
|
||||
url: input.url,
|
||||
...(input.responseStatus === undefined ? {} : { responseStatus: input.responseStatus }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
if (!HttpClientError.isHttpClientError(input.cause)) {
|
||||
return new CloudRelayRequestError({
|
||||
operation: input.operation,
|
||||
phase: "encode-request",
|
||||
method: "POST",
|
||||
url: input.url,
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
const phase: CloudRelayRequestError["phase"] = (() => {
|
||||
switch (input.cause.reason._tag) {
|
||||
case "EncodeError":
|
||||
return "encode-request";
|
||||
case "TransportError":
|
||||
case "InvalidUrlError":
|
||||
return "send-request";
|
||||
case "StatusCodeError":
|
||||
return "check-response-status";
|
||||
case "DecodeError":
|
||||
case "EmptyBodyError":
|
||||
return "decode-response";
|
||||
}
|
||||
})();
|
||||
|
||||
return new CloudRelayRequestError({
|
||||
operation: input.operation,
|
||||
phase,
|
||||
method: "POST",
|
||||
url: input.url,
|
||||
...(input.cause.response === undefined
|
||||
? input.responseStatus === undefined
|
||||
? {}
|
||||
: { responseStatus: input.responseStatus }
|
||||
: { responseStatus: input.cause.response.status }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const responseStatus =
|
||||
this.responseStatus === undefined ? "" : ` with response status ${this.responseStatus}`;
|
||||
return `T3 Connect relay ${this.operation} failed during ${this.phase}${responseStatus}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
|
||||
(_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
|
||||
@@ -97,14 +200,12 @@ const failEnvironmentCloudInternalError =
|
||||
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
|
||||
);
|
||||
|
||||
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error);
|
||||
|
||||
const requireRelayUrl = relayUrlConfig.pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
|
||||
(cause) =>
|
||||
new CloudRelayConfigurationError({
|
||||
configKey: "T3CODE_RELAY_URL",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -126,11 +227,12 @@ export function consumeCloudReplayGuards(input: {
|
||||
input.names.map((name) =>
|
||||
input.secrets.create(name, input.value).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ concurrency: input.names.length },
|
||||
@@ -207,7 +309,7 @@ function validateRelayConfigPayload(
|
||||
function validateLinkedCloudUser(input: {
|
||||
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly cloudUserId: string;
|
||||
}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
|
||||
}) {
|
||||
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -232,9 +334,7 @@ function validateLinkedCloudUser(input: {
|
||||
);
|
||||
}
|
||||
|
||||
function readInstalledCloudUserId(
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
|
||||
function readInstalledCloudUserId(secrets: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -409,17 +509,26 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return proof satisfies RelayEnvironmentLinkProof;
|
||||
},
|
||||
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({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError(
|
||||
"Could not generate environment link proof.",
|
||||
),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError(
|
||||
"Could not generate environment link proof.",
|
||||
),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError(
|
||||
"Could not generate environment link proof.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not generate environment link proof.",
|
||||
),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"Could not generate environment link proof.",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("Could not generate environment link proof."),
|
||||
}),
|
||||
);
|
||||
|
||||
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
|
||||
@@ -472,22 +581,28 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
|
||||
yield* requireEnvironmentScope(AuthRelayWriteScope);
|
||||
return yield* applyCloudRelayConfig(dependencies, payload);
|
||||
},
|
||||
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({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment relay configuration.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment relay configuration.",
|
||||
),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment relay configuration.",
|
||||
),
|
||||
SchemaError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment relay configuration.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const relayClientRequest = <A>(
|
||||
dependencies: CloudHttpDependencies,
|
||||
input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly token: string;
|
||||
readonly payload: unknown;
|
||||
@@ -497,14 +612,46 @@ const relayClientRequest = <A>(
|
||||
HttpClientRequest.post(input.url).pipe(
|
||||
HttpClientRequest.bearerToken(input.token),
|
||||
HttpClientRequest.bodyJson(input.payload),
|
||||
Effect.flatMap(dependencies.httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: `T3 Connect relay request failed: ${String(cause)}`,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((request) =>
|
||||
dependencies.httpClient.execute(request).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.filterStatusOk(response).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.schemaBodyJson(input.schema)(response).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
responseStatus: response.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
@@ -539,6 +686,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
);
|
||||
const relayUrl = yield* requireRelayUrl;
|
||||
const challenge = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-link-challenge",
|
||||
url: `${relayUrl}/v1/client/environment-link-challenges`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -566,6 +714,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
localOrigin,
|
||||
);
|
||||
const link = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-environment-link",
|
||||
url: `${relayUrl}/v1/client/environment-links`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -586,16 +735,43 @@ 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,
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
SchemaError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
CloudRelayConfigurationError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
CloudRelayRequestError: (error) => failEnvironmentCloudInternalError(error.message)(error),
|
||||
CloudCliCredentialRefreshError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -633,10 +809,11 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
|
||||
yield* requireEnvironmentScope(AuthRelayReadScope);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError(
|
||||
"Could not read environment relay configuration.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
@@ -658,10 +835,17 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
yield* setCliDesiredCloudLink(false);
|
||||
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"Could not remove environment relay configuration.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not remove environment relay configuration.",
|
||||
),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError(
|
||||
"Could not remove environment relay configuration.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
@@ -676,10 +860,17 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment cloud preferences.",
|
||||
),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment cloud preferences.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not persist environment cloud preferences.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
@@ -787,17 +978,34 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
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({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudHealthJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError(
|
||||
"Could not answer cloud health request.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not answer cloud health request.",
|
||||
),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError(
|
||||
"Could not answer cloud health request.",
|
||||
),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError(
|
||||
"Could not answer cloud health request.",
|
||||
),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"Could not answer cloud health request.",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("Could not answer cloud health request."),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
|
||||
@@ -908,17 +1116,38 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
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({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
ServerAuthCloudMintJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError(
|
||||
"Could not issue cloud connection credential.",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError(
|
||||
"Could not issue cloud connection credential.",
|
||||
),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError(
|
||||
"Could not issue cloud connection credential.",
|
||||
),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError(
|
||||
"Could not issue cloud connection credential.",
|
||||
),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"Could not issue cloud connection credential.",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError(
|
||||
"Could not issue cloud connection credential.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectHttpApiLayer = HttpApiBuilder.group(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Result from "effect/Result";
|
||||
|
||||
import {
|
||||
makeCloudCliOAuthConfig,
|
||||
@@ -89,27 +88,6 @@ it.effect("requires Clerk OAuth config when the server bundle has no injected va
|
||||
}).pipe(provideEnv({}), Effect.flip),
|
||||
);
|
||||
|
||||
it.effect("reports malformed Clerk publishable keys as typed configuration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* makeCloudCliOAuthConfig({
|
||||
clerkPublishableKeyFallback: "pk_test_not-base64!!",
|
||||
clerkCliOAuthClientIdFallback: "oauth_client_embedded",
|
||||
}).pipe(provideEnv({}), Effect.result);
|
||||
|
||||
assert.isTrue(Result.isFailure(result));
|
||||
if (Result.isFailure(result)) {
|
||||
assert.equal(result.failure.cause._tag, "SourceError");
|
||||
if (result.failure.cause._tag === "SourceError") {
|
||||
assert.equal(
|
||||
result.failure.cause.message,
|
||||
"Failed to derive Clerk Frontend API URL from the publishable key.",
|
||||
);
|
||||
assert.instanceOf(result.failure.cause.cause, Error);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("resolves relay client tracing from runtime config with build-time fallback", () => {
|
||||
const fallback = {
|
||||
tracesUrl: "https://embedded.example.test/v1/traces",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import * as Config from "effect/Config";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -132,29 +131,16 @@ export function makeCloudCliOAuthConfig({
|
||||
clerkCliOAuthClientIdFallback,
|
||||
),
|
||||
}).pipe(
|
||||
Config.mapOrFail(({ clerkPublishableKey, clientId }) =>
|
||||
Effect.try({
|
||||
try: () => clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey),
|
||||
catch: (cause) =>
|
||||
new Config.ConfigError(
|
||||
new ConfigProvider.SourceError({
|
||||
message: "Failed to derive Clerk Frontend API URL from the publishable key.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(clerkFrontendApiUrl) =>
|
||||
({
|
||||
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
|
||||
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
|
||||
clientId,
|
||||
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
|
||||
scopes: CLOUD_CLI_OAUTH_SCOPES,
|
||||
}) satisfies CloudCliOAuthConfig,
|
||||
),
|
||||
),
|
||||
),
|
||||
Config.map(({ clerkPublishableKey, clientId }) => {
|
||||
const clerkFrontendApiUrl = clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey);
|
||||
return {
|
||||
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
|
||||
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
|
||||
clientId,
|
||||
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
|
||||
scopes: CLOUD_CLI_OAUTH_SCOPES,
|
||||
} satisfies CloudCliOAuthConfig;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import * as Option from "effect/Option";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
@@ -220,44 +219,6 @@ describe("ProcessDiagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
code: 17,
|
||||
stdout: "partial process output",
|
||||
stderr: "process access denied",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ProcessDiagnosticsQueryFailedError",
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: process.cwd(),
|
||||
exitCode: 17,
|
||||
stdoutBytes: 22,
|
||||
stderrBytes: 21,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
|
||||
@@ -45,15 +45,10 @@ export class ProcessDiagnostics extends Context.Service<
|
||||
|
||||
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
|
||||
"ProcessDiagnosticsQueryTimeoutError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
},
|
||||
{ command: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
|
||||
return `Process diagnostics query '${this.command}' timed out.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,19 +56,12 @@ class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<Process
|
||||
"ProcessDiagnosticsQueryFailedError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutBytes: Schema.optional(Schema.Number),
|
||||
stderrBytes: Schema.optional(Schema.Number),
|
||||
stdoutTruncated: Schema.optional(Schema.Boolean),
|
||||
stderrTruncated: Schema.optional(Schema.Boolean),
|
||||
stderr: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
|
||||
return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
|
||||
return this.stderr?.trim() || `Failed to query process diagnostics with '${this.command}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,10 +76,7 @@ class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass
|
||||
|
||||
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
|
||||
"ProcessDiagnosticsNotDescendantError",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
serverPid: Schema.Number,
|
||||
},
|
||||
{ pid: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${this.pid} is not a live descendant of the T3 server.`;
|
||||
@@ -327,29 +312,20 @@ function makeResult(input: {
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly cwd: string;
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stdoutBytes: number;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderr: string;
|
||||
readonly stderrBytes: number;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const cwd = process.cwd();
|
||||
return yield* Effect.gen(function* () {
|
||||
const runProcess = Effect.fn("runProcess")(
|
||||
function* (input: { readonly command: string; readonly args: ReadonlyArray<string> }) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
|
||||
// shell mode would re-tokenize the PowerShell `-Command` payload (which
|
||||
// contains pipes) before PowerShell ever sees it.
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd,
|
||||
cwd: process.cwd(),
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
@@ -370,44 +346,36 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
|
||||
);
|
||||
|
||||
return {
|
||||
cwd,
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stdoutBytes: stdout.bytes,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderr: stderr.text,
|
||||
stderrBytes: stderr.bytes,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProcessOutput;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessDiagnosticsQueryTimeoutError({
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessDiagnosticsQueryTimeoutError({
|
||||
command: input.command,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: new ProcessDiagnosticsQueryFailedError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: new ProcessDiagnosticsQueryFailedError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
);
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
@@ -423,13 +391,7 @@ function readPosixProcessRows(): Effect.Effect<
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
stderr: result.stderr.trim() || "ps failed.",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
@@ -459,13 +421,7 @@ function readWindowsProcessRows(): Effect.Effect<
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "powershell.exe",
|
||||
argCount: 4,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
stderr: result.stderr.trim() || "PowerShell process query failed.",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
@@ -508,7 +464,6 @@ function assertDescendantPid(
|
||||
: Effect.fail(
|
||||
new ProcessDiagnosticsNotDescendantError({
|
||||
pid,
|
||||
serverPid: process.pid,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -111,7 +111,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
expect(Option.isNone(result.error)).toBe(true);
|
||||
@@ -171,7 +171,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
@@ -218,38 +218,11 @@ describe("ProcessResourceMonitor", () => {
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(36);
|
||||
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("exposes bounded failure diagnostics while retaining the exact cause", () =>
|
||||
Effect.sync(() => {
|
||||
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const cause = new Error("stderr included credential=secret-value");
|
||||
const failure = new ProcessResourceMonitor.ProcessResourceSamplingError({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
cause,
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples: [],
|
||||
readAt,
|
||||
readAtMs: DateTime.toEpochMillis(readAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: failure,
|
||||
});
|
||||
|
||||
expect(failure.cause).toBe(cause);
|
||||
expect(Option.getOrThrow(result.error)).toEqual({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "Failed to sample process resources (ProcessDiagnosticsQueryFailedError).",
|
||||
});
|
||||
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,8 @@
|
||||
import {
|
||||
ServerProcessResourceHistoryFailureTag,
|
||||
type ServerProcessResourceHistoryBucket,
|
||||
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
|
||||
type ServerProcessResourceHistoryInput,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProcessResourceHistorySummary,
|
||||
import type {
|
||||
ServerProcessResourceHistoryBucket,
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
ServerProcessResourceHistorySummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -12,7 +10,6 @@ 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 ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
@@ -34,21 +31,9 @@ export interface ProcessResourceSample {
|
||||
readonly isServerRoot: boolean;
|
||||
}
|
||||
|
||||
export class ProcessResourceSamplingError extends Schema.TaggedErrorClass<ProcessResourceSamplingError>()(
|
||||
"ProcessResourceSamplingError",
|
||||
{
|
||||
failureTag: ServerProcessResourceHistoryFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to sample process resources (${this.failureTag}).`;
|
||||
}
|
||||
}
|
||||
|
||||
interface MonitorState {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
readonly lastError: string | null;
|
||||
}
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
@@ -233,7 +218,7 @@ export function aggregateProcessResourceHistory(input: {
|
||||
readonly readAtMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
readonly lastError: string | null;
|
||||
}): ServerProcessResourceHistoryResult {
|
||||
const windowMs = Math.max(1_000, input.windowMs);
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
@@ -254,29 +239,13 @@ export function aggregateProcessResourceHistory(input: {
|
||||
totalCpuSecondsApprox,
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
|
||||
topProcesses,
|
||||
error: input.lastFailure
|
||||
? Option.some({
|
||||
failureTag: input.lastFailure.failureTag,
|
||||
message: input.lastFailure.message,
|
||||
})
|
||||
: Option.none(),
|
||||
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastFailure: null });
|
||||
|
||||
const recordSamplingFailure = (cause: {
|
||||
readonly _tag: ServerProcessResourceHistoryFailureTagType;
|
||||
}) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastFailure: new ProcessResourceSamplingError({
|
||||
failureTag: cause._tag,
|
||||
cause,
|
||||
}),
|
||||
}));
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
@@ -292,16 +261,15 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
yield* Ref.update(state, (current) => ({
|
||||
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
|
||||
lastFailure: null,
|
||||
lastError: null,
|
||||
}));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ProcessDiagnosticsQueryTimeoutError: recordSamplingFailure,
|
||||
ProcessDiagnosticsQueryFailedError: recordSamplingFailure,
|
||||
ProcessDiagnosticsServerProcessSignalError: recordSamplingFailure,
|
||||
ProcessDiagnosticsNotDescendantError: recordSamplingFailure,
|
||||
ProcessDiagnosticsSignalFailedError: recordSamplingFailure,
|
||||
}),
|
||||
Effect.catch((error: unknown) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
|
||||
@@ -319,7 +287,7 @@ export const make = Effect.gen(function* () {
|
||||
readAtMs,
|
||||
windowMs: input.windowMs,
|
||||
bucketMs: input.bucketMs,
|
||||
lastFailure: current.lastFailure,
|
||||
lastError: current.lastError,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
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";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerEnvironment from "./ServerEnvironment.ts";
|
||||
|
||||
const isServerEnvironmentIdPersistenceError = Schema.is(
|
||||
ServerEnvironment.ServerEnvironmentIdPersistenceError,
|
||||
);
|
||||
|
||||
const makeServerEnvironmentLayer = (baseDir: string) =>
|
||||
ServerEnvironment.layer.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
|
||||
|
||||
@@ -70,63 +68,62 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("structures persisted environment id filesystem failures", () =>
|
||||
it.effect("fails instead of overwriting a persisted id when reading the file errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-server-environment-error-test-",
|
||||
prefix: "t3-server-environment-read-error-test-",
|
||||
});
|
||||
const serverConfig = yield* makeServerConfig(baseDir);
|
||||
const environmentIdPath = serverConfig.environmentIdPath;
|
||||
const methodByOperation = {
|
||||
check: "exists",
|
||||
read: "readFileString",
|
||||
write: "writeFileString",
|
||||
} as const;
|
||||
yield* fileSystem.makeDirectory(NodePath.dirname(environmentIdPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
|
||||
const writeAttempts: string[] = [];
|
||||
const failingFileSystemLayer = FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(path === environmentIdPath),
|
||||
readFileString: (path) =>
|
||||
path === environmentIdPath
|
||||
? Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
)
|
||||
: Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "not found",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
writeFileString: (path) => {
|
||||
writeAttempts.push(path);
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
for (const operation of ["check", "read", "write"] as const) {
|
||||
const writeAttempts: string[] = [];
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: methodByOperation[operation],
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: environmentIdPath,
|
||||
});
|
||||
const failingFileSystemLayer = FileSystem.layerNoop({
|
||||
exists: () =>
|
||||
operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
|
||||
readFileString: () => Effect.fail(cause),
|
||||
writeFileString: (path) => {
|
||||
writeAttempts.push(path);
|
||||
return Effect.fail(cause);
|
||||
},
|
||||
});
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerEnvironment.layer.pipe(
|
||||
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
|
||||
),
|
||||
const exit = yield* Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerEnvironment.layer.pipe(
|
||||
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
),
|
||||
Effect.exit,
|
||||
);
|
||||
|
||||
expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
|
||||
if (!isServerEnvironmentIdPersistenceError(error)) {
|
||||
throw error;
|
||||
}
|
||||
expect(error.operation).toBe(operation);
|
||||
expect(error.environmentIdPath).toBe(environmentIdPath);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toBe(
|
||||
`Server environment ID ${operation} failed at '${environmentIdPath}'.`,
|
||||
);
|
||||
expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
|
||||
}
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(writeAttempts).toEqual([]);
|
||||
expect(yield* fileSystem.readFileString(environmentIdPath)).toBe(
|
||||
"persisted-environment-id\n",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -6,26 +6,12 @@ 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 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 ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
|
||||
"ServerEnvironmentIdPersistenceError",
|
||||
{
|
||||
operation: Schema.Literals(["check", "read", "write"]),
|
||||
environmentIdPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerEnvironment extends Context.Service<
|
||||
ServerEnvironment,
|
||||
{
|
||||
@@ -69,46 +55,22 @@ export const make = Effect.gen(function* () {
|
||||
const hostArchitecture = yield* HostProcessArchitecture;
|
||||
|
||||
const readPersistedEnvironmentId = Effect.gen(function* () {
|
||||
const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerEnvironmentIdPersistenceError({
|
||||
operation: "check",
|
||||
environmentIdPath: serverConfig.environmentIdPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const exists = yield* fileSystem
|
||||
.exists(serverConfig.environmentIdPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
|
||||
Effect.map((value) => value.trim()),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerEnvironmentIdPersistenceError({
|
||||
operation: "read",
|
||||
environmentIdPath: serverConfig.environmentIdPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const raw = yield* fileSystem
|
||||
.readFileString(serverConfig.environmentIdPath)
|
||||
.pipe(Effect.map((value) => value.trim()));
|
||||
|
||||
return raw.length > 0 ? raw : null;
|
||||
});
|
||||
|
||||
const persistEnvironmentId = (value: string) =>
|
||||
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerEnvironmentIdPersistenceError({
|
||||
operation: "write",
|
||||
environmentIdPath: serverConfig.environmentIdPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
|
||||
|
||||
const environmentIdRaw = yield* Effect.gen(function* () {
|
||||
const persisted = yield* readPersistedEnvironmentId;
|
||||
|
||||
@@ -138,7 +138,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command: "scutil",
|
||||
argumentCount: 2,
|
||||
args: ["--get", "ComputerName"],
|
||||
cause: new Error("spawn scutil ENOENT"),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -3377,18 +3377,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(errorMessage).toContain("Git command failed in GitVcsDriver.commit.commit");
|
||||
expect(errorMessage).not.toContain("hook: fail");
|
||||
expect(errorMessage).toContain("hook: fail");
|
||||
expect(events).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "hook_started",
|
||||
hookName: "pre-commit",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "hook_output",
|
||||
text: "hook: fail",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "action_failed",
|
||||
phase: "commit",
|
||||
|
||||
@@ -35,9 +35,8 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
import {
|
||||
annotateEnvironmentRequest,
|
||||
catchEnvironmentAuthenticationErrors,
|
||||
failEnvironmentScopeRequired,
|
||||
failEnvironmentAuthInvalid,
|
||||
failEnvironmentInternal,
|
||||
} from "./auth/http.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
|
||||
@@ -80,13 +79,8 @@ const authenticateRawRouteWithScope = (
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
);
|
||||
if (!session.scopes.includes(scope)) {
|
||||
return yield* failEnvironmentScopeRequired(scope);
|
||||
|
||||
@@ -49,62 +49,6 @@ it("normalizes empty successful notification responses to accepted", () => {
|
||||
expect(resultResponse.status).toBe(200);
|
||||
});
|
||||
|
||||
it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
|
||||
expect(snapshot.isError).toBe(true);
|
||||
expect(snapshot.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);
|
||||
expect(snapshot.structuredContent).toEqual({
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
operation: "snapshot",
|
||||
failureCount: 1,
|
||||
},
|
||||
});
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("terminates HTTP MCP sessions with DELETE", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -88,37 +88,6 @@ const McpAuthMiddlewareLive = HttpRouter.middleware<{
|
||||
provides: McpInvocationContext.McpInvocationContext;
|
||||
}>()(makeMcpAuthMiddleware).layer;
|
||||
|
||||
const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
|
||||
if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
|
||||
return Effect.failCause(cause).pipe(Effect.orDie);
|
||||
}
|
||||
const failures = cause.reasons.filter(Cause.isFailReason);
|
||||
const firstFailure = failures[0]?.error;
|
||||
const errorTag =
|
||||
typeof firstFailure === "object" &&
|
||||
firstFailure !== null &&
|
||||
"_tag" in firstFailure &&
|
||||
typeof firstFailure._tag === "string"
|
||||
? firstFailure._tag
|
||||
: "PreviewSnapshotError";
|
||||
const result = new McpSchema.CallToolResult({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
_tag: errorTag,
|
||||
operation: "snapshot",
|
||||
failureCount: failures.length,
|
||||
},
|
||||
},
|
||||
content: [{ type: "text", text: "Preview snapshot failed." }],
|
||||
});
|
||||
return Effect.logWarning("preview snapshot failed", {
|
||||
operation: "snapshot",
|
||||
errorTag,
|
||||
failureCount: failures.length,
|
||||
}).pipe(Effect.as(result));
|
||||
};
|
||||
|
||||
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
@@ -153,8 +122,12 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
|
||||
Effect.flatMap(Effect.fromOption),
|
||||
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: previewSnapshotFailure,
|
||||
Effect.matchCause({
|
||||
onFailure: (cause) =>
|
||||
new McpSchema.CallToolResult({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: Cause.pretty(cause) }],
|
||||
}),
|
||||
onSuccess: ({ encodedResult }) => {
|
||||
const snapshot = encodedResult as {
|
||||
readonly screenshot: {
|
||||
@@ -174,20 +147,18 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
|
||||
height: screenshot.height,
|
||||
},
|
||||
};
|
||||
return Effect.succeed(
|
||||
new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent: metadata,
|
||||
content: [
|
||||
{ type: "text", text: JSON.stringify(metadata) },
|
||||
{
|
||||
type: "image",
|
||||
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
|
||||
mimeType: screenshot.mimeType,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent: metadata,
|
||||
content: [
|
||||
{ type: "text", text: JSON.stringify(metadata) },
|
||||
{
|
||||
type: "image",
|
||||
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
|
||||
mimeType: screenshot.mimeType,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationUnavailableError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type PreviewAutomationOwner,
|
||||
@@ -61,95 +59,6 @@ it.effect("atomically registers a connected owner and correlates its response",
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
const locator = "role=button[name='request-secret']";
|
||||
const remoteMessage = "Unexpected token near remote-secret.";
|
||||
const remoteError = {
|
||||
_tag: "PreviewAutomationInvalidSelectorError",
|
||||
message: remoteMessage,
|
||||
detail: { selector: "role=button[name='remote-secret']" },
|
||||
} as const;
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({
|
||||
scope,
|
||||
operation: "click",
|
||||
input: { locator },
|
||||
timeoutMs: 1_234,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationInvalidSelectorError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "click",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
providerSessionId: scope.providerSessionId,
|
||||
providerInstanceId: scope.providerInstanceId,
|
||||
clientId: "client-1",
|
||||
requestId: "preview-0",
|
||||
tabId: "tab-1",
|
||||
timeoutMs: 1_234,
|
||||
selectorKind: "locator",
|
||||
selectorLength: locator.length,
|
||||
remoteTag: "PreviewAutomationInvalidSelectorError",
|
||||
remoteMessageLength: remoteMessage.length,
|
||||
remoteDetailKind: "object",
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Preview automation click received an invalid locator (${locator.length} characters).`,
|
||||
);
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(error.cause).toBe(remoteError);
|
||||
expect("selector" in error).toBe(false);
|
||||
expect("remoteMessage" in error).toBe(false);
|
||||
expect("remoteDetail" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("distinguishes malformed remote failures", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: false }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {}, timeoutMs: 2_000 })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
providerSessionId: scope.providerSessionId,
|
||||
providerInstanceId: scope.providerInstanceId,
|
||||
clientId: "client-1",
|
||||
requestId: "preview-0",
|
||||
timeoutMs: 2_000,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
@@ -157,13 +66,6 @@ it.effect("rejects calls when no focused owner exists", () =>
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
providerSessionId: scope.providerSessionId,
|
||||
providerInstanceId: scope.providerInstanceId,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -260,17 +162,7 @@ it.effect("fails requests assigned to a browser stream when that stream reconnec
|
||||
const _replacementRequests = yield* broker.connect(makeOwner());
|
||||
|
||||
const error = yield* Fiber.join(pending);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
providerSessionId: scope.providerSessionId,
|
||||
providerInstanceId: scope.providerInstanceId,
|
||||
clientId: "client-1",
|
||||
requestId: "preview-0",
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import {
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnavailableError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
@@ -66,21 +62,6 @@ interface ClientConnection {
|
||||
interface PendingRequest {
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
interface PreviewAutomationRequestErrorContext {
|
||||
readonly operation: PreviewAutomationOperation;
|
||||
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
|
||||
readonly threadId: McpInvocationContext.McpInvocationScope["threadId"];
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
|
||||
readonly clientId: string;
|
||||
readonly requestId: string;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly timeoutMs: number;
|
||||
readonly selectorKind?: "locator" | "selector";
|
||||
readonly selectorLength?: number;
|
||||
}
|
||||
|
||||
interface BrokerState {
|
||||
@@ -90,104 +71,48 @@ interface BrokerState {
|
||||
readonly requestSequence: number;
|
||||
}
|
||||
|
||||
const selectorDiagnosticsFromInput = (
|
||||
input: unknown,
|
||||
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
|
||||
if (typeof input !== "object" || input === null) return {};
|
||||
if ("locator" in input && typeof input.locator === "string") {
|
||||
return { selectorKind: "locator", selectorLength: input.locator.length };
|
||||
}
|
||||
if ("selector" in input && typeof input.selector === "string") {
|
||||
return { selectorKind: "selector", selectorLength: input.selector.length };
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
|
||||
|
||||
function remoteDetailKind(detail: unknown): RemoteDetailKind {
|
||||
if (detail === null) return "null";
|
||||
if (Array.isArray(detail)) return "array";
|
||||
switch (typeof detail) {
|
||||
case "string":
|
||||
return "string";
|
||||
case "number":
|
||||
return "number";
|
||||
case "boolean":
|
||||
return "boolean";
|
||||
default:
|
||||
return "object";
|
||||
}
|
||||
}
|
||||
|
||||
const classifyResponseError = (
|
||||
context: PreviewAutomationRequestErrorContext,
|
||||
const makeResponseError = (
|
||||
error: NonNullable<PreviewAutomationResponse["error"]>,
|
||||
): PreviewAutomationError => {
|
||||
const remoteDiagnostics = {
|
||||
remoteTag: error._tag,
|
||||
remoteMessageLength: error.message.length,
|
||||
...(error.detail === undefined ? {} : { remoteDetailKind: remoteDetailKind(error.detail) }),
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
return new PreviewAutomationNoFocusedOwnerError({ message: error.message });
|
||||
case "PreviewAutomationUnsupportedClientError":
|
||||
return new PreviewAutomationUnsupportedClientError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
return new PreviewAutomationUnsupportedClientError({ message: error.message });
|
||||
case "PreviewAutomationTabNotFoundError":
|
||||
return new PreviewAutomationTabNotFoundError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
return new PreviewAutomationTabNotFoundError({ message: error.message });
|
||||
case "PreviewAutomationTimeoutError":
|
||||
return new PreviewAutomationTimeoutError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
return new PreviewAutomationTimeoutError({ message: error.message });
|
||||
case "PreviewAutomationControlInterruptedError":
|
||||
return new PreviewAutomationControlInterruptedError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
return new PreviewAutomationControlInterruptedError({ message: error.message });
|
||||
case "PreviewAutomationInvalidSelectorError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
return new PreviewAutomationInvalidSelectorError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
message: error.message,
|
||||
selector:
|
||||
detail && "selector" in detail && typeof detail.selector === "string"
|
||||
? detail.selector
|
||||
: "",
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationResultTooLargeError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
const maximumBytes =
|
||||
detail &&
|
||||
"maximumBytes" in detail &&
|
||||
typeof detail.maximumBytes === "number" &&
|
||||
Number.isInteger(detail.maximumBytes) &&
|
||||
detail.maximumBytes > 0
|
||||
? detail.maximumBytes
|
||||
: undefined;
|
||||
return new PreviewAutomationResultTooLargeError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
...(maximumBytes === undefined ? {} : { maximumBytes }),
|
||||
message: error.message,
|
||||
maximumBytes:
|
||||
detail && "maximumBytes" in detail && typeof detail.maximumBytes === "number"
|
||||
? detail.maximumBytes
|
||||
: 64_000,
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationUnavailableError":
|
||||
return new PreviewAutomationRemoteUnavailableError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
return new PreviewAutomationUnavailableError({ message: error.message });
|
||||
default:
|
||||
return new PreviewAutomationExecutionError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
message: error.message,
|
||||
detail: error.detail,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -223,8 +148,13 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
toFail,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
({ deferred }) =>
|
||||
Deferred.fail(
|
||||
deferred,
|
||||
new PreviewAutomationUnavailableError({
|
||||
message: "The preview automation client disconnected.",
|
||||
}),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Queue.shutdown(queue);
|
||||
@@ -298,8 +228,10 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
yield* Deferred.fail(
|
||||
pending.deferred,
|
||||
response.error
|
||||
? classifyResponseError(pending.context, response.error)
|
||||
: new PreviewAutomationMalformedResponseError(pending.context),
|
||||
? makeResponseError(response.error)
|
||||
: new PreviewAutomationExecutionError({
|
||||
message: "Preview automation failed without an error payload.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -318,60 +250,28 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
|
||||
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
|
||||
if (!owner) {
|
||||
const disconnectedOwner = candidates[0];
|
||||
if (disconnectedOwner) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: disconnectedOwner.clientId,
|
||||
if (candidates.length > 0) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: "The browser host is not connected.",
|
||||
});
|
||||
}
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
message: "No desktop browser host is available for this thread.",
|
||||
});
|
||||
}
|
||||
const connection = current.clients.get(owner.clientId);
|
||||
if (!connection) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: "The browser host is not connected.",
|
||||
});
|
||||
}
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = `preview-${next.requestSequence}`;
|
||||
const tabId = input.tabId ?? owner.tabId ?? undefined;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
] as const;
|
||||
pending.set(requestId, { queue: connection.queue, deferred });
|
||||
return [requestId, { ...next, pending, requestSequence: next.requestSequence + 1 }] as const;
|
||||
});
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
@@ -383,21 +283,24 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
tabId: input.tabId ?? owner.tabId ?? undefined,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
if (Option.isSome(completion)) {
|
||||
return (yield* completion.value) as A;
|
||||
}
|
||||
return yield* new PreviewAutomationRequestQueueClosedError(requestContext);
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: "The preview automation client is no longer accepting requests.",
|
||||
});
|
||||
}
|
||||
const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(timeoutMs));
|
||||
return yield* Option.match(result, {
|
||||
onNone: () => Effect.fail(new PreviewAutomationTimeoutError(requestContext)),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new PreviewAutomationTimeoutError({
|
||||
message: `Preview automation timed out after ${timeoutMs}ms.`,
|
||||
}),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value as A),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,8 +10,8 @@ import { AuthEnvironmentScopes } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
type AuthPairingLinkRepositoryError,
|
||||
PersistenceDecodeError,
|
||||
PersistenceSqlError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
export const AuthPairingLinkRecord = Schema.Struct({
|
||||
@@ -90,8 +90,8 @@ export class AuthPairingLinkRepository extends Context.Service<
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): AuthPairingLinkRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
|
||||
: new PersistenceSqlError({ operation: sqlOperation, cause });
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
|
||||
@@ -15,8 +15,8 @@ import {
|
||||
|
||||
import {
|
||||
type AuthSessionRepositoryError,
|
||||
PersistenceDecodeError,
|
||||
PersistenceSqlError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
export const AuthSessionClientMetadataRecord = Schema.Struct({
|
||||
@@ -146,8 +146,8 @@ function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionReco
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): AuthSessionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
|
||||
: new PersistenceSqlError({ operation: sqlOperation, cause });
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { PersistenceDecodeError, PersistenceSqlError } from "./Errors.ts";
|
||||
|
||||
const decodeRuntimePayload = Schema.decodeUnknownEffect(
|
||||
Schema.Struct({
|
||||
runtimePayload: Schema.Struct({
|
||||
attempt: Schema.Number,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
it("keeps SQL operation context without a tautological detail", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const error = new PersistenceSqlError({
|
||||
operation: "AuthSessionRepository.list:query",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.equal(error.operation, "AuthSessionRepository.list:query");
|
||||
assert.equal(error.detail, undefined);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal(error.message, "SQL error in AuthSessionRepository.list:query");
|
||||
});
|
||||
|
||||
it.effect("maps schema errors without copying rejected payloads into diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
const rejectedPayload = "runtime-payload-secret-sentinel";
|
||||
const cause = yield* Effect.flip(
|
||||
decodeRuntimePayload({
|
||||
runtimePayload: {
|
||||
attempt: rejectedPayload,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const error = PersistenceDecodeError.fromSchemaError(
|
||||
"ProviderSessionRuntimeRepository.list:decodeRows",
|
||||
cause,
|
||||
);
|
||||
|
||||
assert.equal(error.operation, "ProviderSessionRuntimeRepository.list:decodeRows");
|
||||
assert.equal(error.cause, cause);
|
||||
assert.notInclude(error.issue, rejectedPayload);
|
||||
assert.notInclude(error.message, rejectedPayload);
|
||||
assert.include(error.issue, "InvalidType");
|
||||
}),
|
||||
);
|
||||
@@ -1,20 +1,6 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
|
||||
function summarizeSchemaIssue(issue: SchemaIssue.Issue): string {
|
||||
switch (issue._tag) {
|
||||
case "Filter":
|
||||
case "Encoding":
|
||||
case "Pointer":
|
||||
return `${issue._tag}(${summarizeSchemaIssue(issue.issue)})`;
|
||||
case "Composite":
|
||||
case "AnyOf":
|
||||
return `${issue._tag}(${issue.issues.map(summarizeSchemaIssue).join(",")})`;
|
||||
default:
|
||||
return issue._tag;
|
||||
}
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// Core Persistence Errors
|
||||
// ===============================
|
||||
@@ -23,14 +9,12 @@ export class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlE
|
||||
"PersistenceSqlError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.optional(Schema.String),
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail === undefined
|
||||
? `SQL error in ${this.operation}`
|
||||
: `SQL error in ${this.operation}: ${this.detail}`;
|
||||
return `SQL error in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,14 +26,6 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
static fromSchemaError(operation: string, cause: Schema.SchemaError): PersistenceDecodeError {
|
||||
return new PersistenceDecodeError({
|
||||
operation,
|
||||
issue: summarizeSchemaIssue(cause.issue),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Decode error in ${this.operation}: ${this.issue}`;
|
||||
}
|
||||
@@ -57,7 +33,6 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
|
||||
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
|
||||
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
|
||||
|
||||
// Kept for orchestration/projection call sites, which are being revamped separately.
|
||||
export function toPersistenceSqlError(operation: string) {
|
||||
return (cause: unknown): PersistenceSqlError =>
|
||||
new PersistenceSqlError({
|
||||
@@ -67,10 +42,22 @@ export function toPersistenceSqlError(operation: string) {
|
||||
});
|
||||
}
|
||||
|
||||
// Kept for orchestration/projection call sites, which are being revamped separately.
|
||||
export function toPersistenceDecodeError(operation: string) {
|
||||
return (cause: Schema.SchemaError): PersistenceDecodeError =>
|
||||
PersistenceDecodeError.fromSchemaError(operation, cause);
|
||||
return (error: Schema.SchemaError): PersistenceDecodeError =>
|
||||
new PersistenceDecodeError({
|
||||
operation,
|
||||
issue: SchemaIssue.makeFormatterDefault()(error.issue),
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export function toPersistenceDecodeCauseError(operation: string) {
|
||||
return (cause: unknown): PersistenceDecodeError =>
|
||||
new PersistenceDecodeError({
|
||||
operation,
|
||||
issue: `Failed to execute ${operation}`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
export const isPersistenceError = (u: unknown) =>
|
||||
|
||||
@@ -16,9 +16,9 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
PersistenceDecodeError,
|
||||
PersistenceSqlError,
|
||||
type ProviderSessionRuntimeRepositoryError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
/**
|
||||
@@ -117,8 +117,8 @@ const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
|
||||
: new PersistenceSqlError({ operation: sqlOperation, cause });
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -235,10 +235,9 @@ export const make = Effect.gen(function* () {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
PersistenceDecodeError.fromSchemaError(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
|
||||
cause,
|
||||
),
|
||||
),
|
||||
Effect.map((runtime) => Option.some(runtime)),
|
||||
@@ -260,11 +259,8 @@ export const make = Effect.gen(function* () {
|
||||
rows,
|
||||
(row) =>
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
PersistenceDecodeError.fromSchemaError(
|
||||
"ProviderSessionRuntimeRepository.list:rowToRuntime",
|
||||
cause,
|
||||
),
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"),
|
||||
),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
@@ -277,11 +273,7 @@ export const make = Effect.gen(function* () {
|
||||
) =>
|
||||
deleteRuntimeByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistenceSqlError({
|
||||
operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
|
||||
cause,
|
||||
}),
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
|
||||
import { PreviewUrlNormalizationError } from "@t3tools/shared/preview";
|
||||
import { Effect, PubSub } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
@@ -84,31 +83,6 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(manager.open({ threadId, url: " " }));
|
||||
expect(error._tag).toBe("PreviewInvalidUrlError");
|
||||
expect(error).toMatchObject({ inputLength: 3, reason: "empty" });
|
||||
expect(error).not.toHaveProperty("rawUrl");
|
||||
expect(error.cause).toBeInstanceOf(PreviewUrlNormalizationError);
|
||||
expect((error.cause as PreviewUrlNormalizationError).reason).toBe("empty");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves URL parser failures as the invalid URL cause chain", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const rawUrl = "https://user:[email protected]:bad/path?access_token=secret#fragment";
|
||||
const error = yield* Effect.flip(manager.open({ threadId, url: rawUrl }));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
inputLength: rawUrl.length,
|
||||
reason: "parse",
|
||||
protocol: "https:",
|
||||
});
|
||||
expect(error).not.toHaveProperty("rawUrl");
|
||||
expect(error.cause).toBeInstanceOf(PreviewUrlNormalizationError);
|
||||
const normalizationError = error.cause as PreviewUrlNormalizationError;
|
||||
expect(normalizationError.cause).toBeInstanceOf(Error);
|
||||
expect(error.message).not.toContain((normalizationError.cause as Error).message);
|
||||
expect(error.message).not.toMatch(/user|password|access_token|secret|fragment/);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -24,9 +24,9 @@ import {
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
isPreviewUrlNormalizationError,
|
||||
newPreviewTabId,
|
||||
normalizePreviewUrl,
|
||||
PreviewUrlNormalizationError,
|
||||
} from "@t3tools/shared/preview";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -82,22 +82,16 @@ const sessionsForThread = (
|
||||
const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
|
||||
Effect.try({
|
||||
try: () => normalizePreviewUrl(rawUrl),
|
||||
catch: (cause) => {
|
||||
if (isPreviewUrlNormalizationError(cause)) {
|
||||
return new PreviewInvalidUrlError({
|
||||
inputLength: cause.inputLength,
|
||||
reason: cause.reason,
|
||||
protocol: cause.protocol,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new PreviewInvalidUrlError({
|
||||
inputLength: rawUrl.length,
|
||||
reason: "unexpected",
|
||||
cause,
|
||||
});
|
||||
},
|
||||
catch: (cause) =>
|
||||
new PreviewInvalidUrlError({
|
||||
rawUrl,
|
||||
detail:
|
||||
cause instanceof PreviewUrlNormalizationError
|
||||
? cause.detail
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: String(cause),
|
||||
}),
|
||||
});
|
||||
|
||||
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
|
||||
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user