diff --git a/browser/archive.go b/browser/archive.go index fa9cf48..faadee6 100644 --- a/browser/archive.go +++ b/browser/archive.go @@ -7,8 +7,8 @@ import ( "github.com/moond4rk/hackbrowserdata/browser/chromium" "github.com/moond4rk/hackbrowserdata/filemanager" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) @@ -16,14 +16,14 @@ import ( // cross-host transport (Chromium only). type Archivable interface { BrowserKey() string - ArchiveSources(categories []types.Category) []chromium.ArchiveSource + 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. Files // are staged through a locked-file session first because Windows holds exclusive SQLite locks. Returns // the number of source entries staged (a directory source counts once). -func WriteArchive(browsers []Browser, categories []types.Category, outPath string) (int, error) { +func WriteArchive(browsers []Browser, categories []category.Category, outPath string) (int, error) { session, err := filemanager.NewSession() if err != nil { return 0, err diff --git a/browser/archive_test.go b/browser/archive_test.go index 17af7f6..f3376cf 100644 --- a/browser/archive_test.go +++ b/browser/archive_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/moond4rk/hackbrowserdata/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) @@ -34,7 +35,7 @@ func TestWriteArchive_RoundTrip(t *testing.T) { } zipPath := filepath.Join(t.TempDir(), "data.zip") - n, err := WriteArchive([]Browser{b}, []types.Category{types.History}, zipPath) + n, err := WriteArchive([]Browser{b}, []category.Category{category.History}, zipPath) if err != nil { t.Fatalf("WriteArchive: %v", err) } diff --git a/browser/browser.go b/browser/browser.go index a3a7f20..d619fe8 100644 --- a/browser/browser.go +++ b/browser/browser.go @@ -9,6 +9,7 @@ import ( "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/masterkey" "github.com/moond4rk/hackbrowserdata/types" @@ -19,8 +20,8 @@ type Browser interface { BrowserName() string UserDataDir() string Profiles() []types.Profile - Extract(categories []types.Category) ([]types.ExtractResult, error) - CountEntries(categories []types.Category) ([]types.CountResult, error) + Extract(categories []category.Category) ([]types.ExtractResult, error) + CountEntries(categories []category.Category) ([]types.CountResult, error) } type DiscoverOptions struct { diff --git a/browser/chromium/archive.go b/browser/chromium/archive.go index ab59583..38249c2 100644 --- a/browser/chromium/archive.go +++ b/browser/chromium/archive.go @@ -4,7 +4,7 @@ import ( "path" "path/filepath" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) @@ -23,7 +23,7 @@ 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 []types.Category) []ArchiveSource { +func (b *Browser) ArchiveSources(categories []category.Category) []ArchiveSource { var out []ArchiveSource for _, name := range installationFiles { abs := filepath.Join(b.cfg.UserDataDir, name) diff --git a/browser/chromium/archive_test.go b/browser/chromium/archive_test.go index 72d3cc5..dab5198 100644 --- a/browser/chromium/archive_test.go +++ b/browser/chromium/archive_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -30,7 +31,7 @@ func TestArchiveSources_ForwardSlashLayout(t *testing.T) { t.Fatalf("NewBrowser: b=%v err=%v", b, err) } - srcs := b.ArchiveSources([]types.Category{types.Cookie}) + srcs := b.ArchiveSources([]category.Category{category.Cookie}) var gotCookie, gotMarker, gotLocalState bool for _, s := range srcs { @@ -70,7 +71,7 @@ func TestArchiveSources_FlatLayoutNoExtraLevel(t *testing.T) { t.Fatalf("NewBrowser: b=%v err=%v", b, err) } - srcs := b.ArchiveSources([]types.Category{types.History}) + srcs := b.ArchiveSources([]category.Category{category.History}) phantom := filepath.Base(udd) + "/" var gotHistory bool @@ -106,7 +107,7 @@ func TestArchiveSources_IncludesBothPasswordDatabases(t *testing.T) { t.Fatalf("NewBrowser: b=%v err=%v", b, err) } - srcs := b.ArchiveSources([]types.Category{types.Password}) + srcs := b.ArchiveSources([]category.Category{category.Password}) var gotLocal, gotAccount bool for _, s := range srcs { diff --git a/browser/chromium/chromium.go b/browser/chromium/chromium.go index 1be8456..7367476 100644 --- a/browser/chromium/chromium.go +++ b/browser/chromium/chromium.go @@ -6,6 +6,7 @@ import ( "sync" "github.com/moond4rk/hackbrowserdata/filemanager" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" @@ -68,7 +69,7 @@ func (b *Browser) Profiles() []types.Profile { } // Extract derives the installation's master key once, then extracts every profile. -func (b *Browser) Extract(categories []types.Category) ([]types.ExtractResult, error) { +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 { @@ -81,7 +82,7 @@ func (b *Browser) Extract(categories []types.Category) ([]types.ExtractResult, e } // CountEntries counts entries per category for every profile without decryption. -func (b *Browser) CountEntries(categories []types.Category) ([]types.CountResult, error) { +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{ @@ -145,7 +146,7 @@ func (b *Browser) buildHints(session *filemanager.Session) masterkey.Hints { // 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[types.Category][]sourcePath) []string { +func discoverProfiles(userDataDir string, sources map[category.Category][]sourcePath) []string { entries, err := os.ReadDir(userDataDir) if err != nil { return nil @@ -206,7 +207,7 @@ func isProfileDir(dir string) bool { } // hasAnySource checks if dir contains at least one source file or directory. -func hasAnySource(sources map[types.Category][]sourcePath, dir string) bool { +func hasAnySource(sources map[category.Category][]sourcePath, dir string) bool { for _, candidates := range sources { for _, sp := range candidates { abs := filepath.Join(dir, sp.rel) @@ -228,8 +229,8 @@ type resolvedPath struct { // resolveSourcePaths checks which sources actually exist in profileDir. // Candidates are tried in priority order; the first existing path wins. -func resolveSourcePaths(sources map[types.Category][]sourcePath, profileDir string) map[types.Category]resolvedPath { - resolved := make(map[types.Category]resolvedPath) +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) diff --git a/browser/chromium/chromium_test.go b/browser/chromium/chromium_test.go index 037ca59..daf4f9e 100644 --- a/browser/chromium/chromium_test.go +++ b/browser/chromium/chromium_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -136,7 +137,7 @@ func TestNewBrowsers(t *testing.T) { kind types.BrowserKind wantProfiles []string // expected profile base names wantCats map[string][]string // profile → expected category base names (spot check) - wantDirs []types.Category // categories that should be isDir=true + wantDirs []category.Category // categories that should be isDir=true skipProfiles []string // should NOT appear }{ { @@ -147,7 +148,7 @@ func TestNewBrowsers(t *testing.T) { wantCats: map[string][]string{ "Default": {"Login Data", "Cookies", "History", "Bookmarks", "Web Data", "Secure Preferences", "leveldb", "Session Storage"}, }, - wantDirs: []types.Category{types.LocalStorage, types.SessionStorage}, + wantDirs: []category.Category{category.LocalStorage, category.SessionStorage}, skipProfiles: []string{"System Profile", "Guest Profile", "Snapshot"}, }, { @@ -194,14 +195,14 @@ func TestNewBrowsers(t *testing.T) { dir: fixture.leveldb, kind: types.Chromium, wantProfiles: []string{"Default"}, - wantDirs: []types.Category{types.LocalStorage, types.SessionStorage}, + wantDirs: []category.Category{category.LocalStorage, category.SessionStorage}, }, { name: "leveldb only", dir: fixture.leveldbOnly, kind: types.Chromium, wantProfiles: []string{"Default"}, - wantDirs: []types.Category{types.LocalStorage, types.SessionStorage}, + wantDirs: []category.Category{category.LocalStorage, category.SessionStorage}, }, { name: "empty dir", @@ -323,7 +324,7 @@ func assertCategories(t *testing.T, nameMap map[string]*profile, wantCats map[st } } -func assertDirCategories(t *testing.T, profiles []*profile, cats []types.Category) { +func assertDirCategories(t *testing.T, profiles []*profile, cats []category.Category) { t.Helper() for _, cat := range cats { for _, p := range profiles { @@ -340,15 +341,15 @@ func assertDirCategories(t *testing.T, profiles []*profile, cats []types.Categor func TestCookiePriority(t *testing.T) { resolved := resolveSourcePaths(chromiumSources, filepath.Join(fixture.bothCookies, "Default")) - require.Contains(t, resolved, types.Cookie) - assert.Contains(t, resolved[types.Cookie].absPath, "Network", + 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, types.Cookie) - assert.NotContains(t, resolved[types.Cookie].absPath, "Network", + require.Contains(t, resolved, category.Cookie) + assert.NotContains(t, resolved[category.Cookie].absPath, "Network", "should fallback to root Cookies when Network/Cookies missing") } @@ -358,7 +359,7 @@ func TestCookieFallback(t *testing.T) { func TestSharedSourceFile(t *testing.T) { resolved := resolveSourcePaths(chromiumSources, filepath.Join(fixture.chrome, "Default")) - assert.Equal(t, resolved[types.History].absPath, resolved[types.Download].absPath) + assert.Equal(t, resolved[category.History].absPath, resolved[category.Download].absPath) } // --------------------------------------------------------------------------- @@ -369,10 +370,10 @@ func TestSourcesForKind(t *testing.T) { chromium := sourcesForKind(types.Chromium) yandex := sourcesForKind(types.ChromiumYandex) - assert.Equal(t, "Login Data", chromium[types.Password][0].rel) - assert.Equal(t, "Ya Passman Data", yandex[types.Password][0].rel) + 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[types.History][0].rel, yandex[types.History][0].rel) + assert.Equal(t, chromium[category.History][0].rel, yandex[category.History][0].rel) } func TestExtractorsForKind(t *testing.T) { @@ -380,12 +381,12 @@ func TestExtractorsForKind(t *testing.T) { yandexExt := extractorsForKind(types.ChromiumYandex) require.NotNil(t, yandexExt) - assert.Contains(t, yandexExt, types.Password) - assert.Contains(t, yandexExt, types.CreditCard) + assert.Contains(t, yandexExt, category.Password) + assert.Contains(t, yandexExt, category.CreditCard) operaExt := extractorsForKind(types.ChromiumOpera) require.NotNil(t, operaExt) - assert.Contains(t, operaExt, types.Extension) + assert.Contains(t, operaExt, category.Extension) } // --------------------------------------------------------------------------- @@ -608,13 +609,12 @@ func TestExtract(t *testing.T) { b.SetRetrievers(masterkey.Retrievers{V10: tt.retriever}) } - results, err := b.Extract([]types.Category{types.History}) + 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) - // setupHistoryDB: Example(200) > GitHub(100) > Go Dev(50) - assert.Equal(t, "Example", results[0].Data.Histories[0].Title) + assert.Equal(t, "GitHub", results[0].Data.Histories[0].Title) if tt.wantRetriever { mock, ok := tt.retriever.(*mockRetriever) @@ -641,15 +641,15 @@ func TestCountEntries(t *testing.T) { require.NotNil(t, b) // No retriever set — CountEntries should still work (no decryption needed). - results, err := b.CountEntries([]types.Category{types.History, types.Download}) + 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[types.History]) + 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[types.Download]) + assert.Equal(t, 0, results[0].Counts[category.Download]) } func TestCountEntries_NoRetrieverNeeded(t *testing.T) { @@ -665,10 +665,10 @@ func TestCountEntries_NoRetrieverNeeded(t *testing.T) { require.NotNil(t, b) // No retriever set — CountEntries succeeds without master key. - results, err := b.CountEntries([]types.Category{types.Password}) + results, err := b.CountEntries([]category.Category{category.Password}) require.NoError(t, err) require.Len(t, results, 1) - assert.Equal(t, 2, results[0].Counts[types.Password]) + assert.Equal(t, 2, results[0].Counts[category.Password]) } // --------------------------------------------------------------------------- diff --git a/browser/chromium/extract_bookmark.go b/browser/chromium/extract_bookmark.go index 65a8bd2..33c9e81 100644 --- a/browser/chromium/extract_bookmark.go +++ b/browser/chromium/extract_bookmark.go @@ -2,38 +2,33 @@ package chromium import ( "os" - "sort" "github.com/tidwall/gjson" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) -func extractBookmarks(path string) ([]types.BookmarkEntry, error) { +func extractBookmarks(path string) ([]record.Bookmark, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } - var bookmarks []types.BookmarkEntry + var bookmarks []record.Bookmark roots := gjson.GetBytes(data, "roots") roots.ForEach(func(_, value gjson.Result) bool { walkBookmarks(value, "", &bookmarks) return true }) - - sort.Slice(bookmarks, func(i, j int) bool { - return bookmarks[i].CreatedAt.After(bookmarks[j].CreatedAt) - }) return bookmarks, nil } // walkBookmarks recursively traverses the bookmark tree, collecting URL entries. -func walkBookmarks(node gjson.Result, folder string, out *[]types.BookmarkEntry) { +func walkBookmarks(node gjson.Result, folder string, out *[]record.Bookmark) { nodeType := node.Get("type").String() if nodeType == "url" { - *out = append(*out, types.BookmarkEntry{ + *out = append(*out, record.Bookmark{ ID: node.Get("id").Int(), Name: node.Get("name").String(), Type: nodeType, diff --git a/browser/chromium/extract_bookmark_test.go b/browser/chromium/extract_bookmark_test.go index 1850fcd..97534d8 100644 --- a/browser/chromium/extract_bookmark_test.go +++ b/browser/chromium/extract_bookmark_test.go @@ -43,18 +43,18 @@ func TestExtractBookmarks(t *testing.T) { require.NoError(t, err) require.Len(t, got, 3) - // Verify sort order: date added descending (newest first) - assert.Equal(t, "GitHub", got[0].Name) - assert.Equal(t, "Go", got[1].Name) - assert.Equal(t, "HN", got[2].Name) + // Bookmarks keep the tree's order; the exporter sorts them. + assert.Equal(t, "Go", got[0].Name) + assert.Equal(t, "HN", got[1].Name) + assert.Equal(t, "GitHub", got[2].Name) // Verify field mapping - assert.Equal(t, "https://github.com", got[0].URL) - assert.Equal(t, "Other", got[0].Folder) + assert.Equal(t, "https://github.com", got[2].URL) + assert.Equal(t, "Other", got[2].Folder) // Verify nested folder tracking - assert.Equal(t, "https://news.ycombinator.com", got[2].URL) - assert.Equal(t, "News", got[2].Folder) // parent folder name + assert.Equal(t, "https://news.ycombinator.com", got[1].URL) + assert.Equal(t, "News", got[1].Folder) // parent folder name } func TestCountBookmarks(t *testing.T) { diff --git a/browser/chromium/extract_cookie.go b/browser/chromium/extract_cookie.go index 6c15897..cb81f83 100644 --- a/browser/chromium/extract_cookie.go +++ b/browser/chromium/extract_cookie.go @@ -4,12 +4,11 @@ import ( "bytes" "crypto/sha256" "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" "github.com/moond4rk/hackbrowserdata/masterkey" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -19,9 +18,9 @@ const ( countCookieQuery = `SELECT COUNT(*) FROM cookies` ) -func extractCookies(masterKeys masterkey.MasterKeys, path string) ([]types.CookieEntry, error) { +func extractCookies(masterKeys masterkey.MasterKeys, path string) ([]record.Cookie, error) { cookies, err := sqlitex.QueryRows(path, false, defaultCookieQuery, - func(rows *sql.Rows) (types.CookieEntry, error) { + func(rows *sql.Rows) (record.Cookie, error) { var ( name, host, cookiePath string isSecure, isHTTPOnly int @@ -33,7 +32,7 @@ func extractCookies(masterKeys masterkey.MasterKeys, path string) ([]types.Cooki if err := rows.Scan(&name, &encryptedValue, &host, &cookiePath, &createdAt, &expireAt, &isSecure, &isHTTPOnly, &hasExpire, &isPersistent, &sameSite); err != nil { - return types.CookieEntry{}, err + return record.Cookie{}, err } value, _ := decryptValue(masterKeys, encryptedValue) @@ -49,7 +48,7 @@ func extractCookies(masterKeys masterkey.MasterKeys, path string) ([]types.Cooki case -1: // not specified by Set-Cookie } - return types.CookieEntry{ + return record.Cookie{ Name: name, Host: host, Path: cookiePath, @@ -66,10 +65,6 @@ func extractCookies(masterKeys masterkey.MasterKeys, path string) ([]types.Cooki if err != nil { return nil, err } - - sort.Slice(cookies, func(i, j int) bool { - return cookies[i].CreatedAt.After(cookies[j].CreatedAt) - }) return cookies, nil } diff --git a/browser/chromium/extract_cookie_test.go b/browser/chromium/extract_cookie_test.go index a179166..c359a9e 100644 --- a/browser/chromium/extract_cookie_test.go +++ b/browser/chromium/extract_cookie_test.go @@ -25,20 +25,20 @@ func TestExtractCookies(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Verify sort order: creation time descending (newest first) - assert.Equal(t, ".new.com", got[0].Host) - assert.Equal(t, ".old.com", got[1].Host) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, ".old.com", got[0].Host) + assert.Equal(t, ".new.com", got[1].Host) // Verify field mapping - assert.Equal(t, "token", got[0].Name) - assert.Equal(t, "/api", got[0].Path) - assert.True(t, got[0].IsSecure) - assert.False(t, got[0].IsHTTPOnly) - assert.True(t, got[0].HasExpire) - assert.True(t, got[0].IsPersistent) - assert.False(t, got[0].CreatedAt.IsZero()) - assert.True(t, got[0].ExpireAt.After(got[0].CreatedAt)) - assert.True(t, got[1].IsHTTPOnly) + assert.Equal(t, "token", got[1].Name) + assert.Equal(t, "/api", got[1].Path) + assert.True(t, got[1].IsSecure) + assert.False(t, got[1].IsHTTPOnly) + assert.True(t, got[1].HasExpire) + assert.True(t, got[1].IsPersistent) + assert.False(t, got[1].CreatedAt.IsZero()) + assert.True(t, got[1].ExpireAt.After(got[1].CreatedAt)) + assert.True(t, got[0].IsHTTPOnly) } func TestCountCookies(t *testing.T) { diff --git a/browser/chromium/extract_creditcard.go b/browser/chromium/extract_creditcard.go index d9c3069..44a5fcc 100644 --- a/browser/chromium/extract_creditcard.go +++ b/browser/chromium/extract_creditcard.go @@ -7,9 +7,9 @@ import ( "github.com/moond4rk/hackbrowserdata/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/masterkey" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -36,16 +36,16 @@ type yandexPrivateData struct { SecretComment string `json:"secret_comment"` } -func extractCreditCards(masterKeys masterkey.MasterKeys, path string) ([]types.CreditCardEntry, error) { +func extractCreditCards(masterKeys masterkey.MasterKeys, path string) ([]record.CreditCard, error) { cards, err := sqlitex.QueryRows(path, false, defaultCreditCardQuery, - func(rows *sql.Rows) (types.CreditCardEntry, error) { + func(rows *sql.Rows) (record.CreditCard, error) { var guid, name, month, year, nickname, address string var encNumber []byte if err := rows.Scan(&guid, &name, &month, &year, &encNumber, &nickname, &address); err != nil { - return types.CreditCardEntry{}, err + return record.CreditCard{}, err } number, _ := decryptValue(masterKeys, encNumber) - return types.CreditCardEntry{ + return record.CreditCard{ GUID: guid, Name: name, Number: string(number), @@ -62,7 +62,7 @@ func extractCreditCards(masterKeys masterkey.MasterKeys, path string) ([]types.C } // extractYandexCreditCards reads the records table (not Chromium's credit_cards). AAD = guid. -func extractYandexCreditCards(masterKeys masterkey.MasterKeys, path string) ([]types.CreditCardEntry, error) { +func extractYandexCreditCards(masterKeys masterkey.MasterKeys, path string) ([]record.CreditCard, error) { dataKey, err := loadYandexDataKey(path, masterKeys.V10) if err != nil { if errors.Is(err, errYandexMasterPasswordSet) { @@ -73,11 +73,11 @@ func extractYandexCreditCards(masterKeys masterkey.MasterKeys, path string) ([]t } return sqlitex.QueryRows(path, false, yandexCreditCardQuery, - func(rows *sql.Rows) (types.CreditCardEntry, error) { + func(rows *sql.Rows) (record.CreditCard, error) { var guid, publicData string var privateData []byte if err := rows.Scan(&guid, &publicData, &privateData); err != nil { - return types.CreditCardEntry{}, err + return record.CreditCard{}, err } var public yandexPublicData @@ -86,7 +86,7 @@ func extractYandexCreditCards(masterKeys masterkey.MasterKeys, path string) ([]t log.Debugf("yandex: parse public_data for %s: %v", guid, err) } } - entry := types.CreditCardEntry{ + entry := record.CreditCard{ GUID: guid, Name: public.CardHolder, ExpMonth: public.ExpireDateMonth, diff --git a/browser/chromium/extract_download.go b/browser/chromium/extract_download.go index 62e5dd3..1c72e8e 100644 --- a/browser/chromium/extract_download.go +++ b/browser/chromium/extract_download.go @@ -2,11 +2,10 @@ package chromium import ( "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -15,15 +14,15 @@ const ( countDownloadQuery = `SELECT COUNT(*) FROM downloads` ) -func extractDownloads(path string) ([]types.DownloadEntry, error) { +func extractDownloads(path string) ([]record.Download, error) { downloads, err := sqlitex.QueryRows(path, false, defaultDownloadQuery, - func(rows *sql.Rows) (types.DownloadEntry, error) { + func(rows *sql.Rows) (record.Download, error) { var targetPath, url, mimeType string var totalBytes, startTime, endTime int64 if err := rows.Scan(&targetPath, &url, &totalBytes, &startTime, &endTime, &mimeType); err != nil { - return types.DownloadEntry{}, err + return record.Download{}, err } - return types.DownloadEntry{ + return record.Download{ URL: url, TargetPath: targetPath, MimeType: mimeType, @@ -35,10 +34,6 @@ func extractDownloads(path string) ([]types.DownloadEntry, error) { if err != nil { return nil, err } - - sort.Slice(downloads, func(i, j int) bool { - return downloads[i].StartTime.After(downloads[j].StartTime) - }) return downloads, nil } diff --git a/browser/chromium/extract_download_test.go b/browser/chromium/extract_download_test.go index 9019b02..7e4d09a 100644 --- a/browser/chromium/extract_download_test.go +++ b/browser/chromium/extract_download_test.go @@ -22,17 +22,17 @@ func TestExtractDownloads(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Verify sort order: start time descending (newest first) - assert.Equal(t, "https://new.com/doc.pdf", got[0].URL) - assert.Equal(t, "https://old.com/file.zip", got[1].URL) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, "https://old.com/file.zip", got[0].URL) + assert.Equal(t, "https://new.com/doc.pdf", got[1].URL) // Verify field mapping - assert.Equal(t, "/tmp/new.pdf", got[0].TargetPath) - assert.Equal(t, "application/pdf", got[0].MimeType) - assert.Equal(t, int64(2048), got[0].TotalBytes) - assert.False(t, got[0].StartTime.IsZero()) - assert.False(t, got[0].EndTime.IsZero()) - assert.True(t, got[0].StartTime.Before(got[0].EndTime)) + assert.Equal(t, "/tmp/new.pdf", got[1].TargetPath) + assert.Equal(t, "application/pdf", got[1].MimeType) + assert.Equal(t, int64(2048), got[1].TotalBytes) + assert.False(t, got[1].StartTime.IsZero()) + assert.False(t, got[1].EndTime.IsZero()) + assert.True(t, got[1].StartTime.Before(got[1].EndTime)) } func TestCountDownloads(t *testing.T) { diff --git a/browser/chromium/extract_extension.go b/browser/chromium/extract_extension.go index 1cd1812..7c00e8d 100644 --- a/browser/chromium/extract_extension.go +++ b/browser/chromium/extract_extension.go @@ -6,7 +6,7 @@ import ( "github.com/tidwall/gjson" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) // defaultExtensionKeys are the JSON paths tried for standard Chromium browsers. @@ -16,14 +16,14 @@ var defaultExtensionKeys = []string{ "settings.settings", } -func extractExtensions(path string) ([]types.ExtensionEntry, error) { +func extractExtensions(path string) ([]record.Extension, error) { return extractExtensionsWithKeys(path, defaultExtensionKeys) } // extractExtensionsWithKeys reads Secure Preferences and looks for extension // settings under the given JSON key paths. This allows browser variants // (e.g. Opera with "extensions.opsettings") to reuse the same parsing logic. -func extractExtensionsWithKeys(path string, keys []string) ([]types.ExtensionEntry, error) { +func extractExtensionsWithKeys(path string, keys []string) ([]record.Extension, error) { data, err := os.ReadFile(path) if err != nil { return nil, err @@ -40,7 +40,7 @@ func extractExtensionsWithKeys(path string, keys []string) ([]types.ExtensionEnt return nil, fmt.Errorf("cannot find extensions in settings") } - var extensions []types.ExtensionEntry + var extensions []record.Extension settings.ForEach(func(id, ext gjson.Result) bool { // Skip system/component extensions // https://source.chromium.org/chromium/chromium/src/+/main:extensions/common/mojom/manifest.mojom @@ -54,7 +54,7 @@ func extractExtensionsWithKeys(path string, keys []string) ([]types.ExtensionEnt return true } - extensions = append(extensions, types.ExtensionEntry{ + extensions = append(extensions, record.Extension{ Name: manifest.Get("name").String(), ID: id.String(), Description: manifest.Get("description").String(), @@ -82,7 +82,7 @@ func isExtensionEnabled(ext gjson.Result) bool { // extractOperaExtensions extracts extensions from Opera's Secure Preferences, // which stores extension data under "extensions.opsettings" instead of the // standard "extensions.settings". -func extractOperaExtensions(path string) ([]types.ExtensionEntry, error) { +func extractOperaExtensions(path string) ([]record.Extension, error) { return extractExtensionsWithKeys(path, []string{"extensions.opsettings"}) } diff --git a/browser/chromium/extract_history.go b/browser/chromium/extract_history.go index 5847111..7a9eb9a 100644 --- a/browser/chromium/extract_history.go +++ b/browser/chromium/extract_history.go @@ -2,11 +2,10 @@ package chromium import ( "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -14,16 +13,16 @@ const ( countHistoryQuery = `SELECT COUNT(*) FROM urls` ) -func extractHistories(path string) ([]types.HistoryEntry, error) { +func extractHistories(path string) ([]record.History, error) { histories, err := sqlitex.QueryRows(path, false, defaultHistoryQuery, - func(rows *sql.Rows) (types.HistoryEntry, error) { + func(rows *sql.Rows) (record.History, error) { var url, title string var visitCount int var lastVisit int64 if err := rows.Scan(&url, &title, &visitCount, &lastVisit); err != nil { - return types.HistoryEntry{}, err + return record.History{}, err } - return types.HistoryEntry{ + return record.History{ URL: url, Title: title, VisitCount: visitCount, @@ -33,10 +32,6 @@ func extractHistories(path string) ([]types.HistoryEntry, error) { if err != nil { return nil, err } - - sort.Slice(histories, func(i, j int) bool { - return histories[i].VisitCount > histories[j].VisitCount - }) return histories, nil } diff --git a/browser/chromium/extract_history_test.go b/browser/chromium/extract_history_test.go index 7c5d44c..1afc45c 100644 --- a/browser/chromium/extract_history_test.go +++ b/browser/chromium/extract_history_test.go @@ -23,15 +23,15 @@ func TestExtractHistories(t *testing.T) { require.NoError(t, err) require.Len(t, got, 3) - // Verify sort order: visit count descending - assert.Equal(t, 200, got[0].VisitCount) - assert.Equal(t, 100, got[1].VisitCount) - assert.Equal(t, 50, got[2].VisitCount) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, 100, got[0].VisitCount) + assert.Equal(t, 50, got[1].VisitCount) + assert.Equal(t, 200, got[2].VisitCount) // Verify field mapping - assert.Equal(t, "https://example.com", got[0].URL) - assert.Equal(t, "Example", got[0].Title) - assert.False(t, got[0].LastVisit.IsZero()) + assert.Equal(t, "https://example.com", got[2].URL) + assert.Equal(t, "Example", got[2].Title) + assert.False(t, got[2].LastVisit.IsZero()) } func TestCountHistories(t *testing.T) { diff --git a/browser/chromium/extract_password.go b/browser/chromium/extract_password.go index cfff5e5..b661a63 100644 --- a/browser/chromium/extract_password.go +++ b/browser/chromium/extract_password.go @@ -3,14 +3,13 @@ package chromium import ( "database/sql" "errors" - "sort" "github.com/moond4rk/hackbrowserdata/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" "github.com/moond4rk/hackbrowserdata/masterkey" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -24,33 +23,29 @@ const ( // appendPasswords merges another login DB into dst. Entries are kept even when an identical // credential already exists — the Store field records which DB each one came from. -func appendPasswords(masterKeys masterkey.MasterKeys, path, store string, dst []types.LoginEntry) ([]types.LoginEntry, error) { +func appendPasswords(masterKeys masterkey.MasterKeys, path string, store record.Store, dst []record.Login) ([]record.Login, error) { logins, err := extractPasswords(masterKeys, path, store) if err != nil { return dst, err } - dst = append(dst, logins...) - sort.SliceStable(dst, func(i, j int) bool { - return dst[i].CreatedAt.After(dst[j].CreatedAt) - }) - return dst, nil + return append(dst, logins...), nil } -func extractPasswords(masterKeys masterkey.MasterKeys, path, store string) ([]types.LoginEntry, error) { +func extractPasswords(masterKeys masterkey.MasterKeys, path string, store record.Store) ([]record.Login, error) { return extractPasswordsWithQuery(masterKeys, path, store, defaultLoginQuery) } -func extractPasswordsWithQuery(masterKeys masterkey.MasterKeys, path, store, query string) ([]types.LoginEntry, error) { +func extractPasswordsWithQuery(masterKeys masterkey.MasterKeys, path string, store record.Store, query string) ([]record.Login, error) { logins, err := sqlitex.QueryRows(path, false, query, - func(rows *sql.Rows) (types.LoginEntry, error) { + func(rows *sql.Rows) (record.Login, error) { var url, username string var pwd []byte var created int64 if err := rows.Scan(&url, &username, &pwd, &created); err != nil { - return types.LoginEntry{}, err + return record.Login{}, err } password, _ := decryptValue(masterKeys, pwd) - return types.LoginEntry{ + return record.Login{ URL: url, Username: username, Password: string(password), @@ -61,16 +56,12 @@ func extractPasswordsWithQuery(masterKeys masterkey.MasterKeys, path, store, que if err != nil { return nil, err } - - sort.Slice(logins, func(i, j int) bool { - return logins[i].CreatedAt.After(logins[j].CreatedAt) - }) return logins, nil } // extractYandexPasswords walks Ya Passman Data. // Note: URL column is origin_url — it's what the per-row AAD is computed over (not action_url). -func extractYandexPasswords(masterKeys masterkey.MasterKeys, path string) ([]types.LoginEntry, error) { +func extractYandexPasswords(masterKeys masterkey.MasterKeys, path string) ([]record.Login, error) { dataKey, err := loadYandexDataKey(path, masterKeys.V10) if err != nil { if errors.Is(err, errYandexMasterPasswordSet) { @@ -81,18 +72,18 @@ func extractYandexPasswords(masterKeys masterkey.MasterKeys, path string) ([]typ } logins, err := sqlitex.QueryRows(path, false, yandexLoginQuery, - func(rows *sql.Rows) (types.LoginEntry, error) { + func(rows *sql.Rows) (record.Login, error) { var originURL, usernameElem, usernameVal, passwordElem, signonRealm string var passwordValue []byte var created int64 if err := rows.Scan(&originURL, &usernameElem, &usernameVal, &passwordElem, &passwordValue, &signonRealm, &created); err != nil { - return types.LoginEntry{}, err + return record.Login{}, err } - entry := types.LoginEntry{ + entry := record.Login{ URL: originURL, Username: usernameVal, CreatedAt: timeconv.Chromium(created), - Store: types.PasswordStoreLocal, + Store: record.StoreLocal, } aad := yandexLoginAAD(originURL, usernameElem, usernameVal, passwordElem, signonRealm, nil) plaintext, err := crypto.AESGCMDecryptBlob(dataKey, passwordValue, aad) @@ -106,10 +97,6 @@ func extractYandexPasswords(masterKeys masterkey.MasterKeys, path string) ([]typ if err != nil { return nil, err } - - sort.Slice(logins, func(i, j int) bool { - return logins[i].CreatedAt.After(logins[j].CreatedAt) - }) return logins, nil } diff --git a/browser/chromium/extract_password_test.go b/browser/chromium/extract_password_test.go index bdcecb5..bd4be21 100644 --- a/browser/chromium/extract_password_test.go +++ b/browser/chromium/extract_password_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/masterkey" - "github.com/moond4rk/hackbrowserdata/types" ) func setupLoginDB(t *testing.T) string { @@ -23,20 +23,20 @@ func setupLoginDB(t *testing.T) string { func TestExtractPasswords(t *testing.T) { path := setupLoginDB(t) - got, err := extractPasswords(masterkey.MasterKeys{}, path, types.PasswordStoreLocal) + got, err := extractPasswords(masterkey.MasterKeys{}, path, record.StoreLocal) require.NoError(t, err) require.Len(t, got, 2) - // Verify sort order: date created descending (newest first) - assert.Equal(t, "https://new.com", got[0].URL) - assert.Equal(t, "https://old.com", got[1].URL) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, "https://old.com", got[0].URL) + assert.Equal(t, "https://new.com", got[1].URL) // Verify field mapping - assert.Equal(t, "bob", got[0].Username) - assert.False(t, got[0].CreatedAt.IsZero()) + assert.Equal(t, "bob", got[1].Username) + assert.False(t, got[1].CreatedAt.IsZero()) // Password is empty because masterKey is nil (decrypt returns empty) - assert.Empty(t, got[0].Password) - assert.Equal(t, types.PasswordStoreLocal, got[0].Store) + assert.Empty(t, got[1].Password) + assert.Equal(t, record.StoreLocal, got[1].Store) } // A credential whose blob cannot be decrypted must still be reported, otherwise a missing @@ -46,13 +46,13 @@ func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) { insertLogin("https://enc.com", "https://enc.com/login", "carol", "763130deadbeef", 13350000000000000), ) - got, err := extractPasswords(masterkey.MasterKeys{}, path, types.PasswordStoreAccount) + got, err := extractPasswords(masterkey.MasterKeys{}, path, record.StoreAccount) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "carol", got[0].Username) assert.Empty(t, got[0].Password) - assert.Equal(t, types.PasswordStoreAccount, got[0].Store) + assert.Equal(t, record.StoreAccount, got[0].Store) } func TestCountPasswords(t *testing.T) { @@ -92,11 +92,11 @@ func TestExtractYandexPasswords(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Sorted newest-first on CreatedAt. - assert.Equal(t, "https://new.yandex.ru", got[0].URL) - assert.Equal(t, "bob", got[0].Username) - assert.Equal(t, "sesame", got[0].Password) - assert.Equal(t, "hunter2", got[1].Password) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, "https://new.yandex.ru", got[1].URL) + assert.Equal(t, "bob", got[1].Username) + assert.Equal(t, "sesame", got[1].Password) + assert.Equal(t, "hunter2", got[0].Password) } func TestExtractYandexPasswords_MasterPasswordSkipped(t *testing.T) { diff --git a/browser/chromium/extract_storage.go b/browser/chromium/extract_storage.go index 7c9dfc7..d179de6 100644 --- a/browser/chromium/extract_storage.go +++ b/browser/chromium/extract_storage.go @@ -10,7 +10,7 @@ import ( "github.com/syndtr/goleveldb/leveldb" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) // Chromium localStorage LevelDB key prefixes and string format bytes. @@ -26,7 +26,7 @@ const ( const maxLocalStorageValueLength = 2048 -func extractLocalStorage(path string) ([]types.StorageEntry, error) { +func extractLocalStorage(path string) ([]record.LocalStorage, error) { if _, err := os.Stat(path); err != nil { return nil, fmt.Errorf("leveldb path %q: %w", path, err) } @@ -36,7 +36,7 @@ func extractLocalStorage(path string) ([]types.StorageEntry, error) { } defer db.Close() - var entries []types.StorageEntry + var entries []record.LocalStorage iter := db.NewIterator(nil, nil) defer iter.Release() @@ -52,18 +52,18 @@ func extractLocalStorage(path string) ([]types.StorageEntry, error) { // parseLocalStorageEntry classifies a LevelDB key/value pair and decodes it. // Returns false for VERSION entries and any unrecognized keys. META entries are kept with IsMeta=true. -func parseLocalStorageEntry(key, value []byte) (types.StorageEntry, bool) { +func parseLocalStorageEntry(key, value []byte) (record.LocalStorage, bool) { switch { case bytes.Equal(key, []byte(localStorageVersionKey)): - return types.StorageEntry{}, false + return record.LocalStorage{}, false case bytes.HasPrefix(key, []byte(localStorageMetaAccessKey)): - return types.StorageEntry{ + return record.LocalStorage{ IsMeta: true, URL: string(bytes.TrimPrefix(key, []byte(localStorageMetaAccessKey))), Value: fmt.Sprintf("meta data, value bytes is %v", value), }, true case bytes.HasPrefix(key, []byte(localStorageMetaPrefix)): - return types.StorageEntry{ + return record.LocalStorage{ IsMeta: true, URL: string(bytes.TrimPrefix(key, []byte(localStorageMetaPrefix))), Value: fmt.Sprintf("meta data, value bytes is %v", value), @@ -71,13 +71,13 @@ func parseLocalStorageEntry(key, value []byte) (types.StorageEntry, bool) { case len(key) > 0 && key[0] == localStorageDataPrefix: return parseLocalStorageDataEntry(key[1:], value), true default: - return types.StorageEntry{}, false + return record.LocalStorage{}, false } } // parseLocalStorageDataEntry decodes a data entry with format: origin\x00. -func parseLocalStorageDataEntry(key, value []byte) types.StorageEntry { - entry := types.StorageEntry{ +func parseLocalStorageDataEntry(key, value []byte) record.LocalStorage { + entry := record.LocalStorage{ Value: decodeLocalStorageValue(value), } @@ -157,7 +157,7 @@ func decodeLocalStorageValue(value []byte) string { // namespace-- → (origin mapping) // map-- → (actual data, UTF-16 LE) // next-map-id / version (metadata, skipped) -func extractSessionStorage(path string) ([]types.StorageEntry, error) { +func extractSessionStorage(path string) ([]record.SessionStorage, error) { if _, err := os.Stat(path); err != nil { return nil, fmt.Errorf("leveldb path %q: %w", path, err) } @@ -192,7 +192,7 @@ func extractSessionStorage(path string) ([]types.StorageEntry, error) { } // Pass 2: read map entries and resolve origins. - var entries []types.StorageEntry + var entries []record.SessionStorage iter2 := db.NewIterator(nil, nil) defer iter2.Release() @@ -216,7 +216,7 @@ func extractSessionStorage(path string) ([]types.StorageEntry, error) { } value := decodeSessionStorageValue(iter2.Value()) - entries = append(entries, types.StorageEntry{ + entries = append(entries, record.SessionStorage{ URL: origin, Key: keyName, Value: value, diff --git a/browser/chromium/profile.go b/browser/chromium/profile.go index a06e57e..6889b5a 100644 --- a/browser/chromium/profile.go +++ b/browser/chromium/profile.go @@ -5,7 +5,9 @@ import ( "path/filepath" "github.com/moond4rk/hackbrowserdata/filemanager" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -16,8 +18,8 @@ type profile struct { profileDir string browserName string kind types.BrowserKind - extractors map[types.Category]categoryExtractor - sourcePaths map[types.Category]resolvedPath + extractors map[category.Category]categoryExtractor + sourcePaths map[category.Category]resolvedPath } func (p *profile) name() string { @@ -31,7 +33,7 @@ func (p *profile) label() string { return p.browserName + "/" + p.name() } // extract copies the profile's source files to a temp directory and extracts the // requested categories, decrypting with the installation's master keys. -func (p *profile) extract(masterKeys masterkey.MasterKeys, categories []types.Category) *types.BrowserData { +func (p *profile) extract(masterKeys masterkey.MasterKeys, categories []category.Category) *types.BrowserData { session, err := filemanager.NewSession() if err != nil { log.Debugf("new session for %s: %v", p.label(), err) @@ -49,7 +51,7 @@ func (p *profile) extract(masterKeys masterkey.MasterKeys, categories []types.Ca p.extractCategory(data, cat, masterKeys, path) } if accountDB, ok := p.acquireAccountPasswords(session, categories); ok { - passwords, err := appendPasswords(masterKeys, accountDB, types.PasswordStoreAccount, data.Passwords) + passwords, err := appendPasswords(masterKeys, accountDB, record.StoreAccount, data.Passwords) if err != nil { log.Debugf("extract account passwords for %s: %v", p.label(), err) } else { @@ -60,7 +62,7 @@ func (p *profile) extract(masterKeys masterkey.MasterKeys, categories []types.Ca } // count counts entries per category without decryption. -func (p *profile) count(categories []types.Category) map[types.Category]int { +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) @@ -69,7 +71,7 @@ func (p *profile) count(categories []types.Category) map[types.Category]int { defer session.Cleanup() tempPaths := p.acquireFiles(session, categories) - counts := make(map[types.Category]int) + counts := make(map[category.Category]int) for _, cat := range categories { path, ok := tempPaths[cat] if !ok { @@ -81,7 +83,7 @@ func (p *profile) count(categories []types.Category) map[types.Category]int { if count, err := countPasswords(accountDB); err != nil { log.Debugf("count account passwords for %s: %v", p.label(), err) } else { - counts[types.Password] += count + counts[category.Password] += count } } return counts @@ -89,7 +91,7 @@ func (p *profile) count(categories []types.Category) map[types.Category]int { // 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 []types.Category) (string, bool) { +func (p *profile) acquireAccountPasswords(session *filemanager.Session, categories []category.Category) (string, bool) { accountPath, ok := p.accountPasswordPath(categories) if !ok { return "", false @@ -104,24 +106,24 @@ func (p *profile) acquireAccountPasswords(session *filemanager.Session, categori // primaryPasswordStore labels the resolved primary login DB: a profile that only ever synced // passwords has no local Login Data, so the account DB wins candidate resolution. -func (p *profile) primaryPasswordStore() string { - if primary, ok := p.sourcePaths[types.Password]; ok && primary.rel == accountLoginData { - return types.PasswordStoreAccount +func (p *profile) primaryPasswordStore() record.Store { + if primary, ok := p.sourcePaths[category.Password]; ok && primary.rel == accountLoginData { + return record.StoreAccount } - return types.PasswordStoreLocal + return record.StoreLocal } // 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 []types.Category) (string, bool) { +func (p *profile) accountPasswordPath(categories []category.Category) (string, bool) { requested := false for _, cat := range categories { - if cat == types.Password { + if cat == category.Password { requested = true break } } - primary, ok := p.sourcePaths[types.Password] + primary, ok := p.sourcePaths[category.Password] if !requested || !ok || primary.rel == accountLoginData || p.kind == types.ChromiumYandex { return "", false } @@ -131,8 +133,8 @@ func (p *profile) accountPasswordPath(categories []types.Category) (string, bool } // acquireFiles copies source files to the session temp directory. -func (p *profile) acquireFiles(session *filemanager.Session, categories []types.Category) map[types.Category]string { - tempPaths := make(map[types.Category]string) +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 { @@ -150,7 +152,7 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []types. // extractCategory calls the appropriate extract function for a category. A custom // extractor (registered via extractorsForKind) takes precedence over the switch. -func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, masterKeys masterkey.MasterKeys, path string) { +func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, masterKeys masterkey.MasterKeys, path string) { if ext, ok := p.extractors[cat]; ok { if err := ext.extract(masterKeys, path, data); err != nil { log.Debugf("extract %s for %s: %v", cat, p.label(), err) @@ -160,23 +162,23 @@ func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, m var err error switch cat { - case types.Password: + case category.Password: data.Passwords, err = extractPasswords(masterKeys, path, p.primaryPasswordStore()) - case types.Cookie: + case category.Cookie: data.Cookies, err = extractCookies(masterKeys, path) - case types.History: + case category.History: data.Histories, err = extractHistories(path) - case types.Download: + case category.Download: data.Downloads, err = extractDownloads(path) - case types.Bookmark: + case category.Bookmark: data.Bookmarks, err = extractBookmarks(path) - case types.CreditCard: + case category.CreditCard: data.CreditCards, err = extractCreditCards(masterKeys, path) - case types.Extension: + case category.Extension: data.Extensions, err = extractExtensions(path) - case types.LocalStorage: + case category.LocalStorage: data.LocalStorage, err = extractLocalStorage(path) - case types.SessionStorage: + case category.SessionStorage: data.SessionStorage, err = extractSessionStorage(path) } if err != nil { @@ -185,35 +187,35 @@ func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, m } // countCategory calls the appropriate count function for a category. -func (p *profile) countCategory(cat types.Category, path string) int { +func (p *profile) countCategory(cat category.Category, path string) int { var count int var err error switch cat { - case types.Password: + case category.Password: count, err = countPasswords(path) - case types.Cookie: + case category.Cookie: count, err = countCookies(path) - case types.History: + case category.History: count, err = countHistories(path) - case types.Download: + case category.Download: count, err = countDownloads(path) - case types.Bookmark: + case category.Bookmark: count, err = countBookmarks(path) - case types.CreditCard: + case category.CreditCard: if p.kind == types.ChromiumYandex { count, err = countYandexCreditCards(path) } else { count, err = countCreditCards(path) } - case types.Extension: + case category.Extension: if p.kind == types.ChromiumOpera { count, err = countOperaExtensions(path) } else { count, err = countExtensions(path) } - case types.LocalStorage: + case category.LocalStorage: count, err = countLocalStorage(path) - case types.SessionStorage: + case category.SessionStorage: count, err = countSessionStorage(path) } if err != nil { diff --git a/browser/chromium/profile_test.go b/browser/chromium/profile_test.go index 5c0bc24..67b6010 100644 --- a/browser/chromium/profile_test.go +++ b/browser/chromium/profile_test.go @@ -10,6 +10,8 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/filemanager" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -33,20 +35,20 @@ func TestExtractCategory_CustomExtractor(t *testing.T) { // Create a profile with a custom extractor that records it was called called := false testExtractor := extensionExtractor{ - fn: func(path string) ([]types.ExtensionEntry, error) { + fn: func(path string) ([]record.Extension, error) { called = true - return []types.ExtensionEntry{{Name: "custom", ID: "test-id"}}, nil + return []record.Extension{{Name: "custom", ID: "test-id"}}, nil }, } p := &profile{ - extractors: map[types.Category]categoryExtractor{ - types.Extension: testExtractor, + extractors: map[category.Category]categoryExtractor{ + category.Extension: testExtractor, }, } data := &types.BrowserData{} - p.extractCategory(data, types.Extension, masterkey.MasterKeys{}, "unused-path") + p.extractCategory(data, category.Extension, masterkey.MasterKeys{}, "unused-path") assert.True(t, called, "custom extractor should be called") require.Len(t, data.Extensions, 1) @@ -65,7 +67,7 @@ func TestExtractCategory_DefaultFallback(t *testing.T) { } data := &types.BrowserData{} - p.extractCategory(data, types.History, masterkey.MasterKeys{}, path) + p.extractCategory(data, category.History, masterkey.MasterKeys{}, path) require.Len(t, data.Histories, 1) assert.Equal(t, "Example", data.Histories[0].Title) @@ -85,7 +87,7 @@ func TestAcquireFiles(t *testing.T) { require.NoError(t, err) defer session.Cleanup() - cats := []types.Category{types.History, types.Cookie, types.Bookmark} + cats := []category.Category{category.History, category.Cookie, category.Bookmark} paths := p.acquireFiles(session, cats) assert.Len(t, paths, len(cats)) @@ -109,13 +111,14 @@ func TestExtractAndCountPasswords_MergesLocalAndAccountDatabases(t *testing.T) { kind: types.Chromium, sourcePaths: resolveSourcePaths(chromiumSources, profileDir), } - data := p.extract(masterkey.MasterKeys{}, []types.Category{types.Password}) + data := p.extract(masterkey.MasterKeys{}, []category.Category{category.Password}) require.Len(t, data.Passwords, 2) - assert.Equal(t, "account-user", data.Passwords[0].Username) - assert.Equal(t, types.PasswordStoreAccount, data.Passwords[0].Store) - assert.Equal(t, "local-user", data.Passwords[1].Username) - assert.Equal(t, types.PasswordStoreLocal, data.Passwords[1].Store) - assert.Equal(t, 2, p.count([]types.Category{types.Password})[types.Password]) + // 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 @@ -133,12 +136,12 @@ func TestExtractPasswords_IdenticalCredentialInBothStoresKeepsBoth(t *testing.T) kind: types.Chromium, sourcePaths: resolveSourcePaths(chromiumSources, profileDir), } - data := p.extract(masterkey.MasterKeys{}, []types.Category{types.Password}) + data := p.extract(masterkey.MasterKeys{}, []category.Category{category.Password}) require.Len(t, data.Passwords, 2) - stores := []string{data.Passwords[0].Store, data.Passwords[1].Store} - assert.ElementsMatch(t, []string{types.PasswordStoreLocal, types.PasswordStoreAccount}, stores) - assert.Equal(t, 2, p.count([]types.Category{types.Password})[types.Password]) + 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 @@ -155,31 +158,31 @@ func TestExtractAndCountPasswords_AccountDatabaseOnly(t *testing.T) { kind: types.Chromium, sourcePaths: resolveSourcePaths(chromiumSources, profileDir), } - data := p.extract(masterkey.MasterKeys{}, []types.Category{types.Password}) + data := p.extract(masterkey.MasterKeys{}, []category.Category{category.Password}) require.Len(t, data.Passwords, 1) assert.Equal(t, "account-user", data.Passwords[0].Username) - assert.Equal(t, types.PasswordStoreAccount, data.Passwords[0].Store) - assert.Equal(t, 1, p.count([]types.Category{types.Password})[types.Password]) + 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(types.History, path)) + 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(types.Cookie, path)) + 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(types.Bookmark, path)) + assert.Equal(t, 3, p.countCategory(category.Bookmark, path)) }) t.Run("Extension_Opera", func(t *testing.T) { @@ -191,11 +194,11 @@ func TestCountCategory(t *testing.T) { } }`) p := &profile{kind: types.ChromiumOpera} - assert.Equal(t, 1, p.countCategory(types.Extension, path)) + 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(types.History, "/nonexistent/path")) + assert.Equal(t, 0, p.countCategory(category.History, "/nonexistent/path")) }) } diff --git a/browser/chromium/source.go b/browser/chromium/source.go index 309f368..e158049 100644 --- a/browser/chromium/source.go +++ b/browser/chromium/source.go @@ -1,6 +1,8 @@ package chromium import ( + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -20,20 +22,20 @@ 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[types.Category][]sourcePath{ - types.Password: {file("Login Data"), file(accountLoginData)}, - types.Cookie: {file("Network/Cookies"), file("Cookies")}, - types.History: {file("History")}, - types.Download: {file("History")}, - types.Bookmark: {file("Bookmarks")}, - types.CreditCard: {file("Web Data")}, - types.Extension: {file("Secure Preferences")}, - types.LocalStorage: {dir("Local Storage/leveldb")}, - types.SessionStorage: {dir("Session Storage")}, +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[types.Category][]sourcePath { +func sourcesForKind(kind types.BrowserKind) map[category.Category][]sourcePath { switch kind { case types.ChromiumYandex: return yandexSources() @@ -56,7 +58,7 @@ type categoryExtractor interface { // passwordExtractor wraps a custom password extract function. type passwordExtractor struct { - fn func(masterKeys masterkey.MasterKeys, path string) ([]types.LoginEntry, error) + fn func(masterKeys masterkey.MasterKeys, path string) ([]record.Login, error) } func (e passwordExtractor) extract(masterKeys masterkey.MasterKeys, path string, data *types.BrowserData) error { @@ -67,7 +69,7 @@ func (e passwordExtractor) extract(masterKeys masterkey.MasterKeys, path string, // extensionExtractor wraps a custom extension extract function. type extensionExtractor struct { - fn func(path string) ([]types.ExtensionEntry, error) + fn func(path string) ([]record.Extension, error) } func (e extensionExtractor) extract(_ masterkey.MasterKeys, path string, data *types.BrowserData) error { @@ -79,7 +81,7 @@ func (e extensionExtractor) extract(_ masterkey.MasterKeys, path string, data *t // creditCardExtractor wraps a custom credit-card extract function, used by Yandex whose Ya Credit Cards DB stores // rows as records(guid, public_data, private_data) with JSON blobs rather than Chromium's flat credit_cards table. type creditCardExtractor struct { - fn func(masterKeys masterkey.MasterKeys, path string) ([]types.CreditCardEntry, error) + fn func(masterKeys masterkey.MasterKeys, path string) ([]record.CreditCard, error) } func (e creditCardExtractor) extract(masterKeys masterkey.MasterKeys, path string, data *types.BrowserData) error { @@ -90,13 +92,13 @@ func (e creditCardExtractor) extract(masterKeys masterkey.MasterKeys, path strin // operaExtractors overrides Extension extraction for Opera, // which stores settings under "extensions.opsettings". -var operaExtractors = map[types.Category]categoryExtractor{ - types.Extension: extensionExtractor{fn: extractOperaExtensions}, +var operaExtractors = map[category.Category]categoryExtractor{ + category.Extension: extensionExtractor{fn: extractOperaExtensions}, } // extractorsForKind returns custom category extractors for a browser kind. // nil means all categories use the default extractCategory switch logic. -func extractorsForKind(kind types.BrowserKind) map[types.Category]categoryExtractor { +func extractorsForKind(kind types.BrowserKind) map[category.Category]categoryExtractor { switch kind { case types.ChromiumYandex: return yandexExtractors diff --git a/browser/chromium/yandex.go b/browser/chromium/yandex.go index 2938c8d..1eb9d5d 100644 --- a/browser/chromium/yandex.go +++ b/browser/chromium/yandex.go @@ -11,18 +11,18 @@ import ( _ "modernc.org/sqlite" "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" ) // yandexSourceOverrides contains only the entries that differ from chromiumSources. -var yandexSourceOverrides = map[types.Category][]sourcePath{ - types.Password: {file("Ya Passman Data")}, - types.CreditCard: {file("Ya Credit Cards")}, +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[types.Category][]sourcePath { - sources := make(map[types.Category][]sourcePath, len(chromiumSources)) +func yandexSources() map[category.Category][]sourcePath { + sources := make(map[category.Category][]sourcePath, len(chromiumSources)) for k, v := range chromiumSources { sources[k] = v } @@ -34,9 +34,9 @@ func yandexSources() map[types.Category][]sourcePath { // yandexExtractors overrides Password and CreditCard extraction for Yandex, which wraps its data-encryption key inside // meta.local_encryptor_data, binds per-row AAD to GCM, and stores cards as JSON blobs in a records table. -var yandexExtractors = map[types.Category]categoryExtractor{ - types.Password: passwordExtractor{fn: extractYandexPasswords}, - types.CreditCard: creditCardExtractor{fn: extractYandexCreditCards}, +var yandexExtractors = map[category.Category]categoryExtractor{ + category.Password: passwordExtractor{fn: extractYandexPasswords}, + category.CreditCard: creditCardExtractor{fn: extractYandexCreditCards}, } // yandexLoginAAD is SHA1(origin_url \x00 username_element \x00 username_value \x00 password_element \x00 signon_realm), diff --git a/browser/firefox/extract_bookmark.go b/browser/firefox/extract_bookmark.go index 46d9f54..a51a39b 100644 --- a/browser/firefox/extract_bookmark.go +++ b/browser/firefox/extract_bookmark.go @@ -2,11 +2,10 @@ package firefox import ( "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -16,16 +15,16 @@ const ( INNER JOIN moz_places ON moz_bookmarks.fk=moz_places.id` ) -func extractBookmarks(path string) ([]types.BookmarkEntry, error) { +func extractBookmarks(path string) ([]record.Bookmark, error) { bookmarks, err := sqlitex.QueryRows(path, true, firefoxBookmarkQuery, - func(rows *sql.Rows) (types.BookmarkEntry, error) { + func(rows *sql.Rows) (record.Bookmark, error) { var id, dateAdded int64 var url, title string var bt int64 if err := rows.Scan(&id, &url, &bt, &dateAdded, &title); err != nil { - return types.BookmarkEntry{}, err + return record.Bookmark{}, err } - return types.BookmarkEntry{ + return record.Bookmark{ Name: title, URL: url, Folder: bookmarkType(bt), @@ -35,10 +34,6 @@ func extractBookmarks(path string) ([]types.BookmarkEntry, error) { if err != nil { return nil, err } - - sort.Slice(bookmarks, func(i, j int) bool { - return bookmarks[i].CreatedAt.After(bookmarks[j].CreatedAt) - }) return bookmarks, nil } diff --git a/browser/firefox/extract_bookmark_test.go b/browser/firefox/extract_bookmark_test.go index 8c0a28f..0f62b57 100644 --- a/browser/firefox/extract_bookmark_test.go +++ b/browser/firefox/extract_bookmark_test.go @@ -24,14 +24,14 @@ func TestExtractBookmarks(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Verify sort order: dateAdded descending - assert.Equal(t, "GitHub", got[0].Name) - assert.Equal(t, "Go Website", got[1].Name) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, "Go Website", got[0].Name) + assert.Equal(t, "GitHub", got[1].Name) // Verify field mapping - assert.Equal(t, "https://github.com", got[0].URL) - assert.Equal(t, "url", got[0].Folder) // type=1 → "url" - assert.False(t, got[0].CreatedAt.IsZero()) + assert.Equal(t, "https://github.com", got[1].URL) + assert.Equal(t, "url", got[1].Folder) // type=1 → "url" + assert.False(t, got[1].CreatedAt.IsZero()) } func TestCountBookmarks(t *testing.T) { diff --git a/browser/firefox/extract_cookie.go b/browser/firefox/extract_cookie.go index 2753c0a..fe1c6ce 100644 --- a/browser/firefox/extract_cookie.go +++ b/browser/firefox/extract_cookie.go @@ -2,11 +2,10 @@ package firefox import ( "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -15,9 +14,9 @@ const ( firefoxCountCookieQuery = `SELECT COUNT(*) FROM moz_cookies` ) -func extractCookies(path string) ([]types.CookieEntry, error) { +func extractCookies(path string) ([]record.Cookie, error) { cookies, err := sqlitex.QueryRows(path, true, firefoxCookieQuery, - func(rows *sql.Rows) (types.CookieEntry, error) { + func(rows *sql.Rows) (record.Cookie, error) { var ( name, value, host, cookiePath string isSecure, isHTTPOnly int @@ -26,7 +25,7 @@ func extractCookies(path string) ([]types.CookieEntry, error) { ) if err := rows.Scan(&name, &value, &host, &cookiePath, &createdAt, &expiry, &isSecure, &isHTTPOnly, &sameSite); err != nil { - return types.CookieEntry{}, err + return record.Cookie{}, err } hasExpire := expiry > 0 sameSiteStr := "unspecified" @@ -40,7 +39,7 @@ func extractCookies(path string) ([]types.CookieEntry, error) { case 256: // not specified by Set-Cookie } - return types.CookieEntry{ + return record.Cookie{ Name: name, Host: host, Path: cookiePath, @@ -57,10 +56,6 @@ func extractCookies(path string) ([]types.CookieEntry, error) { if err != nil { return nil, err } - - sort.Slice(cookies, func(i, j int) bool { - return cookies[i].CreatedAt.After(cookies[j].CreatedAt) - }) return cookies, nil } diff --git a/browser/firefox/extract_cookie_test.go b/browser/firefox/extract_cookie_test.go index 5286e25..fee2c80 100644 --- a/browser/firefox/extract_cookie_test.go +++ b/browser/firefox/extract_cookie_test.go @@ -22,21 +22,21 @@ func TestExtractCookies(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Verify sort order: creation time descending - assert.Equal(t, ".new.com", got[0].Host) - assert.Equal(t, ".example.com", got[1].Host) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, ".example.com", got[0].Host) + assert.Equal(t, ".new.com", got[1].Host) // Verify field mapping — Firefox cookies are plaintext - assert.Equal(t, "token", got[0].Name) - assert.Equal(t, "xyz789", got[0].Value) - assert.Equal(t, "/api", got[0].Path) - assert.True(t, got[0].IsSecure) - assert.False(t, got[0].IsHTTPOnly) - assert.True(t, got[0].HasExpire) // expiry > 0 - assert.True(t, got[0].IsPersistent) // expiry > 0 + assert.Equal(t, "token", got[1].Name) + assert.Equal(t, "xyz789", got[1].Value) + assert.Equal(t, "/api", got[1].Path) + assert.True(t, got[1].IsSecure) + assert.False(t, got[1].IsHTTPOnly) + assert.True(t, got[1].HasExpire) // expiry > 0 + assert.True(t, got[1].IsPersistent) // expiry > 0 - assert.Equal(t, "abc123", got[1].Value) - assert.True(t, got[1].IsHTTPOnly) + assert.Equal(t, "abc123", got[0].Value) + assert.True(t, got[0].IsHTTPOnly) } func TestCountCookies(t *testing.T) { diff --git a/browser/firefox/extract_download.go b/browser/firefox/extract_download.go index 0fbef5f..f84a59d 100644 --- a/browser/firefox/extract_download.go +++ b/browser/firefox/extract_download.go @@ -2,14 +2,13 @@ package firefox import ( "database/sql" - "sort" "strings" "github.com/tidwall/gjson" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -22,16 +21,16 @@ const ( GROUP BY place_id)` ) -func extractDownloads(path string) ([]types.DownloadEntry, error) { +func extractDownloads(path string) ([]record.Download, error) { downloads, err := sqlitex.QueryRows(path, true, firefoxDownloadQuery, - func(rows *sql.Rows) (types.DownloadEntry, error) { + func(rows *sql.Rows) (record.Download, error) { var placeID, dateAdded int64 var content, url string if err := rows.Scan(&placeID, &content, &url, &dateAdded); err != nil { - return types.DownloadEntry{}, err + return record.Download{}, err } - entry := types.DownloadEntry{ + entry := record.Download{ URL: url, StartTime: timeconv.UnixMicro(dateAdded), } @@ -53,10 +52,6 @@ func extractDownloads(path string) ([]types.DownloadEntry, error) { if err != nil { return nil, err } - - sort.Slice(downloads, func(i, j int) bool { - return downloads[i].StartTime.After(downloads[j].StartTime) - }) return downloads, nil } diff --git a/browser/firefox/extract_download_test.go b/browser/firefox/extract_download_test.go index 085dc58..29f264d 100644 --- a/browser/firefox/extract_download_test.go +++ b/browser/firefox/extract_download_test.go @@ -24,13 +24,13 @@ func TestExtractDownloads(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Verify sort order: StartTime descending - assert.Equal(t, "https://example.com/new.pdf", got[0].URL) - assert.Equal(t, "https://example.com/old.zip", got[1].URL) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, "https://example.com/old.zip", got[0].URL) + assert.Equal(t, "https://example.com/new.pdf", got[1].URL) // Verify field mapping - assert.Equal(t, "/tmp/new.pdf", got[0].TargetPath) - assert.False(t, got[0].StartTime.IsZero()) + assert.Equal(t, "/tmp/new.pdf", got[1].TargetPath) + assert.False(t, got[1].StartTime.IsZero()) } func TestCountDownloads(t *testing.T) { diff --git a/browser/firefox/extract_extension.go b/browser/firefox/extract_extension.go index 4a14109..f1b345a 100644 --- a/browser/firefox/extract_extension.go +++ b/browser/firefox/extract_extension.go @@ -5,16 +5,16 @@ import ( "github.com/tidwall/gjson" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractExtensions(path string) ([]types.ExtensionEntry, error) { +func extractExtensions(path string) ([]record.Extension, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } - var extensions []types.ExtensionEntry + var extensions []record.Extension for _, v := range gjson.GetBytes(data, "addons").Array() { // Only include user-installed extensions // https://searchfox.org/mozilla-central/source/toolkit/mozapps/extensions/internal/XPIDatabase.jsm#157 @@ -22,7 +22,7 @@ func extractExtensions(path string) ([]types.ExtensionEntry, error) { continue } - extensions = append(extensions, types.ExtensionEntry{ + extensions = append(extensions, record.Extension{ Name: v.Get("defaultLocale.name").String(), ID: v.Get("id").String(), Description: v.Get("defaultLocale.description").String(), diff --git a/browser/firefox/extract_history.go b/browser/firefox/extract_history.go index 014d6dc..9aa33f8 100644 --- a/browser/firefox/extract_history.go +++ b/browser/firefox/extract_history.go @@ -2,11 +2,10 @@ package firefox import ( "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -15,16 +14,16 @@ const ( firefoxCountHistoryQuery = `SELECT COUNT(*) FROM moz_places` ) -func extractHistories(path string) ([]types.HistoryEntry, error) { +func extractHistories(path string) ([]record.History, error) { histories, err := sqlitex.QueryRows(path, true, firefoxHistoryQuery, - func(rows *sql.Rows) (types.HistoryEntry, error) { + func(rows *sql.Rows) (record.History, error) { var url, title string var visitCount int var lastVisit int64 if err := rows.Scan(&url, &lastVisit, &title, &visitCount); err != nil { - return types.HistoryEntry{}, err + return record.History{}, err } - return types.HistoryEntry{ + return record.History{ URL: url, Title: title, VisitCount: visitCount, @@ -34,10 +33,6 @@ func extractHistories(path string) ([]types.HistoryEntry, error) { if err != nil { return nil, err } - - sort.Slice(histories, func(i, j int) bool { - return histories[i].VisitCount < histories[j].VisitCount - }) return histories, nil } diff --git a/browser/firefox/extract_history_test.go b/browser/firefox/extract_history_test.go index bcbc792..2b75e55 100644 --- a/browser/firefox/extract_history_test.go +++ b/browser/firefox/extract_history_test.go @@ -23,15 +23,15 @@ func TestExtractHistories(t *testing.T) { require.NoError(t, err) require.Len(t, got, 3) - // Verify sort order: visit count ascending (Firefox convention) - assert.Equal(t, 50, got[0].VisitCount) - assert.Equal(t, 100, got[1].VisitCount) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, 100, got[0].VisitCount) + assert.Equal(t, 50, got[1].VisitCount) assert.Equal(t, 200, got[2].VisitCount) - // Verify field mapping (first = least visited) - assert.Equal(t, "https://go.dev", got[0].URL) - assert.Equal(t, "Go", got[0].Title) - assert.False(t, got[0].LastVisit.IsZero()) + // Verify field mapping + assert.Equal(t, "https://go.dev", got[1].URL) + assert.Equal(t, "Go", got[1].Title) + assert.False(t, got[1].LastVisit.IsZero()) } func TestCountHistories(t *testing.T) { diff --git a/browser/firefox/extract_password.go b/browser/firefox/extract_password.go index 1564e30..adedecc 100644 --- a/browser/firefox/extract_password.go +++ b/browser/firefox/extract_password.go @@ -4,14 +4,13 @@ import ( "encoding/base64" "fmt" "os" - "sort" "github.com/tidwall/gjson" "github.com/moond4rk/hackbrowserdata/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) func countPasswords(path string) (int, error) { @@ -39,13 +38,13 @@ func decryptPBE(encoded string, masterKey []byte) ([]byte, error) { return plaintext, nil } -func extractPasswords(masterKey []byte, path string) ([]types.LoginEntry, error) { +func extractPasswords(masterKey []byte, path string) ([]record.Login, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } - var logins []types.LoginEntry + var logins []record.Login var decryptFails int var lastErr error for _, v := range gjson.GetBytes(data, "logins").Array() { @@ -65,20 +64,16 @@ func extractPasswords(masterKey []byte, path string) ([]types.LoginEntry, error) lastErr = err } - logins = append(logins, types.LoginEntry{ + logins = append(logins, record.Login{ URL: url, Username: string(user), Password: string(pwd), CreatedAt: timeconv.UnixMilli(v.Get("timeCreated").Int()), - Store: types.PasswordStoreLocal, + Store: record.StoreLocal, }) } if decryptFails > 0 { log.Debugf("decrypt firefox login fields: %d failed: %v", decryptFails, lastErr) } - - sort.Slice(logins, func(i, j int) bool { - return logins[i].CreatedAt.After(logins[j].CreatedAt) - }) return logins, nil } diff --git a/browser/firefox/extract_storage.go b/browser/firefox/extract_storage.go index f20ee9f..9c9527f 100644 --- a/browser/firefox/extract_storage.go +++ b/browser/firefox/extract_storage.go @@ -5,8 +5,8 @@ import ( "fmt" "strings" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -14,14 +14,14 @@ const ( firefoxCountLocalStorageQuery = `SELECT COUNT(*) FROM webappsstore2` ) -func extractLocalStorage(path string) ([]types.StorageEntry, error) { +func extractLocalStorage(path string) ([]record.LocalStorage, error) { return sqlitex.QueryRows(path, true, firefoxLocalStorageQuery, - func(rows *sql.Rows) (types.StorageEntry, error) { + func(rows *sql.Rows) (record.LocalStorage, error) { var originKey, key, value string if err := rows.Scan(&originKey, &key, &value); err != nil { - return types.StorageEntry{}, err + return record.LocalStorage{}, err } - return types.StorageEntry{ + return record.LocalStorage{ URL: parseOriginKey(originKey), Key: key, Value: value, diff --git a/browser/firefox/firefox.go b/browser/firefox/firefox.go index 767bb41..58034d6 100644 --- a/browser/firefox/firefox.go +++ b/browser/firefox/firefox.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -53,7 +54,7 @@ func (b *Browser) Profiles() []types.Profile { } // Extract extracts every profile, deriving each profile's key independently. -func (b *Browser) Extract(categories []types.Category) ([]types.ExtractResult, error) { +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{ @@ -65,7 +66,7 @@ func (b *Browser) Extract(categories []types.Category) ([]types.ExtractResult, e } // CountEntries counts entries per category for every profile without decryption. -func (b *Browser) CountEntries(categories []types.Category) ([]types.CountResult, error) { +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{ @@ -114,7 +115,7 @@ type resolvedPath struct { // 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[types.Category][]sourcePath) []string { +func discoverProfiles(userDataDir string, sources map[category.Category][]sourcePath) []string { entries, err := os.ReadDir(userDataDir) if err != nil { return nil @@ -134,7 +135,7 @@ func discoverProfiles(userDataDir string, sources map[types.Category][]sourcePat } // hasAnySource checks if dir contains at least one source file or directory. -func hasAnySource(sources map[types.Category][]sourcePath, dir string) bool { +func hasAnySource(sources map[category.Category][]sourcePath, dir string) bool { for _, candidates := range sources { for _, sp := range candidates { abs := filepath.Join(dir, sp.rel) @@ -148,8 +149,8 @@ func hasAnySource(sources map[types.Category][]sourcePath, dir string) bool { // resolveSourcePaths checks which sources actually exist in profileDir. // Candidates are tried in priority order; the first existing path wins. -func resolveSourcePaths(sources map[types.Category][]sourcePath, profileDir string) map[types.Category]resolvedPath { - resolved := make(map[types.Category]resolvedPath) +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) diff --git a/browser/firefox/firefox_test.go b/browser/firefox/firefox_test.go index d1f76d6..afbaf9a 100644 --- a/browser/firefox/firefox_test.go +++ b/browser/firefox/firefox_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -147,19 +148,19 @@ func TestResolveSourcePaths(t *testing.T) { resolved := resolveSourcePaths(firefoxSources, profileDir) // All categories should be resolved - for _, cat := range []types.Category{ - types.Password, types.Cookie, types.History, - types.Download, types.Bookmark, types.Extension, types.LocalStorage, + 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[types.History].absPath, resolved[types.Download].absPath) - assert.Equal(t, resolved[types.History].absPath, resolved[types.Bookmark].absPath) + 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[types.Password].absPath, resolved[types.History].absPath) + assert.NotEqual(t, resolved[category.Password].absPath, resolved[category.History].absPath) } func TestResolveSourcePaths_Partial(t *testing.T) { @@ -167,14 +168,14 @@ func TestResolveSourcePaths_Partial(t *testing.T) { resolved := resolveSourcePaths(firefoxSources, profileDir) // Only places.sqlite exists → History, Download, Bookmark resolved - assert.Contains(t, resolved, types.History) - assert.Contains(t, resolved, types.Download) - assert.Contains(t, resolved, types.Bookmark) + 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, types.Password) - assert.NotContains(t, resolved, types.Cookie) - assert.NotContains(t, resolved, types.Extension) + assert.NotContains(t, resolved, category.Password) + assert.NotContains(t, resolved, category.Cookie) + assert.NotContains(t, resolved, category.Extension) } // --------------------------------------------------------------------------- @@ -194,8 +195,8 @@ func TestCountEntries(t *testing.T) { require.NotNil(t, b) // CountEntries works without master key. - results, err := b.CountEntries([]types.Category{types.History}) + results, err := b.CountEntries([]category.Category{category.History}) require.NoError(t, err) require.Len(t, results, 1) - assert.Equal(t, 3, results[0].Counts[types.History]) + assert.Equal(t, 3, results[0].Counts[category.History]) } diff --git a/browser/firefox/profile.go b/browser/firefox/profile.go index eee4fcb..da33202 100644 --- a/browser/firefox/profile.go +++ b/browser/firefox/profile.go @@ -5,6 +5,7 @@ import ( "path/filepath" "github.com/moond4rk/hackbrowserdata/filemanager" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" @@ -15,7 +16,7 @@ import ( type profile struct { profileDir string browserName string - sourcePaths map[types.Category]resolvedPath + sourcePaths map[category.Category]resolvedPath } func (p *profile) name() string { @@ -29,7 +30,7 @@ func (p *profile) label() string { return p.browserName + "/" + p.name() } // extract copies the profile's source files to a temp directory, derives the // per-profile master key, and extracts the requested categories. -func (p *profile) extract(categories []types.Category) *types.BrowserData { +func (p *profile) extract(categories []category.Category) *types.BrowserData { session, err := filemanager.NewSession() if err != nil { log.Debugf("new session for %s: %v", p.label(), err) @@ -55,7 +56,7 @@ func (p *profile) extract(categories []types.Category) *types.BrowserData { return data } -func (p *profile) count(categories []types.Category) map[types.Category]int { +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) @@ -64,7 +65,7 @@ func (p *profile) count(categories []types.Category) map[types.Category]int { defer session.Cleanup() tempPaths := p.acquireFiles(session, categories) - counts := make(map[types.Category]int) + counts := make(map[category.Category]int) for _, cat := range categories { path, ok := tempPaths[cat] if !ok { @@ -75,8 +76,8 @@ func (p *profile) count(categories []types.Category) map[types.Category]int { return counts } -func (p *profile) acquireFiles(session *filemanager.Session, categories []types.Category) map[types.Category]string { - tempPaths := make(map[types.Category]string) +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 { @@ -96,7 +97,7 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []types. // key4.db. The key is derived via NSS ASN1 PBE decryption (platform-agnostic). // If logins.json was already acquired by acquireFiles, the derived key is // validated by attempting to decrypt an actual login entry. -func (p *profile) getMasterKey(session *filemanager.Session, tempPaths map[types.Category]string) ([]byte, error) { +func (p *profile) getMasterKey(session *filemanager.Session, tempPaths map[category.Category]string) ([]byte, error) { key4Src := filepath.Join(p.profileDir, "key4.db") if !fileutil.FileExists(key4Src) { return nil, nil @@ -108,28 +109,28 @@ func (p *profile) getMasterKey(session *filemanager.Session, tempPaths map[types // logins.json is already acquired by acquireFiles as the Password source; // reuse it for master key validation if available. - loginsPath := tempPaths[types.Password] + loginsPath := tempPaths[category.Password] return retrieveMasterKey(key4Dst, loginsPath) } -func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, masterKey []byte, path string) { +func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, masterKey []byte, path string) { var err error switch cat { - case types.Password: + case category.Password: data.Passwords, err = extractPasswords(masterKey, path) - case types.Cookie: + case category.Cookie: data.Cookies, err = extractCookies(path) - case types.History: + case category.History: data.Histories, err = extractHistories(path) - case types.Download: + case category.Download: data.Downloads, err = extractDownloads(path) - case types.Bookmark: + case category.Bookmark: data.Bookmarks, err = extractBookmarks(path) - case types.Extension: + case category.Extension: data.Extensions, err = extractExtensions(path) - case types.LocalStorage: + case category.LocalStorage: data.LocalStorage, err = extractLocalStorage(path) - case types.CreditCard, types.SessionStorage: + case category.CreditCard, category.SessionStorage: // Firefox does not support CreditCard or SessionStorage extraction. } if err != nil { @@ -137,25 +138,25 @@ func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, m } } -func (p *profile) countCategory(cat types.Category, path string) int { +func (p *profile) countCategory(cat category.Category, path string) int { var count int var err error switch cat { - case types.Password: + case category.Password: count, err = countPasswords(path) - case types.Cookie: + case category.Cookie: count, err = countCookies(path) - case types.History: + case category.History: count, err = countHistories(path) - case types.Download: + case category.Download: count, err = countDownloads(path) - case types.Bookmark: + case category.Bookmark: count, err = countBookmarks(path) - case types.Extension: + case category.Extension: count, err = countExtensions(path) - case types.LocalStorage: + case category.LocalStorage: count, err = countLocalStorage(path) - case types.CreditCard, types.SessionStorage: + case category.CreditCard, category.SessionStorage: // Firefox does not support CreditCard or SessionStorage. } if err != nil { diff --git a/browser/firefox/profile_test.go b/browser/firefox/profile_test.go index fd1a6fc..5ce5baa 100644 --- a/browser/firefox/profile_test.go +++ b/browser/firefox/profile_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -13,31 +14,31 @@ func TestCountCategory(t *testing.T) { t.Run("History", func(t *testing.T) { path := setupMozHistoryDB(t) p := &profile{} - assert.Equal(t, 3, p.countCategory(types.History, path)) + 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(types.Cookie, path)) + 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(types.Bookmark, path)) + 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(types.Extension, path)) + assert.Equal(t, 2, p.countCategory(category.Extension, path)) }) t.Run("UnsupportedCategory", func(t *testing.T) { p := &profile{} - assert.Equal(t, 0, p.countCategory(types.CreditCard, "unused")) - assert.Equal(t, 0, p.countCategory(types.SessionStorage, "unused")) + assert.Equal(t, 0, p.countCategory(category.CreditCard, "unused")) + assert.Equal(t, 0, p.countCategory(category.SessionStorage, "unused")) }) } @@ -55,12 +56,10 @@ func TestExtractCategory(t *testing.T) { ) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.History, nil, path) + p.extractCategory(data, category.History, nil, path) require.Len(t, data.Histories, 2) - // Firefox sorts by visit count ascending - assert.Equal(t, 1, data.Histories[0].VisitCount) - assert.Equal(t, 3, data.Histories[1].VisitCount) + assert.ElementsMatch(t, []int{3, 1}, []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount}) }) t.Run("Cookie", func(t *testing.T) { @@ -70,7 +69,7 @@ func TestExtractCategory(t *testing.T) { ) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.Cookie, nil, path) + p.extractCategory(data, category.Cookie, nil, path) require.Len(t, data.Cookies, 1) assert.Equal(t, "session", data.Cookies[0].Name) @@ -85,7 +84,7 @@ func TestExtractCategory(t *testing.T) { ) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.Bookmark, nil, path) + p.extractCategory(data, category.Bookmark, nil, path) require.Len(t, data.Bookmarks, 1) assert.Equal(t, "GitHub", data.Bookmarks[0].Name) @@ -110,7 +109,7 @@ func TestExtractCategory(t *testing.T) { }`) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.Extension, nil, path) + p.extractCategory(data, category.Extension, nil, path) require.Len(t, data.Extensions, 1) // system extension skipped assert.Equal(t, "uBlock Origin", data.Extensions[0].Name) @@ -120,8 +119,8 @@ func TestExtractCategory(t *testing.T) { p := &profile{} data := &types.BrowserData{} // CreditCard and SessionStorage are not supported by Firefox - p.extractCategory(data, types.CreditCard, nil, "unused") - p.extractCategory(data, types.SessionStorage, nil, "unused") + p.extractCategory(data, category.CreditCard, nil, "unused") + p.extractCategory(data, category.SessionStorage, nil, "unused") assert.Empty(t, data.CreditCards) assert.Empty(t, data.SessionStorage) }) diff --git a/browser/firefox/source.go b/browser/firefox/source.go index 29126c5..10ff977 100644 --- a/browser/firefox/source.go +++ b/browser/firefox/source.go @@ -3,7 +3,7 @@ package firefox import ( "path/filepath" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" ) // sourcePath describes a single candidate location for browser data, @@ -19,12 +19,12 @@ func file(rel string) sourcePath { return sourcePath{rel: filepath.FromSlash(rel // 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[types.Category][]sourcePath{ - types.Password: {file("logins.json")}, - types.Cookie: {file("cookies.sqlite")}, - types.History: {file("places.sqlite")}, - types.Download: {file("places.sqlite")}, - types.Bookmark: {file("places.sqlite")}, - types.Extension: {file("extensions.json")}, - types.LocalStorage: {file("webappsstore.sqlite")}, +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/keydump_test.go b/browser/keydump_test.go index ae8e500..b75768c 100644 --- a/browser/keydump_test.go +++ b/browser/keydump_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -37,11 +38,11 @@ func (m *mockBrowser) Profiles() []types.Profile { return out } -func (m *mockBrowser) Extract(_ []types.Category) ([]types.ExtractResult, error) { +func (m *mockBrowser) Extract(_ []category.Category) ([]types.ExtractResult, error) { return nil, nil } -func (m *mockBrowser) CountEntries(_ []types.Category) ([]types.CountResult, error) { +func (m *mockBrowser) CountEntries(_ []category.Category) ([]types.CountResult, error) { return nil, nil } diff --git a/browser/safari/extract_bookmark.go b/browser/safari/extract_bookmark.go index 68c1c0c..72e0660 100644 --- a/browser/safari/extract_bookmark.go +++ b/browser/safari/extract_bookmark.go @@ -7,7 +7,7 @@ import ( "github.com/moond4rk/plist" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) // safariBookmark mirrors the plist structure of Safari's Bookmarks.plist. @@ -28,7 +28,7 @@ const ( bookmarkTypeList = "WebBookmarkTypeList" ) -func extractBookmarks(path string) ([]types.BookmarkEntry, error) { +func extractBookmarks(path string) ([]record.Bookmark, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("open bookmarks: %w", err) @@ -40,13 +40,13 @@ func extractBookmarks(path string) ([]types.BookmarkEntry, error) { return nil, fmt.Errorf("decode bookmarks: %w", err) } - var bookmarks []types.BookmarkEntry + var bookmarks []record.Bookmark walkBookmarks(root.Children, "", &bookmarks) return bookmarks, nil } // walkBookmarks recursively traverses the bookmark tree, collecting leaf entries. -func walkBookmarks(nodes []safariBookmark, folder string, out *[]types.BookmarkEntry) { +func walkBookmarks(nodes []safariBookmark, folder string, out *[]record.Bookmark) { for i, node := range nodes { switch node.Type { case bookmarkTypeLeaf: @@ -57,7 +57,7 @@ func walkBookmarks(nodes []safariBookmark, folder string, out *[]types.BookmarkE if node.URLString == "" { continue } - *out = append(*out, types.BookmarkEntry{ + *out = append(*out, record.Bookmark{ ID: int64(i), Name: title, URL: node.URLString, diff --git a/browser/safari/extract_cookie.go b/browser/safari/extract_cookie.go index b06f694..ef548ec 100644 --- a/browser/safari/extract_cookie.go +++ b/browser/safari/extract_cookie.go @@ -3,26 +3,25 @@ package safari import ( "fmt" "os" - "sort" "github.com/moond4rk/binarycookies" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractCookies(path string) ([]types.CookieEntry, error) { +func extractCookies(path string) ([]record.Cookie, error) { pages, err := decodeBinaryCookies(path) if err != nil { return nil, err } - var cookies []types.CookieEntry + var cookies []record.Cookie for _, page := range pages { for _, c := range page.Cookies { hasExpire := !c.Expires.IsZero() // binarycookies returns time.Time in Local; normalize to UTC // so exported JSON matches Chromium/Firefox cookie output. - cookies = append(cookies, types.CookieEntry{ + cookies = append(cookies, record.Cookie{ Host: string(c.Domain), Path: string(c.Path), Name: string(c.Name), @@ -36,10 +35,6 @@ func extractCookies(path string) ([]types.CookieEntry, error) { }) } } - - sort.Slice(cookies, func(i, j int) bool { - return cookies[i].CreatedAt.After(cookies[j].CreatedAt) - }) return cookies, nil } diff --git a/browser/safari/extract_cookie_test.go b/browser/safari/extract_cookie_test.go index 8315752..c5ca6b2 100644 --- a/browser/safari/extract_cookie_test.go +++ b/browser/safari/extract_cookie_test.go @@ -133,12 +133,12 @@ func TestExtractCookies(t *testing.T) { require.NoError(t, err) require.Len(t, cookies, 2) - // Sorted by CreatedAt descending (newest first) - assert.Equal(t, ".go.dev", cookies[0].Host) - assert.Equal(t, ".example.com", cookies[1].Host) + // Cookies keep the file's order; the exporter sorts them. + assert.Equal(t, ".example.com", cookies[0].Host) + assert.Equal(t, ".go.dev", cookies[1].Host) // Verify field mapping - c := cookies[1] // .example.com cookie + c := cookies[0] // .example.com cookie assert.Equal(t, "session", c.Name) assert.Equal(t, "abc123", c.Value) assert.Equal(t, "/", c.Path) diff --git a/browser/safari/extract_download.go b/browser/safari/extract_download.go index c3fb117..717e240 100644 --- a/browser/safari/extract_download.go +++ b/browser/safari/extract_download.go @@ -6,7 +6,7 @@ import ( "github.com/moond4rk/plist" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) type safariDownloads struct { @@ -25,7 +25,7 @@ type safariDownloadEntry struct { // extractDownloads reads Downloads.plist (shared across Safari profiles) and returns only the entries // owned by ownerUUID — either "DefaultProfile" or a named profile's uppercase UUID. Entries written by // older Safari (no ProfileUUID field) are attributed to the default profile. -func extractDownloads(path, ownerUUID string) ([]types.DownloadEntry, error) { +func extractDownloads(path, ownerUUID string) ([]record.Download, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("open downloads: %w", err) @@ -37,12 +37,12 @@ func extractDownloads(path, ownerUUID string) ([]types.DownloadEntry, error) { return nil, fmt.Errorf("decode downloads: %w", err) } - var downloads []types.DownloadEntry + var downloads []record.Download for _, d := range dl.DownloadHistory { if !ownsDownload(d.ProfileUUID, ownerUUID) { continue } - downloads = append(downloads, types.DownloadEntry{ + downloads = append(downloads, record.Download{ URL: d.URL, TargetPath: d.Path, TotalBytes: d.TotalBytes, diff --git a/browser/safari/extract_extension.go b/browser/safari/extract_extension.go index fd043f2..abc13e2 100644 --- a/browser/safari/extract_extension.go +++ b/browser/safari/extract_extension.go @@ -10,7 +10,7 @@ import ( "github.com/moond4rk/plist" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) // Safari keeps extensions in two sibling plists under the container's Safari dir: @@ -32,7 +32,7 @@ const ( var extensionKeyPattern = regexp.MustCompile(`^(\S+)\s+\(([^)]+)\)$`) // safariExtension mirrors the per-extension dict value in Extensions.plist. -// Only fields that map onto types.ExtensionEntry are decoded; richer fields +// Only fields that map onto record.Extension are decoded; richer fields // (Permissions, AccessibleOrigins, …) are intentionally ignored for the // minimum implementation. type safariExtension struct { @@ -43,15 +43,15 @@ type safariExtension struct { // WebExtensions/Extensions.plist from the profile's Safari container and // returns the merged list, sorted by key for deterministic output. // A missing plist on either side is skipped silently. -func extractExtensions(container string) ([]types.ExtensionEntry, error) { +func extractExtensions(container string) ([]record.Extension, error) { records, err := readSafariExtensions(container) if err != nil { return nil, err } - extensions := make([]types.ExtensionEntry, 0, len(records)) + extensions := make([]record.Extension, 0, len(records)) for _, r := range records { - extensions = append(extensions, types.ExtensionEntry{ + extensions = append(extensions, record.Extension{ Name: r.bundleID, ID: r.key, Enabled: r.enabled, diff --git a/browser/safari/extract_history.go b/browser/safari/extract_history.go index 736abfe..9e5bd0b 100644 --- a/browser/safari/extract_history.go +++ b/browser/safari/extract_history.go @@ -2,11 +2,10 @@ package safari import ( "database/sql" - "sort" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/types" ) const ( @@ -24,18 +23,18 @@ const ( safariCountHistoryQuery = `SELECT COUNT(*) FROM history_items` ) -func extractHistories(path string) ([]types.HistoryEntry, error) { +func extractHistories(path string) ([]record.History, error) { histories, err := sqlitex.QueryRows(path, true, safariHistoryQuery, - func(rows *sql.Rows) (types.HistoryEntry, error) { + func(rows *sql.Rows) (record.History, error) { var ( url, title string visitCount int visitTime float64 ) if err := rows.Scan(&url, &title, &visitCount, &visitTime); err != nil { - return types.HistoryEntry{}, err + return record.History{}, err } - return types.HistoryEntry{ + return record.History{ URL: url, Title: title, VisitCount: visitCount, @@ -45,10 +44,6 @@ func extractHistories(path string) ([]types.HistoryEntry, error) { if err != nil { return nil, err } - - sort.Slice(histories, func(i, j int) bool { - return histories[i].VisitCount > histories[j].VisitCount - }) return histories, nil } diff --git a/browser/safari/extract_history_test.go b/browser/safari/extract_history_test.go index fd13ead..7846ff7 100644 --- a/browser/safari/extract_history_test.go +++ b/browser/safari/extract_history_test.go @@ -29,16 +29,16 @@ func TestExtractHistories(t *testing.T) { require.NoError(t, err) require.Len(t, got, 3) - // Sorted by visit count descending (most visited first). - assert.Equal(t, 200, got[0].VisitCount) - assert.Equal(t, 100, got[1].VisitCount) - assert.Equal(t, 50, got[2].VisitCount) + // Rows keep the database's order; the exporter sorts them. + assert.Equal(t, 100, got[0].VisitCount) + assert.Equal(t, 50, got[1].VisitCount) + assert.Equal(t, 200, got[2].VisitCount) // Verify field mapping. - assert.Equal(t, "https://example.com", got[0].URL) - assert.Equal(t, "https://github.com", got[1].URL) - assert.Equal(t, "https://go.dev", got[2].URL) - assert.False(t, got[0].LastVisit.IsZero()) + assert.Equal(t, "https://github.com", got[0].URL) + assert.Equal(t, "https://go.dev", got[1].URL) + assert.Equal(t, "https://example.com", got[2].URL) + assert.False(t, got[2].LastVisit.IsZero()) } func TestExtractHistories_Dedup(t *testing.T) { diff --git a/browser/safari/extract_password.go b/browser/safari/extract_password.go index f1dc1b2..a81fd65 100644 --- a/browser/safari/extract_password.go +++ b/browser/safari/extract_password.go @@ -2,39 +2,34 @@ package safari import ( "fmt" - "sort" "strings" "github.com/moond4rk/keychainbreaker" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractPasswords(keychainPassword string) ([]types.LoginEntry, error) { +func extractPasswords(keychainPassword string) ([]record.Login, error) { passwords, err := getInternetPasswords(keychainPassword) if err != nil { return nil, err } - var logins []types.LoginEntry + var logins []record.Login for _, p := range passwords { url := buildURL(p.Protocol, p.Server, p.Port, p.Path) if url == "" || p.Account == "" { continue } - logins = append(logins, types.LoginEntry{ + logins = append(logins, record.Login{ URL: url, Username: p.Account, Password: p.PlainPassword, CreatedAt: p.Created.UTC(), - Store: types.PasswordStoreLocal, + Store: record.StoreLocal, }) } - - sort.Slice(logins, func(i, j int) bool { - return logins[i].CreatedAt.After(logins[j].CreatedAt) - }) return logins, nil } diff --git a/browser/safari/extract_storage.go b/browser/safari/extract_storage.go index b5c2f29..7894faa 100644 --- a/browser/safari/extract_storage.go +++ b/browser/safari/extract_storage.go @@ -11,7 +11,7 @@ import ( _ "modernc.org/sqlite" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/record" ) // Modern WebKit (Safari 17+) stores localStorage under a nested, partitioned layout rooted at @@ -52,13 +52,13 @@ const ( originPortExplicitFlag = 0x01 ) -func extractLocalStorage(root string) ([]types.StorageEntry, error) { +func extractLocalStorage(root string) ([]record.LocalStorage, error) { dirs, err := findOriginDataDirs(root) if err != nil { return nil, err } - var entries []types.StorageEntry + var entries []record.LocalStorage for _, od := range dirs { origin, err := readOriginFile(filepath.Join(od, webkitOriginFile)) if err != nil { @@ -72,7 +72,7 @@ func extractLocalStorage(root string) ([]types.StorageEntry, error) { continue } for _, it := range items { - entries = append(entries, types.StorageEntry{ + entries = append(entries, record.LocalStorage{ URL: origin, Key: it.key, Value: it.value, diff --git a/browser/safari/profile.go b/browser/safari/profile.go index fab9557..c69055f 100644 --- a/browser/safari/profile.go +++ b/browser/safari/profile.go @@ -4,6 +4,7 @@ import ( "path/filepath" "github.com/moond4rk/hackbrowserdata/filemanager" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/types" ) @@ -13,7 +14,7 @@ import ( type profile struct { ctx profileContext browserName string - sourcePaths map[types.Category]resolvedPath + sourcePaths map[category.Category]resolvedPath } func (p *profile) name() string { return p.ctx.name } @@ -26,7 +27,7 @@ func (p *profile) dir() string { return filepath.Join(p.ctx.container, "Safari", "Profiles", p.ctx.uuidUpper) } -func (p *profile) extract(categories []types.Category, keychainPassword string) *types.BrowserData { +func (p *profile) extract(categories []category.Category, keychainPassword string) *types.BrowserData { session, err := filemanager.NewSession() if err != nil { log.Debugf("new session for %s: %v", p.label(), err) @@ -39,7 +40,7 @@ func (p *profile) extract(categories []types.Category, keychainPassword string) data := &types.BrowserData{} for _, cat := range categories { // Keychain is user-scope, not per-profile — attribute only to default to avoid duplicates. - if cat == types.Password { + if cat == category.Password { if p.ctx.isDefault() { p.extractCategory(data, cat, "", keychainPassword) } @@ -47,7 +48,7 @@ func (p *profile) extract(categories []types.Category, keychainPassword string) } // Extension plists (AppExtensions + WebExtensions) live directly in the container // and are read in-place; attribute to default only until per-profile layouts are verified. - if cat == types.Extension { + if cat == category.Extension { if p.ctx.isDefault() { p.extractCategory(data, cat, "", keychainPassword) } @@ -62,7 +63,7 @@ func (p *profile) extract(categories []types.Category, keychainPassword string) return data } -func (p *profile) count(categories []types.Category, keychainPassword string) map[types.Category]int { +func (p *profile) count(categories []category.Category, keychainPassword string) map[category.Category]int { session, err := filemanager.NewSession() if err != nil { log.Debugf("new session for %s: %v", p.label(), err) @@ -72,15 +73,15 @@ func (p *profile) count(categories []types.Category, keychainPassword string) ma tempPaths := p.acquireFiles(session, categories) - counts := make(map[types.Category]int) + counts := make(map[category.Category]int) for _, cat := range categories { - if cat == types.Password { + if cat == category.Password { if p.ctx.isDefault() { counts[cat] = p.countCategory(cat, "", keychainPassword) } continue } - if cat == types.Extension { + if cat == category.Extension { if p.ctx.isDefault() { counts[cat] = p.countCategory(cat, "", keychainPassword) } @@ -95,8 +96,8 @@ func (p *profile) count(categories []types.Category, keychainPassword string) ma return counts } -func (p *profile) acquireFiles(session *filemanager.Session, categories []types.Category) map[types.Category]string { - tempPaths := make(map[types.Category]string) +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 { @@ -112,22 +113,22 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []types. return tempPaths } -func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, path, keychainPassword string) { +func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, path, keychainPassword string) { var err error switch cat { - case types.Password: + case category.Password: data.Passwords, err = extractPasswords(keychainPassword) - case types.History: + case category.History: data.Histories, err = extractHistories(path) - case types.Cookie: + case category.Cookie: data.Cookies, err = extractCookies(path) - case types.Bookmark: + case category.Bookmark: data.Bookmarks, err = extractBookmarks(path) - case types.Download: + case category.Download: data.Downloads, err = extractDownloads(path, p.ctx.downloadOwnerUUID()) - case types.LocalStorage: + case category.LocalStorage: data.LocalStorage, err = extractLocalStorage(path) - case types.Extension: + case category.Extension: data.Extensions, err = extractExtensions(p.ctx.container) default: return @@ -137,23 +138,23 @@ func (p *profile) extractCategory(data *types.BrowserData, cat types.Category, p } } -func (p *profile) countCategory(cat types.Category, path, keychainPassword string) int { +func (p *profile) countCategory(cat category.Category, path, keychainPassword string) int { var count int var err error switch cat { - case types.Password: + case category.Password: count, err = countPasswords(keychainPassword) - case types.History: + case category.History: count, err = countHistories(path) - case types.Cookie: + case category.Cookie: count, err = countCookies(path) - case types.Bookmark: + case category.Bookmark: count, err = countBookmarks(path) - case types.Download: + case category.Download: count, err = countDownloads(path, p.ctx.downloadOwnerUUID()) - case types.LocalStorage: + case category.LocalStorage: count, err = countLocalStorage(path) - case types.Extension: + case category.Extension: count, err = countExtensions(p.ctx.container) default: // Unsupported categories silently return 0. diff --git a/browser/safari/profile_test.go b/browser/safari/profile_test.go index 9d2251d..0acfa83 100644 --- a/browser/safari/profile_test.go +++ b/browser/safari/profile_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -16,7 +17,7 @@ func TestCountCategory(t *testing.T) { insertHistoryItem(1, "https://example.com", "example.com", 1), ) p := &profile{} - assert.Equal(t, 1, p.countCategory(types.History, path, "")) + assert.Equal(t, 1, p.countCategory(category.History, path, "")) }) t.Run("Cookie", func(t *testing.T) { @@ -25,7 +26,7 @@ func TestCountCategory(t *testing.T) { {domain: ".go.dev", name: "b", path: "/", value: "2", expires: 2000000000.0, creation: 700000000.0}, }) p := &profile{} - assert.Equal(t, 2, p.countCategory(types.Cookie, path, "")) + assert.Equal(t, 2, p.countCategory(category.Cookie, path, "")) }) t.Run("Bookmark", func(t *testing.T) { @@ -37,7 +38,7 @@ func TestCountCategory(t *testing.T) { }, }) p := &profile{} - assert.Equal(t, 2, p.countCategory(types.Bookmark, path, "")) + assert.Equal(t, 2, p.countCategory(category.Bookmark, path, "")) }) t.Run("Download", func(t *testing.T) { @@ -47,7 +48,7 @@ func TestCountCategory(t *testing.T) { }, }) p := &profile{} - assert.Equal(t, 1, p.countCategory(types.Download, path, "")) + assert.Equal(t, 1, p.countCategory(category.Download, path, "")) }) t.Run("LocalStorage", func(t *testing.T) { @@ -56,13 +57,13 @@ func TestCountCategory(t *testing.T) { "https://go.dev": {{Key: "theme", Value: "dark"}}, }) p := &profile{} - assert.Equal(t, 3, p.countCategory(types.LocalStorage, dir, "")) + assert.Equal(t, 3, p.countCategory(category.LocalStorage, dir, "")) }) t.Run("UnsupportedCategory", func(t *testing.T) { p := &profile{} - assert.Equal(t, 0, p.countCategory(types.CreditCard, "unused", "")) - assert.Equal(t, 0, p.countCategory(types.SessionStorage, "unused", "")) + assert.Equal(t, 0, p.countCategory(category.CreditCard, "unused", "")) + assert.Equal(t, 0, p.countCategory(category.SessionStorage, "unused", "")) }) } @@ -77,12 +78,10 @@ func TestExtractCategory(t *testing.T) { ) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.History, path, "") + p.extractCategory(data, category.History, path, "") require.Len(t, data.Histories, 2) - // Sorted by visit count descending - assert.Equal(t, 3, data.Histories[0].VisitCount) - assert.Equal(t, 1, data.Histories[1].VisitCount) + assert.ElementsMatch(t, []int{3, 1}, []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount}) }) t.Run("Cookie", func(t *testing.T) { @@ -94,7 +93,7 @@ func TestExtractCategory(t *testing.T) { }) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.Cookie, path, "") + p.extractCategory(data, category.Cookie, path, "") require.Len(t, data.Cookies, 1) assert.Equal(t, ".example.com", data.Cookies[0].Host) @@ -112,7 +111,7 @@ func TestExtractCategory(t *testing.T) { }) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.Bookmark, path, "") + p.extractCategory(data, category.Bookmark, path, "") require.Len(t, data.Bookmarks, 1) assert.Equal(t, "GitHub", data.Bookmarks[0].Name) @@ -127,7 +126,7 @@ func TestExtractCategory(t *testing.T) { }) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.Download, path, "") + p.extractCategory(data, category.Download, path, "") require.Len(t, data.Downloads, 1) assert.Equal(t, "https://example.com/file.zip", data.Downloads[0].URL) @@ -140,7 +139,7 @@ func TestExtractCategory(t *testing.T) { }) p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.LocalStorage, dir, "") + p.extractCategory(data, category.LocalStorage, dir, "") require.Len(t, data.LocalStorage, 1) assert.Equal(t, "https://github.com", data.LocalStorage[0].URL) @@ -151,7 +150,7 @@ func TestExtractCategory(t *testing.T) { t.Run("UnsupportedCategory", func(t *testing.T) { p := &profile{} data := &types.BrowserData{} - p.extractCategory(data, types.CreditCard, "unused", "") + p.extractCategory(data, category.CreditCard, "unused", "") assert.Empty(t, data.CreditCards) }) } diff --git a/browser/safari/profiles_test.go b/browser/safari/profiles_test.go index 9eadabe..808e9c2 100644 --- a/browser/safari/profiles_test.go +++ b/browser/safari/profiles_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" ) // containerPaths returns (legacyHome, container) for a fake ~/Library tree @@ -223,12 +223,12 @@ func TestBuildSources_DefaultProfile(t *testing.T) { p := profileContext{legacyHome: legacyHome, container: container} sources := buildSources(p) - assert.Equal(t, filepath.Join(legacyHome, "History.db"), sources[types.History][0].abs) - assert.Equal(t, filepath.Join(legacyHome, "Bookmarks.plist"), sources[types.Bookmark][0].abs) - assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[types.Download][0].abs) - require.Len(t, sources[types.Cookie], 2) - assert.Equal(t, filepath.Join(container, "Cookies", "Cookies.binarycookies"), sources[types.Cookie][0].abs) - assert.Equal(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), sources[types.Cookie][1].abs) + assert.Equal(t, filepath.Join(legacyHome, "History.db"), sources[category.History][0].abs) + assert.Equal(t, filepath.Join(legacyHome, "Bookmarks.plist"), sources[category.Bookmark][0].abs) + assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[category.Download][0].abs) + require.Len(t, sources[category.Cookie], 2) + assert.Equal(t, filepath.Join(container, "Cookies", "Cookies.binarycookies"), sources[category.Cookie][0].abs) + assert.Equal(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), sources[category.Cookie][1].abs) } func TestBuildSources_NamedProfile(t *testing.T) { @@ -247,13 +247,13 @@ func TestBuildSources_NamedProfile(t *testing.T) { assert.Equal(t, filepath.Join(container, "Safari", "Profiles", uuid, "History.db"), - sources[types.History][0].abs) + sources[category.History][0].abs) assert.Equal(t, filepath.Join(container, "WebKit", "WebsiteDataStore", strings.ToLower(uuid), "Cookies", "Cookies.binarycookies"), - sources[types.Cookie][0].abs) + sources[category.Cookie][0].abs) // Download points at the shared plist — filtering by DownloadEntryProfileUUIDStringKey // happens inside extractDownloads, not at the path layer. - assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[types.Download][0].abs) + assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[category.Download][0].abs) // Bookmark is still shared with no per-entry profile tag, so it's attributed to default only. - assert.NotContains(t, sources, types.Bookmark) + assert.NotContains(t, sources, category.Bookmark) } diff --git a/browser/safari/safari.go b/browser/safari/safari.go index 34ac2f5..3eb6a5a 100644 --- a/browser/safari/safari.go +++ b/browser/safari/safari.go @@ -3,6 +3,7 @@ package safari import ( "os" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -53,7 +54,7 @@ func (b *Browser) Profiles() []types.Profile { } // Extract extracts every profile, threading the installation's keychain password. -func (b *Browser) Extract(categories []types.Category) ([]types.ExtractResult, error) { +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{ @@ -65,7 +66,7 @@ func (b *Browser) Extract(categories []types.Category) ([]types.ExtractResult, e } // CountEntries counts entries per category for every profile. -func (b *Browser) CountEntries(categories []types.Category) ([]types.CountResult, error) { +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{ @@ -76,7 +77,7 @@ func (b *Browser) CountEntries(categories []types.Category) ([]types.CountResult return results, nil } -func resolveProfilePaths(p profileContext) map[types.Category]resolvedPath { +func resolveProfilePaths(p profileContext) map[category.Category]resolvedPath { return resolveSourcePaths(buildSources(p)) } @@ -86,8 +87,8 @@ type resolvedPath struct { } // resolveSourcePaths returns only paths that exist; first matching candidate wins per category. -func resolveSourcePaths(sources map[types.Category][]sourcePath) map[types.Category]resolvedPath { - resolved := make(map[types.Category]resolvedPath) +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) diff --git a/browser/safari/safari_test.go b/browser/safari/safari_test.go index af6d5f3..7945367 100644 --- a/browser/safari/safari_test.go +++ b/browser/safari/safari_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -119,20 +120,20 @@ func TestNewBrowsers_MultiProfile(t *testing.T) { switch p.ctx.name { case "default": assert.Equal(t, legacyHome, p.dir()) - assert.Contains(t, p.sourcePaths, types.History) - assert.Equal(t, filepath.Join(legacyHome, "History.db"), p.sourcePaths[types.History].absPath) + 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, types.LocalStorage) + 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, types.History) + assert.Contains(t, p.sourcePaths, category.History) assert.Equal(t, filepath.Join(container, "Safari", "Profiles", uuid, "History.db"), - p.sourcePaths[types.History].absPath) - require.Contains(t, p.sourcePaths, types.LocalStorage) - assert.Equal(t, namedOriginsDir, p.sourcePaths[types.LocalStorage].absPath) - assert.True(t, p.sourcePaths[types.LocalStorage].isDir) + 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) } } } @@ -147,9 +148,9 @@ func TestResolveSourcePaths(t *testing.T) { sources := buildSources(profileContext{legacyHome: dir, container: deriveContainerRoot(dir)}) resolved := resolveSourcePaths(sources) - assert.Contains(t, resolved, types.History) - assert.Equal(t, filepath.Join(dir, "History.db"), resolved[types.History].absPath) - assert.False(t, resolved[types.History].isDir) + 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) { @@ -181,8 +182,8 @@ func TestCountEntries(t *testing.T) { require.NoError(t, err) require.NotNil(t, b) - results, err := b.CountEntries([]types.Category{types.History}) + results, err := b.CountEntries([]category.Category{category.History}) require.NoError(t, err) require.Len(t, results, 1) - assert.Equal(t, 2, results[0].Counts[types.History]) + assert.Equal(t, 2, results[0].Counts[category.History]) } diff --git a/browser/safari/source.go b/browser/safari/source.go index d23cc5b..149e6b6 100644 --- a/browser/safari/source.go +++ b/browser/safari/source.go @@ -3,7 +3,7 @@ package safari import ( "path/filepath" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" ) type sourcePath struct { @@ -21,7 +21,7 @@ func dir(abs string) sourcePath { return sourcePath{abs: abs, isDir: true} } // - 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[types.Category][]sourcePath { +func buildSources(p profileContext) map[category.Category][]sourcePath { if p.isDefault() { return defaultSources(p) } @@ -31,18 +31,18 @@ func buildSources(p profileContext) map[types.Category][]sourcePath { // 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[types.Category][]sourcePath { +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[types.Category][]sourcePath{ - types.History: {file(filepath.Join(home, "History.db"))}, - types.Cookie: {file(containerCookies), file(legacyCookies)}, - types.Bookmark: {file(filepath.Join(home, "Bookmarks.plist"))}, - types.Download: {file(filepath.Join(home, "Downloads.plist"))}, - types.LocalStorage: {dir(defaultLocalStorage)}, + 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)}, } } @@ -52,14 +52,14 @@ func defaultSources(p profileContext) map[types.Category][]sourcePath { // 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[types.Category][]sourcePath { +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[types.Category][]sourcePath{ - types.History: {file(filepath.Join(profileDir, "History.db"))}, - types.Cookie: {file(filepath.Join(webkitStore, "Cookies", "Cookies.binarycookies"))}, - types.Download: {file(filepath.Join(p.legacyHome, "Downloads.plist"))}, - types.LocalStorage: {dir(filepath.Join(webkitStore, "Origins"))}, + 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/cmd/hack-browser-data/archive_golden_test.go b/cmd/hack-browser-data/archive_golden_test.go index f8553a1..8c7f439 100644 --- a/cmd/hack-browser-data/archive_golden_test.go +++ b/cmd/hack-browser-data/archive_golden_test.go @@ -14,6 +14,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/types" ) @@ -89,10 +90,10 @@ func TestArchiveGolden(t *testing.T) { tests := []struct { name string golden string - categories []types.Category + categories []category.Category }{ - {name: "all", golden: "archive-all.golden", categories: types.AllCategories}, - {name: "cookie", golden: "archive-cookie.golden", categories: []types.Category{types.Cookie}}, + {name: "all", golden: "archive-all.golden", categories: category.All()}, + {name: "cookie", golden: "archive-cookie.golden", categories: []category.Category{category.Cookie}}, } for _, tt := range tests { tt := tt diff --git a/cmd/hack-browser-data/categories.go b/cmd/hack-browser-data/categories.go new file mode 100644 index 0000000..d331eff --- /dev/null +++ b/cmd/hack-browser-data/categories.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "strings" + + "github.com/moond4rk/hackbrowserdata/internal/category" +) + +// parseCategories converts a comma-separated string into a Category slice. +// "all" returns all categories. +func parseCategories(s string) ([]category.Category, error) { + s = strings.TrimSpace(s) + if strings.EqualFold(s, "all") { + return category.All(), nil + } + + var categories []category.Category + for _, name := range strings.Split(s, ",") { + name = strings.TrimSpace(strings.ToLower(name)) + if name == "" { + continue + } + c, err := category.Parse(name) + if err != nil { + return nil, fmt.Errorf("%w, available: all|%s", err, categoryNames()) + } + categories = append(categories, c) + } + if len(categories) == 0 { + return nil, fmt.Errorf("no categories specified") + } + return categories, nil +} + +func categoryNames() string { + all := category.All() + names := make([]string, len(all)) + for i, c := range all { + names[i] = c.String() + } + return strings.Join(names, ",") +} diff --git a/cmd/hack-browser-data/categories_test.go b/cmd/hack-browser-data/categories_test.go new file mode 100644 index 0000000..3d44794 --- /dev/null +++ b/cmd/hack-browser-data/categories_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/category" +) + +func TestParseCategories(t *testing.T) { + for _, s := range []string{"all", " ALL "} { + got, err := parseCategories(s) + require.NoError(t, err) + assert.Equal(t, category.All(), got) + } + + got, err := parseCategories(" Cookie, password,,history ") + require.NoError(t, err) + assert.Equal(t, []category.Category{category.Cookie, category.Password, category.History}, got) +} + +func TestParseCategories_Errors(t *testing.T) { + _, err := parseCategories("cookie,bogus") + require.EqualError(t, err, `unknown category: "bogus", available: all|`+ + "password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage") + + _, err = parseCategories(" , ") + require.EqualError(t, err, "no categories specified") +} diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index 2940e97..7d653c4 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -1,14 +1,10 @@ package main import ( - "fmt" - "strings" - "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/types" ) func dumpCmd() *cobra.Command { @@ -61,42 +57,3 @@ func dumpCmd() *cobra.Command { return cmd } - -// parseCategories converts a comma-separated string into a Category slice. -// "all" returns all categories. -func parseCategories(s string) ([]types.Category, error) { - s = strings.TrimSpace(s) - if strings.EqualFold(s, "all") { - return types.AllCategories, nil - } - - categoryMap := make(map[string]types.Category, len(types.AllCategories)) - for _, c := range types.AllCategories { - categoryMap[c.String()] = c - } - - var categories []types.Category - for _, name := range strings.Split(s, ",") { - name = strings.TrimSpace(strings.ToLower(name)) - if name == "" { - continue - } - c, ok := categoryMap[name] - if !ok { - return nil, fmt.Errorf("unknown category: %q, available: all|%s", name, categoryNames()) - } - categories = append(categories, c) - } - if len(categories) == 0 { - return nil, fmt.Errorf("no categories specified") - } - return categories, nil -} - -func categoryNames() string { - names := make([]string, len(types.AllCategories)) - for i, c := range types.AllCategories { - names[i] = c.String() - } - return strings.Join(names, ",") -} diff --git a/cmd/hack-browser-data/export_golden_test.go b/cmd/hack-browser-data/export_golden_test.go index 7ff0da8..1f42950 100644 --- a/cmd/hack-browser-data/export_golden_test.go +++ b/cmd/hack-browser-data/export_golden_test.go @@ -14,7 +14,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/output" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/export" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) @@ -73,7 +75,7 @@ func TestExportGolden(t *testing.T) { got = bundleFiles(t, dir, "cookie.json") } assertGolden(t, "export-"+tc.format+".golden", got) - assert.Equal(t, exportCategoryFiles(tc.ext, types.AllCategories...), exportDirFiles(t, dir)) + assert.Equal(t, exportCategoryFiles(tc.ext, category.All()...), exportDirFiles(t, dir)) exportAssertFileContract(t, dir) for _, form := range tc.urlForms { exportAssertURLForm(t, dir, form) @@ -81,7 +83,7 @@ func TestExportGolden(t *testing.T) { sparse := filepath.Join(t.TempDir(), "sparse") exportWrite(t, sparse, tc.format, exportSparseStamps()) - assert.Equal(t, exportCategoryFiles(tc.ext, types.Password, types.LocalStorage), exportDirFiles(t, sparse)) + assert.Equal(t, exportCategoryFiles(tc.ext, category.Password, category.LocalStorage), exportDirFiles(t, sparse)) }) } @@ -100,15 +102,17 @@ func TestExportGolden(t *testing.T) { func exportWrite(t *testing.T, dir, format string, stamps []exportStamp) { t.Helper() - w, err := output.NewWriter(dir, format) + f, err := export.ParseFormat(format) + require.NoError(t, err) + w, err := export.NewWriter(dir, f) require.NoError(t, err) for _, s := range stamps { - w.Add(s.browser, s.profile, s.data) + require.NoError(t, writeResult(w, s.browser, types.ExtractResult{Profile: types.Profile{Name: s.profile}, Data: s.data})) } - require.NoError(t, w.Write()) + require.NoError(t, w.Close()) } -func exportCategoryFiles(ext string, categories ...types.Category) []string { +func exportCategoryFiles(ext string, categories ...category.Category) []string { names := make([]string, 0, len(categories)) for _, c := range categories { names = append(names, c.String()+"."+ext) @@ -192,18 +196,18 @@ func exportAssertURLForm(t *testing.T, dir string, form exportURLForm) { func exportStamps() []exportStamp { return []exportStamp{ {browser: "Chrome", profile: "Default", data: &types.BrowserData{ - Passwords: []types.LoginEntry{ + Passwords: []record.Login{ { URL: "https://accounts.example.com/signin?continue=/mail&hl=ja", Username: "alice@example.com", Password: "pa$$ \"quoted\", comma\\backslash\nnewline", - CreatedAt: time.Date(2026, 3, 14, 15, 9, 26, 535897932, time.UTC), Store: types.PasswordStoreAccount, + CreatedAt: time.Date(2026, 3, 14, 15, 9, 26, 535897932, time.UTC), Store: record.StoreAccount, }, { URL: "https://例え.jp/ログイン", Username: "日本語ユーザー", Password: "🔑 emoji", - CreatedAt: time.Date(2025, 11, 5, 6, 7, 8, 0, time.UTC), Store: types.PasswordStoreLocal, + CreatedAt: time.Date(2025, 11, 5, 6, 7, 8, 0, time.UTC), Store: record.StoreLocal, }, }, - Cookies: []types.CookieEntry{ + Cookies: []record.Cookie{ { Host: ".example.com", Path: "/", Name: "return_to", Value: exportURLWithHTMLChars, IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true, @@ -215,14 +219,14 @@ func exportStamps() []exportStamp { IsHTTPOnly: true, CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), SameSite: "strict", }, }, - Histories: []types.HistoryEntry{ + Histories: []record.History{ { URL: exportURLWithHTMLChars, Title: `Cart "deals" &, 日本語 🛒`, VisitCount: 42, LastVisit: time.Date(2026, 3, 14, 15, 10, 0, 1000, time.UTC), }, {URL: "file:///C:/Users/Alice/notes.html", Title: "multi\nline title", VisitCount: 3}, }, - Downloads: []types.DownloadEntry{ + Downloads: []record.Download{ { URL: "https://dl.example.com/files/big.iso?token=a&sig=", TargetPath: `C:\Users\Alice\Downloads\Ubuntu "final", v2.iso`, @@ -231,42 +235,42 @@ func exportStamps() []exportStamp { EndTime: time.Date(2026, 3, 14, 15, 30, 0, 750000000, time.UTC), }, }, - Bookmarks: []types.BookmarkEntry{ + Bookmarks: []record.Bookmark{ { ID: 7, Name: "Docs & ", Type: "url", URL: "https://docs.example.com/search?a=1&b=<2>", Folder: "Bookmarks bar", CreatedAt: time.Date(2026, 2, 2, 2, 2, 2, 20202020, time.UTC), }, {ID: 4294967298, Name: "日本語 📚", Type: "url", URL: "https://例え.jp/", Folder: "Other bookmarks"}, }, - CreditCards: []types.CreditCardEntry{ + CreditCards: []record.CreditCard{ { GUID: "00000000-0000-4000-8000-000000000001", Name: "山田 太郎", Number: "4111111111111111", ExpMonth: "12", ExpYear: "2030", NickName: `Work "primary", 💳`, Address: "1-2-3 Chiyoda,\nTokyo 100-0001", }, }, - Extensions: []types.ExtensionEntry{ + Extensions: []record.Extension{ { Name: "Ad Blocker", ID: "abcdefghijklmnopabcdefghijklmnop", Description: `Blocks ads & trackers, "fast" `, Version: "1.58.0", HomepageURL: "https://adblock.example/?a=1&b=<2>", Enabled: true, }, }, - LocalStorage: []types.StorageEntry{ + LocalStorage: []record.LocalStorage{ {URL: "https://app.example.com", Key: "prefs", Value: `{"theme":"dark","greeting":"こんにちは 👋","dir":"C:\Temp"}`}, {IsMeta: true, URL: "https://app.example.com", Value: "meta data, value bytes is [8 128 1]"}, }, - SessionStorage: []types.StorageEntry{ + SessionStorage: []record.SessionStorage{ {URL: "https://app.example.com", Key: "tab-id", Value: "42"}, }, }}, {browser: "Chrome", profile: "Profile 1", data: &types.BrowserData{ - Passwords: []types.LoginEntry{ + Passwords: []record.Login{ { URL: "http://192.168.0.1:8080/admin", Username: "admin", Password: " leading space", - CreatedAt: time.Date(2025, 6, 1, 0, 0, 0, 1, time.UTC), Store: types.PasswordStoreLocal, + CreatedAt: time.Date(2025, 6, 1, 0, 0, 0, 1, time.UTC), Store: record.StoreLocal, }, - {URL: "android://hash@com.example.app/", Store: types.PasswordStoreLocal}, + {URL: "android://hash@com.example.app/", Store: record.StoreLocal}, }, - Cookies: []types.CookieEntry{ + Cookies: []record.Cookie{ { Host: ".tracker.example", Path: "/", Name: "_ga", Value: "GA1.2.1234567890.1700000000", IsSecure: true, HasExpire: true, IsPersistent: true, @@ -275,49 +279,49 @@ func exportStamps() []exportStamp { }, {Host: ".dev.example", Path: "/dev", Name: "multi_line", Value: "line one\nline two, with comma", SameSite: "unspecified"}, }, - Histories: []types.HistoryEntry{ + Histories: []record.History{ { URL: "https://search.example.com/?q=a%26b&lang=日本語", VisitCount: 1000000, LastVisit: time.Date(2025, 7, 7, 7, 7, 7, 700000000, time.UTC), }, {URL: "about:blank", Title: " leading space", LastVisit: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)}, }, - Downloads: []types.DownloadEntry{ + Downloads: []record.Download{ { URL: "https://例え.jp/資料.pdf", TargetPath: "/home/alice/Downloads/資料 📄.pdf", MimeType: "application/pdf", StartTime: time.Date(2025, 8, 1, 8, 0, 0, 0, time.UTC), }, }, - Bookmarks: []types.BookmarkEntry{ + Bookmarks: []record.Bookmark{ { ID: 1, Name: `Quote "this", please`, Type: "url", URL: "https://example.org/a,b", Folder: "multi\nline folder", CreatedAt: time.Date(2025, 3, 3, 3, 3, 3, 0, time.UTC), }, }, - CreditCards: []types.CreditCardEntry{ + CreditCards: []record.CreditCard{ { GUID: "00000000-0000-4000-8000-000000000002", Name: "Alice O'Brien", Number: "5555555555554444", ExpMonth: "1", ExpYear: "2027", CVC: "123", Comment: `note & \ end`, }, }, - Extensions: []types.ExtensionEntry{ + Extensions: []record.Extension{ {Name: "日本語拡張 🧩", ID: "ponmlkjihgfedcbaponmlkjihgfedcba", Description: "line one\nline two", Version: "0.0.1"}, }, - LocalStorage: []types.StorageEntry{ + LocalStorage: []record.LocalStorage{ {URL: "https://example.org", Key: "a&b", Value: "multi\nline"}, }, - SessionStorage: []types.StorageEntry{ + SessionStorage: []record.SessionStorage{ {URL: "https://example.org/?x=1&y=<2>", Key: "draft", Value: `He said "hi", then left \`}, }, }}, {browser: "Microsoft Edge", profile: "Default", data: &types.BrowserData{ - Passwords: []types.LoginEntry{ + Passwords: []record.Login{ { URL: "https://login.example.org//authorize?client=a&scope=b", Username: `CORP\jdoe`, Password: "日本語パスワード", - CreatedAt: time.Date(2024, 2, 29, 12, 0, 0, 500000000, time.UTC), Store: types.PasswordStoreAccount, + CreatedAt: time.Date(2024, 2, 29, 12, 0, 0, 500000000, time.UTC), Store: record.StoreAccount, }, }, - Cookies: []types.CookieEntry{ + Cookies: []record.Cookie{ { Host: ".edge.example", Path: "/", Name: "epoch_expiry", Value: `back\slash "quoted" &`, IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true, @@ -329,34 +333,34 @@ func exportStamps() []exportStamp { CreatedAt: time.Date(2024, 6, 15, 9, 30, 0, 0, time.UTC), SameSite: "strict", }, }, - Histories: []types.HistoryEntry{ + Histories: []record.History{ { URL: "edge://settings/?a=1&b=2", Title: `C:\Windows\System32`, VisitCount: 7, LastVisit: time.Date(2024, 7, 4, 0, 0, 0, 500000000, time.UTC), }, }, - Downloads: []types.DownloadEntry{ + Downloads: []record.Download{ {URL: "blob:https://app.example/1234", TargetPath: `\\fileserver\share\Q3 summary.csv`, TotalBytes: 4294967296}, }, - Bookmarks: []types.BookmarkEntry{ + Bookmarks: []record.Bookmark{ { ID: 12, Name: `C:\Shares\docs`, Type: "url", URL: "https://edge.example/", Folder: "Favorites bar", CreatedAt: time.Date(2024, 4, 4, 4, 4, 4, 400000000, time.UTC), }, }, - CreditCards: []types.CreditCardEntry{ + CreditCards: []record.CreditCard{ {GUID: "00000000-0000-4000-8000-000000000003"}, }, - Extensions: []types.ExtensionEntry{ + Extensions: []record.Extension{ { Name: "Edge Helper", ID: "aaaabbbbccccddddeeeeffffgggghhhh", Description: `Installed under C:\Program Files\Helper`, Version: "2.0", HomepageURL: "https://helper.example/", Enabled: true, }, }, - LocalStorage: []types.StorageEntry{ + LocalStorage: []record.LocalStorage{ {URL: "https://edge.example", Key: "日本語"}, }, - SessionStorage: []types.StorageEntry{ + SessionStorage: []record.SessionStorage{ {IsMeta: true, URL: "https://edge.example", Value: "meta data, value bytes is [16 2]"}, }, }}, @@ -366,13 +370,13 @@ func exportStamps() []exportStamp { func exportSparseStamps() []exportStamp { return []exportStamp{ {browser: "Chrome", profile: "Default", data: &types.BrowserData{ - Passwords: []types.LoginEntry{{URL: "https://example.com/", Username: "alice", Store: types.PasswordStoreLocal}}, - Cookies: []types.CookieEntry{}, + 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{ - Histories: []types.HistoryEntry{}, - LocalStorage: []types.StorageEntry{{URL: "https://example.com", Key: "k", Value: "v"}}, + Histories: []record.History{}, + LocalStorage: []record.LocalStorage{{URL: "https://example.com", Key: "k", Value: "v"}}, }}, } } diff --git a/cmd/hack-browser-data/extract.go b/cmd/hack-browser-data/extract.go index df839b4..b252cc3 100644 --- a/cmd/hack-browser-data/extract.go +++ b/cmd/hack-browser-data/extract.go @@ -1,18 +1,25 @@ package main import ( + "errors" "fmt" "path/filepath" "github.com/moond4rk/hackbrowserdata/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/output" + "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) -func extractAndWrite(browsers []browser.Browser, categories []types.Category, outputDir, outputFormat string, compress bool) error { - w, err := output.NewWriter(outputDir, outputFormat) +func extractAndWrite(browsers []browser.Browser, categories []category.Category, outputDir, outputFormat string, compress bool) error { + format, err := export.ParseFormat(outputFormat) + if err != nil { + return err + } + w, err := export.NewWriter(outputDir, format) if err != nil { return err } @@ -23,10 +30,12 @@ func extractAndWrite(browsers []browser.Browser, categories []types.Category, ou log.Errorf("extract %s: %v", b.BrowserName(), extractErr) } for _, r := range results { - w.Add(b.BrowserName(), r.Name, r.Data) + if err := writeResult(w, b.BrowserName(), r); err != nil { + return errors.Join(err, w.Close()) + } } } - if err := w.Write(); err != nil { + if err := w.Close(); err != nil { return err } if compress { @@ -37,3 +46,56 @@ func extractAndWrite(browsers []browser.Browser, categories []types.Category, ou } return nil } + +// writeResult bridges today's BrowserData to the writer until the pipeline replaces it. +func writeResult(w *export.Writer, browserName string, r types.ExtractResult) error { + if r.Data == nil { + return nil + } + for _, c := range category.All() { + records := profileRecords(r.Data, c) + for _, rec := range records { + record.Stamp(rec, browserName, r.Name) + } + if err := w.Write(c, records); err != nil { + return err + } + } + return nil +} + +func profileRecords(d *types.BrowserData, c category.Category) []record.Record { + switch c { + case category.Password: + return recordsOf(d.Passwords) + case category.Cookie: + return recordsOf(d.Cookies) + case category.Bookmark: + return recordsOf(d.Bookmarks) + case category.History: + return recordsOf(d.Histories) + case category.Download: + return recordsOf(d.Downloads) + case category.CreditCard: + return recordsOf(d.CreditCards) + case category.Extension: + return recordsOf(d.Extensions) + case category.LocalStorage: + return recordsOf(d.LocalStorage) + case category.SessionStorage: + return recordsOf(d.SessionStorage) + default: + return nil + } +} + +func recordsOf[T any, P interface { + *T + record.Record +}](items []T) []record.Record { + records := make([]record.Record, len(items)) + for i := range items { + records[i] = P(&items[i]) + } + return records +} diff --git a/cmd/hack-browser-data/extract_golden_test.go b/cmd/hack-browser-data/extract_golden_test.go index ec9a483..9a4eaa1 100644 --- a/cmd/hack-browser-data/extract_golden_test.go +++ b/cmd/hack-browser-data/extract_golden_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" ) func TestExtractGolden(t *testing.T) { @@ -38,6 +38,6 @@ func TestExtractGolden(t *testing.T) { func extractGoldenRun(t *testing.T, root, format string) string { t.Helper() out := t.TempDir() - require.NoError(t, extractAndWrite(chromiumFixtureBrowsers(t, root), types.AllCategories, out, format, false)) + require.NoError(t, extractAndWrite(chromiumFixtureBrowsers(t, root), category.All(), out, format, false)) return out } diff --git a/cmd/hack-browser-data/keys_golden_test.go b/cmd/hack-browser-data/keys_golden_test.go index 97146db..9d08b37 100644 --- a/cmd/hack-browser-data/keys_golden_test.go +++ b/cmd/hack-browser-data/keys_golden_test.go @@ -15,6 +15,7 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -42,11 +43,11 @@ func (b *keysFakeBrowser) Profiles() []types.Profile { return out } -func (b *keysFakeBrowser) Extract(_ []types.Category) ([]types.ExtractResult, error) { +func (b *keysFakeBrowser) Extract(_ []category.Category) ([]types.ExtractResult, error) { return nil, nil } -func (b *keysFakeBrowser) CountEntries(_ []types.Category) ([]types.CountResult, error) { +func (b *keysFakeBrowser) CountEntries(_ []category.Category) ([]types.CountResult, error) { return nil, nil } diff --git a/cmd/hack-browser-data/list.go b/cmd/hack-browser-data/list.go index c4b6f53..03f1f2c 100644 --- a/cmd/hack-browser-data/list.go +++ b/cmd/hack-browser-data/list.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/browser" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" ) func listCmd() *cobra.Command { @@ -54,16 +54,16 @@ func printDetail(out io.Writer, browsers []browser.Browser) error { // Build header: Browser Profile Password Cookie ... w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) fmt.Fprint(w, "Browser\tProfile") - for _, c := range types.AllCategories { + for _, c := range category.All() { fmt.Fprintf(w, "\t%s", c.String()) } fmt.Fprintln(w) for _, b := range browsers { - results, _ := b.CountEntries(types.AllCategories) + results, _ := b.CountEntries(category.All()) for _, r := range results { fmt.Fprintf(w, "%s\t%s", b.BrowserName(), r.Name) - for _, c := range types.AllCategories { + for _, c := range category.All() { fmt.Fprintf(w, "\t%d", r.Counts[c]) } fmt.Fprintln(w) diff --git a/cmd/hack-browser-data/restore_golden_test.go b/cmd/hack-browser-data/restore_golden_test.go index 9462dbb..8aebb60 100644 --- a/cmd/hack-browser-data/restore_golden_test.go +++ b/cmd/hack-browser-data/restore_golden_test.go @@ -13,8 +13,8 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/masterkey" - "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) @@ -48,7 +48,7 @@ func TestRestoreGolden(t *testing.T) { t.Run("data-zip", func(t *testing.T) { dataZip := filepath.Join(t.TempDir(), "data.zip") - _, err := browser.WriteArchive(chromiumFixtureBrowsers(t, data), types.AllCategories, dataZip) + _, err := browser.WriteArchive(chromiumFixtureBrowsers(t, data), category.All(), dataZip) require.NoError(t, err) out := t.TempDir() diff --git a/internal/category/category.go b/internal/category/category.go new file mode 100644 index 0000000..8d7e315 --- /dev/null +++ b/internal/category/category.go @@ -0,0 +1,57 @@ +package category + +import "fmt" + +// Numbering starts at 1, so the zero Category means "none". +type Category int + +const ( + Password Category = iota + 1 + Cookie + Bookmark + History + Download + CreditCard + Extension + LocalStorage + SessionStorage +) + +// String's values are the -c values and the output file names, so they cannot change. +func (c Category) String() string { + switch c { + case Password: + return "password" + case Cookie: + return "cookie" + case Bookmark: + return "bookmark" + case History: + return "history" + case Download: + return "download" + case CreditCard: + return "creditcard" + case Extension: + return "extension" + case LocalStorage: + return "localstorage" + case SessionStorage: + return "sessionstorage" + default: + return "unknown" + } +} + +func All() []Category { + return []Category{Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage} +} + +func Parse(s string) (Category, error) { + for _, c := range All() { + if c.String() == s { + return c, nil + } + } + return 0, fmt.Errorf("unknown category: %q", s) +} diff --git a/internal/category/category_test.go b/internal/category/category_test.go new file mode 100644 index 0000000..db9ba87 --- /dev/null +++ b/internal/category/category_test.go @@ -0,0 +1,62 @@ +package category + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestString(t *testing.T) { + tests := []struct { + c Category + want string + }{ + {Password, "password"}, + {Cookie, "cookie"}, + {Bookmark, "bookmark"}, + {History, "history"}, + {Download, "download"}, + {CreditCard, "creditcard"}, + {Extension, "extension"}, + {LocalStorage, "localstorage"}, + {SessionStorage, "sessionstorage"}, + {Category(0), "unknown"}, + {Category(999), "unknown"}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, tt.c.String()) + } +} + +func TestAll(t *testing.T) { + assert.Equal(t, []Category{ + Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage, + }, All()) +} + +func TestAll_ReturnsFreshSlice(t *testing.T) { + All()[0] = SessionStorage + assert.Equal(t, Password, All()[0]) +} + +func TestParse_RoundTrip(t *testing.T) { + for _, c := range All() { + got, err := Parse(c.String()) + require.NoError(t, err) + assert.Equal(t, c, got) + } +} + +func TestParse_Unknown(t *testing.T) { + for _, s := range []string{"", "unknown", "all", "Password", " cookie"} { + got, err := Parse(s) + require.EqualError(t, err, "unknown category: \""+s+"\"") + assert.Zero(t, got) + } +} + +func TestZeroIsNone(t *testing.T) { + var c Category + assert.NotContains(t, All(), c) +} diff --git a/internal/export/cookie_editor.go b/internal/export/cookie_editor.go new file mode 100644 index 0000000..a886adb --- /dev/null +++ b/internal/export/cookie_editor.go @@ -0,0 +1,53 @@ +package export + +import ( + "strings" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +var sameSiteNone = "no_restriction" + +func cookieEditorValue(r record.Record) any { + c, ok := r.(*record.Cookie) + if !ok { + return r + } + var expDate float64 + if !c.ExpireAt.IsZero() { + expDate = float64(c.ExpireAt.Unix()) + } + sameSite := &c.SameSite + switch c.SameSite { + case "none": + sameSite = &sameSiteNone + case "", "unspecified": + sameSite = nil + } + return cookieEditorEntry{ + Domain: c.Host, + ExpirationDate: expDate, + HTTPOnly: c.IsHTTPOnly, + Name: c.Name, + Path: c.Path, + Secure: c.IsSecure, + Value: c.Value, + SameSite: sameSite, + Session: expDate == 0., + HostOnly: !strings.HasPrefix(c.Host, "."), + } +} + +// cookieEditorEntry matches the CookieEditor browser extension's import format. +type cookieEditorEntry struct { + Domain string `json:"domain"` + ExpirationDate float64 `json:"expirationDate,omitempty"` + HTTPOnly bool `json:"httpOnly"` + Name string `json:"name"` + Path string `json:"path"` + Secure bool `json:"secure"` + Value string `json:"value"` + SameSite *string `json:"sameSite"` + Session bool `json:"session"` + HostOnly bool `json:"hostOnly"` +} diff --git a/internal/export/csv.go b/internal/export/csv.go new file mode 100644 index 0000000..fea432a --- /dev/null +++ b/internal/export/csv.go @@ -0,0 +1,40 @@ +package export + +import ( + "encoding/csv" + "fmt" + "io" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// utf8BOM is written at the start of CSV files for Excel compatibility. +var utf8BOM = []byte{0xEF, 0xBB, 0xBF} + +type csvEncoder struct { + w io.Writer + rows *csv.Writer + header bool +} + +func newCSVEncoder(w io.Writer) *csvEncoder { + return &csvEncoder{w: w, rows: csv.NewWriter(w)} +} + +func (e *csvEncoder) encode(r record.Record) error { + if !e.header { + if _, err := e.w.Write(utf8BOM); err != nil { + return fmt.Errorf("write BOM: %w", err) + } + if err := e.rows.Write(structCSVHeader(r)); err != nil { + return err + } + e.header = true + } + return e.rows.Write(structCSVRow(r)) +} + +func (e *csvEncoder) end() error { + e.rows.Flush() + return e.rows.Error() +} diff --git a/internal/export/format.go b/internal/export/format.go new file mode 100644 index 0000000..24193dd --- /dev/null +++ b/internal/export/format.go @@ -0,0 +1,55 @@ +package export + +import ( + "fmt" + "io" + + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// The zero Format is JSON, the -f default. +type Format int + +const ( + JSON Format = iota + CSV + CookieEditor +) + +func ParseFormat(s string) (Format, error) { + switch s { + case "json": + return JSON, nil + case "csv": + return CSV, nil + case "cookie-editor": + return CookieEditor, nil + default: + return 0, fmt.Errorf("unsupported format: %s", s) + } +} + +func (f Format) ext() string { + if f == CSV { + return "csv" + } + return "json" +} + +// encoder writes one category's file; it frames the document itself so that every Write can append to it. +type encoder interface { + encode(r record.Record) error + end() error +} + +func newEncoder(w io.Writer, f Format, c category.Category) encoder { + switch { + case f == CSV: + return newCSVEncoder(w) + case f == CookieEditor && c == category.Cookie: + return &jsonEncoder{w: w, value: cookieEditorValue} + default: + return &jsonEncoder{w: w, escapeHTML: true} + } +} diff --git a/internal/export/json.go b/internal/export/json.go new file mode 100644 index 0000000..07a3de4 --- /dev/null +++ b/internal/export/json.go @@ -0,0 +1,53 @@ +package export + +import ( + "bytes" + "encoding/json" + "io" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +const jsonIndent = " " + +// jsonEncoder writes the bytes a single indented Encode of the whole slice would produce, one element at a time. +type jsonEncoder struct { + w io.Writer + escapeHTML bool + value func(record.Record) any + n int +} + +func (e *jsonEncoder) encode(r record.Record) error { + var v any = r + if e.value != nil { + v = e.value(r) + } + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(e.escapeHTML) + enc.SetIndent(jsonIndent, jsonIndent) + if err := enc.Encode(v); err != nil { + return err + } + + sep := ",\n" + jsonIndent + if e.n == 0 { + sep = "[\n" + jsonIndent + } + e.n++ + if _, err := io.WriteString(e.w, sep); err != nil { + return err + } + _, err := e.w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n"))) + return err +} + +func (e *jsonEncoder) end() error { + closing := "\n]\n" + if e.n == 0 { + closing = "[]\n" + } + _, err := io.WriteString(e.w, closing) + return err +} diff --git a/internal/export/json_test.go b/internal/export/json_test.go new file mode 100644 index 0000000..85b40c8 --- /dev/null +++ b/internal/export/json_test.go @@ -0,0 +1,63 @@ +package export + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +func encodeOnce(t *testing.T, v any, escapeHTML bool) string { + t.Helper() + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetIndent("", jsonIndent) + enc.SetEscapeHTML(escapeHTML) + require.NoError(t, enc.Encode(v)) + return buf.String() +} + +func encodeFramed(t *testing.T, e *jsonEncoder, records []record.Record) string { + t.Helper() + var buf bytes.Buffer + e.w = &buf + for _, r := range records { + require.NoError(t, e.encode(r)) + } + require.NoError(t, e.end()) + return buf.String() +} + +func TestJSONEncoder_MatchesOneEncodeOfTheSlice(t *testing.T) { + cookies := []record.Record{ + &record.Cookie{ + Browser: "Chrome", Profile: "Default", Host: ".example.com", Path: "/", Name: "q", + Value: `https://shop.example.com/cart?item=42&qty=<3> "日本語" ` + "\u2028", CreatedAt: testTime, SameSite: "none", + }, + &record.Cookie{Browser: "Chrome", Profile: "Default", Host: "example.com", Name: "empty", ExpireAt: testTime}, + } + + t.Run("json escapes HTML", func(t *testing.T) { + got := encodeFramed(t, &jsonEncoder{escapeHTML: true}, cookies) + assert.Equal(t, encodeOnce(t, cookies, true), got) + assert.Contains(t, got, `\u0026qty=\u003c3\u003e`) + }) + + t.Run("cookie-editor does not", func(t *testing.T) { + entries := make([]any, 0, len(cookies)) + for _, c := range cookies { + entries = append(entries, cookieEditorValue(c)) + } + got := encodeFramed(t, &jsonEncoder{value: cookieEditorValue}, cookies) + assert.Equal(t, encodeOnce(t, entries, false), got) + assert.Contains(t, got, `&qty=<3>`) + }) + + t.Run("one record", func(t *testing.T) { + assert.Equal(t, encodeOnce(t, cookies[:1], true), encodeFramed(t, &jsonEncoder{escapeHTML: true}, cookies[:1])) + }) +} diff --git a/internal/export/order.go b/internal/export/order.go new file mode 100644 index 0000000..e05c5c7 --- /dev/null +++ b/internal/export/order.go @@ -0,0 +1,44 @@ +package export + +import ( + "sort" + "time" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// Stable, so ties and keyless categories keep source order; Safari's bookmarks and downloads have no timestamp to sort by. +func sortRecords(records []record.Record) { + sort.SliceStable(records, func(i, j int) bool { + return keyOf(records[i]).before(keyOf(records[j])) + }) +} + +type sortKey struct { + visits int + at time.Time +} + +func keyOf(r record.Record) sortKey { + switch r := r.(type) { + case *record.Login: + return sortKey{at: r.CreatedAt} + case *record.Cookie: + return sortKey{at: r.CreatedAt} + case *record.Bookmark: + return sortKey{at: r.CreatedAt} + case *record.Download: + return sortKey{at: r.StartTime} + case *record.History: + return sortKey{visits: r.VisitCount} + default: + return sortKey{} + } +} + +func (k sortKey) before(o sortKey) bool { + if k.visits != o.visits { + return k.visits > o.visits + } + return k.at.After(o.at) +} diff --git a/internal/export/order_test.go b/internal/export/order_test.go new file mode 100644 index 0000000..c26219a --- /dev/null +++ b/internal/export/order_test.go @@ -0,0 +1,116 @@ +package export + +import ( + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +const tiedRecords = 20 + +func day(d int) time.Time { return time.Date(2026, 1, d, 0, 0, 0, 0, time.UTC) } + +func TestSortRecords_NewestFirst(t *testing.T) { + logins := []record.Record{ + &record.Login{URL: "old", CreatedAt: day(1)}, + &record.Login{URL: "unset"}, + &record.Login{URL: "new", CreatedAt: day(3)}, + } + sortRecords(logins) + assert.Equal(t, []string{"new", "old", "unset"}, urlsOf(t, logins)) + + downloads := []record.Record{ + &record.Download{URL: "older", StartTime: day(1)}, + &record.Download{URL: "newer", StartTime: day(2)}, + } + sortRecords(downloads) + assert.Equal(t, []string{"newer", "older"}, urlsOf(t, downloads)) +} + +// Firefox used to write its history least visited first; the exporter now orders history the same for every browser. +func TestSortRecords_HistoryMostVisitedFirst(t *testing.T) { + histories := []record.Record{ + &record.History{URL: "once", VisitCount: 1}, + &record.History{URL: "often", VisitCount: 42}, + &record.History{URL: "twice", VisitCount: 2}, + } + sortRecords(histories) + assert.Equal(t, []string{"often", "twice", "once"}, urlsOf(t, histories)) +} + +func TestSortRecords_TiesKeepSourceOrder(t *testing.T) { + logins := make([]record.Record, 0, tiedRecords) + for i := 0; i < tiedRecords; i++ { + store := record.StoreLocal + if i >= tiedRecords/2 { + store = record.StoreAccount + } + logins = append(logins, &record.Login{URL: strconv.Itoa(i), CreatedAt: day(2), Store: store}) + } + want := append([]record.Record(nil), logins...) + sortRecords(logins) + assert.Equal(t, want, logins, "equal timestamps keep emission order, so local rows stay before account rows") + + bookmarks := make([]record.Record, 0, tiedRecords) + for i := 0; i < tiedRecords; i++ { + bookmarks = append(bookmarks, &record.Bookmark{ID: int64(tiedRecords - i)}) + } + want = append([]record.Record(nil), bookmarks...) + sortRecords(bookmarks) + assert.Equal(t, want, bookmarks, "bookmarks without a creation time keep their tree order") +} + +// Interleaved timestamps make the sort move records; an unstable sort would then reorder the ties it moves. +func TestSortRecords_IsStable(t *testing.T) { + logins := make([]record.Record, 0, tiedRecords) + var newer, older []string + for i := 0; i < tiedRecords; i++ { + url := strconv.Itoa(i) + created := day(1) + if i%2 == 1 { + created = day(2) + newer = append(newer, url) + } else { + older = append(older, url) + } + logins = append(logins, &record.Login{URL: url, CreatedAt: created}) + } + sortRecords(logins) + assert.Equal(t, append(newer, older...), urlsOf(t, logins)) +} + +func TestSortRecords_KeylessCategoriesKeepSourceOrder(t *testing.T) { + records := make([]record.Record, 0, 4*tiedRecords) + for i := 0; i < tiedRecords; i++ { + id := strconv.Itoa(i) + records = append(records, + &record.CreditCard{GUID: id}, &record.Extension{ID: id}, + &record.LocalStorage{Key: id}, &record.SessionStorage{Key: id}, + ) + } + want := append([]record.Record(nil), records...) + sortRecords(records) + assert.Equal(t, want, records) +} + +func urlsOf(t *testing.T, records []record.Record) []string { + t.Helper() + urls := make([]string, 0, len(records)) + for _, r := range records { + switch r := r.(type) { + case *record.Login: + urls = append(urls, r.URL) + case *record.Download: + urls = append(urls, r.URL) + case *record.History: + urls = append(urls, r.URL) + default: + t.Fatalf("unexpected record %T", r) + } + } + return urls +} diff --git a/output/reflect.go b/internal/export/reflect.go similarity index 94% rename from output/reflect.go rename to internal/export/reflect.go index 6278cb5..4e4b2ff 100644 --- a/output/reflect.go +++ b/internal/export/reflect.go @@ -1,4 +1,4 @@ -package output +package export import ( "fmt" @@ -12,7 +12,7 @@ var timeType = reflect.TypeOf(time.Time{}) // structCSVHeader extracts CSV column names from a struct's csv tags. func structCSVHeader(v any) []string { - t := reflect.TypeOf(v) + t := reflect.Indirect(reflect.ValueOf(v)).Type() headers := make([]string, 0, t.NumField()) for i := 0; i < t.NumField(); i++ { name := tagName(t.Field(i), "csv") @@ -27,7 +27,7 @@ func structCSVHeader(v any) []string { // structCSVRow converts a struct's field values to CSV string values, // including only fields that have a csv tag. func structCSVRow(v any) []string { - val := reflect.ValueOf(v) + val := reflect.Indirect(reflect.ValueOf(v)) t := val.Type() row := make([]string, 0, t.NumField()) for i := 0; i < t.NumField(); i++ { diff --git a/internal/export/reflect_test.go b/internal/export/reflect_test.go new file mode 100644 index 0000000..7a63a81 --- /dev/null +++ b/internal/export/reflect_test.go @@ -0,0 +1,126 @@ +package export + +import ( + "reflect" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +var refTime = time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC) + +// allRecordTypes lists every record type. If a new record type is added, it must be included here. +var allRecordTypes = []record.Record{ + &record.Login{}, + &record.Cookie{}, + &record.Bookmark{}, + &record.History{}, + &record.Download{}, + &record.CreditCard{}, + &record.Extension{}, + &record.LocalStorage{}, + &record.SessionStorage{}, +} + +// A field without a csv tag would be silently left out of the CSV output. +func TestAllRecordFieldsHaveCSVTag(t *testing.T) { + for _, r := range allRecordTypes { + et := reflect.TypeOf(r).Elem() + t.Run(et.Name(), func(t *testing.T) { + for i := 0; i < et.NumField(); i++ { + f := et.Field(i) + if !f.IsExported() { + continue + } + _, ok := f.Tag.Lookup("csv") + assert.True(t, ok, "field %s.%s missing csv tag", et.Name(), f.Name) + } + }) + } +} + +func TestStructCSVHeader(t *testing.T) { + tests := []struct { + name string + record record.Record + expect []string + }{ + {"Login", &record.Login{}, []string{"browser", "profile", "url", "username", "password", "created_at", "store"}}, + {"Cookie", &record.Cookie{}, []string{ + "browser", "profile", "host", "path", "name", "value", + "is_secure", "is_http_only", "has_expire", "is_persistent", "expire_at", "created_at", "same_site", + }}, + {"Bookmark", &record.Bookmark{}, []string{"browser", "profile", "id", "name", "type", "url", "folder", "created_at"}}, + {"History", &record.History{}, []string{"browser", "profile", "url", "title", "visit_count", "last_visit"}}, + {"Download", &record.Download{}, []string{ + "browser", "profile", "url", "target_path", "mime_type", "total_bytes", "start_time", "end_time", + }}, + {"CreditCard", &record.CreditCard{}, []string{ + "browser", "profile", "guid", "name", "number", "exp_month", "exp_year", "nick_name", "address", "cvc", "comment", + }}, + {"LocalStorage", &record.LocalStorage{}, []string{"browser", "profile", "is_meta", "url", "key", "value"}}, + {"SessionStorage", &record.SessionStorage{}, []string{"browser", "profile", "is_meta", "url", "key", "value"}}, + {"Extension", &record.Extension{}, []string{ + "browser", "profile", "name", "id", "description", "version", "homepage_url", "enabled", + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expect, structCSVHeader(tt.record)) + }) + } +} + +func TestStructCSVRow(t *testing.T) { + tests := []struct { + name string + record record.Record + expect []string + }{ + { + "Login", + &record.Login{ + Browser: "Chrome", Profile: "Default", + URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: refTime, Store: record.StoreLocal, + }, + []string{"Chrome", "Default", "https://example.com", "alice", "secret", "2026-01-15T10:30:00Z", "local"}, + }, + { + "Cookie", + &record.Cookie{ + Host: ".example.com", Path: "/", Name: "session", Value: "abc", + IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: false, + ExpireAt: refTime, CreatedAt: refTime, + }, + []string{"", "", ".example.com", "/", "session", "abc", "true", "true", "true", "false", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z", ""}, + }, + { + "History_int", + &record.History{URL: "https://a.com", Title: "A", VisitCount: 42, LastVisit: refTime}, + []string{"", "", "https://a.com", "A", "42", "2026-01-15T10:30:00Z"}, + }, + { + "Download_int64", + &record.Download{URL: "https://a.com", TargetPath: "/tmp/f", MimeType: "text/plain", TotalBytes: 1024, StartTime: refTime, EndTime: refTime}, + []string{"", "", "https://a.com", "/tmp/f", "text/plain", "1024", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z"}, + }, + { + "Extension_bool", + &record.Extension{Name: "ext", ID: "abc", Description: "desc", Version: "1.0", HomepageURL: "https://x.com", Enabled: true}, + []string{"", "", "ext", "abc", "desc", "1.0", "https://x.com", "true"}, + }, + { + "zero_time", + &record.Login{URL: "https://a.com"}, + []string{"", "", "https://a.com", "", "", "", ""}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expect, structCSVRow(tt.record)) + }) + } +} diff --git a/internal/export/writer.go b/internal/export/writer.go new file mode 100644 index 0000000..1b8ab06 --- /dev/null +++ b/internal/export/writer.go @@ -0,0 +1,117 @@ +package export + +import ( + "bufio" + "errors" + "fmt" + "os" + "path/filepath" + + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +type Writer struct { + dir string + format Format + files map[category.Category]*categoryFile + failed bool +} + +type categoryFile struct { + name string + file *os.File + buf *bufio.Writer + enc encoder + count int +} + +func NewWriter(dir string, f Format) (*Writer, error) { + if err := os.MkdirAll(dir, 0o750); err != nil { + return nil, fmt.Errorf("create output dir: %w", err) + } + return &Writer{dir: dir, format: f, files: make(map[category.Category]*categoryFile)}, nil +} + +// Write reorders records in place. +func (w *Writer) Write(c category.Category, records []record.Record) error { + if err := w.write(c, records); err != nil { + w.failed = true + return err + } + return nil +} + +func (w *Writer) write(c category.Category, records []record.Record) error { + if len(records) == 0 { + return nil + } + for _, r := range records { + if r.Category() != c { + return fmt.Errorf("%T is not a %s record", r, c) + } + } + cf, err := w.open(c) + if err != nil { + return err + } + sortRecords(records) + for _, r := range records { + if err := cf.enc.encode(r); err != nil { + return fmt.Errorf("write %s: %w", cf.name, err) + } + cf.count++ + } + return nil +} + +// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them. +func (w *Writer) Close() error { + var errs []error + for _, c := range category.All() { + if cf, ok := w.files[c]; ok { + errs = append(errs, cf.close()) + } + } + if err := errors.Join(errs...); err != nil { + return err + } + if w.failed || len(w.files) == 0 { + return nil + } + fmt.Fprintln(os.Stderr) + log.Infof("Exported to %s/", w.dir) + for _, c := range category.All() { + if cf, ok := w.files[c]; ok { + log.Infof(" %-24s %d entries", cf.name, cf.count) + } + } + return nil +} + +func (w *Writer) open(c category.Category) (*categoryFile, error) { + if cf, ok := w.files[c]; ok { + return cf, nil + } + name := c.String() + "." + w.format.ext() + f, err := os.OpenFile(filepath.Join(w.dir, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + if err != nil { + return nil, fmt.Errorf("create %s: %w", name, err) + } + buf := bufio.NewWriter(f) + cf := &categoryFile{name: name, file: f, buf: buf, enc: newEncoder(buf, w.format, c)} + w.files[c] = cf + return cf, nil +} + +func (cf *categoryFile) close() error { + err := cf.enc.end() + if err == nil { + err = cf.buf.Flush() + } + if err = errors.Join(err, cf.file.Close()); err != nil { + return fmt.Errorf("write %s: %w", cf.name, err) + } + return nil +} diff --git a/output/output_test.go b/internal/export/writer_test.go similarity index 52% rename from output/output_test.go rename to internal/export/writer_test.go index 2d42cf1..357c5d4 100644 --- a/output/output_test.go +++ b/internal/export/writer_test.go @@ -1,6 +1,7 @@ -package output +package export import ( + "bytes" "encoding/csv" "encoding/json" "os" @@ -12,78 +13,97 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/types" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" ) var testTime = time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC) -func chromeData() *types.BrowserData { - return &types.BrowserData{ - Passwords: []types.LoginEntry{ - {URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: testTime, Store: types.PasswordStoreAccount}, - }, - Cookies: []types.CookieEntry{ - { - Host: ".example.com", Path: "/", Name: "session", Value: "abc123", - IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true, - ExpireAt: testTime, CreatedAt: testTime, - }, - }, - Histories: []types.HistoryEntry{ - {URL: "https://example.com", Title: "Example", VisitCount: 5, LastVisit: testTime}, - }, +type extraction struct { + c category.Category + records []record.Record +} + +func chromeExtractions() []extraction { + return []extraction{ + {category.Password, []record.Record{&record.Login{ + Browser: "Chrome", Profile: "Default", + URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: testTime, Store: record.StoreAccount, + }}}, + {category.Cookie, []record.Record{&record.Cookie{ + Browser: "Chrome", Profile: "Default", + Host: ".example.com", Path: "/", Name: "session", Value: "abc123", + IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true, + ExpireAt: testTime, CreatedAt: testTime, + }}}, + {category.History, []record.Record{&record.History{ + Browser: "Chrome", Profile: "Default", + URL: "https://example.com", Title: "Example", VisitCount: 5, LastVisit: testTime, + }}}, } } -func firefoxData() *types.BrowserData { - return &types.BrowserData{ - Passwords: []types.LoginEntry{ - {URL: "https://reddit.com", Username: "bob", Password: "hunter2", CreatedAt: testTime, Store: types.PasswordStoreLocal}, - }, - Cookies: []types.CookieEntry{ - { - Host: ".reddit.com", Path: "/", Name: "token", Value: "xyz789", - IsSecure: true, IsHTTPOnly: false, ExpireAt: testTime, CreatedAt: testTime, - }, - }, +func firefoxExtractions() []extraction { + return []extraction{ + {category.Password, []record.Record{&record.Login{ + Browser: "Firefox", Profile: "abc123", + URL: "https://reddit.com", Username: "bob", Password: "hunter2", CreatedAt: testTime, Store: record.StoreLocal, + }}}, + {category.Cookie, []record.Record{&record.Cookie{ + Browser: "Firefox", Profile: "abc123", + Host: ".reddit.com", Path: "/", Name: "token", Value: "xyz789", + IsSecure: true, IsHTTPOnly: false, ExpireAt: testTime, CreatedAt: testTime, + }}}, } } -// --- New --- +func writeAll(t *testing.T, dir string, f Format, extractions ...extraction) { + t.Helper() + w, err := NewWriter(dir, f) + require.NoError(t, err) + for _, e := range extractions { + require.NoError(t, w.Write(e.c, e.records)) + } + require.NoError(t, w.Close()) +} -func TestNew(t *testing.T) { +// --- Format --- + +func TestParseFormat(t *testing.T) { tests := []struct { - format string - wantErr bool + in string + want Format }{ - {"csv", false}, - {"json", false}, - {"cookie-editor", false}, - {"unknown", true}, + {"json", JSON}, + {"csv", CSV}, + {"cookie-editor", CookieEditor}, } for _, tt := range tests { - t.Run(tt.format, func(t *testing.T) { - out, err := NewWriter(t.TempDir(), tt.format) - if tt.wantErr { - require.Error(t, err) - assert.Nil(t, out) - } else { - require.NoError(t, err) - assert.NotNil(t, out) - } - }) + got, err := ParseFormat(tt.in) + require.NoError(t, err) + assert.Equal(t, tt.want, got) } + _, err := ParseFormat("unknown") + require.EqualError(t, err, "unsupported format: unknown") +} + +func TestFormat_ZeroIsJSON(t *testing.T) { + var f Format + assert.Equal(t, JSON, f) +} + +func TestNewWriter_CreatesDir(t *testing.T) { + dir := filepath.Join(t.TempDir(), "nested", "results") + _, err := NewWriter(dir, JSON) + require.NoError(t, err) + assert.DirExists(t, dir) } // --- CSV output --- func TestWrite_CSV_Password(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "csv") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - out.Add("Firefox", "abc123", firefoxData()) - require.NoError(t, out.Write()) + writeAll(t, dir, CSV, append(chromeExtractions(), firefoxExtractions()...)...) records := readCSV(t, filepath.Join(dir, "password.csv")) require.Len(t, records, 3) // header + 2 rows @@ -95,10 +115,7 @@ func TestWrite_CSV_Password(t *testing.T) { func TestWrite_CSV_Cookie(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "csv") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - require.NoError(t, out.Write()) + writeAll(t, dir, CSV, chromeExtractions()...) records := readCSV(t, filepath.Join(dir, "cookie.csv")) require.Len(t, records, 2) @@ -121,40 +138,31 @@ func TestWrite_CSV_Cookie(t *testing.T) { func TestWrite_CSV_History(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "csv") - require.NoError(t, err) - out.Add("Chrome", "Profile 1", chromeData()) - require.NoError(t, out.Write()) + writeAll(t, dir, CSV, chromeExtractions()...) records := readCSV(t, filepath.Join(dir, "history.csv")) require.Len(t, records, 2) assert.Equal(t, []string{"browser", "profile", "url", "title", "visit_count", "last_visit"}, records[0]) - assert.Equal(t, []string{"Chrome", "Profile 1", "https://example.com", "Example", "5", "2026-01-15T10:30:00Z"}, records[1]) + assert.Equal(t, []string{"Chrome", "Default", "https://example.com", "Example", "5", "2026-01-15T10:30:00Z"}, records[1]) } func TestWrite_CSV_UTF8BOM(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "csv") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - require.NoError(t, out.Write()) + writeAll(t, dir, CSV, append(chromeExtractions(), firefoxExtractions()...)...) raw, err := os.ReadFile(filepath.Join(dir, "password.csv")) require.NoError(t, err) require.GreaterOrEqual(t, len(raw), 3) assert.Equal(t, utf8BOM, raw[:3], "CSV should start with UTF-8 BOM") + assert.Equal(t, 1, bytes.Count(raw, utf8BOM), "one BOM however many writes") } // --- JSON output --- func TestWrite_JSON_Password(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "json") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - out.Add("Firefox", "abc123", firefoxData()) - require.NoError(t, out.Write()) + writeAll(t, dir, JSON, append(chromeExtractions(), firefoxExtractions()...)...) type pwJSON struct { Browser string `json:"browser"` @@ -180,10 +188,7 @@ func TestWrite_JSON_Password(t *testing.T) { func TestWrite_JSON_Cookie(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "json") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - require.NoError(t, out.Write()) + writeAll(t, dir, JSON, chromeExtractions()...) type ckJSON struct { Browser string `json:"browser"` @@ -213,10 +218,7 @@ func TestWrite_JSON_Cookie(t *testing.T) { func TestWrite_JSON_NoBOM(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "json") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - require.NoError(t, out.Write()) + writeAll(t, dir, JSON, chromeExtractions()...) raw, err := os.ReadFile(filepath.Join(dir, "password.json")) require.NoError(t, err) @@ -229,10 +231,7 @@ func TestWrite_JSON_NoBOM(t *testing.T) { func TestWrite_CookieEditor(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "cookie-editor") - require.NoError(t, err) - out.Add("Chrome", "Default", chromeData()) - require.NoError(t, out.Write()) + writeAll(t, dir, CookieEditor, chromeExtractions()...) var entries []cookieEditorEntry readJSON(t, filepath.Join(dir, "cookie.json"), &entries) @@ -251,15 +250,10 @@ func TestWrite_CookieEditor(t *testing.T) { func TestWrite_CookieEditor_FallbackJSON(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "cookie-editor") - require.NoError(t, err) - out.Add("Chrome", "Default", &types.BrowserData{ - Passwords: []types.LoginEntry{{URL: "https://a.com"}}, - }) - require.NoError(t, out.Write()) + writeAll(t, dir, CookieEditor, extraction{category.Password, []record.Record{&record.Login{URL: "https://a.com"}}}) // non-cookie categories fall back to standard JSON format - _, err = os.Stat(filepath.Join(dir, "password.json")) + _, err := os.Stat(filepath.Join(dir, "password.json")) assert.False(t, os.IsNotExist(err), "password.json should be created via JSON fallback") } @@ -267,15 +261,13 @@ func TestWrite_CookieEditor_FallbackJSON(t *testing.T) { func TestWrite_EmptyCategoryNoFile(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "csv") - require.NoError(t, err) - out.Add("Chrome", "Default", &types.BrowserData{ - Passwords: []types.LoginEntry{{URL: "https://a.com"}}, - }) - require.NoError(t, out.Write()) + writeAll(t, dir, CSV, + extraction{category.Password, []record.Record{&record.Login{URL: "https://a.com"}}}, + extraction{category.Cookie, nil}, + ) assert.FileExists(t, filepath.Join(dir, "password.csv")) - _, err = os.Stat(filepath.Join(dir, "cookie.csv")) + _, err := os.Stat(filepath.Join(dir, "cookie.csv")) assert.True(t, os.IsNotExist(err)) _, err = os.Stat(filepath.Join(dir, "history.csv")) assert.True(t, os.IsNotExist(err)) @@ -283,14 +275,64 @@ func TestWrite_EmptyCategoryNoFile(t *testing.T) { func TestWrite_NoData(t *testing.T) { dir := t.TempDir() - out, err := NewWriter(dir, "csv") - require.NoError(t, err) - require.NoError(t, out.Write()) + writeAll(t, dir, CSV) - entries, _ := os.ReadDir(dir) + entries, err := os.ReadDir(dir) + require.NoError(t, err) assert.Empty(t, entries, "no files should be created when no data added") } +// --- Appending extractions --- + +func TestWrite_AppendsExtractionsInWriteOrder(t *testing.T) { + dir := t.TempDir() + older := &record.History{Browser: "Chrome", Profile: "Default", URL: "https://a.example", VisitCount: 1} + busier := &record.History{Browser: "Chrome", Profile: "Profile 1", URL: "https://b.example", VisitCount: 99} + writeAll(t, dir, JSON, + extraction{category.History, []record.Record{older}}, + extraction{category.History, []record.Record{busier}}, + ) + + var rows []record.History + readJSON(t, filepath.Join(dir, "history.json"), &rows) + assert.Equal(t, []record.History{*older, *busier}, rows, "each extraction is sorted on its own, then appended") +} + +// --- Error paths --- + +func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { + dir := t.TempDir() + w, err := NewWriter(dir, JSON) + require.NoError(t, err) + require.EqualError(t, w.Write(category.Cookie, []record.Record{&record.Login{}}), "*record.Login is not a cookie record") + require.NoError(t, w.Close()) + + entries, err := os.ReadDir(dir) + require.NoError(t, err) + assert.Empty(t, entries) +} + +// A failed Write must not cost the files already written: Close still completes them. +func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { + dir := t.TempDir() + w, err := NewWriter(dir, JSON) + require.NoError(t, err) + require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://kept.example"}})) + + beyondJSON := time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC) + require.Error(t, w.Write(category.Cookie, []record.Record{&record.Cookie{Host: "bad.example", ExpireAt: beyondJSON}})) + require.NoError(t, w.Close()) + + var logins []record.Login + readJSON(t, filepath.Join(dir, "password.json"), &logins) + require.Len(t, logins, 1) + assert.Equal(t, "https://kept.example", logins[0].URL) + + var cookies []record.Cookie + readJSON(t, filepath.Join(dir, "cookie.json"), &cookies) + assert.Empty(t, cookies) +} + // --- helpers --- func readCSV(t *testing.T, path string) [][]string { diff --git a/internal/record/record.go b/internal/record/record.go new file mode 100644 index 0000000..9aecb0e --- /dev/null +++ b/internal/record/record.go @@ -0,0 +1,149 @@ +package record + +import ( + "time" + + "github.com/moond4rk/hackbrowserdata/internal/category" +) + +// Record is sealed by the unexported stamp, so only this package's types are records. +type Record interface { + Category() category.Category + stamp(browser, profile string) +} + +// Stamp is exported because the sealing method stamp cannot be called from other packages. +func Stamp(r Record, browser, profile string) { + r.stamp(browser, profile) +} + +// Named Login, not Password: the row holds a URL and a user name as well as the password. +type Login struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + URL string `json:"url" csv:"url"` + Username string `json:"username" csv:"username"` + Password string `json:"password" csv:"password"` + CreatedAt time.Time `json:"created_at" csv:"created_at"` + Store Store `json:"store" csv:"store"` +} + +// Store names the Chromium login database a Login came from; a credential kept in both is exported twice. +type Store string + +const ( + StoreLocal Store = "local" // Login Data + StoreAccount Store = "account" // Login Data For Account +) + +type Cookie struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + Host string `json:"host" csv:"host"` + Path string `json:"path" csv:"path"` + Name string `json:"name" csv:"name"` + Value string `json:"value" csv:"value"` + IsSecure bool `json:"is_secure" csv:"is_secure"` + IsHTTPOnly bool `json:"is_http_only" csv:"is_http_only"` + HasExpire bool `json:"has_expire" csv:"has_expire"` + IsPersistent bool `json:"is_persistent" csv:"is_persistent"` + ExpireAt time.Time `json:"expire_at" csv:"expire_at"` + CreatedAt time.Time `json:"created_at" csv:"created_at"` + SameSite string `json:"same_site" csv:"same_site"` +} + +type Bookmark struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + ID int64 `json:"id" csv:"id"` + Name string `json:"name" csv:"name"` + Type string `json:"type" csv:"type"` + URL string `json:"url" csv:"url"` + Folder string `json:"folder" csv:"folder"` + CreatedAt time.Time `json:"created_at" csv:"created_at"` +} + +type History struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + URL string `json:"url" csv:"url"` + Title string `json:"title" csv:"title"` + VisitCount int `json:"visit_count" csv:"visit_count"` + LastVisit time.Time `json:"last_visit" csv:"last_visit"` +} + +type Download struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + URL string `json:"url" csv:"url"` + TargetPath string `json:"target_path" csv:"target_path"` + MimeType string `json:"mime_type" csv:"mime_type"` + TotalBytes int64 `json:"total_bytes" csv:"total_bytes"` + StartTime time.Time `json:"start_time" csv:"start_time"` + EndTime time.Time `json:"end_time" csv:"end_time"` +} + +// CreditCard's CVC and Comment are Yandex-specific; Chromium leaves them empty. +type CreditCard struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + GUID string `json:"guid" csv:"guid"` + Name string `json:"name" csv:"name"` + Number string `json:"number" csv:"number"` + ExpMonth string `json:"exp_month" csv:"exp_month"` + ExpYear string `json:"exp_year" csv:"exp_year"` + NickName string `json:"nick_name" csv:"nick_name"` + Address string `json:"address" csv:"address"` + CVC string `json:"cvc" csv:"cvc"` + Comment string `json:"comment" csv:"comment"` +} + +type Extension struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + Name string `json:"name" csv:"name"` + ID string `json:"id" csv:"id"` + Description string `json:"description" csv:"description"` + Version string `json:"version" csv:"version"` + HomepageURL string `json:"homepage_url" csv:"homepage_url"` + Enabled bool `json:"enabled" csv:"enabled"` +} + +type LocalStorage struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + IsMeta bool `json:"is_meta" csv:"is_meta"` + URL string `json:"url" csv:"url"` + Key string `json:"key" csv:"key"` + Value string `json:"value" csv:"value"` +} + +// SessionStorage repeats LocalStorage's fields so that each record type belongs to exactly one category. +type SessionStorage struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + IsMeta bool `json:"is_meta" csv:"is_meta"` + URL string `json:"url" csv:"url"` + Key string `json:"key" csv:"key"` + Value string `json:"value" csv:"value"` +} + +func (r *Login) Category() category.Category { return category.Password } +func (r *Cookie) Category() category.Category { return category.Cookie } +func (r *Bookmark) Category() category.Category { return category.Bookmark } +func (r *History) Category() category.Category { return category.History } +func (r *Download) Category() category.Category { return category.Download } +func (r *CreditCard) Category() category.Category { return category.CreditCard } +func (r *Extension) Category() category.Category { return category.Extension } +func (r *LocalStorage) Category() category.Category { return category.LocalStorage } +func (r *SessionStorage) Category() category.Category { return category.SessionStorage } + +func (r *Login) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *Cookie) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *Bookmark) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *History) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *Download) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *CreditCard) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *Extension) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *LocalStorage) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *SessionStorage) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } diff --git a/internal/record/record_test.go b/internal/record/record_test.go new file mode 100644 index 0000000..c61e9bd --- /dev/null +++ b/internal/record/record_test.go @@ -0,0 +1,89 @@ +package record + +import ( + "reflect" + "strings" + "testing" + "unicode" + + "github.com/stretchr/testify/assert" + + "github.com/moond4rk/hackbrowserdata/internal/category" +) + +func allRecords() map[category.Category]Record { + return map[category.Category]Record{ + category.Password: &Login{}, + category.Cookie: &Cookie{}, + category.Bookmark: &Bookmark{}, + category.History: &History{}, + category.Download: &Download{}, + category.CreditCard: &CreditCard{}, + category.Extension: &Extension{}, + category.LocalStorage: &LocalStorage{}, + category.SessionStorage: &SessionStorage{}, + } +} + +func TestCategory_OneRecordTypePerCategory(t *testing.T) { + records := allRecords() + assert.Len(t, records, len(category.All())) + for _, c := range category.All() { + r, ok := records[c] + if assert.Truef(t, ok, "no record type for %s", c) { + assert.Equalf(t, c, r.Category(), "%T", r) + } + } +} + +func TestStamp(t *testing.T) { + for _, r := range allRecords() { + Stamp(r, "Microsoft Edge", "Profile 1") + v := reflect.ValueOf(r).Elem() + assert.Equalf(t, "Microsoft Edge", v.FieldByName("Browser").String(), "%T", r) + assert.Equalf(t, "Profile 1", v.FieldByName("Profile").String(), "%T", r) + } +} + +// The tags are the output's field names and column headers, so they stay snake_case(field name) and lead with the stamp. +func TestTags_AreSnakeCaseFieldNames(t *testing.T) { + for _, r := range allRecords() { + typ := reflect.TypeOf(r).Elem() + assert.Equalf(t, "Browser", typ.Field(0).Name, "%s", typ) + assert.Equalf(t, "Profile", typ.Field(1).Name, "%s", typ) + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + want := snakeCase(f.Name) + assert.Equalf(t, want, f.Tag.Get("json"), "%s.%s json tag", typ, f.Name) + assert.Equalf(t, want, f.Tag.Get("csv"), "%s.%s csv tag", typ, f.Name) + } + } +} + +func snakeCase(name string) string { + runes := []rune(name) + var b strings.Builder + for i, r := range runes { + if i > 0 && unicode.IsUpper(r) { + prevLower := unicode.IsLower(runes[i-1]) + acronymEnds := unicode.IsUpper(runes[i-1]) && i+1 < len(runes) && unicode.IsLower(runes[i+1]) + if prevLower || acronymEnds { + b.WriteByte('_') + } + } + b.WriteRune(unicode.ToLower(r)) + } + return b.String() +} + +func TestSnakeCase(t *testing.T) { + for name, want := range map[string]string{ + "URL": "url", + "IsHTTPOnly": "is_http_only", + "HomepageURL": "homepage_url", + "NickName": "nick_name", + "GUID": "guid", + } { + assert.Equal(t, want, snakeCase(name)) + } +} diff --git a/output/cookie_editor.go b/output/cookie_editor.go deleted file mode 100644 index ae0bd3d..0000000 --- a/output/cookie_editor.go +++ /dev/null @@ -1,77 +0,0 @@ -package output - -import ( - "encoding/json" - "io" - "strings" - - "github.com/moond4rk/hackbrowserdata/types" -) - -// cookieEditorFormatter outputs cookies in the CookieEditor browser extension -// format. Non-cookie categories fall back to standard JSON output. -type cookieEditorFormatter struct { - fallback *jsonFormatter -} - -func (f *cookieEditorFormatter) ext() string { return "json" } - -var sameSiteNone = "no_restriction" - -func (f *cookieEditorFormatter) format(w io.Writer, rows []row) error { - if len(rows) == 0 { - return nil - } - // aggregate() guarantees all rows in a batch share the same type; - // check the first row to decide the format. - if _, ok := rows[0].entry.(types.CookieEntry); !ok { - return f.fallback.format(w, rows) - } - - entries := make([]cookieEditorEntry, 0, len(rows)) - for _, r := range rows { - c, _ := r.entry.(types.CookieEntry) - var expDate float64 - if !c.ExpireAt.IsZero() { - expDate = float64(c.ExpireAt.Unix()) - } - sameSite := &c.SameSite - switch c.SameSite { - case "none": - sameSite = &sameSiteNone - case "", "unspecified": - sameSite = nil - } - entries = append(entries, cookieEditorEntry{ - Domain: c.Host, - ExpirationDate: expDate, - HTTPOnly: c.IsHTTPOnly, - Name: c.Name, - Path: c.Path, - Secure: c.IsSecure, - Value: c.Value, - SameSite: sameSite, - Session: expDate == 0., - HostOnly: !strings.HasPrefix(c.Host, "."), - }) - } - - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - enc.SetEscapeHTML(false) - return enc.Encode(entries) -} - -// cookieEditorEntry matches the CookieEditor browser extension's import format. -type cookieEditorEntry struct { - Domain string `json:"domain"` - ExpirationDate float64 `json:"expirationDate,omitempty"` - HTTPOnly bool `json:"httpOnly"` - Name string `json:"name"` - Path string `json:"path"` - Secure bool `json:"secure"` - Value string `json:"value"` - SameSite *string `json:"sameSite"` - Session bool `json:"session"` - HostOnly bool `json:"hostOnly"` -} diff --git a/output/csv.go b/output/csv.go deleted file mode 100644 index bf45e0d..0000000 --- a/output/csv.go +++ /dev/null @@ -1,28 +0,0 @@ -package output - -import ( - "encoding/csv" - "io" -) - -type csvFormatter struct{} - -func (f *csvFormatter) ext() string { return "csv" } - -func (f *csvFormatter) format(w io.Writer, rows []row) error { - if len(rows) == 0 { - return nil - } - - cw := csv.NewWriter(w) - if err := cw.Write(rows[0].csvHeader()); err != nil { - return err - } - for _, r := range rows { - if err := cw.Write(r.csvRow()); err != nil { - return err - } - } - cw.Flush() - return cw.Error() -} diff --git a/output/formatter.go b/output/formatter.go deleted file mode 100644 index 9306919..0000000 --- a/output/formatter.go +++ /dev/null @@ -1,25 +0,0 @@ -package output - -import ( - "fmt" - "io" -) - -// formatter serializes rows to a writer. Unexported — only used by Writer. -type formatter interface { - format(w io.Writer, rows []row) error - ext() string -} - -func newFormatter(name string) (formatter, error) { - switch name { - case "csv": - return &csvFormatter{}, nil - case "json": - return &jsonFormatter{}, nil - case "cookie-editor": - return &cookieEditorFormatter{fallback: &jsonFormatter{}}, nil - default: - return nil, fmt.Errorf("unsupported format: %s", name) - } -} diff --git a/output/json.go b/output/json.go deleted file mode 100644 index ccc9c06..0000000 --- a/output/json.go +++ /dev/null @@ -1,17 +0,0 @@ -package output - -import ( - "encoding/json" - "io" -) - -type jsonFormatter struct{} - -func (f *jsonFormatter) ext() string { return "json" } - -func (f *jsonFormatter) format(w io.Writer, rows []row) error { - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - enc.SetEscapeHTML(false) - return enc.Encode(rows) -} diff --git a/output/output.go b/output/output.go deleted file mode 100644 index ed98cf6..0000000 --- a/output/output.go +++ /dev/null @@ -1,168 +0,0 @@ -// Package output writes extracted browser data to files. -// -// Usage: -// -// w, _ := output.NewWriter(dir, "csv") -// w.Add(browserName, profileName, data) -// w.Write() -// -// Supported formats: csv, json, cookie-editor. -package output - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/types" -) - -// utf8BOM is written at the start of CSV files for Excel compatibility. -var utf8BOM = []byte{0xEF, 0xBB, 0xBF} - -// Writer collects browser data and writes it to files. -// It is the only exported type in this package. -type Writer struct { - dir string - formatter formatter - results []result -} - -type result struct { - browser string - profile string - data *types.BrowserData -} - -// NewWriter creates a Writer that writes to dir in the given format. -func NewWriter(dir, format string) (*Writer, error) { - f, err := newFormatter(format) - if err != nil { - return nil, err - } - return &Writer{dir: dir, formatter: f}, nil -} - -// Add accumulates one browser profile's data for later writing. -func (o *Writer) Add(browser, profile string, data *types.BrowserData) { - if data == nil { - return - } - o.results = append(o.results, result{browser, profile, data}) -} - -// Write aggregates all accumulated data by category and writes each -// non-empty category to its own file (e.g. password.csv, cookie.json). -func (o *Writer) Write() error { - if err := os.MkdirAll(o.dir, 0o750); err != nil { - return fmt.Errorf("create output dir: %w", err) - } - agg := o.aggregate() - for _, cs := range agg { - if err := o.writeFile(cs.name, cs.rows); err != nil { - return err - } - } - if len(agg) > 0 { - fmt.Fprintln(os.Stderr) - log.Infof("Exported to %s/", o.dir) - for _, cs := range agg { - filename := fmt.Sprintf("%s.%s", cs.name, o.formatter.ext()) - log.Infof(" %-24s %d entries", filename, len(cs.rows)) - } - } - return nil -} - -// categoryRows holds one category's aggregated rows for writing. -type categoryRows struct { - name string - rows []row -} - -// extractor pulls rows from a single result for one category. -type extractor func(r result) []row - -// makeExtractor creates a type-safe extractor using generics. -func makeExtractor[T any](entries func(*types.BrowserData) []T) extractor { - return func(r result) []row { - items := entries(r.data) - rows := make([]row, 0, len(items)) - for _, e := range items { - rows = append(rows, row{Browser: r.browser, Profile: r.profile, entry: e}) - } - return rows - } -} - -// categories maps each data category to its extractor. -// Adding a new category requires only one line here. -var categories = []struct { - name string - extract extractor -}{ - {"password", makeExtractor(func(d *types.BrowserData) []types.LoginEntry { return d.Passwords })}, - {"cookie", makeExtractor(func(d *types.BrowserData) []types.CookieEntry { return d.Cookies })}, - {"history", makeExtractor(func(d *types.BrowserData) []types.HistoryEntry { return d.Histories })}, - {"download", makeExtractor(func(d *types.BrowserData) []types.DownloadEntry { return d.Downloads })}, - {"bookmark", makeExtractor(func(d *types.BrowserData) []types.BookmarkEntry { return d.Bookmarks })}, - {"creditcard", makeExtractor(func(d *types.BrowserData) []types.CreditCardEntry { return d.CreditCards })}, - {"extension", makeExtractor(func(d *types.BrowserData) []types.ExtensionEntry { return d.Extensions })}, - {"localstorage", makeExtractor(func(d *types.BrowserData) []types.StorageEntry { return d.LocalStorage })}, - {"sessionstorage", makeExtractor(func(d *types.BrowserData) []types.StorageEntry { return d.SessionStorage })}, -} - -// aggregate merges all results into row slices grouped by category, -// returning only non-empty categories. -func (o *Writer) aggregate() []categoryRows { - var s []categoryRows - for _, cat := range categories { - var rows []row - for _, r := range o.results { - rows = append(rows, cat.extract(r)...) - } - if len(rows) > 0 { - s = append(s, categoryRows{cat.name, rows}) - } - } - return s -} - -func (o *Writer) writeFile(category string, rows []row) (err error) { - // Format to buffer first — if formatter produces no output (e.g. - // cookie-editor skipping non-cookie data), don't create the file. - var buf bytes.Buffer - if err := o.formatter.format(&buf, rows); err != nil { - return fmt.Errorf("format %s: %w", category, err) - } - if buf.Len() == 0 { - return nil - } - - filename := fmt.Sprintf("%s.%s", category, o.formatter.ext()) - path := filepath.Join(o.dir, filename) - - f, err := os.OpenFile(filepath.Clean(path), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) - if err != nil { - return fmt.Errorf("create %s: %w", filename, err) - } - defer func() { - if cerr := f.Close(); cerr != nil && err == nil { - err = fmt.Errorf("close %s: %w", filename, cerr) - } - }() - - if strings.HasSuffix(path, ".csv") { - if _, err := f.Write(utf8BOM); err != nil { - return fmt.Errorf("write BOM: %w", err) - } - } - - if _, err := f.Write(buf.Bytes()); err != nil { - return fmt.Errorf("write %s: %w", filename, err) - } - return nil -} diff --git a/output/reflect_test.go b/output/reflect_test.go deleted file mode 100644 index 86dd790..0000000 --- a/output/reflect_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package output - -import ( - "encoding/json" - "reflect" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/types" -) - -var refTime = time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC) - -// allEntryTypes lists every entry type that appears in BrowserData. -// If a new entry type is added, it must be included here. -var allEntryTypes = []any{ - types.LoginEntry{}, - types.CookieEntry{}, - types.BookmarkEntry{}, - types.HistoryEntry{}, - types.DownloadEntry{}, - types.CreditCardEntry{}, - types.StorageEntry{}, - types.ExtensionEntry{}, -} - -// TestAllEntryFieldsHaveCSVTag verifies that every exported field -// in every entry type has a csv tag. A missing tag means the field -// will be silently omitted from CSV output. -func TestAllEntryFieldsHaveCSVTag(t *testing.T) { - for _, entry := range allEntryTypes { - et := reflect.TypeOf(entry) - t.Run(et.Name(), func(t *testing.T) { - for i := 0; i < et.NumField(); i++ { - f := et.Field(i) - if !f.IsExported() { - continue - } - _, ok := f.Tag.Lookup("csv") - assert.True(t, ok, "field %s.%s missing csv tag", et.Name(), f.Name) - } - }) - } -} - -func TestStructCSVHeader(t *testing.T) { - tests := []struct { - name string - entry any - expect []string - }{ - {"LoginEntry", types.LoginEntry{}, []string{"url", "username", "password", "created_at", "store"}}, - {"CookieEntry", types.CookieEntry{}, []string{"host", "path", "name", "value", "is_secure", "is_http_only", "has_expire", "is_persistent", "expire_at", "created_at", "same_site"}}, - {"BookmarkEntry", types.BookmarkEntry{}, []string{"id", "name", "type", "url", "folder", "created_at"}}, - {"HistoryEntry", types.HistoryEntry{}, []string{"url", "title", "visit_count", "last_visit"}}, - {"DownloadEntry", types.DownloadEntry{}, []string{"url", "target_path", "mime_type", "total_bytes", "start_time", "end_time"}}, - {"CreditCardEntry", types.CreditCardEntry{}, []string{"guid", "name", "number", "exp_month", "exp_year", "nick_name", "address", "cvc", "comment"}}, - {"StorageEntry", types.StorageEntry{}, []string{"is_meta", "url", "key", "value"}}, - {"ExtensionEntry", types.ExtensionEntry{}, []string{"name", "id", "description", "version", "homepage_url", "enabled"}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.expect, structCSVHeader(tt.entry)) - }) - } -} - -func TestStructCSVRow(t *testing.T) { - tests := []struct { - name string - entry any - expect []string - }{ - { - "LoginEntry", - types.LoginEntry{URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: refTime, Store: types.PasswordStoreLocal}, - []string{"https://example.com", "alice", "secret", "2026-01-15T10:30:00Z", "local"}, - }, - { - "CookieEntry", - types.CookieEntry{ - Host: ".example.com", Path: "/", Name: "session", Value: "abc", - IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: false, - ExpireAt: refTime, CreatedAt: refTime, - }, - []string{".example.com", "/", "session", "abc", "true", "true", "true", "false", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z", ""}, - }, - { - "HistoryEntry_int", - types.HistoryEntry{URL: "https://a.com", Title: "A", VisitCount: 42, LastVisit: refTime}, - []string{"https://a.com", "A", "42", "2026-01-15T10:30:00Z"}, - }, - { - "DownloadEntry_int64", - types.DownloadEntry{URL: "https://a.com", TargetPath: "/tmp/f", MimeType: "text/plain", TotalBytes: 1024, StartTime: refTime, EndTime: refTime}, - []string{"https://a.com", "/tmp/f", "text/plain", "1024", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z"}, - }, - { - "ExtensionEntry_bool", - types.ExtensionEntry{Name: "ext", ID: "abc", Description: "desc", Version: "1.0", HomepageURL: "https://x.com", Enabled: true}, - []string{"ext", "abc", "desc", "1.0", "https://x.com", "true"}, - }, - { - "zero_time", - types.LoginEntry{URL: "https://a.com"}, - []string{"https://a.com", "", "", "", ""}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.expect, structCSVRow(tt.entry)) - }) - } -} - -// TestRowMarshalJSON verifies that row.MarshalJSON produces flat JSON -// with browser/profile first, followed by entry fields in declaration order. -func TestRowMarshalJSON(t *testing.T) { - t.Run("flat_structure", func(t *testing.T) { - r := row{ - Browser: "Chrome", - Profile: "Default", - entry: types.LoginEntry{ - URL: "https://example.com", Username: "alice", - Password: "secret", CreatedAt: refTime, - }, - } - - data, err := json.Marshal(r) - require.NoError(t, err) - - // Verify flat JSON (all keys at top level, no nesting). - var m map[string]any - require.NoError(t, json.Unmarshal(data, &m)) - assert.Equal(t, "Chrome", m["browser"]) - assert.Equal(t, "Default", m["profile"]) - assert.Equal(t, "https://example.com", m["url"]) - assert.Equal(t, "alice", m["username"]) - assert.Equal(t, "secret", m["password"]) - assert.Len(t, m, 7) // browser + profile + 5 entry fields - - // Verify field order: browser, profile come before entry fields. - raw := string(data) - browserIdx := strings.Index(raw, `"browser"`) - profileIdx := strings.Index(raw, `"profile"`) - urlIdx := strings.Index(raw, `"url"`) - assert.Less(t, browserIdx, urlIdx) - assert.Less(t, profileIdx, urlIdx) - }) - - t.Run("bool_and_time_fields", func(t *testing.T) { - r := row{ - Browser: "Firefox", - Profile: "test", - entry: types.CookieEntry{ - Host: ".example.com", IsSecure: true, IsHTTPOnly: false, - ExpireAt: refTime, - }, - } - - data, err := json.Marshal(r) - require.NoError(t, err) - - var m map[string]any - require.NoError(t, json.Unmarshal(data, &m)) - assert.Equal(t, "Firefox", m["browser"]) - assert.Equal(t, ".example.com", m["host"]) - assert.Equal(t, true, m["is_secure"]) - assert.Equal(t, false, m["is_http_only"]) - }) - - t.Run("special_characters", func(t *testing.T) { - r := row{ - Browser: `Ch"rome`, - Profile: "Default", - entry: types.LoginEntry{ - URL: `https://example.com/path?q="hello"&x=1`, - Password: `pass"word\with`, - }, - } - - data, err := json.Marshal(r) - require.NoError(t, err) - - var m map[string]any - require.NoError(t, json.Unmarshal(data, &m)) - assert.Equal(t, `Ch"rome`, m["browser"]) - assert.Equal(t, `https://example.com/path?q="hello"&x=1`, m["url"]) - assert.Equal(t, `pass"word\with`, m["password"]) - }) -} diff --git a/output/row.go b/output/row.go deleted file mode 100644 index 513f9cf..0000000 --- a/output/row.go +++ /dev/null @@ -1,47 +0,0 @@ -package output - -import ( - "encoding/json" - "reflect" -) - -// row wraps any entry with browser/profile context for output. -type row struct { - Browser string - Profile string - entry any -} - -func (r row) csvHeader() []string { - return append([]string{"browser", "profile"}, structCSVHeader(r.entry)...) -} - -func (r row) csvRow() []string { - return append([]string{r.Browser, r.Profile}, structCSVRow(r.entry)...) -} - -// MarshalJSON produces flat JSON with browser/profile followed by the entry's fields. -// Uses reflect.StructOf to dynamically build a struct that json.Marshal handles natively, -// avoiding manual JSON string concatenation. -func (r row) MarshalJSON() ([]byte, error) { - ev := reflect.ValueOf(r.entry) - et := ev.Type() - - fields := make([]reflect.StructField, 0, et.NumField()+2) - fields = append(fields, - reflect.StructField{Name: "Browser", Type: reflect.TypeOf(""), Tag: `json:"browser"`}, - reflect.StructField{Name: "Profile", Type: reflect.TypeOf(""), Tag: `json:"profile"`}, - ) - for i := 0; i < et.NumField(); i++ { - fields = append(fields, et.Field(i)) - } - - flat := reflect.New(reflect.StructOf(fields)).Elem() - flat.Field(0).SetString(r.Browser) - flat.Field(1).SetString(r.Profile) - for i := 0; i < et.NumField(); i++ { - flat.Field(i + 2).Set(ev.Field(i)) - } - - return json.Marshal(flat.Interface()) -} diff --git a/rfcs/008-output-and-export.md b/rfcs/008-output-and-export.md index c519b69..5cd3aad 100644 --- a/rfcs/008-output-and-export.md +++ b/rfcs/008-output-and-export.md @@ -44,18 +44,19 @@ Every record starts with two flat source fields — `Browser` and `Profile` ([RF ## Deterministic ordering -Output order is defined once per category, in the exporter, for every browser. Files list extractions in plan order — the browser table's order (one merged list whose per-OS projections equal today's `platformBrowsers()` orders), then user data dir ID, then profiles in discovery order (directory order for Chromium and Firefox, the default profile first for Safari) — which matches today's order. Within an extraction, records are sorted by today's key, with tie-breakers added and a stable sort (`sort.SliceStable`; Go 1.20 has no `slices`), so two runs over the same snapshot produce byte-identical files: +Output order is defined once per category, in the exporter, for every browser. Files list extractions in plan order — the browser table's order (one merged list whose per-OS projections equal today's `platformBrowsers()` orders), then user data dir ID, then profiles in discovery order (directory order for Chromium and Firefox, the default profile first for Safari) — which matches today's order. Within an extraction, records are sorted by today's key with a stable sort (`sort.SliceStable`; Go 1.20 has no `slices`), and ties keep the order the extractor emitted them in — the source order, which a snapshot fixes — so two runs over the same snapshot produce byte-identical files: -| Category | Order | -| --------------------------------------------------- | -------------------------------------------------------------------------------------- | -| password | `created_at` descending, then `store` (local before account), `url`, `username` | -| cookie | `created_at` descending, then `host`, `name`, `path` | -| history | `visit_count` descending, then `last_visit` descending, `url` | -| download | `start_time` descending, then `url` | -| bookmark | `created_at` descending, then `id` ascending | -| creditcard, extension, localstorage, sessionstorage | source order, made explicit (`ORDER BY rowid`, LevelDB key order, JSON document order) | +| Category | Order | +| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| password | `created_at` descending; on a tie, local before account, the order the Chromium extractor reads its two stores in | +| cookie, bookmark | `created_at` descending | +| history | `visit_count` descending | +| download | `start_time` descending | +| creditcard, extension, localstorage, sessionstorage | source order (row order, LevelDB key order, JSON document order) | -Today the order is decided in each extractor with an unstable `sort.Slice`, so ties come out in arbitrary order — and Firefox history sorts _ascending_ by visit count (`browser/firefox/extract_history.go`) while Chromium and Safari sort descending. The table above keeps today's keys and fixes Firefox to match the others. +Ties are not broken by a second key, because some sources lack the first: Safari bookmarks carry no creation time and Safari downloads no start time, so a tie-breaker such as `id` or `url` would replace their file order with an order nobody chose. A stable sort leaves them as the browser stored them. + +Today the order is decided in each extractor with an unstable `sort.Slice`, so ties come out in an order nobody chose — and Firefox history sorts _ascending_ by visit count (`browser/firefox/extract_history.go`) while Chromium and Safari sort descending. The table keeps today's keys and fixes Firefox to match the others. ## Streaming vs. buffering diff --git a/rfcs/011-testing-and-quality.md b/rfcs/011-testing-and-quality.md index c337fda..5a81079 100644 --- a/rfcs/011-testing-and-quality.md +++ b/rfcs/011-testing-and-quality.md @@ -67,7 +67,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so ## Import direction -The table in [RFC-002](002-package-layout.md) is kept by review, not by a linter or a test: every new import edge is either in the table or added to it in the same pull request. The compiler still rejects cycles. +The table in [RFC-002](002-package-layout.md) is kept by review, not by a linter or a test: every new import edge is either in the table or added to it in the same pull request. The compiler still rejects cycles. Until the switch-over, today's packages — and `cmd`, which still drives them — also import the new packages they are moving onto; those edges leave with the old code ([RFC-012](012-migration-roadmap.md)). ## Go 1.20 pitfalls diff --git a/rfcs/012-migration-roadmap.md b/rfcs/012-migration-roadmap.md index f03805f..5b8149a 100644 --- a/rfcs/012-migration-roadmap.md +++ b/rfcs/012-migration-roadmap.md @@ -30,7 +30,8 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou - Introduce `internal/category` — `Category` with bare values numbered from 1, today's `String()` values, `All` and `Parse` — and `internal/record`: `Login`, `Cookie`, and the other record types with flat `Browser` + `Profile` fields followed by today's field names and order, set through `record.Stamp` ([RFC-003](003-core-types.md)). - Apply the naming in [RFC-004](004-naming-decisions.md) verbatim: `types.Category` → `category.Category`, `types.LoginEntry` → `record.Login` and every other `…Entry` → its bare name, no `Category` prefix, no `Owner`/`Origin` umbrella. - Move `output` to `internal/export` — `Writer` and the `csv`, `json`, and `cookie-editor` encoders — on the new record types ([RFC-008](008-output-and-export.md)). It depends only on `category`, `record`, and `log`. -- No output change: `tagliatelle` and the parity suite must stay green. +- Move the row order out of the extractors into the exporter ([RFC-008](008-output-and-export.md)), so an extractor emits rows in source order. This lands the Firefox history order fix with its regression test. +- No other output change: `tagliatelle` and the parity suite must stay green. ### Phase 3 — `crypto`, `masterkey`, `keychain`, `winapi` @@ -52,7 +53,7 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou ### Phase 6 — Widen: Firefox and Safari - Port the Firefox and Safari bases one category at a time, each with a `testdata/` fixture and golden. -- Land the listed output fixes here — Firefox history order and bookmark fields, Safari bookmark IDs — each with its regression test and as an expected diff in the parity suite. +- Land the remaining listed output fixes here — Firefox bookmark fields and Safari bookmark IDs — each with its regression test and as an expected diff in the parity suite. ### Phase 7 — Switch over diff --git a/types/browser.go b/types/browser.go new file mode 100644 index 0000000..c7b9227 --- /dev/null +++ b/types/browser.go @@ -0,0 +1,56 @@ +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 // lookup key; doubles as the Windows ABE / winutil.Table key when WindowsABE is true + 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 new file mode 100644 index 0000000..ff65022 --- /dev/null +++ b/types/browser_test.go @@ -0,0 +1,24 @@ +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/category.go b/types/category.go deleted file mode 100644 index 933b66d..0000000 --- a/types/category.go +++ /dev/null @@ -1,124 +0,0 @@ -package types - -// Category represents a kind of browser data. -// It is browser-agnostic — a password is a password regardless of which browser it came from. -type Category int - -const ( - Password Category = iota - Cookie - Bookmark - History - Download - CreditCard - Extension - LocalStorage - SessionStorage -) - -// AllCategories returns all supported data categories. -var AllCategories = []Category{ - Password, Cookie, Bookmark, History, Download, - CreditCard, Extension, LocalStorage, SessionStorage, -} - -// String returns the human-readable name of the category. -func (c Category) String() string { - switch c { - case Password: - return "password" - case Cookie: - return "cookie" - case Bookmark: - return "bookmark" - case History: - return "history" - case Download: - return "download" - case CreditCard: - return "creditcard" - case Extension: - return "extension" - case LocalStorage: - return "localstorage" - case SessionStorage: - return "sessionstorage" - default: - return "unknown" - } -} - -// IsSensitive returns whether the category contains sensitive data -// that requires explicit opt-in to export. -func (c Category) IsSensitive() bool { - switch c { - case Password, Cookie, CreditCard: - return true - default: - return false - } -} - -// NonSensitiveCategories returns categories that are safe to export by default. -func NonSensitiveCategories() []Category { - var cats []Category - for _, c := range AllCategories { - if !c.IsSensitive() { - cats = append(cats, c) - } - } - return cats -} - -// 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 // lookup key; doubles as the Windows ABE / winutil.Table key when WindowsABE is true - 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 []LoginEntry - Cookies []CookieEntry - Histories []HistoryEntry - Downloads []DownloadEntry - Bookmarks []BookmarkEntry - CreditCards []CreditCardEntry - Extensions []ExtensionEntry - LocalStorage []StorageEntry - SessionStorage []StorageEntry -} diff --git a/types/category_test.go b/types/category_test.go deleted file mode 100644 index 44e93aa..0000000 --- a/types/category_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestCategory_String(t *testing.T) { - tests := []struct { - cat Category - want string - }{ - {Password, "password"}, - {Cookie, "cookie"}, - {Bookmark, "bookmark"}, - {History, "history"}, - {Download, "download"}, - {CreditCard, "creditcard"}, - {Extension, "extension"}, - {LocalStorage, "localstorage"}, - {SessionStorage, "sessionstorage"}, - {Category(999), "unknown"}, - } - for _, tt := range tests { - assert.Equal(t, tt.want, tt.cat.String()) - } -} - -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()) - } -} - -func TestCategory_IsSensitive(t *testing.T) { - sensitive := []Category{Password, Cookie, CreditCard} - for _, c := range sensitive { - assert.True(t, c.IsSensitive(), "%s should be sensitive", c) - } - - notSensitive := []Category{Bookmark, History, Download, Extension, LocalStorage, SessionStorage} - for _, c := range notSensitive { - assert.False(t, c.IsSensitive(), "%s should not be sensitive", c) - } -} - -func TestAllCategories(t *testing.T) { - assert.Len(t, AllCategories, 9) -} - -func TestNonSensitiveCategories(t *testing.T) { - cats := NonSensitiveCategories() - assert.Len(t, cats, 6) - for _, c := range cats { - assert.False(t, c.IsSensitive()) - } -} diff --git a/types/models.go b/types/models.go deleted file mode 100644 index 553c7f6..0000000 --- a/types/models.go +++ /dev/null @@ -1,95 +0,0 @@ -package types - -import "time" - -// Chromium keeps profile-local credentials in "Login Data" and account-synced ones in -// "Login Data For Account". The same credential may exist in both, so exported entries -// carry their origin instead of being silently merged. -const ( - PasswordStoreLocal = "local" - PasswordStoreAccount = "account" -) - -// LoginEntry represents a single saved login credential. -type LoginEntry struct { - URL string `json:"url" csv:"url"` - Username string `json:"username" csv:"username"` - Password string `json:"password" csv:"password"` - CreatedAt time.Time `json:"created_at" csv:"created_at"` - Store string `json:"store" csv:"store"` -} - -// CookieEntry represents a single browser cookie. -type CookieEntry struct { - Host string `json:"host" csv:"host"` - Path string `json:"path" csv:"path"` - Name string `json:"name" csv:"name"` - Value string `json:"value" csv:"value"` - IsSecure bool `json:"is_secure" csv:"is_secure"` - IsHTTPOnly bool `json:"is_http_only" csv:"is_http_only"` - HasExpire bool `json:"has_expire" csv:"has_expire"` - IsPersistent bool `json:"is_persistent" csv:"is_persistent"` - ExpireAt time.Time `json:"expire_at" csv:"expire_at"` - CreatedAt time.Time `json:"created_at" csv:"created_at"` - SameSite string `json:"same_site" csv:"same_site"` -} - -// BookmarkEntry represents a single browser bookmark. -type BookmarkEntry struct { - ID int64 `json:"id" csv:"id"` - Name string `json:"name" csv:"name"` - Type string `json:"type" csv:"type"` - URL string `json:"url" csv:"url"` - Folder string `json:"folder" csv:"folder"` - CreatedAt time.Time `json:"created_at" csv:"created_at"` -} - -// HistoryEntry represents a single browser history record. -type HistoryEntry struct { - URL string `json:"url" csv:"url"` - Title string `json:"title" csv:"title"` - VisitCount int `json:"visit_count" csv:"visit_count"` - LastVisit time.Time `json:"last_visit" csv:"last_visit"` -} - -// DownloadEntry represents a single browser download record. -type DownloadEntry struct { - URL string `json:"url" csv:"url"` - TargetPath string `json:"target_path" csv:"target_path"` - MimeType string `json:"mime_type" csv:"mime_type"` - TotalBytes int64 `json:"total_bytes" csv:"total_bytes"` - StartTime time.Time `json:"start_time" csv:"start_time"` - EndTime time.Time `json:"end_time" csv:"end_time"` -} - -// CreditCardEntry represents a single saved credit card. CVC and Comment are -// Yandex-specific; Chromium leaves them empty. -type CreditCardEntry struct { - GUID string `json:"guid" csv:"guid"` - Name string `json:"name" csv:"name"` - Number string `json:"number" csv:"number"` - ExpMonth string `json:"exp_month" csv:"exp_month"` - ExpYear string `json:"exp_year" csv:"exp_year"` - NickName string `json:"nick_name" csv:"nick_name"` - Address string `json:"address" csv:"address"` - CVC string `json:"cvc" csv:"cvc"` - Comment string `json:"comment" csv:"comment"` -} - -// StorageEntry represents a single key-value pair from local or session storage. -type StorageEntry struct { - IsMeta bool `json:"is_meta" csv:"is_meta"` - URL string `json:"url" csv:"url"` - Key string `json:"key" csv:"key"` - Value string `json:"value" csv:"value"` -} - -// ExtensionEntry represents a single browser extension. -type ExtensionEntry struct { - Name string `json:"name" csv:"name"` - ID string `json:"id" csv:"id"` - Description string `json:"description" csv:"description"` - Version string `json:"version" csv:"version"` - HomepageURL string `json:"homepage_url" csv:"homepage_url"` - Enabled bool `json:"enabled" csv:"enabled"` -} diff --git a/types/result.go b/types/result.go index a63361e..72b890e 100644 --- a/types/result.go +++ b/types/result.go @@ -1,5 +1,7 @@ package types +import "github.com/moond4rk/hackbrowserdata/internal/category" + // Profile identifies one browser profile — a leaf under an installation. type Profile struct { Name string @@ -15,5 +17,5 @@ type ExtractResult struct { // CountResult pairs a profile with its per-category entry counts. type CountResult struct { Profile - Counts map[Category]int + Counts map[category.Category]int }