Open History to see the last commit
1import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts";
2import {
3 REMOTE_CAPABLE_EDITOR_IDS,
4 remoteSchemeForEditor,
5 type SystemSettingsPane,
6} from "@t3tools/contracts";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11
12import * as Electron from "electron";
13
14// Remote editor deep links must reach the OS handler.
15const SAFE_WEB_PROTOCOLS = new Set(["http:", "https:"]);
16const REMOTE_EDITOR_PROTOCOLS = new Set(
17 REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
18 const scheme = remoteSchemeForEditor(id);
19 return scheme === undefined ? [] : [`${scheme}:`];
20 }),
21);
22
23// Zed embeds [user@]host in the path; reject passwords and ports there.
24const ZED_SSH_PATHNAME = /^\/(?:[^/@:]+@)?[^/@:]+\/.*$/;
25
26const isRemoteEditorUrl = (url: URL) =>
27 REMOTE_EDITOR_PROTOCOLS.has(url.protocol) &&
28 url.username.length === 0 &&
29 url.password.length === 0 &&
30 (url.protocol === "zed:"
31 ? url.host === "ssh" && ZED_SSH_PATHNAME.test(url.pathname)
32 : url.protocol === "jetbrains:"
33 ? url.host === "gateway" &&
34 url.pathname === "/ssh/environment" &&
35 (url.searchParams.get("h") ?? "").length > 0
36 : url.host === "vscode-remote" &&
37 url.pathname.startsWith("/ssh-remote+") &&
38 url.pathname.length > "/ssh-remote+".length);
39
40export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
41 if (typeof rawUrl !== "string") {
42 return Option.none();
43 }
44
45 try {
46 const url = new URL(rawUrl);
47 return SAFE_WEB_PROTOCOLS.has(url.protocol) || isRemoteEditorUrl(url)
48 ? Option.some(url.href)
49 : Option.none();
50 } catch {
51 return Option.none();
52 }
53}
54
55export class ElectronShell extends Context.Service<
56 ElectronShell,
57 {
58 readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
59 readonly openSystemSettings: (pane: SystemSettingsPane) => Effect.Effect<boolean>;
60 readonly copyText: (text: string) => Effect.Effect<void>;
61 }
62>()("@t3tools/desktop/electron/ElectronShell") {}
63
64/** @public */
65export const make = ElectronShell.of({
66 openExternal: (rawUrl) =>
67 Option.match(parseSafeExternalUrl(rawUrl), {
68 onNone: () => Effect.succeed(false),
69 onSome: (externalUrl) =>
70 Effect.promise(() =>
71 Electron.shell.openExternal(externalUrl).then(
72 () => true,
73 () => false,
74 ),
75 ),
76 }),
77 openSystemSettings: (pane) =>
78 Effect.promise(() =>
79 Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(
80 () => true,
81 () => false,
82 ),
83 ),
84 copyText: (text) =>
85 Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined)),
86});
87
88export const layer = Layer.succeed(ElectronShell, make);