Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

linkEnvironment.test.ts

174 lines6.2 KB

1import {
2 type DesktopBridge,
3 EnvironmentId,
4 type RelayClientInstallProgressEvent,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import { RelayWebClientId } from "@t3tools/contracts/relay";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { HttpClient } from "effect/http";
15import { afterEach, beforeEach, vi } from "vite-plus/test";
16import {
17 AVAILABLE_CONNECTION_STATE,
18 type PreparedConnection,
19 PrimaryConnectionTarget,
20 EnvironmentSupervisor,
21} from "@t3tools/client-runtime/connection";
22import { type RpcSession } from "@t3tools/client-runtime/rpc";
23import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
24import { ManagedRelay } from "@t3tools/client-runtime/relay";
25import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
26import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
27​
28import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
29​
30const TARGET: CloudLinkTarget = {
31 environmentId: "environment-1",
32 label: "Desktop",
33 httpBaseUrl: "http://127.0.0.1:3000",
34 wsBaseUrl: "ws://127.0.0.1:3000",
35};
36​
37const relayClientInstallDialog = vi.hoisted(() => ({
38 requestConfirmation: vi.fn(),
39 reportProgress: vi.fn(),
40 finish: vi.fn(),
41}));
42​
43vi.mock("./relayClientInstallDialog", () => ({
44 requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
45 reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
46 finishRelayClientInstall: relayClientInstallDialog.finish,
47}));
48​
49const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
50const layerDpopSigner = Layer.succeed(
51 ManagedRelay.ManagedRelayDpopSigner,
52 ManagedRelay.ManagedRelayDpopSigner.of({
53 thumbprint: Effect.succeed("thumbprint"),
54 createProof,
55 }),
56);
57​
58function layerRelay() {
59 const layerHttp = layerRemoteHttpClient(globalThis.fetch);
60 return Layer.mergeAll(
61 layerHttp,
62 ManagedRelay.layer({
63 relayUrl: "https://relay.example.test",
64 clientId: RelayWebClientId,
65 }).pipe(Layer.provideMerge(layerDpopSigner), Layer.provide(layerHttp)),
66 );
68​
69function layerRegistry(options?: {
70 readonly status?: { readonly status: "available"; readonly version: string };
71 readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
72}) {
73 return Layer.effect(
74 EnvironmentRegistry.EnvironmentRegistry,
75 Effect.gen(function* () {
76 const client = {
77 [WS_METHODS.cloudGetRelayClientStatus]: () =>
78 Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
79 [WS_METHODS.cloudInstallRelayClient]: () =>
80 Stream.fromIterable(options?.installEvents ?? []),
81 } as unknown as RpcSession["client"];
82 const session: RpcSession = {
83 client,
84 initialConfig: Effect.never,
85 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
86 ready: Effect.void,
87 probe: Effect.void,
88 closed: Effect.never,
89 };
90 const target = new PrimaryConnectionTarget({
91 environmentId: EnvironmentId.make(TARGET.environmentId),
92 label: TARGET.label,
93 httpBaseUrl: TARGET.httpBaseUrl,
94 wsBaseUrl: TARGET.wsBaseUrl,
95 });
96 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
97 target,
98 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
99 session: yield* SubscriptionRef.make(Option.some(session)),
100 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
101 connect: Effect.void,
102 disconnect: Effect.void,
103 retryNow: Effect.void,
104 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
105 const registry = {
106 run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
107 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
108 runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
109 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
110 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"];
111 return EnvironmentRegistry.EnvironmentRegistry.of(registry);
112 }),
113 );
115​
116function layerServices(options?: Parameters<typeof layerRegistry>[0]) {
117 return Layer.mergeAll(layerRelay(), layerRegistry(options));
119​
120function withServices<A, E>(
121 effect: Effect.Effect<
122 A,
123 E,
124 | HttpClient.HttpClient
125 | ManagedRelay.ManagedRelayClient
126 | EnvironmentRegistry.EnvironmentRegistry
127 >,
128 options?: Parameters<typeof layerRegistry>[0],
129) {
130 return effect.pipe(Effect.provide(layerServices(options)));
132​
133beforeEach(() => {
134 vi.clearAllMocks();
135 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
136 relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
137});
138​
139afterEach(() => {
140 __resetDesktopPrimaryAuthForTests();
141 vi.unstubAllGlobals();
142 vi.unstubAllEnvs();
143 vi.restoreAllMocks();
144});
145​
146describe("web cloud link environment client", () => {
147 it.effect("uses desktop bearer auth for primary cloud link state", () =>
148 Effect.gen(function* () {
149 const fetchMock = vi.fn().mockResolvedValue(
150 Response.json({
151 linked: true,
152 cloudUserId: "user-1",
153 relayUrl: "https://relay.example.test",
154 relayIssuer: "https://relay.example.test",
155 managedTunnelActive: true,
156 publishAgentActivity: false,
157 }),
158 );
159 vi.stubGlobal("fetch", fetchMock);
160 vi.stubGlobal("window", {
161 location: { origin: "t3code://app" },
162 desktopBridge: {
163 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
164 } as unknown as DesktopBridge,
165 });
166​
167 yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
168​
169 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
170 expect(request.credentials).not.toBe("include");
171 expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
172 }),
173 );
174});