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

DesktopLinuxUrlHandler.ts

191 lines7.0 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.
23export const 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​
95export const make = Effect.gen(function* () {
96 const environment = yield* DesktopEnvironment.DesktopEnvironment;
97 const fileSystem = yield* FileSystem.FileSystem;
98 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
99​
100 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
101 const desktopEntryPath = environment.path.join(
102 environment.linuxApplicationsDir,
103 URL_HANDLER_DESKTOP_ENTRY_NAME,
104 );
105​
106 const writeDesktopEntry = Effect.gen(function* () {
107 // Inside the mounted AppImage, process.execPath points at a transient
108 // /tmp/.mount_* path — the handler must launch the AppImage itself.
109 const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
110 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
111 yield* fileSystem.writeFileString(
112 desktopEntryPath,
113 renderUrlHandlerDesktopEntry({
114 displayName: environment.displayName,
115 execTarget,
116 scheme,
117 }),
118 );
119 }).pipe(
120 Effect.mapError(
121 (cause) =>
122 new DesktopLinuxUrlHandlerRegistrationError({
123 step: "write-desktop-entry",
124 scheme,
125 desktopEntryPath,
126 cause,
127 }),
128 ),
129 );
130​
131 const setDefaultHandler = Effect.scoped(
132 Effect.gen(function* () {
133 const command = ChildProcess.make(
134 "xdg-mime",
135 ["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
136 {
137 stdin: "ignore",
138 stdout: "ignore",
139 stderr: "ignore",
140 },
141 );
142 const handle = yield* spawner.spawn(command);
143 const exitCode = yield* handle.exitCode;
144 if ((exitCode as unknown as number) !== 0) {
145 return yield* new DesktopLinuxUrlHandlerRegistrationError({
146 step: "set-default-handler",
147 scheme,
148 exitCode: Number(exitCode),
149 });
150 }
151 }),
152 ).pipe(
153 Effect.mapError((error) =>
154 isRegistrationError(error)
155 ? error
156 : new DesktopLinuxUrlHandlerRegistrationError({
157 step: "set-default-handler",
158 scheme,
159 cause: error,
160 }),
161 ),
162 );
163​
164 const register = Effect.gen(function* () {
165 if (environment.platform !== "linux" || !environment.isPackaged) {
166 return;
167 }
168 yield* writeDesktopEntry;
169 yield* setDefaultHandler;
170 yield* logInfo("registered URL scheme handler", { scheme });
171 }).pipe(
172 // Registration is best-effort: a missing xdg-mime or read-only home must
173 // never block startup — the OS chooser remains as fallback.
174 Effect.catch((error) =>
175 logWarning("URL scheme handler registration failed", {
176 scheme,
177 step: error.step,
178 message: error.message,
179 ...(error.desktopEntryPath === undefined
180 ? {}
181 : { desktopEntryPath: error.desktopEntryPath }),
182 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
183 }),
184 ),
185 Effect.withSpan("desktop.linuxUrlHandler.register"),
186 );
187​
188 return DesktopLinuxUrlHandler.of({ register });
189});
190​
191export const layer = Layer.effect(DesktopLinuxUrlHandler, make);