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/unstable/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
9
10import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
11import * as DesktopEnvironment from "./DesktopEnvironment.ts";
12import { makeComponentLogger } from "./DesktopObservability.ts";
13
14// Linux ships as an AppImage, so the .desktop entry users end up with is
15// created by whatever integration tool they use (AppImageLauncher names it
16// appimagekit_<hash>-….desktop) and its filename is not under our control.
17// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
18// setDesktopName, which cannot match those files — so the browser keeps
19// prompting "Choose an application" for every OAuth callback. Instead, write
20// our own handler entry pointing at the current AppImage and claim the
21// scheme default via xdg-mime, exactly what the file manager's "set as
22// default" checkbox would record in mimeapps.list.
23const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
24
25export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError<DesktopLinuxUrlHandlerRegistrationError>()(
26 "DesktopLinuxUrlHandlerRegistrationError",
27 {
28 step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
29 scheme: Schema.String,
30 desktopEntryPath: Schema.optionalKey(Schema.String),
31 exitCode: Schema.optionalKey(Schema.Number),
32 cause: Schema.optionalKey(Schema.Defect()),
33 },
34) {
35 override get message(): string {
36 const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
37 return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
38 }
39}
40
41const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
42
43const escapeDesktopEntryString = (value: string): string =>
44 value
45 .replaceAll("\\", "\\\\")
46 .replaceAll("\n", "\\n")
47 .replaceAll("\r", "\\r")
48 .replaceAll("\t", "\\t");
49
50// Exec values are unescaped twice by implementations: first the general
51// string-value rules, then the Exec quoting rules — so writing composes the
52// layers in reverse. The argument is double-quoted with reserved characters
53// backslash-escaped and literal percent signs doubled (field codes), and the
54// general string escaping is applied on top: a literal backslash ends up as
55// four backslashes in the file, a quote as \\", a dollar sign as \\$.
56export function escapeDesktopEntryExecArgument(value: string): string {
57 const quoted = value
58 .replaceAll("\\", () => "\\\\")
59 .replaceAll("`", () => "\\`")
60 .replaceAll("$", () => "\\$")
61 .replaceAll('"', () => '\\"')
62 .replaceAll("%", () => "%%");
63 return escapeDesktopEntryString(`"${quoted}"`);
64}
65
66// The AppImage integration entry owns the window identity and icon. This
67// hidden URL-only entry must not compete with it for StartupWMClass matching.
68export function renderUrlHandlerDesktopEntry(input: {
69 readonly displayName: string;
70 readonly execTarget: string;
71 readonly scheme: string;
72}): string {
73 return [
74 "[Desktop Entry]",
75 "Type=Application",
76 `Name=${escapeDesktopEntryString(input.displayName)}`,
77 `Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
78 "Terminal=false",
79 "NoDisplay=true",
80 "StartupNotify=false",
81 `MimeType=x-scheme-handler/${input.scheme};`,
82 "",
83 ].join("\n");
84}
85
86export class DesktopLinuxUrlHandler extends Context.Service<
87 DesktopLinuxUrlHandler,
88 {
89 readonly register: Effect.Effect<void>;
90 }
91>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
92
93/** @public Service construction is part of the canonical Effect module API. */
94export const make = Effect.gen(function* () {
95 const environment = yield* DesktopEnvironment.DesktopEnvironment;
96 const fileSystem = yield* FileSystem.FileSystem;
97 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
98
99 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
100 const desktopEntryPath = environment.path.join(
101 environment.linuxApplicationsDir,
102 environment.linuxDesktopEntryName,
103 );
104
105 const writeDesktopEntry = Effect.gen(function* () {
106 // Inside the mounted AppImage, process.execPath points at a transient
107 // /tmp/.mount_* path — the handler must launch the AppImage itself.
108 const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
109 const content = renderUrlHandlerDesktopEntry({
110 displayName: environment.displayName,
111 execTarget,
112 scheme,
113 });
114 // Pre-ready setup normally wrote this already. Avoid truncating a valid
115 // entry while the portal may be reading it during startup.
116 const existing = yield* fileSystem
117 .readFileString(desktopEntryPath)
118 .pipe(Effect.orElseSucceed(() => null));
119 if (existing === content) return;
120 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
121 yield* fileSystem.writeFileString(desktopEntryPath, content);
122 }).pipe(
123 Effect.mapError(
124 (cause) =>
125 new DesktopLinuxUrlHandlerRegistrationError({
126 step: "write-desktop-entry",
127 scheme,
128 desktopEntryPath,
129 cause,
130 }),
131 ),
132 );
133
134 const setDefaultHandler = Effect.scoped(
135 Effect.gen(function* () {
136 const command = ChildProcess.make(
137 "xdg-mime",
138 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
139 {
140 stdin: "ignore",
141 stdout: "ignore",
142 stderr: "ignore",
143 },
144 );
145 const handle = yield* spawner.spawn(command);
146 const exitCode = yield* handle.exitCode;
147 if ((exitCode as unknown as number) !== 0) {
148 return yield* new DesktopLinuxUrlHandlerRegistrationError({
149 step: "set-default-handler",
150 scheme,
151 exitCode: Number(exitCode),
152 });
153 }
154 }),
155 ).pipe(
156 Effect.mapError((error) =>
157 isRegistrationError(error)
158 ? error
159 : new DesktopLinuxUrlHandlerRegistrationError({
160 step: "set-default-handler",
161 scheme,
162 cause: error,
163 }),
164 ),
165 );
166
167 const register = Effect.gen(function* () {
168 if (environment.platform !== "linux") {
169 return;
170 }
171 yield* writeDesktopEntry;
172 if (!environment.isPackaged) return;
173 yield* setDefaultHandler;
174 yield* logInfo("registered URL scheme handler", { scheme });
175 }).pipe(
176 // Registration is best-effort: a missing xdg-mime or read-only home must
177 // never block startup — the OS chooser remains as fallback.
178 Effect.catch((error) =>
179 logWarning("URL scheme handler registration failed", {
180 scheme,
181 step: error.step,
182 message: error.message,
183 ...(error.desktopEntryPath === undefined
184 ? {}
185 : { desktopEntryPath: error.desktopEntryPath }),
186 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
187 }),
188 ),
189 Effect.withSpan("desktop.linuxUrlHandler.register"),
190 );
191
192 return DesktopLinuxUrlHandler.of({ register });
193});
194
195export const layer = Layer.effect(DesktopLinuxUrlHandler, make);