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

DesktopLinuxUrlHandler.ts

354 lines13.3 KB

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 }
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 }
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}"`);
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");
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])];
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 // Distribution packages that run on a shared Electron set
145 // T3CODE_DESKTOP_LAUNCHER_PATH, because process.execPath is that Electron.
146 // Inside the mounted AppImage, process.execPath points at a transient
147 // /tmp/.mount_* path — the handler must launch the AppImage itself.
148 const execTarget = environment.desktopLauncherPath.pipe(
149 Option.orElse(() => environment.appImagePath),
150 Option.getOrElse(() => process.execPath),
151 );
152 const content = renderUrlHandlerDesktopEntry({
153 displayName: environment.displayName,
154 execTarget,
155 scheme,
156 ...(environment.isPackaged ? { iconPath } : {}),
157 });
158 // Pre-ready setup normally wrote this already. Avoid truncating a valid
159 // entry while the portal may be reading it during startup.
160 const existing = yield* fileSystem
161 .readFileString(desktopEntryPath)
162 .pipe(Effect.orElseSucceed(() => null));
163 if (existing === content) return;
164 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
165 yield* fileSystem.writeFileString(desktopEntryPath, content);
166 }).pipe(
167 Effect.mapError(
168 (cause) =>
169 new DesktopLinuxUrlHandlerRegistrationError({
170 step: "write-desktop-entry",
171 scheme,
172 desktopEntryPath,
173 cause,
174 }),
175 ),
176 );
177​
178 const updateDesktopDatabase = Effect.scoped(
179 Effect.gen(function* () {
180 const command = ChildProcess.make(
181 "update-desktop-database",
182 [environment.linuxApplicationsDir],
183 {
184 stdin: "ignore",
185 stdout: "ignore",
186 stderr: "ignore",
187 },
188 );
189 const handle = yield* spawner.spawn(command);
190 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
191 if (exitCode !== 0) {
192 return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
193 applicationsDir: environment.linuxApplicationsDir,
194 exitCode,
195 });
196 }
197 }),
198 ).pipe(
199 Effect.mapError((error) =>
200 isCacheRefreshError(error)
201 ? error
202 : new DesktopLinuxUrlHandlerCacheRefreshError({
203 applicationsDir: environment.linuxApplicationsDir,
204 cause: error,
205 }),
206 ),
207 );
208​
209 const refreshIconThemeCache = Effect.scoped(
210 Effect.gen(function* () {
211 const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], {
212 stdin: "ignore",
213 stdout: "ignore",
214 stderr: "ignore",
215 // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely.
216 forceKillAfter: "1 second",
217 });
218 const handle = yield* spawner.spawn(command);
219 return yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
220 }),
221 );
222​
223 const modifiedAt = (filePath: string) =>
224 fileSystem
225 .stat(filePath)
226 .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0));
227​
228 const installThemeIcons = Effect.gen(function* () {
229 const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`);
230 if (Option.isNone(source)) return;
231 const icon = yield* fileSystem.readFile(source.value);
232 const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) =>
233 environment.path.join(themeIconDir, `${name}.png`),
234 );
235 let changed = false;
236 for (const target of targets) {
237 const current = yield* fileSystem.readFile(target).pipe(Effect.option);
238 if (Option.isSome(current) && sameBytes(current.value, icon)) continue;
239 yield* fileSystem.makeDirectory(themeIconDir, { recursive: true });
240 yield* fileSystem.writeFile(target, icon);
241 changed = true;
242 }
243 // Only keep an existing cache current. Creating one would leave GTK reading
244 // a cache that other tools installing user icons do not update. An icon
245 // newer than the cache also retries a refresh that failed on an earlier
246 // launch.
247 const cachePath = environment.path.join(hicolorDir, "icon-theme.cache");
248 const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option);
249 if (Option.isNone(cachedAt)) return;
250 let stale = changed;
251 for (const target of targets) {
252 if (stale) break;
253 if ((yield* modifiedAt(target)) > cachedAt.value) stale = true;
254 }
255 if (!stale) return;
256 const exitCode = yield* refreshIconThemeCache;
257 if (exitCode !== 0) {
258 yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode });
259 }
260 }).pipe(
261 Effect.catch((error) =>
262 logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }),
263 ),
264 );
265​
266 const setDefaultHandler = Effect.scoped(
267 Effect.gen(function* () {
268 const command = ChildProcess.make(
269 "xdg-mime",
270 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
271 {
272 stdin: "ignore",
273 stdout: "ignore",
274 stderr: "ignore",
275 },
276 );
277 const handle = yield* spawner.spawn(command);
278 const exitCode = yield* handle.exitCode;
279 if ((exitCode as unknown as number) !== 0) {
280 return yield* new DesktopLinuxUrlHandlerRegistrationError({
281 step: "set-default-handler",
282 scheme,
283 exitCode: Number(exitCode),
284 });
285 }
286 }),
287 ).pipe(
288 Effect.mapError((error) =>
289 isRegistrationError(error)
290 ? error
291 : new DesktopLinuxUrlHandlerRegistrationError({
292 step: "set-default-handler",
293 scheme,
294 cause: error,
295 }),
296 ),
297 );
298​
299 const register = Effect.gen(function* () {
300 if (environment.platform !== "linux") {
301 return;
302 }
303 yield* writeDesktopEntry;
304 if (!environment.isPackaged) return;
305​
306 yield* Effect.gen(function* () {
307 const { png } = yield* assets.iconPaths;
308 if (Option.isNone(png)) return;
309 // The AppImage mount is temporary; the chooser needs the icon after exit.
310 yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
311 yield* fileSystem.copyFile(png.value, iconPath);
312 }).pipe(
313 Effect.catch((error) =>
314 logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }),
315 ),
316 );
317​
318 yield* installThemeIcons;
319​
320 yield* updateDesktopDatabase.pipe(
321 // Some MIME implementations, including GIO, use mimeinfo.cache to verify
322 // that a desktop entry is associated with a scheme. Cache refresh is
323 // independently best-effort so a missing update-desktop-database executable
324 // does not prevent xdg-mime from recording the requested default.
325 Effect.catch((error) =>
326 logWarning("desktop MIME cache refresh failed", {
327 applicationsDir: environment.linuxApplicationsDir,
328 message: error.message,
329 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
330 }),
331 ),
332 );
333​
334 yield* setDefaultHandler;
335 yield* logInfo("registered URL scheme handler", { scheme });
336 }).pipe(
337 Effect.catch((error) =>
338 logWarning("URL scheme handler registration failed", {
339 scheme,
340 step: error.step,
341 message: error.message,
342 ...(error.desktopEntryPath === undefined
343 ? {}
344 : { desktopEntryPath: error.desktopEntryPath }),
345 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
346 }),
347 ),
348 Effect.withSpan("desktop.linuxUrlHandler.register"),
349 );
350​
351 return DesktopLinuxUrlHandler.of({ register });
352});
353​
354export const layer = Layer.effect(DesktopLinuxUrlHandler, make);