import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import * as DesktopAssets from "./DesktopAssets.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import { makeComponentLogger } from "./DesktopObservability.ts"; // AppImage integrators choose the .desktop filename, so setDesktopName cannot identify it for protocol registration. const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler"); export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError()( "DesktopLinuxUrlHandlerRegistrationError", { step: Schema.Literals(["write-desktop-entry", "set-default-handler"]), scheme: Schema.String, desktopEntryPath: Schema.optionalKey(Schema.String), exitCode: Schema.optionalKey(Schema.Number), cause: Schema.optionalKey(Schema.Defect()), }, ) { override get message(): string { const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`; return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`; } } const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError); export class DesktopLinuxUrlHandlerCacheRefreshError extends Schema.TaggedError()( "DesktopLinuxUrlHandlerCacheRefreshError", { applicationsDir: Schema.String, exitCode: Schema.optionalKey(Schema.Number), cause: Schema.optionalKey(Schema.Defect()), }, ) { override get message(): string { const exitCode = this.exitCode === undefined ? "" : `, update-desktop-database exit code ${this.exitCode}`; return `Failed to refresh the desktop MIME cache at ${this.applicationsDir}${exitCode}.`; } } const isCacheRefreshError = Schema.is(DesktopLinuxUrlHandlerCacheRefreshError); const escapeDesktopEntryString = (value: string): string => value .replaceAll("\\", "\\\\") .replaceAll("\n", "\\n") .replaceAll("\r", "\\r") .replaceAll("\t", "\\t"); // Exec values undergo general unescaping then Exec unquoting; escape in reverse order. export function escapeDesktopEntryExecArgument(value: string): string { const quoted = value .replaceAll("\\", () => "\\\\") .replaceAll("`", () => "\\`") .replaceAll("$", () => "\\$") .replaceAll('"', () => '\\"') .replaceAll("%", () => "%%"); return escapeDesktopEntryString(`"${quoted}"`); } // Legacy xdg-open looks up the first Exec word without unquoting it. const escapeUrlHandlerExecTarget = (value: string): string => /[ \t\n"'\\><~|&;$*?#()`]/.test(value) ? escapeDesktopEntryExecArgument(value) : escapeDesktopEntryString(value.replaceAll("%", "%%")); // The AppImage integration entry owns the window identity. This // hidden URL-only entry must not compete with it for StartupWMClass matching. export function renderUrlHandlerDesktopEntry(input: { readonly displayName: string; readonly execTarget: string; readonly scheme: string; readonly iconPath?: string; }): string { return [ "[Desktop Entry]", "Type=Application", `Name=${escapeDesktopEntryString(input.displayName)}`, `Exec=${escapeUrlHandlerExecTarget(input.execTarget)} %U`, ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]), "Terminal=false", "NoDisplay=true", "StartupNotify=false", `MimeType=x-scheme-handler/${input.scheme};`, "", ].join("\n"); } function parseUrlHandlerExecTarget(entry: string): string | null { const exec = /^Exec=(.*) %U$/mu.exec(entry)?.[1]; if (exec === undefined) return null; const unescaped = exec.replace(/\\([\\nrt])/gu, (_, char: string) => char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char, ); const quoted = /^"(.*)"$/su.exec(unescaped)?.[1]; return ( quoted === undefined ? unescaped : quoted.replace(/\\([\\`$"])/gu, (_, char: string) => char) ).replaceAll("%%", "%"); } export const appImageUrlHandlerPath = ( applicationsDir: string, desktopEntryName: string, join: (...segments: ReadonlyArray) => string, ): string => join(applicationsDir, "..", desktopEntryName.replace(/\.desktop$/u, ""), "open-url"); const shellWord = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`; // The AppImage runtime mounts through setuid fusermount, which no_new_privs callers cannot run. // A running app's own mount needs no new one; a cold start extracts instead. /tmp paths outlive // the app and anyone can recreate them: reach the mount through /proc//root, which stops // resolving when our process exits, and extract into a private directory. export function renderAppImageUrlHandler(input: { readonly appImagePath: string; readonly executablePath: string; readonly pid: number; }): string { return [ "#!/bin/sh", "# Written by T3 Code: opens links in the AppImage without mounting it again.", `app=${shellWord(input.appImagePath)}`, `exe=${shellWord(input.executablePath)}`, `pid=${input.pid}`, 'if [ -O "/proc/$pid" ] && [ "$(readlink "/proc/$pid/exe")" = "$exe" ]; then', ' mount="/proc/$pid/root${exe%/*}"', ' APPDIR="$mount" APPIMAGE="$app" "$mount/AppRun" "$@"', " status=$?", // 126/127: the app exited before AppRun started, so launch it instead. ' [ "$status" -eq 126 ] || [ "$status" -eq 127 ] || exit "$status"', "fi", "if ! grep -q '^NoNewPrivs:[[:space:]]*1' /proc/self/status 2>/dev/null; then", ' exec "$app" "$@"', "fi", "tmp=$(mktemp -d) || exit 1", 'TMPDIR="$tmp" APPIMAGE_EXTRACT_AND_RUN=1 "$app" "$@"', "status=$?", 'rm -rf "$tmp"', 'exit "$status"', "", ].join("\n"); } const APPIMAGE_NAME_VERSION = /\d+\.\d+\.\d+/u; // An updater from before version-free AppImage names deletes its own file and installs the update // beside it under the new name. The previous launch's entry still names the path launchers use. export function replacedVersionedAppImagePath(input: { readonly previousEntry: string; readonly appImagePath: string; }): string | null { const previous = parseUrlHandlerExecTarget(input.previousEntry); if (previous === null) return null; const previousName = previous.slice(previous.lastIndexOf("/") + 1); const currentName = input.appImagePath.slice(input.appImagePath.lastIndexOf("/") + 1); return previous.startsWith("/") && previous.slice(0, -previousName.length) === input.appImagePath.slice(0, -currentName.length) && APPIMAGE_NAME_VERSION.test(previousName) && !APPIMAGE_NAME_VERSION.test(currentName) ? previous : null; } // Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive. const LINUX_THEME_ICON_SIZE = "256x256"; function linuxThemeIconNames(desktopEntryName: string): readonly string[] { const appId = desktopEntryName.replace(/\.desktop$/u, ""); return [...new Set([appId.toLowerCase(), appId])]; } const sameBytes = (left: Uint8Array, right: Uint8Array): boolean => left.length === right.length && left.every((byte, index) => byte === right[index]); export class DesktopLinuxUrlHandler extends Context.Service< DesktopLinuxUrlHandler, { readonly register: Effect.Effect; } >()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {} /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const assets = yield* DesktopAssets.DesktopAssets; const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment); const desktopEntryPath = environment.path.join( environment.linuxApplicationsDir, environment.linuxDesktopEntryName, ); const appImageHandlerPath = appImageUrlHandlerPath( environment.linuxApplicationsDir, environment.linuxDesktopEntryName, environment.path.join, ); const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons"); const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`); const hicolorDir = environment.path.join(iconsDir, "hicolor"); const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps"); const writeDesktopEntry = Effect.gen(function* () { // Distribution packages that run on a shared Electron set // T3CODE_DESKTOP_LAUNCHER_PATH, because process.execPath is that Electron. // Inside the mounted AppImage, process.execPath points at a transient // /tmp/.mount_* path — the handler must reach the AppImage itself. const launcherPath = Option.getOrUndefined(environment.desktopLauncherPath); const appImagePath = Option.getOrUndefined(environment.appImagePath); let execTarget = launcherPath ?? process.execPath; if (launcherPath === undefined && appImagePath !== undefined) { const script = renderAppImageUrlHandler({ appImagePath, executablePath: process.execPath, pid: process.pid, }); const currentScript = yield* fileSystem .readFileString(appImageHandlerPath) .pipe(Effect.orElseSucceed(() => null)); if (currentScript !== script) { yield* fileSystem.makeDirectory(environment.path.dirname(appImageHandlerPath), { recursive: true, }); // A link opened now must not read a half-written script. const staging = `${appImageHandlerPath}.${process.pid}.tmp`; yield* fileSystem.writeFileString(staging, script, { mode: 0o755 }); yield* fileSystem.rename(staging, appImageHandlerPath); } execTarget = appImageHandlerPath; } const content = renderUrlHandlerDesktopEntry({ displayName: environment.displayName, execTarget, scheme, ...(environment.isPackaged ? { iconPath } : {}), }); // Avoid truncating the pre-ready entry while the portal may be reading it. const existing = yield* fileSystem .readFileString(desktopEntryPath) .pipe(Effect.orElseSucceed(() => null)); if (existing === content) return; yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true }); yield* fileSystem.writeFileString(desktopEntryPath, content); }).pipe( Effect.mapError( (cause) => new DesktopLinuxUrlHandlerRegistrationError({ step: "write-desktop-entry", scheme, desktopEntryPath, cause, }), ), ); const updateDesktopDatabase = Effect.scoped( Effect.gen(function* () { const command = ChildProcess.make( "update-desktop-database", [environment.linuxApplicationsDir], { stdin: "ignore", stdout: "ignore", stderr: "ignore", forceKillAfter: "1 second", }, ); const handle = yield* spawner.spawn(command); const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds")); if (exitCode !== 0) { return yield* new DesktopLinuxUrlHandlerCacheRefreshError({ applicationsDir: environment.linuxApplicationsDir, exitCode, }); } }), ).pipe( Effect.mapError((error) => isCacheRefreshError(error) ? error : new DesktopLinuxUrlHandlerCacheRefreshError({ applicationsDir: environment.linuxApplicationsDir, cause: error, }), ), ); const refreshIconThemeCache = Effect.scoped( Effect.gen(function* () { const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], { stdin: "ignore", stdout: "ignore", stderr: "ignore", // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely. forceKillAfter: "1 second", }); const handle = yield* spawner.spawn(command); return yield* handle.exitCode.pipe(Effect.timeout("5 seconds")); }), ); const modifiedAt = (filePath: string) => fileSystem .stat(filePath) .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0)); const installThemeIcons = Effect.gen(function* () { const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`); if (Option.isNone(source)) return; const icon = yield* fileSystem.readFile(source.value); const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) => environment.path.join(themeIconDir, `${name}.png`), ); let changed = false; for (const target of targets) { const current = yield* fileSystem.readFile(target).pipe(Effect.option); if (Option.isSome(current) && sameBytes(current.value, icon)) continue; yield* fileSystem.makeDirectory(themeIconDir, { recursive: true }); yield* fileSystem.writeFile(target, icon); changed = true; } // Creating a cache would leave GTK reading stale icons from other installers. // A newer icon retries a refresh that failed on an earlier launch. const cachePath = environment.path.join(hicolorDir, "icon-theme.cache"); const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option); if (Option.isNone(cachedAt)) return; let stale = changed; for (const target of targets) { if (stale) break; if ((yield* modifiedAt(target)) > cachedAt.value) stale = true; } if (!stale) return; const exitCode = yield* refreshIconThemeCache; if (exitCode !== 0) { yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode }); } }).pipe( Effect.catch((error) => logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }), ), ); const setDefaultHandler = Effect.scoped( Effect.gen(function* () { const command = ChildProcess.make( "xdg-mime", ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`], { stdin: "ignore", stdout: "ignore", stderr: "ignore", forceKillAfter: "1 second", }, ); const handle = yield* spawner.spawn(command); const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds")); if (exitCode !== 0) { return yield* new DesktopLinuxUrlHandlerRegistrationError({ step: "set-default-handler", scheme, exitCode, }); } }), ).pipe( Effect.mapError((error) => isRegistrationError(error) ? error : new DesktopLinuxUrlHandlerRegistrationError({ step: "set-default-handler", scheme, cause: error, }), ), ); const register = Effect.gen(function* () { if (environment.platform !== "linux") { return; } yield* writeDesktopEntry; if (!environment.isPackaged) return; yield* Effect.gen(function* () { const { png } = yield* assets.iconPaths; if (Option.isNone(png)) return; // The AppImage mount is temporary; the chooser needs the icon after exit. yield* fileSystem.makeDirectory(iconsDir, { recursive: true }); // Electron's copyFile from app.asar extracts to a temp file it never deletes. yield* fileSystem.writeFile(iconPath, yield* fileSystem.readFile(png.value)); }).pipe( Effect.catch((error) => logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }), ), ); yield* installThemeIcons; yield* updateDesktopDatabase.pipe( // GIO verifies scheme associations through mimeinfo.cache. A missing cache updater must not block xdg-mime. Effect.catch((error) => logWarning("desktop MIME cache refresh failed", { applicationsDir: environment.linuxApplicationsDir, message: error.message, ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }), }), ), ); yield* setDefaultHandler; yield* logInfo("registered URL scheme handler", { scheme }); }).pipe( Effect.catch((error) => logWarning("URL scheme handler registration failed", { scheme, step: error.step, message: error.message, ...(error.desktopEntryPath === undefined ? {} : { desktopEntryPath: error.desktopEntryPath }), ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }), }), ), Effect.withSpan("desktop.linuxUrlHandler.register"), ); return DesktopLinuxUrlHandler.of({ register }); }); export const layer = Layer.effect(DesktopLinuxUrlHandler, make);