Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopAppActivation.ts

393 lines13.5 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Local socket ownership checks need lstat, an atomic rename, and a directory watch at the Node adapter boundary.
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4import * as NodeFSP from "node:fs/promises";
5import * as NodeNet from "node:net";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8​
9import {
10 DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
11 DesktopAppActivationRequest,
12 type DesktopAppActivationResponse,
13} from "@t3tools/contracts";
14import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22import * as Scope from "effect/Scope";
23​
24import type * as Electron from "electron";
25​
26import * as ElectronWindow from "../electron/ElectronWindow.ts";
27import { DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL } from "../ipc/channels.ts";
28import * as DesktopWindow from "../window/DesktopWindow.ts";
29import { DesktopAppActivationBroker } from "./DesktopAppActivationBroker.ts";
30import * as DesktopEnvironment from "./DesktopEnvironment.ts";
31import { makeComponentLogger } from "./DesktopObservability.ts";
32​
33const MAX_REQUEST_BYTES = 64 * 1024;
34const REQUEST_TIMEOUT_MS = 15_000;
35const isDesktopAppActivationRequest = Schema.is(DesktopAppActivationRequest);
36​
37export class DesktopAppActivationStartError extends Schema.TaggedError<DesktopAppActivationStartError>()(
38 "DesktopAppActivationStartError",
39 {
40 address: Schema.String,
41 cause: Schema.Defect(),
42 },
43) {
44 override get message(): string {
45 return `Could not start the desktop app control socket at ${this.address}.`;
46 }
48​
49interface RunningControlServer {
50 readonly reclaim: () => Promise<void>;
51 readonly close: () => Promise<void>;
53​
54function invalidResponse(requestId: string, message: string): DesktopAppActivationResponse {
55 return {
56 version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
57 requestId,
58 ok: false,
59 code: "invalid-request",
60 message,
61 };
63​
64function requestIdFromUnknown(value: unknown): string {
65 if (
66 typeof value === "object" &&
67 value !== null &&
68 "requestId" in value &&
69 typeof value.requestId === "string" &&
70 value.requestId.trim().length > 0
71 ) {
72 return value.requestId;
73 }
74 return "invalid-request";
76​
77async function prepareUnixDirectory(input: {
78 readonly directory: string;
79 readonly userId: number | undefined;
80}): Promise<boolean> {
81 const created = await NodeFSP.mkdir(input.directory, { recursive: true, mode: 0o700 });
82 const stat = await NodeFSP.lstat(input.directory);
83 if (!stat.isDirectory() || stat.isSymbolicLink()) {
84 throw new Error(`${input.directory} is not a directory.`);
85 }
86 if (input.userId !== undefined && stat.uid !== input.userId) {
87 throw new Error(`${input.directory} is owned by another user.`);
88 }
89 await NodeFSP.chmod(input.directory, 0o700);
90 return created !== undefined;
92​
93async function inodeAt(path: string): Promise<number | null> {
94 return NodeFSP.lstat(path).then(
95 (stat) => stat.ino,
96 (error: NodeJS.ErrnoException) => {
97 if (error.code === "ENOENT") return null;
98 throw error;
99 },
100 );
102​
103function closeServer(server: NodeNet.Server): Promise<void> {
104 return new Promise((resolve) => server.close(() => resolve()));
106​
107export async function startDesktopAppControlServer(input: {
108 readonly address: string;
109 readonly directory: string | null;
110 readonly userId: number | undefined;
111 readonly handle: (request: DesktopAppActivationRequest) => Promise<DesktopAppActivationResponse>;
112 readonly cancel: (requestId: string) => void;
113 readonly onReclaimError: (error: unknown) => void;
114}): Promise<RunningControlServer> {
115 const sockets = new Set<NodeNet.Socket>();
116 const handleConnection = (socket: NodeNet.Socket) => {
117 sockets.add(socket);
118 socket.setEncoding("utf8");
119 let buffer = "";
120 let handled = false;
121 let responseSent = false;
122 let activeRequestId: string | null = null;
123​
124 socket.setTimeout(5_000, () => socket.destroy());
125​
126 const finish = (response: DesktopAppActivationResponse) => {
127 responseSent = true;
128 if (!socket.destroyed) socket.end(`${JSON.stringify(response)}\n`);
129 };
130​
131 socket.on("data", (chunk) => {
132 if (handled) return;
133 buffer += chunk;
134 if (Buffer.byteLength(buffer, "utf8") > MAX_REQUEST_BYTES) {
135 handled = true;
136 finish(invalidResponse("invalid-request", "The desktop app request is too large."));
137 return;
138 }
139​
140 const newline = buffer.indexOf("\n");
141 if (newline === -1) return;
142 handled = true;
143 socket.setTimeout(0);
144 const line = buffer.slice(0, newline);
145 let parsed: unknown;
146 try {
147 parsed = JSON.parse(line);
148 } catch {
149 finish(invalidResponse("invalid-request", "The desktop app request is not valid JSON."));
150 return;
151 }
152​
153 if (!isDesktopAppActivationRequest(parsed)) {
154 finish(
155 invalidResponse(requestIdFromUnknown(parsed), "The desktop app request is invalid."),
156 );
157 return;
158 }
159 activeRequestId = parsed.requestId;
160 void input.handle(parsed).then(finish, () => {
161 finish(
162 invalidResponse(parsed.requestId, "T3 Code could not process the desktop app request."),
163 );
164 });
165 });
166 socket.on("error", () => socket.destroy());
167 socket.on("close", () => {
168 sockets.delete(socket);
169 if (!responseSent && activeRequestId !== null) input.cancel(activeRequestId);
170 });
171 };
172​
173 const listen = (address: string) =>
174 new Promise<NodeNet.Server>((resolve, reject) => {
175 const server = NodeNet.createServer(handleConnection);
176 const onError = (error: Error) => {
177 server.removeListener("listening", onListening);
178 reject(error);
179 };
180 const onListening = () => {
181 server.removeListener("error", onError);
182 resolve(server);
183 };
184 server.once("error", onError);
185 server.once("listening", onListening);
186 server.listen(address);
187 });
188​
189 // Closing a Unix socket server unlinks the path it was bound to, even when
190 // another app's socket lives there now. Bind a staging path and move it onto
191 // the address instead, so a later close only unlinks the staging path, which
192 // is already gone.
193​
194 const bindUnix = async (directory: string, mode: "take-over" | "claim-free") => {
195 const staging = NodePath.join(directory, `${NodeCrypto.randomBytes(6).toString("hex")}.tmp`);
196 const server = await listen(staging);
197 try {
198 await NodeFSP.chmod(staging, 0o600);
199 const inode = await inodeAt(staging);
200 if (mode === "take-over") {
201 await NodeFSP.rename(staging, input.address);
202 } else {
203 await NodeFSP.link(staging, input.address);
204 await NodeFSP.unlink(staging);
205 }
206 return { server, inode };
207 } catch (error) {
208 await closeServer(server);
209 throw error;
210 }
211 };
212​
213 let server: NodeNet.Server;
214 let inode: number | null = null;
215 if (input.directory === null) {
216 // Named pipes close with the app that owns them, so no other app can remove this one.
217 server = await listen(input.address);
218 } else {
219 await prepareUnixDirectory({ directory: input.directory, userId: input.userId });
220 ({ server, inode } = await bindUnix(input.directory, "take-over"));
221 }
222​
223 let closed = false;
224 const reclaimOnce = async () => {
225 // Never replace a socket that exists, so two apps cannot trade the path back and forth.
226 if (closed || input.directory === null || (await inodeAt(input.address)) !== null) return;
227 if (await prepareUnixDirectory({ directory: input.directory, userId: input.userId })) {
228 // A watch follows the directory's inode, so a recreated directory needs a new one.
229 watchDirectory(input.directory);
230 }
231 const next = await bindUnix(input.directory, "claim-free").catch(
232 (error: NodeJS.ErrnoException) => {
233 if (error.code === "EEXIST") return null;
234 throw error;
235 },
236 );
237 if (next === null) return;
238 const previous = server;
239 ({ server, inode } = next);
240 previous.close();
241 };
242 let pendingReclaim = Promise.resolve();
243 const reclaim = () => {
244 const run = pendingReclaim.then(reclaimOnce);
245 pendingReclaim = run.catch(() => undefined);
246 return run;
247 };
248 let watcher: NodeFS.FSWatcher | null = null;
249 const watchDirectory = (directory: string) => {
250 watcher?.close();
251 watcher = null;
252 try {
253 watcher = NodeFS.watch(directory, { persistent: false }, () => {
254 reclaim().catch(input.onReclaimError);
255 });
256 watcher.on("error", input.onReclaimError);
257 } catch (error) {
258 input.onReclaimError(error);
259 }
260 };
261 if (input.directory !== null) {
262 watchDirectory(input.directory);
263 // Catch a removal that happened before the watcher started.
264 reclaim().catch(input.onReclaimError);
265 }
266​
267 return {
268 reclaim,
269 close: async () => {
270 if (closed) return;
271 closed = true;
272 // A running reclaim can replace the watcher, so close the watcher after it.
273 await pendingReclaim;
274 watcher?.close();
275 for (const socket of sockets) socket.destroy();
276 await closeServer(server);
277 server.removeAllListeners();
278 if (inode !== null && (await inodeAt(input.address)) === inode) {
279 await NodeFSP.unlink(input.address).catch((error: NodeJS.ErrnoException) => {
280 if (error.code !== "ENOENT") throw error;
281 });
282 }
283 },
284 };
286​
287export class DesktopAppActivation extends Context.Service<
288 DesktopAppActivation,
289 {
290 readonly start: Effect.Effect<void, DesktopAppActivationStartError, Scope.Scope>;
291 readonly setRendererReady: (ready: boolean) => Effect.Effect<void>;
292 readonly complete: (response: DesktopAppActivationResponse) => Effect.Effect<void>;
293 }
294>()("@t3tools/desktop/app/DesktopAppActivation") {}
295​
296const { logWarning } = makeComponentLogger("desktop-app-activation");
297​
298/** @public */
299export const make = Effect.gen(function* () {
300 const desktopEnvironment = yield* DesktopEnvironment.DesktopEnvironment;
301 const desktopWindow = yield* DesktopWindow.DesktopWindow;
302 const electronWindow = yield* ElectronWindow.ElectronWindow;
303 const path = yield* Path.Path;
304 const userId = yield* HostProcess.UserId;
305 const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());
306 const address = resolveDesktopAppControlAddress({
307 stateDir: path.resolve(desktopEnvironment.stateDir),
308 platform: desktopEnvironment.platform,
309 tempDir: NodeOS.tmpdir(),
310 userId,
311 joinPath: path.join,
312 });
313 let registeredWebContents: Electron.WebContents | null = null;
314 let detachRendererListeners: (() => void) | null = null;
315​
316 const broker = new DesktopAppActivationBroker({
317 requestTimeoutMs: REQUEST_TIMEOUT_MS,
318 activate: () => {
319 void runPromise(
320 desktopWindow.activate.pipe(
321 Effect.catchCause((cause) => logWarning("failed to focus the desktop window", { cause })),
322 ),
323 );
324 },
325 });
326​
327 const clearRegisteredRenderer = () => {
328 detachRendererListeners?.();
329 detachRendererListeners = null;
330 registeredWebContents = null;
331 broker.clearRenderer();
332 };
333​
334 return DesktopAppActivation.of({
335 start: Effect.acquireRelease(
336 Effect.tryPromise({
337 try: () =>
338 startDesktopAppControlServer({
339 ...address,
340 userId,
341 handle: (request) => broker.request(request),
342 cancel: (requestId) => broker.cancel(requestId),
343 onReclaimError: (cause) =>
344 void runPromise(
345 logWarning("failed to restore the desktop app control socket", { cause }),
346 ),
347 }),
348 catch: (cause) => new DesktopAppActivationStartError({ address: address.address, cause }),
349 }),
350 (server) =>
351 Effect.promise(() => server.close()).pipe(
352 Effect.catchCause((cause) =>
353 logWarning("failed to close the desktop app control socket", { cause }),
354 ),
355 Effect.ensuring(Effect.sync(() => broker.close())),
356 ),
357 ).pipe(Effect.asVoid),
358 setRendererReady: Effect.fn("DesktopAppActivation.setRendererReady")(function* (ready) {
359 if (!ready) {
360 clearRegisteredRenderer();
361 return;
362 }
363 const main = yield* electronWindow.main;
364 if (Option.isNone(main)) return;
365 const webContents = main.value.webContents;
366 if (webContents.isDestroyed()) return;
367​
368 if (registeredWebContents !== webContents) {
369 clearRegisteredRenderer();
370 registeredWebContents = webContents;
371 const onUnavailable = () => clearRegisteredRenderer();
372 const onNavigation = (
373 event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
374 ) => {
375 if (event.isMainFrame && !event.isSameDocument) clearRegisteredRenderer();
376 };
377 webContents.on("did-start-navigation", onNavigation);
378 webContents.once("destroyed", onUnavailable);
379 detachRendererListeners = () => {
380 webContents.removeListener("did-start-navigation", onNavigation);
381 webContents.removeListener("destroyed", onUnavailable);
382 };
383 }
384​
385 broker.registerRenderer((request) => {
386 webContents.send(DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL, request);
387 });
388 }),
389 complete: (response) => Effect.sync(() => broker.complete(response)),
390 });
391});
392​
393export const layer = Layer.effect(DesktopAppActivation, make);