1import type { DesktopBridge } from "@t3tools/contracts";
2import { afterEach, describe, expect, it, vi } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import { HttpClient } from "effect/http";
5
6import { __resetDesktopPrimaryAuthForTests } from "./desktopAuth";
7import * as PrimaryEnvironmentHttpLayer from "./httpLayer";
8
9describe("primary environment HTTP layer", { concurrent: false }, () => {
10 afterEach(() => {
11 __resetDesktopPrimaryAuthForTests();
12 Reflect.deleteProperty(globalThis, "window");
13 vi.unstubAllGlobals();
14 });
15
16 it.effect("uses cookie credentials for browser primary environments", () => {
17 const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
18 vi.stubGlobal("fetch", fetchMock);
19 Object.defineProperty(globalThis, "window", {
20 configurable: true,
21 value: {
22 location: {
23 href: "http://127.0.0.1:3773/settings",
24 origin: "http://127.0.0.1:3773",
25 },
26 },
27 });
28
29 return Effect.gen(function* () {
30 yield* HttpClient.get("http://127.0.0.1:3773/api/auth/session");
31
32 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
33 expect(request.credentials).toBe("include");
34 expect(request.headers.get("authorization")).toBeNull();
35 }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layerForCurrentOrigin()));
36 });
37
38 it.effect("uses bearer auth without cookies for desktop-managed primaries", () => {
39 const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
40 vi.stubGlobal("fetch", fetchMock);
41 Object.defineProperty(globalThis, "window", {
42 configurable: true,
43 value: {
44 location: { origin: "t3code://app" },
45 desktopBridge: {
46 getLocalEnvironmentBootstrap: () => ({
47 label: "Local environment",
48 httpBaseUrl: "http://127.0.0.1:3773",
49 wsBaseUrl: "ws://127.0.0.1:3773",
50 bootstrapToken: "desktop-bootstrap-token",
51 }),
52 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
53 } as unknown as DesktopBridge,
54 },
55 });
56
57 return Effect.gen(function* () {
58 yield* HttpClient.get("http://127.0.0.1:3773/api/connect/link-state");
59
60 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
61 expect(request.credentials).not.toBe("include");
62 expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
63 }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layerForCurrentOrigin()));
64 });
65});