Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7849fa702 |
No files matched your search
@@ -46,49 +46,14 @@ describe("ElectronShell", () => {
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves safe URL context and cause when Electron rejects openExternal", () =>
|
||||
it.effect("returns false when Electron rejects openExternal", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("open failed");
|
||||
openExternalMock.mockRejectedValue(cause);
|
||||
const externalUrl =
|
||||
"HTTPS://user:[email protected]:443/signed-secret-token/path?access_token=secret#fragment";
|
||||
openExternalMock.mockRejectedValue(new Error("open failed"));
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const error = yield* Effect.flip(electronShell.openExternal(externalUrl));
|
||||
const result = yield* electronShell.openExternal("https://example.com/path");
|
||||
|
||||
assert.instanceOf(error, ElectronShell.ElectronShellOpenExternalError);
|
||||
assert.isTrue(ElectronShell.isElectronShellError(error));
|
||||
assert.strictEqual(error.urlHostname, "example.com");
|
||||
assert.strictEqual(error.urlLength, externalUrl.length);
|
||||
assert.strictEqual(error.urlProtocol, "https:");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notProperty(error, "externalUrl");
|
||||
assert.notProperty(error, "requestTarget");
|
||||
assert.notMatch(
|
||||
error.message,
|
||||
/user|password|signed-secret-token|path|access_token|secret|fragment/,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves non-sensitive clipboard context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("clipboard failed");
|
||||
writeTextMock.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const error = yield* Effect.flip(electronShell.copyText("secret text"));
|
||||
|
||||
assert.instanceOf(error, ElectronShell.ElectronShellCopyTextError);
|
||||
assert.isTrue(ElectronShell.isElectronShellError(error));
|
||||
assert.strictEqual(error.textLength, 11);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "11 characters");
|
||||
assert.notInclude(error.message, "secret text");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.equal(result, false);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,47 +1,12 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
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 SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
|
||||
|
||||
export class ElectronShellOpenExternalError extends Schema.TaggedErrorClass<ElectronShellOpenExternalError>()(
|
||||
"ElectronShellOpenExternalError",
|
||||
{
|
||||
urlHostname: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
urlProtocol: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to open external URL for ${this.urlHostname} (${this.urlProtocol}, input length ${this.urlLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronShellCopyTextError extends Schema.TaggedErrorClass<ElectronShellCopyTextError>()(
|
||||
"ElectronShellCopyTextError",
|
||||
{
|
||||
textLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to copy ${this.textLength} characters to the clipboard.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronShellError = Schema.Union([
|
||||
ElectronShellOpenExternalError,
|
||||
ElectronShellCopyTextError,
|
||||
]);
|
||||
export type ElectronShellError = typeof ElectronShellError.Type;
|
||||
export const isElectronShellError = Schema.is(ElectronShellError);
|
||||
|
||||
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
if (typeof rawUrl !== "string") {
|
||||
return Option.none();
|
||||
@@ -55,46 +20,29 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
}
|
||||
}
|
||||
|
||||
function describeExternalUrl(externalUrl: string, inputLength: number) {
|
||||
const diagnostics = getUrlDiagnostics(externalUrl);
|
||||
return {
|
||||
urlHostname: diagnostics.hostname ?? "",
|
||||
urlLength: inputLength,
|
||||
urlProtocol: diagnostics.protocol ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export class ElectronShell extends Context.Service<
|
||||
ElectronShell,
|
||||
{
|
||||
readonly openExternal: (
|
||||
rawUrl: unknown,
|
||||
) => Effect.Effect<boolean, ElectronShellOpenExternalError>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void, ElectronShellCopyTextError>;
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronShell") {}
|
||||
|
||||
export const make = ElectronShell.of({
|
||||
openExternal: (rawUrl) => {
|
||||
const inputLength = typeof rawUrl === "string" ? rawUrl.length : 0;
|
||||
|
||||
return Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
openExternal: (rawUrl) =>
|
||||
Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
onNone: () => Effect.succeed(false),
|
||||
onSome: (externalUrl) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.shell.openExternal(externalUrl),
|
||||
catch: (cause) =>
|
||||
new ElectronShellOpenExternalError({
|
||||
...describeExternalUrl(externalUrl, inputLength),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.as(true)),
|
||||
});
|
||||
},
|
||||
Effect.promise(() =>
|
||||
Electron.shell.openExternal(externalUrl).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
),
|
||||
}),
|
||||
copyText: (text) =>
|
||||
Effect.try({
|
||||
try: () => Electron.clipboard.writeText(text),
|
||||
catch: (cause) => new ElectronShellCopyTextError({ textLength: text.length, cause }),
|
||||
Effect.sync(() => {
|
||||
Electron.clipboard.writeText(text);
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
|
||||
|
||||
@@ -1,28 +1,16 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { SshHttpBridgeError, SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
DesktopSshEnvironmentRequestError,
|
||||
ensureSshEnvironment,
|
||||
fetchSshEnvironmentDescriptor,
|
||||
} from "./sshEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
|
||||
|
||||
const decodeDesktopSshEnvironmentEnsureResult = Schema.decodeUnknownEffect(
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
);
|
||||
|
||||
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
|
||||
return HttpClientResponse.fromWeb(
|
||||
@@ -46,44 +34,6 @@ function makeHttpClientLayer(
|
||||
}
|
||||
|
||||
describe("SSH environment IPC", () => {
|
||||
it.effect("encodes password prompt cancellations with structured context and their cause", () => {
|
||||
const promptCause = new DesktopSshPasswordPrompts.DesktopSshPromptWindowClosedError({
|
||||
requestId: "prompt-1",
|
||||
destination: "[email protected]",
|
||||
});
|
||||
const cause = new SshPasswordPromptError({
|
||||
message: promptCause.message,
|
||||
cause: promptCause,
|
||||
});
|
||||
const layer = Layer.succeed(
|
||||
DesktopSshEnvironment.DesktopSshEnvironment,
|
||||
DesktopSshEnvironment.DesktopSshEnvironment.of({
|
||||
discoverHosts: () => Effect.die("unexpected host discovery"),
|
||||
ensureEnvironment: () => Effect.fail(cause),
|
||||
disconnectEnvironment: () => Effect.die("unexpected disconnect"),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const encoded = yield* ensureSshEnvironment.handler({
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.test",
|
||||
username: "developer",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
const error = yield* decodeDesktopSshEnvironmentEnsureResult(encoded);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPromptCancellationError);
|
||||
assert.equal(error.reason, "window-closed");
|
||||
assert.equal(error.requestId, "prompt-1");
|
||||
assert.equal(error.destination, "[email protected]");
|
||||
assert.instanceOf(error.cause, Error);
|
||||
assert.instanceOf(error.cause.cause, Error);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("fetches and decodes the remote environment descriptor", () => {
|
||||
const requestUrls: string[] = [];
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteWebSocketTicket,
|
||||
isRemoteEnvironmentAuthUndeclaredStatusError,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
type RemoteEnvironmentAuthError,
|
||||
} from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
DesktopSshEnvironmentTargetSchema,
|
||||
DesktopSshHttpBaseUrlInputSchema,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
DesktopSshPasswordPromptCancelledType,
|
||||
DesktopSshPasswordPromptResolutionInputSchema,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
EnvironmentInternalError,
|
||||
@@ -45,13 +45,6 @@ type DesktopSshEnvironmentRequestOperation =
|
||||
|
||||
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
|
||||
|
||||
const desktopSshPasswordPromptCancellationReasons = {
|
||||
DesktopSshPromptCancelledError: "user-cancelled",
|
||||
DesktopSshPromptWindowClosedError: "window-closed",
|
||||
DesktopSshPromptServiceStoppedError: "service-stopped",
|
||||
DesktopSshPromptTimedOutError: "timed-out",
|
||||
} as const;
|
||||
|
||||
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
|
||||
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
|
||||
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
|
||||
@@ -59,7 +52,10 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro
|
||||
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
|
||||
|
||||
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
|
||||
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || cause instanceof SshHttpBridgeError) {
|
||||
if (
|
||||
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
|
||||
cause instanceof SshHttpBridgeError
|
||||
) {
|
||||
return cause.status ?? null;
|
||||
}
|
||||
if (isEnvironmentRequestInvalidError(cause)) {
|
||||
@@ -131,19 +127,14 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
}) {
|
||||
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
|
||||
return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
|
||||
Effect.catchTags({
|
||||
SshPasswordPromptError: (error) =>
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
|
||||
? Effect.succeed(
|
||||
new DesktopSshPasswordPromptCancellationError({
|
||||
reason: desktopSshPasswordPromptCancellationReasons[error.cause._tag],
|
||||
requestId: error.cause.requestId,
|
||||
destination: error.cause.destination,
|
||||
cause: error,
|
||||
}),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
|
||||
? Effect.succeed({
|
||||
type: DesktopSshPasswordPromptCancelledType,
|
||||
message: error.message,
|
||||
})
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
+12
-15
@@ -1,31 +1,28 @@
|
||||
import {
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
DesktopSshPasswordPromptCancellationErrorTag,
|
||||
type DesktopBridge,
|
||||
type DesktopPreviewPointerEvent,
|
||||
type DesktopPreviewRecordingFrame,
|
||||
type DesktopPreviewTabState,
|
||||
import type {
|
||||
DesktopBridge,
|
||||
DesktopPreviewPointerEvent,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewTabState,
|
||||
} from "@t3tools/contracts";
|
||||
import { exposeClerkBridge } from "@clerk/electron/preload";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
|
||||
exposeClerkBridge({ passkeys: true });
|
||||
|
||||
const decodeDesktopSshPasswordPromptCancellationError = Schema.decodeUnknownSync(
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
);
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"_tag" in result &&
|
||||
result._tag === DesktopSshPasswordPromptCancellationErrorTag
|
||||
"type" in result &&
|
||||
result.type === IpcChannels.SSH_PASSWORD_PROMPT_CANCELLED_RESULT
|
||||
) {
|
||||
throw decodeDesktopSshPasswordPromptCancellationError(result);
|
||||
const message =
|
||||
"message" in result && typeof result.message === "string"
|
||||
? result.message
|
||||
: "SSH authentication cancelled.";
|
||||
throw new Error(message);
|
||||
}
|
||||
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
|
||||
}
|
||||
|
||||
@@ -75,9 +75,7 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
|
||||
export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is SshPasswordPromptError & {
|
||||
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
|
||||
} {
|
||||
): error is SshPasswordPromptError {
|
||||
return (
|
||||
error instanceof SshPasswordPromptError &&
|
||||
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
|
||||
|
||||
@@ -226,9 +226,7 @@ export const make = Effect.gen(function* () {
|
||||
{
|
||||
label: "Copy Link",
|
||||
click: () => {
|
||||
void runPromise(
|
||||
electronShell.copyText(params.linkURL).pipe(Effect.ignore({ log: true })),
|
||||
);
|
||||
void runPromise(electronShell.copyText(params.linkURL));
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
@@ -255,7 +253,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
window.webContents.setWindowOpenHandler(({ url }) => {
|
||||
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
|
||||
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
|
||||
void runPromise(electronShell.openExternal(url));
|
||||
}
|
||||
return { action: "deny" };
|
||||
});
|
||||
@@ -271,7 +269,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
event.preventDefault();
|
||||
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
|
||||
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
|
||||
void runPromise(electronShell.openExternal(url));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -3,10 +3,7 @@ import {
|
||||
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -18,38 +15,31 @@ import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
|
||||
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
|
||||
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
|
||||
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
|
||||
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
|
||||
return yield* decodeConnectionCatalogDocument(raw).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "decode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => catalogError("decode", cause),
|
||||
});
|
||||
return yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
|
||||
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
|
||||
});
|
||||
|
||||
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
|
||||
catalog: ConnectionCatalogDocumentType,
|
||||
) {
|
||||
return yield* encodeConnectionCatalogDocument(catalog).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "encode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
|
||||
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
|
||||
return JSON.stringify(encoded);
|
||||
});
|
||||
|
||||
interface CatalogStore {
|
||||
@@ -77,21 +67,12 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
|
||||
legacyRaw === null || legacyRaw.trim() === ""
|
||||
? EMPTY_CONNECTION_CATALOG_DOCUMENT
|
||||
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "migrate",
|
||||
backend: "legacy-migration",
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) => catalogError("migrate", cause)),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
|
||||
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
|
||||
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
|
||||
),
|
||||
}),
|
||||
);
|
||||
if (legacyRaw !== null && legacyRaw.trim() !== "") {
|
||||
const encoded = yield* encodeCatalog(catalog);
|
||||
@@ -110,13 +91,12 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
|
||||
let catalog: ConnectionCatalogDocumentType;
|
||||
if (raw !== null && raw.trim() !== "") {
|
||||
catalog = yield* decodeCatalog(raw).pipe(
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
catalog = yield* loadLegacyCatalog();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { LegacyConnectionMigrationError, migrateLegacyConnectionCatalog } from "./migration";
|
||||
import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
|
||||
describe("migrateLegacyConnectionCatalog", () => {
|
||||
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
|
||||
@@ -75,28 +75,4 @@ describe("migrateLegacyConnectionCatalog", () => {
|
||||
expect(catalog.targets).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves parse failures with a stable structural error", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* migrateLegacyConnectionCatalog("{not-json").pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
|
||||
expect(error.stage).toBe("parse");
|
||||
expect(error.cause).toBeInstanceOf(SyntaxError);
|
||||
expect(error.message).toBe("Could not parse the legacy mobile connection catalog.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("distinguishes catalog decoding failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* migrateLegacyConnectionCatalog('{"connections":"invalid"}').pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
|
||||
expect(error.stage).toBe("decode");
|
||||
expect(error.cause).toBeDefined();
|
||||
expect(error.message).toBe("Could not decode the legacy mobile connection catalog.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -36,14 +36,9 @@ const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnecti
|
||||
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
|
||||
"LegacyConnectionMigrationError",
|
||||
{
|
||||
stage: Schema.Literals(["parse", "decode"]),
|
||||
cause: Schema.Defect(),
|
||||
message: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not ${this.stage} the legacy mobile connection catalog.`;
|
||||
}
|
||||
}
|
||||
) {}
|
||||
|
||||
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
|
||||
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
|
||||
@@ -97,10 +92,18 @@ export const migrateLegacyConnectionCatalog = Effect.fn(
|
||||
)(function* (raw: string) {
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => new LegacyConnectionMigrationError({ stage: "parse", cause }),
|
||||
catch: (cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
|
||||
Effect.mapError((cause) => new LegacyConnectionMigrationError({ stage: "decode", cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
|
||||
|
||||
@@ -100,8 +100,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
detail: "Could not read the T3 Cloud session token.",
|
||||
cause: error,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -127,8 +126,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: "Could not load the mobile device identity.",
|
||||
cause,
|
||||
detail: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { TokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
@@ -55,11 +54,14 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
snapshotReceivedAt: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshot);
|
||||
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownEffect(LegacyStoredShellSnapshot);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
@@ -83,14 +85,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -100,63 +95,28 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
|
||||
threadId: ThreadId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread",
|
||||
) {
|
||||
const directory = yield* threadSnapshotDirectory(environmentId, operation);
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(directory, threadSnapshotFileName(threadId));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const { File } = yield* Effect.promise(() => import("expo-file-system"));
|
||||
return new File(
|
||||
yield* threadSnapshotDirectory(environmentId, operation),
|
||||
threadSnapshotFileName(threadId),
|
||||
);
|
||||
});
|
||||
|
||||
const secureCatalogStorage: SecureCatalogStorage = {
|
||||
getItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(key),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "load",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("load", cause),
|
||||
}),
|
||||
setItem: (key, value) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(key, value),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "save",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("save", cause),
|
||||
}),
|
||||
deleteItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(key),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "delete",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("delete", cause),
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -171,8 +131,6 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
operation: "load-shell" | "save-shell" | "clear-environment",
|
||||
directoryName: string,
|
||||
) {
|
||||
const resource =
|
||||
directoryName === LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY ? "legacy-shell-cache" : "shell-cache";
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, File, Paths } = await import("expo-file-system");
|
||||
@@ -180,14 +138,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource,
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -208,13 +159,8 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "list-targets",
|
||||
fallbackStage: "read",
|
||||
resource: "connection-catalog",
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -223,28 +169,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "register-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: registration.target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "remove-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -334,36 +269,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "parse",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const stored = yield* decodeStoredShellSnapshot(parsed).pipe(
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "decode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
@@ -377,36 +293,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "parse",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const legacyStored = yield* decodeLegacyStoredShellSnapshot(legacyParsed).pipe(
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "decode",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
return legacyStored.environmentId === environmentId
|
||||
@@ -421,16 +318,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* encodeStoredShellSnapshot(stored).pipe(
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "encode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
@@ -440,14 +332,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "write",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -458,39 +343,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "read",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "parse",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
});
|
||||
const stored = yield* decodeStoredThreadSnapshot(parsed).pipe(
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "decode",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
@@ -500,22 +363,16 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}).pipe(
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "encode",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
@@ -525,35 +382,22 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "write",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "remove-thread",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
file.delete();
|
||||
}
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
|
||||
@@ -561,13 +405,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
@@ -575,13 +413,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
@@ -592,13 +424,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -9,11 +9,8 @@ import * as Effect from "effect/Effect";
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
|
||||
import {
|
||||
CloudDpopProofError,
|
||||
CloudDpopStorageError,
|
||||
createDpopProof,
|
||||
generateDpopProofKeyPair,
|
||||
isCloudDpopError,
|
||||
loadOrCreateDpopProofKeyPair,
|
||||
cryptoLayer,
|
||||
} from "./dpop";
|
||||
@@ -98,82 +95,7 @@ describe("mobile DPoP", () => {
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "decode",
|
||||
storageKey: "t3code.cloud.dpop-proof-key",
|
||||
});
|
||||
expect(isCloudDpopError(error)).toBe(true);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects stored key material whose public coordinates do not match", () =>
|
||||
Effect.gen(function* () {
|
||||
secureStore.clear();
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
secureStore.set(
|
||||
"t3code.cloud.dpop-proof-key",
|
||||
JSON.stringify({ ...generated.privateJwk, x: generated.privateJwk.y }),
|
||||
);
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "restore",
|
||||
storageKey: "t3code.cloud.dpop-proof-key",
|
||||
});
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves request context for an invalid proof URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url: "http://",
|
||||
proofKey,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "normalize-url",
|
||||
method: "POST",
|
||||
requestTarget: "<invalid-url>",
|
||||
urlLength: "http://".length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(isCloudDpopError(error)).toBe(true);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("redacts credentials and non-HTU URL components from proof failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const url = "https://user:[email protected]/oauth/token?access_token=secret#fragment";
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url,
|
||||
proofKey: {
|
||||
...proofKey,
|
||||
privateJwk: { ...proofKey.privateJwk, d: "%" },
|
||||
},
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "import-private-key",
|
||||
method: "POST",
|
||||
requestTarget: "https://example.com/oauth/token",
|
||||
urlLength: url.length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error.message).not.toContain("user");
|
||||
expect(error.message).not.toContain("password");
|
||||
expect(error.message).not.toContain("access_token");
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(error.message).not.toContain("fragment");
|
||||
expect(error.message).toBe("Stored DPoP proof key is invalid.");
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ExpoCrypto from "expo-crypto";
|
||||
@@ -12,91 +12,19 @@ import {
|
||||
computeDpopAccessTokenHash,
|
||||
computeDpopJwkThumbprint,
|
||||
DpopPublicJwk,
|
||||
redactDpopRequestTarget,
|
||||
normalizeDpopHtu,
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export class CloudDpopStorageError extends Schema.TaggedErrorClass<CloudDpopStorageError>()(
|
||||
"CloudDpopStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode", "restore", "encode", "write"]),
|
||||
storageKey: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP key storage operation "${this.operation}" failed for key "${this.storageKey}".`;
|
||||
}
|
||||
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
function cloudDpopError(message: string) {
|
||||
return (cause: unknown) => new CloudDpopError({ message, cause });
|
||||
}
|
||||
|
||||
export class CloudDpopKeyError extends Schema.TaggedErrorClass<CloudDpopKeyError>()(
|
||||
"CloudDpopKeyError",
|
||||
{
|
||||
operation: Schema.Literals(["generate-randomness", "derive-public-key"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP key operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudDpopProofError extends Schema.TaggedErrorClass<CloudDpopProofError>()(
|
||||
"CloudDpopProofError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"import-private-key",
|
||||
"generate-id",
|
||||
"normalize-url",
|
||||
"encode-header",
|
||||
"encode-payload",
|
||||
"hash-signing-input",
|
||||
"sign",
|
||||
]),
|
||||
method: Schema.String,
|
||||
requestTarget: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
thumbprint: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP proof operation "${this.operation}" failed for ${this.method.toUpperCase()} ${this.requestTarget}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopPublicKeyFormatError extends Schema.TaggedErrorClass<DpopPublicKeyFormatError>()(
|
||||
"DpopPublicKeyFormatError",
|
||||
{
|
||||
byteLength: Schema.Number,
|
||||
firstByte: Schema.optional(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const prefix =
|
||||
this.firstByte === undefined
|
||||
? "no prefix byte"
|
||||
: `prefix 0x${this.firstByte.toString(16).padStart(2, "0")}`;
|
||||
return `Expected a 65-byte uncompressed P-256 public key beginning with 0x04; received ${this.byteLength} bytes with ${prefix}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopStoredPublicKeyMismatchError extends Schema.TaggedErrorClass<DpopStoredPublicKeyMismatchError>()(
|
||||
"DpopStoredPublicKeyMismatchError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Stored DPoP private and public key material do not match.";
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudDpopError = Schema.Union([
|
||||
CloudDpopStorageError,
|
||||
CloudDpopKeyError,
|
||||
CloudDpopProofError,
|
||||
]);
|
||||
export type CloudDpopError = typeof CloudDpopError.Type;
|
||||
export const isCloudDpopError = Schema.is(CloudDpopError);
|
||||
|
||||
const DpopPrivateJwkSchema = Schema.Struct({
|
||||
...DpopPublicJwk.fields,
|
||||
d: Schema.String,
|
||||
@@ -169,12 +97,29 @@ function base64UrlToBytes(value: string): Uint8Array {
|
||||
return Result.getOrThrow(Encoding.decodeBase64Url(value));
|
||||
}
|
||||
|
||||
function sha256Digest(
|
||||
data: Uint8Array,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function secureRandomBytes(
|
||||
byteCount: number,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
|
||||
if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
|
||||
throw new DpopPublicKeyFormatError({
|
||||
byteLength: publicKey.length,
|
||||
...(publicKey[0] === undefined ? {} : { firstByte: publicKey[0] }),
|
||||
});
|
||||
throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
|
||||
}
|
||||
return {
|
||||
kty: "EC",
|
||||
@@ -199,16 +144,14 @@ export function generateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
let privateKey: Uint8Array;
|
||||
do {
|
||||
privateKey = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(p256.CURVE.nByteLength)),
|
||||
Effect.mapError(
|
||||
(cause) => new CloudDpopKeyError({ operation: "generate-randomness", cause }),
|
||||
),
|
||||
privateKey = yield* secureRandomBytes(
|
||||
p256.CURVE.nByteLength,
|
||||
"Could not generate DPoP key pair randomness.",
|
||||
);
|
||||
} while (!p256.utils.isValidPrivateKey(privateKey));
|
||||
const publicJwk = yield* Effect.try({
|
||||
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
|
||||
catch: (cause) => new CloudDpopKeyError({ operation: "derive-public-key", cause }),
|
||||
catch: cloudDpopError("Generated DPoP public key is invalid."),
|
||||
});
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
return {
|
||||
@@ -227,23 +170,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
const stored = yield* Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "read",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not read the DPoP proof key."),
|
||||
});
|
||||
if (stored) {
|
||||
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "decode",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
|
||||
);
|
||||
const restored = yield* Effect.try({
|
||||
try: () => {
|
||||
@@ -252,16 +183,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
p256.getPublicKey(privateKey, false),
|
||||
);
|
||||
if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
|
||||
throw new DpopStoredPublicKeyMismatchError();
|
||||
throw new Error("Stored DPoP key does not match its public key.");
|
||||
}
|
||||
return { privateJwk: storedPrivateJwk, publicJwk };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "restore",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Stored DPoP proof key is invalid."),
|
||||
});
|
||||
return {
|
||||
...restored,
|
||||
@@ -270,28 +196,23 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
}
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "encode",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
|
||||
);
|
||||
yield* Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "write",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not store the DPoP proof key."),
|
||||
});
|
||||
return generated;
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
|
||||
const normalized = normalizeDpopHtu(url);
|
||||
return normalized
|
||||
? Effect.succeed(normalized)
|
||||
: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
|
||||
}
|
||||
|
||||
export function createDpopProof(input: {
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
@@ -304,69 +225,23 @@ export function createDpopProof(input: {
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
|
||||
const requestTarget = redactDpopRequestTarget(input.url);
|
||||
const urlLength = input.url.length;
|
||||
const privateKey = yield* Effect.try({
|
||||
try: () => base64UrlToBytes(keyPair.privateJwk.d),
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "import-private-key",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not import DPoP private key."),
|
||||
});
|
||||
const nowMs = yield* Clock.currentTimeMillis;
|
||||
const jti = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "generate-id",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
|
||||
);
|
||||
const htu = yield* Effect.try({
|
||||
try: () => {
|
||||
const parsed = new URL(input.url);
|
||||
parsed.hash = "";
|
||||
parsed.search = "";
|
||||
return parsed.toString();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "normalize-url",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const htu = yield* normalizeHtu(input.url);
|
||||
const header = yield* encodeDpopJwtHeaderJson({
|
||||
typ: "dpop+jwt",
|
||||
alg: "ES256",
|
||||
jwk: keyPair.publicJwk,
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "encode-header",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
|
||||
);
|
||||
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
|
||||
const payload = yield* encodeDpopJwtPayloadJson({
|
||||
@@ -377,45 +252,15 @@ export function createDpopProof(input: {
|
||||
...(ath ? { ath } : {}),
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "encode-payload",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
|
||||
);
|
||||
const signatureInputHash = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) =>
|
||||
crypto.digest("SHA-256", new TextEncoder().encode(`${header}.${payload}`)),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "hash-signing-input",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
const signatureInputHash = yield* sha256Digest(
|
||||
new TextEncoder().encode(`${header}.${payload}`),
|
||||
"Could not hash DPoP signing input.",
|
||||
);
|
||||
const signature = yield* Effect.try({
|
||||
try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "sign",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not sign DPoP proof."),
|
||||
});
|
||||
return {
|
||||
proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,
|
||||
|
||||
@@ -9,11 +9,9 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
CloudEnvironmentLinkOperationError,
|
||||
cloudEnvironmentsPendingStatus,
|
||||
linkEnvironmentToCloud,
|
||||
connectCloudEnvironment,
|
||||
isCloudEnvironmentLinkError,
|
||||
listCloudEnvironments,
|
||||
listCloudEnvironmentsWithStatus,
|
||||
normalizeRelayBaseUrl,
|
||||
@@ -150,46 +148,6 @@ describe("mobile cloud link environment client", () => {
|
||||
createProofMock.mockClear();
|
||||
});
|
||||
|
||||
it("keeps URL secrets out of operation error diagnostics", () => {
|
||||
const relayUrl =
|
||||
"https://relay-user:[email protected]/private/workspace?access_token=relay-secret#relay-fragment";
|
||||
const httpBaseUrl =
|
||||
"https://desktop-user:[email protected]/private/workspace?access_token=desktop-secret#desktop-fragment";
|
||||
const cause = new Error("request failed");
|
||||
|
||||
const error = CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "link the environment",
|
||||
cause,
|
||||
environmentId: "env-1",
|
||||
relayUrl,
|
||||
httpBaseUrl,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
relayUrlInputLength: relayUrl.length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "desktop.example.test",
|
||||
});
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"relay-secret",
|
||||
"relay-fragment",
|
||||
"/private/workspace",
|
||||
"desktop-user",
|
||||
"desktop-password",
|
||||
"desktop-secret",
|
||||
"desktop-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
|
||||
expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
|
||||
"https://relay.example.test",
|
||||
@@ -277,14 +235,9 @@ describe("mobile cloud link environment client", () => {
|
||||
listCloudEnvironments({ clerkToken: "clerk-token" }),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "list cloud environments",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "https://relay.example.test/v1/environments failed",
|
||||
});
|
||||
expect(error.message).toBe("Could not list cloud environments.");
|
||||
expect(isCloudEnvironmentLinkError(error)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -545,7 +498,7 @@ describe("mobile cloud link environment client", () => {
|
||||
label: "Desktop",
|
||||
},
|
||||
status: null,
|
||||
statusError: 'Could not read cloud environment status for environment "env-1".',
|
||||
statusError: "https://relay.example.test/v1/environments/env-1/status failed",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
@@ -609,8 +562,7 @@ describe("mobile cloud link environment client", () => {
|
||||
label: "Desktop",
|
||||
},
|
||||
status: null,
|
||||
statusError:
|
||||
'The environment status response identified environment "env-other" instead of "env-1".',
|
||||
statusError: "Relay returned status for a different environment.",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
@@ -638,55 +590,13 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "environment link response",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports invalid endpoint URLs with redacted diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(() => Promise.resolve(Response.json(validLinkChallengeResponse()))),
|
||||
);
|
||||
|
||||
const httpBaseUrl =
|
||||
"https://desktop-user:desktop-password@[invalid-host]/private/workspace?access_token=desktop-secret#desktop-fragment";
|
||||
const error = yield* withCloudServices(
|
||||
linkEnvironmentToCloud({
|
||||
clerkToken: "clerk-token",
|
||||
connection: {
|
||||
...savedConnection,
|
||||
httpBaseUrl,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: "env-1",
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
});
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
const serialized = JSON.stringify({ ...error, cause: undefined });
|
||||
for (const secret of [
|
||||
"desktop-user",
|
||||
"desktop-password",
|
||||
"/private/workspace",
|
||||
"desktop-secret",
|
||||
"desktop-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves typed local environment failures while obtaining a link proof", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn((url: string | URL) => {
|
||||
@@ -697,8 +607,7 @@ describe("mobile cloud link environment client", () => {
|
||||
Response.json(
|
||||
{
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
message: "Invalid environment bearer session.",
|
||||
},
|
||||
{ status: 401 },
|
||||
),
|
||||
@@ -712,20 +621,9 @@ describe("mobile cloud link environment client", () => {
|
||||
connection: savedConnection,
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: "env-1",
|
||||
httpBaseUrlInputLength: "https://desktop.example.test/".length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "desktop.example.test",
|
||||
environmentError: {
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
},
|
||||
});
|
||||
expect(error._tag).toBe("CloudEnvironmentLinkError");
|
||||
expect(error.message).toBe(
|
||||
'Could not obtain an environment link proof for environment "env-1".',
|
||||
"Could not obtain environment link proof: Invalid environment bearer session.",
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
}),
|
||||
@@ -761,19 +659,11 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "link the environment",
|
||||
environmentId: "env-1",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
|
||||
traceId: "trace-test",
|
||||
relayError: {
|
||||
_tag: "RelayEnvironmentLinkProofInvalidError",
|
||||
reason: "origin_not_allowed",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe('Could not link the environment for environment "env-1".');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
);
|
||||
@@ -806,10 +696,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentEndpointProviderMismatchError",
|
||||
environmentId: "env-1",
|
||||
expectedProviderKind: "cloudflare_tunnel",
|
||||
actualProviderKind: "manual",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
@@ -1074,10 +962,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "environment connect response",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1119,21 +1005,11 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "connect to the cloud environment",
|
||||
environmentId: "env-1",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
|
||||
traceId: "trace-connect",
|
||||
relayError: {
|
||||
_tag: "RelayAuthInvalidError",
|
||||
reason: "invalid_dpop",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
'Could not connect to the cloud environment for environment "env-1".',
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1175,23 +1051,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentEndpointMismatchError",
|
||||
source: "environment connect response",
|
||||
environmentId: "env-1",
|
||||
expectedProviderKind: "cloudflare_tunnel",
|
||||
expectedHttpBaseUrlInputLength: "https://desktop.example.test/".length,
|
||||
expectedHttpBaseUrlProtocol: "https:",
|
||||
expectedHttpBaseUrlHostname: "desktop.example.test",
|
||||
expectedWsBaseUrlInputLength: "wss://desktop.example.test/ws".length,
|
||||
expectedWsBaseUrlProtocol: "wss:",
|
||||
expectedWsBaseUrlHostname: "desktop.example.test",
|
||||
actualProviderKind: "cloudflare_tunnel",
|
||||
actualHttpBaseUrlInputLength: "https://other-desktop.example.test/".length,
|
||||
actualHttpBaseUrlProtocol: "https:",
|
||||
actualHttpBaseUrlHostname: "other-desktop.example.test",
|
||||
actualWsBaseUrlInputLength: "wss://other-desktop.example.test/ws".length,
|
||||
actualWsBaseUrlProtocol: "wss:",
|
||||
actualWsBaseUrlHostname: "other-desktop.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different endpoint.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1244,10 +1105,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "connected environment descriptor",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
@@ -16,17 +17,16 @@ import {
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
type RelayDpopAccessTokenScope,
|
||||
type RelayProtectedError as RelayProtectedErrorType,
|
||||
type RelayClientEnvironmentRecord,
|
||||
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
|
||||
RelayManagedEndpointProviderKind,
|
||||
RelayProtectedError,
|
||||
type RelayManagedEndpointProviderKind,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import { authClientMetadata } from "../../lib/authClientMetadata";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
@@ -50,268 +50,11 @@ function readRelayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relay.url;
|
||||
}
|
||||
|
||||
const EnvironmentCloudApiError = Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]);
|
||||
type EnvironmentCloudApiError = typeof EnvironmentCloudApiError.Type;
|
||||
const isEnvironmentCloudApiError = Schema.is(EnvironmentCloudApiError);
|
||||
const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
|
||||
|
||||
export const CloudEnvironmentLinkAction = Schema.Literals([
|
||||
"load the mobile device id",
|
||||
"load mobile notification preferences",
|
||||
"create an environment link challenge",
|
||||
"obtain an environment link proof",
|
||||
"link the environment",
|
||||
"configure environment relay access",
|
||||
"list cloud environments",
|
||||
"read cloud environment status",
|
||||
"connect to the cloud environment",
|
||||
"fetch the connected environment descriptor",
|
||||
"create a bootstrap DPoP proof",
|
||||
"exchange a managed endpoint DPoP access token",
|
||||
"derive the environment endpoint origin",
|
||||
"initialize the environment HTTP client",
|
||||
"parse the managed endpoint URL",
|
||||
]);
|
||||
export type CloudEnvironmentLinkAction = typeof CloudEnvironmentLinkAction.Type;
|
||||
|
||||
function relayUrlDiagnosticFields(relayUrl: string | undefined) {
|
||||
if (relayUrl === undefined) {
|
||||
return {};
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(relayUrl);
|
||||
return {
|
||||
relayUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function httpBaseUrlDiagnosticFields(httpBaseUrl: string | undefined) {
|
||||
if (httpBaseUrl === undefined) {
|
||||
return {};
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(httpBaseUrl);
|
||||
return {
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkOperationError extends Schema.TaggedErrorClass<CloudEnvironmentLinkOperationError>()(
|
||||
"CloudEnvironmentLinkOperationError",
|
||||
{
|
||||
action: CloudEnvironmentLinkAction,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
relayUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
relayUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
relayUrlHostname: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
traceId: Schema.optionalKey(Schema.String),
|
||||
relayError: Schema.optionalKey(RelayProtectedError),
|
||||
environmentError: Schema.optionalKey(EnvironmentCloudApiError),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCause(input: {
|
||||
readonly action: CloudEnvironmentLinkAction;
|
||||
readonly cause: unknown;
|
||||
readonly environmentId?: string;
|
||||
readonly relayUrl?: string;
|
||||
readonly httpBaseUrl?: string;
|
||||
}): CloudEnvironmentLinkOperationError {
|
||||
const relayFailure = isManagedRelayRequestFailedError(input.cause) ? input.cause : undefined;
|
||||
const environmentError = CloudEnvironmentLinkOperationError.findEnvironmentApiError(
|
||||
input.cause,
|
||||
);
|
||||
const traceId = relayFailure?.traceId ?? findErrorTraceId(input.cause);
|
||||
return new CloudEnvironmentLinkOperationError({
|
||||
action: input.action,
|
||||
cause: input.cause,
|
||||
...(input.environmentId === undefined ? {} : { environmentId: input.environmentId }),
|
||||
...relayUrlDiagnosticFields(input.relayUrl),
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
...(traceId === null || traceId === undefined ? {} : { traceId }),
|
||||
...(relayFailure?.relayError === undefined ? {} : { relayError: relayFailure.relayError }),
|
||||
...(environmentError === undefined ? {} : { environmentError }),
|
||||
});
|
||||
}
|
||||
|
||||
private static findEnvironmentApiError(cause: unknown): EnvironmentCloudApiError | undefined {
|
||||
const seen = new Set<unknown>();
|
||||
let current = cause;
|
||||
while (typeof current === "object" && current !== null && !seen.has(current)) {
|
||||
if (isEnvironmentCloudApiError(current)) {
|
||||
return current;
|
||||
}
|
||||
seen.add(current);
|
||||
current = "cause" in current ? current.cause : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment "${this.environmentId}"`;
|
||||
return `Could not ${this.action}${environment}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayUrlNotConfiguredError extends Schema.TaggedErrorClass<CloudRelayUrlNotConfiguredError>()(
|
||||
"CloudRelayUrlNotConfiguredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay URL is not configured.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLocalBearerRequiredError extends Schema.TaggedErrorClass<CloudEnvironmentLocalBearerRequiredError>()(
|
||||
"CloudEnvironmentLocalBearerRequiredError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
httpBaseUrlInputLength: Schema.Number,
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
static fromConnection(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}): CloudEnvironmentLocalBearerRequiredError {
|
||||
const diagnostics = getUrlDiagnostics(input.httpBaseUrl);
|
||||
return new CloudEnvironmentLocalBearerRequiredError({
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Only a locally paired bearer connection can be linked to the cloud.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentIdMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentIdMismatchError>()(
|
||||
"CloudEnvironmentIdMismatchError",
|
||||
{
|
||||
source: Schema.Literals([
|
||||
"environment link response",
|
||||
"environment status response",
|
||||
"environment status descriptor",
|
||||
"environment connect response",
|
||||
"connected environment descriptor",
|
||||
]),
|
||||
expectedEnvironmentId: Schema.String,
|
||||
actualEnvironmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `The ${this.source} identified environment "${this.actualEnvironmentId}" instead of "${this.expectedEnvironmentId}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentEndpointMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointMismatchError>()(
|
||||
"CloudEnvironmentEndpointMismatchError",
|
||||
{
|
||||
source: Schema.Literals(["environment status response", "environment connect response"]),
|
||||
environmentId: Schema.String,
|
||||
expectedProviderKind: RelayManagedEndpointProviderKind,
|
||||
expectedHttpBaseUrlInputLength: Schema.Number,
|
||||
expectedHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
expectedHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
expectedWsBaseUrlInputLength: Schema.Number,
|
||||
expectedWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
expectedWsBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
actualProviderKind: RelayManagedEndpointProviderKind,
|
||||
actualHttpBaseUrlInputLength: Schema.Number,
|
||||
actualHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
actualHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
actualWsBaseUrlInputLength: Schema.Number,
|
||||
actualWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
actualWsBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
static fromEndpoints(input: {
|
||||
readonly source: "environment status response" | "environment connect response";
|
||||
readonly environmentId: string;
|
||||
readonly expectedEndpoint: RelayClientEnvironmentRecord["endpoint"];
|
||||
readonly actualEndpoint: RelayClientEnvironmentRecord["endpoint"];
|
||||
}): CloudEnvironmentEndpointMismatchError {
|
||||
const expectedHttp = getUrlDiagnostics(input.expectedEndpoint.httpBaseUrl);
|
||||
const expectedWs = getUrlDiagnostics(input.expectedEndpoint.wsBaseUrl);
|
||||
const actualHttp = getUrlDiagnostics(input.actualEndpoint.httpBaseUrl);
|
||||
const actualWs = getUrlDiagnostics(input.actualEndpoint.wsBaseUrl);
|
||||
return new CloudEnvironmentEndpointMismatchError({
|
||||
source: input.source,
|
||||
environmentId: input.environmentId,
|
||||
expectedProviderKind: input.expectedEndpoint.providerKind,
|
||||
expectedHttpBaseUrlInputLength: expectedHttp.inputLength,
|
||||
...(expectedHttp.protocol === undefined
|
||||
? {}
|
||||
: { expectedHttpBaseUrlProtocol: expectedHttp.protocol }),
|
||||
...(expectedHttp.hostname === undefined
|
||||
? {}
|
||||
: { expectedHttpBaseUrlHostname: expectedHttp.hostname }),
|
||||
expectedWsBaseUrlInputLength: expectedWs.inputLength,
|
||||
...(expectedWs.protocol === undefined
|
||||
? {}
|
||||
: { expectedWsBaseUrlProtocol: expectedWs.protocol }),
|
||||
...(expectedWs.hostname === undefined
|
||||
? {}
|
||||
: { expectedWsBaseUrlHostname: expectedWs.hostname }),
|
||||
actualProviderKind: input.actualEndpoint.providerKind,
|
||||
actualHttpBaseUrlInputLength: actualHttp.inputLength,
|
||||
...(actualHttp.protocol === undefined
|
||||
? {}
|
||||
: { actualHttpBaseUrlProtocol: actualHttp.protocol }),
|
||||
...(actualHttp.hostname === undefined
|
||||
? {}
|
||||
: { actualHttpBaseUrlHostname: actualHttp.hostname }),
|
||||
actualWsBaseUrlInputLength: actualWs.inputLength,
|
||||
...(actualWs.protocol === undefined ? {} : { actualWsBaseUrlProtocol: actualWs.protocol }),
|
||||
...(actualWs.hostname === undefined ? {} : { actualWsBaseUrlHostname: actualWs.hostname }),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `The ${this.source} returned a different endpoint for environment "${this.environmentId}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentEndpointProviderMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointProviderMismatchError>()(
|
||||
"CloudEnvironmentEndpointProviderMismatchError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
expectedProviderKind: RelayManagedEndpointProviderKind,
|
||||
actualProviderKind: RelayManagedEndpointProviderKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay returned link credentials with endpoint provider "${this.actualProviderKind}" instead of "${this.expectedProviderKind}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudEnvironmentLinkError = Schema.Union([
|
||||
CloudEnvironmentLinkOperationError,
|
||||
CloudRelayUrlNotConfiguredError,
|
||||
CloudEnvironmentLocalBearerRequiredError,
|
||||
CloudEnvironmentIdMismatchError,
|
||||
CloudEnvironmentEndpointMismatchError,
|
||||
CloudEnvironmentEndpointProviderMismatchError,
|
||||
]);
|
||||
export type CloudEnvironmentLinkError = typeof CloudEnvironmentLinkError.Type;
|
||||
export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
readonly traceId?: string;
|
||||
}> {}
|
||||
|
||||
export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly environment: RelayClientEnvironmentRecord;
|
||||
@@ -319,47 +62,132 @@ export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly statusError: string | null;
|
||||
}
|
||||
|
||||
const isEnvironmentCloudApiError = Schema.is(
|
||||
Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]),
|
||||
);
|
||||
|
||||
const MANAGED_ENDPOINT_PROVIDER_KIND =
|
||||
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
|
||||
|
||||
function cloudEnvironmentLinkError(message: string) {
|
||||
return (cause: unknown) => {
|
||||
const environmentError = findEnvironmentCloudApiError(cause);
|
||||
const traceId = findErrorTraceId(cause);
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: environmentError
|
||||
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
|
||||
: withDevCause(message, cause),
|
||||
cause,
|
||||
...(traceId === null ? {} : { traceId }),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function isDevRuntime(): boolean {
|
||||
return typeof __DEV__ !== "undefined" && __DEV__;
|
||||
}
|
||||
|
||||
function causeMessage(cause: unknown): string | null {
|
||||
if (cause instanceof Error && cause.message) {
|
||||
return cause.message;
|
||||
}
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
const record = cause as { readonly message?: unknown; readonly cause?: unknown };
|
||||
if (typeof record.message === "string" && record.message.length > 0) {
|
||||
const nested = causeMessage(record.cause);
|
||||
return nested ? `${record.message}: ${nested}` : record.message;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function withDevCause(message: string, cause: unknown): string {
|
||||
if (!isDevRuntime()) {
|
||||
return message;
|
||||
}
|
||||
const detail = causeMessage(cause);
|
||||
return detail ? `${message} (${detail})` : message;
|
||||
}
|
||||
|
||||
function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
|
||||
switch (error._tag) {
|
||||
case "RelayAuthInvalidError":
|
||||
switch (error.reason) {
|
||||
case "missing_bearer":
|
||||
case "invalid_bearer":
|
||||
return "Relay rejected the cloud session token.";
|
||||
case "invalid_dpop":
|
||||
return "Relay rejected the DPoP proof.";
|
||||
case "not_authorized":
|
||||
return "Relay rejected the authenticated request.";
|
||||
}
|
||||
case "RelayEnvironmentLinkProofExpiredError":
|
||||
return "Relay rejected an expired environment link proof.";
|
||||
case "RelayEnvironmentLinkProofInvalidError":
|
||||
return `Relay rejected the environment link proof (${error.reason}).`;
|
||||
case "RelayEnvironmentConnectNotAuthorizedError":
|
||||
return "Relay rejected the environment connection request.";
|
||||
case "RelayEnvironmentEndpointUnavailableError":
|
||||
return `Relay could not reach the environment endpoint (${error.reason}).`;
|
||||
case "RelayEnvironmentEndpointTimedOutError":
|
||||
return "Relay timed out while contacting the environment endpoint.";
|
||||
case "RelayEnvironmentLinkFailedError":
|
||||
return `Relay could not link the environment (${error.reason}).`;
|
||||
case "RelayEnvironmentLinkUnavailableError":
|
||||
return `Relay cannot provision the managed endpoint (${error.reason}).`;
|
||||
case "RelayAgentActivityPublishProofExpiredError":
|
||||
return "Relay rejected an expired agent activity publish proof.";
|
||||
case "RelayAgentActivityPublishProofInvalidError":
|
||||
return `Relay rejected the agent activity publish proof (${error.reason}).`;
|
||||
case "RelayInternalError":
|
||||
return `Relay encountered an internal error (${error.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
function decodedRelayClientError(message: string) {
|
||||
return (cause: ManagedRelay.ManagedRelayClientError) => {
|
||||
const relayError =
|
||||
cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
|
||||
const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
|
||||
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: detail ? `${message}: ${detail}` : message,
|
||||
cause,
|
||||
...(traceId ? { traceId } : {}),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
|
||||
if (isEnvironmentCloudApiError(cause)) {
|
||||
return cause;
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return null;
|
||||
}
|
||||
return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
|
||||
}
|
||||
|
||||
function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
|
||||
const relayUrl = readRelayUrl();
|
||||
return relayUrl ? Effect.succeed(relayUrl) : Effect.fail(new CloudRelayUrlNotConfiguredError());
|
||||
return relayUrl
|
||||
? Effect.succeed(relayUrl)
|
||||
: Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
|
||||
}
|
||||
|
||||
function endpointOrigin(input: { readonly environmentId: string; readonly httpBaseUrl: string }) {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const url = new URL(input.httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function makeCloudEnvironmentHttpApiClient(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}) {
|
||||
return Effect.try({
|
||||
try: () => makeEnvironmentHttpApiClient(input.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "initialize the environment HTTP client",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.flatten);
|
||||
function endpointOrigin(httpBaseUrl: string) {
|
||||
const url = new URL(httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
}
|
||||
|
||||
function ensureLinkedEnvironmentMatches(input: {
|
||||
@@ -368,17 +196,13 @@ function ensureLinkedEnvironmentMatches(input: {
|
||||
readonly link: RelayEnvironmentLinkResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.link.environmentId !== input.expectedEnvironmentId) {
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment link response",
|
||||
expectedEnvironmentId: input.expectedEnvironmentId,
|
||||
actualEnvironmentId: input.link.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
|
||||
return new CloudEnvironmentEndpointProviderMismatchError({
|
||||
environmentId: input.expectedEnvironmentId,
|
||||
expectedProviderKind: input.expectedProviderKind,
|
||||
actualProviderKind: input.link.endpoint.providerKind,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -400,28 +224,21 @@ function ensureStatusMatchesEnvironment(input: {
|
||||
readonly status: RelayEnvironmentStatusResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.status.environmentId !== input.environment.environmentId) {
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment status response",
|
||||
expectedEnvironmentId: input.environment.environmentId,
|
||||
actualEnvironmentId: input.status.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status for a different environment.",
|
||||
});
|
||||
}
|
||||
if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
|
||||
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
|
||||
source: "environment status response",
|
||||
environmentId: input.environment.environmentId,
|
||||
expectedEndpoint: input.environment.endpoint,
|
||||
actualEndpoint: input.status.endpoint,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status for a different endpoint.",
|
||||
});
|
||||
}
|
||||
if (
|
||||
input.status.descriptor &&
|
||||
input.status.descriptor.environmentId !== input.environment.environmentId
|
||||
) {
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment status descriptor",
|
||||
expectedEnvironmentId: input.environment.environmentId,
|
||||
actualEnvironmentId: input.status.descriptor.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status descriptor for a different environment.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -432,11 +249,8 @@ function ensureConnectEndpointMatchesEnvironment(input: {
|
||||
readonly connect: RelayEnvironmentConnectResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
|
||||
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
|
||||
source: "environment connect response",
|
||||
environmentId: input.environment.environmentId,
|
||||
expectedEndpoint: input.environment.endpoint,
|
||||
actualEndpoint: input.connect.endpoint,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -452,9 +266,8 @@ export function linkEnvironmentToCloud(input: {
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
if (!input.connection.bearerToken) {
|
||||
return yield* CloudEnvironmentLocalBearerRequiredError.fromConnection({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Only a locally paired bearer connection can be linked to the cloud.",
|
||||
});
|
||||
}
|
||||
const localBearerToken = input.connection.bearerToken;
|
||||
@@ -462,21 +275,11 @@ export function linkEnvironmentToCloud(input: {
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load the mobile device id",
|
||||
environmentId: input.connection.environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
const preferences = yield* Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load mobile notification preferences",
|
||||
environmentId: input.connection.environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
|
||||
});
|
||||
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
|
||||
const challenge = yield* relayClient
|
||||
@@ -489,23 +292,11 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "create an environment link challenge",
|
||||
environmentId: input.connection.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
|
||||
),
|
||||
);
|
||||
const origin = yield* endpointOrigin({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
const environmentClient = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
|
||||
const proof = yield* environmentClient.connect
|
||||
.linkProof({
|
||||
headers: { authorization: `Bearer ${localBearerToken}` },
|
||||
@@ -517,19 +308,10 @@ export function linkEnvironmentToCloud(input: {
|
||||
wsBaseUrl: input.connection.wsBaseUrl,
|
||||
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
|
||||
},
|
||||
origin,
|
||||
origin: endpointOrigin(input.connection.httpBaseUrl),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
|
||||
const link = yield* relayClient
|
||||
.linkEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -542,14 +324,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "link the environment",
|
||||
environmentId: input.connection.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
|
||||
);
|
||||
yield* ensureLinkedEnvironmentMatches({
|
||||
expectedEnvironmentId: input.connection.environmentId,
|
||||
@@ -570,14 +345,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "configure environment relay access",
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -593,15 +361,11 @@ export function listCloudEnvironments(input: {
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
|
||||
return yield* relayClient.listEnvironments({ clerkToken: input.clerkToken }).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "list cloud environments",
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* relayClient
|
||||
.listEnvironments({
|
||||
clerkToken: input.clerkToken,
|
||||
})
|
||||
.pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -624,13 +388,10 @@ export function getCloudEnvironmentStatus(input: {
|
||||
environmentId: input.environment.environmentId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "read cloud environment status",
|
||||
environmentId: input.environment.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
|
||||
@@ -697,19 +458,14 @@ export function listCloudEnvironmentsWithStatus(input: {
|
||||
});
|
||||
}
|
||||
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(function* (
|
||||
environmentId: string,
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load the mobile device id",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
|
||||
function* () {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
|
||||
function* (input: {
|
||||
@@ -721,7 +477,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId(input.environmentId);
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId();
|
||||
const connect = yield* relayClient
|
||||
.connectEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -730,20 +486,15 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
deviceId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "connect to the cloud environment",
|
||||
environmentId: input.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (connect.environmentId !== input.environmentId) {
|
||||
return yield* new CloudEnvironmentIdMismatchError({
|
||||
source: "environment connect response",
|
||||
expectedEnvironmentId: input.environmentId,
|
||||
actualEnvironmentId: connect.environmentId,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (input.expectedEnvironment) {
|
||||
@@ -756,69 +507,39 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "fetch the connected environment descriptor",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
|
||||
),
|
||||
);
|
||||
if (descriptor.environmentId !== connect.environmentId) {
|
||||
return yield* new CloudEnvironmentIdMismatchError({
|
||||
source: "connected environment descriptor",
|
||||
expectedEnvironmentId: connect.environmentId,
|
||||
actualEnvironmentId: descriptor.environmentId,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
});
|
||||
}
|
||||
const endpointUrl = yield* Effect.try({
|
||||
try: () => new URL(connect.endpoint.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "parse the managed endpoint URL",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
|
||||
const bootstrapDpop = yield* signer
|
||||
.createProof({
|
||||
method: "POST",
|
||||
url: new URL("/oauth/token", endpointUrl).toString(),
|
||||
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "create a bootstrap DPoP proof",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
|
||||
const bootstrap = yield* exchangeRemoteDpopAccessToken({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
credential: connect.credential,
|
||||
dpopProof: bootstrapDpop,
|
||||
clientMetadata: authClientMetadata(),
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "exchange a managed endpoint DPoP access token",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
|
||||
),
|
||||
);
|
||||
endpointUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
environmentLabel: descriptor.label,
|
||||
pairingUrl: stripPairingTokenFromUrl(endpointUrl).toString(),
|
||||
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
|
||||
displayUrl: connect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: connect.endpoint.wsBaseUrl,
|
||||
|
||||
@@ -28,24 +28,25 @@ const relayDpopSignerLayer = Layer.effect(
|
||||
),
|
||||
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {
|
||||
const proofKey = yield* loadProofKey.pipe(
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopKeyLoadError.fromTarget({
|
||||
keyStore: "expo-secure-store",
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* createDpopProof({ ...input, proofKey }).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.map((proof) => proof.proof),
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopProofCreationError.fromTarget({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -58,7 +58,7 @@ export function useConnectionController() {
|
||||
environment: entry.environment,
|
||||
availability: entry.availability,
|
||||
status: Option.getOrNull(entry.status),
|
||||
error: Option.getOrNull(entry.error)?.detail ?? null,
|
||||
error: Option.getOrNull(entry.error)?.message ?? null,
|
||||
traceId: Option.getOrNull(entry.error)?.traceId ?? null,
|
||||
})),
|
||||
[discovery.environments],
|
||||
@@ -112,7 +112,7 @@ export function useConnectionController() {
|
||||
relayDiscovery: {
|
||||
isRefreshing: discovery.refreshing,
|
||||
isOffline: discovery.offline,
|
||||
error: Option.getOrNull(discovery.error)?.detail ?? null,
|
||||
error: Option.getOrNull(discovery.error)?.message ?? null,
|
||||
errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,
|
||||
},
|
||||
connectPairingUrl,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createSourceHighlightAtomFamily,
|
||||
SourceHighlightError,
|
||||
type SourceHighlightTokens,
|
||||
} from "./sourceHighlightingState";
|
||||
|
||||
@@ -102,29 +100,22 @@ describe("sourceHighlightingState", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves highlighter failures with the source path and theme", async () => {
|
||||
const cause = new Error("highlight failed");
|
||||
const highlight = vi.fn(() => Promise.reject(cause));
|
||||
it("exposes highlighter errors as a failed async result", async () => {
|
||||
const highlight = vi.fn(async () => {
|
||||
throw new Error("highlight failed");
|
||||
});
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
|
||||
const registry = AtomRegistry.make();
|
||||
const path = "src/example.ts";
|
||||
const theme = "light" as const;
|
||||
const atom = sourceHighlightAtom({
|
||||
path,
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 1;",
|
||||
theme,
|
||||
theme: "light",
|
||||
});
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(new SourceHighlightError({ path, theme, cause }));
|
||||
expect((error as SourceHighlightError).cause).toBe(cause);
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -23,18 +22,9 @@ type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighligh
|
||||
|
||||
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
|
||||
|
||||
export class SourceHighlightError extends Schema.TaggedErrorClass<SourceHighlightError>()(
|
||||
"SourceHighlightError",
|
||||
{
|
||||
path: Schema.String,
|
||||
theme: Schema.Literals(["light", "dark"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not highlight ${this.path} with the ${this.theme} theme.`;
|
||||
}
|
||||
}
|
||||
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export function createSourceHighlightAtomFamily(options?: {
|
||||
readonly highlight?: SourceHighlighter;
|
||||
@@ -46,8 +36,7 @@ export function createSourceHighlightAtomFamily(options?: {
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => highlight(request),
|
||||
catch: (cause) =>
|
||||
new SourceHighlightError({ path: request.path, theme: request.theme, cause }),
|
||||
catch: (cause) => new SourceHighlightError({ cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Hash from "effect/Hash";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createWorkspaceFileImageAtomFamily,
|
||||
WorkspaceImagePrefetchFailedError,
|
||||
WorkspaceImagePrefetchUnavailableError,
|
||||
} from "./workspace-file-image-cache";
|
||||
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
|
||||
|
||||
describe("workspaceFileImageAtom", () => {
|
||||
it("reuses a prefetched image across route remounts", async () => {
|
||||
@@ -54,65 +48,15 @@ describe("workspaceFileImageAtom", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("reports an unavailable image when prefetch completes without caching it", async () => {
|
||||
const uri = "https://example.test/api/assets/signed-secret-token/missing.png?signature=private";
|
||||
it("exposes prefetch failures", async () => {
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom(uri);
|
||||
expect(atom.label?.[0]).not.toContain("signed-secret-token");
|
||||
expect(atom.label?.[0]).not.toContain("signature=private");
|
||||
const atom = imageAtom("https://example.test/missing.png");
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(
|
||||
new WorkspaceImagePrefetchUnavailableError({
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "https:",
|
||||
}),
|
||||
);
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("signature=private");
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves rejected prefetch causes without retaining the signed image URI", async () => {
|
||||
const uri =
|
||||
"https://example.test/api/assets/signed-secret-token/rejected.png?signature=private";
|
||||
const cause = new Error("native image loader failed");
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: () => Promise.reject(cause) });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom(uri);
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(
|
||||
new WorkspaceImagePrefetchFailedError({
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "https:",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
expect((error as WorkspaceImagePrefetchFailedError).cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("signature=private");
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Hash from "effect/Hash";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
|
||||
@@ -11,77 +8,39 @@ type ImagePrefetch = (uri: string) => Promise<boolean>;
|
||||
|
||||
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
|
||||
|
||||
export class WorkspaceImagePrefetchUnavailableError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchUnavailableError>()(
|
||||
"WorkspaceImagePrefetchUnavailableError",
|
||||
{
|
||||
uriHash: Schema.Number,
|
||||
uriLength: Schema.Number,
|
||||
uriProtocol: Schema.NullOr(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Image prefetch did not cache the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceImagePrefetchFailedError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchFailedError>()(
|
||||
"WorkspaceImagePrefetchFailedError",
|
||||
{
|
||||
uriHash: Schema.Number,
|
||||
uriLength: Schema.Number,
|
||||
uriProtocol: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Image prefetch failed for the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export const WorkspaceImagePrefetchError = Schema.Union([
|
||||
WorkspaceImagePrefetchUnavailableError,
|
||||
WorkspaceImagePrefetchFailedError,
|
||||
]);
|
||||
export type WorkspaceImagePrefetchError = typeof WorkspaceImagePrefetchError.Type;
|
||||
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
|
||||
readonly cause?: unknown;
|
||||
readonly uri: string;
|
||||
}> {}
|
||||
|
||||
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
|
||||
const { Image } = await import("react-native");
|
||||
return Image.prefetch(uri);
|
||||
}
|
||||
|
||||
function describeWorkspaceImageUri(uri: string) {
|
||||
const diagnostics = getUrlDiagnostics(uri);
|
||||
return {
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: diagnostics.inputLength,
|
||||
uriProtocol: diagnostics.protocol ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function createWorkspaceFileImageAtomFamily(options?: {
|
||||
readonly idleTtlMs?: number;
|
||||
readonly prefetch?: ImagePrefetch;
|
||||
}) {
|
||||
const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
|
||||
const prefetch = options?.prefetch ?? prefetchWithNativeImage;
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) => {
|
||||
const uriContext = describeWorkspaceImageUri(key.uri);
|
||||
return Atom.make(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Effect.tryPromise({
|
||||
try: () => prefetch(key.uri),
|
||||
catch: (cause) => new WorkspaceImagePrefetchFailedError({ ...uriContext, cause }),
|
||||
});
|
||||
if (!cached) {
|
||||
return yield* new WorkspaceImagePrefetchUnavailableError(uriContext);
|
||||
}
|
||||
return key.uri;
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const cached = await prefetch(key.uri);
|
||||
if (!cached) {
|
||||
throw new WorkspaceImagePrefetchError({ uri: key.uri });
|
||||
}
|
||||
return key.uri;
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof WorkspaceImagePrefetchError
|
||||
? cause
|
||||
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
Atom.withLabel(`mobile:workspace-image:${uriContext.uriHash.toString(36)}`),
|
||||
);
|
||||
});
|
||||
).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
|
||||
);
|
||||
|
||||
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
|
||||
|
||||
const missingFileCause = new Error("missing file");
|
||||
const files = new Map<string, { base64: string; deleted: boolean }>();
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
@@ -19,7 +18,7 @@ vi.mock("expo-file-system", () => ({
|
||||
async base64(): Promise<string> {
|
||||
const entry = files.get(this.uri);
|
||||
if (!entry || entry.deleted) {
|
||||
throw missingFileCause;
|
||||
throw new Error("missing file");
|
||||
}
|
||||
return entry.base64;
|
||||
}
|
||||
@@ -92,30 +91,4 @@ describe("native pasted image cleanup", () => {
|
||||
expect(files.get(overflow)?.deleted).toBe(true);
|
||||
expect(files.get(userOwned)?.deleted).toBe(false);
|
||||
});
|
||||
|
||||
it("reports structured context when reading a pasted image fails", async () => {
|
||||
const uri = "file:///private/var/mobile/photos/signed-secret-token/missing.png?token=private";
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
|
||||
await expect(
|
||||
convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }),
|
||||
).resolves.toEqual([]);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"[composer-images] failed to read pasted image",
|
||||
expect.objectContaining({
|
||||
_tag: "ComposerImageOperationError",
|
||||
operation: "read-pasted-image",
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "file:",
|
||||
cause: missingFileCause,
|
||||
message: `Composer image operation read-pasted-image failed for a file: URI (length ${uri.length}).`,
|
||||
}),
|
||||
);
|
||||
const error = warn.mock.calls[0]?.[1];
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("token=private");
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,6 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
@@ -14,31 +12,6 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
export class ComposerImageOperationError extends Schema.TaggedErrorClass<ComposerImageOperationError>()(
|
||||
"ComposerImageOperationError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"load-image-picker",
|
||||
"request-media-library-permission",
|
||||
"launch-image-library",
|
||||
"load-clipboard",
|
||||
"check-clipboard-image",
|
||||
"read-clipboard-image",
|
||||
"check-clipboard-text",
|
||||
"read-clipboard-text",
|
||||
"read-pasted-image",
|
||||
"remove-pasted-image",
|
||||
]),
|
||||
uriLength: Schema.optional(Schema.Number),
|
||||
uriProtocol: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Composer image operation ${this.operation} failed${this.uriLength === undefined ? "" : ` for a ${this.uriProtocol ?? "unknown-protocol"} URI (length ${this.uriLength})`}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
@@ -47,22 +20,16 @@ function estimateBase64ByteSize(base64: string): number {
|
||||
async function loadImagePicker() {
|
||||
try {
|
||||
return await import("expo-image-picker");
|
||||
} catch (cause) {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "load-image-picker",
|
||||
cause,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error("Image attachments are unavailable right now.", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
async function loadClipboard() {
|
||||
try {
|
||||
return await import("expo-clipboard");
|
||||
} catch (cause) {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "load-clipboard",
|
||||
cause,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error("Clipboard paste is unavailable right now.", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,19 +49,14 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
try {
|
||||
imagePicker = await loadImagePicker();
|
||||
} catch (error) {
|
||||
console.warn("[composer-images] image picker unavailable", error);
|
||||
return {
|
||||
images: [],
|
||||
error: "Image attachments are unavailable right now.",
|
||||
error:
|
||||
error instanceof Error ? error.message : "Image attachments are unavailable right now.",
|
||||
};
|
||||
}
|
||||
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "request-media-library-permission",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (!permission.granted) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -102,20 +64,13 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
};
|
||||
}
|
||||
|
||||
const result = await imagePicker
|
||||
.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
})
|
||||
.catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "launch-image-library",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
});
|
||||
|
||||
if (result.canceled) {
|
||||
return {
|
||||
@@ -172,23 +127,16 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
try {
|
||||
clipboard = await loadClipboard();
|
||||
} catch (error) {
|
||||
console.warn("[composer-images] clipboard unavailable", error);
|
||||
return {
|
||||
images: [],
|
||||
text: null,
|
||||
error: "Clipboard paste is unavailable right now.",
|
||||
error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
|
||||
};
|
||||
}
|
||||
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
|
||||
const hasImage = await clipboard.hasImageAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "check-clipboard-image",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (hasImage) {
|
||||
if (await clipboard.hasImageAsync()) {
|
||||
if (remainingSlots <= 0) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -196,12 +144,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
|
||||
};
|
||||
}
|
||||
const image = await clipboard.getImageAsync({ format: "png" }).catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "read-clipboard-image",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const image = await clipboard.getImageAsync({ format: "png" });
|
||||
if (!image) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -237,19 +180,8 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
};
|
||||
}
|
||||
|
||||
const hasText = await clipboard.hasStringAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "check-clipboard-text",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (hasText) {
|
||||
const text = await clipboard.getStringAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "read-clipboard-text",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (await clipboard.hasStringAsync()) {
|
||||
const text = await clipboard.getStringAsync();
|
||||
return {
|
||||
images: [],
|
||||
text: text.length > 0 ? text : null,
|
||||
@@ -298,14 +230,6 @@ export function isOwnedPastedImageUri(uri: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function describeComposerImageUri(uri: string) {
|
||||
const diagnostics = getUrlDiagnostics(uri);
|
||||
return {
|
||||
uriLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { uriProtocol: diagnostics.protocol }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function convertPastedImagesToAttachments(input: {
|
||||
readonly uris: ReadonlyArray<string>;
|
||||
readonly existingCount: number;
|
||||
@@ -336,15 +260,8 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
dataUrl: `data:${mimeType};base64,${base64}`,
|
||||
previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
|
||||
});
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-images] failed to read pasted image",
|
||||
new ComposerImageOperationError({
|
||||
operation: "read-pasted-image",
|
||||
...describeComposerImageUri(uri),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("Failed to read pasted image", uri, error);
|
||||
} finally {
|
||||
if (ownedTemporaryFile) {
|
||||
try {
|
||||
@@ -352,15 +269,8 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-images] failed to remove temporary pasted image",
|
||||
new ComposerImageOperationError({
|
||||
operation: "remove-pasted-image",
|
||||
...describeComposerImageUri(uri),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("Failed to remove temporary pasted image", uri, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import { isEnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -110,9 +109,6 @@ function errorMessage(error: unknown): string | null {
|
||||
}
|
||||
|
||||
export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
if (isEnvironmentRpcUnavailableError(error)) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -263,15 +262,6 @@ describe("thread outbox", () => {
|
||||
});
|
||||
|
||||
it("retries transport failures but drops deterministic command failures", () => {
|
||||
expect(
|
||||
shouldRetryThreadOutboxDelivery(
|
||||
new EnvironmentRpcUnavailableError({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
environmentLabel: "Test environment",
|
||||
method: "thread.turn.start",
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
|
||||
expect(
|
||||
shouldRetryThreadOutboxDelivery({
|
||||
|
||||
@@ -114,16 +114,6 @@ 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())),
|
||||
);
|
||||
|
||||
@@ -262,20 +252,4 @@ 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,50 +85,44 @@ 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 ${this.credentialKind} credential.`;
|
||||
return "Failed to validate session credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
|
||||
"ServerAuthAuthenticatedSessionIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue authenticated session for ${this.subject}.`;
|
||||
return "Failed to issue authenticated session.";
|
||||
}
|
||||
}
|
||||
|
||||
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 for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
return "Failed to issue authenticated access token.";
|
||||
}
|
||||
}
|
||||
|
||||
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 for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
return "Failed to create pairing link.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,25 +140,22 @@ 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 ${this.pairingLinkId}.`;
|
||||
return "Failed to revoke pairing link.";
|
||||
}
|
||||
}
|
||||
|
||||
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 for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
return "Failed to issue session token.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,63 +173,55 @@ 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 ${this.sessionId}.`;
|
||||
return "Failed to revoke session.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
|
||||
"ServerAuthOtherSessionsRevocationError",
|
||||
{
|
||||
excludedSessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke sessions other than ${this.excludedSessionId}.`;
|
||||
return "Failed to revoke other sessions.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
|
||||
"ServerAuthWebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue websocket token for session ${this.sessionId}.`;
|
||||
return "Failed to issue websocket token.";
|
||||
}
|
||||
}
|
||||
|
||||
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 replay state for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
return "Failed to record DPoP proof replay state.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
|
||||
"ServerAuthDpopReplayKeyCalculationError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to calculate replay key for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
return "Failed to calculate DPoP replay key.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,6 +360,11 @@ 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",
|
||||
@@ -389,13 +377,10 @@ 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 `Requested scopes [${this.requestedScopes.join(", ")}] exceed granted scopes [${this.grantedScopes.join(", ")}].`;
|
||||
return "The requested authentication scope was not granted.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,35 +389,28 @@ 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 `Authentication session ${this.currentSessionId} cannot revoke itself.`;
|
||||
return "The current authentication session 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, ServerAuthAuthenticationInternalError>;
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
|
||||
readonly createBrowserSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
@@ -441,9 +419,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly response: AuthBrowserSessionResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedSessionIssueError
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForAccessToken: (
|
||||
credential: string,
|
||||
@@ -454,10 +430,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
},
|
||||
) => Effect.Effect<
|
||||
AuthAccessTokenResult,
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthScopeNotGrantedError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedAccessTokenIssueError
|
||||
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
|
||||
>;
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
@@ -465,61 +438,56 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthPairingLinkCreationError>;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthPairingLinkCreationError>;
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
|
||||
readonly issueStartupPairingCredential: () => Effect.Effect<
|
||||
AuthPairingCredentialResult,
|
||||
ServerAuthPairingLinkCreationError
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthPairingLinksListError>;
|
||||
readonly revokePairingLink: (
|
||||
id: string,
|
||||
) => Effect.Effect<boolean, ServerAuthPairingLinkRevocationError>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthSessionTokenIssueError>;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
ServerAuthSessionsListError
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, ServerAuthSessionRevocationError>;
|
||||
) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthSessionsListError>;
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
ServerAuthForbiddenOperationError | ServerAuthSessionRevocationError
|
||||
>;
|
||||
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
readonly issueWebSocketTicket: (
|
||||
session: Pick<AuthenticatedSession, "sessionId">,
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthWebSocketTokenIssueError>;
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
|
||||
readonly issueStartupPairingUrl: (
|
||||
baseUrl: string,
|
||||
) => Effect.Effect<string, ServerAuthPairingLinkCreationError>;
|
||||
) => Effect.Effect<string, ServerAuthInternalError>;
|
||||
}
|
||||
>()("t3/auth/EnvironmentAuth") {}
|
||||
|
||||
@@ -546,7 +514,7 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
|
||||
|
||||
export function toBootstrapExchangeError(
|
||||
cause: PairingGrantStore.BootstrapCredentialError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthBootstrapCredentialValidationError {
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
|
||||
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
|
||||
return new ServerAuthBootstrapCredentialValidationError({ cause });
|
||||
}
|
||||
@@ -558,17 +526,12 @@ export function toBootstrapExchangeError(
|
||||
|
||||
const mapSessionVerificationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
|
||||
credentialKind: ServerAuthSessionCredentialValidationError["credentialKind"],
|
||||
): Effect.Effect<
|
||||
A,
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError,
|
||||
R
|
||||
> =>
|
||||
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
|
||||
effect.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
SessionStore.isSessionCredentialInvalidError(cause)
|
||||
? new ServerAuthInvalidCredentialError({ cause })
|
||||
: new ServerAuthSessionCredentialValidationError({ credentialKind, cause }),
|
||||
: new ServerAuthSessionCredentialValidationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -602,7 +565,7 @@ export const make = Effect.gen(function* () {
|
||||
token: string,
|
||||
): Effect.Effect<
|
||||
AuthenticatedSession,
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
@@ -622,12 +585,12 @@ export const make = Effect.gen(function* () {
|
||||
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
(effect) => mapSessionVerificationErrors(effect, "session"),
|
||||
mapSessionVerificationErrors,
|
||||
);
|
||||
|
||||
const authenticateRequest = (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError> => {
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const dpopToken = parseDpopToken(request);
|
||||
@@ -679,18 +642,12 @@ export const make = Effect.gen(function* () {
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
}),
|
||||
Effect.catchIf(isServerAuthCredentialError, () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.getSessionState"),
|
||||
);
|
||||
|
||||
@@ -712,13 +669,7 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedSessionIssueError({
|
||||
subject: grant.subject,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
@@ -744,10 +695,7 @@ 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({
|
||||
requestedScopes: grantedScopes,
|
||||
grantedScopes: grant.scopes,
|
||||
});
|
||||
return yield* new ServerAuthScopeNotGrantedError({});
|
||||
}
|
||||
return yield* sessions
|
||||
.issue({
|
||||
@@ -767,12 +715,7 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedAccessTokenIssueError({
|
||||
subject: grant.subject,
|
||||
scopes: grantedScopes,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
@@ -822,33 +765,28 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
|
||||
"EnvironmentAuth.createPairingLink",
|
||||
)(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,
|
||||
)(
|
||||
function* (input) {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
})
|
||||
.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;
|
||||
});
|
||||
});
|
||||
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 })),
|
||||
);
|
||||
|
||||
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
@@ -868,20 +806,16 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials.revoke(id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkRevocationError({ pairingLinkId: id, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
|
||||
);
|
||||
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => {
|
||||
const subject = input?.subject ?? DEFAULT_SESSION_SUBJECT;
|
||||
const scopes = input?.scopes ?? AuthAdministrativeScopes;
|
||||
return sessions
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
|
||||
sessions
|
||||
.issue({
|
||||
subject,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
method: "bearer-access-token",
|
||||
scopes,
|
||||
scopes: input?.scopes ?? AuthAdministrativeScopes,
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
@@ -896,17 +830,14 @@ export const make = Effect.gen(function* () {
|
||||
token: issued.token,
|
||||
method: "bearer-access-token",
|
||||
scopes: issued.scopes,
|
||||
subject,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies IssuedBearerSession,
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthSessionTokenIssueError({ subject, scopes, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.issueSession"),
|
||||
);
|
||||
};
|
||||
|
||||
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
@@ -917,7 +848,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
|
||||
sessions.revoke(sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ sessionId, cause })),
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeSession"),
|
||||
);
|
||||
|
||||
@@ -925,10 +856,7 @@ export const make = Effect.gen(function* () {
|
||||
sessionId,
|
||||
) =>
|
||||
sessions.revokeAllExcept(sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthOtherSessionsRevocationError({ excludedSessionId: sessionId, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
|
||||
);
|
||||
|
||||
@@ -963,10 +891,7 @@ export const make = Effect.gen(function* () {
|
||||
"EnvironmentAuth.revokeClientSession",
|
||||
)(function* (currentSessionId, targetSessionId) {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new ServerAuthForbiddenOperationError({
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
});
|
||||
return yield* new ServerAuthForbiddenOperationError({});
|
||||
}
|
||||
return yield* revokeSession(targetSessionId);
|
||||
});
|
||||
@@ -992,9 +917,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthWebSocketTokenIssueError({ sessionId: session.sessionId, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
@@ -1024,7 +947,7 @@ export const make = Effect.gen(function* () {
|
||||
scopes: session.scopes,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
(effect) => mapSessionVerificationErrors(effect, "websocket-ticket"),
|
||||
mapSessionVerificationErrors,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,31 +45,6 @@ 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* () {
|
||||
@@ -170,56 +145,7 @@ const makeConcurrentCreateSecretStoreLayer = () =>
|
||||
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
|
||||
);
|
||||
|
||||
const ConcurrentCreationWithoutReadableSecretFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
open: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
method: "open",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeConcurrentCreationWithoutReadableSecretStoreLayer = () =>
|
||||
ServerSecretStore.layer.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(ConcurrentCreationWithoutReadableSecretFileSystemLayer),
|
||||
);
|
||||
|
||||
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;
|
||||
@@ -260,25 +186,6 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves the persist failure when a concurrent secret remains unreadable", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreConcurrentReadError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to read secret session-signing-key after concurrent creation.",
|
||||
);
|
||||
assert.instanceOf(error.cause, ServerSecretStore.SecretStorePersistError);
|
||||
assert.equal(error.cause.operation, "create");
|
||||
assert.instanceOf(error.cause.cause, PlatformError.PlatformError);
|
||||
assert.equal(error.cause.cause.reason._tag, "AlreadyExists");
|
||||
}).pipe(Effect.provide(makeConcurrentCreationWithoutReadableSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses restrictive permissions for the secret directory and files", () =>
|
||||
Effect.gen(function* () {
|
||||
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
|
||||
@@ -325,8 +232,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.include(error.message, "Failed to read secret session-signing-key.");
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
||||
@@ -341,9 +247,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
|
||||
assert.equal(error.operation, "set");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.include(error.message, "Failed to persist secret session-signing-key.");
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
||||
@@ -356,8 +260,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.include(error.message, "Failed to remove secret session-signing-key.");
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
||||
|
||||
@@ -11,137 +11,114 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
const storedSecretErrorContext = {
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
const secretStoreErrorContext = {
|
||||
resource: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
|
||||
"SecretStoreDirectoryCreateError",
|
||||
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
|
||||
"SecretStoreSecureError",
|
||||
{
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
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}.`;
|
||||
return `Failed to secure ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
|
||||
"SecretStoreReadError",
|
||||
{
|
||||
...storedSecretErrorContext,
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to read ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
|
||||
"SecretStoreTemporaryPathGenerationError",
|
||||
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
|
||||
"SecretStoreTemporaryPathError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to create temporary path for ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
|
||||
"SecretStorePersistError",
|
||||
{
|
||||
operation: Schema.Literals(["create", "set"]),
|
||||
...storedSecretErrorContext,
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to persist ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
|
||||
"SecretStoreRandomGenerationError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
byteCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`;
|
||||
return `Failed to generate random bytes for ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
|
||||
"SecretStoreConcurrentReadError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
resource: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read secret ${this.secretName} after concurrent creation.`;
|
||||
return `Failed to read ${this.resource} after concurrent creation.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
|
||||
"SecretStoreRemoveError",
|
||||
{
|
||||
...storedSecretErrorContext,
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to remove ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
|
||||
"SecretStoreDecodeError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode secret ${this.secretName}.`;
|
||||
return `Failed to decode ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
|
||||
"SecretStoreEncodeError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode secret ${this.secretName}.`;
|
||||
return `Failed to encode ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const SecretStoreError = Schema.Union([
|
||||
SecretStoreDirectoryCreateError,
|
||||
SecretStoreDirectorySecureError,
|
||||
SecretStoreSecureError,
|
||||
SecretStoreReadError,
|
||||
SecretStoreTemporaryPathGenerationError,
|
||||
SecretStoreTemporaryPathError,
|
||||
SecretStorePersistError,
|
||||
SecretStoreRandomGenerationError,
|
||||
SecretStoreConcurrentReadError,
|
||||
@@ -161,26 +138,14 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
|
||||
export class ServerSecretStore extends Context.Service<
|
||||
ServerSecretStore,
|
||||
{
|
||||
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 get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<
|
||||
Uint8Array,
|
||||
| SecretStoreReadError
|
||||
| SecretStoreRandomGenerationError
|
||||
| SecretStorePersistError
|
||||
| SecretStoreConcurrentReadError
|
||||
>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
>()("t3/auth/ServerSecretStore") {}
|
||||
|
||||
@@ -190,20 +155,12 @@ export const make = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreDirectoryCreateError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreDirectorySecureError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
new SecretStoreSecureError({
|
||||
resource: `secrets directory ${serverConfig.secretsDir}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -211,33 +168,29 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.readFile(secretPath).pipe(
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: Effect.fail(
|
||||
new SecretStoreReadError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.get"),
|
||||
);
|
||||
};
|
||||
|
||||
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreTemporaryPathGenerationError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
new SecretStoreTemporaryPathError({
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -255,9 +208,7 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStorePersistError({
|
||||
operation: "set",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -286,9 +237,7 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -305,33 +254,30 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreRandomGenerationError({
|
||||
secretName: name,
|
||||
byteCount: bytes,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((generated) =>
|
||||
create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
secretName: name,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
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),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -340,23 +286,20 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.remove(secretPath).pipe(
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreRemoveError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.remove"),
|
||||
);
|
||||
};
|
||||
|
||||
return ServerSecretStore.of({
|
||||
get,
|
||||
|
||||
@@ -6,9 +6,7 @@ import { mapDpopReplayStoreError } from "./dpop.ts";
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: "DPoP proof",
|
||||
secretPath: "dpop-proof.bin",
|
||||
resource: "DPoP proof",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -17,16 +15,10 @@ 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, replayContext);
|
||||
const error = mapDpopReplayStoreError(cause);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
|
||||
if (error._tag === "ServerAuthInvalidCredentialError") {
|
||||
@@ -35,18 +27,11 @@ describe("mapDpopReplayStoreError", () => {
|
||||
});
|
||||
|
||||
it("reports replay-store availability failures as internal errors", () => {
|
||||
const cause = storeFailure("PermissionDenied");
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
|
||||
|
||||
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
|
||||
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
|
||||
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);
|
||||
expect(error.message).toBe("Failed to record DPoP proof replay state.");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
ServerAuthDpopReplayStateRecordError,
|
||||
ServerAuthInvalidCredentialError,
|
||||
type ServerAuthInternalError,
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
@@ -30,19 +31,13 @@ export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest)
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
context: {
|
||||
readonly proofKeyThumbprint: string;
|
||||
readonly proofId: string;
|
||||
readonly replayKey: string;
|
||||
},
|
||||
): ServerAuthInvalidCredentialError | ServerAuthDpopReplayStateRecordError =>
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "DPoP proof replayed.",
|
||||
cause: error,
|
||||
})
|
||||
: new ServerAuthDpopReplayStateRecordError({
|
||||
...context,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
@@ -76,8 +71,6 @@ export const verifyRequestDpopProof = (input: {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthDpopReplayKeyCalculationError({
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -95,12 +88,8 @@ export const verifyRequestDpopProof = (input: {
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapDpopReplayStoreError(error, {
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
replayKey,
|
||||
}),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
Effect.fail(mapDpopReplayStoreError(error)),
|
||||
),
|
||||
);
|
||||
return result.thumbprint;
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import * as AuthHttp from "./http.ts";
|
||||
|
||||
const encodeEnvironmentInternalError = Schema.encodeUnknownSync(EnvironmentInternalError);
|
||||
|
||||
const loggerLayer = (messages: Array<unknown>) =>
|
||||
Logger.layer(
|
||||
[
|
||||
Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
}),
|
||||
],
|
||||
{ mergeWithExisting: false },
|
||||
);
|
||||
|
||||
describe("auth http diagnostics", () => {
|
||||
it.effect("logs and encodes bounded internal diagnostics without exposing secrets", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const cause = new Error("credential=secret-value");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
AuthHttp.failEnvironmentInternal("browser_session_cookie_failed", cause),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(AuthHttp.EnvironmentHttpInternalError);
|
||||
expect(error.failureTag).toBe("Error");
|
||||
expect(error.message).toBe(
|
||||
"Environment API operation failed (browser_session_cookie_failed).",
|
||||
);
|
||||
expect(encodeEnvironmentInternalError(error)).toEqual({
|
||||
_tag: "EnvironmentInternalError",
|
||||
code: "internal_error",
|
||||
reason: "browser_session_cookie_failed",
|
||||
traceId: error.traceId,
|
||||
});
|
||||
|
||||
expect(messages).toEqual([
|
||||
[
|
||||
"environment api operation failed",
|
||||
{
|
||||
reason: "browser_session_cookie_failed",
|
||||
traceId: error.traceId,
|
||||
failureTag: "Error",
|
||||
reasonCount: 1,
|
||||
failureCount: 1,
|
||||
defectCount: 0,
|
||||
interruptionCount: 0,
|
||||
},
|
||||
],
|
||||
]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
|
||||
it.effect("logs request failures without serializing their Error or Cause values", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const request = HttpServerRequest.fromWeb(
|
||||
new Request("https://environment.example.test/api/auth/session"),
|
||||
);
|
||||
const requestCause = Cause.combine(
|
||||
Cause.fail(new Error("credential=secret-value")),
|
||||
Cause.die(new Error("stderr=private-value")),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* AuthHttp.annotateEnvironmentRequest("auth.session");
|
||||
return yield* Effect.failCause(requestCause);
|
||||
}),
|
||||
).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(messages).toEqual([
|
||||
[
|
||||
"environment api request failed",
|
||||
{
|
||||
endpoint: "auth.session",
|
||||
traceId: "unavailable",
|
||||
failureTag: "Error",
|
||||
reasonCount: 2,
|
||||
failureCount: 1,
|
||||
defectCount: 1,
|
||||
interruptionCount: 0,
|
||||
},
|
||||
],
|
||||
]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
|
||||
it.effect("re-propagates nested interruption causes without logging a synthetic 500", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const interruption = Cause.interrupt();
|
||||
const cause = new Error("cancelled", { cause: interruption });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(AuthHttp.failEnvironmentInternal("internal_error", cause));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
|
||||
expect(Option.isNone(Cause.findErrorOption(exit.cause))).toBe(true);
|
||||
}
|
||||
expect(messages).toEqual([]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
});
|
||||
+74
-183
@@ -23,12 +23,10 @@ import {
|
||||
import type { AuthEnvironmentScope } from "@t3tools/contracts";
|
||||
import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Cookies from "effect/unstable/http/Cookies";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -45,72 +43,6 @@ const CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
const MAX_FAILURE_TAG_LENGTH = 128;
|
||||
const MAX_CAUSE_CHAIN_DEPTH = 32;
|
||||
|
||||
const EnvironmentFailureTag = Schema.String.check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(MAX_FAILURE_TAG_LENGTH),
|
||||
);
|
||||
|
||||
function failureLogAttributes(input: unknown) {
|
||||
const cause = Cause.isCause(input) ? input : Cause.fail(input);
|
||||
let failureCount = 0;
|
||||
let defectCount = 0;
|
||||
let interruptionCount = 0;
|
||||
for (const reason of cause.reasons) {
|
||||
switch (reason._tag) {
|
||||
case "Fail":
|
||||
failureCount += 1;
|
||||
break;
|
||||
case "Die":
|
||||
defectCount += 1;
|
||||
break;
|
||||
case "Interrupt":
|
||||
interruptionCount += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const unboundedFailureTag = causeErrorTag(cause).trim() || "Unknown";
|
||||
return {
|
||||
failureTag: unboundedFailureTag.slice(0, MAX_FAILURE_TAG_LENGTH),
|
||||
reasonCount: cause.reasons.length,
|
||||
failureCount,
|
||||
defectCount,
|
||||
interruptionCount,
|
||||
};
|
||||
}
|
||||
|
||||
function findInterruptCause(input: unknown): Cause.Cause<never> | undefined {
|
||||
const seen = new Set<object>();
|
||||
let current = input;
|
||||
for (let depth = 0; depth < MAX_CAUSE_CHAIN_DEPTH; depth += 1) {
|
||||
if (Cause.isCause(current)) {
|
||||
return Cause.hasInterruptsOnly(current) ? (current as Cause.Cause<never>) : undefined;
|
||||
}
|
||||
if (typeof current !== "object" || current === null || seen.has(current)) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(current);
|
||||
if (!("cause" in current)) {
|
||||
return undefined;
|
||||
}
|
||||
current = current.cause;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export class EnvironmentHttpInternalError extends EnvironmentInternalError.extend<EnvironmentHttpInternalError>(
|
||||
"EnvironmentHttpInternalError",
|
||||
)({
|
||||
failureTag: EnvironmentFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Environment API operation failed (${this.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),
|
||||
);
|
||||
@@ -143,11 +75,12 @@ export function annotateEnvironmentRequest(endpoint: string) {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
|
||||
yield* Effect.addFinalizer((exit) =>
|
||||
exit._tag === "Failure" && !Cause.hasInterruptsOnly(exit.cause)
|
||||
exit._tag === "Failure"
|
||||
? Effect.logWarning("environment api request failed", {
|
||||
endpoint,
|
||||
traceId,
|
||||
...failureLogAttributes(exit.cause),
|
||||
errorTag: causeErrorTag(exit.cause),
|
||||
cause: exit.cause,
|
||||
})
|
||||
: Effect.void,
|
||||
);
|
||||
@@ -204,44 +137,19 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a
|
||||
);
|
||||
}
|
||||
|
||||
export const failEnvironmentInternal = Effect.fn("environment.auth.failEnvironmentInternal")(
|
||||
function* (reason: EnvironmentInternalErrorReason, cause: unknown) {
|
||||
const interruptCause = findInterruptCause(cause);
|
||||
if (interruptCause !== undefined) {
|
||||
return yield* Effect.failCause(interruptCause);
|
||||
}
|
||||
export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
|
||||
return Effect.gen(function* () {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
const diagnostics = failureLogAttributes(cause);
|
||||
yield* Effect.logError("environment api operation failed", {
|
||||
reason,
|
||||
traceId,
|
||||
...diagnostics,
|
||||
});
|
||||
return yield* new EnvironmentHttpInternalError({
|
||||
code: "internal_error",
|
||||
reason,
|
||||
traceId,
|
||||
failureTag: diagnostics.failureTag,
|
||||
cause,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
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,
|
||||
}),
|
||||
);
|
||||
if (error !== undefined) {
|
||||
yield* Effect.logError("environment api operation failed", {
|
||||
reason,
|
||||
traceId,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
|
||||
});
|
||||
}
|
||||
|
||||
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
|
||||
scope: AuthEnvironmentScope,
|
||||
@@ -260,8 +168,13 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
return (httpEffect) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
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),
|
||||
),
|
||||
);
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
|
||||
@@ -270,11 +183,7 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
}),
|
||||
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized,
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -294,11 +203,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
return yield* serverAuth.getSessionState(request);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -318,12 +225,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
CookieError: (cause) =>
|
||||
failEnvironmentInternal("browser_session_cookie_failed", cause),
|
||||
}),
|
||||
);
|
||||
).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
|
||||
|
||||
yield* HttpEffect.appendPreResponseHandler((_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
|
||||
@@ -331,14 +233,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return result.response;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
ServerAuthAuthenticatedSessionIssueError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -368,16 +268,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
const proofKeyThumbprint = args.headers.dpop
|
||||
? yield* verifyRequestDpopProof({ request }).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
ServerAuthDpopReplayStateRecordError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthDpopReplayKeyCalculationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
)
|
||||
: undefined;
|
||||
yield* appendCredentialResponseHeaders;
|
||||
@@ -398,16 +296,15 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
},
|
||||
traceRelayRequest,
|
||||
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),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
|
||||
failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -419,10 +316,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return yield* serverAuth.issueWebSocketTicket(session);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthWebSocketTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -445,10 +341,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
return yield* serverAuth.issuePairingCredential(args.payload);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -459,10 +354,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listPairingLinks();
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinksListError: (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -474,10 +368,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkRevocationError: (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -488,10 +381,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listClientSessions(session.sessionId);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionsListError: (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -506,12 +398,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthForbiddenOperationError: () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
ServerAuthSessionRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -523,10 +415,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return { revokedCount };
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthOtherSessionsRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -2,11 +2,7 @@ import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerRequestError,
|
||||
projectCommandErrorFromLiveServerRequest,
|
||||
} from "./project.ts";
|
||||
import { ProjectCommandError } from "./project.ts";
|
||||
|
||||
it("maps declared server failures into structural project command errors", () => {
|
||||
const cause = new EnvironmentInternalError({
|
||||
@@ -15,9 +11,8 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
traceId: "trace-123",
|
||||
});
|
||||
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.code, "internal_error");
|
||||
assert.strictEqual(error.traceId, "trace-123");
|
||||
@@ -28,10 +23,10 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
it("preserves unexpected server failures without deriving the message from them", () => {
|
||||
const cause = new Error("credential abc123 was rejected");
|
||||
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerRequestError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.detail, "Failed to call the running server.");
|
||||
assert.strictEqual(error.message, "Failed to call the running server.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
});
|
||||
+49
-138
@@ -51,148 +51,62 @@ type ProjectCliDispatchCommand = Extract<
|
||||
>;
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
const ProjectCommandOperation = Schema.Literals([
|
||||
"generateProjectCommandId",
|
||||
"callLiveServer",
|
||||
"validateProjectTitle",
|
||||
"resolveProjectTarget",
|
||||
"addProject",
|
||||
]);
|
||||
|
||||
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
|
||||
"ProjectCommandIdGenerationError",
|
||||
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
|
||||
"ProjectCommandError",
|
||||
{
|
||||
operation: Schema.Literal("generateProjectCommandId"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to generate a project command identifier.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
|
||||
"ProjectLiveServerDeclaredResponseError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
code: Schema.String,
|
||||
traceId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed (${this.code}, trace ${this.traceId}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
|
||||
"ProjectLiveServerUndeclaredStatusError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed with undeclared status ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
|
||||
"ProjectLiveServerRequestError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to call the running server.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
|
||||
"ProjectTitleEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("validateProjectTitle"),
|
||||
title: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project title cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
|
||||
"ProjectIdentifierEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project identifier cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
|
||||
"ProjectNotFoundError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.optional(Schema.String),
|
||||
activeProjectCount: Schema.Number,
|
||||
operation: ProjectCommandOperation,
|
||||
detail: Schema.String,
|
||||
code: Schema.optional(Schema.String),
|
||||
traceId: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No active project found for '${this.identifier}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
|
||||
"ProjectAlreadyExistsError",
|
||||
{
|
||||
operation: Schema.Literal("addProject"),
|
||||
projectId: ProjectId,
|
||||
workspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `An active project already exists for '${this.workspaceRoot}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ProjectCommandError = Schema.Union([
|
||||
ProjectCommandIdGenerationError,
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerUndeclaredStatusError,
|
||||
ProjectLiveServerRequestError,
|
||||
ProjectTitleEmptyError,
|
||||
ProjectIdentifierEmptyError,
|
||||
ProjectNotFoundError,
|
||||
ProjectAlreadyExistsError,
|
||||
]);
|
||||
export type ProjectCommandError = typeof ProjectCommandError.Type;
|
||||
|
||||
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectLiveServerDeclaredResponseError({
|
||||
static fromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
detail: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
detail: `Server request failed with undeclared status ${cause.response.status}.`,
|
||||
status: cause.response.status,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectLiveServerUndeclaredStatusError({
|
||||
operation: "callLiveServer",
|
||||
status: cause.response.status,
|
||||
detail: "Failed to call the running server.",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
|
||||
const projectCommandUuid = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectCommandIdGenerationError({
|
||||
new ProjectCommandError({
|
||||
operation: "generateProjectCommandId",
|
||||
detail: "Failed to generate a project command identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -244,9 +158,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* new ProjectTitleEmptyError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "validateProjectTitle",
|
||||
title: explicitTitle,
|
||||
detail: "Project title cannot be empty.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -261,9 +175,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* new ProjectIdentifierEmptyError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "resolveProjectTarget",
|
||||
identifier: input.identifier,
|
||||
detail: "Project identifier cannot be empty.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -290,11 +204,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* new ProjectNotFoundError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "resolveProjectTarget",
|
||||
identifier: trimmedIdentifier,
|
||||
activeProjectCount: activeProjects.length,
|
||||
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
|
||||
detail: `No active project found for '${trimmedIdentifier}'.`,
|
||||
...(normalizedWorkspaceRootResult._tag === "Failure"
|
||||
? { cause: normalizedWorkspaceRootResult.failure }
|
||||
: {}),
|
||||
@@ -316,7 +228,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
});
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
@@ -332,7 +244,7 @@ const dispatchLiveOrchestrationCommand = (
|
||||
} as Parameters<typeof client.orchestration.dispatch>[0]);
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
@@ -464,10 +376,9 @@ const projectAddCommand = Command.make("add", {
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* new ProjectAlreadyExistsError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "addProject",
|
||||
projectId: existingProject.id,
|
||||
workspaceRoot,
|
||||
detail: `An active project already exists for '${workspaceRoot}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
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("redacts OAuth endpoint credentials while retaining exact causes", () => {
|
||||
const tokenEndpoint =
|
||||
"https://user:[email protected]/private/token?client_secret=secret#fragment";
|
||||
const redirectUri =
|
||||
"https://callback-user:callback-password@localhost/private/callback?code=secret#fragment";
|
||||
const cause = new Error("exchange failed");
|
||||
|
||||
const refreshError = CliTokenManager.CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint,
|
||||
cause,
|
||||
});
|
||||
const authorizationError = CliTokenManager.CloudCliAuthorizationError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint,
|
||||
redirectUri,
|
||||
cause,
|
||||
});
|
||||
const timeoutError = CliTokenManager.CloudCliAuthorizationTimeoutError.fromRedirectUri({
|
||||
redirectUri,
|
||||
timeoutMillis: 1000,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(refreshError).toMatchObject({
|
||||
tokenEndpointInputLength: tokenEndpoint.length,
|
||||
tokenEndpointProtocol: "https:",
|
||||
tokenEndpointHostname: "auth.example.test",
|
||||
cause,
|
||||
});
|
||||
expect(authorizationError).toMatchObject({
|
||||
tokenEndpointInputLength: tokenEndpoint.length,
|
||||
tokenEndpointHostname: "auth.example.test",
|
||||
redirectUriInputLength: redirectUri.length,
|
||||
redirectUriHostname: "localhost",
|
||||
cause,
|
||||
});
|
||||
expect(timeoutError).toMatchObject({
|
||||
redirectUriInputLength: redirectUri.length,
|
||||
redirectUriHostname: "localhost",
|
||||
cause,
|
||||
});
|
||||
expect(refreshError.cause).toBe(cause);
|
||||
expect(authorizationError.cause).toBe(cause);
|
||||
expect(timeoutError.cause).toBe(cause);
|
||||
for (const error of [refreshError, authorizationError, timeoutError]) {
|
||||
expect(error).not.toHaveProperty("tokenEndpoint");
|
||||
expect(error).not.toHaveProperty("redirectUri");
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"user:password",
|
||||
"callback-user:callback-password",
|
||||
"/private/",
|
||||
"client_secret=secret",
|
||||
"code=secret",
|
||||
"#fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(serialized).not.toContain(secret);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -20,7 +20,6 @@ import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
|
||||
@@ -28,8 +27,6 @@ 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,
|
||||
@@ -49,223 +46,48 @@ 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",
|
||||
]);
|
||||
type CloudCliCredentialRefreshStage = typeof CloudCliCredentialRefreshStage.Type;
|
||||
|
||||
const CloudCliAuthorizationStage = Schema.Literals([
|
||||
"load-oauth-config",
|
||||
"prepare-pkce",
|
||||
"start-callback-server",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
type CloudCliAuthorizationStage = typeof CloudCliAuthorizationStage.Type;
|
||||
|
||||
function tokenEndpointDiagnosticFields(tokenEndpoint: string | undefined) {
|
||||
if (tokenEndpoint === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(tokenEndpoint);
|
||||
return {
|
||||
tokenEndpointInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { tokenEndpointProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { tokenEndpointHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function redirectUriDiagnosticFields(redirectUri: string | undefined) {
|
||||
if (redirectUri === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(redirectUri);
|
||||
return {
|
||||
redirectUriInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
|
||||
"CloudCliCredentialRemovalError",
|
||||
{
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`;
|
||||
return "Could not remove the stored T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
|
||||
"CloudCliCredentialRefreshError",
|
||||
{
|
||||
stage: CloudCliCredentialRefreshStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
|
||||
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
|
||||
tokenEndpointHostname: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromStage(input: {
|
||||
readonly stage: CloudCliCredentialRefreshStage;
|
||||
readonly cause: unknown;
|
||||
readonly tokenEndpoint?: string;
|
||||
}): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: input.stage,
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
const tokenEndpoint =
|
||||
this.tokenEndpointInputLength === undefined
|
||||
? ""
|
||||
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
|
||||
return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`;
|
||||
return "Could not refresh the T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
|
||||
"CloudCliCredentialReadError",
|
||||
{
|
||||
stage: Schema.Literals(["read-credential", "decode-credential"]),
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ 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 inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`;
|
||||
return "Could not read the stored T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
|
||||
"CloudCliAuthorizationError",
|
||||
{
|
||||
stage: CloudCliAuthorizationStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
|
||||
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
|
||||
tokenEndpointHostname: Schema.optionalKey(Schema.String),
|
||||
redirectUriInputLength: Schema.optionalKey(Schema.Number),
|
||||
redirectUriProtocol: Schema.optionalKey(Schema.String),
|
||||
redirectUriHostname: Schema.optionalKey(Schema.String),
|
||||
callbackHost: Schema.optional(Schema.String),
|
||||
callbackPort: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromStage(input: {
|
||||
readonly stage: CloudCliAuthorizationStage;
|
||||
readonly cause: unknown;
|
||||
readonly tokenEndpoint?: string;
|
||||
readonly redirectUri?: string;
|
||||
readonly callbackHost?: string;
|
||||
readonly callbackPort?: number;
|
||||
}): CloudCliAuthorizationError {
|
||||
return new CloudCliAuthorizationError({
|
||||
stage: input.stage,
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
|
||||
...redirectUriDiagnosticFields(input.redirectUri),
|
||||
...(input.callbackHost === undefined ? {} : { callbackHost: input.callbackHost }),
|
||||
...(input.callbackPort === undefined ? {} : { callbackPort: input.callbackPort }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
const tokenEndpoint =
|
||||
this.tokenEndpointInputLength === undefined
|
||||
? ""
|
||||
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
|
||||
const redirectUri =
|
||||
this.redirectUriInputLength === undefined
|
||||
? ""
|
||||
: ` with a callback URI input of length ${this.redirectUriInputLength}`;
|
||||
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}.`;
|
||||
return "Could not authorize the T3 Connect CLI.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
|
||||
"CloudCliAuthorizationTimeoutError",
|
||||
{
|
||||
redirectUriInputLength: Schema.Number,
|
||||
redirectUriProtocol: Schema.optionalKey(Schema.String),
|
||||
redirectUriHostname: Schema.optionalKey(Schema.String),
|
||||
timeoutMillis: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromRedirectUri(input: {
|
||||
readonly redirectUri: string;
|
||||
readonly timeoutMillis: number;
|
||||
readonly cause: unknown;
|
||||
}): CloudCliAuthorizationTimeoutError {
|
||||
const diagnostics = getUrlDiagnostics(input.redirectUri);
|
||||
return new CloudCliAuthorizationTimeoutError({
|
||||
redirectUriInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
|
||||
timeoutMillis: input.timeoutMillis,
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const callback = this.redirectUriHostname ? ` for ${this.redirectUriHostname}` : "";
|
||||
return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization${callback} (callback URI input length ${this.redirectUriInputLength}).`;
|
||||
return "Timed out waiting for T3 Connect authorization.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,21 +103,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
|
||||
export class CloudCliTokenManager extends Context.Service<
|
||||
CloudCliTokenManager,
|
||||
{
|
||||
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>;
|
||||
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>;
|
||||
}
|
||||
>()("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);
|
||||
}
|
||||
@@ -315,15 +134,9 @@ export const make = Effect.gen(function* () {
|
||||
return token;
|
||||
});
|
||||
|
||||
const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliCredentialRemovalError({
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const clear = secrets
|
||||
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
|
||||
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
|
||||
|
||||
const read = Effect.fn("cloud.cli_token.read")(function* () {
|
||||
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
|
||||
@@ -349,54 +162,21 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "load-oauth-config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: token.refreshToken,
|
||||
client_id: metadata.clientId,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const login = Effect.fn("cloud.cli_token.login")(function* () {
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "load-oauth-config",
|
||||
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) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "prepare-pkce",
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
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 state = yield* crypto.randomUUIDv4;
|
||||
const callback = yield* Deferred.make<string>();
|
||||
const callbackRoute = HttpRouter.add(
|
||||
"GET",
|
||||
@@ -427,21 +207,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
port: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
host: "127.0.0.1",
|
||||
port: 34338,
|
||||
disablePreemptiveShutdown: true,
|
||||
}),
|
||||
),
|
||||
Layer.build,
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "start-callback-server",
|
||||
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);
|
||||
@@ -454,16 +225,13 @@ 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.catchTags({
|
||||
TimeoutError: (cause) =>
|
||||
Effect.fail(
|
||||
CloudCliAuthorizationTimeoutError.fromRedirectUri({
|
||||
redirectUri: metadata.redirectUri,
|
||||
timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
Effect.catchTag("TimeoutError", (cause) =>
|
||||
Effect.fail(
|
||||
new CloudCliAuthorizationTimeoutError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "authorization_code",
|
||||
@@ -471,43 +239,26 @@ export const make = Effect.gen(function* () {
|
||||
redirect_uri: metadata.redirectUri,
|
||||
client_id: metadata.clientId,
|
||||
code_verifier: verifier,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
|
||||
const token = yield* read().pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead),
|
||||
);
|
||||
const token = yield* read();
|
||||
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((refreshed) =>
|
||||
persist(refreshed).pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
|
||||
});
|
||||
|
||||
const getExisting = semaphore.withPermits(1)(getExistingNoLock());
|
||||
const getExisting = semaphore.withPermits(1)(
|
||||
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
|
||||
);
|
||||
const hasCredential = semaphore.withPermits(1)(
|
||||
read().pipe(
|
||||
Effect.map(Option.isSome),
|
||||
Effect.mapError(CloudCliCredentialReadError.fromCredentialRead),
|
||||
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
|
||||
),
|
||||
);
|
||||
const get = semaphore.withPermits(1)(
|
||||
@@ -515,14 +266,8 @@ export const make = Effect.gen(function* () {
|
||||
const token = yield* getExistingNoLock();
|
||||
return Option.isSome(token)
|
||||
? token.value
|
||||
: yield* Effect.scoped(login()).pipe(
|
||||
Effect.flatMap((authorized) =>
|
||||
persist(authorized).pipe(
|
||||
Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
|
||||
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
|
||||
);
|
||||
|
||||
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
|
||||
|
||||
@@ -66,9 +66,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: "cloud-link-ed25519-key-pair",
|
||||
secretPath: "cloud-link-ed25519-key-pair.bin",
|
||||
resource: "environment signing key pair",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
@@ -89,24 +87,4 @@ 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,6 +27,17 @@ 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"],
|
||||
) {
|
||||
@@ -35,13 +46,7 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
|
||||
return Option.none<EnvironmentKeyPair>();
|
||||
}
|
||||
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreDecodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(keyPairDecodeError),
|
||||
);
|
||||
return Option.some(decoded);
|
||||
});
|
||||
@@ -51,35 +56,22 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
|
||||
keyPair: EnvironmentKeyPair,
|
||||
) {
|
||||
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreEncodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(keyPairEncodeError),
|
||||
);
|
||||
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
|
||||
Effect.as(keyPair),
|
||||
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,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
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),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,45 +1,23 @@
|
||||
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 Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
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 { EnvironmentHttpInternalServerError } from "@t3tools/contracts";
|
||||
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
|
||||
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import {
|
||||
CloudRelayRequestError,
|
||||
consumeCloudReplayGuards,
|
||||
reconcileDesiredCloudLink,
|
||||
} from "./http.ts";
|
||||
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
|
||||
const encodeEnvironmentHttpInternalServerError = Schema.encodeUnknownSync(
|
||||
EnvironmentHttpInternalServerError,
|
||||
);
|
||||
const decodeEnvironmentHttpInternalServerError = Schema.decodeUnknownSync(
|
||||
EnvironmentHttpInternalServerError,
|
||||
);
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: "cloud replay guard",
|
||||
secretPath: "cloud-replay-guard.bin",
|
||||
resource: "cloud replay guard",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -62,56 +40,6 @@ function makeSecretStore(
|
||||
};
|
||||
}
|
||||
|
||||
function reconcileWith(input: {
|
||||
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
|
||||
readonly httpClient?: HttpClient.HttpClient;
|
||||
readonly secretStore?: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}) {
|
||||
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
input.secretStore ?? 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");
|
||||
|
||||
@@ -165,84 +93,6 @@ describe("consumeCloudReplayGuards", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("CloudRelayRequestError", () => {
|
||||
it("classifies response failures without deriving its message from the cause", () => {
|
||||
const requestUrl =
|
||||
"https://relay-user:[email protected]/private/environment-links?token=relay-secret#relay-fragment";
|
||||
const request = HttpClientRequest.post(requestUrl);
|
||||
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",
|
||||
requestUrlInputLength: requestUrl.length,
|
||||
requestUrlProtocol: "https:",
|
||||
requestUrlHostname: "relay.example.test",
|
||||
responseStatus: 502,
|
||||
cause,
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("url");
|
||||
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);
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"/private/environment-links",
|
||||
"relay-secret",
|
||||
"relay-fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(Object.values(error).join(" ")).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps internal causes out of encoded HTTP error bodies", () => {
|
||||
const cause = new Error("private upstream detail");
|
||||
const error = new EnvironmentHttpInternalServerError({
|
||||
operation: "generate_link_proof",
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodeEnvironmentHttpInternalServerError(error)).toEqual({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "generate_link_proof",
|
||||
message: "Could not generate environment link proof.",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes legacy message-only HTTP errors during rolling deployments", () => {
|
||||
const error = decodeEnvironmentHttpInternalServerError({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
message: "Legacy environment server failure.",
|
||||
});
|
||||
|
||||
expect(error.operation).toBeUndefined();
|
||||
expect(error.message).toBe("Legacy environment server failure.");
|
||||
});
|
||||
|
||||
describe("relay request tracing", () => {
|
||||
it.effect("does not accept an unauthenticated request trace parent", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -310,127 +160,48 @@ 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(
|
||||
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
|
||||
);
|
||||
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
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("attributes link-proof secret failures to proof generation", () => {
|
||||
const cause = new Error("private secret-store detail");
|
||||
const secretFailure = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "environment-key-pair",
|
||||
secretPath: "environment-key-pair.json",
|
||||
cause,
|
||||
});
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
challenge: "relay-link-challenge",
|
||||
expiresAt: "2099-01-01T00:00:00.000Z",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const secretStore = makeSecretStore(unusedSecretStoreOperation);
|
||||
|
||||
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,
|
||||
secretStore: {
|
||||
...secretStore,
|
||||
get: () => Effect.fail(secretFailure),
|
||||
},
|
||||
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "generate_link_proof",
|
||||
cause: secretFailure,
|
||||
});
|
||||
expect(error.message).toBe("Could not generate environment link proof.");
|
||||
expect(error.cause).toBe(secretFailure);
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("redacts relay transport failures behind a stable structural message", () => {
|
||||
const transportCause = new Error("upstream included a sensitive database password");
|
||||
const capturedLogs: Array<ReadonlyArray<unknown>> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
capturedLogs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
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" },
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "relay_request",
|
||||
relayOperation: "create-link-challenge",
|
||||
relayPhase: "send-request",
|
||||
message: "T3 Connect relay create-link-challenge failed during send-request.",
|
||||
cause: {
|
||||
_tag: "CloudRelayRequestError",
|
||||
operation: "create-link-challenge",
|
||||
phase: "send-request",
|
||||
},
|
||||
});
|
||||
expect(error.message).not.toContain(transportCause.message);
|
||||
expect(capturedLogs).toHaveLength(1);
|
||||
const logFields = capturedLogs[0]?.find(
|
||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||
);
|
||||
expect(logFields).toMatchObject({
|
||||
operation: "relay_request",
|
||||
relayOperation: "create-link-challenge",
|
||||
relayPhase: "send-request",
|
||||
causeTag: "CloudRelayRequestError",
|
||||
});
|
||||
expect(logFields).not.toHaveProperty("cause");
|
||||
expect(capturedLogs[0]?.filter((value) => typeof value === "string").join(" ")).not.toContain(
|
||||
transportCause.message,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+116
-333
@@ -9,10 +9,7 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpConflictError,
|
||||
type EnvironmentHttpInternalOperation,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentHttpRelayOperation,
|
||||
EnvironmentHttpRelayPhase,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -44,7 +41,6 @@ import {
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -52,13 +48,8 @@ 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 * 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 { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
@@ -94,145 +85,26 @@ const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
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: EnvironmentHttpRelayOperation,
|
||||
phase: EnvironmentHttpRelayPhase,
|
||||
method: Schema.Literal("POST"),
|
||||
requestUrlInputLength: Schema.Number,
|
||||
requestUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
requestUrlHostname: Schema.optionalKey(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 {
|
||||
const diagnostics = getUrlDiagnostics(input.url);
|
||||
const context = {
|
||||
operation: input.operation,
|
||||
method: "POST" as const,
|
||||
requestUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { requestUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { requestUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
if (input.cause._tag === "SchemaError") {
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase: "decode-response",
|
||||
...(input.responseStatus === undefined ? {} : { responseStatus: input.responseStatus }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
if (!HttpClientError.isHttpClientError(input.cause)) {
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase: "encode-request",
|
||||
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({
|
||||
...context,
|
||||
phase,
|
||||
...(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)),
|
||||
);
|
||||
|
||||
function errorDiagnosticTag(cause: unknown): string {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"_tag" in cause &&
|
||||
typeof cause._tag === "string"
|
||||
) {
|
||||
return cause._tag;
|
||||
}
|
||||
if (cause instanceof Error) return cause.name;
|
||||
return typeof cause;
|
||||
}
|
||||
|
||||
type EnvironmentCloudInternalErrorContext =
|
||||
| Exclude<EnvironmentHttpInternalOperation, "relay_request">
|
||||
| {
|
||||
readonly operation: "relay_request";
|
||||
readonly relayOperation: CloudRelayRequestError["operation"];
|
||||
readonly relayPhase: CloudRelayRequestError["phase"];
|
||||
readonly responseStatus?: number;
|
||||
};
|
||||
|
||||
const failEnvironmentCloudInternalError =
|
||||
(context: EnvironmentCloudInternalErrorContext) =>
|
||||
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> => {
|
||||
const error =
|
||||
typeof context === "string"
|
||||
? new EnvironmentHttpInternalServerError({ operation: context, cause })
|
||||
: new EnvironmentHttpInternalServerError({ ...context, cause });
|
||||
const logContext =
|
||||
typeof context === "string"
|
||||
? { operation: context, causeTag: errorDiagnosticTag(cause) }
|
||||
: { ...context, causeTag: errorDiagnosticTag(cause) };
|
||||
return Effect.logError(error.message, logContext).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
(message: string) =>
|
||||
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
|
||||
Effect.logError(message, { cause }).pipe(
|
||||
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
|
||||
);
|
||||
};
|
||||
|
||||
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error);
|
||||
|
||||
const requireRelayUrl = relayUrlConfig.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudRelayConfigurationError({
|
||||
configKey: "T3CODE_RELAY_URL",
|
||||
cause,
|
||||
() =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -254,12 +126,11 @@ export function consumeCloudReplayGuards(input: {
|
||||
input.names.map((name) =>
|
||||
input.secrets.create(name, input.value).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ concurrency: input.names.length },
|
||||
@@ -282,10 +153,9 @@ function validateCloudMintPublicKey(
|
||||
): Effect.Effect<void, EnvironmentHttpBadRequestError> {
|
||||
return Effect.try({
|
||||
try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
|
||||
catch: (cause) =>
|
||||
catch: () =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_cloud_mint_public_key",
|
||||
cause,
|
||||
message: "Cloud mint public key must be a valid Ed25519 public key.",
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((key) =>
|
||||
@@ -293,7 +163,7 @@ function validateCloudMintPublicKey(
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_cloud_mint_public_key",
|
||||
message: "Cloud mint public key must be a valid Ed25519 public key.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -306,28 +176,28 @@ function validateRelayConfigPayload(
|
||||
if (!isSecureRelayUrl(payload.relayUrl)) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_relay_url",
|
||||
message: "Relay URL must be a secure absolute HTTPS URL.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_relay_issuer",
|
||||
message: "Relay issuer must be a secure absolute HTTPS URL.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.environmentCredential.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "missing_relay_environment_credential",
|
||||
message: "Relay environment credential is required.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.cloudUserId.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "missing_cloud_user_id",
|
||||
message: "Cloud user id is required.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -337,7 +207,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) =>
|
||||
@@ -354,14 +224,17 @@ function validateLinkedCloudUser(input: {
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new EnvironmentHttpConflictError({
|
||||
reason: "linked_to_different_cloud_account",
|
||||
message:
|
||||
"This environment is already linked to a different cloud account. Unlink it before switching accounts.",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function readInstalledCloudUserId(secrets: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
function readInstalledCloudUserId(
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
|
||||
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -486,7 +359,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
|
||||
})
|
||||
) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_managed_endpoint_origin",
|
||||
message: "Invalid managed endpoint origin.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
@@ -529,23 +402,24 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
|
||||
const requestUrl = requestAbsoluteUrl(httpRequest);
|
||||
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_managed_endpoint_origin",
|
||||
message: "Invalid managed endpoint origin.",
|
||||
});
|
||||
}
|
||||
const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return proof satisfies RelayEnvironmentLinkProof;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
}),
|
||||
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."),
|
||||
),
|
||||
);
|
||||
|
||||
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
|
||||
@@ -565,6 +439,7 @@ const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(fu
|
||||
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
|
||||
if (!ok) {
|
||||
return yield* new EnvironmentCloudEndpointUnavailableError({
|
||||
message: "Managed endpoint runtime could not be started.",
|
||||
endpointRuntimeStatus,
|
||||
});
|
||||
}
|
||||
@@ -597,22 +472,22 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
|
||||
yield* requireEnvironmentScope(AuthRelayWriteScope);
|
||||
return yield* applyCloudRelayConfig(dependencies, payload);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
}),
|
||||
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."),
|
||||
),
|
||||
);
|
||||
|
||||
const relayClientRequest = <A>(
|
||||
dependencies: CloudHttpDependencies,
|
||||
input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly token: string;
|
||||
readonly payload: unknown;
|
||||
@@ -622,46 +497,14 @@ const relayClientRequest = <A>(
|
||||
HttpClientRequest.post(input.url).pipe(
|
||||
HttpClientRequest.bearerToken(input.token),
|
||||
HttpClientRequest.bodyJson(input.payload),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
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)}`,
|
||||
}),
|
||||
),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
@@ -670,15 +513,14 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
function* (dependencies: CloudHttpDependencies, localOrigin: string) {
|
||||
const localUrl = yield* Effect.try({
|
||||
try: () => new URL(localOrigin),
|
||||
catch: (cause) =>
|
||||
catch: () =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_local_environment_origin",
|
||||
cause,
|
||||
message: "Could not resolve local environment origin.",
|
||||
}),
|
||||
});
|
||||
if (localUrl.origin !== localOrigin) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_local_environment_origin",
|
||||
message: "Could not resolve local environment origin.",
|
||||
});
|
||||
}
|
||||
const localWsOrigin = localOrigin.replace(/^http/u, "ws");
|
||||
@@ -688,7 +530,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EnvironmentHttpUnauthorizedError({
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
@@ -697,7 +539,6 @@ 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: {
|
||||
@@ -723,20 +564,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
},
|
||||
},
|
||||
localOrigin,
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
}),
|
||||
);
|
||||
const link = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-environment-link",
|
||||
url: `${relayUrl}/v1/client/environment-links`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -747,15 +576,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
},
|
||||
schema: RelayEnvironmentLinkResponse,
|
||||
});
|
||||
yield* setCliDesiredCloudLink(true).pipe(
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_desired_link_state",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_desired_link_state"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_desired_link_state"),
|
||||
}),
|
||||
);
|
||||
yield* setCliDesiredCloudLink(true);
|
||||
return yield* applyCloudRelayConfig(dependencies, {
|
||||
relayUrl,
|
||||
relayIssuer: link.relayIssuer,
|
||||
@@ -763,31 +584,18 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
environmentCredential: link.environmentCredential,
|
||||
cloudMintPublicKey: link.cloudMintPublicKey,
|
||||
endpointRuntime: link.endpointRuntime,
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
CloudRelayConfigurationError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_relay_url_configuration")(error),
|
||||
CloudRelayRequestError: (error) =>
|
||||
failEnvironmentCloudInternalError({
|
||||
operation: "relay_request",
|
||||
relayOperation: error.operation,
|
||||
relayPhase: error.phase,
|
||||
...(error.responseStatus === undefined ? {} : { responseStatus: error.responseStatus }),
|
||||
})(error),
|
||||
CloudCliCredentialRefreshError: (error) =>
|
||||
failEnvironmentCloudInternalError("refresh_cloud_cli_credential")(error),
|
||||
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialReadError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -825,9 +633,10 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
|
||||
yield* requireEnvironmentScope(AuthRelayReadScope);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("read_relay_configuration"),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
@@ -849,13 +658,10 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
yield* setCliDesiredCloudLink(false);
|
||||
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
|
||||
},
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"remove_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("remove_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("remove_relay_configuration"),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
@@ -870,13 +676,10 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_cloud_preferences",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
@@ -927,7 +730,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
reason: "invalid_cloud_health_request",
|
||||
message: "Invalid cloud health request.",
|
||||
});
|
||||
}
|
||||
const proof = proofOption.value;
|
||||
@@ -941,7 +744,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
});
|
||||
if (!consumedReplayGuards) {
|
||||
return yield* new EnvironmentHttpConflictError({
|
||||
reason: "cloud_health_request_replayed",
|
||||
message: "Cloud health request was already consumed.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -984,26 +787,17 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
|
||||
ServerAuthCloudHealthJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_health_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"answer_cloud_health_request",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
}),
|
||||
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."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
|
||||
@@ -1055,7 +849,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
reason: "invalid_cloud_mint_request",
|
||||
message: "Invalid cloud mint request.",
|
||||
});
|
||||
}
|
||||
const proof = proofOption.value;
|
||||
@@ -1069,7 +863,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
});
|
||||
if (!consumedReplayGuards) {
|
||||
return yield* new EnvironmentHttpConflictError({
|
||||
reason: "cloud_mint_request_replayed",
|
||||
message: "Cloud mint request was already consumed.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1114,28 +908,17 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentCloudInternalError("create_cloud_pairing_link")(error),
|
||||
ServerAuthCloudMintJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_mint_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"issue_cloud_connection_credential",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
}),
|
||||
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."),
|
||||
),
|
||||
);
|
||||
|
||||
export const connectHttpApiLayer = HttpApiBuilder.group(
|
||||
|
||||
@@ -171,8 +171,20 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
throw new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
});
|
||||
}
|
||||
|
||||
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
(error as { _tag?: unknown })._tag === "GitHubCliError"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -466,12 +478,16 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return fakeGhOutput("");
|
||||
},
|
||||
catch: (error) =>
|
||||
GitHubCli.isGitHubCliError(error)
|
||||
isGitHubCliError(error)
|
||||
? error
|
||||
: new GitHubCli.GitHubCliCommandError({
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: error,
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `Failed to simulate gh checkout: ${error.message}`
|
||||
: "Failed to simulate gh checkout.",
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -482,10 +498,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
|
||||
if (!cloneUrls) {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected repository lookup: ${repository}`),
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -503,10 +520,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -583,10 +601,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected repository create: ${input.repository}`),
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
@@ -1322,10 +1341,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2463,10 +2483,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2493,10 +2514,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliAuthenticationError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not authenticated"),
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
BrowserOtlpTraceCollectionError,
|
||||
BrowserOtlpTraceDecodeError,
|
||||
BrowserOtlpTraceExportError,
|
||||
isLoopbackHostname,
|
||||
resolveDevRedirectUrl,
|
||||
} from "./http.ts";
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
@@ -31,73 +25,3 @@ describe("http dev routing", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser OTLP diagnostics", () => {
|
||||
it("retains decode causes without retaining the trace payload", () => {
|
||||
const cause = new Error("private trace payload detail");
|
||||
const error = BrowserOtlpTraceDecodeError.fromPayload({ resourceSpans: [] }, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
resourceSpanCount: 0,
|
||||
cause,
|
||||
message: "Failed to decode browser OTLP payload with 0 resource spans.",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("bodyJson");
|
||||
});
|
||||
|
||||
it("describes malformed trace payloads without inspecting unsafe fields", () => {
|
||||
const cause = new Error("private malformed trace payload detail");
|
||||
const error = BrowserOtlpTraceDecodeError.fromPayload(
|
||||
{ resourceSpans: "private malformed resource spans" },
|
||||
cause,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
resourceSpanCount: 0,
|
||||
cause,
|
||||
message: "Failed to decode browser OTLP payload with 0 resource spans.",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("resourceSpans");
|
||||
});
|
||||
|
||||
it("retains local collection causes with a structural record count", () => {
|
||||
const records = [{ type: "private trace record" }];
|
||||
const cause = new Error("private local collector detail");
|
||||
const error = BrowserOtlpTraceCollectionError.fromRecords(records, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
recordCount: 1,
|
||||
cause,
|
||||
message: "Failed to collect 1 browser OTLP trace records locally.",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("records");
|
||||
});
|
||||
|
||||
it("redacts collector URL credentials while retaining the exact cause", () => {
|
||||
const collectorUrl =
|
||||
"https://collector-user:[email protected]/private/v1/traces?access_token=collector-secret#collector-fragment";
|
||||
const cause = new Error("collector transport failed");
|
||||
const error = BrowserOtlpTraceExportError.fromCollectorUrl(collectorUrl, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
collectorUrlInputLength: collectorUrl.length,
|
||||
collectorUrlProtocol: "https:",
|
||||
collectorUrlHostname: "traces.example.test",
|
||||
cause,
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("collectorUrl");
|
||||
for (const secret of [
|
||||
"collector-user",
|
||||
"collector-password",
|
||||
"/private/v1/traces",
|
||||
"collector-secret",
|
||||
"collector-fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
+29
-133
@@ -5,13 +5,12 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Data from "effect/Data";
|
||||
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 Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
HttpBody,
|
||||
@@ -36,8 +35,9 @@ 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,8 +80,13 @@ const authenticateRawRouteWithScope = (
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
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),
|
||||
),
|
||||
);
|
||||
if (!session.scopes.includes(scope)) {
|
||||
return yield* failEnvironmentScopeRequired(scope);
|
||||
@@ -103,95 +108,10 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
|
||||
}),
|
||||
);
|
||||
|
||||
function errorDiagnosticTag(cause: unknown): string {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"_tag" in cause &&
|
||||
typeof cause._tag === "string"
|
||||
) {
|
||||
return cause._tag;
|
||||
}
|
||||
if (cause instanceof Error) return cause.name;
|
||||
return typeof cause;
|
||||
}
|
||||
|
||||
export class BrowserOtlpTraceDecodeError extends Schema.TaggedErrorClass<BrowserOtlpTraceDecodeError>()(
|
||||
"BrowserOtlpTraceDecodeError",
|
||||
{
|
||||
resourceSpanCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromPayload(payload: unknown, cause: unknown): BrowserOtlpTraceDecodeError {
|
||||
const resourceSpanCount =
|
||||
typeof payload === "object" &&
|
||||
payload !== null &&
|
||||
"resourceSpans" in payload &&
|
||||
Array.isArray(payload.resourceSpans)
|
||||
? payload.resourceSpans.length
|
||||
: 0;
|
||||
|
||||
return new BrowserOtlpTraceDecodeError({
|
||||
resourceSpanCount,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Failed to decode browser OTLP payload with ${this.resourceSpanCount} resource spans.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserOtlpTraceCollectionError extends Schema.TaggedErrorClass<BrowserOtlpTraceCollectionError>()(
|
||||
"BrowserOtlpTraceCollectionError",
|
||||
{
|
||||
recordCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromRecords(
|
||||
records: ReadonlyArray<unknown>,
|
||||
cause: unknown,
|
||||
): BrowserOtlpTraceCollectionError {
|
||||
return new BrowserOtlpTraceCollectionError({
|
||||
recordCount: records.length,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Failed to collect ${this.recordCount} browser OTLP trace records locally.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserOtlpTraceExportError extends Schema.TaggedErrorClass<BrowserOtlpTraceExportError>()(
|
||||
"BrowserOtlpTraceExportError",
|
||||
{
|
||||
collectorUrlInputLength: Schema.Number,
|
||||
collectorUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
collectorUrlHostname: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCollectorUrl(collectorUrl: string, cause: unknown): BrowserOtlpTraceExportError {
|
||||
const diagnostics = getUrlDiagnostics(collectorUrl);
|
||||
return new BrowserOtlpTraceExportError({
|
||||
collectorUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { collectorUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { collectorUrlHostname: diagnostics.hostname }),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const collector =
|
||||
this.collectorUrlHostname === undefined
|
||||
? "the configured collector"
|
||||
: this.collectorUrlHostname;
|
||||
return `Failed to export browser OTLP traces to ${collector} (collector URL input length ${this.collectorUrlInputLength}).`;
|
||||
}
|
||||
}
|
||||
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
|
||||
readonly cause: unknown;
|
||||
readonly bodyJson: OtlpTracer.TraceData;
|
||||
}> {}
|
||||
|
||||
export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
@@ -207,31 +127,15 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
|
||||
yield* Effect.try({
|
||||
try: () => decodeOtlpTraceRecords(bodyJson),
|
||||
catch: (cause) => BrowserOtlpTraceDecodeError.fromPayload(bodyJson, cause),
|
||||
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
|
||||
}).pipe(
|
||||
Effect.flatMap((records) =>
|
||||
browserTraceCollector
|
||||
.record(records)
|
||||
.pipe(
|
||||
Effect.catchDefect((cause) =>
|
||||
Effect.fail(BrowserOtlpTraceCollectionError.fromRecords(records, cause)),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((records) => browserTraceCollector.record(records)),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to decode browser OTLP traces", {
|
||||
cause,
|
||||
bodyJson,
|
||||
}),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BrowserOtlpTraceDecodeError: (error) =>
|
||||
Effect.logWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
resourceSpanCount: error.resourceSpanCount,
|
||||
causeTag: errorDiagnosticTag(error.cause),
|
||||
}),
|
||||
BrowserOtlpTraceCollectionError: (error) =>
|
||||
Effect.logWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
recordCount: error.recordCount,
|
||||
causeTag: errorDiagnosticTag(error.cause),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
if (otlpTracesUrl === undefined) {
|
||||
@@ -245,23 +149,15 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
.pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.as(HttpServerResponse.empty({ status: 204 })),
|
||||
Effect.mapError((cause) =>
|
||||
BrowserOtlpTraceExportError.fromCollectorUrl(otlpTracesUrl, cause),
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to export browser OTLP traces", {
|
||||
cause,
|
||||
otlpTracesUrl,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() =>
|
||||
HttpServerResponse.text("Trace export failed.", { status: 502 }),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BrowserOtlpTraceExportError: (error) =>
|
||||
Effect.logWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
collectorUrlInputLength: error.collectorUrlInputLength,
|
||||
...(error.collectorUrlProtocol === undefined
|
||||
? {}
|
||||
: { collectorUrlProtocol: error.collectorUrlProtocol }),
|
||||
...(error.collectorUrlHostname === undefined
|
||||
? {}
|
||||
: { collectorUrlHostname: error.collectorUrlHostname }),
|
||||
causeTag: errorDiagnosticTag(error.cause),
|
||||
}).pipe(Effect.as(HttpServerResponse.text("Trace export failed.", { status: 502 }))),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
import * as Cause from "effect/Cause";
|
||||
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 Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import * as Keybindings from "./keybindings.ts";
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
|
||||
@@ -33,6 +34,12 @@ const makeKeybindingsLayer = () => {
|
||||
);
|
||||
};
|
||||
|
||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError((error) => error.detail),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -216,21 +223,15 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "keybindings.malformed-config",
|
||||
message: "Expected the keybindings configuration to be a JSON array.",
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
},
|
||||
]);
|
||||
assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("ignores invalid entries in runtime and reports them as issues", () => {
|
||||
const logs: ReadonlyArray<unknown>[] = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
logs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const secret = "private-shortcut-payload";
|
||||
|
||||
return Effect.gen(function* () {
|
||||
it.effect("ignores invalid entries in runtime and reports them as issues", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
|
||||
yield* fs.writeFileString(
|
||||
@@ -239,7 +240,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
JSON.stringify([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+d+o", command: "terminal.new" },
|
||||
{ key: "mod+x", command: secret },
|
||||
{ key: "mod+x", command: "invalid.command" },
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -249,55 +250,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
});
|
||||
|
||||
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === secret));
|
||||
assert.isFalse(
|
||||
configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
|
||||
);
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
index: 1,
|
||||
message: "The keybinding entry contains an invalid shortcut or when expression.",
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
},
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
index: 2,
|
||||
message: "Expected a keybinding entry with key, command, and optional when fields.",
|
||||
message: configState.issues[1]?.message ?? "",
|
||||
},
|
||||
]);
|
||||
const invalidEntryLog = logs.find((log) => {
|
||||
const attributes = log[1];
|
||||
return (
|
||||
String(log[0]).includes("ignoring invalid keybinding entry") &&
|
||||
typeof attributes === "object" &&
|
||||
attributes !== null &&
|
||||
Reflect.get(attributes, "entryIndex") === 2
|
||||
);
|
||||
});
|
||||
if (!invalidEntryLog) {
|
||||
return assert.fail("Expected invalid keybinding warning");
|
||||
}
|
||||
const attributes = invalidEntryLog[1];
|
||||
if (typeof attributes !== "object" || attributes === null) {
|
||||
return assert.fail("Expected structured invalid keybinding attributes");
|
||||
}
|
||||
assert.equal(Reflect.get(attributes, "validationStage"), "entry-schema");
|
||||
assert.equal(Reflect.get(attributes, "validationInputKind"), "object");
|
||||
assert.equal(Reflect.get(attributes, "validationInputSize"), 2);
|
||||
assert.equal(Reflect.get(attributes, "validationHasKeyField"), true);
|
||||
assert.equal(Reflect.get(attributes, "validationHasCommandField"), true);
|
||||
assert.equal(Reflect.get(attributes, "validationHasWhenField"), false);
|
||||
assert.equal(Reflect.get(attributes, "causeReasonCount"), 1);
|
||||
assert.isFalse("entry" in attributes);
|
||||
assert.isFalse("cause" in attributes);
|
||||
assert.isFalse(String(invalidEntryLog[0]).includes(secret));
|
||||
assert.isFalse(Object.values(attributes).some((value) => String(value).includes(secret)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeKeybindingsLayer(),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"upserts missing default keybindings on startup without overriding existing command rules",
|
||||
@@ -332,9 +301,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
);
|
||||
|
||||
it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
|
||||
const logs: ReadonlyArray<unknown>[] = [];
|
||||
const messages: string[] = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
logs.push(Array.isArray(message) ? message : [message]);
|
||||
messages.push(String(message));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -352,21 +321,11 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
|
||||
|
||||
const warning = logs.find((log) =>
|
||||
String(log[0]).includes("skipping default keybinding due to shortcut conflict"),
|
||||
assert.isTrue(
|
||||
messages.some((message) =>
|
||||
message.includes("skipping default keybinding due to shortcut conflict"),
|
||||
),
|
||||
);
|
||||
if (!warning) {
|
||||
return assert.fail("Expected shortcut conflict warning");
|
||||
}
|
||||
const attributes = warning[1];
|
||||
if (typeof attributes !== "object" || attributes === null) {
|
||||
return assert.fail("Expected structured shortcut conflict attributes");
|
||||
}
|
||||
assert.equal(Reflect.get(attributes, "defaultCommand"), "terminal.toggle");
|
||||
assert.equal(Reflect.get(attributes, "conflictingCommand"), "script.custom-action.run");
|
||||
assert.equal(Reflect.get(attributes, "hasWhenContext"), false);
|
||||
assert.isFalse("key" in attributes);
|
||||
assert.isFalse("when" in attributes);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
@@ -484,24 +443,15 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(result)) {
|
||||
return assert.fail("Expected malformed config update to fail");
|
||||
}
|
||||
assert.equal(result.failure._tag, "KeybindingsConfigError");
|
||||
assert.equal(result.failure.operation, "decode");
|
||||
assert.isTrue(Schema.isSchemaError(result.failure.cause));
|
||||
assert.equal(
|
||||
result.failure.message,
|
||||
`Keybindings config operation 'decode' failed at ${keybindingsConfigPath}.`,
|
||||
);
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(result, "expected JSON array");
|
||||
|
||||
const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
|
||||
assert.equal(persistedRaw, "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("returns stable structured decode errors across retries", () =>
|
||||
it.effect("reports non-array config parse errors without duplicate prefix", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
|
||||
@@ -516,12 +466,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(firstResult)) {
|
||||
return assert.fail("Expected first malformed config update to fail");
|
||||
}
|
||||
assert.equal(firstResult.failure.operation, "decode");
|
||||
assert.isTrue(Schema.isSchemaError(firstResult.failure.cause));
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(firstResult, "expected JSON array");
|
||||
|
||||
const secondResult = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
@@ -529,13 +475,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(secondResult)) {
|
||||
return assert.fail("Expected second malformed config update to fail");
|
||||
}
|
||||
assert.equal(secondResult.failure.operation, "decode");
|
||||
assert.isTrue(Schema.isSchemaError(secondResult.failure.cause));
|
||||
assert.equal(secondResult.failure.message, firstResult.failure.message);
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(secondResult, "expected JSON array");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
@@ -555,11 +496,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(result)) {
|
||||
return assert.fail("Expected update in a read-only directory to fail");
|
||||
}
|
||||
assert.equal(result.failure.operation, "write");
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(result, "failed to write keybindings config");
|
||||
|
||||
yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
|
||||
|
||||
|
||||
+49
-139
@@ -44,7 +44,6 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
@@ -187,53 +186,23 @@ export interface KeybindingsChangeEvent {
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
}
|
||||
|
||||
const MALFORMED_KEYBINDINGS_CONFIG_MESSAGE =
|
||||
"Expected the keybindings configuration to be a JSON array.";
|
||||
const INVALID_KEYBINDING_ENTRY_MESSAGE =
|
||||
"Expected a keybinding entry with key, command, and optional when fields.";
|
||||
const INVALID_KEYBINDING_RULE_MESSAGE =
|
||||
"The keybinding entry contains an invalid shortcut or when expression.";
|
||||
function trimIssueMessage(message: string): string {
|
||||
const trimmed = message.trim();
|
||||
return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
|
||||
}
|
||||
|
||||
function keybindingsCauseLogAttributes(cause: Cause.Cause<unknown>) {
|
||||
function malformedConfigIssue(detail: string): ServerConfigIssue {
|
||||
return {
|
||||
errorTag: causeErrorTag(cause),
|
||||
causeReasonCount: cause.reasons.length,
|
||||
causeFailureCount: cause.reasons.filter(Cause.isFailReason).length,
|
||||
causeDefectCount: cause.reasons.filter(Cause.isDieReason).length,
|
||||
causeInterruptionCount: cause.reasons.filter(Cause.isInterruptReason).length,
|
||||
kind: "keybindings.malformed-config",
|
||||
message: trimIssueMessage(detail),
|
||||
};
|
||||
}
|
||||
|
||||
function keybindingsValidationInputLogAttributes(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return { validationInputKind: "string", validationInputSize: value.length };
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return { validationInputKind: "array", validationInputSize: value.length };
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return {
|
||||
validationInputKind: "object",
|
||||
validationInputSize: Object.keys(value).length,
|
||||
validationHasKeyField: Object.hasOwn(value, "key"),
|
||||
validationHasCommandField: Object.hasOwn(value, "command"),
|
||||
validationHasWhenField: Object.hasOwn(value, "when"),
|
||||
};
|
||||
}
|
||||
return { validationInputKind: value === null ? "null" : typeof value };
|
||||
}
|
||||
|
||||
function keybindingsValidationLogAttributes(input: {
|
||||
readonly stage: "document" | "entry-schema" | "resolved-rule";
|
||||
readonly value: unknown;
|
||||
readonly cause: Cause.Cause<unknown>;
|
||||
readonly index?: number;
|
||||
}) {
|
||||
function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
|
||||
return {
|
||||
validationStage: input.stage,
|
||||
...(input.index === undefined ? {} : { entryIndex: input.index }),
|
||||
...keybindingsValidationInputLogAttributes(input.value),
|
||||
...keybindingsCauseLogAttributes(input.cause),
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: trimIssueMessage(detail),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -337,7 +306,7 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "access",
|
||||
detail: "failed to access keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -348,7 +317,7 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "read",
|
||||
detail: "failed to read keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -368,24 +337,20 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "decode",
|
||||
detail: "expected JSON array",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.forEach(rawConfig, (entry, index) =>
|
||||
return yield* Effect.forEach(rawConfig, (entry) =>
|
||||
Effect.gen(function* () {
|
||||
const decodedRule = decodeKeybindingRuleExit(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "entry-schema",
|
||||
value: entry,
|
||||
cause: decodedRule.cause,
|
||||
index,
|
||||
}),
|
||||
entry,
|
||||
error: Cause.pretty(decodedRule.cause),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
@@ -393,12 +358,8 @@ const make = Effect.gen(function* () {
|
||||
if (resolved._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "resolved-rule",
|
||||
value: entry,
|
||||
cause: resolved.cause,
|
||||
index,
|
||||
}),
|
||||
entry,
|
||||
error: Cause.pretty(resolved.cause),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
@@ -421,22 +382,10 @@ const make = Effect.gen(function* () {
|
||||
const rawConfig = yield* readRawConfig;
|
||||
const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
|
||||
if (decodedEntries._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring malformed keybindings config", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "document",
|
||||
value: rawConfig,
|
||||
cause: decodedEntries.cause,
|
||||
}),
|
||||
});
|
||||
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
|
||||
return {
|
||||
keybindings: [],
|
||||
issues: [
|
||||
{
|
||||
kind: "keybindings.malformed-config",
|
||||
message: MALFORMED_KEYBINDINGS_CONFIG_MESSAGE,
|
||||
},
|
||||
],
|
||||
issues: [malformedConfigIssue(detail)],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -445,38 +394,26 @@ const make = Effect.gen(function* () {
|
||||
for (const [index, entry] of decodedEntries.value.entries()) {
|
||||
const decodedRule = decodeKeybindingRuleExit(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
issues.push({
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: INVALID_KEYBINDING_ENTRY_MESSAGE,
|
||||
});
|
||||
const detail = Cause.pretty(decodedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "entry-schema",
|
||||
value: entry,
|
||||
cause: decodedRule.cause,
|
||||
index,
|
||||
}),
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
|
||||
if (resolvedRule._tag === "Failure") {
|
||||
issues.push({
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: INVALID_KEYBINDING_RULE_MESSAGE,
|
||||
});
|
||||
const detail = Cause.pretty(resolvedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "resolved-rule",
|
||||
value: entry,
|
||||
cause: resolvedRule.cause,
|
||||
index,
|
||||
}),
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -488,14 +425,6 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
return encodeKeybindingsConfigPrettyJson(rules).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "encode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.flatMap((encoded) =>
|
||||
writeFileStringAtomically({
|
||||
@@ -504,16 +433,16 @@ const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "write",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to write keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -558,13 +487,7 @@ const make = Effect.gen(function* () {
|
||||
"skipping startup keybindings default sync because config has issues",
|
||||
{
|
||||
path: keybindingsConfigPath,
|
||||
issueCount: runtimeConfig.issues.length,
|
||||
malformedConfigIssueCount: runtimeConfig.issues.filter(
|
||||
(issue) => issue.kind === "keybindings.malformed-config",
|
||||
).length,
|
||||
invalidEntryIssueCount: runtimeConfig.issues.filter(
|
||||
(issue) => issue.kind === "keybindings.invalid-entry",
|
||||
).length,
|
||||
issues: runtimeConfig.issues,
|
||||
},
|
||||
);
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
@@ -576,7 +499,8 @@ const make = Effect.gen(function* () {
|
||||
const shortcutConflictWarnings: Array<{
|
||||
defaultCommand: KeybindingRule["command"];
|
||||
conflictingCommand: KeybindingRule["command"];
|
||||
hasWhenContext: boolean;
|
||||
key: string;
|
||||
when: string | null;
|
||||
}> = [];
|
||||
for (const defaultRule of DEFAULT_KEYBINDINGS) {
|
||||
if (existingCommands.has(defaultRule.command)) {
|
||||
@@ -589,7 +513,8 @@ const make = Effect.gen(function* () {
|
||||
shortcutConflictWarnings.push({
|
||||
defaultCommand: defaultRule.command,
|
||||
conflictingCommand: conflictingEntry.command,
|
||||
hasWhenContext: defaultRule.when !== undefined,
|
||||
key: defaultRule.key,
|
||||
when: defaultRule.when ?? null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -600,7 +525,8 @@ const make = Effect.gen(function* () {
|
||||
path: keybindingsConfigPath,
|
||||
defaultCommand: conflict.defaultCommand,
|
||||
conflictingCommand: conflict.conflictingCommand,
|
||||
hasWhenContext: conflict.hasWhenContext,
|
||||
key: conflict.key,
|
||||
when: conflict.when,
|
||||
reason: "shortcut context already used by existing rule",
|
||||
});
|
||||
}
|
||||
@@ -648,22 +574,13 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "prepare-directory",
|
||||
detail: "failed to prepare keybindings config directory",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.void
|
||||
: Effect.logWarning("keybindings config revalidation failed", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsCauseLogAttributes(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
// Debounce watch events so the file is fully written before we read it.
|
||||
// Editors emit multiple events per save (truncate, write, rename) and
|
||||
@@ -680,14 +597,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.void
|
||||
: Effect.logWarning("keybindings config watcher failed", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsCauseLogAttributes(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkIn(watcherScope),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
|
||||
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
|
||||
const invocation: McpInvocationContext.McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
providerSessionId: "provider-session-1",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
|
||||
expect(error).toMatchObject({
|
||||
capability: "preview",
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
});
|
||||
expect(error.message).toBe("MCP credential does not grant the preview capability.");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,5 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
type ProviderInstanceId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -30,11 +26,7 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
capability,
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
message: `MCP credential does not grant the ${capability} capability.`,
|
||||
});
|
||||
}
|
||||
return invocation;
|
||||
|
||||
@@ -20,7 +20,6 @@ import { CommandId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -99,50 +98,6 @@ function makeMemorySecretStore() {
|
||||
}
|
||||
|
||||
describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
it("redacts relay URL secrets from log attributes", () => {
|
||||
const relayUrl =
|
||||
"https://relay-user:[email protected]/private/path?token=relay-secret#fragment";
|
||||
const attributes = AgentAwarenessRelay.relayUrlLogAttributes(relayUrl);
|
||||
|
||||
expect(attributes).toEqual({
|
||||
relayUrlConfigured: true,
|
||||
relayUrlInputLength: relayUrl.length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
});
|
||||
const renderedAttributes = Object.values(attributes).join(" ");
|
||||
expect(renderedAttributes).not.toContain("relay-user");
|
||||
expect(renderedAttributes).not.toContain("relay-password");
|
||||
expect(renderedAttributes).not.toContain("private/path");
|
||||
expect(renderedAttributes).not.toContain("relay-secret");
|
||||
expect(renderedAttributes).not.toContain("fragment");
|
||||
});
|
||||
|
||||
it("summarizes publish causes without serializing nested failures or defects", () => {
|
||||
const privateFailureDetail = "private relay response body";
|
||||
const privateDefectDetail = "private relay defect detail";
|
||||
const cause = Cause.combine(
|
||||
Cause.fail({
|
||||
_tag: "RelayPublishError",
|
||||
cause: new Error(privateFailureDetail),
|
||||
detail: privateFailureDetail,
|
||||
}),
|
||||
Cause.die(new Error(privateDefectDetail)),
|
||||
);
|
||||
const attributes = AgentAwarenessRelay.relayPublishCauseLogAttributes(cause);
|
||||
|
||||
expect(attributes).toEqual({
|
||||
causeReasonCount: 2,
|
||||
causeFailureCount: 1,
|
||||
causeDefectCount: 1,
|
||||
causeInterruptionCount: 0,
|
||||
causeFailureTags: ["RelayPublishError"],
|
||||
});
|
||||
const renderedAttributes = Object.values(attributes).join(" ");
|
||||
expect(renderedAttributes).not.toContain(privateFailureDetail);
|
||||
expect(renderedAttributes).not.toContain(privateDefectDetail);
|
||||
});
|
||||
|
||||
it("distinguishes pending link credentials from disabled publication", () => {
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
RELAY_ACTIVITY_PUBLISH_TYP,
|
||||
signRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -99,44 +98,6 @@ export function isAgentActivityPublishingEnabled(value: string | null): boolean
|
||||
return value === "true";
|
||||
}
|
||||
|
||||
export function relayUrlLogAttributes(relayUrl: string | undefined) {
|
||||
if (relayUrl === undefined) {
|
||||
return { relayUrlConfigured: false };
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(relayUrl);
|
||||
return {
|
||||
relayUrlConfigured: true,
|
||||
relayUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export function relayPublishCauseLogAttributes(cause: Cause.Cause<unknown>) {
|
||||
const failureTags = cause.reasons.flatMap((reason) => {
|
||||
if (!Cause.isFailReason(reason)) {
|
||||
return [];
|
||||
}
|
||||
const error = reason.error;
|
||||
if (
|
||||
typeof error !== "object" ||
|
||||
error === null ||
|
||||
!("_tag" in error) ||
|
||||
typeof error._tag !== "string"
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [error._tag];
|
||||
});
|
||||
return {
|
||||
causeReasonCount: cause.reasons.length,
|
||||
causeFailureCount: cause.reasons.filter(Cause.isFailReason).length,
|
||||
causeDefectCount: cause.reasons.filter(Cause.isDieReason).length,
|
||||
causeInterruptionCount: cause.reasons.filter(Cause.isInterruptReason).length,
|
||||
causeFailureTags: [...new Set(failureTags)],
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAgentActivityPublishingStartupState(input: {
|
||||
readonly relayConfigured: boolean;
|
||||
readonly publishEnabled: boolean;
|
||||
@@ -456,12 +417,12 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
|
||||
publishThreadUnsafe(threadId).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("agent activity publish failed", {
|
||||
Effect.catchCause((cause) => {
|
||||
return Effect.logWarning("agent activity publish failed", {
|
||||
threadId,
|
||||
...relayPublishCauseLogAttributes(cause),
|
||||
}),
|
||||
),
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
Effect.withSpan("AgentAwarenessRelay.publishThread"),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
@@ -506,7 +467,7 @@ export const make = Effect.gen(function* () {
|
||||
if (logEnabledWhenReady) {
|
||||
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
|
||||
yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
|
||||
...relayUrlLogAttributes(relayConfig?.url),
|
||||
relayUrl: relayConfig?.url,
|
||||
});
|
||||
}
|
||||
return;
|
||||
@@ -538,7 +499,7 @@ export const make = Effect.gen(function* () {
|
||||
break;
|
||||
case "enabled":
|
||||
yield* Effect.logInfo("agent activity publishing enabled", {
|
||||
...relayUrlLogAttributes(relayConfig?.url),
|
||||
relayUrl: relayConfig?.url,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -4027,31 +4027,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("continues browser OTLP requests when local trace collection defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const payload = yield* makeBrowserOtlpPayload("client.test");
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
browserTraceCollector: {
|
||||
record: () => Effect.die(new Error("private local collector failure")),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = yield* HttpClient.post("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
cookie: yield* getAuthenticatedSessionCookieHeader(),
|
||||
"content-type": "application/json",
|
||||
},
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc server.upsertKeybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const rule: KeybindingRule = {
|
||||
|
||||
@@ -309,14 +309,13 @@ export const make = Effect.gen(function* () {
|
||||
yield* runStartupPhase(
|
||||
"keybindings.start",
|
||||
keybindings.start.pipe(
|
||||
Effect.catchTags({
|
||||
KeybindingsConfigError: (error) =>
|
||||
Effect.logWarning("failed to start keybindings runtime", {
|
||||
path: error.configPath,
|
||||
operation: error.operation,
|
||||
errorTag: error._tag,
|
||||
}),
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to start keybindings runtime", {
|
||||
path: error.configPath,
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -33,7 +33,7 @@ const makeServerSettingsLayer = () =>
|
||||
),
|
||||
);
|
||||
|
||||
const makeFailingSecretStoreLayer = (cause: ServerSecretStore.SecretStoreReadError) =>
|
||||
const makeFailingSecretStoreLayer = (cause: ServerSecretStore.SecretStoreError) =>
|
||||
Layer.succeed(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
ServerSecretStore.ServerSecretStore.of({
|
||||
@@ -55,8 +55,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
description: "Secret backend unavailable.",
|
||||
});
|
||||
const cause = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "provider environment secret",
|
||||
secretPath: "/test/secrets/provider-environment-secret.bin",
|
||||
resource: "provider environment secret",
|
||||
cause: platformCause,
|
||||
});
|
||||
const configLayer = Layer.fresh(
|
||||
|
||||
@@ -4,9 +4,8 @@ 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 { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
@@ -346,63 +345,11 @@ describe("AzureDevOpsCli.layer", () => {
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
|
||||
assert.strictEqual(error.operation, "execute");
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.argumentCount, 2);
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = "/missing/repo";
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
syscall: "chdir",
|
||||
pathOrDescriptor: cwd,
|
||||
});
|
||||
const cause = new VcsProcessSpawnError({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
cwd,
|
||||
argumentCount: 2,
|
||||
cause: platformCause,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
|
||||
assert.strictEqual(error.cwd, cwd);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps invalid pull request output diagnostics structured", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.outputLength, 8);
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
|
||||
assert.exists(error.cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,11 +1,9 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
@@ -21,61 +19,16 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const azureDevOpsCommandErrorFields = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
argumentCount: NonNegativeInt,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
|
||||
"AzureDevOpsCliUnavailableError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
|
||||
"AzureDevOpsCliError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
|
||||
"AzureDevOpsCliAuthenticationError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
|
||||
"AzureDevOpsPullRequestNotFoundError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Pull request not found. Check the PR number or URL and try again.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
|
||||
"AzureDevOpsCommandFailedError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -85,109 +38,53 @@ export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<Azure
|
||||
readonly operation: "execute";
|
||||
readonly command: "az";
|
||||
readonly cwd: string;
|
||||
readonly argumentCount: number;
|
||||
},
|
||||
cause: VcsError,
|
||||
error: VcsError | unknown,
|
||||
): AzureDevOpsCliError {
|
||||
const fields = { ...context, cause };
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: az") || lower.includes("enoent")) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail:
|
||||
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
cause._tag === "VcsProcessSpawnError" &&
|
||||
cause.cause instanceof PlatformError.PlatformError &&
|
||||
cause.cause.reason._tag === "NotFound" &&
|
||||
cause.cause.reason.pathOrDescriptor !== context.cwd &&
|
||||
cause.cause.reason.syscall !== "chdir"
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
) {
|
||||
return new AzureDevOpsCliUnavailableError(fields);
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (cause._tag === "VcsProcessExitError") {
|
||||
if (cause.failureKind === "authentication") {
|
||||
return new AzureDevOpsCliAuthenticationError(fields);
|
||||
}
|
||||
if (cause.failureKind === "not-found") {
|
||||
return new AzureDevOpsPullRequestNotFoundError(fields);
|
||||
}
|
||||
if (
|
||||
lower.includes("pull request") &&
|
||||
(lower.includes("not found") || lower.includes("does not exist"))
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new AzureDevOpsCommandFailedError(fields);
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const azureDevOpsDecodeErrorFields = {
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
outputLength: NonNegativeInt,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
|
||||
"AzureDevOpsPullRequestListDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("listPullRequests"),
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid PR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
|
||||
"AzureDevOpsPullRequestDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("getPullRequest"),
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid pull request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
|
||||
"getRepositoryCloneUrls",
|
||||
"getDefaultBranch",
|
||||
"createRepository",
|
||||
]);
|
||||
|
||||
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
|
||||
"AzureDevOpsRepositoryDecodeError",
|
||||
{
|
||||
operation: AzureDevOpsRepositoryDecodeOperation,
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const AzureDevOpsCliError = Schema.Union([
|
||||
AzureDevOpsCliUnavailableError,
|
||||
AzureDevOpsCliAuthenticationError,
|
||||
AzureDevOpsPullRequestNotFoundError,
|
||||
AzureDevOpsCommandFailedError,
|
||||
AzureDevOpsPullRequestListDecodeError,
|
||||
AzureDevOpsPullRequestDecodeError,
|
||||
AzureDevOpsRepositoryDecodeError,
|
||||
]);
|
||||
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
|
||||
|
||||
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
|
||||
|
||||
export interface AzureDevOpsRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
@@ -249,6 +146,17 @@ export class AzureDevOpsCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/AzureDevOpsCli") {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeChangeRequestId(reference: string): string {
|
||||
const trimmed = reference.trim().replace(/^#/, "");
|
||||
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
|
||||
@@ -317,18 +225,19 @@ function parseRepositorySpecifier(repository: string): {
|
||||
function decodeAzureDevOpsJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
|
||||
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AzureDevOpsRepositoryDecodeError({
|
||||
(error) =>
|
||||
new AzureDevOpsCliError({
|
||||
operation,
|
||||
command: "az",
|
||||
cwd,
|
||||
outputLength: raw.length,
|
||||
cause,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -348,13 +257,8 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
AzureDevOpsCommandFailedError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
argumentCount: input.args.length,
|
||||
},
|
||||
AzureDevOpsCliError.fromVcsError(
|
||||
{ operation: "execute", command: "az", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
@@ -393,11 +297,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestListDecodeError({
|
||||
new AzureDevOpsCliError({
|
||||
operation: "listPullRequests",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
outputLength: raw.length,
|
||||
detail: "Azure DevOps CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -427,11 +331,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestDecodeError({
|
||||
new AzureDevOpsCliError({
|
||||
operation: "getPullRequest",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
outputLength: raw.length,
|
||||
detail: "Azure DevOps CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -453,6 +357,7 @@ export const make = Effect.gen(function* () {
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
@@ -478,7 +383,13 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"createRepository",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
@@ -510,7 +421,13 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getDefaultBranch",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
|
||||
),
|
||||
|
||||
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
|
||||
|
||||
it.effect("adds change-request context while retaining Azure CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
argumentCount: 2,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
|
||||
@@ -544,61 +544,6 @@ it.effect("preserves the HTTP client failure without deriving the domain message
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
|
||||
const responseBody = '{"error":{"message":"credential=secret-value"}}';
|
||||
const { layer } = makeLayer({
|
||||
response: () => new Response(responseBody, { status: 403 }),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const error = yield* bitbucket
|
||||
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.status, 403);
|
||||
assert.strictEqual(error.responseBodyLength, responseBody.length);
|
||||
assert.notProperty(error, "responseBody");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
|
||||
);
|
||||
assert.notInclude(error.message, "secret-value");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
|
||||
const cause = new Error("response stream failed");
|
||||
const { layer } = makeLayer({
|
||||
response: () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start: (controller) => controller.error(cause),
|
||||
}),
|
||||
{ status: 502 },
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const error = yield* bitbucket
|
||||
.getPullRequest({ cwd: "/repo", reference: "42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.status, 502);
|
||||
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
|
||||
assert.strictEqual(error.cause.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
|
||||
const { git, layer } = makeLayer({
|
||||
response: () =>
|
||||
@@ -685,9 +630,8 @@ it.effect("preserves Git checkout failures without deriving the domain message f
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.reference, "42");
|
||||
assert.strictEqual(error.operation, "checkoutPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
|
||||
|
||||
@@ -6,7 +6,6 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlProviderAuth,
|
||||
type SourceControlRepositoryCloneUrls,
|
||||
@@ -37,156 +36,20 @@ const BitbucketApiEnvConfig = Config.all({
|
||||
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
|
||||
});
|
||||
|
||||
const BitbucketApiOperation = Schema.Literals([
|
||||
"resolveRepository",
|
||||
"getRepository",
|
||||
"getBranchingModel",
|
||||
"getPullRequest",
|
||||
"listPullRequests",
|
||||
"createRepository",
|
||||
"createPullRequest",
|
||||
"probeAuth",
|
||||
"checkoutPullRequest",
|
||||
]);
|
||||
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
|
||||
|
||||
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
|
||||
"BitbucketRepositoryLocatorError",
|
||||
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
|
||||
"BitbucketApiError",
|
||||
{
|
||||
repository: Schema.String,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
|
||||
"BitbucketRequestError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
|
||||
"BitbucketResponseError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
responseBodyLength: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
|
||||
"BitbucketResponseBodyReadError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
|
||||
"BitbucketResponseDecodeError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
|
||||
"BitbucketRepositoryVcsResolveError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
|
||||
"BitbucketRepositoryRemotesListError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
|
||||
"BitbucketRepositoryRemoteNotFoundError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
|
||||
"BitbucketPullRequestBodyReadError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
bodyFile: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
|
||||
"BitbucketCheckoutError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reference: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
|
||||
}
|
||||
}
|
||||
|
||||
export const BitbucketApiError = Schema.Union([
|
||||
BitbucketRepositoryLocatorError,
|
||||
BitbucketRequestError,
|
||||
BitbucketResponseError,
|
||||
BitbucketResponseBodyReadError,
|
||||
BitbucketResponseDecodeError,
|
||||
BitbucketRepositoryVcsResolveError,
|
||||
BitbucketRepositoryRemotesListError,
|
||||
BitbucketRepositoryRemoteNotFoundError,
|
||||
BitbucketPullRequestBodyReadError,
|
||||
BitbucketCheckoutError,
|
||||
]);
|
||||
export type BitbucketApiError = typeof BitbucketApiError.Type;
|
||||
export const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
|
||||
const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
full_name: TrimmedNonEmptyString,
|
||||
@@ -346,14 +209,16 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
|
||||
}
|
||||
|
||||
function requireRepositoryLocator(
|
||||
operation: string,
|
||||
repository: string,
|
||||
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
|
||||
const locator = parseBitbucketRepositorySlug(repository);
|
||||
return locator
|
||||
? Effect.succeed(locator)
|
||||
: Effect.fail(
|
||||
new BitbucketRepositoryLocatorError({
|
||||
repository,
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Bitbucket repositories must be specified as workspace/repository.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -474,24 +339,20 @@ function authFromConfig(
|
||||
}
|
||||
|
||||
function responseError(
|
||||
operation: BitbucketApiOperation,
|
||||
operation: string,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseBodyReadError({
|
||||
operation,
|
||||
status: response.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketResponseError({
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
status: response.status,
|
||||
responseBodyLength: body.length,
|
||||
detail:
|
||||
body.trim().length > 0
|
||||
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
|
||||
: `Bitbucket returned HTTP ${response.status}.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -518,7 +379,7 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
const decodeResponse = <S extends Schema.Top>(
|
||||
operation: BitbucketApiOperation,
|
||||
operation: string,
|
||||
schema: S,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
@@ -527,9 +388,9 @@ export const make = Effect.gen(function* () {
|
||||
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseDecodeError({
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
status: success.status,
|
||||
detail: "Bitbucket returned invalid JSON for the requested resource.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -538,15 +399,16 @@ export const make = Effect.gen(function* () {
|
||||
})(response);
|
||||
|
||||
const executeJson = <S extends Schema.Top>(
|
||||
operation: BitbucketApiOperation,
|
||||
operation: string,
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
schema: S,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketRequestError({
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Failed to send the Bitbucket request.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -571,8 +433,9 @@ export const make = Effect.gen(function* () {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketRepositoryVcsResolveError({
|
||||
cwd: input.cwd,
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -580,8 +443,9 @@ export const make = Effect.gen(function* () {
|
||||
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketRepositoryRemotesListError({
|
||||
cwd: input.cwd,
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to list remotes for ${input.cwd}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -593,8 +457,9 @@ export const make = Effect.gen(function* () {
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
|
||||
return yield* new BitbucketRepositoryRemoteNotFoundError({
|
||||
cwd: input.cwd,
|
||||
return yield* new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -735,7 +600,7 @@ export const make = Effect.gen(function* () {
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
|
||||
createRepository: (input) =>
|
||||
requireRepositoryLocator(input.repository).pipe(
|
||||
requireRepositoryLocator("createRepository", input.repository).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"createRepository",
|
||||
@@ -760,9 +625,9 @@ export const make = Effect.gen(function* () {
|
||||
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketPullRequestBodyReadError({
|
||||
cwd: input.cwd,
|
||||
bodyFile: input.bodyFile,
|
||||
new BitbucketApiError({
|
||||
operation: "createPullRequest",
|
||||
detail: `Failed to read pull request body file ${input.bodyFile}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -878,9 +743,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) =>
|
||||
isBitbucketApiError(cause)
|
||||
? cause
|
||||
: new BitbucketCheckoutError({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
: new BitbucketApiError({
|
||||
operation: "checkoutPullRequest",
|
||||
detail: "Failed to check out the Bitbucket pull request.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -53,10 +53,11 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
|
||||
|
||||
it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const upstreamCause = new Error("raw upstream failure");
|
||||
const cause = new BitbucketApi.BitbucketRequestError({
|
||||
const cause = new BitbucketApi.BitbucketApiError({
|
||||
operation: "getRepository",
|
||||
cause: upstreamCause,
|
||||
detail: "upstream detail that should remain in the cause",
|
||||
status: 503,
|
||||
cause: new Error("raw upstream failure"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
getRepositoryCloneUrls: () => Effect.fail(cause),
|
||||
@@ -85,7 +86,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(upstreamCause.message), false);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
@@ -31,27 +30,6 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
it("does not classify a missing cwd as an unavailable gh executable", () => {
|
||||
const context = { command: "gh", cwd: "/repo" } as const;
|
||||
const missingCwd = new VcsProcessSpawnError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
cwd: context.cwd,
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "access",
|
||||
pathOrDescriptor: context.cwd,
|
||||
}),
|
||||
});
|
||||
|
||||
const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
|
||||
|
||||
assert.equal(commandFailure._tag, "GitHubCliCommandError");
|
||||
assert.strictEqual(commandFailure.cause, missingCwd);
|
||||
assert.notProperty(commandFailure, "operation");
|
||||
});
|
||||
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
@@ -296,7 +274,6 @@ describe("GitHubCli.layer", () => {
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
failureKind: "not-found",
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
});
|
||||
@@ -311,7 +288,6 @@ describe("GitHubCli.layer", () => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Pull request not found"), true);
|
||||
assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
|
||||
assert.strictEqual(error.command, "gh");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -19,163 +18,67 @@ import {
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const gitHubCliFailureFields = {
|
||||
command: Schema.Literal("gh"),
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
} as const;
|
||||
|
||||
export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
|
||||
"GitHubCliUnavailableError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI (`gh`) is required but not available on PATH.";
|
||||
}
|
||||
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
|
||||
"GitHubCliAuthenticationError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "gh";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
|
||||
"GitHubPullRequestNotFoundError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Pull request not found. Check the PR number or URL and try again.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
|
||||
"GitHubCliCommandError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const gitHubCliDecodeFields = {
|
||||
command: Schema.Literal("gh"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
} as const;
|
||||
|
||||
export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
|
||||
"GitHubPullRequestListDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid PR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
|
||||
"GitHubChangeRequestListDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid change request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
|
||||
"GitHubPullRequestDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid pull request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in getPullRequest: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
|
||||
"GitHubRepositoryDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const GitHubCliError = Schema.Union([
|
||||
GitHubCliUnavailableError,
|
||||
GitHubCliAuthenticationError,
|
||||
GitHubPullRequestNotFoundError,
|
||||
GitHubCliCommandError,
|
||||
GitHubPullRequestListDecodeError,
|
||||
GitHubChangeRequestListDecodeError,
|
||||
GitHubPullRequestDecodeError,
|
||||
GitHubRepositoryDecodeError,
|
||||
]);
|
||||
export type GitHubCliError = typeof GitHubCliError.Type;
|
||||
|
||||
export const isGitHubCliError = Schema.is(GitHubCliError);
|
||||
|
||||
export function fromVcsError(
|
||||
context: {
|
||||
readonly command: "gh";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitHubCliError {
|
||||
if (
|
||||
error._tag === "VcsProcessSpawnError" &&
|
||||
error.cause instanceof PlatformError.PlatformError &&
|
||||
error.cause.reason._tag === "NotFound" &&
|
||||
error.cause.reason.module === "ChildProcess" &&
|
||||
error.cause.reason.method === "spawn"
|
||||
) {
|
||||
return new GitHubCliUnavailableError({ ...context, cause: error });
|
||||
}
|
||||
|
||||
if (error._tag === "VcsProcessExitError") {
|
||||
if (error.failureKind === "authentication") {
|
||||
return new GitHubCliAuthenticationError({ ...context, cause: error });
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
if (error.failureKind === "not-found") {
|
||||
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
return new GitHubCliCommandError({ ...context, cause: error });
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
@@ -247,14 +150,22 @@ export class GitHubCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/GitHubCli") {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
|
||||
);
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
@@ -303,6 +214,27 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitHubJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
@@ -315,7 +247,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitHubCliError.fromVcsError(
|
||||
{ operation: "execute", command: "gh", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -343,9 +282,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubPullRequestListDecodeError({
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -375,9 +316,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubPullRequestDecodeError({
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -397,15 +340,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitHubRepositoryDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitHub CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
|
||||
@@ -70,9 +70,11 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
|
||||
|
||||
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
|
||||
const cause = new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: "/repo",
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -158,17 +158,23 @@ export const make = Effect.gen(function* () {
|
||||
})),
|
||||
)
|
||||
: Effect.fail(
|
||||
new GitHubCli.GitHubChangeRequestListDecodeError({
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
Effect.catchTags({
|
||||
GitHubCliError: (error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
@@ -180,7 +186,7 @@ export const make = Effect.gen(function* () {
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -315,11 +315,10 @@ layer("GitLabCli.layer", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
@@ -331,37 +330,11 @@ layer("GitLabCli.layer", (it) => {
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
|
||||
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
assert.strictEqual(error.command, "glab");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps non-merge-request not-found failures generic", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 project not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "missing/project",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error._tag, "GitLabCliCommandError");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Match from "effect/Match";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -22,56 +21,13 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const gitLabCliExecutionErrorContext = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("glab"),
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
const gitLabCliDecodeErrorContext = {
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(
|
||||
"GitLabCliUnavailableError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI (`glab`) is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(
|
||||
"GitLabCliAuthenticationError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(
|
||||
"GitLabMergeRequestNotFoundError",
|
||||
{
|
||||
...gitLabCliExecutionErrorContext,
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
|
||||
}
|
||||
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -81,145 +37,52 @@ export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<Git
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
},
|
||||
error: VcsError,
|
||||
error: VcsError | unknown,
|
||||
): GitLabCliError {
|
||||
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
|
||||
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return GitLabCliCommandError.fromVcsError(
|
||||
{
|
||||
operation: context.operation,
|
||||
command: context.command,
|
||||
cwd: context.cwd,
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
|
||||
"GitLabCliCommandError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI command failed.";
|
||||
}
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
return Match.valueTags(error, {
|
||||
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
|
||||
VcsProcessExitError: (cause) => {
|
||||
switch (cause.failureKind) {
|
||||
case "authentication":
|
||||
return new GitLabCliAuthenticationError({ ...context, cause });
|
||||
case "not-found":
|
||||
case "command-failed":
|
||||
case undefined:
|
||||
return new GitLabCliCommandError({ ...context, cause });
|
||||
}
|
||||
},
|
||||
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsOutputDecodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(
|
||||
"GitLabMergeRequestListDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("listMergeRequests"),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid MR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(
|
||||
"GitLabMergeRequestDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("getMergeRequest"),
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid merge request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(
|
||||
"GitLabRepositoryDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
|
||||
repository: Schema.optional(Schema.String),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(
|
||||
"GitLabNamespaceDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("createRepository"),
|
||||
namespacePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid namespace JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const GitLabCliError = Schema.Union([
|
||||
GitLabCliUnavailableError,
|
||||
GitLabCliAuthenticationError,
|
||||
GitLabMergeRequestNotFoundError,
|
||||
GitLabCliCommandError,
|
||||
GitLabMergeRequestListDecodeError,
|
||||
GitLabMergeRequestDecodeError,
|
||||
GitLabRepositoryDecodeError,
|
||||
GitLabNamespaceDecodeError,
|
||||
]);
|
||||
export type GitLabCliError = typeof GitLabCliError.Type;
|
||||
export const isGitLabCliError = Schema.is(GitLabCliError);
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
@@ -239,6 +102,17 @@ export interface GitLabRepositoryCloneUrls {
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<
|
||||
GitLabCli,
|
||||
{
|
||||
@@ -294,6 +168,15 @@ export class GitLabCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/GitLabCli") {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "VcsProcessSpawnError"
|
||||
);
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
@@ -309,14 +192,6 @@ const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
|
||||
);
|
||||
const decodeGitLabDefaultBranch = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
|
||||
);
|
||||
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
@@ -327,6 +202,27 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
command: "glab",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
@@ -387,10 +283,7 @@ function parseRepositoryPath(repository: string): {
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const run = (
|
||||
input: Parameters<GitLabCli["Service"]["execute"]>[0],
|
||||
mapError: (error: VcsError) => GitLabCliError,
|
||||
) =>
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
@@ -399,32 +292,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError(mapError));
|
||||
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
run(input, (error) =>
|
||||
GitLabCliCommandError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
);
|
||||
|
||||
const executeMergeRequest = (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) =>
|
||||
run(input, (error) =>
|
||||
GitLabMergeRequestNotFoundError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
},
|
||||
error,
|
||||
),
|
||||
);
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitLabCliError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
@@ -451,10 +326,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabMergeRequestListDecodeError({
|
||||
new GitLabCliError({
|
||||
operation: "listMergeRequests",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid MR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -466,9 +342,8 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
executeMergeRequest({
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
@@ -477,11 +352,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabMergeRequestDecodeError({
|
||||
new GitLabCliError({
|
||||
operation: "getMergeRequest",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
detail: "GitLab CLI returned invalid merge request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -499,17 +374,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -523,17 +393,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabNamespace(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabNamespaceDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
namespacePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
@@ -563,17 +428,12 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -607,24 +467,19 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabDefaultBranch(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getDefaultBranch",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
executeMergeRequest({
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
@@ -54,10 +54,11 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
|
||||
|
||||
it.effect("adds repository context while retaining GitLab CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitLabCli.GitLabCliCommandError({
|
||||
const cause = new GitLabCli.GitLabCliError({
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -4,11 +4,7 @@ import { assert, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
|
||||
@@ -39,25 +35,10 @@ interface RecordedBatchBody {
|
||||
}>;
|
||||
}
|
||||
|
||||
interface CapturedLog {
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const isAnalyticsBatchDeliveryError = Schema.is(AnalyticsService.AnalyticsBatchDeliveryError);
|
||||
|
||||
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
it.effect("flush drains buffered events and retries failed batches with structured context", () =>
|
||||
it.effect("flush drains all buffered events across multiple batches", () =>
|
||||
Effect.gen(function* () {
|
||||
const capturedRequests: Array<RecordedBatchRequest> = [];
|
||||
const capturedLogs: CapturedLog[] = [];
|
||||
let rejectNextBatch = false;
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
capturedLogs.push({
|
||||
message,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-telemetry-base-",
|
||||
});
|
||||
@@ -85,20 +66,12 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
|
||||
capturedRequests.push({ path: request.url, body: payload });
|
||||
|
||||
if (rejectNextBatch) {
|
||||
rejectNextBatch = false;
|
||||
return HttpServerResponse.empty({ status: 503 });
|
||||
}
|
||||
|
||||
return HttpServerResponse.jsonUnsafe({});
|
||||
}),
|
||||
);
|
||||
const runtimeLayer = Layer.merge(
|
||||
telemetryLayer.pipe(
|
||||
Layer.provide(configLayer),
|
||||
Layer.provideMerge(NodeHttpServer.layerTest),
|
||||
),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
const runtimeLayer = telemetryLayer.pipe(
|
||||
Layer.provide(configLayer),
|
||||
Layer.provideMerge(NodeHttpServer.layerTest),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -112,17 +85,12 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
}
|
||||
|
||||
yield* analytics.flush;
|
||||
yield* analytics.record("test.flush.retry", { index: 45 });
|
||||
rejectNextBatch = true;
|
||||
yield* analytics.flush;
|
||||
yield* analytics.flush;
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
const batchRequests = capturedRequests
|
||||
.slice(0, 3)
|
||||
.filter((request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
|
||||
const batchRequests = capturedRequests.filter(
|
||||
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
|
||||
Array.isArray(request.body?.batch),
|
||||
);
|
||||
);
|
||||
assert.equal(batchRequests.length, 3);
|
||||
assert.equal(
|
||||
batchRequests.every((request) => request.path === "/batch/" || request.path === "/batch"),
|
||||
@@ -147,53 +115,6 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
const retryRequests = capturedRequests.slice(3);
|
||||
assert.equal(retryRequests.length, 2);
|
||||
assert.deepEqual(retryRequests[0]?.body, retryRequests[1]?.body);
|
||||
|
||||
const deliveryLog = capturedLogs.find((log) =>
|
||||
isAnalyticsBatchDeliveryError(log.annotations.cause),
|
||||
);
|
||||
assert.isDefined(deliveryLog);
|
||||
assert.equal(
|
||||
deliveryLog?.message,
|
||||
"Failed to deliver 1 analytics event to PostHog (endpoint input length 7).",
|
||||
);
|
||||
assert.equal("endpoint" in deliveryLog.annotations, false);
|
||||
assert.equal(deliveryLog.annotations.endpointInputLength, 7);
|
||||
|
||||
const error = deliveryLog?.annotations.cause;
|
||||
assert.instanceOf(error, AnalyticsService.AnalyticsBatchDeliveryError);
|
||||
if (isAnalyticsBatchDeliveryError(error)) {
|
||||
assert.equal(error.endpointInputLength, 7);
|
||||
assert.equal(error.endpointProtocol, undefined);
|
||||
assert.equal(error.endpointHostname, undefined);
|
||||
assert.equal(error.eventCount, 1);
|
||||
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
|
||||
if (error.cause instanceof HttpClientError.HttpClientError) {
|
||||
assert.equal(error.cause.reason._tag, "StatusCodeError");
|
||||
assert.equal(error.cause.response?.status, 503);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps configured PostHog endpoint secrets out of direct error and log context", () => {
|
||||
const endpoint =
|
||||
"https://user:[email protected]/private/project?api_key=secret#fragment";
|
||||
const cause = new Error("delivery failed");
|
||||
const error = AnalyticsService.AnalyticsBatchDeliveryError.fromEndpoint({
|
||||
endpoint,
|
||||
eventCount: 2,
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.equal(error.endpointInputLength, endpoint.length);
|
||||
assert.equal(error.endpointProtocol, "https:");
|
||||
assert.equal(error.endpointHostname, "posthog.example.test");
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal("endpoint" in error, false);
|
||||
assert.equal(/user|password|private|project|api_key|secret|fragment/.test(error.message), false);
|
||||
});
|
||||
@@ -7,7 +7,6 @@
|
||||
* @module AnalyticsService
|
||||
*/
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -15,7 +14,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 HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
@@ -45,38 +43,6 @@ const TelemetryEnvConfig = Config.all({
|
||||
wslDistroName: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
|
||||
});
|
||||
|
||||
export class AnalyticsBatchDeliveryError extends Schema.TaggedErrorClass<AnalyticsBatchDeliveryError>()(
|
||||
"AnalyticsBatchDeliveryError",
|
||||
{
|
||||
endpointInputLength: Schema.Number,
|
||||
endpointProtocol: Schema.optionalKey(Schema.String),
|
||||
endpointHostname: Schema.optionalKey(Schema.String),
|
||||
eventCount: Schema.Int.check(Schema.isGreaterThan(0)),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromEndpoint(input: {
|
||||
readonly endpoint: string;
|
||||
readonly eventCount: number;
|
||||
readonly cause: unknown;
|
||||
}): AnalyticsBatchDeliveryError {
|
||||
const diagnostics = getUrlDiagnostics(input.endpoint);
|
||||
return new AnalyticsBatchDeliveryError({
|
||||
endpointInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { endpointProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { endpointHostname: diagnostics.hostname }),
|
||||
eventCount: input.eventCount,
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const eventLabel = this.eventCount === 1 ? "event" : "events";
|
||||
const destination = this.endpointHostname ? ` at ${this.endpointHostname}` : "";
|
||||
return `Failed to deliver ${this.eventCount} analytics ${eventLabel} to PostHog${destination} (endpoint input length ${this.endpointInputLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AnalyticsService extends Context.Service<
|
||||
AnalyticsService,
|
||||
{
|
||||
@@ -109,7 +75,6 @@ export const make = Effect.gen(function* () {
|
||||
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const hostArchitecture = yield* HostProcessArchitecture;
|
||||
const batchEndpoint = `${telemetryConfig.posthogHost}/batch/`;
|
||||
|
||||
const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
|
||||
Effect.flatMap(DateTime.now, (now) =>
|
||||
@@ -161,17 +126,10 @@ export const make = Effect.gen(function* () {
|
||||
})),
|
||||
};
|
||||
|
||||
yield* HttpClientRequest.post(batchEndpoint).pipe(
|
||||
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
|
||||
HttpClientRequest.bodyJson(payload),
|
||||
Effect.flatMap(httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.mapError((cause) =>
|
||||
AnalyticsBatchDeliveryError.fromEndpoint({
|
||||
endpoint: batchEndpoint,
|
||||
eventCount: events.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -191,32 +149,14 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
yield* sendBatch(batch).pipe(
|
||||
Effect.catchTags({
|
||||
AnalyticsBatchDeliveryError: (error) =>
|
||||
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
),
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
AnalyticsBatchDeliveryError: (error) =>
|
||||
Effect.logError(error.message).pipe(
|
||||
Effect.annotateLogs({
|
||||
endpointInputLength: error.endpointInputLength,
|
||||
...(error.endpointProtocol === undefined
|
||||
? {}
|
||||
: { endpointProtocol: error.endpointProtocol }),
|
||||
...(error.endpointHostname === undefined
|
||||
? {}
|
||||
: { endpointHostname: error.endpointHostname }),
|
||||
eventCount: error.eventCount,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
|
||||
|
||||
const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
|
||||
function* (event, properties) {
|
||||
|
||||
@@ -151,29 +151,20 @@ export const make = Effect.gen(function* () {
|
||||
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
|
||||
return;
|
||||
}
|
||||
const recoverRefreshFailure = (
|
||||
cause:
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
|
||||
yield* searchIndex.refresh();
|
||||
}).pipe(
|
||||
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
|
||||
Effect.catchTags({
|
||||
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
|
||||
}),
|
||||
Effect.catch((cause) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { FileFinder } from "@ff-labs/fff-node";
|
||||
import { afterEach, expect, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
|
||||
@@ -51,35 +49,6 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves FileFinder destroy failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native destroy failed");
|
||||
const finder = {
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
isScanning: vi.fn(() => false),
|
||||
} as unknown as FileFinder;
|
||||
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
|
||||
|
||||
const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
|
||||
Effect.exit,
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasDies(exit.cause)).toBe(true);
|
||||
const error = Cause.squash(exit.cause);
|
||||
expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "WorkspaceSearchIndexDestroyFailed",
|
||||
cwd: "/workspace/project",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves search and refresh failures with operation context", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -71,18 +71,6 @@ export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<W
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
|
||||
"WorkspaceSearchIndexDestroyFailed",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to destroy the workspace search index for '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type WorkspaceSearchIndexError =
|
||||
| WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndexScanTimedOut
|
||||
@@ -213,10 +201,7 @@ const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unkn
|
||||
|
||||
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
|
||||
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
|
||||
Effect.try({
|
||||
try: () => finder.destroy(),
|
||||
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
Effect.sync(() => finder.destroy()),
|
||||
);
|
||||
yield* waitForScan(
|
||||
cwd,
|
||||
|
||||
+26
-32
@@ -110,7 +110,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
|
||||
import * as SessionStore from "./auth/SessionStore.ts";
|
||||
import { catchEnvironmentAuthenticationErrors } from "./auth/http.ts";
|
||||
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
|
||||
@@ -510,26 +510,16 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
|
||||
const loadAuthAccessSnapshot = () =>
|
||||
Effect.all({
|
||||
pairingLinks: serverAuth.listPairingLinks().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthAccessStreamError({
|
||||
operation: "list-pairing-links",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
pairingLinks: serverAuth.listPairingLinks(),
|
||||
clientSessions: serverAuth.listClientSessions(currentSessionId),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AuthAccessStreamError({
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthAccessStreamError({
|
||||
operation: "list-client-sessions",
|
||||
currentSessionId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
);
|
||||
|
||||
const appendSetupScriptActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -1289,16 +1279,15 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
status,
|
||||
}),
|
||||
),
|
||||
Effect.catchTags({
|
||||
RelayClientInstallError: (error) =>
|
||||
Queue.fail(
|
||||
queue,
|
||||
new RelayClientInstallFailedError({
|
||||
reason: error.reason,
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
Effect.catchTag("RelayClientInstallError", (error) =>
|
||||
Queue.fail(
|
||||
queue,
|
||||
new RelayClientInstallFailedError({
|
||||
reason: error.reason,
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.andThen(Queue.end(queue)),
|
||||
Effect.forkScoped,
|
||||
),
|
||||
@@ -1810,8 +1799,13 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateWebSocketUpgrade(request),
|
||||
const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
);
|
||||
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
|
||||
disableTracing: true,
|
||||
|
||||
@@ -28,71 +28,12 @@ describe("browser target resolver", () => {
|
||||
it("refuses public relay hosts until the authenticated gateway exists", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://relay.example.com" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
|
||||
try {
|
||||
expect(() =>
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "environment-port",
|
||||
port: 5173,
|
||||
});
|
||||
expect.unreachable("Expected public environment host resolution to fail");
|
||||
} catch (error) {
|
||||
expect(error).toMatchObject({
|
||||
_tag: "BrowserTargetPrivateNetworkRequiredError",
|
||||
environmentId: "environment-1",
|
||||
hostname: "relay.example.com",
|
||||
message:
|
||||
"Environment environment-1 host relay.example.com needs the planned authenticated preview gateway because it is not directly private-network reachable.",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("identifies the disconnected environment", async () => {
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
|
||||
try {
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "environment-port",
|
||||
port: 5173,
|
||||
});
|
||||
expect.unreachable("Expected disconnected environment resolution to fail");
|
||||
} catch (error) {
|
||||
expect(error).toMatchObject({
|
||||
_tag: "BrowserTargetEnvironmentDisconnectedError",
|
||||
environmentId: "environment-1",
|
||||
message: "Environment environment-1 is not connected.",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves invalid environment URL causes with connection context", async () => {
|
||||
const sensitiveUrl =
|
||||
"https://user:password@[invalid-host]/private/workspace?access_token=secret#fragment";
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: sensitiveUrl });
|
||||
const { BrowserTargetEnvironmentUrlInvalidError, resolveBrowserNavigationTarget } =
|
||||
await import("./browserTargetResolver");
|
||||
|
||||
try {
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "environment-port",
|
||||
port: 5173,
|
||||
});
|
||||
expect.unreachable("Expected browser target resolution to fail");
|
||||
} catch (error) {
|
||||
expect(error).toMatchObject({
|
||||
_tag: "BrowserTargetEnvironmentUrlInvalidError",
|
||||
environmentId: "environment-1",
|
||||
httpBaseUrlInputLength: sensitiveUrl.length,
|
||||
cause: expect.any(TypeError),
|
||||
message: `Environment environment-1 has an invalid HTTP base URL input of length ${sensitiveUrl.length}.`,
|
||||
});
|
||||
expect(error).toBeInstanceOf(BrowserTargetEnvironmentUrlInvalidError);
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
expect(error).not.toHaveProperty("httpBaseUrlProtocol");
|
||||
expect(error).not.toHaveProperty("httpBaseUrlHostname");
|
||||
expect(String((error as Error).message)).not.toMatch(
|
||||
/user|password|private|workspace|access_token|secret|fragment/,
|
||||
);
|
||||
}
|
||||
}),
|
||||
).toThrow(/authenticated preview gateway/);
|
||||
});
|
||||
|
||||
it("normalizes schemeless localhost server-picker values", async () => {
|
||||
|
||||
@@ -1,52 +1,12 @@
|
||||
import {
|
||||
type BrowserNavigationTarget,
|
||||
import type {
|
||||
BrowserNavigationTarget,
|
||||
EnvironmentId,
|
||||
type PreviewUrlResolution,
|
||||
PreviewUrlResolution,
|
||||
} from "@t3tools/contracts";
|
||||
import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { readPreparedConnection } from "~/state/session";
|
||||
|
||||
export class BrowserTargetEnvironmentDisconnectedError extends Schema.TaggedErrorClass<BrowserTargetEnvironmentDisconnectedError>()(
|
||||
"BrowserTargetEnvironmentDisconnectedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment ${this.environmentId} is not connected.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserTargetEnvironmentUrlInvalidError extends Schema.TaggedErrorClass<BrowserTargetEnvironmentUrlInvalidError>()(
|
||||
"BrowserTargetEnvironmentUrlInvalidError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
httpBaseUrlInputLength: Schema.Number,
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment ${this.environmentId} has an invalid HTTP base URL input of length ${this.httpBaseUrlInputLength}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserTargetPrivateNetworkRequiredError extends Schema.TaggedErrorClass<BrowserTargetPrivateNetworkRequiredError>()(
|
||||
"BrowserTargetPrivateNetworkRequiredError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
hostname: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment ${this.environmentId} host ${this.hostname} needs the planned authenticated preview gateway because it is not directly private-network reachable.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isPrivateNetworkHost = (host: string): boolean => {
|
||||
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
if (normalized === "localhost" || normalized === "::1" || normalized.endsWith(".local")) {
|
||||
@@ -77,27 +37,12 @@ export function resolveBrowserNavigationTarget(
|
||||
};
|
||||
}
|
||||
const connection = readPreparedConnection(environmentId);
|
||||
if (!connection) {
|
||||
throw new BrowserTargetEnvironmentDisconnectedError({ environmentId });
|
||||
}
|
||||
let environmentUrl: URL;
|
||||
try {
|
||||
environmentUrl = new URL(connection.httpBaseUrl);
|
||||
} catch (cause) {
|
||||
const diagnostics = getUrlDiagnostics(connection.httpBaseUrl);
|
||||
throw new BrowserTargetEnvironmentUrlInvalidError({
|
||||
environmentId,
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
|
||||
const environmentUrl = new URL(connection.httpBaseUrl);
|
||||
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
|
||||
throw new BrowserTargetPrivateNetworkRequiredError({
|
||||
environmentId,
|
||||
hostname: environmentUrl.hostname,
|
||||
});
|
||||
throw new Error(
|
||||
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
|
||||
);
|
||||
}
|
||||
const protocol = target.protocol ?? "http";
|
||||
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { decodeJwt, SignJWT } from "jose";
|
||||
import { decodeJwt } from "jose";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
browserCryptoLayer,
|
||||
BrowserDpopKeyError,
|
||||
BrowserDpopProofError,
|
||||
createBrowserDpopProof,
|
||||
generateBrowserDpopKey,
|
||||
isBrowserDpopError,
|
||||
} from "./dpop";
|
||||
import { browserCryptoLayer, createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";
|
||||
|
||||
describe("browser DPoP proofs", () => {
|
||||
it.effect("signs relay resource proofs with an access-token hash", () =>
|
||||
@@ -39,80 +32,4 @@ describe("browser DPoP proofs", () => {
|
||||
).toMatchObject({ ok: true });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves safe invalid URL context and the parser cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateBrowserDpopKey;
|
||||
const url = "http://";
|
||||
const error = yield* createBrowserDpopProof({
|
||||
method: "POST",
|
||||
url,
|
||||
proofKey,
|
||||
}).pipe(Effect.provide(browserCryptoLayer), Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(BrowserDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "normalize-url",
|
||||
method: "POST",
|
||||
requestTarget: "<invalid-url>",
|
||||
urlLength: url.length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error).not.toHaveProperty("normalizedUrl");
|
||||
expect(error.cause).toBeInstanceOf(Error);
|
||||
expect(error.message).not.toContain((error.cause as Error).message);
|
||||
expect(isBrowserDpopError(error)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("redacts URL credentials, query, and fragment from proof errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateBrowserDpopKey;
|
||||
const cause = new Error("signing failed");
|
||||
const sign = vi.spyOn(SignJWT.prototype, "sign").mockRejectedValueOnce(cause);
|
||||
const url = "https://user:[email protected]/oauth/token?access_token=secret#fragment";
|
||||
|
||||
const error = yield* createBrowserDpopProof({
|
||||
method: "POST",
|
||||
url,
|
||||
proofKey,
|
||||
}).pipe(Effect.provide(browserCryptoLayer), Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(BrowserDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "sign",
|
||||
method: "POST",
|
||||
requestTarget: "https://example.com/oauth/token",
|
||||
urlLength: url.length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
cause,
|
||||
});
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error).not.toHaveProperty("normalizedUrl");
|
||||
expect(error.message).not.toContain("user");
|
||||
expect(error.message).not.toContain("password");
|
||||
expect(error.message).not.toContain("access_token");
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(error.message).not.toContain("fragment");
|
||||
sign.mockRestore();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the browser crypto cause when key generation fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("browser crypto unavailable");
|
||||
const generateKey = vi
|
||||
.spyOn(globalThis.crypto.subtle, "generateKey")
|
||||
.mockRejectedValueOnce(cause);
|
||||
|
||||
const error = yield* generateBrowserDpopKey.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(BrowserDpopKeyError);
|
||||
expect(error.operation).toBe("generate");
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
generateKey.mockRestore();
|
||||
}),
|
||||
);
|
||||
});
|
||||
+27
-125
@@ -2,9 +2,9 @@ import {
|
||||
computeDpopAccessTokenHash,
|
||||
computeDpopJwkThumbprint,
|
||||
DpopPublicJwk,
|
||||
redactDpopRequestTarget,
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -16,62 +16,10 @@ export interface BrowserDpopKey {
|
||||
readonly thumbprint: string;
|
||||
}
|
||||
|
||||
export class BrowserDpopStorageError extends Schema.TaggedErrorClass<BrowserDpopStorageError>()(
|
||||
"BrowserDpopStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["open", "read", "write"]),
|
||||
databaseName: Schema.String,
|
||||
storeName: Schema.String,
|
||||
keyId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Browser DPoP key storage operation "${this.operation}" failed for database "${this.databaseName}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserDpopKeyError extends Schema.TaggedErrorClass<BrowserDpopKeyError>()(
|
||||
"BrowserDpopKeyError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"generate",
|
||||
"export-private",
|
||||
"export-public",
|
||||
"validate-public",
|
||||
"import-private",
|
||||
]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Browser DPoP key operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserDpopProofError extends Schema.TaggedErrorClass<BrowserDpopProofError>()(
|
||||
"BrowserDpopProofError",
|
||||
{
|
||||
operation: Schema.Literals(["normalize-url", "generate-id", "sign"]),
|
||||
method: Schema.String,
|
||||
requestTarget: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
thumbprint: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Browser DPoP proof operation "${this.operation}" failed for ${this.method.toUpperCase()} ${this.requestTarget}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BrowserDpopError = Schema.Union([
|
||||
BrowserDpopStorageError,
|
||||
BrowserDpopKeyError,
|
||||
BrowserDpopProofError,
|
||||
]);
|
||||
export type BrowserDpopError = typeof BrowserDpopError.Type;
|
||||
export const isBrowserDpopError = Schema.is(BrowserDpopError);
|
||||
export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const DPOP_DATABASE_NAME = "t3code:cloud-auth";
|
||||
const DPOP_DATABASE_VERSION = 1;
|
||||
@@ -92,20 +40,16 @@ export const browserCryptoLayer = Layer.succeed(
|
||||
}),
|
||||
);
|
||||
|
||||
function dpopError(message: string, cause?: unknown) {
|
||||
return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });
|
||||
}
|
||||
|
||||
function openDpopDatabase(): Effect.Effect<IDBDatabase, BrowserDpopError> {
|
||||
return Effect.callback<IDBDatabase, BrowserDpopError>((resume) => {
|
||||
const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION);
|
||||
request.addEventListener("error", () =>
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BrowserDpopStorageError({
|
||||
operation: "open",
|
||||
databaseName: DPOP_DATABASE_NAME,
|
||||
storeName: DPOP_KEY_STORE_NAME,
|
||||
keyId: DPOP_KEY_ID,
|
||||
...(request.error === null ? {} : { cause: request.error }),
|
||||
}),
|
||||
),
|
||||
Effect.fail(dpopError("Could not open DPoP key storage.", request.error ?? undefined)),
|
||||
),
|
||||
);
|
||||
request.addEventListener("upgradeneeded", () => {
|
||||
@@ -130,17 +74,7 @@ export function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null,
|
||||
.objectStore(DPOP_KEY_STORE_NAME)
|
||||
.get(DPOP_KEY_ID);
|
||||
request.addEventListener("error", () =>
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BrowserDpopStorageError({
|
||||
operation: "read",
|
||||
databaseName: DPOP_DATABASE_NAME,
|
||||
storeName: DPOP_KEY_STORE_NAME,
|
||||
keyId: DPOP_KEY_ID,
|
||||
...(request.error === null ? {} : { cause: request.error }),
|
||||
}),
|
||||
),
|
||||
),
|
||||
resume(Effect.fail(dpopError("Could not read DPoP key.", request.error ?? undefined))),
|
||||
);
|
||||
request.addEventListener("success", () =>
|
||||
resume(Effect.succeed((request.result as BrowserDpopKey | undefined) ?? null)),
|
||||
@@ -163,15 +97,7 @@ export function writeStoredBrowserDpopKey(
|
||||
const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite");
|
||||
transaction.addEventListener("error", () =>
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BrowserDpopStorageError({
|
||||
operation: "write",
|
||||
databaseName: DPOP_DATABASE_NAME,
|
||||
storeName: DPOP_KEY_STORE_NAME,
|
||||
keyId: DPOP_KEY_ID,
|
||||
...(transaction.error === null ? {} : { cause: transaction.error }),
|
||||
}),
|
||||
),
|
||||
Effect.fail(dpopError("Could not write DPoP key.", transaction.error ?? undefined)),
|
||||
),
|
||||
);
|
||||
transaction.addEventListener("complete", () => resume(Effect.void));
|
||||
@@ -188,22 +114,26 @@ export const generateBrowserDpopKey = Effect.gen(function* () {
|
||||
"sign",
|
||||
"verify",
|
||||
]) as Promise<CryptoKeyPair>,
|
||||
catch: (cause) => new BrowserDpopKeyError({ operation: "generate", cause }),
|
||||
catch: (cause) => dpopError("Could not generate DPoP proof key.", cause),
|
||||
});
|
||||
const privateJwk = yield* Effect.tryPromise({
|
||||
try: () => crypto.subtle.exportKey("jwk", generated.privateKey),
|
||||
catch: (cause) => new BrowserDpopKeyError({ operation: "export-private", cause }),
|
||||
catch: (cause) => dpopError("Could not export DPoP private key.", cause),
|
||||
});
|
||||
const encodedPublicJwk = yield* Effect.tryPromise({
|
||||
const publicJwk = yield* Effect.tryPromise({
|
||||
try: () => crypto.subtle.exportKey("jwk", generated.publicKey),
|
||||
catch: (cause) => new BrowserDpopKeyError({ operation: "export-public", cause }),
|
||||
});
|
||||
const publicJwk = yield* decodeDpopPublicJwk(encodedPublicJwk).pipe(
|
||||
Effect.mapError((cause) => new BrowserDpopKeyError({ operation: "validate-public", cause })),
|
||||
catch: (cause) => dpopError("Could not export DPoP public key.", cause),
|
||||
}).pipe(
|
||||
Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof BrowserDpopError
|
||||
? cause
|
||||
: dpopError("Generated DPoP public key is invalid.", cause),
|
||||
),
|
||||
);
|
||||
const privateKey = yield* Effect.tryPromise({
|
||||
try: () => importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise<CryptoKey>,
|
||||
catch: (cause) => new BrowserDpopKeyError({ operation: "import-private", cause }),
|
||||
catch: (cause) => dpopError("Could not import DPoP private key.", cause),
|
||||
});
|
||||
return {
|
||||
privateKey,
|
||||
@@ -223,35 +153,15 @@ export function createBrowserDpopProof(input: {
|
||||
Crypto.Crypto
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const requestTarget = redactDpopRequestTarget(input.url);
|
||||
const urlLength = input.url.length;
|
||||
const normalizedUrl = yield* Effect.try({
|
||||
try: () => new URL(input.url),
|
||||
catch: (cause) =>
|
||||
new BrowserDpopProofError({
|
||||
operation: "normalize-url",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: input.proofKey.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),
|
||||
});
|
||||
normalizedUrl.search = "";
|
||||
normalizedUrl.hash = "";
|
||||
const jti = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserDpopProofError({
|
||||
operation: "generate-id",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: input.proofKey.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),
|
||||
);
|
||||
const proof = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
@@ -268,15 +178,7 @@ export function createBrowserDpopProof(input: {
|
||||
})
|
||||
.setIssuedAt()
|
||||
.sign(input.proofKey.privateKey),
|
||||
catch: (cause) =>
|
||||
new BrowserDpopProofError({
|
||||
operation: "sign",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: input.proofKey.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => dpopError("Could not sign DPoP proof.", cause),
|
||||
});
|
||||
return { proof, thumbprint: input.proofKey.thumbprint };
|
||||
});
|
||||
|
||||
@@ -2,14 +2,12 @@ import {
|
||||
type DesktopBridge,
|
||||
EnvironmentId,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type RelayClientStatus,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayWebClientId } from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
@@ -28,9 +26,7 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
|
||||
|
||||
import {
|
||||
CloudEnvironmentLinkOperationError,
|
||||
collectCloudLinkTargets,
|
||||
isCloudEnvironmentLinkError,
|
||||
linkPrimaryEnvironmentToCloud,
|
||||
listManagedCloudEnvironments,
|
||||
normalizeRelayBaseUrl,
|
||||
@@ -52,21 +48,12 @@ const relayClientInstallDialog = vi.hoisted(() => ({
|
||||
finish: vi.fn(),
|
||||
}));
|
||||
|
||||
const cloudPublicConfig = vi.hoisted(() => ({
|
||||
relayUrl: "https://relay.example.test",
|
||||
}));
|
||||
|
||||
vi.mock("./relayClientInstallDialog", () => ({
|
||||
requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
|
||||
reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
|
||||
finishRelayClientInstall: relayClientInstallDialog.finish,
|
||||
}));
|
||||
|
||||
vi.mock("./publicConfig", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("./publicConfig")>()),
|
||||
resolveCloudPublicConfig: () => ({ relayUrl: cloudPublicConfig.relayUrl }),
|
||||
}));
|
||||
|
||||
const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
|
||||
const dpopSignerLayer = Layer.succeed(
|
||||
ManagedRelay.ManagedRelayDpopSigner,
|
||||
@@ -88,7 +75,7 @@ function relayLayer() {
|
||||
}
|
||||
|
||||
function registryLayer(options?: {
|
||||
readonly status?: RelayClientStatus;
|
||||
readonly status?: { readonly status: "available"; readonly version: string };
|
||||
readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
|
||||
}) {
|
||||
return Layer.effect(
|
||||
@@ -96,14 +83,7 @@ function registryLayer(options?: {
|
||||
Effect.gen(function* () {
|
||||
const client = {
|
||||
[WS_METHODS.cloudGetRelayClientStatus]: () =>
|
||||
Effect.succeed(
|
||||
options?.status ?? {
|
||||
status: "available",
|
||||
executablePath: "/managed/cloudflared",
|
||||
source: "managed",
|
||||
version: "2026.6.0",
|
||||
},
|
||||
),
|
||||
Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
|
||||
[WS_METHODS.cloudInstallRelayClient]: () =>
|
||||
Stream.fromIterable(options?.installEvents ?? []),
|
||||
} as unknown as RpcSession["client"];
|
||||
@@ -161,7 +141,6 @@ function bodyText(body: BodyInit | null | undefined): string {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
cloudPublicConfig.relayUrl = "https://relay.example.test";
|
||||
vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
|
||||
relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
|
||||
});
|
||||
@@ -216,47 +195,6 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves structured relay failures and trace IDs", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(
|
||||
Response.json(
|
||||
{
|
||||
_tag: "RelayAuthInvalidError",
|
||||
code: "auth_invalid",
|
||||
reason: "invalid_bearer",
|
||||
traceId: "trace-web-cloud-link",
|
||||
},
|
||||
{ status: 401 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* withServices(
|
||||
listManagedCloudEnvironments({ clerkToken: "clerk-token" }),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudEnvironmentLinkOperationError);
|
||||
expect(error).toMatchObject({
|
||||
action: "list relay-managed environments",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
traceId: "trace-web-cloud-link",
|
||||
relayError: {
|
||||
_tag: "RelayAuthInvalidError",
|
||||
reason: "invalid_bearer",
|
||||
},
|
||||
cause: {
|
||||
_tag: "ManagedRelayRequestFailedError",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe("Could not list relay-managed environments.");
|
||||
expect(isCloudEnvironmentLinkError(error)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads primary cloud link state from the explicit target", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
@@ -287,96 +225,6 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves structured environment API failures and their cause chain", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(
|
||||
Response.json(
|
||||
{
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Environment bearer token is invalid.",
|
||||
},
|
||||
{ status: 401 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* withServices(readPrimaryCloudLinkState({ target: TARGET })).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudEnvironmentLinkOperationError);
|
||||
expect(error).toMatchObject({
|
||||
action: "read environment cloud link state",
|
||||
environmentId: TARGET.environmentId,
|
||||
httpBaseUrlInputLength: TARGET.httpBaseUrl.length,
|
||||
httpBaseUrlProtocol: "http:",
|
||||
httpBaseUrlHostname: "127.0.0.1",
|
||||
environmentError: {
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Environment bearer token is invalid.",
|
||||
},
|
||||
});
|
||||
expect(error.cause).toBeDefined();
|
||||
expect(error.message).toBe(
|
||||
`Could not read environment cloud link state for environment "${TARGET.environmentId}".`,
|
||||
);
|
||||
expect(isCloudEnvironmentLinkError(error)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves invalid environment HTTP URL parser causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const invalidUrl =
|
||||
"https://user:password@[invalid-host]/private/path?access_token=secret#fragment";
|
||||
const error = yield* withServices(
|
||||
readPrimaryCloudLinkState({
|
||||
target: {
|
||||
...TARGET,
|
||||
httpBaseUrl: invalidUrl,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "initialize the environment HTTP client",
|
||||
environmentId: TARGET.environmentId,
|
||||
httpBaseUrlInputLength: invalidUrl.length,
|
||||
});
|
||||
expect(error.cause).toBeInstanceOf(TypeError);
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
expect(error).not.toHaveProperty("httpBaseUrlProtocol");
|
||||
expect(error).not.toHaveProperty("httpBaseUrlHostname");
|
||||
expect(error.message).not.toMatch(/user|password|private|path|access_token|secret|fragment/);
|
||||
}),
|
||||
);
|
||||
|
||||
it("keeps environment endpoint secrets out of mapped error attributes", () => {
|
||||
const httpBaseUrl =
|
||||
"https://user:[email protected]/private/path?access_token=secret#fragment";
|
||||
const cause = new Error("request failed");
|
||||
const error = CloudEnvironmentLinkOperationError.fromEnvironmentApi({
|
||||
action: "read environment cloud link state",
|
||||
environmentId: TARGET.environmentId,
|
||||
httpBaseUrl,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "environment.example.test",
|
||||
cause,
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
const diagnostics = JSON.stringify(error);
|
||||
expect(diagnostics).not.toMatch(/user|password|private|path|access_token|secret|fragment/);
|
||||
expect(error.message).not.toMatch(/user|password|private|path|access_token|secret|fragment/);
|
||||
});
|
||||
|
||||
it.effect("uses desktop bearer auth for primary cloud link state", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
@@ -458,37 +306,6 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("validates the environment endpoint before prompting to install a relay client", () =>
|
||||
Effect.gen(function* () {
|
||||
const invalidUrl =
|
||||
"https://user:password@[invalid-host]/private/path?access_token=secret#fragment";
|
||||
|
||||
const error = yield* withServices(
|
||||
linkPrimaryEnvironmentToCloud({
|
||||
target: {
|
||||
...TARGET,
|
||||
httpBaseUrl: invalidUrl,
|
||||
},
|
||||
clerkToken: "clerk-token",
|
||||
}),
|
||||
{
|
||||
status: { status: "missing", version: "2026.6.0" },
|
||||
},
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: TARGET.environmentId,
|
||||
httpBaseUrlInputLength: invalidUrl.length,
|
||||
});
|
||||
expect(error.cause).toBeInstanceOf(TypeError);
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
expect(error.message).not.toMatch(/user|password|private|path|access_token|secret|fragment/);
|
||||
expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs a missing relay client before linking", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true })));
|
||||
@@ -499,12 +316,7 @@ describe("web cloud link environment client", () => {
|
||||
clerkToken: "clerk-token",
|
||||
}),
|
||||
{
|
||||
status: {
|
||||
status: "available",
|
||||
executablePath: "/managed/cloudflared",
|
||||
source: "managed",
|
||||
version: "2026.6.0",
|
||||
},
|
||||
status: { status: "available", version: "2026.6.0" },
|
||||
installEvents: [],
|
||||
},
|
||||
).pipe(Effect.flip);
|
||||
@@ -536,64 +348,4 @@ describe("web cloud link environment client", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps configured relay URL secrets out of revoke warnings", () => {
|
||||
const relayUrl =
|
||||
"https://relay-user:[email protected]/private/workspace?access_token=relay-secret#relay-fragment";
|
||||
cloudPublicConfig.relayUrl = relayUrl;
|
||||
const capturedLogs: Array<ReadonlyArray<unknown>> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
capturedLogs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
|
||||
)
|
||||
.mockResolvedValueOnce(Response.json({ malformed: true }, { status: 500 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
return unlinkPrimaryEnvironmentFromCloud({
|
||||
target: TARGET,
|
||||
clerkToken: "clerk-token",
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.merge(
|
||||
services(),
|
||||
Logger.layer([logger], {
|
||||
mergeWithExisting: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
expect(capturedLogs).toHaveLength(1);
|
||||
const logFields = capturedLogs[0]?.find(
|
||||
(value): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null,
|
||||
);
|
||||
expect(logFields).toMatchObject({
|
||||
relayUrlInputLength: relayUrl.length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
causeTag: "ManagedRelayRequestFailedError",
|
||||
});
|
||||
expect(logFields).not.toHaveProperty("relayUrl");
|
||||
expect(logFields).not.toHaveProperty("cause");
|
||||
const logText = capturedLogs[0]
|
||||
?.filter((value): value is string => typeof value === "string")
|
||||
.join(" ");
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"/private/workspace",
|
||||
"access_token=relay-secret",
|
||||
"relay-fragment",
|
||||
]) {
|
||||
expect(logText).not.toContain(secret);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -18,14 +19,13 @@ import {
|
||||
type RelayClientDeviceRecord,
|
||||
type RelayClientEnvironmentRecord,
|
||||
type RelayEnvironmentLinkResponse,
|
||||
type RelayProtectedError as RelayProtectedErrorType,
|
||||
type RelayManagedEndpointProviderKind,
|
||||
RelayProtectedError,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
|
||||
import { request, runStream } from "@t3tools/client-runtime/rpc";
|
||||
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import {
|
||||
readPrimaryEnvironmentDescriptor,
|
||||
@@ -51,218 +51,17 @@ function relayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relayUrl;
|
||||
}
|
||||
|
||||
const EnvironmentCloudApiError = Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]);
|
||||
type EnvironmentCloudApiError = typeof EnvironmentCloudApiError.Type;
|
||||
const isEnvironmentCloudApiError = Schema.is(EnvironmentCloudApiError);
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
readonly traceId?: string;
|
||||
}> {}
|
||||
|
||||
function relayUrlDiagnosticFields(relayUrl: string | undefined) {
|
||||
if (relayUrl === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(relayUrl);
|
||||
return {
|
||||
relayUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function httpBaseUrlDiagnosticFields(httpBaseUrl: string | undefined) {
|
||||
if (httpBaseUrl === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(httpBaseUrl);
|
||||
return {
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export const CloudEnvironmentLinkAction = Schema.Literals([
|
||||
"check relay client availability",
|
||||
"confirm relay client installation",
|
||||
"install the relay client",
|
||||
"list relay-managed environments",
|
||||
"list cloud devices",
|
||||
"read environment cloud link state",
|
||||
"update environment cloud preferences",
|
||||
"unlink the environment from cloud",
|
||||
"revoke the cloud environment link",
|
||||
"create an environment link challenge",
|
||||
"obtain an environment link proof",
|
||||
"link the environment",
|
||||
"derive the environment endpoint origin",
|
||||
"initialize the environment HTTP client",
|
||||
"configure environment relay access",
|
||||
]);
|
||||
export type CloudEnvironmentLinkAction = typeof CloudEnvironmentLinkAction.Type;
|
||||
|
||||
export class CloudEnvironmentLinkOperationError extends Schema.TaggedErrorClass<CloudEnvironmentLinkOperationError>()(
|
||||
"CloudEnvironmentLinkOperationError",
|
||||
{
|
||||
action: CloudEnvironmentLinkAction,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
relayUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
relayUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
relayUrlHostname: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
traceId: Schema.optionalKey(Schema.String),
|
||||
relayError: Schema.optionalKey(RelayProtectedError),
|
||||
environmentError: Schema.optionalKey(EnvironmentCloudApiError),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromManagedRelay(input: {
|
||||
readonly action: CloudEnvironmentLinkAction;
|
||||
readonly cause: ManagedRelay.ManagedRelayClientError;
|
||||
readonly environmentId?: string;
|
||||
readonly relayUrl?: string;
|
||||
readonly httpBaseUrl?: string;
|
||||
}): CloudEnvironmentLinkOperationError {
|
||||
const requestFailure =
|
||||
input.cause._tag === "ManagedRelayRequestFailedError" ? input.cause : undefined;
|
||||
return new CloudEnvironmentLinkOperationError({
|
||||
action: input.action,
|
||||
cause: input.cause,
|
||||
...(input.environmentId === undefined ? {} : { environmentId: input.environmentId }),
|
||||
...relayUrlDiagnosticFields(input.relayUrl),
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
...(requestFailure?.traceId === undefined ? {} : { traceId: requestFailure.traceId }),
|
||||
...(requestFailure?.relayError === undefined
|
||||
? {}
|
||||
: { relayError: requestFailure.relayError }),
|
||||
});
|
||||
}
|
||||
|
||||
static fromEnvironmentApi(input: {
|
||||
readonly action: CloudEnvironmentLinkAction;
|
||||
readonly cause: unknown;
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}): CloudEnvironmentLinkOperationError {
|
||||
const environmentError = CloudEnvironmentLinkOperationError.findEnvironmentApiError(
|
||||
input.cause,
|
||||
);
|
||||
return new CloudEnvironmentLinkOperationError({
|
||||
action: input.action,
|
||||
environmentId: input.environmentId,
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
cause: input.cause,
|
||||
...(environmentError === undefined ? {} : { environmentError }),
|
||||
});
|
||||
}
|
||||
|
||||
private static findEnvironmentApiError(cause: unknown): EnvironmentCloudApiError | undefined {
|
||||
const seen = new Set<unknown>();
|
||||
let current = cause;
|
||||
while (typeof current === "object" && current !== null && !seen.has(current)) {
|
||||
if (isEnvironmentCloudApiError(current)) {
|
||||
return current;
|
||||
}
|
||||
seen.add(current);
|
||||
current = "cause" in current ? current.cause : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment "${this.environmentId}"`;
|
||||
return `Could not ${this.action}${environment}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayUrlNotConfiguredError extends Schema.TaggedErrorClass<CloudRelayUrlNotConfiguredError>()(
|
||||
"CloudRelayUrlNotConfiguredError",
|
||||
{ environmentId: Schema.optionalKey(Schema.String) },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "T3CODE_RELAY_URL is not configured.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayClientInstallUnsupportedError extends Schema.TaggedErrorClass<CloudRelayClientInstallUnsupportedError>()(
|
||||
"CloudRelayClientInstallUnsupportedError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
phase: Schema.Literals(["preflight", "post-install"]),
|
||||
version: Schema.String,
|
||||
platform: Schema.String,
|
||||
architecture: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `T3 Code cannot install the relay client automatically on ${this.platform}-${this.architecture}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayClientInstallCancelledError extends Schema.TaggedErrorClass<CloudRelayClientInstallCancelledError>()(
|
||||
"CloudRelayClientInstallCancelledError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
version: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay client installation was cancelled.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayClientInstallIncompleteError extends Schema.TaggedErrorClass<CloudRelayClientInstallIncompleteError>()(
|
||||
"CloudRelayClientInstallIncompleteError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
version: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The relay client install completed without a final status.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayClientUnavailableAfterInstallError extends Schema.TaggedErrorClass<CloudRelayClientUnavailableAfterInstallError>()(
|
||||
"CloudRelayClientUnavailableAfterInstallError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
version: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The relay client is still unavailable after installation.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkResponseMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentLinkResponseMismatchError>()(
|
||||
"CloudEnvironmentLinkResponseMismatchError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
field: Schema.Literals(["environment id", "endpoint provider"]),
|
||||
expected: Schema.String,
|
||||
actual: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay returned link credentials with an unexpected ${this.field}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudEnvironmentLinkError = Schema.Union([
|
||||
CloudEnvironmentLinkOperationError,
|
||||
CloudRelayUrlNotConfiguredError,
|
||||
CloudRelayClientInstallUnsupportedError,
|
||||
CloudRelayClientInstallCancelledError,
|
||||
CloudRelayClientInstallIncompleteError,
|
||||
CloudRelayClientUnavailableAfterInstallError,
|
||||
CloudEnvironmentLinkResponseMismatchError,
|
||||
]);
|
||||
export type CloudEnvironmentLinkError = typeof CloudEnvironmentLinkError.Type;
|
||||
export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
|
||||
const relayClientRpcError = (message: string) => (cause: unknown) =>
|
||||
new CloudEnvironmentLinkError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
function ensureRelayClientAvailable(
|
||||
environmentId: EnvironmentId,
|
||||
@@ -271,40 +70,21 @@ function ensureRelayClientAvailable(
|
||||
const registry = yield* EnvironmentRegistry;
|
||||
const status = yield* registry
|
||||
.run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudEnvironmentLinkOperationError({
|
||||
action: "check relay client availability",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(relayClientRpcError("Could not check relay client availability.")));
|
||||
if (status.status === "available") return;
|
||||
if (status.status === "unsupported") {
|
||||
return yield* new CloudRelayClientInstallUnsupportedError({
|
||||
environmentId,
|
||||
phase: "preflight",
|
||||
version: status.version,
|
||||
platform: status.platform,
|
||||
architecture: status.arch,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: `T3 Code cannot install the relay client automatically on ${status.platform}-${status.arch}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const confirmed = yield* Effect.tryPromise({
|
||||
try: () => requestRelayClientInstallConfirmation(status.version),
|
||||
catch: (cause) =>
|
||||
new CloudEnvironmentLinkOperationError({
|
||||
action: "confirm relay client installation",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: relayClientRpcError("Could not confirm relay client installation."),
|
||||
});
|
||||
if (!confirmed) {
|
||||
return yield* new CloudRelayClientInstallCancelledError({
|
||||
environmentId,
|
||||
version: status.version,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Relay client installation was cancelled.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -317,73 +97,112 @@ function ensureRelayClientAvailable(
|
||||
)
|
||||
.pipe(
|
||||
Stream.runLast,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudEnvironmentLinkOperationError({
|
||||
action: "install the relay client",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(relayClientRpcError("Could not install the relay client.")),
|
||||
Effect.ensuring(Effect.sync(finishRelayClientInstall)),
|
||||
);
|
||||
if (Option.isNone(installed) || installed.value.type !== "complete") {
|
||||
return yield* new CloudRelayClientInstallIncompleteError({
|
||||
environmentId,
|
||||
version: status.version,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "The relay client install completed without a final status.",
|
||||
});
|
||||
}
|
||||
const installedStatus = installed.value.status;
|
||||
if (installedStatus.status !== "available") {
|
||||
return yield* installedStatus.status === "unsupported"
|
||||
? new CloudRelayClientInstallUnsupportedError({
|
||||
environmentId,
|
||||
phase: "post-install",
|
||||
version: installedStatus.version,
|
||||
platform: installedStatus.platform,
|
||||
architecture: installedStatus.arch,
|
||||
})
|
||||
: new CloudRelayClientUnavailableAfterInstallError({
|
||||
environmentId,
|
||||
version: installedStatus.version,
|
||||
});
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message:
|
||||
installedStatus.status === "unsupported"
|
||||
? `T3 Code cannot install the relay client automatically on ${installedStatus.platform}-${installedStatus.arch}.`
|
||||
: "The relay client is still unavailable after installation.",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function endpointOrigin(input: { readonly environmentId: string; readonly httpBaseUrl: string }) {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const url = new URL(input.httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new CloudEnvironmentLinkOperationError({
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: input.environmentId,
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const isEnvironmentCloudApiError = Schema.is(
|
||||
Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]),
|
||||
);
|
||||
|
||||
function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
|
||||
switch (error._tag) {
|
||||
case "RelayAuthInvalidError":
|
||||
switch (error.reason) {
|
||||
case "missing_bearer":
|
||||
case "invalid_bearer":
|
||||
return "Relay rejected the cloud session token.";
|
||||
case "invalid_dpop":
|
||||
return "Relay rejected the DPoP proof.";
|
||||
case "not_authorized":
|
||||
return "Relay rejected the authenticated request.";
|
||||
}
|
||||
case "RelayEnvironmentLinkProofExpiredError":
|
||||
return "Relay rejected an expired environment link proof.";
|
||||
case "RelayEnvironmentLinkProofInvalidError":
|
||||
return `Relay rejected the environment link proof (${error.reason}).`;
|
||||
case "RelayEnvironmentConnectNotAuthorizedError":
|
||||
return "Relay rejected the environment connection request.";
|
||||
case "RelayEnvironmentEndpointUnavailableError":
|
||||
return `Relay could not reach the environment endpoint (${error.reason}).`;
|
||||
case "RelayEnvironmentEndpointTimedOutError":
|
||||
return "Relay timed out while contacting the environment endpoint.";
|
||||
case "RelayEnvironmentLinkFailedError":
|
||||
return `Relay could not link the environment (${error.reason}).`;
|
||||
case "RelayEnvironmentLinkUnavailableError":
|
||||
return `Relay cannot provision the managed endpoint (${error.reason}).`;
|
||||
case "RelayAgentActivityPublishProofExpiredError":
|
||||
return "Relay rejected an expired agent activity publish proof.";
|
||||
case "RelayAgentActivityPublishProofInvalidError":
|
||||
return `Relay rejected the agent activity publish proof (${error.reason}).`;
|
||||
case "RelayInternalError":
|
||||
return `Relay encountered an internal error (${error.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
function makeCloudEnvironmentHttpApiClient(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}) {
|
||||
return Effect.try({
|
||||
try: () => makeEnvironmentHttpApiClient(input.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
new CloudEnvironmentLinkOperationError({
|
||||
action: "initialize the environment HTTP client",
|
||||
environmentId: input.environmentId,
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.flatten);
|
||||
function decodedRelayClientError(message: string) {
|
||||
return (cause: ManagedRelay.ManagedRelayClientError) => {
|
||||
const relayError =
|
||||
cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
|
||||
const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
|
||||
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: detail ? `${message}: ${detail}` : message,
|
||||
cause,
|
||||
...(traceId ? { traceId } : {}),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
|
||||
if (isEnvironmentCloudApiError(cause)) {
|
||||
return cause;
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return null;
|
||||
}
|
||||
return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
|
||||
}
|
||||
|
||||
const environmentApiError = (message: string) => (cause: unknown) => {
|
||||
const environmentError = findEnvironmentCloudApiError(cause);
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: environmentError
|
||||
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
|
||||
: message,
|
||||
cause,
|
||||
});
|
||||
};
|
||||
|
||||
function endpointOrigin(httpBaseUrl: string) {
|
||||
const url = new URL(httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
}
|
||||
|
||||
const MANAGED_ENDPOINT_PROVIDER_KIND =
|
||||
@@ -395,19 +214,13 @@ function ensureLinkedEnvironmentMatches(input: {
|
||||
readonly link: RelayEnvironmentLinkResponse;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.link.environmentId !== input.expectedEnvironmentId) {
|
||||
return new CloudEnvironmentLinkResponseMismatchError({
|
||||
environmentId: input.expectedEnvironmentId,
|
||||
field: "environment id",
|
||||
expected: input.expectedEnvironmentId,
|
||||
actual: input.link.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
|
||||
return new CloudEnvironmentLinkResponseMismatchError({
|
||||
environmentId: input.expectedEnvironmentId,
|
||||
field: "endpoint provider",
|
||||
expected: input.expectedProviderKind,
|
||||
actual: input.link.endpoint.providerKind,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -462,7 +275,9 @@ export function listManagedCloudEnvironments(input: {
|
||||
return Effect.gen(function* () {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudRelayUrlNotConfiguredError({});
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "T3CODE_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
return yield* relayClient
|
||||
@@ -470,12 +285,12 @@ export function listManagedCloudEnvironments(input: {
|
||||
clerkToken: input.clerkToken,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromManagedRelay({
|
||||
action: "list relay-managed environments",
|
||||
relayUrl: configuredRelayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudEnvironmentLinkError({
|
||||
message: "Could not list relay-managed environments.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -489,18 +304,19 @@ export function listCloudDevices(input: {
|
||||
ManagedRelay.ManagedRelayClient
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudRelayUrlNotConfiguredError({});
|
||||
if (!relayUrl()) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "T3CODE_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
return yield* relayClient.listDevices({ clerkToken: input.clerkToken }).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromManagedRelay({
|
||||
action: "list cloud devices",
|
||||
relayUrl: configuredRelayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudEnvironmentLinkError({
|
||||
message: "Could not list cloud devices.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -510,20 +326,10 @@ export function readPrimaryCloudLinkState(input: {
|
||||
readonly target: CloudLinkTarget;
|
||||
}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {
|
||||
return Effect.gen(function* () {
|
||||
const client = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
});
|
||||
return yield* client.connect.linkState({ headers: {} }).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromEnvironmentApi({
|
||||
action: "read environment cloud link state",
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
|
||||
return yield* client.connect
|
||||
.linkState({ headers: {} })
|
||||
.pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
|
||||
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
|
||||
}
|
||||
|
||||
@@ -532,24 +338,14 @@ export function updatePrimaryCloudPreferences(input: {
|
||||
readonly publishAgentActivity: boolean;
|
||||
}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
|
||||
return Effect.gen(function* () {
|
||||
const client = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
});
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
|
||||
return yield* client.connect
|
||||
.preferences({
|
||||
headers: {},
|
||||
payload: input,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromEnvironmentApi({
|
||||
action: "update environment cloud preferences",
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
|
||||
);
|
||||
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
|
||||
}
|
||||
@@ -563,20 +359,10 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
|
||||
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const client = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
});
|
||||
yield* client.connect.unlink({ headers: {} }).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromEnvironmentApi({
|
||||
action: "unlink the environment from cloud",
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
|
||||
yield* client.connect
|
||||
.unlink({ headers: {} })
|
||||
.pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
|
||||
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (configuredRelayUrl && input.clerkToken) {
|
||||
@@ -587,27 +373,11 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
|
||||
environmentId: EnvironmentId.make(input.target.environmentId),
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((cause) => {
|
||||
const error = CloudEnvironmentLinkOperationError.fromManagedRelay({
|
||||
action: "revoke the cloud environment link",
|
||||
environmentId: input.target.environmentId,
|
||||
relayUrl: configuredRelayUrl,
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
|
||||
cause,
|
||||
});
|
||||
return Effect.logWarning(error.message, {
|
||||
environmentId: input.target.environmentId,
|
||||
...(error.relayUrlInputLength === undefined
|
||||
? {}
|
||||
: { relayUrlInputLength: error.relayUrlInputLength }),
|
||||
...(error.relayUrlProtocol === undefined
|
||||
? {}
|
||||
: { relayUrlProtocol: error.relayUrlProtocol }),
|
||||
...(error.relayUrlHostname === undefined
|
||||
? {}
|
||||
: { relayUrlHostname: error.relayUrlHostname }),
|
||||
causeTag: cause._tag,
|
||||
});
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
|
||||
@@ -624,19 +394,12 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
return Effect.gen(function* () {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudRelayUrlNotConfiguredError({
|
||||
environmentId: input.target.environmentId,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "T3CODE_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const origin = yield* endpointOrigin({
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
});
|
||||
const environmentClient = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
});
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
|
||||
yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
|
||||
|
||||
const challenge = yield* relayClient
|
||||
@@ -649,13 +412,10 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromManagedRelay({
|
||||
action: "create an environment link challenge",
|
||||
environmentId: input.target.environmentId,
|
||||
relayUrl: configuredRelayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
|
||||
),
|
||||
),
|
||||
);
|
||||
const proof = yield* environmentClient.connect
|
||||
@@ -669,19 +429,10 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
wsBaseUrl: input.target.wsBaseUrl,
|
||||
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
|
||||
},
|
||||
origin,
|
||||
origin: endpointOrigin(input.target.httpBaseUrl),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromEnvironmentApi({
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
|
||||
const link = yield* relayClient
|
||||
.linkEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -693,13 +444,8 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromManagedRelay({
|
||||
action: "link the environment",
|
||||
environmentId: input.target.environmentId,
|
||||
relayUrl: configuredRelayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
|
||||
),
|
||||
);
|
||||
yield* ensureLinkedEnvironmentMatches({
|
||||
@@ -720,15 +466,6 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
endpointRuntime: link.endpointRuntime,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromEnvironmentApi({
|
||||
action: "configure environment relay access",
|
||||
environmentId: input.target.environmentId,
|
||||
httpBaseUrl: input.target.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
|
||||
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
|
||||
}
|
||||
@@ -50,24 +50,25 @@ export const relayDpopSignerLayer = Layer.effect(
|
||||
),
|
||||
createProof: Effect.fn("web.managedRelayDpopSigner.createProof")(function* (input) {
|
||||
const proofKey = yield* loadOrCreateBrowserDpopKey.pipe(
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopKeyLoadError.fromTarget({
|
||||
keyStore: "indexed-db",
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* createBrowserDpopProof({ ...input, proofKey }).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.map((proof) => proof.proof),
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopProofCreationError.fromTarget({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -7,7 +7,6 @@ import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "~/compone
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
import { reportPreviewActionFailure } from "./reportPreviewActionFailure";
|
||||
|
||||
interface Props {
|
||||
/** Active preview tab id. Tab-targeting actions are disabled without it. */
|
||||
@@ -31,11 +30,9 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
if (!previewBridge) return null;
|
||||
const bridge = previewBridge;
|
||||
const tabDisabled = !tabId || !hasWebContents;
|
||||
const callTab = (operation: string, op: (tabId: string) => Promise<void>) => () => {
|
||||
const callTab = (op: (tabId: string) => Promise<void>) => () => {
|
||||
if (!tabId) return;
|
||||
void op(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation, tabId }, cause);
|
||||
});
|
||||
void op(tabId).catch(() => undefined);
|
||||
};
|
||||
|
||||
const zoomLabel = `${Math.round(zoomFactor * 100)}%`;
|
||||
@@ -56,10 +53,10 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
<TooltipPopup>More</TooltipPopup>
|
||||
</Tooltip>
|
||||
<MenuPopup align="end" sideOffset={6} className="min-w-56">
|
||||
<MenuItem onClick={callTab("hard-reload", bridge.hardReload)} disabled={tabDisabled}>
|
||||
<MenuItem onClick={callTab(bridge.hardReload)} disabled={tabDisabled}>
|
||||
Hard reload
|
||||
</MenuItem>
|
||||
<MenuItem onClick={callTab("open-devtools", bridge.openDevTools)} disabled={tabDisabled}>
|
||||
<MenuItem onClick={callTab(bridge.openDevTools)} disabled={tabDisabled}>
|
||||
Open DevTools
|
||||
</MenuItem>
|
||||
{/*
|
||||
@@ -78,7 +75,7 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
variant="outline"
|
||||
size="icon-xs"
|
||||
type="button"
|
||||
onClick={callTab("zoom-out", bridge.zoomOut)}
|
||||
onClick={callTab(bridge.zoomOut)}
|
||||
aria-label="Zoom out"
|
||||
disabled={tabDisabled}
|
||||
>
|
||||
@@ -91,7 +88,7 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
variant="outline"
|
||||
size="icon-xs"
|
||||
type="button"
|
||||
onClick={callTab("zoom-in", bridge.zoomIn)}
|
||||
onClick={callTab(bridge.zoomIn)}
|
||||
aria-label="Zoom in"
|
||||
disabled={tabDisabled}
|
||||
>
|
||||
@@ -101,7 +98,7 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
type="button"
|
||||
onClick={callTab("reset-zoom", bridge.resetZoom)}
|
||||
onClick={callTab(bridge.resetZoom)}
|
||||
aria-label="Reset zoom"
|
||||
disabled={tabDisabled}
|
||||
>
|
||||
@@ -110,22 +107,10 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
</span>
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem
|
||||
onClick={() =>
|
||||
void bridge.clearCookies().catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "clear-cookies" }, cause);
|
||||
})
|
||||
}
|
||||
>
|
||||
<MenuItem onClick={() => void bridge.clearCookies().catch(() => undefined)}>
|
||||
Clear cookies
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() =>
|
||||
void bridge.clearCache().catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "clear-cache" }, cause);
|
||||
})
|
||||
}
|
||||
>
|
||||
<MenuItem onClick={() => void bridge.clearCache().catch(() => undefined)}>
|
||||
Clear cache
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
|
||||
import { type ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
@@ -21,7 +20,6 @@ import { PreviewChromeRow } from "./PreviewChromeRow";
|
||||
import { formatPreviewUrl } from "./previewUrlPresentation";
|
||||
import { PreviewEmptyState } from "./PreviewEmptyState";
|
||||
import { PreviewMoreMenu } from "./PreviewMoreMenu";
|
||||
import { previewUrlFailureContext, reportPreviewActionFailure } from "./reportPreviewActionFailure";
|
||||
import { PreviewUnreachable } from "./PreviewUnreachable";
|
||||
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
|
||||
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
|
||||
@@ -93,112 +91,58 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
environmentHttpBaseUrl,
|
||||
}) ?? undefined)
|
||||
: undefined;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
|
||||
const handleSubmitUrl = useCallback(
|
||||
async (next: string) => {
|
||||
let operation = "resolve-url";
|
||||
let targetUrl = next;
|
||||
try {
|
||||
const resolvedUrl = resolveDiscoveredServerUrl(threadRef.environmentId, next);
|
||||
targetUrl = resolvedUrl;
|
||||
if (tabId && previewBridge) {
|
||||
// Drive the webview imperatively; `usePreviewBridge` mirrors the
|
||||
// resolved URL back to the server so other clients stay in sync.
|
||||
operation = "navigate";
|
||||
await previewBridge.navigate(tabId, resolvedUrl);
|
||||
rememberPreviewUrl(threadRef, resolvedUrl);
|
||||
} else {
|
||||
operation = "open-session";
|
||||
const result = await openPreviewSession({
|
||||
await openPreviewSession({
|
||||
openPreview: open,
|
||||
threadRef,
|
||||
url: resolvedUrl,
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation,
|
||||
threadKey,
|
||||
...(tabId ? { tabId } : {}),
|
||||
...previewUrlFailureContext(targetUrl),
|
||||
},
|
||||
result.cause,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation,
|
||||
threadKey,
|
||||
...(tabId ? { tabId } : {}),
|
||||
...previewUrlFailureContext(targetUrl),
|
||||
},
|
||||
cause,
|
||||
);
|
||||
} catch {
|
||||
// Server-side `failed` event renders the unreachable view.
|
||||
}
|
||||
},
|
||||
[open, tabId, threadKey, threadRef],
|
||||
[open, tabId, threadRef],
|
||||
);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
void previewBridge.refresh(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "refresh", threadKey, tabId }, cause);
|
||||
});
|
||||
}, [tabId, threadKey]);
|
||||
if (previewBridge && tabId) void previewBridge.refresh(tabId);
|
||||
}, [tabId]);
|
||||
|
||||
const handleZoomIn = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
void previewBridge.zoomIn(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "zoom-in", threadKey, tabId }, cause);
|
||||
});
|
||||
}, [tabId, threadKey]);
|
||||
if (previewBridge && tabId) void previewBridge.zoomIn(tabId);
|
||||
}, [tabId]);
|
||||
|
||||
const handleZoomOut = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
void previewBridge.zoomOut(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "zoom-out", threadKey, tabId }, cause);
|
||||
});
|
||||
}, [tabId, threadKey]);
|
||||
if (previewBridge && tabId) void previewBridge.zoomOut(tabId);
|
||||
}, [tabId]);
|
||||
|
||||
const handleResetZoom = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
void previewBridge.resetZoom(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "reset-zoom", threadKey, tabId }, cause);
|
||||
});
|
||||
}, [tabId, threadKey]);
|
||||
if (previewBridge && tabId) void previewBridge.resetZoom(tabId);
|
||||
}, [tabId]);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
void previewBridge.goBack(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "go-back", threadKey, tabId }, cause);
|
||||
});
|
||||
}, [tabId, threadKey]);
|
||||
if (previewBridge && tabId) void previewBridge.goBack(tabId);
|
||||
}, [tabId]);
|
||||
|
||||
const handleForward = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
void previewBridge.goForward(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure({ operation: "go-forward", threadKey, tabId }, cause);
|
||||
});
|
||||
}, [tabId, threadKey]);
|
||||
if (previewBridge && tabId) void previewBridge.goForward(tabId);
|
||||
}, [tabId]);
|
||||
|
||||
const handleOpenInBrowser = useCallback(() => {
|
||||
if (!localApi || !url) return;
|
||||
void localApi.shell.openExternal(url).catch((cause) => {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "open-external",
|
||||
threadKey,
|
||||
...(tabId ? { tabId } : {}),
|
||||
...previewUrlFailureContext(url),
|
||||
},
|
||||
cause,
|
||||
);
|
||||
});
|
||||
}, [tabId, threadKey, url]);
|
||||
void localApi.shell.openExternal(url).catch(() => undefined);
|
||||
}, [url]);
|
||||
|
||||
const handleCapture = useCallback(
|
||||
(record: boolean) => {
|
||||
@@ -236,15 +180,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, 2_000);
|
||||
},
|
||||
(error) => {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "copy-recording-path",
|
||||
threadKey,
|
||||
tabId,
|
||||
artifactPath: artifact.path,
|
||||
},
|
||||
error,
|
||||
);
|
||||
toastManager.update(
|
||||
toastId,
|
||||
stackedThreadToast({
|
||||
@@ -260,18 +195,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
|
||||
const revealAction = {
|
||||
children: revealInFileExplorerLabel(navigator.platform),
|
||||
onClick: () =>
|
||||
void bridge.revealArtifact(artifact.path).catch((cause) => {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "reveal-recording",
|
||||
threadKey,
|
||||
tabId,
|
||||
artifactPath: artifact.path,
|
||||
},
|
||||
cause,
|
||||
);
|
||||
}),
|
||||
onClick: () => void bridge.revealArtifact(artifact.path),
|
||||
};
|
||||
const updateRecordingToast = () => {
|
||||
toastManager.update(
|
||||
@@ -308,7 +232,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
},
|
||||
(error) => {
|
||||
reportPreviewActionFailure({ operation: "stop-recording", threadKey, tabId }, error);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to stop recording",
|
||||
@@ -328,7 +251,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
return;
|
||||
}
|
||||
void startBrowserRecording(tabId).catch((error) => {
|
||||
reportPreviewActionFailure({ operation: "start-recording", threadKey, tabId }, error);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to start recording",
|
||||
@@ -341,18 +263,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
(artifact) => {
|
||||
const revealAction = {
|
||||
children: revealInFileExplorerLabel(navigator.platform),
|
||||
onClick: () =>
|
||||
void bridge.revealArtifact(artifact.path).catch((cause) => {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "reveal-screenshot",
|
||||
threadKey,
|
||||
tabId,
|
||||
artifactPath: artifact.path,
|
||||
},
|
||||
cause,
|
||||
);
|
||||
}),
|
||||
onClick: () => void bridge.revealArtifact(artifact.path),
|
||||
};
|
||||
let pathCopied = false;
|
||||
let imageCopied = false;
|
||||
@@ -414,15 +325,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, 2_000);
|
||||
},
|
||||
(error) => {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "copy-screenshot-path",
|
||||
threadKey,
|
||||
tabId,
|
||||
artifactPath: artifact.path,
|
||||
},
|
||||
error,
|
||||
);
|
||||
updateScreenshotToast(
|
||||
"error",
|
||||
"Unable to copy screenshot path",
|
||||
@@ -443,15 +345,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, 2_000);
|
||||
},
|
||||
(error) => {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "copy-screenshot-image",
|
||||
threadKey,
|
||||
tabId,
|
||||
artifactPath: artifact.path,
|
||||
},
|
||||
error,
|
||||
);
|
||||
updateScreenshotToast(
|
||||
"error",
|
||||
"Unable to copy screenshot",
|
||||
@@ -488,7 +381,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
},
|
||||
(error) => {
|
||||
reportPreviewActionFailure({ operation: "capture-screenshot", threadKey, tabId }, error);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to capture screenshot",
|
||||
@@ -497,18 +389,13 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
},
|
||||
);
|
||||
},
|
||||
[activeRecordingTabId, tabId, threadKey],
|
||||
[activeRecordingTabId, tabId],
|
||||
);
|
||||
|
||||
const handlePickElement = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (pickActiveRef.current) {
|
||||
void previewBridge.cancelPickElement(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure(
|
||||
{ operation: "cancel-element-picker", threadKey, tabId, trigger: "toggle" },
|
||||
cause,
|
||||
);
|
||||
});
|
||||
void previewBridge.cancelPickElement(tabId).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
// Snapshot whatever the user was focused on (typically the chat
|
||||
@@ -521,18 +408,12 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
pickActiveRef.current = true;
|
||||
setPickActive(true);
|
||||
void (async () => {
|
||||
let operation = "pick-element";
|
||||
let annotationId: string | undefined;
|
||||
try {
|
||||
const annotation = await previewBridge.pickElement(tabId);
|
||||
if (!annotation) return;
|
||||
annotationId = annotation.id;
|
||||
operation = "add-preview-annotation";
|
||||
addPreviewAnnotation(threadRef, annotation);
|
||||
operation = "prepare-annotation-screenshot";
|
||||
const screenshotFile = await previewAnnotationScreenshotFile(annotation);
|
||||
if (screenshotFile && annotation.screenshot) {
|
||||
operation = "attach-annotation-screenshot";
|
||||
addImage(threadRef, {
|
||||
type: "image",
|
||||
id: annotation.id,
|
||||
@@ -543,17 +424,8 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
file: screenshotFile,
|
||||
});
|
||||
}
|
||||
} catch (cause) {
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation,
|
||||
threadKey,
|
||||
tabId,
|
||||
...(annotationId ? { annotationId } : {}),
|
||||
},
|
||||
cause,
|
||||
);
|
||||
// Keep picker failures silent in the UI; navigating during a pick is expected.
|
||||
} catch {
|
||||
// Picker failed (e.g. webview navigated). Treat as silent cancel.
|
||||
} finally {
|
||||
pickActiveRef.current = false;
|
||||
// Avoid `setState on unmounted component` if the panel/thread closed
|
||||
@@ -575,7 +447,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [addImage, addPreviewAnnotation, tabId, threadKey, threadRef]);
|
||||
}, [addImage, addPreviewAnnotation, tabId, threadRef]);
|
||||
|
||||
// If the active tab changes mid-pick (close, thread switch, hot restart),
|
||||
// tell main to tear down the in-flight session AND reset our local toggle
|
||||
@@ -585,16 +457,11 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
if (!pickActiveRef.current) return;
|
||||
pickActiveRef.current = false;
|
||||
if (previewBridge && tabId) {
|
||||
void previewBridge.cancelPickElement(tabId).catch((cause) => {
|
||||
reportPreviewActionFailure(
|
||||
{ operation: "cancel-element-picker", threadKey, tabId, trigger: "tab-change" },
|
||||
cause,
|
||||
);
|
||||
});
|
||||
void previewBridge.cancelPickElement(tabId).catch(() => undefined);
|
||||
}
|
||||
if (isMountedRef.current) setPickActive(false);
|
||||
};
|
||||
}, [tabId, threadKey]);
|
||||
}, [tabId]);
|
||||
|
||||
// Subscribe only while visible; `toggle-panel` is owned by ChatView's
|
||||
// URL-aware handler regardless of whether the panel is currently mounted.
|
||||
@@ -624,7 +491,10 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background" data-thread-key={threadKey}>
|
||||
<div
|
||||
className="flex min-h-0 flex-1 flex-col bg-background"
|
||||
data-thread-key={scopedThreadKey(threadRef)}
|
||||
>
|
||||
<PreviewChromeRow
|
||||
url={url}
|
||||
displayUrl={displayUrl}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { previewUrlFailureContext, reportPreviewActionFailure } from "./reportPreviewActionFailure";
|
||||
|
||||
describe("reportPreviewActionFailure", () => {
|
||||
it("logs safe preview target metadata without credentials or URL parameters", () => {
|
||||
const url =
|
||||
"https://user:[email protected]/preview/signed-secret-token?access_token=private#fragment";
|
||||
const cause = new Error("navigation failed");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
reportPreviewActionFailure(
|
||||
{
|
||||
operation: "navigate",
|
||||
...previewUrlFailureContext(url),
|
||||
},
|
||||
cause,
|
||||
);
|
||||
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
"[preview] action failed",
|
||||
{
|
||||
operation: "navigate",
|
||||
urlHostname: "example.com",
|
||||
urlLength: url.length,
|
||||
urlProtocol: "https:",
|
||||
},
|
||||
cause,
|
||||
);
|
||||
const loggedContext = consoleError.mock.calls[0]?.[1];
|
||||
expect(loggedContext).not.toHaveProperty("url");
|
||||
expect(JSON.stringify(loggedContext)).not.toContain("signed-secret-token");
|
||||
expect(JSON.stringify(loggedContext)).not.toContain("access_token=private");
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
export interface PreviewActionFailureContext {
|
||||
readonly operation: string;
|
||||
readonly threadKey?: string;
|
||||
readonly tabId?: string;
|
||||
readonly urlHostname?: string;
|
||||
readonly urlLength?: number;
|
||||
readonly urlProtocol?: string;
|
||||
readonly artifactPath?: string;
|
||||
readonly annotationId?: string;
|
||||
readonly trigger?: string;
|
||||
}
|
||||
|
||||
export function previewUrlFailureContext(url: string) {
|
||||
const diagnostics = getUrlDiagnostics(url);
|
||||
return {
|
||||
urlLength: diagnostics.inputLength,
|
||||
...(diagnostics.hostname === undefined ? {} : { urlHostname: diagnostics.hostname }),
|
||||
...(diagnostics.protocol === undefined ? {} : { urlProtocol: diagnostics.protocol }),
|
||||
};
|
||||
}
|
||||
|
||||
export function reportPreviewActionFailure(
|
||||
context: PreviewActionFailureContext,
|
||||
cause: unknown,
|
||||
): void {
|
||||
console.error("[preview] action failed", context, cause);
|
||||
}
|
||||
@@ -1837,7 +1837,7 @@ function ConfiguredCloudRemoteEnvironmentRows({
|
||||
? "Relay offline"
|
||||
: availability === "checking"
|
||||
? "Checking relay status"
|
||||
: (Option.getOrNull(error)?.detail ?? "Relay status unavailable")
|
||||
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
|
||||
}
|
||||
/>
|
||||
<p className="truncate text-sm font-medium">{environment.label}</p>
|
||||
@@ -1854,7 +1854,7 @@ function ConfiguredCloudRemoteEnvironmentRows({
|
||||
? "Available · Relay offline"
|
||||
: availability === "checking"
|
||||
? "Available · Checking relay status…"
|
||||
: (Option.getOrNull(error)?.detail ?? "Available · Relay status unavailable")}
|
||||
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import {
|
||||
ConnectionBlockedError,
|
||||
ConnectionTransientError,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
AuthStandardClientScopes,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
EnvironmentId,
|
||||
type DesktopBridge,
|
||||
type DesktopSshEnvironmentTarget,
|
||||
@@ -23,14 +18,11 @@ const TARGET: DesktopSshEnvironmentTarget = {
|
||||
|
||||
function makeBridge(
|
||||
calls: string[],
|
||||
options?: { readonly descriptorError?: unknown; readonly ensureError?: unknown },
|
||||
options?: { readonly failDescriptor?: boolean },
|
||||
): DesktopBridge {
|
||||
return {
|
||||
ensureSshEnvironment: async (target: DesktopSshEnvironmentTarget) => {
|
||||
calls.push("ensure");
|
||||
if (options?.ensureError !== undefined) {
|
||||
throw options.ensureError;
|
||||
}
|
||||
return {
|
||||
target,
|
||||
httpBaseUrl: "http://127.0.0.1:3201/",
|
||||
@@ -40,8 +32,8 @@ function makeBridge(
|
||||
},
|
||||
fetchSshEnvironmentDescriptor: async () => {
|
||||
calls.push("descriptor");
|
||||
if (options?.descriptorError !== undefined) {
|
||||
throw options.descriptorError;
|
||||
if (options?.failDescriptor === true) {
|
||||
throw new Error("descriptor unavailable");
|
||||
}
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment-ssh"),
|
||||
@@ -86,67 +78,11 @@ describe("desktop SSH pairing", () => {
|
||||
const calls: string[] = [];
|
||||
|
||||
yield* provisionDesktopSshEnvironment(
|
||||
makeBridge(calls, { descriptorError: new Error("descriptor unavailable") }),
|
||||
makeBridge(calls, { failDescriptor: true }),
|
||||
TARGET,
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(calls).toEqual(["ensure", "descriptor"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves SSH preparation causes without exposing their message", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("descriptor response contained a private endpoint");
|
||||
|
||||
const error = yield* provisionDesktopSshEnvironment(
|
||||
makeBridge([], { descriptorError: cause }),
|
||||
TARGET,
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionTransientError);
|
||||
expect(error.detail).toBe("Could not prepare the SSH environment.");
|
||||
expect(error.message).toBe("Connection attempt failed (remote-unavailable).");
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
expect(error.cause).toBe(cause);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("classifies password prompt cancellation from its tag and preserves its cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const promptCause = new Error("password prompt closed");
|
||||
const cancellation = new DesktopSshPasswordPromptCancellationError({
|
||||
reason: "window-closed",
|
||||
requestId: "prompt-1",
|
||||
destination: "[email protected]",
|
||||
cause: promptCause,
|
||||
});
|
||||
|
||||
const error = yield* provisionDesktopSshEnvironment(
|
||||
makeBridge([], { ensureError: cancellation }),
|
||||
TARGET,
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionBlockedError);
|
||||
expect(error.detail).toBe(
|
||||
"SSH authentication did not complete for [email protected].",
|
||||
);
|
||||
expect(error.message).toBe("Connection attempt blocked (authentication).");
|
||||
expect(error.cause).toBe(cancellation);
|
||||
expect(cancellation.cause).toBe(promptCause);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not infer cancellation from an unstructured error message", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("remote operation was cancelled");
|
||||
|
||||
const error = yield* provisionDesktopSshEnvironment(
|
||||
makeBridge([], { ensureError: cause }),
|
||||
TARGET,
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionTransientError);
|
||||
expect(error.cause).toBe(cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -21,7 +21,6 @@ import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/cl
|
||||
import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
|
||||
import {
|
||||
AuthStandardClientScopes,
|
||||
isDesktopSshPasswordPromptCancellationError,
|
||||
type DesktopBridge,
|
||||
type DesktopSshEnvironmentTarget,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -106,36 +105,30 @@ function clientMetadata() {
|
||||
};
|
||||
}
|
||||
|
||||
const trySshPreparation = <A>(operation: () => Promise<A>) =>
|
||||
Effect.tryPromise({
|
||||
try: operation,
|
||||
catch: (cause) =>
|
||||
isDesktopSshPasswordPromptCancellationError(cause)
|
||||
? cause
|
||||
: new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: "Could not prepare the SSH environment.",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopSshPasswordPromptCancellationError: (cause) =>
|
||||
new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
function sshPreparationError(cause: unknown) {
|
||||
const message = cause instanceof Error ? cause.message : String(cause);
|
||||
if (message.toLowerCase().includes("cancel")) {
|
||||
return new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: message,
|
||||
});
|
||||
}
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not prepare the SSH environment: ${message}`,
|
||||
});
|
||||
}
|
||||
|
||||
export const provisionDesktopSshEnvironment = Effect.fn(
|
||||
"web.connectionPlatform.ssh.provisionDesktop",
|
||||
)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) {
|
||||
const bootstrap = yield* trySshPreparation(() =>
|
||||
bridge.ensureSshEnvironment(target, {
|
||||
issuePairingToken: true,
|
||||
}),
|
||||
);
|
||||
const bootstrap = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
bridge.ensureSshEnvironment(target, {
|
||||
issuePairingToken: true,
|
||||
}),
|
||||
catch: sshPreparationError,
|
||||
});
|
||||
const pairingToken = bootstrap.pairingToken;
|
||||
if (pairingToken === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
@@ -143,12 +136,14 @@ export const provisionDesktopSshEnvironment = Effect.fn(
|
||||
detail: "The SSH environment did not issue a pairing credential.",
|
||||
});
|
||||
}
|
||||
const descriptor = yield* trySshPreparation(() =>
|
||||
bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
|
||||
);
|
||||
const access = yield* trySshPreparation(() =>
|
||||
bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
|
||||
);
|
||||
const descriptor = yield* Effect.tryPromise({
|
||||
try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
|
||||
catch: sshPreparationError,
|
||||
});
|
||||
const access = yield* Effect.tryPromise({
|
||||
try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
|
||||
catch: sshPreparationError,
|
||||
});
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
label: descriptor.label,
|
||||
@@ -177,8 +172,7 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
detail: "Could not read the T3 Cloud session token.",
|
||||
cause: error,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -200,8 +194,7 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: "Could not load the desktop primary credential.",
|
||||
cause,
|
||||
detail: `Could not load the desktop primary credential: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.fromNullishOr)),
|
||||
});
|
||||
@@ -224,20 +217,24 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
});
|
||||
}
|
||||
const bootstrap = yield* trySshPreparation(() =>
|
||||
bridge.ensureSshEnvironment(input.target, {
|
||||
issuePairingToken: true,
|
||||
}),
|
||||
);
|
||||
const bootstrap = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
bridge.ensureSshEnvironment(input.target, {
|
||||
issuePairingToken: true,
|
||||
}),
|
||||
catch: sshPreparationError,
|
||||
});
|
||||
if (bootstrap.pairingToken === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The SSH environment did not issue a pairing credential.",
|
||||
});
|
||||
}
|
||||
const access = yield* trySshPreparation(() =>
|
||||
bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
|
||||
);
|
||||
const access = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
|
||||
catch: sshPreparationError,
|
||||
});
|
||||
return {
|
||||
bootstrap,
|
||||
bearerToken: access.access_token,
|
||||
@@ -253,8 +250,7 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: "Could not disconnect the SSH environment.",
|
||||
cause,
|
||||
detail: `Could not disconnect the SSH environment: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -70,34 +70,11 @@ describe("makeCatalogBackend", () => {
|
||||
const error = yield* backend.write("{}").pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionTransientError);
|
||||
expect(error.detail).toContain("Desktop secure storage is unavailable");
|
||||
expect(error.message).toBe("Connection attempt failed (remote-unavailable).");
|
||||
expect(error.cause).toMatchObject({ _tag: "DesktopSecureStorageUnavailableError" });
|
||||
expect(error.message).toBe("Could not save the local connection catalog.");
|
||||
expect(error.cause).toEqual(
|
||||
new Error("Desktop secure storage is unavailable in this system context."),
|
||||
);
|
||||
expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves secure-storage write failures without exposing them in the message", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("credential vault path leaked");
|
||||
vi.stubGlobal("window", {
|
||||
desktopBridge: {
|
||||
getConnectionCatalog: vi.fn().mockResolvedValue(null),
|
||||
setConnectionCatalog: vi.fn().mockRejectedValue(cause),
|
||||
},
|
||||
});
|
||||
const backend = makeCatalogBackend({} as IDBDatabase);
|
||||
|
||||
const error = yield* backend.write("{}").pipe(Effect.flip);
|
||||
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "ConnectionStorageOperationError",
|
||||
operation: "save",
|
||||
backend: "desktop-secure-storage",
|
||||
cause,
|
||||
});
|
||||
expect(error.detail).toBe("Could not save local connection data.");
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -13,11 +13,8 @@ import {
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { TokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
CredentialStore,
|
||||
DesktopSecureStorageUnavailableError,
|
||||
IndexedDbUnavailableError,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
@@ -63,11 +60,19 @@ const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshotJson);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* () {
|
||||
return yield* Effect.callback<IDBDatabase, ConnectionTransientError>((resume) => {
|
||||
if (typeof indexedDB === "undefined") {
|
||||
resume(
|
||||
Effect.fail(ConnectionTransientError.fromStorageFailure(new IndexedDbUnavailableError())),
|
||||
Effect.fail(catalogError("open", "IndexedDB is unavailable in this browser context.")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -83,18 +88,8 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* (
|
||||
request.result.createObjectStore(THREAD_STORE_NAME);
|
||||
}
|
||||
});
|
||||
request.addEventListener("error", (event) => {
|
||||
resume(
|
||||
Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "open",
|
||||
backend: "indexed-db",
|
||||
cause: request.error ?? event,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
request.addEventListener("error", () => {
|
||||
resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
|
||||
});
|
||||
request.addEventListener("success", () => {
|
||||
resume(Effect.succeed(request.result));
|
||||
@@ -105,20 +100,8 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* (
|
||||
function readDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
|
||||
return Effect.callback<unknown, ConnectionTransientError>((resume) => {
|
||||
const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
|
||||
request.addEventListener("error", (event) => {
|
||||
resume(
|
||||
Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "read",
|
||||
backend: "indexed-db",
|
||||
storeName,
|
||||
key,
|
||||
cause: request.error ?? event,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
request.addEventListener("error", () => {
|
||||
resume(Effect.fail(catalogError("read", request.error ?? "Unknown IndexedDB read error")));
|
||||
});
|
||||
request.addEventListener("success", () => {
|
||||
resume(Effect.succeed(request.result));
|
||||
@@ -134,19 +117,9 @@ function writeDatabaseValue(
|
||||
) {
|
||||
return Effect.callback<void, ConnectionTransientError>((resume) => {
|
||||
const transaction = database.transaction(storeName, "readwrite");
|
||||
transaction.addEventListener("error", (event) => {
|
||||
transaction.addEventListener("error", () => {
|
||||
resume(
|
||||
Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "write",
|
||||
backend: "indexed-db",
|
||||
storeName,
|
||||
key,
|
||||
cause: transaction.error ?? event,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
|
||||
);
|
||||
});
|
||||
transaction.addEventListener("complete", () => {
|
||||
@@ -159,19 +132,9 @@ function writeDatabaseValue(
|
||||
function removeDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
|
||||
return Effect.callback<void, ConnectionTransientError>((resume) => {
|
||||
const transaction = database.transaction(storeName, "readwrite");
|
||||
transaction.addEventListener("error", (event) => {
|
||||
transaction.addEventListener("error", () => {
|
||||
resume(
|
||||
Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "remove",
|
||||
backend: "indexed-db",
|
||||
storeName,
|
||||
key,
|
||||
cause: transaction.error ?? event,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error")),
|
||||
);
|
||||
});
|
||||
transaction.addEventListener("complete", () => {
|
||||
@@ -184,36 +147,18 @@ function removeDatabaseValue(database: IDBDatabase, storeName: string, key: IDBV
|
||||
function removeDatabaseValuesInRange(database: IDBDatabase, storeName: string, range: IDBKeyRange) {
|
||||
return Effect.callback<void, ConnectionTransientError>((resume) => {
|
||||
const transaction = database.transaction(storeName, "readwrite");
|
||||
transaction.addEventListener("error", (event) => {
|
||||
transaction.addEventListener("error", () => {
|
||||
resume(
|
||||
Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "remove",
|
||||
backend: "indexed-db",
|
||||
storeName,
|
||||
cause: transaction.error ?? event,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB cursor error")),
|
||||
);
|
||||
});
|
||||
transaction.addEventListener("complete", () => {
|
||||
resume(Effect.void);
|
||||
});
|
||||
const request = transaction.objectStore(storeName).openCursor(range);
|
||||
request.addEventListener("error", (event) => {
|
||||
request.addEventListener("error", () => {
|
||||
resume(
|
||||
Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "remove",
|
||||
backend: "indexed-db",
|
||||
storeName,
|
||||
cause: request.error ?? event,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),
|
||||
);
|
||||
});
|
||||
request.addEventListener("success", () => {
|
||||
@@ -233,15 +178,7 @@ function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
|
||||
|
||||
const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
|
||||
return yield* decodeConnectionCatalogDocument(raw).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "decode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.mapError((cause) => catalogError("decode", cause)),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -249,15 +186,7 @@ const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function*
|
||||
catalog: ConnectionCatalogDocumentType,
|
||||
) {
|
||||
return yield* encodeConnectionCatalogDocument(catalog).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "encode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.mapError((cause) => catalogError("encode", cause)),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -273,33 +202,20 @@ export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
|
||||
return {
|
||||
read: Effect.tryPromise({
|
||||
try: () => bridge.getConnectionCatalog!(),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "load",
|
||||
backend: "desktop-secure-storage",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("load", cause),
|
||||
}),
|
||||
write: (raw) =>
|
||||
Effect.tryPromise({
|
||||
try: () => bridge.setConnectionCatalog!(raw),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "save",
|
||||
backend: "desktop-secure-storage",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("save", cause),
|
||||
}).pipe(
|
||||
Effect.flatMap((stored) =>
|
||||
stored
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new DesktopSecureStorageUnavailableError(),
|
||||
catalogError(
|
||||
"save",
|
||||
new Error("Desktop secure storage is unavailable in this system context."),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -339,33 +255,31 @@ export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStor
|
||||
let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
|
||||
if (raw !== null && raw.trim() !== "") {
|
||||
catalog = yield* decodeCatalog(raw).pipe(
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Discarding a corrupt web connection catalog.", { error });
|
||||
if (backend.quarantine !== undefined) {
|
||||
yield* backend.quarantine(raw).pipe(
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning(
|
||||
"Could not quarantine the corrupt web connection catalog.",
|
||||
{ error },
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
|
||||
error: error.message,
|
||||
});
|
||||
if (backend.quarantine !== undefined) {
|
||||
yield* backend.quarantine(raw).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
|
||||
error: cause.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
|
||||
yield* backend.write(encoded).pipe(
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning("Could not persist the recovered web connection catalog.", {
|
||||
error,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return EMPTY_CONNECTION_CATALOG_DOCUMENT;
|
||||
}),
|
||||
}),
|
||||
}
|
||||
const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
|
||||
yield* backend.write(encoded).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not persist the recovered web connection catalog.", {
|
||||
error: cause.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return EMPTY_CONNECTION_CATALOG_DOCUMENT;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
yield* Ref.set(state, Option.some(catalog));
|
||||
@@ -398,13 +312,8 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "list-targets",
|
||||
fallbackStage: "read",
|
||||
resource: "connection-catalog",
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -413,28 +322,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "register-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: registration.target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "remove-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -520,30 +418,13 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const cacheStore = EnvironmentCacheStore.of({
|
||||
loadShell: (environmentId) =>
|
||||
readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((raw) => {
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "decode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
@@ -552,6 +433,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -561,61 +447,30 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
snapshot,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "encode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "write",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
readDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, threadId),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "read",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((raw) => {
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "decode",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
@@ -624,6 +479,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -634,15 +494,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
thread,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "encode",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
yield* writeDatabaseValue(
|
||||
@@ -650,20 +502,14 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, thread.id),
|
||||
encoded,
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "write",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
removeDatabaseValue(
|
||||
database,
|
||||
@@ -671,50 +517,24 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
threadCacheKey(environmentId, threadId),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "remove-thread",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
Effect.all(
|
||||
[
|
||||
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
|
||||
removeDatabaseValuesInRange(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
function createStorage(overrides: Partial<Storage> = {}): Storage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
clear: () => store.clear(),
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
removeItem: (key) => {
|
||||
store.delete(key);
|
||||
},
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.doUnmock("react");
|
||||
vi.resetModules();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("theme failure handling", () => {
|
||||
it("preserves exact storage causes and operation context", async () => {
|
||||
const readCause = new Error("storage read blocked");
|
||||
const writeCause = new Error("storage quota exceeded");
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: createStorage({
|
||||
getItem: () => {
|
||||
throw readCause;
|
||||
},
|
||||
setItem: () => {
|
||||
throw writeCause;
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const { readThemePreference, ThemeStorageError, writeThemePreference } =
|
||||
await import("./useTheme");
|
||||
|
||||
try {
|
||||
readThemePreference();
|
||||
expect.unreachable("expected the theme read to fail");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ThemeStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "read",
|
||||
storageKey: "t3code:theme",
|
||||
cause: readCause,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
writeThemePreference("dark");
|
||||
expect.unreachable("expected the theme write to fail");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ThemeStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "write",
|
||||
storageKey: "t3code:theme",
|
||||
theme: "dark",
|
||||
cause: writeCause,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back during initial theme application and logs only safe attributes", async () => {
|
||||
const cause = new Error("private browsing storage failure");
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: createStorage({
|
||||
getItem: () => {
|
||||
throw cause;
|
||||
},
|
||||
}),
|
||||
matchMedia: () => ({ matches: false }),
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList: { toggle: vi.fn() },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(import("./useTheme")).resolves.toBeDefined();
|
||||
|
||||
expect(errorLog).toHaveBeenCalledWith(
|
||||
"Failed to read theme preference for t3code:theme.",
|
||||
expect.objectContaining({
|
||||
operation: "read",
|
||||
storageKey: "t3code:theme",
|
||||
errorTag: "ThemeStorageError",
|
||||
}),
|
||||
);
|
||||
const attributes = errorLog.mock.calls[0]?.[1];
|
||||
expect(attributes).not.toHaveProperty("cause");
|
||||
expect(JSON.stringify(attributes)).not.toContain(cause.message);
|
||||
});
|
||||
|
||||
it("retries a failed storage read only after a relevant storage event", async () => {
|
||||
const cause = new Error("persistent storage failure");
|
||||
const getItem = vi.fn(() => {
|
||||
throw cause;
|
||||
});
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
let readSnapshot: (() => unknown) | undefined;
|
||||
let subscribeToTheme: ((listener: () => void) => () => void) | undefined;
|
||||
let storageHandler: ((event: StorageEvent) => void) | undefined;
|
||||
vi.doMock("react", () => ({
|
||||
useCallback: <A>(callback: A) => callback,
|
||||
useEffect: () => undefined,
|
||||
useSyncExternalStore: (
|
||||
subscribe: (listener: () => void) => () => void,
|
||||
getSnapshot: () => unknown,
|
||||
) => {
|
||||
subscribeToTheme = subscribe;
|
||||
readSnapshot = getSnapshot;
|
||||
return getSnapshot();
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal("window", {
|
||||
addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
|
||||
if (type === "storage") storageHandler = listener;
|
||||
},
|
||||
localStorage: createStorage({ getItem }),
|
||||
matchMedia: () => ({
|
||||
matches: false,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
}),
|
||||
removeEventListener: () => undefined,
|
||||
});
|
||||
|
||||
const { useTheme } = await import("./useTheme");
|
||||
useTheme();
|
||||
readSnapshot?.();
|
||||
readSnapshot?.();
|
||||
|
||||
expect(getItem).toHaveBeenCalledTimes(1);
|
||||
expect(errorLog).toHaveBeenCalledTimes(1);
|
||||
|
||||
const unsubscribe = subscribeToTheme?.(() => undefined);
|
||||
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
|
||||
readSnapshot?.();
|
||||
|
||||
expect(getItem).toHaveBeenCalledTimes(2);
|
||||
expect(errorLog).toHaveBeenCalledTimes(2);
|
||||
unsubscribe?.();
|
||||
});
|
||||
|
||||
it("preserves desktop sync causes and retries after a failed cosmetic sync", async () => {
|
||||
const cause = new Error("desktop IPC unavailable");
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const setTheme = vi.fn().mockRejectedValue(cause);
|
||||
vi.stubGlobal("window", { desktopBridge: { setTheme } });
|
||||
|
||||
const { DesktopThemeSyncError, syncDesktopTheme, syncDesktopThemePreference } =
|
||||
await import("./useTheme");
|
||||
|
||||
const error = await syncDesktopThemePreference({ setTheme }, "dark").then(
|
||||
() => undefined,
|
||||
(failure: unknown) => failure,
|
||||
);
|
||||
expect(error).toBeInstanceOf(DesktopThemeSyncError);
|
||||
expect(error).toMatchObject({ theme: "dark", cause });
|
||||
|
||||
setTheme.mockClear();
|
||||
syncDesktopTheme("dark");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
syncDesktopTheme("dark");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(setTheme).toHaveBeenCalledTimes(2);
|
||||
expect(errorLog).toHaveBeenCalledWith(
|
||||
"Failed to sync the dark theme to the desktop shell.",
|
||||
expect.objectContaining({
|
||||
theme: "dark",
|
||||
errorTag: "DesktopThemeSyncError",
|
||||
}),
|
||||
);
|
||||
for (const [, attributes] of errorLog.mock.calls) {
|
||||
expect(attributes).not.toHaveProperty("cause");
|
||||
expect(JSON.stringify(attributes)).not.toContain(cause.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
+14
-132
@@ -1,17 +1,11 @@
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
const ThemePreference = Schema.Literals(["light", "dark", "system"]);
|
||||
type Theme = typeof ThemePreference.Type;
|
||||
type Theme = "light" | "dark" | "system";
|
||||
type ThemeSnapshot = {
|
||||
theme: Theme;
|
||||
systemDark: boolean;
|
||||
};
|
||||
|
||||
type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
|
||||
@@ -21,46 +15,19 @@ const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
|
||||
const THEME_COLOR_META_NAME = "theme-color";
|
||||
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
|
||||
|
||||
export class ThemeStorageError extends Schema.TaggedErrorClass<ThemeStorageError>()(
|
||||
"ThemeStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "write"]),
|
||||
storageKey: Schema.String,
|
||||
theme: Schema.optional(ThemePreference),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} theme preference for ${this.storageKey}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isThemeStorageError = Schema.is(ThemeStorageError);
|
||||
|
||||
export class DesktopThemeSyncError extends Schema.TaggedErrorClass<DesktopThemeSyncError>()(
|
||||
"DesktopThemeSyncError",
|
||||
{
|
||||
theme: ThemePreference,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to sync the ${this.theme} theme to the desktop shell.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isDesktopThemeSyncError = Schema.is(DesktopThemeSyncError);
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let lastSnapshot: ThemeSnapshot | null = null;
|
||||
let lastDesktopTheme: Theme | null = null;
|
||||
let lastAppliedTheme: ThemeSnapshot | null = null;
|
||||
let themeStorageReadFailure: ThemeStorageError | null = null;
|
||||
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function hasThemeStorage() {
|
||||
return typeof window !== "undefined" && typeof localStorage !== "undefined";
|
||||
}
|
||||
|
||||
function getSystemDark() {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
@@ -69,61 +36,13 @@ function getSystemDark() {
|
||||
);
|
||||
}
|
||||
|
||||
export function readThemePreference(): Theme {
|
||||
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
} catch (cause) {
|
||||
throw new ThemeStorageError({
|
||||
operation: "read",
|
||||
storageKey: STORAGE_KEY,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
function getStored(): Theme {
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") return raw;
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
}
|
||||
|
||||
export function writeThemePreference(theme: Theme): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
themeStorageReadFailure = null;
|
||||
} catch (cause) {
|
||||
throw new ThemeStorageError({
|
||||
operation: "write",
|
||||
storageKey: STORAGE_KEY,
|
||||
theme,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getStored(): Theme {
|
||||
if (themeStorageReadFailure !== null) {
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
}
|
||||
try {
|
||||
return readThemePreference();
|
||||
} catch (cause) {
|
||||
const error = isThemeStorageError(cause)
|
||||
? cause
|
||||
: new ThemeStorageError({
|
||||
operation: "read",
|
||||
storageKey: STORAGE_KEY,
|
||||
cause,
|
||||
});
|
||||
themeStorageReadFailure = error;
|
||||
console.error(error.message, {
|
||||
operation: error.operation,
|
||||
storageKey: error.storageKey,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureThemeColorMetaTag(): HTMLMetaElement {
|
||||
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
|
||||
if (element) {
|
||||
@@ -199,18 +118,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncDesktopThemePreference(
|
||||
bridge: DesktopThemeBridge,
|
||||
theme: Theme,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await bridge.setTheme(theme);
|
||||
} catch (cause) {
|
||||
throw new DesktopThemeSyncError({ theme, cause });
|
||||
}
|
||||
}
|
||||
|
||||
export function syncDesktopTheme(theme: Theme) {
|
||||
function syncDesktopTheme(theme: Theme) {
|
||||
if (typeof window === "undefined") return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) {
|
||||
@@ -218,14 +126,7 @@ export function syncDesktopTheme(theme: Theme) {
|
||||
}
|
||||
|
||||
lastDesktopTheme = theme;
|
||||
void syncDesktopThemePreference(bridge, theme).catch((cause: unknown) => {
|
||||
const error = isDesktopThemeSyncError(cause)
|
||||
? cause
|
||||
: new DesktopThemeSyncError({ theme, cause });
|
||||
console.error(error.message, {
|
||||
theme: error.theme,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
void bridge.setTheme(theme).catch(() => {
|
||||
if (lastDesktopTheme === theme) {
|
||||
lastDesktopTheme = null;
|
||||
}
|
||||
@@ -233,12 +134,12 @@ export function syncDesktopTheme(theme: Theme) {
|
||||
}
|
||||
|
||||
// Apply immediately on module load to prevent flash
|
||||
if (typeof document !== "undefined" && typeof window !== "undefined") {
|
||||
if (typeof document !== "undefined" && hasThemeStorage()) {
|
||||
applyTheme(getStored());
|
||||
}
|
||||
|
||||
function getSnapshot(): ThemeSnapshot {
|
||||
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT;
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT;
|
||||
const theme = getStored();
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
|
||||
@@ -269,7 +170,6 @@ function subscribe(listener: () => void): () => void {
|
||||
// Listen for storage changes from other tabs
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY) {
|
||||
themeStorageReadFailure = null;
|
||||
applyTheme(getStored(), true);
|
||||
emitChange();
|
||||
}
|
||||
@@ -291,26 +191,8 @@ export function useTheme() {
|
||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
writeThemePreference(next);
|
||||
} catch (cause) {
|
||||
const error = isThemeStorageError(cause)
|
||||
? cause
|
||||
: new ThemeStorageError({
|
||||
operation: "write",
|
||||
storageKey: STORAGE_KEY,
|
||||
theme: next,
|
||||
cause,
|
||||
});
|
||||
console.error(error.message, {
|
||||
operation: error.operation,
|
||||
storageKey: error.storageKey,
|
||||
theme: next,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!hasThemeStorage()) return;
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
applyTheme(next, true);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -62,42 +62,17 @@ afterEach(() => {
|
||||
|
||||
describe("LocalApi", () => {
|
||||
it("keeps backend operations unavailable in the browser facade", async () => {
|
||||
const { createLocalApi, LocalBackendUnavailableError } = await import("./localApi");
|
||||
const { createLocalApi } = await import("./localApi");
|
||||
const api = createLocalApi();
|
||||
|
||||
await expect(api.server.getConfig()).rejects.toEqual(
|
||||
new LocalBackendUnavailableError({ operation: "get-config" }),
|
||||
await expect(api.server.getConfig()).rejects.toThrow(
|
||||
"Local backend API is unavailable before a backend is paired.",
|
||||
);
|
||||
await expect(api.shell.openInEditor("/tmp", "cursor")).rejects.toEqual(
|
||||
new LocalBackendUnavailableError({ operation: "open-in-editor" }),
|
||||
await expect(api.shell.openInEditor("/tmp", "cursor")).rejects.toThrow(
|
||||
"Local backend API is unavailable before a backend is paired.",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves desktop bridge failures when opening external URLs", async () => {
|
||||
const cause = new Error("shell rejected request");
|
||||
const url =
|
||||
"https://user:[email protected]/pull/42?access_token=signed-secret-token#private";
|
||||
testWindow().desktopBridge = {
|
||||
openExternal: vi.fn().mockRejectedValue(cause),
|
||||
} as unknown as DesktopBridge;
|
||||
|
||||
const { createLocalApi } = await import("./localApi");
|
||||
const promise = createLocalApi().shell.openExternal(url);
|
||||
|
||||
const error = await promise.catch((error: unknown) => error);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "LocalExternalUrlOpenError",
|
||||
urlHostname: "example.com",
|
||||
urlLength: url.length,
|
||||
urlProtocol: "https:",
|
||||
cause,
|
||||
message: `Unable to open an external URL for example.com through the desktop bridge (https:, input length ${url.length}).`,
|
||||
});
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(String(error)).not.toContain("user:password");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
});
|
||||
|
||||
it("uses the browser context-menu fallback without a desktop bridge", async () => {
|
||||
showContextMenuFallbackMock.mockResolvedValue("rename");
|
||||
const { createLocalApi } = await import("./localApi");
|
||||
|
||||
+18
-96
@@ -1,6 +1,4 @@
|
||||
import type { ContextMenuItem, LocalApi } from "@t3tools/contracts";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
|
||||
import { showContextMenuFallback } from "./contextMenuFallback";
|
||||
@@ -8,61 +6,8 @@ import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientP
|
||||
|
||||
let cachedApi: LocalApi | undefined;
|
||||
|
||||
export class LocalBackendUnavailableError extends Schema.TaggedErrorClass<LocalBackendUnavailableError>()(
|
||||
"LocalBackendUnavailableError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"open-in-editor",
|
||||
"get-config",
|
||||
"refresh-providers",
|
||||
"update-provider",
|
||||
"upsert-keybinding",
|
||||
"remove-keybinding",
|
||||
"get-settings",
|
||||
"update-settings",
|
||||
"discover-source-control",
|
||||
"get-trace-diagnostics",
|
||||
"get-process-diagnostics",
|
||||
"get-process-resource-history",
|
||||
"signal-process",
|
||||
]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Local backend operation ${this.operation} is unavailable before a backend is paired.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalExternalUrlOpenError extends Schema.TaggedErrorClass<LocalExternalUrlOpenError>()(
|
||||
"LocalExternalUrlOpenError",
|
||||
{
|
||||
urlHostname: Schema.NullOr(Schema.String),
|
||||
urlLength: Schema.Number,
|
||||
urlProtocol: Schema.NullOr(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unable to open an external URL for ${this.urlHostname ?? "an unknown host"} through the desktop bridge (${this.urlProtocol ?? "unknown protocol"}, input length ${this.urlLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalApiUnavailableError extends Schema.TaggedErrorClass<LocalApiUnavailableError>()(
|
||||
"LocalApiUnavailableError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Local API is unavailable in the server runtime.";
|
||||
}
|
||||
}
|
||||
|
||||
function describeExternalUrl(url: string) {
|
||||
const diagnostics = getUrlDiagnostics(url);
|
||||
return {
|
||||
urlHostname: diagnostics.hostname ?? null,
|
||||
urlLength: diagnostics.inputLength,
|
||||
urlProtocol: diagnostics.protocol ?? null,
|
||||
};
|
||||
function unavailableLocalBackendError(): Error {
|
||||
return new Error("Local backend API is unavailable before a backend is paired.");
|
||||
}
|
||||
|
||||
function createBrowserLocalApi(): LocalApi {
|
||||
@@ -80,21 +25,12 @@ function createBrowserLocalApi(): LocalApi {
|
||||
},
|
||||
},
|
||||
shell: {
|
||||
openInEditor: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "open-in-editor" })),
|
||||
openInEditor: () => Promise.reject(unavailableLocalBackendError()),
|
||||
openExternal: async (url) => {
|
||||
if (window.desktopBridge) {
|
||||
let opened: boolean;
|
||||
try {
|
||||
opened = await window.desktopBridge.openExternal(url);
|
||||
} catch (cause) {
|
||||
throw new LocalExternalUrlOpenError({
|
||||
...describeExternalUrl(url),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
const opened = await window.desktopBridge.openExternal(url);
|
||||
if (!opened) {
|
||||
throw new LocalExternalUrlOpenError(describeExternalUrl(url));
|
||||
throw new Error("Unable to open link.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -128,32 +64,18 @@ function createBrowserLocalApi(): LocalApi {
|
||||
},
|
||||
},
|
||||
server: {
|
||||
getConfig: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "get-config" })),
|
||||
refreshProviders: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "refresh-providers" })),
|
||||
updateProvider: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "update-provider" })),
|
||||
upsertKeybinding: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "upsert-keybinding" })),
|
||||
removeKeybinding: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "remove-keybinding" })),
|
||||
getSettings: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "get-settings" })),
|
||||
updateSettings: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "update-settings" })),
|
||||
discoverSourceControl: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "discover-source-control" })),
|
||||
getTraceDiagnostics: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "get-trace-diagnostics" })),
|
||||
getProcessDiagnostics: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "get-process-diagnostics" })),
|
||||
getProcessResourceHistory: () =>
|
||||
Promise.reject(
|
||||
new LocalBackendUnavailableError({ operation: "get-process-resource-history" }),
|
||||
),
|
||||
signalProcess: () =>
|
||||
Promise.reject(new LocalBackendUnavailableError({ operation: "signal-process" })),
|
||||
getConfig: () => Promise.reject(unavailableLocalBackendError()),
|
||||
refreshProviders: () => Promise.reject(unavailableLocalBackendError()),
|
||||
updateProvider: () => Promise.reject(unavailableLocalBackendError()),
|
||||
upsertKeybinding: () => Promise.reject(unavailableLocalBackendError()),
|
||||
removeKeybinding: () => Promise.reject(unavailableLocalBackendError()),
|
||||
getSettings: () => Promise.reject(unavailableLocalBackendError()),
|
||||
updateSettings: () => Promise.reject(unavailableLocalBackendError()),
|
||||
discoverSourceControl: () => Promise.reject(unavailableLocalBackendError()),
|
||||
getTraceDiagnostics: () => Promise.reject(unavailableLocalBackendError()),
|
||||
getProcessDiagnostics: () => Promise.reject(unavailableLocalBackendError()),
|
||||
getProcessResourceHistory: () => Promise.reject(unavailableLocalBackendError()),
|
||||
signalProcess: () => Promise.reject(unavailableLocalBackendError()),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -178,7 +100,7 @@ export function readLocalApi(): LocalApi | undefined {
|
||||
export function ensureLocalApi(): LocalApi {
|
||||
const api = readLocalApi();
|
||||
if (!api) {
|
||||
throw new LocalApiUnavailableError();
|
||||
throw new Error("Local API not found");
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
@@ -56,10 +56,6 @@ const decodeMintRequestBody = Schema.decodeUnknownSync(
|
||||
const isEnvironmentConnectNotAuthorized = Schema.is(
|
||||
EnvironmentConnector.EnvironmentConnectNotAuthorized,
|
||||
);
|
||||
const isEnvironmentMintRequestFailed = Schema.is(EnvironmentConnector.EnvironmentMintRequestFailed);
|
||||
const isEnvironmentMintResponseInvalid = Schema.is(
|
||||
EnvironmentConnector.EnvironmentMintResponseInvalid,
|
||||
);
|
||||
|
||||
function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
|
||||
return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";
|
||||
@@ -231,55 +227,6 @@ function makeLinks(
|
||||
}
|
||||
|
||||
describe("EnvironmentConnector", () => {
|
||||
it("redacts endpoint secrets while preserving mapped causes", () => {
|
||||
const httpBaseUrl =
|
||||
"https://environment-user:[email protected]/private/workspace?access_token=environment-secret#environment-fragment";
|
||||
const cause = new Error("mint failed");
|
||||
const requestError = EnvironmentConnector.EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
operation: "connect",
|
||||
stage: "send_request",
|
||||
httpBaseUrl,
|
||||
cause,
|
||||
});
|
||||
const responseError = EnvironmentConnector.EnvironmentMintResponseInvalid.fromEndpoint({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
operation: "connect",
|
||||
httpBaseUrl,
|
||||
reason: "proof_verification_failed",
|
||||
cause,
|
||||
});
|
||||
const timeoutError = EnvironmentConnector.EnvironmentMintRequestTimedOut.fromEndpoint({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
httpBaseUrl,
|
||||
timeoutMs: EnvironmentConnector.ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
for (const error of [requestError, responseError, timeoutError]) {
|
||||
expect(error).toMatchObject({
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "env.example.test",
|
||||
});
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"environment-user",
|
||||
"environment-password",
|
||||
"/private/workspace",
|
||||
"environment-secret",
|
||||
"environment-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
}
|
||||
expect(requestError.cause).toBe(cause);
|
||||
expect(responseError.cause).toBe(cause);
|
||||
});
|
||||
|
||||
it.effect("loads the environment link and managed allocation concurrently", () =>
|
||||
Effect.gen(function* () {
|
||||
const started = yield* Ref.make(0);
|
||||
@@ -397,9 +344,6 @@ describe("EnvironmentConnector", () => {
|
||||
operation: "status",
|
||||
reason: "endpoint_provider_not_managed",
|
||||
});
|
||||
expect(result.failure.message).toBe(
|
||||
"Environment 'env-connector-test' is not authorized for status (endpoint_provider_not_managed).",
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
@@ -457,57 +401,24 @@ describe("EnvironmentConnector", () => {
|
||||
const resolutionSpan = spans.find(
|
||||
(span) => span.name === "relay.environment_connector.resolve_managed_endpoint",
|
||||
);
|
||||
const resolutionAttributes = Object.fromEntries(resolutionSpan?.attributes ?? []);
|
||||
expect(resolutionAttributes).toMatchObject({
|
||||
expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({
|
||||
"relay.authorization.allocation_hostname": "env.example.test",
|
||||
"relay.authorization.allocation_has_ready_at": true,
|
||||
"relay.authorization.allocation_has_tunnel_id": true,
|
||||
"relay.authorization.allocation_has_dns_record_id": true,
|
||||
"relay.authorization.linked_http_base_url.input_length":
|
||||
"https://attacker-user:[email protected]/private/workspace?access_token=attacker-secret#attacker-fragment"
|
||||
.length,
|
||||
"relay.authorization.linked_http_base_url.protocol": "https:",
|
||||
"relay.authorization.linked_http_base_url.hostname": "attacker.example.test",
|
||||
"relay.authorization.linked_ws_base_url.input_length":
|
||||
"wss://socket-user:[email protected]/private/socket?access_token=socket-secret#socket-fragment"
|
||||
.length,
|
||||
"relay.authorization.linked_ws_base_url.protocol": "wss:",
|
||||
"relay.authorization.linked_ws_base_url.hostname": "attacker.example.test",
|
||||
"relay.authorization.resolved_http_base_url.input_length": "https://env.example.test/"
|
||||
.length,
|
||||
"relay.authorization.resolved_http_base_url.protocol": "https:",
|
||||
"relay.authorization.resolved_http_base_url.hostname": "env.example.test",
|
||||
"relay.authorization.resolved_ws_base_url.input_length": "wss://env.example.test/ws".length,
|
||||
"relay.authorization.resolved_ws_base_url.protocol": "wss:",
|
||||
"relay.authorization.resolved_ws_base_url.hostname": "env.example.test",
|
||||
"relay.authorization.linked_http_base_url": "https://attacker.example.test/",
|
||||
"relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",
|
||||
"relay.authorization.resolved_http_base_url": "https://env.example.test/",
|
||||
"relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",
|
||||
});
|
||||
const serializedAttributes = Object.entries(resolutionAttributes)
|
||||
.flatMap(([key, value]) => [key, String(value)])
|
||||
.join("\n");
|
||||
for (const secret of [
|
||||
"attacker-user",
|
||||
"attacker-password",
|
||||
"/private/workspace",
|
||||
"attacker-secret",
|
||||
"attacker-fragment",
|
||||
"socket-user",
|
||||
"socket-password",
|
||||
"/private/socket",
|
||||
"socket-secret",
|
||||
"socket-fragment",
|
||||
]) {
|
||||
expect(serializedAttributes).not.toContain(secret);
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
connectorTestLayer(execute, {
|
||||
links: makeLinks({
|
||||
endpoint: {
|
||||
httpBaseUrl:
|
||||
"https://attacker-user:[email protected]/private/workspace?access_token=attacker-secret#attacker-fragment",
|
||||
wsBaseUrl:
|
||||
"wss://socket-user:[email protected]/private/socket?access_token=socket-secret#socket-fragment",
|
||||
httpBaseUrl: "https://attacker.example.test/",
|
||||
wsBaseUrl: "wss://attacker.example.test/ws",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
},
|
||||
}),
|
||||
@@ -606,7 +517,6 @@ describe("EnvironmentConnector", () => {
|
||||
Response.json(
|
||||
{
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "answer_cloud_health_request",
|
||||
message: "Environment is unavailable.",
|
||||
},
|
||||
{ status: 500 },
|
||||
@@ -790,7 +700,7 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const connector = yield* EnvironmentConnector.EnvironmentConnector;
|
||||
const result = yield* Effect.result(
|
||||
const result = yield* Effect.exit(
|
||||
connector.connect({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
@@ -798,21 +708,9 @@ describe("EnvironmentConnector", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(isEnvironmentMintResponseInvalid(result.failure)).toBe(true);
|
||||
if (isEnvironmentMintResponseInvalid(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
operation: "connect",
|
||||
httpBaseUrlInputLength: "https://env.example.test/".length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "env.example.test",
|
||||
reason: "proof_verification_failed",
|
||||
cause: { _tag: "RelayJwtError" },
|
||||
});
|
||||
}
|
||||
expect(result._tag).toBe("Failure");
|
||||
if (result._tag === "Failure") {
|
||||
expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
|
||||
}
|
||||
}).pipe(Effect.provide(connectorTestLayer(execute)));
|
||||
});
|
||||
@@ -882,52 +780,6 @@ describe("EnvironmentConnector", () => {
|
||||
}).pipe(Effect.provide(connectorTestLayer(execute)));
|
||||
});
|
||||
|
||||
it.effect("preserves context and cause when the mint request fails", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(
|
||||
{
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
message: "Environment is unavailable.",
|
||||
},
|
||||
{ status: 500 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const connector = yield* EnvironmentConnector.EnvironmentConnector;
|
||||
const result = yield* Effect.result(
|
||||
connector.connect({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
clientProofKeyThumbprint: "client-proof-key-thumbprint",
|
||||
deviceId: "device-123",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(isEnvironmentMintRequestFailed(result.failure)).toBe(true);
|
||||
if (isEnvironmentMintRequestFailed(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
operation: "connect",
|
||||
stage: "send_request",
|
||||
httpBaseUrlInputLength: "https://env.example.test/".length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "env.example.test",
|
||||
deviceId: "device-123",
|
||||
cause: { _tag: "EnvironmentHttpInternalServerError" },
|
||||
});
|
||||
}
|
||||
}
|
||||
}).pipe(Effect.provide(connectorTestLayer(execute)));
|
||||
});
|
||||
|
||||
it.effect("times out hung managed endpoint mint requests", () => {
|
||||
let resolveRequestStarted: (() => void) | undefined;
|
||||
const requestStarted = new Promise<void>((resolve) => {
|
||||
@@ -958,11 +810,7 @@ describe("EnvironmentConnector", () => {
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure._tag).toBe("EnvironmentMintRequestTimedOut");
|
||||
expect(result.failure).toMatchObject({
|
||||
userId: "user_123",
|
||||
environmentId: "env-connector-test",
|
||||
httpBaseUrlInputLength: "https://env.example.test/".length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "env.example.test",
|
||||
timeoutMs: EnvironmentConnector.ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -58,6 +57,29 @@ export const EnvironmentConnectNotAuthorizedReason = Schema.Literals([
|
||||
export type EnvironmentConnectNotAuthorizedReason =
|
||||
typeof EnvironmentConnectNotAuthorizedReason.Type;
|
||||
|
||||
function environmentConnectNotAuthorizedReasonMessage(
|
||||
reason: EnvironmentConnectNotAuthorizedReason,
|
||||
): string {
|
||||
switch (reason) {
|
||||
case "client_proof_key_thumbprint_missing":
|
||||
return "the client proof key thumbprint is missing";
|
||||
case "environment_link_not_found":
|
||||
return "no active environment link was found";
|
||||
case "endpoint_provider_not_managed":
|
||||
return "the linked endpoint is not relay-managed";
|
||||
case "managed_endpoint_allocation_not_found":
|
||||
return "no managed endpoint allocation was found";
|
||||
case "managed_endpoint_base_domain_not_configured":
|
||||
return "the managed endpoint base domain is not configured";
|
||||
case "managed_endpoint_allocation_not_ready":
|
||||
return "the managed endpoint allocation is incomplete";
|
||||
case "managed_endpoint_hostname_invalid":
|
||||
return "the managed endpoint hostname is invalid";
|
||||
case "managed_endpoint_mismatch":
|
||||
return "the linked endpoint does not match its managed allocation";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentConnectNotAuthorized extends Schema.TaggedErrorClass<EnvironmentConnectNotAuthorized>()(
|
||||
"EnvironmentConnectNotAuthorized",
|
||||
{
|
||||
@@ -67,144 +89,44 @@ export class EnvironmentConnectNotAuthorized extends Schema.TaggedErrorClass<Env
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' is not authorized for ${this.operation} (${this.reason}).`;
|
||||
return `Environment '${this.environmentId}' is not authorized for ${this.operation}: ${environmentConnectNotAuthorizedReasonMessage(this.reason)}`;
|
||||
}
|
||||
}
|
||||
|
||||
const httpBaseUrlDiagnosticSchema = {
|
||||
httpBaseUrlInputLength: Schema.Number,
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
} as const;
|
||||
|
||||
function httpBaseUrlDiagnosticFields(httpBaseUrl: string) {
|
||||
const diagnostics = getUrlDiagnostics(httpBaseUrl);
|
||||
return {
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function urlDiagnosticSpanAttributes(prefix: string, input: string) {
|
||||
const diagnostics = getUrlDiagnostics(input);
|
||||
return {
|
||||
[`${prefix}.input_length`]: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { [`${prefix}.protocol`]: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { [`${prefix}.hostname`]: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class EnvironmentMintRequestFailed extends Schema.TaggedErrorClass<EnvironmentMintRequestFailed>()(
|
||||
"EnvironmentMintRequestFailed",
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
operation: Schema.Literals(["connect", "status"]),
|
||||
stage: Schema.Literals(["generate_nonce", "generate_request_id", "sign_proof", "send_request"]),
|
||||
...httpBaseUrlDiagnosticSchema,
|
||||
deviceId: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromEndpoint(input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly operation: "connect" | "status";
|
||||
readonly stage: "generate_nonce" | "generate_request_id" | "sign_proof" | "send_request";
|
||||
readonly httpBaseUrl: string;
|
||||
readonly deviceId?: string;
|
||||
readonly cause: unknown;
|
||||
}): EnvironmentMintRequestFailed {
|
||||
const { httpBaseUrl, ...context } = input;
|
||||
return new EnvironmentMintRequestFailed({
|
||||
...context,
|
||||
...httpBaseUrlDiagnosticFields(httpBaseUrl),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' ${this.operation} request failed during ${this.stage}`;
|
||||
return `Environment '${this.environmentId}' ${this.operation} request failed`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentMintRequestTimedOut extends Schema.TaggedErrorClass<EnvironmentMintRequestTimedOut>()(
|
||||
"EnvironmentMintRequestTimedOut",
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
...httpBaseUrlDiagnosticSchema,
|
||||
deviceId: Schema.optional(Schema.String),
|
||||
timeoutMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
static fromEndpoint(input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
readonly deviceId?: string;
|
||||
readonly timeoutMs: number;
|
||||
}): EnvironmentMintRequestTimedOut {
|
||||
const { httpBaseUrl, ...context } = input;
|
||||
return new EnvironmentMintRequestTimedOut({
|
||||
...context,
|
||||
...httpBaseUrlDiagnosticFields(httpBaseUrl),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' mint request timed out after ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
|
||||
export const EnvironmentMintResponseInvalidReason = Schema.Literals([
|
||||
"environment_public_key_missing",
|
||||
"proof_verification_failed",
|
||||
"response_environment_id_mismatch",
|
||||
"proof_environment_id_mismatch",
|
||||
"request_nonce_mismatch",
|
||||
"client_proof_key_thumbprint_mismatch",
|
||||
"credential_mismatch",
|
||||
"expires_at_invalid",
|
||||
"expires_at_mismatch",
|
||||
"status_mismatch",
|
||||
"checked_at_invalid",
|
||||
"checked_at_mismatch",
|
||||
"descriptor_mismatch",
|
||||
"checked_at_out_of_range",
|
||||
]);
|
||||
export type EnvironmentMintResponseInvalidReason = typeof EnvironmentMintResponseInvalidReason.Type;
|
||||
|
||||
export class EnvironmentMintResponseInvalid extends Schema.TaggedErrorClass<EnvironmentMintResponseInvalid>()(
|
||||
"EnvironmentMintResponseInvalid",
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
operation: Schema.Literals(["connect", "status"]),
|
||||
...httpBaseUrlDiagnosticSchema,
|
||||
deviceId: Schema.optional(Schema.String),
|
||||
reason: EnvironmentMintResponseInvalidReason,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
static fromEndpoint(input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly operation: "connect" | "status";
|
||||
readonly httpBaseUrl: string;
|
||||
readonly deviceId?: string;
|
||||
readonly reason: EnvironmentMintResponseInvalidReason;
|
||||
readonly cause?: unknown;
|
||||
}): EnvironmentMintResponseInvalid {
|
||||
const { httpBaseUrl, ...context } = input;
|
||||
return new EnvironmentMintResponseInvalid({
|
||||
...context,
|
||||
...httpBaseUrlDiagnosticFields(httpBaseUrl),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' returned an invalid ${this.operation} response (${this.reason})`;
|
||||
return `Environment '${this.environmentId}' returned an invalid ${this.operation} response`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,24 +210,17 @@ const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A, E>(input: {
|
||||
readonly decodePayload: (input: unknown) => Effect.Effect<A, E>;
|
||||
}) {
|
||||
const { decodePayload, ...rest } = input;
|
||||
let lastFailure: { readonly cause: unknown } | undefined;
|
||||
for (const publicKey of input.environmentPublicKeys) {
|
||||
const result = yield* verifyRelayJwt({ ...rest, publicKey }).pipe(
|
||||
const proof = yield* verifyRelayJwt({ ...rest, publicKey }).pipe(
|
||||
Effect.flatMap(decodePayload),
|
||||
Effect.match({
|
||||
onFailure: (cause) => ({ _tag: "Failure" as const, cause }),
|
||||
onSuccess: (proof) => ({ _tag: "Success" as const, proof }),
|
||||
}),
|
||||
Effect.option,
|
||||
);
|
||||
if (result._tag === "Success") {
|
||||
return result;
|
||||
if (Option.isSome(proof)) {
|
||||
return proof.value;
|
||||
}
|
||||
lastFailure = result;
|
||||
// A linked environment can have rotated keys; try the remaining active keys.
|
||||
}
|
||||
return lastFailure
|
||||
? { _tag: "Failure" as const, cause: lastFailure.cause }
|
||||
: { _tag: "MissingPublicKey" as const };
|
||||
return null;
|
||||
});
|
||||
|
||||
function verifyEnvironmentResponse(input: {
|
||||
@@ -326,35 +241,18 @@ function verifyEnvironmentResponse(input: {
|
||||
environmentPublicKeys: input.environmentPublicKeys,
|
||||
decodePayload: decodeMintResponseProof,
|
||||
}).pipe(
|
||||
Effect.map((verification) => {
|
||||
if (verification._tag === "MissingPublicKey") {
|
||||
return { reason: "environment_public_key_missing" as const };
|
||||
}
|
||||
if (verification._tag === "Failure") {
|
||||
return { reason: "proof_verification_failed" as const, cause: verification.cause };
|
||||
}
|
||||
const proof = verification.proof;
|
||||
if (proof.environmentId !== input.environmentId) {
|
||||
return { reason: "proof_environment_id_mismatch" as const };
|
||||
}
|
||||
if (proof.requestNonce !== input.requestNonce) {
|
||||
return { reason: "request_nonce_mismatch" as const };
|
||||
}
|
||||
if (proof.clientProofKeyThumbprint !== input.clientProofKeyThumbprint) {
|
||||
return { reason: "client_proof_key_thumbprint_mismatch" as const };
|
||||
}
|
||||
if (proof.credential !== input.response.credential) {
|
||||
return { reason: "credential_mismatch" as const };
|
||||
}
|
||||
const expiresAt = DateTime.make(input.response.expiresAt);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return { reason: "expires_at_invalid" as const };
|
||||
}
|
||||
if (Math.floor(expiresAt.value.epochMilliseconds / 1_000) !== proof.exp) {
|
||||
return { reason: "expires_at_mismatch" as const };
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
Effect.map(
|
||||
(proof) =>
|
||||
proof !== null &&
|
||||
proof.environmentId === input.environmentId &&
|
||||
proof.requestNonce === input.requestNonce &&
|
||||
proof.clientProofKeyThumbprint === input.clientProofKeyThumbprint &&
|
||||
proof.credential === input.response.credential &&
|
||||
Option.match(DateTime.make(input.response.expiresAt), {
|
||||
onNone: () => false,
|
||||
onSome: (expiresAt) => Math.floor(expiresAt.epochMilliseconds / 1_000) === proof.exp,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -376,45 +274,28 @@ function verifyEnvironmentHealthResponse(input: {
|
||||
environmentPublicKeys: input.environmentPublicKeys,
|
||||
decodePayload: decodeHealthResponseProof,
|
||||
}).pipe(
|
||||
Effect.map((verification) => {
|
||||
if (verification._tag === "MissingPublicKey") {
|
||||
return { reason: "environment_public_key_missing" as const };
|
||||
}
|
||||
if (verification._tag === "Failure") {
|
||||
return { reason: "proof_verification_failed" as const, cause: verification.cause };
|
||||
}
|
||||
const proof = verification.proof;
|
||||
if (input.response.environmentId !== input.environmentId) {
|
||||
return { reason: "response_environment_id_mismatch" as const };
|
||||
}
|
||||
if (proof.environmentId !== input.environmentId) {
|
||||
return { reason: "proof_environment_id_mismatch" as const };
|
||||
}
|
||||
if (proof.requestNonce !== input.requestNonce) {
|
||||
return { reason: "request_nonce_mismatch" as const };
|
||||
}
|
||||
if (proof.status !== input.response.status) {
|
||||
return { reason: "status_mismatch" as const };
|
||||
}
|
||||
if (proof.checkedAt !== input.response.checkedAt) {
|
||||
return { reason: "checked_at_mismatch" as const };
|
||||
}
|
||||
if (stableStringify(proof.descriptor) !== stableStringify(input.response.descriptor)) {
|
||||
return { reason: "descriptor_mismatch" as const };
|
||||
Effect.map((proof) => {
|
||||
if (
|
||||
proof === null ||
|
||||
input.response.environmentId !== input.environmentId ||
|
||||
proof.environmentId !== input.environmentId ||
|
||||
proof.requestNonce !== input.requestNonce ||
|
||||
proof.status !== input.response.status ||
|
||||
proof.checkedAt !== input.response.checkedAt ||
|
||||
stableStringify(proof.descriptor) !== stableStringify(input.response.descriptor)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const checkedAt = DateTime.make(input.response.checkedAt);
|
||||
if (Option.isNone(checkedAt)) {
|
||||
return { reason: "checked_at_invalid" as const };
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
checkedAt.value.epochMilliseconds <
|
||||
input.requestIssuedAt.epochMilliseconds - ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS ||
|
||||
checkedAt.value.epochMilliseconds >
|
||||
return (
|
||||
checkedAt.value.epochMilliseconds >=
|
||||
input.requestIssuedAt.epochMilliseconds - ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS &&
|
||||
checkedAt.value.epochMilliseconds <=
|
||||
input.now.epochMilliseconds + ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS
|
||||
) {
|
||||
return { reason: "checked_at_out_of_range" as const };
|
||||
}
|
||||
return null;
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -503,24 +384,12 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
...allocationAttributes,
|
||||
...urlDiagnosticSpanAttributes(
|
||||
"relay.authorization.linked_http_base_url",
|
||||
input.link.endpoint.httpBaseUrl,
|
||||
),
|
||||
...urlDiagnosticSpanAttributes(
|
||||
"relay.authorization.linked_ws_base_url",
|
||||
input.link.endpoint.wsBaseUrl,
|
||||
),
|
||||
"relay.authorization.linked_http_base_url": input.link.endpoint.httpBaseUrl,
|
||||
"relay.authorization.linked_ws_base_url": input.link.endpoint.wsBaseUrl,
|
||||
...(endpoint
|
||||
? {
|
||||
...urlDiagnosticSpanAttributes(
|
||||
"relay.authorization.resolved_http_base_url",
|
||||
endpoint.httpBaseUrl,
|
||||
),
|
||||
...urlDiagnosticSpanAttributes(
|
||||
"relay.authorization.resolved_ws_base_url",
|
||||
endpoint.wsBaseUrl,
|
||||
),
|
||||
"relay.authorization.resolved_http_base_url": endpoint.httpBaseUrl,
|
||||
"relay.authorization.resolved_ws_base_url": endpoint.wsBaseUrl,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
@@ -562,15 +431,13 @@ const make = Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
stage: "generate_nonce",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = {
|
||||
@@ -578,15 +445,13 @@ const make = Effect.gen(function* () {
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
stage: "generate_request_id",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
@@ -600,15 +465,13 @@ const make = Effect.gen(function* () {
|
||||
typ: RELAY_HEALTH_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
stage: "sign_proof",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const checkedAt = DateTime.formatIso(now);
|
||||
@@ -629,7 +492,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
yield* Effect.logWarning("Managed endpoint health request timed out", {
|
||||
environmentId: link.environmentId,
|
||||
...httpBaseUrlDiagnosticFields(endpoint.httpBaseUrl),
|
||||
endpoint: endpoint.httpBaseUrl,
|
||||
traceId,
|
||||
});
|
||||
return {
|
||||
@@ -650,7 +513,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
yield* Effect.logWarning("Managed endpoint health request failed", {
|
||||
environmentId: link.environmentId,
|
||||
...httpBaseUrlDiagnosticFields(endpoint.httpBaseUrl),
|
||||
endpoint: endpoint.httpBaseUrl,
|
||||
failureReason,
|
||||
traceId,
|
||||
});
|
||||
@@ -664,7 +527,7 @@ const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
const decoded = responseOption.value.response;
|
||||
const invalidResponse = yield* verifyEnvironmentHealthResponse({
|
||||
const verified = yield* verifyEnvironmentHealthResponse({
|
||||
response: decoded,
|
||||
environmentId: input.environmentId,
|
||||
requestNonce: nonce,
|
||||
@@ -673,14 +536,10 @@ const make = Effect.gen(function* () {
|
||||
relayIssuer,
|
||||
now: yield* DateTime.now,
|
||||
});
|
||||
if (invalidResponse) {
|
||||
return yield* EnvironmentMintResponseInvalid.fromEndpoint({
|
||||
userId: input.userId,
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
reason: invalidResponse.reason,
|
||||
...(invalidResponse.cause !== undefined ? { cause: invalidResponse.cause } : {}),
|
||||
});
|
||||
}
|
||||
return {
|
||||
@@ -727,16 +586,13 @@ const make = Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
stage: "generate_nonce",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = {
|
||||
@@ -744,16 +600,13 @@ const make = Effect.gen(function* () {
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
stage: "generate_request_id",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
@@ -770,16 +623,13 @@ const make = Effect.gen(function* () {
|
||||
typ: RELAY_MINT_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
stage: "sign_proof",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
|
||||
@@ -787,27 +637,21 @@ const make = Effect.gen(function* () {
|
||||
.t3MintCredential({ payload: { proof } })
|
||||
.pipe(
|
||||
withoutRedirects,
|
||||
Effect.mapError((cause) =>
|
||||
EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
stage: "send_request",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
EnvironmentMintRequestTimedOut.fromEndpoint({
|
||||
userId: input.userId,
|
||||
new EnvironmentMintRequestTimedOut({
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
),
|
||||
@@ -815,7 +659,7 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const invalidResponse = yield* verifyEnvironmentResponse({
|
||||
const verified = yield* verifyEnvironmentResponse({
|
||||
response: decoded,
|
||||
environmentId: input.environmentId,
|
||||
requestNonce: nonce,
|
||||
@@ -824,15 +668,10 @@ const make = Effect.gen(function* () {
|
||||
relayIssuer,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
if (invalidResponse) {
|
||||
return yield* EnvironmentMintResponseInvalid.fromEndpoint({
|
||||
userId: input.userId,
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
httpBaseUrl: endpoint.httpBaseUrl,
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
reason: invalidResponse.reason,
|
||||
...(invalidResponse.cause !== undefined ? { cause: invalidResponse.cause } : {}),
|
||||
});
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -391,9 +391,7 @@ describe("remote environment authorization", () => {
|
||||
|
||||
expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
|
||||
expect(error.message).toBe(
|
||||
`Remote environment endpoint at host remote.example.com (${
|
||||
"http://remote.example.com/.well-known/t3/environment".length
|
||||
} URL characters) timed out after 25ms.`,
|
||||
"Remote environment endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
|
||||
);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
@@ -448,9 +446,7 @@ describe("remote environment authorization", () => {
|
||||
|
||||
expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);
|
||||
expect(error.message).toBe(
|
||||
`Remote environment endpoint at host remote.example.com (${
|
||||
"https://remote.example.com/oauth/token".length
|
||||
} URL characters) returned an invalid response.`,
|
||||
"Remote environment endpoint returned an invalid response from https://remote.example.com/oauth/token.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
} from "../rpc/http.ts";
|
||||
|
||||
export {
|
||||
isRemoteEnvironmentAuthUndeclaredStatusError,
|
||||
RemoteEnvironmentAuthFetchError,
|
||||
RemoteEnvironmentAuthInvalidJsonError,
|
||||
RemoteEnvironmentAuthTimeoutError,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
resolveRemoteDpopWebSocketConnectionUrl,
|
||||
resolveRemoteWebSocketConnectionUrl,
|
||||
} from "./remote.ts";
|
||||
import { mapRemoteEnvironmentError } from "../connection/errors.ts";
|
||||
import { environmentMismatchError, mapRemoteEnvironmentError } from "../connection/errors.ts";
|
||||
import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
|
||||
import { environmentEndpointUrl } from "../environment/endpoint.ts";
|
||||
@@ -112,11 +112,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
);
|
||||
if (descriptor.environmentId !== input.expectedEnvironmentId) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: `Connected environment ${descriptor.environmentId} does not match ${input.expectedEnvironmentId}.`,
|
||||
expectedEnvironmentId: input.expectedEnvironmentId,
|
||||
actualEnvironmentId: descriptor.environmentId,
|
||||
return yield* environmentMismatchError({
|
||||
expected: input.expectedEnvironmentId,
|
||||
actual: descriptor.environmentId,
|
||||
});
|
||||
}
|
||||
const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
|
||||
@@ -150,11 +148,10 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
() =>
|
||||
new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: "Could not create the websocket authorization proof.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -178,11 +175,10 @@ export const make = Effect.gen(function* () {
|
||||
}) {
|
||||
const thumbprint = yield* signer.thumbprint.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
() =>
|
||||
new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: "Could not load the environment authorization key.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("environment.authorization.dpopKey.resolve"),
|
||||
@@ -240,11 +236,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("environment.authorization.descriptor"),
|
||||
);
|
||||
if (descriptor.environmentId !== input.expectedEnvironmentId) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: `Connected environment ${descriptor.environmentId} does not match ${input.expectedEnvironmentId}.`,
|
||||
expectedEnvironmentId: input.expectedEnvironmentId,
|
||||
actualEnvironmentId: descriptor.environmentId,
|
||||
return yield* environmentMismatchError({
|
||||
expected: input.expectedEnvironmentId,
|
||||
actual: descriptor.environmentId,
|
||||
});
|
||||
}
|
||||
const bootstrapProof = yield* signer
|
||||
@@ -254,11 +248,10 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
() =>
|
||||
new ConnectionBlockedError({
|
||||
reason: "configuration",
|
||||
detail: "Could not create the environment authorization proof.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { mapRemoteEnvironmentError } from "./errors.ts";
|
||||
import {
|
||||
RemoteEnvironmentAuthFetchError,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
} from "../rpc/http.ts";
|
||||
|
||||
describe("connection error mapping", () => {
|
||||
it("keeps transport diagnostics structured and redacted", () => {
|
||||
const transportCause = new Error("sensitive transport implementation detail");
|
||||
const requestUrl =
|
||||
"https://environment-user:[email protected]/private/session?access_token=environment-secret#environment-fragment";
|
||||
const source = RemoteEnvironmentAuthFetchError.fromRequestUrl(requestUrl, transportCause);
|
||||
|
||||
const error = mapRemoteEnvironmentError(source);
|
||||
|
||||
expect(source.message).toBe(
|
||||
`Failed to fetch remote environment endpoint at host environment.example.test (${requestUrl.length} URL characters).`,
|
||||
);
|
||||
expect(source.message).not.toContain(transportCause.message);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ConnectionTransientError",
|
||||
reason: "network",
|
||||
});
|
||||
expect(source).toMatchObject({
|
||||
requestUrlInputLength: requestUrl.length,
|
||||
requestUrlProtocol: "https:",
|
||||
requestUrlHostname: "environment.example.test",
|
||||
});
|
||||
const diagnostics = JSON.stringify(source);
|
||||
for (const secret of [
|
||||
"environment-user",
|
||||
"environment-password",
|
||||
"/private/session",
|
||||
"environment-secret",
|
||||
"environment-fragment",
|
||||
]) {
|
||||
expect(diagnostics).not.toContain(secret);
|
||||
expect(source.message).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps undeclared status diagnostics structured and redacted", () => {
|
||||
const cause = new Error("upstream response metadata");
|
||||
const requestUrl =
|
||||
"https://environment-user:[email protected]/private/session?access_token=environment-secret#environment-fragment";
|
||||
const error = RemoteEnvironmentAuthUndeclaredStatusError.fromRequestUrl(requestUrl, 502, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
status: 502,
|
||||
requestUrlInputLength: requestUrl.length,
|
||||
requestUrlProtocol: "https:",
|
||||
requestUrlHostname: "environment.example.test",
|
||||
});
|
||||
expect(error).not.toHaveProperty("requestUrl");
|
||||
});
|
||||
});
|
||||
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user