Compare commits

..

No commits in common. "814b5aa239a9dd3a0b8073f70a203a1a7fbedd3e" and "7530fb1de735a01e3c503564493e3e1b5cc00a08" have entirely different histories.

30 changed files with 986 additions and 1551 deletions

View file

@ -1,10 +1,5 @@
# Changelog # Changelog
## Unreleased
### New
- **Link previews in chats (Chat+).** X's web chat shows a link as a bare card with only the site's name. wayBetter shows the page's title, text and picture under the message, an image link's image, and for YouTube, Vimeo and SoundCloud the video or track, playable right in the chat (Spotify and other sites get a card that opens the link). Only the link is sent to its site (no cookies, never the message or who sent it), and nothing is saved. On by default; Chat+ → Link previews turns it off.
## 1.0.2 ## 1.0.2
### New ### New
@ -67,7 +62,7 @@ offered for download; the macOS and Linux packaging in the release tooling is no
- **Icon packs**: Appearance → Icons follows the theme, keeps X's own icons, or picks one of four packs (Line, Classic, Aero, Pixel 98). You can import an icon pack too; it applies to X tabs and to the app's own chrome. - **Icon packs**: Appearance → Icons follows the theme, keeps X's own icons, or picks one of four packs (Line, Classic, Aero, Pixel 98). You can import an icon pack too; it applies to X tabs and to the app's own chrome.
- **Share my setup**: Settings → Backup & sync can Copy link or Save file for your theme, icon pack, mode and features (nothing personal). "Use a setup" takes a pasted link or a file, shows what will change, and applies only after you confirm; a `waybetter://setup` link opened from outside shows the same preview. - **Share my setup**: Settings → Backup & sync can Copy link or Save file for your theme, icon pack, mode and features (nothing personal). "Use a setup" takes a pasted link or a file, shows what will change, and applies only after you confirm; a `waybetter://setup` link opened from outside shows the same preview.
- **String packs**: data that replaces X's own interface strings (a language X does not offer, a fixed translation, a rewording). Drop a `.strings.json` on the window, open a link or pick one in the Store under Languages; the install screen shows its language, its coverage of X's strings and a sample. Languages turns packs on or off and orders them. Only known string keys can change, and a pack is data, never code. The Store lists one so far (Esperanto). See docs/STRING-PACKS.md in the framework repository. - **String packs**: data that replaces X's own interface strings (a language X does not offer, a fixed translation, a rewording). Drop a `.strings.json` on the window, open a link or pick one in the Store under Languages; the install screen shows its language, its coverage of X's strings and a sample. Languages turns packs on or off and orders them. Only known string keys can change, and a pack is data, never code. The Store lists one so far (Esperanto). See docs/STRING-PACKS.md in the framework repository.
- **Builds carry no trace of the machine that made them**: `waybetter build-env` removes the build paths from the binary. - **Builds carry no trace of the machine that made them**: `waybetter build-env` removes the build paths from the binary and every release runs a privacy scan over its files, installer and updater bundle before anything is signed.
### New: the Store, workspaces, backup and the deck ### New: the Store, workspaces, backup and the deck
- **Store, install links and drag-and-drop**: install themes and plugins from the new Store section - **Store, install links and drag-and-drop**: install themes and plugins from the new Store section

View file

@ -125,7 +125,7 @@ cd waybetter-for-x
bun install --frozen-lockfile bun install --frozen-lockfile
bun run dev # the desktop app with live reload of the page runtime bun run dev # the desktop app with live reload of the page runtime
bun run build # contracts, api, desktop (type check, bundles, vite) bun run build # contracts, api, desktop (type check, bundles, vite)
bun run test # contracts, api, web, desktop bun run test # contracts, api, web, desktop, and the privacy scan
bun run test:rust # cargo tests, headless bun run test:rust # cargo tests, headless
bun run desktop:build # an unsigned native build (no installer) bun run desktop:build # an unsigned native build (no installer)
``` ```

View file

@ -751,10 +751,6 @@
"plugin.chat-plus.bookmarks.importBad": "This is not an export of starred messages.", "plugin.chat-plus.bookmarks.importBad": "This is not an export of starred messages.",
"plugin.chat-plus.bookmarks.imported": "{count, plural, =0 {Nothing new to import} one {# starred message imported} other {# starred messages imported}}", "plugin.chat-plus.bookmarks.imported": "{count, plural, =0 {Nothing new to import} one {# starred message imported} other {# starred messages imported}}",
"plugin.chat-plus.bookmarks.close": "Close", "plugin.chat-plus.bookmarks.close": "Close",
"plugin.chat-plus.feature.linkPreviews.label": "Link previews",
"plugin.chat-plus.feature.linkPreviews.description": "Shows a preview under a link in a chat: the page's title, text and picture, an image link's image, and for YouTube, Vimeo and SoundCloud the video or track, playable in place. To make one, the app asks the link's site for its preview itself: only the link is sent, without cookies, never the message or who sent it. Nothing is saved.",
"plugin.chat-plus.linkPreviews.play": "Play the video here",
"plugin.chat-plus.linkPreviews.open": "Open the link",
"plugin.chat-plus.feature.searchLoaded.label": "Find in conversation", "plugin.chat-plus.feature.searchLoaded.label": "Find in conversation",
"plugin.chat-plus.feature.searchLoaded.description": "Ctrl+Shift+F in a chat searches the messages X has loaded so far and jumps to each match. It can load older messages while it is open.", "plugin.chat-plus.feature.searchLoaded.description": "Ctrl+Shift+F in a chat searches the messages X has loaded so far and jumps to each match. It can load older messages while it is open.",
"plugin.chat-plus.searchLoaded.title": "Find in conversation", "plugin.chat-plus.searchLoaded.title": "Find in conversation",

View file

@ -17,7 +17,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ar-x-fm", "code": "ar-x-fm",
@ -28,7 +28,7 @@
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"fallback": "ar", "fallback": "ar",
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "bn", "code": "bn",
@ -38,7 +38,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "eu", "code": "eu",
@ -48,7 +48,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "en-GB", "code": "en-GB",
@ -69,7 +69,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ca", "code": "ca",
@ -79,7 +79,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "zh-Hans", "code": "zh-Hans",
@ -89,7 +89,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "zh-Hant", "code": "zh-Hant",
@ -99,7 +99,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "hr", "code": "hr",
@ -109,7 +109,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "cs", "code": "cs",
@ -119,7 +119,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "da", "code": "da",
@ -129,7 +129,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "nl", "code": "nl",
@ -139,7 +139,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "fil", "code": "fil",
@ -149,7 +149,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "fi", "code": "fi",
@ -159,7 +159,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "fr", "code": "fr",
@ -169,7 +169,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "gl", "code": "gl",
@ -179,7 +179,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "de", "code": "de",
@ -189,7 +189,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "el", "code": "el",
@ -199,7 +199,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "gu", "code": "gu",
@ -209,7 +209,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ha", "code": "ha",
@ -219,7 +219,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "he", "code": "he",
@ -229,7 +229,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "hi", "code": "hi",
@ -239,7 +239,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "hu", "code": "hu",
@ -249,7 +249,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ig", "code": "ig",
@ -259,7 +259,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "id", "code": "id",
@ -269,7 +269,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ga", "code": "ga",
@ -279,7 +279,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "it", "code": "it",
@ -289,7 +289,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ja", "code": "ja",
@ -299,7 +299,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "kn", "code": "kn",
@ -309,7 +309,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ko", "code": "ko",
@ -319,7 +319,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ms", "code": "ms",
@ -329,7 +329,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "mr", "code": "mr",
@ -339,7 +339,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "nb", "code": "nb",
@ -349,7 +349,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "fa", "code": "fa",
@ -359,7 +359,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "pl", "code": "pl",
@ -369,7 +369,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "pt", "code": "pt",
@ -379,7 +379,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ro", "code": "ro",
@ -389,7 +389,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ru", "code": "ru",
@ -399,7 +399,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "sr", "code": "sr",
@ -409,7 +409,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "sk", "code": "sk",
@ -419,7 +419,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "es", "code": "es",
@ -429,7 +429,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "sv", "code": "sv",
@ -439,7 +439,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ta", "code": "ta",
@ -449,7 +449,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "th", "code": "th",
@ -459,7 +459,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "tr", "code": "tr",
@ -479,7 +479,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "ur", "code": "ur",
@ -489,7 +489,7 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "vi", "code": "vi",
@ -499,7 +499,7 @@
"status": "machine", "status": "machine",
"tier": "supported", "tier": "supported",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
}, },
{ {
"code": "yo", "code": "yo",
@ -509,6 +509,6 @@
"status": "machine", "status": "machine",
"tier": "community", "tier": "community",
"reviewers": [], "reviewers": [],
"coverage": 0.996 "coverage": 1
} }
] ]

View file

@ -800,10 +800,6 @@
"plugin.chat-plus.personFilter.groupOnly": "Önce bir grup sohbeti aç", "plugin.chat-plus.personFilter.groupOnly": "Önce bir grup sohbeti aç",
"plugin.chat-plus.personFilter.nobody": "Henüz seçilecek kimse yok: hiç mesaj yüklenmedi.", "plugin.chat-plus.personFilter.nobody": "Henüz seçilecek kimse yok: hiç mesaj yüklenmedi.",
"plugin.chat-plus.personFilter.hint": "Şimdiye kadar yüklenen mesajları yazan kişiler. Daha fazlası için yukarı kaydır.", "plugin.chat-plus.personFilter.hint": "Şimdiye kadar yüklenen mesajları yazan kişiler. Daha fazlası için yukarı kaydır.",
"plugin.chat-plus.feature.linkPreviews.label": "Link önizlemeleri",
"plugin.chat-plus.feature.linkPreviews.description": "Sohbetteki bir linkin altında önizlemesini gösterir: sayfanın başlığı, metni ve görseli; görsel linklerinde görselin kendisi; YouTube, Vimeo ve SoundCloud'da ise yerinde oynatılabilen video ya da parça. Önizleme için uygulama linkin sitesine kendisi sorar: yalnızca link gider, çerezsiz; mesaj ya da gönderen asla gitmez. Hiçbir şey kaydedilmez.",
"plugin.chat-plus.linkPreviews.play": "Videoyu burada oynat",
"plugin.chat-plus.linkPreviews.open": "Linki aç",
"plugin.chat-plus.feature.keywords.label": "Sohbetlerde anahtar kelimeler", "plugin.chat-plus.feature.keywords.label": "Sohbetlerde anahtar kelimeler",
"plugin.chat-plus.feature.keywords.description": "Kelimelerini içeren sohbet mesajlarını vurgular, sessize aldığın kelimeleri içeren mesajları katlar. Katlanmış bir mesaj tıklayınca açılır.", "plugin.chat-plus.feature.keywords.description": "Kelimelerini içeren sohbet mesajlarını vurgular, sessize aldığın kelimeleri içeren mesajları katlar. Katlanmış bir mesaj tıklayınca açılır.",
"plugin.chat-plus.keywords.highlight": "Vurgulanacak kelimeler", "plugin.chat-plus.keywords.highlight": "Vurgulanacak kelimeler",

View file

@ -296,9 +296,7 @@ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"chacha20poly1305", "chacha20poly1305",
"chrono", "chrono",
"reqwest",
"rusqlite", "rusqlite",
"rustls",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",

View file

@ -25,8 +25,6 @@ desktop = [
"waybetter-host/app", "waybetter-host/app",
"waybetter-host/net", "waybetter-host/net",
"waybetter-host/macos-private-api", "waybetter-host/macos-private-api",
"dep:reqwest",
"dep:rustls",
] ]
[build-dependencies] [build-dependencies]
@ -54,9 +52,6 @@ url = "2"
tauri-plugin-deep-link = { version = "2", optional = true } tauri-plugin-deep-link = { version = "2", optional = true }
# Gallery folder picker, driven from Rust only (no JS capability grants the dialog plugin). # Gallery folder picker, driven from Rust only (no JS capability grants the dialog plugin).
tauri-plugin-dialog = { version = "2", optional = true } tauri-plugin-dialog = { version = "2", optional = true }
# Chat+ link previews (src/link_preview.rs): the same client the host's store uses, no cookies.
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"], optional = true }
rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true }
sha2 = "0.10" sha2 = "0.10"
base64 = "0.22" base64 = "0.22"
# Encrypted settings sync (a folder the owner picks): Argon2id key from the passphrase, # Encrypted settings sync (a folder the owner picks): Argon2id key from the passphrase,

View file

@ -1,26 +1,25 @@
fn main() { fn main() {
#[cfg(feature = "desktop")] #[cfg(feature = "desktop")]
tauri_build::try_build(tauri_build::Attributes::new().app_manifest( tauri_build::try_build(tauri_build::Attributes::new().app_manifest(
// X's own commands; `manifest` adds the ones the wayBetter host serves for every app // X's own commands; `manifest` adds the ones the wayBetter host serves for every app
// (`waybetter_host::commands`: tab layout and actions, shell raise, profiles, language, // (`waybetter_host::commands`: tab layout and actions, shell raise, profiles, language,
// the plugins folder and custom CSS, the tweak flags, the shell's settings). // the plugins folder and custom CSS, the tweak flags, the shell's settings).
tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&[ tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&[
"capture_draft", "capture_draft",
"column_configure", "column_configure",
"tab_report", "tab_report",
"drafts_picker_open", "drafts_picker_open",
"tab_insert_text", "tab_insert_text",
"drafts_popover_dismiss", "drafts_popover_dismiss",
"drafts_hint", "drafts_hint",
"popover_state", "popover_state",
"popover_drafts", "popover_drafts",
"popover_insert", "popover_insert",
"popover_close", "popover_close",
"popover_open_vault", "popover_open_vault",
"keyword_alert", "keyword_alert",
"link_preview", "tab_attach_image",
"tab_attach_image", ])),
])), ))
)) .expect("Tauri build configuration must be valid");
.expect("Tauri build configuration must be valid"); }
}

View file

@ -1,10 +1,10 @@
{ {
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "x-capture", "identifier": "x-capture",
"description": "X tabs: append-only draft capture, opening the wayBetter tab, asking for the drafts popover under its composer and closing it, asking whether a captured draft exists for exactly its own post page (yes/no, no text or ids), reporting keyword matches about itself and, on its own chat page only, asking for the preview of one link it shows (native fetch: public https hosts only, no cookies, size caps; src/link_preview.rs). No reads of the local vault, no shell, filesystem or generic APIs.", "description": "X tabs: append-only draft capture, opening the wayBetter tab, asking for the drafts popover under its composer and closing it, asking whether a captured draft exists for exactly its own post page (yes/no, no text or ids) and reporting keyword matches about itself. No reads of the local vault, no shell, filesystem or generic APIs.",
"webviews": ["tab-*"], "webviews": ["tab-*"],
"local": false, "local": false,
"platforms": ["macOS", "windows", "linux"], "platforms": ["macOS", "windows", "linux"],
"remote": { "urls": ["https://x.com/*"] }, "remote": { "urls": ["https://x.com/*"] },
"permissions": ["allow-capture-draft", "allow-open-panel", "allow-drafts-picker-open", "allow-drafts-popover-dismiss", "allow-drafts-hint", "allow-keyword-alert", "allow-link-preview"] "permissions": ["allow-capture-draft", "allow-open-panel", "allow-drafts-picker-open", "allow-drafts-popover-dismiss", "allow-drafts-hint", "allow-keyword-alert"]
} }

View file

@ -77,7 +77,6 @@ pub const FLAGS: &[&str] = &[
"chat.searchLoaded", "chat.searchLoaded",
"chat.pins", "chat.pins",
"chat.personFilter", "chat.personFilter",
"chat.linkPreviews",
"chat.keywords", "chat.keywords",
"mediaDownload", "mediaDownload",
"rememberVideoVolume", "rememberVideoVolume",

View file

@ -233,19 +233,6 @@ async fn keyword_alert(webview: Webview, state: State<'_, AppState>, hit: Keywor
Ok(()) Ok(())
} }
/// Chat+ link previews (owner-approved network use, 2026-10-10): an X tab on its own chat page asks
/// for the preview of one link it shows. Only the link reaches native code; the fetch rules
/// (public https hosts, no cookies, pinned addresses, size caps, memory-only cache) are in link_preview.rs.
#[tauri::command]
async fn link_preview(webview: Webview, url: String) -> Result<crate::link_preview::LinkPreview, String> {
policy::require_capture(webview.label(), &webview.url().map_err(|_| "FORBIDDEN: cannot verify origin")?)?;
let page = webview.url().map_err(|_| "FORBIDDEN: cannot verify origin")?;
if !crate::link_preview::is_chat_page(page.path()) {
return Err("FORBIDDEN: link previews are for X's chat pages only".into());
}
crate::link_preview::preview(&url).await
}
/// Tells an X tab whether its left navigation repeats one already on screen; the runtime hides it /// Tells an X tab whether its left navigation repeats one already on screen; the runtime hides it
/// while the `singleSplitNav` feature is on. Queued in `__btPane` until the runtime exists. /// while the `singleSplitNav` feature is on. Queued in `__btPane` until the runtime exists.
fn pane_script(nav_redundant: bool) -> String { fn pane_script(nav_redundant: bool) -> String {
@ -591,7 +578,6 @@ pub fn run() {
desktop_popover::popover_close, desktop_popover::popover_close,
desktop_popover::popover_open_vault, desktop_popover::popover_open_vault,
keyword_alert, keyword_alert,
link_preview,
crate::desktop_media::tab_attach_image, crate::desktop_media::tab_attach_image,
], ],
); );

View file

@ -9,7 +9,6 @@ pub mod devmode;
pub mod distribution; pub mod distribution;
pub mod gfonts; pub mod gfonts;
pub mod hotfix; pub mod hotfix;
pub mod link_preview;
pub mod media; pub mod media;
pub mod model; pub mod model;
pub mod palette_commands; pub mod palette_commands;

View file

@ -1,675 +0,0 @@
//! Chat+ link previews (owner-approved network use, 2026-10-10): X's web chat shows a link as a bare
//! card (an icon and the domain), so an X tab on a chat page may ask native code for the preview of
//! ONE link it shows. Native code fetches that link's page head (an image link: the image; YouTube:
//! its oEmbed and thumbnail) itself:
//!
//! - https only, no user info, default port, a domain name (no IP literal), not X's own hosts;
//! - every address the name resolves to must be public (no loopback, private, link-local, CGNAT,
//! multicast, documentation or unique-local ranges), and the connection is pinned to those
//! addresses, so a DNS answer cannot point the request into the owner's network;
//! - no cookies (no cookie store), no referrer, a plain user agent naming the app;
//! - redirects followed by hand, at most [`MAX_REDIRECTS`], each hop checked again;
//! - only an HTML head is read, at most [`MAX_PAGE_BYTES`]; an image at most [`MAX_IMAGE_BYTES`],
//! PNG/JPEG/GIF/WebP by its magic bytes only, handed back as a `data:` URL;
//! - the request carries the link and nothing else: no conversation, sender or message text.
//!
//! Results live in memory only (a bounded cache) and are never written anywhere. A link to YouTube,
//! Vimeo or SoundCloud also gets a player address on one of the hosts X's own CSP allows as a frame
//! ([`embed_for`]); the page loads it only when the user presses play.
use serde::Serialize;
use std::net::IpAddr;
use url::Url;
pub const MAX_URL_LEN: usize = 2_048;
pub const MAX_REDIRECTS: usize = 4;
pub const MAX_PAGE_BYTES: usize = 512 * 1024;
pub const MAX_IMAGE_BYTES: usize = 1_536 * 1024;
pub const MAX_TITLE: usize = 200;
pub const MAX_DESCRIPTION: usize = 300;
pub const MAX_SITE: usize = 80;
pub const USER_AGENT: &str = "Mozilla/5.0 (compatible; wayBetter-LinkPreview/1.0; +https://waybetter.fyi/x/)";
/// What a chat tab gets back: plain text, an image as a `data:` URL, and for a video or audio link the
/// address of its site's own player ([`embed_for`]).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LinkPreview {
pub url: String,
pub site: String,
pub title: String,
pub description: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub image: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub embed: Option<String>,
}
/// The site's own player for a link, on a host X's chat page allows as a frame (its CSP frame-src:
/// www.youtube.com, player.vimeo.com, w.soundcloud.com); None for anything else.
pub fn embed_for(url: &Url) -> Option<String> {
if let Some(id) = youtube_id(url) {
return Some(format!("https://www.youtube.com/embed/{id}?autoplay=1&rel=0"));
}
let host = url.host_str()?.trim_start_matches("www.").trim_start_matches("m.").to_ascii_lowercase();
let segments: Vec<&str> = url.path_segments()?.filter(|s| !s.is_empty()).collect();
match host.as_str() {
"vimeo.com" => {
let id = segments.first()?;
(segments.len() == 1 && (6..=12).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_digit()))
.then(|| format!("https://player.vimeo.com/video/{id}?autoplay=1"))
}
"soundcloud.com" => {
const NOT_CONTENT: [&str; 9] = ["discover", "search", "you", "upload", "settings", "stream", "messages", "notifications", "pages"];
let safe = |s: &&str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
if segments.is_empty() || segments.len() > 3 || NOT_CONTENT.contains(&segments[0]) || !segments.iter().all(safe) {
return None;
}
Some(format!("https://w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F{}&auto_play=true&visual=true", segments.join("%2F")))
}
_ => None,
}
}
/// X's chat pages (`/i/chat`, `/messages`): the only pages that may ask for a preview.
pub fn is_chat_page(path: &str) -> bool {
["/i/chat", "/messages"].iter().any(|root| path == *root || path.starts_with(&format!("{root}/")))
}
/// X's own hosts: their links are X's to show, never fetched from here.
fn is_x_host(host: &str) -> bool {
["x.com", "twitter.com", "t.co", "twimg.com", "x.co"].iter().any(|own| host == *own || host.ends_with(&format!(".{own}")))
}
/// A link a chat tab may ask about: https, a domain name, default port, no user info, not X.
pub fn check_link(value: &str) -> Result<Url, String> {
if value.is_empty() || value.len() > MAX_URL_LEN || value.chars().any(|c| c.is_control() || c.is_whitespace()) {
return Err("VALIDATION: invalid link".into());
}
let url = Url::parse(value).map_err(|_| "VALIDATION: invalid link")?;
check_url(&url)?;
Ok(url)
}
fn check_url(url: &Url) -> Result<(), String> {
if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() {
return Err("VALIDATION: only plain https links".into());
}
if url.port().is_some_and(|port| port != 443) {
return Err("VALIDATION: only the default port".into());
}
let host = match url.host() {
Some(url::Host::Domain(host)) => host.to_ascii_lowercase(),
_ => return Err("VALIDATION: the link must name a host".into()),
};
if !host.contains('.') || host.ends_with(".local") || host.ends_with(".localhost") || host.ends_with(".internal") || host == "localhost" {
return Err("VALIDATION: not a public host".into());
}
if is_x_host(&host) {
return Err("UNSUPPORTED: X's own links".into());
}
Ok(())
}
/// Public unicast only: anything that could reach the owner's machine or network is refused.
pub fn is_public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
let [a, b, c, _] = v4.octets();
!(v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_broadcast()
|| v4.is_multicast()
|| v4.is_unspecified()
|| v4.is_documentation()
|| a == 0
|| (a == 100 && (64..=127).contains(&b))
|| (a == 192 && b == 0 && c == 0)
|| (a == 198 && (18..=19).contains(&b))
|| a >= 240)
}
IpAddr::V6(v6) => {
if let Some(v4) = v6.to_ipv4_mapped() {
return is_public(IpAddr::V4(v4));
}
let first = v6.segments()[0];
!(v6.is_loopback()
|| v6.is_unspecified()
|| v6.is_multicast()
|| (first & 0xfe00) == 0xfc00
|| (first & 0xffc0) == 0xfe80
|| first == 0x2001 && v6.segments()[1] == 0x0db8
|| first == 0x0064 && v6.segments()[1] == 0xff9b)
}
}
}
/// The video id of a YouTube watch, short, shorts or embed link.
pub fn youtube_id(url: &Url) -> Option<String> {
let host = url.host_str()?.trim_start_matches("www.").trim_start_matches("m.").to_ascii_lowercase();
let id = match host.as_str() {
"youtu.be" => url.path_segments()?.next()?.to_string(),
"youtube.com" | "music.youtube.com" => {
let mut segments = url.path_segments()?;
match segments.next()? {
"watch" => url.query_pairs().find(|(k, _)| k == "v")?.1.into_owned(),
"shorts" | "embed" | "live" => segments.next()?.to_string(),
_ => return None,
}
}
_ => return None,
};
(id.len() == 11 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')).then_some(id)
}
/// Plain text: entities decoded, control characters and runs of white space collapsed, capped.
pub fn clean(value: &str, max: usize) -> String {
let decoded = decode_entities(value);
let mut out = String::new();
let mut space = false;
for c in decoded.chars() {
if c.is_whitespace() || c.is_control() {
space = !out.is_empty();
continue;
}
if matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') {
continue;
}
if space {
out.push(' ');
space = false;
}
out.push(c);
}
if out.chars().count() > max {
out = out.chars().take(max.saturating_sub(1)).collect::<String>().trim_end().to_string() + "\u{2026}";
}
out
}
fn decode_entities(value: &str) -> String {
let mut out = String::with_capacity(value.len());
let mut rest = value;
while let Some(at) = rest.find('&') {
out.push_str(&rest[..at]);
rest = &rest[at..];
let end = rest[..rest.len().min(12)].find(';');
let decoded = end.and_then(|end| {
let name = &rest[1..end];
let c = match name {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" | "#39" => Some('\''),
"nbsp" => Some(' '),
_ if name.starts_with("#x") || name.starts_with("#X") => u32::from_str_radix(&name[2..], 16).ok().and_then(char::from_u32),
_ if name.starts_with('#') => name[1..].parse().ok().and_then(char::from_u32),
_ => None,
}?;
Some((c, end + 1))
});
match decoded {
Some((c, len)) => {
out.push(c);
rest = &rest[len..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
/// The attributes of one tag (`<meta a="b" c='d' e=f>`), names lowercased.
fn attributes(tag: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let bytes = tag.as_bytes();
let mut i = 0;
while i < bytes.len() {
while i < bytes.len() && (bytes[i].is_ascii_whitespace() || bytes[i] == b'/') {
i += 1;
}
let start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'=' && bytes[i] != b'>' {
i += 1;
}
if start == i {
i += 1;
continue;
}
let name = tag[start..i].to_ascii_lowercase();
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
let mut value = String::new();
if i < bytes.len() && bytes[i] == b'=' {
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < bytes.len() && (bytes[i] == b'"' || bytes[i] == b'\'') {
let quote = bytes[i];
i += 1;
let from = i;
while i < bytes.len() && bytes[i] != quote {
i += 1;
}
value = tag[from..i].to_string();
i += 1;
} else {
let from = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
i += 1;
}
value = tag[from..i].to_string();
}
}
out.push((name, value));
}
out
}
/// What a page's head says about itself: Open Graph first, then Twitter cards, then `<title>` and
/// the description meta. `image` is resolved against `base` and checked like a link.
#[derive(Debug, Default, PartialEq)]
pub struct PageMeta {
pub title: String,
pub description: String,
pub site: String,
pub image: Option<Url>,
}
pub fn parse_head(html: &str, base: &Url) -> PageMeta {
let lower = html.to_ascii_lowercase();
let head_end = lower.find("</head").unwrap_or(lower.len());
let (html, lower) = (&html[..head_end], &lower[..head_end]);
let mut found: Vec<(String, String)> = Vec::new();
let mut at = 0;
while let Some(start) = lower[at..].find("<meta").map(|i| at + i) {
let Some(end) = lower[start..].find('>').map(|i| start + i) else { break };
let attrs = attributes(&html[start + 5..end]);
let key = attrs.iter().find(|(n, _)| n == "property" || n == "name").map(|(_, v)| v.to_ascii_lowercase());
let content = attrs.iter().find(|(n, _)| n == "content").map(|(_, v)| v.clone());
if let (Some(key), Some(content)) = (key, content) {
found.push((key, content));
}
at = end;
}
let get = |keys: &[&str]| keys.iter().find_map(|key| found.iter().find(|(k, v)| k == key && !v.trim().is_empty()).map(|(_, v)| v.clone()));
let title_tag = lower.find("<title").and_then(|start| {
let open = start + lower[start..].find('>')? + 1;
let close = open + lower[open..].find("</title")?;
Some(html[open..close].to_string())
});
let title = get(&["og:title", "twitter:title"]).or(title_tag).unwrap_or_default();
let description = get(&["og:description", "twitter:description", "description"]).unwrap_or_default();
let site = get(&["og:site_name", "application-name"]).unwrap_or_default();
let image = get(&["og:image:secure_url", "og:image", "og:image:url", "twitter:image", "twitter:image:src"])
.and_then(|value| base.join(decode_entities(value.trim()).as_str()).ok())
.filter(|url| check_url(url).is_ok());
PageMeta {
title: clean(&title, MAX_TITLE),
description: clean(&description, MAX_DESCRIPTION),
site: clean(&site, MAX_SITE),
image,
}
}
/// The image type by its first bytes; anything else (SVG included) is refused.
pub fn image_mime(bytes: &[u8]) -> Option<&'static str> {
match bytes {
[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, ..] => Some("image/png"),
[0xff, 0xd8, 0xff, ..] => Some("image/jpeg"),
[b'G', b'I', b'F', b'8', b'7' | b'9', b'a', ..] => Some("image/gif"),
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => Some("image/webp"),
_ => None,
}
}
/// The host as shown under a preview when the page names no site (`www.` dropped).
pub fn display_host(url: &Url) -> String {
clean(url.host_str().unwrap_or_default().trim_start_matches("www."), MAX_SITE)
}
#[cfg(feature = "desktop")]
pub use fetch::preview;
#[cfg(feature = "desktop")]
mod fetch {
use super::*;
use base64::Engine;
use std::collections::HashMap;
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
const CACHE_ENTRIES: usize = 256;
const CACHE_TTL: Duration = Duration::from_secs(30 * 60);
/// At most this many fresh fetches per minute for the whole app (cached answers are free).
const PER_MINUTE: usize = 30;
type Cached = (Instant, Result<LinkPreview, String>);
fn cache() -> &'static Mutex<HashMap<String, Cached>> {
static CACHE: OnceLock<Mutex<HashMap<String, Cached>>> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
fn allow_fetch() -> bool {
static RECENT: OnceLock<Mutex<Vec<Instant>>> = OnceLock::new();
let mut recent = RECENT.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
let now = Instant::now();
recent.retain(|at| now.duration_since(*at) < Duration::from_secs(60));
if recent.len() >= PER_MINUTE {
return false;
}
recent.push(now);
true
}
/// The preview of one link: from the cache, else fetched under the rules above.
pub async fn preview(link: &str) -> Result<LinkPreview, String> {
let url = check_link(link)?;
let key = url.as_str().to_string();
if let Some((at, result)) = cache().lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
if at.elapsed() < CACHE_TTL {
return result.clone();
}
}
if !allow_fetch() {
return Err("BUSY: too many previews, try again shortly".into());
}
let result = match youtube_id(&url) {
Some(id) => youtube(&url, id).await,
None => page(&url).await.map(|preview| LinkPreview { embed: embed_for(&url), ..preview }),
};
let mut cache = cache().lock().unwrap_or_else(|e| e.into_inner());
if cache.len() >= CACHE_ENTRIES {
cache.retain(|_, (at, _)| at.elapsed() < CACHE_TTL);
if cache.len() >= CACHE_ENTRIES {
cache.clear();
}
}
cache.insert(key, (Instant::now(), result.clone()));
result
}
/// Resolves the host off the async runtime and keeps only public addresses (all must be public).
async fn public_addrs(url: &Url) -> Result<(String, Vec<SocketAddr>), String> {
let host = url.host_str().ok_or("VALIDATION: no host")?.to_string();
let lookup = host.clone();
let addrs: Vec<SocketAddr> = tauri::async_runtime::spawn_blocking(move || (lookup.as_str(), 443).to_socket_addrs().map(|a| a.collect::<Vec<_>>()))
.await
.map_err(|_| "NETWORK: lookup failed")?
.map_err(|_| "NETWORK: the host does not resolve")?;
if addrs.is_empty() || !addrs.iter().all(|addr| is_public(addr.ip())) {
return Err("FORBIDDEN: the host is not on the public internet".into());
}
Ok((host, addrs))
}
fn client(host: &str, addrs: &[SocketAddr]) -> Result<reqwest::Client, String> {
if rustls::crypto::CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
// No cookie store: nothing is sent or kept. Redirects are followed by hand (each hop checked).
reqwest::Client::builder()
.user_agent(USER_AGENT)
.redirect(reqwest::redirect::Policy::none())
.referer(false)
.https_only(true)
.connect_timeout(Duration::from_secs(6))
.timeout(Duration::from_secs(12))
.resolve_to_addrs(host, addrs)
.build()
.map_err(|e| format!("NETWORK: {e}"))
}
/// GET with hand-followed redirects; returns the final URL and up to `max` bytes of the body
/// (`stop` may end the read early, e.g. once the page head is complete).
async fn get(start: &Url, accept: &str, max: usize, stop: fn(&[u8]) -> bool) -> Result<(Url, String, Vec<u8>), String> {
let mut url = start.clone();
for _ in 0..=MAX_REDIRECTS {
check_url(&url)?;
let (host, addrs) = public_addrs(&url).await?;
let mut response = client(&host, &addrs)?
.get(url.clone())
.header(reqwest::header::ACCEPT, accept)
.header(reqwest::header::ACCEPT_LANGUAGE, "en;q=0.9, *;q=0.5")
.send()
.await
.map_err(|e| format!("NETWORK: {}", e.without_url()))?;
let status = response.status();
if status.is_redirection() {
let location = response.headers().get(reqwest::header::LOCATION).and_then(|v| v.to_str().ok()).ok_or("NETWORK: redirect without a location")?;
url = url.join(location).map_err(|_| "NETWORK: invalid redirect")?;
continue;
}
if !status.is_success() {
return Err(format!("NETWORK: the site answered {}", status.as_u16()));
}
let mime = response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_ascii_lowercase();
if response.content_length().is_some_and(|len| len as usize > max) && !accept.starts_with("text/html") {
return Err("VALIDATION: too large".into());
}
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| format!("NETWORK: {}", e.without_url()))? {
let room = max.saturating_sub(body.len());
body.extend_from_slice(&chunk[..chunk.len().min(room)]);
if body.len() >= max || stop(&body) {
break;
}
}
return Ok((url, mime, body));
}
Err("NETWORK: too many redirects".into())
}
fn head_complete(body: &[u8]) -> bool {
let tail = &body[body.len().saturating_sub(16 * 1024)..];
tail.windows(7).any(|w| w.eq_ignore_ascii_case(b"</head>"))
}
fn never(_: &[u8]) -> bool {
false
}
async fn page(url: &Url) -> Result<LinkPreview, String> {
let (final_url, mime, body) = get(url, "text/html,application/xhtml+xml;q=0.9,image/*;q=0.8", MAX_PAGE_BYTES, head_complete).await?;
if mime.starts_with("image/") {
// A link to an image: the image itself, named by its file.
let name = final_url.path_segments().and_then(|mut s| s.next_back()).unwrap_or_default();
let name = url::form_urlencoded::parse(name.as_bytes()).map(|(k, v)| if v.is_empty() { k.into_owned() } else { format!("{k}={v}") }).collect::<String>();
return Ok(LinkPreview { url: url.to_string(), site: display_host(&final_url), title: clean(&name, MAX_TITLE), description: String::new(), image: Some(fetch_image(&final_url).await?), embed: None });
}
if !(mime.starts_with("text/html") || mime.starts_with("application/xhtml")) {
return Err("UNSUPPORTED: not a web page".into());
}
let html = String::from_utf8_lossy(&body);
let meta = parse_head(&html, &final_url);
if meta.title.is_empty() && meta.image.is_none() {
return Err("UNSUPPORTED: the page has no preview".into());
}
let image = match &meta.image {
Some(image) => fetch_image(image).await.ok(),
None => None,
};
Ok(LinkPreview {
url: url.to_string(),
site: if meta.site.is_empty() { display_host(&final_url) } else { meta.site },
title: meta.title,
description: meta.description,
image,
embed: None,
})
}
async fn fetch_image(url: &Url) -> Result<String, String> {
let (_, _, bytes) = get(url, "image/avif,image/webp,image/png,image/jpeg,image/gif;q=0.8", MAX_IMAGE_BYTES, never).await?;
if bytes.len() >= MAX_IMAGE_BYTES {
return Err("VALIDATION: image too large".into());
}
let mime = image_mime(&bytes).ok_or("UNSUPPORTED: not an image")?;
Ok(format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(&bytes)))
}
/// YouTube: its oEmbed answer (title, channel) and the video's thumbnail; the player is YouTube's
/// own www.youtube.com, which X's page allows as a frame, loaded only when the user presses play.
async fn youtube(url: &Url, id: String) -> Result<LinkPreview, String> {
let mut oembed = Url::parse("https://www.youtube.com/oembed?format=json").expect("static URL");
oembed.query_pairs_mut().append_pair("url", &format!("https://www.youtube.com/watch?v={id}"));
let (_, _, body) = get(&oembed, "application/json", 64 * 1024, never).await?;
let value: serde_json::Value = serde_json::from_slice(&body).map_err(|_| "UNSUPPORTED: no video data")?;
let text = |key: &str, max: usize| clean(value.get(key).and_then(|v| v.as_str()).unwrap_or(""), max);
// The thumbnail comes as data too: X's chat page does not reliably load it from i.ytimg.com.
let thumbnail = Url::parse(&format!("https://i.ytimg.com/vi/{id}/hqdefault.jpg")).expect("checked id");
Ok(LinkPreview {
url: url.to_string(),
site: "YouTube".into(),
title: text("title", MAX_TITLE),
description: text("author_name", MAX_SITE),
image: fetch_image(&thumbnail).await.ok(),
embed: embed_for(url),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_plain_public_https_links() {
for ok in ["https://example.com/a?b=c", "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "https://sub.example.co.uk:443/"] {
assert!(check_link(ok).is_ok(), "{ok}");
}
for bad in [
"http://example.com/",
"https://user:pw@example.com/",
"https://example.com:8443/",
"https://127.0.0.1/",
"https://[::1]/",
"https://192.168.0.1/",
"https://localhost/",
"https://printer.local/",
"https://intranet/",
"https://x.com/someone/status/1",
"https://pbs.twimg.com/media/a.jpg",
"https://t.co/abc",
"file:///etc/passwd",
"javascript:alert(1)",
"https://exa mple.com/",
"",
] {
assert!(check_link(bad).is_err(), "{bad}");
}
assert!(check_link(&format!("https://example.com/{}", "a".repeat(MAX_URL_LEN))).is_err());
}
#[test]
fn private_and_special_addresses_are_not_public() {
for ip in ["127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.0.192", "169.254.1.1", "100.64.0.1", "0.0.0.0", "224.0.0.1", "255.255.255.255", "198.18.0.1", "::1", "fe80::1", "fd00::1", "::ffff:192.168.0.1", "2001:db8::1", "64:ff9b::a00:1"] {
assert!(!is_public(ip.parse().unwrap()), "{ip}");
}
for ip in ["1.1.1.1", "142.250.185.78", "2606:4700:4700::1111"] {
assert!(is_public(ip.parse().unwrap()), "{ip}");
}
}
#[test]
fn chat_pages_only() {
for ok in ["/i/chat", "/i/chat/1-2", "/messages", "/messages/1-2"] {
assert!(is_chat_page(ok), "{ok}");
}
for bad in ["/home", "/i/chatter", "/messagesx", "/someone/status/1", "/"] {
assert!(!is_chat_page(bad), "{bad}");
}
}
#[test]
fn youtube_ids() {
let id = |s: &str| youtube_id(&Url::parse(s).unwrap());
assert_eq!(id("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1"), Some("dQw4w9WgXcQ".into()));
assert_eq!(id("https://youtu.be/dQw4w9WgXcQ?si=x"), Some("dQw4w9WgXcQ".into()));
assert_eq!(id("https://m.youtube.com/shorts/dQw4w9WgXcQ"), Some("dQw4w9WgXcQ".into()));
assert_eq!(id("https://www.youtube.com/embed/dQw4w9WgXcQ"), Some("dQw4w9WgXcQ".into()));
assert_eq!(id("https://www.youtube.com/watch?v=bad\"id"), None);
assert_eq!(id("https://www.youtube.com/@channel"), None);
assert_eq!(id("https://example.com/watch?v=dQw4w9WgXcQ"), None);
}
#[test]
fn players_only_on_the_hosts_x_allows_as_frames() {
let embed = |s: &str| embed_for(&Url::parse(s).unwrap());
assert_eq!(embed("https://youtu.be/dQw4w9WgXcQ").as_deref(), Some("https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&rel=0"));
assert_eq!(embed("https://vimeo.com/76979871").as_deref(), Some("https://player.vimeo.com/video/76979871?autoplay=1"));
assert_eq!(embed("https://vimeo.com/channels/staffpicks"), None);
assert_eq!(
embed("https://soundcloud.com/crtkafa/sets/albums").as_deref(),
Some("https://w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2Fcrtkafa%2Fsets%2Falbums&auto_play=true&visual=true")
);
assert_eq!(embed("https://soundcloud.com/discover"), None);
assert_eq!(embed("https://soundcloud.com/a%22b"), None);
assert_eq!(embed("https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT"), None, "not a frame X allows");
assert_eq!(embed("https://example.com/video"), None);
}
#[test]
fn reads_a_page_head() {
let base = Url::parse("https://fishies.lol/play/").unwrap();
let html = r#"<!doctype html><html><head><title>Fallback</title>
<meta property="og:title" content="Fishies &amp; friends">
<meta name=description content='The social aquarium'>
<meta property="og:site_name" content="Fishies">
<meta property="og:image" content="/img/card.png">
</head><body><meta property="og:title" content="not this"></body></html>"#;
let meta = parse_head(html, &base);
assert_eq!(meta.title, "Fishies & friends");
assert_eq!(meta.description, "The social aquarium");
assert_eq!(meta.site, "Fishies");
assert_eq!(meta.image.unwrap().as_str(), "https://fishies.lol/img/card.png");
let bare = parse_head("<head><title>\n Only a title \u{202e}</title><meta property='og:image' content='http://insecure.example/a.png'></head>", &base);
assert_eq!(bare.title, "Only a title");
assert_eq!(bare.image, None, "an image off the link rules is dropped");
assert_eq!(parse_head("<head><meta property='og:image' content='https://10.0.0.1/a.png'></head>", &base).image, None);
}
#[test]
fn text_is_plain_and_capped() {
assert_eq!(clean("a&lt;b&gt; &#x41;&#66; &unknown; &", 50), "a<b> AB &unknown; &");
assert_eq!(clean(&"x".repeat(500), 10).chars().count(), 10);
assert_eq!(clean("\u{0}\u{7}one\ttwo\n", 50), "one two");
}
#[test]
fn images_by_magic_bytes_only() {
assert_eq!(image_mime(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));
assert_eq!(image_mime(b"\xff\xd8\xff\xe0"), Some("image/jpeg"));
assert_eq!(image_mime(b"GIF89a"), Some("image/gif"));
assert_eq!(image_mime(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp"));
assert_eq!(image_mime(b"<svg xmlns="), None);
assert_eq!(image_mime(b"<html>"), None);
}
}
/// Live check against real sites (network): `LINK_PREVIEW_LIVE="url url" cargo test --lib live_previews -- --ignored --nocapture`.
#[cfg(all(test, feature = "desktop"))]
mod live {
#[test]
#[ignore]
fn live_previews() {
let urls = std::env::var("LINK_PREVIEW_LIVE").unwrap_or_default();
for url in urls.split_whitespace() {
let result = tauri::async_runtime::block_on(super::preview(url));
match result {
Ok(p) => println!("OK {url}\n site={:?} title={:?}\n desc={:?}\n image={} embed={:?}", p.site, p.title, p.description.chars().take(80).collect::<String>(), p.image.as_ref().map(|i| format!("{} bytes", i.len())).unwrap_or("none".into()), p.embed),
Err(e) => println!("ERR {url}: {e}"),
}
}
}
}

View file

@ -1,434 +1,430 @@
use url::Url; use url::Url;
use better_twttr::{policy::*, site::SITE, theme::{x_default, XTheme, X_THEMES}}; use better_twttr::{policy::*, site::SITE, theme::{x_default, XTheme, X_THEMES}};
#[test] #[test]
fn exact_origin_and_window_scope_is_enforced() { fn exact_origin_and_window_scope_is_enforced() {
let x = Url::parse("https://x.com/home").unwrap(); let x = Url::parse("https://x.com/home").unwrap();
assert!(require_capture("tab-1", &x).is_ok()); assert!(require_capture("tab-1", &x).is_ok());
assert!(require_capture("shell", &x).is_err()); assert!(require_capture("shell", &x).is_err());
assert!(require_local( assert!(require_local(
"tab-1", "tab-1",
&Url::parse("tauri://localhost/index.html").unwrap(), &Url::parse("tauri://localhost/index.html").unwrap(),
false false
) )
.is_err()); .is_err());
for value in [ for value in [
"https://evil.x.com/home", "https://evil.x.com/home",
"http://x.com/home", "http://x.com/home",
"https://x.com:8443/home", "https://x.com:8443/home",
"https://x.com.evil.test/home", "https://x.com.evil.test/home",
"https://x.com@evil.test/home", "https://x.com@evil.test/home",
"https://evil@x.com/home", "https://evil@x.com/home",
"file:///tmp/index.html", "file:///tmp/index.html",
"https://twitter.com/home", "https://twitter.com/home",
] { ] {
assert!( assert!(
require_capture("tab-1", &Url::parse(value).unwrap()).is_err(), require_capture("tab-1", &Url::parse(value).unwrap()).is_err(),
"accepted {value}" "accepted {value}"
); );
} }
} }
#[test] #[test]
fn local_origin_has_no_production_localhost_backdoor() { fn local_origin_has_no_production_localhost_backdoor() {
for value in [ for value in [
"tauri://localhost/index.html", "tauri://localhost/index.html",
"http://tauri.localhost/index.html", "http://tauri.localhost/index.html",
"https://tauri.localhost/index.html", "https://tauri.localhost/index.html",
] { ] {
assert!(require_local("shell", &Url::parse(value).unwrap(), false).is_ok()); assert!(require_local("shell", &Url::parse(value).unwrap(), false).is_ok());
} }
assert!(require_local("shell", &Url::parse("http://127.0.0.1:1420/").unwrap(), true).is_ok()); assert!(require_local("shell", &Url::parse("http://127.0.0.1:1420/").unwrap(), true).is_ok());
for value in [ for value in [
"https://x.com/", "https://x.com/",
"http://127.0.0.1:1420/", "http://127.0.0.1:1420/",
"http://localhost:1420/", "http://localhost:1420/",
"https://tauri.localhost.evil.test/", "https://tauri.localhost.evil.test/",
"tauri://evil/", "tauri://evil/",
] { ] {
assert!( assert!(
require_local("shell", &Url::parse(value).unwrap(), false).is_err(), require_local("shell", &Url::parse(value).unwrap(), false).is_err(),
"accepted {value}" "accepted {value}"
); );
} }
} }
#[test] #[test]
fn navigation_allows_only_x_and_specific_legacy_login_routes() { fn navigation_allows_only_x_and_specific_legacy_login_routes() {
for value in [ for value in [
"https://x.com/home", "https://x.com/home",
"https://twitter.com/login", "https://twitter.com/login",
"https://twitter.com/i/flow/login", "https://twitter.com/i/flow/login",
"https://twitter.com/i/flow/login/step", "https://twitter.com/i/flow/login/step",
] { ] {
assert!(x_navigation_allowed(&Url::parse(value).unwrap())); assert!(x_navigation_allowed(&Url::parse(value).unwrap()));
} }
for value in [ for value in [
"https://twitter.com/home", "https://twitter.com/home",
"https://t.co/test", "https://t.co/test",
"https://accounts.google.com/", "https://accounts.google.com/",
"javascript:alert(1)", "javascript:alert(1)",
"mailto:test@example.com", "mailto:test@example.com",
"https://twitter.com/login/evil", "https://twitter.com/login/evil",
] { ] {
assert!( assert!(
!x_navigation_allowed(&Url::parse(value).unwrap()), !x_navigation_allowed(&Url::parse(value).unwrap()),
"accepted {value}" "accepted {value}"
); );
} }
} }
#[test] #[test]
fn remote_capabilities_cannot_reach_the_vault() { fn remote_capabilities_cannot_reach_the_vault() {
let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap(); let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap();
let x = read(include_str!("../capabilities/x-capture.json")); let x = read(include_str!("../capabilities/x-capture.json"));
// Drafts popover (2026-09-27): X may only open/close it about itself and ask one yes/no hint question. // Drafts popover (2026-09-27): X may only open/close it about itself and ask one yes/no hint question.
// Chat+ link previews (owner-approved, 2026-10-10): one link at a time, from a chat page only. assert_eq!(x["permissions"], serde_json::json!(["allow-capture-draft", "allow-open-panel", "allow-drafts-picker-open", "allow-drafts-popover-dismiss", "allow-drafts-hint", "allow-keyword-alert"]));
assert_eq!(x["permissions"], serde_json::json!(["allow-capture-draft", "allow-open-panel", "allow-drafts-picker-open", "allow-drafts-popover-dismiss", "allow-drafts-hint", "allow-keyword-alert", "allow-link-preview"])); for vault in ["allow-popover-drafts", "allow-popover-insert", "allow-popover-state", "allow-draft-list"] {
let desktop = include_str!("../src/desktop.rs"); assert!(!x["permissions"].as_array().unwrap().iter().any(|p| p == vault), "X tabs have {vault}");
waybetter_host::testkit::assert_guarded(desktop, "link_preview", "policy::require_capture(webview.label(), &webview.url()"); }
assert!(desktop.contains("link_preview::is_chat_page(page.path())"), "link previews answer chat pages only");
for vault in ["allow-popover-drafts", "allow-popover-insert", "allow-popover-state", "allow-draft-list"] { // The drafts popover is local-only and gets nothing beyond its own five commands.
assert!(!x["permissions"].as_array().unwrap().iter().any(|p| p == vault), "X tabs have {vault}"); let popover = read(include_str!("../capabilities/drafts-popover.json"));
} assert_eq!(popover["webviews"], serde_json::json!(["popover-*"]));
assert_eq!(popover["local"], true);
// The drafts popover is local-only and gets nothing beyond its own five commands. assert!(popover.get("remote").is_none());
let popover = read(include_str!("../capabilities/drafts-popover.json")); assert_eq!(popover["permissions"], serde_json::json!(["allow-popover-state", "allow-popover-drafts", "allow-popover-insert", "allow-popover-close", "allow-popover-open-vault"]));
assert_eq!(popover["webviews"], serde_json::json!(["popover-*"])); assert_eq!(x["webviews"], serde_json::json!(["tab-*"]));
assert_eq!(popover["local"], true); assert_eq!(x["remote"]["urls"], serde_json::json!(["https://x.com/*"]));
assert!(popover.get("remote").is_none()); assert_eq!(x["local"], false);
assert_eq!(popover["permissions"], serde_json::json!(["allow-popover-state", "allow-popover-drafts", "allow-popover-insert", "allow-popover-close", "allow-popover-open-vault"])); // Linux joined with the same permissions (owner request, 2026-09-28): platforms only, no new grants.
assert_eq!(x["webviews"], serde_json::json!(["tab-*"])); assert_eq!(x["platforms"], serde_json::json!(["macOS", "windows", "linux"]));
assert_eq!(x["remote"]["urls"], serde_json::json!(["https://x.com/*"]));
assert_eq!(x["local"], false); let tabs = read(include_str!("../capabilities/tab-chrome.json"));
// Linux joined with the same permissions (owner request, 2026-09-28): platforms only, no new grants. assert_eq!(tabs["permissions"], serde_json::json!(["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"]));
assert_eq!(x["platforms"], serde_json::json!(["macOS", "windows", "linux"])); assert_eq!(tabs["webviews"], serde_json::json!(["tab-*"]));
assert_eq!(tabs["local"], false);
let tabs = read(include_str!("../capabilities/tab-chrome.json"));
assert_eq!(tabs["permissions"], serde_json::json!(["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"])); let local = read(include_str!("../capabilities/workspace-local.json"));
assert_eq!(tabs["webviews"], serde_json::json!(["tab-*"])); assert!(local.get("remote").is_none());
assert_eq!(tabs["local"], false); // My Space (profile customization) is removed: its commands do not exist, so no capability
// file grants them and neither the command manifest nor the handler names them.
let local = read(include_str!("../capabilities/workspace-local.json")); let (build, desktop) = (include_str!("../build.rs"), include_str!("../src/desktop.rs"));
assert!(local.get("remote").is_none()); for gone in [
// My Space (profile customization) is removed: its commands do not exist, so no capability "profile_owner_get", "profile_create", "profile_api", "profile_media_pick", "profile_media_still", "profile_media_upload", "profile_still_to_x", "profile_view_get", "profile_view_set",
// file grants them and neither the command manifest nor the handler names them. "bt_profiles_resolve", "bt_media_get", "bt_profile_link_seen",
let (build, desktop) = (include_str!("../build.rs"), include_str!("../src/desktop.rs")); ] {
for gone in [ let permission = format!("allow-{}", gone.replace('_', "-"));
"profile_owner_get", "profile_create", "profile_api", "profile_media_pick", "profile_media_still", "profile_media_upload", "profile_still_to_x", "profile_view_get", "profile_view_set", for (name, capability) in [("x-capture", &x), ("drafts-popover", &popover), ("tab-chrome", &tabs), ("workspace-local", &local)] {
"bt_profiles_resolve", "bt_media_get", "bt_profile_link_seen", assert!(!capability["permissions"].as_array().unwrap().iter().any(|p| p == permission.as_str()), "{name} grants {permission}");
] { }
let permission = format!("allow-{}", gone.replace('_', "-")); assert!(!build.contains(&format!("\"{gone}\"")), "build.rs still lists {gone}");
for (name, capability) in [("x-capture", &x), ("drafts-popover", &popover), ("tab-chrome", &tabs), ("workspace-local", &local)] { assert!(!desktop.contains(gone), "desktop.rs still names {gone}");
assert!(!capability["permissions"].as_array().unwrap().iter().any(|p| p == permission.as_str()), "{name} grants {permission}"); }
} assert_eq!(local["webviews"], serde_json::json!(["shell"]));
assert!(!build.contains(&format!("\"{gone}\"")), "build.rs still lists {gone}");
assert!(!desktop.contains(gone), "desktop.rs still names {gone}"); // Update commands are shell-only; no capability exposes the updater/process plugin JS APIs.
} let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>();
assert_eq!(local["webviews"], serde_json::json!(["shell"])); // Account profiles (separate X logins) are managed only by the shell.
// Drafts are inserted and alert keywords edited only by the shell; X tabs only ask/report.
// Update commands are shell-only; no capability exposes the updater/process plugin JS APIs. for name in [
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>(); "allow-update-status", "allow-apply-update", "allow-app-ready", "allow-profiles-get", "allow-profiles-set",
// Account profiles (separate X logins) are managed only by the shell. "allow-tab-insert-text", "allow-alerts-get", "allow-alerts-set", "allow-draft-list", "allow-draft-revisions",
// Drafts are inserted and alert keywords edited only by the shell; X tabs only ask/report. // Google Fonts downloads (network), account/pane themes and the builder preview: shell only.
for name in [ "allow-gfonts-installed", "allow-gfonts-install", "allow-gfonts-remove", "allow-gfonts-faces", "allow-gfonts-preview",
"allow-update-status", "allow-apply-update", "allow-app-ready", "allow-profiles-get", "allow-profiles-set", "allow-theme-scopes-get", "allow-theme-scopes-set", "allow-theme-preview",
"allow-tab-insert-text", "allow-alerts-get", "allow-alerts-set", "allow-draft-list", "allow-draft-revisions", // Installing themes/plugins (links, dropped files, the signed store; owner-approved 2026-09-28):
// Google Fonts downloads (network), account/pane themes and the builder preview: shell only. // only the shell, after its confirmation screen. X tabs and web pages cannot install anything.
"allow-gfonts-installed", "allow-gfonts-install", "allow-gfonts-remove", "allow-gfonts-faces", "allow-gfonts-preview", "allow-install-pending", "allow-install-stage-link", "allow-install-stage-file", "allow-install-cancel",
"allow-theme-scopes-get", "allow-theme-scopes-set", "allow-theme-preview", "allow-install-commit", "allow-install-records", "allow-install-forget", "allow-plugin-remove",
// Installing themes/plugins (links, dropped files, the signed store; owner-approved 2026-09-28): "allow-store-catalog", "allow-store-stage",
// only the shell, after its confirmation screen. X tabs and web pages cannot install anything. ] {
"allow-install-pending", "allow-install-stage-link", "allow-install-stage-file", "allow-install-cancel", assert!(perms(&local).iter().any(|p| p == name), "shell lacks {name}");
"allow-install-commit", "allow-install-records", "allow-install-forget", "allow-plugin-remove", assert!(!perms(&x).iter().chain(perms(&tabs).iter()).any(|p| p == name), "tab has {name}");
"allow-store-catalog", "allow-store-stage", }
] { for p in perms(&local).iter().chain(perms(&x).iter()).chain(perms(&tabs).iter()) {
assert!(perms(&local).iter().any(|p| p == name), "shell lacks {name}"); assert!(
assert!(!perms(&x).iter().chain(perms(&tabs).iter()).any(|p| p == name), "tab has {name}"); !p.starts_with("updater:") && !p.starts_with("process:") && !p.starts_with("notification:") && !p.starts_with("deep-link:"),
} "plugin API exposed: {p}"
for p in perms(&local).iter().chain(perms(&x).iter()).chain(perms(&tabs).iter()) { );
assert!( }
!p.starts_with("updater:") && !p.starts_with("process:") && !p.starts_with("notification:") && !p.starts_with("deep-link:"), }
"plugin API exposed: {p}"
); #[test]
} fn theme_accepts_only_known_presets_and_hex_accents() {
} let script = |theme: XTheme| theme.script(&X_THEMES, &SITE);
let valid = XTheme { preset: "night-ink".into(), accent: Some("#1d9bf0".into()), ..x_default() };
#[test] let text = script(valid).unwrap();
fn theme_accepts_only_known_presets_and_hex_accents() { assert!(text.contains("location.origin!=='https://x.com'"));
let script = |theme: XTheme| theme.script(&X_THEMES, &SITE); assert!(text.contains(r#""preset":"night-ink""#));
let valid = XTheme { preset: "night-ink".into(), accent: Some("#1d9bf0".into()), ..x_default() }; assert!(x_default().is_default(&X_THEMES));
let text = script(valid).unwrap(); for preset in ["x", "classic", "night-ink", "terminal", "paper"] {
assert!(text.contains("location.origin!=='https://x.com'")); assert!(script(XTheme { preset: preset.into(), ..x_default() }).is_ok());
assert!(text.contains(r#""preset":"night-ink""#)); }
assert!(x_default().is_default(&X_THEMES)); for hostile in ["evil", "x;display:none", "</script>", ""] {
for preset in ["x", "classic", "night-ink", "terminal", "paper"] { assert!(script(XTheme { preset: hostile.into(), ..x_default() }).is_err(), "accepted {hostile}");
assert!(script(XTheme { preset: preset.into(), ..x_default() }).is_ok()); }
} for hostile in ["red", "#fff", "url(https://evil.test)", "#000000;display:none", "</style><script>", "#00000é"] {
for hostile in ["evil", "x;display:none", "</script>", ""] { assert!(script(XTheme { accent: Some(hostile.into()), ..x_default() }).is_err(), "accepted {hostile}");
assert!(script(XTheme { preset: hostile.into(), ..x_default() }).is_err(), "accepted {hostile}"); }
} assert!(serde_json::from_str::<XTheme>(r#"{"preset":"x","css":"body{}"}"#).is_err());
for hostile in ["red", "#fff", "url(https://evil.test)", "#000000;display:none", "</style><script>", "#00000é"] { }
assert!(script(XTheme { accent: Some(hostile.into()), ..x_default() }).is_err(), "accepted {hostile}");
} #[test]
assert!(serde_json::from_str::<XTheme>(r#"{"preset":"x","css":"body{}"}"#).is_err()); fn bundle_keeps_macos_targets_and_signed_updater() {
} let conf: serde_json::Value = serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
let targets = conf["bundle"]["targets"].as_array().unwrap();
#[test] for target in ["nsis", "app", "dmg"] {
fn bundle_keeps_macos_targets_and_signed_updater() { assert!(targets.iter().any(|t| t == target), "missing bundle target {target}");
let conf: serde_json::Value = serde_json::from_str(include_str!("../tauri.conf.json")).unwrap(); }
let targets = conf["bundle"]["targets"].as_array().unwrap(); assert!(!conf["plugins"]["updater"]["pubkey"].as_str().unwrap_or("").is_empty());
for target in ["nsis", "app", "dmg"] { for endpoint in conf["plugins"]["updater"]["endpoints"].as_array().unwrap() {
assert!(targets.iter().any(|t| t == target), "missing bundle target {target}"); assert!(endpoint.as_str().unwrap().starts_with("https://"), "updater endpoint must be https");
} }
assert!(!conf["plugins"]["updater"]["pubkey"].as_str().unwrap_or("").is_empty()); // One URL scheme, only for install links; the installer/Info.plist register exactly this.
for endpoint in conf["plugins"]["updater"]["endpoints"].as_array().unwrap() { assert_eq!(conf["plugins"]["deep-link"]["desktop"]["schemes"], serde_json::json!(["waybetter"]));
assert!(endpoint.as_str().unwrap().starts_with("https://"), "updater endpoint must be https"); assert!(conf["plugins"]["deep-link"].get("mobile").is_none());
} }
// One URL scheme, only for install links; the installer/Info.plist register exactly this.
assert_eq!(conf["plugins"]["deep-link"]["desktop"]["schemes"], serde_json::json!(["waybetter"])); #[test]
assert!(conf["plugins"]["deep-link"].get("mobile").is_none()); fn backup_sync_workspace_palette_and_dev_commands_are_shell_only() {
} let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap();
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>();
#[test] let local = perms(&read(include_str!("../capabilities/workspace-local.json")));
fn backup_sync_workspace_palette_and_dev_commands_are_shell_only() { let x = perms(&read(include_str!("../capabilities/x-capture.json")));
let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap(); let tabs = perms(&read(include_str!("../capabilities/tab-chrome.json")));
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>(); let popover = perms(&read(include_str!("../capabilities/drafts-popover.json")));
let local = perms(&read(include_str!("../capabilities/workspace-local.json"))); // Settings backup/sync (files and the sync key stay native), workspaces, running a plugin's
let x = perms(&read(include_str!("../capabilities/x-capture.json"))); // palette command in a tab, and developer mode (file watcher, hot reload).
let tabs = perms(&read(include_str!("../capabilities/tab-chrome.json"))); for name in [
let popover = perms(&read(include_str!("../capabilities/drafts-popover.json"))); "allow-tab-run-command", "allow-workspaces-get", "allow-workspaces-set",
// Settings backup/sync (files and the sync key stay native), workspaces, running a plugin's "allow-backup-collect", "allow-backup-export-file", "allow-backup-open-file", "allow-backup-apply",
// palette command in a tab, and developer mode (file watcher, hot reload). "allow-sync-status", "allow-sync-choose-folder", "allow-sync-unlock", "allow-sync-lock", "allow-sync-disable",
for name in [ "allow-sync-configure", "allow-sync-push", "allow-sync-check", "allow-sync-open", "allow-sync-mark-pulled",
"allow-tab-run-command", "allow-workspaces-get", "allow-workspaces-set", "allow-dev-get", "allow-dev-set", "allow-dev-pick-theme", "allow-dev-clear-theme", "allow-dev-reload-plugin", "allow-dev-report-error",
"allow-backup-collect", "allow-backup-export-file", "allow-backup-open-file", "allow-backup-apply", ] {
"allow-sync-status", "allow-sync-choose-folder", "allow-sync-unlock", "allow-sync-lock", "allow-sync-disable", assert!(local.iter().any(|p| p == name), "shell lacks {name}");
"allow-sync-configure", "allow-sync-push", "allow-sync-check", "allow-sync-open", "allow-sync-mark-pulled", assert!(!x.iter().chain(tabs.iter()).chain(popover.iter()).any(|p| p == name), "a tab or the popover has {name}");
"allow-dev-get", "allow-dev-set", "allow-dev-pick-theme", "allow-dev-clear-theme", "allow-dev-reload-plugin", "allow-dev-report-error", }
] { // X tabs report their plugins' commands only through tab_report (owner-approved 2026-09-28);
assert!(local.iter().any(|p| p == name), "shell lacks {name}"); // the tab capabilities gained nothing for it.
assert!(!x.iter().chain(tabs.iter()).chain(popover.iter()).any(|p| p == name), "a tab or the popover has {name}"); assert_eq!(tabs, ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"]);
} }
// X tabs report their plugins' commands only through tab_report (owner-approved 2026-09-28);
// the tab capabilities gained nothing for it. #[test]
assert_eq!(tabs, ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"]); fn language_commands_are_shell_only() {
} let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap();
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>();
#[test] let local = perms(&read(include_str!("../capabilities/workspace-local.json")));
fn language_commands_are_shell_only() { let others: Vec<String> = [
let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap(); include_str!("../capabilities/x-capture.json"),
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>(); include_str!("../capabilities/tab-chrome.json"),
let local = perms(&read(include_str!("../capabilities/workspace-local.json"))); include_str!("../capabilities/drafts-popover.json"),
let others: Vec<String> = [ ]
include_str!("../capabilities/x-capture.json"), .iter()
include_str!("../capabilities/tab-chrome.json"), .flat_map(|json| perms(&read(json)))
include_str!("../capabilities/drafts-popover.json"), .collect();
] // The shell picks the language and hands native code and X tabs their strings; tabs and the
.iter() // popover only ever receive them (X tabs as data through the runtime), never set them.
.flat_map(|json| perms(&read(json))) for command in ["allow-i18n-get", "allow-i18n-set"] {
.collect(); assert!(local.iter().any(|p| p == command), "shell lacks {command}");
// The shell picks the language and hands native code and X tabs their strings; tabs and the assert!(!others.iter().any(|p| p == command), "a tab or the popover has {command}");
// popover only ever receive them (X tabs as data through the runtime), never set them. }
for command in ["allow-i18n-get", "allow-i18n-set"] { // The commands are the framework's (waybetter-host `app`); each checks shell_only first.
assert!(local.iter().any(|p| p == command), "shell lacks {command}"); for command in ["i18n_get", "i18n_set"] {
assert!(!others.iter().any(|p| p == command), "a tab or the popover has {command}"); waybetter_host::testkit::assert_guarded(include_str!("../../../../waybetter/crates/waybetter-host/src/app.rs"), command, "shell_only(&webview)?");
} }
// The commands are the framework's (waybetter-host `app`); each checks shell_only first. // X tabs get the strings only as a guarded data value, and only the runtime's own prefixes.
for command in ["i18n_get", "i18n_set"] { let source = include_str!("../src/desktop_i18n.rs");
waybetter_host::testkit::assert_guarded(include_str!("../../../../waybetter/crates/waybetter-host/src/app.rs"), command, "shell_only(&webview)?"); assert!(source.contains(r#"&["x.", "kit.", "plugin."]"#), "X tabs receive only x./kit./plugin. strings");
} assert!(include_str!("../src/desktop.rs").contains("page_string_prefixes: crate::desktop_i18n::PAGE_PREFIXES"), "X's config hands tabs exactly those");
// X tabs get the strings only as a guarded data value, and only the runtime's own prefixes. let strings = waybetter_host::i18n::NativeStrings {
let source = include_str!("../src/desktop_i18n.rs"); locale: "tr".into(),
assert!(source.contains(r#"&["x.", "kit.", "plugin."]"#), "X tabs receive only x./kit./plugin. strings"); preference: "site".into(),
assert!(include_str!("../src/desktop.rs").contains("page_string_prefixes: crate::desktop_i18n::PAGE_PREFIXES"), "X's config hands tabs exactly those"); messages: [("x.fab.title", "wayBetter"), ("kit.ok", "Tamam"), ("native.notify.alert.title", "Uyarı")]
let strings = waybetter_host::i18n::NativeStrings { .into_iter()
locale: "tr".into(), .map(|(key, value)| (key.to_owned(), value.to_owned()))
preference: "site".into(), .collect(),
messages: [("x.fab.title", "wayBetter"), ("kit.ok", "Tamam"), ("native.notify.alert.title", "Uyarı")] };
.into_iter() let script = waybetter_host::i18n::page_script(&better_twttr::site::SITE, &strings.page_payload(&["x.", "kit.", "plugin."]));
.map(|(key, value)| (key.to_owned(), value.to_owned())) assert!(script.starts_with("if(location.origin==='https://x.com')("), "page strings must be x.com only: {script}");
.collect(), assert!(script.contains("x.fab.title") && script.contains("kit.ok") && !script.contains("native.notify"), "{script}");
}; // "Follow X": a tab may report X's <html lang>, only as a valid tag and only while on x.com.
let script = waybetter_host::i18n::page_script(&better_twttr::site::SITE, &strings.page_payload(&["x.", "kit.", "plugin."])); let desktop = include_str!("../src/desktop.rs");
assert!(script.starts_with("if(location.origin==='https://x.com')("), "page strings must be x.com only: {script}"); assert!(
assert!(script.contains("x.fab.title") && script.contains("kit.ok") && !script.contains("native.notify"), "{script}"); desktop.contains("report.lang.filter(|lang| waybetter_host::i18n::valid_tag(lang) && webview.url().is_ok_and(|url| policy::x_origin(&url)))"),
// "Follow X": a tab may report X's <html lang>, only as a valid tag and only while on x.com. "tab_report lang must be a validated tag from a webview on x.com"
let desktop = include_str!("../src/desktop.rs"); );
assert!( }
desktop.contains("report.lang.filter(|lang| waybetter_host::i18n::valid_tag(lang) && webview.url().is_ok_and(|url| policy::x_origin(&url)))"),
"tab_report lang must be a validated tag from a webview on x.com" #[test]
); fn language_strings_are_plain_text() {
} use waybetter_host::i18n::NativeStrings;
let set = |value: &str| NativeStrings {
#[test] locale: "ar".into(),
fn language_strings_are_plain_text() { preference: "site".into(),
use waybetter_host::i18n::NativeStrings; messages: [("x.fab.title".to_owned(), value.to_owned())].into_iter().collect(),
let set = |value: &str| NativeStrings { };
locale: "ar".into(), assert!(set("wayBetter لـ X").validated().is_ok());
preference: "site".into(), for bad in ["<img src=x onerror=alert(1)>", "&lt;script&gt;", "javascript:alert(1)", "a\u{202e}b"] {
messages: [("x.fab.title".to_owned(), value.to_owned())].into_iter().collect(), assert!(set(bad).validated().is_err(), "{bad:?}");
}; }
assert!(set("wayBetter لـ X").validated().is_ok()); }
for bad in ["<img src=x onerror=alert(1)>", "&lt;script&gt;", "javascript:alert(1)", "a\u{202e}b"] {
assert!(set(bad).validated().is_err(), "{bad:?}"); #[test]
} fn shell_raise_is_shell_only() {
} let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap();
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>();
#[test] let local = perms(&read(include_str!("../capabilities/workspace-local.json")));
fn shell_raise_is_shell_only() { let x = perms(&read(include_str!("../capabilities/x-capture.json")));
let read = |json: &str| serde_json::from_str::<serde_json::Value>(json).unwrap(); let tabs = perms(&read(include_str!("../capabilities/tab-chrome.json")));
let perms = |v: &serde_json::Value| v["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_owned()).collect::<Vec<_>>(); let popover = perms(&read(include_str!("../capabilities/drafts-popover.json")));
let local = perms(&read(include_str!("../capabilities/workspace-local.json"))); // Re-orders the shell webview over the tabs for its own overlays: only the shell may.
let x = perms(&read(include_str!("../capabilities/x-capture.json"))); assert!(local.iter().any(|p| p == "allow-shell-raise"), "shell lacks allow-shell-raise");
let tabs = perms(&read(include_str!("../capabilities/tab-chrome.json"))); assert!(!x.iter().chain(tabs.iter()).chain(popover.iter()).any(|p| p == "allow-shell-raise"), "a tab or the popover can raise the shell");
let popover = perms(&read(include_str!("../capabilities/drafts-popover.json"))); // The command is the framework's (waybetter-host `app`).
// Re-orders the shell webview over the tabs for its own overlays: only the shell may. waybetter_host::testkit::assert_guarded(include_str!("../../../../waybetter/crates/waybetter-host/src/app.rs"), "shell_raise", "shell_only(&webview)?");
assert!(local.iter().any(|p| p == "allow-shell-raise"), "shell lacks allow-shell-raise"); waybetter_host::testkit::Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities")).assert_shell_only("shell_raise");
assert!(!x.iter().chain(tabs.iter()).chain(popover.iter()).any(|p| p == "allow-shell-raise"), "a tab or the popover can raise the shell"); }
// The command is the framework's (waybetter-host `app`).
waybetter_host::testkit::assert_guarded(include_str!("../../../../waybetter/crates/waybetter-host/src/app.rs"), "shell_raise", "shell_only(&webview)?"); /// The wayBetter host's own commands (tab layout and actions, shell raise, external links, window
waybetter_host::testkit::Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities")).assert_shell_only("shell_raise"); /// menu, profiles, language; tab shortcuts and link drags) keep their callers in X's capability
} /// files, and every command wrapper checks its caller first. Every capability file is read, so a
/// new one cannot quietly widen them.
/// The wayBetter host's own commands (tab layout and actions, shell raise, external links, window #[test]
/// menu, profiles, language; tab shortcuts and link drags) keep their callers in X's capability fn host_commands_keep_their_callers() {
/// files, and every command wrapper checks its caller first. Every capability file is read, so a use waybetter_host::testkit::{assert_guarded, assert_host_guards, Capabilities};
/// new one cannot quietly widen them. let caps = Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities"));
#[test] caps.assert_host_commands();
fn host_commands_keep_their_callers() { assert_host_guards();
use waybetter_host::testkit::{assert_guarded, assert_host_guards, Capabilities}; // Only Rust drives the plugins; no capability exposes their JS APIs.
let caps = Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities")); caps.assert_no_plugin_apis(&["updater", "process", "notification", "deep-link", "single-instance", "window-state", "opener", "dialog"]);
caps.assert_host_commands(); // X's own: vault, settings, themes, installs, backups, sync, dev mode, updates are the shell's.
assert_host_guards(); for command in [
// Only Rust drives the plugins; no capability exposes their JS APIs. "draft_list", "draft_save", "draft_revisions", "draft_status", "observation_list", "data_export",
caps.assert_no_plugin_apis(&["updater", "process", "notification", "deep-link", "single-instance", "window-state", "opener", "dialog"]); "gfonts_installed", "gfonts_install", "gfonts_remove", "gfonts_faces", "gfonts_preview",
// X's own: vault, settings, themes, installs, backups, sync, dev mode, updates are the shell's. "tab_run_command", "workspaces_get", "workspaces_set", "backup_collect", "backup_export_file", "backup_open_file", "backup_apply",
for command in [ "sync_status", "sync_choose_folder", "sync_unlock", "sync_lock", "sync_disable", "sync_configure", "sync_push", "sync_check", "sync_open", "sync_mark_pulled",
"draft_list", "draft_save", "draft_revisions", "draft_status", "observation_list", "data_export", "dev_get", "dev_set", "dev_pick_theme", "dev_clear_theme", "dev_reload_plugin", "dev_report_error",
"gfonts_installed", "gfonts_install", "gfonts_remove", "gfonts_faces", "gfonts_preview", "plugins_list", "plugin_set_enabled", "plugins_open_folder", "plugin_remove",
"tab_run_command", "workspaces_get", "workspaces_set", "backup_collect", "backup_export_file", "backup_open_file", "backup_apply", "install_pending", "install_stage_link", "install_stage_file", "install_stage_opened", "install_cancel", "install_commit", "install_records", "install_forget", "store_catalog", "store_stage",
"sync_status", "sync_choose_folder", "sync_unlock", "sync_lock", "sync_disable", "sync_configure", "sync_push", "sync_check", "sync_open", "sync_mark_pulled", "custom_css_get", "custom_css_set", "features_get", "features_set", "mode_get", "mode_set", "settings_get", "settings_set", "column_configure",
"dev_get", "dev_set", "dev_pick_theme", "dev_clear_theme", "dev_reload_plugin", "dev_report_error", "update_status", "update_check", "apply_update", "app_ready", "tab_insert_text", "alerts_get", "alerts_set",
"plugins_list", "plugin_set_enabled", "plugins_open_folder", "plugin_remove", "media_get", "media_set", "gallery_add_folder", "gallery_list", "gallery_thumb", "clip_list", "clip_thumb", "clip_remove", "tab_attach_image",
"install_pending", "install_stage_link", "install_stage_file", "install_stage_opened", "install_cancel", "install_commit", "install_records", "install_forget", "store_catalog", "store_stage", ] {
"custom_css_get", "custom_css_set", "features_get", "features_set", "mode_get", "mode_set", "settings_get", "settings_set", "column_configure", caps.assert_shell_only(command);
"update_status", "update_check", "apply_update", "app_ready", "tab_insert_text", "alerts_get", "alerts_set", }
"media_get", "media_set", "gallery_add_folder", "gallery_list", "gallery_thumb", "clip_list", "clip_thumb", "clip_remove", "tab_attach_image", // Tabs, about themselves only; the X-only ones are granted only on https://x.com.
] { for command in ["tab_report", "capture_draft", "open_panel", "drafts_picker_open", "drafts_popover_dismiss", "drafts_hint", "keyword_alert"] {
caps.assert_shell_only(command); caps.assert_tab_only(command);
} }
// Tabs, about themselves only; the X-only ones are granted only on https://x.com. let desktop = include_str!("../src/desktop.rs");
for command in ["tab_report", "capture_draft", "open_panel", "drafts_picker_open", "drafts_popover_dismiss", "drafts_hint", "keyword_alert", "link_preview"] { assert_guarded(desktop, "tab_insert_text", "shell_only(&webview)?");
caps.assert_tab_only(command); // The vault commands are the host's: shell-only in the capability files and each checking its caller
} // first; X's own handler no longer has them, and X turns the vault on with its rules.
let desktop = include_str!("../src/desktop.rs"); caps.assert_shell_only_group(waybetter_host::commands::VAULT);
assert_guarded(desktop, "tab_insert_text", "shell_only(&webview)?"); waybetter_host::testkit::assert_vault_guards();
// The vault commands are the host's: shell-only in the capability files and each checking its caller assert!(desktop.contains(".with_vault("), "the app enables the host's vault");
// first; X's own handler no longer has them, and X turns the vault on with its rules. for command in waybetter_host::commands::VAULT {
caps.assert_shell_only_group(waybetter_host::commands::VAULT); assert!(!desktop.contains(&format!("fn {command}(")), "{command} is served by the host only");
waybetter_host::testkit::assert_vault_guards(); }
assert!(desktop.contains(".with_vault("), "the app enables the host's vault"); // The updater commands are the shell's too, each checking its caller first; `update_check` runs the
for command in waybetter_host::commands::VAULT { // timer's own check once (no other endpoint), and tabs have no updater command at all.
assert!(!desktop.contains(&format!("fn {command}(")), "{command} is served by the host only"); caps.assert_shell_only_group(waybetter_host::commands::UPDATE);
} waybetter_host::testkit::assert_update_guards();
// The updater commands are the shell's too, each checking its caller first; `update_check` runs the assert!(desktop.contains(".with_updates("), "the app enables the updater");
// timer's own check once (no other endpoint), and tabs have no updater command at all. // Plugins, custom CSS, the tweak flags and the browser settings are served by the host: they
caps.assert_shell_only_group(waybetter_host::commands::UPDATE); // are in its shell-only list (checked against the capability files and for their caller
waybetter_host::testkit::assert_update_guards(); // check above), and X's own handler no longer has them.
assert!(desktop.contains(".with_updates("), "the app enables the updater"); let host = include_str!("../../../../waybetter/crates/waybetter-host/src/app.rs");
// Plugins, custom CSS, the tweak flags and the browser settings are served by the host: they for command in ["plugins_list", "plugin_set_enabled", "plugins_open_folder", "custom_css_get", "custom_css_set", "features_get", "features_set", "mode_get", "mode_set", "settings_get", "settings_set"] {
// are in its shell-only list (checked against the capability files and for their caller assert!(waybetter_host::commands::SHELL.contains(&command), "{command} is a host shell-only command");
// check above), and X's own handler no longer has them. assert_guarded(host, command, "shell_only(&webview)?");
let host = include_str!("../../../../waybetter/crates/waybetter-host/src/app.rs"); assert!(!desktop.contains(&format!("fn {command}(")), "{command} is served by the host only");
for command in ["plugins_list", "plugin_set_enabled", "plugins_open_folder", "custom_css_get", "custom_css_set", "features_get", "features_set", "mode_get", "mode_set", "settings_get", "settings_set"] { }
assert!(waybetter_host::commands::SHELL.contains(&command), "{command} is a host shell-only command"); assert_guarded(desktop, "tab_report", "tab_only(&webview)?");
assert_guarded(host, command, "shell_only(&webview)?"); // Opening the panel from a page is the host's site command: only X tabs on x.com have it.
assert!(!desktop.contains(&format!("fn {command}(")), "{command} is served by the host only"); caps.assert_site_only("open_panel", &better_twttr::site::SITE);
} assert!(!desktop.contains("fn open_panel("), "open_panel is served by the host only");
assert_guarded(desktop, "tab_report", "tab_only(&webview)?"); }
// Opening the panel from a page is the host's site command: only X tabs on x.com have it.
caps.assert_site_only("open_panel", &better_twttr::site::SITE); #[test]
assert!(!desktop.contains("fn open_panel("), "open_panel is served by the host only"); fn install_store_media_and_font_commands_are_shell_only() {
} // The store's commands are the framework's (waybetter-host `store_commands`, served because
// this app sets `AppConfig::store`): shell-only in the capability files, and each wrapper
#[test] // checks shell_only before anything else.
fn install_store_media_and_font_commands_are_shell_only() { use waybetter_host::testkit::assert_guarded;
// The store's commands are the framework's (waybetter-host `store_commands`, served because let caps = waybetter_host::testkit::Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities"));
// this app sets `AppConfig::store`): shell-only in the capability files, and each wrapper caps.assert_shell_only_group(waybetter_host::commands::STORE);
// checks shell_only before anything else. waybetter_host::testkit::assert_store_guards();
use waybetter_host::testkit::assert_guarded; // The media panel's commands are the framework's too (AppConfig::with_media): shell-only, each
let caps = waybetter_host::testkit::Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities")); // checking its caller first; only attaching to X's composer is the app's own.
caps.assert_shell_only_group(waybetter_host::commands::STORE); caps.assert_shell_only_group(waybetter_host::commands::MEDIA);
waybetter_host::testkit::assert_store_guards(); waybetter_host::testkit::assert_media_guards();
// The media panel's commands are the framework's too (AppConfig::with_media): shell-only, each // Workspaces and encrypted sync too (AppConfig::with_sync; workspaces are served for every app).
// checking its caller first; only attaching to X's composer is the app's own. caps.assert_shell_only_group(waybetter_host::commands::WORKSPACES);
caps.assert_shell_only_group(waybetter_host::commands::MEDIA); caps.assert_shell_only_group(waybetter_host::commands::SYNC);
waybetter_host::testkit::assert_media_guards(); waybetter_host::testkit::assert_sync_guards();
// Workspaces and encrypted sync too (AppConfig::with_sync; workspaces are served for every app). // The settings backup's commands are the framework's too (what it carries is the app's hooks).
caps.assert_shell_only_group(waybetter_host::commands::WORKSPACES); caps.assert_shell_only_group(waybetter_host::commands::BACKUP);
caps.assert_shell_only_group(waybetter_host::commands::SYNC); waybetter_host::testkit::assert_backup_guards();
waybetter_host::testkit::assert_sync_guards(); // Developer mode (AppConfig::with_dev): the framework's commands; the theme file is the app's hook.
// The settings backup's commands are the framework's too (what it carries is the app's hooks). caps.assert_shell_only_group(waybetter_host::commands::DEV);
caps.assert_shell_only_group(waybetter_host::commands::BACKUP); waybetter_host::testkit::assert_dev_guards();
waybetter_host::testkit::assert_backup_guards(); assert!(include_str!("../src/desktop.rs").contains(".with_dev()"), "the app enables developer mode");
// Developer mode (AppConfig::with_dev): the framework's commands; the theme file is the app's hook. assert!(include_str!("../src/desktop.rs").contains(".with_sync()"), "the app enables sync");
caps.assert_shell_only_group(waybetter_host::commands::DEV); // Site themes too (AppConfig::with_themes): the framework's commands; X only names its built-in themes.
waybetter_host::testkit::assert_dev_guards(); caps.assert_shell_only_group(waybetter_host::commands::THEME);
assert!(include_str!("../src/desktop.rs").contains(".with_dev()"), "the app enables developer mode"); waybetter_host::testkit::assert_theme_guards();
assert!(include_str!("../src/desktop.rs").contains(".with_sync()"), "the app enables sync"); assert!(include_str!("../src/desktop.rs").contains(".with_themes(&crate::theme::THEMES)"), "the app configures its themes");
// Site themes too (AppConfig::with_themes): the framework's commands; X only names its built-in themes. // The keyword alert settings (AppConfig::with_alerts): the framework's commands; the hit and its notification are X's.
caps.assert_shell_only_group(waybetter_host::commands::THEME); caps.assert_shell_only_group(waybetter_host::commands::ALERTS);
waybetter_host::testkit::assert_theme_guards(); waybetter_host::testkit::assert_alerts_guards();
assert!(include_str!("../src/desktop.rs").contains(".with_themes(&crate::theme::THEMES)"), "the app configures its themes"); assert!(include_str!("../src/desktop.rs").contains(".with_alerts(&alerts::ALERTS)"), "the app configures its alerts");
// The keyword alert settings (AppConfig::with_alerts): the framework's commands; the hit and its notification are X's. // Google Fonts too (AppConfig::with_fonts).
caps.assert_shell_only_group(waybetter_host::commands::ALERTS); caps.assert_shell_only_group(waybetter_host::commands::GFONTS);
waybetter_host::testkit::assert_alerts_guards(); waybetter_host::testkit::assert_fonts_guards();
assert!(include_str!("../src/desktop.rs").contains(".with_alerts(&alerts::ALERTS)"), "the app configures its alerts"); assert!(include_str!("../src/desktop.rs").contains(".with_fonts()"), "the app enables Google Fonts");
// Google Fonts too (AppConfig::with_fonts). assert!(include_str!("../src/desktop.rs").contains(".with_media()"), "the app enables the media panel");
caps.assert_shell_only_group(waybetter_host::commands::GFONTS); assert_guarded(include_str!("../src/desktop_media.rs"), "tab_attach_image", "shell_only(&webview)?");
waybetter_host::testkit::assert_fonts_guards(); let source = include_str!("../../../../waybetter/crates/waybetter-host/src/store_commands.rs");
assert!(include_str!("../src/desktop.rs").contains(".with_fonts()"), "the app enables Google Fonts"); // Links only ever propose an install: the deep-link handler queues and emits, nothing more.
assert!(include_str!("../src/desktop.rs").contains(".with_media()"), "the app enables the media panel"); let received = &source[source.find("fn received(").unwrap()..];
assert_guarded(include_str!("../src/desktop_media.rs"), "tab_attach_image", "shell_only(&webview)?"); let received = &received[..received.find("\n}").unwrap()];
let source = include_str!("../../../../waybetter/crates/waybetter-host/src/store_commands.rs"); assert!(!received.contains("commit") && !received.contains("stage"), "a link must not stage or install by itself");
// Links only ever propose an install: the deep-link handler queues and emits, nothing more. // The app's store settings: X's id and the framework's hosts; the compiled-in key; and it asks
let received = &source[source.find("fn received(").unwrap()..]; // the framework to serve the store.
let received = &received[..received.find("\n}").unwrap()]; let settings = include_str!("../src/distribution.rs");
assert!(!received.contains("commit") && !received.contains("stage"), "a link must not stage or install by itself"); assert!(settings.contains("app_id: \"x\"") && settings.contains("allowed_hosts: DEFAULT_HOSTS") && settings.contains("include_str!(\"../keys/store.pub\")"));
// The app's store settings: X's id and the framework's hosts; the compiled-in key; and it asks assert!(include_str!("../src/desktop.rs").contains(".with_store(&crate::distribution::STORE)"), "the app configures the store");
// the framework to serve the store. }
let settings = include_str!("../src/distribution.rs");
assert!(settings.contains("app_id: \"x\"") && settings.contains("allowed_hosts: DEFAULT_HOSTS") && settings.contains("include_str!(\"../keys/store.pub\")")); /// The popover's webview and session are the host's; X's commands reached by the popover each check
assert!(include_str!("../src/desktop.rs").contains(".with_store(&crate::distribution::STORE)"), "the app configures the store"); /// their caller first (the popover webview with the open session), and inserting a draft only
} /// focuses the tab and types (`compose` scripts), never clicks Post.
#[test]
/// The popover's webview and session are the host's; X's commands reached by the popover each check fn popover_commands_check_their_caller_and_never_post() {
/// their caller first (the popover webview with the open session), and inserting a draft only use waybetter_host::testkit::assert_guarded;
/// focuses the tab and types (`compose` scripts), never clicks Post. let source = include_str!("../src/desktop_popover.rs");
#[test] assert_guarded(source, "popover_state", "host::session_of(&webview)");
fn popover_commands_check_their_caller_and_never_post() { for command in ["popover_drafts", "popover_insert", "popover_open_vault"] {
use waybetter_host::testkit::assert_guarded; assert_guarded(source, command, "host::current(&webview,");
let source = include_str!("../src/desktop_popover.rs"); }
assert_guarded(source, "popover_state", "host::session_of(&webview)"); // popover_close only acts for the current popover, and does nothing otherwise.
for command in ["popover_drafts", "popover_insert", "popover_open_vault"] { let close = &source[source.find("fn popover_close(").unwrap()..];
assert_guarded(source, command, "host::current(&webview,"); let close = &close[..close.find("
} }").unwrap()];
// popover_close only acts for the current popover, and does nothing otherwise. assert!(close.contains("host::current(&webview, seq).is_ok()"));
let close = &source[source.find("fn popover_close(").unwrap()..]; let insert = &source[source.find("fn popover_insert(").unwrap()..];
let close = &close[..close.find(" let insert = &insert[..insert.find("
}").unwrap()]; }").unwrap()];
assert!(close.contains("host::current(&webview, seq).is_ok()")); assert!(insert.contains("compose::insert_script") && insert.contains("compose::append_script"));
let insert = &source[source.find("fn popover_insert(").unwrap()..]; assert!(!insert.contains("click") && !insert.contains("submit") && !insert.contains("Post"), "popover_insert never posts");
let insert = &insert[..insert.find(" assert!(insert.contains("policy::x_origin(&url)"), "only into X tabs");
}").unwrap()]; // The host's popover check: only a `popover-<n>` webview on the app's own local origin.
assert!(insert.contains("compose::insert_script") && insert.contains("compose::append_script")); let host = include_str!("../../../../waybetter/crates/waybetter-host/src/popover_host.rs");
assert!(!insert.contains("click") && !insert.contains("submit") && !insert.contains("Post"), "popover_insert never posts"); let only = &host[host.find("pub fn popover_only(").unwrap()..];
assert!(insert.contains("policy::x_origin(&url)"), "only into X tabs"); let only = &only[..only.find("
// The host's popover check: only a `popover-<n>` webview on the app's own local origin. }").unwrap()];
let host = include_str!("../../../../waybetter/crates/waybetter-host/src/popover_host.rs"); assert!(only.contains("popover::valid_label(webview.label())") && only.contains("local_navigation_allowed"));
let only = &host[host.find("pub fn popover_only(").unwrap()..]; }
let only = &only[..only.find("
}").unwrap()];
assert!(only.contains("popover::valid_label(webview.label())") && only.contains("local_navigation_allowed"));
}

View file

@ -18,8 +18,6 @@ export const FEATURES: readonly FeatureSpec[] = [
{ id: 'chat.searchLoaded', surfaces: CHAT, heavy: true, ...words('searchLoaded'), keywords: 'find search in conversation ctrl shift f messages', permissions: ['ui', 'commands'] }, { id: 'chat.searchLoaded', surfaces: CHAT, heavy: true, ...words('searchLoaded'), keywords: 'find search in conversation ctrl shift f messages', permissions: ['ui', 'commands'] },
{ id: 'chat.pins', surfaces: CHAT, heavy: true, ...words('pins'), keywords: 'pin pinned label color chats conversations strip', permissions: ['storage', 'ui', 'commands'] }, { id: 'chat.pins', surfaces: CHAT, heavy: true, ...words('pins'), keywords: 'pin pinned label color chats conversations strip', permissions: ['storage', 'ui', 'commands'] },
{ id: 'chat.personFilter', surfaces: CHAT, heavy: true, ...words('personFilter'), keywords: 'group chat person participant filter only from', permissions: ['storage', 'ui', 'commands'] }, { id: 'chat.personFilter', surfaces: CHAT, heavy: true, ...words('personFilter'), keywords: 'group chat person participant filter only from', permissions: ['storage', 'ui', 'commands'] },
// On by default (owner, 2026-10-10): asks native code for the preview of a link on screen (link_preview.rs).
{ id: 'chat.linkPreviews', surfaces: CHAT, heavy: true, default: true, ...words('linkPreviews'), keywords: 'link preview embed youtube card unfurl', permissions: ['ui'] },
{ id: 'chat.keywords', surfaces: CHAT, heavy: true, settings: true, ...words('keywords'), keywords: 'highlight mute words keywords hide messages', permissions: ['storage', 'ui'] }, { id: 'chat.keywords', surfaces: CHAT, heavy: true, settings: true, ...words('keywords'), keywords: 'highlight mute words keywords hide messages', permissions: ['storage', 'ui'] },
]), ]),
]; ];

View file

@ -5,14 +5,12 @@
// X's chat is the one place the rest of the app stays out of (a heavy page). These modules run // X's chat is the one place the rest of the app stays out of (a heavy page). These modules run
// there on purpose and keep it cheap: one shared watch each (child list only, one frame), looking // there on purpose and keep it cheap: one shared watch each (child list only, one frame), looking
// only at X's message list or its conversation list. ./x.ts is what they know about X's chat. // only at X's message list or its conversation list. ./x.ts is what they know about X's chat.
// None of them writes or sends a message, reacts, deletes or marks anything read. The one request is // None of them makes a request, writes or sends a message, reacts, deletes or marks anything read.
// Link previews' (owner-approved, 2026-10-10): the link alone, to native code, which fetches its preview.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts'; import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts'; import type { PluginApi } from '../../inject/pluginApi.ts';
import { bookmarks } from './bookmarks.ts'; import { bookmarks } from './bookmarks.ts';
import { keywords } from './keywords.ts'; import { keywords } from './keywords.ts';
import { linkPreviews } from './linkPreviews.ts';
import { personFilter } from './personFilter.ts'; import { personFilter } from './personFilter.ts';
import { pins } from './pins.ts'; import { pins } from './pins.ts';
import { searchLoaded } from './searchLoaded.ts'; import { searchLoaded } from './searchLoaded.ts';
@ -23,5 +21,4 @@ export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
pins, pins,
personFilter, personFilter,
keywords, keywords,
linkPreviews,
]; ];

View file

@ -1,239 +0,0 @@
// Chat+ · Link previews. X's web chat shows a link as a bare card (an icon and the domain). For a
// link in a message that is on screen, this asks native code (`link_preview`, one link at a time;
// src-tauri/src/link_preview.rs) for its preview and shows it under the message: any page's title,
// description and picture, an image link's image, and for YouTube, Vimeo and SoundCloud a play
// button that opens the site's own player in place (hosts X's own CSP allows as frames).
//
// Owner-approved network use (2026-10-10). Only the link leaves the page: never the message text,
// the sender or the conversation. Nothing is stored: answers are kept in memory for this page only.
// X's card is hidden while a preview stands in for it and comes back when the feature stops.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { clearAttribute } from './ui.ts';
import { CONVERSATION_PROBES, CHAT_PAGE_PROBE, chatRoot, chatSelectors, renderedRows } from './x.ts';
export type LinkPreview = { url: string; site: string; title: string; description: string; image?: string; embed?: string };
type Invoke = (command: 'link_preview', args: { url: string }) => Promise<unknown>;
let bridge: Invoke | null = null;
/** The runtime hands over its native bridge (src/inject/entry.tsx); without one the feature shows nothing. */
export function setLinkPreviewBridge(invoke: Invoke | null | undefined): void { bridge = invoke ?? null; }
/** The players a preview may open: the sites' own, on hosts X's chat page allows as frames. */
const PLAYERS = [
/^https:\/\/www\.youtube\.com\/embed\/[A-Za-z0-9_-]{11}\?autoplay=1&rel=0$/,
/^https:\/\/player\.vimeo\.com\/video\/\d{6,12}\?autoplay=1$/,
/^https:\/\/w\.soundcloud\.com\/player\/\?url=https%3A%2F%2Fsoundcloud\.com(?:%2F[A-Za-z0-9_-]+){1,3}&auto_play=true&visual=true$/,
];
const X_HOSTS = /(^|\.)(x\.com|twitter\.com|t\.co|twimg\.com|x\.co)$/i;
/** A link worth a preview: plain https, a public-looking host name, not X's own. */
export function previewable(href: string | null | undefined): string | null {
if (!href) return null;
let url: URL;
try { url = new URL(href); } catch { return null; }
if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')) return null;
const host = url.hostname.toLowerCase();
if (!host.includes('.') || /^[\d.]+$/.test(host) || host.startsWith('[') || X_HOSTS.test(host)) return null;
return url.href;
}
/** A native answer as a preview, or null: every field is checked again (it becomes page text). */
export function asPreview(value: unknown): LinkPreview | null {
if (!value || typeof value !== 'object') return null;
const v = value as Record<string, unknown>;
const str = (key: string, max: number) => (typeof v[key] === 'string' ? (v[key] as string).slice(0, max) : '');
const url = previewable(str('url', 2048));
if (!url) return null;
const image = str('image', 3_000_000);
const embed = str('embed', 400);
const preview: LinkPreview = { url, site: str('site', 80), title: str('title', 200), description: str('description', 300) };
if (/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(image)) preview.image = image;
if (PLAYERS.some(player => player.test(embed))) preview.embed = embed;
return preview.title || preview.image || preview.embed ? preview : null;
}
const CARD = 'bt-chat-lp';
const HIDE = 'data-bt-chat-lp-hidden';
const FOR = 'data-bt-chat-lp-for';
const ACCENT = 'var(--wb-accent, rgb(29, 155, 240))';
const CSS = `
[${HIDE}] { display: none !important; }
.${CARD} { display: block; box-sizing: border-box; width: 340px; max-width: 100%; margin: 6px 0 2px; overflow: hidden; border-radius: 16px; border: 1px solid rgba(127,127,127,.28); background: rgba(127,127,127,.10); color: inherit; text-decoration: none; font: 400 14px/1.35 var(--wb-font, system-ui, sans-serif); cursor: pointer; }
.${CARD}:hover { background: rgba(127,127,127,.16); }
.${CARD}:focus-visible { outline: 2px solid ${ACCENT}; outline-offset: 2px; }
.${CARD}-media { position: relative; display: block; width: 100%; aspect-ratio: 1.91 / 1; background: rgba(0,0,0,.35); }
.${CARD}-media.is-video { aspect-ratio: 16 / 9; }
.${CARD}-media img, .${CARD}-media iframe { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; border: 0; display: block; }
.${CARD}-play { position: absolute; left: 50%; top: 50%; width: 68px; height: 48px; transform: translate(-50%, -50%); border: 0; border-radius: 14px; background: rgba(0,0,0,.72); color: #fff; display: flex; align-items: center; justify-content: center; cursor: pointer; }
.${CARD}-play:hover { background: #f00; }
.${CARD}-play svg { width: 26px; height: 26px; fill: currentColor; }
.${CARD}-body { display: block; padding: 10px 14px 12px; }
.${CARD}-site { display: block; font-size: 12.5px; opacity: .65; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.${CARD}-title { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 2px; font-weight: 700; }
.${CARD}-desc { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 2px; font-size: 13.5px; opacity: .78; }
`;
/** The links of one message: its own anchors to the outside, first one only per address. */
export function rowLinks(row: Element): HTMLAnchorElement[] {
const seen = new Set<string>();
const out: HTMLAnchorElement[] = [];
for (const anchor of Array.from(row.querySelectorAll<HTMLAnchorElement>('a[href]'))) {
if (anchor.closest(`.${CARD}`)) continue;
const url = previewable(anchor.href || anchor.getAttribute('href'));
if (!url || seen.has(url)) continue;
seen.add(url);
out.push(anchor);
}
return out.slice(0, 2);
}
/**
* X's bare link card (a message that is only a link: an icon and the host name, no picture). A link
* inside a message's text shows its path too and is never hidden.
*/
export function isBareCard(anchor: Element): boolean {
if (anchor.querySelector('img, video')) return false;
const text = (anchor.textContent ?? '').trim().replace(/^www\./i, '');
return /^[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i.test(text);
}
/**
* Where a link's preview goes: after the message's bubble (X's `[role="article"]`), or after X's own
* link card when the link is one; null when the anchor is in neither (nothing is placed).
*/
export function cardPlace(anchor: Element): Element | null {
const bubble = anchor.closest('[role="article"]') ?? anchor.closest('[data-testid^="message-text-"]');
return bubble?.parentElement ? bubble : null;
}
const PLAY = 'M8 5.5v13l11-6.5z';
const SVG = 'http://www.w3.org/2000/svg';
function el<K extends keyof HTMLElementTagNameMap>(doc: Document, tag: K, className: string, text?: string): HTMLElementTagNameMap[K] {
const node = doc.createElement(tag);
node.className = className;
if (text) node.textContent = text;
return node;
}
/** The preview card for `preview` (text only through textContent; URLs re-checked). */
export function renderCard(doc: Document, preview: LinkPreview, words: { play: string; open: string }): HTMLAnchorElement {
const card = el(doc, 'a', CARD);
card.href = preview.url;
card.target = '_blank';
card.rel = 'noopener noreferrer';
card.setAttribute(FOR, preview.url);
card.title = words.open;
if (preview.embed) {
const embed = preview.embed;
const media = el(doc, 'span', `${CARD}-media is-video`);
if (preview.image) {
const thumb = el(doc, 'img', '');
thumb.src = preview.image;
thumb.alt = '';
media.append(thumb);
}
const play = el(doc, 'button', `${CARD}-play`);
play.type = 'button';
play.setAttribute('aria-label', words.play);
const svg = doc.createElementNS(SVG, 'svg');
svg.setAttribute('viewBox', '0 0 24 24');
const path = doc.createElementNS(SVG, 'path');
path.setAttribute('d', PLAY);
svg.append(path);
play.append(svg);
play.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
const frame = el(doc, 'iframe', '');
frame.src = embed;
frame.allow = 'autoplay; encrypted-media; picture-in-picture; fullscreen';
frame.allowFullscreen = true;
frame.referrerPolicy = 'strict-origin-when-cross-origin';
frame.title = preview.title || preview.site;
media.replaceChildren(frame);
card.removeAttribute('href');
card.style.cursor = 'default';
});
media.append(play);
card.append(media);
} else if (preview.image) {
const media = el(doc, 'span', `${CARD}-media`);
const image = el(doc, 'img', '');
image.src = preview.image;
image.alt = '';
image.decoding = 'async';
media.append(image);
card.append(media);
}
const body = el(doc, 'span', `${CARD}-body`);
body.append(el(doc, 'span', `${CARD}-site`, preview.site));
if (preview.title) body.append(el(doc, 'span', `${CARD}-title`, preview.title));
if (preview.description) body.append(el(doc, 'span', `${CARD}-desc`, preview.description));
card.append(body);
return card;
}
type Ctx = FeatureContext<PluginApi>;
export const linkPreviews: FeatureModule<PluginApi> = {
id: 'chat.linkPreviews',
probes: { ...CONVERSATION_PROBES, ...CHAT_PAGE_PROBE },
start(ctx: Ctx) {
const { win } = ctx;
const doc = win.document;
const sel = chatSelectors(ctx, CONVERSATION_PROBES);
/** Answers for this page only (null: no preview for that link). */
const answers = new Map<string, LinkPreview | null>();
const pending = new Set<string>();
let stopped = false;
const words = () => ({ play: ctx.text('play'), open: ctx.text('open') });
const ask = (url: string) => {
if (!bridge || pending.has(url) || answers.has(url)) return;
pending.add(url);
bridge('link_preview', { url })
.then(value => answers.set(url, asPreview(value)), () => answers.set(url, null))
.finally(() => { pending.delete(url); if (!stopped) watch.schedule(); });
};
const scan = () => {
for (const row of renderedRows(chatRoot(doc), sel)) {
let after: Element | null = null;
for (const anchor of rowLinks(row)) {
const url = previewable(anchor.href || anchor.getAttribute('href'))!;
const answer = answers.get(url);
if (answer === undefined) { ask(url); continue; }
if (!answer) { if (anchor.hasAttribute(HIDE)) anchor.removeAttribute(HIDE); continue; }
// Under the message's bubble (live 2026-10-10: X keeps a link in the text as a plain anchor),
// in the bubble's own column, so it lines up with the message on either side.
const bubble = cardPlace(anchor);
if (!bubble) continue;
const column = bubble.parentElement!;
const existing = Array.from(column.children).find(node => node.getAttribute(FOR) === url);
const card = existing ?? renderCard(doc, answer, words());
const anchorAfter: Element = after ?? bubble;
if (anchorAfter.nextElementSibling !== card) anchorAfter.after(card);
after = card;
if (isBareCard(anchor) && !anchor.hasAttribute(HIDE)) anchor.setAttribute(HIDE, '');
}
}
};
ctx.css(CSS);
const watch = ctx.watch(scan);
ctx.onRouteChange(() => watch.schedule());
ctx.defer(() => {
stopped = true;
for (const place of new Set<ParentNode>([doc, chatRoot(doc)])) {
for (const card of Array.from(place.querySelectorAll(`.${CARD}`))) card.remove();
clearAttribute(place, HIDE);
}
});
watch.schedule();
},
};

View file

@ -7,7 +7,6 @@
// flag-controlled parts and the palette command report; panelButton.ts keeps the way into the // flag-controlled parts and the palette command report; panelButton.ts keeps the way into the
// panel on the page). This file is X's: which parts exist, X's own members (alerts, fixes) // panel on the page). This file is X's: which parts exist, X's own members (alerts, fixes)
// and how the "wayBetter" item joins X's navigation. // and how the "wayBetter" item joins X's navigation.
import { setLinkPreviewBridge } from '../areas/chat/linkPreviews.ts';
import { installFeatures, type FeatureConfig } from './features'; import { installFeatures, type FeatureConfig } from './features';
import { ALL_MODULES } from '../areas/modules'; import { ALL_MODULES } from '../areas/modules';
import { surfacesOf } from '../areas/surfaces'; import { surfacesOf } from '../areas/surfaces';
@ -89,8 +88,6 @@ function install() {
// This runtime only ships inside the app's X tabs; automated test browsers have no bridge, and // This runtime only ships inside the app's X tabs; automated test browsers have no bridge, and
// the features that need it stay off there. // the features that need it stay off there.
const invoke = pageInvoke(window, LABEL); const invoke = pageInvoke(window, LABEL);
// Chat+ link previews ask native code for one link's preview (the only feature module with a bridge).
setLinkPreviewBridge(invoke as Parameters<typeof setLinkPreviewBridge>[0]);
// Flag-controlled fixes and tweaks: installed on enable, disposed on disable. The first ones wrap // Flag-controlled fixes and tweaks: installed on enable, disposed on disable. The first ones wrap
// fetch like the mutation gate: installed at document start, before X's bundle runs. // fetch like the mutation gate: installed at document start, before X's bundle runs.

View file

@ -61,11 +61,11 @@ const pace = (chat: FakeChat) => ({ sleep: (ms: number) => new Promise<void>(res
const star = (row: El) => row.querySelector('.bt-chat-star')!; const star = (row: El) => row.querySelector('.bt-chat-star')!;
const group = (chat: FakeChat) => chat.conversations.get(GROUP)!.history; const group = (chat: FakeChat) => chat.conversations.get(GROUP)!.history;
test('Chat+: six features, each its own flag, off by default but link previews (owner, 2026-10-10), all allowed on X\'s chat pages', () => { test('Chat+: five features, each its own flag, all off by default, all allowed on X\'s chat pages', () => {
assert.deepEqual(FEATURES.map(feature => feature.id), ['chat.bookmarks', 'chat.searchLoaded', 'chat.pins', 'chat.personFilter', 'chat.linkPreviews', 'chat.keywords']); assert.deepEqual(FEATURES.map(feature => feature.id), ['chat.bookmarks', 'chat.searchLoaded', 'chat.pins', 'chat.personFilter', 'chat.keywords']);
assert.deepEqual(MODULES.map(module => module.id).sort(), FEATURES.map(feature => feature.id).sort()); assert.deepEqual(MODULES.map(module => module.id).sort(), FEATURES.map(feature => feature.id).sort());
for (const feature of FEATURES) { for (const feature of FEATURES) {
assert.equal(feature.default, feature.id === 'chat.linkPreviews', feature.id); assert.equal(feature.default, false, feature.id);
assert.equal(feature.heavy, true, `${feature.id} runs on the heavy chat pages`); assert.equal(feature.heavy, true, `${feature.id} runs on the heavy chat pages`);
assert.ok(feature.permissions && !feature.permissions.includes('network'), `${feature.id}: no network`); assert.ok(feature.permissions && !feature.permissions.includes('network'), `${feature.id}: no network`);
} }
@ -175,7 +175,7 @@ test('starred messages: stored in full, valid ones only, each once; the list fil
}); });
test('Starred messages: a star on every rendered row; a click stores exactly that message, in full; off leaves nothing', () => { test('Starred messages: a star on every rendered row; a click stores exactly that message, in full; off leaves nothing', () => {
const { env, chat, stored } = page(`/i/chat/${GROUP}`, { 'chat.bookmarks': true, 'chat.linkPreviews': false }); const { env, chat, stored } = page(`/i/chat/${GROUP}`, { 'chat.bookmarks': true });
assert.deepEqual(env.registry.active(), ['chat.bookmarks']); assert.deepEqual(env.registry.active(), ['chat.bookmarks']);
const all = group(chat); const all = group(chat);
const rows = chat.rendered(); const rows = chat.rendered();

View file

@ -133,8 +133,6 @@ const DEFAULT_ON = [
'logoBrush', 'twitterWording', 'singleSplitNav', 'logoBrush', 'twitterWording', 'singleSplitNav',
'fixLikeFollow', 'fixScrollRestore', 'fixTimelineJump', 'fixHomeTab', 'fixNotificationBadge', 'fixNewPostsPill', 'fixMediaUpload', 'followingChronological', 'fixChatButton', 'composerRestorePrompt', 'fixLikeFollow', 'fixScrollRestore', 'fixTimelineJump', 'fixHomeTab', 'fixNotificationBadge', 'fixNewPostsPill', 'fixMediaUpload', 'followingChronological', 'fixChatButton', 'composerRestorePrompt',
'composerDrafts', 'hidePromotedPosts', 'mediaDownload', 'rememberVideoVolume', 'searchOperators', 'notifications.keywordAlerts', 'composerDrafts', 'hidePromotedPosts', 'mediaDownload', 'rememberVideoVolume', 'searchOperators', 'notifications.keywordAlerts',
// On by default by the owner's choice (2026-10-10): Chat+ link previews.
'chat.linkPreviews',
]; ];
/** What Advanced adds: the calm features that came with the area plugins (they add something; none hides or changes X). */ /** What Advanced adds: the calm features that came with the area plugins (they add something; none hides or changes X). */
const ADVANCED_ADDS = [ const ADVANCED_ADDS = [
@ -168,7 +166,7 @@ test('modes: the exact flags of Basic, Advanced and Power User; an existing setu
assert.deepEqual(on(defaults), [...DEFAULT_ON].sort()); assert.deepEqual(on(defaults), [...DEFAULT_ON].sort());
assert.deepEqual(running(null), [...DEFAULT_ON].sort()); assert.deepEqual(running(null), [...DEFAULT_ON].sort());
for (const [flag, value] of Object.entries(FEATURE_DEFAULTS)) assert.equal(defaults[flag], value, flag); for (const [flag, value] of Object.entries(FEATURE_DEFAULTS)) assert.equal(defaults[flag], value, flag);
for (const feature of X_FEATURES) if (!(feature.id in FEATURE_DEFAULTS) && feature.id !== 'notifications.keywordAlerts' && feature.id !== 'chat.linkPreviews' && feature.backing !== 'plugin') assert.equal(defaults[feature.id], false, `${feature.id} is new: off by default`); for (const feature of X_FEATURES) if (!(feature.id in FEATURE_DEFAULTS) && feature.id !== 'notifications.keywordAlerts' && feature.backing !== 'plugin') assert.equal(defaults[feature.id], false, `${feature.id} is new: off by default`);
for (const row of supersededFiles(X_TABLE)) assert.equal(defaults[row.flag], false, `${row.flag}: what came from an opt-in plugin stays off`); for (const row of supersededFiles(X_TABLE)) assert.equal(defaults[row.flag], false, `${row.flag}: what came from an opt-in plugin stays off`);
// Basic: every area off (so everything an area owns is off), no logo or wording; the fixes and split-view navigation stay. // Basic: every area off (so everything an area owns is off), no logo or wording; the fixes and split-view navigation stay.

View file

@ -1,53 +0,0 @@
// Chat+ link previews (src/areas/chat/linkPreviews.ts; native side src-tauri/src/link_preview.rs):
// which links are asked about, how a native answer is checked again before it becomes page text,
// and which of X's cards a preview stands in for. Nothing here touches the network or x.com.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { asPreview, isBareCard, previewable } from '../src/areas/chat/linkPreviews.ts';
test('link previews: only plain https links to hosts that are not X\'s own', () => {
assert.equal(previewable('https://www.youtube.com/watch?v=dQw4w9WgXcQ'), 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
assert.equal(previewable('https://fishies.lol/'), 'https://fishies.lol/');
for (const bad of [
'http://example.com/', 'https://user:pw@example.com/', 'https://example.com:8443/', 'https://192.168.0.1/', 'https://[::1]/',
'https://intranet/', 'https://x.com/a/status/1', 'https://t.co/abc', 'https://pbs.twimg.com/media/a.jpg', 'javascript:alert(1)', '/i/chat/1-2', '', null,
]) assert.equal(previewable(bad), null, String(bad));
});
test('link previews: a native answer is checked again: plain fields, capped, data: images of four types, an 11-character video id', () => {
const good = asPreview({ url: 'https://fishies.lol/', site: 'Fishies', title: 'The social aquarium', description: 'x'.repeat(400), image: 'data:image/png;base64,iVBORw0KGgo=' });
assert.ok(good);
assert.equal(good.description.length, 300);
assert.equal(good.image, 'data:image/png;base64,iVBORw0KGgo=');
assert.equal(asPreview({ url: 'https://a.example/', title: 't', image: 'data:image/svg+xml;base64,PHN2Zz4=' })?.image, undefined, 'no SVG');
assert.equal(asPreview({ url: 'https://a.example/', title: 't', image: 'https://tracker.example/p.gif' })?.image, undefined, 'no remote image');
for (const embed of [
'https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&rel=0',
'https://player.vimeo.com/video/76979871?autoplay=1',
'https://w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2Fcrtkafa%2Fsets%2Falbums&auto_play=true&visual=true',
]) assert.equal(asPreview({ url: 'https://a.example/', title: 't', embed })?.embed, embed, embed);
for (const embed of ['https://evil.example/embed', 'https://www.youtube.com/embed/a"onload="x', 'javascript:alert(1)', 'https://open.spotify.com/embed/track/1'])
assert.equal(asPreview({ url: 'https://a.example/', title: 't', embed })?.embed, undefined, embed);
assert.equal(asPreview({ url: 'javascript:alert(1)', title: 't' }), null, 'the link itself is re-checked');
assert.equal(asPreview({ url: 'https://a.example/', title: '' }), null, 'nothing to show, no card');
assert.equal(asPreview('nope'), null);
});
test('link previews: X\'s bare card (a host name and an icon) is replaced; a card with its own picture or a sentence is not', () => {
const anchor = (text: string, media = false) => ({ textContent: text, querySelector: () => (media ? {} : null) }) as unknown as Element;
assert.equal(isBareCard(anchor('www.youtube.com')), true);
assert.equal(isBareCard(anchor('fishies.lol')), true);
assert.equal(isBareCard(anchor('www.youtube.com', true)), false);
assert.equal(isBareCard(anchor('watch this video')), false);
assert.equal(isBareCard(anchor('www.youtube.com/watch?v=jNQXAC9IVRw')), false, 'a link in the text (live 2026-10-10) stays');
assert.equal(isBareCard(anchor('')), false);
});
test('link previews: page text only through textContent, players only on the hosts X allows as frames, no request from the page', () => {
const source = readFileSync(new URL('../src/areas/chat/linkPreviews.ts', import.meta.url), 'utf8');
assert.doesNotMatch(source, /innerHTML|insertAdjacentHTML|outerHTML|document\.write/);
assert.doesNotMatch(source, /\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon/);
assert.doesNotMatch(source, /i\.ytimg\.com/, 'thumbnails come as data from native code');
assert.match(source, /rel = 'noopener noreferrer'/);
});

View file

@ -153,7 +153,7 @@ Commit path-limited to your own files. `src-tauri/src/areas.rs` is committed tog
- `areaPage(path)` (`tests/helpers/areaPage.ts`) gives the registry with every module defined, the X plugin API, recorded styles/listeners/storage/observers, `go(path)`, `mutate()`, `matches` (elements per selector). `flagsWith({ flag: true })` builds the flags as the runtime applies them; `flagsOnly({ … })` forces every other module off first. Some modules are on by default (`hidePromotedPosts`, `rememberVideoVolume`, `searchOperators`): an area's test turns the other areas off (`area.<other>: false`) so only its own modules run. - `areaPage(path)` (`tests/helpers/areaPage.ts`) gives the registry with every module defined, the X plugin API, recorded styles/listeners/storage/observers, `go(path)`, `mutate()`, `matches` (elements per selector). `flagsWith({ flag: true })` builds the flags as the runtime applies them; `flagsOnly({ … })` forces every other module off first. Some modules are on by default (`hidePromotedPosts`, `rememberVideoVolume`, `searchOperators`): an area's test turns the other areas off (`area.<other>: false`) so only its own modules run.
- Per feature: its pure decision functions (as the old plugin tests did); on -> the expected effect; off -> nothing left (`tests/areas.test.ts` already checks styles, commands, listeners and observers for every module); a port -> compared with the old plugin file loaded from `src-tauri/bundled-plugins/` (Focus Mode compares all 64 setting combinations byte for byte). - Per feature: its pure decision functions (as the old plugin tests did); on -> the expected effect; off -> nothing left (`tests/areas.test.ts` already checks styles, commands, listeners and observers for every module); a port -> compared with the old plugin file loaded from `src-tauri/bundled-plugins/` (Focus Mode compares all 64 setting combinations byte for byte).
- Always `registry.dispose()` at the end of a test that made a page. (A test that fails before it no longer hangs the run: the route poll does not keep the process alive.) - Always `registry.dispose()` at the end of a test that made a page. (A test that fails before it no longer hangs the run: the route poll does not keep the process alive.)
- Fixtures: `tests/fixtures/x/<area>/*.html` when a feature needs real markup. Sanitized: neutral names, invented text, no real DM content. - Fixtures: `tests/fixtures/x/<area>/*.html` when a feature needs real markup. Sanitized: neutral names, invented text, no real DM content; `node scripts/privacy-scan.mjs --fast` must stay green.
- In-page screenshots: `node scripts/area-plugins-shots.mjs <outDir> 'name|path|flags|command'` (built runtime in a static x.com fixture). Panel screenshots: `node scripts/panel-screenshots.mjs` with `?section=plugins&flags=…&off=…&onboarding=fresh|existing&lang=…` (dev harness on port 1433). - In-page screenshots: `node scripts/area-plugins-shots.mjs <outDir> 'name|path|flags|command'` (built runtime in a static x.com fixture). Panel screenshots: `node scripts/panel-screenshots.mjs` with `?section=plugins&flags=…&off=…&onboarding=fresh|existing&lang=…` (dev harness on port 1433).
- Live checks on x.com are a separate step with the two test accounts only. Nothing is "verified live" from fixtures. - Live checks on x.com are a separate step with the two test accounts only. Nothing is "verified live" from fixtures.
@ -175,12 +175,11 @@ Commit path-limited to your own files. `src-tauri/src/areas.rs` is committed tog
- [ ] Selector health as in section 8. - [ ] Selector health as in section 8.
- [ ] At most 5 palette commands for the area; every command in the table of `tests/areaCommands.test.ts`; no shortcut the app takes. - [ ] At most 5 palette commands for the area; every command in the table of `tests/areaCommands.test.ts`; no shortcut the app takes.
- [ ] Words: English complete in `messages.en.json`; nothing hard-coded. - [ ] Words: English complete in `messages.en.json`; nothing hard-coded.
- [ ] Gates green: `bun run build`, `bun run test`, `bun run test:rust`, and in `waybetter/`: `bun run check` when the framework changed (integrator). - [ ] Gates green: `bun run build`, `bun run test`, `bun run test:rust`, `node scripts/privacy-scan.mjs --fast`, and in `waybetter/`: `bun run check` when the framework changed (integrator).
Owner decisions that bind the areas: Owner decisions that bind the areas:
- **Hide Blue Checks (Reader+ `reader.collapseVerified`, Profile+)**: never collapse a post by the owner of the profile page being visited (every profile sub-route, handle compared case-insensitively), nor the focal post of an opened post page. A post they reposted from someone else follows the normal rule. An author X has not described yet is never collapsed. Leaving the profile re-checks the posts on screen. The `hideVerifiedBadges` tweak keeps the badge in the visited profile's header. - **Hide Blue Checks (Reader+ `reader.collapseVerified`, Profile+)**: never collapse a post by the owner of the profile page being visited (every profile sub-route, handle compared case-insensitively), nor the focal post of an opened post page. A post they reposted from someone else follows the normal rule. An author X has not described yet is never collapsed. Leaving the profile re-checks the posts on screen. The `hideVerifiedBadges` tweak keeps the badge in the visited profile's header.
- **Link previews (Chat+, owner-approved 2026-10-10, on by default)**: for a link in a chat message on screen, the page asks native code (`link_preview`, X tabs on X's chat pages only) for that one link's preview. Native code fetches it itself (`src-tauri/src/link_preview.rs`): https only, a public host name (every resolved address public, the connection pinned to them), never X's own hosts, no cookies or referrer, redirects re-checked (at most 4), a page head of at most 512 KB, an image of at most 1.5 MB by its magic bytes (PNG/JPEG/GIF/WebP) returned as a `data:` URL, at most 30 fresh fetches a minute, a memory-only cache. Only the link leaves the page, never the message, its sender or the conversation. A YouTube, Vimeo or SoundCloud link also gets its site's own player (www.youtube.com, player.vimeo.com, w.soundcloud.com: frames X's CSP allows; the page re-checks the address against that list), loaded only when the user presses play. An image link previews the image itself.
- **Starred DMs (Chat+)**: a message the user explicitly stars may be stored locally in full (message id, conversation id, sender, text, time, media references). Never in sync. In a backup only when the owner ticks it (not built yet: Export/Import as JSON stands in). No passive collection of any kind. - **Starred DMs (Chat+)**: a message the user explicitly stars may be stored locally in full (message id, conversation id, sender, text, time, media references). Never in sync. In a backup only when the owner ticks it (not built yet: Export/Import as JSON stands in). No passive collection of any kind.
- **Launch scope**: the ports of what exists and the 29 "must" items of the plan. The 35 "nice" and 7 "later" items come after launch. - **Launch scope**: the ports of what exists and the 29 "must" items of the plan. The 35 "nice" and 7 "later" items come after launch.
- **Modes** (first run; an existing setup keeps what it has): - **Modes** (first run; an existing setup keeps what it has):

View file

@ -16,7 +16,7 @@
"dev:api": "bun run --cwd apps/api dev", "dev:api": "bun run --cwd apps/api dev",
"build": "bun run --cwd packages/contracts build && bun run --cwd apps/api build && bun run --cwd apps/desktop build", "build": "bun run --cwd packages/contracts build && bun run --cwd apps/api build && bun run --cwd apps/desktop build",
"typecheck": "bun run --cwd packages/contracts typecheck && bun run --cwd apps/api typecheck && bun run --cwd apps/desktop typecheck", "typecheck": "bun run --cwd packages/contracts typecheck && bun run --cwd apps/api typecheck && bun run --cwd apps/desktop typecheck",
"test": "bun run --cwd packages/contracts test && bun run --cwd apps/api test && bun run --cwd apps/web test && bun run --cwd apps/desktop test", "test": "bun run --cwd packages/contracts test && bun run --cwd apps/api test && bun run --cwd apps/web test && bun run --cwd apps/desktop test && node scripts/privacy-scan.mjs --fast",
"test:e2e": "bun run --cwd apps/desktop test:e2e", "test:e2e": "bun run --cwd apps/desktop test:e2e",
"test:rust": "cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --no-default-features --locked", "test:rust": "cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --no-default-features --locked",
"desktop:build": "bun run --cwd apps/desktop desktop:build", "desktop:build": "bun run --cwd apps/desktop desktop:build",
@ -26,6 +26,7 @@
"i18n:site": "node scripts/i18n-site.mjs", "i18n:site": "node scripts/i18n-site.mjs",
"check:store": "node scripts/check-store.mjs", "check:store": "node scripts/check-store.mjs",
"i18n:extract": "node scripts/i18n-extract.mjs", "i18n:extract": "node scripts/i18n-extract.mjs",
"privacy:scan": "node scripts/privacy-scan.mjs",
"check": "bun run typecheck && bun run test && bun run test:rust", "check": "bun run typecheck && bun run test && bun run test:rust",
"build:server": "git submodule update --init waybetter && bun run --cwd packages/contracts build && bun run --cwd apps/api build && bun run --cwd apps/web build" "build:server": "git submodule update --init waybetter && bun run --cwd packages/contracts build && bun run --cwd apps/api build && bun run --cwd apps/web build"
}, },

75
scripts/privacy-scan.mjs Normal file
View file

@ -0,0 +1,75 @@
#!/usr/bin/env node
// Checks that nothing this repository publishes names a person: `waybetter privacy-scan` (the
// framework's command, waybetter/packages/waybetter/cli/privacy.mjs) over
//
// 1. every file git tracks here and in the framework submodule (and their names),
// 2. the built site (apps/web/dist, when it exists),
// 3. the npm tarballs of `waybetter` and `create-waybetter`, packed into a temporary folder.
//
// The forbidden terms are a file outside every repository ("forbiddenTerms" in
// waybetter.release.json, or WAYBETTER_FORBIDDEN_TERMS); this machine's account name is always
// added. A term is never printed: hits show the file, the line or offset and `x***`. Reviewed
// false positives: privacy-allowlist.txt.
//
// node scripts/privacy-scan.mjs everything above (bun run privacy:scan)
// node scripts/privacy-scan.mjs --fast tracked files only, and nothing at all (quietly)
// when the terms file does not exist (bun run test)
// node scripts/privacy-scan.mjs --history every blob, path, commit message and identity of
// both repositories (before a history is published)
// --all list every hit, not the first five of each file
//
// Native artifacts are checked by the release itself (`waybetter release` refuses an installer, a
// binary, a dmg or an updater bundle with a hit); to check one by hand:
// node waybetter/packages/waybetter/bin/waybetter.mjs privacy-scan <file or folder>
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { TERMS_ENV, privacyCommand, privacyConfig } from '../waybetter/packages/waybetter/cli/privacy.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2);
const fast = args.includes('--fast');
const extra = args.includes('--all') ? ['--all'] : [];
const allow = ['--allow', join(root, 'privacy-allowlist.txt')];
// The same terms for every step, also the ones that run in a temporary folder.
const configured = process.env[TERMS_ENV] || privacyConfig(root).forbiddenTerms;
const terms = configured && existsSync(configured) ? ['--terms', configured] : [];
let worst = 0;
const run = (label, scanArgs, cwd = root) => {
if (!fast) console.log(`\n${label}`);
worst = Math.max(worst, privacyCommand([...scanArgs, ...terms, ...allow, ...extra, ...(fast ? ['--if-terms'] : [])], { cwd }));
};
try {
if (args.includes('--history')) {
run('history of this repository and of the framework', ['--history', '.', 'waybetter']);
} else {
run('tracked files (this repository, the framework)', ['--tracked', '.', 'waybetter']);
if (!fast) {
const site = join(root, 'apps/web/dist');
if (existsSync(site)) run('the built site (apps/web/dist)', ['apps/web/dist']);
else console.log('\nthe built site: apps/web/dist does not exist (bun run build:server), skipped');
const packed = mkdtempSync(join(tmpdir(), 'wb-pack-'));
try {
for (const name of ['waybetter', 'create-waybetter']) {
const cwd = join(root, 'waybetter/packages', name);
if (name === 'waybetter' && !existsSync(join(cwd, 'dist'))) console.log('\nnote: waybetter/packages/waybetter/dist is not built; the tarball is packed without it');
// A fixed command (no user input); the shell resolves npm's .cmd shim on Windows.
const pack = spawnSync(`npm pack --silent --pack-destination "${packed}"`, { cwd, shell: true, stdio: ['ignore', 'ignore', 'inherit'] });
if (pack.status !== 0) throw new Error(`npm pack failed in waybetter/packages/${name}`);
}
run(`npm tarballs (${readdirSync(packed).join(', ')})`, ['.'], packed);
} finally {
rmSync(packed, { recursive: true, force: true });
}
}
}
} catch (error) {
console.error(`privacy-scan: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
if (worst) console.error('\nprivacy-scan: FAILED. Fix the files above (or, for a reviewed false positive, add a line to privacy-allowlist.txt).');
process.exit(worst);

311
scripts/public-tree.mjs Normal file
View file

@ -0,0 +1,311 @@
#!/usr/bin/env node
// Builds the exact tree that becomes the single initial commit of the public repository, in a
// scratch directory OUTSIDE the working tree, and checks it. Re-runnable: it always starts from
// the committed HEAD (git archive), never from the working tree.
//
// node scripts/public-tree.mjs [--out <dir>] [--fw-commit <sha>] [--fw-url <url>] [--no-history-scan]
//
// Default --out is %USERPROFILE%/Desktop/twttr/public-dryrun. It writes
// <out>/tree/ the file set (no .git)
// <out>/repo/ the same set as one commit, authored as CRT (a throwaway repository)
// <out>/REPORT.md file count, size, exclusions and why, scan results, the commands to publish
//
// Nothing is pushed or uploaded. The privacy scan uses the framework's `waybetter privacy-scan`
// with the terms file named in waybetter.release.json; no term is ever printed (hits are masked)
// and the machine user's name is masked in every path this script prints.
import { execFileSync, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
process.on('uncaughtException', error => { console.error(`public-tree: ${String(error?.message ?? error).replace(process.env.USERNAME || 'no-user', '<user>')}`); process.exit(1); });
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2);
const opt = (name, fallback) => {
const at = args.indexOf(`--${name}`);
return at >= 0 && args[at + 1] ? args[at + 1] : fallback;
};
const out = path.resolve(opt('out', path.join(os.homedir(), 'Desktop', 'twttr', 'public-dryrun')));
const PUBLIC_REPO = 'https://git.crt.fyi/CRT/waybetter-for-x.git';
const FW_URL = opt('fw-url', 'https://git.crt.fyi/CRT/waybetter.git');
const UPDATE = args.includes('--update');
const MESSAGE = opt('message', '');
if (UPDATE && !MESSAGE) throw new Error('--update needs --message "<commit message>"');
const AUTHOR = { name: 'CRT', email: 'hi@crt.fyi' };
const MAX_FILE = 3_000_000; // bytes; larger files are listed for review
// Never print the machine user's name or the home folder.
const user = os.userInfo().username;
const mask = text =>
String(text)
.split(os.homedir()).join('%USERPROFILE%')
.split(os.homedir().replace(/\\/g, '/')).join('%USERPROFILE%')
.replace(new RegExp(user.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), '<user>');
const show = p => mask(p);
const git = (cwd, ...a) => execFileSync('git', a, { cwd, encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
const head = git(root, 'rev-parse', 'HEAD');
// ---------------------------------------------------------------------------------------------
// What is left out, and why. First match wins. Keep the reasons honest: they go in the report.
const EXCLUDE = [
[/^\.omc\//, 'agent plans, research and notes (local tool state)'],
[/^\.claude\//, 'agent worktrees and local settings'],
[/^(HANDOFF|CLAUDE)\.md$/, 'private working notes for the maintainer\'s tools'],
[/^verification\//, 'screenshots, recordings and QA reports from live sessions on real accounts (about 87 MB); they can show account content and are not part of the product'],
[/^releases\//, 'built installers and old private builds'],
[/^ecosystem\.config\.cjs$/, 'the maintainer\'s own server process configuration'],
[/^docs\/IMPLEMENTATION-CONTRACT\.md$/, 'the first private working contract (says "Private local working repository"); superseded by the code and the other docs'],
[/^apps\/desktop\/(tmp|test-results)\//, 'scratch output'],
[/^main\.bundle$/, 'a git bundle'],
[/\.(log|db|sqlite3?|pem|key|p12|pfx)$/i, 'logs, databases and key material'],
// The reviewed allowlist names the context around each hit, and a context can give the private
// word away (a well-known header name with the word cut out is the word): never public.
[/(^|\/)privacy-allowlist[^/]*\.txt$/, 'the privacy scan\'s reviewed contexts (a context can reveal the private term)'],
];
// Files that must exist in the tree because a public doc links to them (checked below).
const files = execFileSync('git', ['ls-tree', '-r', '-z', head], { cwd: root, encoding: 'utf8', maxBuffer: 1 << 28 })
.split('\0').filter(Boolean).map(line => {
const tab = line.indexOf('\t');
const [mode, type, sha] = line.slice(0, tab).split(' ');
return { mode, type, sha, path: line.slice(tab + 1) };
});
const gitlink = files.find(f => f.mode === '160000' && f.path === 'waybetter');
const fwCommit = opt('fw-commit', gitlink?.sha);
if (!fwCommit) throw new Error('no waybetter gitlink at HEAD');
const kept = [];
const excluded = new Map(); // reason -> { count, bytes, samples }
for (const file of files) {
if (file.type === 'commit') continue; // the submodule: re-added below as a gitlink
const rule = EXCLUDE.find(([re]) => re.test(file.path));
if (rule) {
const entry = excluded.get(rule[1]) ?? { count: 0, bytes: 0, samples: [] };
entry.count++;
if (entry.samples.length < 3) entry.samples.push(file.path);
excluded.set(rule[1], entry);
} else kept.push(file);
}
// ---------------------------------------------------------------------------------------------
// Extract HEAD into <out>/tree, then delete what is excluded.
fs.rmSync(out, { recursive: true, force: true });
fs.mkdirSync(path.join(out, 'tree'), { recursive: true });
const tree = path.join(out, 'tree');
{
const archive = spawnSync('git', ['archive', '--format=tar', head], { cwd: root, maxBuffer: 1 << 30 });
if (archive.status !== 0) throw new Error('git archive failed');
const untar = spawnSync('tar', ['-x'], { cwd: tree, input: archive.stdout, maxBuffer: 1 << 28 });
if (untar.status !== 0) throw new Error(`tar failed: ${mask(untar.stderr)}`);
}
const keepSet = new Set(kept.map(f => f.path));
let removed = 0;
const walk = dir => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
const rel = path.relative(tree, full).split(path.sep).join('/');
if (entry.isDirectory()) walk(full);
else if (!keepSet.has(rel)) { fs.rmSync(full); removed++; }
}
};
walk(tree);
// Empty directories left by the exclusions (and the empty submodule folder).
const prune = dir => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) prune(path.join(dir, entry.name));
if (dir !== tree && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
};
prune(tree);
// .gitmodules: the public framework URL, no comments about the maintainer's servers.
fs.writeFileSync(path.join(tree, '.gitmodules'),
`[submodule "waybetter"]\n\tpath = waybetter\n\turl = ${FW_URL}\n\tbranch = main\n`);
// ---------------------------------------------------------------------------------------------
// Inventory
const all = [];
const scanDir = dir => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) scanDir(full);
else all.push({ rel: path.relative(tree, full).split(path.sep).join('/'), full, size: fs.statSync(full).size });
}
};
scanDir(tree);
const totalBytes = all.reduce((sum, f) => sum + f.size, 0);
for (const [, entry] of excluded) entry.bytes = 0;
const big = all.filter(f => f.size > MAX_FILE).sort((a, b) => b.size - a.size);
const images = all.filter(f => /\.(png|jpe?g|webp|gif|svg|ico|icns|mp4|webm)$/i.test(f.rel));
const reviewedFile = path.join(root, 'scripts', 'public-tree.reviewed-images.json');
const reviewed = fs.existsSync(reviewedFile) ? JSON.parse(fs.readFileSync(reviewedFile, 'utf8')).reviewed : {};
const unreviewed = images.filter(f => !/^apps\/web\/public\/(og\/items|store\/previews)\//.test(f.rel) && reviewed[f.rel] !== createHash('sha256').update(fs.readFileSync(f.full)).digest('hex')).map(f => f.rel);
// ---------------------------------------------------------------------------------------------
// Checks on the tree
const textFile = f => !/\.(png|jpe?g|webp|gif|ico|icns|mp4|webm|woff2?|ttf|otf|zip|gz|exe|dll|bin|pdf)$/i.test(f.rel) && f.size < 5_000_000;
const pathPatterns = [
[/C:\\Users\\[^\\\s"'`]+/g],
[/C:\/Users\/[^/\s"'`]+/g],
[/\/Users\/(?!<)[A-Za-z0-9._-]+/g],
[/\/home\/(?!<)[A-Za-z0-9._-]+/g, '/home/<user>'],
];
const pathHits = [];
for (const f of all.filter(textFile)) {
const text = fs.readFileSync(f.full, 'utf8');
if (!/Users|home/.test(text)) continue;
text.split('\n').forEach((line, i) => {
for (const [re] of pathPatterns) {
re.lastIndex = 0;
const m = line.match(re);
if (m) pathHits.push(`${f.rel}:${i + 1}: ${m.map(x => mask(x)).join(', ')}`);
}
});
}
// Relative links in kept Markdown that point at something the tree does not have.
const present = new Set(all.map(f => f.rel));
const dirs = new Set();
for (const rel of present) for (let d = path.posix.dirname(rel); d !== '.'; d = path.posix.dirname(d)) dirs.add(d);
const deadLinks = [];
for (const f of all.filter(f => f.rel.endsWith('.md'))) {
const text = fs.readFileSync(f.full, 'utf8');
for (const m of text.matchAll(/\]\(([^)\s#]+)(?:#[^)]*)?\)/g)) {
const target = m[1];
if (/^([a-z]+:|\/\/|#|mailto:)/i.test(target)) continue;
const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(f.rel), target));
if (resolved.startsWith('waybetter/')) continue; // the submodule
if (!present.has(resolved) && !dirs.has(resolved.replace(/\/$/, ''))) deadLinks.push(`${f.rel}: ${target}`);
}
}
// Names of files and the whole tree through the framework's scan (terms from the keys folder).
const cli = path.join(root, 'waybetter', 'packages', 'waybetter', 'bin', 'waybetter.mjs');
const { TERMS_ENV, privacyConfig } = await import(pathToFileURL(path.join(root, 'waybetter', 'packages', 'waybetter', 'cli', 'privacy.mjs')).href);
const configured = process.env[TERMS_ENV] || privacyConfig(root).forbiddenTerms;
const termsArgs = configured && fs.existsSync(configured) ? ['--terms', configured] : [];
const allowArgs = ['--allow', path.join(root, 'privacy-allowlist.txt')];
const runScan = (cwd, ...scanArgs) => {
const r = spawnSync(process.execPath, [cli, 'privacy-scan', ...scanArgs, ...termsArgs, ...allowArgs], {
cwd, encoding: 'utf8', maxBuffer: 1 << 28,
});
return { status: r.status, text: mask(`${r.stdout ?? ''}${r.stderr ?? ''}`).trim(), terms: termsArgs.length > 0 };
};
const scanTree = runScan(root, tree);
// ---------------------------------------------------------------------------------------------
// The single commit, authored as CRT, in a throwaway repository next to the tree.
const repo = path.join(out, 'repo');
const emptyConfig = path.join(out, 'empty.gitconfig');
fs.writeFileSync(emptyConfig, '');
const env = { ...process.env, GIT_AUTHOR_NAME: AUTHOR.name, GIT_AUTHOR_EMAIL: AUTHOR.email, GIT_COMMITTER_NAME: AUTHOR.name, GIT_COMMITTER_EMAIL: AUTHOR.email, GIT_CONFIG_GLOBAL: emptyConfig, GIT_CONFIG_NOSYSTEM: '1' };
const g = (...a) => execFileSync('git', a, { cwd: repo, env, encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
if (UPDATE) {
// One new commit on top of the public repository's current main: its history is the only history.
execFileSync('git', ['clone', '-q', '--branch', 'main', PUBLIC_REPO, repo], { env, encoding: 'utf8', maxBuffer: 1 << 28 });
g('config', 'core.autocrlf', 'false');
for (const entry of fs.readdirSync(repo)) if (entry !== '.git') fs.rmSync(path.join(repo, entry), { recursive: true, force: true });
fs.cpSync(tree, repo, { recursive: true });
} else {
fs.cpSync(tree, repo, { recursive: true });
g('init', '-q', '-b', 'main');
g('config', 'core.autocrlf', 'false');
}
g('add', '-A');
g('update-index', '--add', '--cacheinfo', `160000,${fwCommit},waybetter`);
if (UPDATE && !g('status', '--porcelain')) throw new Error('nothing changed: the public main already has this tree');
g('commit', '-q', '-m', UPDATE ? MESSAGE : 'wayBetter for X');
const commit = g('rev-parse', 'HEAD');
const parent = UPDATE ? g('rev-parse', 'HEAD~1') : null;
const changed = UPDATE ? g('diff', '--stat', 'HEAD~1', 'HEAD').split('\n').pop() : '';
const identity = g('log', '-1', '--format=%an <%ae> | %cn <%ce>');
const scanHistory = args.includes('--no-history-scan') ? { status: null, text: 'skipped' } : runScan(repo, '--history', '.');
const subStatus = g('ls-tree', 'HEAD', 'waybetter');
const gitmodules = g('show', 'HEAD:.gitmodules');
// ---------------------------------------------------------------------------------------------
// The framework's unpushed commits: authors, messages and the diff range through the same scan.
const fwDir = path.join(root, 'waybetter');
const fwGit = (...a) => execFileSync('git', a, { cwd: fwDir, encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
let fwSection;
try {
try { fwGit('fetch', 'origin'); } catch { /* offline: use the refs as they are */ }
const upstream = fwGit('rev-parse', '--abbrev-ref', '@{upstream}');
const base = fwGit('merge-base', 'HEAD', upstream);
const ahead = fwGit('rev-list', '--count', `${base}..HEAD`);
const behind = fwGit('rev-list', '--count', `HEAD..${upstream}`);
const idents = fwGit('log', '--format=%an <%ae> | %cn <%ce>', `${base}..HEAD`).split('\n').filter(Boolean);
const counts = [...new Set(idents)].map(i => `${idents.filter(x => x === i).length} x ${i}`);
const tmp = path.join(out, 'fw-range');
fs.mkdirSync(tmp, { recursive: true });
fs.writeFileSync(path.join(tmp, 'range.patch'), fwGit('log', '-p', '--format=commit %H%nAuthor: %an <%ae>%nCommitter: %cn <%ce>%n%n%B', `${base}..HEAD`));
fs.writeFileSync(path.join(tmp, 'names.txt'), fwGit('diff', '--name-only', `${base}..HEAD`));
const scanRange = runScan(root, tmp);
const scanAll = runScan(fwDir, '--history', '.');
const log = fwGit('log', '--format=- %h %s', `${base}..HEAD`).split('\n').map(l => l.slice(0, 160));
fwSection = ['', '## Framework unpushed commits', '',
`Local branch is ${ahead} ahead and ${behind} behind ${upstream} (base ${base.slice(0, 10)}, head ${fwGit('rev-parse', 'HEAD').slice(0, 10)}).`, '',
`Authors and committers: ${counts.join('; ')}`, '',
`- Privacy scan over the patch text (messages, authors, every added and removed line) and the changed file names: exit ${scanRange.status}`, '', '```', scanRange.text, '```', '',
`- Privacy scan over the framework's whole history (every blob, path, message, identity): exit ${scanAll.status}`, '', '```', scanAll.text, '```', '',
'<details><summary>Commits</summary>', '', ...log, '', '</details>'];
fs.rmSync(tmp, { recursive: true, force: true });
} catch (error) {
fwSection = ['', '## Framework unpushed commits', '', `Could not be computed: ${mask(error.message).split('\n')[0]}`];
}
// ---------------------------------------------------------------------------------------------
// Report
const mb = n => (n / 1e6).toFixed(1);
const lines = [];
const p = (...t) => lines.push(...t);
p('# Public tree dry run', '',
`Generated by \`node scripts/public-tree.mjs\` from app HEAD \`${head.slice(0, 12)}\` and framework commit \`${fwCommit.slice(0, 12)}\` (the gitlink at HEAD unless \`--fw-commit\` was given). Re-run it whenever HEAD moves.`, '',
'## Result', '',
`- Files: **${all.length}** (HEAD has ${files.length - 1} plus the submodule; ${files.length - 1 - kept.length} excluded)`,
`- Size: **${mb(totalBytes)} MB** (git objects will be smaller: compressed)`,
`- Images and media in the set: ${images.length}`,
`- Initial commit: \`${commit.slice(0, 12)}\`, author and committer: ${identity}`,
`- Submodule entry: \`${subStatus}\``, '', '```', gitmodules, '```', '',
'## Excluded, and why', '', '| Files | Reason | Examples |', '| ---: | --- | --- |');
for (const [reason, entry] of excluded) p(`| ${entry.count} | ${reason} | ${entry.samples.map(s => `\`${s}\``).join(', ')} |`);
p('', 'Everything else tracked at HEAD is in the set. `.gitmodules` is rewritten to the public framework URL.', '',
'## Scans', '',
`- Forbidden-terms file: ${scanTree.terms ? 'present and used' : 'MISSING (only the machine account name was checked)'}`,
`- Privacy scan over the tree (file contents, binaries, archives and file names): exit ${scanTree.status}`, '', '```', scanTree.text || '(no output)', '```', '',
`- Privacy scan over the new repository's history (blobs, paths, commit message, identity): exit ${scanHistory.status}`, '', '```', scanHistory.text || '(no output)', '```', '',
`- Absolute user paths (\`C:\\Users\\\`, \`/Users/\`, \`/home/\`): **${pathHits.length}** hit(s), user names masked`);
if (pathHits.length) p('', '```', ...pathHits.slice(0, 60), pathHits.length > 60 ? `... ${pathHits.length - 60} more` : '', '```');
p('', `- Relative Markdown links to files that are not in the set: **${deadLinks.length}**`);
if (deadLinks.length) p('', '```', ...deadLinks, '```');
p('', `- Files over ${mb(MAX_FILE)} MB (review): ${big.length}`);
if (big.length) p('', ...big.map(f => ` - \`${f.rel}\` ${mb(f.size)} MB`));
p('', '## Images', '',
`${images.length} image and media files; ${images.length - unreviewed.length} match the reviewed list (scripts/public-tree.reviewed-images.json: path and sha256 of what a person looked at, or a generated card). Unreviewed or changed, to look at before publishing: **${unreviewed.length}**`, '', ...unreviewed.map(r => '- ' + r), '',
'## Publish (the coordinator runs these)', '',
'The framework goes first: push it, then use its pushed commit as the submodule pointer. Re-run this script with `--fw-commit <that sha>` if it differs from the gitlink above.', '',
...(UPDATE ? ['Update mode: one new commit on top of the public main (' + parent.slice(0, 12) + '): ' + changed + '. Push it with:', '', '```sh', `cd "${show(repo)}"`, 'git push origin main', '```', ''] : []),
'```sh',
'# 1. framework (already public; its remote is behind the local branch)',
'# after reading section "Framework unpushed commits" of the report and fixing what it lists:',
'# git -C waybetter push origin main',
'',
`# 2. re-run the dry run and read the report again`,
`node scripts/public-tree.mjs`,
'',
'# 3. the new repository: an empty repo at ' + PUBLIC_REPO + ' first (created on the forge by the owner or coordinator), then',
`cd "${show(repo)}"`,
`git remote add origin ${PUBLIC_REPO}`,
'git push -u origin main',
'```', '',
`The commit in \`${show(repo)}\` is already authored as ${AUTHOR.name} <${AUTHOR.email}> with the message "wayBetter for X". To use another message or a date, amend it there before pushing (\`git commit --amend\` with the same identity in the environment).`, '');
lines.push(...fwSection, '');
fs.writeFileSync(path.join(out, 'REPORT.md'), lines.join('\n'));
fs.writeFileSync(path.join(out, 'images.txt'), images.map(f => `${f.rel}\t${f.size}`).join('\n') + '\n');
if (UPDATE) console.log(`update commit ${commit.slice(0, 12)} on public main ${parent.slice(0, 12)}: ${changed}\npush: cd "${show(repo)}" && git push origin main`);
console.log(`public tree: ${all.length} files, ${mb(totalBytes)} MB, commit ${commit.slice(0, 12)}`);
console.log(`scan tree: exit ${scanTree.status}; scan history: exit ${scanHistory.status}; path hits: ${pathHits.length}; dead links: ${deadLinks.length}`);
console.log(`report: ${show(path.join(out, 'REPORT.md'))}`);

View file

@ -0,0 +1,64 @@
{
"note": "Images looked at by a person (hero, fix-like, thread-reader frames shown only @CRTkafa and @playfishies; the rest are logos, icons and generated cards). Generated cards under apps/web/public/og/items and store/previews are covered by pattern. Anything not listed or with another hash is reported as unreviewed.",
"reviewed": {
"apps/desktop/src-tauri/icons/128x128.png": "4f9cbaaa7bc493b8d5194af3dc6291f27b091ee2a19c54cba70eeda7c1269e3d",
"apps/desktop/src-tauri/icons/128x128@2x.png": "5db8610d37798eccbfa97912e06ec6f3ea5d090a871766ed4035877cd43931bb",
"apps/desktop/src-tauri/icons/32x32.png": "900f86a59e78d33a50d23e400f8f35c8a6b7bf40e3b2bd89ef057a015fe15b08",
"apps/desktop/src-tauri/icons/64x64.png": "ec94bcc56ecb7d483fa424629855ad58ee12af11856954a7f02508e4f8d591f8",
"apps/desktop/src-tauri/icons/app-icon.png": "55804f5efdb837223362c56cd39c4041d0d030e33a5db153b702dbc3d43e6ce8",
"apps/desktop/src-tauri/icons/icon.icns": "d9658badddd2ed3d96a9da8ce6c4428efa979818ef5441a13a7b9a9b37391161",
"apps/desktop/src-tauri/icons/icon.ico": "422cd8b400e0c0a107bdcc0e8dc91d797f8e8b279aaaf363d5d4037c409e280a",
"apps/desktop/src-tauri/icons/icon.png": "cc9357e5d149b8d1e2f8fefea1ffee26fb0f72423f224bc19b5d9e3a2809db98",
"apps/web/public/app-icon.png": "55804f5efdb837223362c56cd39c4041d0d030e33a5db153b702dbc3d43e6ce8",
"apps/web/public/brand/brush-swash.svg": "9680bc3e94c9f159f8e702abeda48fd4bdec8cc054377ee778cd62bd253eca98",
"apps/web/public/brand/wb-icon-128.png": "056705755ecd72a704558e668be887ae6ad87bd25f5fc51668445270d52f1b76",
"apps/web/public/brand/wb-icon-256.png": "33a989958398e6cb547f8964d361d103f8c09bbe430744a9698daabe5ed72c2c",
"apps/web/public/brand/wb-icon-32.png": "f2961851434245ad5abb33cfce62285a844eb440af9f0bb72f2bdbf160e2d522",
"apps/web/public/brand/wb-icon-512.png": "e0425c029a5b3784164d16728ea45cf542164ea55f5312e4768d90ef5716a3b7",
"apps/web/public/brand/wb-icon-64.png": "940246b4f9d8789497e983c22c9b22bc1b4cbcd2f539b4aa5ca3d6053ed0ac2d",
"apps/web/public/brand/wb-icon.svg": "c0e43b05c111c4b6cbe813158bdd5cf19df1e34168a3fc456be1142cb6ac10b6",
"apps/web/public/brand/wb-mark-128.png": "40f249a1f33f7ffbcbce4c920e62144b162765fa537bac428c4d57a1802cff09",
"apps/web/public/brand/wb-mark-256.png": "1a6bf95513f796538a791a6d3b868f6dbceb34c80388d83db2f13dbe48562c92",
"apps/web/public/brand/wb-mark-32.png": "33152842c6431ea6da07015223020ad2734eebda9a640a1f8900ed4cb4dc47e2",
"apps/web/public/brand/wb-mark-512.png": "584dc90c4568a186a3c19446500b48c8e7ccb390081e8341bd8e5ad122e7284e",
"apps/web/public/brand/wb-mark-64.png": "c5b766c2a3232ea68d12d84cb05b1eb7d1c6374e53b6c883a007fb544271eb16",
"apps/web/public/brand/wb-mark-light.svg": "2007ba9de2b59139f5d8462290b789ce7d60f762943498b0e643a8af2c41ab9c",
"apps/web/public/brand/wb-mark-simple.svg": "0aaf4d04edf0d41218d872673e1ac980d53d16eb79f35dac3c3658ced9f71cb6",
"apps/web/public/brand/wb-mark.svg": "9140015c771cde09ece44ec8a11d76025c90e2ca947045758651b0f374f274f6",
"apps/web/public/demo/fix-like-m.jpg": "6143ad2df62d38eb8abce1f3ac624fc2323b2a34ee4a350c2d09845ed11fd4ac",
"apps/web/public/demo/fix-like-m.mp4": "b536b2d687270acf3196ca59139eb83a660cd32a5c9d366cbc1f803d6040383f",
"apps/web/public/demo/fix-like-m.webp": "4f0134b06cb34e9907997afc6b970e5c419498e65d52f64f0aadd7f1a46eab0e",
"apps/web/public/demo/fix-like.jpg": "6bd9b88581f7999f9cda94051e17581cfc7283b9c69d64d94dbcedb8d5ce54d1",
"apps/web/public/demo/fix-like.mp4": "6af489657b9f0ca46a7835e9d6b3fcf9ebbc760541137f5e0d28c9c182c3a380",
"apps/web/public/demo/fix-like.webp": "ee2c107f747f1f48f6954849cb75120c697a18791d0494856c5dc118c41bdbf7",
"apps/web/public/demo/hero.jpg": "3f951c12bb061d529f2d07638129bb76ddfd717902c2dd0729d44401eb42574b",
"apps/web/public/demo/hero.mp4": "abe14a93ea9e6f272de5a4706a26068e17a407d55ab4e6e7b6ac6780b472b3d9",
"apps/web/public/demo/hero.webp": "48a1f58e2a8bae501745e95fb46fe30b3a42061c5f2b9e582fa07963a97ae82a",
"apps/web/public/git-crt-logo.svg": "997bea1b94c9b40a4f59d45b127119a51b364edb7d9d689045d4a97876739e89",
"apps/web/public/og/home.png": "7ce32572720777713b26f7ad3d42f04db116e16a18da6ab42cf3053702e070f6",
"apps/web/public/og/store.png": "6eb9b284a3bccf173dd72befca20fb6f3e9955a8c1083df09f0a81efc7e66d80",
"apps/web/public/og/x.png": "128e751ba1a2d270cf2a1266594b934f2487601db4054c87b51cb8bc93ac62d8",
"apps/web/public/wb-mark.svg": "19f08a0321c008b94c8ea691b8ac9fb5f107c6fa8b083418d4a8cb4f82d62e53",
"docs/brand/logo-source.png": "b8f1a64b7104be1ed2d32f1b1714d27782c2ee273b204a3c9fde7f08b8e90695",
"store/x/areas/reader/media/copy-as-markdown.png": "d9aa931d19a3d84282c4cc1776b8cab4bce64496bd0278898a730fe7723720a8",
"store/x/areas/reader/media/cover.webp": "c5f7d41a144c6a2e7be278df14b21bbbfd07c384cfe618fbc6530d01598ae05f",
"store/x/areas/reader/media/demo.mp4": "e74810ddf6210ddbd185e37123d41cfcc214c9bcae5eee3152a6392ee92cc1b1",
"store/x/areas/reader/media/demo.webp": "62ee097cdab833b2cc1dc10d1503fa2a16a501d1a97a4ac7d62c616438e7d1b2",
"store/x/areas/reader/media/reading-view.webp": "3c24634b09d7c9a2fa79bf4fa62c7d9704ed15a38281ef253ae2bcbf6410c3f7",
"assets/readme/app-menu.mp4": "ac951bb3db05489ce6bd7f9f9d918273bab20d12b91c3bf7ba7d84f47766ea6c",
"assets/readme/app-menu.webp": "8936170ce5beab50aa6d8afbdbcfc11b2512cc878aeb0988d7cb84ebf5c11364",
"assets/readme/chat-plus.mp4": "7ab687c9d6e1c805e6499283854e334d1bb1f1af593950982852961420d49cf5",
"assets/readme/chat-plus.webp": "0b240aa32f0e99b7d907b8ed72c1a3ffed46f8ff9ebf5902c4e180932b7741b1",
"assets/readme/hero.webp": "b4d9ec3ebf86e0bad0b3fb40f82f18dd4544cdee332b5042cc0c2408a63cf1a7",
"assets/readme/like-fix.mp4": "7d7b68137537ca2b02d093c19c97a21dcda3dc7f1cc74475f166e6c17dbc2dbb",
"assets/readme/like-fix.webp": "970494d80ee1f02952a5069523fa4bef83c8c3d976e3df839d8458821d426eeb",
"assets/readme/split-accounts.mp4": "c05e04a54ebd2c87c28808ec8091c403b9f1b0ec2703ca39e25f71a4a6cdb63d",
"assets/readme/split-accounts.webp": "c4117094d0f5f66da20fa0400ad923678ca01f9ac652a6c74f164c97b70a5cc0",
"assets/readme/store.mp4": "9020db21e8cd9ea758181e90d535af2a6fda01570dcf14ac3c3fe545b2ba97c0",
"assets/readme/store.webp": "47a10af6dc32d3b5bacef6d4d59824ddb2e5f72ec9ed046dc26714f378adffdc",
"assets/readme/string-pack.mp4": "5dfbc59c7b31455796eccb28c03fa5fb4caff72c2e4e4127237efa8eec8862e4",
"assets/readme/string-pack.webp": "f91095cd272b7b7fb059ad2329c9d7532066698d77f1e00e010b183832ae5b7d",
"assets/readme/theme-burst.mp4": "b7d151650b96f0cbff5000fc7e06a525adefe022c7ba6f8f9236c4b53f273682",
"assets/readme/theme-burst.webp": "00924d81b087bedee154c69503e3b7c35319039f30aa30e934da7dc4f35d4c62"
}
}

View file

@ -25,8 +25,9 @@
// //
// node scripts/release-macos.mjs --dmg <file.dmg> --updater <file.app.tar.gz> // node scripts/release-macos.mjs --dmg <file.dmg> --updater <file.app.tar.gz>
// //
// Both files go through the optional release check first (WAYBETTER_RELEASE_CHECK): a failure // Both files go through `waybetter privacy-scan` first (the dmg's image and the .app inside the
// stops this script before anything is copied or signed. // updater bundle are opened): a forbidden name in either stops this script before anything is
// copied or signed.
// //
// A universal build serves both darwin-aarch64 and darwin-x86_64. Run scripts/release.mjs (Windows) // A universal build serves both darwin-aarch64 and darwin-x86_64. Run scripts/release.mjs (Windows)
// first: this script keeps every platform already in latest.json and refuses a version mismatch. // first: this script keeps every platform already in latest.json and refuses a version mismatch.

View file

@ -7,10 +7,10 @@
// //
// node scripts/release.mjs [--skip-build] [--notes "text"] // node scripts/release.mjs [--skip-build] [--notes "text"]
// //
// The build runs with `waybetter build-env` (no absolute build path in the binary), and the // Privacy: the build runs with `waybetter build-env` (no absolute build path, so no account name,
// installer, the binary and the front end go through the optional release check // in the binary), and the installer (opened with 7-Zip), the binary and the front end must pass
// (WAYBETTER_RELEASE_CHECK) before anything is copied to releases/. The .pdb next to the binary // `waybetter privacy-scan` against ~/.better-twttr-keys/forbidden-names.txt before anything is
// holds every path: never publish it. // copied to releases/. The .pdb next to the binary holds every path: never publish it.
// //
// Env: // Env:
// CARGO_TARGET_DIR optional; the bundle is read from <it>/release/bundle/nsis // CARGO_TARGET_DIR optional; the bundle is read from <it>/release/bundle/nsis
@ -19,7 +19,7 @@
// DEPLOY_TARGET ssh target for the printed steps, e.g. user@host (no default: printed as a placeholder) // DEPLOY_TARGET ssh target for the printed steps, e.g. user@host (no default: printed as a placeholder)
// CDN_DIR remote folder behind CDN_BASE (placeholder when unset) // CDN_DIR remote folder behind CDN_BASE (placeholder when unset)
// RELEASES_DIR remote API RELEASES_DIR (placeholder when unset) // RELEASES_DIR remote API RELEASES_DIR (placeholder when unset)
// WAYBETTER_RELEASE_CHECK optional command run on every artifact first (a non-zero exit stops the release) // WAYBETTER_FORBIDDEN_TERMS another terms file; WAYBETTER_7Z 7-Zip when it is not installed in Program Files
import { dirname, resolve } from 'node:path'; import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { releaseCommand } from '../waybetter/packages/waybetter/cli/release.mjs'; import { releaseCommand } from '../waybetter/packages/waybetter/cli/release.mjs';

@ -1 +1 @@
Subproject commit 699daaa0b2adfa806381f5a60029803242938ba8 Subproject commit 9b42e84cdd71b8ce9378916f09df41a438aae4c5

View file

@ -21,6 +21,8 @@
"windows": { "silentSwitches": "/S", "scope": "user" }, "windows": { "silentSwitches": "/S", "scope": "user" },
"macos": { "app": "wayBetter for X.app", "zap": ["~/Library/Application Support/app.bettertwttr.desktop", "~/Library/Caches/app.bettertwttr.desktop"] } "macos": { "app": "wayBetter for X.app", "zap": ["~/Library/Application Support/app.bettertwttr.desktop", "~/Library/Caches/app.bettertwttr.desktop"] }
}, },
"forbiddenTerms": "~/.better-twttr-keys/forbidden-names.txt",
"privacyAllowlist": "privacy-allowlist.txt",
"manifestValidator": { "manifestValidator": {
"module": "packages/contracts/dist/index.js", "module": "packages/contracts/dist/index.js",
"export": "NativeRelease", "export": "NativeRelease",