Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions apps/desktop/src/app/DesktopApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,8 @@ const startLocalBackend = Effect.gen(function* () {
return false;
}

const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const primaryBackend = yield* pool.primary;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;

if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
Expand All @@ -212,16 +213,8 @@ const startLocalBackend = Effect.gen(function* () {
!(settings.wslOnly && settings.wslBackendEnabled) &&
!(yield* DesktopHomeOwner.awaitHomeOwnershipRelease())
) {
const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
yield* logBootstrapWarning("bootstrap found another server owning the T3 home", {
owner: Option.getOrNull(owner),
});
yield* (yield* ElectronDialog.ElectronDialog).showErrorBox(
"This T3 home is unavailable",
DesktopHomeOwner.homeOwnedMessage(owner),
);
yield* (yield* ElectronApp.ElectronApp).quit;
return false;
yield* logBootstrapInfo("connecting to the server that owns the T3 home");
return yield* pool.connectToHomeOwner;
}

const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/src/backend/DesktopBackendPool.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, describe, it } from "@effect/vitest";
import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
Expand All @@ -19,6 +20,7 @@ import { ChildProcessSpawner } from "effect/process";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
Expand Down Expand Up @@ -194,6 +196,8 @@ function layerPool(
currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
DesktopAppSettings.layerTest(),
DesktopManagedPolicy.layerTest(),
NodeCrypto.layer,
DesktopState.layer,
DesktopWslEnvironment.layerTest(),
Layer.succeed(ElectronDialog.ElectronDialog, {
Expand Down
58 changes: 46 additions & 12 deletions apps/desktop/src/backend/DesktopBackendPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
Expand All @@ -11,6 +12,7 @@ import * as FiberHandle from "effect/FiberHandle";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
Expand All @@ -26,6 +28,7 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
Expand Down Expand Up @@ -74,6 +77,8 @@ export class DesktopBackendPool extends Context.Service<
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
readonly primary: Effect.Effect<DesktopBackendInstance>;
readonly attachedHomeOwner: Effect.Effect<Option.Option<DesktopHomeOwner.HomeOwnerSession>>;
readonly connectToHomeOwner: Effect.Effect<boolean>;
readonly register: (
spec: BackendInstanceSpec,
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
Expand Down Expand Up @@ -129,7 +134,12 @@ export const layer = Layer.effect(
const layerScope = yield* Scope.Scope;
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
const homeOwnerContext = yield* Effect.context<
FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment
| FileSystem.FileSystem
| Path.Path
| DesktopEnvironment.DesktopEnvironment
| DesktopManagedPolicy.DesktopManagedPolicy
| SecureRandom.SecureRandom
| ChildProcessSpawner.ChildProcessSpawner
>();

const updateMarkerPath = environment.path.join(
Expand Down Expand Up @@ -219,6 +229,32 @@ export const layer = Layer.effect(
},
);

const attachedHomeOwner = yield* Ref.make(Option.none<DesktopHomeOwner.HomeOwnerSession>());
const connectToHomeOwner = Effect.gen(function* () {
const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
const session = Option.isSome(owner)
? yield* DesktopHomeOwner.authenticateHomeOwner(owner.value)
: Option.none();
if (Option.isNone(session)) {
yield* electronDialog.showErrorBox(
"This T3 home is unavailable",
DesktopHomeOwner.homeOwnedMessage(owner),
);
yield* electronApp.quit;
return false;
}
yield* Ref.set(attachedHomeOwner, session);
yield* reloadStaleMain;
yield* desktopWindow.handleBackendReady(new URL(`http://127.0.0.1:${session.value.port}/`));
yield* SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" });
return true;
}).pipe(
Scope.provide(layerScope),
Effect.provideContext(homeOwnerContext),
Effect.orDie,
Effect.withSpan("desktop.backendPool.connectToHomeOwner"),
);

const primary = yield* DesktopBackendManager.makeBackendInstance({
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
// Resolve lazily: startup loads persisted settings after pool initialization.
Expand All @@ -244,17 +280,11 @@ export const layer = Layer.effect(
Effect.andThen(desktopWindow.handleBackendNotReady),
),
onPreflightFailed: handlePrimaryPreflightFailure,
onStateDirOwned: () =>
DesktopHomeOwner.readLiveHomeOwner().pipe(
Effect.flatMap((owner) =>
electronDialog.showErrorBox(
"This T3 home is unavailable",
DesktopHomeOwner.homeOwnedMessage(owner),
),
),
Effect.provideContext(homeOwnerContext),
Effect.andThen(electronApp.quit),
),
onStateDirOwned: () => {
// The window may already have read the endpoint selected for the child that lost the lock.
reloadMainOnReady = true;
return connectToHomeOwner.pipe(Effect.asVoid);
},
});

const instancesRef = yield* SynchronizedRef.make<
Expand Down Expand Up @@ -389,6 +419,8 @@ export const layer = Layer.effect(
),
),
primary: Effect.succeed(primary),
attachedHomeOwner: Ref.get(attachedHomeOwner),
connectToHomeOwner,
register,
unregister,
});
Expand All @@ -414,6 +446,8 @@ export const layerTest = (
}),
list: Effect.succeed(Array.from(byId.values())),
primary: Effect.succeed(primary),
attachedHomeOwner: Effect.succeedNone,
connectToHomeOwner: Effect.die("unexpected home owner"),
register: Effect.fn("DesktopBackendPool.register")(function () {
return Effect.die("DesktopBackendPool.layerTest does not support register");
}),
Expand Down
107 changes: 104 additions & 3 deletions apps/desktop/src/backend/DesktopHomeOwner.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// @effect-diagnostics nodeBuiltinImport:off -- The fixture signs a challenge on the actual TCP listener the desktop verifies.
import * as NodeCrypto from "node:crypto";
import * as NodeHttp from "node:http";
import * as NodeSqlite from "node:sqlite";

import * as NodeCryptoServices from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { lanDiscoveryProofMessage } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
Expand All @@ -12,15 +17,16 @@ import * as TestClock from "effect/testing/TestClock";

import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";

const withTempHome = <A, E>(
const withTempHome = <A, E, R>(
run: (
userdata: string,
) => Effect.Effect<
A,
E,
DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem | Path.Path
DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem | Path.Path | R
>,
) =>
Effect.gen(function* () {
Expand All @@ -35,7 +41,7 @@ const withTempHome = <A, E>(
platform: "linux",
processArch: "x64",
appVersion: "0.0.0",
appPath: "/repo",
appPath: home,
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
Expand Down Expand Up @@ -120,3 +126,98 @@ describe("DesktopHomeOwner.awaitHomeOwnershipRelease", () => {
),
);
});

describe("DesktopHomeOwner.authenticateHomeOwner", () => {
it.live("attaches only to the home that signed the session and revokes it at exit", () =>
withTempHome((userdata) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const env = yield* DesktopEnvironment.DesktopEnvironment;
const environmentId = "bde15824-93d9-4339-a70a-599fcbe36b27";
const sessionId = "9f907b0c-c099-47b3-8568-eb4594cf5ef1";
const key = Buffer.alloc(32, 1);
const token = `YQ.${key.toString("base64url")}`;
yield* fs.makeDirectory(env.path.dirname(env.backendEntryPath), { recursive: true });
yield* fs.writeFileString(env.path.join(userdata, "environment-id"), environmentId);
yield* fs.writeFileString(
env.backendEntryPath,
`
import { appendFileSync } from "node:fs";
const args = process.argv.slice(2);
const home = args[args.indexOf("--base-dir") + 1];
appendFileSync(home + "/commands", args.slice(0, 3).join(" ") + "\\n");
if (args[2] === "issue") console.log(JSON.stringify(${JSON.stringify({ sessionId, token })}));
else if (!args.includes("${sessionId}")) process.exit(1);
`,
);

let correctHome = false;
const server = NodeHttp.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const { nonce, payload } = JSON.parse(Buffer.concat(chunks).toString());
const address = server.address();
if (!address || typeof address === "string" || payload !== "YQ") {
response.writeHead(400).end();
return;
}
const proof = NodeCrypto.createHmac("sha256", correctHome ? key : Buffer.alloc(32, 2))
.update(lanDiscoveryProofMessage(nonce, environmentId, "127.0.0.1", address.port))
.digest("base64url");
response.end(JSON.stringify({ proof }));
});
yield* Effect.acquireRelease(
Effect.promise(
() => new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)),
),
() =>
Effect.promise(
() =>
new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
}),
),
);
const address = server.address();
assert(address !== null && typeof address !== "string");
const legacy = { pid: process.pid, port: address.port };
assert.isTrue(Option.isNone(yield* DesktopHomeOwner.authenticateHomeOwner(legacy)));
const owner = { ...legacy, managedPolicy: null };
const attach = DesktopHomeOwner.authenticateHomeOwner(owner);
assert.isTrue(
Option.isNone(
yield* attach.pipe(
Effect.provide(
DesktopManagedPolicy.layerTest({
schemaVersion: 1,
organization: "Managed",
}),
),
),
),
);
assert.isTrue(
Option.isNone(
yield* DesktopHomeOwner.authenticateHomeOwner({
...owner,
managedPolicy: { organization: "Managed" },
}),
),
);
assert.isTrue(Option.isNone(yield* attach));
correctHome = true;
assert.deepEqual(yield* Effect.scoped(attach), Option.some({ port: address.port, token }));
assert.deepEqual(
(yield* fs.readFileString(env.path.join(env.baseDir, "commands"))).trim().split("\n"),
[
"auth session issue",
"auth session revoke",
"auth session issue",
"auth session revoke",
],
);
}).pipe(Effect.provide([DesktopManagedPolicy.layerTest(), NodeCryptoServices.layer])),
),
);
});
Loading
Loading