|
| 1 | +use std::path::{Path, PathBuf}; |
| 2 | + |
| 3 | +use rusqlite::{Connection, OpenFlags}; |
| 4 | +use serde::Serialize; |
| 5 | + |
| 6 | +const BUZZ_RELEASE_IDENTIFIER_PREFIX: &str = "xyz.block.buzz.app"; |
| 7 | +const SPROUT_RELEASE_IDENTIFIER: &str = "xyz.block.sprout.app"; |
| 8 | +const BUZZ_DEV_IDENTIFIER_PREFIX: &str = "xyz.block.buzz.app.dev"; |
| 9 | +const SPROUT_DEV_IDENTIFIER_PREFIX: &str = "xyz.block.sprout.app.dev"; |
| 10 | + |
| 11 | +const SPROUT_WORKSPACES_KEY: &str = "sprout-workspaces"; |
| 12 | +const SPROUT_ACTIVE_WORKSPACE_KEY: &str = "sprout-active-workspace-id"; |
| 13 | +const SPROUT_ONBOARDING_COMPLETE_PREFIX: &str = "sprout-onboarding-complete.v1:"; |
| 14 | + |
| 15 | +#[derive(Debug, Default, Serialize)] |
| 16 | +#[serde(rename_all = "camelCase")] |
| 17 | +pub struct LegacyWorkspaceStorage { |
| 18 | + workspaces: Option<String>, |
| 19 | + active_workspace_id: Option<String>, |
| 20 | + onboarding_completions: Vec<LegacyOnboardingCompletion>, |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(Debug, Serialize)] |
| 24 | +#[serde(rename_all = "camelCase")] |
| 25 | +pub struct LegacyOnboardingCompletion { |
| 26 | + pubkey: String, |
| 27 | + value: String, |
| 28 | +} |
| 29 | + |
| 30 | +fn legacy_identifier(current_identifier: &str) -> Option<String> { |
| 31 | + if current_identifier.starts_with(BUZZ_DEV_IDENTIFIER_PREFIX) { |
| 32 | + Some(current_identifier.replacen( |
| 33 | + BUZZ_DEV_IDENTIFIER_PREFIX, |
| 34 | + SPROUT_DEV_IDENTIFIER_PREFIX, |
| 35 | + 1, |
| 36 | + )) |
| 37 | + } else if current_identifier.starts_with(BUZZ_RELEASE_IDENTIFIER_PREFIX) { |
| 38 | + Some(current_identifier.replacen( |
| 39 | + BUZZ_RELEASE_IDENTIFIER_PREFIX, |
| 40 | + SPROUT_RELEASE_IDENTIFIER, |
| 41 | + 1, |
| 42 | + )) |
| 43 | + } else { |
| 44 | + None |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(target_os = "macos")] |
| 49 | +fn legacy_webkit_data_root(identifier: &str) -> Option<PathBuf> { |
| 50 | + dirs::home_dir().map(|home| { |
| 51 | + home.join("Library") |
| 52 | + .join("WebKit") |
| 53 | + .join(identifier) |
| 54 | + .join("WebsiteData") |
| 55 | + }) |
| 56 | +} |
| 57 | + |
| 58 | +#[cfg(not(target_os = "macos"))] |
| 59 | +fn legacy_webkit_data_root(_identifier: &str) -> Option<PathBuf> { |
| 60 | + None |
| 61 | +} |
| 62 | + |
| 63 | +fn collect_local_storage_databases(root: &Path, databases: &mut Vec<PathBuf>) { |
| 64 | + let Ok(entries) = std::fs::read_dir(root) else { |
| 65 | + return; |
| 66 | + }; |
| 67 | + |
| 68 | + for entry in entries.flatten() { |
| 69 | + let path = entry.path(); |
| 70 | + if path.is_dir() { |
| 71 | + collect_local_storage_databases(&path, databases); |
| 72 | + } else if path.file_name().and_then(|name| name.to_str()) == Some("localstorage.sqlite3") { |
| 73 | + databases.push(path); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +fn decode_webkit_local_storage_value(bytes: &[u8]) -> Option<String> { |
| 79 | + if bytes.is_empty() { |
| 80 | + return Some(String::new()); |
| 81 | + } |
| 82 | + |
| 83 | + if bytes.len() % 2 == 0 { |
| 84 | + let has_utf16_ascii_shape = bytes.chunks_exact(2).any(|chunk| chunk[1] == 0); |
| 85 | + if has_utf16_ascii_shape { |
| 86 | + let utf16: Vec<u16> = bytes |
| 87 | + .chunks_exact(2) |
| 88 | + .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) |
| 89 | + .collect(); |
| 90 | + if let Ok(value) = String::from_utf16(&utf16) { |
| 91 | + return Some(value.trim_end_matches('\0').to_string()); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + String::from_utf8(bytes.to_vec()).ok() |
| 97 | +} |
| 98 | + |
| 99 | +fn read_legacy_workspace_storage_db(path: &Path) -> Result<LegacyWorkspaceStorage, String> { |
| 100 | + let conn = Connection::open_with_flags( |
| 101 | + path, |
| 102 | + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, |
| 103 | + ) |
| 104 | + .map_err(|e| format!("open legacy localStorage db: {e}"))?; |
| 105 | + |
| 106 | + let mut stmt = conn |
| 107 | + .prepare( |
| 108 | + "SELECT key, value FROM ItemTable \ |
| 109 | + WHERE key = ?1 OR key = ?2 OR key LIKE ?3", |
| 110 | + ) |
| 111 | + .map_err(|e| format!("prepare legacy localStorage query: {e}"))?; |
| 112 | + let mut rows = stmt |
| 113 | + .query([ |
| 114 | + SPROUT_WORKSPACES_KEY, |
| 115 | + SPROUT_ACTIVE_WORKSPACE_KEY, |
| 116 | + &format!("{SPROUT_ONBOARDING_COMPLETE_PREFIX}%"), |
| 117 | + ]) |
| 118 | + .map_err(|e| format!("query legacy localStorage: {e}"))?; |
| 119 | + |
| 120 | + let mut result = LegacyWorkspaceStorage::default(); |
| 121 | + while let Some(row) = rows |
| 122 | + .next() |
| 123 | + .map_err(|e| format!("read legacy localStorage row: {e}"))? |
| 124 | + { |
| 125 | + let key: String = row |
| 126 | + .get(0) |
| 127 | + .map_err(|e| format!("read legacy localStorage key: {e}"))?; |
| 128 | + let value_bytes: Vec<u8> = row |
| 129 | + .get(1) |
| 130 | + .map_err(|e| format!("read legacy localStorage value: {e}"))?; |
| 131 | + let Some(value) = decode_webkit_local_storage_value(&value_bytes) else { |
| 132 | + continue; |
| 133 | + }; |
| 134 | + |
| 135 | + if key == SPROUT_WORKSPACES_KEY { |
| 136 | + result.workspaces = Some(value); |
| 137 | + } else if key == SPROUT_ACTIVE_WORKSPACE_KEY { |
| 138 | + result.active_workspace_id = Some(value); |
| 139 | + } else if let Some(pubkey) = key.strip_prefix(SPROUT_ONBOARDING_COMPLETE_PREFIX) { |
| 140 | + result |
| 141 | + .onboarding_completions |
| 142 | + .push(LegacyOnboardingCompletion { |
| 143 | + pubkey: pubkey.to_string(), |
| 144 | + value, |
| 145 | + }); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + Ok(result) |
| 150 | +} |
| 151 | + |
| 152 | +fn merge_legacy_workspace_storage( |
| 153 | + target: &mut LegacyWorkspaceStorage, |
| 154 | + source: LegacyWorkspaceStorage, |
| 155 | +) { |
| 156 | + if target.workspaces.is_none() { |
| 157 | + target.workspaces = source.workspaces; |
| 158 | + } |
| 159 | + if target.active_workspace_id.is_none() { |
| 160 | + target.active_workspace_id = source.active_workspace_id; |
| 161 | + } |
| 162 | + target |
| 163 | + .onboarding_completions |
| 164 | + .extend(source.onboarding_completions); |
| 165 | +} |
| 166 | + |
| 167 | +/// Return workspace-scoped localStorage values from the legacy Sprout WebKit |
| 168 | +/// data directory so the frontend can seed Buzz localStorage before first |
| 169 | +/// render. This is separate from `migrate_legacy_app_data_dir`: Tauri app data |
| 170 | +/// migration copies files such as `identity.key`, but WebKit localStorage lives |
| 171 | +/// under `~/Library/WebKit/<identifier>/...` on macOS and is not included in the |
| 172 | +/// app data directory. |
| 173 | +#[tauri::command] |
| 174 | +pub fn get_legacy_workspace_storage( |
| 175 | + app: tauri::AppHandle, |
| 176 | +) -> Result<LegacyWorkspaceStorage, String> { |
| 177 | + let Some(identifier) = legacy_identifier(&app.config().identifier) else { |
| 178 | + return Ok(LegacyWorkspaceStorage::default()); |
| 179 | + }; |
| 180 | + let Some(root) = legacy_webkit_data_root(&identifier) else { |
| 181 | + return Ok(LegacyWorkspaceStorage::default()); |
| 182 | + }; |
| 183 | + if !root.exists() { |
| 184 | + return Ok(LegacyWorkspaceStorage::default()); |
| 185 | + } |
| 186 | + |
| 187 | + let mut databases = Vec::new(); |
| 188 | + collect_local_storage_databases(&root, &mut databases); |
| 189 | + |
| 190 | + let mut result = LegacyWorkspaceStorage::default(); |
| 191 | + for database in databases { |
| 192 | + match read_legacy_workspace_storage_db(&database) { |
| 193 | + Ok(storage) => merge_legacy_workspace_storage(&mut result, storage), |
| 194 | + Err(error) => eprintln!( |
| 195 | + "buzz-desktop: legacy-local-storage-migration: {}: {error}", |
| 196 | + database.display() |
| 197 | + ), |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + Ok(result) |
| 202 | +} |
| 203 | + |
| 204 | +#[cfg(test)] |
| 205 | +mod tests { |
| 206 | + use super::*; |
| 207 | + |
| 208 | + #[test] |
| 209 | + fn legacy_identifier_maps_release_identifier() { |
| 210 | + assert_eq!( |
| 211 | + legacy_identifier("xyz.block.buzz.app"), |
| 212 | + Some("xyz.block.sprout.app".to_string()) |
| 213 | + ); |
| 214 | + } |
| 215 | + |
| 216 | + #[test] |
| 217 | + fn legacy_identifier_maps_dev_worktree_identifier() { |
| 218 | + assert_eq!( |
| 219 | + legacy_identifier("xyz.block.buzz.app.dev.my-branch"), |
| 220 | + Some("xyz.block.sprout.app.dev.my-branch".to_string()) |
| 221 | + ); |
| 222 | + } |
| 223 | + |
| 224 | + #[test] |
| 225 | + fn decode_webkit_local_storage_value_reads_utf16le() { |
| 226 | + let bytes: Vec<u8> = "true".encode_utf16().flat_map(u16::to_le_bytes).collect(); |
| 227 | + assert_eq!( |
| 228 | + decode_webkit_local_storage_value(&bytes).as_deref(), |
| 229 | + Some("true") |
| 230 | + ); |
| 231 | + } |
| 232 | + |
| 233 | + #[test] |
| 234 | + fn decode_webkit_local_storage_value_reads_utf8_fallback() { |
| 235 | + assert_eq!( |
| 236 | + decode_webkit_local_storage_value(b"plain utf8").as_deref(), |
| 237 | + Some("plain utf8") |
| 238 | + ); |
| 239 | + } |
| 240 | + |
| 241 | + #[test] |
| 242 | + fn read_legacy_workspace_storage_db_reads_workspace_keys() { |
| 243 | + let dir = tempfile::tempdir().unwrap(); |
| 244 | + let path = dir.path().join("localstorage.sqlite3"); |
| 245 | + let conn = Connection::open(&path).unwrap(); |
| 246 | + conn.execute( |
| 247 | + "CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)", |
| 248 | + [], |
| 249 | + ) |
| 250 | + .unwrap(); |
| 251 | + |
| 252 | + fn utf16le(value: &str) -> Vec<u8> { |
| 253 | + value.encode_utf16().flat_map(u16::to_le_bytes).collect() |
| 254 | + } |
| 255 | + |
| 256 | + conn.execute( |
| 257 | + "INSERT INTO ItemTable (key, value) VALUES (?1, ?2)", |
| 258 | + ( |
| 259 | + SPROUT_WORKSPACES_KEY, |
| 260 | + utf16le("[{\"relayUrl\":\"wss://relay.example.com\"}]"), |
| 261 | + ), |
| 262 | + ) |
| 263 | + .unwrap(); |
| 264 | + conn.execute( |
| 265 | + "INSERT INTO ItemTable (key, value) VALUES (?1, ?2)", |
| 266 | + (SPROUT_ACTIVE_WORKSPACE_KEY, utf16le("workspace-1")), |
| 267 | + ) |
| 268 | + .unwrap(); |
| 269 | + conn.execute( |
| 270 | + "INSERT INTO ItemTable (key, value) VALUES (?1, ?2)", |
| 271 | + ( |
| 272 | + format!("{SPROUT_ONBOARDING_COMPLETE_PREFIX}abc123"), |
| 273 | + utf16le("true"), |
| 274 | + ), |
| 275 | + ) |
| 276 | + .unwrap(); |
| 277 | + drop(conn); |
| 278 | + |
| 279 | + let storage = read_legacy_workspace_storage_db(&path).unwrap(); |
| 280 | + assert_eq!( |
| 281 | + storage.workspaces.as_deref(), |
| 282 | + Some("[{\"relayUrl\":\"wss://relay.example.com\"}]") |
| 283 | + ); |
| 284 | + assert_eq!(storage.active_workspace_id.as_deref(), Some("workspace-1")); |
| 285 | + assert_eq!(storage.onboarding_completions.len(), 1); |
| 286 | + assert_eq!(storage.onboarding_completions[0].pubkey, "abc123"); |
| 287 | + assert_eq!(storage.onboarding_completions[0].value, "true"); |
| 288 | + } |
| 289 | +} |
0 commit comments