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

DesktopLinuxUrlHandler.ts

192 lines7.1 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/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 URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
24​
25const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
26​
27export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
28 "DesktopLinuxUrlHandlerRegistrationError",
29 {
30 step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
31 scheme: Schema.String,
32 desktopEntryPath: Schema.optionalKey(Schema.String),
33 exitCode: Schema.optionalKey(Schema.Number),
34 cause: Schema.optionalKey(Schema.Defect()),
35 },
36) {
37 override get message(): string {
38 const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
39 return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
40 }
42​
43const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
44​
45const escapeDesktopEntryString = (value: string): string =>
46 value
47 .replaceAll("\\", "\\\\")
48 .replaceAll("\n", "\\n")
49 .replaceAll("\r", "\\r")
50 .replaceAll("\t", "\\t");
51​
52// Exec values are unescaped twice by implementations: first the general
53// string-value rules, then the Exec quoting rules — so writing composes the
54// layers in reverse. The argument is double-quoted with reserved characters
55// backslash-escaped and literal percent signs doubled (field codes), and the
56// general string escaping is applied on top: a literal backslash ends up as
57// four backslashes in the file, a quote as \\", a dollar sign as \\$.
58export function escapeDesktopEntryExecArgument(value: string): string {
59 const quoted = value
60 .replaceAll("\\", () => "\\\\")
61 .replaceAll("`", () => "\\`")
62 .replaceAll("$", () => "\\$")
63 .replaceAll('"', () => '\\"')
64 .replaceAll("%", () => "%%");
65 return escapeDesktopEntryString(`"${quoted}"`);
67​
68// The AppImage integration entry owns the window identity and icon. This
69// hidden URL-only entry must not compete with it for StartupWMClass matching.
70export function renderUrlHandlerDesktopEntry(input: {
71 readonly displayName: string;
72 readonly execTarget: string;
73 readonly scheme: string;
74}): string {
75 return [
76 "[Desktop Entry]",
77 "Type=Application",
78 `Name=${escapeDesktopEntryString(input.displayName)}`,
79 `Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
80 "Terminal=false",
81 "NoDisplay=true",
82 "StartupNotify=false",
83 `MimeType=x-scheme-handler/${input.scheme};`,
84 "",
85 ].join("\n");
87​
88export class DesktopLinuxUrlHandler extends Context.Service<
89 DesktopLinuxUrlHandler,
90 {
91 readonly register: Effect.Effect<void>;
92 }
93>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
94​
95/** @public Service construction is part of the canonical Effect module API. */
96export const make = Effect.gen(function* () {
97 const environment = yield* DesktopEnvironment.DesktopEnvironment;
98 const fileSystem = yield* FileSystem.FileSystem;
99 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
100​
101 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
102 const desktopEntryPath = environment.path.join(
103 environment.linuxApplicationsDir,
104 URL_HANDLER_DESKTOP_ENTRY_NAME,
105 );
106​
107 const writeDesktopEntry = Effect.gen(function* () {
108 // Inside the mounted AppImage, process.execPath points at a transient
109 // /tmp/.mount_* path — the handler must launch the AppImage itself.
110 const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
111 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
112 yield* fileSystem.writeFileString(
113 desktopEntryPath,
114 renderUrlHandlerDesktopEntry({
115 displayName: environment.displayName,
116 execTarget,
117 scheme,
118 }),
119 );
120 }).pipe(
121 Effect.mapError(
122 (cause) =>
123 new DesktopLinuxUrlHandlerRegistrationError({
124 step: "write-desktop-entry",
125 scheme,
126 desktopEntryPath,
127 cause,
128 }),
129 ),
130 );
131​
132 const setDefaultHandler = Effect.scoped(
133 Effect.gen(function* () {
134 const command = ChildProcess.make(
135 "xdg-mime",
136 ["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
137 {
138 stdin: "ignore",
139 stdout: "ignore",
140 stderr: "ignore",
141 },
142 );
143 const handle = yield* spawner.spawn(command);
144 const exitCode = yield* handle.exitCode;
145 if ((exitCode as unknown as number) !== 0) {
146 return yield* new DesktopLinuxUrlHandlerRegistrationError({
147 step: "set-default-handler",
148 scheme,
149 exitCode: Number(exitCode),
150 });
151 }
152 }),
153 ).pipe(
154 Effect.mapError((error) =>
155 isRegistrationError(error)
156 ? error
157 : new DesktopLinuxUrlHandlerRegistrationError({
158 step: "set-default-handler",
159 scheme,
160 cause: error,
161 }),
162 ),
163 );
164​
165 const register = Effect.gen(function* () {
166 if (environment.platform !== "linux" || !environment.isPackaged) {
167 return;
168 }
169 yield* writeDesktopEntry;
170 yield* setDefaultHandler;
171 yield* logInfo("registered URL scheme handler", { scheme });
172 }).pipe(
173 // Registration is best-effort: a missing xdg-mime or read-only home must
174 // never block startup — the OS chooser remains as fallback.
175 Effect.catch((error) =>
176 logWarning("URL scheme handler registration failed", {
177 scheme,
178 step: error.step,
179 message: error.message,
180 ...(error.desktopEntryPath === undefined
181 ? {}
182 : { desktopEntryPath: error.desktopEntryPath }),
183 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
184 }),
185 ),
186 Effect.withSpan("desktop.linuxUrlHandler.register"),
187 );
188​
189 return DesktopLinuxUrlHandler.of({ register });
190});
191​
192export const layer = Layer.effect(DesktopLinuxUrlHandler, make);