Skip to content

Commit f88dc8b

Browse files
fix(desktop): connect to the server already using the T3 home
1 parent 26d72fd commit f88dc8b

17 files changed

Lines changed: 413 additions & 39 deletions

‎apps/desktop/src/app/DesktopApp.ts‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,8 @@ const startLocalBackend = Effect.gen(function* () {
200200
return false;
201201
}
202202

203-
const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
203+
const pool = yield* DesktopBackendPool.DesktopBackendPool;
204+
const primaryBackend = yield* pool.primary;
204205
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
205206

206207
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
@@ -212,16 +213,8 @@ const startLocalBackend = Effect.gen(function* () {
212213
!(settings.wslOnly && settings.wslBackendEnabled) &&
213214
!(yield* DesktopHomeOwner.awaitHomeOwnershipRelease())
214215
) {
215-
const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
216-
yield* logBootstrapWarning("bootstrap found another server owning the T3 home", {
217-
owner: Option.getOrNull(owner),
218-
});
219-
yield* (yield* ElectronDialog.ElectronDialog).showErrorBox(
220-
"This T3 home is unavailable",
221-
DesktopHomeOwner.homeOwnedMessage(owner),
222-
);
223-
yield* (yield* ElectronApp.ElectronApp).quit;
224-
return false;
216+
yield* logBootstrapInfo("connecting to the server that owns the T3 home");
217+
return yield* pool.connectToHomeOwner;
225218
}
226219

227220
const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);

‎apps/desktop/src/backend/DesktopBackendPool.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
12
import { assert, describe, it } from "@effect/vitest";
23
import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts";
34
import * as Deferred from "effect/Deferred";
@@ -19,6 +20,7 @@ import { ChildProcessSpawner } from "effect/process";
1920
import * as DesktopConfig from "../app/DesktopConfig.ts";
2021
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
2122
import * as DesktopObservability from "../app/DesktopObservability.ts";
23+
import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
2224
import * as DesktopState from "../app/DesktopState.ts";
2325
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
2426
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
@@ -194,6 +196,8 @@ function layerPool(
194196
currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
195197
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
196198
DesktopAppSettings.layerTest(),
199+
DesktopManagedPolicy.layerTest(),
200+
NodeCrypto.layer,
197201
DesktopState.layer,
198202
DesktopWslEnvironment.layerTest(),
199203
Layer.succeed(ElectronDialog.ElectronDialog, {

‎apps/desktop/src/backend/DesktopBackendPool.ts‎

Lines changed: 46 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
44
} from "@t3tools/contracts";
55
import * as Context from "effect/Context";
6+
import * as SecureRandom from "effect/crypto/SecureRandom";
67
import * as Deferred from "effect/Deferred";
78
import * as Duration from "effect/Duration";
89
import * as Effect from "effect/Effect";
@@ -11,6 +12,7 @@ import * as FiberHandle from "effect/FiberHandle";
1112
import * as Layer from "effect/Layer";
1213
import * as Option from "effect/Option";
1314
import * as Path from "effect/Path";
15+
import * as Ref from "effect/Ref";
1416
import * as Schedule from "effect/Schedule";
1517
import * as Schema from "effect/Schema";
1618
import * as Scope from "effect/Scope";
@@ -26,6 +28,7 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
2628
import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
2729
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
2830
import * as DesktopObservability from "../app/DesktopObservability.ts";
31+
import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
2932
import * as DesktopState from "../app/DesktopState.ts";
3033
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
3134
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
@@ -74,6 +77,8 @@ export class DesktopBackendPool extends Context.Service<
7477
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
7578
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
7679
readonly primary: Effect.Effect<DesktopBackendInstance>;
80+
readonly attachedHomeOwner: Effect.Effect<Option.Option<DesktopHomeOwner.HomeOwnerSession>>;
81+
readonly connectToHomeOwner: Effect.Effect<boolean>;
7782
readonly register: (
7883
spec: BackendInstanceSpec,
7984
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
@@ -129,7 +134,12 @@ export const layer = Layer.effect(
129134
const layerScope = yield* Scope.Scope;
130135
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
131136
const homeOwnerContext = yield* Effect.context<
132-
FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment
137+
| FileSystem.FileSystem
138+
| Path.Path
139+
| DesktopEnvironment.DesktopEnvironment
140+
| DesktopManagedPolicy.DesktopManagedPolicy
141+
| SecureRandom.SecureRandom
142+
| ChildProcessSpawner.ChildProcessSpawner
133143
>();
134144

135145
const updateMarkerPath = environment.path.join(
@@ -219,6 +229,32 @@ export const layer = Layer.effect(
219229
},
220230
);
221231

232+
const attachedHomeOwner = yield* Ref.make(Option.none<DesktopHomeOwner.HomeOwnerSession>());
233+
const connectToHomeOwner = Effect.gen(function* () {
234+
const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
235+
const session = Option.isSome(owner)
236+
? yield* DesktopHomeOwner.authenticateHomeOwner(owner.value)
237+
: Option.none();
238+
if (Option.isNone(session)) {
239+
yield* electronDialog.showErrorBox(
240+
"This T3 home is unavailable",
241+
DesktopHomeOwner.homeOwnedMessage(owner),
242+
);
243+
yield* electronApp.quit;
244+
return false;
245+
}
246+
yield* Ref.set(attachedHomeOwner, session);
247+
yield* reloadStaleMain;
248+
yield* desktopWindow.handleBackendReady(new URL(`http://127.0.0.1:${session.value.port}/`));
249+
yield* SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" });
250+
return true;
251+
}).pipe(
252+
Scope.provide(layerScope),
253+
Effect.provideContext(homeOwnerContext),
254+
Effect.orDie,
255+
Effect.withSpan("desktop.backendPool.connectToHomeOwner"),
256+
);
257+
222258
const primary = yield* DesktopBackendManager.makeBackendInstance({
223259
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
224260
// Resolve lazily: startup loads persisted settings after pool initialization.
@@ -244,17 +280,11 @@ export const layer = Layer.effect(
244280
Effect.andThen(desktopWindow.handleBackendNotReady),
245281
),
246282
onPreflightFailed: handlePrimaryPreflightFailure,
247-
onStateDirOwned: () =>
248-
DesktopHomeOwner.readLiveHomeOwner().pipe(
249-
Effect.flatMap((owner) =>
250-
electronDialog.showErrorBox(
251-
"This T3 home is unavailable",
252-
DesktopHomeOwner.homeOwnedMessage(owner),
253-
),
254-
),
255-
Effect.provideContext(homeOwnerContext),
256-
Effect.andThen(electronApp.quit),
257-
),
283+
onStateDirOwned: () => {
284+
// The window may already have read the endpoint selected for the child that lost the lock.
285+
reloadMainOnReady = true;
286+
return connectToHomeOwner.pipe(Effect.asVoid);
287+
},
258288
});
259289

260290
const instancesRef = yield* SynchronizedRef.make<
@@ -389,6 +419,8 @@ export const layer = Layer.effect(
389419
),
390420
),
391421
primary: Effect.succeed(primary),
422+
attachedHomeOwner: Ref.get(attachedHomeOwner),
423+
connectToHomeOwner,
392424
register,
393425
unregister,
394426
});
@@ -414,6 +446,8 @@ export const layerTest = (
414446
}),
415447
list: Effect.succeed(Array.from(byId.values())),
416448
primary: Effect.succeed(primary),
449+
attachedHomeOwner: Effect.succeedNone,
450+
connectToHomeOwner: Effect.die("unexpected home owner"),
417451
register: Effect.fn("DesktopBackendPool.register")(function () {
418452
return Effect.die("DesktopBackendPool.layerTest does not support register");
419453
}),

‎apps/desktop/src/backend/DesktopHomeOwner.test.ts‎

Lines changed: 104 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- The fixture signs a challenge on the actual TCP listener the desktop verifies.
2+
import * as NodeCrypto from "node:crypto";
3+
import * as NodeHttp from "node:http";
14
import * as NodeSqlite from "node:sqlite";
25

6+
import * as NodeCryptoServices from "@effect/platform-node/NodeCrypto";
37
import * as NodeServices from "@effect/platform-node/NodeServices";
8+
import { lanDiscoveryProofMessage } from "@t3tools/contracts";
49
import { assert, describe, it } from "@effect/vitest";
510
import * as Effect from "effect/Effect";
611
import * as Fiber from "effect/Fiber";
@@ -12,15 +17,16 @@ import * as TestClock from "effect/testing/TestClock";
1217

1318
import * as DesktopConfig from "../app/DesktopConfig.ts";
1419
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
20+
import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
1521
import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
1622

17-
const withTempHome = <A, E>(
23+
const withTempHome = <A, E, R>(
1824
run: (
1925
userdata: string,
2026
) => Effect.Effect<
2127
A,
2228
E,
23-
DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem | Path.Path
29+
DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem | Path.Path | R
2430
>,
2531
) =>
2632
Effect.gen(function* () {
@@ -35,7 +41,7 @@ const withTempHome = <A, E>(
3541
platform: "linux",
3642
processArch: "x64",
3743
appVersion: "0.0.0",
38-
appPath: "/repo",
44+
appPath: home,
3945
isPackaged: true,
4046
resourcesPath: "/missing/resources",
4147
runningUnderArm64Translation: false,
@@ -120,3 +126,98 @@ describe("DesktopHomeOwner.awaitHomeOwnershipRelease", () => {
120126
),
121127
);
122128
});
129+
130+
describe("DesktopHomeOwner.authenticateHomeOwner", () => {
131+
it.live("attaches only to the home that signed the session and revokes it at exit", () =>
132+
withTempHome((userdata) =>
133+
Effect.gen(function* () {
134+
const fs = yield* FileSystem.FileSystem;
135+
const env = yield* DesktopEnvironment.DesktopEnvironment;
136+
const environmentId = "bde15824-93d9-4339-a70a-599fcbe36b27";
137+
const sessionId = "9f907b0c-c099-47b3-8568-eb4594cf5ef1";
138+
const key = Buffer.alloc(32, 1);
139+
const token = `YQ.${key.toString("base64url")}`;
140+
yield* fs.makeDirectory(env.path.dirname(env.backendEntryPath), { recursive: true });
141+
yield* fs.writeFileString(env.path.join(userdata, "environment-id"), environmentId);
142+
yield* fs.writeFileString(
143+
env.backendEntryPath,
144+
`
145+
import { appendFileSync } from "node:fs";
146+
const args = process.argv.slice(2);
147+
const home = args[args.indexOf("--base-dir") + 1];
148+
appendFileSync(home + "/commands", args.slice(0, 3).join(" ") + "\\n");
149+
if (args[2] === "issue") console.log(JSON.stringify(${JSON.stringify({ sessionId, token })}));
150+
else if (!args.includes("${sessionId}")) process.exit(1);
151+
`,
152+
);
153+
154+
let correctHome = false;
155+
const server = NodeHttp.createServer(async (request, response) => {
156+
const chunks = [];
157+
for await (const chunk of request) chunks.push(chunk);
158+
const { nonce, payload } = JSON.parse(Buffer.concat(chunks).toString());
159+
const address = server.address();
160+
if (!address || typeof address === "string" || payload !== "YQ") {
161+
response.writeHead(400).end();
162+
return;
163+
}
164+
const proof = NodeCrypto.createHmac("sha256", correctHome ? key : Buffer.alloc(32, 2))
165+
.update(lanDiscoveryProofMessage(nonce, environmentId, "127.0.0.1", address.port))
166+
.digest("base64url");
167+
response.end(JSON.stringify({ proof }));
168+
});
169+
yield* Effect.acquireRelease(
170+
Effect.promise(
171+
() => new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)),
172+
),
173+
() =>
174+
Effect.promise(
175+
() =>
176+
new Promise<void>((resolve) => {
177+
server.close(() => resolve());
178+
server.closeAllConnections();
179+
}),
180+
),
181+
);
182+
const address = server.address();
183+
assert(address !== null && typeof address !== "string");
184+
const legacy = { pid: process.pid, port: address.port };
185+
assert.isTrue(Option.isNone(yield* DesktopHomeOwner.authenticateHomeOwner(legacy)));
186+
const owner = { ...legacy, managedPolicy: null };
187+
const attach = DesktopHomeOwner.authenticateHomeOwner(owner);
188+
assert.isTrue(
189+
Option.isNone(
190+
yield* attach.pipe(
191+
Effect.provide(
192+
DesktopManagedPolicy.layerTest({
193+
schemaVersion: 1,
194+
organization: "Managed",
195+
}),
196+
),
197+
),
198+
),
199+
);
200+
assert.isTrue(
201+
Option.isNone(
202+
yield* DesktopHomeOwner.authenticateHomeOwner({
203+
...owner,
204+
managedPolicy: { organization: "Managed" },
205+
}),
206+
),
207+
);
208+
assert.isTrue(Option.isNone(yield* attach));
209+
correctHome = true;
210+
assert.deepEqual(yield* Effect.scoped(attach), Option.some({ port: address.port, token }));
211+
assert.deepEqual(
212+
(yield* fs.readFileString(env.path.join(env.baseDir, "commands"))).trim().split("\n"),
213+
[
214+
"auth session issue",
215+
"auth session revoke",
216+
"auth session issue",
217+
"auth session revoke",
218+
],
219+
);
220+
}).pipe(Effect.provide([DesktopManagedPolicy.layerTest(), NodeCryptoServices.layer])),
221+
),
222+
);
223+
});

0 commit comments

Comments
 (0)