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

DesktopLinuxUrlHandler.ts

269 lines9.7 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// The AppImage integration entry owns the window identity. This
79// hidden URL-only entry must not compete with it for StartupWMClass matching.
80export function renderUrlHandlerDesktopEntry(input: {
81 readonly displayName: string;
82 readonly execTarget: string;
83 readonly scheme: string;
84 readonly iconPath?: string;
85}): string {
86 return [
87 "[Desktop Entry]",
88 "Type=Application",
89 `Name=${escapeDesktopEntryString(input.displayName)}`,
90 `Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
91 ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]),
92 "Terminal=false",
93 "NoDisplay=true",
94 "StartupNotify=false",
95 `MimeType=x-scheme-handler/${input.scheme};`,
96 "",
97 ].join("\n");
99​
100export class DesktopLinuxUrlHandler extends Context.Service<
101 DesktopLinuxUrlHandler,
102 {
103 readonly register: Effect.Effect<void>;
104 }
105>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
106​
107/** @public Service construction is part of the canonical Effect module API. */
108export const make = Effect.gen(function* () {
109 const environment = yield* DesktopEnvironment.DesktopEnvironment;
110 const fileSystem = yield* FileSystem.FileSystem;
111 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
112 const assets = yield* DesktopAssets.DesktopAssets;
113​
114 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
115 const desktopEntryPath = environment.path.join(
116 environment.linuxApplicationsDir,
117 environment.linuxDesktopEntryName,
118 );
119 const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons");
120 const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`);
121​
122 const writeDesktopEntry = Effect.gen(function* () {
123 // Inside the mounted AppImage, process.execPath points at a transient
124 // /tmp/.mount_* path — the handler must launch the AppImage itself.
125 const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
126 const content = renderUrlHandlerDesktopEntry({
127 displayName: environment.displayName,
128 execTarget,
129 scheme,
130 ...(environment.isPackaged ? { iconPath } : {}),
131 });
132 // Pre-ready setup normally wrote this already. Avoid truncating a valid
133 // entry while the portal may be reading it during startup.
134 const existing = yield* fileSystem
135 .readFileString(desktopEntryPath)
136 .pipe(Effect.orElseSucceed(() => null));
137 if (existing === content) return;
138 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
139 yield* fileSystem.writeFileString(desktopEntryPath, content);
140 }).pipe(
141 Effect.mapError(
142 (cause) =>
143 new DesktopLinuxUrlHandlerRegistrationError({
144 step: "write-desktop-entry",
145 scheme,
146 desktopEntryPath,
147 cause,
148 }),
149 ),
150 );
151​
152 const updateDesktopDatabase = Effect.scoped(
153 Effect.gen(function* () {
154 const command = ChildProcess.make(
155 "update-desktop-database",
156 [environment.linuxApplicationsDir],
157 {
158 stdin: "ignore",
159 stdout: "ignore",
160 stderr: "ignore",
161 },
162 );
163 const handle = yield* spawner.spawn(command);
164 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
165 if (exitCode !== 0) {
166 return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
167 applicationsDir: environment.linuxApplicationsDir,
168 exitCode,
169 });
170 }
171 }),
172 ).pipe(
173 Effect.mapError((error) =>
174 isCacheRefreshError(error)
175 ? error
176 : new DesktopLinuxUrlHandlerCacheRefreshError({
177 applicationsDir: environment.linuxApplicationsDir,
178 cause: error,
179 }),
180 ),
181 );
182​
183 const setDefaultHandler = Effect.scoped(
184 Effect.gen(function* () {
185 const command = ChildProcess.make(
186 "xdg-mime",
187 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
188 {
189 stdin: "ignore",
190 stdout: "ignore",
191 stderr: "ignore",
192 },
193 );
194 const handle = yield* spawner.spawn(command);
195 const exitCode = yield* handle.exitCode;
196 if ((exitCode as unknown as number) !== 0) {
197 return yield* new DesktopLinuxUrlHandlerRegistrationError({
198 step: "set-default-handler",
199 scheme,
200 exitCode: Number(exitCode),
201 });
202 }
203 }),
204 ).pipe(
205 Effect.mapError((error) =>
206 isRegistrationError(error)
207 ? error
208 : new DesktopLinuxUrlHandlerRegistrationError({
209 step: "set-default-handler",
210 scheme,
211 cause: error,
212 }),
213 ),
214 );
215​
216 const register = Effect.gen(function* () {
217 if (environment.platform !== "linux") {
218 return;
219 }
220 yield* writeDesktopEntry;
221 if (!environment.isPackaged) return;
222​
223 yield* Effect.gen(function* () {
224 const { png } = yield* assets.iconPaths;
225 if (Option.isNone(png)) return;
226 // The AppImage mount is temporary; the chooser needs the icon after exit.
227 yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
228 yield* fileSystem.copyFile(png.value, iconPath);
229 }).pipe(
230 Effect.catch((error) =>
231 logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }),
232 ),
233 );
234​
235 yield* updateDesktopDatabase.pipe(
236 // Some MIME implementations, including GIO, use mimeinfo.cache to verify
237 // that a desktop entry is associated with a scheme. Cache refresh is
238 // independently best-effort so a missing update-desktop-database executable
239 // does not prevent xdg-mime from recording the requested default.
240 Effect.catch((error) =>
241 logWarning("desktop MIME cache refresh failed", {
242 applicationsDir: environment.linuxApplicationsDir,
243 message: error.message,
244 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
245 }),
246 ),
247 );
248​
249 yield* setDefaultHandler;
250 yield* logInfo("registered URL scheme handler", { scheme });
251 }).pipe(
252 Effect.catch((error) =>
253 logWarning("URL scheme handler registration failed", {
254 scheme,
255 step: error.step,
256 message: error.message,
257 ...(error.desktopEntryPath === undefined
258 ? {}
259 : { desktopEntryPath: error.desktopEntryPath }),
260 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
261 }),
262 ),
263 Effect.withSpan("desktop.linuxUrlHandler.register"),
264 );
265​
266 return DesktopLinuxUrlHandler.of({ register });
267});
268​
269export const layer = Layer.effect(DesktopLinuxUrlHandler, make);