Skip to content

Commit 7ec1894

Browse files
authored
fix(desktop): control sockets work with long temporary paths (#27125)
Co-authored-by: Simone <[email protected]>
1 parent 1b9437f commit 7ec1894

4 files changed

Lines changed: 106 additions & 17 deletions

File tree

‎apps/server/src/cli/app.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ async function startFakeDesktop(input: {
108108
});
109109

110110
return {
111+
directory: target.directory,
111112
received,
112113
close: async () => {
113114
await new Promise<void>((resolve) => server.close(() => resolve()));
@@ -134,9 +135,10 @@ const fakeDesktop = Effect.fn(function* (
134135
const withTempDirectory = <A, E, R>(
135136
prefix: string,
136137
use: (root: string) => Effect.Effect<A, E, R>,
138+
tempDir = NodeOS.tmpdir(),
137139
) =>
138140
Effect.acquireUseRelease(
139-
Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), prefix))),
141+
Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(tempDir, prefix))),
140142
use,
141143
(root) => Effect.promise(() => NodeFSP.rm(root, { recursive: true, force: true })),
142144
);
@@ -215,6 +217,60 @@ describe("t3 server command safety", () => {
215217
});
216218

217219
describe("t3 app", () => {
220+
it.live.each(["permissions", "owner", "symlink", "missing owner"] as const)(
221+
"rejects unsafe %s on the socket directory before sending",
222+
(unsafe) =>
223+
Effect.gen(function* () {
224+
const platform = yield* HostProcess.Platform;
225+
if (platform === "win32") return;
226+
yield* withTempDirectory(
227+
"t3-app-unsafe-",
228+
(root) =>
229+
Effect.gen(function* () {
230+
const previousTmpdir = process.env.TMPDIR;
231+
yield* Effect.acquireRelease(
232+
Effect.sync(() => {
233+
process.env.TMPDIR = root;
234+
}),
235+
() =>
236+
Effect.sync(() => {
237+
if (previousTmpdir === undefined) delete process.env.TMPDIR;
238+
else process.env.TMPDIR = previousTmpdir;
239+
}),
240+
);
241+
const baseDir = NodePath.join(root, ".t3");
242+
const userId = yield* HostProcess.UserId;
243+
assert(userId !== undefined);
244+
const expectedUserId =
245+
unsafe === "missing owner" ? undefined : unsafe === "owner" ? userId + 1 : userId;
246+
const desktop = yield* fakeDesktop({ baseDir }).pipe(
247+
Effect.provideService(HostProcess.UserId, expectedUserId),
248+
);
249+
const directory = desktop.directory;
250+
assert(directory !== null);
251+
if (unsafe === "permissions") {
252+
yield* Effect.promise(() => NodeFSP.chmod(directory, 0o755));
253+
} else if (unsafe === "symlink") {
254+
const moved = NodePath.join(root, "moved");
255+
yield* Effect.promise(() => NodeFSP.rename(directory, moved));
256+
yield* Effect.promise(() => NodeFSP.symlink(moved, directory));
257+
}
258+
const result = yield* runCli(["app"]).pipe(
259+
Effect.provideService(HostProcess.HomeDirectory, root),
260+
Effect.provideService(HostProcess.UserId, expectedUserId),
261+
Effect.result,
262+
);
263+
expect(desktop.received).toEqual([]);
264+
expect(result).toMatchObject({
265+
_tag: "Failure",
266+
failure: { _tag: "DesktopAppUnreachableError" },
267+
});
268+
}).pipe(Effect.scoped),
269+
"/tmp",
270+
);
271+
}),
272+
);
273+
218274
it.effect("uses T3CODE_HOME or --base-dir and sends the default or explicit path", () =>
219275
withTempDirectory("t3-app-command-test-", (root) =>
220276
Effect.gen(function* () {

‎apps/server/src/cli/app.ts‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// @effect-diagnostics globalTimers:off -- The Node socket client owns its response deadline and clears it on every completion path.
2+
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect stat follows symlinks; IPC ownership validation requires lstat.
3+
import * as NodeFSP from "node:fs/promises";
24
import * as NodeNet from "node:net";
35
import * as NodeOS from "node:os";
46

@@ -9,7 +11,10 @@ import {
911
type DesktopAppActivationPlatform,
1012
type DesktopAppActivationRequest,
1113
} from "@t3tools/contracts";
12-
import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
14+
import {
15+
resolveDesktopAppControlAddress,
16+
type DesktopAppControlAddress,
17+
} from "@t3tools/shared/desktopAppControl";
1318
import * as HostProcess from "@t3tools/shared/HostProcess";
1419
import * as Config from "effect/Config";
1520
import * as Console from "effect/Console";
@@ -77,14 +82,26 @@ function isDesktopPlatform(platform: NodeJS.Platform): platform is DesktopAppAct
7782
return platform === "darwin" || platform === "linux" || platform === "win32";
7883
}
7984

80-
function sendDesktopAppActivationRequest(input: {
81-
readonly address: string;
82-
readonly fallbackAddress?: string;
85+
async function sendDesktopAppActivationRequest(input: {
86+
readonly address: DesktopAppControlAddress;
87+
readonly fallbackAddress?: DesktopAppControlAddress;
88+
readonly userId: number | undefined;
8389
readonly request: DesktopAppActivationRequest;
8490
readonly timeoutMs?: number;
8591
}): Promise<DesktopAppActivationResponse> {
92+
if (input.address.directory !== null) {
93+
const stat = await NodeFSP.lstat(input.address.directory);
94+
if (
95+
!stat.isDirectory() ||
96+
input.userId === undefined ||
97+
stat.uid !== input.userId ||
98+
(stat.mode & 0o077) !== 0
99+
) {
100+
throw new Error("The desktop app socket directory is not private or owned by this user.");
101+
}
102+
}
86103
return new Promise((resolve, reject) => {
87-
const socket = NodeNet.createConnection(input.address);
104+
const socket = NodeNet.createConnection(input.address.address);
88105
socket.setEncoding("utf8");
89106
let buffer = "";
90107
let settled = false;
@@ -159,6 +176,7 @@ function sendDesktopAppActivationRequest(input: {
159176
resolve(
160177
sendDesktopAppActivationRequest({
161178
address: input.fallbackAddress,
179+
userId: input.userId,
162180
request: input.request,
163181
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
164182
}),
@@ -207,7 +225,7 @@ const runAppCommand = Effect.fn("cli.app")(function* (flags: {
207225
tempDir: NodeOS.tmpdir(),
208226
userId,
209227
joinPath: path.join,
210-
}).address;
228+
});
211229
const crypto = yield* Crypto.Crypto;
212230
const requestId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
213231
const request: DesktopAppActivationRequest = {
@@ -224,12 +242,16 @@ const runAppCommand = Effect.fn("cli.app")(function* (flags: {
224242
try: () =>
225243
sendDesktopAppActivationRequest({
226244
address,
245+
userId,
227246
...(fallbackAddress === undefined ? {} : { fallbackAddress }),
228247
request,
229248
}),
230249
catch: (cause) =>
231250
new DesktopAppUnreachableError({
232-
candidateAddresses: fallbackAddress === undefined ? [address] : [address, fallbackAddress],
251+
candidateAddresses:
252+
fallbackAddress === undefined
253+
? [address.address]
254+
: [address.address, fallbackAddress.address],
233255
requestId: request.requestId,
234256
workspaceRoot,
235257
cause,

‎packages/shared/src/desktopAppControl.test.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,30 @@ import { describe, expect, it } from "vite-plus/test";
33
import { resolveDesktopAppControlAddress } from "./desktopAppControl.ts";
44

55
describe("resolveDesktopAppControlAddress", () => {
6-
it("keeps Unix socket paths short and separates desktop state directories", () => {
6+
it.each([
7+
["linux", "/tmp", "/tmp/t3code-1000", 107],
8+
["linux", "/var/tmp/custom", "/var/tmp/custom/t3code-1000", 107],
9+
["linux", `/tmp/${"x".repeat(120)}`, "/tmp/t3code-1000", 107],
10+
["darwin", `/tmp/${"é".repeat(30)}`, "/tmp/t3code-1000", 103],
11+
["darwin", `/tmp/${"x".repeat(56)}`, `/tmp/${"x".repeat(56)}/t3code-1000`, 103],
12+
] as const)("keeps %s sockets short under %s", (platform, tempDir, directory, maxBytes) => {
713
const first = resolveDesktopAppControlAddress({
814
stateDir: `/home/user/${"long/".repeat(40)}userdata`,
9-
platform: "linux",
10-
tempDir: "/tmp",
15+
platform,
16+
tempDir,
1117
userId: 1000,
1218
joinPath: (...segments) => segments.join("/"),
1319
});
1420
const second = resolveDesktopAppControlAddress({
1521
stateDir: "/home/user/.t3/other/userdata",
16-
platform: "linux",
17-
tempDir: "/tmp",
22+
platform,
23+
tempDir,
1824
userId: 1000,
1925
joinPath: (...segments) => segments.join("/"),
2026
});
2127

22-
expect(first.directory).toBe("/tmp/t3code-1000");
23-
expect(first.address.length).toBeLessThan(108);
28+
expect(new TextEncoder().encode(first.address).byteLength).toBeLessThanOrEqual(maxBytes);
29+
expect(first.directory).toBe(directory);
2430
expect(first.address).not.toBe(second.address);
2531
});
2632

‎packages/shared/src/desktopAppControl.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,14 @@ export function resolveDesktopAppControlAddress(input: {
2929

3030
const userKey =
3131
input.userId === undefined ? shortHash(input.stateDir).slice(0, 12) : input.userId;
32-
const directory = input.joinPath(input.tempDir, `t3code-${userKey}`);
32+
const socketName = `${stateHash}.sock`;
33+
const maxPathBytes = input.platform === "linux" ? 107 : 103;
34+
let directory = input.joinPath(input.tempDir, `t3code-${userKey}`);
35+
if (new TextEncoder().encode(input.joinPath(directory, socketName)).byteLength > maxPathBytes) {
36+
directory = input.joinPath("/tmp", `t3code-${userKey}`);
37+
}
3338
return {
34-
address: input.joinPath(directory, `${stateHash}.sock`),
39+
address: input.joinPath(directory, socketName),
3540
directory,
3641
};
3742
}

0 commit comments

Comments
 (0)