Skip to content

Commit 55c51e0

Browse files
committed
fix(desktop): derive bootstrap tokens per backend instance
Derive renderer tokens using each backend's own configured secret rather than mutating the shared credential. This prevents auto-attaching to an external server with a different secret from breaking authentication for already running WSL or local backends.
1 parent a1a70ae commit 55c51e0

9 files changed

Lines changed: 246 additions & 66 deletions

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

Lines changed: 171 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import { assert, describe, it } from "@effect/vitest";
2+
import * as DateTime from "effect/DateTime";
3+
import * as Duration from "effect/Duration";
24
import * as Effect from "effect/Effect";
35
import * as FileSystem from "effect/FileSystem";
46
import * as Layer from "effect/Layer";
@@ -7,7 +9,6 @@ import * as Path from "effect/Path";
79
import * as Ref from "effect/Ref";
810
import { HttpClient, HttpClientResponse } from "effect/http";
911

10-
import type { DesktopBackendConfiguration } from "./DesktopBackendConfiguration.ts";
1112
import type { DesktopBackendInstance, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
1213
import * as DesktopAutoAttach from "./DesktopAutoAttach.ts";
1314

@@ -23,10 +24,6 @@ describe("DesktopAutoAttach", () => {
2324
}),
2425
} as unknown as DesktopBackendInstance;
2526

26-
const mockConfiguration = {
27-
setBootstrapSecret: () => Effect.void,
28-
} as unknown as DesktopBackendConfiguration["Service"];
29-
3027
const testLayer = Layer.mergeAll(
3128
FileSystem.layerNoop({}),
3229
Path.layer,
@@ -40,7 +37,6 @@ describe("DesktopAutoAttach", () => {
4037
stateDir,
4138
backendCwd: "/repo",
4239
primary: mockPrimary,
43-
configuration: mockConfiguration,
4440
}).pipe(Effect.provide(testLayer));
4541

4642
assert.isFalse(result);
@@ -67,10 +63,6 @@ describe("DesktopAutoAttach", () => {
6763
}),
6864
} as unknown as DesktopBackendInstance;
6965

70-
const mockConfiguration = {
71-
setBootstrapSecret: () => Effect.void,
72-
} as unknown as DesktopBackendConfiguration["Service"];
73-
7466
const fsLayer = Layer.succeed(
7567
FileSystem.FileSystem,
7668
FileSystem.FileSystem.of({
@@ -92,7 +84,6 @@ describe("DesktopAutoAttach", () => {
9284
stateDir,
9385
backendCwd: "/repo",
9486
primary: mockPrimary,
95-
configuration: mockConfiguration,
9687
}).pipe(Effect.provide(testLayer));
9788

9889
assert.isFalse(result);
@@ -118,10 +109,6 @@ describe("DesktopAutoAttach", () => {
118109
}),
119110
} as unknown as DesktopBackendInstance;
120111

121-
const mockConfiguration = {
122-
setBootstrapSecret: () => Effect.void,
123-
} as unknown as DesktopBackendConfiguration["Service"];
124-
125112
const fsLayer = Layer.succeed(
126113
FileSystem.FileSystem,
127114
FileSystem.FileSystem.of({
@@ -143,7 +130,109 @@ describe("DesktopAutoAttach", () => {
143130
stateDir: "/tmp/t3-state-no-credentials",
144131
backendCwd: "/repo",
145132
primary: mockPrimary,
146-
configuration: mockConfiguration,
133+
}).pipe(Effect.provide(testLayer));
134+
135+
assert.isFalse(result);
136+
assert.isFalse(attached);
137+
}),
138+
);
139+
140+
it.effect("returns false when token-only runtime record is older than 24 hours", () =>
141+
Effect.gen(function* () {
142+
const stateDir = "/tmp/t3-state-expired-token";
143+
const currentPid = process.pid;
144+
const now = yield* DateTime.now;
145+
const expiredStartedAt = DateTime.formatIso(
146+
DateTime.subtractDuration(now, Duration.hours(25)),
147+
);
148+
const runtimeContent = JSON.stringify({
149+
version: 1,
150+
pid: currentPid,
151+
origin: "http://127.0.0.1:4545",
152+
port: 4545,
153+
startedAt: expiredStartedAt,
154+
desktopBootstrapToken: "expired-token",
155+
});
156+
157+
let attached = false;
158+
const mockPrimary = {
159+
attachExternal: () =>
160+
Effect.sync(() => {
161+
attached = true;
162+
}),
163+
} as unknown as DesktopBackendInstance;
164+
165+
const fsLayer = Layer.succeed(
166+
FileSystem.FileSystem,
167+
FileSystem.FileSystem.of({
168+
exists: () => Effect.succeed(true),
169+
readFileString: () => Effect.succeed(runtimeContent),
170+
} as unknown as FileSystem.FileSystem),
171+
);
172+
173+
const mockHttpClient = HttpClient.make((request) =>
174+
Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok", { status: 200 }))),
175+
);
176+
177+
const testLayer = Layer.mergeAll(
178+
fsLayer,
179+
Path.layer,
180+
Layer.succeed(HttpClient.HttpClient, mockHttpClient),
181+
);
182+
183+
const result = yield* DesktopAutoAttach.tryAutoAttachToRunningServer({
184+
stateDir,
185+
backendCwd: "/repo",
186+
primary: mockPrimary,
187+
}).pipe(Effect.provide(testLayer));
188+
189+
assert.isFalse(result);
190+
assert.isFalse(attached);
191+
}),
192+
);
193+
194+
it.effect("returns false when token-only runtime record has an invalid startedAt", () =>
195+
Effect.gen(function* () {
196+
const stateDir = "/tmp/t3-state-invalid-timestamp";
197+
const runtimeContent = JSON.stringify({
198+
version: 1,
199+
pid: process.pid,
200+
origin: "http://127.0.0.1:4545",
201+
port: 4545,
202+
startedAt: "invalid-timestamp",
203+
desktopBootstrapToken: "some-token",
204+
});
205+
206+
let attached = false;
207+
const mockPrimary = {
208+
attachExternal: () =>
209+
Effect.sync(() => {
210+
attached = true;
211+
}),
212+
} as unknown as DesktopBackendInstance;
213+
214+
const fsLayer = Layer.succeed(
215+
FileSystem.FileSystem,
216+
FileSystem.FileSystem.of({
217+
exists: () => Effect.succeed(true),
218+
readFileString: () => Effect.succeed(runtimeContent),
219+
} as unknown as FileSystem.FileSystem),
220+
);
221+
222+
const mockHttpClient = HttpClient.make((request) =>
223+
Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok", { status: 200 }))),
224+
);
225+
226+
const testLayer = Layer.mergeAll(
227+
fsLayer,
228+
Path.layer,
229+
Layer.succeed(HttpClient.HttpClient, mockHttpClient),
230+
);
231+
232+
const result = yield* DesktopAutoAttach.tryAutoAttachToRunningServer({
233+
stateDir,
234+
backendCwd: "/repo",
235+
primary: mockPrimary,
147236
}).pipe(Effect.provide(testLayer));
148237

149238
assert.isFalse(result);
@@ -169,10 +258,6 @@ describe("DesktopAutoAttach", () => {
169258
}),
170259
} as unknown as DesktopBackendInstance;
171260

172-
const mockConfiguration = {
173-
setBootstrapSecret: () => Effect.void,
174-
} as unknown as DesktopBackendConfiguration["Service"];
175-
176261
const fsLayer = Layer.succeed(
177262
FileSystem.FileSystem,
178263
FileSystem.FileSystem.of({
@@ -194,15 +279,14 @@ describe("DesktopAutoAttach", () => {
194279
stateDir: "/tmp/t3-state-invalid",
195280
backendCwd: "/repo",
196281
primary: mockPrimary,
197-
configuration: mockConfiguration,
198282
}).pipe(Effect.provide(testLayer));
199283

200284
assert.isFalse(result);
201285
assert.isFalse(attached);
202286
}),
203287
);
204288

205-
it.effect("successfully auto-attaches to live server and updates bootstrap credentials", () =>
289+
it.effect("successfully auto-attaches to live server with secret", () =>
206290
Effect.gen(function* () {
207291
const stateDir = "/tmp/t3-state-live";
208292
const currentPid = process.pid; // Guarantee a live PID
@@ -213,13 +297,12 @@ describe("DesktopAutoAttach", () => {
213297
origin: "http://127.0.0.1:4545",
214298
port: 4545,
215299
host: "127.0.0.1",
216-
startedAt: "2026-01-01T00:00:00.000Z",
300+
startedAt: "2020-01-01T00:00:00.000Z",
217301
desktopBootstrapSecret: testSecret,
218302
});
219303

220304
const attachedConfigRef = Ref.makeUnsafe<DesktopBackendStartConfig | null>(null);
221305
const attachedPidRef = Ref.makeUnsafe<number | null>(null);
222-
const updatedSecretRef = Ref.makeUnsafe<string | null>(null);
223306

224307
const mockPrimary = {
225308
attachExternal: (config: DesktopBackendStartConfig, pid: Option.Option<number>) =>
@@ -229,10 +312,6 @@ describe("DesktopAutoAttach", () => {
229312
}),
230313
} as unknown as DesktopBackendInstance;
231314

232-
const mockConfiguration = {
233-
setBootstrapSecret: (secret: string) => Ref.set(updatedSecretRef, secret),
234-
} as unknown as DesktopBackendConfiguration["Service"];
235-
236315
const fsLayer = Layer.succeed(
237316
FileSystem.FileSystem,
238317
FileSystem.FileSystem.of({
@@ -256,7 +335,6 @@ describe("DesktopAutoAttach", () => {
256335
stateDir,
257336
backendCwd: "/repo",
258337
primary: mockPrimary,
259-
configuration: mockConfiguration,
260338
}).pipe(Effect.provide(testLayer));
261339

262340
assert.isTrue(result);
@@ -268,9 +346,71 @@ describe("DesktopAutoAttach", () => {
268346

269347
const attachedPid = yield* Ref.get(attachedPidRef);
270348
assert.strictEqual(attachedPid, currentPid);
349+
}),
350+
);
271351

272-
const updatedSecret = yield* Ref.get(updatedSecretRef);
273-
assert.strictEqual(updatedSecret, testSecret);
352+
it.effect("successfully auto-attaches to live server with recent token-only record", () =>
353+
Effect.gen(function* () {
354+
const stateDir = "/tmp/t3-state-recent-token";
355+
const currentPid = process.pid;
356+
const now = yield* DateTime.now;
357+
const recentStartedAt = DateTime.formatIso(now);
358+
const testToken = "recent-token-123";
359+
const runtimeContent = JSON.stringify({
360+
version: 1,
361+
pid: currentPid,
362+
origin: "http://127.0.0.1:4545",
363+
port: 4545,
364+
host: "127.0.0.1",
365+
startedAt: recentStartedAt,
366+
desktopBootstrapToken: testToken,
367+
});
368+
369+
const attachedConfigRef = Ref.makeUnsafe<DesktopBackendStartConfig | null>(null);
370+
const attachedPidRef = Ref.makeUnsafe<number | null>(null);
371+
372+
const mockPrimary = {
373+
attachExternal: (config: DesktopBackendStartConfig, pid: Option.Option<number>) =>
374+
Effect.gen(function* () {
375+
yield* Ref.set(attachedConfigRef, config);
376+
yield* Ref.set(attachedPidRef, Option.getOrNull(pid));
377+
}),
378+
} as unknown as DesktopBackendInstance;
379+
380+
const fsLayer = Layer.succeed(
381+
FileSystem.FileSystem,
382+
FileSystem.FileSystem.of({
383+
exists: () => Effect.succeed(true),
384+
readFileString: () => Effect.succeed(runtimeContent),
385+
} as unknown as FileSystem.FileSystem),
386+
);
387+
388+
const mockHttpClient = HttpClient.make((request) =>
389+
Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok", { status: 200 }))),
390+
);
391+
392+
const testLayer = Layer.mergeAll(
393+
fsLayer,
394+
Path.layer,
395+
Layer.succeed(HttpClient.HttpClient, mockHttpClient),
396+
);
397+
398+
const result = yield* DesktopAutoAttach.tryAutoAttachToRunningServer({
399+
stateDir,
400+
backendCwd: "/repo",
401+
primary: mockPrimary,
402+
}).pipe(Effect.provide(testLayer));
403+
404+
assert.isTrue(result);
405+
406+
const attachedConfig = yield* Ref.get(attachedConfigRef);
407+
assert.isNotNull(attachedConfig);
408+
assert.strictEqual(attachedConfig?.httpBaseUrl.origin, "http://127.0.0.1:4545");
409+
assert.strictEqual(attachedConfig?.bootstrap.desktopBootstrapToken, testToken);
410+
assert.isUndefined(attachedConfig?.bootstrap.desktopBootstrapSecret);
411+
412+
const attachedPid = yield* Ref.get(attachedPidRef);
413+
assert.strictEqual(attachedPid, currentPid);
274414
}),
275415
);
276416
});

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

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as DateTime from "effect/DateTime";
12
import * as Duration from "effect/Duration";
23
import * as Effect from "effect/Effect";
34
import * as FileSystem from "effect/FileSystem";
@@ -8,7 +9,6 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
89

910
import { PersistedServerRuntimeState } from "@t3tools/contracts";
1011
import * as DesktopObservability from "../app/DesktopObservability.ts";
11-
import type { DesktopBackendConfiguration } from "./DesktopBackendConfiguration.ts";
1212
import type { DesktopBackendInstance, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
1313

1414
const { logInfo, logWarning } = DesktopObservability.makeComponentLogger("desktop-auto-attach");
@@ -17,6 +17,7 @@ const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
1717
const PROBE_TIMEOUT = Duration.millis(1500);
1818
const PROBE_RETRY_INTERVAL = Duration.millis(500);
1919
const MAX_PROBE_RETRIES = 3;
20+
const TOKEN_ONLY_BOOTSTRAP_TTL = Duration.hours(24);
2021

2122
const isProcessAlive = (pid: number): boolean => {
2223
if (pid <= 0) {
@@ -58,7 +59,6 @@ export const tryAutoAttachToRunningServer = Effect.fn(
5859
readonly stateDir: string;
5960
readonly backendCwd: string;
6061
readonly primary: DesktopBackendInstance;
61-
readonly configuration: DesktopBackendConfiguration["Service"];
6262
}) {
6363
const fs = yield* FileSystem.FileSystem;
6464
const path = yield* Path.Path;
@@ -97,14 +97,43 @@ export const tryAutoAttachToRunningServer = Effect.fn(
9797
return false;
9898
}
9999

100-
if (state.desktopBootstrapSecret === undefined && state.desktopBootstrapToken === undefined) {
100+
const hasSecret =
101+
state.desktopBootstrapSecret !== undefined && state.desktopBootstrapSecret.trim() !== "";
102+
const hasToken =
103+
state.desktopBootstrapToken !== undefined && state.desktopBootstrapToken.trim() !== "";
104+
105+
if (!hasSecret && !hasToken) {
101106
yield* logWarning(
102107
"server-runtime.json has no desktop bootstrap credentials; auto-attach skipped",
103108
{ runtimeStatePath, pid: state.pid },
104109
);
105110
return false;
106111
}
107112

113+
if (!hasSecret) {
114+
const startedAt = DateTime.make(state.startedAt);
115+
if (Option.isNone(startedAt)) {
116+
yield* logWarning(
117+
"server-runtime.json has an invalid startedAt timestamp; auto-attach skipped",
118+
{ runtimeStatePath, startedAt: state.startedAt },
119+
);
120+
return false;
121+
}
122+
const expiresAt = DateTime.addDuration(startedAt.value, TOKEN_ONLY_BOOTSTRAP_TTL);
123+
const now = yield* DateTime.now;
124+
if (DateTime.isGreaterThanOrEqualTo(now, expiresAt)) {
125+
yield* logWarning(
126+
"server-runtime.json token-only bootstrap credential has expired; auto-attach skipped",
127+
{
128+
runtimeStatePath,
129+
startedAt: state.startedAt,
130+
expiresAt: DateTime.formatIso(expiresAt),
131+
},
132+
);
133+
return false;
134+
}
135+
}
136+
108137
if (!isProcessAlive(state.pid)) {
109138
yield* logWarning("Server recorded in server-runtime.json is dead; auto-attach skipped", {
110139
pid: state.pid,
@@ -133,10 +162,6 @@ export const tryAutoAttachToRunningServer = Effect.fn(
133162
return false;
134163
}
135164

136-
if (state.desktopBootstrapSecret) {
137-
yield* input.configuration.setBootstrapSecret(state.desktopBootstrapSecret);
138-
}
139-
140165
const attachedConfig: DesktopBackendStartConfig = {
141166
executablePath: "",
142167
entryPath: "",

0 commit comments

Comments
 (0)