From 0ed920f84657cb44b829eca2ed46fa913a8742dc Mon Sep 17 00:00:00 2001 From: Roger Date: Mon, 2 Nov 2026 00:03:03 +0800 Subject: [PATCH] docs: trim code comments to the why (#676) Comments that restated names or narrated the code are gone, and multi-line ones are cut to a line of why. Only comments change: each edited Go file has the same token stream as before. winapi and abe come later. --- CLAUDE.md | 2 +- cmd/hack-browser-data/helpers_test.go | 2 +- cmd/hack-browser-data/main.go | 4 +- cmd/hack-browser-data/main_windows.go | 3 +- cmd/hack-browser-data/restore.go | 2 - internal/app/app.go | 21 +++----- internal/app/app_test.go | 1 - internal/app/archive.go | 5 +- internal/app/discover.go | 12 ++--- internal/app/discover_test.go | 3 +- internal/app/execute.go | 19 +++---- internal/app/execute_test.go | 1 - internal/app/extract_golden_test.go | 2 +- internal/app/keys.go | 3 +- internal/app/password.go | 3 +- internal/app/plan.go | 14 ++--- internal/app/plan_test.go | 1 - internal/app/report.go | 3 +- internal/app/restore_golden_test.go | 1 - internal/app/restore_test.go | 1 - internal/browser/browser.go | 5 +- internal/browser/browser_test.go | 3 +- internal/browser/browsertest/firefox.go | 3 +- internal/browser/browsertest/safari.go | 3 +- internal/browser/chromium/chromium.go | 24 +++------ internal/browser/chromium/chromium_test.go | 1 - internal/browser/chromium/cipher.go | 24 +-------- internal/browser/chromium/cipher_test.go | 10 ++-- internal/browser/chromium/decrypt.go | 22 +------- .../browser/chromium/decrypt_mixed_test.go | 16 ++---- internal/browser/chromium/decrypt_test.go | 6 +-- internal/browser/chromium/decrypt_v20_test.go | 9 +--- .../browser/chromium/decrypt_windows_test.go | 8 +-- internal/browser/chromium/extract_bookmark.go | 1 - .../browser/chromium/extract_bookmark_test.go | 4 +- internal/browser/chromium/extract_cookie.go | 5 +- .../browser/chromium/extract_cookie_test.go | 1 - .../browser/chromium/extract_creditcard.go | 2 - .../chromium/extract_creditcard_test.go | 1 - .../browser/chromium/extract_download_test.go | 1 - .../browser/chromium/extract_extension.go | 12 +---- .../chromium/extract_extension_test.go | 3 +- .../browser/chromium/extract_history_test.go | 1 - internal/browser/chromium/extract_password.go | 3 +- .../browser/chromium/extract_password_test.go | 4 +- internal/browser/chromium/extract_storage.go | 33 +++--------- .../browser/chromium/extract_storage_test.go | 17 ------ internal/browser/chromium/extractors.go | 7 +-- internal/browser/chromium/testutil_test.go | 27 +--------- internal/browser/chromium/vault.go | 4 +- internal/browser/chromium/yandex.go | 4 -- internal/browser/chromium/yandex_key.go | 1 - internal/browser/chromium/yandex_key_test.go | 6 +-- .../browser/chromium/yandex_testutil_test.go | 41 +++------------ internal/browser/extractor.go | 16 ++---- .../browser/firefox/extract_bookmark_test.go | 1 - .../browser/firefox/extract_cookie_test.go | 1 - internal/browser/firefox/extract_download.go | 3 +- .../browser/firefox/extract_download_test.go | 1 - .../browser/firefox/extract_history_test.go | 1 - internal/browser/firefox/extract_password.go | 1 - .../browser/firefox/extract_password_test.go | 9 ++-- internal/browser/firefox/extract_storage.go | 3 +- .../browser/firefox/extract_storage_test.go | 1 - internal/browser/firefox/firefox.go | 13 ++--- internal/browser/firefox/firefox_test.go | 4 +- internal/browser/firefox/masterkey.go | 37 +++---------- internal/browser/firefox/masterkey_test.go | 1 - internal/browser/firefox/testutil_test.go | 14 +---- internal/browser/platform_darwin.go | 1 - internal/browser/platform_linux.go | 1 - internal/browser/platform_windows.go | 1 - internal/browser/safari/extract_bookmark.go | 4 +- .../browser/safari/extract_bookmark_test.go | 1 - internal/browser/safari/extract_cookie.go | 3 +- .../browser/safari/extract_cookie_test.go | 22 ++------ internal/browser/safari/extract_download.go | 4 +- .../browser/safari/extract_download_test.go | 3 +- internal/browser/safari/extract_extension.go | 19 ++----- .../browser/safari/extract_extension_test.go | 8 +-- internal/browser/safari/extract_history.go | 3 +- .../browser/safari/extract_history_test.go | 1 - internal/browser/safari/extract_password.go | 1 - internal/browser/safari/extract_storage.go | 52 +++++-------------- .../browser/safari/extract_storage_test.go | 28 ++-------- internal/browser/safari/profiles.go | 12 ++--- internal/browser/safari/profiles_test.go | 4 +- internal/browser/safari/safari.go | 16 ++---- internal/browser/safari/safari_test.go | 2 - internal/browser/safari/testutil_test.go | 52 +++---------------- internal/browser/userdatadir.go | 3 +- internal/crypto/asn1pbe.go | 48 +---------------- internal/crypto/asn1pbe_test.go | 9 ++-- internal/crypto/blob_test.go | 1 - internal/crypto/crypto.go | 14 +---- internal/crypto/crypto_test.go | 7 +-- internal/crypto/errors.go | 1 - internal/crypto/pbkdf2.go | 21 +------- internal/export/csv.go | 2 +- internal/export/order.go | 2 +- internal/export/reflect.go | 7 --- internal/export/reflect_test.go | 2 +- internal/export/writer.go | 4 +- internal/export/writer_test.go | 21 -------- internal/golden/golden.go | 14 ++--- internal/log/level.go | 6 --- internal/log/log.go | 2 - internal/log/log_test.go | 2 +- internal/log/logger.go | 26 +--------- internal/log/logger_test.go | 2 - internal/masterkey/dump.go | 10 ++-- internal/masterkey/gcoredump_darwin.go | 19 +------ internal/masterkey/gcoredump_stub_darwin.go | 5 +- internal/masterkey/keys_golden_test.go | 3 +- internal/masterkey/masterkey.go | 7 +-- internal/masterkey/params.go | 1 - internal/masterkey/retriever_darwin.go | 15 ++---- internal/masterkey/retriever_linux.go | 7 +-- internal/masterkey/retriever_linux_test.go | 7 +-- internal/masterkey/retriever_windows.go | 1 - internal/record/record_test.go | 2 +- internal/snapshot/copy_windows_test.go | 5 +- internal/snapshot/manifest.go | 3 -- internal/snapshot/snapshot.go | 4 +- internal/snapshot/zip.go | 3 +- internal/snapshot/zip_test.go | 1 - internal/sqlitex/query.go | 10 +--- internal/sqlitex/sqlite.go | 10 +--- internal/sqlitex/sqlite_test.go | 2 - internal/timeconv/timeconv.go | 2 +- 130 files changed, 201 insertions(+), 869 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e385a74..1367ffb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,7 +60,7 @@ make payload-clean # rm internal/abe/payload/*.bin - **Error handling**: `fmt.Errorf("context: %w", err)` for wrapping, never `_ =` to ignore errors - **Logging**: `log.Debugf` for record-level diagnostics, `log.Infof` for user-facing progress/status, `log.Warnf` for unexpected conditions. Extract methods should return errors, not log them. - **Naming**: follow Go conventions and the settled names in `rfcs/004-naming-decisions.md` — `Def` not `BrowserConfig`, `Extract` not `BrowsingData` -- **Comment width**: wrap comments at 140 columns (matches `.golangci.yml` `lll.line-length`) +- **Comments**: none by default; when one is needed, one line of at most 120 characters that says why, never what the code does (up to 3 lines only when the reason cannot fit) - **Tests**: `internal/browser/browsertest` builds real fixture files (SQLite, JSON, LevelDB, plist) into a `t.TempDir()` — never a live browser, never a database mock; goldens live in each package's `testdata/` and `HBD_UPDATE_GOLDEN=1 go test ./...` regenerates them - **Architecture**: see `rfcs/README.md` — design RFCs 000–011, format and technique RFCs 013–021 diff --git a/cmd/hack-browser-data/helpers_test.go b/cmd/hack-browser-data/helpers_test.go index f43e0b4..8eeeebc 100644 --- a/cmd/hack-browser-data/helpers_test.go +++ b/cmd/hack-browser-data/helpers_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" ) -// setHome points the commands' home directory at a fixture: HOME, and USERPROFILE, which Windows reads instead. +// Windows reads USERPROFILE rather than HOME, so both point at the fixture. func setHome(t *testing.T, home string) { t.Helper() t.Setenv("HOME", home) diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index dc1f909..ed46e68 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -36,9 +36,7 @@ GitHub: https://github.com/moonD4rk/HackBrowserData`, dump := dumpCmd() root.AddCommand(dump, dumpKeysCmd(), archiveCmd(), restoreCmd(), listCmd(), versionCmd()) - // Default to dump when no subcommand is given. - // Copy dump flags to root so that `hack-browser-data -b chrome` - // works the same as `hack-browser-data dump -b chrome`. + // Without a subcommand the root runs dump, as v1.1.0 did, so it carries dump's flags too. root.RunE = func(cmd *cobra.Command, args []string) error { dump.SetContext(cmd.Context()) return dump.RunE(dump, args) diff --git a/cmd/hack-browser-data/main_windows.go b/cmd/hack-browser-data/main_windows.go index 618a82b..29bc37a 100644 --- a/cmd/hack-browser-data/main_windows.go +++ b/cmd/hack-browser-data/main_windows.go @@ -12,8 +12,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/winapi" ) -// configureDoubleClickMode hides the console and bypasses cobra's -// double-click guard when launched from Explorer (issue #344). +// configureDoubleClickMode lets a double-click from Explorer run the tool with its console hidden (issue #344). func configureDoubleClickMode() { if !mousetrap.StartedByExplorer() { return diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 52f4435..7324912 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -69,8 +69,6 @@ func runRestore(ctx context.Context, stderr io.Writer, f app.RestoreFlags) error return err } -// openRestoreData returns the snapshot directory restore reads from: --data-dir in place, or --data-zip extracted -// into a temporary one. func openRestoreData(dataDir, dataZip string) (*snapshot.Dir, error) { if dataDir != "" { return snapshot.Open(dataDir), nil diff --git a/internal/app/app.go b/internal/app/app.go index 9ed8914..d272b06 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1,6 +1,4 @@ -// Package app runs the pipeline: Validate turns flags into a Request, Discover finds the user data dirs, NewPlan crosses -// them with the requested categories, Execute captures, extracts, and exports one user data dir at a time, and Report -// prints what every extraction got. +// Package app runs the pipeline: Validate, Discover, NewPlan, Execute, and Report. package app import ( @@ -19,7 +17,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// Flags are a run's command-line values as cobra parsed them. type Flags struct { Browser string Categories string @@ -31,7 +28,6 @@ type Flags struct { KeychainPasswordStdin bool } -// Request is a validated run. type Request struct { Browser string // "all" or one Def.ID Categories []category.Category @@ -41,15 +37,13 @@ type Request struct { ProfilePath string Home string - // KeychainPassword yields the macOS login password when the login keychain is first opened; "" leaves it locked. - // nil, as list has it, leaves the keychain locked without saying so. + // Called when the login keychain is first opened; "" leaves it locked, and nil, as list has it, does so silently. KeychainPassword func(ctx context.Context) (string, error) // Keys are a dump's keys by user data dir; nil retrieves every dir's keys from this machine. Keys map[browser.DirID]masterkey.Set } -// Validate checks every flag before any browser is touched or any secret is read, and resolves the home directory, so -// nothing later reads the environment. +// Validate checks every flag before any browser or secret is touched, so a bad flag fails fast. func Validate(f Flags) (Request, error) { return validate(f, os.Stdin) } @@ -94,7 +88,6 @@ func validate(f Flags, stdin *os.File) (Request, error) { }, nil } -// ValidateKeys checks dumpkeys' flags: the browser, and how the keychain password is given. func ValidateKeys(f Flags) (Request, error) { id, err := parseBrowser(f.Browser) if err != nil { @@ -111,7 +104,7 @@ func ValidateKeys(f Flags) (Request, error) { return Request{Browser: id, Home: home, KeychainPassword: password}, nil } -// ValidateArchive checks archive's flags. An archive copies files and reads no secret. +// ValidateArchive takes no keychain password: an archive copies files and reads no secret. func ValidateArchive(f Flags) (Request, error) { id, err := parseBrowser(f.Browser) if err != nil { @@ -161,8 +154,7 @@ func parseBrowser(s string) (string, error) { return "", fmt.Errorf("unknown browser %q, available: %s|%s", s, allBrowsers, strings.Join(browser.IDs(), "|")) } -// checkOutputDir creates nothing: -d must already be a directory, or its nearest existing ancestor must be one that a -// directory can be created in. +// checkOutputDir creates nothing: -d, or its nearest existing ancestor, must be a directory we can create in. func checkOutputDir(dir string) error { path := filepath.Clean(dir) for { @@ -205,8 +197,7 @@ func checkProfilePath(id, path string) (string, error) { return path, nil } -// parseCategories reads a comma-separated -c value; a repeated category is kept once, or its records would be -// exported twice. +// parseCategories keeps a repeated category once, or its records would be exported twice. func parseCategories(s string) ([]category.Category, error) { s = strings.TrimSpace(s) if strings.EqualFold(s, "all") { diff --git a/internal/app/app_test.go b/internal/app/app_test.go index f7b7743..eac2f9b 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -56,7 +56,6 @@ func TestValidate_RejectsBadInput(t *testing.T) { } } -// otherOSBrowser is a browser in the table that the running OS does not have. func otherOSBrowser(t *testing.T) string { t.Helper() for _, id := range []string{"sogou", "safari"} { diff --git a/internal/app/archive.go b/internal/app/archive.go index 8e2dd0d..d1e6a49 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -11,9 +11,8 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// Archive captures every Chromium user data dir into one snapshot directory, records what it holds in the manifest, -// and zips it to dst. Beside the requested categories' files it keeps Local State and each profile's marker, so a -// reader without the manifest still finds the profiles. It returns how many files and directories were captured. +// Archive also keeps Local State and each profile's marker, so a reader without the manifest still finds the profiles. +// It returns how many files and directories were captured. func Archive(ctx context.Context, d Discovery, req Request, dst string) (int, error) { var dirs []browser.UserDataDir for _, dir := range d.Dirs { diff --git a/internal/app/discover.go b/internal/app/discover.go index 510dda3..f59f597 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -9,14 +9,13 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser/safari" ) -// Discovery is what Discover found: the user data dirs, and an error result for each browser whose data could not be -// read, which is reported rather than mistaken for absence. +// Discovery holds an error result per browser whose data could not be read, so it is reported, not taken as absence. type Discovery struct { Dirs []browser.UserDataDir Failed []Result } -// Discover looks for the requested browsers on this machine. -p applies only when one browser is named. +// Discover applies -p only when one browser is named. func Discover(req Request) Discovery { var d Discovery for _, def := range browser.Supported() { @@ -36,9 +35,7 @@ func Discover(req Request) Discovery { return d } -// withData keeps the profiles holding a file some category reads, and the user data dirs with such a profile: a -// Preferences marker alone is no data, so a profile created and never used is not listed, archived, or keyed. A -// profile whose files cannot be checked stays, so the plan reports the error. +// withData drops profiles holding no file any category reads, such as a bare Preferences, but keeps unreadable ones. func withData(dirs []browser.UserDataDir) []browser.UserDataDir { extractors := extractorsWith(nil) var out []browser.UserDataDir @@ -69,8 +66,7 @@ func hasData(dir browser.UserDataDir, p browser.Profile, ex browser.Extractors) return false } -// discover and extractorsWith dispatch on the base here, because the base packages import browser and so browser -// cannot call them. +// The base packages import browser, so the dispatch on Base lives here rather than in browser. func discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { switch def.Base { case browser.Chromium: diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index 0d0510f..26299a4 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -12,7 +12,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" ) -// installAt creates a profile where this OS's table expects the browser's user data dir under home. func installAt(t *testing.T, home, id string) string { t.Helper() def := lookup(t, id) @@ -60,7 +59,7 @@ func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) { assert.NotEqual(t, custom, d.Dirs[0].Path, "-p is ignored without a specific browser") } -// A profile created and never used holds only its Preferences marker; it is not listed, archived, or keyed, as today. +// A profile created and never used holds only its Preferences marker, so it is not listed, archived, or keyed. func TestDiscover_KeepsOnlyProfilesWithData(t *testing.T) { home := t.TempDir() chrome := installAt(t, home, "chrome") diff --git a/internal/app/execute.go b/internal/app/execute.go index 595a182..191b90e 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -19,18 +19,16 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// runKeychain is the run's one login keychain, read by the Chromium v10 retriever and the Safari password extractor; -// nil off macOS. +// runKeychain is the run's one login keychain, shared by Chromium's v10 key and Safari's passwords; nil off macOS. type runKeychain interface { masterkey.LoginKeychain safari.LoginKeychain } -// keySource retrieves one user data dir's Chromium keys, reading what it needs from the dir's snapshot. type keySource func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) -// Execute runs Capture, Extract, and Export one user data dir at a time, so at most one dir's copies are on disk. Its -// error means the run could not finish, such as a failed output write; every other failure is a Result. +// Execute handles one user data dir at a time, so at most one dir's copies are on disk. +// Its error means the run could not finish; every other failure is a Result. func Execute(ctx context.Context, p Plan, req Request) (Summary, error) { kc := loginKeychain(req) keys := dumpKeys(req.Keys) @@ -65,13 +63,11 @@ func announceOutput(out export.Output) { } } -// Count runs every planned extraction with no key and the keychain locked, and counts the records instead of exporting -// them, which is all list --detail shows. +// Count runs the plan with no key and the keychain locked, counting records instead of exporting them. func Count(ctx context.Context, p Plan, req Request) (Summary, error) { return runner{w: discard{}, extractors: extractorsWith(loginKeychain(req)), keys: dumpKeys(nil)}.run(ctx, p) } -// recordWriter takes each extraction's records as it finishes. type recordWriter interface { Write(c category.Category, records []record.Record) error } @@ -200,7 +196,6 @@ func closeSnapshot(d *snapshot.Dir) { } } -// collector stamps every record with its browser and profile, and keeps one extraction's output for the writer. type collector struct { browser, profile string records []record.Record @@ -221,8 +216,7 @@ func (c *collector) Fail(err error) { log.Debugf("%s/%s: %v", c.browser, c.profile, err) } -// result applies the outcome rules: a source that vanished after planning is absent, and problems with no record to -// show for them are an error, while problems beside records are partial. +// A source gone since planning is absent; failures with no record are an error, and beside records, partial. func (c *collector) result(e Extraction, err error) Result { r := Result{Extraction: e, Count: len(c.records), Failed: c.failed} switch { @@ -240,8 +234,7 @@ func (c *collector) result(e Extraction, err error) Result { return r } -// dirKeys retrieves a user data dir's keys on first use and keeps them, and the error, for the dir's other profiles. -// Go 1.20 has no sync.OnceValues. +// dirKeys retrieves a dir's keys on first use, for all its profiles; Go 1.20 has no sync.OnceValues. type dirKeys struct { once sync.Once retrieve func(context.Context) (masterkey.Set, error) diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index 7ae9722..ee2e8a4 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -166,7 +166,6 @@ func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) { assert.Equal(t, 1, calls) } -// At most one user data dir's copies are on disk: a dir's snapshot is removed before the next dir is captured. func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) { var captured []string base := fakeBase(map[category.Category]extractFunc{ diff --git a/internal/app/extract_golden_test.go b/internal/app/extract_golden_test.go index c6649b1..0b64044 100644 --- a/internal/app/extract_golden_test.go +++ b/internal/app/extract_golden_test.go @@ -16,7 +16,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// The extract goldens pin dump's output on fixtures; the fixtures' keys are handed in, since no secret store holds them. +// The fixtures' keys are handed in, since no secret store holds them. func TestExtractGolden(t *testing.T) { home := t.TempDir() keys := make(map[browser.DirID]masterkey.Set) diff --git a/internal/app/keys.go b/internal/app/keys.go index 6f9aa8e..a9e4e89 100644 --- a/internal/app/keys.go +++ b/internal/app/keys.go @@ -11,8 +11,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// DumpKeys retrieves each Chromium user data dir's keys for keys.json, capturing only its Local State. A dir whose -// keys partly fail keeps the rest, because a v20 failure must not cost a usable v10 key; a dir with none is left out. +// DumpKeys keeps the keys that worked when a dir's others fail, and leaves out a dir with none. // It fails only when the run is stopped, so a stopped run writes no keys.json. func DumpKeys(ctx context.Context, d Discovery, req Request) (masterkey.Dump, error) { return dumpKeysWith(ctx, d, machineKeys(loginKeychain(req))) diff --git a/internal/app/password.go b/internal/app/password.go index ca3a94b..ccba285 100644 --- a/internal/app/password.go +++ b/internal/app/password.go @@ -14,8 +14,7 @@ import ( var errNoPassword = errors.New("macOS login password not given and stdin is not a terminal") -// keychainPassword picks the run's one source of the macOS login password, read when the keychain is first opened: a -// flag, else a no-echo prompt on a terminal, else none, which leaves keychain-protected data as metadata only. +// keychainPassword is read lazily: a flag, else a no-echo prompt on a terminal, else none (metadata only). func keychainPassword(f Flags, stdin *os.File) (func(context.Context) (string, error), error) { switch { case f.KeychainPassword != "" && f.KeychainPasswordStdin: diff --git a/internal/app/plan.go b/internal/app/plan.go index 03d5ec9..3463fa5 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -11,16 +11,14 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// Extraction is one category of data from one profile of one user data dir. It is plain data, looked up again when it -// runs, so a Plan prints as it is and compares with reflect.DeepEqual. +// Extraction is plain data, looked up again when it runs, so a Plan prints as it is and compares with DeepEqual. type Extraction struct { DirID browser.DirID Profile string // Profile.Name; "" in a result about a whole user data dir Category category.Category // zero in a result about a whole user data dir } -// Plan is what a run will do: the extractions in output order, the files they need captured once each, and the -// requested extractions that cannot run. +// Plan lists extractions in output order, each file to capture once, and the requested extractions that cannot run. type Plan struct { Dirs []browser.UserDataDir Files []snapshot.File @@ -30,8 +28,7 @@ type Plan struct { type extractorsFunc func(browser.UserDataDir, browser.Profile) browser.Extractors -// NewPlan crosses every discovered profile with the requested categories. It only stats files; it opens nothing. -// Planning reads only the extractors' sources, so it needs no keychain. +// NewPlan only stats files and reads only the extractors' sources, so it opens nothing and needs no keychain. func NewPlan(d Discovery, req Request) Plan { return newPlan(d, req, extractorsWith(nil)) } @@ -71,9 +68,8 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan { return p } -// locate finds each source's first candidate on disk. An extraction needs every required source and at least one of -// the profile's own; a shared one such as Local State never makes it present by itself. An extraction that reads no -// file, such as Safari's keychain passwords, always runs. A candidate that cannot be checked is an error, not absence. +// An extraction needs every required source and one of the profile's own: Local State alone never makes it present. +// One that reads no file always runs, and a candidate that cannot be checked is an error, not absence. func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool, error) { if len(sources) == 0 { return nil, true, nil diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index 0e391f3..e585085 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -131,7 +131,6 @@ func lock(t *testing.T, dir string) { t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) }) } -// A candidate that cannot be checked is not absence: the extraction is an error, and nothing is captured for it. func TestNewPlan_UnreadableSourceIsAnError(t *testing.T) { dir := chromeDir(t, "chrome", "Default") lock(t, filepath.Join(dir.Path, "Default")) diff --git a/internal/app/report.go b/internal/app/report.go index 07238cc..33d9318 100644 --- a/internal/app/report.go +++ b/internal/app/report.go @@ -6,8 +6,7 @@ import ( "text/tabwriter" ) -// Report writes every result as one line, in output order. The summary is additive: it is not part of the output -// contract, and it never changes the exit status. +// The summary is not part of the output contract and never changes the exit status. func Report(w io.Writer, s Summary) error { tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) fmt.Fprintln(tw, "Browser\tProfile\tCategory\tResult\tRecords\tDetail") diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index aeff212..173f245 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -87,7 +87,6 @@ func chromiumFixtureKeysFile(t *testing.T) string { return path } -// restoreGolden drives the restore pipeline the way the cobra command does, and returns the output directory. func restoreGolden(t *testing.T, f app.RestoreFlags) string { t.Helper() if f.Categories == "" { diff --git a/internal/app/restore_test.go b/internal/app/restore_test.go index 952ca67..d536a37 100644 --- a/internal/app/restore_test.go +++ b/internal/app/restore_test.go @@ -29,7 +29,6 @@ func vault(browserKey string) masterkey.Vault { return masterkey.Vault{Browser: browserKey, Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte(browserKey)}} } -// layoutProfile lays out one restorable profile under root/. func layoutProfile(t *testing.T, root, rel string) { t.Helper() touch(t, root, filepath.FromSlash(rel), "Default", "Preferences") diff --git a/internal/browser/browser.go b/internal/browser/browser.go index e8bf02f..9807368 100644 --- a/internal/browser/browser.go +++ b/internal/browser/browser.go @@ -1,5 +1,4 @@ -// Package browser holds the browser table and what the base packages hand the pipeline: user data dirs, profiles, -// and the extractors that read them. +// Package browser holds the browser table and the types the base packages hand the pipeline. package browser import ( @@ -42,7 +41,7 @@ func (b Base) String() string { } } -// Platform is how one browser appears on one OS; a Platform without UserDataDirs means the OS is not supported. +// A Platform without UserDataDirs means the browser is not supported on that OS. type Platform struct { UserDataDirs []string // slash-separated, relative to the home directory; globs allowed KeychainLabel string // macOS Keychain account / Linux Secret Service label; "" = none diff --git a/internal/browser/browser_test.go b/internal/browser/browser_test.go index 34a5713..c3dc459 100644 --- a/internal/browser/browser_test.go +++ b/internal/browser/browser_test.go @@ -97,8 +97,7 @@ func TestTableRows(t *testing.T) { } } -// The payload looks a browser up by its executable inside the browser process, so its C table is the other half of each -// ABE row. It may list browsers the Go table does not. +// The payload finds a browser by its executable, so every Go ABE row needs a C row; the C table may list more. func TestABERowsMatchPayloadTable(t *testing.T) { src, err := os.ReadFile("../abe/native/com_iid.c") require.NoError(t, err) diff --git a/internal/browser/browsertest/firefox.go b/internal/browser/browsertest/firefox.go index e9b0f84..5758a36 100644 --- a/internal/browser/browsertest/firefox.go +++ b/internal/browser/browsertest/firefox.go @@ -14,8 +14,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/crypto" ) -// home's logins open only with its second key candidate (AES-256) and work's with its only one (3DES), so the golden -// covers the candidate check and both login ciphers. +// home's logins open only with its second key candidate and work's with its only one, so the golden covers both paths. var firefoxFixtureProfiles = []struct { dir string label string diff --git a/internal/browser/browsertest/safari.go b/internal/browser/browsertest/safari.go index 26d9f87..955c254 100644 --- a/internal/browser/browsertest/safari.go +++ b/internal/browser/browsertest/safari.go @@ -232,8 +232,7 @@ type safariFixtureEndpoint struct { port uint16 } -// One partition of a WebKit origins root: top and frame differ for third-party storage, and an origin without -// localStorage items keeps only its origin file. +// Top and frame differ for third-party storage; an origin without localStorage items keeps only its origin file. func safariFixtureOrigin(t *testing.T, root string, top, frame safariFixtureEndpoint, items ...[2]string) { t.Helper() dir := filepath.Join(root, safariFixtureHash(top), safariFixtureHash(frame)) diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index bef6e8f..7ac7044 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -1,5 +1,4 @@ -// Package chromium is the Chromium base: where Chromium-family browsers keep their profiles, how their files are -// parsed, and where a user data dir's keys come from. +// Package chromium is the Chromium base: profile discovery, file parsing, and where a user data dir's keys come from. package chromium import ( @@ -14,12 +13,10 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// profileMarkers name the per-profile preferences file Chromium writes on first use; QQ Browser and Sogou Explorer write -// Preferences_02. The marker keeps Crashpad, ShaderCache, and the like from passing as profiles. +// Sogou and QQ write Preferences_02; a marker keeps dirs like Crashpad and ShaderCache from passing as profiles. var profileMarkers = []string{"Preferences", "Preferences_02"} -// Discover finds def's user data dirs and their profiles. A user data dir that does not exist yields nothing; any -// other failure is returned, joined across dirs, beside whatever was found. +// A user data dir that does not exist yields nothing; any other failure is returned beside whatever was found. func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { if dir, ok := profileAt(def, opts.ProfilePath); ok { return []browser.UserDataDir{dir}, nil @@ -54,8 +51,7 @@ func DiscoverAt(def browser.Def, id browser.DirID, path string) (browser.UserDat return dir, nil } -// profileAt reads -p as the path chrome://version shows: a directory with a profile marker but no Local State is one -// profile, so its parent is the user data dir that holds the keys, and only that profile is selected. +// -p is the path chrome://version shows: a profile dir without Local State selects that profile of its parent. func profileAt(def browser.Def, path string) (browser.UserDataDir, bool) { if path == "" || !isProfileDir(path) || hasAnySource(path, localState.Paths) { return browser.UserDataDir{}, false @@ -70,8 +66,7 @@ func profileAt(def browser.Def, path string) (browser.UserDataDir, bool) { }, true } -// userDataDirPaths keeps every glob match, so both of a machine's Arc packages are found. Joining with "/" keeps the -// path strings keys.json has always recorded; -p replaces the table's entries. +// Every glob match is kept, for both of a machine's Arc packages; "/" joins keep the paths keys.json has recorded. func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) ([]string, error) { if opts.ProfilePath != "" { return []string{opts.ProfilePath}, nil @@ -115,8 +110,7 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { return profiles, nil } - // Flat layout (older Opera): data files directly under the user data dir. Check the root before the subdir fallback - // so a stray source-bearing subdir can't suppress root discovery. + // Flat layout (older Opera): check the root before subdirs, so a stray source-bearing subdir can't hide it. sources := profileSourcePaths(dir) if hasAnySource(dir.Path, sources) { return []browser.Profile{{Name: filepath.Base(dir.Path)}}, nil @@ -169,8 +163,7 @@ func hasAnySource(dir string, paths []string) bool { return false } -// KeyLocator says where the user data dir's keys are: the Local State in snap and its browser's OS fields. On macOS -// the caller adds the run's login keychain. +// On macOS the caller adds the run's login keychain to the Locator. func KeyLocator(dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Locator, error) { p := dir.Def.Platform() loc := masterkey.Locator{KeychainLabel: p.KeychainLabel, Exe: p.Exe, ExeFallbacks: p.ExeFallbacks, ABE: p.ABE} @@ -189,8 +182,7 @@ func KeySources(_ browser.UserDataDir) []browser.Source { return []browser.Source{localState} } -// ArchiveSources are what an archive keeps beside the categories' own files: Local State, and each profile's marker so -// that a reader without the manifest still finds every profile. +// ArchiveSources add Local State and each profile's marker, so a reader without the manifest finds every profile. func ArchiveSources(_ browser.UserDataDir) []browser.Source { sources := []browser.Source{localState} for _, marker := range profileMarkers { diff --git a/internal/browser/chromium/chromium_test.go b/internal/browser/chromium/chromium_test.go index 2523898..ac6bd51 100644 --- a/internal/browser/chromium/chromium_test.go +++ b/internal/browser/chromium/chromium_test.go @@ -29,7 +29,6 @@ func touch(t *testing.T, parts ...string) { require.NoError(t, os.WriteFile(path, []byte("{}"), 0o600)) } -// snapshotOf lays fixture files out as one user data dir's snapshot, keyed by their path relative to the dir. func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { t.Helper() root := t.TempDir() diff --git a/internal/browser/chromium/cipher.go b/internal/browser/chromium/cipher.go index 6230ace..2ce1016 100644 --- a/internal/browser/chromium/cipher.go +++ b/internal/browser/chromium/cipher.go @@ -9,33 +9,23 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/crypto" ) -// cipherVersion represents the encryption version used by Chromium browsers. type cipherVersion string const ( - // cipherV10 is Chrome 80+ encryption (AES-GCM on Windows, AES-CBC on macOS/Linux). cipherV10 cipherVersion = "v10" - // cipherV11 is the Linux-only AES-CBC variant where the key comes from - // libsecret / kwallet. Same algorithm as cipherV10; only the key source differs. cipherV11 cipherVersion = "v11" - // cipherV20 is Chrome 127+ App-Bound Encryption. cipherV20 cipherVersion = "v20" - // cipherV12 is Chromium's SecretPortalKeyProvider (Flatpak / xdg-desktop-portal) tier — - // HKDF-SHA256 + AES-256-GCM with a secret retrieved via org.freedesktop.portal.Desktop. - // Recognized by detectVersion so decryptValue can emit a known-gap error rather than a - // generic "unsupported cipher version" message; not yet implemented. + // Recognized only to report a known gap: v12 is not implemented yet. cipherV12 cipherVersion = "v12" - // cipherDPAPI is pre-Chrome 80 raw DPAPI encryption (no version prefix). cipherDPAPI cipherVersion = "dpapi" versionPrefixLen = 3 ) -// detectVersion identifies the encryption version from a ciphertext prefix. func detectVersion(ciphertext []byte) cipherVersion { if len(ciphertext) < versionPrefixLen { return cipherDPAPI @@ -57,20 +47,13 @@ func detectVersion(ciphertext []byte) cipherVersion { var errShortCiphertext = errors.New("ciphertext too short") -// gcmNonceSize is the AES-GCM standard nonce size used by Chromium's v10/v20 -// cipher formats. Cross-platform because the v20 ciphertext layout is the -// same regardless of host OS (only Windows currently produces v20). const gcmNonceSize = 12 -// chromiumCBCIV is the fixed IV Chromium uses for AES-CBC v10/v11 (macOS/Linux). var chromiumCBCIV = bytes.Repeat([]byte{0x20}, aes.BlockSize) -// kEmptyKey is Chromium's decrypt-only fallback for data corrupted by a KWallet -// race in Chrome ~89 (crbug.com/40055416). Matches kEmptyKey in os_crypt_linux.cc. +// Chromium's decrypt-only fallback for data a KWallet race corrupted in Chrome ~89 (crbug.com/40055416). var kEmptyKey = crypto.PBKDF2Key([]byte(""), []byte("saltysalt"), 1, 16, sha1.New) -// decryptGCM decrypts a prefixed AES-GCM blob: version(3B)+nonce(12B)+ct+tag. -// Used by Windows v10 (AES-256) and v20; the layout is identical and platform-neutral. func decryptGCM(key, ciphertext []byte) ([]byte, error) { if len(ciphertext) < versionPrefixLen+gcmNonceSize { return nil, errShortCiphertext @@ -80,9 +63,6 @@ func decryptGCM(key, ciphertext []byte) ([]byte, error) { return crypto.AESGCMDecrypt(key, nonce, payload) } -// decryptCBC decrypts a prefixed AES-CBC blob (version(3B)+ct) with Chromium's -// fixed IV, retrying with kEmptyKey to recover crbug.com/40055416 KWallet-corrupted data. -// Used by macOS/Linux v10 and Linux v11 (both AES-128). func decryptCBC(key, ciphertext []byte) ([]byte, error) { if len(ciphertext) < versionPrefixLen+aes.BlockSize { return nil, errShortCiphertext diff --git a/internal/browser/chromium/cipher_test.go b/internal/browser/chromium/cipher_test.go index 72ced53..e527d90 100644 --- a/internal/browser/chromium/cipher_test.go +++ b/internal/browser/chromium/cipher_test.go @@ -33,12 +33,10 @@ func TestDetectVersion(t *testing.T) { } } -// --- Cross-OS Chromium v10/v11 decryption --- -// decryptGCM / decryptCBC are platform-neutral, so these run on every -// GOOS and prove a key dumped on one platform decrypts that platform's data anywhere. +// decryptGCM and decryptCBC are platform-neutral, so a key dumped on one OS decrypts its data on any OS. var ( - // cbcKey is the 16-byte AES-128-CBC tier (macOS/Linux v10/v11); gcmKey the 32-byte AES-256-GCM tier (Windows v10 / v20). + // cbcKey is the 16-byte tier (macOS/Linux v10, v11); gcmKey the 32-byte tier (Windows v10, v20). cbcKey = bytes.Repeat([]byte("moond4rk"), 2) gcmKey = bytes.Repeat([]byte("moond4rk"), 4) gcmNonce = cbcKey[:12] @@ -66,9 +64,7 @@ func TestDecryptCBC_CrossPlatform(t *testing.T) { assert.Equal(t, plaintext, got) } -// TestKEmptyKey_MatchesChromium pins the runtime-derived kEmptyKey to Chromium's -// reference bytes in os_crypt_linux.cc; now cross-platform since kEmptyKey is -// defined for every GOOS. +// Pins the derived kEmptyKey to the reference bytes in Chromium's os_crypt_linux.cc. func TestKEmptyKey_MatchesChromium(t *testing.T) { want := []byte{ 0xd0, 0xd0, 0xec, 0x9c, 0x7d, 0x77, 0xd4, 0x3a, diff --git a/internal/browser/chromium/decrypt.go b/internal/browser/chromium/decrypt.go index 5884bba..10c0e72 100644 --- a/internal/browser/chromium/decrypt.go +++ b/internal/browser/chromium/decrypt.go @@ -6,17 +6,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// decryptValue decrypts a Chromium-encrypted value by dispatching on the ciphertext's version -// prefix to the matching version in masterKeys: -// -// - v10 → masterKeys[masterkey.V10] (Windows DPAPI / macOS Keychain / Linux peanuts kV10Key) -// - v11 → masterKeys[masterkey.V11] (Linux keyring kV11Key; nil on Windows/macOS — Chromium doesn't emit v11 there) -// - v20 → masterKeys[masterkey.V20] (Windows ABE; nil on non-Windows — Chromium doesn't emit v20 there) -// -// A single profile can carry mixed prefixes (Chrome 127+ upgrades on Windows; Linux session-mode -// changes), so every applicable key must be populated upstream for lossless extraction. Missing -// version keys surface as decrypt errors at the ciphertext level; the extract layer treats those as -// empty plaintexts rather than fatal errors. +// A profile can mix versions, so a missing key fails only the values sealed under that version. func decryptValue(masterKeys masterkey.Set, ciphertext []byte) ([]byte, error) { if len(ciphertext) == 0 { return nil, nil @@ -25,24 +15,16 @@ func decryptValue(masterKeys masterkey.Set, ciphertext []byte) ([]byte, error) { version := detectVersion(ciphertext) switch version { case cipherV10: - // v10's cipher depends on the platform that sealed it: a 32-byte AES-256 key means GCM - // (Windows), a 16-byte AES-128 key means CBC (macOS/Linux). Dispatching on key length keeps - // cross-host decryption OS-independent: a 32-byte key dumped on Windows decrypts here on macOS. + // Key length tells which platform sealed v10: 32 bytes is GCM, 16 is CBC, so a key from another OS still works. if len(masterKeys[masterkey.V10]) == 32 { return decryptGCM(masterKeys[masterkey.V10], ciphertext) } return decryptCBC(masterKeys[masterkey.V10], ciphertext) case cipherV11: - // v11 is Linux-only AES-CBC; same algorithm as Linux v10 but the key comes from the keyring - // (kV11Key) rather than peanuts (kV10Key), so both versions need distinct keys. return decryptCBC(masterKeys[masterkey.V11], ciphertext) case cipherV20: - // v20 is cross-platform AES-GCM (Chrome 127+ ABE); same wire layout as Windows v10. return decryptGCM(masterKeys[masterkey.V20], ciphertext) case cipherV12: - // Chromium's SecretPortalKeyProvider (Flatpak / xdg-desktop-portal) — HKDF-SHA256 + - // AES-256-GCM with a secret retrieved via org.freedesktop.portal.Desktop. Recognized here - // to surface an actionable "known gap" error rather than the generic "unsupported" one. return nil, fmt.Errorf("unsupported cipher version v12 (Chromium SecretPortal / Flatpak; not yet implemented)") case cipherDPAPI: return masterkey.DecryptDPAPI(ciphertext) diff --git a/internal/browser/chromium/decrypt_mixed_test.go b/internal/browser/chromium/decrypt_mixed_test.go index 7f8208f..76e0251 100644 --- a/internal/browser/chromium/decrypt_mixed_test.go +++ b/internal/browser/chromium/decrypt_mixed_test.go @@ -11,15 +11,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// TestDecryptValue_MixedTier is the regression test for mixed-cipher profiles (issue #578 on -// Windows; the analogous Linux v10/v11 gap). A single MasterKeys struct must carry distinct keys -// for each tier, and decryptValue must dispatch each ciphertext to the matching tier's key. -// Before the refactor the master-key retriever returned only one tier, so a profile mixing -// cipher prefixes silently lost whichever tier wasn't retrieved. -// -// Uses v20 (cross-platform AES-GCM) to cover the prefix→slot routing property without depending -// on platform-specific v10/v11 cipher primitives (AES-CBC on darwin/linux, AES-GCM on Windows). -// The per-platform v10/v11 formats are covered by decrypt_test.go and decrypt_windows_test.go. +// Regression for #578: a profile mixing cipher versions must route each value to its own version's key. func TestDecryptValue_MixedTier(t *testing.T) { k10 := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (wrong for v20 payload) k11 := bytes.Repeat([]byte{0x11}, 16) // V11 slot key (wrong for v20 payload) @@ -39,15 +31,13 @@ func TestDecryptValue_MixedTier(t *testing.T) { }) t.Run("V20 holds wrong key: v20 still picks V20 slot (not V10/V11), errors", func(t *testing.T) { - // If the dispatcher incorrectly fell back to V10 or V11 when V20 had a wrong key, this - // would succeed. Proves the router uses prefix-based selection, not first-usable-key. + // Wrong keys in the V20 slot must fail even when another slot holds the right one: routing is by prefix. _, err := decryptValue(masterkey.Set{masterkey.V10: k20, masterkey.V11: k20, masterkey.V20: k10}, v20Ciphertext) require.Error(t, err) }) t.Run("only V20 populated: v20 still decrypts", func(t *testing.T) { - // The pre-#578 symmetric regression: when DPAPI/keyring failed and only V20 was retrieved, - // v20 cookies had to still decrypt. This asserts V10 and V11 being nil doesn't block v20. + // Missing V10 and V11 keys must not block v20 values. got, err := decryptValue(masterkey.Set{masterkey.V20: k20}, v20Ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) diff --git a/internal/browser/chromium/decrypt_test.go b/internal/browser/chromium/decrypt_test.go index 25874d7..61b6785 100644 --- a/internal/browser/chromium/decrypt_test.go +++ b/internal/browser/chromium/decrypt_test.go @@ -66,11 +66,7 @@ func TestDecryptValue_V11(t *testing.T) { assert.Equal(t, plaintext, got) } -// TestDecryptValue_V10_V11_SlotSeparation is the Linux analog of the #578 regression test: a -// profile carrying both v10 (peanuts) and v11 (keyring) ciphertexts must route each prefix to -// its own slot, not share a single key. Build-tag scoped to darwin/linux because v10/v11 use -// AES-CBC on these platforms; Windows uses AES-GCM for v10 and is covered separately by -// decrypt_windows_test.go. +// Linux analog of #578: v10 and v11 values in one profile must each route to their own key. func TestDecryptValue_V10_V11_SlotSeparation(t *testing.T) { k10 := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (peanuts-derived kV10Key) k11 := bytes.Repeat([]byte{0x11}, 16) // V11 slot key (keyring-derived kV11Key) diff --git a/internal/browser/chromium/decrypt_v20_test.go b/internal/browser/chromium/decrypt_v20_test.go index 9eacb9d..c191684 100644 --- a/internal/browser/chromium/decrypt_v20_test.go +++ b/internal/browser/chromium/decrypt_v20_test.go @@ -10,10 +10,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// TestDecryptValue_V20 is cross-platform because v20's ciphertext format -// (AES-GCM with 12-byte nonce) is platform-independent; only the key source -// (Chrome ABE on Windows) differs by OS. Running on Linux/macOS CI protects -// the routing in decryptValue + crypto.DecryptChromiumGCM from regressions. +// v20's format is the same on every OS, so CI on Linux and macOS guards its routing too. func TestDecryptValue_V20(t *testing.T) { plaintext := []byte("v20_test_value") nonce := []byte("v20_nonce_12") // 12-byte AES-GCM nonce @@ -35,9 +32,7 @@ func TestDecryptValue_V20_ShortCiphertext(t *testing.T) { require.Error(t, err) } -// TestDecryptValue_V10_CrossHostGCM proves a v10 ciphertext sealed with a 32-byte -// AES-256 key (a Windows-origin dump) decrypts via decryptValue on any host — the -// core cross-OS guarantee. testAESKey is 16B, so this uses an explicit 32B key. +// A v10 value sealed with a 32-byte key, as on Windows, decrypts on any host: the cross-OS guarantee. func TestDecryptValue_V10_CrossHostGCM(t *testing.T) { key32 := []byte("0123456789abcdef0123456789abcdef") // 32 bytes plaintext := []byte("v10_cross_host") diff --git a/internal/browser/chromium/decrypt_windows_test.go b/internal/browser/chromium/decrypt_windows_test.go index 140eaa6..8f3f038 100644 --- a/internal/browser/chromium/decrypt_windows_test.go +++ b/internal/browser/chromium/decrypt_windows_test.go @@ -15,8 +15,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// encryptWithDPAPI encrypts data using Windows DPAPI (CryptProtectData). -// This is the reverse of DecryptDPAPI, used only for testing. func encryptWithDPAPI(plaintext []byte) ([]byte, error) { crypt32 := syscall.NewLazyDLL("Crypt32.dll") kernel32 := syscall.NewLazyDLL("Kernel32.dll") @@ -54,9 +52,8 @@ func encryptWithDPAPI(plaintext []byte) ([]byte, error) { } func TestDecryptValue_V10_Windows(t *testing.T) { - // Windows v10 is AES-256-GCM, so the master key is 32 bytes; decryptValue routes v10 by key - // length (32B→GCM). testAESKey is 16B, so this uses an explicit 32B key. - key32 := []byte("0123456789abcdef0123456789abcdef") // 32 bytes + // Windows v10 keys are 32 bytes, which routes them to GCM. + key32 := []byte("0123456789abcdef0123456789abcdef") plaintext := []byte("test_secret_value") nonce := []byte("123456789012") // 12-byte nonce @@ -72,7 +69,6 @@ func TestDecryptValue_V10_Windows(t *testing.T) { } func TestDecryptValue_DPAPI_Windows(t *testing.T) { - // Round-trip: encrypt with CryptProtectData, decrypt with decryptValue plaintext := []byte("dpapi_test_secret") encrypted, err := encryptWithDPAPI(plaintext) diff --git a/internal/browser/chromium/extract_bookmark.go b/internal/browser/chromium/extract_bookmark.go index 00f75fa..c020723 100644 --- a/internal/browser/chromium/extract_bookmark.go +++ b/internal/browser/chromium/extract_bookmark.go @@ -26,7 +26,6 @@ func extractBookmarks(path string, out browser.Collector) error { return nil } -// walkBookmarks recursively traverses the bookmark tree, collecting URL entries. func walkBookmarks(node gjson.Result, folder string, out *[]record.Bookmark) { nodeType := node.Get("type").String() if nodeType == "url" { diff --git a/internal/browser/chromium/extract_bookmark_test.go b/internal/browser/chromium/extract_bookmark_test.go index e7254de..48f044e 100644 --- a/internal/browser/chromium/extract_bookmark_test.go +++ b/internal/browser/chromium/extract_bookmark_test.go @@ -52,13 +52,11 @@ func TestExtractBookmarks(t *testing.T) { assert.Equal(t, "HN", got[1].Name) assert.Equal(t, "GitHub", got[2].Name) - // Verify field mapping 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[1].URL) - assert.Equal(t, "News", got[1].Folder) // parent folder name + assert.Equal(t, "News", got[1].Folder) } func TestExtractBookmarks_FoldersExcluded(t *testing.T) { diff --git a/internal/browser/chromium/extract_cookie.go b/internal/browser/chromium/extract_cookie.go index b63d019..5fb88fc 100644 --- a/internal/browser/chromium/extract_cookie.go +++ b/internal/browser/chromium/extract_cookie.go @@ -71,10 +71,7 @@ func extractCookies(masterKeys masterkey.Set, path string, out browser.Collector return nil } -// stripCookieHash removes the SHA256(host_key) prefix from a decrypted cookie value. Chrome 130+ -// (Cookie DB schema version 24) prepends SHA256(domain) to the cookie value before encryption to -// prevent cross-domain cookie replay attacks. If the first 32 bytes don't match SHA256(hostKey), the -// value is returned unchanged, which handles both older Chrome versions and tampered data. +// Chrome 130+ prepends SHA256(host_key) to the value; a value whose prefix does not match is returned unchanged. func stripCookieHash(value []byte, hostKey string) []byte { if len(value) < sha256.Size { return value diff --git a/internal/browser/chromium/extract_cookie_test.go b/internal/browser/chromium/extract_cookie_test.go index 878c4fa..27672d1 100644 --- a/internal/browser/chromium/extract_cookie_test.go +++ b/internal/browser/chromium/extract_cookie_test.go @@ -33,7 +33,6 @@ func TestExtractCookies(t *testing.T) { assert.Equal(t, ".old.com", got[0].Host) assert.Equal(t, ".new.com", got[1].Host) - // Verify field mapping assert.Equal(t, "token", got[1].Name) assert.Equal(t, "/api", got[1].Path) assert.True(t, got[1].IsSecure) diff --git a/internal/browser/chromium/extract_creditcard.go b/internal/browser/chromium/extract_creditcard.go index df62b63..4ffd423 100644 --- a/internal/browser/chromium/extract_creditcard.go +++ b/internal/browser/chromium/extract_creditcard.go @@ -19,7 +19,6 @@ const ( yandexCreditCardQuery = `SELECT guid, public_data, private_data FROM records` ) -// yandexPublicData is the plaintext JSON in records.public_data. type yandexPublicData struct { CardHolder string `json:"card_holder"` CardTitle string `json:"card_title"` @@ -27,7 +26,6 @@ type yandexPublicData struct { ExpireDateMonth string `json:"expire_date_month"` } -// yandexPrivateData is the AES-GCM-sealed JSON in records.private_data. type yandexPrivateData struct { FullCardNumber string `json:"full_card_number"` PinCode string `json:"pin_code"` diff --git a/internal/browser/chromium/extract_creditcard_test.go b/internal/browser/chromium/extract_creditcard_test.go index c615413..a5e0ab1 100644 --- a/internal/browser/chromium/extract_creditcard_test.go +++ b/internal/browser/chromium/extract_creditcard_test.go @@ -29,7 +29,6 @@ func TestExtractCreditCards(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) - // Verify field mapping assert.Equal(t, "John Doe", got[0].Name) assert.Equal(t, "12", got[0].ExpMonth) assert.Equal(t, "2025", got[0].ExpYear) diff --git a/internal/browser/chromium/extract_download_test.go b/internal/browser/chromium/extract_download_test.go index 4de4473..b401297 100644 --- a/internal/browser/chromium/extract_download_test.go +++ b/internal/browser/chromium/extract_download_test.go @@ -30,7 +30,6 @@ func TestExtractDownloads(t *testing.T) { 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[1].TargetPath) assert.Equal(t, "application/pdf", got[1].MimeType) assert.Equal(t, int64(2048), got[1].TotalBytes) diff --git a/internal/browser/chromium/extract_extension.go b/internal/browser/chromium/extract_extension.go index fd1703a..6243b80 100644 --- a/internal/browser/chromium/extract_extension.go +++ b/internal/browser/chromium/extract_extension.go @@ -10,7 +10,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// defaultExtensionKeys are the JSON paths tried for standard Chromium browsers. var defaultExtensionKeys = []string{ "extensions.settings", "settings.extensions", @@ -21,9 +20,7 @@ func extractExtensions(path string, out browser.Collector) error { return extractExtensionsWithKeys(path, defaultExtensionKeys, out) } -// 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. +// Browser variants keep extension settings under other JSON paths, such as Opera's extensions.opsettings. func extractExtensionsWithKeys(path string, keys []string, out browser.Collector) error { data, err := os.ReadFile(path) if err != nil { @@ -70,9 +67,7 @@ func extractExtensionsWithKeys(path string, keys []string, out browser.Collector return nil } -// isExtensionEnabled checks whether an extension is enabled. -// Modern Chrome uses disable_reasons (array): empty [] = enabled, non-empty [1] = disabled. -// Older Chrome uses state (int): 1 = enabled. +// Modern Chrome sets disable_reasons (empty means enabled); older Chrome sets state, where 1 means enabled. func isExtensionEnabled(ext gjson.Result) bool { reasons := ext.Get("disable_reasons") if reasons.Exists() { @@ -81,9 +76,6 @@ func isExtensionEnabled(ext gjson.Result) bool { return ext.Get("state").Int() == 1 } -// 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, out browser.Collector) error { return extractExtensionsWithKeys(path, []string{"extensions.opsettings"}, out) } diff --git a/internal/browser/chromium/extract_extension_test.go b/internal/browser/chromium/extract_extension_test.go index 2dee645..5491d31 100644 --- a/internal/browser/chromium/extract_extension_test.go +++ b/internal/browser/chromium/extract_extension_test.go @@ -52,7 +52,7 @@ func TestExtractExtensions(t *testing.T) { require.NoError(t, err) require.Len(t, got, 2) // system (location=5) and component (location=10) skipped - // Verify field mapping (order may vary since gjson.ForEach iterates map) + // gjson.ForEach walks a map, so the order may vary. ids := map[string]bool{} for _, ext := range got { ids[ext.ID] = true @@ -108,7 +108,6 @@ func TestExtractOperaExtensions(t *testing.T) { } }`) - // extractOperaExtensions should find extensions under opsettings var out testCollector err := extractOperaExtensions(path, &out) got := collected[record.Extension](t, &out) diff --git a/internal/browser/chromium/extract_history_test.go b/internal/browser/chromium/extract_history_test.go index fdd95f4..1b79ff6 100644 --- a/internal/browser/chromium/extract_history_test.go +++ b/internal/browser/chromium/extract_history_test.go @@ -32,7 +32,6 @@ func TestExtractHistories(t *testing.T) { assert.Equal(t, 50, got[1].VisitCount) assert.Equal(t, 200, got[2].VisitCount) - // Verify field mapping assert.Equal(t, "https://example.com", got[2].URL) assert.Equal(t, "Example", got[2].Title) assert.False(t, got[2].LastVisit.IsZero()) diff --git a/internal/browser/chromium/extract_password.go b/internal/browser/chromium/extract_password.go index 89dec95..0402b2a 100644 --- a/internal/browser/chromium/extract_password.go +++ b/internal/browser/chromium/extract_password.go @@ -51,8 +51,7 @@ func extractPasswordsWithQuery(masterKeys masterkey.Set, path string, store reco return 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). +// The URL column is origin_url, which the per-row AAD covers, not action_url. func extractYandexPasswords(masterKeys masterkey.Set, path string, out browser.Collector) error { dataKey, keyErr := loadYandexDataKey(path, masterKeys[masterkey.V10]) diff --git a/internal/browser/chromium/extract_password_test.go b/internal/browser/chromium/extract_password_test.go index abde67a..d8e2ac4 100644 --- a/internal/browser/chromium/extract_password_test.go +++ b/internal/browser/chromium/extract_password_test.go @@ -33,7 +33,6 @@ func TestExtractPasswords(t *testing.T) { 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[1].Username) assert.False(t, got[1].CreatedAt.IsZero()) // Password is empty because masterKey is nil (decrypt returns empty) @@ -41,8 +40,7 @@ func TestExtractPasswords(t *testing.T) { assert.Equal(t, record.StoreLocal, got[1].Store) } -// A credential whose blob cannot be decrypted must still be reported, otherwise a missing -// master key would silently shrink the export instead of yielding empty passwords. +// An undecryptable credential is still listed, or a missing key would silently shrink the export. func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) { path := createTestDB(t, "Login Data", loginsSchema, insertLogin("https://enc.com", "https://enc.com/login", "carol", "763130deadbeef", 13350000000000000), diff --git a/internal/browser/chromium/extract_storage.go b/internal/browser/chromium/extract_storage.go index 9f9129c..ccd4905 100644 --- a/internal/browser/chromium/extract_storage.go +++ b/internal/browser/chromium/extract_storage.go @@ -15,8 +15,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Chromium localStorage LevelDB key prefixes and string format bytes. -// Reference: https://chromium.googlesource.com/chromium/src/+/main/components/services/storage/dom_storage/local_storage_impl.cc +// Key prefixes and format bytes from Chromium's components/services/storage/dom_storage/local_storage_impl.cc. const ( localStorageVersionKey = "VERSION" localStorageMetaPrefix = "META:" @@ -56,8 +55,7 @@ func extractLocalStorage(path string, out browser.Collector) error { return iter.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. +// VERSION and unknown keys are dropped; META entries are kept with IsMeta set. func parseLocalStorageEntry(key, value []byte) (record.LocalStorage, bool) { switch { case bytes.Equal(key, []byte(localStorageVersionKey)): @@ -101,8 +99,7 @@ func parseLocalStorageDataEntry(key, value []byte) record.LocalStorage { return entry } -// decodeChromiumString decodes a Chromium-encoded string. -// Format byte 0x01 = Latin-1, 0x00 = UTF-16 LE. +// The first byte selects the encoding: 0x01 is Latin-1, 0x00 is UTF-16 LE. func decodeChromiumString(b []byte) (string, error) { if len(b) == 0 { return "", fmt.Errorf("empty chromium string") @@ -117,8 +114,6 @@ func decodeChromiumString(b []byte) (string, error) { } } -// decodeLatin1 converts ISO-8859-1 bytes to a valid UTF-8 Go string. -// Latin-1 byte values map 1:1 to Unicode code points U+0000–U+00FF. func decodeLatin1(b []byte) string { runes := make([]rune, len(b)) for i, c := range b { @@ -127,7 +122,6 @@ func decodeLatin1(b []byte) string { return string(runes) } -// decodeUTF16LE decodes a UTF-16 Little-Endian byte slice to a Go string. func decodeUTF16LE(b []byte) (string, error) { if len(b) == 0 { return "", nil @@ -156,13 +150,7 @@ func decodeLocalStorageValue(value []byte) string { return decoded } -// extractSessionStorage reads Chromium session storage LevelDB. -// -// LevelDB key format: -// -// namespace-- → (origin mapping) -// map-- → (actual data, UTF-16 LE) -// next-map-id / version (metadata, skipped) +// Keys are namespace-- -> map_id and map-- -> UTF-16 LE value; the rest is metadata. func extractSessionStorage(path string, out browser.Collector) error { if _, err := os.Stat(path); err != nil { return fmt.Errorf("leveldb path %q: %w", path, err) @@ -173,8 +161,6 @@ func extractSessionStorage(path string, out browser.Collector) error { } defer db.Close() - // Pass 1: build map_id → origin lookup from namespace entries. - // Key: "namespace--", Value: "" (ASCII digits). originByMapID := make(map[string]string) iter := db.NewIterator(nil, nil) for iter.Next() { @@ -182,9 +168,7 @@ func extractSessionStorage(path string, out browser.Collector) error { if !strings.HasPrefix(key, "namespace-") { continue } - // Extract origin by finding "-https://", "-http://", or "-chrome://" in the key. - // Namespace GUIDs use underscores (e.g., "03b2df3a_0d95_4d55_ae57_...") so - // there is no ambiguity with the origin separator. + // Namespace GUIDs use underscores, so the first -https://, -http://, or -chrome:// starts the origin. origin := extractNamespaceOrigin(key) if origin == "" { continue @@ -197,7 +181,6 @@ func extractSessionStorage(path string, out browser.Collector) error { return fmt.Errorf("read namespace entries: %w", err) } - // Pass 2: read map entries and resolve origins. var entries []record.SessionStorage iter2 := db.NewIterator(nil, nil) defer iter2.Release() @@ -232,9 +215,6 @@ func extractSessionStorage(path string, out browser.Collector) error { return iter2.Error() } -// extractNamespaceOrigin extracts the origin from a namespace key. -// Key format: "namespace--" -// The GUID uses underscores, so we find the origin by looking for "-http" or "-chrome". func extractNamespaceOrigin(key string) string { for _, prefix := range []string{"-https://", "-http://", "-chrome://"} { idx := strings.Index(key, prefix) @@ -245,8 +225,7 @@ func extractNamespaceOrigin(key string) string { return "" } -// decodeSessionStorageValue decodes a session storage value. -// Values are raw UTF-16 LE (no format byte prefix, unlike localStorage). +// Values are raw UTF-16 LE, without localStorage's format byte. func decodeSessionStorageValue(value []byte) string { if len(value) == 0 { return "" diff --git a/internal/browser/chromium/extract_storage_test.go b/internal/browser/chromium/extract_storage_test.go index be4282c..9b3db62 100644 --- a/internal/browser/chromium/extract_storage_test.go +++ b/internal/browser/chromium/extract_storage_test.go @@ -14,9 +14,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// --------------------------------------------------------------------------- -// decodeChromiumString -// --------------------------------------------------------------------------- func TestDecodeChromiumString(t *testing.T) { tests := []struct { name string @@ -80,10 +77,6 @@ func TestDecodeChromiumString(t *testing.T) { } } -// --------------------------------------------------------------------------- -// parseLocalStorageEntry -// --------------------------------------------------------------------------- - func TestParseLocalStorageEntry(t *testing.T) { tests := []struct { name string @@ -162,10 +155,6 @@ func TestParseLocalStorageEntry(t *testing.T) { } } -// --------------------------------------------------------------------------- -// extractLocalStorage (integration with LevelDB) -// --------------------------------------------------------------------------- - func setupLocalStorageLevelDB(t *testing.T) string { t.Helper() return createTestLevelDB(t, map[string]string{ @@ -214,10 +203,6 @@ func TestExtractLocalStorage(t *testing.T) { assert.Equal(t, "データ", byKey["テスト"]) } -// --------------------------------------------------------------------------- -// extractSessionStorage -// --------------------------------------------------------------------------- - func TestExtractSessionStorage(t *testing.T) { dir := setupSessionStorageLevelDB(t) @@ -285,8 +270,6 @@ func testEncodeUTF16(s string) []byte { return result } -// testEncodeUTF16Raw encodes as raw UTF-16 LE without format byte prefix -// (used by session storage values). func testEncodeUTF16Raw(s string) []byte { encoded := utf16.Encode([]rune(s)) result := make([]byte, 0, len(encoded)*2) diff --git a/internal/browser/chromium/extractors.go b/internal/browser/chromium/extractors.go index 12fc03e..eb3d680 100644 --- a/internal/browser/chromium/extractors.go +++ b/internal/browser/chromium/extractors.go @@ -29,8 +29,7 @@ var defaultExtractors = browser.Extractors{ category.SessionStorage: plain(directory("Session Storage"), extractSessionStorage), } -// overrides holds the forks with their own on-disk format: Yandex's password and card databases, and the Opera family's -// extension settings. It is keyed by Def.ID, never by DirID, which differs for a second user data dir of one browser. +// overrides is keyed by Def.ID, never DirID, which differs for a second user data dir of one browser. var overrides = map[string]browser.Extractors{ "yandex": { category.Password: encrypted(file("Ya Passman Data"), extractYandexPasswords), @@ -45,7 +44,6 @@ var operaExtractors = browser.Extractors{ category.Extension: plain(file("Secure Preferences"), extractOperaExtensions), } -// Extractors maps every category a Chromium profile supports to its extractor, with the forks' own formats applied. func Extractors(dir browser.UserDataDir, _ browser.Profile) browser.Extractors { ex := make(browser.Extractors, len(defaultExtractors)) for c, e := range defaultExtractors { @@ -87,8 +85,7 @@ func plain(src browser.Source, parse func(string, browser.Collector) error) brow } } -// extractPasswordStores reads both password databases: a profile that only ever synced passwords has just the account -// one, and one database failing does not hide the other's logins. +// A profile that only synced passwords has just the account store, and one store failing keeps the other's logins. func extractPasswordStores(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { stores := []struct { src browser.Source diff --git a/internal/browser/chromium/testutil_test.go b/internal/browser/chromium/testutil_test.go index 964b4a2..73f6c9d 100644 --- a/internal/browser/chromium/testutil_test.go +++ b/internal/browser/chromium/testutil_test.go @@ -14,18 +14,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// --------------------------------------------------------------------------- -// Shared test constants for Chromium encryption. -// Reusable across decrypt, cookie, password, and creditcard tests. -// --------------------------------------------------------------------------- - -// testAESKey is a 16-byte AES-128 key for constructing test ciphertext. var testAESKey = []byte("0123456789abcdef") -// --------------------------------------------------------------------------- -// Real Chrome table schemas — extracted via `sqlite3 ".schema "`. -// Using complete schemas ensures our SQL queries work against real browser data. -// --------------------------------------------------------------------------- +// Real Chrome schemas from sqlite3 .schema, so the queries are tested against the columns browsers have. const loginsSchema = `CREATE TABLE logins ( origin_url VARCHAR NOT NULL, @@ -141,10 +132,7 @@ const creditCardsSchema = `CREATE TABLE credit_cards ( nickname VARCHAR )` -// --------------------------------------------------------------------------- -// INSERT helpers — each returns one SQL statement with only the fields -// our extract functions care about; other NOT NULL columns get defaults. -// --------------------------------------------------------------------------- +// Each insert sets only the fields the extractors read; other NOT NULL columns take their defaults. func insertLogin(originURL, actionURL, username, pwdHex string, dateCreated int64) string { return fmt.Sprintf( @@ -194,13 +182,6 @@ func insertCreditCard(name string, month, year int, encNumberHex, nickName, addr ) } -// --------------------------------------------------------------------------- -// Test fixture builders -// --------------------------------------------------------------------------- - -// installFile copies a test fixture file into a profile directory. -// This bridges per-category setup functions (which return standalone paths) -// and browser-level integration tests (which need files inside a profile). func installFile(t *testing.T, profileDir, srcPath, dstName string) { t.Helper() data, err := os.ReadFile(srcPath) @@ -208,7 +189,6 @@ func installFile(t *testing.T, profileDir, srcPath, dstName string) { require.NoError(t, os.WriteFile(filepath.Join(profileDir, dstName), data, 0o644)) } -// createTestDB creates a SQLite database with the given schema and insert statements. func createTestDB(t *testing.T, name, schema string, inserts ...string) string { t.Helper() path := filepath.Join(t.TempDir(), name) @@ -226,7 +206,6 @@ func createTestDB(t *testing.T, name, schema string, inserts ...string) string { return path } -// createTestJSON creates a file with the given JSON content. func createTestJSON(t *testing.T, name, content string) string { t.Helper() path := filepath.Join(t.TempDir(), name) @@ -234,7 +213,6 @@ func createTestJSON(t *testing.T, name, content string) string { return path } -// createTestLevelDB creates a LevelDB directory with the given key-value pairs. func createTestLevelDB(t *testing.T, entries map[string]string) string { t.Helper() dir := filepath.Join(t.TempDir(), "leveldb") @@ -247,7 +225,6 @@ func createTestLevelDB(t *testing.T, entries map[string]string) string { return dir } -// testCollector keeps what an extractor hands it, in order. type testCollector struct { records []record.Record fails []error diff --git a/internal/browser/chromium/vault.go b/internal/browser/chromium/vault.go index ddd0489..35378a9 100644 --- a/internal/browser/chromium/vault.go +++ b/internal/browser/chromium/vault.go @@ -6,8 +6,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" ) -// A keys.json vault names its on-disk format by kind, so a reader without the browser in its table still picks the -// forks' own files. +// A vault names its on-disk format by kind, so a reader without the browser in its table still picks its files. const ( kindChromium = "chromium" kindYandex = "chromium-yandex" @@ -22,7 +21,6 @@ var kinds = map[string]string{ "vought": kindOpera, } -// VaultKind is def's kind in keys.json. func VaultKind(def browser.Def) string { if kind, ok := kinds[def.ID]; ok { return kind diff --git a/internal/browser/chromium/yandex.go b/internal/browser/chromium/yandex.go index a311e4d..87d4055 100644 --- a/internal/browser/chromium/yandex.go +++ b/internal/browser/chromium/yandex.go @@ -11,8 +11,6 @@ import ( _ "modernc.org/sqlite" ) -// yandexLoginAAD is SHA1(origin_url \x00 username_element \x00 username_value \x00 password_element \x00 signon_realm), -// with keyID appended when the profile has a master password (v1 always passes nil). func yandexLoginAAD(originURL, usernameElem, usernameVal, passwordElem, signonRealm string, keyID []byte) []byte { h := sha1.New() h.Write([]byte(originURL)) @@ -34,7 +32,6 @@ func yandexLoginAAD(originURL, usernameElem, usernameVal, passwordElem, signonRe return out } -// yandexCardAAD is the raw guid bytes (+ keyID if the profile has a master password). func yandexCardAAD(guid string, keyID []byte) []byte { if len(keyID) == 0 { return []byte(guid) @@ -48,7 +45,6 @@ func yandexCardAAD(guid string, keyID []byte) []byte { // errYandexMasterPasswordSet fails the extraction; unsealing a master-password profile is deferred. var errYandexMasterPasswordSet = errors.New("yandex: profile protected by master password, skipping") -// loadYandexDataKey honors the master-password gate and returns the per-DB data key. func loadYandexDataKey(dbPath string, masterKey []byte) ([]byte, error) { if len(masterKey) == 0 { return nil, fmt.Errorf("yandex: master key not available") diff --git a/internal/browser/chromium/yandex_key.go b/internal/browser/chromium/yandex_key.go index 618ace6..63d2b85 100644 --- a/internal/browser/chromium/yandex_key.go +++ b/internal/browser/chromium/yandex_key.go @@ -24,7 +24,6 @@ var ( errYandexKeyTooShort = errors.New("yandex: decrypted intermediate key shorter than 32 bytes") ) -// decryptYandexIntermediateKey unwraps the per-DB data key from meta.local_encryptor_data. func decryptYandexIntermediateKey(masterKey, blob []byte) ([]byte, error) { idx := bytes.Index(blob, localEncryptorPrefix) if idx < 0 { diff --git a/internal/browser/chromium/yandex_key_test.go b/internal/browser/chromium/yandex_key_test.go index 6d2e77d..2f0b14c 100644 --- a/internal/browser/chromium/yandex_key_test.go +++ b/internal/browser/chromium/yandex_key_test.go @@ -8,7 +8,6 @@ import ( "testing" ) -// encryptAESGCM is a test helper that produces a GCM ciphertext with caller-supplied AAD. func encryptAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { t.Helper() block, err := aes.NewCipher(key) @@ -22,8 +21,7 @@ func encryptAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { return aead.Seal(nil, nonce, plaintext, aad) } -// testPlaintextPayloadLen: plaintext size before AES-GCM seal inside meta.local_encryptor_data. -// 96 (blob) - 12 (nonce) - 16 (tag) = 68 bytes. +// 96 (blob) - 12 (nonce) - 16 (tag) = 68 bytes of payload before sealing. const testPlaintextPayloadLen = yandexIntKeyBlobLen - gcmNonceSize - 16 func buildLocalEncryptorBlob(t *testing.T, masterKey, dataKey []byte) []byte { @@ -90,8 +88,6 @@ func TestDecryptYandexIntermediateKey_BadSignature(t *testing.T) { } } -// TestDecryptYandexIntermediateKey_TrailingDataIgnored verifies that trailing bytes past -// signature+32 are discarded. func TestDecryptYandexIntermediateKey_TrailingDataIgnored(t *testing.T) { masterKey := bytes.Repeat([]byte{0x11}, 32) nonce := bytes.Repeat([]byte{0xAB}, gcmNonceSize) diff --git a/internal/browser/chromium/yandex_testutil_test.go b/internal/browser/chromium/yandex_testutil_test.go index 4b26aee..2481a75 100644 --- a/internal/browser/chromium/yandex_testutil_test.go +++ b/internal/browser/chromium/yandex_testutil_test.go @@ -16,19 +16,7 @@ import ( "github.com/stretchr/testify/require" ) -// --------------------------------------------------------------------------- -// Yandex-specific SQLite schemas and test fixtures. -// -// Ya Passman Data: -// - meta(key, value) holds local_encryptor_data -// - active_keys(key_id, sealed_key) non-empty sealed_key = master password set -// - logins(...) same column set as Chromium, minus columns we -// don't query, plus a signon_realm NOT NULL -// -// Ya Credit Cards: -// - meta(key, value) holds its own local_encryptor_data -// - records(guid, public_data, private_data) -// --------------------------------------------------------------------------- +// Ya Passman Data holds meta, active_keys, and logins; Ya Credit Cards holds meta and records. const yandexLoginsSchema = `CREATE TABLE logins ( origin_url VARCHAR NOT NULL, @@ -57,21 +45,15 @@ const yandexRecordsSchema = `CREATE TABLE records ( private_data BLOB )` -// yandexTestNonce is a fixed 12-byte nonce used across fixtures so test failures -// are easy to reproduce by hand. Real Yandex uses CSPRNG nonces per row. +// A fixed nonce keeps failures reproducible by hand; Yandex itself draws a random one per row. var yandexTestNonce = bytes.Repeat([]byte{0x77}, 12) -// yandexMasterKeyBlobNonce is a fixed 12-byte nonce for sealing the intermediate -// data key inside meta.local_encryptor_data. Distinct from yandexTestNonce so a -// test mix-up surfaces as a decrypt error rather than a false pass. +// Distinct from yandexTestNonce, so mixing the two up fails to decrypt instead of passing. var yandexMasterKeyBlobNonce = bytes.Repeat([]byte{0xAB}, 12) -// yandexSignatureForFixtures duplicates crypto.yandexSignature so tests can -// construct blobs without the crypto package exporting its internal constant. -// Protobuf header bytes: field1 varint=1, field2 len=32. +// Protobuf header: field 1 varint 1, field 2 length 32. var yandexSignatureForFixtures = []byte{0x08, 0x01, 0x12, 0x20} -// yandexSealAESGCM seals plaintext under (key, nonce, aad) using AES-GCM. func yandexSealAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { t.Helper() block, err := aes.NewCipher(key) @@ -81,9 +63,7 @@ func yandexSealAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { return aead.Seal(nil, nonce, plaintext, aad) } -// buildYandexLocalEncryptorBlob produces the exact byte layout stored in -// meta.local_encryptor_data: [preamble]"v10"[12B nonce][68B plaintext + 16B GCM tag]. -// The plaintext is signature (4B) + dataKey (32B) + zero padding to 68B. +// meta.local_encryptor_data: preamble, "v10", nonce, then signature and key sealed and padded to 68 bytes. func buildYandexLocalEncryptorBlob(t *testing.T, masterKey, dataKey []byte) []byte { t.Helper() plaintext := append([]byte{}, yandexSignatureForFixtures...) @@ -99,17 +79,12 @@ func buildYandexLocalEncryptorBlob(t *testing.T, masterKey, dataKey []byte) []by return blob } -// yandexPassword describes one row of test data for the logins table. type yandexPassword struct { OriginURL, UsernameElem, UsernameVal, PasswordElem, SignonRealm, Password string DateCreated int64 } -// setupYandexPasswordDB creates a Ya Passman Data SQLite file with meta, -// active_keys, and logins populated. Each logins row is sealed under dataKey -// using the same per-row AAD derivation the production extractor expects. -// Set hasMasterPassword=true to simulate a profile protected by a master -// password (a non-empty sealed_key row). +// hasMasterPassword adds a non-empty sealed_key row, as a master-password profile has. func setupYandexPasswordDB(t *testing.T, masterKey, dataKey []byte, hasMasterPassword bool, rows ...yandexPassword) string { t.Helper() path := filepath.Join(t.TempDir(), "Ya Passman Data") @@ -149,16 +124,12 @@ func setupYandexPasswordDB(t *testing.T, masterKey, dataKey []byte, hasMasterPas return path } -// yandexCreditCard describes one row of test data for the records table. type yandexCreditCard struct { GUID string CardHolder, CardTitle, ExpYear, ExpMonth string FullCardNumber, PinCode, SecretComment string } -// setupYandexCreditCardDB creates a Ya Credit Cards SQLite file with meta and -// records populated. Each record's private_data is sealed under dataKey with -// AAD = guid bytes, matching the production extractor. func setupYandexCreditCardDB(t *testing.T, masterKey, dataKey []byte, rows ...yandexCreditCard) string { t.Helper() path := filepath.Join(t.TempDir(), "Ya Credit Cards") diff --git a/internal/browser/extractor.go b/internal/browser/extractor.go index 032c912..a669e29 100644 --- a/internal/browser/extractor.go +++ b/internal/browser/extractor.go @@ -34,38 +34,31 @@ func (s Source) Candidates(p Profile) []string { return rels } -// Extractor declares the sources a category needs and how to parse them. type Extractor struct { Sources []Source Extract func(ctx context.Context, ps ProfileSnapshot, out Collector) error } -// Extractors maps each category a profile supports to its extractor. type Extractors map[category.Category]Extractor -// Collector receives one extraction's output and stamps Browser and Profile on every record, so no extractor can omit -// them. Fail records one record-level problem, a secret that could not be recovered or a row that could not be parsed, -// and the extraction goes on. +// Collector stamps every record's Browser and Profile; Fail reports a bad record and the extraction goes on. type Collector interface { Add(r record.Record) Fail(err error) } -// ProfileSnapshot is what an extractor is handed: its profile's view of the user data dir's snapshot, and the dir's keys. type ProfileSnapshot struct { Profile Profile snap snapshot.Snapshot masterKeys func(ctx context.Context) masterkey.Set } -// NewProfileSnapshot gives a profile its share of snap. masterKeys is the user data dir's call-once retrieval, nil for -// the bases that keep no Chromium keys. +// masterKeys is the user data dir's call-once retrieval, nil for the bases that keep no Chromium keys. func NewProfileSnapshot(snap snapshot.Snapshot, p Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot { return ProfileSnapshot{Profile: p, snap: snap, masterKeys: masterKeys} } -// Path returns where src was captured: its first candidate present in the snapshot. A candidate that was never captured -// is skipped; one whose copy failed returns that copy's error. +// Path skips a candidate that was never captured but returns the error of one whose copy failed. func (ps ProfileSnapshot) Path(src Source) (string, error) { for _, rel := range src.Candidates(ps.Profile) { p, err := ps.snap.Path(rel) @@ -77,8 +70,7 @@ func (ps ProfileSnapshot) Path(src Source) (string, error) { return "", fmt.Errorf("%s: %w", strings.Join(src.Paths, " or "), fs.ErrNotExist) } -// MasterKeys returns the user data dir's Chromium keys, one per version; a version that could not be retrieved is -// absent. It may block on the first call, which retrieves them for every profile of the dir. +// MasterKeys may block on its first call; a key version that could not be retrieved is absent from the Set. func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set { if ps.masterKeys == nil { return nil diff --git a/internal/browser/firefox/extract_bookmark_test.go b/internal/browser/firefox/extract_bookmark_test.go index 914173a..b6433c9 100644 --- a/internal/browser/firefox/extract_bookmark_test.go +++ b/internal/browser/firefox/extract_bookmark_test.go @@ -32,7 +32,6 @@ func TestExtractBookmarks(t *testing.T) { 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[1].URL) assert.Equal(t, int64(2), got[1].ID) assert.Equal(t, "url", got[1].Type) diff --git a/internal/browser/firefox/extract_cookie_test.go b/internal/browser/firefox/extract_cookie_test.go index 9f3d4ea..261cb36 100644 --- a/internal/browser/firefox/extract_cookie_test.go +++ b/internal/browser/firefox/extract_cookie_test.go @@ -30,7 +30,6 @@ func TestExtractCookies(t *testing.T) { 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[1].Name) assert.Equal(t, "xyz789", got[1].Value) assert.Equal(t, "/api", got[1].Path) diff --git a/internal/browser/firefox/extract_download.go b/internal/browser/firefox/extract_download.go index 381050c..7758d16 100644 --- a/internal/browser/firefox/extract_download.go +++ b/internal/browser/firefox/extract_download.go @@ -30,8 +30,7 @@ func extractDownloads(path string, out browser.Collector) error { StartTime: timeconv.UnixMicro(dateAdded), } - // Firefox stores download metadata as: "target_path,{json}" - // Parse the JSON part to extract fileSize and endTime. + // Firefox stores the content as "target_path,{json}"; the JSON holds fileSize and endTime. contentList := strings.SplitN(content, ",{", 2) if len(contentList) == 2 { entry.TargetPath = contentList[0] diff --git a/internal/browser/firefox/extract_download_test.go b/internal/browser/firefox/extract_download_test.go index 21f2e9a..53882bf 100644 --- a/internal/browser/firefox/extract_download_test.go +++ b/internal/browser/firefox/extract_download_test.go @@ -32,7 +32,6 @@ func TestExtractDownloads(t *testing.T) { 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[1].TargetPath) assert.False(t, got[1].StartTime.IsZero()) } diff --git a/internal/browser/firefox/extract_history_test.go b/internal/browser/firefox/extract_history_test.go index 82cb8e4..ffe7c28 100644 --- a/internal/browser/firefox/extract_history_test.go +++ b/internal/browser/firefox/extract_history_test.go @@ -32,7 +32,6 @@ func TestExtractHistories(t *testing.T) { assert.Equal(t, 50, got[1].VisitCount) assert.Equal(t, 200, got[2].VisitCount) - // 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()) diff --git a/internal/browser/firefox/extract_password.go b/internal/browser/firefox/extract_password.go index 892a321..8ffb277 100644 --- a/internal/browser/firefox/extract_password.go +++ b/internal/browser/firefox/extract_password.go @@ -13,7 +13,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -// decryptPBE combines base64 decode + ASN1 PBE parse + decrypt into one call. func decryptPBE(encoded string, masterKey []byte) ([]byte, error) { raw, err := base64.StdEncoding.DecodeString(encoded) if err != nil { diff --git a/internal/browser/firefox/extract_password_test.go b/internal/browser/firefox/extract_password_test.go index ece7e54..d4e1a86 100644 --- a/internal/browser/firefox/extract_password_test.go +++ b/internal/browser/firefox/extract_password_test.go @@ -13,8 +13,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// These values are from crypto/asn1pbe_test.go loginPBETestCases. -// loginPBE hex decrypts to "Hello, World!" with globalSalt = "moond4rk" * 3. +// From crypto's loginPBETestCases: decrypts to "Hello, World!" with globalSalt = "moond4rk" * 3. const loginPBEHex = "303b0410f8000000000000000000000000000001301506092a864886f70d010503040830313233343536370410fe968b6565149114ea688defd6683e45" var testGlobalSalt = bytes.Repeat([]byte("moond4rk"), 3) // 24 bytes @@ -31,7 +30,6 @@ func loginPBEBase64(t *testing.T) string { func TestExtractPasswords(t *testing.T) { encB64 := loginPBEBase64(t) - // Construct a logins.json with known encrypted username/password json := fmt.Sprintf(`{ "logins": [ { @@ -52,7 +50,6 @@ func TestExtractPasswords(t *testing.T) { require.NoError(t, err) require.Len(t, got, 1) - // Both username and password decrypt to "Hello, World!" assert.Equal(t, "Hello, World!", got[0].Username) assert.Equal(t, "Hello, World!", got[0].Password) assert.Equal(t, "https://example.com/login", got[0].URL) @@ -106,8 +103,8 @@ func TestExtractPasswords_DecryptFailureKeepsEntry(t *testing.T) { require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "https://bad.com", got[0].URL) - assert.Empty(t, got[0].Username) // decrypt failed → empty - assert.Empty(t, got[0].Password) // decrypt failed → empty + assert.Empty(t, got[0].Username) + assert.Empty(t, got[0].Password) assert.Len(t, out.fails, 2) } diff --git a/internal/browser/firefox/extract_storage.go b/internal/browser/firefox/extract_storage.go index 3dffc6f..395b800 100644 --- a/internal/browser/firefox/extract_storage.go +++ b/internal/browser/firefox/extract_storage.go @@ -40,8 +40,7 @@ func reverseString(s string) string { return string(b) } -// parseOriginKey converts Firefox's reversed origin format to a URL. -// Example: "moc.buhtig.:https:443" → "https://github.com:443" +// Firefox reverses the host: "moc.buhtig.:https:443" is https://github.com:443. func parseOriginKey(originKey string) string { parts := strings.SplitN(originKey, ":", 3) if len(parts) < 2 { diff --git a/internal/browser/firefox/extract_storage_test.go b/internal/browser/firefox/extract_storage_test.go index b7605e1..9b63f4e 100644 --- a/internal/browser/firefox/extract_storage_test.go +++ b/internal/browser/firefox/extract_storage_test.go @@ -27,7 +27,6 @@ func TestExtractLocalStorage(t *testing.T) { require.NoError(t, err) require.Len(t, got, 3) - // Verify field mapping by collecting into lookup byKey := map[string]string{} for _, entry := range got { byKey[entry.URL+"/"+entry.Key] = entry.Value diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go index 9989d19..bd6e207 100644 --- a/internal/browser/firefox/firefox.go +++ b/internal/browser/firefox/firefox.go @@ -1,5 +1,4 @@ -// Package firefox is the Firefox base: where Firefox keeps its profiles, how their files are parsed, and how each -// profile's own key4.db opens its logins. +// Package firefox is the Firefox base: profile discovery, file parsing, and each profile's own key4.db. package firefox import ( @@ -32,8 +31,7 @@ var extractors = browser.Extractors{ category.LocalStorage: plain(file("webappsstore.sqlite"), extractLocalStorage), } -// Discover finds def's Profiles directory and the profiles in it. -p names one profile: its parent is the Profiles -// directory, and only that profile is selected. +// -p names one profile: its parent is the Profiles directory, and only that profile is selected. func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { if opts.ProfilePath != "" { return profileAt(def, opts.ProfilePath), nil @@ -85,8 +83,7 @@ func dirID(def browser.Def, i int) browser.DirID { return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) } -// discoverProfiles takes every subdirectory holding a file some category reads, since profile directories have random -// names; key4.db alone does not make one. +// Profile directories have random names, so any subdirectory holding a source counts; key4.db alone does not. func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { entries, err := os.ReadDir(dir.Path) if err != nil { @@ -117,7 +114,6 @@ func hasDataFile(dir string) bool { return false } -// Extractors maps every category a Firefox profile supports to its extractor. func Extractors(_ browser.UserDataDir, _ browser.Profile) browser.Extractors { ex := make(browser.Extractors, len(extractors)) for c, e := range extractors { @@ -141,8 +137,7 @@ func plain(src browser.Source, parse func(string, browser.Collector) error) brow } } -// extractLogins derives the profile's key only once a login needs it. Without a key the logins are still exported, -// their username and password empty, and the reason is the extraction's first problem. +// The key is derived only once a login needs it; without one the logins export with empty secrets. func extractLogins(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { path, err := ps.Path(loginsJSON) if err != nil { diff --git a/internal/browser/firefox/firefox_test.go b/internal/browser/firefox/firefox_test.go index 56a2a9e..c0c9484 100644 --- a/internal/browser/firefox/firefox_test.go +++ b/internal/browser/firefox/firefox_test.go @@ -30,7 +30,6 @@ func touch(t *testing.T, parts ...string) { require.NoError(t, os.WriteFile(path, []byte("{}"), 0o600)) } -// snapshotOf lays fixture files out as one user data dir's snapshot, keyed by their path relative to the dir. func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { t.Helper() root := t.TempDir() @@ -122,8 +121,7 @@ func TestExtractors_CoverFirefoxCategories(t *testing.T) { } } -// Without key4.db the logins are still exported with empty secrets, and the missing key is the first problem; before, -// decrypting a legacy-cipher login without a key panicked and ended the run. +// Without key4.db the logins export with empty secrets; before, a legacy-cipher login without a key panicked. func TestExtractLogins_WithoutKeyStore(t *testing.T) { enc := loginPBEBase64(t) logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test", diff --git a/internal/browser/firefox/masterkey.go b/internal/browser/firefox/masterkey.go index d8be134..dde1a4b 100644 --- a/internal/browser/firefox/masterkey.go +++ b/internal/browser/firefox/masterkey.go @@ -37,32 +37,21 @@ func retrieveMasterKey(key4Path, loginsPath string) ([]byte, error) { return nil, fmt.Errorf("derived %d key(s) but none could decrypt logins", len(keys)) } -// key4DB holds the parsed contents of Firefox's key4.db NSS key storage. -// -// Firefox stores the master encryption key in key4.db using two SQLite tables: -// - metaData: contains the global salt and an encrypted "password-check" marker -// - nssPrivate: contains one or more encrypted master key candidates -// -// Reference: https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/ +// See https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/ for key4.db's layout. type key4DB struct { globalSalt []byte // metaData.item1: salt used as PBE decryption input passwordCheck []byte // metaData.item2: encrypted marker to verify DB integrity privateKeys []privateKey // nssPrivate rows: encrypted master key candidates } -// privateKey is a single encrypted master key entry from nssPrivate. type privateKey struct { encrypted []byte // a11: PBE-encrypted master key blob typeTag []byte // a102: key type identifier (must match nssKeyTypeTag) } -// nssKeyTypeTag identifies valid master key entries in key4.db. -// Only nssPrivate rows where a102 matches this tag contain actual master keys; -// other rows may be certificates or other NSS objects. -// See: https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/pkcs11i.h +// Only nssPrivate rows tagged with this a102 value hold keys; see softoken/pkcs11i.h in NSS. var nssKeyTypeTag = []byte{248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} -// readKey4DB opens key4.db and parses it into a structured key4DB. func readKey4DB(path string) (*key4DB, error) { db, err := sql.Open("sqlite", path) if err != nil { @@ -101,8 +90,6 @@ func readKey4DB(path string) (*key4DB, error) { return &record, nil } -// deriveKeys verifies the database integrity via the password-check marker, -// then decrypts all valid master key candidates. func (k *key4DB) deriveKeys() ([][]byte, error) { if err := k.verifyPasswordCheck(); err != nil { return nil, err @@ -123,8 +110,6 @@ func (k *key4DB) deriveKeys() ([][]byte, error) { return keys, nil } -// verifyPasswordCheck decrypts the password-check marker from metaData -// to confirm the database is valid and accessible. func (k *key4DB) verifyPasswordCheck() error { pbe, err := crypto.NewASN1PBE(k.passwordCheck) if err != nil { @@ -140,7 +125,6 @@ func (k *key4DB) verifyPasswordCheck() error { return nil } -// decryptPrivateKey decrypts a single master key candidate using the global salt. func (k *key4DB) decryptPrivateKey(pk privateKey) ([]byte, error) { pbe, err := crypto.NewASN1PBE(pk.encrypted) if err != nil { @@ -153,20 +137,16 @@ func (k *key4DB) decryptPrivateKey(pk privateKey) ([]byte, error) { if len(derivedKey) < 24 { return nil, fmt.Errorf("derived key too short: %d bytes (need >= 24)", len(derivedKey)) } - // Firefox 144+ uses AES-256-CBC instead of 3DES; the full derived key - // must be preserved to support modern cipher suites. + // Firefox 144+ uses AES-256-CBC, so the whole derived key is kept rather than 3DES's 24 bytes. return derivedKey, nil } -// encryptedLogin holds PBE-encrypted credentials from logins.json, -// used as test samples for master key validation. type encryptedLogin struct { - username []byte // PBE-encrypted username blob - password []byte // PBE-encrypted password blob + username []byte + password []byte } -// validateKeyWithLogins reads logins.json and returns the first key that -// can successfully decrypt an actual login entry. Returns nil if no key matches. +// validateKeyWithLogins returns nil when no key decrypts a login. func validateKeyWithLogins(keys [][]byte, loginsPath string) []byte { raw, err := os.ReadFile(loginsPath) if err != nil { @@ -184,8 +164,7 @@ func validateKeyWithLogins(keys [][]byte, loginsPath string) []byte { return nil } -// sampleEncryptedLogins extracts up to 5 encrypted login entries from -// logins.json as test samples for master key validation. +// Up to 5 logins are enough to tell which key opens them. func sampleEncryptedLogins(raw []byte) []encryptedLogin { arr := gjson.GetBytes(raw, "logins").Array() var samples []encryptedLogin @@ -206,8 +185,6 @@ func sampleEncryptedLogins(raw []byte) []encryptedLogin { return samples } -// tryDecryptLogins checks if masterKey can decrypt at least one encrypted -// login entry (both username and password). func tryDecryptLogins(masterKey []byte, samples []encryptedLogin) bool { for _, login := range samples { userPBE, err := crypto.NewASN1PBE(login.username) diff --git a/internal/browser/firefox/masterkey_test.go b/internal/browser/firefox/masterkey_test.go index 3c91a66..df5e84e 100644 --- a/internal/browser/firefox/masterkey_test.go +++ b/internal/browser/firefox/masterkey_test.go @@ -9,7 +9,6 @@ import ( ) func TestReadKey4DB(t *testing.T) { - // Create a minimal key4.db with metaData and nssPrivate tables path := createTestDB(t, "key4.db", []string{ `CREATE TABLE metaData (id TEXT PRIMARY KEY, item1 BLOB, item2 BLOB)`, diff --git a/internal/browser/firefox/testutil_test.go b/internal/browser/firefox/testutil_test.go index 6deb431..65c2a93 100644 --- a/internal/browser/firefox/testutil_test.go +++ b/internal/browser/firefox/testutil_test.go @@ -13,9 +13,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// --------------------------------------------------------------------------- -// Real Firefox table schemas — extracted via `sqlite3 ".schema
"`. -// --------------------------------------------------------------------------- +// Real Firefox schemas from sqlite3 .schema, so the queries are tested against the columns browsers have. const mozCookiesSchema = `CREATE TABLE moz_cookies ( id INTEGER PRIMARY KEY, @@ -95,10 +93,6 @@ const webappsstore2Schema = `CREATE TABLE webappsstore2 ( value TEXT )` -// --------------------------------------------------------------------------- -// INSERT helpers -// --------------------------------------------------------------------------- - func insertMozCookie(name, value, host, path string, creationTime, expiry int64, isSecure, isHTTPOnly int) string { return fmt.Sprintf( `INSERT INTO moz_cookies (name, value, host, path, creationTime, expiry, isSecure, isHttpOnly, lastAccessed) @@ -139,11 +133,6 @@ func insertWebappsstore(originKey, key, value string) string { ) } -// --------------------------------------------------------------------------- -// Test fixture builders -// --------------------------------------------------------------------------- - -// installFile copies a test fixture file into a profile directory. func installFile(t *testing.T, profileDir, srcPath, dstName string) { t.Helper() data, err := os.ReadFile(srcPath) @@ -176,7 +165,6 @@ func createTestJSON(t *testing.T, name, content string) string { return path } -// testCollector keeps what an extractor hands it, in order. type testCollector struct { records []record.Record fails []error diff --git a/internal/browser/platform_darwin.go b/internal/browser/platform_darwin.go index eba17e7..969e540 100644 --- a/internal/browser/platform_darwin.go +++ b/internal/browser/platform_darwin.go @@ -2,5 +2,4 @@ package browser -// Platform returns the running OS's entry. func (d Def) Platform() Platform { return d.Darwin } diff --git a/internal/browser/platform_linux.go b/internal/browser/platform_linux.go index 2831ba1..1f4712b 100644 --- a/internal/browser/platform_linux.go +++ b/internal/browser/platform_linux.go @@ -2,5 +2,4 @@ package browser -// Platform returns the running OS's entry. func (d Def) Platform() Platform { return d.Linux } diff --git a/internal/browser/platform_windows.go b/internal/browser/platform_windows.go index 12f60fa..7a2fc52 100644 --- a/internal/browser/platform_windows.go +++ b/internal/browser/platform_windows.go @@ -2,5 +2,4 @@ package browser -// Platform returns the running OS's entry. func (d Def) Platform() Platform { return d.Windows } diff --git a/internal/browser/safari/extract_bookmark.go b/internal/browser/safari/extract_bookmark.go index ec0ad78..408559e 100644 --- a/internal/browser/safari/extract_bookmark.go +++ b/internal/browser/safari/extract_bookmark.go @@ -11,7 +11,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// safariBookmark mirrors the plist structure of Safari's Bookmarks.plist. type safariBookmark struct { Type string `plist:"WebBookmarkType"` Title string `plist:"Title"` @@ -47,8 +46,7 @@ func extractBookmarks(path string, out browser.Collector) error { return nil } -// walkBookmarks collects the leaves in tree order. A leaf's ID is its position among them, counting from 1, because -// the plist stores no number and an index within one folder repeats across folders. +// A leaf's ID is its position among all leaves, from 1: the plist stores no number, and per-folder indexes repeat. func walkBookmarks(nodes []safariBookmark, folder string, out *[]record.Bookmark) { for _, node := range nodes { switch node.Type { diff --git a/internal/browser/safari/extract_bookmark_test.go b/internal/browser/safari/extract_bookmark_test.go index cc36d8c..d57ad9f 100644 --- a/internal/browser/safari/extract_bookmark_test.go +++ b/internal/browser/safari/extract_bookmark_test.go @@ -63,7 +63,6 @@ func TestExtractBookmarks(t *testing.T) { require.NoError(t, err) require.Len(t, bookmarks, 3) - // Verify folder assignment assert.Equal(t, "GitHub", bookmarks[0].Name) assert.Equal(t, "https://github.com", bookmarks[0].URL) assert.Equal(t, "BookmarksBar", bookmarks[0].Folder) diff --git a/internal/browser/safari/extract_cookie.go b/internal/browser/safari/extract_cookie.go index faa0898..5863116 100644 --- a/internal/browser/safari/extract_cookie.go +++ b/internal/browser/safari/extract_cookie.go @@ -20,8 +20,7 @@ func extractCookies(path string, out browser.Collector) error { 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. + // binarycookies returns local times; UTC keeps the JSON in line with Chromium's and Firefox's cookies. cookies = append(cookies, record.Cookie{ Host: string(c.Domain), Path: string(c.Path), diff --git a/internal/browser/safari/extract_cookie_test.go b/internal/browser/safari/extract_cookie_test.go index 8520fac..cf5deb2 100644 --- a/internal/browser/safari/extract_cookie_test.go +++ b/internal/browser/safari/extract_cookie_test.go @@ -13,8 +13,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// buildTestBinaryCookies constructs a minimal valid Cookies.binarycookies file -// containing the given cookies. Each cookie is placed in its own page. +// Each cookie goes in its own page of a minimal Cookies.binarycookies file. func buildTestBinaryCookies(t *testing.T, cookies []testCookie) string { t.Helper() @@ -38,7 +37,6 @@ func buildTestBinaryCookies(t *testing.T, cookies []testCookie) string { require.NoError(t, binary.Write(f, binary.BigEndian, uint32(len(p)))) } - // Page data for _, p := range pages { _, err = f.Write(p) require.NoError(t, err) @@ -64,11 +62,7 @@ func buildPage(c testCookie) []byte { cpath := c.path + "\x00" value := c.value + "\x00" - // Cookie binary layout (all offsets are from cookie start): - // size(4) + unknown1(4) + flags(4) + unknown2(4) - // + domainOff(4) + nameOff(4) + pathOff(4) + valueOff(4) + commentOff(4) - // + endHeader(4) + expires(8) + creation(8) - // = 56 bytes header, then string data + // A cookie is a 56-byte header (sizes, flags, string offsets, expiry, creation), then its strings. const headerSize = 56 domainOffset := uint32(headerSize) nameOffset := domainOffset + uint32(len(domain)) @@ -86,18 +80,14 @@ func buildPage(c testCookie) []byte { flags = 0x1 } - // Build cookie bytes (little-endian) + // Cookie fields are little-endian, unlike the file header. cookie := make([]byte, cookieSize) binary.LittleEndian.PutUint32(cookie[0:], cookieSize) - // cookie[4:8] = unknown1 (zero) binary.LittleEndian.PutUint32(cookie[8:], flags) - // cookie[12:16] = unknown2 (zero) binary.LittleEndian.PutUint32(cookie[16:], domainOffset) binary.LittleEndian.PutUint32(cookie[20:], nameOffset) binary.LittleEndian.PutUint32(cookie[24:], pathOffset) binary.LittleEndian.PutUint32(cookie[28:], valueOffset) - // cookie[32:36] = commentOffset (zero = no comment) - // cookie[36:40] = endHeader marker (zero) binary.LittleEndian.PutUint64(cookie[40:], math.Float64bits(c.expires)) binary.LittleEndian.PutUint64(cookie[48:], math.Float64bits(c.creation)) copy(cookie[domainOffset:], domain) @@ -106,12 +96,11 @@ func buildPage(c testCookie) []byte { copy(cookie[valueOffset:], value) // Page layout: marker(4) + cookieCount(4) + offsets(4*N) + endMarker(4) + cookies - const pageHeaderSize = 16 // marker + count + 1 offset + end marker + const pageHeaderSize = 16 page := make([]byte, pageHeaderSize+len(cookie)) copy(page[0:4], []byte{0x00, 0x00, 0x01, 0x00}) // page start marker binary.LittleEndian.PutUint32(page[4:], 1) // 1 cookie binary.LittleEndian.PutUint32(page[8:], pageHeaderSize) - // page[12:16] = page end marker (zero) copy(page[pageHeaderSize:], cookie) return page @@ -141,8 +130,7 @@ func TestExtractCookies(t *testing.T) { assert.Equal(t, ".example.com", cookies[0].Host) assert.Equal(t, ".go.dev", cookies[1].Host) - // Verify field mapping - c := cookies[0] // .example.com cookie + c := cookies[0] assert.Equal(t, "session", c.Name) assert.Equal(t, "abc123", c.Value) assert.Equal(t, "/", c.Path) diff --git a/internal/browser/safari/extract_download.go b/internal/browser/safari/extract_download.go index efedf80..47a1f9f 100644 --- a/internal/browser/safari/extract_download.go +++ b/internal/browser/safari/extract_download.go @@ -23,9 +23,7 @@ type safariDownloadEntry struct { DownloadIdentifier string `plist:"DownloadEntryIdentifier"` } -// 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. +// Downloads.plist is shared across profiles: entries are kept by owner UUID, and untagged ones are the default's. func extractDownloads(path, ownerUUID string, out browser.Collector) error { f, err := os.Open(path) if err != nil { diff --git a/internal/browser/safari/extract_download_test.go b/internal/browser/safari/extract_download_test.go index 346b388..96c75dd 100644 --- a/internal/browser/safari/extract_download_test.go +++ b/internal/browser/safari/extract_download_test.go @@ -23,8 +23,7 @@ func buildTestDownloadsPlist(t *testing.T, dl safariDownloads) string { } func TestExtractDownloads_DefaultProfileOnly(t *testing.T) { - // Mixed-owner plist: only entries tagged with DefaultProfile (or untagged, for - // pre-profile Safari) should surface for the default profile. + // Only DefaultProfile and untagged (pre-profile) entries surface for the default profile. const namedUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" dl := safariDownloads{ DownloadHistory: []safariDownloadEntry{ diff --git a/internal/browser/safari/extract_extension.go b/internal/browser/safari/extract_extension.go index 338f3d1..2bcbc9f 100644 --- a/internal/browser/safari/extract_extension.go +++ b/internal/browser/safari/extract_extension.go @@ -13,21 +13,11 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Safari keeps extensions in two sibling plists under the container's Safari dir: -// -// Safari/AppExtensions/Extensions.plist — legacy App Extensions (XPC-based) -// Safari/WebExtensions/Extensions.plist — modern Safari Web Extensions -// -// Both files share the same top-level shape: a dictionary keyed by -// " ()". Only WebExtensions carry an `Enabled` field; -// an App Extension that appears in the plist is implicitly enabled. -// extensionKeyPattern matches the " ()" key format Safari uses. +// Safari keeps App Extensions and Web Extensions in two plists keyed by " ()". +// Only Web Extensions carry Enabled; a listed App Extension is enabled. var extensionKeyPattern = regexp.MustCompile(`^(\S+)\s+\(([^)]+)\)$`) -// safariExtension mirrors the per-extension dict value in Extensions.plist. -// Only fields that map onto record.Extension are decoded; richer fields -// (Permissions, AccessibleOrigins, …) are intentionally ignored for the -// minimum implementation. +// Only the fields record.Extension needs are decoded. type safariExtension struct { Enabled *bool `plist:"Enabled"` } @@ -97,8 +87,7 @@ func decodeSafariExtensionsPlist(path string) ([]extensionRecord, error) { return records, nil } -// bundleIDFromExtensionKey extracts the bundle ID from a " ()" -// key; falls back to the trimmed full key when the format doesn't match. +// A key that does not match the pattern falls back to the whole trimmed key. func bundleIDFromExtensionKey(key string) string { if m := extensionKeyPattern.FindStringSubmatch(key); m != nil { return m[1] diff --git a/internal/browser/safari/extract_extension_test.go b/internal/browser/safari/extract_extension_test.go index e0b689f..49c974b 100644 --- a/internal/browser/safari/extract_extension_test.go +++ b/internal/browser/safari/extract_extension_test.go @@ -12,15 +12,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// testExtensionEntry mirrors the shape of one entry in Safari's Extensions.plist: -// an untyped dictionary keyed by string. Using a map (instead of safariExtension) -// lets tests omit keys like Enabled for AppExtension-style fixtures, matching -// what Safari actually writes. +// A map rather than safariExtension, so fixtures can omit Enabled as App Extensions do. type testExtensionEntry map[string]any -// writeTestExtensionsPlist writes an Extensions.plist under -// /Safari//Extensions.plist. subdir is either -// "AppExtensions" or "WebExtensions". func writeTestExtensionsPlist(t *testing.T, container, subdir string, entries map[string]testExtensionEntry) { t.Helper() dir := filepath.Join(container, "Safari", subdir) diff --git a/internal/browser/safari/extract_history.go b/internal/browser/safari/extract_history.go index 766b0bc..c1e1526 100644 --- a/internal/browser/safari/extract_history.go +++ b/internal/browser/safari/extract_history.go @@ -10,8 +10,7 @@ import ( ) const ( - // safariHistoryQuery joins each history item to its latest visit so - // title and visit_time come from the same history_visits row. + // Each item joins its latest visit, so title and visit_time come from the same history_visits row. safariHistoryQuery = `SELECT hi.url, COALESCE(hv.title, ''), hi.visit_count, COALESCE(hv.visit_time, 0) FROM history_items hi diff --git a/internal/browser/safari/extract_history_test.go b/internal/browser/safari/extract_history_test.go index a3e1dcb..f1f4c87 100644 --- a/internal/browser/safari/extract_history_test.go +++ b/internal/browser/safari/extract_history_test.go @@ -38,7 +38,6 @@ func TestExtractHistories(t *testing.T) { assert.Equal(t, 50, got[1].VisitCount) assert.Equal(t, 200, got[2].VisitCount) - // Verify field mapping. 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) diff --git a/internal/browser/safari/extract_password.go b/internal/browser/safari/extract_password.go index f98765b..d6ce186 100644 --- a/internal/browser/safari/extract_password.go +++ b/internal/browser/safari/extract_password.go @@ -33,7 +33,6 @@ func extractPasswords(ctx context.Context, kc LoginKeychain, out browser.Collect return nil } -// buildURL constructs a URL from InternetPassword fields. func buildURL(protocol, server string, port uint32, path string) string { if server == "" { return "" diff --git a/internal/browser/safari/extract_storage.go b/internal/browser/safari/extract_storage.go index 3065b77..60395c6 100644 --- a/internal/browser/safari/extract_storage.go +++ b/internal/browser/safari/extract_storage.go @@ -15,20 +15,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Modern WebKit (Safari 17+) stores localStorage under a nested, partitioned layout rooted at -// either WebsiteDataStore//Origins (per named profile) or WebsiteData/Default -// (the pre-profile default store). Within that root: -// -// ///origin — binary; encodes top+frame origins -// ///LocalStorage/localstorage.sqlite3 -// -// top-hash == frame-hash ⇒ first-party; they differ for third-party partitioned storage. -// We report the frame origin because that's what window.localStorage exposes to JS. -// ItemTable: (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL); -// value BLOBs are UTF-16 LE strings. -// -// The flat "LocalStorage/__.localstorage" directory that older builds used -// is empty on current Safari and is no longer a supported source. +// Safari 17+ keeps localStorage at ///{origin,LocalStorage/localstorage.sqlite3}, +// where root is WebsiteDataStore//Origins or WebsiteData/Default; the hashes differ for third-party storage. +// The frame origin is reported, since window.localStorage exposes it; the old flat layout is no longer read. const ( webkitOriginFile = "origin" @@ -45,9 +34,7 @@ const ( originEncUTF16 = 0x00 // UTF-16 LE ) -// Port marker values after the (scheme, host) pair in an origin block. -// 0x00 → port is the scheme default (stored as 0). -// 0x01 → next two bytes are a uint16_le port. +// After scheme and host, 0x00 means the default port and 0x01 a uint16 LE port in the next two bytes. const ( originPortDefaultMarker = 0x00 originPortExplicitFlag = 0x01 @@ -84,9 +71,7 @@ func extractLocalStorage(root string, out browser.Collector) error { return nil } -// findOriginDataDirs returns /

/

/ paths that contain both an "origin" file and -// a "LocalStorage/localstorage.sqlite3" database. Non-directory entries, the "salt" sibling, -// and partition dirs without localStorage data are silently skipped. +// Only dirs holding both an origin file and a localstorage.sqlite3 count; the salt sibling and the rest are skipped. func findOriginDataDirs(root string) ([]string, error) { topEntries, err := os.ReadDir(root) if err != nil { @@ -120,18 +105,14 @@ func findOriginDataDirs(root string) ([]string, error) { return out, nil } -// originEndpoint is one half of an origin file (top-frame or frame). Port 0 means the scheme -// default (443 for https, 80 for http) and is omitted from the URL rendering. +// Port 0 is the scheme's default and is left out of the URL. type originEndpoint struct { scheme string host string port uint16 } -// readOriginFile parses WebKit's SecurityOrigin binary serialization and returns the frame -// origin URL (scheme://host[:port]). The file holds two origin blocks back-to-back: top-frame -// then frame. When the frame block is missing/unreadable we fall back to the top-frame so we -// can still attribute the data to *something* meaningful. +// The file holds the top-frame block, then the frame block; without a readable frame the top frame is reported. func readOriginFile(path string) (string, error) { data, err := os.ReadFile(path) if err != nil { @@ -143,7 +124,6 @@ func readOriginFile(path string) (string, error) { } frame, _, ferr := readOriginBlock(data, pos) if ferr != nil { - // Partitioned info unavailable — attribute to the top-frame origin. frame = top } if frame.scheme == "" || frame.host == "" { @@ -152,8 +132,6 @@ func readOriginFile(path string) (string, error) { return formatOriginURL(frame), nil } -// readOriginBlock reads one origin block: scheme record, host record, port marker. -// Returns the parsed endpoint and the byte offset immediately after the block. func readOriginBlock(data []byte, pos int) (originEndpoint, int, error) { var ep originEndpoint var err error @@ -208,8 +186,6 @@ func readOriginString(data []byte, pos int) (string, int, error) { } } -// decodeLatin1 converts ISO-8859-1 bytes to a valid UTF-8 Go string. Latin-1 byte values map -// 1:1 to Unicode code points U+0000–U+00FF. Mirrors the helper in chromium/extract_storage.go. func decodeLatin1(b []byte) string { runes := make([]rune, len(b)) for i, c := range b { @@ -232,8 +208,8 @@ type localStorageItem struct { } func readLocalStorageFile(path string) ([]localStorageItem, error) { - // mode=ro without immutable, so SQLite replays the copied -wal sidecar and surfaces entries Safari has not yet - // checkpointed. ORDER BY key, rowid makes exports byte-for-byte stable across runs and SQLite versions. + // mode=ro without immutable lets SQLite replay the copied -wal, so entries Safari has not checkpointed appear. + // ORDER BY key, rowid keeps exports stable across runs and SQLite versions. dsn := "file:" + path + "?mode=ro" db, err := sql.Open("sqlite", dsn) if err != nil { @@ -259,9 +235,7 @@ func readLocalStorageFile(path string) ([]localStorageItem, error) { continue } if !key.Valid { - // NULL keys would collide with legitimate empty-string keys in the output and are - // not meaningful localStorage entries. The UNIQUE constraint in ItemTable still - // permits multiple NULL rows in SQLite, so we filter them here. + // NULL keys would collide with empty-string keys in the output, and ItemTable's UNIQUE still allows several. log.Debugf("safari localstorage: skip row with NULL key in %s", path) continue } @@ -273,8 +247,7 @@ func readLocalStorageFile(path string) ([]localStorageItem, error) { return items, rows.Err() } -// decodeLocalStorageValue treats the BLOB as UTF-16 LE. Values at or above the cap are replaced -// with a size marker to keep JSON/CSV output bounded, matching chromium/extract_storage.go. +// Values at or above the cap become a size marker to bound the output, as in chromium/extract_storage.go. func decodeLocalStorageValue(b []byte) string { if len(b) >= maxLocalStorageValueLength { return fmt.Sprintf( @@ -285,8 +258,7 @@ func decodeLocalStorageValue(b []byte) string { return decodeUTF16LE(b) } -// decodeUTF16LE returns the input as a Go string on odd-length (malformed) inputs; WebKit values -// are always even-length in practice but we don't want a stray byte to drop a whole row. +// An odd-length value comes back as is, so a stray byte does not drop the row. func decodeUTF16LE(b []byte) string { if len(b) == 0 { return "" diff --git a/internal/browser/safari/extract_storage_test.go b/internal/browser/safari/extract_storage_test.go index f3e779d..4d7f0f1 100644 --- a/internal/browser/safari/extract_storage_test.go +++ b/internal/browser/safari/extract_storage_test.go @@ -14,10 +14,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// --------------------------------------------------------------------------- -// readOriginBlock / readOriginFile -// --------------------------------------------------------------------------- - func TestReadOriginBlock_FirstParty(t *testing.T) { data := encodeOriginFile("https://example.com", "https://example.com") top, pos, err := readOriginBlock(data, 0) @@ -40,8 +36,7 @@ func TestReadOriginBlock_NonDefaultPort(t *testing.T) { } func TestReadOriginBlock_Latin1HighByte(t *testing.T) { - // WebKit stores scheme/host records with encoding byte 0x01 = Latin-1. Verify high-byte - // bytes decode as Latin-1 (é = 0xE9) rather than being passed through as invalid UTF-8. + // Scheme and host records are Latin-1 (0x01), so é is 0xE9, not invalid UTF-8 passed through. data := []byte{ 0x04, 0x00, 0x00, 0x00, 0x01, 'h', 't', 't', 'p', // scheme "http" 0x04, 0x00, 0x00, 0x00, 0x01, 'c', 'a', 'f', 0xe9, // host "café" (Latin-1) @@ -71,8 +66,7 @@ func TestReadOriginFile_FramePreferred(t *testing.T) { } func TestReadOriginFile_FallbackToTop(t *testing.T) { - // Write only the top-frame block — no frame follows. Extractor should still succeed by - // falling back to the top-frame origin. + // Only the top-frame block is written; the extractor falls back to it. var buf []byte buf = appendOriginBlock(buf, "https://example.com") originPath := filepath.Join(t.TempDir(), "origin") @@ -91,10 +85,6 @@ func TestReadOriginFile_Malformed(t *testing.T) { require.Error(t, err) } -// --------------------------------------------------------------------------- -// decodeUTF16LE / decodeLocalStorageValue -// --------------------------------------------------------------------------- - func TestDecodeUTF16LE(t *testing.T) { t.Run("ascii", func(t *testing.T) { assert.Equal(t, "hello", decodeUTF16LE(encodeUTF16LE("hello"))) @@ -122,10 +112,6 @@ func TestDecodeLocalStorageValue_Truncates(t *testing.T) { assert.Contains(t, got, "2048") } -// --------------------------------------------------------------------------- -// extractLocalStorage — end-to-end over real nested layout fixtures -// --------------------------------------------------------------------------- - func TestExtractLocalStorage_SingleOrigin(t *testing.T) { root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{ "https://example.com": {{Key: "auth_token", Value: "abc123"}}, @@ -243,8 +229,7 @@ func TestExtractLocalStorage_SkipsSaltAndStrayFiles(t *testing.T) { } func TestExtractLocalStorage_SkipsFrameDirsWithoutDB(t *testing.T) { - // Partition dirs that only have "origin" but no LocalStorage/ subdir must not error out — - // real Safari has plenty of these (cookies-only partitions). + // Partition dirs with only an origin file are common (cookies-only) and must not fail the extraction. root := filepath.Join(t.TempDir(), "Origins") frameDir := filepath.Join(root, "topHash", "frameHash") require.NoError(t, os.MkdirAll(frameDir, 0o755)) @@ -272,10 +257,6 @@ func TestExtractLocalStorage_EmptyRoot(t *testing.T) { assert.Empty(t, entries) } -// --------------------------------------------------------------------------- -// NULL-key handling — readLocalStorageFile skips NULL keys. -// --------------------------------------------------------------------------- - func TestReadLocalStorageFile_SkipsNullKey(t *testing.T) { dbPath := filepath.Join(t.TempDir(), "ls.sqlite3") writeLocalStorageDB(t, dbPath, []testLocalStorageItem{ @@ -290,8 +271,7 @@ func TestReadLocalStorageFile_SkipsNullKey(t *testing.T) { } func TestReadLocalStorageFile_ReturnsRowsInKeyOrder(t *testing.T) { - // Rows are inserted in reverse alphabetical order; ORDER BY key, rowid in the extractor - // query must surface them ascending so exports are deterministic across runs. + // Rows go in reverse order; ORDER BY key, rowid must return them ascending so exports are deterministic. dbPath := filepath.Join(t.TempDir(), "ls.sqlite3") writeLocalStorageDB(t, dbPath, []testLocalStorageItem{ {Key: "zebra", Value: "z"}, diff --git a/internal/browser/safari/profiles.go b/internal/browser/safari/profiles.go index 5827d92..4459887 100644 --- a/internal/browser/safari/profiles.go +++ b/internal/browser/safari/profiles.go @@ -16,8 +16,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// SafariTabs.db lists profiles in bookmarks rows with subtype=2. external_uuid "DefaultProfile" -// is the sentinel for the implicit default, which has no per-UUID directory. +// Profiles are SafariTabs.db bookmarks rows with subtype=2; "DefaultProfile" is the default, which has no UUID dir. const ( safariTabsDBRelPath = containerDir + "/Safari/SafariTabs.db" safariProfileSubtype = 2 @@ -34,15 +33,12 @@ var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a- func namedProfiles(library string) []browser.Profile { named, err := readNamedProfilesFromDB(library) if err != nil { - // Empty DB (nil, nil) is authoritative; fall back only when DB itself is unreadable. named = readNamedProfilesFromDir(library) } return named } -// readNamedProfilesFromDB returns (nil, err) when the DB is missing/unreadable so the caller can -// try the ReadDir fallback; (slice, nil) — possibly empty — is authoritative. -// Discovery reads a snapshot copy, never the live file Safari has open. +// A copy is read, never the live file Safari has open; (nil, err) means unreadable, any slice is authoritative. func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { d, err := snapshot.Temp() if err != nil { @@ -101,7 +97,7 @@ func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { return out, nil } -// readNamedProfilesFromDir is the fallback for missing SafariTabs.db. Names are synthesized from UUIDs. +// Names are synthesized from UUIDs when SafariTabs.db is missing. func readNamedProfilesFromDir(library string) []browser.Profile { entries, err := os.ReadDir(filepath.Join(library, filepath.FromSlash(namedProfilesDir))) if err != nil { @@ -125,7 +121,6 @@ func newNamedProfile(upperUUID, title string) browser.Profile { func isCanonicalUUID(s string) bool { return uuidPattern.MatchString(s) } -// resolveProfileName prefers the SafariTabs.db title, falling back to "profile-". func resolveProfileName(title, upperUUID string) string { if name := sanitizeProfileName(title); name != "" { return name @@ -141,7 +136,6 @@ func sanitizeProfileName(name string) string { return unsafeNameChars.ReplaceAllString(name, "_") } -// disambiguateNames appends "-2", "-3", … to duplicate names, in place. func disambiguateNames(profiles []browser.Profile) { occurrences := make(map[string]int, len(profiles)) for i := range profiles { diff --git a/internal/browser/safari/profiles_test.go b/internal/browser/safari/profiles_test.go index 18d249c..2d3a13d 100644 --- a/internal/browser/safari/profiles_test.go +++ b/internal/browser/safari/profiles_test.go @@ -16,7 +16,6 @@ func testDef() browser.Def { return browser.Def{ID: "safari", Name: "Safari", Base: browser.Safari, Darwin: p, Linux: p, Windows: p} } -// libraryAt lays out a fake home: ~/Library/Safari with a History.db, and the container beside it. func libraryAt(t *testing.T, home string) (container string) { t.Helper() mkFile(t, home, "Library", "Safari", "History.db") @@ -118,8 +117,7 @@ func TestDiscover_EmptyDBIsAuthoritative(t *testing.T) { assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home)) } -// Without SafariTabs.db the Profiles directory is listed and names are synthesized; directories without data are kept, -// because whether a category's file exists is the plan's question. +// Without SafariTabs.db the Profiles dir is listed; dirs without data stay, since a file's presence is Plan's question. func TestDiscover_MissingDBFallsBackToReadDir(t *testing.T) { const uuid = "11111111-2222-3333-4444-555555555555" const empty = "4E2D8DD0-A7D2-4684-939A-898B7675C700" diff --git a/internal/browser/safari/safari.go b/internal/browser/safari/safari.go index 6fc0aa0..e91bce2 100644 --- a/internal/browser/safari/safari.go +++ b/internal/browser/safari/safari.go @@ -1,5 +1,4 @@ -// Package safari is the Safari base: where Safari keeps its default and named profiles under ~/Library, how their -// files are parsed, and the login keychain its passwords come from. +// Package safari is the Safari base: default and named profiles under ~/Library, their files, and the login keychain. package safari import ( @@ -35,8 +34,7 @@ type LoginKeychain interface { InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) } -// Discover finds Safari's data under ~/Library: the default profile, whose Dir is the Safari directory, and the named -// profiles SafariTabs.db lists. -p names another Safari directory, whose parent stands in for ~/Library. +// The default profile's Dir is the Safari directory; -p names another one, whose parent stands in for ~/Library. func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { var errs []error var dirs []browser.UserDataDir @@ -73,9 +71,8 @@ func dirID(def browser.Def, i int) browser.DirID { return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) } -// Extractors maps the categories a Safari profile supports to their extractors. A named profile's files sit under -// two directories named for its UUID, so its sources are built from Profile.Dir; the keychain, Bookmarks.plist, and -// the extension plists carry no profile tag, so only the default profile reads them. +// A named profile's files sit under two directories named for its UUID, so its sources are built from Profile.Dir. +// The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them. func Extractors(dir browser.UserDataDir, p browser.Profile, kc LoginKeychain) browser.Extractors { library := func(rel string) string { return fromLibrary(p, rel) } uuid, named := profileUUID(p) @@ -143,8 +140,7 @@ func plain(src browser.Source, parse func(string, browser.Collector) error) brow } } -// passwordsFrom reads no file, so the extraction always runs; the keychain stays locked without a usable password and -// yields metadata only. +// It reads no file, so it always runs; without a usable password the keychain stays locked and yields metadata only. func passwordsFrom(kc LoginKeychain) func(context.Context, browser.ProfileSnapshot, browser.Collector) error { return func(ctx context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { if kc == nil { @@ -154,8 +150,6 @@ func passwordsFrom(kc LoginKeychain) func(context.Context, browser.ProfileSnapsh } } -// downloadsOf keeps the entries of one profile: Downloads.plist is shared, and each entry names the profile it -// belongs to. func downloadsOf(owner string) func(string, browser.Collector) error { return func(path string, out browser.Collector) error { return extractDownloads(path, owner, out) } } diff --git a/internal/browser/safari/safari_test.go b/internal/browser/safari/safari_test.go index 0a04206..e53b7c4 100644 --- a/internal/browser/safari/safari_test.go +++ b/internal/browser/safari/safari_test.go @@ -28,7 +28,6 @@ var ( libraryDir = browser.UserDataDir{Def: testDef(), Profiles: []browser.Profile{defaultProfile, workProfile}} ) -// sourcePaths is where each category's candidates land under ~/Library once joined with the profile's Dir. func sourcePaths(p browser.Profile, ex browser.Extractors) map[category.Category][]string { got := make(map[category.Category][]string, len(ex)) for c, e := range ex { @@ -70,7 +69,6 @@ func TestExtractors_NamedProfileSources(t *testing.T) { }, sourcePaths(workProfile, Extractors(libraryDir, workProfile, nil))) } -// snapshotOf lays fixture files out as the Safari user data dir's snapshot, keyed by their path under ~/Library. func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { t.Helper() root := t.TempDir() diff --git a/internal/browser/safari/testutil_test.go b/internal/browser/safari/testutil_test.go index 043b5bb..2c23745 100644 --- a/internal/browser/safari/testutil_test.go +++ b/internal/browser/safari/testutil_test.go @@ -17,9 +17,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// --------------------------------------------------------------------------- -// Real Safari table schemas — extracted via `sqlite3 History.db ".schema"`. -// --------------------------------------------------------------------------- +// Real Safari schemas from sqlite3 History.db .schema, so the queries are tested against the columns Safari has. const safariHistoryItemsSchema = `CREATE TABLE history_items ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -49,10 +47,6 @@ const safariHistoryVisitsSchema = `CREATE TABLE history_visits ( score INTEGER NOT NULL DEFAULT 0 )` -// --------------------------------------------------------------------------- -// INSERT helpers -// --------------------------------------------------------------------------- - func insertHistoryItem(id int, url, domainExpansion string, visitCount int) string { return fmt.Sprintf( `INSERT INTO history_items (id, url, domain_expansion, visit_count) @@ -69,10 +63,6 @@ func insertHistoryVisit(id, historyItem int, visitTime float64, title string) st ) } -// --------------------------------------------------------------------------- -// Test fixture builders -// --------------------------------------------------------------------------- - func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { //nolint:unparam // name will vary when future data types are added t.Helper() path := filepath.Join(t.TempDir(), name) @@ -91,19 +81,12 @@ func createTestDB(t *testing.T, name string, schemas []string, inserts ...string return path } -// --------------------------------------------------------------------------- -// SafariTabs.db fixtures -// --------------------------------------------------------------------------- - -// tabRow describes one profile entry to stamp into the fake SafariTabs.db. type tabRow struct { uuid string title string } -// writeSafariTabsDB creates a minimal SafariTabs.db at path containing only -// the bookmarks columns discoverSafariProfiles reads. Every row gets -// subtype=2 (profile record) so the production query picks it up. +// Every row gets subtype=2, the profile record the production query selects. func writeSafariTabsDB(t *testing.T, path string, rows []tabRow) { t.Helper() require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) @@ -126,20 +109,12 @@ func writeSafariTabsDB(t *testing.T, path string, rows []tabRow) { } } -// --------------------------------------------------------------------------- -// LocalStorage fixtures — modern WebKit nested Origins layout -// --------------------------------------------------------------------------- - -// testLocalStorageItem is one key/value pair written to an ItemTable row. -// Value is encoded as UTF-16 LE, matching WebKit's on-disk format. +// Value is written as UTF-16 LE, as WebKit stores it. type testLocalStorageItem struct { Key, Value string } -// buildTestLocalStorageDir creates a root dir that mirrors Safari 17+'s nested -// localStorage layout (/

/

/origin + LocalStorage/localstorage.sqlite3) -// for each origin URL passed in. Origins are written as first-party (top == frame); -// for partitioned-origin coverage, use buildTestPartitionedLocalStorage. +// Every origin is written first-party, with top == frame. func buildTestLocalStorageDir(t *testing.T, origins map[string][]testLocalStorageItem) string { t.Helper() root := filepath.Join(t.TempDir(), "Origins") @@ -154,8 +129,6 @@ func buildTestLocalStorageDir(t *testing.T, origins map[string][]testLocalStorag return root } -// writeTestOriginStore writes one /// tree with the given -// origins encoded into the binary origin file and items inserted into localstorage.sqlite3. func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, frameOrigin string, items []testLocalStorageItem) { t.Helper() frameDir := filepath.Join(root, topHash, frameHash) @@ -182,10 +155,7 @@ func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, fra require.NoError(t, db.Close()) } -// encodeOriginFile mirrors WebKit's SecurityOrigin binary serialization. Layout per origin -// block: length-prefixed scheme record, length-prefixed host record, then a port marker -// (0x00 for the scheme default, or 0x01 + uint16_le port). Two blocks back-to-back: top-frame -// then frame. +// WebKit's SecurityOrigin layout: per block a scheme record, a host record, and a port marker; top, then frame. func encodeOriginFile(topOrigin, frameOrigin string) []byte { var buf []byte buf = appendOriginBlock(buf, topOrigin) @@ -215,8 +185,7 @@ func appendOriginRecord(buf []byte, s string) []byte { return append(buf, []byte(s)...) } -// splitTestOriginURL parses "https://example.com[:port]" into (scheme, host, port). -// Port 0 means the URL had no explicit port (use scheme default). +// Port 0 means the URL had no explicit port. func splitTestOriginURL(u string) (scheme, host string, port uint16) { idx := strings.Index(u, "://") if idx < 0 { @@ -232,11 +201,7 @@ func splitTestOriginURL(u string) (scheme, host string, port uint16) { return scheme, rest, 0 } -// writeLocalStorageDB creates a minimal localstorage.sqlite3 at path with ItemTable populated -// from items. When addNullKey is true, a NULL-key row is inserted first to exercise the -// skip-NULL-key logic in readLocalStorageFile / countLocalStorageFile. This is a direct-DB -// variant of buildTestLocalStorageDir — use it when the test targets one DB, not the full -// Origins nesting. +// addNullKey inserts a NULL-key row first, to exercise the reader's skip of NULL keys. func writeLocalStorageDB(t *testing.T, path string, items []testLocalStorageItem, addNullKey bool) { t.Helper() db, err := sql.Open("sqlite", path) @@ -260,8 +225,6 @@ func writeLocalStorageDB(t *testing.T, path string, items []testLocalStorageItem require.NoError(t, db.Close()) } -// encodeUTF16LE is the inverse of extract_storage.go's decodeUTF16LE — it mirrors -// the WebKit encoding so test fixtures round-trip through the extractor. func encodeUTF16LE(s string) []byte { u16 := utf16.Encode([]rune(s)) buf := make([]byte, 2*len(u16)) @@ -278,7 +241,6 @@ func mkFile(t *testing.T, parts ...string) { require.NoError(t, os.WriteFile(path, []byte("test"), 0o644)) } -// testCollector keeps what an extractor hands it, in order. type testCollector struct { records []record.Record fails []error diff --git a/internal/browser/userdatadir.go b/internal/browser/userdatadir.go index efee204..a2f8cf6 100644 --- a/internal/browser/userdatadir.go +++ b/internal/browser/userdatadir.go @@ -6,8 +6,7 @@ type DiscoverOptions struct { ProfilePath string // the -p value; "" when not given } -// DirID names one user data dir: Def.ID for the first one of a Def, then "-2", "-3"… in Path order. Its own type -// keeps it from being passed where a Def.ID belongs: the two are equal on a machine with one Arc. +// DirID is Def.ID, then "-2", "-3"... in Path order; its own type keeps it apart from a Def.ID, which it often equals. type DirID string // UserDataDir is one browser data directory found on this machine; ID also names its snapshot and archive directory. diff --git a/internal/crypto/asn1pbe.go b/internal/crypto/asn1pbe.go index 51fc4de..54ef152 100644 --- a/internal/crypto/asn1pbe.go +++ b/internal/crypto/asn1pbe.go @@ -11,10 +11,7 @@ import ( const des3KeySize = 24 // 3DES uses 24-byte (192-bit) keys -// ASN1PBE represents a Password-Based Encryption structure from Firefox's NSS. -// The key parameter semantics vary by implementation: -// - privateKeyPBE / passwordCheckPBE: key is the global salt used for key derivation -// - credentialPBE: key is the already-derived master key +// The key is the global salt for privateKeyPBE and passwordCheckPBE, and the derived master key for credentialPBE. type ASN1PBE interface { Decrypt(key []byte) ([]byte, error) Encrypt(key, plaintext []byte) ([]byte, error) @@ -38,14 +35,6 @@ func NewASN1PBE(b []byte) (pbe ASN1PBE, err error) { return nil, errDecodeASN1 } -// privateKeyPBE Struct -// -// SEQUENCE (2 elem) -// OBJECT IDENTIFIER -// SEQUENCE (2 elem) -// OCTET STRING (20 byte) -// INTEGER 1 -// OCTET STRING (16 byte) type privateKeyPBE struct { AlgoAttr struct { asn1.ObjectIdentifier @@ -67,18 +56,7 @@ func (n privateKeyPBE) Encrypt(globalSalt, plaintext []byte) ([]byte, error) { return DES3Encrypt(key, iv, plaintext) } -// deriveKeyAndIV implements NSS PBE-SHA1-3DES key derivation. // Reference: https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/lowpbe.c -// -// Derivation steps: -// -// hp = SHA1(globalSalt) -// ck = SHA1(hp || entrySalt) -// hmac1 = HMAC-SHA1(ck, paddedSalt) -// k1 = HMAC-SHA1(ck, paddedSalt || entrySalt) -// k2 = HMAC-SHA1(ck, hmac1 || entrySalt) -// dk = k1 || k2 (40 bytes) -// key = dk[:24], iv = dk[32:] func (n privateKeyPBE) deriveKeyAndIV(globalSalt []byte) ([]byte, []byte) { entrySalt := n.AlgoAttr.SaltAttr.EntrySalt hp := sha1.Sum(globalSalt) @@ -98,23 +76,6 @@ func (n privateKeyPBE) deriveKeyAndIV(globalSalt []byte) ([]byte, []byte) { return dk[:24], dk[len(dk)-8:] } -// passwordCheckPBE Struct -// -// SEQUENCE (2 elem) -// OBJECT IDENTIFIER -// SEQUENCE (2 elem) -// SEQUENCE (2 elem) -// OBJECT IDENTIFIER -// SEQUENCE (4 elem) -// OCTET STRING (32 byte) -// INTEGER 1 -// INTEGER 32 -// SEQUENCE (1 elem) -// OBJECT IDENTIFIER -// SEQUENCE (2 elem) -// OBJECT IDENTIFIER -// OCTET STRING (14 byte) -// OCTET STRING (16 byte) type passwordCheckPBE struct { AlgoAttr algoAttr Encrypted []byte @@ -167,13 +128,6 @@ func (m passwordCheckPBE) deriveKeyAndIV(globalSalt []byte) ([]byte, []byte) { return key, iv } -// credentialPBE Struct -// -// OCTET STRING (16 byte) -// SEQUENCE (2 elem) -// OBJECT IDENTIFIER -// OCTET STRING (8 byte) -// OCTET STRING (16 byte) type credentialPBE struct { KeyCheck []byte Algo struct { diff --git a/internal/crypto/asn1pbe_test.go b/internal/crypto/asn1pbe_test.go index eabf3b5..bbd4e9a 100644 --- a/internal/crypto/asn1pbe_test.go +++ b/internal/crypto/asn1pbe_test.go @@ -303,12 +303,10 @@ func TestNewASN1PBE_InvalidData(t *testing.T) { } func TestCredentialPBE_AES256CBC(t *testing.T) { - // Test the Firefox 144+ AES-256-CBC path (IV length = 16). - // Construct a credentialPBE with a 16-byte IV to exercise the AES branch. - masterKey := bytes.Repeat([]byte("k"), 32) // AES-256 key - iv := bytes.Repeat([]byte{0x01}, 16) // 16-byte IV → AES-CBC path + // Firefox 144+ path: a 16-byte IV selects AES-256-CBC. + masterKey := bytes.Repeat([]byte("k"), 32) + iv := bytes.Repeat([]byte{0x01}, 16) - // Encrypt plaintext to get valid ciphertext for round-trip test. encrypted, err := AESCBCEncrypt(masterKey, iv, pbePlaintext) require.NoError(t, err) @@ -328,7 +326,6 @@ func TestCredentialPBE_AES256CBC(t *testing.T) { require.NoError(t, err) assert.Equal(t, pbePlaintext, decrypted) - // Verify encrypt round-trip reEncrypted, err := pbe.Encrypt(masterKey, pbePlaintext) require.NoError(t, err) assert.Equal(t, encrypted, reEncrypted) diff --git a/internal/crypto/blob_test.go b/internal/crypto/blob_test.go index f7584fc..0997f16 100644 --- a/internal/crypto/blob_test.go +++ b/internal/crypto/blob_test.go @@ -8,7 +8,6 @@ import ( "testing" ) -// encryptAESGCM is a test helper that produces a GCM ciphertext with caller-supplied AAD. func encryptAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { t.Helper() block, err := aes.NewCipher(key) diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index 9f74917..5b0a2c7 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -7,8 +7,6 @@ import ( "fmt" ) -// AESCBCEncrypt encrypts data using AES-CBC mode with PKCS5 padding. -// Supports all AES key sizes: 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256). func AESCBCEncrypt(key, iv, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { @@ -17,8 +15,6 @@ func AESCBCEncrypt(key, iv, plaintext []byte) ([]byte, error) { return cbcEncrypt(block, iv, plaintext) } -// AESCBCDecrypt decrypts data using AES-CBC mode with PKCS5 unpadding. -// Supports all AES key sizes: 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256). func AESCBCDecrypt(key, iv, ciphertext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { @@ -27,7 +23,6 @@ func AESCBCDecrypt(key, iv, ciphertext []byte) ([]byte, error) { return cbcDecrypt(block, iv, ciphertext) } -// DES3Encrypt encrypts data using 3DES-CBC mode with PKCS5 padding. func DES3Encrypt(key, iv, plaintext []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(key) if err != nil { @@ -36,7 +31,6 @@ func DES3Encrypt(key, iv, plaintext []byte) ([]byte, error) { return cbcEncrypt(block, iv, plaintext) } -// DES3Decrypt decrypts data using 3DES-CBC mode with PKCS5 unpadding. func DES3Decrypt(key, iv, ciphertext []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(key) if err != nil { @@ -47,7 +41,6 @@ func DES3Decrypt(key, iv, ciphertext []byte) ([]byte, error) { const gcmNonceSize = 12 -// AESGCMEncrypt encrypts data using AES-GCM mode. func AESGCMEncrypt(key, nonce, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { @@ -63,7 +56,6 @@ func AESGCMEncrypt(key, nonce, plaintext []byte) ([]byte, error) { return aead.Seal(nil, nonce, plaintext, nil), nil } -// AESGCMDecrypt decrypts data using AES-GCM mode. func AESGCMDecrypt(key, nonce, ciphertext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { @@ -79,8 +71,7 @@ func AESGCMDecrypt(key, nonce, ciphertext []byte) ([]byte, error) { return aead.Open(nil, nonce, ciphertext, nil) } -// AESGCMDecryptBlob decrypts a blob shaped as [12B nonce][ciphertext+16B GCM tag] with caller-supplied AAD. -// Used by protocols that wrap AES-GCM output with a fixed-length nonce prefix (Yandex passwords/cards). +// blob is [12-byte nonce][ciphertext + 16-byte tag], as Yandex stores it. func AESGCMDecryptBlob(key, blob, aad []byte) ([]byte, error) { if len(blob) < gcmNonceSize { return nil, errShortCiphertext @@ -139,8 +130,7 @@ func paddingZero(src []byte, length int) []byte { return dst } -// pkcs5Padding adds PKCS5/PKCS7 padding to src. -// Always returns a new slice; never modifies src. +// pkcs5Padding always returns a new slice and never modifies src. func pkcs5Padding(src []byte, blockSize int) []byte { n := blockSize - (len(src) % blockSize) dst := make([]byte, len(src)+n) diff --git a/internal/crypto/crypto_test.go b/internal/crypto/crypto_test.go index 249d446..c520689 100644 --- a/internal/crypto/crypto_test.go +++ b/internal/crypto/crypto_test.go @@ -72,12 +72,7 @@ func TestAESGCMDecrypt(t *testing.T) { assert.Equal(t, plainText, decrypted) } -// --- Bug-fix verification tests --- -// These tests verify the fixes for known issues in the crypto primitives. -// Tests marked with t.Skip document bugs that exist before the fix. - func TestPkcs5Padding_NoMutation(t *testing.T) { - // pkcs5Padding should not mutate the original slice's backing array. src := make([]byte, 3, 32) // len=3, cap=32 — append won't allocate copy(src, "abc") backup := make([]byte, cap(src)) @@ -85,7 +80,7 @@ func TestPkcs5Padding_NoMutation(t *testing.T) { padded := pkcs5Padding(src, 16) assert.Len(t, padded, 16) - assert.Equal(t, []byte("abc"), src) // original length unchanged + assert.Equal(t, []byte("abc"), src) // The bytes beyond len(src) in the original backing array must not be touched. current := make([]byte, cap(src)) diff --git a/internal/crypto/errors.go b/internal/crypto/errors.go index 50bdbc0..b0d5a9b 100644 --- a/internal/crypto/errors.go +++ b/internal/crypto/errors.go @@ -2,7 +2,6 @@ package crypto import "errors" -// Sentinel errors for crypto operations. var ( errShortCiphertext = errors.New("ciphertext too short") errInvalidBlockSize = errors.New("ciphertext is not a multiple of the block size") diff --git a/internal/crypto/pbkdf2.go b/internal/crypto/pbkdf2.go index 8882b19..27dc291 100644 --- a/internal/crypto/pbkdf2.go +++ b/internal/crypto/pbkdf2.go @@ -5,23 +5,7 @@ import ( "hash" ) -// PBKDF2Key derives a key from the password, salt and iteration count, returning a -// []byte of length keylen that can be used as cryptographic key. The key is -// derived based on the method described as PBKDF2 with the HMAC variant using -// the supplied hash function. -// -// For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you -// can get a derived key for e.g. AES-256 (which needs a 32-byte key) by -// doing: -// -// dk := PBKDF2Key([]byte("some password"), salt, 4096, 32, sha1.New) -// -// Remember to get a good random salt. At least 8 bytes is recommended by the -// RFC. -// -// Using a higher iteration count will increase the cost of an exhaustive -// search but will also make derivation proportionally slower. -// Copy from https://golang.org/x/crypto/pbkdf2 +// Copied from golang.org/x/crypto/pbkdf2. func PBKDF2Key(password, salt []byte, iterations, keyLen int, h func() hash.Hash) []byte { prf := hmac.New(h, password) hashLen := prf.Size() @@ -31,9 +15,6 @@ func PBKDF2Key(password, salt []byte, iterations, keyLen int, h func() hash.Hash dk := make([]byte, 0, numBlocks*hashLen) u := make([]byte, hashLen) for block := 1; block <= numBlocks; block++ { - // N.B.: || means concatenation, ^ means XOR - // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter - // U_1 = PRF(password, salt || uint(i)) prf.Reset() prf.Write(salt) buf[0] = byte(block >> 24) diff --git a/internal/export/csv.go b/internal/export/csv.go index fea432a..3b06355 100644 --- a/internal/export/csv.go +++ b/internal/export/csv.go @@ -8,7 +8,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// utf8BOM is written at the start of CSV files for Excel compatibility. +// Excel reads a CSV file as UTF-8 only when it starts with a BOM. var utf8BOM = []byte{0xEF, 0xBB, 0xBF} type csvEncoder struct { diff --git a/internal/export/order.go b/internal/export/order.go index e05c5c7..4b02301 100644 --- a/internal/export/order.go +++ b/internal/export/order.go @@ -7,7 +7,7 @@ import ( "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. +// Stable, so ties and keyless records keep source order: Safari's bookmarks and downloads have no timestamp. func sortRecords(records []record.Record) { sort.SliceStable(records, func(i, j int) bool { return keyOf(records[i]).before(keyOf(records[j])) diff --git a/internal/export/reflect.go b/internal/export/reflect.go index 4e4b2ff..e12469e 100644 --- a/internal/export/reflect.go +++ b/internal/export/reflect.go @@ -10,7 +10,6 @@ import ( var timeType = reflect.TypeOf(time.Time{}) -// structCSVHeader extracts CSV column names from a struct's csv tags. func structCSVHeader(v any) []string { t := reflect.Indirect(reflect.ValueOf(v)).Type() headers := make([]string, 0, t.NumField()) @@ -24,8 +23,6 @@ func structCSVHeader(v any) []string { return headers } -// 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.Indirect(reflect.ValueOf(v)) t := val.Type() @@ -39,9 +36,6 @@ func structCSVRow(v any) []string { return row } -// tagName extracts the tag value for the given key from a struct field. -// Uses Lookup (not Get) to distinguish "no tag" from "empty tag". -// Returns "" if the tag is absent, empty, or "-". func tagName(f reflect.StructField, key string) string { tag, ok := f.Tag.Lookup(key) if !ok || tag == "-" { @@ -57,7 +51,6 @@ func tagName(f reflect.StructField, key string) string { } func fieldToString(v reflect.Value) string { - // Check time.Time before kind switch since it's a struct. if v.Type() == timeType { t, _ := v.Interface().(time.Time) return formatTime(t) diff --git a/internal/export/reflect_test.go b/internal/export/reflect_test.go index 7a63a81..520bae4 100644 --- a/internal/export/reflect_test.go +++ b/internal/export/reflect_test.go @@ -12,7 +12,7 @@ import ( 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. +// allRecordTypes must list every record type, or a new one escapes these checks. var allRecordTypes = []record.Record{ &record.Login{}, &record.Cookie{}, diff --git a/internal/export/writer.go b/internal/export/writer.go index 6431e1b..9c2b893 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -83,7 +83,7 @@ func (w *Writer) write(c category.Category, records []record.Record) error { return nil } -// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them in Output. +// Close completes the files even after a failed Write, so they keep what was written; only a clean run fills Output. func (w *Writer) Close() error { var ( errs []error @@ -138,7 +138,7 @@ func (w *Writer) pack() error { return nil } -// writeZip writes the zip under a temp name beside dst and renames it into place once it is complete. +// writeZip renames a finished temp file into place, so dst is never a partial zip. func writeZip(dst, dir string, names []string) (err error) { tmp, err := os.OpenFile(dst+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { diff --git a/internal/export/writer_test.go b/internal/export/writer_test.go index 8882d4e..d20884e 100644 --- a/internal/export/writer_test.go +++ b/internal/export/writer_test.go @@ -71,8 +71,6 @@ func writeAll(t *testing.T, dir string, f Format, extractions ...extraction) { require.NoError(t, w.Close()) } -// --- Format --- - func TestParseFormat(t *testing.T) { tests := []struct { in string @@ -103,8 +101,6 @@ func TestNewWriter_CreatesDir(t *testing.T) { assert.DirExists(t, dir) } -// --- CSV output --- - func TestWrite_CSV_Password(t *testing.T) { dir := t.TempDir() writeAll(t, dir, CSV, append(chromeExtractions(), firefoxExtractions()...)...) @@ -162,8 +158,6 @@ func TestWrite_CSV_UTF8BOM(t *testing.T) { 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() writeAll(t, dir, JSON, append(chromeExtractions(), firefoxExtractions()...)...) @@ -231,8 +225,6 @@ func TestWrite_JSON_NoBOM(t *testing.T) { } } -// --- CookieEditor output --- - func TestWrite_CookieEditor(t *testing.T) { dir := t.TempDir() writeAll(t, dir, CookieEditor, chromeExtractions()...) @@ -256,13 +248,10 @@ func TestWrite_CookieEditor_FallbackJSON(t *testing.T) { dir := t.TempDir() 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")) assert.False(t, os.IsNotExist(err), "password.json should be created via JSON fallback") } -// --- File creation --- - func TestWrite_EmptyCategoryNoFile(t *testing.T) { dir := t.TempDir() writeAll(t, dir, CSV, @@ -286,8 +275,6 @@ func TestWrite_NoData(t *testing.T) { 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} @@ -302,8 +289,6 @@ func TestWrite_AppendsExtractionsInWriteOrder(t *testing.T) { 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, false) @@ -316,7 +301,6 @@ func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { 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, false) @@ -351,8 +335,6 @@ func TestClose_OutputListsTheFilesInCategoryOrder(t *testing.T) { assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, w.Output()) } -// --- --zip --- - func TestClose_ZipReplacesTheFilesWithOneArchive(t *testing.T) { loose := filepath.Join(t.TempDir(), "results") writeAll(t, loose, CSV, chromeExtractions()...) @@ -413,8 +395,6 @@ func TestClose_ZipWithNothingWrittenFails(t *testing.T) { assert.Empty(t, dirNames(t, dir)) } -// --- helpers --- - func zipAll(dir string, extractions ...extraction) error { w, err := NewWriter(dir, CSV, true) if err != nil { @@ -470,7 +450,6 @@ func readCSV(t *testing.T, path string) [][]string { t.Helper() raw, err := os.ReadFile(path) require.NoError(t, err) - // Skip UTF-8 BOM if present content := string(raw) if strings.HasPrefix(content, string(utf8BOM)) { content = content[len(utf8BOM):] diff --git a/internal/golden/golden.go b/internal/golden/golden.go index 56f2c63..9159e85 100644 --- a/internal/golden/golden.go +++ b/internal/golden/golden.go @@ -1,4 +1,4 @@ -// Package golden compares test output against files in the calling package's testdata/, which HBD_UPDATE_GOLDEN=1 rewrites. +// Package golden compares test output with files in the calling package's testdata/; HBD_UPDATE_GOLDEN=1 rewrites them. package golden import ( @@ -14,13 +14,11 @@ import ( "github.com/stretchr/testify/require" ) -// updateEnv is an environment variable, not a test flag: go test ./... passes a flag to packages that do not define it, -// and reading the variable at test time keys go test's cache on it. +// An env var, not a test flag, reaches every package of go test ./... and, read at test time, keys its cache. const updateEnv = "HBD_UPDATE_GOLDEN" const dir = "testdata" -// Assert compares got with testdata/, rewriting it first when HBD_UPDATE_GOLDEN=1. func Assert(t testing.TB, name, got string) { t.Helper() path := filepath.Join(dir, name) @@ -33,7 +31,6 @@ func Assert(t testing.TB, name, got string) { assert.Equal(t, string(want), got, "regenerate with: %s=1 go test ./... -run '%s'", updateEnv, t.Name()) } -// Read returns testdata/. func Read(t testing.TB, name string) string { t.Helper() data, err := os.ReadFile(filepath.Join(dir, name)) @@ -41,7 +38,6 @@ func Read(t testing.TB, name string) string { return string(data) } -// Bundle renders every regular file in dir as a named, length-tagged block, in directory order. func Bundle(t testing.TB, dir string) string { t.Helper() entries, err := os.ReadDir(dir) @@ -54,7 +50,6 @@ func Bundle(t testing.TB, dir string) string { return BundleFiles(t, dir, names...) } -// BundleFiles renders the named files under dir as named, length-tagged blocks, in the given order. func BundleFiles(t testing.TB, dir string, names ...string) string { t.Helper() var b strings.Builder @@ -70,7 +65,6 @@ func BundleFiles(t testing.TB, dir string, names ...string) string { return b.String() } -// DirFiles maps each file name under dir to its contents. func DirFiles(t testing.TB, dir string) map[string]string { t.Helper() entries, err := os.ReadDir(dir) @@ -84,8 +78,7 @@ func DirFiles(t testing.TB, dir string) map[string]string { return files } -// AssertJSONFallback checks that Cookie-Editor output matches the json output for every category but cookies, whose -// own format Cookie-Editor alone writes. +// Cookie-Editor writes its own format for cookies only, so every other file must match the json output. func AssertJSONFallback(t testing.TB, cookieEditorDir, jsonDir string) { t.Helper() got, want := DirFiles(t, cookieEditorDir), DirFiles(t, jsonDir) @@ -95,7 +88,6 @@ func AssertJSONFallback(t testing.TB, cookieEditorDir, jsonDir string) { assert.Equal(t, want, got) } -// ZipListing renders a zip's entries as one deterministic line each: name, method, modified time, size, and CRC. func ZipListing(t testing.TB, path string) string { t.Helper() r, err := zip.OpenReader(path) diff --git a/internal/log/level.go b/internal/log/level.go index 740e679..d254721 100644 --- a/internal/log/level.go +++ b/internal/log/level.go @@ -1,18 +1,12 @@ package log -// Level defines all the available levels we can log at. type Level int32 const ( - // DebugLevel is the lowest level of logging. - // Debug logs are intended for debugging and development purposes. DebugLevel Level = iota + 1 - // InfoLevel is used for user-facing progress and status messages. InfoLevel - // WarnLevel is used for undesired but relatively expected events, - // which may indicate a problem. WarnLevel ) diff --git a/internal/log/log.go b/internal/log/log.go index 83ec32f..110362b 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -2,10 +2,8 @@ package log import "fmt" -// defaultLogger is the default logger used by the package-level functions. var defaultLogger = NewLogger(nil) -// SetVerbose lowers the package-level logger to DebugLevel. func SetVerbose() { defaultLogger.SetLevel(DebugLevel) } diff --git a/internal/log/log_test.go b/internal/log/log_test.go index c3c859c..9795129 100644 --- a/internal/log/log_test.go +++ b/internal/log/log_test.go @@ -8,7 +8,7 @@ import ( ) func TestSetVerbose(t *testing.T) { - t.Cleanup(func() { defaultLogger.SetLevel(InfoLevel) }) // restore package default + t.Cleanup(func() { defaultLogger.SetLevel(InfoLevel) }) assert.False(t, defaultLogger.canLogAt(DebugLevel), "Debug must be suppressed by default") SetVerbose() diff --git a/internal/log/logger.go b/internal/log/logger.go index d68b4dc..ddef68f 100644 --- a/internal/log/logger.go +++ b/internal/log/logger.go @@ -11,8 +11,6 @@ import ( "sync/atomic" ) -// NewLogger creates and returns a new instance of Logger. -// Default level is InfoLevel (Debug messages are suppressed unless SetVerbose is called). func NewLogger(base Base) *Logger { if base == nil { base = newBase(os.Stderr) @@ -20,22 +18,16 @@ func NewLogger(base Base) *Logger { return &Logger{base: base, minLevel: InfoLevel} } -// Logger logs messages to io.Writer at various log levels. type Logger struct { base Base - // Minimum log level for this logger. - // Messages with level lower than this won't be outputted. minLevel Level } -// canLogAt reports whether logger can log at level v. func (l *Logger) canLogAt(v Level) bool { return v >= Level(atomic.LoadInt32((*int32)(&l.minLevel))) } -// SetLevel sets the logger level. -// It panics if v is less than DebugLevel or greater than WarnLevel. func (l *Logger) SetLevel(v Level) { if v < DebugLevel || v > WarnLevel { panic("log: invalid log level") @@ -43,13 +35,9 @@ func (l *Logger) SetLevel(v Level) { atomic.StoreInt32((*int32)(&l.minLevel), int32(v)) } -// baseCallerSkip is the number of frames to skip in runtime.Caller to reach -// the actual call site. Both package-level functions (log.Xxx -> logMsg -> base.Log) -// and Logger methods (Logger.Xxx -> logMsg -> base.Log) add exactly one frame -// above logMsg, so the skip is the same: base.Log(0) -> logMsg(1) -> caller_wrapper(2) -> caller(3). +// Frames between runtime.Caller and the caller: base.Log, logMsg, and the exported Debugf/Infof/Warnf. const baseCallerSkip = 3 -// logMsg is the internal method all public methods delegate to. func (l *Logger) logMsg(lvl Level, msg string) { if !l.canLogAt(lvl) { return @@ -69,18 +57,10 @@ func (l *Logger) Warnf(format string, args ...any) { l.logMsg(WarnLevel, fmt.Sprintf(format, args...)) } -// Base is the interface that underlies the Logger. It receives the caller -// skip count, log level, and formatted message. type Base interface { Log(callerSkip int, lvl Level, msg string) } -// baseLogger writes formatted log messages to an io.Writer. -// Output format: -// -// [DBG] file.go:42: message -// [INF] message -// [WRN] message type baseLogger struct { out io.Writer mu sync.Mutex @@ -90,8 +70,7 @@ func newBase(out io.Writer) *baseLogger { return &baseLogger{out: out} } -// continuation is the indent for multi-line messages. -// Width matches "[DBG] " (6 chars). +// continuation lines a message's later lines up under its first, past the "[DBG] " label. const continuation = " " func (l *baseLogger) Log(callerSkip int, lvl Level, msg string) { @@ -120,7 +99,6 @@ func (l *baseLogger) Log(callerSkip int, lvl Level, msg string) { l.mu.Unlock() } -// formatLabel returns the bracketed level label, e.g. "[DBG]". func (l *baseLogger) formatLabel(lvl Level) string { return "[" + lvl.String() + "]" } diff --git a/internal/log/logger_test.go b/internal/log/logger_test.go index 8951d15..64127ab 100644 --- a/internal/log/logger_test.go +++ b/internal/log/logger_test.go @@ -188,11 +188,9 @@ func TestDefaultLevelIsInfo(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) - // Debug should be suppressed at default level (InfoLevel). logger.Debugf("debug msg") assert.Empty(t, buf.String(), "Debug should be suppressed at default InfoLevel") - // Info should be visible at default level. logger.Infof("info msg") assert.Contains(t, buf.String(), "info msg") } diff --git a/internal/masterkey/dump.go b/internal/masterkey/dump.go index 0f3796a..7ba2f7d 100644 --- a/internal/masterkey/dump.go +++ b/internal/masterkey/dump.go @@ -12,8 +12,7 @@ import ( const DumpVersion = "2" -// Dump is the portable, cross-host container for Chromium master keys — produce it on one host to -// decrypt copied profile data on another without DPAPI / ABE / Keychain / D-Bus. +// Dump is keys.json: produced on one host, it decrypts copied profile data on another. type Dump struct { Version string `json:"version"` CreatedAt time.Time `json:"created_at"` @@ -29,9 +28,7 @@ type Host struct { User string `json:"user,omitempty"` } -// Vault groups profiles sharing master keys (master keys are per-installation, not per-profile). -// Browser is the lookup key (e.g. "chrome"); Kind is the engine ("chromium"|"chromium-yandex"| -// "chromium-opera") so a consumer can rebuild the engine without the local browser table. +// Kind names the engine, so a consumer can read a vault without the browser in its own table. type Vault struct { Browser string `json:"browser"` // ID names a second user data dir of the same browser ("arc-2"); the first one's is Browser, so it is left out. @@ -71,8 +68,7 @@ func (d Dump) WriteJSON(w io.Writer) error { return nil } -// ReadJSON parses a Dump and rejects any version this build can't interpret — a silent misparse of an -// unrecognized schema is worse than a clear error. +// ReadJSON rejects a version it cannot interpret, since a silent misparse is worse than an error. func ReadJSON(r io.Reader) (Dump, error) { var d Dump dec := json.NewDecoder(r) diff --git a/internal/masterkey/gcoredump_darwin.go b/internal/masterkey/gcoredump_darwin.go index d426446..34b86d3 100644 --- a/internal/masterkey/gcoredump_darwin.go +++ b/internal/masterkey/gcoredump_darwin.go @@ -29,8 +29,6 @@ var ( loginKeychainPath = homeDir + "/Library/Keychains/login.keychain-db" ) -// findProcessByName returns the PID of the first process matching name. -// If forceRoot is true, only matches processes owned by root (uid 0). func findProcessByName(name string, forceRoot bool) (int, error) { buf, err := unix.SysctlRaw("kern.proc.all") if err != nil { @@ -60,8 +58,7 @@ type addressRange struct { end uint64 } -// DecryptKeychainRecords dumps securityd memory, scans for the keychain master key, and uses it to -// read login.keychain-db's generic password records. Requires root. +// DecryptKeychainRecords requires root. func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { if os.Geteuid() != 0 { return nil, errors.New("requires root privileges") @@ -82,7 +79,6 @@ func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { return nil, fmt.Errorf("failed to dump securityd memory: %w", err) } - // vmmap identifies MALLOC_SMALL heap regions where securityd stores keys regions, err := findMallocSmallRegions(pid) if err != nil { return nil, fmt.Errorf("failed to find malloc small regions: %w", err) @@ -96,7 +92,6 @@ func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { return nil, fmt.Errorf("no master key candidates found in securityd memory") } - // read keychain file once, reuse buffer for each candidate keychainBuf, err := os.ReadFile(loginKeychainPath) if err != nil { return nil, fmt.Errorf("read keychain: %w", err) @@ -123,14 +118,6 @@ func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { return nil, fmt.Errorf("tried %d candidates, none unlocked keychain", len(candidates)) } -// scanMasterKeyCandidates scans the core dump for 24-byte master key candidates. -// -// securityd stores the master key in a MALLOC_SMALL region with the layout: -// -// [0x18 (8 bytes)] [pointer to key data (8 bytes)] -// -// 0x18 = 24 is the key length. The pointer references a 24-byte buffer -// within the same region containing the raw master key. func scanMasterKeyCandidates(corePath string, regions []addressRange) ([]string, error) { cmf, err := macho.Open(corePath) if err != nil { @@ -146,12 +133,10 @@ func scanMasterKeyCandidates(corePath string, regions []addressRange) ([]string, continue } for i := 0; i < len(data)-16; i += 8 { - // look for the length marker (0x18 = 24 bytes) val := binary.LittleEndian.Uint64(data[i : i+8]) if val != 0x18 { continue } - // next 8 bytes should be a pointer within this region ptr := binary.LittleEndian.Uint64(data[i+8 : i+16]) if ptr < region.start || ptr > region.end { continue @@ -172,7 +157,6 @@ func scanMasterKeyCandidates(corePath string, regions []addressRange) ([]string, return candidates, nil } -// findMallocSmallRegions parses vmmap output to find MALLOC_SMALL heap regions. func findMallocSmallRegions(pid int) ([]addressRange, error) { cmd := exec.Command("vmmap", "--wide", strconv.Itoa(pid)) output, err := cmd.Output() @@ -207,7 +191,6 @@ func findMallocSmallRegions(pid int) ([]addressRange, error) { return regions, nil } -// getMallocSmallRegionData returns the Mach-O segment data + vaddr for the given address range. func getMallocSmallRegionData(f *macho.File, region addressRange) ([]byte, uint64, error) { for _, seg := range f.Loads { if s, ok := seg.(*macho.Segment); ok { diff --git a/internal/masterkey/gcoredump_stub_darwin.go b/internal/masterkey/gcoredump_stub_darwin.go index def8d81..26386ef 100644 --- a/internal/masterkey/gcoredump_stub_darwin.go +++ b/internal/masterkey/gcoredump_stub_darwin.go @@ -8,10 +8,7 @@ import ( "github.com/moond4rk/keychainbreaker" ) -// DecryptKeychainRecords returns an error in default builds so GcoredumpRetriever -// falls through silently to the next tier. The CVE-2025-24204 securityd-dump -// implementation (gcoredump_darwin.go) is only compiled with -tags keychain_gcore, -// keeping the default `go build` free of the exploit code and its byte signatures. +// Default builds leave out the securityd dump (built only with -tags keychain_gcore), so this tier steps aside. func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { return nil, errors.New("keychain gcore dump not built in (rebuild with -tags keychain_gcore)") } diff --git a/internal/masterkey/keys_golden_test.go b/internal/masterkey/keys_golden_test.go index 454ee55..786cdf5 100644 --- a/internal/masterkey/keys_golden_test.go +++ b/internal/masterkey/keys_golden_test.go @@ -38,8 +38,7 @@ func keysFreeze(t *testing.T, dump masterkey.Dump, host masterkey.Host) masterke return dump } -// keysVaultsDump is what dumpkeys wrote for the golden's machine: two Chromium installs, the Opera and Yandex forks, and -// a vault whose v20 key failed, which keeps its v10 key; a Firefox install and a vault with no key are not in it. +// Two Chromium installs, the Opera and Yandex forks, and a vault that kept its v10 key when v20 failed. func keysVaultsDump(t *testing.T) masterkey.Dump { t.Helper() return masterkey.Dump{ diff --git a/internal/masterkey/masterkey.go b/internal/masterkey/masterkey.go index 2c89e7d..3d1e80f 100644 --- a/internal/masterkey/masterkey.go +++ b/internal/masterkey/masterkey.go @@ -1,5 +1,4 @@ -// Package masterkey retrieves Chromium master keys (per-platform retrievers + a cross-host Dump format). -// Firefox and Safari own their own key paths and don't route through here. +// Package masterkey retrieves Chromium master keys; Firefox and Safari keep their own key paths. package masterkey import ( @@ -31,7 +30,6 @@ type Retriever interface { // ErrNotApplicable is a retriever's way of stepping aside; it never counts as a failure. var ErrNotApplicable = errors.New("retriever not applicable") -// errStorageNotFound: the browser's account is absent from the credential store (keychain/keyring). var errStorageNotFound = errors.New("not found in credential store") //nolint:unused // only used on darwin and linux // Locator is where one user data dir's keys are found; each retriever reads only the fields of its OS. @@ -59,8 +57,7 @@ const ( ABEAvast ) -// RetrieveAll runs this OS's retrievers in order. Per version the first key wins and later retrievers are not -// tried; a version's error is reported only when all its retrievers fail, and a v20 failure never drops the v10 key. +// Per version the first key wins, and an error is reported only when every retriever of that version fails. func RetrieveAll(ctx context.Context, loc Locator) (Set, error) { return retrieveAll(ctx, loc, platformRetrievers) } diff --git a/internal/masterkey/params.go b/internal/masterkey/params.go index b0ae777..ab528f9 100644 --- a/internal/masterkey/params.go +++ b/internal/masterkey/params.go @@ -8,7 +8,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/crypto" ) -// pbkdf2Params holds platform-specific PBKDF2 parameters (each platform file defines its own). type pbkdf2Params struct { salt []byte iterations int diff --git a/internal/masterkey/retriever_darwin.go b/internal/masterkey/retriever_darwin.go index 6bf8ae9..017cbb5 100644 --- a/internal/masterkey/retriever_darwin.go +++ b/internal/masterkey/retriever_darwin.go @@ -29,16 +29,14 @@ var darwinParams = pbkdf2Params{ const securityCmdTimeout = 30 * time.Second -// The v10 strategies in order, first success wins: the securityd dump (root only), the run's login keychain, -// then the `security` CLI, which may prompt. +// First success wins; the security CLI goes last because it may prompt. var platformRetrievers = []Retriever{ &gcoredumpRetriever{}, keychainRetriever{}, &securityRetriever{cache: make(map[string]securityResult)}, } -// gcoredumpRetriever extracts keychain secrets via CVE-2025-24204 (dumps securityd memory; needs root). -// Records are cached once (sync.Once) so the dump runs a single time across all browsers. +// Records are read once (sync.Once), so the dump runs a single time for all browsers. type gcoredumpRetriever struct { once sync.Once records []keychainbreaker.GenericPassword @@ -74,8 +72,7 @@ func findStorageKey(records []keychainbreaker.GenericPassword, storage string) ( return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound) } -// keychainRetriever reads the label's secret from the run's login keychain (no root). Without a keychain, or with a -// locked one, it steps aside: the keychain reports why once for the whole run. +// Without a keychain, or with a locked one, it steps aside: the keychain reports why once for the run. type keychainRetriever struct{} func (keychainRetriever) Version() Version { return V10 } @@ -94,8 +91,7 @@ func (keychainRetriever) Retrieve(ctx context.Context, loc Locator) ([]byte, err return darwinParams.deriveKey(secret), nil } -// securityRetriever queries Keychain via the macOS `security` CLI (may prompt). Results are -// cached per storage name so each browser's key is fetched once. +// Results are cached per storage name, so each browser's key is fetched, and prompted for, once. type securityRetriever struct { mu sync.Mutex cache map[string]securityResult @@ -135,8 +131,7 @@ func (r *securityRetriever) retrieveKeyOnce(ctx context.Context, storage string) if errors.Is(ctx.Err(), context.DeadlineExceeded) { return nil, fmt.Errorf("security command timed out after %s", securityCmdTimeout) } - // `security` exits non-zero with empty stderr when the user denies the prompt or mistypes; - // surface that instead of the cryptic "exit status 128 ()". + // `security` exits non-zero with empty stderr when the prompt is denied; say so instead of "exit status 128 ()". stderrStr := strings.TrimSpace(stderr.String()) if stderrStr == "" { return nil, fmt.Errorf("security command: %w (likely keychain access denied or wrong password)", err) diff --git a/internal/masterkey/retriever_linux.go b/internal/masterkey/retriever_linux.go index 7090544..f5cf31f 100644 --- a/internal/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -19,11 +19,9 @@ var linuxParams = pbkdf2Params{ hashFunc: sha1.New, } -// One per prefix Chromium emits: v10 = PBKDF2("peanuts") when no keyring exists, v11 = PBKDF2(keyring secret). -// A profile carries both if the host moved between headless and keyring sessions. +// A profile holds both v10 and v11 values when its host moved between headless and keyring sessions. var platformRetrievers = []Retriever{posixRetriever{}, dbusRetriever{}} -// dbusRetriever queries GNOME Keyring / KDE Wallet via D-Bus Secret Service. type dbusRetriever struct{} func (dbusRetriever) Version() Version { return V11 } @@ -76,8 +74,7 @@ func (dbusRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound) } -// posixRetriever derives Chromium's kV10Key via PBKDF2 over the hardcoded "peanuts" password — the -// deterministic v10 key used when no keyring exists (headless/Docker/CI). Mirrors PosixKeyProvider. +// posixRetriever covers hosts without a keyring (headless, Docker, CI), mirroring Chromium's PosixKeyProvider. type posixRetriever struct{} func (posixRetriever) Version() Version { return V10 } diff --git a/internal/masterkey/retriever_linux_test.go b/internal/masterkey/retriever_linux_test.go index 77e5af9..779d616 100644 --- a/internal/masterkey/retriever_linux_test.go +++ b/internal/masterkey/retriever_linux_test.go @@ -18,7 +18,6 @@ func TestPosixRetriever(t *testing.T) { assert.Equal(t, linuxParams.deriveKey([]byte("peanuts")), key) assert.Len(t, key, linuxParams.keySize) - // The key should not be all zeros. allZero := true for _, b := range key { if b != 0 { @@ -28,15 +27,13 @@ func TestPosixRetriever(t *testing.T) { } assert.False(t, allZero, "derived key should not be all zeros") - // "peanuts" is a hardcoded password, so the result should be the same regardless of the locator - // or number of calls. + // The password is fixed, so the key is the same for any locator and on every call. key2, err := r.Retrieve(context.Background(), Locator{KeychainLabel: "Brave"}) require.NoError(t, err) assert.Equal(t, key, key2, "kV10Key should be constant across any storage label") } -// TestPosixRetriever_MatchesChromiumKV10Key pins posixRetriever's output to Chromium's kV10Key -// reference bytes (PBKDF2-HMAC-SHA1 of "peanuts" with "saltysalt", 1 iteration, 16 bytes). +// Pins the output to Chromium's kV10Key reference bytes. func TestPosixRetriever_MatchesChromiumKV10Key(t *testing.T) { want := []byte{ 0xfd, 0x62, 0x1f, 0xe5, 0xa2, 0xb4, 0x02, 0x53, diff --git a/internal/masterkey/retriever_windows.go b/internal/masterkey/retriever_windows.go index 995ab1e..fec42fb 100644 --- a/internal/masterkey/retriever_windows.go +++ b/internal/masterkey/retriever_windows.go @@ -16,7 +16,6 @@ import ( // Both run: a profile upgraded past Chrome 127 holds v10 and v20 values side by side. var platformRetrievers = []Retriever{dpapiRetriever{}, abeRetriever{}} -// dpapiRetriever unwraps Chrome's Local State os_crypt.encrypted_key via Windows DPAPI. type dpapiRetriever struct{} func (dpapiRetriever) Version() Version { return V10 } diff --git a/internal/record/record_test.go b/internal/record/record_test.go index c61e9bd..303b870 100644 --- a/internal/record/record_test.go +++ b/internal/record/record_test.go @@ -45,7 +45,7 @@ func TestStamp(t *testing.T) { } } -// The tags are the output's field names and column headers, so they stay snake_case(field name) and lead with the stamp. +// The tags are the output's field names and column headers, so they stay snake_case and lead with the stamp. func TestTags_AreSnakeCaseFieldNames(t *testing.T) { for _, r := range allRecords() { typ := reflect.TypeOf(r).Elem() diff --git a/internal/snapshot/copy_windows_test.go b/internal/snapshot/copy_windows_test.go index e8917ea..4e93642 100644 --- a/internal/snapshot/copy_windows_test.go +++ b/internal/snapshot/copy_windows_test.go @@ -41,8 +41,7 @@ func TestCopy_PlainWhenNotLocked(t *testing.T) { assert.Equal(t, testData, copied) } -// openExclusive opens a file with exclusive lock (dwShareMode=0), -// simulating Chrome's PRAGMA locking_mode=EXCLUSIVE behavior. +// Share mode 0 locks the file the way Chrome's locking_mode=EXCLUSIVE does. func openExclusive(t *testing.T, path string) syscall.Handle { t.Helper() srcPtr, err := syscall.UTF16PtrFromString(path) @@ -51,7 +50,7 @@ func openExclusive(t *testing.T, path string) syscall.Handle { handle, err := syscall.CreateFile( srcPtr, syscall.GENERIC_READ|syscall.GENERIC_WRITE, - 0, // exclusive: no sharing + 0, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, diff --git a/internal/snapshot/manifest.go b/internal/snapshot/manifest.go index ff52806..cc29567 100644 --- a/internal/snapshot/manifest.go +++ b/internal/snapshot/manifest.go @@ -9,7 +9,6 @@ import ( "path/filepath" ) -// ManifestVersion is the manifest.json schema this build writes and reads. const ManifestVersion = 1 const manifestName = "manifest.json" @@ -20,8 +19,6 @@ type Manifest struct { Dirs []ManifestDir `json:"dirs"` } -// ManifestDir is one user data dir in the snapshot directory: its DirID, the browser it belongs to, and what was -// captured from it. type ManifestDir struct { ID string `json:"id"` Browser string `json:"browser"` diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 090fdf9..b98a67a 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -88,7 +88,6 @@ func (d *Dir) Snapshot(dirID string) Snapshot { return Snapshot{dirID: dirID, root: d.path, failed: d.failed} } -// Close removes a temporary snapshot directory and leaves an opened one in place. func (d *Dir) Close() error { if !d.temp { return nil @@ -105,8 +104,7 @@ type Snapshot struct { failed map[string]error } -// Path returns rel's location in the snapshot, or why it is not there: fs.ErrNotExist when it was never captured -// or had vanished before Capture reached it, else the copy's error. +// Path reports fs.ErrNotExist for a file never captured or gone before Capture reached it, else the copy's error. func (s Snapshot) Path(rel string) (string, error) { local, err := localPath(s.dirID, rel) if err != nil { diff --git a/internal/snapshot/zip.go b/internal/snapshot/zip.go index 4a263e6..03c9f98 100644 --- a/internal/snapshot/zip.go +++ b/internal/snapshot/zip.go @@ -44,8 +44,7 @@ func (d *Dir) Zip(dst string) (err error) { return nil } -// zipTarget follows a symlinked dst and reports an archive already there, so replacing it keeps the link and the -// mode that writing through os.Create would have kept. +// Replacing an archive through a symlinked dst keeps the link and the mode os.Create would have kept. func zipTarget(dst string) (string, fs.FileInfo, error) { target := dst if resolved, err := filepath.EvalSymlinks(dst); err == nil { diff --git a/internal/snapshot/zip_test.go b/internal/snapshot/zip_test.go index e87d344..992db97 100644 --- a/internal/snapshot/zip_test.go +++ b/internal/snapshot/zip_test.go @@ -143,7 +143,6 @@ func TestZip_WritesThroughASymlinkedArchive(t *testing.T) { assert.Len(t, zr.File, 1, "the archive lands in the link's target") } -// snapshotSource is a snapshot directory holding one captured file. func snapshotSource(t *testing.T) string { t.Helper() src := t.TempDir() diff --git a/internal/sqlitex/query.go b/internal/sqlitex/query.go index a819a64..360a1af 100644 --- a/internal/sqlitex/query.go +++ b/internal/sqlitex/query.go @@ -6,9 +6,7 @@ import ( "os" ) -// CountRows runs a scalar count query (e.g. SELECT COUNT(*) FROM ...) and -// returns the integer result. Unlike eachRow (which swallows per-row scan -// errors), CountRows uses QueryRow for fail-fast behavior on scan failures. +// CountRows fails fast on a scan error, unlike QueryRows, which skips the row. func CountRows(dbPath string, journalOff bool, query string) (int, error) { if _, err := os.Stat(dbPath); err != nil { return 0, fmt.Errorf("database file: %w", err) @@ -32,11 +30,7 @@ func CountRows(dbPath string, journalOff bool, query string) (int, error) { return count, nil } -// QueryRows is a generic helper (Go 1.18+) that wraps eachRow and collects -// results into a typed slice. Each extract method only needs to provide the -// scan function that converts one database row into a typed value. -// -// Rows that fail to scan are skipped (logged at debug level by eachRow). +// Rows that fail to scan are skipped and logged at debug level. func QueryRows[T any](dbPath string, journalOff bool, query string, scanRow func(*sql.Rows) (T, error)) ([]T, error) { var items []T err := eachRow(dbPath, journalOff, query, func(rows *sql.Rows) error { diff --git a/internal/sqlitex/sqlite.go b/internal/sqlitex/sqlite.go index 082fac0..041d735 100644 --- a/internal/sqlitex/sqlite.go +++ b/internal/sqlitex/sqlite.go @@ -11,14 +11,8 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) -// eachRow opens a SQLite database, optionally disables journal mode (required -// for Firefox databases), runs the query, and calls scanFn for each row. -// -// It validates the database file exists before opening to prevent sql.Open from -// silently creating an empty database. -// -// scanFn should return nil to continue iteration, or an error to skip the current -// row (the error is logged at debug level and iteration continues). +// journalOff is for Firefox databases; the file is checked first so sql.Open never creates an empty one. +// A row whose scanFn returns an error is skipped and logged at debug level. func eachRow(dbPath string, journalOff bool, query string, scanFn func(*sql.Rows) error) error { if _, err := os.Stat(dbPath); err != nil { return fmt.Errorf("database file: %w", err) diff --git a/internal/sqlitex/sqlite_test.go b/internal/sqlitex/sqlite_test.go index 6d61bde..c4e8127 100644 --- a/internal/sqlitex/sqlite_test.go +++ b/internal/sqlitex/sqlite_test.go @@ -10,7 +10,6 @@ import ( ) func TestEachRow(t *testing.T) { - // Create a temp SQLite database dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") @@ -23,7 +22,6 @@ func TestEachRow(t *testing.T) { require.NoError(t, err) require.NoError(t, db.Close()) - // Query using our helper var names []string err = eachRow(dbPath, false, "SELECT name FROM items ORDER BY id", func(rows *sql.Rows) error { var name string diff --git a/internal/timeconv/timeconv.go b/internal/timeconv/timeconv.go index 6b802b8..7f90faf 100644 --- a/internal/timeconv/timeconv.go +++ b/internal/timeconv/timeconv.go @@ -1,4 +1,4 @@ -// Package timeconv converts browser timestamps to UTC; browsers write 0 for "unset", so non-positive input is the zero time. +// Package timeconv converts browser timestamps to UTC; a non-positive input, which browsers write for unset, is zero. package timeconv import "time"