Skip to content

Security: justingluska/penguin

Security

docs/SECURITY.md

Penguin security

Penguin is a local-first email client. There is no Penguin server, and mail flows only between your Mac and Google. So the things worth attacking are the mail itself (hostile HTML), the tokens on disk, and the code we ship. This document covers how each is defended. Background research is in research/08-security-privacy-oss.md.

Threat model

# Threat Surface Precedent Mitigation in Penguin Status
T1 Script in an email runs with app privileges (session theft, IPC calls, mailbox exfiltration) HTML body rendering Zero (Mail-0) CVE-2025-52557; Roundcube CVE-2025-68461; Zimbra CVE-2022-24682 Four layers: allowlist sanitizer in Rust, sandboxed iframe without allow-scripts, a deny-by-default CSP inside the frame, and the app CSP the frame inherits. See Rendering pipeline. Done
T2 Email navigates the app, or phishes inside it Links, forms, meta refresh, <base> Classic webmail phishing overlays Forms, meta, and base are removed. Every link gets target=_blank rel="noopener noreferrer". The native link guard cancels every navigation away from the app and opens http/https/mailto in the system browser. position: fixed is stripped. Done (link guard lives in src-tauri)
T3 Sender learns you opened the mail, and your IP, from remote content <img>, srcset, background, CSS url() Superhuman read receipts (2019); spy pixels in general Remote images are blocked until you click "Load images". Known trackers and tiny or hidden images are stripped even after that (Settings → Privacy "Block tracking pixels", on by default; off treats them like any other remote image, still reported). Loaded images are forced to https. no-referrer. Remote fonts, @import, cursor/list-style URLs are never loaded. Done
T4 CSS used to exfiltrate or overlay <style>, style="" Roundcube CVE-2026-26079 (CSS injection) Allowlist CSS sanitizer: property allowlist, function allowlist, no escapes, no @import/@font-face, and url() only through the image policy. Each message sits in its own frame, so selectors can't reach app UI or other messages. Done
T5 Parser differential (mXSS): markup that is safe as sanitized but mutates when the browser re-parses it Sanitizer output DOMPurify bypasses 2019–2024 ammonia uses the html5ever tree builder, the same algorithm browsers use. SVG and MathML are dropped wholesale, and raw-text elements are removed with their content. Tests re-parse our output with html5ever and check the resulting DOM, not the string. Done
T6 Hostile message stalls the app Deeply nested or attribute-flooded HTML Parser DoS Complexity guard: past 2048 nesting levels or 128 attributes on one tag, the message renders as a simplified text view. A 2 MB newsletter renders in about 31 ms (release). Done
T7 OAuth refresh tokens stolen from disk or logs Token storage, logs Spark storing credentials server-side; npm malware that harvests tokens from disk Refresh tokens live only in the macOS Keychain. Access tokens are memory only. Tokens, codes, verifiers and client secrets have redacting Debug impls and are never logged. Done (auth agent)
T8 Compromised dependency ships to users Cargo and npm supply chain node-ipc, the chalk/debug phishing, the @ctrl/tinycolor worm Committed lockfiles, cargo deny (advisories, licenses, sources), npm audit, review of new dependencies. See Supply chain. cargo deny check passes; CI pending
T9 Mail data leaks through the local DB SQLite file in the app data dir – The file sits under FileVault in the user's data dir. SQLCipher encryption at rest is a planned follow-up. Bodies are never logged. Partial
T10 Encrypted mail exfiltrated through HTML (EFAIL) PGP/S/MIME, not supported yet EFAIL (2018) No PGP/S/MIME today. If it is added, decrypted parts must never be combined with remote content. N/A
T11 Sender avatars leak who writes to you, attack the image decoder, or reach the local network BIMI logos, company icons, Gravatar, People API photos Hostile SVG (script, external refs, entity bombs); SSRF via attacker DNS Fetched only by Rust, never from email HTML or the webview; no per-message data in any request; every image decoded under limits and re-encoded as our own PNG (SVG only rasterized); public-IP-only resolver, HTTPS only; brand imagery only for DMARC-authenticated senders. See Sender avatars. Done
T12 The image viewer becomes a way in: email content opens the app's UI on its own terms, loads a blocked image, or navigates the app Clicks on pictures in message bodies – The only bridge out of the frame is an anchor the app writes itself, on a custom scheme the sanitizer can never produce; the native link guard validates and re-emits it; the UI honors only a per-document nonce it minted and an index it assigned, and shows only a source the frame already rendered. Files that leave the app (drag out, Save As) come only from those same checked bytes, and the native drag accepts only a file the app itself wrote this session. See Image viewer. Done
T13 Share links publish more than the user meant, leak the storage secret, or outlive their purpose Copy Share Link; agents' create_share_link / penguin-cli share-link Public buckets exposing mail attachments; prompt injection steering agents Off until the user sets up their own storage. Uploads happen only on the user's click, or on an agent's request answered by the app when the agent level is at least Read, organize and draft and the user turned on "Let agents (CLI and MCP) create share links" (both checked by the app on every request; agents name attachments and cid: pictures only, never a web address; the CLI never sees the storage or its secret; the audit line has no link, key or file name). Private bucket plus SigV4 presigned GETs that expire (1 h to 7 days) under a 128-bit random key; the Settings test warns if the bucket answers without a signature. The secret stays in the Keychain; links, keys and the secret are never logged. Expired uploads are deleted in the background, with a lifecycle rule as the backstop. See Share links. Done
T14 An email steers an AI agent into sending your data to its author, deleting your drafts, or mailing on your behalf penguin-cli and its MCP server (draft and send tools) Indirect prompt injection against email agents (2023–2026 research and incidents) Off by default; levels set only in Settings; sending needs a typed acknowledgement; agents touch only drafts agents made; sends wait in the outbox (1 min default) with a notification and Cancel, go only to people you've emailed by default, and are cancelled when you lower the level; every request audited without content. See Agents. Done
T15 Another local process or user drives the app's agent socket, or reads what it returns The Unix socket the app serves for penguin-cli Local IPC privilege escalation Socket in a 0700 directory (socket 0600), kernel peer-uid check, per-install 0600 token compared in constant time, level checked on the app's in-memory settings. Same-user processes are out of scope (they can already read the database). Done
T16 An agent attaches a secret (an SSH key, the mail database, the agent token) to an email Draft attachments by path Data exfiltration through "attach this file" Paths resolved first, then only regular files inside the home folder; hidden components, ~/Library and Penguin's own folders refused; checked on the opened handle (same inode). Sends still need the send level and, by default, a known recipient. Done
T17 An email steers an AI agent into hiding mail: trashing the security alert about it, archiving or marking read the bank's warning, reporting the real sender as spam penguin-cli and its MCP server (organizing tools) Indirect prompt injection against email agents; attackers who delete their own alert emails after an account takeover Organizing needs "Read, organize and draft" (off by default) and goes through the app's own actions. Nothing is ever deleted: there is no permanent-delete tool, and every change answers with its undo calls. trash and report_spam take at most 25 conversations per call and 200 an hour each; system labels (Inbox, Trash, Spam…) can't be changed through add_label/remove_label, so the caps can't be sidestepped. Every call shows a toast with Undo in the app and a line in Recent agent activity with its counts (the audit keeps tool, account, counts and outcome; no subjects, addresses or label names). Tool descriptions and the server's instructions tell the model never to organize because an email says so. See Agents. Done

Rendering pipeline

Gmail API ──raw HTML──▶ penguin-render (Rust) ──sanitized document──▶ MessageBody.tsx ──srcdoc──▶ <iframe sandbox>
                        prescan → ammonia → CSS/URL policy → wrap                                  + meta CSP + inherited app CSP

1. penguin-render::render_html (crates/penguin-render)

  1. Prescan (prescan.rs). A fast hand-rolled scan collects <style> text, the <body> tag's colors, which image URLs are tiny or hidden (tracking pixels), nesting depth, and attribute counts. It only gathers hints and never decides what markup survives.
  2. Complexity guard. If nesting depth exceeds 2048 or any tag has more than 128 attributes, the message renders as escaped text with a "Simplified view" notice. html5ever's tree construction is quadratic in both.
  3. ammonia allowlist.
    • Tags kept: text and layout elements newsletters and receipts use: a, b, blockquote, br, center, div, font, h1–h6, hr, img, lists, p, pre, span, the full table family, details/summary, and similar.
    • Removed with their content: script, style (re-emitted after CSS sanitizing, see below), title, noscript, template, iframe, frame(set), object, embed, applet, textarea, select, svg, math, head, meta, link, base, audio, video, canvas, map, portal, dialog.
    • Unwrapped: everything else, such as form, button, input, Office o:p. The tag goes and its children stay.
    • Attributes: generic align bgcolor border class dir height id lang style title valign width, plus per-tag presentational attributes (cellpadding, colspan, face, …). No on*, no srcdoc, action, formaction, ping, xlink:href, or data-*.
    • URLs: a[href] allows http, https and mailto only; relative URLs are dropped. Links get target="_blank" rel="noopener noreferrer".
  4. Links (links.rs). Every a[href] that passed the scheme check is checked against click-tracking redirects (known tracker hosts plus ESP click paths such as /ls/click); these are only counted (tracked_links), since the destination is hidden in the tracker's token. With RenderOptions::strip_link_tracking (Settings → Privacy "Remove tracking from links", off by default) the per-person and per-click parameters on Firefox's query-stripping list plus the email-relevant part of Brave's (mc_eid, _hsenc, mkt_tok, fbclid, gclid, …; not utm_*) are removed. Links to unsubscribe or preference pages are left alone, because some identify the reader with exactly these parameters. The rewritten URL is re-serialized by the url crate, so it can't carry markup, and the XSS corpus runs with stripping on. The renderer reports names only (link_params), never values, and keeps a cleaned → original map (not serialized) so the Unsubscribe button acts on the link as sent.
  5. Image policy applies to every image URL: img[src], srcset, background, and CSS url().
    • cid: is rewritten to the message's own inline part as a data: URL. Only data:image/{png,jpeg,gif,webp,bmp,avif,x-icon};base64 is accepted; SVG and non-image parts are rejected.
    • A known tracker (trackers.rs: Mailchimp, HubSpot, SendGrid, Superhuman, Mixmax, Yesware, Streak, Mailtrack, Salesforce, Marketo, Iterable, Brevo, SES, Postmark, LinkedIn, GitHub and ~60 more), or an image the prescan marked tiny (≤ 3×3 px) or hidden, is removed and counted as a tracker, even when images are allowed. The user can turn this off (RenderOptions::allow_tracking_pixels, Settings → Privacy "Block tracking pixels"): the tracker then goes through the rest of this policy like any remote image, and is still reported, with status held (images blocked) or loaded (images allowed) instead of removed, so the privacy row can warn that it loaded. For the message's privacy details the renderer also reports what it removed (RenderedHtml.trackers: host, path, known-tracker vs hidden image, matched rule and company), capped at 50 entries and 80-character paths. The query string and fragment are never included, because they usually carry the recipient's address or a per-recipient id; only a hadQuery flag says one was there.
    • Other http(s) images are removed and counted (distinct URLs) unless allow_remote_images is set. When they are allowed, they are upgraded to https.
    • Images whose host is this machine or a private network are always dropped, even after "Load images". That covers localhost, *.localhost (including the app's own tauri./ipc./avatar.localhost origins on Windows), .local/.internal/.home.arpa names and dotless names, and loopback, private, link-local, CGNAT and ULA IP literals in any notation. This stops an email from making the user's machine send GET requests to the app's protocols, the local network or router admin pages. Hostnames that resolve to private addresses (DNS rebinding) are out of reach, because the webview does that fetch.
  6. CSS sanitizer (css.rs), used for style="", <style> blocks, and body styles.
    • Allowed: an allowlist of ~130 layout, typography, color and table properties, and a function allowlist (color functions, calc/min/max/clamp, gradients, and url() only on background/background-image).
    • Rejected: backslash escapes, <, >, braces, expression, behavior, -moz-binding, javascript:, position: fixed/sticky, and viewport-height units (they would feed back into the auto-height).
    • Stylesheets keep plain style rules and @media blocks. @import, @font-face, @keyframes, @supports, nested at-rules and light-mode or negated color-scheme queries are dropped. A (prefers-color-scheme: dark) block goes through the same rule checks and is moved to a separate dark sheet (the test rewritten to (min-width:0)), which stays off until the UI turns it on.
    • The output is rebuilt from the validated pieces, so it cannot break out of <style> or the attribute.
  7. Wrap the result in a complete document:
    • <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:[ https:]; style-src 'unsafe-inline'; font-src 'none'; media-src 'none'; form-action 'none'; base-uri 'none'">
    • <meta name="referrer" content="no-referrer">
    • Our base stylesheet: HTML mail gets a light canvas (and a dark one behind html[data-pg-scheme=dark]); plain text follows the app theme.
    • For a message that ships dark rules or declares color-scheme with dark (meta tag or CSS), the dark sheet: <style class="pg-dark-css" media="not all">, possibly empty. Its presence is the UI's signal that the message has its own dark design; the body can't forge it, because <style> never survives in the body.

render_text escapes every character, linkifies http/https/www./email, and folds >-quoted blocks and Outlook "Original Message" tails into <details>, which needs no JS.

2. The iframe (apps/desktop/src/features/message-body/MessageBody.tsx)

<iframe sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox" srcdoc=…>

  • No allow-scripts, so nothing in the message executes: no inline handlers, no javascript: URLs, no script elements. Also no allow-forms, allow-top-navigation, allow-modals or allow-downloads.
  • allow-same-origin without allow-scripts. This is the documented-safe combination. The sandbox-escape warning applies only when both flags are present, because frame script could then remove the sandbox attribute. Here the only script touching the frame is the parent's. We need same-origin so the parent can measure the document for auto-height.
  • Why not an opaque origin? We checked the alternatives. A sandboxed frame without same-origin is unreadable from the parent, so auto-height would need script inside the frame, which we won't allow; or a fixed max-height with nested scrolling in every message; or a Rust-side height estimate, which can't know layout width or font metrics. Same-origin without scripts gives exact, live height with no script in the frame.
  • Height. The parent reads .pg-root's box, and a parent-realm ResizeObserver watches it, which catches late images and <details> toggles. Height is capped at 40,000 px, after which the frame scrolls.
  • Pictures. The image viewer's click bridge reuses the link path below with an app-written penguin-image: anchor; see Image viewer.
  • Links. Verified in WKWebView: the parent's event listeners never fire on a no-script sandboxed document. So on macOS, clicks can't be caught in JS. Every link is target=_blank, and the sandbox allows popups, so a click becomes a new-window navigation request. The Rust link guard (a Tauri on_navigation plugin in src-tauri) cancels it and opens http/https/mailto in the system browser through the opener. The in-frame listener still helps on Chromium-based webviews and in the browser mock.
  • Dark email bodies (experimental setting, darkBody.ts). The parent darkens a loaded HTML document through the same same-origin access: it sets the dark sheet's media to all and data-pg-scheme on <html>, and writes inline color, background-color, background-image (a light gradient's stops, darkened), border-*-color and color-scheme values it computed itself from parsed computed styles. It never copies markup or URLs out of the message, and every write is recorded and undone by "Show original colors". The sanitizer, CSP and sandbox are unchanged.
  • Keyboard. Clicking into the frame moves focus there, where app shortcuts can't hear keys. When the pointer leaves the frame with no button held, focus returns to the app. Any selection in the frame stays, and a parent copy handler serves ⌘C from it as plain text. Importing frame nodes for an HTML flavor would let their images load outside the frame's CSP.

3. App CSP (apps/desktop/src-tauri/tauri.conf.json → app.security)

default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';
img-src 'self' data: https: avatar: http://avatar.localhost; font-src 'self' data:; connect-src ipc: http://ipc.localhost;
media-src 'self'; frame-src about: blob:; child-src about: blob:; worker-src 'none'; object-src 'none';
manifest-src 'none'; base-uri 'none'; form-action 'none';
frame-ancestors tauri://localhost http://tauri.localhost https://tauri.localhost
  • No remote scripts. Only the bundled 'self'. Fonts are self-hosted with @fontsource.
  • img-src avatar: http://avatar.localhost is the sender-avatar protocol (the second form is its Windows origin). It serves only cached PNGs we encoded; see Sender avatars. Email frames can't use it: their meta CSP allows only data: and https: images, and the sanitizer drops non-http(s) image URLs.
  • srcdoc frames inherit this policy, on top of their own meta CSP, so both are enforced. That is why style-src has 'unsafe-inline': email styles are inline. It is also why img-src includes https:: the frame's own policy is the one that decides whether remote images load.
  • dangerousDisableAssetCspModification: ["style-src"]. At build time, Tauri adds nonces or hashes to style-src for any <style> in index.html. Once a nonce is present, browsers ignore 'unsafe-inline', which would silently break every email's styling. script-src keeps Tauri's hashing.
  • frame-src about:. about:srcdoc isn't a fetch, so CSP doesn't govern it. We verified that WKWebView renders srcdoc frames even under frame-src 'none'. about: is the narrowest source that stays compatible with engines that check it anyway.
  • frame-src blob: is for the attachment PDF preview. WebKit disables its PDF viewer in sandboxed frames, so that frame can't carry a sandbox attribute.
    • Only our own script can mint blob URLs. The Rust side returns "pdf" only for bytes starting with %PDF-, the UI builds the Blob with the fixed type application/pdf, and the URL is revoked on close.
    • A blob document inherits this CSP, so even an HTML blob can't run inline script. Verified in WKWebView: pwned=0 both for a text/html blob with inline script and onerror, and for a PDF/HTML polyglot.
    • HTML attachments are never rendered as HTML.
  • frame-ancestors is the app origin, not 'none'. A blob document inherits its creator's CSP, including frame-ancestors. With 'none', the PDF-preview blob refused to be framed by the app itself. WebKit also doesn't match 'self' for a blob document under a custom-scheme origin, so the origin is listed explicitly (the two tauri.localhost entries are the Windows origin). Nothing outside the app can frame it. Email frames share the app origin through allow-same-origin, but they can't create frames: no frame elements survive sanitizing, and no script runs to mint blobs.
  • freezePrototype: true. Verified: the production bundle boots in WKWebView with Object.prototype frozen and this CSP, with no errors or violations.
  • Dev mode. On desktop, Tauri serves the CSP only through its asset protocol. tauri dev loads the Vite server directly, so the app CSP is not applied in development. The frame's meta CSP and sandbox still are.

Verification

  • XSS corpus. cargo test -p penguin-render runs 217 hand-written payloads plus a matrix of 38 URL-bearing attributes × 24 scheme tricks, each also placed inside CSS (1,824 more). Each payload renders with images blocked and allowed. The output is re-parsed with html5ever and walked against the allowlist: only allowed elements in the HTML namespace, no on*, safe URLs in every attribute, CSS free of script, escapes and unexpected url(). The oracle itself is tested against unsanitized input so it can't pass vacuously.
  • What the corpus covers: OWASP evasion classics, mXSS and namespace confusion (noscript, svg/math + style/mglyph/foreignObject, template, CDATA, comment tricks), the Zero CVE-2025-52557 shape, Roundcube SVG <animate> and body-attribute payloads, Zimbra-style breakouts, VML/conditional comments, and unclosed, deep, attribute-flooded and oversized inputs.
  • Performance: cargo test -p penguin-render --release --test perf. A 2 MB newsletter renders in about 31 ms, against a 50 ms budget.
  • WKWebView harness (manual, macOS). The real output, sandbox and app CSP were checked in a WKWebView served over a custom scheme like Tauri's. It confirmed: no script execution, email styles applied, srcdoc allowed under frame-src about:, parent-realm ResizeObserver and contentDocument reads working, and links reaching the navigation delegate as new-window requests.

Residual risks

  • Link destinations aren't previewed. WebKit gives the parent no hover events from the frame, so deceptive link text is possible. The system browser shows the real URL once opened.
  • Trusted image senders load automatically only when Gmail authenticated the message (sender_authenticated: DMARC pass or aligned DKIM). A spoofed "trusted" From is blocked and labeled as an unverified sender (settings.rs remote_images_for). What remains: a sender that is legitimately authenticated but compromised.
  • Loading images reveals your IP to image hosts. There is no proxy, because we don't run a server. Unknown trackers with normal-sized images are indistinguishable from content.
  • Focus. Keys pressed while the pointer is still over a message you just clicked go nowhere until the pointer leaves the frame.
  • Browser bugs. A browser sandbox or CSP bug in WebKit remains possible. The sanitizer is designed so that such a bug alone isn't enough.
  • Notifications. New-mail notifications (off by default) show the sender and subject in macOS Notification Center, which may also show them on the lock screen depending on System Settings. Never the body, and nothing about the message is logged.
  • Tracker list maintenance. The list needs periodic updates. Custom tracking domains of unlisted ESPs rely on the tiny/hidden heuristic.
  • Read receipt requests. Mail that asks for a read receipt (Disposition-Notification-To) never gets one from Penguin. The message/disposition-notification parts of receipts that come back for your own mail are parsed as plain text fields (penguin_core::receipts, capped at 16 KB), and only the Message-ID, recipient address and disposition are stored. See docs/PRIVACY.md.
  • Click tracking. Links wrapped by a sender's click tracker report the click when opened, and Penguin can't unwrap them without visiting them. They are counted and explained in the message's privacy details. See docs/PRIVACY.md.

Image viewer

Clicking a picture in a message opens a full-window viewer (src/features/image-viewer/, src-tauri/src/image_viewer.rs). It covers inline cid: pictures, remote pictures the user let load, and image attachments. The frame boundary stays as it was: no script in the frame, no new sandbox flags, the same CSPs.

Getting the click out of the frame. WebKit never delivers a no-script frame's events to parent listeners, so the parent can't see a click on an <img>. The bridge reuses the one channel that already works for links:

  1. After a body loads, and again on each layout change, decorate.ts (parent realm, same-origin DOM access, like auto-height and dark bodies) marks each loaded picture of at least 40×40 px:
    • A picture that isn't inside a link is wrapped in the app's own <a href="penguin-image://open/<nonce>/<index>" target="_blank">. The anchor is display: contents, so it adds no box.
    • A picture inside the sender's link keeps its click for the link. It gets a corner button in a zero-size layer instead, shown on hover by CSS alone (:has(img:hover)).
    • Each document gets a fresh 128-bit nonce from crypto.getRandomValues, registered with the frame element, the document, the message and the list of decorated <img> elements. The registration is dropped when the frame unmounts or loads another document.
  2. On macOS a click becomes a new-window navigation request. The link guard (lib.rs) sends penguin-image: URLs to image_viewer::parse_open. That function accepts only penguin-image://open/<32 lowercase hex>/<0–9999, no leading zeros>: no userinfo, port, query, fragment or extra segment. A match is emitted to the webview as penguin://image-open {nonce, index}. The navigation is always cancelled, matched or not. On Chromium (the browser mock), MessageBody's in-frame capture listener sees the click first, cancels it, and passes the href along with the document it was seen in.
  3. bridge.ts checks the request against a strict schema: the exact URL grammar, or a plain object with exactly nonce and index, typed and bounded. It then resolves it against the registry. The nonce must be one the app minted, for a frame that is still connected and still showing the same document. On the listener path the nonce must belong to the document the click came from. The index must be one the app assigned. That <img> must still be in that document, loaded, with a viewable source. Anything else is dropped and logged to the console as ignored.

Why email content can't forge a request. The sanitizer keeps only http/https/mailto hrefs, and data-* attributes never survive, so the email can't write a penguin-image: link or mimic the marker attributes. No script runs in the frame to create one. The 128-bit nonce and the index check are a second layer: even a forged event, from a future bug anywhere, can only open a picture that is already on screen.

What the viewer shows. Only pictures the app already has:

  • For a body picture, the <img>'s own source, and only if it is data:image/{png,jpeg,gif,webp,bmp,avif,x-icon};base64 with valid base64 (inline parts that penguin-render embedded; never SVG) or a plain https URL without credentials.
  • A remote picture must also have loaded in the frame (complete and naturalWidth > 0). That proves the frame's own CSP and the remote-images setting allowed it. Blocked and tracker images were removed by the sanitizer, so they are never in the document and can never be named.
  • The viewer's <img> uses referrerPolicy="no-referrer". It is served from the webview cache when possible.
  • Attachments come from preview_attachment, which sniffs the bytes as an image. The viewer takes PNG, JPEG, GIF and WebP.
  • Nothing from the message is inserted as markup in the app. The viewer is React text plus one <img src> that went through the checks above.

Save, Copy, Open in Preview. An attachment, or an inline picture whose part can be identified (the only inline part with exactly that byte size), is saved with save_attachment under its real name. Other pictures go through save_message_image or fetch_message_image:

  • They accept only a base64 raster data: URL (decoded locally) or an https URL that passes avatars::net::acceptable_url: a DNS host with a dot, not .local/.localhost, port 443, no userinfo.
  • Remote bytes are fetched with the sender-avatar client: HTTPS only (redirects too, at most 3), a public-address-only resolver, no cookies, no Referer, a generic User-Agent, 5 s connect and 12 s total timeouts, a 20 MB streaming cap.
  • The bytes must sniff as PNG/JPEG/GIF/WebP/BMP/ICO/AVIF, or the command fails. The file name is sanitized and its extension comes from the sniffed type.
  • A remote fetch happens only on an explicit Save or Copy, never on open or hover, and only for a URL that already loaded. So it tells the image host nothing new beyond a second request. Logs name the host and type, never the URL.
  • open_path still opens only files this session saved. "Open in Preview" passes open -a Preview through the opener (macOS).
  • Copy re-encodes the picture to PNG on a canvas from a data: URL, which is always untainted, and writes it with ClipboardItem during the key press or click.
  • Right-click menu (imageMenu.ts, the app's own menu, never WebKit's): Copy Image, Copy File Path, Copy Share Link (see Share links), Copy Original Web Address (remote https pictures only; it copies the source the viewer already accepted), Save to Downloads, Save As…, Open in Preview, Show in Finder (only after a save), Zoom to Fit / Actual Size, Close. An image attachment's card in the thread gets the same menu. Each item calls the commands above or below; the menu adds no new source of bytes.
  • Save all images (the "Save all images (N)" button in the message's control row, shown from 2 pictures up, and the viewer's and the message's right-click menus). The UI lists the same pictures the viewer would (decorated body pictures that loaded, plus image attachments, an inline part that is also an attachment once) and sends save_message_images(accountId, messageId, items): attachments by id, other body pictures by source. Rust looks up the message, refuses the whole batch if any attachment id isn't that message's or any source fails the save_message_image check, caps it at 400 items, and drops repeats. Each picture then goes through the same bytes path (the attachment cache or provider fetch, or the hardened fetch) and must sniff as an image; the extension follows the sniffed type. Files go into a new ~/Downloads/<subject> images/ folder (the stored subject, sanitized, 80 characters; created with create_dir, so an existing entry is never reused, (1), (2)… instead), written with create_new. A picture that fails is counted ("Saved 4 of 5") and logged by index, kind and error, never by URL. Only the folder and the files written are added to the session's saved paths, so Show in Finder can reveal the folder.

Drag out and Save As (src-tauri/src/file_export.rs, UI fileDrag.ts). Dragging a picture from the viewer (at fit, or ⌥-drag when zoomed, or the "Drag" grip in the bar), or an attachment card from the thread, drops a real file in Finder, on the Desktop or in another app.

  • Why native. WKWebView's own HTML drag of an <img> exports only a URL or a picture of the page. A file drag needs a file on disk and an AppKit NSDraggingSession. The UI cancels the element's dragstart and asks Rust to start one, through CrabNebula's drag crate (drag-rs, the crate behind tauri-plugin-drag), called directly rather than through the plugin, whose JS API would drag any path the webview names.
  • Where the file comes from. prepare_image_drag takes the same inputs and checks as save_message_image (a base64 raster data: URL, or a public https URL fetched with the hardened avatar client, sniffed as an image; the extension follows the sniffed type). prepare_attachment_drag uses the attachment's cached or fetched bytes under its sanitized name. A remote picture is fetched again only when the user actually drags it (an explicit gesture, like Save), never on hover or open.
  • Temp files. Each file is written with create_new to <cache>/drag-out/<session>/<n>/<name>: a random 64-bit session directory, a directory per file so the name stays exact, never replacing or following anything already there. At launch, earlier files older than a day are removed (file_export::prune, which never follows symlinks and never touches the current session). By then every drop has been copied by its destination (the drag offers NSDragOperationCopy only, so nothing is moved out of the cache).
  • Only files the app wrote. start_file_drag takes a path, but accepts it only if this session's Exports registry wrote it, it is under the session directory, and it is still a plain file (not replaced by a symlink or directory). Anything else is refused with invalidInput, so a compromised or buggy UI still can't drag ~/.ssh out.
  • The drag preview is our own PNG: the picture decoded under limits (≤ 12,000 px a side, 512 MB allocation) and shrunk to 160 px, or a page glyph drawn in Rust for anything that isn't a raster Penguin decodes (PDF, SVG, documents). AppKit only ever decodes that PNG for the preview.
  • Save As uses the system save panel (rfd's NSSavePanel sheet, no tauri-plugin-dialog and no fs plugin). The destination comes from the panel, never from the UI; the bytes are the same checked bytes as Save. The saved path joins open_path's and reveal_saved_path's allowlist for this session, which is all Show in Finder accepts.
  • Options weighed. (1) tauri-plugin-drag: works, but its startDrag({item, icon}) takes any path from JS, so it would widen what the webview can hand the OS. (2) A hand-written objc2 NSDraggingSource + beginDraggingSessionWithItems:event:source:: the same AppKit calls, but ours to maintain. (3) The drag crate directly (chosen): the plugin's own tested implementation (objc2 0.6 / objc2-app-kit 0.3, already in the tree; adds only itself and core-graphics 0.24 on macOS), behind our own path check. The dragstart → preventDefault → start-drag pattern and the main-thread call are the plugin's (its commands.rs runs drag::start_drag inside run_on_main_thread). Sources: github.com/crabnebula-dev/drag-rs (crates/drag/src/platform_impl/macos/mod.rs, crates/tauri-plugin-drag/src/commands.rs, examples/tauri/index.html), crates.io/crates/drag 2.1.1, drag-rs issue #23 / PR #57 (the macOS crash fixed by building the drag event from mouseLocationOutsideOfEventStream), Apple's NSView.beginDraggingSession(with:event:source:) and NSDraggingSource documentation.
  • Platforms. Drag out and Save As are macOS-only (nativeFiles in the UI; the commands answer invalidInput elsewhere). Linux and the browser mock keep WebKit's or the browser's default drag.

Navigation. Every injected anchor is target=_blank, and every penguin-image: navigation is cancelled in Rust or by the listener, so neither the frame nor the app window navigates. penguin-image is not a registered URI scheme, so nothing could load even if a navigation slipped through.

Tests. tests/imageViewer.test.ts: the request schema (about 40 malformed URLs and payloads, including extra keys, prototype tricks and class instances); nonce format and uniqueness; viewable sources (SVG, text/html, raw data, http, credentials, javascript:, blob:, avatar:, file:, cid: rejected); rejection of unknown nonces, unassigned indexes, clicks from another message's document, a frame that unmounted or reloaded, a picture removed or swapped to a disallowed source, and a remote picture that never loaded. tests/imageMenu.test.ts: which menu items each kind of picture gets (embedded, remote, attachment; viewer and card; Mac and elsewhere). cargo test -p penguin-desktop file_export: drag-out names, only files this session wrote are draggable (a stray file in the same directory, another session, a path outside, a file replaced by a directory), previews (small PNG, or the page glyph for a PDF or SVG), pruning (old sessions and their directories go, the current session stays, symlinks aren't followed). cargo test -p penguin-desktop image_viewer: the Rust URL grammar, allowed sources (private hosts, http, ports, credentials, SVG and HTML data rejected), bytes that aren't an image refused, and file names.

Residual risks.

  • Decoration adds our own nodes to a hostile document. The email's stylesheet can't target them by attribute through the sanitizer, but broad rules (a, svg, *) can still restyle, hide or move them. The worst case is a missing or misplaced button, or a click on one of the email's own pictures opening the viewer.
  • Wrapping a picture in an anchor can break an email CSS rule that relies on it being a direct child (td > img). The display: contents anchor keeps boxes and inheritance as they were.
  • The right-click menu on a wrapped picture in the message body (inside the frame) is still WebKit's and includes its link items. "Open Link" opens the viewer. "Copy Link" copies the inert penguin-image: URL. The viewer and the attachment cards use the app's menu.
  • A dropped drag-out file stays in the destination the user chose; its cache copy lives up to a day (longer if Penguin isn't relaunched). Dropping it on Penguin's own composer attaches it, like any file dropped there.
  • The native drag starts after an IPC round trip from dragstart. If the button is released before a remote picture or attachment has downloaded, the drag doesn't start; the file is kept and the next drag starts at once.
  • The inline-part match by byte size can only fail to find a name (two parts of the same size). It never saves the wrong bytes: Save writes the part that was matched, and an unmatched picture is saved from the bytes on screen.

Rich-text composer

The composer (src/features/compose/editor/, TipTap/ProseMirror) edits HTML that can come from untrusted mail: a reopened draft (which may hold forwarded mail), a paste from a web page or Google Docs, a dropped selection. Three layers keep it inert:

  1. penguin_render::sanitize_compose_html (crates/penguin-render/src/compose.rs), a separate, much stricter ammonia profile than render_html: only p br b strong i em u s strike del a ul ol li blockquote code pre h1–h6 div span hr; href http(s) with a host or mailto only; no images (see Inline images below), ids, event handlers or data-*; class only penguin-signature/gmail_signature/gmail_quote; style only font-weight/font-style/text-decoration with keyword values (so a Docs paste keeps bold/italic/underline). It runs on every paste and drop (sanitize_compose_html command, before the editor sees it), on get_draft's HTML part, and on every signature, both when settings are written and when settings.json is loaded (it is hand-editable).
  2. The editor schema is an allowlist too: a node or mark the composer doesn't have is dropped by the parser, and the link mark rejects anything but http(s)/mailto. Serializers escape all text and re-check every href (editor/serialize.ts).
  3. On send and on every draft save, penguin-provider/src/compose.rs (every provider's outgoing MIME) puts the HTML part through penguin_render::sanitize_outgoing_html: the same tags, plus the few inline CSS properties the composer emits for mail clients (font stack, margins, quote border, code background), first through the crate's own css::sanitize_declarations with a resolver that refuses every URL, then kept only for those properties and only with values in [A-Za-z0-9 #.,%'"-], which can't express url(), expression(), escapes or comments. Classes are ammonia allowed_classes on div only. xss_tests::composer_profiles_survive_the_corpus runs the full XSS/mXSS corpus through both profiles, re-parses with html5ever and checks the tree and a two-pass fixpoint.

Both profiles return parser-stable output, so one call is a fixpoint and a draft never drifts when it's re-sanitized on reopen. ammonia's unwrapping of a disallowed container (a table, marquee, object…) can leave allowed elements nested where the HTML parser would restructure them. After ammonia, compose.rs re-tokenizes its output into the same tree, unwraps (keeping the content) any <a> inside an <a>, any <p> that contains a block, any <li> in an <li> with no list, quote, heading or pre between them, and any heading that is a direct child of a heading. It adds back the newline the parser drops after <pre>, flattens nesting deeper than 256 elements, then serializes once with html5ever. one_pass_is_a_fixpoint_over_the_corpus asserts f(f(x)) == f(x) for the whole XSS corpus in both profiles. Style values must also have balanced quotes.

Inline images. The _with_images variants of the three profiles add img with only src, alt, width and height, and src only as cid: plus a Content-ID the caller's CidMap names: the draft's own inline parts (reopening, sending) or a quoted original's parts rewritten to fresh ids (quoting). Everything else (remote, data:, relative, srcset, a cid: the message doesn't carry) is removed, and an img without a surviving src goes entirely. Ids are only written when they match [A-Za-z0-9._@+=-]{1,200} (is_safe_cid), so they need no escaping in an attribute, a URL or a Content-ID header; anything else gets a fresh id or is left out. Only max-width/width/height CSS is added, and only on img in the outgoing profile. The corpus test runs every payload through the image variants too and asserts the only image sources are the mapped ids. Choice for quotes: a reply or forward keeps the original's inline (cid:) images, whose bytes the message itself carries, and drops its remote images even when the user loaded them, because quoting a remote URL would make every recipient's client fetch it (a tracking pixel keeps firing for everyone the mail is forwarded to). In the composer an inline image's picture comes from a registry keyed by cid (the pasted bytes as a data: URL, or a saved draft's part read through preview_attachment, which sniffs the bytes as an image); the editor document only holds the cid, so a reopened draft can't point the webview at a URL.

The quoted original of a reply is never loaded as HTML: it comes from the text part and is re-escaped into a blockquote inside div.gmail_quote. Tests: compose.rs tests (scripts, handlers, schemes, CSS payloads, a Docs clipboard), tests/richtext.test.ts (link rules, schema, draft round trip, paste parsing).

Sender avatars

Photos and logos next to senders: the resolver, fetcher and image code are the penguin-avatars crate (crates/penguin-avatars/, shared by the Mac app and the iPhone app); the Mac's commands, avatar: scheme and account photos are apps/desktop/src-tauri/src/avatars/. Settings → Privacy → Sender photos turns each source on or off, and the backend honors the switches.

Sources and what each request reveals

Source Default Request Who learns what
Google contact photos Off; per-account opt-in ("Connect contact photos") People API otherContacts.list + people/me/connections (bulk, paginated, about once a day), then *.googleusercontent.com photo URLs Google, which already has the contacts. Never a per-sender lookup.
BIMI logo On DNS TXT default._bimi.<domain> through the system resolver (libresolv), then the l= HTTPS URL Your resolver and the logo host learn that someone at your IP looked up that brand. Once per domain per 30 days (misses: 7 days).
Company icon On https://<org domain>/apple-touch-icon.png, then /favicon.ico, then the same on www. That company's web server sees your IP. Once per domain per 30 days.
Gravatar Off https://gravatar.com/avatar/<sha256(address)>?d=404 Gravatar (Automattic) learns which addresses write to you. The Settings copy says so.
  • No per-message identifiers ever leave the Mac. Requests carry a domain, a fixed path, the BIMI logo URL, a hash of the address, or a People API page token. No message id, subject, recipient or timing tied to opening a message. Resolution runs in a background worker and is never triggered from email content.
  • Brand imagery needs authentication. BIMI logos and company icons are only used when Gmail authenticated the sender (sender_authenticated: DMARC pass or aligned DKIM). The thread view passes the message's own flag, so a spoofed message shows a monogram even if the brand's logo is cached. List rows use whether the newest stored message from that address was authenticated (Store::latest_sender_authenticated). Mailbox providers (gmail.com, outlook.com, …) never get a brand image.
  • Fetch hardening (penguin-avatars/src/net.rs): HTTPS only, including redirects (at most 3); IP-literal, localhost, .local, userinfo and non-443 URLs are refused; hostnames go through a resolver that drops loopback, private, link-local, CGNAT, multicast and NAT64 addresses. That stops a sender's DNS from aiming requests at the LAN. No cookies, no Referer, a generic User-Agent, 5 s connect and 12 s total timeouts, and responses are streamed with a hard size cap (SVG 64 KB, rasters 2 MB, icons 512 KB). Concurrency is 4, and each source key is single-flight.
  • Images are never passed through (penguin-avatars/src/image.rs). Rasters (PNG, JPEG, GIF, WebP, ICO, BMP) are sniffed by content, decoded with dimension (4096 px) and allocation (64 MB) limits, center-cropped, resized to 128 px and re-encoded as PNG. SVG is only rasterized, with resvg built without text, fonts or raster-image support. Before parsing, compressed (svgz), oversized, non-UTF-8 and DTD/entity documents are refused. usvg runs no script and renders no foreignObject. Its <image href> resolver is replaced by one that refuses everything: the default one reads local files. cargo test -p penguin-avatars runs a malicious-SVG corpus: script, foreignObject, event handlers, javascript: links, <image> pointing at a local file, file://, data: and remote URLs, external <use>, CSS @import, recursive use, huge blurs, pattern bombs, billion laughs and external entities. It asserts the output is our PNG with nothing pulled in.
  • Serving. The webview gets avatar://localhost/<sha256>.png URLs. The protocol handler accepts only /<64 lowercase hex>.png (checked character by character before touching the filesystem), GET only, and serves the file only if it starts with the PNG signature, with nosniff and immutable caching. Tests cover path traversal, encoded dots, other files in the cache dir, and tampered non-PNG content.
  • Storage. <cache>/avatars/: img/ (content-addressed PNGs), index.json (records keyed by a hash of "source:identity"; no addresses in clear), contacts/<hash(account)>.json (sha256(address) → photo URL). All disposable. "Clear photo cache" deletes it all, and a removed account's contacts file is deleted on the next start.
  • Scopes. Contact photos use contacts.other.readonly and contacts.readonly: read-only and "sensitive" (not "restricted"). They're requested through incremental authorization (AuthManager::sign_in_with_scopes, include_granted_scopes=true) only when the user connects contact photos for an account. Accounts that never connect keep the original scopes. The People API must be enabled in the user's Cloud project; Penguin reports that case separately from a missing grant.

Residual risks. Company-icon and BIMI fetches tell those companies (and your DNS resolver) that someone at your IP receives their mail. That's domain-level, rate-limited by the cache, and switchable, but not zero. A list row can show a brand logo for a spoofed message when that sender's newest stored message was authentic (the open message itself never does). Gravatar, when on, reveals your correspondents' address hashes, which are guessable for known addresses.

Unsubscribe

The thread view's Unsubscribe button (src-tauri/src/unsubscribe.rs, plan in penguin-core/src/unsubscribe.rs) is the only place Penguin sends an HTTP request to a URL taken from an email.

  • User-initiated only. Nothing unsubscribes automatically. Every action (button, menu item, ⌘U, ⌘K) shows the same confirm dialog first, naming the sender and exactly what happens: the one-click request and its domain, the email (from, to, subject), or the full URL of the page that opens. Spam, Sent and Drafts never get the button: unsubscribing from spam confirms the address is live.
  • The UI never supplies a URL. unsubscribe re-derives the plan from the stored message, and the requested method must match it. Unsubscribe URLs carry per-recipient tokens: a one-click URL stays in Rust (the UI sees only the domain); a link offer also carries linkUrl, display only, so the confirm can show the full address before the browser opens it. It is never logged and never read back.
  • One-click POST (RFC 8058) only when List-Unsubscribe has an https URL, List-Unsubscribe-Post: List-Unsubscribe=One-Click is present, and Gmail authenticated the sender (sender_authenticated: DMARC pass or aligned DKIM, which is what makes those headers the sender's). Hardening: HTTPS only; a DNS host (no IP literals, localhost, .local, userinfo or non-443 ports, avatars::net::acceptable_url); the avatar fetcher's public-only resolver drops loopback, private, link-local, CGNAT, ULA and NAT64 addresses, so a sender's DNS can't aim the POST at the LAN; no redirects at all (a redirect could reach a private address or become a GET); no cookie store, no Referer, a generic User-Agent, 5 s connect / 10 s total timeouts; the body is only List-Unsubscribe=One-Click and the response body is never read. Non-2xx is a failure, and the toast offers opening the page instead.
  • mailto sends a plain-text message from the receiving account through Gmail, to one parsed address (extra recipients and to= additions are dropped, the subject is forced to one line, subject/body are capped). Only for authenticated senders: otherwise a spoofed message could make you send mail to any address, so the composer opens with it filled in for review.
  • Links (header https, or a body link found in the sanitized output by penguin_render::unsubscribe) open in the default browser through the same scheme check as open_external. Body links are http(s) only; javascript:, data:, mailto and relative links are never chosen.
  • Logging. Domain and method only, never the URL or the mailto body.
  • Memory. Successful unsubscribes are stored per (account, sender) in the local DB so later mail shows "Unsubscribed". Nothing leaves the Mac for this.

Share links

"Copy Share Link" (apps/desktop/src-tauri/src/share/, user guide docs/SHARE-LINKS.md) uploads a picture or attachment to the user's own S3-compatible storage and copies a presigned link.

  • Off by default, bring-your-own. Nothing is configured in source and there is no shared bucket. Until the user saves an endpoint, bucket, key ID and secret, the menu item only opens the setup page.
  • User-initiated. An upload happens on the menu choice only (or when setup finishes after that choice; the waiting file is kept in memory and dropped when Settings closes). Agents (create_share_link in MCP, penguin-cli share-link) ask the running app over the agent socket, which calls share::share_attachment with Caller::Agent. They are refused (permissionDenied, CLI exit 77) unless the agent level is at least Read, organize and draft and storage is set up with "Let agents (CLI and MCP) create share links" on (share::agent_gate); they can name attachments and embedded (cid:) pictures by id, never a picture by URL. Both Settings pages point to each other, and the share-link switch warns that email text can try to trick an agent into sharing. See Agents.
  • The link is the only key. Objects live in a private bucket under penguin/<128-bit random base32>/<ASCII file name>. The link is a SigV4 presigned GET that expires after 1 hour, 24 hours or 7 days (S3's maximum). The Settings test checks that an unsigned GET is refused and warns otherwise. Raster pictures are served inline; everything else attachment, so HTML never renders on the storage's origin.
  • The secret (secret access key) is in the Keychain (co.gluska.penguin.share-links), read at most once per process, never returned to the UI, never in settings JSON, logs or error messages. The form's Debug redacts it. Share-link settings, set, clear and test, are main-window commands; conversation windows may only read the settings, share and delete.
  • Requests go to the configured endpoint only: HTTPS (plain HTTP only to loopback, for a local MinIO), no redirects, a generic user agent, request signatures valid 15 minutes, one PUT of at most 100 MB. A remote body picture is fetched through the same hardened path as Save (see Image viewer).
  • Logging. A share logs size, content type and lifetime; failures log the host, status and S3 error code. Never the link (a bearer credential), the object key, the file name or anything about the email.
  • Cleanup. share-uploads.json (data dir) records key, endpoint, bucket and times. A background task deletes expired uploads with backoff and forgets records 30 days after expiry. share_delete only deletes keys in that record, so the UI can't make Penguin delete arbitrary objects.

Network traffic

Penguin has no server. Everything it sends over the network, and to whom:

  • Mail providers: Gmail API and Google OAuth; Microsoft Graph and Microsoft sign-in; IMAP and SMTP servers for other accounts. Google Calendar for calendars and RSVPs; the People API for contact photos when connected.
  • Remote images in email bodies: only after "Load images" (or an allow rule), from the WebKit view; see Rendering pipeline. Save, Copy and Copy Share Link on a remote picture fetch it again from Rust, hardened.
  • Sender avatars: BIMI logos, company icons and Gravatar, when on; see Sender avatars.
  • Unsubscribe: the one-click POST or mailto the user confirms; see Unsubscribe.
  • Share links: uploads, test requests and deletes to the storage endpoint the user configured; see Share links.
  • Search by meaning: the embedding model's files from huggingface.co when search by meaning downloads its model (docs/SEMANTIC.md).
  • Updates: release builds only, the update feed that release was built with; source builds never check.
  • Links you click open in your browser, not in Penguin.
  • Pair iPhone: while the pairing dialog is open (two minutes at most), a listener on the local network that one phone holding the QR code can use; the tokens and IMAP passwords it sends are end-to-end encrypted to that phone. See docs/PAIRING.md for the protocol and its threat model.

Agents (CLI and MCP)

penguin-cli and its MCP server let AI agents use Penguin (docs/CLI.md has the user-facing detail). The design keeps two things apart: reading, which the CLI process does itself from a read-only database, and everything that changes mail or needs the network, which only the running app does, on request, after checking the level the user set.

Levels (Settings → Developer → Agents; settings.json → mcp.access): Off (default) → Read only → Read, organize and draft → Read, organize, draft and send. The stored values are unchanged (off, read, draft, send); organizing joined the draft step, whose name grew, so older files keep their level. An unknown value loads as Off. Raising the level to send goes only through enable_agent_send, from a confirmation that explains the risks and needs "I understand" typed; update_settings refuses access: "send" and Settings::apply ignores it as a second line. Lowering takes effect on the next request (the app checks its in-memory settings each time) and cancels every send an agent queued (Store::cancel_agent_sends, by the schedule ids agents recorded, so the user's own scheduled sends are untouched). At startup the app cancels them too when the level is below send, which covers a level lowered in the file while Penguin was closed.

The write path.

  • The CLI and the MCP server never hold credentials: no mail client, no Keychain access, a read-only database. For organizing, a draft, a send or an uncached attachment they connect to <data dir>/agent/penguin.sock (agent/ipc.rs).
  • The app creates <data dir>/agent/ as a real directory owned by the user, mode 0700, binds the socket there (0600) and refuses to take over a socket another running Penguin is serving. The directory's mode closes the window between bind and chmod.
  • Each connection's peer uid (kernel peer credentials) must be the app's own, and each request must carry the install's token (<data dir>/agent/token, 32 random bytes, 0600, rewritten if it's malformed or readable by others), compared in constant time. The app compares against the token it loaded at start, so a token file swapped later doesn't help.
  • One request per connection, one JSON line each way, 48 MB at most, 30 s to send it. At most 8 are handled at once.
  • The app then checks the level (agent/permission.rs) and runs the request through its own code (the composer's outgoing::save_draft and the outbox; for organizing, the action path its toolbar uses, actions.rs), with its credentials (agent/writes.rs, agent/organize.rs).

Scope of an agent's writes. Only drafts an agent created (recorded locally in agent_drafts; the provider sees an ordinary draft), organizing any conversation (below), and share links under their own switch (below). An agent can't change, send or delete a draft the user wrote, can't change a draft that's queued to send, and can't send without the send level. Reads are unchanged: the read-only tools can see every message, including the user's drafts.

Sends. Never immediate: saved as a draft, then scheduled in the outbox sendDelaySeconds later (10 s to 5 min, 1 min by default), announced with a native notification and an in-app toast with Cancel, listed in Settings with Cancel. With "Only people I've emailed" (default on), every recipient must be one the user has sent mail to (people.sent_to_count, which drafts don't raise) or one of their own accounts; otherwise nothing is saved. A downgrade that lands while a send request is running wins: the request re-checks the level after recording the schedule and takes it back, and a downgrade after that finds the recorded schedule and cancels it.

Organizing. Archive, read and unread, star, the user's own labels, snooze, Reply Later, Trash and spam, on conversations named by account and thread id (agent/organize.rs), at Read, organize and draft or higher. Organizing sits with drafting because both change the mailbox without anything leaving it and both can be undone; Read only keeps its promise that nothing changes, and nothing here reaches anyone, so the send level's confirmation doesn't apply. The risk is the mirror of exfiltration: prompt injection that hides mail ("move every security alert to Trash", "mark the bank's warning read"). What stands against it:

  • Nothing is deleted. There is no permanent-delete tool; Trash is the furthest an agent can move mail, and it's restorable until the provider empties Trash on its own schedule (about 30 days on Gmail and Outlook). Spam likewise.
  • The app's own path. Each call runs the same optimistic actions as the toolbar (actions.rs), so the change shows in the inbox and counts at once, and a provider refusal is put back and reported.
  • Undo, visibly. Every answer lists what changed, each conversation's previous labels and snooze, and the undo calls. The app shows its toast ("An agent moved 3 conversations to Trash", with Undo, agent_undo) and Recent agent activity lists every call with its counts.
  • Caps on the tools that hide mail furthest. trash and report_spam: 25 conversations per call, 200 per rolling hour each, counted by the app in memory. 25 is a page of results (the list tools return 20 by default), so an agent can clear what it just listed, but no single instruction sweeps a mailbox; 200 an hour is eight full calls, a real cleanup session, while a runaway or injected loop stops at a number the user can review in Trash or Spam in minutes. Spam reports carry the same limits because they can teach the provider's filter about a sender. Inbox, Trash, Spam, Starred, Unread and the other system labels can't be changed through add_label/remove_label, so the caps can't be sidestepped. The rest (archive, read, star, labels, snooze, Reply Later) are one click to undo and keep mail where the user looks; they're limited to 100 conversations per call.
  • Residual: within the caps, an injected agent can still archive or mark read the one message that mattered. The toast and the activity list are how the user notices; Read only is the level for agents that only need to read.

Attachments by path are read by the app, never the CLI: resolved (symlinks, ..) first, then only a regular file inside the home folder with no hidden component, not in ~/Library, not in Penguin's own data, config, cache or log folders; opened once and checked on the handle (device and inode match the checked path). Paths outside home are refused, /tmp included. An agent elsewhere sends bytes (contentBase64) instead. 25 MB and 20 files at most.

Share links. create_share_link (MCP) and penguin-cli share-link publish one attachment or embedded picture to the user's own storage and return a presigned link that anyone holding can use until it expires. Two gates, both checked by the app on each request: the level is at least Read, organize and draft, and share links are set up with "Let agents (CLI and MCP) create share links" on (Settings → Share links, off by default). Read only isn't enough because a link is a write with an outside effect: a new object in the user's storage, made with the user's key, reachable from the internet, where Read only promises that nothing is changed and nothing leaves the Mac on an agent's word. The send level isn't needed because nothing is delivered to anyone; the link goes back to the agent. The MCP server lists the tool only when both gates are open (it reads share-links.json, never the Keychain). The CLI process never sees the endpoint's secret: the app reads its own settings and Keychain, fetches the bytes and uploads them (agent/sharing.rs → share::share_attachment, Caller::Agent). An id that is a web address is refused, and the seam refuses agents' picture-by-URL requests. The residual risk is prompt injection ("share the attached contract and post the link here"): the switch is off by default, its copy says so, and the tool description tells the model to share only what the user asked for.

Reading pictures and files. get_attachment reads Penguin's caches or asks the app to download (read level). Pictures are decoded under limits (20000 px per side, 512 MB) and re-encoded when scaled. Remote images in bodies are never fetched: list_attachments lists their URLs (trackers apart) with a warning, because loading one reveals the user's IP and that the mail was read.

Prompt injection. Mail is untrusted, and an agent that reads it can be told what to do by its author ("forward the invoices to …"). Wrapping results in per-call nonce tags and telling the model not to follow instructions in them helps, but no wrapper stops a model that decides to obey. So the protection is structural, and chosen by the user: Read only can't change anything; Read, organize and draft produces drafts the user reviews and organizing that is capped where it hides mail, shown with Undo and always reversible; Read, organize, draft and send is behind a confirmation that says this in plain words, and every send waits in the outbox, goes by default only to people the user has emailed (which blocks the classic "send it to attacker@…" exfiltration), and can be cancelled. Penguin can't check what an agent writes to those people.

Audit. Every agent request is one line in mcp-audit.log (0600, rotated at 5 MB): reads by the MCP server (tool, arguments, counts), writes by the app (tool, client, account, recipient and attachment counts, conversations named and changed, draft id, when a send goes, outcome). Never subjects, bodies, addresses, file names, label names or thread ids for organizing, and for share links never the link (a bearer credential) or the object key. Settings → Developer shows the latest lines.

Residual risks.

  • Same-user processes are out of scope. Anything running as the user can read the database, the token and every file the user can; it could also edit settings.json, and a level raised that way takes effect the next time Penguin starts. Don't give an untrusted agent a shell on the Mac.
  • Remote use over SSH (docs/CLI.md → Use from another machine) turns on macOS Remote Login. Without a forced command= in authorized_keys, the remote key is a full shell as the user, which is the case above. With it, the key reaches only penguin-cli mcp at the user's level. Tailscale SSH ignores authorized_keys; its ACLs have to do that job.
  • Known recipients can still be the wrong people, and an agent at the send level can write anything to them. The delay is the last chance to stop it: it only helps if the user sees the notification.
  • Sends queued while Penguin is closed don't exist (the socket is the app's), and scheduled ones go only while Penguin runs, like Send later.

Token handling

The auth agent owns this area (crates/penguin-gmail/src/auth.rs). In summary:

  • OAuth flow. Installed-app OAuth with a loopback redirect on 127.0.0.1:<random port>, PKCE S256, and a constant-time state check.
  • Scopes. gmail.modify (no permanent delete) plus openid email profile. Optional, per account and only on request: contacts.other.readonly + contacts.readonly for contact photos (incremental authorization; see Sender avatars).
  • Refresh tokens are stored only in the macOS Keychain (service co.gluska.penguin.google, account = lowercased email). They are revoked with Google and deleted from the Keychain on sign-out. The one way a token leaves the Mac is Pair iPhone, after the user confirms the phone, encrypted to it (docs/PAIRING.md); browser sign-ins go with the Mac's Desktop app client, which the phone keeps in its Keychain only to refresh those tokens.
  • IMAP passwords and Microsoft refresh tokens live in their own Keychain items (co.gluska.penguin.imap, co.gluska.penguin.microsoft, account credentials.v1, penguin-provider credentials.rs). Like Google's, they leave the Mac only through Pair iPhone, encrypted to the confirmed phone, which keeps them in its own Keychain.
  • Access tokens exist only in memory.
  • Logging. Tokens, auth codes, PKCE verifiers and client secrets are never logged. Every type holding one has a redacting Debug. Message bodies are never logged either.
  • OAuth client JSON. The user's own Google Cloud "Desktop app" client, kept in the app config dir and never committed. See docs/google-setup.md. Google treats an installed app's secret as not confidential; Penguin still never logs it, and it leaves the Mac only inside Pair iPhone's encrypted transfer, when browser sign-ins move (the phone stores it in the Keychain, item desktop-clients.v1, never in a file).

Supply chain

  • Lockfiles. Cargo.lock and apps/desktop/package-lock.json are committed. Install with npm ci, never a blind npm update, and use cargo build --locked in CI and release.
  • Rust: run cargo deny check (config: deny.toml). Every workspace crate must set publish = false, so our unlicensed crates and path dependencies are treated as private.
    • advisories fails on RustSec vulnerabilities, unsound crates and yanked crates anywhere in the tree, and on unmaintained crates we depend on directly.
    • licenses allows only permissive licenses plus MPL-2.0.
    • sources allows crates.io only, with no git dependencies.
    • bans warns on duplicate versions.
  • Rust (optional): cargo audit gives a second, RustSec-only check.
  • JS: run npm audit --omit=dev for shipped code, and a full npm audit before releases.
  • New dependencies. Review before adding: maintenance, owners, install scripts, transitive size. Prefer the standard library and existing crates. penguin-render depends only on ammonia, serde and html5ever. html5ever is the parser ammonia already builds; the composer uses it to stabilize its output.
  • Releases: signed and notarized macOS builds, with SBOM generation and diffing, planned for the first public release.

Reporting a vulnerability

Placeholder until the repository is public. Before publishing:

  • enable GitHub private vulnerability reporting;
  • add a monitored security@ address;
  • fill in the response targets below.

Please do not open a public issue for security problems. Report privately through GitHub's "Report a vulnerability" button on this repository, or email security@<domain TBD>. Include:

  • the affected version or commit,
  • a proof of concept (a raw .eml is ideal; use fictional addresses), and
  • the impact you observed.

What we commit to:

  • Acknowledge within [TBD, e.g. 3 business days].
  • Assess severity within [TBD, e.g. 7 days].
  • Coordinate disclosure: we fix before public disclosure, credit reporters who want credit, and request a CVE for confirmed high-severity issues.
  • Good-faith research on your own accounts and data is welcome. Do not access other people's mail.

There aren't any published security advisories