diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index e137878..b5cfaac 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -56,6 +56,8 @@ func runDump(ctx context.Context, f app.Flags) error { return nil } summary, err := app.Execute(ctx, app.NewPlan(d, req), req) - report(summary) + if ctx.Err() == nil { + report(summary) + } return err } diff --git a/cmd/hack-browser-data/dumpkeys.go b/cmd/hack-browser-data/dumpkeys.go index 5b91eb9..468b102 100644 --- a/cmd/hack-browser-data/dumpkeys.go +++ b/cmd/hack-browser-data/dumpkeys.go @@ -27,7 +27,10 @@ func dumpKeysCmd() *cobra.Command { if err != nil { return err } - dump := app.DumpKeys(cmd.Context(), app.Discover(req), req) + dump, err := app.DumpKeys(cmd.Context(), app.Discover(req), req) + if err != nil { + return err + } log.Infof("Exported keys for %d vault(s)", len(dump.Vaults)) if outputPath == "" { diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index 8e89ffb..3a4bf57 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -1,7 +1,11 @@ package main import ( + "context" + "errors" "os" + "os/signal" + "syscall" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -46,12 +50,60 @@ GitHub: https://github.com/moonD4rk/HackBrowserData`, } }) + for _, c := range root.Commands() { + quietWhenStopped(c) + } + quietWhenStopped(root) return root } +// quietWhenStopped keeps a stopped run's error and usage off the screen; main then ends the process by the signal. +func quietWhenStopped(c *cobra.Command) { + run := c.RunE + if run == nil { + return + } + c.RunE = func(cmd *cobra.Command, args []string) error { + err := run(cmd, args) + if err != nil && cmd.Context().Err() != nil { + cmd.SilenceErrors, cmd.SilenceUsage = true, true + } + return err + } +} + +// 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} + +type stopError struct{ sig os.Signal } + +func (e stopError) Error() string { return "stopped by " + e.sig.String() } + func main() { configureDoubleClickMode() - if err := rootCmd().Execute(); err != nil { + ctx, cancel := context.WithCancelCause(context.Background()) + signals := make(chan os.Signal, 1) + for _, sig := range stopSignals { + if !signal.Ignored(sig) { // nohup and background jobs keep ignoring what they ignore today + signal.Notify(signals, sig) + } + } + go func() { + sig := <-signals + signal.Stop(signals) // a second signal ends the process at once + if sig == os.Interrupt { + log.Warnf("Interrupted; cleaning up (press Ctrl-C again to quit at once)") + } else { + log.Warnf("Stopping; cleaning up") + } + cancel(stopError{sig}) + }() + err := rootCmd().ExecuteContext(ctx) + var stop stopError + if errors.As(context.Cause(ctx), &stop) { + exitBy(stop.sig) + } + if err != nil { os.Exit(1) } } diff --git a/cmd/hack-browser-data/main_others.go b/cmd/hack-browser-data/main_others.go index 61e7611..c60c4aa 100644 --- a/cmd/hack-browser-data/main_others.go +++ b/cmd/hack-browser-data/main_others.go @@ -2,4 +2,20 @@ package main +import ( + "os" + "os/signal" + "syscall" + "time" +) + func configureDoubleClickMode() {} + +// exitBy ends the process by sig itself, as the signal would have, so a calling shell or script sees it was stopped. +func exitBy(sig os.Signal) { + signal.Reset(sig) + if s, ok := sig.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), s) == nil { + time.Sleep(time.Second) // the signal ends the process first unless it was ignored at start + } + os.Exit(1) +} diff --git a/cmd/hack-browser-data/main_others_test.go b/cmd/hack-browser-data/main_others_test.go new file mode 100644 index 0000000..577ac82 --- /dev/null +++ b/cmd/hack-browser-data/main_others_test.go @@ -0,0 +1,20 @@ +//go:build !windows + +package main + +import ( + "os" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) { + t.Helper() + status, ok := ps.Sys().(syscall.WaitStatus) + require.True(t, ok) + assert.True(t, status.Signaled(), "ended by the signal, not by an exit code") + assert.Equal(t, syscall.SIGINT, status.Signal()) +} diff --git a/cmd/hack-browser-data/main_test.go b/cmd/hack-browser-data/main_test.go new file mode 100644 index 0000000..ec2569a --- /dev/null +++ b/cmd/hack-browser-data/main_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "bytes" + "context" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestStoppedRunPrintsNoErrorOrUsage(t *testing.T) { + home := t.TempDir() + setHome(t, home) + chromiumFixtureUserData(t, userDataDirOf(t, home, "chrome"), "chrome") + + for _, tc := range []struct { + name, browser string + stop bool + }{ + {name: "stopped", browser: "chrome", stop: true}, + {name: "failed", browser: "nosuch"}, + } { + tc := tc + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if tc.stop { + cancel() + } + var screen bytes.Buffer + root := rootCmd() + root.SetOut(&screen) + root.SetErr(&screen) + root.SetArgs([]string{"-b", tc.browser, "-d", filepath.Join(t.TempDir(), "results")}) + + err := root.ExecuteContext(ctx) + require.Error(t, err) + if tc.stop { + require.ErrorIs(t, err, context.Canceled) + assert.Empty(t, screen.String()) + } else { + assert.Contains(t, screen.String(), "Error: ") + } + }) + } +} + +func TestExitByEndsTheProcessAsTheSignalWould(t *testing.T) { + if os.Getenv("HBD_TEST_EXIT_BY") == "1" { + exitBy(os.Interrupt) + return + } + cmd := exec.Command(os.Args[0], "-test.run=^TestExitByEndsTheProcessAsTheSignalWould$") + cmd.Env = append(os.Environ(), "HBD_TEST_EXIT_BY=1") + var exitErr *exec.ExitError + require.ErrorAs(t, cmd.Run(), &exitErr) + assertEndedByInterrupt(t, exitErr.ProcessState) +} diff --git a/cmd/hack-browser-data/main_windows.go b/cmd/hack-browser-data/main_windows.go index 7c1dccf..618a82b 100644 --- a/cmd/hack-browser-data/main_windows.go +++ b/cmd/hack-browser-data/main_windows.go @@ -3,8 +3,11 @@ package main import ( + "os" + "github.com/inconshreveable/mousetrap" "github.com/spf13/cobra" + "golang.org/x/sys/windows" "github.com/moond4rk/hackbrowserdata/internal/winapi" ) @@ -19,3 +22,9 @@ func configureDoubleClickMode() { cobra.MousetrapHelpText = "" winapi.HideConsoleWindow() } + +// exitBy ends the process with the status Windows gives a console process that Ctrl-C or closing the console ends. +func exitBy(os.Signal) { + status := uint32(windows.STATUS_CONTROL_C_EXIT) + os.Exit(int(int32(status))) +} diff --git a/cmd/hack-browser-data/main_windows_test.go b/cmd/hack-browser-data/main_windows_test.go new file mode 100644 index 0000000..91a7e83 --- /dev/null +++ b/cmd/hack-browser-data/main_windows_test.go @@ -0,0 +1,16 @@ +//go:build windows + +package main + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" + "golang.org/x/sys/windows" +) + +func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) { + t.Helper() + assert.Equal(t, uint32(windows.STATUS_CONTROL_C_EXIT), uint32(ps.ExitCode())) +} diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index cf50db3..3481c83 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -62,7 +62,9 @@ func runRestore(ctx context.Context, f app.RestoreFlags) error { } req.Keys = keys summary, err := app.Execute(ctx, app.NewPlan(d, req), req) - report(summary) + if ctx.Err() == nil { + report(summary) + } return err } diff --git a/internal/app/execute.go b/internal/app/execute.go index 2ba7d4a..3d89772 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -66,6 +66,9 @@ func (discard) Write(category.Category, []record.Record) error { return nil } func runPlan(ctx context.Context, p Plan, w recordWriter, extractors extractorsFunc, keys keySource, announce bool) (Summary, error) { results := append([]Result(nil), p.Skipped...) for _, dir := range p.Dirs { + if err := ctx.Err(); err != nil { + return Summary{Results: results}, fmt.Errorf("run stopped: %w", err) + } dirResults, err := executeDir(ctx, dir, p, w, extractors, keys, announce) results = append(results, dirResults...) if err != nil { @@ -117,6 +120,9 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr results := make([]Result, 0, len(extractions)+1) for _, e := range extractions { + if err := ctx.Err(); err != nil { + return results, fmt.Errorf("run stopped: %w", err) + } x, ok := byProfile[e.Profile][e.Category] if !ok || x.Extract == nil { results = append(results, Result{Extraction: e, Outcome: OutcomeUnsupported}) diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index bc16b90..7ae9722 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -190,6 +190,33 @@ func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) { } } +func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var copied []string + base := fakeBase(map[category.Category]extractFunc{ + category.History: func(_ context.Context, ps browser.ProfileSnapshot, _ browser.Collector) error { + path, err := ps.Path(history) + require.NoError(t, err) + copied = append(copied, path) + cancel() + return nil + }, + category.Download: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { + t.Error("an extraction ran after the stop") + return nil + }, + }) + req := Request{Categories: []category.Category{category.History, category.Download}, Dir: t.TempDir()} + d := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} + + _, err := execute(ctx, newPlan(d, req, base), req, base, noKeys(t)) + require.ErrorIs(t, err, context.Canceled) + require.Len(t, copied, 1, "the next user data dir is never captured") + _, statErr := os.Stat(copied[0]) + assert.ErrorIs(t, statErr, fs.ErrNotExist) +} + func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { if runtime.GOOS == "windows" || os.Geteuid() == 0 { t.Skip("directory permissions do not deny writes here") diff --git a/internal/app/keys.go b/internal/app/keys.go index c63e735..bee2600 100644 --- a/internal/app/keys.go +++ b/internal/app/keys.go @@ -2,6 +2,7 @@ package app import ( "context" + "fmt" "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" @@ -12,17 +13,21 @@ import ( // 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. -func DumpKeys(ctx context.Context, d Discovery, req Request) masterkey.Dump { +// 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))) } -func dumpKeysWith(ctx context.Context, d Discovery, keys keySource) masterkey.Dump { +func dumpKeysWith(ctx context.Context, d Discovery, keys keySource) (masterkey.Dump, error) { dump := masterkey.NewDump() for _, dir := range d.Dirs { if dir.Def.Base != browser.Chromium { continue } set, err := retrieveKeys(ctx, dir, keys) + if ctxErr := ctx.Err(); ctxErr != nil { + return masterkey.Dump{}, fmt.Errorf("run stopped: %w", ctxErr) + } if err != nil { status := "partial" if len(set) == 0 { @@ -45,7 +50,7 @@ func dumpKeysWith(ctx context.Context, d Discovery, keys keySource) masterkey.Du } dump.Vaults = append(dump.Vaults, v) } - return dump + return dump, nil } func retrieveKeys(ctx context.Context, dir browser.UserDataDir, keys keySource) (masterkey.Set, error) { diff --git a/internal/app/keys_test.go b/internal/app/keys_test.go index 5844ea9..9b62dbe 100644 --- a/internal/app/keys_test.go +++ b/internal/app/keys_test.go @@ -41,7 +41,8 @@ func TestDumpKeys(t *testing.T) { return masterkey.Set{masterkey.V10: []byte(dir.ID)}, nil } d := Discovery{Dirs: []browser.UserDataDir{chrome, firefox, arc2, opera, vivaldi, brave}} - dump := dumpKeysWith(context.Background(), d, keys) + dump, err := dumpKeysWith(context.Background(), d, keys) + require.NoError(t, err) assert.Equal(t, []masterkey.Vault{ { @@ -62,3 +63,19 @@ func TestDumpKeys(t *testing.T) { }, }, dump.Vaults, "a failed dir is left out, a partly failed one keeps what it has") } + +func TestDumpKeys_StoppedRunReturnsNoDump(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + chrome, brave := chromeDir(t, "chrome", "Default"), dirOf(t, "brave", "brave") + touch(t, chrome.Path, "Local State") + keys := func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) { + require.Equal(t, browser.DirID("chrome"), dir.ID, "keys were retrieved after the stop") + cancel() + return masterkey.Set{masterkey.V10: []byte("chrome")}, nil + } + + dump, err := dumpKeysWith(ctx, Discovery{Dirs: []browser.UserDataDir{chrome, brave}}, keys) + require.ErrorIs(t, err, context.Canceled) + assert.Empty(t, dump.Vaults) +} diff --git a/internal/app/password.go b/internal/app/password.go index 9758d8f..ca3a94b 100644 --- a/internal/app/password.go +++ b/internal/app/password.go @@ -24,9 +24,11 @@ func keychainPassword(f Flags, stdin *os.File) (func(context.Context) (string, e password := f.KeychainPassword return func(context.Context) (string, error) { return password, nil }, nil case f.KeychainPasswordStdin: - return func(context.Context) (string, error) { return firstLine(stdin) }, nil + return func(ctx context.Context) (string, error) { + return untilDone(ctx, func() (string, error) { return firstLine(stdin) }) + }, nil case term.IsTerminal(int(stdin.Fd())): - return func(context.Context) (string, error) { return prompt(stdin) }, nil + return func(ctx context.Context) (string, error) { return prompt(ctx, stdin) }, nil default: return func(context.Context) (string, error) { return "", errNoPassword }, nil } @@ -40,12 +42,43 @@ func firstLine(r io.Reader) (string, error) { return strings.TrimRight(line, "\r\n"), nil } -func prompt(stdin *os.File) (string, error) { +func prompt(ctx context.Context, stdin *os.File) (string, error) { + fd := int(stdin.Fd()) + state, err := term.GetState(fd) + if err != nil { + return "", fmt.Errorf("read the password: %w", err) + } fmt.Fprint(os.Stderr, "Enter macOS login password: ") - password, err := term.ReadPassword(int(stdin.Fd())) + password, err := untilDone(ctx, func() (string, error) { + p, err := term.ReadPassword(fd) + return string(p), 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(fd, state)) + } fmt.Fprintln(os.Stderr) if err != nil { return "", fmt.Errorf("read the password: %w", err) } - return string(password), nil + 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 a := <-answers: + return a.value, a.err + case <-ctx.Done(): + return "", ctx.Err() + } } diff --git a/rfcs/007-snapshot-and-acquisition.md b/rfcs/007-snapshot-and-acquisition.md index e8db19f..7f836f5 100644 --- a/rfcs/007-snapshot-and-acquisition.md +++ b/rfcs/007-snapshot-and-acquisition.md @@ -42,7 +42,7 @@ func (s Snapshot) Path(rel string) (string, error) // absolute path inside the s `dump` captures one user data dir at a time ([RFC-001](001-architecture-and-pipeline.md)): `Execute` creates a `Temp` snapshot directory for the dir, captures its files, runs its extractions, and `Close`s it before the next dir. At most one user data dir's copies of `Login Data`, `Cookies`, and the like exist at once — close to today's per-profile session, and far from a run-long snapshot directory holding every browser's copies until the end. `archive` captures every user data dir into one snapshot directory, because the zip of that directory is its product. `restore --data-zip` unzips into a `Temp` snapshot directory; `restore --data-dir` `Open`s the given directory, which `Close` leaves in place. -Because it holds those copies, a temporary snapshot directory is created with mode `0700` and always removed — on success, on error, and on cancellation (the run's context is cancelled on Ctrl-C). The live profile still exists, so removing the copy never loses anything. +Because it holds those copies, a temporary snapshot directory is created with mode `0700` and always removed — on success, on error, and on cancellation (the run's context is cancelled on Ctrl-C, `SIGTERM`, or `SIGHUP`; [RFC-009](009-cli-surface.md)). The live profile still exists, so removing the copy never loses anything. ## Layout and user data dir identity diff --git a/rfcs/009-cli-surface.md b/rfcs/009-cli-surface.md index f6e4836..329e8d9 100644 --- a/rfcs/009-cli-surface.md +++ b/rfcs/009-cli-surface.md @@ -67,6 +67,8 @@ There is no environment variable. Every child process the tool starts would inhe After a run, the reporter prints a per-browser, per-profile, per-category summary with each extraction's outcome and count on stderr, after today's "Exported to …" lines. The summary is additive and not part of the contract. `-v` adds record-level debug lines, as today. The exit status is today's: `0` when the run completes, whatever the per-extraction outcomes, and `1` when it cannot start or finish ([RFC-001](001-architecture-and-pipeline.md)). +**Stopping.** Ctrl-C, `SIGTERM`, and `SIGHUP` still end a run, but cleanly: the run stops before its next user data dir, file, or extraction, a waiting keychain prompt returns with the echo back on, the temporary snapshot is removed ([RFC-007](007-snapshot-and-acquisition.md)), and `dumpkeys` writes no `keys.json`. One line replaces the error, usage, and summary, and the process then ends by the same signal (on Windows, with the status Ctrl-C gives), so a calling shell or script sees what it sees today. A second signal ends the process at once, as the first one does today. + ## `restore` specifics (unchanged) `restore`'s universe is its `keys.json`, not the local table: `-b` filters the dump's vaults, and a vault's `Def` is resolved with `browser.Lookup`, which searches the whole table whatever the host OS ([RFC-005](005-browser-definitions.md)), so a Windows-only fork restores on macOS. Exactly one of `--data-dir` and `--data-zip` is required. A zip is extracted into a temporary snapshot directory (`snapshot.Unzip`), rejecting entries that escape it, and removed when the run ends; a `--data-dir` is opened in place (`snapshot.Open`) and never removed ([RFC-007](007-snapshot-and-acquisition.md)). The data has two layouts, as today: `/` subdirectories (the archive layout), from which every selected vault restores, or one browser's hand-copied `User Data`, which is unambiguous only when `-b` selects a single vault. diff --git a/rfcs/011-testing-and-quality.md b/rfcs/011-testing-and-quality.md index 141b154..c63c484 100644 --- a/rfcs/011-testing-and-quality.md +++ b/rfcs/011-testing-and-quality.md @@ -44,6 +44,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so - **Yandex without a key**: logins and cards still export with empty secrets, each a record-level problem, so `list --detail`, which reads no key, counts them as today does. - **Arc multi-dir**: two `arc` user data dirs yield IDs `arc` and `arc-2`, distinct snapshots, and distinct `keys.json` vaults, while overrides and the vaults' `browser` key still use `arc`. - **`--zip` data loss**: a failing zip write leaves every output file in place. +- **Copies left on Ctrl-C**: a stopped run ends before its next extraction and removes its snapshot, `dumpkeys` returns no vaults, the command prints no error or usage, and the process ends by the signal. - **Late flag validation**: `-f bogus` exits `1` with no discovery call and no password resolution (both injected as spies). - **Eager secrets**: `dump -b chrome -c history` never calls `ProfileSnapshot.MasterKeys` and never opens the login keychain: a counting fake `PasswordFunc` stays at zero. - **JSON escaping**: a URL with `&` and `<` is written escaped in `json` and unescaped in `cookie-editor`, as today. diff --git a/rfcs/012-migration-roadmap.md b/rfcs/012-migration-roadmap.md index 85cabef..59c87bf 100644 --- a/rfcs/012-migration-roadmap.md +++ b/rfcs/012-migration-roadmap.md @@ -66,7 +66,7 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou ### Phase 8 — Delete & document - Remove the superseded top-level packages — `browser/`, `crypto/` except the ABE unit's `crypto/windows/`, `filemanager/`, `log/`, `masterkey/`, `output/`, `types/`, and `utils/` except `utils/injector` — once nothing references them. -- Move the compatibility tests out of `cmd/hack-browser-data` into the packages they cover — the export goldens into `export`, `keys.json` into `masterkey`, the archive into `snapshot`, the extract goldens into `browser/chromium`, `browser/firefox`, and `browser/safari`, and `restore` into `app` — each with its goldens in its own `testdata/`; `cmd` keeps only the flag-surface test, and the root `testdata/` goes away. +- Move the compatibility tests out of `cmd/hack-browser-data` into the packages they cover — the export goldens into `export`, `keys.json` into `masterkey`, the archive into `snapshot`, the extract goldens into `browser/chromium`, `browser/firefox`, and `browser/safari`, and `restore` into `app` — each with its goldens in its own `testdata/`; `cmd` keeps the flag-surface and `list` tests, with their goldens in its own `testdata/`, and the root `testdata/` goes away. - Update CLAUDE.md (the new paths), the README (Safari, the `cookie-editor` behavior), and the root help text. - Bring the RFCs to their finished state: the format and technique RFCs (013–021) move from today's type names — `BrowserConfig`, `WindowsABE`, `winutil.Table`, `Hints`, the `Retrievers` struct — to the names in [RFC-004](004-naming-decisions.md); the design RFCs describe the code as it is instead of comparing it with today's; and this roadmap is removed. - Final `go mod tidy` under go@1.20; confirm the `go` directive is still `1.20` and `otiai10/copy` and `mint` are gone.