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.
This commit is contained in:
Roger authored and GitHub committed 2026-11-22 23:52:12 +08:00
1 parent f36790d4dd
commit c823d83e57
53 files changed
+1238 -1167

No files matched your search

+2 -1
View File
@@ -25,7 +25,8 @@ func newArchiveCommand() *cobra.Command {
return err
}
if len(discovery.Dirs) == 0 {
printNothingFound(command.ErrOrStderr(), discovery, "no browsers found")
printDirFailures(command.ErrOrStderr(), discovery.DirFailures)
log.Warnf("no browsers found")
return nil
}
log.Infof("Archived %d entries to %s", fileCount, options.ArchivePath)
+18 -11
View File
@@ -8,13 +8,14 @@ import (
"github.com/spf13/cobra"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
func newDumpCommand() *cobra.Command {
var (
flags app.DumpFlags
keychain passwordFlags
firefox passwordFlags
flags app.DumpFlags
keychainFlags passwordFlags
firefoxFlags passwordFlags
)
command := &cobra.Command{
@@ -26,7 +27,7 @@ func newDumpCommand() *cobra.Command {
hack-browser-data dump -f cookie-editor
hack-browser-data dump --zip`,
RunE: func(command *cobra.Command, args []string) error {
return runDump(command.Context(), command.ErrOrStderr(), flags, keychain, firefox)
return runDump(command.Context(), command.ErrOrStderr(), flags, keychainFlags, firefoxFlags)
},
}
@@ -34,19 +35,20 @@ func newDumpCommand() *cobra.Command {
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
command.Flags().StringVarP(&flags.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version")
addOutputFlags(command, &flags.Output)
addPasswordFlags(command, &keychain, "keychain-pw", "macOS keychain password")
addPasswordFlags(command, &firefox, "firefox-pw", "Firefox primary password")
addPasswordFlags(command, &keychainFlags, "keychain-pw", "macOS keychain password")
addPasswordFlags(command, &firefoxFlags, "firefox-pw", "Firefox primary password")
command.MarkFlagsMutuallyExclusive("keychain-pw-stdin", "firefox-pw-stdin")
return command
}
func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychain, firefox passwordFlags) error {
options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin))
func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychainFlags, firefoxFlags passwordFlags) error {
options, err := app.ValidateDump(flags)
if err != nil {
return err
}
if options.FirefoxPrimaryPassword, err = readFirefoxPassword(ctx, firefox, os.Stdin); err != nil {
options.KeychainPassword = keychainPasswordFunc(keychainFlags, os.Stdin)
if options.FirefoxPrimaryPassword, err = readFirefoxPassword(ctx, firefoxFlags, os.Stdin); err != nil {
return err
}
discovery, summary, err := app.Dump(ctx, options)
@@ -54,10 +56,15 @@ func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychai
return err
}
if len(discovery.Dirs) == 0 {
printNothingFound(stderr, discovery, "no browsers found")
printDirFailures(stderr, discovery.DirFailures)
log.Warnf("no browsers found")
return nil
}
printExported(stderr, summary.Exported)
// A stopped run says nothing of the keychain: the stop itself may be what left it locked.
if summary.KeychainErr != nil && ctx.Err() == nil {
log.Warnf("%v; keychain-protected data was exported as metadata only", summary.KeychainErr)
}
printExportedFiles(stderr, summary.Exported)
if ctx.Err() == nil {
printSummary(stderr, summary)
}
+10 -6
View File
@@ -11,8 +11,8 @@ import (
func newDumpKeysCommand() *cobra.Command {
var (
flags app.DumpKeysFlags
keychain passwordFlags
flags app.DumpKeysFlags
keychainFlags passwordFlags
)
command := &cobra.Command{
@@ -21,22 +21,26 @@ func newDumpKeysCommand() *cobra.Command {
Example: ` hack-browser-data dumpkeys -o keys.json
hack-browser-data dumpkeys -b chrome`,
RunE: func(command *cobra.Command, args []string) error {
options, err := app.ValidateDumpKeys(flags, keychainPasswordFunc(keychain, os.Stdin))
options, err := app.ValidateDumpKeys(flags)
if err != nil {
return err
}
vaultCount, err := app.DumpKeys(command.Context(), options, command.OutOrStdout())
options.KeychainPassword = keychainPasswordFunc(keychainFlags, os.Stdin)
summary, err := app.DumpKeys(command.Context(), options, command.OutOrStdout())
if err != nil {
return err
}
log.Infof("Exported keys for %d vault(s)", vaultCount)
if summary.KeychainErr != nil {
log.Warnf("%v; keys only it holds are missing from the key file", summary.KeychainErr)
}
log.Infof("Exported keys for %d vault(s)", summary.Vaults)
return nil
},
}
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
command.Flags().StringVarP(&flags.OutputPath, "output", "o", "", "output file (default: stdout)")
addPasswordFlags(command, &keychain, "keychain-pw", "macOS keychain password")
addPasswordFlags(command, &keychainFlags, "keychain-pw", "macOS keychain password")
return command
}
+1 -1
View File
@@ -21,7 +21,7 @@ func newListCommand() *cobra.Command {
return err
}
for _, failure := range discovery.DirFailures {
log.Warnf("%s: %v", failure.UserDataDirID, failure.Err)
log.Warnf("%s: %v", failure.DirID, failure.Err)
}
if len(discovery.Dirs) == 0 {
command.Println("No browsers found.")
+1 -1
View File
@@ -11,7 +11,7 @@ import (
func configureDoubleClickMode() {}
// exitBy ends the process by sig itself, as the signal would have, so a calling shell or script sees it was stopped.
// exitBy ends the process by the signal itself, as it would have, so a calling shell or script sees it was stopped.
func exitBy(received os.Signal) {
signal.Reset(received)
if syscallSignal, ok := received.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), syscallSignal) == nil {
+5 -5
View File
@@ -32,7 +32,7 @@ func addPasswordFlags(command *cobra.Command, flags *passwordFlags, name, what s
// readFirefoxPassword takes the flag, else the first line of stdin; "" is the empty password, and it never prompts.
func readFirefoxPassword(ctx context.Context, flags passwordFlags, stdin io.Reader) (string, error) {
if flags.fromStdin {
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
return readContext(ctx, func() (string, error) { return firstLine(stdin) })
}
return flags.value, nil
}
@@ -47,7 +47,7 @@ func keychainPasswordFunc(flags passwordFlags, stdin *os.File) keychain.Password
return func(context.Context) (string, error) { return password, nil }
case flags.fromStdin:
return func(ctx context.Context) (string, error) {
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
return readContext(ctx, func() (string, error) { return firstLine(stdin) })
}
case term.IsTerminal(int(stdin.Fd())):
return func(ctx context.Context) (string, error) { return promptPassword(ctx, stdin) }
@@ -71,7 +71,7 @@ func promptPassword(ctx context.Context, stdin *os.File) (string, error) {
return "", fmt.Errorf("read the password: %w", err)
}
fmt.Fprint(os.Stderr, "Enter macOS login password: ")
password, err := untilDone(ctx, func() (string, error) {
password, err := readContext(ctx, func() (string, error) {
entered, err := term.ReadPassword(fileDescriptor)
return string(entered), err
})
@@ -86,8 +86,8 @@ func promptPassword(ctx context.Context, stdin *os.File) (string, error) {
return password, nil
}
// untilDone stops waiting when the run is stopped; the read itself stays blocked until the process ends.
func untilDone(ctx context.Context, read func() (string, error)) (string, error) {
// readContext stops waiting when the run is stopped; the read itself stays blocked until the process ends.
func readContext(ctx context.Context, read func() (string, error)) (string, error) {
type answer struct {
value string
err error
+9 -10
View File
@@ -17,11 +17,11 @@ func printSummary(stderr io.Writer, summary app.Summary) {
table := tabwriter.NewWriter(stderr, 0, 0, 2, ' ', 0)
fmt.Fprintln(table, "Browser\tProfile\tCategory\tResult\tRecords\tDetail")
for _, failure := range summary.DirFailures {
fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.UserDataDirID, app.OutcomeError, failure.Err)
fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.DirID, app.OutcomeError, failure.Err)
}
for _, result := range summary.Results {
fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n",
result.UserDataDirID, result.ProfileName, result.Category, result.Outcome, result.Records, resultDetail(result))
result.DirID, result.Profile.Name, result.Category, result.Outcome, result.Records, resultDetail(result))
}
if err := table.Flush(); err != nil {
log.Warnf("print summary: %v", err)
@@ -39,16 +39,15 @@ func resultDetail(result app.Result) string {
}
}
// printNothingFound lists discovery's failures first, the likely reason a run found no browser data.
func printNothingFound(stderr io.Writer, discovery app.Discovery, message string) {
if len(discovery.DirFailures) > 0 {
printSummary(stderr, app.Summary{DirFailures: discovery.DirFailures})
// printDirFailures lists discovery's failures, the likely reason a run found no browser data.
func printDirFailures(stderr io.Writer, failures []app.DirFailure) {
if len(failures) > 0 {
printSummary(stderr, app.Summary{DirFailures: failures})
}
log.Warnf("%s", message)
}
// printExported lists the files a run wrote, even when it stopped early, so the user finds what it left.
func printExported(stderr io.Writer, exported export.Listing) {
// printExportedFiles lists the files a run wrote, even when it stopped early, so the user finds what it left.
func printExportedFiles(stderr io.Writer, exported export.Listing) {
if len(exported.Files) == 0 {
return
}
@@ -90,7 +89,7 @@ func printRecordCounts(out io.Writer, discovery app.Discovery, summary app.Summa
for _, profile := range dir.Profiles {
fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name)
for _, dataCategory := range category.All() {
fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory}])
fmt.Fprintf(table, "\t%d", counts[app.Extraction{DirID: dir.ID, Profile: profile, Category: dataCategory}])
}
fmt.Fprintln(table)
}
+6 -4
View File
@@ -10,22 +10,24 @@ import (
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
func TestPrintSummary(t *testing.T) {
cookie := app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie}
defaultProfile := browser.Profile{Name: "Default", RelativePath: "Default"}
cookie := app.Extraction{DirID: "chrome", Profile: defaultProfile, Category: category.Cookie}
var buffer bytes.Buffer
printSummary(&buffer, app.Summary{
Results: []app.Result{
{Extraction: cookie, Outcome: app.OutcomePartial, Records: 224, Failures: 4},
{
Extraction: app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Password},
Extraction: app.Extraction{DirID: "chrome", Profile: defaultProfile, Category: category.Password},
Outcome: app.OutcomeError, Failures: 2, Err: errors.New("password not decrypted"),
},
{Extraction: app.Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}},
{Extraction: app.Extraction{DirID: "edge", Profile: defaultProfile, Category: category.Password}},
},
DirFailures: []app.DirFailure{{UserDataDirID: "arc-2", Err: errors.New("permission denied")}},
DirFailures: []app.DirFailure{{DirID: "arc-2", Err: errors.New("permission denied")}},
})
lines := strings.Split(strings.TrimSpace(buffer.String()), "\n")
+4 -2
View File
@@ -8,6 +8,7 @@ import (
"github.com/spf13/cobra"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
func newRestoreCommand() *cobra.Command {
@@ -48,10 +49,11 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e
return err
}
if len(discovery.Dirs) == 0 {
printNothingFound(stderr, discovery, "no browsers to restore from the supplied keys and data")
printDirFailures(stderr, discovery.DirFailures)
log.Warnf("no browsers to restore from the supplied keys and data")
return nil
}
printExported(stderr, summary.Exported)
printExportedFiles(stderr, summary.Exported)
if ctx.Err() == nil {
printSummary(stderr, summary)
}