Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions apps/server/src/isolatedApprovalHttp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { AuthSessionId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient, HttpRouter } from "effect/http";
import { expect, it, vi } from "vite-plus/test";

import { EnvironmentAuth } from "./auth/EnvironmentAuth.ts";
import { layer } from "./isolatedApprovalHttp.ts";

it("forwards only explicit approvals from the configured authenticated operator", async () => {
vi.stubEnv("T3CODE_ISOLATED_APPROVAL_PORT", "45678");
vi.stubEnv("T3CODE_ISOLATED_APPROVAL_TOKEN", "sidecar-test-token");
vi.stubEnv("T3CODE_ISOLATED_APPROVAL_SUBJECT", "operator");
let subject = "different-account";
const upstream = vi
.spyOn(globalThis, "fetch")
.mockImplementation(async () =>
Response.json({ runId: "existing-run", revision: "a".repeat(64) }),
);
const { handler, dispose } = HttpRouter.toWebHandler(
layer.pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(
Layer.mock(EnvironmentAuth)({
authenticateHttpRequest: () =>
Effect.succeed({
sessionId: AuthSessionId.make("fixture-session"),
subject,
method: "bearer-access-token",
scopes: ["orchestration:operate"],
}),
}),
),
),
{ disableLogger: true },
);
try {
const send = (body: string, auth?: string, cookie?: string, action = "approve") =>
handler(
new Request(`http://localhost/api/isolated-approval/v1/${action}`, {
method: "POST",
headers: {
"content-type": "application/json",
"content-length": String(body.length),
...(auth ? { authorization: auth } : {}),
...(cookie ? { cookie } : {}),
},
body,
}),
);
const body = JSON.stringify({ ticket: "fixture", revision: "a".repeat(64) });
expect((await send(body)).status).toBe(401);
expect((await send(body, "Bearer t3-session")).status).toBe(403);
subject = "operator";
expect((await send(body, "Bearer t3-session", "session=fixture")).status).toBe(401);
expect((await send("{}", "Bearer t3-session")).status).toBe(400);
expect(upstream).not.toHaveBeenCalled();
expect((await send(body, "Bearer t3-session")).status).toBe(200);
const [url, forwarded] = upstream.mock.calls[0] ?? [];
expect(String(url)).toBe("http://127.0.0.1:45678/isolated-approval/v1/approve");
expect(forwarded?.redirect).toBe("error");
expect(new Headers(forwarded?.headers).get("authorization")).toBe("Bearer sidecar-test-token");
expect(forwarded?.body).toBeInstanceOf(Uint8Array);
expect(new TextDecoder().decode(forwarded?.body as Uint8Array<ArrayBuffer>)).toBe(body);
const draft = JSON.stringify({ ticket: "fixture", scope: "Update fixture" });
expect((await send(draft, "Bearer t3-session", undefined, "prepare")).status).toBe(200);
const [prepareUrl, prepared] = upstream.mock.calls[1] ?? [];
expect(String(prepareUrl)).toBe("http://127.0.0.1:45678/isolated-approval/v1/prepare");
expect(new TextDecoder().decode(prepared?.body as Uint8Array<ArrayBuffer>)).toBe(draft);
} finally {
await dispose();
upstream.mockRestore();
vi.unstubAllEnvs();
}
});
111 changes: 111 additions & 0 deletions apps/server/src/isolatedApprovalHttp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/** Isolated operator-only access to the loopback brief approval service. */
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 {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpRouter,
HttpServerRequest,
HttpServerResponse,
} from "effect/http";

import { EnvironmentAuth } from "./auth/EnvironmentAuth.ts";

const ticket = Schema.String.check(Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}$/));
const prepareBody = Schema.Struct({
ticket,
scope: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(4000)),
});
const reviewBody = Schema.Struct({ ticket });
const approveBody = Schema.Struct({
ticket,
revision: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)),
});

function isolatedConfig() {
return {
port: Number(process.env.T3CODE_ISOLATED_APPROVAL_PORT),
token: process.env.T3CODE_ISOLATED_APPROVAL_TOKEN,
operator: process.env.T3CODE_ISOLATED_APPROVAL_SUBJECT,
};
}

const bodies = { prepare: prepareBody, review: reviewBody, approve: approveBody };

const route = (action: keyof typeof bodies) =>
HttpRouter.add(
"POST",
`/api/isolated-approval/v1/${action}`,
Effect.gen(function* () {
const { port, token, operator } = isolatedConfig();
if (!Number.isInteger(port) || port < 1 || port > 65535 || !token || !operator) {
return HttpServerResponse.empty({ status: 404 });
}

const request = yield* HttpServerRequest.HttpServerRequest;
if (
request.headers.cookie !== undefined ||
!/^Bearer \S+$/i.test(request.headers.authorization ?? "")
) {
return HttpServerResponse.empty({ status: 401 });
}
const auth = yield* EnvironmentAuth;
const session = yield* auth.authenticateHttpRequest(request).pipe(Effect.option);
if (Option.isNone(session)) {
return HttpServerResponse.empty({ status: 401 });
}
if (
session.value.subject !== operator ||
!session.value.scopes.includes("orchestration:operate")
) {
return HttpServerResponse.empty({ status: 403 });
}

const length = Number(request.headers["content-length"]);
if (
!Number.isInteger(length) ||
length < 1 ||
length > 8192 ||
request.headers["content-encoding"] !== undefined ||
request.headers["content-type"]?.split(";")[0]?.trim().toLowerCase() !== "application/json"
) {
return HttpServerResponse.empty({ status: 400 });
}
const body = yield* request.json.pipe(Effect.option);
if (Option.isNone(body)) {
return HttpServerResponse.empty({ status: 400 });
}
const schema = bodies[action];
const input = Schema.decodeUnknownOption(schema)(body.value);
if (Option.isNone(input)) {
return HttpServerResponse.empty({ status: 400 });
}
const client = yield* HttpClient.HttpClient;
const response = yield* HttpClientRequest.post(
`http://127.0.0.1:${port}/isolated-approval/v1/${action}`,
).pipe(
HttpClientRequest.setHeader("authorization", `Bearer ${token}`),
HttpClientRequest.bodyJson(input.value),
Effect.flatMap((outbound) => client.execute(outbound)),
Effect.flatMap((result) =>
Effect.map(result.text, (body) => ({ status: result.status, body })),
),
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
Effect.timeout("15 seconds"),
Effect.option,
);
if (Option.isNone(response) || ![200, 400, 404, 409].includes(response.value.status)) {
return HttpServerResponse.empty({ status: 502, headers: { "cache-control": "no-store" } });
}
return HttpServerResponse.text(response.value.body, {
status: response.value.status,
contentType: "application/json",
headers: { "cache-control": "no-store" },
});
}),
);

export const layer = Layer.mergeAll(route("prepare"), route("review"), route("approve"));
2 changes: 2 additions & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts";
import * as KeepAwake from "./background/KeepAwake.ts";
import * as ServerConfig from "./config.ts";
import { withUntracedRequests } from "./http.ts";
import * as IsolatedApprovalHttp from "./isolatedApprovalHttp.ts";
import * as ServerHttp from "./http.ts";
import {
guardHttpResponseWriteErrors,
Expand Down Expand Up @@ -837,6 +838,7 @@ const layerMakeRoutes = Layer.mergeAll(
Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))),
Layer.provide(AuthHttp.layerAuthenticatedAuth),
),
IsolatedApprovalHttp.layer,
ServerHttp.layerOtlpTracesProxyRoute,
ServerHttp.layerAssetRoute,
ServerHttp.layerAttachmentUploadRoute,
Expand Down
21 changes: 18 additions & 3 deletions apps/web/src/components/chat/ChatHeader.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { userEvent } from "vite-plus/test/browser";

const persisted = vi.hoisted(() => ({ title: "" }));
const openMenu = vi.hoisted(() => vi.fn());
vi.mock(import("../../state/environments"), async (importOriginal) => ({
...(await importOriginal()),
usePrimaryEnvironmentId: () => EnvironmentId.make("local-backend-generated-id"),
}));

vi.mock(import("../../state/session"), async (importOriginal) => ({
...(await importOriginal()),
useEnvironmentScope: () => true,
Expand All @@ -24,14 +29,14 @@ vi.mock(import("~/hooks/useThreadActionMenu"), () => ({
import { render, stubGlobal } from "../../../test/render";
import { ChatHeader } from "./ChatHeader";

function header(title: string) {
function header(title: string, environment = "environment", isServerThread = true) {
return (
<>
<ChatHeader
activeThreadEnvironmentId={EnvironmentId.make("environment")}
activeThreadEnvironmentId={EnvironmentId.make(environment)}
activeThreadId={ThreadId.make("thread")}
activeThreadTitle={title}
isServerThread
isServerThread={isServerThread}
activeProject={null}
parentThreadLink={null}
onOpenThread={() => {}}
Expand Down Expand Up @@ -103,3 +108,13 @@ it("keeps the Escape that cancels a rename from also reaching window shortcuts",
expect(persisted.title).toBe("New thread");
expect(windowEscapes).toEqual([true]);
});

it("offers isolated brief review on a draft in the resolved primary desktop environment", async () => {
using _bridge = stubGlobal("desktopBridge", {});
await using screen = await render(header("New thread", "local-backend-generated-id", false));
const review = screen.getByRole("button", { name: "Review isolated brief" });
await expect.element(review).toBeVisible();

await screen.rerender(header("Other thread", "linked-environment", false));
await expect.element(review).not.toBeInTheDocument();
});
7 changes: 7 additions & 0 deletions apps/web/src/components/chat/ChatHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { toastManager } from "../ui/toast";
import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
import { readLocalApi } from "~/localApi";
import { threadEnvironment } from "../../state/threads";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { canShareWithGuestAtom } from "./guestShareAvailability";
import { useAtomValue } from "@effect/atom-react";
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
Expand All @@ -43,6 +44,7 @@ import { cn } from "~/lib/utils";
import { textDirection } from "~/textDirection";
import { useClientSettings } from "../../hooks/useSettings";
import { GuestShareIndicator } from "./GuestShareControls";
import { IsolatedBriefDialog } from "./IsolatedBriefDialog";

interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
Expand Down Expand Up @@ -88,6 +90,7 @@ export const ChatHeader = memo(function ChatHeader({
const interfaceFont = useClientSettings((settings) => settings.fontFamilySans);
const breadcrumbContainerRef = useRef<HTMLDivElement>(null);
const [collapseParentTitle, setCollapseParentTitle] = useState(false);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const activeThreadRef = scopeThreadRef(activeThreadEnvironmentId, activeThreadId);
const canOperateThread = useEnvironmentScope(
activeThreadEnvironmentId,
Expand Down Expand Up @@ -398,6 +401,10 @@ export const ChatHeader = memo(function ChatHeader({
) : null}
</WorkspaceBreadcrumbItem>
</WorkspaceBreadcrumb>
{canOperateThread &&
activeThreadEnvironmentId === primaryEnvironmentId &&
typeof window !== "undefined" &&
window.desktopBridge && <IsolatedBriefDialog key={activeThreadId} />}
{isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
</div>
);
Expand Down
78 changes: 78 additions & 0 deletions apps/web/src/components/chat/IsolatedBriefDialog.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import "~/index.css";
import { expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";
import { render, stubGlobal } from "../../../test/render";
import { IsolatedBriefDialog } from "./IsolatedBriefDialog";

vi.mock(import("~/environments/primary/desktopAuth"), () => ({
readDesktopPrimaryBearerToken: async () => "fixture-session",
}));
vi.mock(import("~/environments/primary/target"), () => ({
resolvePrimaryEnvironmentHttpUrl: (pathname: string) => `http://127.0.0.1:3210${pathname}`,
}));

it.each(["review", "prepare"] as const)(
"requires explicit approval after %s and can recover a missing receipt",
async (action) => {
const revision = "a".repeat(64);
const baseSha = "b".repeat(40);
const runId = "a16fdb25-00e8-4061-97c2-14cd6e10c27b";
const fetchApproval = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json({
ticket: "fixture",
revision,
brief: {
repository: "lab/fixture",
workspaceId: "isolated",
scope: "Update the clamp fixture",
baseSha,
tokens: 1000,
nativeStages: {
lead: {
projectId: "fixture-project",
message: "Review the clamp brief",
tokens: 100,
modelSelection: { instanceId: "codex-lab", model: "codex-fixture" },
},
},
},
}),
)
.mockRejectedValueOnce(new Error("Reply lost"))
.mockResolvedValueOnce(Response.json({ runId, revision }));
using _fetch = stubGlobal("fetch", fetchApproval);
await using screen = await render(<IsolatedBriefDialog />);
await screen.getByRole("button", { name: "Review isolated brief" }).click();
const dialog = page.getByRole("dialog");
const approve = dialog.getByRole("button", { name: "Approve isolated run" });
await expect.element(approve).not.toBeInTheDocument();
await dialog.getByRole("textbox", { name: "Ticket", exact: true }).fill("fixture");
if (action === "prepare") {
await dialog.getByRole("textbox", { name: "Task scope" }).fill("Update the clamp fixture");
}
await dialog
.getByRole("button", {
name: action === "prepare" ? "Prepare draft" : "Review existing draft",
exact: true,
})
.click();
await expect.element(dialog.getByText(`Base commit ${baseSha}`)).toBeVisible();
await expect.element(dialog.getByText("lead · codex-lab · codex-fixture")).toBeVisible();
expect(fetchApproval).toHaveBeenCalledTimes(1);
expect(fetchApproval.mock.calls[0]?.[0]).toMatch(new RegExp(`/${action}$`));
await approve.click();
await expect.element(dialog.getByRole("alert")).toHaveTextContent("Reply lost");
await approve.click();
await expect
.element(dialog.getByRole("link", { name: "Open run in Delivery" }))
.toHaveAttribute("href", `/delivery?run=${runId}`);
const approvalCalls = fetchApproval.mock.calls.slice(1);
expect(approvalCalls).toHaveLength(2);
expect(approvalCalls[0]).toEqual(approvalCalls[1]);
expect(approvalCalls[0]?.[0]).toMatch(/\/approve$/);
expect(approvalCalls[0]?.[1]?.body).toBe(JSON.stringify({ ticket: "fixture", revision }));
expect(approvalCalls[0]?.[1]?.credentials).toBe("omit");
},
);
Loading
Loading