diff --git a/browser/archive.go b/browser/archive.go deleted file mode 100644 index 807cb5e..0000000 --- a/browser/archive.go +++ /dev/null @@ -1,79 +0,0 @@ -package browser - -import ( - "context" - "fmt" - - "github.com/moond4rk/hackbrowserdata/browser/chromium" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/snapshot" -) - -// Archivable is implemented by installations that can enumerate their decryption-relevant files for -// cross-host transport (Chromium only). -type Archivable interface { - BrowserKey() string - UserDataDir() string - ArchiveSources(categories []category.Category) []chromium.ArchiveSource -} - -// WriteArchive packs each browser's decryption-relevant files into a zip whose internal layout is -// /, so a restore can re-expand it and decrypt with a keys.json. Returns -// the number of source entries captured (a directory source counts once). -func WriteArchive(browsers []Browser, categories []category.Category, outPath string) (int, error) { - files := archiveFiles(browsers, categories) - - d, err := snapshot.Temp() - if err != nil { - return 0, err - } - defer closeSnapshot(d) - - if err := d.Capture(context.Background(), files); err != nil { - return 0, err - } - count := 0 - for _, f := range files { - if _, err := d.Snapshot(f.DirID).Path(f.Rel); err != nil { - log.Warnf("archive: acquire %s/%s: %v", f.DirID, f.Rel, err) - continue - } - count++ - } - if count == 0 { - return 0, fmt.Errorf("no decryption-relevant files found to archive") - } - if err := d.Zip(outPath); err != nil { - return 0, fmt.Errorf("write archive %s: %w", outPath, err) - } - return count, nil -} - -// archiveFiles lists each source once; the browser key is its snapshot ID, so the zip's top level stays /. -func archiveFiles(browsers []Browser, categories []category.Category) []snapshot.File { - var files []snapshot.File - seen := make(map[string]bool) - for _, b := range browsers { - archivable, ok := b.(Archivable) - if !ok { - continue - } - key := archivable.BrowserKey() - for _, src := range archivable.ArchiveSources(categories) { - entry := key + "/" + src.LayoutRel - if seen[entry] { - continue - } - seen[entry] = true - files = append(files, snapshot.File{DirID: key, From: archivable.UserDataDir(), Rel: src.LayoutRel, IsDir: src.IsDir}) - } - } - return files -} - -func closeSnapshot(d *snapshot.Dir) { - if err := d.Close(); err != nil { - log.Warnf("archive: %v", err) - } -} diff --git a/browser/archive_test.go b/browser/archive_test.go deleted file mode 100644 index fa28152..0000000 --- a/browser/archive_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package browser - -import ( - "archive/zip" - "os" - "path/filepath" - "reflect" - "sort" - "testing" - - "github.com/moond4rk/hackbrowserdata/browser/chromium" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/snapshot" - "github.com/moond4rk/hackbrowserdata/types" -) - -// TestWriteArchive_RoundTrip exercises the archive path: ArchiveSources -> WriteArchive (stage+zip) -// -> Unzip, asserting the archive's internal layout is /. -func TestWriteArchive_RoundTrip(t *testing.T) { - origin := t.TempDir() - def := filepath.Join(origin, "Default") - if err := os.MkdirAll(def, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(def, "Preferences"), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(def, "History"), []byte("hist"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(origin, "Local State"), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - - b, err := chromium.NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: origin}) - if err != nil || b == nil { - t.Fatalf("NewBrowser: b=%v err=%v", b, err) - } - - zipPath := filepath.Join(t.TempDir(), "data.zip") - n, err := WriteArchive([]Browser{b}, []category.Category{category.History}, zipPath) - if err != nil { - t.Fatalf("WriteArchive: %v", err) - } - if n == 0 { - t.Fatal("WriteArchive captured 0 entries") - } - - d, err := snapshot.Unzip(zipPath) - if err != nil { - t.Fatalf("Unzip: %v", err) - } - defer d.Close() - extracted := d.Path() - for _, rel := range []string{ - filepath.Join("chrome", "Default", "History"), - filepath.Join("chrome", "Default", "Preferences"), - filepath.Join("chrome", "Local State"), - } { - if _, err := os.Stat(filepath.Join(extracted, rel)); err != nil { - t.Errorf("expected %s in archive layout: %v", rel, err) - } - } -} - -// WriteArchive copies each source from UserDataDir/LayoutRel, so that path must be exactly the source's AbsPath. -func TestArchiveSources_AbsPathIsUserDataDirPlusLayoutRel(t *testing.T) { - nested := t.TempDir() - for _, rel := range []string{ - "Local State", "Default/Preferences", "Default/History", "Default/Login Data", - "Default/Login Data For Account", "Profile 1/Preferences", "Profile 1/Network/Cookies", - } { - writeArchiveFile(t, nested, rel) - } - flat := t.TempDir() - writeArchiveFile(t, flat, "History") - - for _, udd := range []string{nested, flat} { - b, err := chromium.NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: udd}) - if err != nil || b == nil { - t.Fatalf("NewBrowser(%s): b=%v err=%v", udd, b, err) - } - srcs := b.ArchiveSources(category.All()) - if len(srcs) == 0 { - t.Fatalf("%s: no archive sources", udd) - } - for _, src := range srcs { - if want := filepath.Join(b.UserDataDir(), filepath.FromSlash(src.LayoutRel)); src.AbsPath != want { - t.Errorf("AbsPath = %q, want %q", src.AbsPath, want) - } - } - } -} - -func TestWriteArchive_CountsOnlyCapturedSources(t *testing.T) { - origin := t.TempDir() - for _, rel := range []string{"Local State", "Default/Preferences", "Default/History", "Default/Bookmarks"} { - writeArchiveFile(t, origin, rel) - } - b, err := chromium.NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: origin}) - if err != nil || b == nil { - t.Fatalf("NewBrowser: b=%v err=%v", b, err) - } - if err := os.Remove(filepath.Join(origin, "Default", "History")); err != nil { - t.Fatal(err) - } - - zipPath := filepath.Join(t.TempDir(), "data.zip") - n, err := WriteArchive([]Browser{b}, []category.Category{category.History, category.Bookmark}, zipPath) - if err != nil { - t.Fatalf("WriteArchive: %v", err) - } - if n != 3 { - t.Errorf("WriteArchive counted %d entries, want 3: the vanished History must not count", n) - } - - r, err := zip.OpenReader(zipPath) - if err != nil { - t.Fatal(err) - } - defer r.Close() - var got []string - for _, f := range r.File { - got = append(got, f.Name) - } - sort.Strings(got) - want := []string{"chrome/Default/Bookmarks", "chrome/Default/Preferences", "chrome/Local State"} - if !reflect.DeepEqual(got, want) { - t.Errorf("archive entries = %q, want %q", got, want) - } -} - -func writeArchiveFile(t *testing.T, root, rel string) { - t.Helper() - path := filepath.Join(root, filepath.FromSlash(rel)) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte(rel), 0o600); err != nil { - t.Fatal(err) - } -} diff --git a/browser/browser.go b/browser/browser.go deleted file mode 100644 index 46a0581..0000000 --- a/browser/browser.go +++ /dev/null @@ -1,179 +0,0 @@ -package browser - -import ( - "fmt" - "path/filepath" - "sort" - "strings" - - "github.com/moond4rk/hackbrowserdata/browser/chromium" - "github.com/moond4rk/hackbrowserdata/browser/firefox" - "github.com/moond4rk/hackbrowserdata/browser/safari" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/types" -) - -// Browser is one installation: a UserDataDir holding profiles that (for Chromium) share one master key. -type Browser interface { - BrowserName() string - UserDataDir() string - Profiles() []types.Profile - Extract(categories []category.Category) ([]types.ExtractResult, error) - CountEntries(categories []category.Category) ([]types.CountResult, error) -} - -type DiscoverOptions struct { - Name string // "all"|"chrome"|"firefox"|... - ProfilePath string // custom profile dir override - KeychainPassword string // macOS only — see browser_darwin.go -} - -// browserInjector injects decryption credentials into a Browser; built per-platform by newCredentialInjector. -type browserInjector func(Browser) - -// DiscoverBrowsersWithKeys is DiscoverBrowsers plus credential injection, so the returned installations are ready for Extract. -// On macOS it may prompt for the login password — metadata-only callers should use DiscoverBrowsers to avoid the prompt. -func DiscoverBrowsersWithKeys(opts DiscoverOptions) ([]Browser, error) { - browsers, err := DiscoverBrowsers(opts) - if err != nil { - return nil, err - } - inject := newCredentialInjector(opts) - for _, b := range browsers { - inject(b) - } - return browsers, nil -} - -// DiscoverBrowsers skips credential injection: metadata (Profiles, CountEntries) works, Extract won't decrypt protected data, -// and macOS never prompts. Use it for list-style commands. -func DiscoverBrowsers(opts DiscoverOptions) ([]Browser, error) { - return discoverFromConfigs(platformBrowsers(), opts) -} - -// discoverFromConfigs is the testable core of DiscoverBrowsers; it deliberately does no credential injection. -func discoverFromConfigs(configs []types.BrowserConfig, opts DiscoverOptions) ([]Browser, error) { - name := strings.ToLower(opts.Name) - if name == "" { - name = "all" - } - - configs = resolveGlobs(configs) - - var browsers []Browser - for _, cfg := range configs { - if name != "all" && cfg.Key != name { - continue - } - - if opts.ProfilePath != "" && name != "all" { - if cfg.Kind == types.Firefox { - cfg.UserDataDir = filepath.Dir(filepath.Clean(opts.ProfilePath)) - } else { - cfg.UserDataDir = opts.ProfilePath - } - } - - b, err := newBrowser(cfg) - if err != nil { - log.Errorf("browser %s: %v", cfg.Name, err) - continue - } - if b == nil { - log.Debugf("browser %s not found at %s", cfg.Name, cfg.UserDataDir) - continue - } - - browsers = append(browsers, b) - } - return browsers, nil -} - -// KeyManager is implemented by installations accepting external master-key retrievers (Chromium only). -// BrowserKey/Kind expose the identity a portable dump needs to rebuild the engine off the platform table. -type KeyManager interface { - SetLocator(masterkey.Locator) // live: the run's cross-cutting key sources (macOS keychain, Windows ABE exe) - SetKeys(masterkey.Set) // restore: keys already known from a dump - ExportKeys() (masterkey.Set, error) - BrowserKey() string - Kind() types.BrowserKind -} - -// KeychainPasswordReceiver is implemented by installations that need the macOS login password (Safari only). -type KeychainPasswordReceiver interface { - SetKeychainPassword(string) -} - -// resolveGlobs expands UserDataDir glob patterns for Windows MSIX/UWP browsers whose package dirs carry a dynamic -// publisher-hash suffix (e.g. "TheBrowserCompany.Arc_*"). A glob matching N dirs yields N configs. -func resolveGlobs(configs []types.BrowserConfig) []types.BrowserConfig { - var out []types.BrowserConfig - for _, cfg := range configs { - matches, _ := filepath.Glob(cfg.UserDataDir) - if len(matches) == 0 { - out = append(out, cfg) - continue - } - for _, dir := range matches { - c := cfg - c.UserDataDir = dir - out = append(out, c) - } - } - return out -} - -// newBrowser dispatches on BrowserKind, returning a nil Browser when no profile is found. -func newBrowser(cfg types.BrowserConfig) (Browser, error) { - switch cfg.Kind { - case types.Chromium, types.ChromiumYandex, types.ChromiumOpera: - b, err := chromium.NewBrowser(cfg) - if err != nil { - return nil, err - } - if b == nil { - return nil, nil - } - return b, nil - - case types.Firefox: - b, err := firefox.NewBrowser(cfg) - if err != nil { - return nil, err - } - if b == nil { - return nil, nil - } - return b, nil - - case types.Safari: - b, err := safari.NewBrowser(cfg) - if err != nil { - return nil, err - } - if b == nil { - return nil, nil - } - return b, nil - - default: - return nil, fmt.Errorf("unknown browser kind: %d", cfg.Kind) - } -} - -// ListBrowsers returns sorted keys of all platform browsers. -func ListBrowsers() []string { - var l []string - for _, cfg := range platformBrowsers() { - l = append(l, cfg.Key) - } - sort.Strings(l) - return l -} - -// Names returns a pipe-separated list of browser keys for CLI help text. -func Names() string { - return strings.Join(ListBrowsers(), "|") -} diff --git a/browser/browser_darwin.go b/browser/browser_darwin.go deleted file mode 100644 index fb58f79..0000000 --- a/browser/browser_darwin.go +++ /dev/null @@ -1,93 +0,0 @@ -//go:build darwin - -package browser - -import ( - "context" - "fmt" - "os" - "path/filepath" - - "github.com/moond4rk/keychainbreaker" - "golang.org/x/term" - - "github.com/moond4rk/hackbrowserdata/internal/keychain" - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" -) - -// loginKeychainPath is the per-user login keychain the run reads Chromium v10 secrets from. -func loginKeychainPath() string { - home, err := os.UserHomeDir() - if err != nil { - return "" - } - return filepath.Join(home, "Library", "Keychains", "login.keychain-db") -} - -// resolveKeychainPassword resolves the macOS login password (CLI flag, else TTY prompt) and verifies it against -// keychainbreaker. On any failure it returns "" so callers fall back to no-password mode rather than a known-bad credential. -func resolveKeychainPassword(flagPassword string) string { - password := flagPassword - if password == "" { - if !term.IsTerminal(int(os.Stdin.Fd())) { - log.Warnf("macOS login password not provided and stdin is not a TTY; keychain-protected data will be exported as metadata only") - return "" - } - fmt.Fprint(os.Stderr, "Enter macOS login password: ") - pwd, err := term.ReadPassword(int(os.Stdin.Fd())) - fmt.Fprintln(os.Stderr) - if err != nil { - log.Warnf("failed to read macOS login password: %v; keychain-protected data will be exported as metadata only", err) - return "" - } - password = string(pwd) - } - - if password == "" { - log.Warnf("no macOS login password entered; keychain-protected data will be exported as metadata only") - return "" - } - - kc, err := keychainbreaker.Open() - if err != nil { - log.Warnf("keychain open failed: %v; keychain-protected data will be exported as metadata only", err) - return "" - } - if err := kc.TryUnlock(keychainbreaker.WithPassword(password)); err != nil { - log.Warnf("keychain unlock failed with provided password; keychain-protected data will be exported as metadata only") - log.Debugf("keychain unlock detail: %v", err) - return "" - } - - return password -} - -// newCredentialInjector lazily resolves the macOS login password and hands every Chromium browser the run's -// login keychain; `-b firefox` never triggers a prompt because resolution is skipped for browsers that need neither. -func newCredentialInjector(opts DiscoverOptions) browserInjector { - var ( - password string - kc *keychain.Keychain - resolved bool - ) - return func(b Browser) { - km, needsKeychain := b.(KeyManager) - kps, needsKeychainPassword := b.(KeychainPasswordReceiver) - if !needsKeychain && !needsKeychainPassword { - return - } - if !resolved { - password = resolveKeychainPassword(opts.KeychainPassword) - pw := password - kc = keychain.New(loginKeychainPath(), func(context.Context) (string, error) { return pw, nil }) - resolved = true - } - if needsKeychain { - km.SetLocator(masterkey.Locator{Keychain: kc}) - } - if needsKeychainPassword { - kps.SetKeychainPassword(password) - } - } -} diff --git a/browser/browser_linux.go b/browser/browser_linux.go deleted file mode 100644 index df187d7..0000000 --- a/browser/browser_linux.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build linux - -package browser - -// newCredentialInjector is a no-op on Linux: RetrieveAll runs the peanuts (v10) and D-Bus keyring (v11) -// retrievers itself, and a Chromium browser builds the rest of its Locator from its own config. -func newCredentialInjector(_ DiscoverOptions) browserInjector { - return func(Browser) {} -} diff --git a/browser/browser_test.go b/browser/browser_test.go deleted file mode 100644 index 8049a86..0000000 --- a/browser/browser_test.go +++ /dev/null @@ -1,436 +0,0 @@ -package browser - -import ( - "os" - "path/filepath" - "sort" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/types" -) - -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)) -} - -func TestListBrowsers(t *testing.T) { - list := ListBrowsers() - assert.NotEmpty(t, list) - assert.True(t, sort.StringsAreSorted(list)) -} - -type pickTest struct { - name string - configs []types.BrowserConfig - opts DiscoverOptions - wantNames []string - wantProfiles []string -} - -func runPickTests(t *testing.T, tests []pickTest) { - t.Helper() - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - browsers, err := discoverFromConfigs(tt.configs, tt.opts) - require.NoError(t, err) - assertBrowsers(t, browsers, tt.wantNames, tt.wantProfiles) - }) - } -} - -func TestPickFromConfigs(t *testing.T) { - // --- fixtures: single-profile chromium (for name filter tests) --- - singleDir := t.TempDir() - mkFile(t, singleDir, "Default", "Preferences") - mkFile(t, singleDir, "Default", "Login Data") - mkFile(t, singleDir, "Default", "History") - - // --- fixtures: multi-profile chromium --- - chromeDir := t.TempDir() - mkFile(t, chromeDir, "Default", "Preferences") - mkFile(t, chromeDir, "Default", "Login Data") - mkFile(t, chromeDir, "Default", "History") - mkFile(t, chromeDir, "Profile 1", "Preferences") - mkFile(t, chromeDir, "Profile 1", "Login Data") - mkFile(t, chromeDir, "Profile 1", "History") - - // --- fixtures: firefox --- - firefoxDir := t.TempDir() - mkFile(t, firefoxDir, "abc123.default-release", "logins.json") - mkFile(t, firefoxDir, "abc123.default-release", "places.sqlite") - - // --- fixtures: yandex --- - yandexDir := t.TempDir() - mkFile(t, yandexDir, "Default", "Preferences") - mkFile(t, yandexDir, "Default", "Ya Passman Data") - mkFile(t, yandexDir, "Default", "History") - - // --- fixtures: glob (MSIX-like package directories) --- - globBase := t.TempDir() - mkFile(t, globBase, "App.Browser_abc123", "UserData", "Default", "Preferences") - mkFile(t, globBase, "App.Browser_abc123", "UserData", "Default", "History") - mkFile(t, globBase, "App.Browser_def456", "UserData", "Default", "Preferences") - mkFile(t, globBase, "App.Browser_def456", "UserData", "Default", "History") - mkFile(t, globBase, "Solo.Browser_xyz789", "UserData", "Default", "Preferences") - mkFile(t, globBase, "Solo.Browser_xyz789", "UserData", "Default", "History") - - nameFilterConfigs := []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: singleDir}, - {Key: "edge", Name: "Edge", Kind: types.Chromium, UserDataDir: singleDir}, - } - - t.Run("NameFilter", func(t *testing.T) { - runPickTests(t, []pickTest{ - { - name: "exact match", - configs: nameFilterConfigs, - opts: DiscoverOptions{Name: "chrome"}, - wantNames: []string{"Chrome"}, - wantProfiles: []string{"Default"}, - }, - { - name: "case insensitive", - configs: nameFilterConfigs, - opts: DiscoverOptions{Name: "Chrome"}, - wantNames: []string{"Chrome"}, - wantProfiles: []string{"Default"}, - }, - { - name: "all returns both", - configs: nameFilterConfigs, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Chrome", "Edge"}, - wantProfiles: []string{"Default", "Default"}, - }, - { - name: "unknown returns empty", - configs: nameFilterConfigs, - opts: DiscoverOptions{Name: "safari"}, - }, - }) - }) - - t.Run("BrowserKind", func(t *testing.T) { - runPickTests(t, []pickTest{ - { - name: "chromium multi-profile", - configs: []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: chromeDir}, - }, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Chrome", "Chrome"}, - wantProfiles: []string{"Default", "Profile 1"}, - }, - { - name: "firefox random dir", - configs: []types.BrowserConfig{ - {Key: "firefox", Name: "Firefox", Kind: types.Firefox, UserDataDir: firefoxDir}, - }, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Firefox"}, - wantProfiles: []string{"abc123.default-release"}, - }, - { - name: "yandex variant", - configs: []types.BrowserConfig{ - {Key: "yandex", Name: "Yandex", Kind: types.ChromiumYandex, UserDataDir: yandexDir}, - }, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Yandex"}, - wantProfiles: []string{"Default"}, - }, - { - name: "nonexistent dir", - configs: []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: "/nonexistent"}, - }, - opts: DiscoverOptions{Name: "all"}, - }, - }) - }) - - t.Run("ProfilePath", func(t *testing.T) { - runPickTests(t, []pickTest{ - { - name: "chromium uses path directly", - configs: []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: "/wrong"}, - }, - opts: DiscoverOptions{Name: "chrome", ProfilePath: filepath.Join(chromeDir, "Default")}, - wantNames: []string{"Chrome"}, - wantProfiles: []string{"Default"}, - }, - { - name: "firefox uses parent dir", - configs: []types.BrowserConfig{ - {Key: "firefox", Name: "Firefox", Kind: types.Firefox, UserDataDir: "/wrong"}, - }, - opts: DiscoverOptions{Name: "firefox", ProfilePath: filepath.Join(firefoxDir, "abc123.default-release")}, - wantNames: []string{"Firefox"}, - wantProfiles: []string{"abc123.default-release"}, - }, - { - name: "ignored when name is all", - configs: []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: chromeDir}, - }, - opts: DiscoverOptions{Name: "all", ProfilePath: "/some/override"}, - wantNames: []string{"Chrome", "Chrome"}, - wantProfiles: []string{"Default", "Profile 1"}, - }, - }) - }) - - t.Run("Glob", func(t *testing.T) { - runPickTests(t, []pickTest{ - { - name: "single match", - configs: []types.BrowserConfig{ - {Key: "solo", Name: "Solo", Kind: types.Chromium, UserDataDir: filepath.Join(globBase, "Solo.Browser_*", "UserData")}, - }, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Solo"}, - wantProfiles: []string{"Default"}, - }, - { - name: "multiple matches", - configs: []types.BrowserConfig{ - {Key: "arc", Name: "Arc", Kind: types.Chromium, UserDataDir: filepath.Join(globBase, "App.Browser_*", "UserData")}, - }, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Arc", "Arc"}, - wantProfiles: []string{"Default", "Default"}, - }, - { - name: "no match", - configs: []types.BrowserConfig{ - {Key: "missing", Name: "Missing", Kind: types.Chromium, UserDataDir: filepath.Join(globBase, "NoSuch_*", "UserData")}, - }, - opts: DiscoverOptions{Name: "all"}, - }, - { - name: "mixed with literal", - configs: []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: singleDir}, - {Key: "arc", Name: "Arc", Kind: types.Chromium, UserDataDir: filepath.Join(globBase, "Solo.Browser_*", "UserData")}, - }, - opts: DiscoverOptions{Name: "all"}, - wantNames: []string{"Arc", "Chrome"}, - wantProfiles: []string{"Default", "Default"}, - }, - { - name: "with name filter", - configs: []types.BrowserConfig{ - {Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: singleDir}, - {Key: "arc", Name: "Arc", Kind: types.Chromium, UserDataDir: filepath.Join(globBase, "App.Browser_*", "UserData")}, - }, - opts: DiscoverOptions{Name: "arc"}, - wantNames: []string{"Arc", "Arc"}, - wantProfiles: []string{"Default", "Default"}, - }, - }) - }) -} - -func TestResolveGlobs(t *testing.T) { - // Create directories for glob matching: - // base/ - // ├── App.Browser_abc123/UserData/ (match 1) - // ├── App.Browser_def456/UserData/ (match 2) - // └── ExactBrowser/UserData/ (literal path) - base := t.TempDir() - require.NoError(t, os.MkdirAll(filepath.Join(base, "App.Browser_abc123", "UserData"), 0o755)) - require.NoError(t, os.MkdirAll(filepath.Join(base, "App.Browser_def456", "UserData"), 0o755)) - require.NoError(t, os.MkdirAll(filepath.Join(base, "ExactBrowser", "UserData"), 0o755)) - - tests := []struct { - name string - configs []types.BrowserConfig - wantDirs []string // expected UserDataDir values after resolution - }{ - { - name: "literal path exists", - configs: []types.BrowserConfig{ - {Key: "exact", UserDataDir: filepath.Join(base, "ExactBrowser", "UserData")}, - }, - wantDirs: []string{filepath.Join(base, "ExactBrowser", "UserData")}, - }, - { - name: "literal path not exists preserved", - configs: []types.BrowserConfig{ - {Key: "missing", UserDataDir: filepath.Join(base, "NoSuchBrowser", "UserData")}, - }, - wantDirs: []string{filepath.Join(base, "NoSuchBrowser", "UserData")}, - }, - { - name: "glob single match", - configs: []types.BrowserConfig{ - {Key: "single", UserDataDir: filepath.Join(base, "ExactBrow*", "UserData")}, - }, - wantDirs: []string{filepath.Join(base, "ExactBrowser", "UserData")}, - }, - { - name: "glob multiple matches", - configs: []types.BrowserConfig{ - {Key: "multi", UserDataDir: filepath.Join(base, "App.Browser_*", "UserData")}, - }, - wantDirs: []string{ - filepath.Join(base, "App.Browser_abc123", "UserData"), - filepath.Join(base, "App.Browser_def456", "UserData"), - }, - }, - { - name: "glob no match preserved", - configs: []types.BrowserConfig{ - {Key: "nomatch", UserDataDir: filepath.Join(base, "NoSuch_*", "UserData")}, - }, - wantDirs: []string{filepath.Join(base, "NoSuch_*", "UserData")}, - }, - { - name: "mixed literal and glob", - configs: []types.BrowserConfig{ - {Key: "chrome", UserDataDir: filepath.Join(base, "ExactBrowser", "UserData")}, - {Key: "arc", UserDataDir: filepath.Join(base, "App.Browser_*", "UserData")}, - }, - wantDirs: []string{ - filepath.Join(base, "ExactBrowser", "UserData"), - filepath.Join(base, "App.Browser_abc123", "UserData"), - filepath.Join(base, "App.Browser_def456", "UserData"), - }, - }, - { - name: "empty input", - configs: nil, - wantDirs: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := resolveGlobs(tt.configs) - - var gotDirs []string - for _, cfg := range got { - gotDirs = append(gotDirs, cfg.UserDataDir) - } - sort.Strings(gotDirs) - sort.Strings(tt.wantDirs) - assert.Equal(t, tt.wantDirs, gotDirs) - - // Verify non-UserDataDir fields are preserved. - for _, cfg := range got { - found := false - for _, orig := range tt.configs { - if cfg.Key != orig.Key { - continue - } - found = true - assert.Equal(t, orig.Name, cfg.Name) - assert.Equal(t, orig.Kind, cfg.Kind) - break - } - assert.True(t, found, "unexpected key %q in output", cfg.Key) - } - }) - } -} - -func TestNewBrowserDispatch(t *testing.T) { - chromiumDir := t.TempDir() - mkFile(t, chromiumDir, "Default", "Preferences") - mkFile(t, chromiumDir, "Default", "History") - - firefoxDir := t.TempDir() - mkFile(t, firefoxDir, "abc.default", "places.sqlite") - - safariDir := t.TempDir() - mkFile(t, safariDir, "History.db") - - emptyDir := t.TempDir() - - tests := []struct { - name string - cfg types.BrowserConfig - wantNil bool - wantName string - wantProfile string - wantErr string - }{ - { - name: "chromium dispatch", - cfg: types.BrowserConfig{Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: chromiumDir}, - wantName: "Chrome", - wantProfile: "Default", - }, - { - name: "firefox dispatch", - cfg: types.BrowserConfig{Key: "firefox", Name: "Firefox", Kind: types.Firefox, UserDataDir: firefoxDir}, - wantName: "Firefox", - wantProfile: "abc.default", - }, - { - name: "safari dispatch", - cfg: types.BrowserConfig{Key: "safari", Name: "Safari", Kind: types.Safari, UserDataDir: safariDir}, - wantName: "Safari", - wantProfile: "default", - }, - { - name: "unknown kind returns error", - cfg: types.BrowserConfig{Key: "unknown", Name: "Unknown", Kind: types.BrowserKind(99)}, - wantErr: "unknown browser kind", - }, - { - name: "empty dir returns nil", - cfg: types.BrowserConfig{Key: "chrome", Name: "Chrome", Kind: types.Chromium, UserDataDir: emptyDir}, - wantNil: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - b, err := newBrowser(tt.cfg) - if tt.wantErr != "" { - require.Error(t, err) - assert.Contains(t, err.Error(), tt.wantErr) - return - } - require.NoError(t, err) - if tt.wantNil { - assert.Nil(t, b) - return - } - require.NotNil(t, b) - assert.Equal(t, tt.wantName, b.BrowserName()) - profiles := b.Profiles() - require.NotEmpty(t, profiles) - assert.Equal(t, tt.wantProfile, profiles[0].Name) - }) - } -} - -// assertBrowsers flattens installations into (browser, profile) pairs and -// verifies they match expectations (order-independent). -func assertBrowsers(t *testing.T, browsers []Browser, wantNames, wantProfiles []string) { - t.Helper() - - var gotNames, gotProfiles []string - for _, b := range browsers { - for _, p := range b.Profiles() { - gotNames = append(gotNames, b.BrowserName()) - gotProfiles = append(gotProfiles, p.Name) - } - } - sort.Strings(gotNames) - sort.Strings(gotProfiles) - sort.Strings(wantNames) - sort.Strings(wantProfiles) - - assert.Equal(t, wantNames, gotNames) - assert.Equal(t, wantProfiles, gotProfiles) -} diff --git a/browser/browser_windows.go b/browser/browser_windows.go deleted file mode 100644 index ad55750..0000000 --- a/browser/browser_windows.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build windows - -package browser - -import ( - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" -) - -// newCredentialInjector hands each ABE browser its executable and dialect; RetrieveAll runs v10 (DPAPI) and, -// when the Locator carries an ABE kind, v20 (reflective injection) — both, since an upgraded profile mixes them. -func newCredentialInjector(_ DiscoverOptions) browserInjector { - return func(b Browser) { - km, ok := b.(KeyManager) - if !ok { - return - } - def, ok := ibrowser.Lookup(km.BrowserKey()) - if !ok { - return - } - if p := def.Platform(); p.ABE != masterkey.ABENone { - km.SetLocator(masterkey.Locator{Exe: p.Exe, ExeFallbacks: p.ExeFallbacks, ABE: p.ABE}) - } - } -} diff --git a/browser/browser_windows_test.go b/browser/browser_windows_test.go deleted file mode 100644 index 4f09c90..0000000 --- a/browser/browser_windows_test.go +++ /dev/null @@ -1,42 +0,0 @@ -//go:build windows - -package browser - -import ( - "testing" - - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" -) - -type locatorRecorder struct { - mockChromiumBrowser - got *masterkey.Locator -} - -func (r *locatorRecorder) SetLocator(loc masterkey.Locator) { r.got = &loc } - -// A lost ABE hand-off silently disables v20 decryption on Windows, so the injector's wiring is pinned here. -func TestCredentialInjector_HandsABEBrowsersTheirTarget(t *testing.T) { - inject := newCredentialInjector(DiscoverOptions{}) - - chrome := &locatorRecorder{mockChromiumBrowser: mockChromiumBrowser{key: "chrome"}} - inject(chrome) - if chrome.got == nil { - t.Fatal("chrome got no Locator") - } - def, ok := ibrowser.Lookup("chrome") - if !ok { - t.Fatal("chrome is not in the browser table") - } - want := def.Platform() - if chrome.got.Exe != want.Exe || chrome.got.ABE != want.ABE || len(chrome.got.ExeFallbacks) != len(want.ExeFallbacks) { - t.Errorf("chrome Locator = %+v, want exe %q, kind %v, %d fallbacks", *chrome.got, want.Exe, want.ABE, len(want.ExeFallbacks)) - } - - opera := &locatorRecorder{mockChromiumBrowser: mockChromiumBrowser{key: "opera"}} - inject(opera) - if opera.got != nil { - t.Errorf("opera has no ABE, so it keeps DPAPI only; got Locator %+v", *opera.got) - } -} diff --git a/browser/chromium/archive.go b/browser/chromium/archive.go deleted file mode 100644 index 38249c2..0000000 --- a/browser/chromium/archive.go +++ /dev/null @@ -1,71 +0,0 @@ -package chromium - -import ( - "path" - "path/filepath" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" -) - -// ArchiveSource is one decryption-relevant file or directory plus its path inside the browser's -// User Data tree (forward-slash), so an archive can be re-expanded into a working profile layout. -type ArchiveSource struct { - AbsPath string - LayoutRel string - IsDir bool -} - -// installationFiles live at the User Data root (shared across profiles); archived for fidelity even -// though keys.json-based restore does not read them. -var installationFiles = []string{"Local State"} - -// ArchiveSources lists the files an archive must capture for the given categories: the User Data root -// files (Local State), every resolved category source per profile, plus each profile's Preferences -// marker so a restore can rediscover the profile. LayoutRel is forward-slash, relative to the root. -func (b *Browser) ArchiveSources(categories []category.Category) []ArchiveSource { - var out []ArchiveSource - for _, name := range installationFiles { - abs := filepath.Join(b.cfg.UserDataDir, name) - if fileutil.FileExists(abs) { - out = append(out, ArchiveSource{AbsPath: abs, LayoutRel: name, IsDir: false}) - } - } - for _, p := range b.profiles { - // Flat-layout installs hold data directly under UserDataDir (profileDir == root); skip the - // basename so the archive matches the real layout instead of inserting a phantom level. - profileRel := "" - if p.profileDir != b.cfg.UserDataDir { - profileRel = filepath.Base(p.profileDir) - } - for _, marker := range profileMarkers { - abs := filepath.Join(p.profileDir, marker) - if fileutil.FileExists(abs) { - out = append(out, ArchiveSource{ - AbsPath: abs, - LayoutRel: path.Join(profileRel, marker), - IsDir: false, - }) - } - } - for _, cat := range categories { - rp, ok := p.sourcePaths[cat] - if !ok { - continue - } - out = append(out, ArchiveSource{ - AbsPath: rp.absPath, - LayoutRel: path.Join(profileRel, rp.rel), - IsDir: rp.isDir, - }) - } - if accountPath, ok := p.accountPasswordPath(categories); ok { - out = append(out, ArchiveSource{ - AbsPath: accountPath, - LayoutRel: path.Join(profileRel, accountLoginData), - IsDir: false, - }) - } - } - return out -} diff --git a/browser/chromium/archive_test.go b/browser/chromium/archive_test.go deleted file mode 100644 index dab5198..0000000 --- a/browser/chromium/archive_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package chromium - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" -) - -func TestArchiveSources_ForwardSlashLayout(t *testing.T) { - udd := t.TempDir() - networkDir := filepath.Join(udd, "Default", "Network") - if err := os.MkdirAll(networkDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(udd, "Default", "Preferences"), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(networkDir, "Cookies"), []byte("x"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(udd, "Local State"), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - - b, err := NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: udd}) - if err != nil || b == nil { - t.Fatalf("NewBrowser: b=%v err=%v", b, err) - } - - srcs := b.ArchiveSources([]category.Category{category.Cookie}) - - var gotCookie, gotMarker, gotLocalState bool - for _, s := range srcs { - if strings.Contains(s.LayoutRel, `\`) { - t.Errorf("LayoutRel must be forward-slash, got %q", s.LayoutRel) - } - switch s.LayoutRel { - case "Default/Network/Cookies": - gotCookie = true - case "Default/Preferences": - gotMarker = true - case "Local State": - gotLocalState = true - } - } - if !gotCookie { - t.Errorf("missing Cookies entry with layout path, got %+v", srcs) - } - if !gotMarker { - t.Errorf("missing Preferences marker entry (needed for restore profile discovery), got %+v", srcs) - } - if !gotLocalState { - t.Errorf("missing Local State entry (User Data root file), got %+v", srcs) - } -} - -func TestArchiveSources_FlatLayoutNoExtraLevel(t *testing.T) { - // Flat-layout install: data lives directly under UserDataDir with no Default/ subdir, so - // discoverProfiles falls back to UserDataDir itself as the profile (profileDir == root). - udd := t.TempDir() - if err := os.WriteFile(filepath.Join(udd, "History"), []byte("x"), 0o600); err != nil { - t.Fatal(err) - } - - b, err := NewBrowser(types.BrowserConfig{Key: "opera", Name: "opera", Kind: types.Chromium, UserDataDir: udd}) - if err != nil || b == nil { - t.Fatalf("NewBrowser: b=%v err=%v", b, err) - } - - srcs := b.ArchiveSources([]category.Category{category.History}) - - phantom := filepath.Base(udd) + "/" - var gotHistory bool - for _, s := range srcs { - if strings.HasPrefix(s.LayoutRel, phantom) { - t.Errorf("flat layout must not insert a %q level, got %q", phantom, s.LayoutRel) - } - if s.LayoutRel == "History" { - gotHistory = true - } - } - if !gotHistory { - t.Errorf("expected History at archive root, got %+v", srcs) - } -} - -// Restoring an archive must reproduce both password DBs, otherwise account-synced credentials -// are lost on the round trip even though a live extract would have found them. -func TestArchiveSources_IncludesBothPasswordDatabases(t *testing.T) { - udd := t.TempDir() - profileDir := filepath.Join(udd, "Default") - if err := os.MkdirAll(profileDir, 0o755); err != nil { - t.Fatal(err) - } - for _, name := range []string{"Preferences", "Login Data", accountLoginData} { - if err := os.WriteFile(filepath.Join(profileDir, name), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - } - - b, err := NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: udd}) - if err != nil || b == nil { - t.Fatalf("NewBrowser: b=%v err=%v", b, err) - } - - srcs := b.ArchiveSources([]category.Category{category.Password}) - - var gotLocal, gotAccount bool - for _, s := range srcs { - switch s.LayoutRel { - case "Default/Login Data": - gotLocal = true - case "Default/" + accountLoginData: - gotAccount = true - } - } - if !gotLocal || !gotAccount { - t.Errorf("expected both password DBs archived (local=%v account=%v), got %+v", gotLocal, gotAccount, srcs) - } -} diff --git a/browser/chromium/chromium.go b/browser/chromium/chromium.go deleted file mode 100644 index 5e37165..0000000 --- a/browser/chromium/chromium.go +++ /dev/null @@ -1,258 +0,0 @@ -package chromium - -import ( - "context" - "os" - "path/filepath" - "sync" - - "github.com/moond4rk/hackbrowserdata/filemanager" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/types" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" -) - -// Browser is one Chromium installation: a single UserDataDir holding profiles -// that share a master key. The key is derived once and reused across profiles. -type Browser struct { - cfg types.BrowserConfig - locator masterkey.Locator // cross-cutting bits the injector adds (macOS keychain, Windows ABE); live only - static masterkey.Set // keys known from a dump; restore skips retrieval - isStatic bool - profiles []*profile - - keysOnce sync.Once - keys masterkey.Set -} - -// NewBrowser discovers the profiles under cfg.UserDataDir, or returns nil if none resolve. -// Call SetLocator (live) or SetKeys (restore) before Extract to enable decryption. -func NewBrowser(cfg types.BrowserConfig) (*Browser, error) { - sources := sourcesForKind(cfg.Kind) - extractors := extractorsFor(cfg.Kind) - - var profiles []*profile - for _, profileDir := range discoverProfiles(cfg.UserDataDir, sources) { - sourcePaths := resolveSourcePaths(sources, profileDir) - if len(sourcePaths) == 0 { - continue - } - profiles = append(profiles, &profile{ - profileDir: profileDir, - browserName: cfg.Name, - kind: cfg.Kind, - extractors: extractors, - sourcePaths: sourcePaths, - }) - } - if len(profiles) == 0 { - return nil, nil - } - return &Browser{cfg: cfg, profiles: profiles}, nil -} - -// SetLocator adds the live run's cross-cutting key sources — the macOS login keychain, the Windows ABE executable. -func (b *Browser) SetLocator(loc masterkey.Locator) { b.locator = loc } - -// SetKeys supplies keys already known from a dump, so restore decrypts without touching any OS secret store. -func (b *Browser) SetKeys(keys masterkey.Set) { b.static, b.isStatic = keys, true } - -func (b *Browser) BrowserName() string { return b.cfg.Name } -func (b *Browser) BrowserKey() string { return b.cfg.Key } -func (b *Browser) UserDataDir() string { return b.cfg.UserDataDir } -func (b *Browser) Kind() types.BrowserKind { return b.cfg.Kind } - -// Profiles returns the identity of every profile in this installation. -func (b *Browser) Profiles() []types.Profile { - out := make([]types.Profile, 0, len(b.profiles)) - for _, p := range b.profiles { - out = append(out, types.Profile{Name: p.name(), Dir: p.profileDir}) - } - return out -} - -// Extract derives the installation's master key once, then extracts every profile. -func (b *Browser) Extract(categories []category.Category) ([]types.ExtractResult, error) { - masterKeys := b.masterKeys() - results := make([]types.ExtractResult, 0, len(b.profiles)) - for _, p := range b.profiles { - results = append(results, types.ExtractResult{ - Profile: types.Profile{Name: p.name(), Dir: p.profileDir}, - Data: p.extract(masterKeys, categories), - }) - } - return results, nil -} - -// CountEntries counts entries per category for every profile without decryption. -func (b *Browser) CountEntries(categories []category.Category) ([]types.CountResult, error) { - results := make([]types.CountResult, 0, len(b.profiles)) - for _, p := range b.profiles { - results = append(results, types.CountResult{ - Profile: types.Profile{Name: p.name(), Dir: p.profileDir}, - Counts: p.count(categories), - }) - } - return results, nil -} - -// ExportKeys derives the master keys without extracting. Returns the versions that succeeded plus a -// joined error for those that failed — partial results matter (a v20-only failure keeps the v10 key). -func (b *Browser) ExportKeys() (masterkey.Set, error) { - if b.isStatic { - return b.static, nil - } - session, err := filemanager.NewSession() - if err != nil { - return masterkey.Set{}, err - } - defer session.Cleanup() - - return masterkey.RetrieveAll(context.Background(), b.buildLocator(session)) -} - -// masterKeys derives and caches the installation's keys exactly once (sync.Once), so a failure is -// warned once — no cross-profile dedup state needed. -func (b *Browser) masterKeys() masterkey.Set { - b.keysOnce.Do(func() { - masterKeys, err := b.ExportKeys() - if err != nil { - log.Warnf("%s: master key retrieval: %v", b.BrowserName(), err) - } - b.keys = masterKeys - }) - return b.keys -} - -// buildLocator copies Local State into the session temp dir (so Windows DPAPI/ABE retrievers read it -// from a process-owned path) and fills in the dir's own fields; the injector added the rest. -func (b *Browser) buildLocator(session *filemanager.Session) masterkey.Locator { - loc := b.locator - loc.KeychainLabel = b.cfg.KeychainLabel - candidate := filepath.Join(b.cfg.UserDataDir, "Local State") - if fileutil.FileExists(candidate) { - dst := filepath.Join(session.TempDir(), "Local State") - if err := session.Acquire(candidate, dst, false); err != nil { - log.Debugf("acquire Local State for %s: %v", b.BrowserName(), err) - } else { - loc.LocalState = dst - } - } - return loc -} - -// discoverProfiles lists subdirectories of userDataDir that are valid -// Chromium profile directories. A directory is considered a profile if it -// contains a "Preferences" file, which Chromium creates for every profile. -func discoverProfiles(userDataDir string, sources map[category.Category][]sourcePath) []string { - entries, err := os.ReadDir(userDataDir) - if err != nil { - return nil - } - - var profiles []string - for _, e := range entries { - if !e.IsDir() || isSkippedDir(e.Name()) { - continue - } - dir := filepath.Join(userDataDir, e.Name()) - if isProfileDir(dir) { - profiles = append(profiles, dir) - } - } - - // Flat layout (older Opera): data files directly under userDataDir with no profile subdir. Check the - // root before the subdir fallback so a stray source-bearing subdir can't suppress root discovery. - if len(profiles) == 0 && hasAnySource(sources, userDataDir) { - profiles = append(profiles, userDataDir) - } - - // Restored/copied trees may omit the Preferences marker (it is no extraction source). When the marker - // scan and flat-layout check both find nothing, treat any source-bearing subdir as a profile. - if len(profiles) == 0 { - for _, e := range entries { - if !e.IsDir() || isSkippedDir(e.Name()) { - continue - } - dir := filepath.Join(userDataDir, e.Name()) - if hasAnySource(sources, dir) { - profiles = append(profiles, dir) - } - } - } - return profiles -} - -// profileMarkers are filenames that identify a directory as a Chromium profile. -// Chromium creates a per-profile preferences file on first use; checking for -// its existence filters out non-profile subdirectories (Crashpad, ShaderCache, etc.). -// -// - "Preferences" — standard Chromium and all major forks (Chrome, Edge, Brave, …) -// - "Preferences_02" — Tencent-based browsers (QQ Browser, Sogou Explorer) -var profileMarkers = []string{ - "Preferences", - "Preferences_02", -} - -// isProfileDir reports whether dir is a valid Chromium profile directory. -func isProfileDir(dir string) bool { - for _, name := range profileMarkers { - if _, err := os.Stat(filepath.Join(dir, name)); err == nil { - return true - } - } - return false -} - -// hasAnySource checks if dir contains at least one source file or directory. -func hasAnySource(sources map[category.Category][]sourcePath, dir string) bool { - for _, candidates := range sources { - for _, sp := range candidates { - abs := filepath.Join(dir, sp.rel) - if _, err := os.Stat(abs); err == nil { - return true - } - } - } - return false -} - -// resolvedPath holds the absolute path, the slash-relative source path, and the type of a discovered -// source. rel is retained (not just absPath) so archive can reproduce the User Data layout. -type resolvedPath struct { - absPath string - rel string - isDir bool -} - -// resolveSourcePaths checks which sources actually exist in profileDir. -// Candidates are tried in priority order; the first existing path wins. -func resolveSourcePaths(sources map[category.Category][]sourcePath, profileDir string) map[category.Category]resolvedPath { - resolved := make(map[category.Category]resolvedPath) - for cat, candidates := range sources { - for _, sp := range candidates { - abs := filepath.Join(profileDir, sp.rel) - info, err := os.Stat(abs) - if err != nil { - continue - } - if sp.isDir == info.IsDir() { - resolved[cat] = resolvedPath{absPath: abs, rel: sp.rel, isDir: sp.isDir} - break - } - } - } - return resolved -} - -// isSkippedDir returns true for directory names that should never be -// treated as browser profiles. -func isSkippedDir(name string) bool { - switch name { - case "System Profile", "Guest Profile", "Snapshot": - return true - } - return false -} diff --git a/browser/chromium/chromium_test.go b/browser/chromium/chromium_test.go deleted file mode 100644 index 880e802..0000000 --- a/browser/chromium/chromium_test.go +++ /dev/null @@ -1,551 +0,0 @@ -package chromium - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/types" -) - -// --------------------------------------------------------------------------- -// Shared fixture -// --------------------------------------------------------------------------- - -var fixture struct { - root string - chrome string // multi-profile + skipped dirs - opera string // has Default/ - operaFlat string // no Default/, data in root - yandex string // Ya Passman Data, Ya Credit Cards - oldCookies string // Cookies at root (no Network/) - bothCookies string // Network/Cookies + Cookies - leveldb string // Local Storage/leveldb + Session Storage - leveldbOnly string // only LevelDB dirs, no files - empty string -} - -func TestMain(m *testing.M) { - root, err := os.MkdirTemp("", "chromium-test-*") - if err != nil { - panic(err) - } - fixture.root = root - buildFixtures() - code := m.Run() - os.RemoveAll(root) - os.Exit(code) -} - -func buildFixtures() { - fixture.chrome = filepath.Join(fixture.root, "chrome") - mkFile(fixture.chrome, "Local State") - for _, p := range []string{"Default", "Profile 1", "Profile 3"} { - mkFile(fixture.chrome, p, "Preferences") - mkFile(fixture.chrome, p, "Login Data") - mkFile(fixture.chrome, p, "History") - mkFile(fixture.chrome, p, "Bookmarks") - mkFile(fixture.chrome, p, "Web Data") - mkFile(fixture.chrome, p, "Secure Preferences") - mkFile(fixture.chrome, p, "Network", "Cookies") - mkDir(fixture.chrome, p, "Local Storage", "leveldb") - mkDir(fixture.chrome, p, "Session Storage") - } - mkFile(fixture.chrome, "System Profile", "History") - mkFile(fixture.chrome, "Guest Profile", "History") - mkFile(fixture.chrome, "Snapshot", "Default", "History") - - fixture.opera = filepath.Join(fixture.root, "opera") - mkFile(fixture.opera, "Local State") - mkFile(fixture.opera, "Default", "Preferences") - mkFile(fixture.opera, "Default", "Login Data") - mkFile(fixture.opera, "Default", "History") - mkFile(fixture.opera, "Default", "Bookmarks") - mkFile(fixture.opera, "Default", "Cookies") - - fixture.operaFlat = filepath.Join(fixture.root, "opera-flat") - mkFile(fixture.operaFlat, "Local State") - mkFile(fixture.operaFlat, "Login Data") - mkFile(fixture.operaFlat, "History") - mkFile(fixture.operaFlat, "Cookies") - - fixture.yandex = filepath.Join(fixture.root, "yandex") - mkFile(fixture.yandex, "Local State") - mkFile(fixture.yandex, "Default", "Preferences") - mkFile(fixture.yandex, "Default", "Ya Passman Data") - mkFile(fixture.yandex, "Default", "Ya Credit Cards") - mkFile(fixture.yandex, "Default", "History") - mkFile(fixture.yandex, "Default", "Network", "Cookies") - mkFile(fixture.yandex, "Default", "Bookmarks") - - fixture.oldCookies = filepath.Join(fixture.root, "old-cookies") - mkFile(fixture.oldCookies, "Default", "Preferences") - mkFile(fixture.oldCookies, "Default", "History") - mkFile(fixture.oldCookies, "Default", "Cookies") - - fixture.bothCookies = filepath.Join(fixture.root, "both-cookies") - mkFile(fixture.bothCookies, "Default", "Preferences") - mkFile(fixture.bothCookies, "Default", "Cookies") - mkFile(fixture.bothCookies, "Default", "Network", "Cookies") - - fixture.leveldb = filepath.Join(fixture.root, "leveldb") - mkFile(fixture.leveldb, "Default", "Preferences") - mkFile(fixture.leveldb, "Default", "History") - mkDir(fixture.leveldb, "Default", "Local Storage", "leveldb") - mkFile(fixture.leveldb, "Default", "Local Storage", "leveldb", "000001.ldb") - mkDir(fixture.leveldb, "Default", "Session Storage") - mkFile(fixture.leveldb, "Default", "Session Storage", "000001.ldb") - - fixture.leveldbOnly = filepath.Join(fixture.root, "leveldb-only") - mkFile(fixture.leveldbOnly, "Default", "Preferences") - mkDir(fixture.leveldbOnly, "Default", "Local Storage", "leveldb") - mkDir(fixture.leveldbOnly, "Default", "Session Storage") - - fixture.empty = filepath.Join(fixture.root, "empty") - mkDir(fixture.empty) -} - -func mkFile(parts ...string) { - path := filepath.Join(parts...) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - panic(err) - } - if err := os.WriteFile(path, []byte("test"), 0o644); err != nil { - panic(err) - } -} - -func mkDir(parts ...string) { - if err := os.MkdirAll(filepath.Join(parts...), 0o755); err != nil { - panic(err) - } -} - -// --------------------------------------------------------------------------- -// NewBrowsers: table-driven, covers all layouts end-to-end -// --------------------------------------------------------------------------- - -func TestNewBrowsers(t *testing.T) { - tests := []struct { - name string - dir string - kind types.BrowserKind - wantProfiles []string // expected profile base names - wantCats map[string][]string // profile → expected category base names (spot check) - wantDirs []category.Category // categories that should be isDir=true - skipProfiles []string // should NOT appear - }{ - { - name: "chrome multi-profile", - dir: fixture.chrome, - kind: types.Chromium, - wantProfiles: []string{"Default", "Profile 1", "Profile 3"}, - wantCats: map[string][]string{ - "Default": {"Login Data", "Cookies", "History", "Bookmarks", "Web Data", "Secure Preferences", "leveldb", "Session Storage"}, - }, - wantDirs: []category.Category{category.LocalStorage, category.SessionStorage}, - skipProfiles: []string{"System Profile", "Guest Profile", "Snapshot"}, - }, - { - name: "opera with Default", - dir: fixture.opera, - kind: types.Chromium, - wantProfiles: []string{"Default"}, - wantCats: map[string][]string{ - "Default": {"Login Data", "History", "Bookmarks", "Cookies"}, - }, - }, - { - name: "opera flat layout", - dir: fixture.operaFlat, - kind: types.Chromium, - wantProfiles: []string{filepath.Base(fixture.operaFlat)}, // userDataDir itself - wantCats: map[string][]string{ - filepath.Base(fixture.operaFlat): {"Login Data", "History", "Cookies"}, - }, - }, - { - name: "yandex custom files", - dir: fixture.yandex, - kind: types.ChromiumYandex, - wantProfiles: []string{"Default"}, - wantCats: map[string][]string{ - "Default": {"Ya Passman Data", "Ya Credit Cards", "History", "Cookies", "Bookmarks"}, - }, - }, - { - name: "old cookies fallback", - dir: fixture.oldCookies, - kind: types.Chromium, - wantProfiles: []string{"Default"}, - }, - { - name: "cookie priority", - dir: fixture.bothCookies, - kind: types.Chromium, - wantProfiles: []string{"Default"}, - }, - { - name: "leveldb directories", - dir: fixture.leveldb, - kind: types.Chromium, - wantProfiles: []string{"Default"}, - wantDirs: []category.Category{category.LocalStorage, category.SessionStorage}, - }, - { - name: "leveldb only", - dir: fixture.leveldbOnly, - kind: types.Chromium, - wantProfiles: []string{"Default"}, - wantDirs: []category.Category{category.LocalStorage, category.SessionStorage}, - }, - { - name: "empty dir", - dir: fixture.empty, - kind: types.Chromium, - }, - { - name: "nonexistent dir", - dir: "/nonexistent/path", - kind: types.Chromium, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := types.BrowserConfig{Name: "Test", Kind: tt.kind, UserDataDir: tt.dir} - b, err := NewBrowser(cfg) - require.NoError(t, err) - - if len(tt.wantProfiles) == 0 { - assert.Nil(t, b) - return - } - require.NotNil(t, b) - require.Len(t, b.profiles, len(tt.wantProfiles)) - - nameMap := profilesByName(b) - assertProfiles(t, nameMap, tt.wantProfiles, tt.skipProfiles) - assertCategories(t, nameMap, tt.wantCats) - assertDirCategories(t, b.profiles, tt.wantDirs) - }) - } -} - -// --------------------------------------------------------------------------- -// discoverProfiles: fallback boundaries (marker-less copies, flat-layout precedence) -// --------------------------------------------------------------------------- - -func TestDiscoverProfiles(t *testing.T) { - t.Run("markerless multi-subdir resolves all source-bearing dirs", func(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "Default", "History") - mkFile(dir, "Profile 1", "History") - assert.Len(t, discoverProfiles(dir, chromiumSources), 2) - }) - - t.Run("marker present keeps fallback dormant", func(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "Default", "Preferences") - mkFile(dir, "Default", "History") - mkFile(dir, "NotAProfile", "History") - got := discoverProfiles(dir, chromiumSources) - require.Len(t, got, 1) - assert.Equal(t, filepath.Join(dir, "Default"), got[0]) - }) - - t.Run("skipped dir ignored by markerless fallback", func(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "System Profile", "History") - assert.Empty(t, discoverProfiles(dir, chromiumSources)) - }) - - t.Run("sourceless subdir ignored", func(t *testing.T) { - dir := t.TempDir() - mkDir(dir, "Crashpad") - assert.Empty(t, discoverProfiles(dir, chromiumSources)) - }) - - t.Run("flat-layout root wins over source-bearing subdir", func(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "History") - mkFile(dir, "Subthing", "History") - got := discoverProfiles(dir, chromiumSources) - require.Len(t, got, 1) - assert.Equal(t, dir, got[0], "flat-layout root must win; subdir must not hijack discovery") - }) -} - -// --------------------------------------------------------------------------- -// Test helpers -// --------------------------------------------------------------------------- - -func profilesByName(b *Browser) map[string]*profile { - m := make(map[string]*profile, len(b.profiles)) - for _, p := range b.profiles { - m[filepath.Base(p.profileDir)] = p - } - return m -} - -func assertProfiles(t *testing.T, nameMap map[string]*profile, want, skip []string) { - t.Helper() - for _, w := range want { - assert.Contains(t, nameMap, w, "should find profile %s", w) - } - for _, s := range skip { - assert.NotContains(t, nameMap, s, "should skip %s", s) - } -} - -func assertCategories(t *testing.T, nameMap map[string]*profile, wantCats map[string][]string) { - t.Helper() - for profileName, wantFiles := range wantCats { - p, ok := nameMap[profileName] - if !ok { - t.Errorf("profile %s not found", profileName) - continue - } - for _, wantFile := range wantFiles { - found := false - for _, rp := range p.sourcePaths { - if filepath.Base(rp.absPath) == wantFile { - found = true - break - } - } - assert.True(t, found, "profile %s should have %s", profileName, wantFile) - } - } -} - -func assertDirCategories(t *testing.T, profiles []*profile, cats []category.Category) { - t.Helper() - for _, cat := range cats { - for _, p := range profiles { - if rp, ok := p.sourcePaths[cat]; ok { - assert.True(t, rp.isDir, "%s should be isDir=true", cat) - } - } - } -} - -// --------------------------------------------------------------------------- -// Cookie priority: Network/Cookies wins over root Cookies -// --------------------------------------------------------------------------- - -func TestCookiePriority(t *testing.T) { - resolved := resolveSourcePaths(chromiumSources, filepath.Join(fixture.bothCookies, "Default")) - require.Contains(t, resolved, category.Cookie) - assert.Contains(t, resolved[category.Cookie].absPath, "Network", - "Network/Cookies should win over root Cookies") -} - -func TestCookieFallback(t *testing.T) { - resolved := resolveSourcePaths(chromiumSources, filepath.Join(fixture.oldCookies, "Default")) - require.Contains(t, resolved, category.Cookie) - assert.NotContains(t, resolved[category.Cookie].absPath, "Network", - "should fallback to root Cookies when Network/Cookies missing") -} - -// --------------------------------------------------------------------------- -// History/Download share the same source file -// --------------------------------------------------------------------------- - -func TestSharedSourceFile(t *testing.T) { - resolved := resolveSourcePaths(chromiumSources, filepath.Join(fixture.chrome, "Default")) - assert.Equal(t, resolved[category.History].absPath, resolved[category.Download].absPath) -} - -// --------------------------------------------------------------------------- -// Source helpers -// --------------------------------------------------------------------------- - -func TestSourcesForKind(t *testing.T) { - chromium := sourcesForKind(types.Chromium) - yandex := sourcesForKind(types.ChromiumYandex) - - assert.Equal(t, "Login Data", chromium[category.Password][0].rel) - assert.Equal(t, "Ya Passman Data", yandex[category.Password][0].rel) - // Yandex inherits non-overridden categories - assert.Equal(t, chromium[category.History][0].rel, yandex[category.History][0].rel) -} - -func TestExtractorsFor(t *testing.T) { - assert.Equal(t, []string{"Login Data"}, extractorsFor(types.Chromium)[category.Password].Sources[0].Paths) - assert.Equal(t, []string{"Ya Passman Data"}, extractorsFor(types.ChromiumYandex)[category.Password].Sources[0].Paths) - assert.Equal(t, []string{"Ya Credit Cards"}, extractorsFor(types.ChromiumYandex)[category.CreditCard].Sources[0].Paths) -} - -// The kind still selects a fork's own format: Opera keeps its extensions under extensions.opsettings. -func TestExtract_OperaKindReadsOpsettings(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "Default", "Preferences") - installFile(t, filepath.Join(dir, "Default"), createTestJSON(t, "Secure Preferences", `{ - "extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Ext", "version": "1.0"}}}} - }`), "Secure Preferences") - - b, err := NewBrowser(types.BrowserConfig{Name: "Opera", Kind: types.ChromiumOpera, UserDataDir: dir}) - require.NoError(t, err) - require.NotNil(t, b) - b.SetKeys(masterkey.Set{}) - - results, err := b.Extract([]category.Category{category.Extension}) - require.NoError(t, err) - require.Len(t, results, 1) - require.Len(t, results[0].Data.Extensions, 1) - assert.Equal(t, "Ext", results[0].Data.Extensions[0].Name) -} - -// --------------------------------------------------------------------------- -// Local State path validation -// --------------------------------------------------------------------------- - -func TestLocalStatePath(t *testing.T) { - tests := []struct { - name string - dir string - want bool // Local State should be at Dir(profileDir)/Local State - }{ - {"chrome", fixture.chrome, true}, - {"opera", fixture.opera, true}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - b, err := NewBrowser(types.BrowserConfig{Name: "Test", Kind: types.Chromium, UserDataDir: tt.dir}) - require.NoError(t, err) - require.NotNil(t, b) - - for _, p := range b.profiles { - localState := filepath.Join(filepath.Dir(p.profileDir), "Local State") - if tt.want { - assert.FileExists(t, localState) - } - } - }) - } -} - -// --------------------------------------------------------------------------- -// Keys -// --------------------------------------------------------------------------- - -// Live key retrieval (per-version first-key-wins, ABE dispatch) is tested in the masterkey package; -// here the Browser only has to carry the keys a dump hands it and surface an empty Set when it has none. - -func TestMasterKeys_StaticFromDump(t *testing.T) { - keys := masterkey.Set{masterkey.V10: []byte("k10"), masterkey.V20: []byte("k20")} - b, err := NewBrowser(types.BrowserConfig{Name: "Test", Kind: types.Chromium, UserDataDir: fixture.chrome}) - require.NoError(t, err) - require.NotNil(t, b) - - b.SetKeys(keys) - assert.Equal(t, keys, b.masterKeys()) -} - -func TestMasterKeys_EmptyDumpYieldsEmptySet(t *testing.T) { - b, err := NewBrowser(types.BrowserConfig{Name: "Test", Kind: types.Chromium, UserDataDir: fixture.chrome}) - require.NoError(t, err) - require.NotNil(t, b) - - b.SetKeys(masterkey.Set{}) - assert.Empty(t, b.masterKeys(), "a dump with no keys for this browser decrypts nothing, rather than crashing") -} - -// --------------------------------------------------------------------------- -// Extract -// --------------------------------------------------------------------------- - -func TestExtract(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "Default", "Preferences") - installFile(t, filepath.Join(dir, "Default"), setupHistoryDB(t), "History") - - tests := []struct { - name string - keys masterkey.Set - }{ - {name: "without keys extracts unencrypted data", keys: masterkey.Set{}}, - {name: "with dump keys", keys: masterkey.Set{masterkey.V10: []byte("test-key-16byte0")}}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - b, err := NewBrowser(types.BrowserConfig{ - Name: "Test", Kind: types.Chromium, UserDataDir: dir, KeychainLabel: "Chrome", - }) - require.NoError(t, err) - require.NotNil(t, b) - - // Even an empty Set is needed: without SetKeys, Extract queries the host's real secret stores. - b.SetKeys(tt.keys) - - results, err := b.Extract([]category.Category{category.History}) - require.NoError(t, err) - require.Len(t, results, 1) - require.NotNil(t, results[0].Data) - require.Len(t, results[0].Data.Histories, 3) - assert.Equal(t, "GitHub", results[0].Data.Histories[0].Title) - }) - } -} - -// --------------------------------------------------------------------------- -// CountEntries -// --------------------------------------------------------------------------- - -func TestCountEntries(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "Default", "Preferences") - installFile(t, filepath.Join(dir, "Default"), setupHistoryDB(t), "History") - - b, err := NewBrowser(types.BrowserConfig{ - Name: "Test", Kind: types.Chromium, UserDataDir: dir, - }) - require.NoError(t, err) - require.NotNil(t, b) - - // No retriever set — CountEntries should still work (no decryption needed). - results, err := b.CountEntries([]category.Category{category.History, category.Download}) - require.NoError(t, err) - require.Len(t, results, 1) - - assert.Equal(t, 3, results[0].Counts[category.History]) - // Download uses a different table in the same file; since we only - // created the urls table (not downloads), the count query will fail - // gracefully and return 0. - assert.Equal(t, 0, results[0].Counts[category.Download]) -} - -func TestCountEntries_NoRetrieverNeeded(t *testing.T) { - dir := t.TempDir() - mkFile(dir, "Default", "Preferences") - // Login Data normally needs master key to extract, but CountEntries skips decryption. - installFile(t, filepath.Join(dir, "Default"), setupLoginDB(t), "Login Data") - - b, err := NewBrowser(types.BrowserConfig{ - Name: "Test", Kind: types.Chromium, UserDataDir: dir, - }) - require.NoError(t, err) - require.NotNil(t, b) - - // No retriever set — CountEntries succeeds without master key. - results, err := b.CountEntries([]category.Category{category.Password}) - require.NoError(t, err) - require.Len(t, results, 1) - assert.Equal(t, 2, results[0].Counts[category.Password]) -} - -// *Browser must satisfy the key-injection shape app uses after construction (live Locator or dump keys). -func TestBrowser_SatisfiesKeyManager(t *testing.T) { - var _ interface { - SetLocator(masterkey.Locator) - SetKeys(masterkey.Set) - ExportKeys() (masterkey.Set, error) - } = (*Browser)(nil) -} diff --git a/browser/chromium/count.go b/browser/chromium/count.go deleted file mode 100644 index 28b86ce..0000000 --- a/browser/chromium/count.go +++ /dev/null @@ -1,182 +0,0 @@ -package chromium - -import ( - "bytes" - "os" - - "github.com/syndtr/goleveldb/leveldb" - "github.com/tidwall/gjson" - - "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 ( - countLoginQuery = `SELECT COUNT(*) FROM logins` - countCookieQuery = `SELECT COUNT(*) FROM cookies` - countHistoryQuery = `SELECT COUNT(*) FROM urls` - countDownloadQuery = `SELECT COUNT(*) FROM downloads` - countCreditCardQuery = `SELECT COUNT(*) FROM credit_cards` - yandexCreditCardCountQuery = `SELECT COUNT(*) FROM records` -) - -// defaultExtensionKeys are the JSON paths tried for standard Chromium browsers. -var defaultExtensionKeys = []string{ - "extensions.settings", - "settings.extensions", - "settings.settings", -} - -func countPasswords(path string) (int, error) { - return sqlitex.CountRows(path, false, countLoginQuery) -} - -func countCookies(path string) (int, error) { - return sqlitex.CountRows(path, false, countCookieQuery) -} - -func countHistories(path string) (int, error) { - return sqlitex.CountRows(path, false, countHistoryQuery) -} - -func countDownloads(path string) (int, error) { - return sqlitex.CountRows(path, false, countDownloadQuery) -} - -func countBookmarks(path string) (int, error) { - data, err := os.ReadFile(path) - if err != nil { - return 0, err - } - var count int - roots := gjson.GetBytes(data, "roots") - roots.ForEach(func(_, value gjson.Result) bool { - count += walkCountBookmarks(value) - return true - }) - return count, nil -} - -// walkCountBookmarks recursively counts URL nodes in the bookmark tree. -func walkCountBookmarks(node gjson.Result) int { - count := 0 - if node.Get("type").String() == "url" { - count++ - } - children := node.Get("children") - if children.Exists() && children.IsArray() { - for _, child := range children.Array() { - count += walkCountBookmarks(child) - } - } - return count -} - -func countCreditCards(path string) (int, error) { - return sqlitex.CountRows(path, false, countCreditCardQuery) -} - -func countYandexCreditCards(path string) (int, error) { - return sqlitex.CountRows(path, false, yandexCreditCardCountQuery) -} - -func countExtensions(path string) (int, error) { - return countExtensionsWithKeys(path, defaultExtensionKeys) -} - -func countOperaExtensions(path string) (int, error) { - return countExtensionsWithKeys(path, []string{"extensions.opsettings"}) -} - -// countExtensionsWithKeys counts non-system extensions without building -// full ExtensionEntry structs. Mirrors the filtering logic in extractExtensionsWithKeys. -func countExtensionsWithKeys(path string, keys []string) (int, error) { - data, err := os.ReadFile(path) - if err != nil { - return 0, err - } - - var settings gjson.Result - for _, key := range keys { - settings = gjson.GetBytes(data, key) - if settings.Exists() { - break - } - } - if !settings.Exists() { - return 0, nil - } - - var count int - settings.ForEach(func(_, ext gjson.Result) bool { - location := ext.Get("location").Int() - if location == 5 || location == 10 { - return true - } - if !ext.Get("manifest").Exists() { - return true - } - count++ - return true - }) - return count, nil -} - -func countLocalStorage(path string) (int, error) { - if _, err := os.Stat(path); err != nil { - return 0, err - } - db, err := leveldb.OpenFile(path, nil) - if err != nil { - return 0, err - } - defer db.Close() - - var count int - iter := db.NewIterator(nil, nil) - defer iter.Release() - - for iter.Next() { - if isLocalStorageEntry(iter.Key()) { - count++ - } - } - return count, iter.Error() -} - -func countSessionStorage(path string) (int, error) { - if _, err := os.Stat(path); err != nil { - return 0, err - } - db, err := leveldb.OpenFile(path, nil) - if err != nil { - return 0, err - } - defer db.Close() - - var count int - iter := db.NewIterator(nil, nil) - defer iter.Release() - - mapPrefix := []byte("map-") - for iter.Next() { - if bytes.HasPrefix(iter.Key(), mapPrefix) { - if sep := bytes.IndexByte(iter.Key()[len(mapPrefix):], '-'); sep >= 0 { - count++ - } - } - } - return count, iter.Error() -} - -// isLocalStorageEntry keeps the keys the localStorage extractor emits: data and META entries, never VERSION. -func isLocalStorageEntry(key []byte) bool { - switch { - case bytes.Equal(key, []byte("VERSION")): - return false - case bytes.HasPrefix(key, []byte("METAACCESS:")), bytes.HasPrefix(key, []byte("META:")): - return true - default: - return len(key) > 0 && key[0] == '_' - } -} diff --git a/browser/chromium/count_test.go b/browser/chromium/count_test.go deleted file mode 100644 index 6c55e91..0000000 --- a/browser/chromium/count_test.go +++ /dev/null @@ -1,348 +0,0 @@ -package chromium - -import ( - "encoding/binary" - "testing" - "unicode/utf16" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCountBookmarks(t *testing.T) { - path := setupBookmarkJSON(t) - - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 3, count) // 3 URLs, folders not counted -} - -func TestCountBookmarks_Empty(t *testing.T) { - path := createTestJSON(t, "Bookmarks", `{"roots": {}}`) - - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountCookies(t *testing.T) { - path := setupCookieDB(t) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountCookies_Empty(t *testing.T) { - path := createTestDB(t, "Cookies", cookiesSchema) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountCreditCards(t *testing.T) { - path := setupCreditCardDB(t) - - count, err := countCreditCards(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountCreditCards_Empty(t *testing.T) { - path := createTestDB(t, "Web Data", creditCardsSchema) - - count, err := countCreditCards(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountYandexCreditCards(t *testing.T) { - path := createTestDB(t, "Ya Credit Cards", `CREATE TABLE records (guid TEXT, public_data TEXT, private_data BLOB)`, - `INSERT INTO records (guid) VALUES ('g1')`, - `INSERT INTO records (guid) VALUES ('g2')`, - `INSERT INTO records (guid) VALUES ('g3')`, - ) - - count, err := countYandexCreditCards(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountDownloads(t *testing.T) { - path := setupDownloadDB(t) - - count, err := countDownloads(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountDownloads_Empty(t *testing.T) { - path := createTestDB(t, "History", downloadsSchema) - - count, err := countDownloads(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountExtensions(t *testing.T) { - path := setupExtensionJSON(t) - - count, err := countExtensions(path) - require.NoError(t, err) - assert.Equal(t, 2, count) // system (5) and component (10) skipped -} - -func TestCountOperaExtensions(t *testing.T) { - path := createTestJSON(t, "Secure Preferences", `{ - "extensions": { - "opsettings": { - "opera-ext-1": { - "location": 1, - "manifest": {"name": "Opera Ad Blocker", "version": "2.0.0"} - }, - "system-ext": { - "location": 5, - "manifest": {"name": "System", "version": "1.0"} - } - } - } - }`) - - count, err := countOperaExtensions(path) - require.NoError(t, err) - assert.Equal(t, 1, count) -} - -func TestCountExtensions_Empty(t *testing.T) { - path := createTestJSON(t, "Secure Preferences", `{ - "extensions": {"settings": {}} - }`) - - count, err := countExtensions(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountHistories(t *testing.T) { - path := setupHistoryDB(t) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountHistories_Empty(t *testing.T) { - path := createTestDB(t, "History", urlsSchema) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountPasswords(t *testing.T) { - path := setupLoginDB(t) - - count, err := countPasswords(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountPasswords_Empty(t *testing.T) { - path := createTestDB(t, "Login Data", loginsSchema) - - count, err := countPasswords(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountLocalStorage(t *testing.T) { - dir := setupLocalStorageLevelDB(t) - - count, err := countLocalStorage(dir) - require.NoError(t, err) - assert.Equal(t, 4, count) // VERSION filtered, 2 META + 2 data entries kept -} - -// --------------------------------------------------------------------------- -// countSessionStorage -// --------------------------------------------------------------------------- - -func TestCountSessionStorage(t *testing.T) { - dir := setupSessionStorageLevelDB(t) - - count, err := countSessionStorage(dir) - require.NoError(t, err) - assert.Equal(t, 2, count) // only map- entries with key separator -} - -func TestCountSessionStorage_Empty(t *testing.T) { - dir := createTestLevelDB(t, map[string]string{ - "next-map-id": "1", - "version": "1", - }) - - count, err := countSessionStorage(dir) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -// --------------------------------------------------------------------------- -// Test helpers -// --------------------------------------------------------------------------- - -func setupBookmarkJSON(t *testing.T) string { - t.Helper() - return createTestJSON(t, "Bookmarks", `{ - "roots": { - "bookmark_bar": { - "name": "Bookmarks Bar", - "type": "folder", - "children": [ - {"name": "Go", "type": "url", "url": "https://go.dev", "date_added": "13360000000000000"}, - { - "name": "News", - "type": "folder", - "children": [ - {"name": "HN", "type": "url", "url": "https://news.ycombinator.com", "date_added": "13350000000000000"} - ] - } - ] - }, - "other": { - "name": "Other", - "type": "folder", - "children": [ - {"name": "GitHub", "type": "url", "url": "https://github.com", "date_added": "13370000000000000"} - ] - } - } - }`) -} - -func setupCookieDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "Cookies", cookiesSchema, - insertCookie("session", ".old.com", "/", "", 13340000000000000, 13350000000000000, 1, 1), - insertCookie("token", ".new.com", "/api", "", 13360000000000000, 13370000000000000, 1, 0), - ) -} - -func setupCreditCardDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "Web Data", creditCardsSchema, - insertCreditCard("John Doe", 12, 2025, "", "Johnny", "addr-1"), - insertCreditCard("Jane Smith", 6, 2027, "", "", ""), - ) -} - -func setupDownloadDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "History", downloadsSchema, - insertDownload("/tmp/old.zip", "https://old.com/file.zip", "application/zip", 1024, 13340000000000000, 13340000100000000), - insertDownload("/tmp/new.pdf", "https://new.com/doc.pdf", "application/pdf", 2048, 13360000000000000, 13360000200000000), - ) -} - -func setupExtensionJSON(t *testing.T) string { - t.Helper() - return createTestJSON(t, "Secure Preferences", `{ - "extensions": { - "settings": { - "abc123": { - "location": 1, - "manifest": { - "name": "React DevTools", - "description": "React debugging", - "version": "4.28.0" - } - }, - "system-ext": { - "location": 5, - "manifest": {"name": "System", "version": "1.0"} - }, - "component-ext": { - "location": 10, - "manifest": {"name": "Component", "version": "1.0"} - }, - "def456": { - "location": 1, - "manifest": { - "name": "uBlock Origin", - "description": "Ad blocker", - "version": "1.52.0" - } - } - } - } - }`) -} - -func setupHistoryDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "History", urlsSchema, - insertURL("https://github.com", "GitHub", 100, 13370000000000000), - insertURL("https://go.dev", "Go Dev", 50, 13360000000000000), - insertURL("https://example.com", "Example", 200, 13350000000000000), - ) -} - -func setupLocalStorageLevelDB(t *testing.T) string { - t.Helper() - return createTestLevelDB(t, map[string]string{ - "VERSION": "1", - "META:" + "https://example.com": string([]byte{0x08, 0x96, 0x01}), - "METAACCESS:" + "https://example.com": string([]byte{0x10, 0x20}), - string(append([]byte("_https://example.com\x00"), testEncodeLatin1("token")...)): string(testEncodeLatin1("abc123")), - string(append([]byte("_https://example.com\x00"), testEncodeUTF16("テスト")...)): string(testEncodeUTF16("データ")), - }) -} - -func setupLoginDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "Login Data", loginsSchema, - insertLogin("https://old.com", "https://old.com/login", "alice", 13340000000000000), - insertLogin("https://new.com", "https://new.com/login", "bob", 13360000000000000), - ) -} - -func setupSessionStorageLevelDB(t *testing.T) string { - t.Helper() - return createTestLevelDB(t, map[string]string{ - "namespace-abcd1234_5678_9abc_def0_111111111111-https://github.com/": "100", - "namespace-abcd1234_5678_9abc_def0_111111111111-https://example.com/": "101", - "map-100-__darkreader__wasEnabledForHost": string(testEncodeUTF16Raw("false")), - "map-101-token": string(testEncodeUTF16Raw("abc123")), - "next-map-id": "200", - "version": "1", - }) -} - -func testEncodeLatin1(s string) []byte { - return append([]byte{1}, []byte(s)...) -} - -func testEncodeUTF16(s string) []byte { - encoded := utf16.Encode([]rune(s)) - result := make([]byte, 1, 1+len(encoded)*2) - result[0] = 0 - for _, r := range encoded { - var raw [2]byte - binary.LittleEndian.PutUint16(raw[:], r) - result = append(result, raw[:]...) - } - return result -} - -// testEncodeUTF16Raw encodes as raw UTF-16 LE without format byte prefix -// (used by session storage values). -func testEncodeUTF16Raw(s string) []byte { - encoded := utf16.Encode([]rune(s)) - result := make([]byte, 0, len(encoded)*2) - for _, r := range encoded { - var raw [2]byte - binary.LittleEndian.PutUint16(raw[:], r) - result = append(result, raw[:]...) - } - return result -} diff --git a/browser/chromium/profile.go b/browser/chromium/profile.go deleted file mode 100644 index cfdcba1..0000000 --- a/browser/chromium/profile.go +++ /dev/null @@ -1,255 +0,0 @@ -package chromium - -import ( - "context" - "os" - "path/filepath" - - "github.com/moond4rk/hackbrowserdata/filemanager" - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "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 the profile dir itself. -const snapshotDirID = "profile" - -// profile is one Chromium profile under an installation — the leaf extraction -// unit. It reads its own source files but reuses the installation's master keys. -type profile struct { - profileDir string - browserName string - kind types.BrowserKind - extractors ibrowser.Extractors - sourcePaths map[category.Category]resolvedPath -} - -func (p *profile) name() string { - if p.profileDir == "" { - return "" - } - return filepath.Base(p.profileDir) -} - -func (p *profile) label() string { return p.browserName + "/" + p.name() } - -// extract captures the profile's sources into a private snapshot and runs the Chromium base's extractors on it, -// decrypting with the installation's master keys. -func (p *profile) extract(masterKeys masterkey.Set, categories []category.Category) *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) - } - }() - - ctx := context.Background() - if err := d.Capture(ctx, p.snapshotFiles(categories)); err != nil { - log.Debugf("capture %s: %v", p.label(), err) - return data - } - keys := func(context.Context) masterkey.Set { return masterKeys } - ps := ibrowser.NewProfileSnapshot(d.Snapshot(snapshotDirID), ibrowser.Profile{Name: p.name()}, keys) - out := &dataCollector{data: data, label: p.label()} - for _, cat := range categories { - ex, ok := p.extractors[cat] - if _, found := p.sourcePaths[cat]; !ok || !found { - continue - } - 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 profile source the categories read. -func (p *profile) snapshotFiles(categories []category.Category) []snapshot.File { - var files []snapshot.File - seen := make(map[string]bool) - for _, cat := range categories { - if _, found := p.sourcePaths[cat]; !found { - continue - } - for _, src := range p.extractors[cat].Sources { - if src.Shared { - continue - } - rel, ok := firstOnDisk(p.profileDir, src) - if !ok || seen[rel] { - continue - } - seen[rel] = true - files = append(files, snapshot.File{DirID: snapshotDirID, From: p.profileDir, Rel: rel, IsDir: src.IsDir}) - } - } - return files -} - -func firstOnDisk(dir string, src ibrowser.Source) (string, bool) { - for _, rel := range src.Paths { - info, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))) - if err == nil && info.IsDir() == src.IsDir { - return rel, true - } - } - return "", false -} - -// dataCollector files the records the Chromium 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.CreditCard: - c.data.CreditCards = append(c.data.CreditCards, *v) - case *record.Extension: - c.data.Extensions = append(c.data.Extensions, *v) - case *record.LocalStorage: - c.data.LocalStorage = append(c.data.LocalStorage, *v) - case *record.SessionStorage: - c.data.SessionStorage = append(c.data.SessionStorage, *v) - } -} - -func (c *dataCollector) Fail(err error) { log.Debugf("%s: %v", c.label, err) } - -// count counts entries per category without decryption. -func (p *profile) count(categories []category.Category) map[category.Category]int { - session, err := filemanager.NewSession() - if err != nil { - log.Debugf("new session for %s: %v", p.label(), err) - return nil - } - defer session.Cleanup() - - tempPaths := p.acquireFiles(session, categories) - counts := make(map[category.Category]int) - for _, cat := range categories { - path, ok := tempPaths[cat] - if !ok { - continue - } - counts[cat] = p.countCategory(cat, path) - } - if accountDB, ok := p.acquireAccountPasswords(session, categories); ok { - if count, err := countPasswords(accountDB); err != nil { - log.Debugf("count account passwords for %s: %v", p.label(), err) - } else { - counts[category.Password] += count - } - } - return counts -} - -// acquireAccountPasswords copies the account-synced password DB into the session, when the -// profile has one alongside the local DB. -func (p *profile) acquireAccountPasswords(session *filemanager.Session, categories []category.Category) (string, bool) { - accountPath, ok := p.accountPasswordPath(categories) - if !ok { - return "", false - } - dst := filepath.Join(session.TempDir(), "password_account") - if err := session.Acquire(accountPath, dst, false); err != nil { - log.Debugf("acquire account passwords for %s: %v", p.label(), err) - return "", false - } - return dst, true -} - -// accountPasswordPath returns the account-synced password DB when the primary source resolved to -// the local Login Data DB. If only Login Data For Account exists, it is already the primary source. -func (p *profile) accountPasswordPath(categories []category.Category) (string, bool) { - requested := false - for _, cat := range categories { - if cat == category.Password { - requested = true - break - } - } - primary, ok := p.sourcePaths[category.Password] - if !requested || !ok || primary.rel == accountLoginData || p.kind == types.ChromiumYandex { - return "", false - } - path := filepath.Join(p.profileDir, accountLoginData) - info, err := os.Stat(path) - return path, err == nil && !info.IsDir() -} - -// acquireFiles copies source files to the session temp directory. -func (p *profile) acquireFiles(session *filemanager.Session, categories []category.Category) map[category.Category]string { - tempPaths := make(map[category.Category]string) - for _, cat := range categories { - rp, ok := p.sourcePaths[cat] - if !ok { - continue - } - dst := filepath.Join(session.TempDir(), cat.String()) - if err := session.Acquire(rp.absPath, dst, rp.isDir); err != nil { - log.Debugf("acquire %s: %v", cat, err) - continue - } - tempPaths[cat] = dst - } - return tempPaths -} - -// countCategory calls the appropriate count function for a category. -func (p *profile) countCategory(cat category.Category, path string) int { - var count int - var err error - switch cat { - case category.Password: - count, err = countPasswords(path) - case category.Cookie: - count, err = countCookies(path) - case category.History: - count, err = countHistories(path) - case category.Download: - count, err = countDownloads(path) - case category.Bookmark: - count, err = countBookmarks(path) - case category.CreditCard: - if p.kind == types.ChromiumYandex { - count, err = countYandexCreditCards(path) - } else { - count, err = countCreditCards(path) - } - case category.Extension: - if p.kind == types.ChromiumOpera { - count, err = countOperaExtensions(path) - } else { - count, err = countExtensions(path) - } - case category.LocalStorage: - count, err = countLocalStorage(path) - case category.SessionStorage: - count, err = countSessionStorage(path) - } - if err != nil { - log.Debugf("count %s for %s: %v", cat, p.label(), err) - } - return count -} diff --git a/browser/chromium/profile_test.go b/browser/chromium/profile_test.go deleted file mode 100644 index bafd8c5..0000000 --- a/browser/chromium/profile_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package chromium - -import ( - "database/sql" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/filemanager" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/types" -) - -func createLoginDBAt(t *testing.T, path string, inserts ...string) { - t.Helper() - db, err := sql.Open("sqlite", path) - require.NoError(t, err) - defer db.Close() - _, err = db.Exec(loginsSchema) - require.NoError(t, err) - for _, stmt := range inserts { - _, err = db.Exec(stmt) - require.NoError(t, err) - } -} - -// --------------------------------------------------------------------------- -// acquireFiles -// --------------------------------------------------------------------------- - -func TestAcquireFiles(t *testing.T) { - profileDir := filepath.Join(fixture.chrome, "Default") - resolved := resolveSourcePaths(chromiumSources, profileDir) - - p := &profile{profileDir: profileDir, sourcePaths: resolved} - - session, err := filemanager.NewSession() - require.NoError(t, err) - defer session.Cleanup() - - cats := []category.Category{category.History, category.Cookie, category.Bookmark} - paths := p.acquireFiles(session, cats) - - assert.Len(t, paths, len(cats)) - for _, path := range paths { - _, err := os.Stat(path) - require.NoError(t, err, "acquired file should exist") - } -} - -func TestExtractAndCountPasswords_MergesLocalAndAccountDatabases(t *testing.T) { - profileDir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(profileDir, "Preferences"), []byte(`{}`), 0o600)) - createLoginDBAt(t, filepath.Join(profileDir, "Login Data"), - insertLogin("https://local.example", "", "local-user", 13340000000000000)) - createLoginDBAt(t, filepath.Join(profileDir, accountLoginData), - insertLogin("https://account.example", "", "account-user", 13360000000000000)) - - p := &profile{ - profileDir: profileDir, - browserName: "Chrome", - kind: types.Chromium, - extractors: extractorsFor(types.Chromium), - sourcePaths: resolveSourcePaths(chromiumSources, profileDir), - } - data := p.extract(masterkey.Set{}, []category.Category{category.Password}) - require.Len(t, data.Passwords, 2) - // Account rows are emitted after local ones; the exporter's stable sort relies on that when timestamps tie. - assert.Equal(t, "local-user", data.Passwords[0].Username) - assert.Equal(t, record.StoreLocal, data.Passwords[0].Store) - assert.Equal(t, "account-user", data.Passwords[1].Username) - assert.Equal(t, record.StoreAccount, data.Passwords[1].Store) - assert.Equal(t, 2, p.count([]category.Category{category.Password})[category.Password]) -} - -// A credential synced to both stores is reported twice; the Store field is what tells them -// apart, so it must survive the merge rather than being deduplicated away. -func TestExtractPasswords_IdenticalCredentialInBothStoresKeepsBoth(t *testing.T) { - profileDir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(profileDir, "Preferences"), []byte(`{}`), 0o600)) - login := insertLogin("https://same.example", "", "same-user", 13340000000000000) - createLoginDBAt(t, filepath.Join(profileDir, "Login Data"), login) - createLoginDBAt(t, filepath.Join(profileDir, accountLoginData), login) - - p := &profile{ - profileDir: profileDir, - browserName: "Chrome", - kind: types.Chromium, - extractors: extractorsFor(types.Chromium), - sourcePaths: resolveSourcePaths(chromiumSources, profileDir), - } - data := p.extract(masterkey.Set{}, []category.Category{category.Password}) - - require.Len(t, data.Passwords, 2) - stores := []record.Store{data.Passwords[0].Store, data.Passwords[1].Store} - assert.ElementsMatch(t, []record.Store{record.StoreLocal, record.StoreAccount}, stores) - assert.Equal(t, 2, p.count([]category.Category{category.Password})[category.Password]) -} - -// A profile that only ever synced passwords has no local DB, so the account DB wins candidate -// resolution and must not also be picked up as a second source. -func TestExtractAndCountPasswords_AccountDatabaseOnly(t *testing.T) { - profileDir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(profileDir, "Preferences"), []byte(`{}`), 0o600)) - createLoginDBAt(t, filepath.Join(profileDir, accountLoginData), - insertLogin("https://account.example", "", "account-user", 13360000000000000)) - - p := &profile{ - profileDir: profileDir, - browserName: "Chrome", - kind: types.Chromium, - extractors: extractorsFor(types.Chromium), - sourcePaths: resolveSourcePaths(chromiumSources, profileDir), - } - data := p.extract(masterkey.Set{}, []category.Category{category.Password}) - - require.Len(t, data.Passwords, 1) - assert.Equal(t, "account-user", data.Passwords[0].Username) - assert.Equal(t, record.StoreAccount, data.Passwords[0].Store) - assert.Equal(t, 1, p.count([]category.Category{category.Password})[category.Password]) -} - -func TestCountCategory(t *testing.T) { - t.Run("History", func(t *testing.T) { - path := setupHistoryDB(t) - p := &profile{kind: types.Chromium} - assert.Equal(t, 3, p.countCategory(category.History, path)) - }) - - t.Run("Cookie", func(t *testing.T) { - path := setupCookieDB(t) - p := &profile{kind: types.Chromium} - assert.Equal(t, 2, p.countCategory(category.Cookie, path)) - }) - - t.Run("Bookmark", func(t *testing.T) { - path := setupBookmarkJSON(t) - p := &profile{kind: types.Chromium} - assert.Equal(t, 3, p.countCategory(category.Bookmark, path)) - }) - - t.Run("Extension_Opera", func(t *testing.T) { - path := createTestJSON(t, "Secure Preferences", `{ - "extensions": { - "opsettings": { - "ext1": {"location": 1, "manifest": {"name": "Ext", "version": "1.0"}} - } - } - }`) - p := &profile{kind: types.ChromiumOpera} - assert.Equal(t, 1, p.countCategory(category.Extension, path)) - }) - - t.Run("FileNotFound", func(t *testing.T) { - p := &profile{kind: types.Chromium} - assert.Equal(t, 0, p.countCategory(category.History, "/nonexistent/path")) - }) -} diff --git a/browser/chromium/source.go b/browser/chromium/source.go deleted file mode 100644 index 3edaca7..0000000 --- a/browser/chromium/source.go +++ /dev/null @@ -1,80 +0,0 @@ -package chromium - -import ( - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - ichromium "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" -) - -const accountLoginData = `Login Data For Account` - -// sourcePath describes a single candidate location for browser data, -// relative to the profile directory. -type sourcePath struct { - rel string // relative path from profileDir, e.g. "Network/Cookies" - isDir bool // true for directory targets (LevelDB, Session Storage) -} - -// rel stays slash-canonical (e.g. "Network/Cookies"); filepath.Join converts at resolve time, and -// archive reuses it verbatim as a forward-slash zip entry name. -func file(rel string) sourcePath { return sourcePath{rel: rel, isDir: false} } -func dir(rel string) sourcePath { return sourcePath{rel: rel, isDir: true} } - -// chromiumSources defines the standard Chromium file layout. -// Each category maps to one or more candidate paths tried in priority order; -// the first existing path wins. -var chromiumSources = map[category.Category][]sourcePath{ - category.Password: {file("Login Data"), file(accountLoginData)}, - category.Cookie: {file("Network/Cookies"), file("Cookies")}, - category.History: {file("History")}, - category.Download: {file("History")}, - category.Bookmark: {file("Bookmarks")}, - category.CreditCard: {file("Web Data")}, - category.Extension: {file("Secure Preferences")}, - category.LocalStorage: {dir("Local Storage/leveldb")}, - category.SessionStorage: {dir("Session Storage")}, -} - -// sourcesForKind returns the source mapping for a browser kind. -func sourcesForKind(kind types.BrowserKind) map[category.Category][]sourcePath { - switch kind { - case types.ChromiumYandex: - return yandexSources() - default: - return chromiumSources - } -} - -// yandexSourceOverrides contains only the entries that differ from chromiumSources. -var yandexSourceOverrides = map[category.Category][]sourcePath{ - category.Password: {file("Ya Passman Data")}, - category.CreditCard: {file("Ya Credit Cards")}, -} - -// yandexSources returns chromiumSources with Yandex-specific overrides applied. -func yandexSources() map[category.Category][]sourcePath { - sources := make(map[category.Category][]sourcePath, len(chromiumSources)) - for k, v := range chromiumSources { - sources[k] = v - } - for k, v := range yandexSourceOverrides { - sources[k] = v - } - return sources -} - -// extractorsFor picks the Chromium base's per-fork extractors by kind, which is what chose them before the base had -// its own override table. -func extractorsFor(kind types.BrowserKind) ibrowser.Extractors { - var id string - switch kind { - case types.ChromiumYandex: - id = "yandex" - case types.ChromiumOpera: - id = "opera" - default: - id = "chromium" - } - return ichromium.Extractors(ibrowser.UserDataDir{Def: ibrowser.Def{ID: id, Base: ibrowser.Chromium}}, ibrowser.Profile{}) -} diff --git a/browser/chromium/testutil_test.go b/browser/chromium/testutil_test.go deleted file mode 100644 index 7023cc2..0000000 --- a/browser/chromium/testutil_test.go +++ /dev/null @@ -1,238 +0,0 @@ -package chromium - -import ( - "database/sql" - "fmt" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/require" - "github.com/syndtr/goleveldb/leveldb" - _ "modernc.org/sqlite" -) - -// --------------------------------------------------------------------------- -// Real Chrome table schemas — extracted via `sqlite3 ".schema "`. -// Using complete schemas ensures our SQL queries work against real browser data. -// --------------------------------------------------------------------------- - -const loginsSchema = `CREATE TABLE logins ( - origin_url VARCHAR NOT NULL, - action_url VARCHAR, - username_element VARCHAR, - username_value VARCHAR, - password_element VARCHAR, - password_value BLOB, - submit_element VARCHAR, - signon_realm VARCHAR NOT NULL, - date_created INTEGER NOT NULL, - blacklisted_by_user INTEGER NOT NULL, - scheme INTEGER NOT NULL, - password_type INTEGER, - times_used INTEGER, - form_data BLOB, - display_name VARCHAR, - icon_url VARCHAR, - federation_url VARCHAR, - skip_zero_click INTEGER, - generation_upload_status INTEGER, - possible_username_pairs BLOB, - id INTEGER PRIMARY KEY AUTOINCREMENT, - date_last_used INTEGER NOT NULL DEFAULT 0, - moving_blocked_for BLOB, - date_password_modified INTEGER NOT NULL DEFAULT 0, - sender_email VARCHAR, - sender_name VARCHAR, - date_received INTEGER, - sharing_notification_displayed INTEGER NOT NULL DEFAULT 0, - keychain_identifier BLOB, - sender_profile_image_url VARCHAR, - date_last_filled INTEGER NOT NULL DEFAULT 0, - actor_login_approved INTEGER NOT NULL DEFAULT 0, - UNIQUE (origin_url, username_element, username_value, password_element, signon_realm) -)` - -const cookiesSchema = `CREATE TABLE cookies ( - creation_utc INTEGER NOT NULL, - host_key TEXT NOT NULL, - top_frame_site_key TEXT NOT NULL, - name TEXT NOT NULL, - value TEXT NOT NULL, - encrypted_value BLOB NOT NULL, - path TEXT NOT NULL, - expires_utc INTEGER NOT NULL, - is_secure INTEGER NOT NULL, - is_httponly INTEGER NOT NULL, - last_access_utc INTEGER NOT NULL, - has_expires INTEGER NOT NULL, - is_persistent INTEGER NOT NULL, - priority INTEGER NOT NULL, - samesite INTEGER NOT NULL, - source_scheme INTEGER NOT NULL, - source_port INTEGER NOT NULL, - last_update_utc INTEGER NOT NULL, - source_type INTEGER NOT NULL, - has_cross_site_ancestor INTEGER NOT NULL -)` - -const urlsSchema = `CREATE TABLE urls ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - url LONGVARCHAR, - title LONGVARCHAR, - visit_count INTEGER DEFAULT 0 NOT NULL, - typed_count INTEGER DEFAULT 0 NOT NULL, - last_visit_time INTEGER NOT NULL, - hidden INTEGER DEFAULT 0 NOT NULL -)` - -const downloadsSchema = `CREATE TABLE downloads ( - id INTEGER PRIMARY KEY, - guid VARCHAR NOT NULL, - current_path LONGVARCHAR NOT NULL, - target_path LONGVARCHAR NOT NULL, - start_time INTEGER NOT NULL, - received_bytes INTEGER NOT NULL, - total_bytes INTEGER NOT NULL, - state INTEGER NOT NULL, - danger_type INTEGER NOT NULL, - interrupt_reason INTEGER NOT NULL, - hash BLOB NOT NULL, - end_time INTEGER NOT NULL, - opened INTEGER NOT NULL, - last_access_time INTEGER NOT NULL, - transient INTEGER NOT NULL, - referrer VARCHAR NOT NULL, - site_url VARCHAR NOT NULL, - embedder_download_data VARCHAR NOT NULL, - tab_url VARCHAR NOT NULL, - tab_referrer_url VARCHAR NOT NULL, - http_method VARCHAR NOT NULL, - by_ext_id VARCHAR NOT NULL, - by_ext_name VARCHAR NOT NULL, - by_web_app_id VARCHAR NOT NULL, - etag VARCHAR NOT NULL, - last_modified VARCHAR NOT NULL, - mime_type VARCHAR(255) NOT NULL, - original_mime_type VARCHAR(255) NOT NULL -)` - -const creditCardsSchema = `CREATE TABLE credit_cards ( - guid VARCHAR PRIMARY KEY, - name_on_card VARCHAR, - expiration_month INTEGER, - expiration_year INTEGER, - card_number_encrypted BLOB, - date_modified INTEGER NOT NULL DEFAULT 0, - origin VARCHAR DEFAULT '', - use_count INTEGER NOT NULL DEFAULT 0, - use_date INTEGER NOT NULL DEFAULT 0, - billing_address_id VARCHAR, - nickname VARCHAR -)` - -// --------------------------------------------------------------------------- -// INSERT helpers — each returns one SQL statement with only the fields -// our extract functions care about; other NOT NULL columns get defaults. -// --------------------------------------------------------------------------- - -func insertLogin(originURL, actionURL, username string, dateCreated int64) string { - return fmt.Sprintf( - `INSERT INTO logins (origin_url, action_url, username_element, username_value, - password_element, password_value, submit_element, signon_realm, date_created, - blacklisted_by_user, scheme) - VALUES ('%s', '%s', '', '%s', '', x'', '', '%s', %d, 0, 0)`, - originURL, actionURL, username, originURL, dateCreated, - ) -} - -func insertCookie(name, host, path, encValueHex string, creationUTC, expiresUTC int64, secure, httpOnly int) string { - return fmt.Sprintf( - `INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, value, - encrypted_value, path, expires_utc, is_secure, is_httponly, last_access_utc, - has_expires, is_persistent, priority, samesite, source_scheme, source_port, - last_update_utc, source_type, has_cross_site_ancestor) - VALUES (%d, '%s', '', '%s', '', x'%s', '%s', %d, %d, %d, %d, 1, 1, 1, 0, 2, 443, %d, 0, 0)`, - creationUTC, host, name, encValueHex, path, expiresUTC, secure, httpOnly, creationUTC, creationUTC, - ) -} - -func insertURL(url, title string, visitCount int, lastVisitTime int64) string { - return fmt.Sprintf( - `INSERT INTO urls (url, title, visit_count, typed_count, last_visit_time, hidden) - VALUES ('%s', '%s', %d, 0, %d, 0)`, - url, title, visitCount, lastVisitTime, - ) -} - -func insertDownload(targetPath, tabURL, mimeType string, totalBytes, startTime, endTime int64) string { - return fmt.Sprintf( - `INSERT INTO downloads (id, guid, current_path, target_path, start_time, received_bytes, - total_bytes, state, danger_type, interrupt_reason, hash, end_time, opened, last_access_time, - transient, referrer, site_url, embedder_download_data, tab_url, tab_referrer_url, - http_method, by_ext_id, by_ext_name, by_web_app_id, etag, last_modified, mime_type, original_mime_type) - VALUES (NULL, '', '', '%s', %d, %d, %d, 1, 0, 0, x'', %d, 0, 0, 0, '', '', '', '%s', '', 'GET', '', '', '', '', '', '%s', '')`, - targetPath, startTime, totalBytes, totalBytes, endTime, tabURL, mimeType, - ) -} - -func insertCreditCard(name string, month, year int, encNumberHex, nickName, address string) string { - return fmt.Sprintf( - `INSERT INTO credit_cards (guid, name_on_card, expiration_month, expiration_year, card_number_encrypted, nickname, billing_address_id) - VALUES ('%s-%d-%d', '%s', %d, %d, x'%s', '%s', '%s')`, - name, month, year, name, month, year, encNumberHex, nickName, address, - ) -} - -// --------------------------------------------------------------------------- -// Test fixture builders -// --------------------------------------------------------------------------- - -// installFile copies a test fixture file into a profile directory. -// This bridges per-category setup functions (which return standalone paths) -// and browser-level integration tests (which need files inside a profile). -func installFile(t *testing.T, profileDir, srcPath, dstName string) { - t.Helper() - data, err := os.ReadFile(srcPath) - require.NoError(t, err) - require.NoError(t, os.WriteFile(filepath.Join(profileDir, dstName), data, 0o644)) -} - -// createTestDB creates a SQLite database with the given schema and insert statements. -func createTestDB(t *testing.T, name, schema string, inserts ...string) string { - t.Helper() - path := filepath.Join(t.TempDir(), name) - db, err := sql.Open("sqlite", path) - require.NoError(t, err) - defer db.Close() - - _, err = db.Exec(schema) - require.NoError(t, err) - - for _, stmt := range inserts { - _, err = db.Exec(stmt) - require.NoError(t, err) - } - return path -} - -// createTestJSON creates a file with the given JSON content. -func createTestJSON(t *testing.T, name, content string) string { - t.Helper() - path := filepath.Join(t.TempDir(), name) - require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) - return path -} - -// createTestLevelDB creates a LevelDB directory with the given key-value pairs. -func createTestLevelDB(t *testing.T, entries map[string]string) string { - t.Helper() - dir := filepath.Join(t.TempDir(), "leveldb") - db, err := leveldb.OpenFile(dir, nil) - require.NoError(t, err) - for k, v := range entries { - require.NoError(t, db.Put([]byte(k), []byte(v), nil)) - } - require.NoError(t, db.Close()) - return dir -} diff --git a/browser/defs.go b/browser/defs.go deleted file mode 100644 index 846f3d8..0000000 --- a/browser/defs.go +++ /dev/null @@ -1,46 +0,0 @@ -package browser - -import ( - "os" - - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/types" -) - -var homeDir, _ = os.UserHomeDir() - -// platformBrowsers adapts this OS's rows of the browser table; joining with "/" keeps today's user data dir strings. -func platformBrowsers() []types.BrowserConfig { - var configs []types.BrowserConfig - for _, d := range ibrowser.Supported() { - p := d.Platform() - for _, dir := range p.UserDataDirs { - configs = append(configs, types.BrowserConfig{ - Key: d.ID, - Name: d.Name, - Kind: kindOf(d), - KeychainLabel: p.KeychainLabel, - WindowsABE: p.ABE != masterkey.ABENone, - UserDataDir: homeDir + "/" + dir, - }) - } - } - return configs -} - -// kindOf derives today's engine kind; Yandex and the Opera family are the forks with their own on-disk format. -func kindOf(d ibrowser.Def) types.BrowserKind { - switch { - case d.Base == ibrowser.Firefox: - return types.Firefox - case d.Base == ibrowser.Safari: - return types.Safari - case d.ID == "yandex": - return types.ChromiumYandex - case d.ID == "opera", d.ID == "opera-gx", d.ID == "vought": - return types.ChromiumOpera - default: - return types.Chromium - } -} diff --git a/browser/firefox/count.go b/browser/firefox/count.go deleted file mode 100644 index b49e57d..0000000 --- a/browser/firefox/count.go +++ /dev/null @@ -1,65 +0,0 @@ -package firefox - -import ( - "os" - - "github.com/tidwall/gjson" - - "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 ( - firefoxCountCookieQuery = `SELECT COUNT(*) FROM moz_cookies` - firefoxCountHistoryQuery = `SELECT COUNT(*) FROM moz_places` - firefoxCountDownloadQuery = `SELECT COUNT(*) FROM - (SELECT place_id FROM moz_annos - INNER JOIN moz_places ON moz_annos.place_id=moz_places.id - GROUP BY place_id)` - firefoxCountBookmarkQuery = `SELECT COUNT(*) FROM moz_bookmarks - INNER JOIN moz_places ON moz_bookmarks.fk=moz_places.id` - firefoxCountLocalStorageQuery = `SELECT COUNT(*) FROM webappsstore2` -) - -func countPasswords(path string) (int, error) { - data, err := os.ReadFile(path) - if err != nil { - return 0, err - } - return len(gjson.GetBytes(data, "logins").Array()), nil -} - -func countCookies(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountCookieQuery) -} - -func countHistories(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountHistoryQuery) -} - -func countDownloads(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountDownloadQuery) -} - -func countBookmarks(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountBookmarkQuery) -} - -func countExtensions(path string) (int, error) { - data, err := os.ReadFile(path) - if err != nil { - return 0, err - } - - var count int - for _, v := range gjson.GetBytes(data, "addons").Array() { - if v.Get("location").String() == "app-profile" { - count++ - } - } - return count, nil -} - -func countLocalStorage(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountLocalStorageQuery) -} diff --git a/browser/firefox/count_test.go b/browser/firefox/count_test.go deleted file mode 100644 index 9018b0a..0000000 --- a/browser/firefox/count_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package firefox - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCountBookmarks(t *testing.T) { - path := setupMozBookmarkDB(t) - - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountBookmarks_Empty(t *testing.T) { - path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozBookmarksSchema}) - - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountCookies(t *testing.T) { - path := setupMozCookieDB(t) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountCookies_Empty(t *testing.T) { - path := createTestDB(t, "cookies.sqlite", []string{mozCookiesSchema}) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountDownloads(t *testing.T) { - path := setupMozDownloadDB(t) - - count, err := countDownloads(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountDownloads_Empty(t *testing.T) { - path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozAnnosSchema}) - - count, err := countDownloads(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountExtensions(t *testing.T) { - path := setupMozExtensionJSON(t) - - count, err := countExtensions(path) - require.NoError(t, err) - assert.Equal(t, 2, count) // system addon filtered out -} - -func TestCountExtensions_Empty(t *testing.T) { - path := createTestJSON(t, "extensions.json", `{"addons": []}`) - - count, err := countExtensions(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountHistories(t *testing.T) { - path := setupMozHistoryDB(t) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountHistories_Empty(t *testing.T) { - path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema}) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountLocalStorage(t *testing.T) { - path := setupWebappsDB(t) - - count, err := countLocalStorage(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountLocalStorage_Empty(t *testing.T) { - path := createTestDB(t, "webappsstore.sqlite", []string{webappsstore2Schema}) - - count, err := countLocalStorage(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - -func TestCountPasswords(t *testing.T) { - json := `{ - "logins": [ - {"hostname": "https://a.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 1000}, - {"hostname": "https://b.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 2000}, - {"hostname": "https://c.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 3000} - ] - }` - path := createTestJSON(t, "logins.json", json) - - count, err := countPasswords(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountPasswords_Empty(t *testing.T) { - path := createTestJSON(t, "logins.json", `{"logins": []}`) - - count, err := countPasswords(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} diff --git a/browser/firefox/firefox.go b/browser/firefox/firefox.go deleted file mode 100644 index 34ea028..0000000 --- a/browser/firefox/firefox.go +++ /dev/null @@ -1,136 +0,0 @@ -package firefox - -import ( - "os" - "path/filepath" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" -) - -// Browser is one Firefox installation: the Profiles directory holding one or -// more profiles. Firefox keys are per-profile (each profile's key4.db), so the -// installation does not implement KeyManager. -type Browser struct { - cfg types.BrowserConfig - profiles []*profile -} - -// NewBrowser discovers the Firefox profiles under cfg.UserDataDir and returns -// the installation, or nil if no profile with resolvable sources exists. -// Firefox profile directories have random names (e.g. "97nszz88.default-release"); -// any subdirectory containing known data files is treated as a valid profile. -func NewBrowser(cfg types.BrowserConfig) (*Browser, error) { - var profiles []*profile - for _, profileDir := range discoverProfiles(cfg.UserDataDir, firefoxSources) { - sourcePaths := resolveSourcePaths(firefoxSources, profileDir) - if len(sourcePaths) == 0 { - continue - } - profiles = append(profiles, &profile{ - profileDir: profileDir, - browserName: cfg.Name, - sourcePaths: sourcePaths, - }) - } - if len(profiles) == 0 { - return nil, nil - } - return &Browser{cfg: cfg, profiles: profiles}, nil -} - -func (b *Browser) BrowserName() string { return b.cfg.Name } -func (b *Browser) UserDataDir() string { return b.cfg.UserDataDir } - -// Profiles returns the identity of every profile in this installation. -func (b *Browser) Profiles() []types.Profile { - out := make([]types.Profile, 0, len(b.profiles)) - for _, p := range b.profiles { - out = append(out, types.Profile{Name: p.name(), Dir: p.profileDir}) - } - return out -} - -// Extract extracts every profile, deriving each profile's key independently. -func (b *Browser) Extract(categories []category.Category) ([]types.ExtractResult, error) { - results := make([]types.ExtractResult, 0, len(b.profiles)) - for _, p := range b.profiles { - results = append(results, types.ExtractResult{ - Profile: types.Profile{Name: p.name(), Dir: p.profileDir}, - Data: p.extract(categories), - }) - } - return results, nil -} - -// CountEntries counts entries per category for every profile without decryption. -func (b *Browser) CountEntries(categories []category.Category) ([]types.CountResult, error) { - results := make([]types.CountResult, 0, len(b.profiles)) - for _, p := range b.profiles { - results = append(results, types.CountResult{ - Profile: types.Profile{Name: p.name(), Dir: p.profileDir}, - Counts: p.count(categories), - }) - } - return results, nil -} - -// resolvedPath holds the absolute path and type for a discovered source. -type resolvedPath struct { - absPath string - isDir bool -} - -// discoverProfiles lists subdirectories of userDataDir that contain at least -// one known data source. Each such directory is a Firefox profile. -func discoverProfiles(userDataDir string, sources map[category.Category][]sourcePath) []string { - entries, err := os.ReadDir(userDataDir) - if err != nil { - return nil - } - - var profiles []string - for _, e := range entries { - if !e.IsDir() { - continue - } - dir := filepath.Join(userDataDir, e.Name()) - if hasAnySource(sources, dir) { - profiles = append(profiles, dir) - } - } - return profiles -} - -// hasAnySource checks if dir contains at least one source file or directory. -func hasAnySource(sources map[category.Category][]sourcePath, dir string) bool { - for _, candidates := range sources { - for _, sp := range candidates { - abs := filepath.Join(dir, sp.rel) - if _, err := os.Stat(abs); err == nil { - return true - } - } - } - return false -} - -// resolveSourcePaths checks which sources actually exist in profileDir. -// Candidates are tried in priority order; the first existing path wins. -func resolveSourcePaths(sources map[category.Category][]sourcePath, profileDir string) map[category.Category]resolvedPath { - resolved := make(map[category.Category]resolvedPath) - for cat, candidates := range sources { - for _, sp := range candidates { - abs := filepath.Join(profileDir, sp.rel) - info, err := os.Stat(abs) - if err != nil { - continue - } - if sp.isDir == info.IsDir() { - resolved[cat] = resolvedPath{abs, sp.isDir} - break - } - } - } - return resolved -} diff --git a/browser/firefox/firefox_test.go b/browser/firefox/firefox_test.go deleted file mode 100644 index afbaf9a..0000000 --- a/browser/firefox/firefox_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package firefox - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" -) - -// Shared fixtures built once for all tests. -var fixture struct { - root string - multiProf string // two Firefox profiles + non-profile dir - singleProf string // one profile with all data files - partial string // profile missing some files - empty string -} - -func TestMain(m *testing.M) { - root, err := os.MkdirTemp("", "firefox-test-*") - if err != nil { - panic(err) - } - fixture.root = root - buildFixtures() - code := m.Run() - os.RemoveAll(root) - os.Exit(code) -} - -func buildFixtures() { - allFiles := []string{ - "places.sqlite", "cookies.sqlite", "logins.json", - "extensions.json", "webappsstore.sqlite", "key4.db", - } - - // Multi-profile: two valid profiles + one non-profile directory - fixture.multiProf = filepath.Join(fixture.root, "multi") - for _, prof := range []string{"abc123.default-release", "xyz789.default"} { - for _, f := range allFiles { - mkFile(fixture.multiProf, prof, f) - } - } - mkDir(fixture.multiProf, "Crash Reports") - mkDir(fixture.multiProf, "Pending Pings") - - // Single profile: one profile with all files - fixture.singleProf = filepath.Join(fixture.root, "single") - for _, f := range allFiles { - mkFile(fixture.singleProf, "m1n2o3.default-release", f) - } - - // Partial profile: only places.sqlite (no logins, no cookies) - fixture.partial = filepath.Join(fixture.root, "partial") - mkFile(fixture.partial, "p4q5r6.default", "places.sqlite") - - // Empty directory - fixture.empty = filepath.Join(fixture.root, "empty") - mkDir(fixture.empty) -} - -func mkFile(parts ...string) { - path := filepath.Join(parts...) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - panic(err) - } - if err := os.WriteFile(path, []byte("test"), 0o644); err != nil { - panic(err) - } -} - -func mkDir(parts ...string) { - if err := os.MkdirAll(filepath.Join(parts...), 0o755); err != nil { - panic(err) - } -} - -// TestNewBrowsers is table-driven, covering all profile discovery scenarios. -func TestNewBrowsers(t *testing.T) { - tests := []struct { - name string - dir string - wantProfiles []string // expected profile base names - skipDirs []string // should NOT appear as profiles - }{ - { - name: "multi-profile discovery", - dir: fixture.multiProf, - wantProfiles: []string{"abc123.default-release", "xyz789.default"}, - skipDirs: []string{"Crash Reports", "Pending Pings"}, - }, - { - name: "single profile", - dir: fixture.singleProf, - wantProfiles: []string{"m1n2o3.default-release"}, - }, - { - name: "partial profile", - dir: fixture.partial, - wantProfiles: []string{"p4q5r6.default"}, - }, - { - name: "empty dir", - dir: fixture.empty, - }, - { - name: "nonexistent dir", - dir: "/nonexistent/path", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := types.BrowserConfig{Name: "Firefox", Kind: types.Firefox, UserDataDir: tt.dir} - b, err := NewBrowser(cfg) - require.NoError(t, err) - - if len(tt.wantProfiles) == 0 { - assert.Nil(t, b) - return - } - require.NotNil(t, b) - require.Len(t, b.profiles, len(tt.wantProfiles)) - - profileNames := make(map[string]bool) - for _, p := range b.profiles { - profileNames[filepath.Base(p.profileDir)] = true - } - for _, want := range tt.wantProfiles { - assert.True(t, profileNames[want], "should find profile %s", want) - } - for _, skip := range tt.skipDirs { - assert.False(t, profileNames[skip], "should not find %s", skip) - } - }) - } -} - -// TestResolveSourcePaths verifies that source resolution correctly maps -// categories to files, including shared files (places.sqlite). -func TestResolveSourcePaths(t *testing.T) { - profileDir := filepath.Join(fixture.singleProf, "m1n2o3.default-release") - resolved := resolveSourcePaths(firefoxSources, profileDir) - - // All categories should be resolved - for _, cat := range []category.Category{ - category.Password, category.Cookie, category.History, - category.Download, category.Bookmark, category.Extension, category.LocalStorage, - } { - assert.Contains(t, resolved, cat, "should resolve %s", cat) - } - - // History, Download, Bookmark share places.sqlite - assert.Equal(t, resolved[category.History].absPath, resolved[category.Download].absPath) - assert.Equal(t, resolved[category.History].absPath, resolved[category.Bookmark].absPath) - - // Password is a different file - assert.NotEqual(t, resolved[category.Password].absPath, resolved[category.History].absPath) -} - -func TestResolveSourcePaths_Partial(t *testing.T) { - profileDir := filepath.Join(fixture.partial, "p4q5r6.default") - resolved := resolveSourcePaths(firefoxSources, profileDir) - - // Only places.sqlite exists → History, Download, Bookmark resolved - assert.Contains(t, resolved, category.History) - assert.Contains(t, resolved, category.Download) - assert.Contains(t, resolved, category.Bookmark) - - // No logins.json, cookies.sqlite, etc. - assert.NotContains(t, resolved, category.Password) - assert.NotContains(t, resolved, category.Cookie) - assert.NotContains(t, resolved, category.Extension) -} - -// --------------------------------------------------------------------------- -// CountEntries -// --------------------------------------------------------------------------- - -func TestCountEntries(t *testing.T) { - dir := t.TempDir() - profileDir := filepath.Join(dir, "test-profile") - mkDir(profileDir) - installFile(t, profileDir, setupMozHistoryDB(t), "places.sqlite") - - b, err := NewBrowser(types.BrowserConfig{ - Name: "Firefox", Kind: types.Firefox, UserDataDir: dir, - }) - require.NoError(t, err) - require.NotNil(t, b) - - // CountEntries works without master key. - results, err := b.CountEntries([]category.Category{category.History}) - require.NoError(t, err) - require.Len(t, results, 1) - assert.Equal(t, 3, results[0].Counts[category.History]) -} diff --git a/browser/firefox/profile.go b/browser/firefox/profile.go deleted file mode 100644 index 7ec75a2..0000000 --- a/browser/firefox/profile.go +++ /dev/null @@ -1,191 +0,0 @@ -package firefox - -import ( - "context" - "os" - "path/filepath" - - "github.com/moond4rk/hackbrowserdata/filemanager" - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - ifirefox "github.com/moond4rk/hackbrowserdata/internal/browser/firefox" - "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 the profile dir itself. -const snapshotDirID = "profile" - -// profile is one Firefox profile — the leaf extraction unit. Unlike Chromium, -// each Firefox profile owns its own master key (derived from its key4.db). -type profile struct { - profileDir string - browserName string - sourcePaths map[category.Category]resolvedPath -} - -func (p *profile) name() string { - if p.profileDir == "" { - return "" - } - return filepath.Base(p.profileDir) -} - -func (p *profile) label() string { return p.browserName + "/" + p.name() } - -// extract captures the profile's sources into a private snapshot and runs the Firefox base's extractors on it. -func (p *profile) extract(categories []category.Category) *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) - } - }() - - extractors := ifirefox.Extractors(ibrowser.UserDataDir{}, ibrowser.Profile{}) - ctx := context.Background() - if err := d.Capture(ctx, p.snapshotFiles(extractors, categories)); err != nil { - log.Debugf("capture %s: %v", p.label(), err) - return data - } - ps := ibrowser.NewProfileSnapshot(d.Snapshot(snapshotDirID), ibrowser.Profile{Name: p.name()}, nil) - out := &dataCollector{data: data, label: p.label()} - for _, cat := range categories { - ex, ok := extractors[cat] - if _, found := p.sourcePaths[cat]; !ok || !found { - continue - } - 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 (p *profile) snapshotFiles(extractors ibrowser.Extractors, categories []category.Category) []snapshot.File { - var files []snapshot.File - seen := make(map[string]bool) - for _, cat := range categories { - if _, found := p.sourcePaths[cat]; !found { - continue - } - for _, src := range extractors[cat].Sources { - rel, ok := firstOnDisk(p.profileDir, src) - if !ok || seen[rel] { - continue - } - seen[rel] = true - files = append(files, snapshot.File{DirID: snapshotDirID, From: p.profileDir, Rel: rel, IsDir: src.IsDir}) - } - } - return files -} - -func firstOnDisk(dir string, src ibrowser.Source) (string, bool) { - for _, rel := range src.Paths { - info, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))) - if err == nil && info.IsDir() == src.IsDir { - return rel, true - } - } - return "", false -} - -// dataCollector files the records the Firefox 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) } - -func (p *profile) count(categories []category.Category) map[category.Category]int { - session, err := filemanager.NewSession() - if err != nil { - log.Debugf("new session for %s: %v", p.label(), err) - return nil - } - defer session.Cleanup() - - tempPaths := p.acquireFiles(session, categories) - counts := make(map[category.Category]int) - for _, cat := range categories { - path, ok := tempPaths[cat] - if !ok { - continue - } - counts[cat] = p.countCategory(cat, path) - } - return counts -} - -func (p *profile) acquireFiles(session *filemanager.Session, categories []category.Category) map[category.Category]string { - tempPaths := make(map[category.Category]string) - for _, cat := range categories { - rp, ok := p.sourcePaths[cat] - if !ok { - continue - } - dst := filepath.Join(session.TempDir(), cat.String()) - if err := session.Acquire(rp.absPath, dst, rp.isDir); err != nil { - log.Debugf("acquire %s: %v", cat, err) - continue - } - tempPaths[cat] = dst - } - return tempPaths -} - -func (p *profile) countCategory(cat category.Category, path string) int { - var count int - var err error - switch cat { - case category.Password: - count, err = countPasswords(path) - case category.Cookie: - count, err = countCookies(path) - case category.History: - count, err = countHistories(path) - case category.Download: - count, err = countDownloads(path) - case category.Bookmark: - count, err = countBookmarks(path) - case category.Extension: - count, err = countExtensions(path) - case category.LocalStorage: - count, err = countLocalStorage(path) - case category.CreditCard, category.SessionStorage: - // Firefox does not support CreditCard or SessionStorage. - } - if err != nil { - log.Debugf("count %s for %s: %v", cat, p.label(), err) - } - return count -} diff --git a/browser/firefox/profile_test.go b/browser/firefox/profile_test.go deleted file mode 100644 index 7a162ad..0000000 --- a/browser/firefox/profile_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package firefox - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/internal/category" -) - -func TestCountCategory(t *testing.T) { - t.Run("History", func(t *testing.T) { - path := setupMozHistoryDB(t) - p := &profile{} - assert.Equal(t, 3, p.countCategory(category.History, path)) - }) - - t.Run("Cookie", func(t *testing.T) { - path := setupMozCookieDB(t) - p := &profile{} - assert.Equal(t, 2, p.countCategory(category.Cookie, path)) - }) - - t.Run("Bookmark", func(t *testing.T) { - path := setupMozBookmarkDB(t) - p := &profile{} - assert.Equal(t, 2, p.countCategory(category.Bookmark, path)) - }) - - t.Run("Extension", func(t *testing.T) { - path := setupMozExtensionJSON(t) - p := &profile{} - assert.Equal(t, 2, p.countCategory(category.Extension, path)) - }) - - 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")) - }) -} - -// extract runs the Firefox base's extractors on a private snapshot of the profile. -func TestExtract(t *testing.T) { - profileDir := t.TempDir() - installFile(t, profileDir, setupMozHistoryDB(t), "places.sqlite") - installFile(t, profileDir, setupMozCookieDB(t), "cookies.sqlite") - installFile(t, profileDir, setupMozExtensionJSON(t), "extensions.json") - p := &profile{profileDir: profileDir, browserName: "Firefox", sourcePaths: resolveSourcePaths(firefoxSources, profileDir)} - - data := p.extract([]category.Category{ - category.History, category.Cookie, category.Extension, category.CreditCard, category.SessionStorage, - }) - require.Len(t, data.Histories, 3) - visits := []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount, data.Histories[2].VisitCount} - assert.ElementsMatch(t, []int{100, 50, 200}, visits) - require.Len(t, data.Cookies, 2) - assert.Equal(t, "abc123", data.Cookies[0].Value) // Firefox cookies are not encrypted - assert.Len(t, data.Extensions, 2) // the system add-on is skipped - assert.Empty(t, data.CreditCards) - assert.Empty(t, data.SessionStorage) -} diff --git a/browser/firefox/source.go b/browser/firefox/source.go deleted file mode 100644 index 10ff977..0000000 --- a/browser/firefox/source.go +++ /dev/null @@ -1,30 +0,0 @@ -package firefox - -import ( - "path/filepath" - - "github.com/moond4rk/hackbrowserdata/internal/category" -) - -// sourcePath describes a single candidate location for browser data, -// relative to the profile directory. -type sourcePath struct { - rel string // relative path from profileDir - isDir bool // true for directory targets -} - -func file(rel string) sourcePath { return sourcePath{rel: filepath.FromSlash(rel), isDir: false} } - -// firefoxSources defines the Firefox file layout. -// Each category maps to one or more candidate paths tried in priority order; -// the first existing path wins. -// Firefox does not support SessionStorage or CreditCard extraction. -var firefoxSources = map[category.Category][]sourcePath{ - category.Password: {file("logins.json")}, - category.Cookie: {file("cookies.sqlite")}, - category.History: {file("places.sqlite")}, - category.Download: {file("places.sqlite")}, - category.Bookmark: {file("places.sqlite")}, - category.Extension: {file("extensions.json")}, - category.LocalStorage: {file("webappsstore.sqlite")}, -} diff --git a/browser/firefox/testutil_test.go b/browser/firefox/testutil_test.go deleted file mode 100644 index 8c5ea67..0000000 --- a/browser/firefox/testutil_test.go +++ /dev/null @@ -1,255 +0,0 @@ -package firefox - -import ( - "database/sql" - "fmt" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/require" - _ "modernc.org/sqlite" -) - -// --------------------------------------------------------------------------- -// Real Firefox table schemas — extracted via `sqlite3 ".schema
"`. -// --------------------------------------------------------------------------- - -const mozCookiesSchema = `CREATE TABLE moz_cookies ( - id INTEGER PRIMARY KEY, - originAttributes TEXT NOT NULL DEFAULT '', - name TEXT, - value TEXT, - host TEXT, - path TEXT, - expiry INTEGER, - lastAccessed INTEGER, - creationTime INTEGER, - isSecure INTEGER, - isHttpOnly INTEGER, - inBrowserElement INTEGER DEFAULT 0, - sameSite INTEGER DEFAULT 0, - rawSameSite INTEGER DEFAULT 0, - schemeMap INTEGER DEFAULT 0, - isPartitionedAttributeSet INTEGER DEFAULT 0, - CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes) -)` - -const mozPlacesSchema = `CREATE TABLE moz_places ( - id INTEGER PRIMARY KEY, - url LONGVARCHAR, - title LONGVARCHAR, - rev_host LONGVARCHAR, - visit_count INTEGER DEFAULT 0, - hidden INTEGER DEFAULT 0 NOT NULL, - typed INTEGER DEFAULT 0 NOT NULL, - frecency INTEGER DEFAULT -1 NOT NULL, - last_visit_date INTEGER, - guid TEXT, - foreign_count INTEGER DEFAULT 0 NOT NULL, - url_hash INTEGER DEFAULT 0 NOT NULL, - description TEXT, - preview_image_url TEXT, - site_name TEXT, - origin_id INTEGER, - recalc_frecency INTEGER NOT NULL DEFAULT 0, - alt_frecency INTEGER, - recalc_alt_frecency INTEGER NOT NULL DEFAULT 0 -)` - -const mozBookmarksSchema = `CREATE TABLE moz_bookmarks ( - id INTEGER PRIMARY KEY, - type INTEGER, - fk INTEGER DEFAULT NULL, - parent INTEGER, - position INTEGER, - title LONGVARCHAR, - keyword_id INTEGER, - folder_type TEXT, - dateAdded INTEGER, - lastModified INTEGER, - guid TEXT, - syncStatus INTEGER NOT NULL DEFAULT 0, - syncChangeCounter INTEGER NOT NULL DEFAULT 1 -)` - -const mozAnnosSchema = `CREATE TABLE moz_annos ( - id INTEGER PRIMARY KEY, - place_id INTEGER NOT NULL, - anno_attribute_id INTEGER, - content LONGVARCHAR, - flags INTEGER DEFAULT 0, - expiration INTEGER DEFAULT 0, - type INTEGER DEFAULT 0, - dateAdded INTEGER DEFAULT 0, - lastModified INTEGER DEFAULT 0 -)` - -const webappsstore2Schema = `CREATE TABLE webappsstore2 ( - originAttributes TEXT, - originKey TEXT, - scope TEXT, - key TEXT, - value TEXT -)` - -// --------------------------------------------------------------------------- -// INSERT helpers -// --------------------------------------------------------------------------- - -func insertMozCookie(name, value, host, path string, creationTime, expiry int64, isSecure, isHTTPOnly int) string { - return fmt.Sprintf( - `INSERT INTO moz_cookies (name, value, host, path, creationTime, expiry, isSecure, isHttpOnly, lastAccessed) - VALUES ('%s', '%s', '%s', '%s', %d, %d, %d, %d, %d)`, - name, value, host, path, creationTime, expiry, isSecure, isHTTPOnly, creationTime, - ) -} - -func insertMozPlace(id int, url, title string, visitCount int, lastVisitDate int64) string { - return fmt.Sprintf( - `INSERT INTO moz_places (id, url, title, visit_count, last_visit_date, rev_host, guid, url_hash) - VALUES (%d, '%s', '%s', %d, %d, '', 'guid-%d', 0)`, - id, url, title, visitCount, lastVisitDate, id, - ) -} - -func insertMozBookmark(id, fk, bookmarkType int, title string, dateAdded int64) string { - return fmt.Sprintf( - `INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, dateAdded, lastModified, guid) - VALUES (%d, %d, %d, 0, 0, '%s', %d, %d, 'bm-guid-%d')`, - id, bookmarkType, fk, title, dateAdded, dateAdded, id, - ) -} - -func insertMozAnno(placeID int, content string, dateAdded int64) string { - return fmt.Sprintf( - `INSERT INTO moz_annos (place_id, anno_attribute_id, content, dateAdded, lastModified) - VALUES (%d, 1, '%s', %d, %d)`, - placeID, content, dateAdded, dateAdded, - ) -} - -func insertWebappsstore(originKey, key, value string) string { - return fmt.Sprintf( - `INSERT INTO webappsstore2 (originAttributes, originKey, scope, key, value) - VALUES ('', '%s', '', '%s', '%s')`, - originKey, key, value, - ) -} - -// --------------------------------------------------------------------------- -// Test fixture builders -// --------------------------------------------------------------------------- - -// installFile copies a test fixture file into a profile directory. -func installFile(t *testing.T, profileDir, srcPath, dstName string) { - t.Helper() - data, err := os.ReadFile(srcPath) - require.NoError(t, err) - require.NoError(t, os.WriteFile(filepath.Join(profileDir, dstName), data, 0o644)) -} - -func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { - 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 -} - -func createTestJSON(t *testing.T, name, content string) string { - t.Helper() - path := filepath.Join(t.TempDir(), name) - require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) - return path -} - -func setupMozBookmarkDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozBookmarksSchema}, - insertMozPlace(1, "https://go.dev", "Go", 0, 0), - insertMozPlace(2, "https://github.com", "GitHub", 0, 0), - insertMozBookmark(1, 1, 1, "Go Website", 1700000000000000), - insertMozBookmark(2, 2, 1, "GitHub", 1710000000000000), - ) -} - -func setupMozCookieDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "cookies.sqlite", []string{mozCookiesSchema}, - insertMozCookie("session", "abc123", ".example.com", "/", 1700000000000000, 1800000000, 1, 1), - insertMozCookie("token", "xyz789", ".new.com", "/api", 1710000000000000, 1810000000, 1, 0), - ) -} - -func setupMozDownloadDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozAnnosSchema}, - insertMozPlace(1, "https://example.com/old.zip", "Old File", 0, 0), - insertMozPlace(2, "https://example.com/new.pdf", "New File", 0, 0), - insertMozAnno(1, "/tmp/old.zip", 1700000000000000), - insertMozAnno(2, "/tmp/new.pdf", 1710000000000000), - ) -} - -func setupMozExtensionJSON(t *testing.T) string { - t.Helper() - return createTestJSON(t, "extensions.json", `{ - "addons": [ - { - "id": "ublock@gorhill.org", - "location": "app-profile", - "version": "1.52.0", - "active": true, - "defaultLocale": { - "name": "uBlock Origin", - "description": "An efficient blocker" - } - }, - { - "id": "system@mozilla.org", - "location": "app-system-defaults", - "version": "1.0", - "defaultLocale": {"name": "System Addon"} - }, - { - "id": "bitwarden@bitwarden.com", - "location": "app-profile", - "version": "2024.1.0", - "active": true, - "defaultLocale": { - "name": "Bitwarden", - "description": "Password manager" - } - } - ] - }`) -} - -func setupMozHistoryDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, - insertMozPlace(1, "https://github.com", "GitHub", 100, 1700000000000000), - insertMozPlace(2, "https://go.dev", "Go", 50, 1710000000000000), - insertMozPlace(3, "https://example.com", "Example", 200, 1690000000000000), - ) -} - -func setupWebappsDB(t *testing.T) string { - t.Helper() - return createTestDB(t, "webappsstore.sqlite", []string{webappsstore2Schema}, - insertWebappsstore("moc.buhtig.:https:443", "theme", "dark"), - insertWebappsstore("moc.buhtig.:https:443", "lang", "en"), - insertWebappsstore("moc.elpmaxe.:http:8080", "token", "abc123"), - ) -} diff --git a/browser/keydump.go b/browser/keydump.go deleted file mode 100644 index ee042a0..0000000 --- a/browser/keydump.go +++ /dev/null @@ -1,178 +0,0 @@ -package browser - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/types" -) - -// BuildDump exports one Vault per installation (Firefox/Safari, lacking KeyManager, are skipped). -// Partial results are kept — a Chrome 127+ profile mixes v10+v20, so a v20-only failure must not -// discard a usable v10 key. -func BuildDump(browsers []Browser) masterkey.Dump { - dump := masterkey.NewDump() - for _, b := range browsers { - km, ok := b.(KeyManager) - if !ok { - continue - } - mk, err := km.ExportKeys() - if err != nil { - status := "partial" - if len(mk) == 0 { - status = "failed" - } - log.Warnf("dump-keys: %s %s: %v", b.BrowserName(), status, err) - } - if len(mk) == 0 { - continue - } - kind, err := kindToDump(km.Kind()) - if err != nil { - log.Warnf("dump-keys: %s: %v", b.BrowserName(), err) - continue - } - dump.Vaults = append(dump.Vaults, masterkey.Vault{ - Browser: km.BrowserKey(), - Kind: kind, - UserDataDir: b.UserDataDir(), - Profiles: profileNames(b), - Keys: mk, - }) - } - return dump -} - -func profileNames(b Browser) []string { - profiles := b.Profiles() - names := make([]string, 0, len(profiles)) - for _, p := range profiles { - names = append(names, p.Name) - } - return names -} - -// BuildFromDump reconstructs Chromium engines straight from a dump's vaults, rooted at copied data -// instead of the local platform table — this is what lets an analyst host decrypt a browser its OS -// never installs. filter is a browser key ("" or "all" = every vault); a filter matching no vault is -// an error rather than silent empty output. -// -// Data layout is resolved two ways. When dataDir holds per-key subdirs (the archive layout), each -// vault is rooted at dataDir/. Otherwise dataDir is treated as one browser's User Data (a -// hand-copied folder), which is unambiguous only for a single vault — so filter must pick one. -func BuildFromDump(dump masterkey.Dump, dataDir, filter string) ([]Browser, error) { - filter = strings.ToLower(filter) - if filter == "all" { - filter = "" - } - - var selected []masterkey.Vault - for _, v := range dump.Vaults { - if filter != "" && !strings.EqualFold(v.Browser, filter) { - continue - } - selected = append(selected, v) - } - if filter != "" && len(selected) == 0 { - return nil, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultKeys(dump)) - } - - if !dirExists(dataDir) { - return nil, fmt.Errorf("data dir %q does not exist", dataDir) - } - - archiveLayout := isArchiveLayout(dataDir, selected) - if !archiveLayout && len(selected) > 1 { - return nil, fmt.Errorf("--data-dir %q has no per-browser subdir but keys has %d browsers; "+ - "point it at the archive root, or use -b for one browser's User Data (have: %s)", - dataDir, len(selected), vaultKeys(dump)) - } - - var browsers []Browser - for _, v := range selected { - root := dataDir - if archiveLayout { - root = filepath.Join(dataDir, strings.ToLower(v.Browser)) - if !dirExists(root) { - log.Warnf("restore: %s has no data under %s, skipping", v.Browser, root) - continue - } - } - kind, err := kindFromDump(v.Kind) - if err != nil { - log.Warnf("restore: %s: %v", v.Browser, err) - continue - } - cfg := types.BrowserConfig{ - Key: strings.ToLower(v.Browser), - Name: v.Browser, - Kind: kind, - UserDataDir: root, - } - b, err := newBrowser(cfg) - if err != nil { - log.Errorf("restore: build %s: %v", v.Browser, err) - continue - } - if b == nil { - log.Warnf("restore: %s found no profiles under %s", v.Browser, root) - continue - } - if km, ok := b.(KeyManager); ok { - km.SetKeys(v.Keys) - } - browsers = append(browsers, b) - } - return browsers, nil -} - -// isArchiveLayout reports whether dataDir uses the archive layout — one per-browser subdir named by -// the vault key — rather than a raw single-browser User Data copy. -func isArchiveLayout(dataDir string, vaults []masterkey.Vault) bool { - for _, v := range vaults { - if dirExists(filepath.Join(dataDir, strings.ToLower(v.Browser))) { - return true - } - } - return false -} - -func vaultKeys(dump masterkey.Dump) string { - keys := make([]string, 0, len(dump.Vaults)) - for _, v := range dump.Vaults { - keys = append(keys, strings.ToLower(v.Browser)) - } - return strings.Join(keys, ", ") -} - -func dirExists(path string) bool { - info, err := os.Stat(path) - return err == nil && info.IsDir() -} - -// dumpableKinds are the engine kinds a vault may carry; kindToDump/kindFromDump translate to and from -// the wire form via BrowserKind.String(), keeping the vocabulary single-sourced in the types enum. -var dumpableKinds = []types.BrowserKind{types.Chromium, types.ChromiumYandex, types.ChromiumOpera} - -func kindToDump(k types.BrowserKind) (string, error) { - for _, dk := range dumpableKinds { - if k == dk { - return k.String(), nil - } - } - return "", fmt.Errorf("engine kind %s is not exportable", k) -} - -func kindFromDump(s string) (types.BrowserKind, error) { - for _, k := range dumpableKinds { - if k.String() == s { - return k, nil - } - } - return 0, fmt.Errorf("unknown engine kind %q", s) -} diff --git a/browser/keydump_test.go b/browser/keydump_test.go deleted file mode 100644 index c803300..0000000 --- a/browser/keydump_test.go +++ /dev/null @@ -1,382 +0,0 @@ -package browser - -import ( - "bytes" - "errors" - "os" - "path/filepath" - "runtime" - "strings" - "testing" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/types" -) - -const ( - testProfileDefault = "Default" - testProfile1 = "Profile 1" - testUDD = "/p" - testEdgeName = "Edge" - testChromeName = "Chrome" - testFirefoxName = "Firefox" -) - -// mockBrowser is one installation holding zero or more profile names. -type mockBrowser struct { - name, userDataDir string - profiles []string -} - -func (m *mockBrowser) BrowserName() string { return m.name } -func (m *mockBrowser) UserDataDir() string { return m.userDataDir } - -func (m *mockBrowser) Profiles() []types.Profile { - out := make([]types.Profile, 0, len(m.profiles)) - for _, p := range m.profiles { - out = append(out, types.Profile{Name: p, Dir: m.userDataDir + "/" + p}) - } - return out -} - -func (m *mockBrowser) Extract(_ []category.Category) ([]types.ExtractResult, error) { - return nil, nil -} - -func (m *mockBrowser) CountEntries(_ []category.Category) ([]types.CountResult, error) { - return nil, nil -} - -type mockChromiumBrowser struct { - mockBrowser - key string - kind types.BrowserKind - keys masterkey.Set - exportErr error - calls int - receivedKeys masterkey.Set -} - -func (m *mockChromiumBrowser) SetLocator(masterkey.Locator) {} - -func (m *mockChromiumBrowser) SetKeys(keys masterkey.Set) { m.receivedKeys = keys } - -func (m *mockChromiumBrowser) ExportKeys() (masterkey.Set, error) { - m.calls++ - return m.keys, m.exportErr -} - -func (m *mockChromiumBrowser) BrowserKey() string { - if m.key != "" { - return m.key - } - return strings.ToLower(m.name) -} - -func (m *mockChromiumBrowser) Kind() types.BrowserKind { return m.kind } - -func TestBuildDump_Empty(t *testing.T) { - dump := BuildDump(nil) - if dump.Version != masterkey.DumpVersion { - t.Errorf("Version = %q, want %q", dump.Version, masterkey.DumpVersion) - } - if dump.Host.OS != runtime.GOOS { - t.Errorf("Host.OS = %q, want %q", dump.Host.OS, runtime.GOOS) - } - if len(dump.Vaults) != 0 { - t.Errorf("Vaults len = %d, want 0", len(dump.Vaults)) - } -} - -func TestBuildDump_SingleChromium(t *testing.T) { - b := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testChromeName, userDataDir: testUDD, profiles: []string{testProfileDefault}}, - keys: masterkey.Set{masterkey.V10: []byte("v10-key")}, - } - - dump := BuildDump([]Browser{b}) - - if len(dump.Vaults) != 1 { - t.Fatalf("Vaults len = %d, want 1", len(dump.Vaults)) - } - inst := dump.Vaults[0] - if !strings.EqualFold(inst.Browser, testChromeName) || inst.UserDataDir != testUDD { - t.Errorf("inst metadata = %+v", inst) - } - if inst.Kind != "chromium" { - t.Errorf("Kind = %q, want chromium", inst.Kind) - } - if len(inst.Profiles) != 1 || inst.Profiles[0] != testProfileDefault { - t.Errorf("Profiles = %v", inst.Profiles) - } - if string(inst.Keys[masterkey.V10]) != "v10-key" { - t.Errorf("Keys[masterkey.V10] = %q", inst.Keys[masterkey.V10]) - } -} - -// TestBuildDump_MultipleProfilesOneVault verifies that one installation holding -// multiple profiles produces a single vault with all profile names, deriving the -// key exactly once. -func TestBuildDump_MultipleProfilesOneVault(t *testing.T) { - b := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testChromeName, userDataDir: testUDD, profiles: []string{testProfileDefault, testProfile1}}, - keys: masterkey.Set{masterkey.V10: []byte("v10")}, - } - - dump := BuildDump([]Browser{b}) - - if len(dump.Vaults) != 1 { - t.Fatalf("Vaults len = %d, want 1 (one installation = one vault)", len(dump.Vaults)) - } - if len(dump.Vaults[0].Profiles) != 2 { - t.Errorf("Profiles = %v, want both profiles", dump.Vaults[0].Profiles) - } - if b.calls != 1 { - t.Errorf("ExportKeys calls = %d, want 1 (one call per installation)", b.calls) - } -} - -func TestBuildDump_SkipsNonKeyManager(t *testing.T) { - chrome := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testChromeName, userDataDir: "/chrome", profiles: []string{testProfileDefault}}, - keys: masterkey.Set{masterkey.V10: []byte("v10")}, - } - firefox := &mockBrowser{name: testFirefoxName, userDataDir: "/ff", profiles: []string{"default-release"}} - - dump := BuildDump([]Browser{chrome, firefox}) - - if len(dump.Vaults) != 1 { - t.Fatalf("Vaults len = %d, want 1 (firefox skipped)", len(dump.Vaults)) - } - if !strings.EqualFold(dump.Vaults[0].Browser, testChromeName) { - t.Errorf("Browser = %q, want %q", dump.Vaults[0].Browser, strings.ToLower(testChromeName)) - } -} - -func TestBuildDump_SkipsExportError(t *testing.T) { - good := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testChromeName, userDataDir: "/chrome", profiles: []string{testProfileDefault}}, - keys: masterkey.Set{masterkey.V10: []byte("v10")}, - } - failing := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testEdgeName, userDataDir: "/edge", profiles: []string{testProfileDefault}}, - exportErr: errors.New("retriever failed"), - } - - dump := BuildDump([]Browser{good, failing}) - - if len(dump.Vaults) != 1 { - t.Fatalf("Vaults len = %d, want 1 (failing browser skipped)", len(dump.Vaults)) - } - if !strings.EqualFold(dump.Vaults[0].Browser, testChromeName) { - t.Errorf("Browser = %q, want %q", dump.Vaults[0].Browser, strings.ToLower(testChromeName)) - } -} - -func TestBuildDump_JSONRoundTrip(t *testing.T) { - b := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testChromeName, userDataDir: testUDD, profiles: []string{testProfileDefault}}, - keys: masterkey.Set{masterkey.V10: []byte{0x01, 0x02, 0x03}, masterkey.V20: []byte{0xff, 0xee}}, - } - - dump := BuildDump([]Browser{b}) - - var buf bytes.Buffer - if err := dump.WriteJSON(&buf); err != nil { - t.Fatalf("WriteJSON: %v", err) - } - - parsed, err := masterkey.ReadJSON(&buf) - if err != nil { - t.Fatalf("ReadJSON: %v", err) - } - - if parsed.Version != dump.Version { - t.Errorf("Version round-trip: got %q, want %q", parsed.Version, dump.Version) - } - if len(parsed.Vaults) != 1 { - t.Fatalf("Vaults len = %d", len(parsed.Vaults)) - } - if parsed.Vaults[0].Kind != "chromium" { - t.Errorf("Kind round-trip: got %q, want chromium", parsed.Vaults[0].Kind) - } - if !bytes.Equal(parsed.Vaults[0].Keys[masterkey.V10], dump.Vaults[0].Keys[masterkey.V10]) { - t.Errorf("V10 round-trip mismatch") - } - if !bytes.Equal(parsed.Vaults[0].Keys[masterkey.V20], dump.Vaults[0].Keys[masterkey.V20]) { - t.Errorf("V20 round-trip mismatch") - } - if parsed.Vaults[0].Keys[masterkey.V11] != nil { - t.Errorf("V11 should be omitted (nil), got %v", parsed.Vaults[0].Keys[masterkey.V11]) - } -} - -func TestBuildDump_PartialKeys(t *testing.T) { - b := &mockChromiumBrowser{ - mockBrowser: mockBrowser{name: testChromeName, userDataDir: testUDD, profiles: []string{testProfileDefault}}, - keys: masterkey.Set{masterkey.V10: []byte("v10")}, - exportErr: errors.New("v20: ABE failed"), - } - - dump := BuildDump([]Browser{b}) - - if len(dump.Vaults) != 1 { - t.Fatalf("Vaults len = %d, want 1 (partial result must be preserved)", len(dump.Vaults)) - } - if string(dump.Vaults[0].Keys[masterkey.V10]) != "v10" { - t.Errorf("V10 should be preserved despite V20 error, got %q", dump.Vaults[0].Keys[masterkey.V10]) - } - if dump.Vaults[0].Keys[masterkey.V20] != nil { - t.Errorf("V20 should remain nil, got %v", dump.Vaults[0].Keys[masterkey.V20]) - } -} - -func TestKindDumpRoundTrip(t *testing.T) { - for _, k := range []types.BrowserKind{types.Chromium, types.ChromiumYandex, types.ChromiumOpera} { - s, err := kindToDump(k) - if err != nil { - t.Fatalf("kindToDump(%d): %v", k, err) - } - got, err := kindFromDump(s) - if err != nil || got != k { - t.Errorf("round trip %d -> %q -> %d (err %v)", k, s, got, err) - } - } - if _, err := kindToDump(types.Firefox); err == nil { - t.Error("kindToDump(Firefox) should error") - } - if _, err := kindFromDump("nope"); err == nil { - t.Error("kindFromDump(nope) should error") - } -} - -// makeUserData writes a minimal Chromium profile tree: a Preferences marker plus History (a real -// extraction source, so the profile resolves) under each named profile dir. -func makeUserData(t *testing.T, root string, profiles ...string) { - t.Helper() - for _, p := range profiles { - dir := filepath.Join(root, p) - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } - for _, f := range []string{"Preferences", "History"} { - if err := os.WriteFile(filepath.Join(dir, f), []byte("x"), 0o600); err != nil { - t.Fatal(err) - } - } - } -} - -func TestBuildFromDump_ConventionMultiBrowser(t *testing.T) { - dataDir := t.TempDir() - makeUserData(t, filepath.Join(dataDir, "chrome"), testProfileDefault) - makeUserData(t, filepath.Join(dataDir, "edge"), testProfileDefault) - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, - {Browser: "edge", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("e")}}, - }} - - browsers, err := BuildFromDump(dump, dataDir, "") - if err != nil { - t.Fatalf("BuildFromDump: %v", err) - } - if len(browsers) != 2 { - t.Fatalf("got %d browsers, want 2", len(browsers)) - } -} - -// TestBuildFromDump_ForeignKindNoPlatformTable proves restore never consults platformBrowsers(): -// sogou is Windows-only yet reconstructs from its vault on any OS. -func TestBuildFromDump_ForeignKindNoPlatformTable(t *testing.T) { - dataDir := t.TempDir() - makeUserData(t, filepath.Join(dataDir, "sogou"), testProfileDefault) - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "sogou", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("k")}}, - }} - - browsers, err := BuildFromDump(dump, dataDir, "") - if err != nil { - t.Fatalf("BuildFromDump: %v", err) - } - if len(browsers) != 1 { - t.Fatalf("got %d browsers, want 1", len(browsers)) - } - if browsers[0].BrowserName() != "sogou" { - t.Errorf("BrowserName = %q, want sogou", browsers[0].BrowserName()) - } -} - -func TestBuildFromDump_RawSingleBrowser(t *testing.T) { - dataDir := t.TempDir() - makeUserData(t, dataDir, testProfileDefault) - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, - }} - - browsers, err := BuildFromDump(dump, dataDir, "chrome") - if err != nil { - t.Fatalf("BuildFromDump: %v", err) - } - if len(browsers) != 1 { - t.Fatalf("got %d browsers, want 1", len(browsers)) - } - if browsers[0].UserDataDir() != dataDir { - t.Errorf("UserDataDir = %q, want %q (raw root)", browsers[0].UserDataDir(), dataDir) - } -} - -func TestBuildFromDump_UnknownBrowserErrors(t *testing.T) { - dataDir := t.TempDir() - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, - }} - if _, err := BuildFromDump(dump, dataDir, "sogou"); err == nil { - t.Fatal("expected error for -b matching no vault") - } -} - -func TestBuildFromDump_RawAmbiguousErrors(t *testing.T) { - dataDir := t.TempDir() - makeUserData(t, dataDir, testProfileDefault) - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, - {Browser: "edge", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("e")}}, - }} - if _, err := BuildFromDump(dump, dataDir, ""); err == nil { - t.Fatal("expected ambiguity error for raw multi-vault restore without -b") - } -} - -func TestBuildFromDump_MissingDataDirErrors(t *testing.T) { - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, - }} - if _, err := BuildFromDump(dump, "/no/such/dir", ""); err == nil { - t.Fatal("expected error when data dir does not exist") - } -} - -// TestBuildFromDump_MarkerlessTreeStillResolves covers an archive/copy that omitted Preferences: -// the source-bearing-subdir fallback in discoverProfiles must still find the profile. -func TestBuildFromDump_MarkerlessTreeStillResolves(t *testing.T) { - dataDir := t.TempDir() - dir := filepath.Join(dataDir, "chrome", testProfileDefault) - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "History"), []byte("x"), 0o600); err != nil { - t.Fatal(err) - } - dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, - }} - - browsers, err := BuildFromDump(dump, dataDir, "") - if err != nil { - t.Fatalf("BuildFromDump: %v", err) - } - if len(browsers) != 1 { - t.Fatalf("got %d browsers, want 1 (marker-less profile must resolve via source fallback)", len(browsers)) - } -} diff --git a/browser/safari/count.go b/browser/safari/count.go deleted file mode 100644 index e3f68fc..0000000 --- a/browser/safari/count.go +++ /dev/null @@ -1,106 +0,0 @@ -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 deleted file mode 100644 index 25fb118..0000000 --- a/browser/safari/count_test.go +++ /dev/null @@ -1,84 +0,0 @@ -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/keychain.go b/browser/safari/keychain.go deleted file mode 100644 index 8821661..0000000 --- a/browser/safari/keychain.go +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 1709f4c..0000000 --- a/browser/safari/profile.go +++ /dev/null @@ -1,226 +0,0 @@ -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 { - ctx profileContext - browserName string - sourcePaths map[category.Category]resolvedPath -} - -func (p *profile) name() string { return p.ctx.name } -func (p *profile) label() string { return p.browserName + "/" + p.name() } - -func (p *profile) dir() string { - if p.ctx.isDefault() { - return p.ctx.legacyHome - } - return filepath.Join(p.ctx.container, "Safari", "Profiles", p.ctx.uuidUpper) -} - -// 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} - } - 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 { - ex, ok := extractors[cat] - if !ok { - continue - } - 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 counts - } - defer session.Cleanup() - 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 { - rp, ok := p.sourcePaths[cat] - if !ok { - continue - } - dst := filepath.Join(session.TempDir(), cat.String()) - if err := session.Acquire(rp.absPath, dst, rp.isDir); err != nil { - log.Debugf("acquire %s: %v", cat, err) - continue - } - tempPaths[cat] = dst - } - return tempPaths -} - -func (p *profile) countCategory(cat category.Category, file string) int { - var count int - var err error - switch cat { - case category.History: - count, err = countHistories(file) - case category.LocalStorage: - count, err = countLocalStorage(file) - default: - // The other categories are counted from their extracted records. - } - if err != nil { - log.Debugf("count %s for %s: %v", cat, p.label(), err) - } - return count -} diff --git a/browser/safari/profile_test.go b/browser/safari/profile_test.go deleted file mode 100644 index e89eca7..0000000 --- a/browser/safari/profile_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package safari - -import ( - "os" - "path/filepath" - "testing" - - "github.com/moond4rk/plist" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" -) - -const fixtureWorkUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - -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 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)) -} - -// 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") - - 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"}, - }}, - }}, - }) - 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 -} - -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 -} - -// 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} - -func TestExtract_RunsTheBaseOnEachProfile(t *testing.T) { - results, err := fixtureBrowser(t).Extract(adapterCategories) - require.NoError(t, err) - require.Len(t, results, 2) - - 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) -} - -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 deleted file mode 100644 index f3cf4d7..0000000 --- a/browser/safari/profiles.go +++ /dev/null @@ -1,168 +0,0 @@ -package safari - -import ( - "database/sql" - "fmt" - "os" - "path/filepath" - "regexp" - "strings" - - _ "modernc.org/sqlite" - - "github.com/moond4rk/hackbrowserdata/internal/log" -) - -// profileContext tracks the uppercase (Safari/Profiles/) and lowercase -// (WebKit/WebsiteDataStore/) UUID forms a named profile needs. Both empty ⇒ default profile. -type profileContext struct { - name string - uuidUpper string - uuidLower string - legacyHome string // ~/Library/Safari - container string // ~/Library/Containers/com.apple.Safari/Data/Library -} - -func (p profileContext) isDefault() bool { 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 ( - safariTabsDBRelPath = "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}$`) - -// discoverSafariProfiles always lists the default first, then named profiles from SafariTabs.db -// (authoritative) with a ReadDir fallback only if the DB itself is unreadable. -func discoverSafariProfiles(legacyHome string) []profileContext { - container := deriveContainerRoot(legacyHome) - - profiles := []profileContext{{ - name: "default", - legacyHome: legacyHome, - container: container, - }} - - named, err := readNamedProfilesFromDB(container) - if err != nil { - // Empty DB (nil, nil) is authoritative; fall back only when DB itself is unreadable. - named = readNamedProfilesFromDir(container) - } - for _, p := range named { - p.legacyHome = legacyHome - p.container = container - profiles = append(profiles, p) - } - - disambiguateNames(profiles) - return profiles -} - -func deriveContainerRoot(legacyHome string) string { - return filepath.Join(filepath.Dir(legacyHome), "Containers", "com.apple.Safari", "Data", "Library") -} - -// readNamedProfilesFromDB returns (nil, err) when the DB is missing/unreadable so the caller can -// try the ReadDir fallback; (slice, nil) — possibly empty — is authoritative. -func readNamedProfilesFromDB(container string) ([]profileContext, error) { - // Read-only + immutable so we don't disturb Safari's live WAL. - dsn := "file:" + filepath.Join(container, safariTabsDBRelPath) + "?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 []profileContext - 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(container string) []profileContext { - entries, err := os.ReadDir(filepath.Join(container, "Safari", "Profiles")) - if err != nil { - return nil - } - - var out []profileContext - for _, e := range entries { - if !e.IsDir() || !isCanonicalUUID(e.Name()) { - continue - } - out = append(out, newNamedProfile(e.Name(), "")) - } - return out -} - -func newNamedProfile(upperUUID, title string) profileContext { - return profileContext{ - name: resolveProfileName(title, upperUUID), - uuidUpper: upperUUID, - uuidLower: strings.ToLower(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 []profileContext) { - 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/browser/safari/safari.go b/browser/safari/safari.go deleted file mode 100644 index 3eb6a5a..0000000 --- a/browser/safari/safari.go +++ /dev/null @@ -1,105 +0,0 @@ -package safari - -import ( - "os" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" -) - -// Browser is one Safari installation, holding the default profile and any named -// profiles. Passwords come from the shared macOS Keychain; the login password is -// set on the installation and threaded to each profile at extract time. -type Browser struct { - cfg types.BrowserConfig - keychainPassword string - profiles []*profile -} - -// SetKeychainPassword sets the macOS login password used to unlock the Keychain. -func (b *Browser) SetKeychainPassword(password string) { b.keychainPassword = password } - -// NewBrowser returns the Safari installation with one profile per Safari profile -// that has resolvable data, or nil if none. Named profiles are enumerated from -// SafariTabs.db. -func NewBrowser(cfg types.BrowserConfig) (*Browser, error) { - var profiles []*profile - for _, p := range discoverSafariProfiles(cfg.UserDataDir) { - paths := resolveProfilePaths(p) - if len(paths) == 0 { - continue - } - profiles = append(profiles, &profile{ - ctx: p, - browserName: cfg.Name, - sourcePaths: paths, - }) - } - if len(profiles) == 0 { - return nil, nil - } - return &Browser{cfg: cfg, profiles: profiles}, nil -} - -func (b *Browser) BrowserName() string { return b.cfg.Name } -func (b *Browser) UserDataDir() string { return b.cfg.UserDataDir } - -// Profiles returns the identity of every Safari profile in this installation. -func (b *Browser) Profiles() []types.Profile { - out := make([]types.Profile, 0, len(b.profiles)) - for _, p := range b.profiles { - out = append(out, types.Profile{Name: p.ctx.name, Dir: p.dir()}) - } - return out -} - -// Extract extracts every profile, threading the installation's keychain password. -func (b *Browser) Extract(categories []category.Category) ([]types.ExtractResult, error) { - results := make([]types.ExtractResult, 0, len(b.profiles)) - for _, p := range b.profiles { - results = append(results, types.ExtractResult{ - Profile: types.Profile{Name: p.ctx.name, Dir: p.dir()}, - Data: p.extract(categories, b.keychainPassword), - }) - } - return results, nil -} - -// CountEntries counts entries per category for every profile. -func (b *Browser) CountEntries(categories []category.Category) ([]types.CountResult, error) { - results := make([]types.CountResult, 0, len(b.profiles)) - for _, p := range b.profiles { - results = append(results, types.CountResult{ - Profile: types.Profile{Name: p.ctx.name, Dir: p.dir()}, - Counts: p.count(categories, b.keychainPassword), - }) - } - return results, nil -} - -func resolveProfilePaths(p profileContext) map[category.Category]resolvedPath { - return resolveSourcePaths(buildSources(p)) -} - -type resolvedPath struct { - absPath string - isDir bool -} - -// resolveSourcePaths returns only paths that exist; first matching candidate wins per category. -func resolveSourcePaths(sources map[category.Category][]sourcePath) map[category.Category]resolvedPath { - resolved := make(map[category.Category]resolvedPath) - for cat, candidates := range sources { - for _, sp := range candidates { - info, err := os.Stat(sp.abs) - if err != nil { - continue - } - if sp.isDir == info.IsDir() { - resolved[cat] = resolvedPath{sp.abs, sp.isDir} - break - } - } - } - return resolved -} diff --git a/browser/safari/safari_test.go b/browser/safari/safari_test.go deleted file mode 100644 index 7945367..0000000 --- a/browser/safari/safari_test.go +++ /dev/null @@ -1,189 +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" - "github.com/moond4rk/hackbrowserdata/types" -) - -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)) -} - -// --------------------------------------------------------------------------- -// NewBrowsers — backward-compat (single flat profile) -// --------------------------------------------------------------------------- - -func TestNewBrowsers(t *testing.T) { - tests := []struct { - name string - setup func(t *testing.T) string - wantLen int - }{ - { - name: "dir with History.db", - setup: func(t *testing.T) string { - dir := t.TempDir() - mkFile(t, dir, "History.db") - return dir - }, - wantLen: 1, - }, - { - name: "empty dir", - setup: func(t *testing.T) string { - return t.TempDir() - }, - wantLen: 0, - }, - { - name: "nonexistent dir", - setup: func(t *testing.T) string { - return "/nonexistent/path" - }, - wantLen: 0, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - dir := tt.setup(t) - cfg := types.BrowserConfig{Name: "Safari", Kind: types.Safari, UserDataDir: dir} - b, err := NewBrowser(cfg) - require.NoError(t, err) - - if tt.wantLen == 0 { - assert.Nil(t, b) - return - } - require.NotNil(t, b) - assert.Equal(t, "Safari", b.BrowserName()) - require.Len(t, b.Profiles(), 1) - assert.Equal(t, "default", b.Profiles()[0].Name) - assert.Equal(t, dir, b.Profiles()[0].Dir) - }) - } -} - -// --------------------------------------------------------------------------- -// NewBrowser — multi-profile (macOS 14+ named profiles) -// --------------------------------------------------------------------------- - -func TestNewBrowsers_MultiProfile(t *testing.T) { - const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - uuidLower := strings.ToLower(uuid) - - // Build a pretend ~/Library that mirrors a macOS 14+ layout. - library := t.TempDir() - legacyHome := filepath.Join(library, "Safari") - container := filepath.Join(library, "Containers", "com.apple.Safari", "Data", "Library") - - // Default profile data in legacyHome. - mkFile(t, legacyHome, "History.db") - mkFile(t, legacyHome, "Bookmarks.plist") - - // Named profile data under the container. - mkFile(t, container, "Safari", "Profiles", uuid, "History.db") - - // Named profile's Origins directory (Safari 17+ nested localStorage root) — must exist - // for resolveSourcePaths to register it. - namedOriginsDir := filepath.Join(container, "WebKit", "WebsiteDataStore", uuidLower, "Origins") - require.NoError(t, os.MkdirAll(namedOriginsDir, 0o755)) - - // SafariTabs.db registering the named profile with a human-readable title. - writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{ - {uuid: "DefaultProfile", title: ""}, - {uuid: uuid, title: "work"}, - }) - - cfg := types.BrowserConfig{Name: "Safari", Kind: types.Safari, UserDataDir: legacyHome} - b, err := NewBrowser(cfg) - require.NoError(t, err) - require.NotNil(t, b) - require.Len(t, b.profiles, 2) - - names := []string{b.profiles[0].ctx.name, b.profiles[1].ctx.name} - assert.Contains(t, names, "default") - assert.Contains(t, names, "work") - - for _, p := range b.profiles { - switch p.ctx.name { - case "default": - assert.Equal(t, legacyHome, p.dir()) - assert.Contains(t, p.sourcePaths, category.History) - assert.Equal(t, filepath.Join(legacyHome, "History.db"), p.sourcePaths[category.History].absPath) - // Default profile's LocalStorage root (WebsiteData/Default) isn't created in this fixture, - // so it won't resolve — which is the point: resolveSourcePaths only registers paths that exist. - assert.NotContains(t, p.sourcePaths, category.LocalStorage) - case "work": - assert.Equal(t, filepath.Join(container, "Safari", "Profiles", uuid), p.dir()) - assert.Contains(t, p.sourcePaths, category.History) - assert.Equal(t, - filepath.Join(container, "Safari", "Profiles", uuid, "History.db"), - p.sourcePaths[category.History].absPath) - require.Contains(t, p.sourcePaths, category.LocalStorage) - assert.Equal(t, namedOriginsDir, p.sourcePaths[category.LocalStorage].absPath) - assert.True(t, p.sourcePaths[category.LocalStorage].isDir) - } - } -} - -// --------------------------------------------------------------------------- -// resolveSourcePaths -// --------------------------------------------------------------------------- - -func TestResolveSourcePaths(t *testing.T) { - dir := t.TempDir() - mkFile(t, dir, "History.db") - - sources := buildSources(profileContext{legacyHome: dir, container: deriveContainerRoot(dir)}) - resolved := resolveSourcePaths(sources) - assert.Contains(t, resolved, category.History) - assert.Equal(t, filepath.Join(dir, "History.db"), resolved[category.History].absPath) - assert.False(t, resolved[category.History].isDir) -} - -func TestResolveSourcePaths_Empty(t *testing.T) { - dir := t.TempDir() - sources := buildSources(profileContext{legacyHome: dir, container: deriveContainerRoot(dir)}) - assert.Empty(t, resolveSourcePaths(sources)) -} - -// --------------------------------------------------------------------------- -// CountEntries -// --------------------------------------------------------------------------- - -func TestCountEntries(t *testing.T) { - dir := t.TempDir() - dbPath := createTestDB(t, "History.db", - []string{safariHistoryItemsSchema, safariHistoryVisitsSchema}, - insertHistoryItem(1, "https://example.com", "example.com", 5), - insertHistoryItem(2, "https://go.dev", "go.dev", 10), - insertHistoryVisit(1, 1, 700000000.0, "Example"), - insertHistoryVisit(2, 2, 700000000.0, "Go"), - ) - data, err := os.ReadFile(dbPath) - require.NoError(t, err) - require.NoError(t, os.WriteFile(filepath.Join(dir, "History.db"), data, 0o644)) - - b, err := NewBrowser(types.BrowserConfig{ - Name: "Safari", Kind: types.Safari, UserDataDir: dir, - }) - require.NoError(t, err) - require.NotNil(t, b) - - results, err := b.CountEntries([]category.Category{category.History}) - require.NoError(t, err) - require.Len(t, results, 1) - assert.Equal(t, 2, results[0].Counts[category.History]) -} diff --git a/browser/safari/source.go b/browser/safari/source.go deleted file mode 100644 index 149e6b6..0000000 --- a/browser/safari/source.go +++ /dev/null @@ -1,65 +0,0 @@ -package safari - -import ( - "path/filepath" - - "github.com/moond4rk/hackbrowserdata/internal/category" -) - -type sourcePath struct { - abs string - isDir bool -} - -func file(abs string) sourcePath { return sourcePath{abs: abs} } -func dir(abs string) sourcePath { return sourcePath{abs: abs, isDir: true} } - -// buildSources dispatches between the default and named-profile path layouts. -// -// macOS 14+ layout: -// - History, Cookie: per-profile (separate files per profile UUID) -// - Download: shared plist, filtered by DownloadEntryProfileUUIDStringKey at extract time -// - Bookmark: shared plist, attributed to default only (no per-entry UUID available) -// - Password: macOS Keychain (shared, not listed) -func buildSources(p profileContext) map[category.Category][]sourcePath { - if p.isDefault() { - return defaultSources(p) - } - return namedSources(p) -} - -// defaultSources: cookies try macOS 14+ container first, then the ≤13 legacy path. -// LocalStorage for the default profile lives under WebsiteData/Default — the pre-profile-era -// WebKit store that stays readable even after profiles are introduced. -func defaultSources(p profileContext) map[category.Category][]sourcePath { - home := p.legacyHome - containerCookies := filepath.Join(p.container, "Cookies", "Cookies.binarycookies") - legacyCookies := filepath.Join(filepath.Dir(home), "Cookies", "Cookies.binarycookies") - defaultLocalStorage := filepath.Join(p.container, "WebKit", "WebsiteData", "Default") - - return map[category.Category][]sourcePath{ - category.History: {file(filepath.Join(home, "History.db"))}, - category.Cookie: {file(containerCookies), file(legacyCookies)}, - category.Bookmark: {file(filepath.Join(home, "Bookmarks.plist"))}, - category.Download: {file(filepath.Join(home, "Downloads.plist"))}, - category.LocalStorage: {dir(defaultLocalStorage)}, - } -} - -// namedSources omits Bookmark (shared plist with no per-entry profile tag, so attributed to default). -// Download is included because Downloads.plist carries DownloadEntryProfileUUIDStringKey per entry; -// extractDownloads filters by owner UUID so default and named profiles each see their own downloads. -// LocalStorage lives under WebKit/WebsiteDataStore//Origins — Safari 17+ uses a nested -// //LocalStorage/localstorage.sqlite3 layout; the flat -// WebsiteDataStore//LocalStorage directory from older builds is empty on modern Safari. -func namedSources(p profileContext) map[category.Category][]sourcePath { - profileDir := filepath.Join(p.container, "Safari", "Profiles", p.uuidUpper) - webkitStore := filepath.Join(p.container, "WebKit", "WebsiteDataStore", p.uuidLower) - - return map[category.Category][]sourcePath{ - category.History: {file(filepath.Join(profileDir, "History.db"))}, - category.Cookie: {file(filepath.Join(webkitStore, "Cookies", "Cookies.binarycookies"))}, - category.Download: {file(filepath.Join(p.legacyHome, "Downloads.plist"))}, - category.LocalStorage: {dir(filepath.Join(webkitStore, "Origins"))}, - } -} diff --git a/browser/safari/testutil_test.go b/browser/safari/testutil_test.go deleted file mode 100644 index 98614cd..0000000 --- a/browser/safari/testutil_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package safari - -import ( - "database/sql" - "encoding/binary" - "fmt" - "os" - "path/filepath" - "testing" - "unicode/utf16" - - "github.com/stretchr/testify/require" - _ "modernc.org/sqlite" -) - -// --------------------------------------------------------------------------- -// 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), []byte(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()) -} - -// 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 -} diff --git a/cmd/hack-browser-data/archive_golden_test.go b/cmd/hack-browser-data/archive_golden_test.go index b138d27..869b501 100644 --- a/cmd/hack-browser-data/archive_golden_test.go +++ b/cmd/hack-browser-data/archive_golden_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/internal/app" - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/browser" ) const archiveLayoutKey = "chrome" @@ -76,7 +76,7 @@ func archiveLayoutEntryNames(t *testing.T, zipPath string) []string { func TestArchiveGolden(t *testing.T) { home := t.TempDir() - def, ok := ibrowser.Lookup(archiveLayoutKey) + def, ok := browser.Lookup(archiveLayoutKey) require.True(t, ok) archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))) @@ -123,7 +123,7 @@ func TestArchiveRestoreRoundTrip(t *testing.T) { home := t.TempDir() setHome(t, home) for _, inst := range chromiumFixtureInstalls { - def, ok := ibrowser.Lookup(inst.key) + def, ok := browser.Lookup(inst.key) require.True(t, ok, inst.key) chromiumFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.key) } diff --git a/cmd/hack-browser-data/export_golden_test.go b/cmd/hack-browser-data/export_golden_test.go index 952f96e..6e9e570 100644 --- a/cmd/hack-browser-data/export_golden_test.go +++ b/cmd/hack-browser-data/export_golden_test.go @@ -17,7 +17,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -29,7 +28,19 @@ const ( type exportStamp struct { browser string profile string - data *types.BrowserData + data *exportData +} + +type exportData struct { + Passwords []record.Login + Cookies []record.Cookie + Histories []record.History + Downloads []record.Download + Bookmarks []record.Bookmark + CreditCards []record.CreditCard + Extensions []record.Extension + LocalStorage []record.LocalStorage + SessionStorage []record.SessionStorage } type exportURLForm struct { @@ -106,7 +117,7 @@ func exportWrite(t *testing.T, dir, format string, compress bool, stamps []expor w, err := export.NewWriter(dir, f, compress) require.NoError(t, err) for _, s := range stamps { - require.NoError(t, writeResult(w, s.browser, types.ExtractResult{Profile: types.Profile{Name: s.profile}, Data: s.data})) + require.NoError(t, writeStamp(w, s)) } require.NoError(t, w.Close()) } @@ -194,7 +205,7 @@ func exportAssertURLForm(t *testing.T, dir string, form exportURLForm) { // Entries are listed in extractor sort order with unique sort keys, so re-sorting a profile cannot change a golden. func exportStamps() []exportStamp { return []exportStamp{ - {browser: "Chrome", profile: "Default", data: &types.BrowserData{ + {browser: "Chrome", profile: "Default", data: &exportData{ Passwords: []record.Login{ { URL: "https://accounts.example.com/signin?continue=/mail&hl=ja", Username: "alice@example.com", @@ -261,7 +272,7 @@ func exportStamps() []exportStamp { {URL: "https://app.example.com", Key: "tab-id", Value: "42"}, }, }}, - {browser: "Chrome", profile: "Profile 1", data: &types.BrowserData{ + {browser: "Chrome", profile: "Profile 1", data: &exportData{ Passwords: []record.Login{ { URL: "http://192.168.0.1:8080/admin", Username: "admin", Password: " leading space", @@ -313,7 +324,7 @@ func exportStamps() []exportStamp { {URL: "https://example.org/?x=1&y=<2>", Key: "draft", Value: `He said "hi", then left \`}, }, }}, - {browser: "Microsoft Edge", profile: "Default", data: &types.BrowserData{ + {browser: "Microsoft Edge", profile: "Default", data: &exportData{ Passwords: []record.Login{ { URL: "https://login.example.org//authorize?client=a&scope=b", Username: `CORP\jdoe`, Password: "日本語パスワード", @@ -368,27 +379,26 @@ func exportStamps() []exportStamp { func exportSparseStamps() []exportStamp { return []exportStamp{ - {browser: "Chrome", profile: "Default", data: &types.BrowserData{ + {browser: "Chrome", profile: "Default", data: &exportData{ Passwords: []record.Login{{URL: "https://example.com/", Username: "alice", Store: record.StoreLocal}}, Cookies: []record.Cookie{}, }}, {browser: "Chrome", profile: "Profile 1"}, - {browser: "Microsoft Edge", profile: "Default", data: &types.BrowserData{ + {browser: "Microsoft Edge", profile: "Default", data: &exportData{ Histories: []record.History{}, LocalStorage: []record.LocalStorage{{URL: "https://example.com", Key: "k", Value: "v"}}, }}, } } -// writeResult writes the export fixtures, which are kept in today's BrowserData until the goldens move into export. -func writeResult(w *export.Writer, browserName string, r types.ExtractResult) error { - if r.Data == nil { +func writeStamp(w *export.Writer, s exportStamp) error { + if s.data == nil { return nil } for _, c := range category.All() { - records := profileRecords(r.Data, c) + records := profileRecords(s.data, c) for _, rec := range records { - record.Stamp(rec, browserName, r.Name) + record.Stamp(rec, s.browser, s.profile) } if err := w.Write(c, records); err != nil { return err @@ -397,7 +407,7 @@ func writeResult(w *export.Writer, browserName string, r types.ExtractResult) er return nil } -func profileRecords(d *types.BrowserData, c category.Category) []record.Record { +func profileRecords(d *exportData, c category.Category) []record.Record { switch c { case category.Password: return recordsOf(d.Passwords) diff --git a/cmd/hack-browser-data/extract_golden_test.go b/cmd/hack-browser-data/extract_golden_test.go index 347cdbc..6729bca 100644 --- a/cmd/hack-browser-data/extract_golden_test.go +++ b/cmd/hack-browser-data/extract_golden_test.go @@ -9,20 +9,20 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/internal/app" - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // The extract goldens pin dump's output on fixtures; the fixtures' keys are handed in, since no secret store holds them. func TestExtractGolden(t *testing.T) { home := t.TempDir() - keys := make(map[ibrowser.DirID]masterkey.Set) + keys := make(map[browser.DirID]masterkey.Set) for _, inst := range chromiumFixtureInstalls { - def, ok := ibrowser.Lookup(inst.key) + def, ok := browser.Lookup(inst.key) require.True(t, ok, inst.key) require.Equal(t, inst.name, def.Name, "records are stamped with the table's display name") chromiumFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.key) - keys[ibrowser.DirID(inst.key)] = chromiumFixtureKeys + keys[browser.DirID(inst.key)] = chromiumFixtureKeys } assertExtractGoldens(t, "extract", func(t *testing.T, format string) string { @@ -32,7 +32,7 @@ func TestExtractGolden(t *testing.T) { func TestExtractGoldenFirefox(t *testing.T) { home := t.TempDir() - def, ok := ibrowser.Lookup("firefox") + def, ok := browser.Lookup("firefox") require.True(t, ok) firefoxFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))) @@ -53,7 +53,7 @@ func TestExtractGoldenSafari(t *testing.T) { }) } -func extractGoldenRun(t *testing.T, home string, keys map[ibrowser.DirID]masterkey.Set, format string) string { +func extractGoldenRun(t *testing.T, home string, keys map[browser.DirID]masterkey.Set, format string) string { t.Helper() out := t.TempDir() req, err := app.Validate(app.Flags{Browser: "all", Categories: "all", Format: format, Dir: out}) diff --git a/cmd/hack-browser-data/list_test.go b/cmd/hack-browser-data/list_test.go index e3119e7..f2884df 100644 --- a/cmd/hack-browser-data/list_test.go +++ b/cmd/hack-browser-data/list_test.go @@ -2,129 +2,61 @@ package main import ( "bytes" - "fmt" "path/filepath" "runtime" + "strings" "testing" - "text/tabwriter" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/browser" - "github.com/moond4rk/hackbrowserdata/browser/chromium" - "github.com/moond4rk/hackbrowserdata/browser/firefox" - "github.com/moond4rk/hackbrowserdata/browser/safari" - ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/browser" ) -// list prints what today's code printed on the same machine, its counts included; the comparison goes with the old -// packages. -func TestListMatchesToday(t *testing.T) { +func TestListGolden(t *testing.T) { home := t.TempDir() setHome(t, home) + var paths []string for _, inst := range chromiumFixtureInstalls { - chromiumFixtureUserData(t, userDataDirOf(t, home, inst.key), inst.key) + dir := userDataDirOf(t, home, inst.key) + chromiumFixtureUserData(t, dir, inst.key) + paths = append(paths, dir, "<"+inst.key+">") } - firefoxFixtureUserData(t, userDataDirOf(t, home, "firefox")) - if runtime.GOOS == "darwin" { - safariFixtureLibrary(t, filepath.Join(home, "Library")) - } - today := todayBrowsers(t, home) - require.NotEmpty(t, today) + dir := userDataDirOf(t, home, "firefox") + firefoxFixtureUserData(t, dir) + paths = append(paths, dir, "", `\`, "/") + assertListGoldens(t, "list", strings.NewReplacer(paths...)) +} +func TestListGoldenSafari(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("Safari is in the browser table on macOS only") + } + home := t.TempDir() + setHome(t, home) + library := filepath.Join(home, "Library") + safariFixtureLibrary(t, library) + assertListGoldens(t, "list-safari", strings.NewReplacer(library, "")) +} + +// The goldens hold the fixture's paths as placeholders, so one golden serves every OS. +func assertListGoldens(t *testing.T, prefix string, paths *strings.Replacer) { + t.Helper() for _, detail := range []bool{false, true} { var out bytes.Buffer cmd := listCmd() cmd.SetOut(&out) - args := []string{} + name, args := prefix+".golden", []string{} if detail { - args = append(args, "--detail") + name, args = prefix+"-detail.golden", []string{"--detail"} } runCmd(t, cmd, args...) - assert.Equalf(t, todayList(t, today, detail), out.String(), "--detail=%v", detail) + assertGolden(t, name, paths.Replace(out.String())) } } func userDataDirOf(t *testing.T, home, id string) string { t.Helper() - def, ok := ibrowser.Lookup(id) + def, ok := browser.Lookup(id) require.True(t, ok, id) return filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])) } - -// todayBrowsers finds the fixture's browsers as today's discovery did: each table row's directory under home, kept -// when its base finds a profile there. -func todayBrowsers(t *testing.T, home string) []browser.Browser { - t.Helper() - var out []browser.Browser - for _, def := range ibrowser.Supported() { - cfg := types.BrowserConfig{Key: def.ID, Name: def.Name, UserDataDir: home + "/" + def.Platform().UserDataDirs[0]} - var ( - b browser.Browser - err error - ) - switch def.Base { - case ibrowser.Chromium: - cfg.Kind = types.Chromium - var c *chromium.Browser - if c, err = chromium.NewBrowser(cfg); c != nil { - b = c - } - case ibrowser.Firefox: - cfg.Kind = types.Firefox - var f *firefox.Browser - if f, err = firefox.NewBrowser(cfg); f != nil { - b = f - } - case ibrowser.Safari: - cfg.Kind = types.Safari - var s *safari.Browser - if s, err = safari.NewBrowser(cfg); s != nil { - b = s - } - } - require.NoError(t, err, def.ID) - if b != nil { - out = append(out, b) - } - } - return out -} - -// todayList prints as today's list command did. -func todayList(t *testing.T, browsers []browser.Browser, detail bool) string { - t.Helper() - var buf bytes.Buffer - w := tabwriter.NewWriter(&buf, 0, 0, 3, ' ', 0) - if !detail { - fmt.Fprintln(w, "Browser\tProfile\tPath") - for _, b := range browsers { - for _, p := range b.Profiles() { - fmt.Fprintf(w, "%s\t%s\t%s\n", b.BrowserName(), p.Name, p.Dir) - } - } - require.NoError(t, w.Flush()) - return buf.String() - } - fmt.Fprint(w, "Browser\tProfile") - for _, c := range category.All() { - fmt.Fprintf(w, "\t%s", c.String()) - } - fmt.Fprintln(w) - for _, b := range browsers { - results, err := b.CountEntries(category.All()) - require.NoError(t, err) - for _, r := range results { - fmt.Fprintf(w, "%s\t%s", b.BrowserName(), r.Name) - for _, c := range category.All() { - fmt.Fprintf(w, "\t%d", r.Counts[c]) - } - fmt.Fprintln(w) - } - } - require.NoError(t, w.Flush()) - return buf.String() -} diff --git a/filemanager/session.go b/filemanager/session.go deleted file mode 100644 index a9ed1b4..0000000 --- a/filemanager/session.go +++ /dev/null @@ -1,39 +0,0 @@ -package filemanager - -import ( - "fmt" - "os" - - "github.com/moond4rk/hackbrowserdata/internal/snapshot" -) - -// Session manages temporary files for a single browser extraction run. -// It creates an isolated temp directory and provides methods to copy -// browser files into it. Call Cleanup() when done to remove all temp files. -type Session struct { - tempDir string -} - -// NewSession creates a session with a unique temporary directory. -func NewSession() (*Session, error) { - dir, err := os.MkdirTemp("", "hbd-*") - if err != nil { - return nil, fmt.Errorf("create temp dir: %w", err) - } - return &Session{tempDir: dir}, nil -} - -// TempDir returns the session's temporary directory path. -func (s *Session) TempDir() string { - return s.tempDir -} - -// Acquire copies a browser file (or directory) from src to dst with the snapshot copier. -func (s *Session) Acquire(src, dst string, isDir bool) error { - return snapshot.Copy(src, dst, isDir) -} - -// Cleanup removes the session's temporary directory and all its contents. -func (s *Session) Cleanup() { - os.RemoveAll(s.tempDir) -} diff --git a/filemanager/session_test.go b/filemanager/session_test.go deleted file mode 100644 index 5209dd0..0000000 --- a/filemanager/session_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package filemanager - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewSession(t *testing.T) { - s, err := NewSession() - require.NoError(t, err) - defer s.Cleanup() - - assert.DirExists(t, s.TempDir()) - assert.Contains(t, s.TempDir(), "hbd-") -} - -func TestSession_Cleanup(t *testing.T) { - s, err := NewSession() - require.NoError(t, err) - - dir := s.TempDir() - assert.DirExists(t, dir) - - s.Cleanup() - assert.NoDirExists(t, dir) -} - -func TestSession_Acquire_File(t *testing.T) { - s, err := NewSession() - require.NoError(t, err) - defer s.Cleanup() - - // Create a source file - srcDir := t.TempDir() - srcFile := filepath.Join(srcDir, "Login Data") - require.NoError(t, os.WriteFile(srcFile, []byte("test data"), 0o644)) - - // Acquire it - dst := filepath.Join(s.TempDir(), "Login Data") - err = s.Acquire(srcFile, dst, false) - require.NoError(t, err) - - // Verify copy - data, err := os.ReadFile(dst) - require.NoError(t, err) - assert.Equal(t, "test data", string(data)) -} - -func TestSession_Acquire_WAL(t *testing.T) { - s, err := NewSession() - require.NoError(t, err) - defer s.Cleanup() - - srcDir := t.TempDir() - srcFile := filepath.Join(srcDir, "Cookies") - require.NoError(t, os.WriteFile(srcFile, []byte("db"), 0o644)) - require.NoError(t, os.WriteFile(srcFile+"-wal", []byte("wal"), 0o644)) - require.NoError(t, os.WriteFile(srcFile+"-shm", []byte("shm"), 0o644)) - - dst := filepath.Join(s.TempDir(), "Cookies") - err = s.Acquire(srcFile, dst, false) - require.NoError(t, err) - - // Main file copied - assert.FileExists(t, dst) - // WAL and SHM also copied - assert.FileExists(t, dst+"-wal") - assert.FileExists(t, dst+"-shm") -} - -func TestSession_Acquire_Dir(t *testing.T) { - s, err := NewSession() - require.NoError(t, err) - defer s.Cleanup() - - // Create a source directory with files - srcDir := filepath.Join(t.TempDir(), "leveldb") - require.NoError(t, os.MkdirAll(srcDir, 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(srcDir, "000001.ldb"), []byte("data"), 0o644)) - require.NoError(t, os.WriteFile(filepath.Join(srcDir, "LOCK"), []byte(""), 0o644)) - - dst := filepath.Join(s.TempDir(), "leveldb") - err = s.Acquire(srcDir, dst, true) - require.NoError(t, err) - - // Data file copied - assert.FileExists(t, filepath.Join(dst, "000001.ldb")) - // LOCK file skipped (CopyDir skips "lock" suffix) -} - -func TestSession_Acquire_NotFound(t *testing.T) { - s, err := NewSession() - require.NoError(t, err) - defer s.Cleanup() - - dst := filepath.Join(s.TempDir(), "nope") - err = s.Acquire("/nonexistent/file", dst, false) - require.Error(t, err) -} diff --git a/testdata/list-detail.golden b/testdata/list-detail.golden new file mode 100644 index 0000000..e30ac8e --- /dev/null +++ b/testdata/list-detail.golden @@ -0,0 +1,7 @@ +Browser Profile password cookie bookmark history download creditcard extension localstorage sessionstorage +Chrome Default 3 4 3 3 2 2 3 5 3 +Chrome Profile 1 2 4 3 3 2 2 3 5 3 +Microsoft Edge Default 3 4 3 3 2 2 3 5 3 +Microsoft Edge Profile 1 2 4 3 3 2 2 3 5 3 +Firefox abcd1234.default-release 3 4 4 9 3 0 2 3 0 +Firefox wxyz5678.work 3 4 4 9 3 0 2 3 0 diff --git a/testdata/list-safari-detail.golden b/testdata/list-safari-detail.golden new file mode 100644 index 0000000..c9cb697 --- /dev/null +++ b/testdata/list-safari-detail.golden @@ -0,0 +1,4 @@ +Browser Profile password cookie bookmark history download creditcard extension localstorage sessionstorage +Safari default 0 4 6 4 2 0 4 4 0 +Safari Work 0 2 0 2 1 0 0 1 0 +Safari profile-9a1b2c3d 0 0 0 1 0 0 0 0 0 diff --git a/testdata/list-safari.golden b/testdata/list-safari.golden new file mode 100644 index 0000000..75c7a9b --- /dev/null +++ b/testdata/list-safari.golden @@ -0,0 +1,4 @@ +Browser Profile Path +Safari default /Safari +Safari Work /Containers/com.apple.Safari/Data/Library/Safari/Profiles/5604E6F5-02ED-4E40-8249-63DE7BC986C8 +Safari profile-9a1b2c3d /Containers/com.apple.Safari/Data/Library/Safari/Profiles/9A1B2C3D-4E5F-4A6B-8C7D-0E1F2A3B4C5D diff --git a/testdata/list.golden b/testdata/list.golden new file mode 100644 index 0000000..f2a0560 --- /dev/null +++ b/testdata/list.golden @@ -0,0 +1,7 @@ +Browser Profile Path +Chrome Default /Default +Chrome Profile 1 /Profile 1 +Microsoft Edge Default /Default +Microsoft Edge Profile 1 /Profile 1 +Firefox abcd1234.default-release /abcd1234.default-release +Firefox wxyz5678.work /wxyz5678.work diff --git a/types/browser.go b/types/browser.go deleted file mode 100644 index 1990e67..0000000 --- a/types/browser.go +++ /dev/null @@ -1,56 +0,0 @@ -package types - -import "github.com/moond4rk/hackbrowserdata/internal/record" - -// BrowserKind identifies the browser engine type. -type BrowserKind int - -const ( - Chromium BrowserKind = iota - ChromiumYandex // Chromium variant with different file names and extract logic - ChromiumOpera // Opera: extensions in "opsettings" key, data in Roaming - Firefox - Safari -) - -// String returns the canonical lowercase name of the engine kind; the chromium-family values are -// also the stable wire form carried in a keys dump, so don't change them lightly. -func (k BrowserKind) String() string { - switch k { - case Chromium: - return "chromium" - case ChromiumYandex: - return "chromium-yandex" - case ChromiumOpera: - return "chromium-opera" - case Firefox: - return "firefox" - case Safari: - return "safari" - default: - return "unknown" - } -} - -// BrowserConfig holds the declarative configuration for a browser installation. -type BrowserConfig struct { - Key string // Def.ID in internal/browser; the Windows injector looks the ABE target up by it - Name string // display name - Kind BrowserKind // engine type - KeychainLabel string // macOS Keychain account / Linux D-Bus Secret Service label; "" = none - WindowsABE bool // enable Windows App-Bound Encryption v20 (reflective injection) - UserDataDir string // base browser directory -} - -// BrowserData holds all extracted browser data with typed slices. -type BrowserData struct { - Passwords []record.Login - Cookies []record.Cookie - Histories []record.History - Downloads []record.Download - Bookmarks []record.Bookmark - CreditCards []record.CreditCard - Extensions []record.Extension - LocalStorage []record.LocalStorage - SessionStorage []record.SessionStorage -} diff --git a/types/browser_test.go b/types/browser_test.go deleted file mode 100644 index ff65022..0000000 --- a/types/browser_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestBrowserKind_String(t *testing.T) { - tests := []struct { - kind BrowserKind - want string - }{ - {Chromium, "chromium"}, - {ChromiumYandex, "chromium-yandex"}, - {ChromiumOpera, "chromium-opera"}, - {Firefox, "firefox"}, - {Safari, "safari"}, - {BrowserKind(999), "unknown"}, - } - for _, tt := range tests { - assert.Equal(t, tt.want, tt.kind.String()) - } -} diff --git a/types/result.go b/types/result.go deleted file mode 100644 index 72b890e..0000000 --- a/types/result.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import "github.com/moond4rk/hackbrowserdata/internal/category" - -// Profile identifies one browser profile — a leaf under an installation. -type Profile struct { - Name string - Dir string -} - -// ExtractResult pairs a profile with the data extracted from it. -type ExtractResult struct { - Profile - Data *BrowserData -} - -// CountResult pairs a profile with its per-category entry counts. -type CountResult struct { - Profile - Counts map[category.Category]int -} diff --git a/utils/fileutil/fileutil.go b/utils/fileutil/fileutil.go deleted file mode 100644 index 948558b..0000000 --- a/utils/fileutil/fileutil.go +++ /dev/null @@ -1,15 +0,0 @@ -package fileutil - -import "os" - -// FileExists checks if the file exists in the provided path. -func FileExists(filename string) bool { - info, err := os.Stat(filename) - if os.IsNotExist(err) { - return false - } - if err != nil { - return false - } - return !info.IsDir() -}