Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/desktop/src/app/DesktopApp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import * as DesktopWebLinks from "./DesktopWebLinks.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as PermissionPrompt from "../permissions/PermissionPrompt.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as MacPermissions from "../permissions/MacPermissions.ts";
Expand Down Expand Up @@ -231,6 +232,7 @@ const runStubbedDesktop = (stub: StubbedDesktop) =>
Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}),
Layer.mock(ElectronMenu.ElectronMenu, {}),
Layer.mock(ElectronShell.ElectronShell, {}),
Layer.mock(PermissionPrompt.PermissionPrompt, {}),
Layer.mock(ElectronTheme.ElectronTheme, {}),
Layer.mock(ElectronWindow.ElectronWindow, {}),
Layer.mock(MacPermissions.MacPermissions, {}),
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/app/DesktopClerk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const layerDesktopClerk = (
}),
shell: ElectronShell.ElectronShell["Service"] = {
openExternal: () => Effect.succeed(true),
openAppLink: () => Effect.succeed(false),
openSystemSettings: () => Effect.succeed(false),
copyText: () => Effect.void,
},
Expand Down Expand Up @@ -387,6 +388,7 @@ it.effect.each(["startup", "open-url", "early-second-instance"] as const)(
delivered.resolve(response.headers.get("location")!);
return true;
}),
openAppLink: () => Effect.succeed(false),
openSystemSettings: () => Effect.succeed(false),
copyText: () => Effect.void,
});
Expand Down
14 changes: 14 additions & 0 deletions apps/desktop/src/electron/ElectronShell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
remoteSchemeForEditor,
type SystemSettingsPane,
} from "@t3tools/contracts";
import { appLinkUrl } from "@t3tools/shared/appLinks";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -71,6 +72,8 @@ export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
/** Opens any app link without asking; callers confirm with the user first. */
readonly openAppLink: (url: string) => Effect.Effect<boolean>;
readonly openSystemSettings: (pane: SystemSettingsPane) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
Expand All @@ -90,6 +93,17 @@ export const make = ElectronShell.of({
),
});
}),
openAppLink: Effect.fn("ElectronShell.openAppLink")(function (rawUrl) {
const url = appLinkUrl(rawUrl);
return url === null
? Effect.succeed(false)
: Effect.promise(() =>
Electron.shell.openExternal(url).then(
() => true,
() => false,
),
);
}),
openSystemSettings: Effect.fn("ElectronShell.openSystemSettings")(function (pane) {
return Effect.promise(() =>
Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/ipc/DesktopIpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
getPrimaryPasteEnabled,
getWindowFullscreenState,
openExternal,
openAppLink,
readMedia,
restartAudioService,
openSystemSettings,
Expand Down Expand Up @@ -161,6 +162,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(openAppLink);
yield* ipc.handle(readMedia);
yield* ipc.handle(receiveProviderAuthCallback);
yield* ipc.handle(cancelProviderAuthCallback);
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/ipc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const OPEN_APP_LINK_CHANNEL = "desktop:open-app-link";
export const READ_MEDIA_CHANNEL = "desktop:read-media";
export const OPEN_SYSTEM_SETTINGS_CHANNEL = "desktop:open-system-settings";
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
Expand Down
36 changes: 36 additions & 0 deletions apps/desktop/src/ipc/methods/window.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,15 @@ import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts
import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
import * as PermissionPrompt from "../../permissions/PermissionPrompt.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import {
getLocalEnvironmentBootstraps,
installRelayTelemetryEnabled,
openAppLink,
pickProjectFavicon,
probeRemoteEditors,
readMedia,
Expand Down Expand Up @@ -361,6 +364,39 @@ describe("readMedia", () => {
);
});

describe("openAppLink", () => {
it.effect("hands an app link to the OS only after the user confirms it", () =>
Effect.gen(function* () {
const confirmations: Array<boolean> = [true, false];
const confirmAppLink = vi.fn((_owner: unknown, _url: string | undefined) =>
Effect.sync(() => confirmations.shift() ?? false),
);
const opened: Array<string> = [];
const open = (url: string) =>
openAppLink.handler(url, { sender: { id: 1 } }).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(ElectronWindow.ElectronWindow)({ currentMainOrFirst: Effect.succeedNone }),
Layer.mock(PermissionPrompt.PermissionPrompt)({ confirmAppLink }),
Layer.mock(ElectronShell.ElectronShell)({
openAppLink: (url) => Effect.sync(() => opened.push(url)).pipe(Effect.as(true)),
}),
),
),
);

assert.strictEqual(yield* open("obsidian://open?vault=v&file=A"), "opened");
assert.strictEqual(yield* open("obsidian://open?vault=v&file=B"), "cancelled");
assert.deepEqual(opened, ["obsidian://open?vault=v&file=A"]);
// Web pages and in-app thread links are never the OS's to open, so nothing is asked.
for (const url of ["https://example.com", "javascript:alert(1)", "t3-thread://v2/e/t"]) {
assert.strictEqual(yield* open(url), "unavailable", url);
}
assert.strictEqual(confirmAppLink.mock.calls.length, 2);
}),
);
});

describe("pickProjectFavicon", () => {
const pickerLayer = (
pickFiles: () => Effect.Effect<Array<string>>,
Expand Down
22 changes: 22 additions & 0 deletions apps/desktop/src/ipc/methods/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ContextMenuSource,
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopAppLinkOpenResultSchema,
DesktopMediaReadSchema,
DesktopThemeSchema,
EDITORS,
Expand All @@ -17,7 +18,9 @@ import {
} from "@t3tools/contracts";
import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
import { resolveEditorCommand } from "@t3tools/shared/editor";
import { appLinkUrl } from "@t3tools/shared/appLinks";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { THREAD_LINK_PROTOCOL } from "@t3tools/shared/threadLinks";
import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
Expand Down Expand Up @@ -46,6 +49,7 @@ import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as Electron from "electron";
import { msg } from "gt-i18n";
import * as MacPermissions from "../../permissions/MacPermissions.ts";
import * as PermissionPrompt from "../../permissions/PermissionPrompt.ts";
import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
import { m } from "../../i18n/messages.ts";
import * as IpcChannels from "../channels.ts";
Expand Down Expand Up @@ -368,6 +372,24 @@ export const openExternal = DesktopIpc.makeIpcMethod({
}),
});

/** The renderer has already taken in-app thread links; anything else asks before an app opens. */
export const openAppLink = DesktopIpc.makeIpcMethod({
channel: IpcChannels.OPEN_APP_LINK_CHANNEL,
payload: Schema.String,
result: DesktopAppLinkOpenResultSchema,
handler: Effect.fn("desktop.ipc.window.openAppLink")(function* (rawUrl) {
const url = appLinkUrl(rawUrl);
if (url === null || url.startsWith(`${THREAD_LINK_PROTOCOL}:`)) return "unavailable" as const;
const owner = yield* (yield* ElectronWindow.ElectronWindow).currentMainOrFirst;
const prompt = yield* PermissionPrompt.PermissionPrompt;
if (!(yield* prompt.confirmAppLink(Option.getOrUndefined(owner), url))) {
return "cancelled" as const;
}
const shell = yield* ElectronShell.ElectronShell;
return (yield* shell.openAppLink(url)) ? ("opened" as const) : ("unavailable" as const);
}),
});

const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;

// No URL field: media URLs can carry signed query tokens.
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.ts";
import * as AppleSpeech from "./speech/AppleSpeech.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PermissionPrompt from "./permissions/PermissionPrompt.ts";
import * as DesktopBrowserHost from "./preview/DesktopBrowserHost.ts";
import * as LoopbackTunnel from "./preview/LoopbackTunnel.ts";
import * as PreviewManager from "./preview/Manager.ts";
Expand Down Expand Up @@ -175,6 +176,7 @@ const layerDesktopPreview = PreviewManager.layer.pipe(
// IPC needs both services on the same BrowserSession.
Layer.provideMerge(BrowserImport.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
Layer.provideMerge(BrowserSession.layer),
Layer.provideMerge(PermissionPrompt.layer),
Layer.provideMerge(PreviewPasskeys.layer),
Layer.provideMerge(layerDesktopFoundation),
);
Expand Down
87 changes: 87 additions & 0 deletions apps/desktop/src/permissions/PermissionPrompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { appLinkUrl } from "@t3tools/shared/appLinks";
import * as HostProcess from "@t3tools/shared/HostProcess";
import type { BrowserWindow } from "electron";
import { msg } from "gt-i18n";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import * as ElectronDialog from "../electron/ElectronDialog.ts";
import { m } from "../i18n/messages.ts";

const MAX_PROMPT_TEXT_LENGTH = 300;

export const truncateForPrompt = (text: string): string =>
text.length > MAX_PROMPT_TEXT_LENGTH ? `${text.slice(0, MAX_PROMPT_TEXT_LENGTH)}…` : text;

export interface PermissionQuestion {
readonly buttons: readonly [allow: string, deny: string];
readonly message: string;
readonly detail?: string;
}

/** Native questions a page or a frame's content asks the user, one at a time. */
export class PermissionPrompt extends Context.Service<
PermissionPrompt,
{
/** `undefined` when the user gave no answer: another prompt was open or the dialog failed. */
readonly ask: (
owner: BrowserWindow | undefined,
question: PermissionQuestion,
) => Effect.Effect<boolean | undefined>;
/** Asks before the OS opens an app link; false for anything that is not one. */
readonly confirmAppLink: (
owner: BrowserWindow | undefined,
rawUrl: string | undefined,
) => Effect.Effect<boolean>;
}
>()("@t3tools/desktop/permissions/PermissionPrompt") {}

const make = Effect.gen(function* PermissionPromptMake() {
const electronDialog = yield* ElectronDialog.ElectronDialog;
const platform = yield* HostProcess.Platform;
// One prompt at a time, so a page cannot stack dialogs by looping a deep link.
let open = false;
const ask = (owner: BrowserWindow | undefined, question: PermissionQuestion) =>
Effect.suspend(() => {
if (open) return Effect.undefined;
open = true;
return electronDialog
.showMessageBox(
{
type: "question",
buttons: [...question.buttons],
// Default to deny so an Enter typed into the page cannot accept a prompt it raised.
defaultId: 1,
cancelId: 1,
message: question.message,
...(question.detail === undefined ? {} : { detail: question.detail }),
},
platform === "win32" ? undefined : owner,
)
.pipe(
Effect.map(({ response }): boolean | undefined => response === 0),
Effect.orElseSucceed(() => undefined),
Effect.ensuring(Effect.sync(() => (open = false))),
);
});
const confirmAppLink = (owner: BrowserWindow | undefined, rawUrl: string | undefined) => {
const url = rawUrl === undefined ? null : appLinkUrl(rawUrl);
if (url === null) return Effect.succeed(false);
return ask(owner, {
buttons: [
m(msg("Open", { $context: "button, opens a link in another app" })),
m(msg("Cancel")),
],
message: m(msg("Open this {protocol} link?"), {
protocol: new URL(url).protocol.slice(0, -1),
}),
detail: m(msg("A page in the browser wants to open another application:\n\n{url}"), {
url: truncateForPrompt(url),
}),
}).pipe(Effect.map((answer) => answer === true));
};
return PermissionPrompt.of({ ask, confirmAppLink });
});

export const layer = Layer.effect(PermissionPrompt, make);
1 change: 1 addition & 0 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url),
startFileDrag: (input) => ipcRenderer.invoke(IpcChannels.START_FILE_DRAG_CHANNEL, input),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
openAppLink: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_APP_LINK_CHANNEL, url),
readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url),
checkSystemPermission: (pane: string) =>
ipcRenderer.invoke(IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL, pane),
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/preview/BrowserSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ vi.mock("electron", () => ({

import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as PermissionPrompt from "../permissions/PermissionPrompt.ts";
import * as BrowserSession from "./BrowserSession.ts";

const { showMessageBox, showErrorBox } = vi.hoisted(() => ({
Expand All @@ -75,6 +76,7 @@ const layerDialog = Layer.succeed(ElectronDialog.ElectronDialog, {
showErrorBox: (title, content) => Effect.sync(() => showErrorBox(title, content)),
});
const layer = BrowserSession.layer.pipe(
Layer.provide(PermissionPrompt.layer),
Layer.provide(
Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerDialog, ElectronApp.layer),
),
Expand Down
Loading
Loading