Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as ChildProcess from "effect/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9
10import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
11import * as DesktopAssets from "./DesktopAssets.ts";
12import * as DesktopEnvironment from "./DesktopEnvironment.ts";
13import { makeComponentLogger } from "./DesktopObservability.ts";
14
15// AppImage integrators choose the .desktop filename, so setDesktopName cannot identify it for protocol registration.
16const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
17
18export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError<DesktopLinuxUrlHandlerRegistrationError>()(
19 "DesktopLinuxUrlHandlerRegistrationError",
20 {
21 step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
22 scheme: Schema.String,
23 desktopEntryPath: Schema.optionalKey(Schema.String),
24 exitCode: Schema.optionalKey(Schema.Number),
25 cause: Schema.optionalKey(Schema.Defect()),
26 },
27) {
28 override get message(): string {
29 const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
30 return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
31 }
32}
33
34const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
35
36export class DesktopLinuxUrlHandlerCacheRefreshError extends Schema.TaggedError<DesktopLinuxUrlHandlerCacheRefreshError>()(
37 "DesktopLinuxUrlHandlerCacheRefreshError",
38 {
39 applicationsDir: Schema.String,
40 exitCode: Schema.optionalKey(Schema.Number),
41 cause: Schema.optionalKey(Schema.Defect()),
42 },
43) {
44 override get message(): string {
45 const exitCode =
46 this.exitCode === undefined ? "" : `, update-desktop-database exit code ${this.exitCode}`;
47 return `Failed to refresh the desktop MIME cache at ${this.applicationsDir}${exitCode}.`;
48 }
49}
50
51const isCacheRefreshError = Schema.is(DesktopLinuxUrlHandlerCacheRefreshError);
52
53const escapeDesktopEntryString = (value: string): string =>
54 value
55 .replaceAll("\\", "\\\\")
56 .replaceAll("\n", "\\n")
57 .replaceAll("\r", "\\r")
58 .replaceAll("\t", "\\t");
59
60// Exec values undergo general unescaping then Exec unquoting; escape in reverse order.
61export function escapeDesktopEntryExecArgument(value: string): string {
62 const quoted = value
63 .replaceAll("\\", () => "\\\\")
64 .replaceAll("`", () => "\\`")
65 .replaceAll("$", () => "\\$")
66 .replaceAll('"', () => '\\"')
67 .replaceAll("%", () => "%%");
68 return escapeDesktopEntryString(`"${quoted}"`);
69}
70
71// Legacy xdg-open looks up the first Exec word without unquoting it.
72const escapeUrlHandlerExecTarget = (value: string): string =>
73 /[ \t\n"'\\><~|&;$*?#()`]/.test(value)
74 ? escapeDesktopEntryExecArgument(value)
75 : escapeDesktopEntryString(value.replaceAll("%", "%%"));
76
77// The AppImage integration entry owns the window identity. This
78// hidden URL-only entry must not compete with it for StartupWMClass matching.
79export function renderUrlHandlerDesktopEntry(input: {
80 readonly displayName: string;
81 readonly execTarget: string;
82 readonly scheme: string;
83 readonly iconPath?: string;
84}): string {
85 return [
86 "[Desktop Entry]",
87 "Type=Application",
88 `Name=${escapeDesktopEntryString(input.displayName)}`,
89 `Exec=${escapeUrlHandlerExecTarget(input.execTarget)} %U`,
90 ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]),
91 "Terminal=false",
92 "NoDisplay=true",
93 "StartupNotify=false",
94 `MimeType=x-scheme-handler/${input.scheme};`,
95 "",
96 ].join("\n");
97}
98
99function parseUrlHandlerExecTarget(entry: string): string | null {
100 const exec = /^Exec=(.*) %U$/mu.exec(entry)?.[1];
101 if (exec === undefined) return null;
102 const unescaped = exec.replace(/\\([\\nrt])/gu, (_, char: string) =>
103 char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char,
104 );
105 const quoted = /^"(.*)"$/su.exec(unescaped)?.[1];
106 return (
107 quoted === undefined ? unescaped : quoted.replace(/\\([\\`$"])/gu, (_, char: string) => char)
108 ).replaceAll("%%", "%");
109}
110
111export const appImageUrlHandlerPath = (
112 applicationsDir: string,
113 desktopEntryName: string,
114 join: (...segments: ReadonlyArray<string>) => string,
115): string => join(applicationsDir, "..", desktopEntryName.replace(/\.desktop$/u, ""), "open-url");
116
117const shellWord = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`;
118
119// The AppImage runtime mounts through setuid fusermount, which no_new_privs callers cannot run.
120// A running app's own mount needs no new one; a cold start extracts instead. /tmp paths outlive
121// the app and anyone can recreate them: reach the mount through /proc/<pid>/root, which stops
122// resolving when our process exits, and extract into a private directory.
123export function renderAppImageUrlHandler(input: {
124 readonly appImagePath: string;
125 readonly executablePath: string;
126 readonly pid: number;
127}): string {
128 return [
129 "#!/bin/sh",
130 "# Written by T3 Code: opens links in the AppImage without mounting it again.",
131 `app=${shellWord(input.appImagePath)}`,
132 `exe=${shellWord(input.executablePath)}`,
133 `pid=${input.pid}`,
134 'if [ -O "/proc/$pid" ] && [ "$(readlink "/proc/$pid/exe")" = "$exe" ]; then',
135 ' mount="/proc/$pid/root${exe%/*}"',
136 ' APPDIR="$mount" APPIMAGE="$app" "$mount/AppRun" "$@"',
137 " status=$?",
138 // 126/127: the app exited before AppRun started, so launch it instead.
139 ' [ "$status" -eq 126 ] || [ "$status" -eq 127 ] || exit "$status"',
140 "fi",
141 "if ! grep -q '^NoNewPrivs:[[:space:]]*1' /proc/self/status 2>/dev/null; then",
142 ' exec "$app" "$@"',
143 "fi",
144 "tmp=$(mktemp -d) || exit 1",
145 'TMPDIR="$tmp" APPIMAGE_EXTRACT_AND_RUN=1 "$app" "$@"',
146 "status=$?",
147 'rm -rf "$tmp"',
148 'exit "$status"',
149 "",
150 ].join("\n");
151}
152
153const APPIMAGE_NAME_VERSION = /\d+\.\d+\.\d+/u;
154
155// An updater from before version-free AppImage names deletes its own file and installs the update
156// beside it under the new name. The previous launch's entry still names the path launchers use.
157export function replacedVersionedAppImagePath(input: {
158 readonly previousEntry: string;
159 readonly appImagePath: string;
160}): string | null {
161 const previous = parseUrlHandlerExecTarget(input.previousEntry);
162 if (previous === null) return null;
163 const previousName = previous.slice(previous.lastIndexOf("/") + 1);
164 const currentName = input.appImagePath.slice(input.appImagePath.lastIndexOf("/") + 1);
165 return previous.startsWith("/") &&
166 previous.slice(0, -previousName.length) === input.appImagePath.slice(0, -currentName.length) &&
167 APPIMAGE_NAME_VERSION.test(previousName) &&
168 !APPIMAGE_NAME_VERSION.test(currentName)
169 ? previous
170 : null;
171}
172
173// Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive.
174const LINUX_THEME_ICON_SIZE = "256x256";
175
176function linuxThemeIconNames(desktopEntryName: string): readonly string[] {
177 const appId = desktopEntryName.replace(/\.desktop$/u, "");
178 return [...new Set([appId.toLowerCase(), appId])];
179}
180
181const sameBytes = (left: Uint8Array, right: Uint8Array): boolean =>
182 left.length === right.length && left.every((byte, index) => byte === right[index]);
183
184export class DesktopLinuxUrlHandler extends Context.Service<
185 DesktopLinuxUrlHandler,
186 {
187 readonly register: Effect.Effect<void>;
188 }
189>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
190
191/** @public */
192export const make = Effect.gen(function* () {
193 const environment = yield* DesktopEnvironment.DesktopEnvironment;
194 const fileSystem = yield* FileSystem.FileSystem;
195 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
196 const assets = yield* DesktopAssets.DesktopAssets;
197
198 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
199 const desktopEntryPath = environment.path.join(
200 environment.linuxApplicationsDir,
201 environment.linuxDesktopEntryName,
202 );
203 const appImageHandlerPath = appImageUrlHandlerPath(
204 environment.linuxApplicationsDir,
205 environment.linuxDesktopEntryName,
206 environment.path.join,
207 );
208 const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons");
209 const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`);
210 const hicolorDir = environment.path.join(iconsDir, "hicolor");
211 const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps");
212
213 const writeDesktopEntry = Effect.gen(function* () {
214 // Distribution packages that run on a shared Electron set
215 // T3CODE_DESKTOP_LAUNCHER_PATH, because process.execPath is that Electron.
216 // Inside the mounted AppImage, process.execPath points at a transient
217 // /tmp/.mount_* path — the handler must reach the AppImage itself.
218 const launcherPath = Option.getOrUndefined(environment.desktopLauncherPath);
219 const appImagePath = Option.getOrUndefined(environment.appImagePath);
220 let execTarget = launcherPath ?? process.execPath;
221 if (launcherPath === undefined && appImagePath !== undefined) {
222 const script = renderAppImageUrlHandler({
223 appImagePath,
224 executablePath: process.execPath,
225 pid: process.pid,
226 });
227 const currentScript = yield* fileSystem
228 .readFileString(appImageHandlerPath)
229 .pipe(Effect.orElseSucceed(() => null));
230 if (currentScript !== script) {
231 yield* fileSystem.makeDirectory(environment.path.dirname(appImageHandlerPath), {
232 recursive: true,
233 });
234 // A link opened now must not read a half-written script.
235 const staging = `${appImageHandlerPath}.${process.pid}.tmp`;
236 yield* fileSystem.writeFileString(staging, script, { mode: 0o755 });
237 yield* fileSystem.rename(staging, appImageHandlerPath);
238 }
239 execTarget = appImageHandlerPath;
240 }
241 const content = renderUrlHandlerDesktopEntry({
242 displayName: environment.displayName,
243 execTarget,
244 scheme,
245 ...(environment.isPackaged ? { iconPath } : {}),
246 });
247 // Avoid truncating the pre-ready entry while the portal may be reading it.
248 const existing = yield* fileSystem
249 .readFileString(desktopEntryPath)
250 .pipe(Effect.orElseSucceed(() => null));
251 if (existing === content) return;
252 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
253 yield* fileSystem.writeFileString(desktopEntryPath, content);
254 }).pipe(
255 Effect.mapError(
256 (cause) =>
257 new DesktopLinuxUrlHandlerRegistrationError({
258 step: "write-desktop-entry",
259 scheme,
260 desktopEntryPath,
261 cause,
262 }),
263 ),
264 );
265
266 const updateDesktopDatabase = Effect.scoped(
267 Effect.gen(function* () {
268 const command = ChildProcess.make(
269 "update-desktop-database",
270 [environment.linuxApplicationsDir],
271 {
272 stdin: "ignore",
273 stdout: "ignore",
274 stderr: "ignore",
275 forceKillAfter: "1 second",
276 },
277 );
278 const handle = yield* spawner.spawn(command);
279 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
280 if (exitCode !== 0) {
281 return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
282 applicationsDir: environment.linuxApplicationsDir,
283 exitCode,
284 });
285 }
286 }),
287 ).pipe(
288 Effect.mapError((error) =>
289 isCacheRefreshError(error)
290 ? error
291 : new DesktopLinuxUrlHandlerCacheRefreshError({
292 applicationsDir: environment.linuxApplicationsDir,
293 cause: error,
294 }),
295 ),
296 );
297
298 const refreshIconThemeCache = Effect.scoped(
299 Effect.gen(function* () {
300 const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], {
301 stdin: "ignore",
302 stdout: "ignore",
303 stderr: "ignore",
304 // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely.
305 forceKillAfter: "1 second",
306 });
307 const handle = yield* spawner.spawn(command);
308 return yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
309 }),
310 );
311
312 const modifiedAt = (filePath: string) =>
313 fileSystem
314 .stat(filePath)
315 .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0));
316
317 const installThemeIcons = Effect.gen(function* () {
318 const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`);
319 if (Option.isNone(source)) return;
320 const icon = yield* fileSystem.readFile(source.value);
321 const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) =>
322 environment.path.join(themeIconDir, `${name}.png`),
323 );
324 let changed = false;
325 for (const target of targets) {
326 const current = yield* fileSystem.readFile(target).pipe(Effect.option);
327 if (Option.isSome(current) && sameBytes(current.value, icon)) continue;
328 yield* fileSystem.makeDirectory(themeIconDir, { recursive: true });
329 yield* fileSystem.writeFile(target, icon);
330 changed = true;
331 }
332 // Creating a cache would leave GTK reading stale icons from other installers.
333 // A newer icon retries a refresh that failed on an earlier launch.
334 const cachePath = environment.path.join(hicolorDir, "icon-theme.cache");
335 const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option);
336 if (Option.isNone(cachedAt)) return;
337 let stale = changed;
338 for (const target of targets) {
339 if (stale) break;
340 if ((yield* modifiedAt(target)) > cachedAt.value) stale = true;
341 }
342 if (!stale) return;
343 const exitCode = yield* refreshIconThemeCache;
344 if (exitCode !== 0) {
345 yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode });
346 }
347 }).pipe(
348 Effect.catch((error) =>
349 logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }),
350 ),
351 );
352
353 const setDefaultHandler = Effect.scoped(
354 Effect.gen(function* () {
355 const command = ChildProcess.make(
356 "xdg-mime",
357 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
358 {
359 stdin: "ignore",
360 stdout: "ignore",
361 stderr: "ignore",
362 forceKillAfter: "1 second",
363 },
364 );
365 const handle = yield* spawner.spawn(command);
366 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
367 if (exitCode !== 0) {
368 return yield* new DesktopLinuxUrlHandlerRegistrationError({
369 step: "set-default-handler",
370 scheme,
371 exitCode,
372 });
373 }
374 }),
375 ).pipe(
376 Effect.mapError((error) =>
377 isRegistrationError(error)
378 ? error
379 : new DesktopLinuxUrlHandlerRegistrationError({
380 step: "set-default-handler",
381 scheme,
382 cause: error,
383 }),
384 ),
385 );
386
387 const register = Effect.gen(function* () {
388 if (environment.platform !== "linux") {
389 return;
390 }
391 yield* writeDesktopEntry;
392 if (!environment.isPackaged) return;
393
394 yield* Effect.gen(function* () {
395 const { png } = yield* assets.iconPaths;
396 if (Option.isNone(png)) return;
397 // The AppImage mount is temporary; the chooser needs the icon after exit.
398 yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
399 // Electron's copyFile from app.asar extracts to a temp file it never deletes.
400 yield* fileSystem.writeFile(iconPath, yield* fileSystem.readFile(png.value));
401 }).pipe(
402 Effect.catch((error) =>
403 logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }),
404 ),
405 );
406
407 yield* installThemeIcons;
408
409 yield* updateDesktopDatabase.pipe(
410 // GIO verifies scheme associations through mimeinfo.cache. A missing cache updater must not block xdg-mime.
411 Effect.catch((error) =>
412 logWarning("desktop MIME cache refresh failed", {
413 applicationsDir: environment.linuxApplicationsDir,
414 message: error.message,
415 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
416 }),
417 ),
418 );
419
420 yield* setDefaultHandler;
421 yield* logInfo("registered URL scheme handler", { scheme });
422 }).pipe(
423 Effect.catch((error) =>
424 logWarning("URL scheme handler registration failed", {
425 scheme,
426 step: error.step,
427 message: error.message,
428 ...(error.desktopEntryPath === undefined
429 ? {}
430 : { desktopEntryPath: error.desktopEntryPath }),
431 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
432 }),
433 ),
434 Effect.withSpan("desktop.linuxUrlHandler.register"),
435 );
436
437 return DesktopLinuxUrlHandler.of({ register });
438});
439
440export const layer = Layer.effect(DesktopLinuxUrlHandler, make);