Open History to see the last commit
1import {
2 AuthStandardClientScopes,
3 EnvironmentId,
4 ORCHESTRATION_PROTOCOL_VERSION,
5} from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10
11import * as RpcHttp from "../rpc/http.ts";
12import * as ClientCapabilities from "../platform/capabilities.ts";
13import { BearerConnectionCredential, BearerConnectionProfile } from "./catalog.ts";
14import { BearerConnectionTarget } from "./model.ts";
15import {
16 prepareBearerConnectionUpdate,
17 preparePairingRegistration,
18 prepareSshRegistration,
19} from "./onboarding.ts";
20
21const layerClientPresentation = Layer.succeed(
22 ClientCapabilities.ClientPresentation,
23 ClientCapabilities.ClientPresentation.of({
24 metadata: {
25 label: "T3 Code Test",
26 deviceType: "desktop",
27 os: "Test OS",
28 },
29 scopes: AuthStandardClientScopes,
30 }),
31);
32
33function layerPairingHttp(
34 calls: Array<{ readonly url: string; readonly init: RequestInit }>,
35 options?: {
36 readonly failDescriptor?: boolean;
37 readonly protocolVersion?: number;
38 readonly selfUpdate?: boolean;
39 },
40) {
41 const fetchFn = ((input, init = {}) => {
42 const url = String(input);
43 calls.push({ url, init });
44
45 if (url.endsWith("/.well-known/t3/environment")) {
46 if (options?.failDescriptor === true) {
47 return Promise.resolve(
48 Response.json({ message: "descriptor unavailable" }, { status: 503 }),
49 );
50 }
51 return Promise.resolve(
52 Response.json({
53 environmentId: "environment-paired",
54 label: "Paired environment",
55 platform: {
56 os: "linux",
57 arch: "x64",
58 },
59 serverVersion: "0.0.0-test",
60 orchestrationProtocolVersion: options?.protocolVersion ?? ORCHESTRATION_PROTOCOL_VERSION,
61 capabilities: {
62 repositoryIdentity: true,
63 ...(options?.selfUpdate === true ? { serverSelfUpdate: "boot-service" } : {}),
64 },
65 }),
66 );
67 }
68
69 if (url.endsWith("/oauth/token")) {
70 return Promise.resolve(
71 Response.json({
72 access_token: "bearer-token",
73 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
74 token_type: "Bearer",
75 expires_in: 3600,
76 scope: AuthStandardClientScopes.join(" "),
77 }),
78 );
79 }
80
81 return Promise.reject(new Error(`Unexpected request: ${url}`));
82 }) satisfies typeof fetch;
83
84 return RpcHttp.layerRemoteHttpClient(fetchFn);
85}
86
87describe("connection onboarding", () => {
88 it.effect("prepares a persisted bearer registration from pairing details", () =>
89 Effect.gen(function* () {
90 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
91 const registration = yield* preparePairingRegistration({
92 host: "remote.example.test",
93 pairingCode: "pairing-token",
94 }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))));
95
96 expect(registration).toMatchObject({
97 _tag: "BearerConnectionRegistration",
98 target: {
99 environmentId: "environment-paired",
100 label: "Paired environment",
101 connectionId: "bearer:environment-paired:https://remote.example.test",
102 },
103 profile: {
104 environmentId: "environment-paired",
105 label: "Paired environment",
106 connectionId: "bearer:environment-paired:https://remote.example.test",
107 httpBaseUrl: "https://remote.example.test/",
108 wsBaseUrl: "wss://remote.example.test/",
109 },
110 credential: {
111 token: "bearer-token",
112 },
113 });
114 expect(calls.map((call) => call.url)).toEqual([
115 "https://remote.example.test/.well-known/t3/environment",
116 "https://remote.example.test/oauth/token",
117 ]);
118
119 const tokenRequest = calls.find((call) => call.url.endsWith("/oauth/token"));
120 const tokenBody =
121 tokenRequest?.init.body instanceof Uint8Array
122 ? new TextDecoder().decode(tokenRequest.init.body)
123 : String(tokenRequest?.init.body);
124 const tokenParams = new URLSearchParams(tokenBody);
125 expect(tokenParams.get("subject_token")).toBe("pairing-token");
126 expect(tokenParams.get("scope")).toBe(AuthStandardClientScopes.join(" "));
127 expect(tokenParams.get("client_label")).toBe("T3 Code Test");
128 }),
129 );
130
131 it.effect("rejects an incompatible server without consuming the pairing credential", () =>
132 Effect.gen(function* () {
133 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
134 const error = yield* preparePairingRegistration({
135 host: "remote.example.test",
136 pairingCode: "pairing-token",
137 }).pipe(
138 Effect.provide(
139 Layer.mergeAll(
140 layerClientPresentation,
141 layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }),
142 ),
143 ),
144 Effect.flip,
145 );
146 expect(error).toMatchObject({ reason: "unsupported" });
147 expect(calls.map((call) => call.url)).toEqual([
148 "https://remote.example.test/.well-known/t3/environment",
149 ]);
150 }),
151 );
152
153 it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>
154 Effect.gen(function* () {
155 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
156 const error = yield* preparePairingRegistration({
157 host: "remote.example.test",
158 pairingCode: "pairing-token",
159 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
160 }).pipe(
161 Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))),
162 Effect.flip,
163 );
164 expect(error).toMatchObject({ reason: "configuration" });
165 expect(error.message).toContain("different machine");
166 expect(calls.map((call) => call.url)).toEqual([
167 "https://remote.example.test/.well-known/t3/environment",
168 ]);
169 }),
170 );
171
172 it.effect("pairs an outdated server so it can be updated from this client", () =>
173 Effect.gen(function* () {
174 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
175 const registration = yield* preparePairingRegistration({
176 host: "remote.example.test",
177 pairingCode: "pairing-token",
178 }).pipe(
179 Effect.provide(
180 Layer.mergeAll(
181 layerClientPresentation,
182 layerPairingHttp(calls, {
183 protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1,
184 selfUpdate: true,
185 }),
186 ),
187 ),
188 );
189 expect(registration.target.environmentId).toBe("environment-paired");
190 expect(calls.map((call) => call.url)).toContain("https://remote.example.test/oauth/token");
191 }),
192 );
193
194 it.effect("refuses an outdated server that cannot update itself", () =>
195 Effect.gen(function* () {
196 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
197 const error = yield* preparePairingRegistration({
198 host: "remote.example.test",
199 pairingCode: "pairing-token",
200 }).pipe(
201 Effect.provide(
202 Layer.mergeAll(
203 layerClientPresentation,
204 layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }),
205 ),
206 ),
207 Effect.flip,
208 );
209 expect(error).toMatchObject({ reason: "unsupported" });
210 expect(error).not.toHaveProperty("serverUpdateRequired");
211 expect(calls.map((call) => call.url)).toEqual([
212 "https://remote.example.test/.well-known/t3/environment",
213 ]);
214 }),
215 );
216
217 it.effect("does not consume a pairing credential when descriptor discovery fails", () =>
218 Effect.gen(function* () {
219 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
220
221 yield* preparePairingRegistration({
222 host: "remote.example.test",
223 pairingCode: "pairing-token",
224 }).pipe(
225 Effect.provide(
226 Layer.mergeAll(
227 layerClientPresentation,
228 layerPairingHttp(calls, { failDescriptor: true }),
229 ),
230 ),
231 Effect.flip,
232 );
233
234 expect(calls.map((call) => call.url)).toEqual([
235 "https://remote.example.test/.well-known/t3/environment",
236 ]);
237 }),
238 );
239
240 it.effect("rejects invalid pairing details before making a request", () =>
241 Effect.gen(function* () {
242 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
243 const error = yield* preparePairingRegistration({
244 host: "",
245 pairingCode: "",
246 }).pipe(
247 Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))),
248 Effect.flip,
249 );
250
251 expect(error).toMatchObject({
252 _tag: "ConnectionBlockedError",
253 reason: "configuration",
254 message: "Enter a backend URL.",
255 });
256 expect(calls).toEqual([]);
257 }),
258 );
259
260 it.effect("updates bearer metadata while preserving the credential and identity", () =>
261 Effect.gen(function* () {
262 const environmentId = EnvironmentId.make("environment-paired");
263 const registration = yield* prepareBearerConnectionUpdate({
264 input: {
265 environmentId,
266 label: " Renamed environment ",
267 httpBaseUrl: "http://100.65.180.100:3773/path",
268 },
269 entry: Option.some({
270 target: new BearerConnectionTarget({
271 environmentId,
272 label: "Old label",
273 connectionId: "bearer:environment-paired",
274 }),
275 profile: Option.some(
276 new BearerConnectionProfile({
277 connectionId: "bearer:environment-paired",
278 environmentId,
279 label: "Old label",
280 httpBaseUrl: "http://old.example.test/",
281 wsBaseUrl: "ws://old.example.test/",
282 }),
283 ),
284 enabled: true,
285 }),
286 credential: Option.some(new BearerConnectionCredential({ token: "bearer-token" })),
287 });
288
289 expect(registration).toMatchObject({
290 target: {
291 environmentId,
292 label: "Renamed environment",
293 connectionId: "bearer:environment-paired",
294 },
295 profile: {
296 environmentId,
297 label: "Renamed environment",
298 httpBaseUrl: "http://100.65.180.100:3773/",
299 wsBaseUrl: "ws://100.65.180.100:3773/",
300 },
301 credential: { token: "bearer-token" },
302 });
303 }),
304 );
305
306 it.effect("prepares an SSH registration from the provisioned platform environment", () =>
307 Effect.gen(function* () {
308 const target = {
309 alias: "devbox",
310 hostname: "devbox.example.test",
311 username: "developer",
312 port: 22,
313 };
314 const registration = yield* prepareSshRegistration({
315 target,
316 }).pipe(
317 Effect.provideService(
318 ClientCapabilities.SshEnvironmentGateway,
319 ClientCapabilities.SshEnvironmentGateway.of({
320 provision: () =>
321 Effect.succeed({
322 environmentId: EnvironmentId.make("environment-ssh"),
323 label: "Remote development box",
324 bootstrap: {
325 target,
326 httpBaseUrl: "http://127.0.0.1:3201",
327 wsBaseUrl: "ws://127.0.0.1:3201",
328 pairingToken: "pairing-token",
329 },
330 bearerToken: "bearer-token",
331 }),
332 prepare: () => Effect.die("unused"),
333 disconnect: () => Effect.die("unused"),
334 }),
335 ),
336 );
337
338 expect(registration).toMatchObject({
339 _tag: "SshConnectionRegistration",
340 target: {
341 environmentId: "environment-ssh",
342 label: "Remote development box",
343 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
344 },
345 profile: {
346 environmentId: "environment-ssh",
347 label: "Remote development box",
348 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
349 target,
350 },
351 });
352 }),
353 );
354});