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 open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`,
15// `zed://ssh/<host>/<path>`) must reach the OS handler; every other non-web
16// scheme stays blocked.
17const SAFE_WEB_PROTOCOLS = new Set(["http:", "https:"]);
18const REMOTE_EDITOR_PROTOCOLS = new Set(
19 REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
20 const scheme = remoteSchemeForEditor(id);
21 return scheme === undefined ? [] : [`${scheme}:`];
22 }),
23);
24
25// Zed's host sits in the first path segment, so it needs its own userinfo ban.
26const ZED_SSH_PATHNAME = /^\/[^/@:]+\/.*$/;
27
28const isRemoteEditorUrl = (url: URL) =>
29 REMOTE_EDITOR_PROTOCOLS.has(url.protocol) &&
30 url.username.length === 0 &&
31 url.password.length === 0 &&
32 (url.protocol === "zed:"
33 ? url.host === "ssh" && ZED_SSH_PATHNAME.test(url.pathname)
34 : url.host === "vscode-remote" &&
35 url.pathname.startsWith("/ssh-remote+") &&
36 url.pathname.length > "/ssh-remote+".length);
37
38export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
39 if (typeof rawUrl !== "string") {
40 return Option.none();
41 }
42
43 try {
44 const url = new URL(rawUrl);
45 return SAFE_WEB_PROTOCOLS.has(url.protocol) || isRemoteEditorUrl(url)
46 ? Option.some(url.href)
47 : Option.none();
48 } catch {
49 return Option.none();
50 }
51}
52
53export class ElectronShell extends Context.Service<
54 ElectronShell,
55 {
56 readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
57 /** Opens a known System Settings pane by identifier, not by URL. */
58 readonly openSystemSettings: (pane: SystemSettingsPane) => Effect.Effect<boolean>;
59 readonly copyText: (text: string) => Effect.Effect<void>;
60 }
61>()("@t3tools/desktop/electron/ElectronShell") {}
62
63/** @public Service construction is part of the canonical Effect module API. */
64export const make = ElectronShell.of({
65 openExternal: (rawUrl) =>
66 Option.match(parseSafeExternalUrl(rawUrl), {
67 onNone: () => Effect.succeed(false),
68 onSome: (externalUrl) =>
69 Effect.promise(() =>
70 Electron.shell.openExternal(externalUrl).then(
71 () => true,
72 () => false,
73 ),
74 ),
75 }),
76 openSystemSettings: (pane) =>
77 Effect.promise(() =>
78 Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(
79 () => true,
80 () => false,
81 ),
82 ),
83 copyText: (text) =>
84 Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined)),
85});
86
87export const layer = Layer.succeed(ElectronShell, make);