diff --git a/browser/safari/count.go b/browser/safari/count.go new file mode 100644 index 0000000..e3f68fc --- /dev/null +++ b/browser/safari/count.go @@ -0,0 +1,106 @@ +package safari + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + + _ "modernc.org/sqlite" + + "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/sqlitex" +) + +// list --detail keeps today's counting queries until the switch-over, when it counts what the extractors emit. +const safariCountHistoryQuery = `SELECT COUNT(*) FROM history_items` + +const ( + webkitOriginFile = "origin" + webkitLocalStorageSubdir = "LocalStorage" + webkitLocalStorageDB = "localstorage.sqlite3" + webkitOriginSaltName = "salt" +) + +func countHistories(path string) (int, error) { + return sqlitex.CountRows(path, true, safariCountHistoryQuery) +} + +// countLocalStorage sums ItemTable row counts across every origin DB under root without +// parsing origin files or decoding values — CountEntries callers only need the total, not the +// URLs or plaintext. COUNT(key) naturally excludes NULL keys, matching the same skip rule +// applied by readLocalStorageFile, so count and extract stay in sync. +func countLocalStorage(root string) (int, error) { + dirs, err := findOriginDataDirs(root) + if err != nil { + return 0, err + } + total := 0 + for _, od := range dirs { + dbPath := filepath.Join(od, webkitLocalStorageSubdir, webkitLocalStorageDB) + n, err := countLocalStorageFile(dbPath) + if err != nil { + log.Debugf("safari localstorage: count %s: %v", dbPath, err) + continue + } + total += n + } + return total, nil +} + +func countLocalStorageFile(path string) (int, error) { + // mode=ro (no immutable) so SQLite replays the copied -wal sidecar — this surfaces entries + // Safari has committed to WAL but not yet checkpointed to the main DB. Writes SQLite might + // make to the temp-copy's -shm during replay are harmless; the Session cleanup removes + // everything. Live-file reads (profiles.go) still use immutable=1 to stay off the real WAL. + dsn := "file:" + path + "?mode=ro" + db, err := sql.Open("sqlite", dsn) + if err != nil { + return 0, fmt.Errorf("open %s: %w", path, err) + } + defer db.Close() + if err := db.Ping(); err != nil { + return 0, fmt.Errorf("ping %s: %w", path, err) + } + var count int + if err := db.QueryRow(`SELECT COUNT(key) FROM ItemTable`).Scan(&count); err != nil { + return 0, fmt.Errorf("count ItemTable: %w", err) + } + return count, nil +} + +// findOriginDataDirs returns /

/

/ paths that contain both an "origin" file and +// a "LocalStorage/localstorage.sqlite3" database. Non-directory entries, the "salt" sibling, +// and partition dirs without localStorage data are silently skipped. +func findOriginDataDirs(root string) ([]string, error) { + topEntries, err := os.ReadDir(root) + if err != nil { + return nil, fmt.Errorf("read origins root %s: %w", root, err) + } + var out []string + for _, top := range topEntries { + if !top.IsDir() || top.Name() == webkitOriginSaltName { + continue + } + topPath := filepath.Join(root, top.Name()) + frameEntries, err := os.ReadDir(topPath) + if err != nil { + continue + } + for _, frame := range frameEntries { + if !frame.IsDir() { + continue + } + framePath := filepath.Join(topPath, frame.Name()) + if _, err := os.Stat(filepath.Join(framePath, webkitOriginFile)); err != nil { + continue + } + dbPath := filepath.Join(framePath, webkitLocalStorageSubdir, webkitLocalStorageDB) + if _, err := os.Stat(dbPath); err != nil { + continue + } + out = append(out, framePath) + } + } + return out, nil +} diff --git a/browser/safari/count_test.go b/browser/safari/count_test.go new file mode 100644 index 0000000..25fb118 --- /dev/null +++ b/browser/safari/count_test.go @@ -0,0 +1,84 @@ +package safari + +import ( + "database/sql" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupSafariHistoryDB(t *testing.T) string { + t.Helper() + return createTestDB(t, "History.db", + []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, + insertHistoryItem(1, "https://github.com", "github.com", 100), + insertHistoryItem(2, "https://go.dev", "go.dev", 50), + insertHistoryItem(3, "https://example.com", "example.com", 200), + // Item 1 has two visits — extractHistories must deduplicate. + insertHistoryVisit(1, 1, 704067600.0, "GitHub"), + insertHistoryVisit(2, 1, 705067600.0, "GitHub - Latest"), + insertHistoryVisit(3, 2, 703067600.0, "The Go Programming Language"), + insertHistoryVisit(4, 3, 700067600.0, "Example Domain"), + ) +} + +func TestCountHistories(t *testing.T) { + path := setupSafariHistoryDB(t) + + count, err := countHistories(path) + require.NoError(t, err) + assert.Equal(t, 3, count) +} + +func TestCountHistories_Empty(t *testing.T) { + path := createTestDB(t, "History.db", + []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}) + + count, err := countHistories(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountLocalStorage(t *testing.T) { + root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ + "https://a.com": {{Key: "k1", Value: "v1"}, {Key: "k2", Value: "v2"}}, + "https://b.com": {{Key: "k3", Value: "v3"}}, + "https://c.com:8443": {{Key: "k4", Value: "v4"}}, + }) + count, err := countLocalStorage(root) + require.NoError(t, err) + assert.Equal(t, 4, count) +} + +func TestCountLocalStorage_DirMissing(t *testing.T) { + count, err := countLocalStorage(filepath.Join(t.TempDir(), "nope")) + require.Error(t, err) + assert.Equal(t, 0, count) +} + +func TestCountLocalStorageFile_SkipsNullKey(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "ls.sqlite3") + writeLocalStorageDB(t, dbPath, []testLocalStorageItem{ + {Key: "k1", Value: "v1"}, + {Key: "k2", Value: "v2"}, + }, true /*addNullKey*/) + + count, err := countLocalStorageFile(dbPath) + require.NoError(t, err) + assert.Equal(t, 2, count, "NULL keys are excluded from count to match extract's skip rule") +} + +func TestCountLocalStorageFile_MissingTable(t *testing.T) { + // Real Safari has origin dirs with LocalStorage/localstorage.sqlite3 but no ItemTable yet + // (seen during live verification). countLocalStorageFile must surface the error so the + // caller can log-and-skip rather than counting 0 silently. + dbPath := filepath.Join(t.TempDir(), "empty.sqlite3") + db, err := sql.Open("sqlite", dbPath) + require.NoError(t, err) + require.NoError(t, db.Close()) + + _, err = countLocalStorageFile(dbPath) + require.Error(t, err) +} diff --git a/browser/safari/extract_password.go b/browser/safari/extract_password.go deleted file mode 100644 index a81fd65..0000000 --- a/browser/safari/extract_password.go +++ /dev/null @@ -1,91 +0,0 @@ -package safari - -import ( - "fmt" - "strings" - - "github.com/moond4rk/keychainbreaker" - - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/record" -) - -func extractPasswords(keychainPassword string) ([]record.Login, error) { - passwords, err := getInternetPasswords(keychainPassword) - if err != nil { - return nil, err - } - - var logins []record.Login - for _, p := range passwords { - url := buildURL(p.Protocol, p.Server, p.Port, p.Path) - if url == "" || p.Account == "" { - continue - } - logins = append(logins, record.Login{ - URL: url, - Username: p.Account, - Password: p.PlainPassword, - CreatedAt: p.Created.UTC(), - Store: record.StoreLocal, - }) - } - return logins, nil -} - -func countPasswords(keychainPassword string) (int, error) { - passwords, err := extractPasswords(keychainPassword) - if err != nil { - return 0, err - } - return len(passwords), nil -} - -// getInternetPasswords reads InternetPassword records straight from the macOS login keychain (Safari owns its own key -// path, separate from the masterkey package). TryUnlock always runs — even without a password — so a locked keychain -// still yields metadata-only records (URL, account, blank password) instead of failing with ErrLocked. -func getInternetPasswords(keychainPassword string) ([]keychainbreaker.InternetPassword, error) { - kc, err := keychainbreaker.Open() - if err != nil { - return nil, fmt.Errorf("open keychain: %w", err) - } - - var unlockOpts []keychainbreaker.UnlockOption - if keychainPassword != "" { - unlockOpts = append(unlockOpts, keychainbreaker.WithPassword(keychainPassword)) - } - if err := kc.TryUnlock(unlockOpts...); err != nil { - log.Debugf("keychain unlock detail: %v", err) - } - - passwords, err := kc.InternetPasswords() - if err != nil { - return nil, fmt.Errorf("extract internet passwords: %w", err) - } - return passwords, nil -} - -// buildURL constructs a URL from InternetPassword fields. -func buildURL(protocol, server string, port uint32, path string) string { - if server == "" { - return "" - } - - // macOS Keychain stores the protocol as a FourCC code; only "htps" needs remapping, others just trim padding. - scheme := strings.TrimRight(protocol, " ") - if scheme == "" || scheme == "htps" { - scheme = "https" - } - - url := scheme + "://" + server - - defaultPorts := map[string]uint32{"https": 443, "http": 80, "ftp": 21} - if port > 0 && port != defaultPorts[scheme] { - url += fmt.Sprintf(":%d", port) - } - - if path != "" && path != "/" { - url += path - } - return url -} diff --git a/browser/safari/keychain.go b/browser/safari/keychain.go new file mode 100644 index 0000000..8821661 --- /dev/null +++ b/browser/safari/keychain.go @@ -0,0 +1,42 @@ +package safari + +import ( + "context" + "fmt" + + "github.com/moond4rk/keychainbreaker" + + "github.com/moond4rk/hackbrowserdata/internal/log" +) + +// passwordKeychain is today's direct read of the login keychain, handed to the Safari base until the switch-over +// gives every reader the run's one handle. +type passwordKeychain string + +func (pw passwordKeychain) InternetPasswords(context.Context) ([]keychainbreaker.InternetPassword, error) { + return getInternetPasswords(string(pw)) +} + +// getInternetPasswords reads InternetPassword records straight from the macOS login keychain (Safari owns its own key +// path, separate from the masterkey package). TryUnlock always runs — even without a password — so a locked keychain +// still yields metadata-only records (URL, account, blank password) instead of failing with ErrLocked. +func getInternetPasswords(keychainPassword string) ([]keychainbreaker.InternetPassword, error) { + kc, err := keychainbreaker.Open() + if err != nil { + return nil, fmt.Errorf("open keychain: %w", err) + } + + var unlockOpts []keychainbreaker.UnlockOption + if keychainPassword != "" { + unlockOpts = append(unlockOpts, keychainbreaker.WithPassword(keychainPassword)) + } + if err := kc.TryUnlock(unlockOpts...); err != nil { + log.Debugf("keychain unlock detail: %v", err) + } + + passwords, err := kc.InternetPasswords() + if err != nil { + return nil, fmt.Errorf("extract internet passwords: %w", err) + } + return passwords, nil +} diff --git a/browser/safari/profile.go b/browser/safari/profile.go index c69055f..1709f4c 100644 --- a/browser/safari/profile.go +++ b/browser/safari/profile.go @@ -1,14 +1,24 @@ package safari import ( + "context" + "os" + "path" "path/filepath" "github.com/moond4rk/hackbrowserdata/filemanager" + ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" + isafari "github.com/moond4rk/hackbrowserdata/internal/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" "github.com/moond4rk/hackbrowserdata/types" ) +// snapshotDirID names the one user data dir in a profile's private snapshot, whose root is ~/Library. +const snapshotDirID = "library" + // profile is one Safari profile — the leaf extraction unit. Passwords come from // the shared macOS Keychain; everything else reads from the profile's directories. type profile struct { @@ -27,75 +37,160 @@ func (p *profile) dir() string { return filepath.Join(p.ctx.container, "Safari", "Profiles", p.ctx.uuidUpper) } -func (p *profile) extract(categories []category.Category, keychainPassword string) *types.BrowserData { - session, err := filemanager.NewSession() - if err != nil { - log.Debugf("new session for %s: %v", p.label(), err) - return &types.BrowserData{} +// asBase is this profile as the Safari base sees it: ~/Library as the user data dir, the Safari directory as the +// default profile's Dir, and a named profile's own directory under the container as its Dir. +func (p *profile) asBase() (ibrowser.UserDataDir, ibrowser.Profile) { + library := filepath.Dir(p.ctx.legacyHome) + def := ibrowser.Profile{Name: "default", Dir: filepath.Base(p.ctx.legacyHome)} + prof := def + if !p.ctx.isDefault() { + prof = ibrowser.Profile{Name: p.ctx.name, Dir: "Containers/com.apple.Safari/Data/Library/Safari/Profiles/" + p.ctx.uuidUpper} } - defer session.Cleanup() - - tempPaths := p.acquireFiles(session, categories) + return ibrowser.UserDataDir{Path: library, Profiles: []ibrowser.Profile{def, prof}}, prof +} +// extract captures the profile's files into a private snapshot of ~/Library and runs the Safari base's extractors on +// it; passwords keep today's direct keychain read until the switch-over. +func (p *profile) extract(categories []category.Category, keychainPassword string) *types.BrowserData { data := &types.BrowserData{} + d, err := snapshot.Temp() + if err != nil { + log.Debugf("new snapshot for %s: %v", p.label(), err) + return data + } + defer func() { + if err := d.Close(); err != nil { + log.Debugf("remove snapshot for %s: %v", p.label(), err) + } + }() + + dir, prof := p.asBase() + extractors := isafari.Extractors(dir, prof, passwordKeychain(keychainPassword)) + ctx := context.Background() + if err := d.Capture(ctx, snapshotFiles(dir.Path, prof, extractors, categories)); err != nil { + log.Debugf("capture %s: %v", p.label(), err) + return data + } + ps := ibrowser.NewProfileSnapshot(d.Snapshot(snapshotDirID), prof, nil) + out := &dataCollector{data: data, label: p.label()} for _, cat := range categories { - // Keychain is user-scope, not per-profile — attribute only to default to avoid duplicates. - if cat == category.Password { - if p.ctx.isDefault() { - p.extractCategory(data, cat, "", keychainPassword) - } - continue - } - // Extension plists (AppExtensions + WebExtensions) live directly in the container - // and are read in-place; attribute to default only until per-profile layouts are verified. - if cat == category.Extension { - if p.ctx.isDefault() { - p.extractCategory(data, cat, "", keychainPassword) - } - continue - } - path, ok := tempPaths[cat] + ex, ok := extractors[cat] if !ok { continue } - p.extractCategory(data, cat, path, keychainPassword) + if err := ex.Extract(ctx, ps, out); err != nil { + log.Debugf("extract %s for %s: %v", cat, p.label(), err) + } } return data } +// snapshotFiles lists, once each, the first candidate on disk of every source the categories read. +func snapshotFiles(library string, prof ibrowser.Profile, extractors ibrowser.Extractors, categories []category.Category) []snapshot.File { + var files []snapshot.File + seen := make(map[string]bool) + for _, cat := range categories { + for _, src := range extractors[cat].Sources { + rel, ok := firstOnDisk(library, prof, src) + if !ok || seen[rel] { + continue + } + seen[rel] = true + files = append(files, snapshot.File{DirID: snapshotDirID, From: library, Rel: rel, IsDir: src.IsDir}) + } + } + return files +} + +func firstOnDisk(library string, prof ibrowser.Profile, src ibrowser.Source) (string, bool) { + for _, rel := range src.Paths { + rel = path.Join(prof.Dir, rel) + info, err := os.Stat(filepath.Join(library, filepath.FromSlash(rel))) + if err == nil && info.IsDir() == src.IsDir { + return rel, true + } + } + return "", false +} + +// dataCollector files the records the Safari base hands back into today's per-category slices. +type dataCollector struct { + data *types.BrowserData + label string +} + +func (c *dataCollector) Add(r record.Record) { + switch v := r.(type) { + case *record.Login: + c.data.Passwords = append(c.data.Passwords, *v) + case *record.Cookie: + c.data.Cookies = append(c.data.Cookies, *v) + case *record.Bookmark: + c.data.Bookmarks = append(c.data.Bookmarks, *v) + case *record.History: + c.data.Histories = append(c.data.Histories, *v) + case *record.Download: + c.data.Downloads = append(c.data.Downloads, *v) + case *record.Extension: + c.data.Extensions = append(c.data.Extensions, *v) + case *record.LocalStorage: + c.data.LocalStorage = append(c.data.LocalStorage, *v) + } +} + +func (c *dataCollector) Fail(err error) { log.Debugf("%s: %v", c.label, err) } + +// count keeps today's counting queries for history and localStorage. Safari's other counters always counted what +// extraction parses, so they count the base's records. func (p *profile) count(categories []category.Category, keychainPassword string) map[category.Category]int { + counts := make(map[category.Category]int) + var parsed, queried []category.Category + for _, cat := range categories { + if cat == category.History || cat == category.LocalStorage { + queried = append(queried, cat) + } else { + parsed = append(parsed, cat) + } + } + if len(parsed) > 0 { + data := p.extract(parsed, keychainPassword) + for _, cat := range parsed { + counts[cat] = recordCount(data, cat) + } + } + if len(queried) == 0 { + return counts + } + session, err := filemanager.NewSession() if err != nil { log.Debugf("new session for %s: %v", p.label(), err) - return nil + return counts } defer session.Cleanup() - - tempPaths := p.acquireFiles(session, categories) - - counts := make(map[category.Category]int) - for _, cat := range categories { - if cat == category.Password { - if p.ctx.isDefault() { - counts[cat] = p.countCategory(cat, "", keychainPassword) - } - continue - } - if cat == category.Extension { - if p.ctx.isDefault() { - counts[cat] = p.countCategory(cat, "", keychainPassword) - } - continue - } - path, ok := tempPaths[cat] - if !ok { - continue - } - counts[cat] = p.countCategory(cat, path, keychainPassword) + for cat, file := range p.acquireFiles(session, queried) { + counts[cat] = p.countCategory(cat, file) } return counts } +func recordCount(data *types.BrowserData, cat category.Category) int { + switch cat { + case category.Password: + return len(data.Passwords) + case category.Cookie: + return len(data.Cookies) + case category.Bookmark: + return len(data.Bookmarks) + case category.Download: + return len(data.Downloads) + case category.Extension: + return len(data.Extensions) + default: + return 0 + } +} + func (p *profile) acquireFiles(session *filemanager.Session, categories []category.Category) map[category.Category]string { tempPaths := make(map[category.Category]string) for _, cat := range categories { @@ -113,51 +208,16 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []catego return tempPaths } -func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, path, keychainPassword string) { - var err error - switch cat { - case category.Password: - data.Passwords, err = extractPasswords(keychainPassword) - case category.History: - data.Histories, err = extractHistories(path) - case category.Cookie: - data.Cookies, err = extractCookies(path) - case category.Bookmark: - data.Bookmarks, err = extractBookmarks(path) - case category.Download: - data.Downloads, err = extractDownloads(path, p.ctx.downloadOwnerUUID()) - case category.LocalStorage: - data.LocalStorage, err = extractLocalStorage(path) - case category.Extension: - data.Extensions, err = extractExtensions(p.ctx.container) - default: - return - } - if err != nil { - log.Debugf("extract %s for %s: %v", cat, p.label(), err) - } -} - -func (p *profile) countCategory(cat category.Category, path, keychainPassword string) int { +func (p *profile) countCategory(cat category.Category, file string) int { var count int var err error switch cat { - case category.Password: - count, err = countPasswords(keychainPassword) case category.History: - count, err = countHistories(path) - case category.Cookie: - count, err = countCookies(path) - case category.Bookmark: - count, err = countBookmarks(path) - case category.Download: - count, err = countDownloads(path, p.ctx.downloadOwnerUUID()) + count, err = countHistories(file) case category.LocalStorage: - count, err = countLocalStorage(path) - case category.Extension: - count, err = countExtensions(p.ctx.container) + count, err = countLocalStorage(file) default: - // Unsupported categories silently return 0. + // The other categories are counted from their extracted records. } if err != nil { log.Debugf("count %s for %s: %v", cat, p.label(), err) diff --git a/browser/safari/profile_test.go b/browser/safari/profile_test.go index 0acfa83..e89eca7 100644 --- a/browser/safari/profile_test.go +++ b/browser/safari/profile_test.go @@ -1,8 +1,11 @@ package safari import ( + "os" + "path/filepath" "testing" + "github.com/moond4rk/plist" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -10,147 +13,112 @@ import ( "github.com/moond4rk/hackbrowserdata/types" ) -func TestCountCategory(t *testing.T) { - t.Run("History", func(t *testing.T) { - path := createTestDB(t, "History.db", - []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, - insertHistoryItem(1, "https://example.com", "example.com", 1), - ) - p := &profile{} - assert.Equal(t, 1, p.countCategory(category.History, path, "")) - }) +const fixtureWorkUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - t.Run("Cookie", func(t *testing.T) { - path := buildTestBinaryCookies(t, []testCookie{ - {domain: ".example.com", name: "a", path: "/", value: "1", expires: 2000000000.0, creation: 700000000.0}, - {domain: ".go.dev", name: "b", path: "/", value: "2", expires: 2000000000.0, creation: 700000000.0}, - }) - p := &profile{} - assert.Equal(t, 2, p.countCategory(category.Cookie, path, "")) - }) - - t.Run("Bookmark", func(t *testing.T) { - path := buildTestBookmarksPlist(t, safariBookmark{ - Type: bookmarkTypeList, - Children: []safariBookmark{ - {Type: bookmarkTypeLeaf, URLString: "https://a.com", URIDictionary: uriDictionary{Title: "A"}}, - {Type: bookmarkTypeLeaf, URLString: "https://b.com", URIDictionary: uriDictionary{Title: "B"}}, - }, - }) - p := &profile{} - assert.Equal(t, 2, p.countCategory(category.Bookmark, path, "")) - }) - - t.Run("Download", func(t *testing.T) { - path := buildTestDownloadsPlist(t, safariDownloads{ - DownloadHistory: []safariDownloadEntry{ - {URL: "https://example.com/file.zip", Path: "/tmp/file.zip", TotalBytes: 100}, - }, - }) - p := &profile{} - assert.Equal(t, 1, p.countCategory(category.Download, path, "")) - }) - - t.Run("LocalStorage", func(t *testing.T) { - dir := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ - "https://example.com": {{Key: "k1", Value: "v1"}, {Key: "k2", Value: "v2"}}, - "https://go.dev": {{Key: "theme", Value: "dark"}}, - }) - p := &profile{} - assert.Equal(t, 3, p.countCategory(category.LocalStorage, dir, "")) - }) - - t.Run("UnsupportedCategory", func(t *testing.T) { - p := &profile{} - assert.Equal(t, 0, p.countCategory(category.CreditCard, "unused", "")) - assert.Equal(t, 0, p.countCategory(category.SessionStorage, "unused", "")) - }) +func writePlist(t *testing.T, path string, v any) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + defer f.Close() + require.NoError(t, plist.NewBinaryEncoder(f).Encode(v)) } -func TestExtractCategory(t *testing.T) { - t.Run("History", func(t *testing.T) { - path := createTestDB(t, "History.db", - []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, - insertHistoryItem(1, "https://example.com", "example.com", 3), - insertHistoryItem(2, "https://go.dev", "go.dev", 1), - insertHistoryVisit(1, 1, 700000000.0, "Example"), - insertHistoryVisit(2, 2, 700000000.0, "Go"), - ) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.History, path, "") +func installDB(t *testing.T, dst, src string) { + t.Helper() + data, err := os.ReadFile(src) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(filepath.Dir(dst), 0o755)) + require.NoError(t, os.WriteFile(dst, data, 0o644)) +} - require.Len(t, data.Histories, 2) - assert.ElementsMatch(t, []int{3, 1}, []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount}) - }) - - t.Run("Cookie", func(t *testing.T) { - path := buildTestBinaryCookies(t, []testCookie{ - { - domain: ".example.com", name: "session", path: "/", value: "abc", - secure: true, httpOnly: true, expires: 2000000000.0, creation: 700000000.0, - }, - }) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.Cookie, path, "") +// libraryFixture is a ~/Library with a default and a named profile: bookmarks belong to the default one only, and the +// shared Downloads.plist holds one entry for each. +func libraryFixture(t *testing.T) string { + t.Helper() + library := t.TempDir() + legacyHome := filepath.Join(library, "Safari") + container := filepath.Join(library, "Containers", "com.apple.Safari", "Data", "Library") - require.Len(t, data.Cookies, 1) - assert.Equal(t, ".example.com", data.Cookies[0].Host) - assert.Equal(t, "session", data.Cookies[0].Name) - assert.True(t, data.Cookies[0].IsSecure) - assert.True(t, data.Cookies[0].IsHTTPOnly) + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: fixtureWorkUUID, title: "work"}}) + installDB(t, filepath.Join(legacyHome, "History.db"), createTestDB(t, "History.db", + []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, + insertHistoryItem(1, "https://home.test/a", "home.test", 3), + insertHistoryItem(2, "https://home.test/b", "home.test", 1), + )) + installDB(t, filepath.Join(container, "Safari", "Profiles", fixtureWorkUUID, "History.db"), createTestDB(t, "History.db", + []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, + insertHistoryItem(1, "https://work.test/", "work.test", 5), + )) + writePlist(t, filepath.Join(legacyHome, "Bookmarks.plist"), map[string]any{ + "WebBookmarkType": "WebBookmarkTypeList", + "Children": []any{map[string]any{ + "WebBookmarkType": "WebBookmarkTypeList", + "Title": "BookmarksBar", + "Children": []any{map[string]any{ + "WebBookmarkType": "WebBookmarkTypeLeaf", + "URLString": "https://go.dev/", + "URIDictionary": map[string]any{"title": "Go"}, + }}, + }}, }) - - t.Run("Bookmark", func(t *testing.T) { - path := buildTestBookmarksPlist(t, safariBookmark{ - Type: bookmarkTypeList, - Children: []safariBookmark{ - {Type: bookmarkTypeLeaf, URLString: "https://github.com", URIDictionary: uriDictionary{Title: "GitHub"}}, - }, - }) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.Bookmark, path, "") - - require.Len(t, data.Bookmarks, 1) - assert.Equal(t, "GitHub", data.Bookmarks[0].Name) - assert.Equal(t, "https://github.com", data.Bookmarks[0].URL) + writePlist(t, filepath.Join(legacyHome, "Downloads.plist"), map[string]any{ + "DownloadHistory": []any{ + map[string]any{"DownloadEntryURL": "https://home.test/a.zip", "DownloadEntryPath": "/tmp/a.zip", "DownloadEntryProfileUUIDStringKey": "DefaultProfile"}, + map[string]any{"DownloadEntryURL": "https://work.test/b.zip", "DownloadEntryPath": "/tmp/b.zip", "DownloadEntryProfileUUIDStringKey": fixtureWorkUUID}, + }, }) + return legacyHome +} - t.Run("Download", func(t *testing.T) { - path := buildTestDownloadsPlist(t, safariDownloads{ - DownloadHistory: []safariDownloadEntry{ - {URL: "https://example.com/file.zip", Path: "/tmp/file.zip", TotalBytes: 1024}, - }, - }) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.Download, path, "") +func fixtureBrowser(t *testing.T) *Browser { + t.Helper() + b, err := NewBrowser(types.BrowserConfig{Name: "Safari", Kind: types.Safari, UserDataDir: libraryFixture(t)}) + require.NoError(t, err) + require.NotNil(t, b) + return b +} - require.Len(t, data.Downloads, 1) - assert.Equal(t, "https://example.com/file.zip", data.Downloads[0].URL) - assert.Equal(t, int64(1024), data.Downloads[0].TotalBytes) - }) +// Password is left out: it would read this machine's login keychain. +var adapterCategories = []category.Category{category.History, category.Bookmark, category.Download, category.Cookie, category.Extension} - t.Run("LocalStorage", func(t *testing.T) { - dir := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ - "https://github.com": {{Key: "theme", Value: "dark"}}, - }) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.LocalStorage, dir, "") +func TestExtract_RunsTheBaseOnEachProfile(t *testing.T) { + results, err := fixtureBrowser(t).Extract(adapterCategories) + require.NoError(t, err) + require.Len(t, results, 2) - require.Len(t, data.LocalStorage, 1) - assert.Equal(t, "https://github.com", data.LocalStorage[0].URL) - assert.Equal(t, "theme", data.LocalStorage[0].Key) - assert.Equal(t, "dark", data.LocalStorage[0].Value) - }) + byName := map[string]*types.BrowserData{} + for _, r := range results { + byName[r.Name] = r.Data + } + require.Contains(t, byName, "default") + require.Contains(t, byName, "work") + assert.Len(t, byName["default"].Histories, 2) + assert.Len(t, byName["default"].Bookmarks, 1) + require.Len(t, byName["default"].Downloads, 1) + assert.Equal(t, "https://home.test/a.zip", byName["default"].Downloads[0].URL) + assert.Len(t, byName["work"].Histories, 1) + assert.Empty(t, byName["work"].Bookmarks, "Bookmarks.plist belongs to the default profile") + require.Len(t, byName["work"].Downloads, 1) + assert.Equal(t, "https://work.test/b.zip", byName["work"].Downloads[0].URL) +} - t.Run("UnsupportedCategory", func(t *testing.T) { - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.CreditCard, "unused", "") - assert.Empty(t, data.CreditCards) - }) +func TestCountEntries_MatchesExtract(t *testing.T) { + results, err := fixtureBrowser(t).CountEntries(adapterCategories) + require.NoError(t, err) + require.Len(t, results, 2) + for _, r := range results { + switch r.Name { + case "default": + assert.Equal(t, 2, r.Counts[category.History]) + assert.Equal(t, 1, r.Counts[category.Bookmark]) + assert.Equal(t, 1, r.Counts[category.Download]) + case "work": + assert.Equal(t, 1, r.Counts[category.History]) + assert.Equal(t, 0, r.Counts[category.Bookmark]) + assert.Equal(t, 1, r.Counts[category.Download]) + default: + t.Fatalf("unexpected profile %q", r.Name) + } + } } diff --git a/browser/safari/profiles.go b/browser/safari/profiles.go index 12ec444..f3cf4d7 100644 --- a/browser/safari/profiles.go +++ b/browser/safari/profiles.go @@ -25,16 +25,6 @@ type profileContext struct { func (p profileContext) isDefault() bool { return p.uuidUpper == "" } -// downloadOwnerUUID is the value Safari writes into DownloadEntryProfileUUIDStringKey -// for downloads that belong to this profile. The default profile uses the sentinel -// "DefaultProfile"; named profiles use their uppercase UUID. -func (p profileContext) downloadOwnerUUID() string { - if p.isDefault() { - return defaultProfileSentinel - } - return p.uuidUpper -} - // SafariTabs.db lists profiles in bookmarks rows with subtype=2. external_uuid "DefaultProfile" // is the sentinel for the implicit default, which has no per-UUID directory. const ( diff --git a/browser/safari/profiles_test.go b/browser/safari/profiles_test.go deleted file mode 100644 index 808e9c2..0000000 --- a/browser/safari/profiles_test.go +++ /dev/null @@ -1,259 +0,0 @@ -package safari - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/internal/category" -) - -// containerPaths returns (legacyHome, container) for a fake ~/Library tree -// anchored at root. Call sites use this to mirror the production layout where -// legacyHome sits next to Containers/. -func containerPaths(root string) (string, string) { - legacyHome := filepath.Join(root, "Safari") - container := filepath.Join(root, "Containers", "com.apple.Safari", "Data", "Library") - return legacyHome, container -} - -func TestDiscoverSafariProfiles_DefaultOnly(t *testing.T) { - library := t.TempDir() - legacyHome, _ := containerPaths(library) - mkFile(t, legacyHome, "History.db") - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 1) - assert.Equal(t, "default", got[0].name) - assert.Empty(t, got[0].uuidUpper) - assert.Empty(t, got[0].uuidLower) -} - -func TestDiscoverSafariProfiles_WithNamedProfile(t *testing.T) { - const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - mkFile(t, container, "Safari", "Profiles", uuid, "History.db") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: "DefaultProfile", title: ""}, - {uuid: uuid, title: "work"}, - }) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 2) - assert.Equal(t, "default", got[0].name) - assert.Equal(t, "work", got[1].name) - assert.Equal(t, uuid, got[1].uuidUpper) - assert.Equal(t, strings.ToLower(uuid), got[1].uuidLower) -} - -func TestDiscoverSafariProfiles_EmptyTitleFallbackToUUID(t *testing.T) { - const uuid = "ABCDEF01-2345-6789-ABCD-EF0123456789" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: uuid, title: ""}, - }) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 2) - assert.Equal(t, "profile-abcdef01", got[1].name) -} - -func TestDiscoverSafariProfiles_OrphanUUIDWithoutDBEntry(t *testing.T) { - // Profile directory with a History.db exists on disk but is absent from - // SafariTabs.db. When the DB is readable and doesn't mention it, we trust - // the DB — the orphan stays hidden because production filters profiles - // with no resolvable data in NewBrowser anyway. Here we assert discovery - // returns only what the DB declares. - const dbUUID = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" - const orphanUUID = "11111111-2222-3333-4444-555555555555" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - mkFile(t, container, "Safari", "Profiles", dbUUID, "History.db") - mkFile(t, container, "Safari", "Profiles", orphanUUID, "AppExtensions", "Extensions.plist") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: dbUUID, title: "declared"}, - }) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 2) - assert.Equal(t, "default", got[0].name) - assert.Equal(t, "declared", got[1].name) -} - -func TestDiscoverSafariProfiles_EmptyDBIsAuthoritative(t *testing.T) { - // SafariTabs.db exists and is readable but contains no named-profile rows. - // A stray Profiles// directory on disk must NOT sneak in via the - // ReadDir fallback — the DB is the authoritative source of truth. - const strayUUID = "99999999-AAAA-BBBB-CCCC-DDDDDDDDDDDD" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - mkFile(t, container, "Safari", "Profiles", strayUUID, "History.db") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), nil) // zero rows - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 1) - assert.Equal(t, "default", got[0].name) -} - -func TestDiscoverSafariProfiles_MissingDBFallsBackToReadDir(t *testing.T) { - // SafariTabs.db absent → enumerate Safari/Profiles/ and synthesize names. - const uuid = "11111111-2222-3333-4444-555555555555" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - mkFile(t, container, "Safari", "Profiles", uuid, "History.db") - // Deliberately also drop a non-UUID directory that must be ignored. - require.NoError(t, os.MkdirAll(filepath.Join(container, "Safari", "Profiles", "Bogus"), 0o755)) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 2) - assert.Equal(t, "default", got[0].name) - assert.Equal(t, "profile-11111111", got[1].name) - assert.Equal(t, uuid, got[1].uuidUpper) -} - -func TestDiscoverSafariProfiles_DuplicateTitlesDisambiguate(t *testing.T) { - const uuidA = "AAAAAAAA-0000-0000-0000-000000000001" - const uuidB = "BBBBBBBB-0000-0000-0000-000000000002" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: uuidA, title: "team"}, - {uuid: uuidB, title: "team"}, - }) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 3) - // Order mirrors DB insertion order; the second "team" becomes "team-2". - assert.Equal(t, "default", got[0].name) - assert.Equal(t, "team", got[1].name) - assert.Equal(t, "team-2", got[2].name) -} - -func TestDiscoverSafariProfiles_UUIDCaseNormalisation(t *testing.T) { - // SafariTabs.db always stores UUIDs uppercase (verified on real Mac). - // WebKit/WebsiteDataStore uses lowercase — we must carry both. - const uuid = "FEDCBA98-7654-3210-FEDC-BA9876543210" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: uuid, title: "alpha"}, - }) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 2) - assert.Equal(t, uuid, got[1].uuidUpper) - assert.Equal(t, strings.ToLower(uuid), got[1].uuidLower) -} - -func TestDiscoverSafariProfiles_DefaultProfileSentinelIgnored(t *testing.T) { - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: defaultProfileSentinel, title: ""}, - }) - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 1) - assert.Equal(t, "default", got[0].name) -} - -func TestDiscoverSafariProfiles_EmptyProfileDirectoryFiltersOutInNewBrowsers(t *testing.T) { - // Matches the real 4E2D8DD0 orphan on the author's Mac: a profile dir - // listed in neither SafariTabs.db nor containing any extractable data. - // Discovery without the DB surfaces it; NewBrowser then drops it when - // resolveSourcePaths yields zero matches. - const uuid = "4E2D8DD0-A7D2-4684-939A-898B7675C700" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - mkFile(t, legacyHome, "History.db") - mkFile(t, container, "Safari", "Profiles", uuid, "AppExtensions", "Extensions.plist") - - got := discoverSafariProfiles(legacyHome) - require.Len(t, got, 2) // discovery includes it … - paths := resolveSourcePaths(buildSources(got[1])) - assert.Empty(t, paths) // … but no supported data resolves for it. -} - -func TestResolveProfileName(t *testing.T) { - tests := []struct { - title string - uuid string - want string - }{ - {"work", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "work"}, - {" spaced ", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "spaced"}, - {"", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "profile-5604e6f5"}, - {"with/slash", "AAAAAAAA-0000-0000-0000-000000000000", "with_slash"}, - {"中文", "AAAAAAAA-0000-0000-0000-000000000000", "中文"}, - } - for _, tt := range tests { - t.Run(tt.title, func(t *testing.T) { - assert.Equal(t, tt.want, resolveProfileName(tt.title, tt.uuid)) - }) - } -} - -func TestBuildSources_DefaultProfile(t *testing.T) { - library := t.TempDir() - legacyHome, container := containerPaths(library) - - p := profileContext{legacyHome: legacyHome, container: container} - sources := buildSources(p) - - assert.Equal(t, filepath.Join(legacyHome, "History.db"), sources[category.History][0].abs) - assert.Equal(t, filepath.Join(legacyHome, "Bookmarks.plist"), sources[category.Bookmark][0].abs) - assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[category.Download][0].abs) - require.Len(t, sources[category.Cookie], 2) - assert.Equal(t, filepath.Join(container, "Cookies", "Cookies.binarycookies"), sources[category.Cookie][0].abs) - assert.Equal(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), sources[category.Cookie][1].abs) -} - -func TestBuildSources_NamedProfile(t *testing.T) { - const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - library := t.TempDir() - legacyHome, container := containerPaths(library) - - p := profileContext{ - name: "work", - uuidUpper: uuid, - uuidLower: strings.ToLower(uuid), - legacyHome: legacyHome, - container: container, - } - sources := buildSources(p) - - assert.Equal(t, - filepath.Join(container, "Safari", "Profiles", uuid, "History.db"), - sources[category.History][0].abs) - assert.Equal(t, - filepath.Join(container, "WebKit", "WebsiteDataStore", strings.ToLower(uuid), "Cookies", "Cookies.binarycookies"), - sources[category.Cookie][0].abs) - // Download points at the shared plist — filtering by DownloadEntryProfileUUIDStringKey - // happens inside extractDownloads, not at the path layer. - assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[category.Download][0].abs) - // Bookmark is still shared with no per-entry profile tag, so it's attributed to default only. - assert.NotContains(t, sources, category.Bookmark) -} diff --git a/browser/safari/testutil_test.go b/browser/safari/testutil_test.go index dbd0d9a..98614cd 100644 --- a/browser/safari/testutil_test.go +++ b/browser/safari/testutil_test.go @@ -6,8 +6,6 @@ import ( "fmt" "os" "path/filepath" - "strconv" - "strings" "testing" "unicode/utf16" @@ -159,11 +157,7 @@ func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, fra frameDir := filepath.Join(root, topHash, frameHash) require.NoError(t, os.MkdirAll(filepath.Join(frameDir, webkitLocalStorageSubdir), 0o755)) - require.NoError(t, os.WriteFile( - filepath.Join(frameDir, webkitOriginFile), - encodeOriginFile(topOrigin, frameOrigin), - 0o644, - )) + require.NoError(t, os.WriteFile(filepath.Join(frameDir, webkitOriginFile), []byte(topOrigin+" "+frameOrigin), 0o644)) dbPath := filepath.Join(frameDir, webkitLocalStorageSubdir, webkitLocalStorageDB) db, err := sql.Open("sqlite", dbPath) @@ -180,56 +174,6 @@ func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, fra require.NoError(t, db.Close()) } -// encodeOriginFile mirrors WebKit's SecurityOrigin binary serialization. Layout per origin -// block: length-prefixed scheme record, length-prefixed host record, then a port marker -// (0x00 for the scheme default, or 0x01 + uint16_le port). Two blocks back-to-back: top-frame -// then frame. -func encodeOriginFile(topOrigin, frameOrigin string) []byte { - var buf []byte - buf = appendOriginBlock(buf, topOrigin) - buf = appendOriginBlock(buf, frameOrigin) - return buf -} - -func appendOriginBlock(buf []byte, originURL string) []byte { - scheme, host, port := splitTestOriginURL(originURL) - buf = appendOriginRecord(buf, scheme) - buf = appendOriginRecord(buf, host) - if port == 0 { - buf = append(buf, originPortDefaultMarker) - return buf - } - buf = append(buf, originPortExplicitFlag) - portBytes := make([]byte, 2) - binary.LittleEndian.PutUint16(portBytes, port) - return append(buf, portBytes...) -} - -func appendOriginRecord(buf []byte, s string) []byte { - lenBytes := make([]byte, 4) - binary.LittleEndian.PutUint32(lenBytes, uint32(len(s))) - buf = append(buf, lenBytes...) - buf = append(buf, originEncASCII) - return append(buf, []byte(s)...) -} - -// splitTestOriginURL parses "https://example.com[:port]" into (scheme, host, port). -// Port 0 means the URL had no explicit port (use scheme default). -func splitTestOriginURL(u string) (scheme, host string, port uint16) { - idx := strings.Index(u, "://") - if idx < 0 { - return "", u, 0 - } - scheme = u[:idx] - rest := u[idx+3:] - if colon := strings.LastIndex(rest, ":"); colon >= 0 { - if p, err := strconv.ParseUint(rest[colon+1:], 10, 16); err == nil { - return scheme, rest[:colon], uint16(p) - } - } - return scheme, rest, 0 -} - // writeLocalStorageDB creates a minimal localstorage.sqlite3 at path with ItemTable populated // from items. When addNullKey is true, a NULL-key row is inserted first to exercise the // skip-NULL-key logic in readLocalStorageFile / countLocalStorageFile. This is a direct-DB diff --git a/cmd/hack-browser-data/pipeline_golden_test.go b/cmd/hack-browser-data/pipeline_golden_test.go index 7944822..f4db91b 100644 --- a/cmd/hack-browser-data/pipeline_golden_test.go +++ b/cmd/hack-browser-data/pipeline_golden_test.go @@ -3,6 +3,7 @@ package main import ( "context" "path/filepath" + "runtime" "testing" "github.com/stretchr/testify/require" @@ -41,6 +42,18 @@ func TestPipelineGoldenFirefox(t *testing.T) { }) } +func TestPipelineGoldenSafari(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("Safari is in the browser table on macOS only") + } + home := t.TempDir() + safariFixtureLibrary(t, filepath.Join(home, "Library")) + + assertExtractGoldens(t, "extract-safari", func(t *testing.T, format string) string { + return pipelineGoldenRun(t, home, nil, format) + }) +} + func pipelineGoldenRun(t *testing.T, home string, keys map[ibrowser.DirID]masterkey.Set, format string) string { t.Helper() out := t.TempDir() diff --git a/internal/app/discover.go b/internal/app/discover.go index 0671079..876207f 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -1,9 +1,12 @@ package app import ( + "fmt" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" "github.com/moond4rk/hackbrowserdata/internal/browser/firefox" + "github.com/moond4rk/hackbrowserdata/internal/browser/safari" ) // Discovery is what Discover found: the user data dirs, and an error result for each browser whose data could not be @@ -33,26 +36,33 @@ func Discover(req Request) Discovery { return d } -// discover and extractorsOf dispatch on the base here, because the base packages import browser and so browser cannot -// call them. +// discover and extractorsWith dispatch on the base here, because the base packages import browser and so browser +// cannot call them. func discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { switch def.Base { case browser.Chromium: return chromium.Discover(def, opts) case browser.Firefox: return firefox.Discover(def, opts) + case browser.Safari: + return safari.Discover(def, opts) default: - return nil, nil // Safari is not on the pipeline yet + return nil, fmt.Errorf("%s: no base package", def.ID) } } -func extractorsOf(dir browser.UserDataDir, p browser.Profile) browser.Extractors { - switch dir.Def.Base { - case browser.Chromium: - return chromium.Extractors(dir, p) - case browser.Firefox: - return firefox.Extractors(dir, p) - default: - return nil +// extractorsWith hands Safari the run's login keychain, which its default profile's password extractor reads. +func extractorsWith(kc safari.LoginKeychain) extractorsFunc { + return func(dir browser.UserDataDir, p browser.Profile) browser.Extractors { + switch dir.Def.Base { + case browser.Chromium: + return chromium.Extractors(dir, p) + case browser.Firefox: + return firefox.Extractors(dir, p) + case browser.Safari: + return safari.Extractors(dir, p, kc) + default: + return nil + } } } diff --git a/internal/app/execute.go b/internal/app/execute.go index 8c11068..2bc31e7 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -9,6 +9,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/masterkey" @@ -16,17 +17,25 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) +// runKeychain is the run's one login keychain, read by the Chromium v10 retriever and the Safari password extractor; +// nil off macOS. +type runKeychain interface { + masterkey.LoginKeychain + safari.LoginKeychain +} + // keySource retrieves one user data dir's Chromium keys, reading what it needs from the dir's snapshot. type keySource func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) // Execute runs Capture, Extract, and Export one user data dir at a time, so at most one dir's copies are on disk. Its // error means the run could not finish, such as a failed output write; every other failure is a Result. func Execute(ctx context.Context, p Plan, req Request) (Summary, error) { + kc := loginKeychain(req) keys := dumpKeys(req.Keys) if req.Keys == nil { - keys = machineKeys(loginKeychain(req)) + keys = machineKeys(kc) } - return execute(ctx, p, req, extractorsOf, keys) + return execute(ctx, p, req, extractorsWith(kc), keys) } func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc, keys keySource) (Summary, error) { diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index 4f21792..bc16b90 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -155,14 +155,14 @@ func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) { touch(t, path, "Default", "Network", "Cookies") dir := browser.UserDataDir{ID: "chrome", Def: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}} - run(t, extractorsOf, noKeys(t), []category.Category{category.History, category.Download}, dir) + run(t, extractorsWith(nil), noKeys(t), []category.Category{category.History, category.Download}, dir) calls := 0 counting := func(context.Context, browser.UserDataDir, snapshot.Snapshot) (masterkey.Set, error) { calls++ return nil, nil } - run(t, extractorsOf, counting, []category.Category{category.Cookie, category.History}, dir) + run(t, extractorsWith(nil), counting, []category.Category{category.Cookie, category.History}, dir) assert.Equal(t, 1, calls) } diff --git a/internal/app/keychain_darwin.go b/internal/app/keychain_darwin.go index e61a0d2..6804336 100644 --- a/internal/app/keychain_darwin.go +++ b/internal/app/keychain_darwin.go @@ -7,11 +7,10 @@ import ( "path/filepath" "github.com/moond4rk/hackbrowserdata/internal/keychain" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // loginKeychain builds the run's one login keychain without opening it, so a run that never decrypts never prompts. -func loginKeychain(req Request) masterkey.LoginKeychain { +func loginKeychain(req Request) runKeychain { password := keychain.PasswordFunc(req.KeychainPassword) if password == nil { password = func(context.Context) (string, error) { return "", nil } diff --git a/internal/app/keychain_other.go b/internal/app/keychain_other.go index ac430e7..668adb4 100644 --- a/internal/app/keychain_other.go +++ b/internal/app/keychain_other.go @@ -2,6 +2,4 @@ package app -import "github.com/moond4rk/hackbrowserdata/internal/masterkey" - -func loginKeychain(Request) masterkey.LoginKeychain { return nil } +func loginKeychain(Request) runKeychain { return nil } diff --git a/internal/app/plan.go b/internal/app/plan.go index ba93c02..c3910a8 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -30,8 +30,9 @@ type Plan struct { type extractorsFunc func(browser.UserDataDir, browser.Profile) browser.Extractors // NewPlan crosses every discovered profile with the requested categories. It only stats files; it opens nothing. +// Planning reads only the extractors' sources, so it needs no keychain. func NewPlan(d Discovery, req Request) Plan { - return newPlan(d, req, extractorsOf) + return newPlan(d, req, extractorsWith(nil)) } func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan { @@ -66,8 +67,12 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan { } // locate finds each source's first candidate on disk. An extraction needs every required source and at least one of -// the profile's own; a shared one such as Local State never makes it present by itself. +// the profile's own; a shared one such as Local State never makes it present by itself. An extraction that reads no +// file, such as Safari's keychain passwords, always runs. func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool) { + if len(sources) == 0 { + return nil, true + } var files []snapshot.File present := false for _, src := range sources { diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index 9e429c1..18839b9 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -102,3 +102,16 @@ func TestNewPlan_UnsupportedCategory(t *testing.T) { got.Skipped) assert.Empty(t, got.Extractions) } + +// Safari's passwords come from the keychain: an extractor that reads no file is never absent. +func TestNewPlan_ExtractorWithoutSourcesRuns(t *testing.T) { + dir := browser.UserDataDir{ID: "safari", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "default", Dir: "Safari"}}} + keychainOnly := func(browser.UserDataDir, browser.Profile) browser.Extractors { + return browser.Extractors{category.Password: {}} + } + + got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.Password}}, keychainOnly) + assert.Equal(t, []Extraction{{DirID: "safari", Profile: "default", Category: category.Password}}, got.Extractions) + assert.Empty(t, got.Files) + assert.Empty(t, got.Skipped) +} diff --git a/browser/safari/extract_bookmark.go b/internal/browser/safari/extract_bookmark.go similarity index 82% rename from browser/safari/extract_bookmark.go rename to internal/browser/safari/extract_bookmark.go index 72e0660..cc543a8 100644 --- a/browser/safari/extract_bookmark.go +++ b/internal/browser/safari/extract_bookmark.go @@ -7,6 +7,7 @@ import ( "github.com/moond4rk/plist" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" ) @@ -28,21 +29,22 @@ const ( bookmarkTypeList = "WebBookmarkTypeList" ) -func extractBookmarks(path string) ([]record.Bookmark, error) { +func extractBookmarks(path string, out browser.Collector) error { f, err := os.Open(path) if err != nil { - return nil, fmt.Errorf("open bookmarks: %w", err) + return fmt.Errorf("open bookmarks: %w", err) } defer f.Close() var root safariBookmark if err := plist.NewDecoder(f).Decode(&root); err != nil { - return nil, fmt.Errorf("decode bookmarks: %w", err) + return fmt.Errorf("decode bookmarks: %w", err) } var bookmarks []record.Bookmark walkBookmarks(root.Children, "", &bookmarks) - return bookmarks, nil + emit(out, bookmarks) + return nil } // walkBookmarks recursively traverses the bookmark tree, collecting leaf entries. @@ -74,11 +76,3 @@ func walkBookmarks(nodes []safariBookmark, folder string, out *[]record.Bookmark } } } - -func countBookmarks(path string) (int, error) { - bookmarks, err := extractBookmarks(path) - if err != nil { - return 0, err - } - return len(bookmarks), nil -} diff --git a/browser/safari/extract_bookmark_test.go b/internal/browser/safari/extract_bookmark_test.go similarity index 85% rename from browser/safari/extract_bookmark_test.go rename to internal/browser/safari/extract_bookmark_test.go index 484240c..d2d81b4 100644 --- a/browser/safari/extract_bookmark_test.go +++ b/internal/browser/safari/extract_bookmark_test.go @@ -8,6 +8,8 @@ import ( "github.com/moond4rk/plist" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func buildTestBookmarksPlist(t *testing.T, root safariBookmark) string { @@ -55,7 +57,9 @@ func TestExtractBookmarks(t *testing.T) { } path := buildTestBookmarksPlist(t, root) - bookmarks, err := extractBookmarks(path) + var out testCollector + err := extractBookmarks(path, &out) + bookmarks := collected[record.Bookmark](t, &out) require.NoError(t, err) require.Len(t, bookmarks, 3) @@ -90,7 +94,9 @@ func TestExtractBookmarks_ReadingList(t *testing.T) { } path := buildTestBookmarksPlist(t, root) - bookmarks, err := extractBookmarks(path) + var out testCollector + err := extractBookmarks(path, &out) + bookmarks := collected[record.Bookmark](t, &out) require.NoError(t, err) require.Len(t, bookmarks, 1) assert.Equal(t, "ReadingList", bookmarks[0].Folder) @@ -114,7 +120,9 @@ func TestExtractBookmarks_SkipsEmptyURL(t *testing.T) { } path := buildTestBookmarksPlist(t, root) - bookmarks, err := extractBookmarks(path) + var out testCollector + err := extractBookmarks(path, &out) + bookmarks := collected[record.Bookmark](t, &out) require.NoError(t, err) require.Len(t, bookmarks, 1) assert.Equal(t, "Valid", bookmarks[0].Name) @@ -142,7 +150,9 @@ func TestExtractBookmarks_NestedFolders(t *testing.T) { } path := buildTestBookmarksPlist(t, root) - bookmarks, err := extractBookmarks(path) + var out testCollector + err := extractBookmarks(path, &out) + bookmarks := collected[record.Bookmark](t, &out) require.NoError(t, err) require.Len(t, bookmarks, 2) @@ -154,26 +164,13 @@ func TestExtractBookmarks_NestedFolders(t *testing.T) { assert.Equal(t, "Work", bookmarks[1].Folder) } -func TestCountBookmarks(t *testing.T) { - root := safariBookmark{ - Type: bookmarkTypeList, - Children: []safariBookmark{ - {Type: bookmarkTypeLeaf, URLString: "https://a.com", URIDictionary: uriDictionary{Title: "A"}}, - {Type: bookmarkTypeLeaf, URLString: "https://b.com", URIDictionary: uriDictionary{Title: "B"}}, - }, - } - - path := buildTestBookmarksPlist(t, root) - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - func TestExtractBookmarks_Empty(t *testing.T) { root := safariBookmark{Type: bookmarkTypeList} path := buildTestBookmarksPlist(t, root) - bookmarks, err := extractBookmarks(path) + var out testCollector + err := extractBookmarks(path, &out) + bookmarks := collected[record.Bookmark](t, &out) require.NoError(t, err) assert.Empty(t, bookmarks) } diff --git a/browser/safari/extract_cookie.go b/internal/browser/safari/extract_cookie.go similarity index 78% rename from browser/safari/extract_cookie.go rename to internal/browser/safari/extract_cookie.go index ef548ec..faa0898 100644 --- a/browser/safari/extract_cookie.go +++ b/internal/browser/safari/extract_cookie.go @@ -6,13 +6,14 @@ import ( "github.com/moond4rk/binarycookies" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractCookies(path string) ([]record.Cookie, error) { +func extractCookies(path string, out browser.Collector) error { pages, err := decodeBinaryCookies(path) if err != nil { - return nil, err + return err } var cookies []record.Cookie @@ -35,19 +36,8 @@ func extractCookies(path string) ([]record.Cookie, error) { }) } } - return cookies, nil -} - -func countCookies(path string) (int, error) { - pages, err := decodeBinaryCookies(path) - if err != nil { - return 0, err - } - var total int - for _, page := range pages { - total += len(page.Cookies) - } - return total, nil + emit(out, cookies) + return nil } func decodeBinaryCookies(path string) ([]binarycookies.Page, error) { diff --git a/browser/safari/extract_cookie_test.go b/internal/browser/safari/extract_cookie_test.go similarity index 88% rename from browser/safari/extract_cookie_test.go rename to internal/browser/safari/extract_cookie_test.go index c5ca6b2..8520fac 100644 --- a/browser/safari/extract_cookie_test.go +++ b/internal/browser/safari/extract_cookie_test.go @@ -9,6 +9,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) // buildTestBinaryCookies constructs a minimal valid Cookies.binarycookies file @@ -129,7 +131,9 @@ func TestExtractCookies(t *testing.T) { }, }) - cookies, err := extractCookies(path) + var out testCollector + err := extractCookies(path, &out) + cookies := collected[record.Cookie](t, &out) require.NoError(t, err) require.Len(t, cookies, 2) @@ -148,27 +152,15 @@ func TestExtractCookies(t *testing.T) { assert.False(t, c.ExpireAt.IsZero()) } -func TestCountCookies(t *testing.T) { - path := buildTestBinaryCookies(t, []testCookie{ - {domain: ".a.com", name: "a", path: "/", value: "1", expires: 2000000000.0, creation: 700000000.0}, - {domain: ".b.com", name: "b", path: "/", value: "2", expires: 2000000000.0, creation: 700000000.0}, - {domain: ".c.com", name: "c", path: "/", value: "3", expires: 2000000000.0, creation: 700000000.0}, - }) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - func TestExtractCookies_InvalidFile(t *testing.T) { path := filepath.Join(t.TempDir(), "bad.binarycookies") require.NoError(t, os.WriteFile(path, []byte("not a cookies file"), 0o644)) - _, err := extractCookies(path) + err := extractCookies(path, &testCollector{}) assert.Error(t, err) } func TestExtractCookies_FileNotFound(t *testing.T) { - _, err := extractCookies("/nonexistent/Cookies.binarycookies") + err := extractCookies("/nonexistent/Cookies.binarycookies", &testCollector{}) assert.Error(t, err) } diff --git a/browser/safari/extract_download.go b/internal/browser/safari/extract_download.go similarity index 80% rename from browser/safari/extract_download.go rename to internal/browser/safari/extract_download.go index 717e240..efedf80 100644 --- a/browser/safari/extract_download.go +++ b/internal/browser/safari/extract_download.go @@ -6,6 +6,7 @@ import ( "github.com/moond4rk/plist" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" ) @@ -25,16 +26,16 @@ type safariDownloadEntry struct { // extractDownloads reads Downloads.plist (shared across Safari profiles) and returns only the entries // owned by ownerUUID — either "DefaultProfile" or a named profile's uppercase UUID. Entries written by // older Safari (no ProfileUUID field) are attributed to the default profile. -func extractDownloads(path, ownerUUID string) ([]record.Download, error) { +func extractDownloads(path, ownerUUID string, out browser.Collector) error { f, err := os.Open(path) if err != nil { - return nil, fmt.Errorf("open downloads: %w", err) + return fmt.Errorf("open downloads: %w", err) } defer f.Close() var dl safariDownloads if err := plist.NewDecoder(f).Decode(&dl); err != nil { - return nil, fmt.Errorf("decode downloads: %w", err) + return fmt.Errorf("decode downloads: %w", err) } var downloads []record.Download @@ -48,15 +49,8 @@ func extractDownloads(path, ownerUUID string) ([]record.Download, error) { TotalBytes: d.TotalBytes, }) } - return downloads, nil -} - -func countDownloads(path, ownerUUID string) (int, error) { - downloads, err := extractDownloads(path, ownerUUID) - if err != nil { - return 0, err - } - return len(downloads), nil + emit(out, downloads) + return nil } // ownsDownload treats empty ProfileUUID as DefaultProfile for backward compat with pre-profile Safari. diff --git a/browser/safari/extract_download_test.go b/internal/browser/safari/extract_download_test.go similarity index 73% rename from browser/safari/extract_download_test.go rename to internal/browser/safari/extract_download_test.go index 6967151..346b388 100644 --- a/browser/safari/extract_download_test.go +++ b/internal/browser/safari/extract_download_test.go @@ -8,6 +8,8 @@ import ( "github.com/moond4rk/plist" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func buildTestDownloadsPlist(t *testing.T, dl safariDownloads) string { @@ -33,7 +35,9 @@ func TestExtractDownloads_DefaultProfileOnly(t *testing.T) { } path := buildTestDownloadsPlist(t, dl) - downloads, err := extractDownloads(path, defaultProfileSentinel) + var out testCollector + err := extractDownloads(path, defaultProfileSentinel, &out) + downloads := collected[record.Download](t, &out) require.NoError(t, err) require.Len(t, downloads, 2) assert.Equal(t, "https://a.com/a.zip", downloads[0].URL) @@ -50,33 +54,22 @@ func TestExtractDownloads_NamedProfileOnly(t *testing.T) { } path := buildTestDownloadsPlist(t, dl) - downloads, err := extractDownloads(path, namedUUID) + var out testCollector + err := extractDownloads(path, namedUUID, &out) + downloads := collected[record.Download](t, &out) require.NoError(t, err) require.Len(t, downloads, 1) assert.Equal(t, "https://b.com/b.zip", downloads[0].URL) assert.Equal(t, int64(200), downloads[0].TotalBytes) } -func TestCountDownloads(t *testing.T) { - dl := safariDownloads{ - DownloadHistory: []safariDownloadEntry{ - {URL: "https://a.com/1.zip", Path: "/tmp/1.zip", TotalBytes: 100, ProfileUUID: defaultProfileSentinel}, - {URL: "https://b.com/2.zip", Path: "/tmp/2.zip", TotalBytes: 200, ProfileUUID: defaultProfileSentinel}, - {URL: "https://c.com/3.zip", Path: "/tmp/3.zip", TotalBytes: 300, ProfileUUID: defaultProfileSentinel}, - }, - } - - path := buildTestDownloadsPlist(t, dl) - count, err := countDownloads(path, defaultProfileSentinel) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - func TestExtractDownloads_Empty(t *testing.T) { dl := safariDownloads{} path := buildTestDownloadsPlist(t, dl) - downloads, err := extractDownloads(path, defaultProfileSentinel) + var out testCollector + err := extractDownloads(path, defaultProfileSentinel, &out) + downloads := collected[record.Download](t, &out) require.NoError(t, err) assert.Empty(t, downloads) } diff --git a/browser/safari/extract_extension.go b/internal/browser/safari/extract_extension.go similarity index 70% rename from browser/safari/extract_extension.go rename to internal/browser/safari/extract_extension.go index abc13e2..338f3d1 100644 --- a/browser/safari/extract_extension.go +++ b/internal/browser/safari/extract_extension.go @@ -3,13 +3,13 @@ package safari import ( "fmt" "os" - "path/filepath" "regexp" "sort" "strings" "github.com/moond4rk/plist" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" ) @@ -21,13 +21,6 @@ import ( // Both files share the same top-level shape: a dictionary keyed by // " ()". Only WebExtensions carry an `Enabled` field; // an App Extension that appears in the plist is implicitly enabled. -const ( - safariExtensionsSubdir = "Safari" - safariAppExtensionsSubdir = "AppExtensions" - safariWebExtensionsSubdir = "WebExtensions" - safariExtensionsPlistFile = "Extensions.plist" -) - // extensionKeyPattern matches the " ()" key format Safari uses. var extensionKeyPattern = regexp.MustCompile(`^(\S+)\s+\(([^)]+)\)$`) @@ -39,14 +32,11 @@ type safariExtension struct { Enabled *bool `plist:"Enabled"` } -// extractExtensions reads both AppExtensions/Extensions.plist and -// WebExtensions/Extensions.plist from the profile's Safari container and -// returns the merged list, sorted by key for deterministic output. -// A missing plist on either side is skipped silently. -func extractExtensions(container string) ([]record.Extension, error) { - records, err := readSafariExtensions(container) +// extractExtensions merges the plists in paths, sorted by key for deterministic output. +func extractExtensions(paths []string, out browser.Collector) error { + records, err := readSafariExtensions(paths) if err != nil { - return nil, err + return err } extensions := make([]record.Extension, 0, len(records)) @@ -57,15 +47,8 @@ func extractExtensions(container string) ([]record.Extension, error) { Enabled: r.enabled, }) } - return extensions, nil -} - -func countExtensions(container string) (int, error) { - records, err := readSafariExtensions(container) - if err != nil { - return 0, err - } - return len(records), nil + emit(out, extensions) + return nil } type extensionRecord struct { @@ -74,16 +57,11 @@ type extensionRecord struct { enabled bool } -func readSafariExtensions(container string) ([]extensionRecord, error) { - safariDir := filepath.Join(container, safariExtensionsSubdir) +func readSafariExtensions(paths []string) ([]extensionRecord, error) { var all []extensionRecord - for _, sub := range []string{safariAppExtensionsSubdir, safariWebExtensionsSubdir} { - p := filepath.Join(safariDir, sub, safariExtensionsPlistFile) + for _, p := range paths { records, err := decodeSafariExtensionsPlist(p) if err != nil { - if os.IsNotExist(err) { - continue - } return nil, err } all = append(all, records...) diff --git a/browser/safari/extract_extension_test.go b/internal/browser/safari/extract_extension_test.go similarity index 60% rename from browser/safari/extract_extension_test.go rename to internal/browser/safari/extract_extension_test.go index 9b635b0..e0b689f 100644 --- a/browser/safari/extract_extension_test.go +++ b/internal/browser/safari/extract_extension_test.go @@ -8,6 +8,8 @@ import ( "github.com/moond4rk/plist" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) // testExtensionEntry mirrors the shape of one entry in Safari's Extensions.plist: @@ -21,25 +23,43 @@ type testExtensionEntry map[string]any // "AppExtensions" or "WebExtensions". func writeTestExtensionsPlist(t *testing.T, container, subdir string, entries map[string]testExtensionEntry) { t.Helper() - dir := filepath.Join(container, safariExtensionsSubdir, subdir) + dir := filepath.Join(container, "Safari", subdir) require.NoError(t, os.MkdirAll(dir, 0o755)) - f, err := os.Create(filepath.Join(dir, safariExtensionsPlistFile)) + f, err := os.Create(filepath.Join(dir, "Extensions.plist")) require.NoError(t, err) defer f.Close() require.NoError(t, plist.NewBinaryEncoder(f).Encode(entries)) } +// extensionPlists lists the plists present under container, as the extractor finds them in its snapshot. +func extensionPlists(container string) []string { + var paths []string + for _, sub := range []string{"AppExtensions", "WebExtensions"} { + if p := filepath.Join(container, "Safari", sub, "Extensions.plist"); fileExists(p) { + paths = append(paths, p) + } + } + return paths +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + func TestExtractExtensions_AppAndWebMerged(t *testing.T) { container := t.TempDir() - writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{ + writeTestExtensionsPlist(t, container, "AppExtensions", map[string]testExtensionEntry{ "com.colliderli.iina.OpenInIINA (67CQ77V27R)": {}, }) - writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{ + writeTestExtensionsPlist(t, container, "WebExtensions", map[string]testExtensionEntry{ "com.1password.safari.extension (2BUA8C4S2C)": {"Enabled": true}, }) - got, err := extractExtensions(container) + var out testCollector + err := extractExtensions(extensionPlists(container), &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 2) @@ -56,12 +76,14 @@ func TestExtractExtensions_AppAndWebMerged(t *testing.T) { func TestExtractExtensions_EnabledFlag(t *testing.T) { container := t.TempDir() - writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{ + writeTestExtensionsPlist(t, container, "WebExtensions", map[string]testExtensionEntry{ "com.example.a (AAAAAAAAAA)": {"Enabled": true}, "com.example.b (BBBBBBBBBB)": {"Enabled": false}, }) - got, err := extractExtensions(container) + var out testCollector + err := extractExtensions(extensionPlists(container), &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 2) assert.True(t, got[0].Enabled) @@ -70,11 +92,13 @@ func TestExtractExtensions_EnabledFlag(t *testing.T) { func TestExtractExtensions_BundleIDFallbackOnUnexpectedKey(t *testing.T) { container := t.TempDir() - writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{ + writeTestExtensionsPlist(t, container, "AppExtensions", map[string]testExtensionEntry{ "legacy-key-without-team-id": {}, }) - got, err := extractExtensions(container) + var out testCollector + err := extractExtensions(extensionPlists(container), &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 1) // Regex miss → fall back to the full trimmed key. @@ -84,11 +108,13 @@ func TestExtractExtensions_BundleIDFallbackOnUnexpectedKey(t *testing.T) { func TestExtractExtensions_OnlyAppExt(t *testing.T) { container := t.TempDir() - writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{ + writeTestExtensionsPlist(t, container, "AppExtensions", map[string]testExtensionEntry{ "com.example.only (XXXXXXXXX1)": {}, }) - got, err := extractExtensions(container) + var out testCollector + err := extractExtensions(extensionPlists(container), &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "com.example.only", got[0].Name) @@ -96,11 +122,13 @@ func TestExtractExtensions_OnlyAppExt(t *testing.T) { func TestExtractExtensions_OnlyWebExt(t *testing.T) { container := t.TempDir() - writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{ + writeTestExtensionsPlist(t, container, "WebExtensions", map[string]testExtensionEntry{ "com.example.web (XXXXXXXXX2)": {"Enabled": true}, }) - got, err := extractExtensions(container) + var out testCollector + err := extractExtensions(extensionPlists(container), &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "com.example.web", got[0].Name) @@ -108,22 +136,9 @@ func TestExtractExtensions_OnlyWebExt(t *testing.T) { func TestExtractExtensions_NoPlists(t *testing.T) { container := t.TempDir() - got, err := extractExtensions(container) + var out testCollector + err := extractExtensions(extensionPlists(container), &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) assert.Empty(t, got) } - -func TestCountExtensions(t *testing.T) { - container := t.TempDir() - writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{ - "com.example.a (AAAAAAAAAA)": {}, - "com.example.b (BBBBBBBBBB)": {}, - }) - writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{ - "com.example.c (CCCCCCCCCC)": {"Enabled": true}, - }) - - count, err := countExtensions(container) - require.NoError(t, err) - assert.Equal(t, 3, count) -} diff --git a/browser/safari/extract_history.go b/internal/browser/safari/extract_history.go similarity index 80% rename from browser/safari/extract_history.go rename to internal/browser/safari/extract_history.go index 9e5bd0b..766b0bc 100644 --- a/browser/safari/extract_history.go +++ b/internal/browser/safari/extract_history.go @@ -3,6 +3,7 @@ package safari import ( "database/sql" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" @@ -19,11 +20,9 @@ const ( WHERE hv2.history_item = hi.id ORDER BY hv2.visit_time DESC LIMIT 1 )` - - safariCountHistoryQuery = `SELECT COUNT(*) FROM history_items` ) -func extractHistories(path string) ([]record.History, error) { +func extractHistories(path string, out browser.Collector) error { histories, err := sqlitex.QueryRows(path, true, safariHistoryQuery, func(rows *sql.Rows) (record.History, error) { var ( @@ -42,11 +41,8 @@ func extractHistories(path string) ([]record.History, error) { }, nil }) if err != nil { - return nil, err + return err } - return histories, nil -} - -func countHistories(path string) (int, error) { - return sqlitex.CountRows(path, true, safariCountHistoryQuery) + emit(out, histories) + return nil } diff --git a/browser/safari/extract_history_test.go b/internal/browser/safari/extract_history_test.go similarity index 82% rename from browser/safari/extract_history_test.go rename to internal/browser/safari/extract_history_test.go index 7846ff7..a3e1dcb 100644 --- a/browser/safari/extract_history_test.go +++ b/internal/browser/safari/extract_history_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupSafariHistoryDB(t *testing.T) string { @@ -25,7 +27,9 @@ func setupSafariHistoryDB(t *testing.T) string { func TestExtractHistories(t *testing.T) { path := setupSafariHistoryDB(t) - got, err := extractHistories(path) + var out testCollector + err := extractHistories(path, &out) + got := collected[record.History](t, &out) require.NoError(t, err) require.Len(t, got, 3) @@ -44,7 +48,9 @@ func TestExtractHistories(t *testing.T) { func TestExtractHistories_Dedup(t *testing.T) { path := setupSafariHistoryDB(t) - got, err := extractHistories(path) + var out testCollector + err := extractHistories(path, &out) + got := collected[record.History](t, &out) require.NoError(t, err) // 3 history_items, not 4 visits. require.Len(t, got, 3) @@ -62,23 +68,6 @@ func TestExtractHistories_Dedup(t *testing.T) { t.Fatal("expected https://github.com in results") } -func TestCountHistories(t *testing.T) { - path := setupSafariHistoryDB(t) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountHistories_Empty(t *testing.T) { - path := createTestDB(t, "History.db", - []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - func TestExtractHistories_NullTitle(t *testing.T) { path := createTestDB(t, "History.db", []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, @@ -87,7 +76,9 @@ func TestExtractHistories_NullTitle(t *testing.T) { `INSERT INTO history_visits (id, history_item, visit_time) VALUES (1, 1, 700000000.0)`, ) - got, err := extractHistories(path) + var out testCollector + err := extractHistories(path, &out) + got := collected[record.History](t, &out) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "https://null.test", got[0].URL) diff --git a/internal/browser/safari/extract_password.go b/internal/browser/safari/extract_password.go new file mode 100644 index 0000000..f98765b --- /dev/null +++ b/internal/browser/safari/extract_password.go @@ -0,0 +1,59 @@ +package safari + +import ( + "context" + "fmt" + "strings" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +func extractPasswords(ctx context.Context, kc LoginKeychain, out browser.Collector) error { + passwords, err := kc.InternetPasswords(ctx) + if err != nil { + return err + } + + var logins []record.Login + for _, p := range passwords { + url := buildURL(p.Protocol, p.Server, p.Port, p.Path) + if url == "" || p.Account == "" { + continue + } + logins = append(logins, record.Login{ + URL: url, + Username: p.Account, + Password: p.PlainPassword, + CreatedAt: p.Created.UTC(), + Store: record.StoreLocal, + }) + } + emit(out, logins) + return nil +} + +// buildURL constructs a URL from InternetPassword fields. +func buildURL(protocol, server string, port uint32, path string) string { + if server == "" { + return "" + } + + // macOS Keychain stores the protocol as a FourCC code; only "htps" needs remapping, others just trim padding. + scheme := strings.TrimRight(protocol, " ") + if scheme == "" || scheme == "htps" { + scheme = "https" + } + + url := scheme + "://" + server + + defaultPorts := map[string]uint32{"https": 443, "http": 80, "ftp": 21} + if port > 0 && port != defaultPorts[scheme] { + url += fmt.Sprintf(":%d", port) + } + + if path != "" && path != "/" { + url += path + } + return url +} diff --git a/browser/safari/extract_password_test.go b/internal/browser/safari/extract_password_test.go similarity index 100% rename from browser/safari/extract_password_test.go rename to internal/browser/safari/extract_password_test.go diff --git a/browser/safari/extract_storage.go b/internal/browser/safari/extract_storage.go similarity index 82% rename from browser/safari/extract_storage.go rename to internal/browser/safari/extract_storage.go index 7894faa..3065b77 100644 --- a/browser/safari/extract_storage.go +++ b/internal/browser/safari/extract_storage.go @@ -10,6 +10,7 @@ import ( _ "modernc.org/sqlite" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/record" ) @@ -52,10 +53,10 @@ const ( originPortExplicitFlag = 0x01 ) -func extractLocalStorage(root string) ([]record.LocalStorage, error) { +func extractLocalStorage(root string, out browser.Collector) error { dirs, err := findOriginDataDirs(root) if err != nil { - return nil, err + return err } var entries []record.LocalStorage @@ -79,50 +80,8 @@ func extractLocalStorage(root string) ([]record.LocalStorage, error) { }) } } - return entries, nil -} - -// countLocalStorage sums ItemTable row counts across every origin DB under root without -// parsing origin files or decoding values — CountEntries callers only need the total, not the -// URLs or plaintext. COUNT(key) naturally excludes NULL keys, matching the same skip rule -// applied by readLocalStorageFile, so count and extract stay in sync. -func countLocalStorage(root string) (int, error) { - dirs, err := findOriginDataDirs(root) - if err != nil { - return 0, err - } - total := 0 - for _, od := range dirs { - dbPath := filepath.Join(od, webkitLocalStorageSubdir, webkitLocalStorageDB) - n, err := countLocalStorageFile(dbPath) - if err != nil { - log.Debugf("safari localstorage: count %s: %v", dbPath, err) - continue - } - total += n - } - return total, nil -} - -func countLocalStorageFile(path string) (int, error) { - // mode=ro (no immutable) so SQLite replays the copied -wal sidecar — this surfaces entries - // Safari has committed to WAL but not yet checkpointed to the main DB. Writes SQLite might - // make to the temp-copy's -shm during replay are harmless; the Session cleanup removes - // everything. Live-file reads (profiles.go) still use immutable=1 to stay off the real WAL. - dsn := "file:" + path + "?mode=ro" - db, err := sql.Open("sqlite", dsn) - if err != nil { - return 0, fmt.Errorf("open %s: %w", path, err) - } - defer db.Close() - if err := db.Ping(); err != nil { - return 0, fmt.Errorf("ping %s: %w", path, err) - } - var count int - if err := db.QueryRow(`SELECT COUNT(key) FROM ItemTable`).Scan(&count); err != nil { - return 0, fmt.Errorf("count ItemTable: %w", err) - } - return count, nil + emit(out, entries) + return nil } // findOriginDataDirs returns /

/

/ paths that contain both an "origin" file and @@ -273,9 +232,8 @@ type localStorageItem struct { } func readLocalStorageFile(path string) ([]localStorageItem, error) { - // mode=ro (no immutable) — see countLocalStorageFile for the WAL-replay rationale; the same - // live-vs-temp split applies here. ORDER BY key, rowid makes exports byte-for-byte stable - // across runs and SQLite versions. + // mode=ro without immutable, so SQLite replays the copied -wal sidecar and surfaces entries Safari has not yet + // checkpointed. ORDER BY key, rowid makes exports byte-for-byte stable across runs and SQLite versions. dsn := "file:" + path + "?mode=ro" db, err := sql.Open("sqlite", dsn) if err != nil { diff --git a/browser/safari/extract_storage_test.go b/internal/browser/safari/extract_storage_test.go similarity index 80% rename from browser/safari/extract_storage_test.go rename to internal/browser/safari/extract_storage_test.go index 9c979e6..f3e779d 100644 --- a/browser/safari/extract_storage_test.go +++ b/internal/browser/safari/extract_storage_test.go @@ -1,7 +1,6 @@ package safari import ( - "database/sql" "os" "path/filepath" "strings" @@ -9,7 +8,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + _ "modernc.org/sqlite" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) // --------------------------------------------------------------------------- @@ -128,7 +130,9 @@ func TestExtractLocalStorage_SingleOrigin(t *testing.T) { root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ "https://example.com": {{Key: "auth_token", Value: "abc123"}}, }) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, entries, 1) assert.Equal(t, "https://example.com", entries[0].URL) @@ -147,7 +151,9 @@ func TestExtractLocalStorage_MultiOrigin(t *testing.T) { {Key: "session", Value: "xyz"}, }, }) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, entries, 3) @@ -166,7 +172,9 @@ func TestExtractLocalStorage_CJKAndEmoji(t *testing.T) { {Key: "status", Value: "hello 世界 🌍"}, }, }) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, entries, 2) @@ -182,7 +190,9 @@ func TestExtractLocalStorage_EmptyItemTable(t *testing.T) { root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ "https://example.com": nil, }) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) assert.Empty(t, entries) } @@ -191,7 +201,9 @@ func TestExtractLocalStorage_TruncatesOversizedValue(t *testing.T) { root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ "https://example.com": {{Key: "big", Value: strings.Repeat("x", 1100)}}, }) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, entries, 1) assert.Contains(t, entries[0].Value, "too long") @@ -206,7 +218,9 @@ func TestExtractLocalStorage_Partitioned(t *testing.T) { []testLocalStorageItem{{Key: "yt-session", Value: "embedded"}}, ) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, entries, 1) assert.Equal(t, "https://accounts.youtube.com", entries[0].URL, "frame origin preferred over top-frame") @@ -220,7 +234,9 @@ func TestExtractLocalStorage_SkipsSaltAndStrayFiles(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(root, "salt"), []byte("pretend salt"), 0o644)) require.NoError(t, os.WriteFile(filepath.Join(root, "README"), []byte("noise"), 0o644)) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, entries, 1) assert.Equal(t, "https://example.com", entries[0].URL) @@ -236,46 +252,28 @@ func TestExtractLocalStorage_SkipsFrameDirsWithoutDB(t *testing.T) { filepath.Join(frameDir, "origin"), encodeOriginFile("https://example.com", "https://example.com"), 0o644)) - entries, err := extractLocalStorage(root) + var out testCollector + err := extractLocalStorage(root, &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) assert.Empty(t, entries) } func TestExtractLocalStorage_DirMissing(t *testing.T) { - _, err := extractLocalStorage(filepath.Join(t.TempDir(), "does-not-exist")) + err := extractLocalStorage(filepath.Join(t.TempDir(), "does-not-exist"), &testCollector{}) require.Error(t, err) } func TestExtractLocalStorage_EmptyRoot(t *testing.T) { - entries, err := extractLocalStorage(t.TempDir()) + var out testCollector + err := extractLocalStorage(t.TempDir(), &out) + entries := collected[record.LocalStorage](t, &out) require.NoError(t, err) assert.Empty(t, entries) } // --------------------------------------------------------------------------- -// countLocalStorage -// --------------------------------------------------------------------------- - -func TestCountLocalStorage(t *testing.T) { - root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ - "https://a.com": {{Key: "k1", Value: "v1"}, {Key: "k2", Value: "v2"}}, - "https://b.com": {{Key: "k3", Value: "v3"}}, - "https://c.com:8443": {{Key: "k4", Value: "v4"}}, - }) - count, err := countLocalStorage(root) - require.NoError(t, err) - assert.Equal(t, 4, count) -} - -func TestCountLocalStorage_DirMissing(t *testing.T) { - count, err := countLocalStorage(filepath.Join(t.TempDir(), "nope")) - require.Error(t, err) - assert.Equal(t, 0, count) -} - -// --------------------------------------------------------------------------- -// NULL-key handling — readLocalStorageFile / countLocalStorageFile both skip NULL keys, -// keeping count and extract in sync. +// NULL-key handling — readLocalStorageFile skips NULL keys. // --------------------------------------------------------------------------- func TestReadLocalStorageFile_SkipsNullKey(t *testing.T) { @@ -291,18 +289,6 @@ func TestReadLocalStorageFile_SkipsNullKey(t *testing.T) { assert.Equal(t, "keeper", items[0].value) } -func TestCountLocalStorageFile_SkipsNullKey(t *testing.T) { - dbPath := filepath.Join(t.TempDir(), "ls.sqlite3") - writeLocalStorageDB(t, dbPath, []testLocalStorageItem{ - {Key: "k1", Value: "v1"}, - {Key: "k2", Value: "v2"}, - }, true /*addNullKey*/) - - count, err := countLocalStorageFile(dbPath) - require.NoError(t, err) - assert.Equal(t, 2, count, "NULL keys are excluded from count to match extract's skip rule") -} - func TestReadLocalStorageFile_ReturnsRowsInKeyOrder(t *testing.T) { // Rows are inserted in reverse alphabetical order; ORDER BY key, rowid in the extractor // query must surface them ascending so exports are deterministic across runs. @@ -320,16 +306,3 @@ func TestReadLocalStorageFile_ReturnsRowsInKeyOrder(t *testing.T) { assert.Equal(t, "mango", items[1].key) assert.Equal(t, "zebra", items[2].key) } - -func TestCountLocalStorageFile_MissingTable(t *testing.T) { - // Real Safari has origin dirs with LocalStorage/localstorage.sqlite3 but no ItemTable yet - // (seen during live verification). countLocalStorageFile must surface the error so the - // caller can log-and-skip rather than counting 0 silently. - dbPath := filepath.Join(t.TempDir(), "empty.sqlite3") - db, err := sql.Open("sqlite", dbPath) - require.NoError(t, err) - require.NoError(t, db.Close()) - - _, err = countLocalStorageFile(dbPath) - require.Error(t, err) -} diff --git a/internal/browser/safari/profiles.go b/internal/browser/safari/profiles.go new file mode 100644 index 0000000..5827d92 --- /dev/null +++ b/internal/browser/safari/profiles.go @@ -0,0 +1,154 @@ +package safari + +import ( + "context" + "database/sql" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + + _ "modernc.org/sqlite" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +// SafariTabs.db lists profiles in bookmarks rows with subtype=2. external_uuid "DefaultProfile" +// is the sentinel for the implicit default, which has no per-UUID directory. +const ( + safariTabsDBRelPath = containerDir + "/Safari/SafariTabs.db" + safariProfileSubtype = 2 + defaultProfileSentinel = "DefaultProfile" +) + +// Path-unsafe bytes for filenames/CSV values; Unicode letters (CJK etc.) survive. +var unsafeNameChars = regexp.MustCompile(`[/\\:*?"<>|\x00-\x1f]+`) + +// Canonical 8-4-4-4-12 hex UUID — format check only, no semantic parse. +var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`) + +// namedProfiles reads SafariTabs.db (authoritative), with a ReadDir fallback only if the DB itself is unreadable. +func namedProfiles(library string) []browser.Profile { + named, err := readNamedProfilesFromDB(library) + if err != nil { + // Empty DB (nil, nil) is authoritative; fall back only when DB itself is unreadable. + named = readNamedProfilesFromDir(library) + } + return named +} + +// readNamedProfilesFromDB returns (nil, err) when the DB is missing/unreadable so the caller can +// try the ReadDir fallback; (slice, nil) — possibly empty — is authoritative. +// Discovery reads a snapshot copy, never the live file Safari has open. +func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { + d, err := snapshot.Temp() + if err != nil { + return nil, err + } + defer func() { + if err := d.Close(); err != nil { + log.Warnf("%v", err) + } + }() + if err := d.Capture(context.Background(), []snapshot.File{{DirID: discoverDirID, From: library, Rel: safariTabsDBRelPath}}); err != nil { + return nil, fmt.Errorf("copy SafariTabs.db: %w", err) + } + path, err := d.Snapshot(discoverDirID).Path(safariTabsDBRelPath) + if err != nil { + return nil, fmt.Errorf("copy SafariTabs.db: %w", err) + } + + // Immutable, as on the live file before: the copied -wal is not replayed, so the profile list stays today's. + dsn := "file:" + path + "?mode=ro&immutable=1" + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, fmt.Errorf("open SafariTabs.db: %w", err) + } + defer db.Close() + + // Ping forces connection; sql.Open is lazy and won't detect a missing file. + if err := db.Ping(); err != nil { + return nil, fmt.Errorf("ping SafariTabs.db: %w", err) + } + + rows, err := db.Query( + `SELECT external_uuid, title FROM bookmarks WHERE subtype = ? AND external_uuid != ?`, + safariProfileSubtype, defaultProfileSentinel, + ) + if err != nil { + return nil, fmt.Errorf("query SafariTabs.db: %w", err) + } + defer rows.Close() + + var out []browser.Profile + for rows.Next() { + var externalUUID, title sql.NullString + if err := rows.Scan(&externalUUID, &title); err != nil { + log.Debugf("safari profiles: scan row: %v", err) + continue + } + if !isCanonicalUUID(externalUUID.String) { + continue + } + out = append(out, newNamedProfile(externalUUID.String, title.String)) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate SafariTabs.db rows: %w", err) + } + return out, nil +} + +// readNamedProfilesFromDir is the fallback for missing SafariTabs.db. Names are synthesized from UUIDs. +func readNamedProfilesFromDir(library string) []browser.Profile { + entries, err := os.ReadDir(filepath.Join(library, filepath.FromSlash(namedProfilesDir))) + if err != nil { + return nil + } + + var out []browser.Profile + for _, e := range entries { + if !e.IsDir() || !isCanonicalUUID(e.Name()) { + continue + } + out = append(out, newNamedProfile(e.Name(), "")) + } + return out +} + +// A named profile's Dir is its own History.db directory, so its UUID travels with it to Extractors. +func newNamedProfile(upperUUID, title string) browser.Profile { + return browser.Profile{Name: resolveProfileName(title, upperUUID), Dir: namedProfilesDir + "/" + upperUUID} +} + +func isCanonicalUUID(s string) bool { return uuidPattern.MatchString(s) } + +// resolveProfileName prefers the SafariTabs.db title, falling back to "profile-". +func resolveProfileName(title, upperUUID string) string { + if name := sanitizeProfileName(title); name != "" { + return name + } + return "profile-" + strings.ToLower(upperUUID[:8]) +} + +func sanitizeProfileName(name string) string { + name = strings.TrimSpace(name) + if name == "" { + return "" + } + return unsafeNameChars.ReplaceAllString(name, "_") +} + +// disambiguateNames appends "-2", "-3", … to duplicate names, in place. +func disambiguateNames(profiles []browser.Profile) { + occurrences := make(map[string]int, len(profiles)) + for i := range profiles { + original := profiles[i].Name + if prior := occurrences[original]; prior > 0 { + profiles[i].Name = fmt.Sprintf("%s-%d", original, prior+1) + } + occurrences[original]++ + } +} diff --git a/internal/browser/safari/profiles_test.go b/internal/browser/safari/profiles_test.go new file mode 100644 index 0000000..3c0ac8c --- /dev/null +++ b/internal/browser/safari/profiles_test.go @@ -0,0 +1,163 @@ +package safari + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/browser" +) + +func testDef() browser.Def { + p := browser.Platform{UserDataDirs: []string{"Library/Safari"}} + return browser.Def{ID: "safari", Name: "Safari", Base: browser.Safari, Darwin: p, Linux: p, Windows: p} +} + +// libraryAt lays out a fake home: ~/Library/Safari with a History.db, and the container beside it. +func libraryAt(t *testing.T, home string) (container string) { + t.Helper() + mkFile(t, home, "Library", "Safari", "History.db") + return filepath.Join(home, "Library", "Containers", "com.apple.Safari", "Data", "Library") +} + +func discoverProfiles(t *testing.T, home string) []browser.Profile { + t.Helper() + dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: home}) + require.NoError(t, err) + require.Len(t, dirs, 1) + assert.Equal(t, browser.DirID("safari"), dirs[0].ID) + assert.Equal(t, filepath.Join(home, "Library"), dirs[0].Path) + return dirs[0].Profiles +} + +func named(name, uuid string) browser.Profile { + return browser.Profile{Name: name, Dir: namedProfilesDir + "/" + uuid} +} + +var defaultProfile = browser.Profile{Name: "default", Dir: "Safari"} + +func TestDiscover_DefaultOnly(t *testing.T) { + home := t.TempDir() + libraryAt(t, home) + assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home)) +} + +func TestDiscover_MissingSafariYieldsNothing(t *testing.T) { + dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: t.TempDir()}) + require.NoError(t, err) + assert.Empty(t, dirs) +} + +// -p does not apply to Safari: the table's directory is used, and Validate rejects -p at the switch-over. +func TestDiscover_IgnoresProfilePath(t *testing.T) { + home := t.TempDir() + libraryAt(t, home) + dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: home, ProfilePath: t.TempDir()}) + require.NoError(t, err) + require.Len(t, dirs, 1) + assert.Equal(t, filepath.Join(home, "Library"), dirs[0].Path) +} + +func TestDiscover_WithNamedProfile(t *testing.T) { + const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" + home := t.TempDir() + container := libraryAt(t, home) + mkFile(t, container, "Safari", "Profiles", uuid, "History.db") + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{ + {uuid: "DefaultProfile", title: ""}, + {uuid: uuid, title: "work"}, + }) + assert.Equal(t, []browser.Profile{defaultProfile, named("work", uuid)}, discoverProfiles(t, home)) +} + +// A '#' in the live path cuts a SQLite URI short, so the titles come through only when discovery opens its copy. +func TestDiscover_ReadsACopyOfSafariTabs(t *testing.T) { + const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" + home := filepath.Join(t.TempDir(), "user#1") + container := libraryAt(t, home) + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: uuid, title: "work"}}) + assert.Equal(t, []browser.Profile{defaultProfile, named("work", uuid)}, discoverProfiles(t, home)) +} + +func TestDiscover_EmptyTitleFallbackToUUID(t *testing.T) { + const uuid = "ABCDEF01-2345-6789-ABCD-EF0123456789" + home := t.TempDir() + container := libraryAt(t, home) + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: uuid, title: ""}}) + assert.Equal(t, []browser.Profile{defaultProfile, named("profile-abcdef01", uuid)}, discoverProfiles(t, home)) +} + +// A profile directory SafariTabs.db does not mention stays hidden: a readable DB is authoritative. +func TestDiscover_OrphanUUIDWithoutDBEntry(t *testing.T) { + const dbUUID = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" + const orphanUUID = "11111111-2222-3333-4444-555555555555" + home := t.TempDir() + container := libraryAt(t, home) + mkFile(t, container, "Safari", "Profiles", dbUUID, "History.db") + mkFile(t, container, "Safari", "Profiles", orphanUUID, "History.db") + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: dbUUID, title: "declared"}}) + assert.Equal(t, []browser.Profile{defaultProfile, named("declared", dbUUID)}, discoverProfiles(t, home)) +} + +func TestDiscover_EmptyDBIsAuthoritative(t *testing.T) { + home := t.TempDir() + container := libraryAt(t, home) + mkFile(t, container, "Safari", "Profiles", "99999999-AAAA-BBBB-CCCC-DDDDDDDDDDDD", "History.db") + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), nil) + assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home)) +} + +// Without SafariTabs.db the Profiles directory is listed and names are synthesized; directories without data are kept, +// because whether a category's file exists is the plan's question. +func TestDiscover_MissingDBFallsBackToReadDir(t *testing.T) { + const uuid = "11111111-2222-3333-4444-555555555555" + const empty = "4E2D8DD0-A7D2-4684-939A-898B7675C700" + home := t.TempDir() + container := libraryAt(t, home) + mkFile(t, container, "Safari", "Profiles", uuid, "History.db") + require.NoError(t, os.MkdirAll(filepath.Join(container, "Safari", "Profiles", empty), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(container, "Safari", "Profiles", "Bogus"), 0o755)) + assert.Equal(t, []browser.Profile{defaultProfile, named("profile-11111111", uuid), named("profile-4e2d8dd0", empty)}, + discoverProfiles(t, home)) +} + +func TestDiscover_DuplicateTitlesDisambiguate(t *testing.T) { + const uuidA = "AAAAAAAA-0000-0000-0000-000000000001" + const uuidB = "BBBBBBBB-0000-0000-0000-000000000002" + home := t.TempDir() + container := libraryAt(t, home) + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{ + {uuid: uuidA, title: "team"}, + {uuid: uuidB, title: "team"}, + }) + assert.Equal(t, []browser.Profile{defaultProfile, named("team", uuidA), named("team-2", uuidB)}, discoverProfiles(t, home)) +} + +func TestDiscover_DefaultProfileSentinelIgnored(t *testing.T) { + home := t.TempDir() + container := libraryAt(t, home) + writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: defaultProfileSentinel, title: ""}}) + assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home)) +} + +func TestResolveProfileName(t *testing.T) { + tests := []struct { + title string + uuid string + want string + }{ + {"work", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "work"}, + {" spaced ", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "spaced"}, + {"", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "profile-5604e6f5"}, + {"with/slash", "AAAAAAAA-0000-0000-0000-000000000000", "with_slash"}, + {"中文", "AAAAAAAA-0000-0000-0000-000000000000", "中文"}, + } + for _, tt := range tests { + t.Run(tt.title, func(t *testing.T) { + assert.Equal(t, tt.want, resolveProfileName(tt.title, tt.uuid)) + }) + } +} diff --git a/internal/browser/safari/safari.go b/internal/browser/safari/safari.go new file mode 100644 index 0000000..fb08a7c --- /dev/null +++ b/internal/browser/safari/safari.go @@ -0,0 +1,185 @@ +// Package safari is the Safari base: where Safari keeps its default and named profiles under ~/Library, how their +// files are parsed, and the login keychain its passwords come from. +package safari + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + + "github.com/moond4rk/keychainbreaker" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// Paths below are relative to the user data dir, ~/Library. +const ( + containerDir = "Containers/com.apple.Safari/Data/Library" + namedProfilesDir = containerDir + "/Safari/Profiles" + + defaultProfileName = "default" + discoverDirID = "safari" +) + +var errNoKeychain = errors.New("no login keychain") + +// LoginKeychain is the one method the password extractor reads from the run's login keychain. +type LoginKeychain interface { + InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) +} + +// Discover finds Safari's data under ~/Library: the default profile, whose Dir is the Safari directory, and the named +// profiles SafariTabs.db lists. -p does not apply to Safari, and Validate rejects it at the switch-over. +func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { + var errs []error + var dirs []browser.UserDataDir + for i, rel := range def.Platform().UserDataDirs { + safariPath := filepath.Join(opts.Home, filepath.FromSlash(rel)) + if _, err := os.Stat(safariPath); err != nil { + if !errors.Is(err, fs.ErrNotExist) { + errs = append(errs, fmt.Errorf("%s: %w", safariPath, err)) + } + continue + } + library := filepath.Dir(safariPath) + profiles := append([]browser.Profile{{Name: defaultProfileName, Dir: filepath.Base(safariPath)}}, namedProfiles(library)...) + disambiguateNames(profiles) + dirs = append(dirs, browser.UserDataDir{ID: dirID(def, i), Def: def, Path: library, Profiles: profiles}) + } + return dirs, errors.Join(errs...) +} + +func dirID(def browser.Def, i int) browser.DirID { + if i == 0 { + return browser.DirID(def.ID) + } + return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) +} + +// Extractors maps the categories a Safari profile supports to their extractors. A named profile's files sit under +// two directories named for its UUID, so its sources are built from Profile.Dir; the keychain, Bookmarks.plist, and +// the extension plists carry no profile tag, so only the default profile reads them. +func Extractors(dir browser.UserDataDir, p browser.Profile, kc LoginKeychain) browser.Extractors { + library := func(rel string) string { return fromLibrary(p, rel) } + uuid, named := profileUUID(p) + if !named { + return browser.Extractors{ + category.Password: {Extract: passwordsFrom(kc)}, + category.History: plain(file("History.db"), extractHistories), + category.Cookie: plain(file( + library(containerDir+"/Cookies/Cookies.binarycookies"), + library("Cookies/Cookies.binarycookies"), + ), extractCookies), + category.Bookmark: plain(file("Bookmarks.plist"), extractBookmarks), + category.Download: plain(file("Downloads.plist"), downloadsOf(defaultProfileSentinel)), + category.LocalStorage: plain(directory(library(containerDir+"/WebKit/WebsiteData/Default")), extractLocalStorage), + category.Extension: extensionsFrom(library), + } + } + store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid) + return browser.Extractors{ + category.History: plain(file("History.db"), extractHistories), + category.Cookie: plain(file(library(store+"/Cookies/Cookies.binarycookies")), extractCookies), + category.Download: plain(file(library(safariDir(dir)+"/Downloads.plist")), downloadsOf(uuid)), + category.LocalStorage: plain(directory(library(store+"/Origins")), extractLocalStorage), + } +} + +func profileUUID(p browser.Profile) (string, bool) { + if path.Dir(p.Dir) != namedProfilesDir { + return "", false + } + return path.Base(p.Dir), true +} + +// safariDir is the default profile's Dir, which holds the Downloads.plist every profile reads its entries from. +func safariDir(dir browser.UserDataDir) string { + for _, p := range dir.Profiles { + if _, named := profileUUID(p); !named { + return p.Dir + } + } + return "Safari" +} + +// fromLibrary turns a path under ~/Library into one relative to p.Dir, because a profile's sources are joined with it. +func fromLibrary(p browser.Profile, rel string) string { + if p.Dir == "" { + return rel + } + return strings.Repeat("../", strings.Count(p.Dir, "/")+1) + rel +} + +func file(paths ...string) browser.Source { return browser.Source{Paths: paths} } +func directory(rel string) browser.Source { return browser.Source{Paths: []string{rel}, IsDir: true} } + +func plain(src browser.Source, parse func(string, browser.Collector) error) browser.Extractor { + return browser.Extractor{ + Sources: []browser.Source{src}, + Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { + captured, err := ps.Path(src) + if err != nil { + return err + } + return parse(captured, out) + }, + } +} + +// passwordsFrom reads no file, so the extraction always runs; the keychain stays locked without a usable password and +// yields metadata only. +func passwordsFrom(kc LoginKeychain) func(context.Context, browser.ProfileSnapshot, browser.Collector) error { + return func(ctx context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { + if kc == nil { + return errNoKeychain + } + return extractPasswords(ctx, kc, out) + } +} + +// downloadsOf keeps the entries of one profile: Downloads.plist is shared, and each entry names the profile it +// belongs to. +func downloadsOf(owner string) func(string, browser.Collector) error { + return func(path string, out browser.Collector) error { return extractDownloads(path, owner, out) } +} + +func extensionsFrom(library func(string) string) browser.Extractor { + sources := []browser.Source{ + {Paths: []string{library(containerDir + "/Safari/AppExtensions/Extensions.plist")}, Optional: true}, + {Paths: []string{library(containerDir + "/Safari/WebExtensions/Extensions.plist")}, Optional: true}, + } + return browser.Extractor{ + Sources: sources, + Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { + var paths []string + for _, src := range sources { + captured, err := ps.Path(src) + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return err + } + paths = append(paths, captured) + } + return extractExtensions(paths, out) + }, + } +} + +// emit hands rows to out by pointer, because out stamps each record in place. +func emit[T any, P interface { + *T + record.Record +}](out browser.Collector, rows []T) { + for i := range rows { + out.Add(P(&rows[i])) + } +} diff --git a/internal/browser/safari/safari_test.go b/internal/browser/safari/safari_test.go new file mode 100644 index 0000000..0a04206 --- /dev/null +++ b/internal/browser/safari/safari_test.go @@ -0,0 +1,186 @@ +package safari + +import ( + "context" + "errors" + "os" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/moond4rk/keychainbreaker" + "github.com/moond4rk/plist" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +const workUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" + +var ( + workProfile = named("work", workUUID) + libraryDir = browser.UserDataDir{Def: testDef(), Profiles: []browser.Profile{defaultProfile, workProfile}} +) + +// sourcePaths is where each category's candidates land under ~/Library once joined with the profile's Dir. +func sourcePaths(p browser.Profile, ex browser.Extractors) map[category.Category][]string { + got := make(map[category.Category][]string, len(ex)) + for c, e := range ex { + for _, src := range e.Sources { + for _, rel := range src.Paths { + got[c] = append(got[c], path.Join(p.Dir, rel)) + } + } + } + return got +} + +func TestExtractors_DefaultProfileSources(t *testing.T) { + ex := Extractors(libraryDir, defaultProfile, nil) + assert.Equal(t, map[category.Category][]string{ + category.History: {"Safari/History.db"}, + category.Cookie: {containerDir + "/Cookies/Cookies.binarycookies", "Cookies/Cookies.binarycookies"}, + category.Bookmark: {"Safari/Bookmarks.plist"}, + category.Download: {"Safari/Downloads.plist"}, + category.LocalStorage: { + containerDir + "/WebKit/WebsiteData/Default", + }, + category.Extension: { + containerDir + "/Safari/AppExtensions/Extensions.plist", + containerDir + "/Safari/WebExtensions/Extensions.plist", + }, + }, sourcePaths(defaultProfile, ex)) + require.Contains(t, ex, category.Password) + assert.Empty(t, ex[category.Password].Sources, "passwords come from the keychain, not a file") +} + +func TestExtractors_NamedProfileSources(t *testing.T) { + store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(workUUID) + assert.Equal(t, map[category.Category][]string{ + category.History: {namedProfilesDir + "/" + workUUID + "/History.db"}, + category.Cookie: {store + "/Cookies/Cookies.binarycookies"}, + category.Download: {"Safari/Downloads.plist"}, + category.LocalStorage: {store + "/Origins"}, + }, sourcePaths(workProfile, Extractors(libraryDir, workProfile, nil))) +} + +// snapshotOf lays fixture files out as the Safari user data dir's snapshot, keyed by their path under ~/Library. +func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { + t.Helper() + root := t.TempDir() + for rel, src := range files { + data, err := os.ReadFile(src) + require.NoError(t, err) + dst := filepath.Join(root, "safari", filepath.FromSlash(rel)) + require.NoError(t, os.MkdirAll(filepath.Dir(dst), 0o755)) + require.NoError(t, os.WriteFile(dst, data, 0o644)) + } + return snapshot.Open(root).Snapshot("safari") +} + +func writeTestPlist(t *testing.T, v any) string { + t.Helper() + p := filepath.Join(t.TempDir(), "fixture.plist") + f, err := os.Create(p) + require.NoError(t, err) + defer f.Close() + require.NoError(t, plist.NewBinaryEncoder(f).Encode(v)) + return p +} + +func extract(t *testing.T, snap snapshot.Snapshot, p browser.Profile, kc LoginKeychain, c category.Category) (*testCollector, error) { + t.Helper() + ex, ok := Extractors(libraryDir, p, kc)[c] + require.Truef(t, ok, "no %s extractor for %s", c, p.Name) + var out testCollector + err := ex.Extract(context.Background(), browser.NewProfileSnapshot(snap, p, nil), &out) + return &out, err +} + +// Each profile keeps its own entries of the shared Downloads.plist; an entry without an owner is the default's. +func TestExtractors_DownloadsBelongToTheirProfile(t *testing.T) { + snap := snapshotOf(t, map[string]string{"Safari/Downloads.plist": writeTestPlist(t, map[string]any{ + "DownloadHistory": []any{ + map[string]any{"DownloadEntryURL": "https://a.test/home", "DownloadEntryProfileUUIDStringKey": "DefaultProfile"}, + map[string]any{"DownloadEntryURL": "https://a.test/work", "DownloadEntryProfileUUIDStringKey": workUUID}, + map[string]any{"DownloadEntryURL": "https://a.test/legacy"}, + }, + })}) + urls := func(p browser.Profile) []string { + out, err := extract(t, snap, p, nil, category.Download) + require.NoError(t, err) + var got []string + for _, d := range collected[record.Download](t, out) { + got = append(got, d.URL) + } + return got + } + assert.Equal(t, []string{"https://a.test/home", "https://a.test/legacy"}, urls(defaultProfile)) + assert.Equal(t, []string{"https://a.test/work"}, urls(workProfile)) +} + +// The extension plists are read from the snapshot; a missing one is skipped. +func TestExtractors_ExtensionsFromTheSnapshot(t *testing.T) { + snap := snapshotOf(t, map[string]string{ + containerDir + "/Safari/WebExtensions/Extensions.plist": writeTestPlist(t, map[string]any{ + "com.example.Blocker.Extension (ABCDE12345)": map[string]any{"Enabled": false}, + }), + }) + out, err := extract(t, snap, defaultProfile, nil, category.Extension) + require.NoError(t, err) + got := collected[record.Extension](t, out) + require.Len(t, got, 1) + assert.Equal(t, "com.example.Blocker.Extension", got[0].Name) + assert.False(t, got[0].Enabled) +} + +type fakeKeychain struct { + passwords []keychainbreaker.InternetPassword + err error + calls int +} + +func (k *fakeKeychain) InternetPasswords(context.Context) ([]keychainbreaker.InternetPassword, error) { + k.calls++ + return k.passwords, k.err +} + +func TestExtractors_PasswordsFromTheKeychain(t *testing.T) { + created := time.Date(2024, 3, 1, 9, 0, 0, 0, time.FixedZone("CET", 3600)) + kc := &fakeKeychain{passwords: []keychainbreaker.InternetPassword{ + {Protocol: "htps", Server: "github.com", Port: 443, Account: "alice", PlainPassword: "s3cret", Created: created}, + {Protocol: "htps", Server: "locked.test", Account: "bob"}, + {Protocol: "htps", Server: "", Account: "nobody"}, + {Protocol: "htps", Server: "anonymous.test", Account: ""}, + }} + out, err := extract(t, snapshotOf(t, nil), defaultProfile, kc, category.Password) + require.NoError(t, err) + assert.Equal(t, []record.Login{ + {URL: "https://github.com", Username: "alice", Password: "s3cret", CreatedAt: created.UTC(), Store: record.StoreLocal}, + {URL: "https://locked.test", Username: "bob", Store: record.StoreLocal}, + }, collected[record.Login](t, out)) + assert.Equal(t, 1, kc.calls) +} + +func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) { + _, err := extract(t, snapshotOf(t, nil), defaultProfile, nil, category.Password) + require.ErrorIs(t, err, errNoKeychain) + + broken := errors.New("keychain unreadable") + _, err = extract(t, snapshotOf(t, nil), defaultProfile, &fakeKeychain{err: broken}, category.Password) + require.ErrorIs(t, err, broken) +} + +// The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them. +func TestExtractors_NamedProfileSkipsUserWideSources(t *testing.T) { + ex := Extractors(libraryDir, workProfile, &fakeKeychain{}) + for _, c := range []category.Category{category.Password, category.Bookmark, category.Extension} { + assert.NotContains(t, ex, c) + } +} diff --git a/internal/browser/safari/testutil_test.go b/internal/browser/safari/testutil_test.go new file mode 100644 index 0000000..043b5bb --- /dev/null +++ b/internal/browser/safari/testutil_test.go @@ -0,0 +1,299 @@ +package safari + +import ( + "database/sql" + "encoding/binary" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "unicode/utf16" + + "github.com/stretchr/testify/require" + _ "modernc.org/sqlite" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// --------------------------------------------------------------------------- +// Real Safari table schemas — extracted via `sqlite3 History.db ".schema"`. +// --------------------------------------------------------------------------- + +const safariHistoryItemsSchema = `CREATE TABLE history_items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT NOT NULL UNIQUE, + domain_expansion TEXT NULL, + visit_count INTEGER NOT NULL DEFAULT 0, + daily_visit_counts BLOB NOT NULL DEFAULT x'', + weekly_visit_counts BLOB NULL, + autocomplete_triggers BLOB NULL, + should_recompute_derived_visit_counts INTEGER NOT NULL DEFAULT 1, + visit_count_score INTEGER NOT NULL DEFAULT 0 +)` + +const safariHistoryVisitsSchema = `CREATE TABLE history_visits ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + history_item INTEGER NOT NULL REFERENCES history_items(id), + visit_time REAL NOT NULL, + title TEXT NULL, + load_successful BOOLEAN NOT NULL DEFAULT 1, + http_non_get INTEGER NOT NULL DEFAULT 0, + synthesized INTEGER NOT NULL DEFAULT 0, + redirect_source INTEGER NULL, + redirect_destination INTEGER NULL, + origin INTEGER NOT NULL DEFAULT 0, + generation INTEGER NOT NULL DEFAULT 0, + attributes INTEGER NOT NULL DEFAULT 0, + score INTEGER NOT NULL DEFAULT 0 +)` + +// --------------------------------------------------------------------------- +// INSERT helpers +// --------------------------------------------------------------------------- + +func insertHistoryItem(id int, url, domainExpansion string, visitCount int) string { + return fmt.Sprintf( + `INSERT INTO history_items (id, url, domain_expansion, visit_count) + VALUES (%d, '%s', '%s', %d)`, + id, url, domainExpansion, visitCount, + ) +} + +func insertHistoryVisit(id, historyItem int, visitTime float64, title string) string { + return fmt.Sprintf( + `INSERT INTO history_visits (id, history_item, visit_time, title) + VALUES (%d, %d, %f, '%s')`, + id, historyItem, visitTime, title, + ) +} + +// --------------------------------------------------------------------------- +// Test fixture builders +// --------------------------------------------------------------------------- + +func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { //nolint:unparam // name will vary when future data types are added + t.Helper() + path := filepath.Join(t.TempDir(), name) + db, err := sql.Open("sqlite", path) + require.NoError(t, err) + defer db.Close() + + for _, schema := range schemas { + _, err = db.Exec(schema) + require.NoError(t, err) + } + for _, stmt := range inserts { + _, err = db.Exec(stmt) + require.NoError(t, err) + } + return path +} + +// --------------------------------------------------------------------------- +// SafariTabs.db fixtures +// --------------------------------------------------------------------------- + +// tabRow describes one profile entry to stamp into the fake SafariTabs.db. +type tabRow struct { + uuid string + title string +} + +// writeSafariTabsDB creates a minimal SafariTabs.db at path containing only +// the bookmarks columns discoverSafariProfiles reads. Every row gets +// subtype=2 (profile record) so the production query picks it up. +func writeSafariTabsDB(t *testing.T, path string, rows []tabRow) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + + db, err := sql.Open("sqlite", path) + require.NoError(t, err) + defer db.Close() + + _, err = db.Exec(`CREATE TABLE bookmarks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + external_uuid TEXT, + title TEXT, + subtype INTEGER DEFAULT 0 + )`) + require.NoError(t, err) + + for _, r := range rows { + _, err = db.Exec(`INSERT INTO bookmarks (external_uuid, title, subtype) VALUES (?, ?, 2)`, r.uuid, r.title) + require.NoError(t, err) + } +} + +// --------------------------------------------------------------------------- +// LocalStorage fixtures — modern WebKit nested Origins layout +// --------------------------------------------------------------------------- + +// testLocalStorageItem is one key/value pair written to an ItemTable row. +// Value is encoded as UTF-16 LE, matching WebKit's on-disk format. +type testLocalStorageItem struct { + Key, Value string +} + +// buildTestLocalStorageDir creates a root dir that mirrors Safari 17+'s nested +// localStorage layout (/

/

/origin + LocalStorage/localstorage.sqlite3) +// for each origin URL passed in. Origins are written as first-party (top == frame); +// for partitioned-origin coverage, use buildTestPartitionedLocalStorage. +func buildTestLocalStorageDir(t *testing.T, origins map[string][]testLocalStorageItem) string { + t.Helper() + root := filepath.Join(t.TempDir(), "Origins") + require.NoError(t, os.MkdirAll(root, 0o755)) + + i := 0 + for origin, items := range origins { + hash := fmt.Sprintf("h%02d", i) + i++ + writeTestOriginStore(t, root, hash, hash, origin, origin, items) + } + return root +} + +// writeTestOriginStore writes one /// tree with the given +// origins encoded into the binary origin file and items inserted into localstorage.sqlite3. +func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, frameOrigin string, items []testLocalStorageItem) { + t.Helper() + frameDir := filepath.Join(root, topHash, frameHash) + require.NoError(t, os.MkdirAll(filepath.Join(frameDir, webkitLocalStorageSubdir), 0o755)) + + require.NoError(t, os.WriteFile( + filepath.Join(frameDir, webkitOriginFile), + encodeOriginFile(topOrigin, frameOrigin), + 0o644, + )) + + dbPath := filepath.Join(frameDir, webkitLocalStorageSubdir, webkitLocalStorageDB) + db, err := sql.Open("sqlite", dbPath) + require.NoError(t, err) + _, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`) + require.NoError(t, err) + for _, item := range items { + _, err = db.Exec( + `INSERT INTO ItemTable (key, value) VALUES (?, ?)`, + item.Key, encodeUTF16LE(item.Value), + ) + require.NoError(t, err) + } + require.NoError(t, db.Close()) +} + +// encodeOriginFile mirrors WebKit's SecurityOrigin binary serialization. Layout per origin +// block: length-prefixed scheme record, length-prefixed host record, then a port marker +// (0x00 for the scheme default, or 0x01 + uint16_le port). Two blocks back-to-back: top-frame +// then frame. +func encodeOriginFile(topOrigin, frameOrigin string) []byte { + var buf []byte + buf = appendOriginBlock(buf, topOrigin) + buf = appendOriginBlock(buf, frameOrigin) + return buf +} + +func appendOriginBlock(buf []byte, originURL string) []byte { + scheme, host, port := splitTestOriginURL(originURL) + buf = appendOriginRecord(buf, scheme) + buf = appendOriginRecord(buf, host) + if port == 0 { + buf = append(buf, originPortDefaultMarker) + return buf + } + buf = append(buf, originPortExplicitFlag) + portBytes := make([]byte, 2) + binary.LittleEndian.PutUint16(portBytes, port) + return append(buf, portBytes...) +} + +func appendOriginRecord(buf []byte, s string) []byte { + lenBytes := make([]byte, 4) + binary.LittleEndian.PutUint32(lenBytes, uint32(len(s))) + buf = append(buf, lenBytes...) + buf = append(buf, originEncASCII) + return append(buf, []byte(s)...) +} + +// splitTestOriginURL parses "https://example.com[:port]" into (scheme, host, port). +// Port 0 means the URL had no explicit port (use scheme default). +func splitTestOriginURL(u string) (scheme, host string, port uint16) { + idx := strings.Index(u, "://") + if idx < 0 { + return "", u, 0 + } + scheme = u[:idx] + rest := u[idx+3:] + if colon := strings.LastIndex(rest, ":"); colon >= 0 { + if p, err := strconv.ParseUint(rest[colon+1:], 10, 16); err == nil { + return scheme, rest[:colon], uint16(p) + } + } + return scheme, rest, 0 +} + +// writeLocalStorageDB creates a minimal localstorage.sqlite3 at path with ItemTable populated +// from items. When addNullKey is true, a NULL-key row is inserted first to exercise the +// skip-NULL-key logic in readLocalStorageFile / countLocalStorageFile. This is a direct-DB +// variant of buildTestLocalStorageDir — use it when the test targets one DB, not the full +// Origins nesting. +func writeLocalStorageDB(t *testing.T, path string, items []testLocalStorageItem, addNullKey bool) { + t.Helper() + db, err := sql.Open("sqlite", path) + require.NoError(t, err) + _, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`) + require.NoError(t, err) + if addNullKey { + _, err = db.Exec( + `INSERT INTO ItemTable (key, value) VALUES (NULL, ?)`, + encodeUTF16LE("null-key-sentinel"), + ) + require.NoError(t, err) + } + for _, item := range items { + _, err = db.Exec( + `INSERT INTO ItemTable (key, value) VALUES (?, ?)`, + item.Key, encodeUTF16LE(item.Value), + ) + require.NoError(t, err) + } + require.NoError(t, db.Close()) +} + +// encodeUTF16LE is the inverse of extract_storage.go's decodeUTF16LE — it mirrors +// the WebKit encoding so test fixtures round-trip through the extractor. +func encodeUTF16LE(s string) []byte { + u16 := utf16.Encode([]rune(s)) + buf := make([]byte, 2*len(u16)) + for i, r := range u16 { + binary.LittleEndian.PutUint16(buf[i*2:], r) + } + return buf +} + +func mkFile(t *testing.T, parts ...string) { + t.Helper() + path := filepath.Join(parts...) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte("test"), 0o644)) +} + +// testCollector keeps what an extractor hands it, in order. +type testCollector struct { + records []record.Record + fails []error +} + +func (c *testCollector) Add(r record.Record) { c.records = append(c.records, r) } +func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } + +func collected[T any](t *testing.T, c *testCollector) []T { + t.Helper() + got := make([]T, 0, len(c.records)) + for _, r := range c.records { + v, ok := any(r).(*T) + require.Truef(t, ok, "collected a %T, want *%T", r, *new(T)) + got = append(got, *v) + } + return got +} diff --git a/rfcs/003-core-types.md b/rfcs/003-core-types.md index ac9a58a..bb45617 100644 --- a/rfcs/003-core-types.md +++ b/rfcs/003-core-types.md @@ -42,7 +42,7 @@ Two IDs sit side by side and must not be confused: `dir.ID` (`arc-2`) names the `Profile.Name` is frozen by the output contract ([RFC-000](000-goals-and-constraints.md)): for Chromium the directory's base name (`Default`, `Profile 1` — what Chromium's `Profile::GetBaseName()` returns, not the display name `Local State` keeps in `profile.info_cache`); for Firefox the directory name (`97nszz88.default-release`); for Safari, `default` or the named profile's title (deduplicated with a `-N` suffix, the UUID when untitled). It is never a path. -Safari has no single data directory — History lives under `~/Library/Safari`, cookies under `~/Library/Containers/com.apple.Safari/…` or `~/Library/Cookies` — so its user data dir is `~/Library`, the nearest common ancestor. +Safari has no single data directory — History lives under `~/Library/Safari`, cookies under `~/Library/Containers/com.apple.Safari/…` or `~/Library/Cookies` — so its user data dir is `~/Library`, the nearest common ancestor. The default profile's `Dir` is `Safari`; a named profile's is its own directory, `Containers/com.apple.Safari/Data/Library/Safari/Profiles/`. ## Extractor contract — `internal/browser` @@ -65,9 +65,9 @@ type Extractor struct { type Extractors map[category.Category]Extractor ``` -Sources are static data: a base package declares them once per category and never rewrites them per profile. Plan joins a profile-scoped path with the profile's `Dir`, leaves a `Shared` one as it is, and captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. +Sources are static data: a base package declares them once per category and never rewrites them per profile. Plan joins a profile-scoped path with the profile's `Dir`, leaves a `Shared` one as it is, and captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. Safari is the exception: a named profile's files sit under two directories named for its UUID, so `safari.Extractors` builds each profile's sources from its `Dir`, and reaches files elsewhere under `~/Library` with `..` from there. -An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none of the profile's own is there: a shared source such as `Local State` never makes an extraction present by itself. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces today's output, including a profile that only ever synced passwords, without a special case. +An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none of the profile's own is there: a shared source such as `Local State` never makes an extraction present by itself. An extractor that reads no file — Safari's passwords, which come from the login keychain — always runs. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces today's output, including a profile that only ever synced passwords, without a special case. `Extractor` / `Extractors` are **DECIDED**.