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// Linux ships as an AppImage, so the .desktop entry users end up with is
16// created by whatever integration tool they use (AppImageLauncher names it
17// appimagekit_<hash>-….desktop) and its filename is not under our control.
18// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
19// setDesktopName, which cannot match those files — so the browser keeps
20// prompting "Choose an application" for every OAuth callback.
21const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
22
23export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError<DesktopLinuxUrlHandlerRegistrationError>()(
24 "DesktopLinuxUrlHandlerRegistrationError",
25 {
26 step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
27 scheme: Schema.String,
28 desktopEntryPath: Schema.optionalKey(Schema.String),
29 exitCode: Schema.optionalKey(Schema.Number),
30 cause: Schema.optionalKey(Schema.Defect()),
31 },
32) {
33 override get message(): string {
34 const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
35 return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
36 }
37}
38
39const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
40
41export class DesktopLinuxUrlHandlerCacheRefreshError extends Schema.TaggedError<DesktopLinuxUrlHandlerCacheRefreshError>()(
42 "DesktopLinuxUrlHandlerCacheRefreshError",
43 {
44 applicationsDir: Schema.String,
45 exitCode: Schema.optionalKey(Schema.Number),
46 cause: Schema.optionalKey(Schema.Defect()),
47 },
48) {
49 override get message(): string {
50 const exitCode =
51 this.exitCode === undefined ? "" : `, update-desktop-database exit code ${this.exitCode}`;
52 return `Failed to refresh the desktop MIME cache at ${this.applicationsDir}${exitCode}.`;
53 }
54}
55
56const isCacheRefreshError = Schema.is(DesktopLinuxUrlHandlerCacheRefreshError);
57
58const escapeDesktopEntryString = (value: string): string =>
59 value
60 .replaceAll("\\", "\\\\")
61 .replaceAll("\n", "\\n")
62 .replaceAll("\r", "\\r")
63 .replaceAll("\t", "\\t");
64
65// Exec values are unescaped twice by implementations: first the general
66// string-value rules, then the Exec quoting rules — so writing composes the
67// layers in reverse.
68export function escapeDesktopEntryExecArgument(value: string): string {
69 const quoted = value
70 .replaceAll("\\", () => "\\\\")
71 .replaceAll("`", () => "\\`")
72 .replaceAll("$", () => "\\$")
73 .replaceAll('"', () => '\\"')
74 .replaceAll("%", () => "%%");
75 return escapeDesktopEntryString(`"${quoted}"`);
76}
77
78// Legacy xdg-open looks up the first Exec word without unquoting it.
79const escapeUrlHandlerExecTarget = (value: string): string =>
80 /[ \t\n"'\\><~|&;$*?#()`]/.test(value)
81 ? escapeDesktopEntryExecArgument(value)
82 : escapeDesktopEntryString(value.replaceAll("%", "%%"));
83
84// The AppImage integration entry owns the window identity. This
85// hidden URL-only entry must not compete with it for StartupWMClass matching.
86export function renderUrlHandlerDesktopEntry(input: {
87 readonly displayName: string;
88 readonly execTarget: string;
89 readonly scheme: string;
90 readonly iconPath?: string;
91}): string {
92 return [
93 "[Desktop Entry]",
94 "Type=Application",
95 `Name=${escapeDesktopEntryString(input.displayName)}`,
96 `Exec=${escapeUrlHandlerExecTarget(input.execTarget)} %U`,
97 ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]),
98 "Terminal=false",
99 "NoDisplay=true",
100 "StartupNotify=false",
101 `MimeType=x-scheme-handler/${input.scheme};`,
102 "",
103 ].join("\n");
104}
105
106// Some docks and bars look the Wayland app id up in the icon theme when no
107// visible desktop entry matches the window, for example an AppImage run without
108// integration. Theme lookups are case-sensitive, so install both spellings.
109const LINUX_THEME_ICON_SIZE = "256x256";
110
111function linuxThemeIconNames(desktopEntryName: string): readonly string[] {
112 const appId = desktopEntryName.replace(/\.desktop$/u, "");
113 return [...new Set([appId.toLowerCase(), appId])];
114}
115
116const sameBytes = (left: Uint8Array, right: Uint8Array): boolean =>
117 left.length === right.length && left.every((byte, index) => byte === right[index]);
118
119export class DesktopLinuxUrlHandler extends Context.Service<
120 DesktopLinuxUrlHandler,
121 {
122 readonly register: Effect.Effect<void>;
123 }
124>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
125
126/** @public Service construction is part of the canonical Effect module API. */
127export const make = Effect.gen(function* () {
128 const environment = yield* DesktopEnvironment.DesktopEnvironment;
129 const fileSystem = yield* FileSystem.FileSystem;
130 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
131 const assets = yield* DesktopAssets.DesktopAssets;
132
133 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
134 const desktopEntryPath = environment.path.join(
135 environment.linuxApplicationsDir,
136 environment.linuxDesktopEntryName,
137 );
138 const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons");
139 const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`);
140 const hicolorDir = environment.path.join(iconsDir, "hicolor");
141 const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps");
142
143 const writeDesktopEntry = Effect.gen(function* () {
144 // Inside the mounted AppImage, process.execPath points at a transient
145 // /tmp/.mount_* path — the handler must launch the AppImage itself.
146 const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
147 const content = renderUrlHandlerDesktopEntry({
148 displayName: environment.displayName,
149 execTarget,
150 scheme,
151 ...(environment.isPackaged ? { iconPath } : {}),
152 });
153 // Pre-ready setup normally wrote this already. Avoid truncating a valid
154 // entry while the portal may be reading it during startup.
155 const existing = yield* fileSystem
156 .readFileString(desktopEntryPath)
157 .pipe(Effect.orElseSucceed(() => null));
158 if (existing === content) return;
159 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
160 yield* fileSystem.writeFileString(desktopEntryPath, content);
161 }).pipe(
162 Effect.mapError(
163 (cause) =>
164 new DesktopLinuxUrlHandlerRegistrationError({
165 step: "write-desktop-entry",
166 scheme,
167 desktopEntryPath,
168 cause,
169 }),
170 ),
171 );
172
173 const updateDesktopDatabase = Effect.scoped(
174 Effect.gen(function* () {
175 const command = ChildProcess.make(
176 "update-desktop-database",
177 [environment.linuxApplicationsDir],
178 {
179 stdin: "ignore",
180 stdout: "ignore",
181 stderr: "ignore",
182 },
183 );
184 const handle = yield* spawner.spawn(command);
185 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
186 if (exitCode !== 0) {
187 return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
188 applicationsDir: environment.linuxApplicationsDir,
189 exitCode,
190 });
191 }
192 }),
193 ).pipe(
194 Effect.mapError((error) =>
195 isCacheRefreshError(error)
196 ? error
197 : new DesktopLinuxUrlHandlerCacheRefreshError({
198 applicationsDir: environment.linuxApplicationsDir,
199 cause: error,
200 }),
201 ),
202 );
203
204 const refreshIconThemeCache = Effect.scoped(
205 Effect.gen(function* () {
206 const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], {
207 stdin: "ignore",
208 stdout: "ignore",
209 stderr: "ignore",
210 // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely.
211 forceKillAfter: "1 second",
212 });
213 const handle = yield* spawner.spawn(command);
214 return yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
215 }),
216 );
217
218 const modifiedAt = (filePath: string) =>
219 fileSystem
220 .stat(filePath)
221 .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0));
222
223 const installThemeIcons = Effect.gen(function* () {
224 const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`);
225 if (Option.isNone(source)) return;
226 const icon = yield* fileSystem.readFile(source.value);
227 const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) =>
228 environment.path.join(themeIconDir, `${name}.png`),
229 );
230 let changed = false;
231 for (const target of targets) {
232 const current = yield* fileSystem.readFile(target).pipe(Effect.option);
233 if (Option.isSome(current) && sameBytes(current.value, icon)) continue;
234 yield* fileSystem.makeDirectory(themeIconDir, { recursive: true });
235 yield* fileSystem.writeFile(target, icon);
236 changed = true;
237 }
238 // Only keep an existing cache current. Creating one would leave GTK reading
239 // a cache that other tools installing user icons do not update. An icon
240 // newer than the cache also retries a refresh that failed on an earlier
241 // launch.
242 const cachePath = environment.path.join(hicolorDir, "icon-theme.cache");
243 const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option);
244 if (Option.isNone(cachedAt)) return;
245 let stale = changed;
246 for (const target of targets) {
247 if (stale) break;
248 if ((yield* modifiedAt(target)) > cachedAt.value) stale = true;
249 }
250 if (!stale) return;
251 const exitCode = yield* refreshIconThemeCache;
252 if (exitCode !== 0) {
253 yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode });
254 }
255 }).pipe(
256 Effect.catch((error) =>
257 logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }),
258 ),
259 );
260
261 const setDefaultHandler = Effect.scoped(
262 Effect.gen(function* () {
263 const command = ChildProcess.make(
264 "xdg-mime",
265 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
266 {
267 stdin: "ignore",
268 stdout: "ignore",
269 stderr: "ignore",
270 },
271 );
272 const handle = yield* spawner.spawn(command);
273 const exitCode = yield* handle.exitCode;
274 if ((exitCode as unknown as number) !== 0) {
275 return yield* new DesktopLinuxUrlHandlerRegistrationError({
276 step: "set-default-handler",
277 scheme,
278 exitCode: Number(exitCode),
279 });
280 }
281 }),
282 ).pipe(
283 Effect.mapError((error) =>
284 isRegistrationError(error)
285 ? error
286 : new DesktopLinuxUrlHandlerRegistrationError({
287 step: "set-default-handler",
288 scheme,
289 cause: error,
290 }),
291 ),
292 );
293
294 const register = Effect.gen(function* () {
295 if (environment.platform !== "linux") {
296 return;
297 }
298 yield* writeDesktopEntry;
299 if (!environment.isPackaged) return;
300
301 yield* Effect.gen(function* () {
302 const { png } = yield* assets.iconPaths;
303 if (Option.isNone(png)) return;
304 // Electron's copyFile extracts ASAR entries to temporary files it never removes.
305 const icon = yield* fileSystem.readFile(png.value);
306 const current = yield* fileSystem.readFile(iconPath).pipe(Effect.option);
307 if (Option.isSome(current) && sameBytes(current.value, icon)) return;
308 // The AppImage mount is temporary; the chooser needs the icon after exit.
309 yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
310 yield* fileSystem.writeFile(iconPath, icon, { mode: 0o600 });
311 }).pipe(
312 Effect.catch((error) =>
313 logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }),
314 ),
315 );
316
317 yield* installThemeIcons;
318
319 yield* updateDesktopDatabase.pipe(
320 // Some MIME implementations, including GIO, use mimeinfo.cache to verify
321 // that a desktop entry is associated with a scheme. Cache refresh is
322 // independently best-effort so a missing update-desktop-database executable
323 // does not prevent xdg-mime from recording the requested default.
324 Effect.catch((error) =>
325 logWarning("desktop MIME cache refresh failed", {
326 applicationsDir: environment.linuxApplicationsDir,
327 message: error.message,
328 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
329 }),
330 ),
331 );
332
333 yield* setDefaultHandler;
334 yield* logInfo("registered URL scheme handler", { scheme });
335 }).pipe(
336 Effect.catch((error) =>
337 logWarning("URL scheme handler registration failed", {
338 scheme,
339 step: error.step,
340 message: error.message,
341 ...(error.desktopEntryPath === undefined
342 ? {}
343 : { desktopEntryPath: error.desktopEntryPath }),
344 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
345 }),
346 ),
347 Effect.withSpan("desktop.linuxUrlHandler.register"),
348 );
349
350 return DesktopLinuxUrlHandler.of({ register });
351});
352
353export const layer = Layer.effect(DesktopLinuxUrlHandler, make);