'use client'; // Runtime that boots inside the null-origin plugin sandbox iframe. // // Lifecycle: // 1. Iframe loads → posts 'sandbox-ready' to the window that framed it // (`window.parent`, targeted at this document's own URL origin - see // `resolveHost`). A top-level load has no host and stays inert. // 2. Parent posts 'init' with the bundle code + manifest + mode/slot. // 3. We evaluate the bundle in a `new Function` scope with React/ReactDOM // injected as globals; the bundle is CommonJS-style (`module.exports = { // slots, hooks, activate }`). ES-module syntax inside the bundle is a // build-time concern handled by the plugin's bundler. // 4. In background mode: register hook handlers and call `activate(api)`. // The host installs HookBus stubs and dispatches via 'hook-invoke'. // 5. In slot mode: look up `slots[slot].component`, render it into the // iframe body, push height back via ResizeObserver. import { useEffect } from 'react'; import * as React from 'react'; import * as ReactJSXRuntime from 'react/jsx-runtime'; import type { HostToSandbox, SandboxToHost, InitPayload, BackgroundInit, SlotInit, RegionalSnapshot, } from './protocol'; import { themeSnapshotToCSS, type ThemeSnapshot } from './host-theme'; import { backgroundReactDom, backgroundUiKit } from './ui-kit/background-kit'; import { initFloatingDropdownBridge, dispatchFloatingDropdownEvent } from './ui-kit/floating-dropdown-bridge'; import { interpolate, lookup, textDirection, type LocaleTables } from './plugin-i18n'; import { isFillableSlot, isInlineSlot, MAX_INLINE_SLOT_WIDTH } from './slot-layout'; import type { AppInfoView, AppSettingsView, HostFeaturesView, SettingsSearchResult, CalendarEventInput, CalendarEventView, CalendarView, ComposeInput, DraftInput, EmailForwardInput, EmailForwardResult, EmailReadView, EmailSummary, IdentityPatch, IdentityView, MailboxView, NotificationInput, SlotName, TaskInput, TaskView, TemplateInput, TemplateView, VacationInput, VacationView, } from '../plugin-types'; import { AddressBook, ContactCard } from '../jmap/types'; import { EncryptionAtRestConfig, PublicKeyInput } from '@/stores/account-security-store'; // ─── Module-scope state ────────────────────────────────────── interface PluginExports { slots?: Record>; shouldShow?: (ctx: unknown) => boolean; order?: number; fill?: boolean; startFolded?: boolean }>; hooks?: Record unknown>; /** * Keyboard shortcut bindings. Each entry's `handler` is registered as a * hook named `shortcut:` so the host's keydown dispatcher can fire it. */ shortcuts?: Record void | Promise; }>; activate?: (api: unknown) => void | Promise | { dispose: () => void }; default?: unknown; } let parentWindow: Window | null = null; let parentOrigin: string | null = null; let pluginExports: PluginExports | null = null; let mode: 'background' | 'slot' | null = null; let slotName: SlotName | null = null; let bootDone = false; // Guards the initial sandbox-ready post against React strict mode's double // useEffect invocation; the parent only needs to be pinged once per iframe. let readyPosted = false; const pendingApi = new Map void; reject: (err: Error) => void }>(); // The plugin's settings. One object for the iframe's lifetime, updated in // place on 'settings-change', so code that kept a reference sees new values. const settingsState: Record = {}; // The app language and regional settings, pushed by the host on init and on every change. let currentRegional: RegionalSnapshot = { locale: 'en', dateLocale: 'en', hour12: false, timeZone: 'UTC', firstDayOfWeek: 1, }; const localeListeners = new Set<(locale: string) => void>(); // The plugin's strings. The host sends only the tables of the current locale // chain (plugin-i18n tablesFor) and the next ones with each locale-change. let localeTables: LocaleTables = {}; /** Add the tables a locale-change brought; strings the plugin added itself win. */ function mergeLocaleTables(next: LocaleTables | undefined): void { if (!next) return; for (const [locale, table] of Object.entries(next)) { localeTables[locale] = { ...table, ...(localeTables[locale] ?? {}) }; } } function currentLocale(): string { return (globalThis as unknown as { __PLUGIN_LOCALE__?: string }).__PLUGIN_LOCALE__ || 'en'; } function applyLocale(locale: string, regional?: RegionalSnapshot): void { (globalThis as unknown as { __PLUGIN_LOCALE__?: string }).__PLUGIN_LOCALE__ = locale; if (regional) { currentRegional = regional; } else { currentRegional = { ...currentRegional, locale, dateLocale: locale, }; } document.documentElement.lang = locale; // Slots sit inside an RTL page in Arabic, Hebrew and Persian; their own // document has to flip too. document.documentElement.dir = textDirection(locale); for (const listener of localeListeners) { try { listener(locale); } catch (err) { console.error('[plugin] locale listener failed', err); } } } function formatIntl(date: Date | number | string, options: Intl.DateTimeFormatOptions): string { try { const d = date instanceof Date ? date : new Date(date); if (isNaN(d.getTime())) return ''; const locale = currentRegional.dateLocale || currentRegional.locale || 'en'; return new Intl.DateTimeFormat(locale, { timeZone: currentRegional.timeZone, ...options }).format(d); } catch { return ''; } } function formatTime(date: Date | number | string, options?: Intl.DateTimeFormatOptions): string { return formatIntl(date, { hour12: currentRegional.hour12, hour: 'numeric', minute: 'numeric', ...options }); } function formatDate(date: Date | number | string, options?: Intl.DateTimeFormatOptions): string { return formatIntl(date, options ?? {}); } const settingsListeners = new Set<(settings: Record) => void>(); function applySettings(next: Record): void { for (const key of Object.keys(settingsState)) delete settingsState[key]; Object.assign(settingsState, next); for (const listener of settingsListeners) { try { listener(settingsState); } catch (err) { console.error('[plugin] settings listener failed', err); } } } // What api.host.features says: one object for the iframe's lifetime, // updated in place on 'host-change' like the settings. const hostFeaturesState: HostFeaturesView = { externalSenderLabel: false, externalRecipientWarning: false }; const hostFeatureListeners = new Set<(features: HostFeaturesView) => void>(); function applyHostFeatures(next: HostFeaturesView | undefined): void { if (!next) return; hostFeaturesState.externalSenderLabel = next.externalSenderLabel === true; hostFeaturesState.externalRecipientWarning = next.externalRecipientWarning === true; for (const listener of hostFeatureListeners) { try { listener(hostFeaturesState); } catch (err) { console.error('[plugin] host feature listener failed', err); } } } const pendingCallbacks = new Map void; reject: (err: Error) => void }>(); const hookHandlers: Record unknown> = {}; function sendToHost(msg: SandboxToHost, transfer?: Transferable[]): void { if (!parentWindow || !parentOrigin) return; if (transfer) parentWindow.postMessage(msg, parentOrigin, transfer); else parentWindow.postMessage(msg, parentOrigin); } // ─── Activity reports ──────────────────────────────────────── /** * Input that counts as the user being here for the host's idle timeout: the * host window's own list (components/session/session-timeout-guard.tsx), * which input in this frame never reaches. Focus doesn't count there and * doesn't here: a focused frame left alone would keep the session open. */ const ACTIVITY_EVENTS = ['pointerdown', 'pointermove', 'keydown', 'touchstart', 'wheel'] as const; /** * At most one report this often. The idle limit is whole minutes, so a * report up to 15 s late costs at most 15 s of it, while a user working in * the frame sends no more than four messages a minute. */ export const ACTIVITY_REPORT_MS = 15_000; let reportActivity: (() => void) | null = null; let lastActivityReport = -Infinity; function onUserInput(event: Event): void { // A plugin can dispatch events, but not trusted ones. if (!event.isTrusted || !reportActivity) return; const at = Date.now(); if (at - lastActivityReport < ACTIVITY_REPORT_MS) return; lastActivityReport = at; reportActivity(); } /** * The port reports go through, handed to the host with 'sandbox-ready', * before any plugin code runs. The plugin shares this frame and can post to * the host as the runtime does, but it never sees this port, and the host * counts only what comes through it. `postMessage` is bound now, so a * plugin patching MessagePort.prototype later doesn't get hold of the port. * (A privileged, same-origin plugin can reach the host page anyway.) */ function openActivityPort(): MessagePort | null { if (typeof MessageChannel === 'undefined') return null; const channel = new MessageChannel(); const post = channel.port1.postMessage.bind(channel.port1); reportActivity = () => { try { post(null); } catch { /* host gone */ } }; return channel.port2; } // ─── Host binding ──────────────────────────────────────────── /** * The one window allowed to drive this runtime, and the origin it must post * from. Both are fixed from browser-owned facts at load time and never * learned from a message: * * - `window.parent` is the document that framed us. The host bridge creates * that iframe itself, so this is the mirror of its own contentWindow check. * A top-level load (window.open from another site, a typed URL) has no * parent - `parent === window` - and gets no host at all: `window.opener` * is never a host. * - `location.origin` is the URL origin even when this iframe runs with an * opaque origin (sandbox="allow-scripts"), and the host page is served * from that same origin: the bridge loads a same-origin path and the route * CSP pins `frame-ancestors 'self'`. * * Pinning the first sender instead (pre-fix) let any website window.open() * the route, post its own `init` before a real host could, and run its code * under this document's `'unsafe-eval'` CSP in the webmail origin * (GHSA-96cx-gx36-3g79). Returns null when there is no acceptable host. */ function resolveHost(): { window: Window; origin: string } | null { if (typeof window === 'undefined') return null; const parent = window.parent; if (!parent || parent === window) return null; const origin = window.location.origin; // 'null' is what opaque URL origins (blob:, data:, file:) serialise to; an // attacker frame could match it, so it never counts as a host origin. if (!origin || origin === 'null') return null; return { window: parent, origin }; } // ─── Theme replay ──────────────────────────────────────────── const THEME_STYLE_ID = '__plugin_host_theme'; /** * Replay a host theme snapshot inside the iframe: inject the token + font CSS * and mirror the `.dark` class onto so plugin styles that key off * `.dark` (or read `var(--color-*)`) behave like the host. Idempotent — safe * to call again on every 'theme-change'. */ function applyHostTheme(theme: ThemeSnapshot): void { if (typeof document === 'undefined') return; let styleEl = document.getElementById(THEME_STYLE_ID) as HTMLStyleElement | null; if (!styleEl) { styleEl = document.createElement('style'); styleEl.id = THEME_STYLE_ID; document.head.appendChild(styleEl); } styleEl.textContent = themeSnapshotToCSS(theme); document.documentElement.classList.toggle('dark', theme.dark); } function uid(): string { return Math.random().toString(36).slice(2) + Date.now().toString(36); } // ─── Sandboxed API facade (calls flow to host via postMessage) ─ const DEFAULT_API_TIMEOUT_MS = 30_000; // http.post / http.fetch can be carrying an attachment to an external store, // which is a transfer rather than a round-trip - 30s is not enough for the // files a plugin has any reason to offload. Still bounded so a hung host // can't leak the pending promise. const NETWORK_API_TIMEOUT_MS = 120_000; function callApi(method: string, args: unknown[], timeoutMs: number = DEFAULT_API_TIMEOUT_MS): Promise { const id = uid(); return new Promise((resolve, reject) => { pendingApi.set(id, { resolve, reject }); sendToHost({ type: 'api-request', id, method, args }); // Bounded so a hung host can't leak the promise forever. Interactive UI // dialogs (ui.confirm/ui.alert) pass timeoutMs <= 0 to opt out: they wait // for human input, the host always resolves them on confirm/cancel/close, // and any still-pending call dies with the iframe on teardown - so there's // nothing to leak, and a thinking user must not trip a 30s timeout. if (timeoutMs > 0 && Number.isFinite(timeoutMs)) { setTimeout(() => { const entry = pendingApi.get(id); if (!entry) return; pendingApi.delete(id); entry.reject(new Error(`API call ${method} timed out after ${Math.round(timeoutMs / 1000)}s`)); }, timeoutMs); } }); } // ─── api.proxy streams ─────────────────────────────────────── interface ProxyStream { controller?: ReadableStreamDefaultController; onProgress?: (loaded: number, total: number) => void; } const proxyStreams = new Map(); interface ProxyFetchInit { method?: string; headers?: Record; body?: string | ArrayBuffer | Uint8Array | Blob | null; /** "text" (default), "json", "arraybuffer", or "stream" for a ReadableStream body. */ responseType?: 'text' | 'json' | 'arraybuffer' | 'stream'; /** Upload progress, in bytes. */ onProgress?: (loaded: number, total: number) => void; /** Store these JSON fields of the response as the credential instead of returning them. */ capture?: { secret: string; username?: string }; /** Stops the request (and a streamed body). */ signal?: AbortSignal; } async function proxyFetch(credentialId: string, url: string, init: ProxyFetchInit = {}): Promise { const streamId = uid().replace(/[^a-z0-9]/g, '').slice(0, 24); const entry: ProxyStream = { onProgress: init.onProgress }; proxyStreams.set(streamId, entry); const stream = init.responseType === 'stream' ? new ReadableStream({ start(controller) { entry.controller = controller; }, cancel() { proxyStreams.delete(streamId); void callApi('proxy.cancel', [streamId]).catch(() => {}); }, }) : null; const abort = () => { void callApi('proxy.cancel', [streamId]).catch(() => {}); try { entry.controller?.error(new Error('cancelled')); } catch { /* closed */ } proxyStreams.delete(streamId); }; init.signal?.addEventListener('abort', abort, { once: true }); const { onProgress: _p, signal: _s, ...plain } = init; void _p; void _s; try { // No overall timeout: a big upload or a long AI answer takes as long as // it takes, and api.proxy.cancel / the signal stop it. const res = await callApi('proxy.fetch', [credentialId, url, { ...plain, streamId }], 0) as Record; if (!stream || !res.ok) proxyStreams.delete(streamId); return stream && res.ok ? { ...res, body: stream } : res; } catch (err) { proxyStreams.delete(streamId); throw err; } } function invokeHostCallback(callbackId: string, args: unknown[]): Promise { const id = uid(); return new Promise((resolve, reject) => { pendingCallbacks.set(id, { resolve, reject }); sendToHost({ type: 'callback-invoke', id, callbackId, args }); setTimeout(() => { const entry = pendingCallbacks.get(id); if (!entry) return; pendingCallbacks.delete(id); entry.reject(new Error('host callback timed out after 30s')); }, 30_000); }); } /** * Walks an object graph received from the host and rehydrates * `{ __pluginCallback: id }` markers into stub functions that round-trip via * the 'callback-invoke' RPC. Mirrors `encodeCallbacks` in host-bridge.ts. */ function decodeCallbacks(value: unknown, depth = 0): unknown { if (depth > 6) return null; if (value === null || value === undefined) return value; const t = typeof value; if (t !== 'object') return value; if (Array.isArray(value)) return value.map((v) => decodeCallbacks(v, depth + 1)); const obj = value as Record; if (typeof obj.__pluginCallback === 'string') { const cbId = obj.__pluginCallback; return (...args: unknown[]) => invokeHostCallback(cbId, args); } const out: Record = {}; for (const [k, v] of Object.entries(obj)) { out[k] = decodeCallbacks(v, depth + 1); } return out; } type PluginManifest = BackgroundInit['manifest']; type PluginKeywordVisibility = 'show' | 'hide' | 'unread'; interface PluginKeywordDefinition { id: string; label: string; color: string; visibility?: PluginKeywordVisibility; /** The plugin that added it with keywords.add; absent on the user's own tags. */ addedBy?: string; } type PluginKeywordDefinitionInput = Omit & { color?: string }; type PluginKeywordPatch = Pick & Partial>; interface PluginKeywordCounts { total: number; unread: number; } function buildPluginApi(manifest: PluginManifest) { applySettings({ ...manifest.settings }); localeTables = JSON.parse(JSON.stringify(manifest.locales ?? {})); return { plugin: { id: manifest.id, version: manifest.version, /** Current settings, defaults filled in. Updated in place when the user changes them. */ settings: settingsState, /** Called with the new settings whenever the user changes them. Returns an unsubscribe function. */ onSettingsChange: (listener: (settings: Record) => void) => { settingsListeners.add(listener); return () => { settingsListeners.delete(listener); }; }, }, /** * Bulwark features that replace what plugins did, so a plugin can step * back while Bulwark does its job. Updated in place; no permission needed. */ host: { features: hostFeaturesState, /** Called with the new features whenever one turns on or off. Returns an unsubscribe function. */ onFeaturesChange: (listener: (features: HostFeaturesView) => void) => { hostFeatureListeners.add(listener); return () => { hostFeatureListeners.delete(listener); }; }, }, /** The app the plugin runs in: product, the administrator's name for it, version, edition. No permission needed. */ app: { getInfo: () => callApi('app.getInfo', []) as Promise, /** Settings matching a query (the user's language or English): page, label, description. No permission needed. */ searchSettings: (query: string, options?: { limit?: number }) => callApi('app.searchSettings', [query, options]) as Promise, /** The user's preferences: layout, formats, reading and sending behaviour. Needs settings:read. */ getSettings: () => callApi('app.getSettings', []) as Promise, }, crypto: { getPublicKeys: () => callApi('crypto.getPublicKeys', []), createPublicKey: (input: PublicKeyInput) => callApi('crypto.createPublicKey', [input]), removePublicKey: (keyId: string) => callApi('crypto.removePublicKey', [keyId]), setEncryptionAtRest: (config: EncryptionAtRestConfig) => callApi('crypto.setEncryptionAtRest', [config]), getEncryptionAtRest: () => callApi('crypto.getEncryptionAtRest', []), getWebAuthn: (masterCredentialIdBytes: number[]) => callApi('crypto.getWebAuthn', [masterCredentialIdBytes, manifest.id], 0), createWebAuthn: (name: string, displayName: string) => callApi('crypto.createWebAuthn', [manifest.id, name, displayName], 0), getPublicKeyFromWKD: (email: string) => callApi('crypto.getPublicKeyFromWKD', [email]), }, storage: { get: (key: string) => callApi('storage.get', [key]), set: (key: string, value: unknown) => callApi('storage.set', [key, value]), remove: (key: string) => callApi('storage.remove', [key]), keys: () => callApi('storage.keys', []), }, user: { getAccounts: () => callApi('user.getAccounts', []), /** * The signed-in user: their own JMAP account id (Stalwart's principal * id), address and name. Needs account:read. */ getSelf: () => callApi('user.getSelf', []) as Promise<{ accountId: string; email: string; name: string }>, /** * Every mail account of the signed-in login: their own ('personal'), * team mailboxes they are a member of ('group') and mailboxes others * shared with them ('shared'); `isOpen` marks the open folder's. * Needs account:read. */ getMailAccounts: () => callApi('user.getMailAccounts', []) as Promise>, /** * People from the server's directory, as the named mail account (else * the user's own) sees it: by principal id (at most 20) or by a part * of their name or address (3 characters or more). At most 20 results * and 10 lookups a minute. `complete` is false when the administrator * turned directory lookups off; only the people the user shares an * account with are known then. Needs directory:read. */ findPeople: (query: { text?: string; ids?: string[]; accountId?: string }) => callApi('user.findPeople', [query], NETWORK_API_TIMEOUT_MS) as Promise<{ people: Array<{ id: string; type: string; name: string; email: string }>; complete: boolean; }>, getIdentities: () => callApi('user.getIdentities', []), /** The IANA time zone the app shows times in (the user's setting, else the browser's). */ getTimeZone: () => callApi('user.getTimeZone', []) as Promise, logout: () => callApi('user.logout', []), }, http: { // A Blob/File body is sent as a binary request; options.headers may then // carry Content-Type and X-Plugin-* metadata for the receiving route. // Any other body keeps the stock JSON behaviour. post: (path: string, body: Record | Blob, options?: { headers?: Record }) => callApi('http.post', [path, body, options], NETWORK_API_TIMEOUT_MS), fetch: (url: string, init?: unknown) => callApi('http.fetch', [url, init], NETWORK_API_TIMEOUT_MS), }, // Safe keyword methods are available to untrusted plugins with the // matching email permission. Raw blob/submission methods remain restricted // to the privileged tier for crypto plugins. jmap: { /** * Enumerate keywords in the active account. JMAP servers supporting * Keyword/get supply exact counts and provider-label metadata; other * servers fall back to scanning message keywords. */ getKeywords: (options?: { limit?: number }) => callApi('jmap.getKeywords', [options]) as Promise<{ keywords: Record; scanned: number; total: number; complete: boolean; labels: Array<{ id: string; name: string; color: string | null; total: number; unread: number; isProviderLabel: boolean; source: 'provider' | 'message'; }>; }>, /** * Replace an email's complete keyword map. Omitted keywords are removed; * use api.email.setKeyword/removeKeyword for an incremental mutation. */ setKeywords: (emailId: string, keywords: Record, accountId?: string) => callApi('jmap.setKeywords', [emailId, keywords, accountId]) as Promise, /** Add one keyword without changing the message's other keywords. */ setKeyword: (emailId: string, keyword: string, accountId?: string) => callApi('jmap.setKeyword', [emailId, keyword, accountId]) as Promise, /** Remove one keyword without changing the message's other keywords. */ removeKeyword: (emailId: string, keyword: string, accountId?: string) => callApi('jmap.removeKeyword', [emailId, keyword, accountId]) as Promise, /** Fetch a blob's raw bytes by id. Resolves to a Uint8Array. */ fetchBlob: (blobId: string, opts?: { name?: string; type?: string, rangeHeader?: number }) => callApi('jmap.fetchBlob', [blobId, opts]) as Promise, /** Upload bytes to the mail server (email:blob-write); pass the blob id to a composer's onAttach. */ uploadBlob: (content: Uint8Array, name: string, type: string) => callApi('jmap.uploadBlob', [content, name, type]) as Promise<{ blobId: string; size: number; type: string; }>, /** Submit a fully-formed raw RFC822 message (already signed/encrypted). */ sendRaw: ( rawBytes: ArrayBuffer | ArrayBufferView, identityId: string, opts?: { delayedUntil?: string; envelopeRecipients?: string[] }, ) => callApi('jmap.sendRaw', [rawBytes, identityId, opts]), /** Submit without putting in sent box a fully-formed raw RFC822 message (already signed/encrypted). */ submitRaw: ( rawBytes: ArrayBuffer | ArrayBufferView, identityId: string, opts?: { delayedUntil?: string; envelopeRecipients?: string[] }, ) => callApi('jmap.submitRaw', [rawBytes, identityId, opts]), /** Import a fully-formed raw RFC822 message into the user's mailbox. */ importRaw: ( rawBytes: ArrayBuffer | ArrayBufferView, mailboxRoles: string[], opts?: { keywords?: Record; accountId?: string }, ) => callApi('jmap.importRaw', [rawBytes, mailboxRoles, opts]), }, contacts: { get: (contactId: string) => callApi('contact.get', [contactId]) as Promise, update: (contactId: string, updates: Partial) => callApi('contact.update', [contactId, updates]) as Promise, create: (contact: ContactCard) => callApi('contact.create', [contact]) as Promise, search: (query: string) => callApi('contact.search', [query]) as Promise, list: (addressBookId?: string) => callApi('contact.list', [addressBookId]) as Promise, remove: (contactId: string) => callApi('contact.delete', [contactId]) as Promise, }, addressBooks: { list: () => callApi('addressbook.list', []) as Promise, create: (name: string) => callApi('addressbook.create', [name]) as Promise, }, /** * Used to alterate files before they are uploaded to server. * Edited files are saved on indexedDB and remove once the upload to server begins. * `get` needs the email:blob-read permission. `save` needs * email:blob-write AND the privileged tier - replacing the bytes of a file * the user is about to send is not something an untrusted plugin may do. */ upfiles: { save: (formerFileId:string, file:File) => callApi('upfiles.save', [formerFileId, file]) as Promise, get: (fileId:string) => callApi('upfiles.get', [fileId]) as Promise, }, // Notifications (permission: ui:notifications). notifications: { /** * A system notification when the user allowed them for the webmail, * otherwise a toast; either way it names this plugin. At most 5 a * minute. Clicking a system notification brings the webmail to the * front and fires this plugin's onNotificationClick hook with the tag. * Resolves to 'system' or 'toast'. */ show: (notification: NotificationInput) => callApi('notifications.show', [notification]) as Promise<'system' | 'toast'>, }, // The message being written. `composerId` comes from the composer: the // context of a click on a composer action, or a composer slot's props. composer: { /** The user's own text (no signature, no quote) as { html, text }. Needs compose:read. */ getBody: (composerId: string) => callApi('composer.getBody', [composerId]) as Promise<{ html: string; text: string }>, /** The selection as { html, text, empty }. Needs compose:read. */ getSelection: (composerId: string) => callApi('composer.getSelection', [composerId]) as Promise<{ html: string; text: string; empty: boolean }>, /** * Replace the selection, or insert at the caret when nothing is * selected; `{ below: true }` adds after the selection instead. One * Ctrl+Z undoes it. Needs compose:write. */ replaceSelection: (composerId: string, content: { text: string } | { html: string }, options?: { below?: boolean }) => callApi('composer.replaceSelection', [composerId, content, options]) as Promise, /** Replace the user's own text; the signature and the quote stay. Needs compose:write. */ replaceBody: (composerId: string, content: { text: string } | { html: string }) => callApi('composer.replaceBody', [composerId, content]) as Promise, /** Attach a blob from jmap.uploadBlob. Needs email:blob-write. */ attach: (composerId: string, file: { blobId: string; name: string; type?: string; size: number }) => callApi('composer.attach', [composerId, file]) as Promise, }, toast: { success: (m: string) => { void callApi('toast.success', [m]); }, error: (m: string) => { void callApi('toast.error', [m]); }, info: (m: string) => { void callApi('toast.info', [m]); }, warning: (m: string) => { void callApi('toast.warning', [m]); }, }, ui: { /** Opens a host-rendered confirm dialog. Resolves to true on confirm, false otherwise. * No timeout - it waits for the user's choice. */ confirm: (opts: { title?: string; message?: string; confirmLabel?: string; cancelLabel?: string; danger?: boolean }) => callApi('ui.confirm', [opts], 0) as Promise, /** Opens a host-rendered alert (one button). Resolves once dismissed. No timeout. */ alert: (opts: { title?: string; message?: string; confirmLabel?: string }) => callApi('ui.alert', [opts], 0) as Promise, /** Opens a host-rendered prompt collecting one or more (optionally masked) * fields. Resolves to a name→value map on submit, or null if cancelled. * No timeout. */ prompt: (opts: { title?: string; message?: string; confirmLabel?: string; cancelLabel?: string; fields?: Array<{ name: string; label: string; type?: 'text' | 'password'; placeholder?: string; required?: boolean }>; }) => callApi('ui.prompt', [opts], 0) as Promise | null>, /** Opens one of this plugin's OWN slots (see the 'plugin-dialog' * SlotName) inside a real, app-root, full-size dialog - unlike every * other slot, which renders wherever it's placed in the page and is * constrained by that spot's own layout. Use this for anything that * needs to be a large, genuinely clickable custom UI (a file browser, * a multi-step form, etc.) rather than a toolbar/row-sized control. * Resolves to whatever value the slot component passes to its * `onResult` prop, or null if the user closes the dialog without * calling it. No timeout - it waits for the user. */ openDialog: (opts: { title?: string; slot: string; extraProps?: Record; width?: number }) => callApi('ui.openDialog', [opts], 0) as Promise, /** Re-runs the onRenderEmailBody hook for the open message (e.g. after a * crypto plugin unlocks a key) so its body re-renders without a reload. */ rerenderEmail: () => callApi('ui.rerenderEmail', []) as Promise, rerenderFetchedEmails: () => callApi('ui.rerenderFetchedEmails', []) as Promise, /** Opens an http/https URL in a new tab via host `window.open`. */ openExternalUrl: (url: string, target?: string) => callApi('ui.openExternalUrl', [url, target]) as Promise, /** * Print a page the plugin made, such as a document drawn from data: * HTML with