refactor(app): per-stage inputs and per-dir planning (#689)

* refactor(app): per-command flags and per-stage inputs

One Options bag fed every stage and cmd patched restore's keys into it after validation; each stage now takes what it
reads, dir-level failures are their own type, and cmd prints what a run exported.

* refactor(app): group the plan by dir and profile

Execute now walks the plan's own shape instead of filtering a flat list and looking profiles up by name.

* refactor(app): file code by command and stage

Pure moves: each command's flags and validation sit beside its stage, and execute.go keeps only the runner.

* refactor: read the keychain password in cmd

Prompting and reading stdin are terminal work, so app now receives the password func; cobra already rejects both flags.

* refactor(app): plan each user data dir right before it runs

A run-wide Plan had to drop its extractors and rebuild them with the keychain; per-dir planning keeps one extractor.
This commit is contained in:
Roger authored and GitHub committed 2026-11-09 17:25:36 +08:00
1 parent fed6c722e2
commit 7e6f325508
39 files changed
+936 -805

No files matched your search

+4 -5
View File
@@ -9,7 +9,7 @@ import (
func newArchiveCommand() *cobra.Command {
var (
flags app.Flags
flags app.ArchiveFlags
outputPath string
)
@@ -23,12 +23,11 @@ func newArchiveCommand() *cobra.Command {
if err != nil {
return err
}
discovery := app.Discover(options)
if len(discovery.Dirs) == 0 {
log.Warnf("no browsers found")
discovery := app.Discover(options.Target)
if foundNothing(command.ErrOrStderr(), discovery, "no browsers found") {
return nil
}
fileCount, err := app.Archive(command.Context(), discovery, options, outputPath)
fileCount, err := app.Archive(command.Context(), discovery, options.Categories, outputPath)
if err != nil {
return err
}
+13 -20
View File
@@ -3,15 +3,18 @@ package main
import (
"context"
"io"
"os"
"github.com/spf13/cobra"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
func newDumpCommand() *cobra.Command {
var flags app.Flags
var (
flags app.DumpFlags
keychain keychainFlags
)
command := &cobra.Command{
Use: "dump",
@@ -22,7 +25,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)
return runDump(command.Context(), command.ErrOrStderr(), flags, keychain)
},
}
@@ -31,33 +34,23 @@ func newDumpCommand() *cobra.Command {
command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor")
command.Flags().StringVarP(&flags.OutputDir, "dir", "d", "results", "output directory")
command.Flags().StringVarP(&flags.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version")
addKeychainPasswordFlags(command, &flags)
addKeychainPasswordFlags(command, &keychain)
command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip")
return command
}
func addKeychainPasswordFlags(command *cobra.Command, flags *app.Flags) {
command.Flags().StringVar(&flags.KeychainPassword, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)")
command.Flags().BoolVar(&flags.KeychainPasswordStdin, "keychain-pw-stdin", false,
"read the macOS keychain password from the first line of stdin")
command.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin")
}
func runDump(ctx context.Context, stderr io.Writer, flags app.Flags) error {
options, err := app.ValidateDump(flags)
func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychain keychainFlags) error {
options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin))
if err != nil {
return err
}
discovery := app.Discover(options)
if len(discovery.Dirs) == 0 {
if len(discovery.Errors) > 0 {
report(stderr, app.Summary{Results: discovery.Errors})
}
log.Warnf("no browsers found")
discovery := app.Discover(options.Target)
if foundNothing(stderr, discovery, "no browsers found") {
return nil
}
summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options)
summary, err := app.Execute(ctx, discovery, options.Categories, options.Output, options.Keychain)
announceExport(stderr, summary.Exported)
if ctx.Err() == nil {
report(stderr, summary)
}
+8 -4
View File
@@ -1,6 +1,8 @@
package main
import (
"os"
"github.com/spf13/cobra"
"github.com/moond4rk/hackbrowserdata/internal/app"
@@ -9,7 +11,8 @@ import (
func newDumpKeysCommand() *cobra.Command {
var (
flags app.Flags
flags app.DumpKeysFlags
keychain keychainFlags
outputPath string
)
@@ -19,11 +22,12 @@ 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)
options, err := app.ValidateDumpKeys(flags, keychainPasswordFunc(keychain, os.Stdin))
if err != nil {
return err
}
vaultCount, err := app.DumpKeys(command.Context(), app.Discover(options), options, outputPath)
discovery := app.Discover(options.Target)
vaultCount, err := app.DumpKeys(command.Context(), discovery, options.Keychain, command.OutOrStdout(), outputPath)
if err != nil {
return err
}
@@ -34,7 +38,7 @@ func newDumpKeysCommand() *cobra.Command {
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
command.Flags().StringVarP(&outputPath, "output", "o", "", "output file (default: stdout)")
addKeychainPasswordFlags(command, &flags)
addKeychainPasswordFlags(command, &keychain)
return command
}
+4 -4
View File
@@ -26,9 +26,9 @@ func newListCommand() *cobra.Command {
if err != nil {
return err
}
discovery := app.Discover(options)
for _, result := range discovery.Errors {
log.Warnf("%s: %v", result.UserDataDirID, result.Err)
discovery := app.Discover(options.Target)
for _, failure := range discovery.DirFailures {
log.Warnf("%s: %v", failure.UserDataDirID, failure.Err)
}
if len(discovery.Dirs) == 0 {
command.Println("No browsers found.")
@@ -37,7 +37,7 @@ func newListCommand() *cobra.Command {
if !detail {
return printProfiles(command.OutOrStdout(), discovery)
}
summary, err := app.CountRecords(command.Context(), app.NewPlan(discovery, options), options)
summary, err := app.CountRecords(command.Context(), discovery, options.Categories, options.Keychain)
if err != nil {
return err
}
+29
View File
@@ -3,6 +3,7 @@ package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
@@ -12,6 +13,7 @@ import (
"github.com/spf13/pflag"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/export"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
@@ -78,6 +80,33 @@ func report(writer io.Writer, summary app.Summary) {
}
}
// foundNothing reports discovery's failures, the likely reason it found no browser data, then says so.
func foundNothing(stderr io.Writer, discovery app.Discovery, message string) bool {
if len(discovery.Dirs) > 0 {
return false
}
if len(discovery.DirFailures) > 0 {
report(stderr, app.Summary{DirFailures: discovery.DirFailures})
}
log.Warnf("%s", message)
return true
}
// announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left.
func announceExport(stderr io.Writer, exported export.Output) {
if len(exported.Files) == 0 {
return
}
fmt.Fprintln(stderr)
log.Infof("Exported to %s/", exported.Dir)
for _, file := range exported.Files {
log.Infof(" %-24s %d entries", file.Name, file.Count)
}
if exported.ZipName != "" {
log.Infof("Compressed: %s/%s", exported.Dir, exported.ZipName)
}
}
// stopSignals end the process by default; each first cancels the run, so its temporary copies are removed.
var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
+95
View File
@@ -0,0 +1,95 @@
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/spf13/cobra"
"golang.org/x/term"
)
// keychainFlags say where the macOS login keychain password comes from; both empty means a prompt, or none.
type keychainFlags struct {
password string
passwordStdin bool
}
func addKeychainPasswordFlags(command *cobra.Command, flags *keychainFlags) {
command.Flags().StringVar(&flags.password, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)")
command.Flags().BoolVar(&flags.passwordStdin, "keychain-pw-stdin", false,
"read the macOS keychain password from the first line of stdin")
command.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin")
}
var errNoPassword = errors.New("macOS login password not given and stdin is not a terminal")
// keychainPasswordFunc is read lazily: a flag, else a no-echo prompt on a terminal, else none (metadata only).
func keychainPasswordFunc(flags keychainFlags, stdin *os.File) func(context.Context) (string, error) {
switch {
case flags.password != "":
password := flags.password
return func(context.Context) (string, error) { return password, nil }
case flags.passwordStdin:
return func(ctx context.Context) (string, error) {
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
}
case term.IsTerminal(int(stdin.Fd())):
return func(ctx context.Context) (string, error) { return promptPassword(ctx, stdin) }
default:
return func(context.Context) (string, error) { return "", errNoPassword }
}
}
func firstLine(reader io.Reader) (string, error) {
line, err := bufio.NewReader(reader).ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return "", fmt.Errorf("read the password from stdin: %w", err)
}
return strings.TrimRight(line, "\r\n"), nil
}
func promptPassword(ctx context.Context, stdin *os.File) (string, error) {
fileDescriptor := int(stdin.Fd())
state, err := term.GetState(fileDescriptor)
if err != nil {
return "", fmt.Errorf("read the password: %w", err)
}
fmt.Fprint(os.Stderr, "Enter macOS login password: ")
password, err := untilDone(ctx, func() (string, error) {
entered, err := term.ReadPassword(fileDescriptor)
return string(entered), err
})
if ctx.Err() != nil {
// The abandoned read never turns the echo back on, and the stop notice has already ended the line.
return "", errors.Join(ctx.Err(), term.Restore(fileDescriptor, state))
}
fmt.Fprintln(os.Stderr)
if err != nil {
return "", fmt.Errorf("read the password: %w", err)
}
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) {
type answer struct {
value string
err error
}
answers := make(chan answer, 1)
go func() {
value, err := read()
answers <- answer{value, err}
}()
select {
case reply := <-answers:
return reply.value, reply.err
case <-ctx.Done():
return "", ctx.Err()
}
}
+58
View File
@@ -0,0 +1,58 @@
package main
import (
"context"
"errors"
"io"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestKeychainPasswordFunc(t *testing.T) {
tests := []struct {
name string
flags keychainFlags
stdin string
want string
err error
}{
{name: "flag", flags: keychainFlags{password: "from-flag"}, stdin: "from-stdin\n", want: "from-flag"},
{name: "stdin", flags: keychainFlags{passwordStdin: true}, stdin: "from-stdin\r\nnext\n", want: "from-stdin"},
{name: "stdin without newline", flags: keychainFlags{passwordStdin: true}, stdin: "from-stdin", want: "from-stdin"},
{name: "none off a terminal", stdin: "from-stdin\n", err: errNoPassword},
}
for _, testCase := range tests {
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
pipeReader, pipeWriter, err := os.Pipe()
require.NoError(t, err)
defer pipeReader.Close()
_, err = pipeWriter.WriteString(testCase.stdin)
require.NoError(t, errors.Join(err, pipeWriter.Close()))
got, err := keychainPasswordFunc(testCase.flags, pipeReader)(context.Background())
require.ErrorIs(t, err, testCase.err)
assert.Equal(t, testCase.want, got)
})
}
}
// TestKeychainPasswordFlagsAreExclusive covers the root command too, which runs dump with dump's flags.
func TestKeychainPasswordFlagsAreExclusive(t *testing.T) {
setHome(t, t.TempDir())
out := t.TempDir()
for _, args := range [][]string{
{"-d", out, "--keychain-pw", "pw", "--keychain-pw-stdin"},
{"dump", "-d", out, "--keychain-pw", "pw", "--keychain-pw-stdin"},
{"dumpkeys", "--keychain-pw", "pw", "--keychain-pw-stdin"},
} {
root := newRootCommand()
root.SetOut(io.Discard)
root.SetErr(io.Discard)
root.SetArgs(args)
assert.ErrorContains(t, root.Execute(), "keychain-pw", args)
}
}
+5 -6
View File
@@ -43,7 +43,7 @@ func newRestoreCommand() *cobra.Command {
}
func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) error {
options, dump, err := app.ValidateRestore(flags)
options, keyFile, err := app.ValidateRestore(flags)
if err != nil {
return err
}
@@ -53,16 +53,15 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e
}
defer closeRestoreData(data)
discovery, keys, err := app.DiscoverRestore(data.Path(), dump, options)
discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options.Target.BrowserName)
if err != nil {
return err
}
if len(discovery.Dirs) == 0 {
log.Warnf("no browsers to restore from the supplied keys and data")
if foundNothing(stderr, discovery, "no browsers to restore from the supplied keys and data") {
return nil
}
options.ImportedKeys = keys
summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options)
summary, err := app.ExecuteWithKeys(ctx, discovery, options.Categories, options.Output, keys)
announceExport(stderr, summary.Exported)
if ctx.Err() == nil {
report(stderr, summary)
}