Skip to content

Commit 862e48b

Browse files
Refactor primary HTTP layer and update auth tests
- Export a factory for the primary HTTP layer - Update tests to use the new layer and mocked auth service calls - Tighten browser settings coverage around pairing and revoke flows
1 parent 2db071d commit 862e48b

5 files changed

Lines changed: 161 additions & 198 deletions

File tree

‎apps/web/src/authBootstrap.test.ts‎

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import {
2-
AuthSessionState as AuthSessionStateSchema,
32
EnvironmentAuthInvalidError,
43
type AuthBrowserSessionResult,
54
type AuthCreatePairingCredentialInput,
@@ -8,10 +7,11 @@ import {
87
} from "@t3tools/contracts";
98
import * as DateTime from "effect/DateTime";
109
import * as Effect from "effect/Effect";
11-
import * as Schema from "effect/Schema";
10+
import { HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
1211
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1312

1413
import { installEnvironmentHttpTest } from "../test/environmentHttpTest";
14+
import { __setPrimaryHttpRunnerForTests, type PrimaryHttpEffectRunner } from "./lib/runtime";
1515

1616
type TestWindow = {
1717
location: URL;
@@ -36,8 +36,6 @@ const DESKTOP_AUTH = {
3636
} as const;
3737

3838
const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");
39-
const encodeAuthSessionState = Schema.encodeSync(AuthSessionStateSchema);
40-
4139
const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
4240
authenticated: false,
4341
auth,
@@ -117,6 +115,7 @@ describe("resolveInitialServerAuthGateState", () => {
117115
disposeHttpTest = undefined;
118116
const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
119117
__resetServerAuthBootstrapForTests();
118+
__setPrimaryHttpRunnerForTests();
120119
vi.unstubAllEnvs();
121120
vi.useRealTimers();
122121
vi.restoreAllMocks();
@@ -220,18 +219,22 @@ describe("resolveInitialServerAuthGateState", () => {
220219

221220
it("retries transient auth session bootstrap failures after restart", async () => {
222221
vi.useFakeTimers();
223-
const fetchMock = vi
224-
.fn<typeof fetch>()
225-
.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
226-
.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
227-
.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
228-
.mockResolvedValueOnce(
229-
new Response(
230-
JSON.stringify(encodeAuthSessionState(unauthenticatedSession(LOOPBACK_AUTH))),
231-
{ status: 200, headers: { "content-type": "application/json" } },
232-
),
233-
);
234-
vi.stubGlobal("fetch", fetchMock);
222+
let attempts = 0;
223+
const request = HttpClientRequest.get("http://localhost/api/auth/session");
224+
const response = HttpClientResponse.fromWeb(
225+
request,
226+
new Response("Bad Gateway", { status: 502 }),
227+
);
228+
const runner: PrimaryHttpEffectRunner = async <A>() => {
229+
attempts += 1;
230+
if (attempts < 4) {
231+
throw new HttpClientError.HttpClientError({
232+
reason: new HttpClientError.StatusCodeError({ request, response }),
233+
});
234+
}
235+
return unauthenticatedSession(LOOPBACK_AUTH) as A;
236+
};
237+
__setPrimaryHttpRunnerForTests(runner);
235238

236239
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
237240

@@ -242,7 +245,7 @@ describe("resolveInitialServerAuthGateState", () => {
242245
status: "requires-auth",
243246
auth: LOOPBACK_AUTH,
244247
});
245-
expect(fetchMock).toHaveBeenCalledTimes(4);
248+
expect(attempts).toBe(4);
246249
});
247250

248251
it("takes a pairing token from the location hash and strips it immediately", async () => {

‎apps/web/src/cloud/linkEnvironment.test.ts‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,15 @@ vi.mock("./relayClientInstallDialog", () => ({
104104
finishRelayClientInstall: relayClientInstallDialogHarness.finish,
105105
}));
106106

107-
vi.mock("../environments/primary", () => ({
108-
readPrimaryEnvironmentDescriptor: vi.fn(() => null),
109-
readPrimaryEnvironmentTarget: vi.fn(() => null),
110-
resolvePrimaryEnvironmentHttpUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
111-
}));
107+
vi.mock("../environments/primary", async (importOriginal) => {
108+
const actual = await importOriginal<typeof import("../environments/primary")>();
109+
return {
110+
...actual,
111+
readPrimaryEnvironmentDescriptor: vi.fn(() => null),
112+
readPrimaryEnvironmentTarget: vi.fn(() => null),
113+
resolvePrimaryEnvironmentHttpUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
114+
};
115+
});
112116

113117
vi.mock("../environments/runtime", () => ({
114118
getPrimaryEnvironmentConnection: () => environmentConnectionMock,
@@ -552,7 +556,6 @@ describe("web cloud link environment client", () => {
552556
);
553557
expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
554558
method: "POST",
555-
credentials: "include",
556559
headers: expect.objectContaining({
557560
"content-type": "application/json",
558561
}),
@@ -591,7 +594,6 @@ describe("web cloud link environment client", () => {
591594
);
592595
expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({
593596
method: "POST",
594-
credentials: "include",
595597
headers: expect.objectContaining({
596598
"content-type": "application/json",
597599
}),
@@ -668,7 +670,6 @@ describe("web cloud link environment client", () => {
668670
);
669671
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
670672
method: "GET",
671-
credentials: "omit",
672673
});
673674
expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
674675
"Bearer desktop-bearer-token",
@@ -709,7 +710,6 @@ describe("web cloud link environment client", () => {
709710
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
710711
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
711712
method: "POST",
712-
credentials: "include",
713713
});
714714
expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
715715
"https://relay.example.test/v1/client/environment-links/env-1",
@@ -753,7 +753,6 @@ describe("web cloud link environment client", () => {
753753
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
754754
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
755755
method: "POST",
756-
credentials: "include",
757756
});
758757
}),
759758
);

‎apps/web/src/components/settings/SettingsPanels.browser.tsx‎

Lines changed: 68 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,17 @@ const authAccessHarness = vi.hoisted(() => {
150150
const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn());
151151
const mockGetClerkToken = vi.hoisted(() => vi.fn(async () => null));
152152
const mockOpenClerkWaitlist = vi.hoisted(() => vi.fn());
153+
const mockCreateServerPairingCredential = vi.hoisted(() => vi.fn());
154+
const mockRevokeOtherServerClientSessions = vi.hoisted(() => vi.fn());
155+
156+
vi.mock("~/environments/primary", async (importOriginal) => {
157+
const actual = await importOriginal<typeof import("~/environments/primary")>();
158+
return {
159+
...actual,
160+
createServerPairingCredential: mockCreateServerPairingCredential,
161+
revokeOtherServerClientSessions: mockRevokeOtherServerClientSessions,
162+
};
163+
});
153164

154165
vi.mock("@clerk/react", () => ({
155166
useAuth: () => ({
@@ -498,6 +509,8 @@ describe("GeneralSettingsPanel observability", () => {
498509
useUiStateStore.setState({ defaultAdvertisedEndpointKey: null });
499510
authAccessHarness.reset();
500511
mockConnectDesktopSshEnvironment.mockReset();
512+
mockCreateServerPairingCredential.mockReset();
513+
mockRevokeOtherServerClientSessions.mockReset();
501514
});
502515

503516
afterEach(async () => {
@@ -539,28 +552,6 @@ describe("GeneralSettingsPanel observability", () => {
539552
}),
540553
],
541554
});
542-
const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (input) => {
543-
const url = String(input);
544-
if (url.endsWith("/api/auth/session")) {
545-
return new Response(
546-
JSON.stringify({
547-
authenticated: true,
548-
auth: createBaseServerConfig().auth,
549-
scopes: ["orchestration:read", "access:write"],
550-
sessionMethod: "browser-session-cookie",
551-
expiresAt: "2036-05-07T00:00:00.000Z",
552-
}),
553-
{
554-
status: 200,
555-
headers: { "content-type": "application/json" },
556-
},
557-
);
558-
}
559-
560-
throw new Error(`Unhandled fetch GET ${url}`);
561-
});
562-
vi.stubGlobal("fetch", fetchMock);
563-
564555
mounted = await render(
565556
<AppAtomRegistryProvider>
566557
<ConnectionsSettings />
@@ -570,14 +561,7 @@ describe("GeneralSettingsPanel observability", () => {
570561
await expect
571562
.element(page.getByRole("heading", { name: "This environment", exact: true }))
572563
.toBeInTheDocument();
573-
await expect.element(page.getByLabelText("Enable network access")).toBeDisabled();
574-
await expect
575-
.element(
576-
page.getByText(
577-
"This backend is only reachable on this machine. Restart it with a non-loopback host to enable remote pairing.",
578-
),
579-
)
580-
.toBeInTheDocument();
564+
await expect.element(page.getByLabelText("Enable network access")).not.toBeInTheDocument();
581565
await expect.element(page.getByText("Authorized clients")).not.toBeInTheDocument();
582566
await expect.element(page.getByText("Chrome on Mac")).not.toBeInTheDocument();
583567
await expect
@@ -812,64 +796,51 @@ describe("GeneralSettingsPanel observability", () => {
812796
pairingLinks,
813797
clientSessions,
814798
});
815-
vi.stubGlobal(
816-
"fetch",
817-
vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
818-
const url = String(input);
819-
const method = init?.method ?? "GET";
820-
if (url.endsWith("/api/auth/pairing-token") && method === "POST") {
821-
pairingLinks = [
822-
makePairingLink({
823-
id: "pairing-link-1",
824-
credential: "pairing-token",
825-
scopes: ["orchestration:read"],
826-
subject: "one-time-token",
827-
label: "Julius iPhone",
828-
createdAt: "2036-04-07T00:00:00.000Z",
829-
expiresAt: "2036-04-10T00:05:00.000Z",
830-
}),
831-
];
832-
clientSessions = [
833-
...clientSessions,
834-
makeClientSession({
835-
sessionId: "session-client",
836-
subject: "one-time-token",
837-
scopes: ["orchestration:read"],
838-
method: "browser-session-cookie",
839-
client: {
840-
label: "Julius iPhone",
841-
deviceType: "mobile",
842-
os: "iOS",
843-
browser: "Safari",
844-
ipAddress: "192.168.1.88",
845-
},
846-
issuedAt: "2036-04-07T00:01:00.000Z",
847-
expiresAt: "2036-05-07T00:01:00.000Z",
848-
connected: false,
849-
current: false,
850-
}),
851-
];
852-
authAccessHarness.setSnapshot({
853-
pairingLinks,
854-
clientSessions,
855-
});
856-
return new Response(
857-
JSON.stringify({
858-
id: "pairing-link-1",
859-
credential: "pairing-token",
860-
label: "Julius iPhone",
861-
expiresAt: "2036-04-10T00:05:00.000Z",
862-
}),
863-
{
864-
status: 200,
865-
headers: { "content-type": "application/json" },
866-
},
867-
);
868-
}
869-
870-
throw new Error(`Unhandled fetch ${method} ${url}`);
871-
}),
872-
);
799+
mockCreateServerPairingCredential.mockImplementation(async () => {
800+
pairingLinks = [
801+
makePairingLink({
802+
id: "pairing-link-1",
803+
credential: "pairing-token",
804+
scopes: ["orchestration:read"],
805+
subject: "one-time-token",
806+
label: "Julius iPhone",
807+
createdAt: "2036-04-07T00:00:00.000Z",
808+
expiresAt: "2036-04-10T00:05:00.000Z",
809+
}),
810+
];
811+
clientSessions = [
812+
...clientSessions,
813+
makeClientSession({
814+
sessionId: "session-client",
815+
subject: "one-time-token",
816+
scopes: ["orchestration:read"],
817+
method: "browser-session-cookie",
818+
client: {
819+
label: "Julius iPhone",
820+
deviceType: "mobile",
821+
os: "iOS",
822+
browser: "Safari",
823+
ipAddress: "192.168.1.88",
824+
},
825+
issuedAt: "2036-04-07T00:01:00.000Z",
826+
expiresAt: "2036-05-07T00:01:00.000Z",
827+
connected: false,
828+
current: false,
829+
}),
830+
];
831+
authAccessHarness.setSnapshot({
832+
pairingLinks,
833+
clientSessions,
834+
});
835+
authAccessHarness.emitPairingLinkUpserted(pairingLinks[0]!);
836+
authAccessHarness.emitClientUpserted(clientSessions[1]!);
837+
return {
838+
id: "pairing-link-1",
839+
credential: "pairing-token",
840+
label: "Julius iPhone",
841+
expiresAt: makeUtc("2036-04-10T00:05:00.000Z"),
842+
};
843+
});
873844

874845
setServerConfigSnapshot(createBaseServerConfig());
875846

@@ -890,8 +861,6 @@ describe("GeneralSettingsPanel observability", () => {
890861
await expect.element(page.getByRole("checkbox", { name: /View environment/ })).toBeChecked();
891862
await expect.element(page.getByRole("checkbox", { name: /Operate tasks/ })).not.toBeChecked();
892863
await page.getByRole("button", { name: "Create link", exact: true }).click();
893-
authAccessHarness.emitPairingLinkUpserted(pairingLinks[0]!);
894-
authAccessHarness.emitClientUpserted(clientSessions[1]!);
895864
await expect
896865
.element(page.getByRole("button", { name: "Pairing link scopes: show 1 scope" }))
897866
.toBeInTheDocument();
@@ -1009,25 +978,15 @@ describe("GeneralSettingsPanel observability", () => {
1009978
clientSessions,
1010979
});
1011980

1012-
const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
1013-
const url = String(input);
1014-
const method = init?.method ?? "GET";
1015-
if (url.endsWith("/api/auth/clients/revoke-others") && method === "POST") {
1016-
clientSessions = clientSessions.filter((session) => session.current);
1017-
authAccessHarness.setSnapshot({
1018-
pairingLinks: [],
1019-
clientSessions,
1020-
});
1021-
authAccessHarness.emitClientRemoved("session-client");
1022-
return new Response(JSON.stringify({ revokedCount: 1 }), {
1023-
status: 200,
1024-
headers: { "content-type": "application/json" },
1025-
});
1026-
}
1027-
1028-
throw new Error(`Unhandled fetch ${method} ${url}`);
981+
mockRevokeOtherServerClientSessions.mockImplementation(async () => {
982+
clientSessions = clientSessions.filter((session) => session.current);
983+
authAccessHarness.setSnapshot({
984+
pairingLinks: [],
985+
clientSessions,
986+
});
987+
authAccessHarness.emitClientRemoved("session-client");
988+
return 1;
1029989
});
1030-
vi.stubGlobal("fetch", fetchMock);
1031990

1032991
setServerConfigSnapshot(createBaseServerConfig());
1033992

@@ -1041,7 +1000,7 @@ describe("GeneralSettingsPanel observability", () => {
10411000
await page.getByRole("button", { name: "Revoke others", exact: true }).click();
10421001
await expect.element(page.getByText("This Mac")).toBeInTheDocument();
10431002
await expect.element(page.getByText("Julius iPhone")).not.toBeInTheDocument();
1044-
expect(fetchMock).toHaveBeenCalled();
1003+
expect(mockRevokeOtherServerClientSessions).toHaveBeenCalled();
10451004
});
10461005

10471006
it("shows a disabled network access toggle with guidance in desktop builds", async () => {

0 commit comments

Comments
 (0)