super-productivity/electron/preload.ts
Johannes Millan 7f029b1798
fix(plugins): harden nodeExecution grants (#8205)
* fix(plugins): harden node execution grants

* fix(plugins): harden iframe bridge boundaries (#8208)

* fix(plugins): harden iframe bridge boundaries

* fix(plugins): tighten iframe bridge follow-up

* test(plugins): make node-executor electron test hermetic

The new plugin-node-executor test read the real built-in plugin manifest
(src/assets/bundled-plugins/sync-md/manifest.json), which is a build
artifact absent when 'npm run test:electron' runs in CI (before the
frontend/plugin build). Stub the manifest read, scoped to the executor
module via Module._load, so the grant/token/webContents assertions no
longer depend on built plugin assets.

* fix(plugins): allow iframe formatDate & getCurrentLanguage i18n methods

The iframe API allow-list gate added in #8208 only listed a subset of
the i18n methods that master's #8146 exposes to iframe plugins. Without
this, plugin calls to formatDate/getCurrentLanguage (and translate) are
rejected with 'Unknown API method'. Add all three so the merged gate
matches the methods createBoundMethods/createPluginApiScript expose.

* docs(plugins): document node-exec handoff bootstrap-ordering invariant

The one-shot consumePluginNodeExecutionApi() handoff is defended by
construction ordering, not structural isolation: PluginBridgeService must
consume it before any plugin 'new Function' code runs (both share window.ea
in one renderer realm). Document the invariant at the consumption site so a
future lazy-service/early-plugin-load refactor can't silently regress it.
Surfaced by the post-merge security review (latent finding; not currently
exploitable).

* fix(plugins): use static iframe sandbox attribute to avoid NG0910

Binding a security-sensitive iframe attribute (sandbox) via [attr.sandbox]
makes Angular throw RuntimeError NG0910 and tear down the iframe, crashing
the plugin view to the global error screen. This broke the plugin-iframe,
plugin-loading and plugin-lifecycle e2e tests.

Restore the static sandbox attribute (still without allow-same-origin, so
the opaque-origin isolation from #8208 is preserved) and drop the now-unused
iframeSandbox binding/import.
2026-06-09 18:16:41 +02:00

305 lines
9.8 KiB
TypeScript

import {
ipcRenderer,
IpcRendererEvent,
webFrame,
contextBridge,
webUtils,
} from 'electron';
import { ElectronAPI } from './electronAPI.d';
import { IPC, IPCEventValue } from './shared-with-frontend/ipc-events.const';
import {
getDistChannel,
ElectronDistChannel,
} from './shared-with-frontend/get-dist-channel';
import { LocalBackupMeta } from '../src/app/imex/local-backup/local-backup.model';
import {
PluginNodeScriptRequest,
PluginNodeScriptResult,
} from '../packages/plugin-api/src/types';
import {
LocalRestApiRequestPayload,
LocalRestApiResponsePayload,
} from './shared-with-frontend/local-rest-api.model';
let pluginNodeExecutionApiConsumed = false;
const _send: (channel: IPCEventValue, ...args: unknown[]) => void = (channel, ...args) =>
ipcRenderer.send(channel, ...args);
const _invoke: (channel: IPCEventValue, ...args: unknown[]) => Promise<unknown> = (
channel,
...args
) => ipcRenderer.invoke(channel, ...args);
const isGnomeDesktop = (): boolean => {
if (process.platform !== 'linux') {
return false;
}
const desktopValues = [
process.env.XDG_CURRENT_DESKTOP,
process.env.XDG_SESSION_DESKTOP,
process.env.DESKTOP_SESSION,
process.env.GNOME_SHELL_SESSION_MODE,
]
.filter((value): value is string => !!value)
.map((value) => value.toLowerCase());
return desktopValues.some(
(value) => value.includes('gnome') || value.includes('ubuntu'),
);
};
const ea: ElectronAPI = {
on: (
channel: string,
listener: (event: IpcRendererEvent, ...args: unknown[]) => void,
) => {
// NOTE: there is no proper way to unsubscribe apart from unsubscribing all
ipcRenderer.on(channel, listener);
},
// SYNC
// ----
getDistChannel: (): ElectronDistChannel | null => getDistChannel(),
// INVOKE
// ------
getUserDataPath: () => _invoke('GET_PATH', 'userData') as Promise<string>,
getBackupPath: () => _invoke('GET_BACKUP_PATH') as Promise<string>,
checkBackupAvailable: () =>
_invoke('BACKUP_IS_AVAILABLE') as Promise<false | LocalBackupMeta>,
loadBackupData: (backupPath) =>
_invoke('BACKUP_LOAD_DATA', backupPath) as Promise<string>,
fileSyncSave: (filePath) =>
_invoke('FILE_SYNC_SAVE', filePath) as Promise<string | Error>,
fileSyncLoad: (filePath) =>
_invoke('FILE_SYNC_LOAD', filePath) as Promise<{
rev: string;
dataStr: string | undefined;
}>,
fileSyncRemove: (filePath) => _invoke('FILE_SYNC_REMOVE', filePath) as Promise<void>,
fileSyncListFiles: (args) =>
_invoke('FILE_SYNC_LIST_FILES', args) as Promise<string[] | Error>,
checkDirExists: (dirPath) =>
_invoke('CHECK_DIR_EXISTS', dirPath) as Promise<true | Error>,
pickDirectory: () => _invoke('PICK_DIRECTORY') as Promise<string | undefined>,
showOpenDialog: (options: {
properties: string[];
title?: string;
defaultPath?: string;
filters?: { name: string; extensions: string[] }[];
}) => _invoke('SHOW_OPEN_DIALOG', options) as Promise<string[] | undefined>,
toFileUrl: (filePath: string) => ipcRenderer.invoke(IPC.TO_FILE_URL, filePath),
readLocalImageAsDataUrl: (filePathOrUrl: string) =>
_invoke('READ_LOCAL_IMAGE_AS_DATA_URL', filePathOrUrl) as Promise<string | null>,
// STANDARD
// --------
setZoomFactor: (zoomFactor: number) => {
webFrame.setZoomFactor(zoomFactor);
},
getZoomFactor: () => webFrame.getZoomFactor(),
isLinux: () => process.platform === 'linux',
isGnomeDesktop,
isMacOS: () => process.platform === 'darwin',
isAppleSilicon: () => process.platform === 'darwin' && process.arch === 'arm64',
isSnap: () => process && process.env && !!process.env.SNAP,
isFlatpak: () => process && process.env && !!process.env.FLATPAK_ID,
// CLIPBOARD IMAGES
// ----------------
saveClipboardImage: (
basePath: string,
fileName: string,
base64Data: string,
mimeType: string,
) =>
_invoke('CLIPBOARD_IMAGE_SAVE', {
basePath,
fileName,
base64Data,
mimeType,
}) as Promise<string>,
loadClipboardImage: (basePath: string, imageId: string) =>
_invoke('CLIPBOARD_IMAGE_LOAD', { basePath, imageId }) as Promise<{
base64: string;
mimeType: string;
} | null>,
deleteClipboardImage: (basePath: string, imageId: string) =>
_invoke('CLIPBOARD_IMAGE_DELETE', { basePath, imageId }) as Promise<boolean>,
listClipboardImages: (basePath: string) =>
_invoke('CLIPBOARD_IMAGE_LIST', { basePath }) as Promise<
{ id: string; mimeType: string; createdAt: number; size: number }[]
>,
getClipboardImagePath: (basePath: string, imageId: string) =>
_invoke('CLIPBOARD_IMAGE_GET_PATH', { basePath, imageId }) as Promise<string | null>,
getClipboardFilePaths: () => _invoke('CLIPBOARD_GET_FILE_PATHS') as Promise<string[]>,
copyClipboardImageFile: (basePath: string, filePath: string) =>
_invoke('CLIPBOARD_COPY_IMAGE_FILE', {
basePath,
filePath,
}) as Promise<{
id: string;
mimeType: string;
size: number;
createdAt: number;
} | null>,
readClipboardImage: (basePath: string) =>
_invoke('CLIPBOARD_READ_IMAGE', { basePath }) as Promise<{
id: string;
mimeType: string;
size: number;
createdAt: number;
} | null>,
getPathForFile: (file: File) => {
try {
return webUtils.getPathForFile(file);
} catch (error) {
console.error('[CLIPBOARD] Error getting path for file:', error);
return null;
}
},
// SEND
// ----
relaunch: () => _send('RELAUNCH'),
exit: () => _send('EXIT'),
flashFrame: () => _send('FLASH_FRAME'),
showOrFocus: () => _send('SHOW_OR_FOCUS'),
lockScreen: () => _send('LOCK_SCREEN'),
shutdownNow: () => _send('SHUTDOWN_NOW'),
reloadMainWin: () => _send('RELOAD_MAIN_WIN'),
openDevTools: () => _send('OPEN_DEV_TOOLS'),
showEmojiPanel: () => _send('SHOW_EMOJI_PANEL'),
informAboutAppReady: () => _send('APP_READY'),
openPath: (path: string) => _send('OPEN_PATH', path),
openExternalUrl: (url: string) => _send('OPEN_EXTERNAL', url),
saveFileDialog: (filename: string, data: string) =>
_invoke('SAVE_FILE_DIALOG', { filename, data }) as Promise<{
success: boolean;
path?: string;
}>,
shareNative: (payload: {
text?: string;
url?: string;
title?: string;
files?: string[];
}) =>
_invoke('SHARE_NATIVE', payload) as Promise<{
success: boolean;
error?: string;
}>,
scheduleRegisterBeforeClose: (id) => _send('REGISTER_BEFORE_CLOSE', { id }),
unscheduleRegisterBeforeClose: (id) => _send('UNREGISTER_BEFORE_CLOSE', { id }),
setDoneRegisterBeforeClose: (id) => _send('BEFORE_CLOSE_DONE', { id }),
setProgressBar: (args) => _send('SET_PROGRESS_BAR', args),
sendAppSettingsToElectron: (globalCfg) =>
_send('TRANSFER_SETTINGS_TO_ELECTRON', globalCfg),
sendSettingsUpdate: (globalCfg) => _send('UPDATE_SETTINGS', globalCfg),
updateTaskWidgetSettings: (cfg) => _send('UPDATE_TASK_WIDGET_SETTINGS', cfg),
updateTitleBarDarkMode: (isDarkMode: boolean) =>
_send('UPDATE_TITLE_BAR_DARK_MODE', isDarkMode),
registerGlobalShortcuts: (keyboardCfg) =>
_send('REGISTER_GLOBAL_SHORTCUTS', keyboardCfg),
showFullScreenBlocker: (args) => _send('FULL_SCREEN_BLOCKER', args),
makeJiraRequest: (args) => _send('JIRA_MAKE_REQUEST_EVENT', args),
jiraSetupImgHeaders: (args) => _send('JIRA_SETUP_IMG_HEADERS', args),
backupAppData: (appData) => _send('BACKUP', appData),
updateCurrentTask: (
task,
isPomodoroEnabled,
currentPomodoroSessionTime,
isFocusModeEnabled?,
currentFocusSessionTime?,
focusModeMode?,
) =>
_send(
'CURRENT_TASK_UPDATED',
task,
isPomodoroEnabled,
currentPomodoroSessionTime,
isFocusModeEnabled,
currentFocusSessionTime,
focusModeMode,
),
exec: (command: string) => _send('EXEC', command),
updateTodayTasks: (tasks: any[]) => _send('TODAY_TASKS_UPDATED', tasks),
onSwitchTask: (listener: (taskId: string) => void) => {
// We register the listener directly without using standard 'on' method
// Because the standard 'on' method doesn't strip out the event arg like we need
ipcRenderer.on('SWITCH_TASK', (_: any, taskId: string) => listener(taskId));
},
// Plugin API
consumePluginNodeExecutionApi: () => {
if (pluginNodeExecutionApiConsumed) {
return null;
}
pluginNodeExecutionApiConsumed = true;
return {
requestGrant: (pluginId: string) =>
_invoke('PLUGIN_REQUEST_NODE_EXECUTION_GRANT', pluginId) as Promise<{
token: string;
} | null>,
executeScript: (
pluginId: string,
grantToken: string,
request: PluginNodeScriptRequest,
) =>
_invoke(
'PLUGIN_EXEC_NODE_SCRIPT',
pluginId,
grantToken,
request,
) as Promise<PluginNodeScriptResult>,
revokeGrant: (pluginId: string, grantToken: string) =>
_invoke(
'PLUGIN_REVOKE_NODE_EXECUTION_GRANT',
pluginId,
grantToken,
) as Promise<void>,
};
},
// Plugin OAuth
pluginOAuthPrepare: () => _invoke('PLUGIN_OAUTH_PREPARE') as Promise<{ port: number }>,
pluginOAuthStart: (url: string) => _send('PLUGIN_OAUTH_START', { url }),
onPluginOAuthCb: (
listener: (data: { code?: string; error?: string; state?: string }) => void,
) => {
ipcRenderer.on(
IPC.PLUGIN_OAUTH_CB,
(_: unknown, data: { code?: string; error?: string; state?: string }) =>
listener(data),
);
},
onLocalRestApiRequest: (listener: (payload: LocalRestApiRequestPayload) => void) => {
ipcRenderer.on(IPC.LOCAL_REST_API_REQUEST, (_event, payload) =>
listener(payload as LocalRestApiRequestPayload),
);
},
sendLocalRestApiResponse: (payload: LocalRestApiResponsePayload) =>
_send(IPC.LOCAL_REST_API_RESPONSE, payload),
};
// Expose ea to window for ipc-event.ts using contextBridge for context isolation
contextBridge.exposeInMainWorld('ea', ea);