Files
HackBrowserData/internal/browser/firefox/firefox.go
T
Roger c823d83e57 refactor(browser): give each base Sources and Extract (#714)
* refactor(browser): give each base Sources and Extract

browser.Input carried every base's secret, so no base said what it needs.
Each base now takes its own secret as a typed parameter, and app holds the
one switch that knows all three. Safari's files no longer need ../ paths.

* refactor(app): make execute the runner's export method

* docs: add a package map to CONTRIBUTING.md

* refactor(app): keep each base's secret on the runner

The bases interface had one real implementation and existed for the test
fake, so it held two of a run's three secrets. The runner holds them all,
and the run tests use real fixtures.

* refactor(chromium): pass data where a function was passed

DiscoverAt took a UserDataDir field by field, the Opera extension list was
a second function for one JSON key, and NeedsMasterKeys repeated by hand
which extractors decrypt.

* refactor(app): set both passwords after the flags are valid

The keychain password went in as a ValidateDump argument and the Firefox
one was assigned afterwards; cmd now sets both the same way.

* refactor: rename dumpKeysWith and CandidatePaths

buildKeyFile says what it returns, and DirRelativePaths says what its paths
are relative to. A failed browser's dir ID no longer comes from a cast.

* refactor(app): plan extractions without a plan struct

dirPlan and plannedExtraction existed to carry a profile and three lists.
An Extraction now holds its Profile, and planExtractions returns the lists.

* refactor(browser): rename profileAt and downloadsOf

profileAt returned a user data dir in two shapes, and downloadsOf returned
a function. Both bases now have dirFromProfilePath with one shape, and
Safari has newDownloadExtractor beside its other constructors.

* refactor: use one short name for a user data dir in app

Fields said UserDataDirID beside Dirs and DirFailure, and runDir did not
say what it runs. They are DirID and runExtractions; the type keeps its
full name.

* refactor(app): rename withData to dropEmptyProfiles

With reads as adding something, and the function removes profiles. hasData
loses a parameter that always held sourcesFor's result.

* refactor: rename five functions that misstate what they do

untilDone had no verb, canCreateIn asked a yes/no question but returned an
error, failAll only built results, sortKeyOf was the last xxxOf, and
checkProfilePath returned a value where its siblings return only an error.

* refactor: name forks as forks and drop the For lookups

The fork table was typed override while every variable said fork, and six
lookups were named for a preposition, not for what they return. The other
renames make one name mean one thing: extractors, dataSources, extractFile.

* refactor(browser): drop parameters Sources and Extract ignore

No interface makes the three bases share a signature, so the blank
parameters only hid that Chromium's sources vary by dir, Safari's by
profile, and that only Safari's extraction can be cancelled.

* refactor(browser): ask a base for one category's sources

Sources returned every category's files, so its name had no object and
each base carried a loop projecting its table. Keyed by category it is
the same lookup as Extract and NeedsMasterKeys.

* refactor: report a locked keychain as data, not a log line

Dump and DumpKeys return results for cmd to print, yet warned about the
keychain themselves, with the sentence passed in as an argument. Now cmd
says every sentence; warnIfLocked and printNothingFound take no message.

* refactor(cmd): rename printExported to printExportedFiles

Exported is an adjective; the function lists the files a run wrote.
2026-11-22 23:52:12 +08:00

170 lines
6.1 KiB
Go

// Package firefox is the Firefox base: profile discovery, file parsing, and each profile's own key4.db.
package firefox
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
var (
loginsJSON = browser.Source{RelativePath: "logins.json"}
keyStore = browser.Source{RelativePath: "key4.db", Optional: true}
placesDB = browser.Source{RelativePath: "places.sqlite"}
cookiesDB = browser.Source{RelativePath: "cookies.sqlite"}
extensionsJSON = browser.Source{RelativePath: "extensions.json"}
webappsStore = browser.Source{RelativePath: "webappsstore.sqlite"}
)
// extractor is how one category is read: the files it needs, and how it parses them with the user's primary password.
type extractor struct {
sources []browser.Source
extract func(captured browser.ProfileSnapshot, primaryPassword string, out browser.Collector) error
}
// extractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads.
var extractors = map[category.Category]extractor{
category.Password: newDecryptingExtractor(extractPasswords, loginsJSON),
category.Cookie: newPlainExtractor(extractCookies, cookiesDB),
category.Bookmark: newPlainExtractor(extractBookmarks, placesDB),
category.History: newPlainExtractor(extractHistories, placesDB),
category.Download: newPlainExtractor(extractDownloads, placesDB),
category.Extension: newPlainExtractor(extractExtensions, extensionsJSON),
category.LocalStorage: newPlainExtractor(extractLocalStorage, webappsStore),
}
// Discover takes -p as one profile: its parent is the Profiles directory, and only that profile is selected.
func Discover(firefoxBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) {
if options.ProfilePath != "" {
if dir, ok := dirFromProfilePath(firefoxBrowser, options.ProfilePath); ok {
return []browser.UserDataDir{dir}, nil
}
return nil, nil
}
var errs []error
var dirs []browser.UserDataDir
for i, path := range userDataDirPaths(firefoxBrowser, options) {
dir := browser.UserDataDir{ID: firefoxBrowser.UserDataDirID(i), Browser: firefoxBrowser, Path: path}
profiles, err := discoverProfiles(dir)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
errs = append(errs, fmt.Errorf("%s: %w", path, err))
continue
}
dir.Profiles = profiles
dirs = append(dirs, dir)
}
return dirs, errors.Join(errs...)
}
func dirFromProfilePath(firefoxBrowser browser.Browser, path string) (browser.UserDataDir, bool) {
clean := filepath.Clean(path)
if !hasDataFile(clean) {
return browser.UserDataDir{}, false
}
name := filepath.Base(clean)
return browser.UserDataDir{
ID: firefoxBrowser.UserDataDirID(0),
Browser: firefoxBrowser,
Path: filepath.Dir(clean),
Profiles: []browser.Profile{{Name: name, RelativePath: name}},
}, true
}
func userDataDirPaths(firefoxBrowser browser.Browser, options browser.DiscoverOptions) []string {
paths := make([]string, 0, len(firefoxBrowser.Platform().UserDataDirPaths))
for _, relativePath := range firefoxBrowser.Platform().UserDataDirPaths {
paths = append(paths, filepath.Join(options.HomeDir, filepath.FromSlash(relativePath)))
}
return paths
}
// discoverProfiles counts any subdirectory with a file an extractor reads, as names are random; key4.db does not.
func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) {
entries, err := os.ReadDir(dir.Path)
if err != nil {
return nil, err
}
var profiles []browser.Profile
for _, entry := range entries {
if entry.IsDir() && hasDataFile(filepath.Join(dir.Path, entry.Name())) {
profiles = append(profiles, browser.Profile{Name: entry.Name(), RelativePath: entry.Name()})
}
}
return profiles, nil
}
func hasDataFile(path string) bool {
for _, extractor := range extractors {
for _, source := range extractor.sources {
if source.Optional {
continue
}
for _, relativePath := range source.RelativePaths() {
if _, err := os.Stat(filepath.Join(path, filepath.FromSlash(relativePath))); err == nil {
return true
}
}
}
}
return false
}
// Sources lists the files dataCategory is read from in any profile; Firefox may not support it.
func Sources(dataCategory category.Category) (sources []browser.Source, supported bool) {
extractor, ok := extractors[dataCategory]
return extractor.sources, ok
}
// Extract opens a protected profile's key store with primaryPassword, "" when the user gave none.
func Extract(captured browser.ProfileSnapshot, primaryPassword string, dataCategory category.Category, out browser.Collector) error {
extractor, ok := extractors[dataCategory]
if !ok {
return fmt.Errorf("%s has no %s extractor", captured.UserDataDir.Browser.Name, dataCategory)
}
return extractor.extract(captured, primaryPassword, out)
}
func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor {
return extractor{
sources: []browser.Source{source},
extract: func(captured browser.ProfileSnapshot, _ string, out browser.Collector) error {
path, err := captured.Path(source)
if err != nil {
return err
}
return extractFile(path, out)
},
}
}
// newDecryptingExtractor also captures key4.db, the profile's own key store.
func newDecryptingExtractor(extractFile func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) extractor {
return extractor{
sources: []browser.Source{source, keyStore},
extract: func(captured browser.ProfileSnapshot, primaryPassword string, out browser.Collector) error {
path, err := captured.Path(source)
if err != nil {
return err
}
masterKey := func() ([]byte, error) { return profileKey(captured, path, primaryPassword) }
return extractFile(masterKey, path, out)
},
}
}
func profileKey(captured browser.ProfileSnapshot, loginsPath, primaryPassword string) ([]byte, error) {
key4Path, err := captured.Path(keyStore)
if err != nil {
return nil, err
}
return retrieveMasterKey(key4Path, loginsPath, []byte(primaryPassword))
}