From e1875f295d7a031f8f27d0f2bbca5a3a7e7043cd Mon Sep 17 00:00:00 2001 From: moonD4rk Date: Sat, 21 Nov 2026 19:08:13 +0800 Subject: [PATCH 1/3] test(cmd): pin help, usage errors and nothing-found paths The next refactor moves every command's entry code. These tests show that what a run prints and leaves behind stays the same. --- cmd/hack-browser-data/cli_test.go | 107 +++++++++++++ cmd/hack-browser-data/testdata/errors.golden | 51 ++++++ cmd/hack-browser-data/testdata/help.golden | 154 +++++++++++++++++++ 3 files changed, 312 insertions(+) create mode 100644 cmd/hack-browser-data/cli_test.go create mode 100644 cmd/hack-browser-data/testdata/errors.golden create mode 100644 cmd/hack-browser-data/testdata/help.golden diff --git a/cmd/hack-browser-data/cli_test.go b/cmd/hack-browser-data/cli_test.go new file mode 100644 index 0000000..885daa2 --- /dev/null +++ b/cmd/hack-browser-data/cli_test.go @@ -0,0 +1,107 @@ +package main + +import ( + "bytes" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/golden" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" +) + +// browsersPlaceholder stands for this OS's browser names, so one golden serves every OS. +const browsersPlaceholder = "" + +func TestHelpGolden(t *testing.T) { + var screens strings.Builder + for _, args := range [][]string{ + {"-h"}, {"dump", "-h"}, {"dumpkeys", "-h"}, {"archive", "-h"}, {"restore", "-h"}, {"list", "-h"}, {"version", "-h"}, + } { + _, screen, err := runRoot(args...) + require.NoError(t, err, args) + screens.WriteString(commandLine(args) + screen) + } + golden.Assert(t, "help.golden", screens.String()) +} + +// TestUsageErrorsGolden puts a marker where a run printed its usage: help.golden pins the wording, this pins when it shows. +func TestUsageErrorsGolden(t *testing.T) { + setHome(t, t.TempDir()) + var screens strings.Builder + for _, args := range [][]string{ + {"-b", "nosuch"}, + {"dump", "-b", "nosuch"}, + {"dump", "-c", "nosuch"}, + {"dump", "-f", "xml"}, + {"dump", "--max-storage-value", "-1"}, + {"dump", "--keychain-pw", "secret", "--keychain-pw-stdin"}, + {"dumpkeys", "-b", "nosuch"}, + {"archive", "-c", "nosuch"}, + {"restore"}, + {"restore", "--keys", "keys.json"}, + {"restore", "--keys", "keys.json", "--data-dir", "data", "--data-zip", "data.zip"}, + {"list", "--nosuch"}, + {"nosuch"}, + } { + root, screen, err := runRoot(args...) + require.Error(t, err, args) + for _, command := range sortedCommands(root) { + usage := strings.ReplaceAll(command.UsageString(), browserNames(), browsersPlaceholder) + screen = strings.Replace(screen, usage, "\n", 1) + } + screens.WriteString(commandLine(args) + screen) + } + golden.Assert(t, "errors.golden", screens.String()) +} + +func TestNothingFound(t *testing.T) { + setHome(t, t.TempDir()) + + t.Run("dump creates no output dir", func(t *testing.T) { + outputDir := filepath.Join(t.TempDir(), "results") + _, _, err := runRoot("dump", "-d", outputDir) + require.NoError(t, err) + assert.NoDirExists(t, outputDir) + }) + + t.Run("archive creates no archive", func(t *testing.T) { + archivePath := filepath.Join(t.TempDir(), "browser-data.zip") + _, _, err := runRoot("archive", "-o", archivePath) + require.NoError(t, err) + assert.NoFileExists(t, archivePath) + }) + + t.Run("list says so", func(t *testing.T) { + _, screen, err := runRoot("list") + require.NoError(t, err) + assert.Equal(t, "No browsers found.\n", screen) + }) + + t.Run("dumpkeys prints a key file without vaults", func(t *testing.T) { + _, screen, err := runRoot("dumpkeys") + require.NoError(t, err) + keyFile, err := masterkey.ReadKeyFile(strings.NewReader(screen)) + require.NoError(t, err) + assert.Empty(t, keyFile.Vaults) + }) +} + +// runRoot returns the root it ran, for its commands' usage texts, and everything the run printed. +func runRoot(args ...string) (*cobra.Command, string, error) { + var screen bytes.Buffer + root := newRootCommand() + root.SetOut(&screen) + root.SetErr(&screen) + root.SetArgs(args) + err := root.Execute() + return root, strings.ReplaceAll(screen.String(), browserNames(), browsersPlaceholder), err +} + +func commandLine(args []string) string { + return "$ hack-browser-data " + strings.Join(args, " ") + "\n" +} diff --git a/cmd/hack-browser-data/testdata/errors.golden b/cmd/hack-browser-data/testdata/errors.golden new file mode 100644 index 0000000..1720883 --- /dev/null +++ b/cmd/hack-browser-data/testdata/errors.golden @@ -0,0 +1,51 @@ +$ hack-browser-data -b nosuch +Error: unknown browser "nosuch", available: all| + + +$ hack-browser-data dump -b nosuch +Error: unknown browser "nosuch", available: all| + + +$ hack-browser-data dump -c nosuch +Error: unknown category: "nosuch", available: all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage + + +$ hack-browser-data dump -f xml +Error: unsupported format: xml + + +$ hack-browser-data dump --max-storage-value -1 +Error: --max-storage-value must be >= 0 (0 means unlimited), got -1 + + +$ hack-browser-data dump --keychain-pw secret --keychain-pw-stdin +Error: if any flags in the group [keychain-pw keychain-pw-stdin] are set none of the others can be; [keychain-pw keychain-pw-stdin] were all set + + +$ hack-browser-data dumpkeys -b nosuch +Error: unknown browser "nosuch", available: all| + + +$ hack-browser-data archive -c nosuch +Error: unknown category: "nosuch", available: all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage + + +$ hack-browser-data restore +Error: required flag(s) "keys" not set + + +$ hack-browser-data restore --keys keys.json +Error: exactly one of --data-dir or --data-zip is required + + +$ hack-browser-data restore --keys keys.json --data-dir data --data-zip data.zip +Error: if any flags in the group [data-dir data-zip] are set none of the others can be; [data-dir data-zip] were all set + + +$ hack-browser-data list --nosuch +Error: unknown flag: --nosuch + + +$ hack-browser-data nosuch +Error: unknown command "nosuch" for "hack-browser-data" +Run 'hack-browser-data --help' for usage. diff --git a/cmd/hack-browser-data/testdata/help.golden b/cmd/hack-browser-data/testdata/help.golden new file mode 100644 index 0000000..3429129 --- /dev/null +++ b/cmd/hack-browser-data/testdata/help.golden @@ -0,0 +1,154 @@ +$ hack-browser-data -h +hack-browser-data decrypts and exports browser data from Chromium-based +browsers, Firefox, and Safari on Windows, macOS, and Linux. + +GitHub: https://github.com/moonD4rk/HackBrowserData + +Usage: + hack-browser-data [flags] + hack-browser-data [command] + +Available Commands: + archive Pack decryption-relevant profile files into a zip for cross-host restore + dump Extract and decrypt browser data (default command) + dumpkeys Export Chromium master keys as JSON for cross-host decryption + help Help about any command + list List detected browsers and profiles + restore Decrypt copied profile data using exported master keys + version Print version information + +Flags: + -b, --browser string target browser: all| (default "all") + -c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all") + -d, --dir string output directory (default "results") + --firefox-pw string Firefox primary password (visible in ps and shell history) + --firefox-pw-stdin[=true|false] read the Firefox primary password from the first line of stdin + -f, --format string output format: csv|json|cookie-editor (default "json") + -h, --help[=true|false] help for hack-browser-data + --keychain-pw string macOS keychain password (visible in ps and shell history) + --keychain-pw-stdin[=true|false] read the macOS keychain password from the first line of stdin + --max-storage-value int max storage value chars, 0=unlimited (default 2048) + -p, --profile-path string custom profile dir path, get with chrome://version + -v, --verbose[=true|false] enable debug logging + --zip[=true|false] compress output to zip + +Use "hack-browser-data [command] --help" for more information about a command. +$ hack-browser-data dump -h +Extract and decrypt browser data (default command) + +Usage: + hack-browser-data dump [flags] + +Examples: + hack-browser-data dump + hack-browser-data dump -b chrome -c password,cookie + hack-browser-data dump -b chrome -f json -d output + hack-browser-data dump -f cookie-editor + hack-browser-data dump --zip + +Flags: + -b, --browser string target browser: all| (default "all") + -c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all") + -d, --dir string output directory (default "results") + --firefox-pw string Firefox primary password (visible in ps and shell history) + --firefox-pw-stdin[=true|false] read the Firefox primary password from the first line of stdin + -f, --format string output format: csv|json|cookie-editor (default "json") + -h, --help[=true|false] help for dump + --keychain-pw string macOS keychain password (visible in ps and shell history) + --keychain-pw-stdin[=true|false] read the macOS keychain password from the first line of stdin + --max-storage-value int max storage value chars, 0=unlimited (default 2048) + -p, --profile-path string custom profile dir path, get with chrome://version + --zip[=true|false] compress output to zip + +Global Flags: + -v, --verbose[=true|false] enable debug logging +$ hack-browser-data dumpkeys -h +Export Chromium master keys as JSON for cross-host decryption + +Usage: + hack-browser-data dumpkeys [flags] + +Examples: + hack-browser-data dumpkeys -o keys.json + hack-browser-data dumpkeys -b chrome + +Flags: + -b, --browser string target browser: all| (default "all") + -h, --help[=true|false] help for dumpkeys + --keychain-pw string macOS keychain password (visible in ps and shell history) + --keychain-pw-stdin[=true|false] read the macOS keychain password from the first line of stdin + -o, --output string output file (default: stdout) + +Global Flags: + -v, --verbose[=true|false] enable debug logging +$ hack-browser-data archive -h +Pack decryption-relevant profile files into a zip for cross-host restore + +Usage: + hack-browser-data archive [flags] + +Examples: + hack-browser-data archive + hack-browser-data archive -b chrome -c cookie -o chrome-cookies.zip + +Flags: + -b, --browser string target browser: all| (default "all") + -c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all") + -h, --help[=true|false] help for archive + -o, --output string output archive of decryption-relevant browser files (default "browser-data.zip") + +Global Flags: + -v, --verbose[=true|false] enable debug logging +$ hack-browser-data restore -h +Decrypt copied profile data using exported master keys + +Usage: + hack-browser-data restore [flags] + +Examples: + hack-browser-data restore --keys keys.json --data-zip data.zip + hack-browser-data restore --keys keys.json --data-dir ./data -b chrome -c cookie + hack-browser-data restore --keys keys.json --data-dir ./chrome-userdata -b chrome + ssh origin "hack-browser-data dumpkeys" | hack-browser-data restore --keys - --data-zip data.zip + +Flags: + -b, --browser string restore only this browser (optional; must match a vault in --keys) + -c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all") + --data-dir string copied profile data dir (archive layout, or one browser's User Data with -b) + --data-zip string zip produced by the archive command (alternative to --data-dir) + -d, --dir string output directory (default "results") + -f, --format string output format: csv|json|cookie-editor (default "json") + -h, --help[=true|false] help for restore + --keys string keys file from dumpkeys (use - for stdin) + --max-storage-value int max storage value chars, 0=unlimited (default 2048) + --zip[=true|false] compress output to zip + +Global Flags: + -v, --verbose[=true|false] enable debug logging +$ hack-browser-data list -h +List detected browsers and profiles + +Usage: + hack-browser-data list [flags] + +Examples: + hack-browser-data list + hack-browser-data list --detail + +Flags: + --detail[=true|false] show per-category entry counts + -h, --help[=true|false] help for list + +Global Flags: + -v, --verbose[=true|false] enable debug logging +$ hack-browser-data version -h +Print version information + +Usage: + hack-browser-data version [flags] + +Flags: + -h, --help[=true|false] help for version + +Global Flags: + -v, --verbose[=true|false] enable debug logging From b7c3345ad577d17186494c621efa46377d381691 Mon Sep 17 00:00:00 2001 From: moonD4rk Date: Sat, 21 Nov 2026 19:08:30 +0800 Subject: [PATCH 2/3] refactor: rename path fields, snapshot.NewRoot and printers A field named for a thing now holds the thing itself and Path means an absolute path, so a default location, a found user data dir and a relative path no longer share a name. --- cmd/hack-browser-data/dump.go | 4 +- cmd/hack-browser-data/list_test.go | 2 +- cmd/hack-browser-data/report.go | 10 +- cmd/hack-browser-data/report_test.go | 4 +- cmd/hack-browser-data/restore.go | 4 +- internal/app/archive.go | 2 +- internal/app/archive_golden_test.go | 2 +- internal/app/discover_test.go | 4 +- internal/app/dump.go | 4 +- internal/app/dump_test.go | 2 +- internal/app/dumpkeys.go | 4 +- internal/app/execute.go | 11 +- internal/app/execute_test.go | 14 +- internal/app/extract_golden_test.go | 4 +- internal/app/options.go | 16 +-- internal/app/restore.go | 4 +- internal/app/restore_golden_test.go | 2 +- internal/browser/browser.go | 6 +- internal/browser/browser_test.go | 2 +- internal/browser/chromium/chromium.go | 10 +- internal/browser/chromium/extractors.go | 26 ++-- internal/browser/chromium/extractors_test.go | 4 +- internal/browser/chromium/override_test.go | 2 +- internal/browser/chromium/testutil_test.go | 2 +- internal/browser/extractor.go | 22 +-- internal/browser/extractor_test.go | 18 +-- internal/browser/firefox/firefox.go | 18 +-- internal/browser/firefox/firefox_test.go | 2 +- internal/browser/safari/profiles.go | 2 +- internal/browser/safari/profiles_test.go | 2 +- internal/browser/safari/safari.go | 28 ++-- internal/browser/safari/safari_test.go | 2 +- internal/browser/table.go | 134 +++++++++---------- internal/browser/table_test.go | 2 +- internal/export/writer.go | 8 +- internal/snapshot/snapshot.go | 6 +- internal/snapshot/snapshot_test.go | 14 +- internal/zipfile/zipfile.go | 6 +- 38 files changed, 206 insertions(+), 203 deletions(-) diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index 1a82421..fba801b 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -54,9 +54,9 @@ func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychai return nil } summary, err := app.Execute(ctx, discovery, options.Categories, options.Output, options.Keychain, options.FirefoxPassword) - announceExport(stderr, summary.Exported) + printExported(stderr, summary.Exported) if ctx.Err() == nil { - report(stderr, summary) + printSummary(stderr, summary) } return err } diff --git a/cmd/hack-browser-data/list_test.go b/cmd/hack-browser-data/list_test.go index cf291e6..ed01d16 100644 --- a/cmd/hack-browser-data/list_test.go +++ b/cmd/hack-browser-data/list_test.go @@ -60,5 +60,5 @@ func userDataDirOf(t *testing.T, home, browserName string) string { t.Helper() namedBrowser, ok := browser.Lookup(browserName) require.True(t, ok, browserName) - return filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])) + return filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])) } diff --git a/cmd/hack-browser-data/report.go b/cmd/hack-browser-data/report.go index 60d35c2..2d10fb3 100644 --- a/cmd/hack-browser-data/report.go +++ b/cmd/hack-browser-data/report.go @@ -12,8 +12,8 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) -// report prints the run's summary; it is not part of the output, so failing to print it never fails the run. -func report(stderr io.Writer, summary app.Summary) { +// printSummary is not part of the output, so failing to print it never fails the run. +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 { @@ -45,14 +45,14 @@ func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message strin return false } if len(discovery.DirFailures) > 0 { - report(stderr, app.Summary{DirFailures: discovery.DirFailures}) + printSummary(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.Listing) { +// 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) { if len(exported.Files) == 0 { return } diff --git a/cmd/hack-browser-data/report_test.go b/cmd/hack-browser-data/report_test.go index eaee0b9..8fa20e4 100644 --- a/cmd/hack-browser-data/report_test.go +++ b/cmd/hack-browser-data/report_test.go @@ -13,10 +13,10 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/category" ) -func TestReport(t *testing.T) { +func TestPrintSummary(t *testing.T) { cookie := app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie} var buffer bytes.Buffer - report(&buffer, app.Summary{ + printSummary(&buffer, app.Summary{ Results: []app.Result{ {Extraction: cookie, Outcome: app.OutcomePartial, Records: 224, Failures: 4}, { diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 84ac9ab..d0e127b 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -63,9 +63,9 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e return nil } summary, err := app.ExecuteWithKeys(ctx, discovery, options.Categories, options.Output, keys) - announceExport(stderr, summary.Exported) + printExported(stderr, summary.Exported) if ctx.Err() == nil { - report(stderr, summary) + printSummary(stderr, summary) } return err } diff --git a/internal/app/archive.go b/internal/app/archive.go index e0e6c6f..079142f 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -50,7 +50,7 @@ func Archive(ctx context.Context, discovery Discovery, categories []category.Cat } files := archiveFiles(dirs, categories) - root, err := snapshot.Temp() + root, err := snapshot.NewRoot() if err != nil { return 0, err } diff --git a/internal/app/archive_golden_test.go b/internal/app/archive_golden_test.go index c00197f..d764871 100644 --- a/internal/app/archive_golden_test.go +++ b/internal/app/archive_golden_test.go @@ -80,7 +80,7 @@ func TestArchiveGolden(t *testing.T) { home := t.TempDir() namedBrowser, ok := browser.Lookup(archiveLayoutBrowser) require.True(t, ok) - archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0]))) + archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0]))) tests := []struct { name string diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index 16e7fc5..4ea43ab 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -16,8 +16,8 @@ import ( func writeUserDataDir(t *testing.T, home, browserName string) string { t.Helper() namedBrowser := lookup(t, browserName) - require.NotEmpty(t, namedBrowser.Platform().UserDataDirs, browserName) - path := filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])) + require.NotEmpty(t, namedBrowser.Platform().UserDataDirPaths, browserName) + path := filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])) touch(t, path, "Default", "Preferences") touch(t, path, "Default", "History") return path diff --git a/internal/app/dump.go b/internal/app/dump.go index 113a462..482ae5c 100644 --- a/internal/app/dump.go +++ b/internal/app/dump.go @@ -25,7 +25,7 @@ type DumpFlags struct { type DumpOptions struct { Target Target Categories []category.Category - Output Output + Output OutputOptions Keychain KeychainConfig FirefoxPassword func(ctx context.Context) (string, error) // nil is the empty password; Execute reads it at most once } @@ -61,7 +61,7 @@ func ValidateDump(flags DumpFlags, keychainPassword, firefoxPassword func(contex return DumpOptions{ Target: Target{Browsers: browsers, ProfilePath: profilePath, HomeDir: home}, Categories: categories, - Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue}, + Output: OutputOptions{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue}, Keychain: KeychainConfig{Path: loginKeychainPath(home), Password: keychainPassword}, FirefoxPassword: firefoxPassword, }, nil diff --git a/internal/app/dump_test.go b/internal/app/dump_test.go index a386c7b..3ed6fc1 100644 --- a/internal/app/dump_test.go +++ b/internal/app/dump_test.go @@ -67,7 +67,7 @@ func otherOSBrowser(t *testing.T) string { for _, name := range []string{"sogou", "safari"} { namedBrowser, ok := browser.Lookup(name) require.True(t, ok, name) - if len(namedBrowser.Platform().UserDataDirs) == 0 { + if len(namedBrowser.Platform().UserDataDirPaths) == 0 { return name } } diff --git a/internal/app/dumpkeys.go b/internal/app/dumpkeys.go index 200ad3e..6925154 100644 --- a/internal/app/dumpkeys.go +++ b/internal/app/dumpkeys.go @@ -100,14 +100,14 @@ func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (m } func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysFunc) (masterkey.Set, error) { - root, err := snapshot.Temp() + root, err := snapshot.NewRoot() if err != nil { return nil, err } defer closeRoot(root) var files []snapshot.File for _, source := range chromium.KeySources() { - if file, ok, err := firstOnDisk(dir, source.Paths(), source.IsDir); err == nil && ok { + if file, ok, err := firstOnDisk(dir, source.RelativePaths(), source.IsDir); err == nil && ok { files = append(files, file) } } diff --git a/internal/app/execute.go b/internal/app/execute.go index 726df5d..070f9de 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -19,7 +19,7 @@ import ( // dir's copies are on disk. Its error means the run ended early; like os.ReadDir, it still returns the Summary of what // ran before it, with the files written, so the caller can list them. func Execute( - ctx context.Context, discovery Discovery, categories []category.Category, output Output, keychainConfig KeychainConfig, + ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions, keychainConfig KeychainConfig, firefoxPassword func(context.Context) (string, error), ) (Summary, error) { keychain := newLoginKeychain(keychainConfig) @@ -46,13 +46,16 @@ func readOnce(read func(context.Context) (string, error)) func(context.Context) // ExecuteWithKeys decrypts with a key file's keys, so it never reads this machine's secret stores. func ExecuteWithKeys( - ctx context.Context, discovery Discovery, categories []category.Category, output Output, keys map[browser.UserDataDirID]masterkey.Set, + ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions, + keys map[browser.UserDataDirID]masterkey.Set, ) (Summary, error) { return execute(ctx, discovery, categories, output, runner{extractors: extractorsFor, retrieveKeys: keysFromFile(keys)}) } // execute gives the runner the run's writer; the caller sets where its extractors, keys, and keychain come from. -func execute(ctx context.Context, discovery Discovery, categories []category.Category, output Output, dirRunner runner) (Summary, error) { +func execute( + ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions, dirRunner runner, +) (Summary, error) { writer, err := export.NewWriter(output.Dir, output.Format, output.Zip) if err != nil { return Summary{}, err @@ -106,7 +109,7 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories log.Infof("Extracting %s...", dir.Browser.DisplayName) } - root, err := snapshot.Temp() + root, err := snapshot.NewRoot() if err != nil { summary.Results = append(summary.Results, failAll(plan.extractions, err)...) return summary, nil diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index 0e2a103..33c1510 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -22,7 +22,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -var history = browser.Source{Path: "History"} +var history = browser.Source{RelativePath: "History"} type extractFunc func(ctx context.Context, input browser.Input, out browser.Collector) error @@ -56,7 +56,7 @@ func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) brows func run(t *testing.T, base extractorsFunc, keys dirKeysFunc, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { t.Helper() - output := Output{Dir: t.TempDir()} + output := OutputOptions{Dir: t.TempDir()} summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, runner{extractors: base, retrieveKeys: keys}) require.NoError(t, err) return summary, output.Dir @@ -136,7 +136,7 @@ func TestExecute_ReportsEachDirWhatNeverRanFirst(t *testing.T) { categories := []category.Category{category.Password, category.History} discovery := Discovery{Dirs: []browser.UserDataDir{chrome, brave}, DirFailures: []DirFailure{failed}} - summary, err := execute(context.Background(), discovery, categories, Output{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)}) + summary, err := execute(context.Background(), discovery, categories, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)}) require.NoError(t, err) assert.Equal(t, []DirFailure{failed}, summary.DirFailures, "discovery's failures are reported with the run's") var got []string @@ -233,7 +233,7 @@ func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testi categories := []category.Category{category.History, category.Download} discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} - _, err := execute(ctx, discovery, categories, Output{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)}) + _, err := execute(ctx, discovery, categories, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: 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]) @@ -258,7 +258,7 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { return nil }, }) - output := Output{Dir: t.TempDir()} + output := OutputOptions{Dir: t.TempDir()} require.NoError(t, os.Chmod(output.Dir, 0o500)) defer func() { require.NoError(t, os.Chmod(output.Dir, 0o700)) }() @@ -275,7 +275,7 @@ func TestExecute_FirefoxPasswordReadOnce(t *testing.T) { home := t.TempDir() firefoxBrowser, ok := browser.Lookup("firefox") require.True(t, ok) - profilesDir := filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirs[0])) + profilesDir := filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirPaths[0])) globalSalt, masterKey := bytes.Repeat([]byte("16-byte-salt-abc"), 3), []byte("firefox-pw-master-key-24") for _, profile := range []string{"a.default", "b.work"} { browsertest.WriteFirefoxPrimaryPasswordProfile(t, filepath.Join(profilesDir, profile), globalSalt, []byte("hunter2"), [][]byte{masterKey}) @@ -287,7 +287,7 @@ func TestExecute_FirefoxPasswordReadOnce(t *testing.T) { } discovery := Discover(context.Background(), Target{Browsers: []browser.Browser{firefoxBrowser}, HomeDir: home}) - summary, err := Execute(context.Background(), discovery, []category.Category{category.Password}, Output{Dir: t.TempDir()}, KeychainConfig{}, password) + summary, err := Execute(context.Background(), discovery, []category.Category{category.Password}, OutputOptions{Dir: t.TempDir()}, KeychainConfig{}, password) require.NoError(t, err) require.Len(t, summary.Results, 2) for _, result := range summary.Results { diff --git a/internal/app/extract_golden_test.go b/internal/app/extract_golden_test.go index c0f44a9..d3dd69b 100644 --- a/internal/app/extract_golden_test.go +++ b/internal/app/extract_golden_test.go @@ -24,7 +24,7 @@ func TestExtractGolden(t *testing.T) { namedBrowser, ok := browser.Lookup(fixture.Name) require.True(t, ok, fixture.Name) require.Equal(t, fixture.DisplayName, namedBrowser.DisplayName, "records carry the table's display name") - browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name) + browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])), fixture.Name) keys[browser.UserDataDirID(fixture.Name)] = browsertest.ChromiumKeys } @@ -37,7 +37,7 @@ func TestExtractGoldenFirefox(t *testing.T) { home := t.TempDir() firefoxBrowser, ok := browser.Lookup("firefox") require.True(t, ok) - browsertest.WriteFirefoxUserDataDir(t, filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirs[0]))) + browsertest.WriteFirefoxUserDataDir(t, filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirPaths[0]))) assertExtractGoldens(t, "extract-firefox", func(t *testing.T, format string) string { return extractGoldenRun(t, home, nil, format) diff --git a/internal/app/options.go b/internal/app/options.go index b924174..fd4e150 100644 --- a/internal/app/options.go +++ b/internal/app/options.go @@ -21,8 +21,8 @@ type Target struct { HomeDir string } -// Output is where and how Execute writes records. -type Output struct { +// OutputOptions is where and how Execute writes records. +type OutputOptions struct { Dir string Format export.Format Zip bool @@ -99,24 +99,24 @@ func parseCategories(value string) ([]category.Category, error) { } // 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) +func checkOutputDir(outputDir string) error { + path := filepath.Clean(outputDir) for { info, err := os.Stat(path) switch { case err == nil && info.IsDir(): if err := canCreateIn(path); err != nil { - return fmt.Errorf("output dir %s: %w", dir, err) + return fmt.Errorf("output dir %s: %w", outputDir, err) } return nil case err == nil: - return fmt.Errorf("output dir %s: %s is not a directory", dir, path) + return fmt.Errorf("output dir %s: %s is not a directory", outputDir, path) case !errors.Is(err, fs.ErrNotExist): - return fmt.Errorf("output dir %s: %w", dir, err) + return fmt.Errorf("output dir %s: %w", outputDir, err) } parent := filepath.Dir(path) if parent == path { - return fmt.Errorf("output dir %s: no existing parent directory", dir) + return fmt.Errorf("output dir %s: no existing parent directory", outputDir) } path = parent } diff --git a/internal/app/restore.go b/internal/app/restore.go index 9b9e281..d7dfc37 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -32,7 +32,7 @@ type RestoreFlags struct { type RestoreOptions struct { Vaults []masterkey.Vault // the key file's vaults that -b selects Categories []category.Category - Output Output + Output OutputOptions } // ValidateRestore checks restore's flags and reads its keys, from stdin for "-", before any data is opened. A restore's @@ -72,7 +72,7 @@ func ValidateRestore(flags RestoreFlags, stdin io.Reader) (RestoreOptions, error return RestoreOptions{ Vaults: vaults, Categories: categories, - Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue}, + Output: OutputOptions{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue}, }, nil } diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index 1cd0339..aec46ca 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -65,7 +65,7 @@ func TestArchiveRestoreRoundTrip(t *testing.T) { for _, fixture := range browsertest.ChromiumUserDataDirs { namedBrowser, ok := browser.Lookup(fixture.Name) require.True(t, ok, fixture.Name) - browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name) + browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])), fixture.Name) } options, err := app.ValidateArchive(app.ArchiveFlags{Browser: "all", Categories: "all"}) require.NoError(t, err) diff --git a/internal/browser/browser.go b/internal/browser/browser.go index 7e51eda..7701ead 100644 --- a/internal/browser/browser.go +++ b/internal/browser/browser.go @@ -28,9 +28,9 @@ const ( Safari ) -// Platform is one OS's half of a Browser; one without UserDataDirs means the browser is not supported there. +// Platform is one OS's half of a Browser; one without UserDataDirPaths means the browser is not supported there. type Platform struct { - UserDataDirs []string // slash-separated, relative to the home directory; globs allowed + UserDataDirPaths []string // slash-separated, relative to the home directory; globs allowed SecretLabel string // macOS Keychain account / Linux Secret Service label; "" = none PortalAppID string // Linux: the app id whose XDG portal secret decrypts v12 values; "" = none Executable string // Windows: the program the ABE payload is injected into @@ -42,7 +42,7 @@ type Platform struct { func Supported() []Browser { var out []Browser for _, browser := range browsers { - if len(browser.Platform().UserDataDirs) > 0 { + if len(browser.Platform().UserDataDirPaths) > 0 { out = append(out, browser) } } diff --git a/internal/browser/browser_test.go b/internal/browser/browser_test.go index e7fc8ff..dfb22b2 100644 --- a/internal/browser/browser_test.go +++ b/internal/browser/browser_test.go @@ -17,7 +17,7 @@ var platformOf = map[string]func(Browser) Platform{ func namesOn(platform func(Browser) Platform) []string { var names []string for _, browser := range browsers { - if len(platform(browser).UserDataDirs) > 0 { + if len(platform(browser).UserDataDirPaths) > 0 { names = append(names, browser.Name) } } diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index 977b927..5bd1a94 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -58,7 +58,7 @@ func DiscoverAt(chromiumBrowser browser.Browser, vaultKind string, id browser.Us // profileAt takes chrome://version's path: a profile dir without Local State selects that profile of its parent. func profileAt(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) { - if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.Paths()) { + if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.RelativePaths()) { return browser.UserDataDir{}, false } clean := filepath.Clean(path) @@ -80,7 +80,7 @@ func userDataDirPaths(chromiumBrowser browser.Browser, options browser.DiscoverO paths []string errs []error ) - for _, relativePath := range chromiumBrowser.Platform().UserDataDirs { + for _, relativePath := range chromiumBrowser.Platform().UserDataDirPaths { matches, err := filepath.Glob(options.HomeDir + "/" + relativePath) if err != nil { errs = append(errs, fmt.Errorf("user data dir %q: %w", relativePath, err)) @@ -144,7 +144,7 @@ func profileFilePaths(dir browser.UserDataDir) []string { for _, extractor := range kindExtractors(vaultKindOf(dir)) { for _, source := range extractor.Sources { if !source.Shared { - paths = append(paths, source.Paths()...) + paths = append(paths, source.RelativePaths()...) } } } @@ -167,7 +167,7 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk SecretLabel: platform.SecretLabel, Executable: platform.Executable, ExecutableFallbacks: platform.ExecutableFallbacks, ABE: platform.ABE, PortalAppID: portalAppID(dir.Path, platform.PortalAppID), } - path, err := dirSnapshot.Path(localState.Path) + path, err := dirSnapshot.Path(localState.RelativePath) switch { case err == nil: locator.LocalState = path @@ -205,7 +205,7 @@ func KeySources() []browser.Source { func ArchiveSources() []browser.Source { sources := KeySources() for _, marker := range profileMarkers { - sources = append(sources, browser.Source{Path: marker, Optional: true}) + sources = append(sources, browser.Source{RelativePath: marker, Optional: true}) } return sources } diff --git a/internal/browser/chromium/extractors.go b/internal/browser/chromium/extractors.go index d98149e..66ce876 100644 --- a/internal/browser/chromium/extractors.go +++ b/internal/browser/chromium/extractors.go @@ -11,19 +11,19 @@ import ( ) var ( - localState = browser.Source{Path: "Local State", Shared: true, Optional: true} - loginData = browser.Source{Path: "Login Data", Optional: true} - loginDataForAccount = browser.Source{Path: accountLoginData, Optional: true} - cookies = browser.Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}} - bookmarks = browser.Source{Path: "Bookmarks"} - history = browser.Source{Path: "History"} - webData = browser.Source{Path: "Web Data"} - securePreferences = browser.Source{Path: "Secure Preferences"} - preferences = browser.Source{Path: "Preferences", Optional: true} - localStorage = browser.Source{Path: "Local Storage/leveldb", IsDir: true} - sessionStorage = browser.Source{Path: "Session Storage", IsDir: true} - yaPassmanData = browser.Source{Path: "Ya Passman Data"} - yaCreditCards = browser.Source{Path: "Ya Credit Cards"} + localState = browser.Source{RelativePath: "Local State", Shared: true, Optional: true} + loginData = browser.Source{RelativePath: "Login Data", Optional: true} + loginDataForAccount = browser.Source{RelativePath: accountLoginData, Optional: true} + cookies = browser.Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}} + bookmarks = browser.Source{RelativePath: "Bookmarks"} + history = browser.Source{RelativePath: "History"} + webData = browser.Source{RelativePath: "Web Data"} + securePreferences = browser.Source{RelativePath: "Secure Preferences"} + preferences = browser.Source{RelativePath: "Preferences", Optional: true} + localStorage = browser.Source{RelativePath: "Local Storage/leveldb", IsDir: true} + sessionStorage = browser.Source{RelativePath: "Session Storage", IsDir: true} + yaPassmanData = browser.Source{RelativePath: "Ya Passman Data"} + yaCreditCards = browser.Source{RelativePath: "Ya Credit Cards"} ) var defaultExtractors = browser.Extractors{ diff --git a/internal/browser/chromium/extractors_test.go b/internal/browser/chromium/extractors_test.go index 4491b30..8b6687a 100644 --- a/internal/browser/chromium/extractors_test.go +++ b/internal/browser/chromium/extractors_test.go @@ -27,8 +27,8 @@ func TestExtractors_OverridesFollowTheBrowserNotTheDirectory(t *testing.T) { yandex, ok := browser.Lookup("yandex") require.True(t, ok) extractors := Extractors(browser.UserDataDir{ID: "yandex-2", Browser: yandex}, browser.Profile{}) - assert.Equal(t, "Ya Passman Data", extractors[category.Password].Sources[0].Path) - assert.Equal(t, "Ya Credit Cards", extractors[category.CreditCard].Sources[0].Path) + assert.Equal(t, "Ya Passman Data", extractors[category.Password].Sources[0].RelativePath) + assert.Equal(t, "Ya Credit Cards", extractors[category.CreditCard].Sources[0].RelativePath) } // TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files. diff --git a/internal/browser/chromium/override_test.go b/internal/browser/chromium/override_test.go index 96e1eb9..131a6a9 100644 --- a/internal/browser/chromium/override_test.go +++ b/internal/browser/chromium/override_test.go @@ -60,7 +60,7 @@ func TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) { dir, err := DiscoverAt(nightly, "chromium-yandex", "nightly", t.TempDir()) require.NoError(t, err) assert.Equal(t, nightly, dir.Browser) - assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].Path) + assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].RelativePath) _, err = DiscoverAt(nightly, "bogus", "nightly", t.TempDir()) require.Error(t, err) diff --git a/internal/browser/chromium/testutil_test.go b/internal/browser/chromium/testutil_test.go index 0d5aeaf..8467e31 100644 --- a/internal/browser/chromium/testutil_test.go +++ b/internal/browser/chromium/testutil_test.go @@ -184,7 +184,7 @@ func insertCreditCard(name string, month, year int, encNumberHex, nickName, addr } func testBrowser(name string, userDataDirs ...string) browser.Browser { - platform := browser.Platform{UserDataDirs: userDataDirs, SecretLabel: "Test Safe Storage"} + platform := browser.Platform{UserDataDirPaths: userDataDirs, SecretLabel: "Test Safe Storage"} return browser.Browser{Name: name, DisplayName: name, Base: browser.Chromium, Darwin: platform, Linux: platform, Windows: platform} } diff --git a/internal/browser/extractor.go b/internal/browser/extractor.go index 447adf4..3c64b12 100644 --- a/internal/browser/extractor.go +++ b/internal/browser/extractor.go @@ -17,21 +17,21 @@ import ( // Source is one file or directory an extractor reads. type Source struct { - Path string // slash-separated, relative to the profile dir, or to the user data dir when Shared - Fallbacks []string // older locations, read only when Path is absent - IsDir bool - Shared bool // belongs to the whole user data dir, such as Local State, so it is captured once per dir - Optional bool // the extraction still runs without it + RelativePath string // slash-separated, relative to the profile dir, or to the user data dir when Shared + Fallbacks []string // older locations, read only when RelativePath is absent + IsDir bool + Shared bool // belongs to the whole user data dir, such as Local State, so it is captured once per dir + Optional bool // the extraction still runs without it } -// Paths lists Path and then its Fallbacks, the order they are tried in. -func (s Source) Paths() []string { - return append([]string{s.Path}, s.Fallbacks...) +// RelativePaths lists RelativePath and then its Fallbacks, the order they are tried in. +func (s Source) RelativePaths() []string { + return append([]string{s.RelativePath}, s.Fallbacks...) } -// CandidatePaths are the Paths for a profile, relative to the user data dir. +// CandidatePaths are the RelativePaths for a profile, relative to the user data dir. func (s Source) CandidatePaths(profile Profile) []string { - paths := s.Paths() + paths := s.RelativePaths() if !s.Shared { for i, relativePath := range paths { paths[i] = path.Join(profile.RelativePath, relativePath) @@ -84,7 +84,7 @@ func (in Input) Path(source Source) (string, error) { } return capturedPath, err } - return "", fmt.Errorf("%s: %w", strings.Join(source.Paths(), " or "), fs.ErrNotExist) + return "", fmt.Errorf("%s: %w", strings.Join(source.RelativePaths(), " or "), fs.ErrNotExist) } // MasterKeys may block on its first call; a key version that could not be retrieved is absent from the Set. diff --git a/internal/browser/extractor_test.go b/internal/browser/extractor_test.go index 2299a30..4d9f720 100644 --- a/internal/browser/extractor_test.go +++ b/internal/browser/extractor_test.go @@ -29,15 +29,15 @@ func TestInputPath(t *testing.T) { dirSnapshot := snapshot.Open(root).Snapshot("chrome") input := NewInput(dirSnapshot, Profile{Name: "Default", RelativePath: "Default"}, nil, nil) - got, err := input.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) + got, err := input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.NoError(t, err) assert.Equal(t, legacyCookies, got, "a candidate that was never captured is skipped") - got, err = input.Path(Source{Path: "Local State", Shared: true}) + got, err = input.Path(Source{RelativePath: "Local State", Shared: true}) require.NoError(t, err) assert.Equal(t, localState, got, "a shared source resolves under the user data dir, not the profile") - _, err = input.Path(Source{Path: "History"}) + _, err = input.Path(Source{RelativePath: "History"}) require.ErrorIs(t, err, fs.ErrNotExist) } @@ -46,7 +46,7 @@ func TestInputPath_FlatLayoutProfile(t *testing.T) { history := writeSnapshotFile(t, root, "opera/History") input := NewInput(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil, nil) - got, err := input.Path(Source{Path: "History"}) + got, err := input.Path(Source{RelativePath: "History"}) require.NoError(t, err) assert.Equal(t, history, got) } @@ -57,7 +57,7 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(from, "Default", "Network", "Cookies"), 0o700)) writeSnapshotFile(t, from, "Default/Cookies") - root, err := snapshot.Temp() + root, err := snapshot.NewRoot() require.NoError(t, err) defer func() { require.NoError(t, root.Close()) }() require.NoError(t, root.Capture(context.Background(), []snapshot.File{ @@ -66,7 +66,7 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) { })) input := NewInput(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil, nil) - _, err = input.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) + _, err = input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.Error(t, err) assert.NotErrorIs(t, err, fs.ErrNotExist) } @@ -87,8 +87,8 @@ func TestInputMasterKeys(t *testing.T) { func TestSourceCandidatePaths(t *testing.T) { profile := Profile{Name: "Default", RelativePath: "Default"} - assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile)) - assert.Equal(t, []string{"Local State"}, Source{Path: "Local State", Shared: true}.CandidatePaths(profile)) - assert.Equal(t, []string{"History"}, Source{Path: "History"}.CandidatePaths(Profile{Name: "default"}), + assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile)) + assert.Equal(t, []string{"Local State"}, Source{RelativePath: "Local State", Shared: true}.CandidatePaths(profile)) + assert.Equal(t, []string{"History"}, Source{RelativePath: "History"}.CandidatePaths(Profile{Name: "default"}), "a user data dir that is itself the profile") } diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go index e544f3c..0c1ca16 100644 --- a/internal/browser/firefox/firefox.go +++ b/internal/browser/firefox/firefox.go @@ -14,12 +14,12 @@ import ( ) var ( - loginsJSON = browser.Source{Path: "logins.json"} - keyStore = browser.Source{Path: "key4.db", Optional: true} - placesDB = browser.Source{Path: "places.sqlite"} - cookiesDB = browser.Source{Path: "cookies.sqlite"} - extensionsJSON = browser.Source{Path: "extensions.json"} - webappsStore = browser.Source{Path: "webappsstore.sqlite"} + 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"} ) // defaultExtractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads. @@ -71,8 +71,8 @@ func profileAt(firefoxBrowser browser.Browser, path string) []browser.UserDataDi } func userDataDirPaths(firefoxBrowser browser.Browser, options browser.DiscoverOptions) []string { - paths := make([]string, 0, len(firefoxBrowser.Platform().UserDataDirs)) - for _, relativePath := range firefoxBrowser.Platform().UserDataDirs { + 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 @@ -99,7 +99,7 @@ func hasDataFile(path string) bool { if source.Optional { continue } - for _, relativePath := range source.Paths() { + for _, relativePath := range source.RelativePaths() { if _, err := os.Stat(filepath.Join(path, filepath.FromSlash(relativePath))); err == nil { return true } diff --git a/internal/browser/firefox/firefox_test.go b/internal/browser/firefox/firefox_test.go index b706a20..873d1e5 100644 --- a/internal/browser/firefox/firefox_test.go +++ b/internal/browser/firefox/firefox_test.go @@ -19,7 +19,7 @@ import ( ) func testBrowser(userDataDirs ...string) browser.Browser { - platform := browser.Platform{UserDataDirs: userDataDirs} + platform := browser.Platform{UserDataDirPaths: userDataDirs} return browser.Browser{Name: "firefox", DisplayName: "Firefox", Base: browser.Firefox, Darwin: platform, Linux: platform, Windows: platform} } diff --git a/internal/browser/safari/profiles.go b/internal/browser/safari/profiles.go index 9572116..7f65ebc 100644 --- a/internal/browser/safari/profiles.go +++ b/internal/browser/safari/profiles.go @@ -39,7 +39,7 @@ func namedProfiles(ctx context.Context, library string, id browser.UserDataDirID // readNamedProfilesFromDB reads a copy, never Safari's live file; (nil, err) means unreadable, and any slice is final. func readNamedProfilesFromDB(ctx context.Context, library string, id browser.UserDataDirID) ([]browser.Profile, error) { - root, err := snapshot.Temp() + root, err := snapshot.NewRoot() if err != nil { return nil, err } diff --git a/internal/browser/safari/profiles_test.go b/internal/browser/safari/profiles_test.go index 2e7c8b7..388a4ed 100644 --- a/internal/browser/safari/profiles_test.go +++ b/internal/browser/safari/profiles_test.go @@ -15,7 +15,7 @@ import ( ) func testBrowser() browser.Browser { - platform := browser.Platform{UserDataDirs: []string{"Library/Safari"}} + platform := browser.Platform{UserDataDirPaths: []string{"Library/Safari"}} return browser.Browser{Name: "safari", DisplayName: "Safari", Base: browser.Safari, Darwin: platform, Linux: platform, Windows: platform} } diff --git a/internal/browser/safari/safari.go b/internal/browser/safari/safari.go index 5429b35..dd56025 100644 --- a/internal/browser/safari/safari.go +++ b/internal/browser/safari/safari.go @@ -50,8 +50,8 @@ func userDataDirPaths(safariBrowser browser.Browser, options browser.DiscoverOpt if options.ProfilePath != "" { return []string{filepath.Clean(options.ProfilePath)} } - paths := make([]string, 0, len(safariBrowser.Platform().UserDataDirs)) - for _, relativePath := range safariBrowser.Platform().UserDataDirs { + paths := make([]string, 0, len(safariBrowser.Platform().UserDataDirPaths)) + for _, relativePath := range safariBrowser.Platform().UserDataDirPaths { paths = append(paths, filepath.Join(options.HomeDir, filepath.FromSlash(relativePath))) } return paths @@ -68,16 +68,16 @@ func Extractors(dir browser.UserDataDir, profile browser.Profile) browser.Extrac func defaultProfileExtractors(profile browser.Profile) browser.Extractors { var ( - history = browser.Source{Path: "History.db"} + history = browser.Source{RelativePath: "History.db"} cookies = browser.Source{ - Path: fromLibrary(profile, containerDir+"/Cookies/Cookies.binarycookies"), - Fallbacks: []string{fromLibrary(profile, "Cookies/Cookies.binarycookies")}, + RelativePath: fromLibrary(profile, containerDir+"/Cookies/Cookies.binarycookies"), + Fallbacks: []string{fromLibrary(profile, "Cookies/Cookies.binarycookies")}, } - bookmarks = browser.Source{Path: "Bookmarks.plist"} - downloads = browser.Source{Path: "Downloads.plist"} - localStorage = browser.Source{Path: fromLibrary(profile, containerDir+"/WebKit/WebsiteData/Default"), IsDir: true} - appExtensions = browser.Source{Path: fromLibrary(profile, containerDir+"/Safari/AppExtensions/Extensions.plist"), Optional: true} - webExtensions = browser.Source{Path: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true} + bookmarks = browser.Source{RelativePath: "Bookmarks.plist"} + downloads = browser.Source{RelativePath: "Downloads.plist"} + localStorage = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/WebKit/WebsiteData/Default"), IsDir: true} + appExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/AppExtensions/Extensions.plist"), Optional: true} + webExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true} ) return browser.Extractors{ category.Password: {Extract: extractPasswords}, @@ -93,10 +93,10 @@ func defaultProfileExtractors(profile browser.Profile) browser.Extractors { func namedProfileExtractors(dir browser.UserDataDir, profile browser.Profile, uuid string) browser.Extractors { store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid) var ( - history = browser.Source{Path: "History.db"} - cookies = browser.Source{Path: fromLibrary(profile, store+"/Cookies/Cookies.binarycookies")} - downloads = browser.Source{Path: fromLibrary(profile, defaultProfileDir(dir)+"/Downloads.plist")} - localStorage = browser.Source{Path: fromLibrary(profile, store+"/Origins"), IsDir: true} + history = browser.Source{RelativePath: "History.db"} + cookies = browser.Source{RelativePath: fromLibrary(profile, store+"/Cookies/Cookies.binarycookies")} + downloads = browser.Source{RelativePath: fromLibrary(profile, defaultProfileDir(dir)+"/Downloads.plist")} + localStorage = browser.Source{RelativePath: fromLibrary(profile, store+"/Origins"), IsDir: true} ) return browser.Extractors{ category.History: newPlainExtractor(extractHistories, history), diff --git a/internal/browser/safari/safari_test.go b/internal/browser/safari/safari_test.go index cade6a1..cf47f0b 100644 --- a/internal/browser/safari/safari_test.go +++ b/internal/browser/safari/safari_test.go @@ -32,7 +32,7 @@ func sourcePaths(profile browser.Profile, extractors browser.Extractors) map[cat got := make(map[category.Category][]string, len(extractors)) for dataCategory, extractor := range extractors { for _, source := range extractor.Sources { - for _, relativePath := range source.Paths() { + for _, relativePath := range source.RelativePaths() { got[dataCategory] = append(got[dataCategory], path.Join(profile.RelativePath, relativePath)) } } diff --git a/internal/browser/table.go b/internal/browser/table.go index dd4a1d4..6468243 100644 --- a/internal/browser/table.go +++ b/internal/browser/table.go @@ -9,17 +9,17 @@ var browsers = []Browser{ DisplayName: "Chrome", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Google/Chrome"}, - SecretLabel: "Chrome", + UserDataDirPaths: []string{"Library/Application Support/Google/Chrome"}, + SecretLabel: "Chrome", }, Linux: Platform{ - UserDataDirs: []string{".config/google-chrome"}, - SecretLabel: "Chrome Safe Storage", - PortalAppID: "com.google.Chrome", + UserDataDirPaths: []string{".config/google-chrome"}, + SecretLabel: "Chrome Safe Storage", + PortalAppID: "com.google.Chrome", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Google/Chrome/User Data"}, - Executable: "chrome.exe", + UserDataDirPaths: []string{"AppData/Local/Google/Chrome/User Data"}, + Executable: "chrome.exe", ExecutableFallbacks: []string{ `%ProgramFiles%\Google\Chrome\Application\chrome.exe`, `%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`, @@ -33,16 +33,16 @@ var browsers = []Browser{ DisplayName: "Microsoft Edge", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Microsoft Edge"}, - SecretLabel: "Microsoft Edge", + UserDataDirPaths: []string{"Library/Application Support/Microsoft Edge"}, + SecretLabel: "Microsoft Edge", }, Linux: Platform{ - UserDataDirs: []string{".config/microsoft-edge"}, - SecretLabel: "Chromium Safe Storage", + UserDataDirPaths: []string{".config/microsoft-edge"}, + SecretLabel: "Chromium Safe Storage", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Microsoft/Edge/User Data"}, - Executable: "msedge.exe", + UserDataDirPaths: []string{"AppData/Local/Microsoft/Edge/User Data"}, + Executable: "msedge.exe", ExecutableFallbacks: []string{ `%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`, `%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`, @@ -55,16 +55,16 @@ var browsers = []Browser{ DisplayName: "Chromium", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Chromium"}, - SecretLabel: "Chromium", + UserDataDirPaths: []string{"Library/Application Support/Chromium"}, + SecretLabel: "Chromium", }, Linux: Platform{ - UserDataDirs: []string{".config/chromium"}, - SecretLabel: "Chromium Safe Storage", - PortalAppID: "org.chromium.Chromium", + UserDataDirPaths: []string{".config/chromium"}, + SecretLabel: "Chromium Safe Storage", + PortalAppID: "org.chromium.Chromium", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Chromium/User Data"}, + UserDataDirPaths: []string{"AppData/Local/Chromium/User Data"}, }, }, { @@ -72,17 +72,17 @@ var browsers = []Browser{ DisplayName: "Chrome Beta", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Google/Chrome Beta"}, - SecretLabel: "Chrome", + UserDataDirPaths: []string{"Library/Application Support/Google/Chrome Beta"}, + SecretLabel: "Chrome", }, Linux: Platform{ - UserDataDirs: []string{".config/google-chrome-beta"}, - SecretLabel: "Chrome Safe Storage", - PortalAppID: "com.google.Chrome.beta", + UserDataDirPaths: []string{".config/google-chrome-beta"}, + SecretLabel: "Chrome Safe Storage", + PortalAppID: "com.google.Chrome.beta", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Google/Chrome Beta/User Data"}, - Executable: "chrome.exe", + UserDataDirPaths: []string{"AppData/Local/Google/Chrome Beta/User Data"}, + Executable: "chrome.exe", ExecutableFallbacks: []string{ `%ProgramFiles%\Google\Chrome Beta\Application\chrome.exe`, `%ProgramFiles(x86)%\Google\Chrome Beta\Application\chrome.exe`, @@ -96,15 +96,15 @@ var browsers = []Browser{ DisplayName: "Opera", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/com.operasoftware.Opera"}, - SecretLabel: "Opera", + UserDataDirPaths: []string{"Library/Application Support/com.operasoftware.Opera"}, + SecretLabel: "Opera", }, Linux: Platform{ - UserDataDirs: []string{".config/opera"}, - SecretLabel: "Chromium Safe Storage", + UserDataDirPaths: []string{".config/opera"}, + SecretLabel: "Chromium Safe Storage", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Roaming/Opera Software/Opera Stable"}, + UserDataDirPaths: []string{"AppData/Roaming/Opera Software/Opera Stable"}, }, }, { @@ -112,11 +112,11 @@ var browsers = []Browser{ DisplayName: "OperaGX", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/com.operasoftware.OperaGX"}, - SecretLabel: "Opera", + UserDataDirPaths: []string{"Library/Application Support/com.operasoftware.OperaGX"}, + SecretLabel: "Opera", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Roaming/Opera Software/Opera GX Stable"}, + UserDataDirPaths: []string{"AppData/Roaming/Opera Software/Opera GX Stable"}, }, }, { @@ -124,7 +124,7 @@ var browsers = []Browser{ DisplayName: "Browser from Vought", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Roaming/Browser from Vought"}, + UserDataDirPaths: []string{"AppData/Roaming/Browser from Vought"}, }, }, { @@ -132,15 +132,15 @@ var browsers = []Browser{ DisplayName: "Vivaldi", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Vivaldi"}, - SecretLabel: "Vivaldi", + UserDataDirPaths: []string{"Library/Application Support/Vivaldi"}, + SecretLabel: "Vivaldi", }, Linux: Platform{ - UserDataDirs: []string{".config/vivaldi"}, - SecretLabel: "Chrome Safe Storage", + UserDataDirPaths: []string{".config/vivaldi"}, + SecretLabel: "Chrome Safe Storage", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Vivaldi/User Data"}, + UserDataDirPaths: []string{"AppData/Local/Vivaldi/User Data"}, }, }, { @@ -148,12 +148,12 @@ var browsers = []Browser{ DisplayName: "CocCoc", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Coccoc"}, - SecretLabel: "CocCoc", + UserDataDirPaths: []string{"Library/Application Support/Coccoc"}, + SecretLabel: "CocCoc", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/CocCoc/Browser/User Data"}, - Executable: "browser.exe", + UserDataDirPaths: []string{"AppData/Local/CocCoc/Browser/User Data"}, + Executable: "browser.exe", ExecutableFallbacks: []string{ `%ProgramFiles%\CocCoc\Browser\Application\browser.exe`, `%ProgramFiles(x86)%\CocCoc\Browser\Application\browser.exe`, @@ -167,17 +167,17 @@ var browsers = []Browser{ DisplayName: "Brave", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/BraveSoftware/Brave-Browser"}, - SecretLabel: "Brave", + UserDataDirPaths: []string{"Library/Application Support/BraveSoftware/Brave-Browser"}, + SecretLabel: "Brave", }, Linux: Platform{ - UserDataDirs: []string{".config/BraveSoftware/Brave-Browser"}, - SecretLabel: "Brave Safe Storage", - PortalAppID: "com.brave.Browser", + UserDataDirPaths: []string{".config/BraveSoftware/Brave-Browser"}, + SecretLabel: "Brave Safe Storage", + PortalAppID: "com.brave.Browser", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/BraveSoftware/Brave-Browser/User Data"}, - Executable: "brave.exe", + UserDataDirPaths: []string{"AppData/Local/BraveSoftware/Brave-Browser/User Data"}, + Executable: "brave.exe", ExecutableFallbacks: []string{ `%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`, `%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`, @@ -191,11 +191,11 @@ var browsers = []Browser{ DisplayName: "Yandex", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Yandex/YandexBrowser"}, - SecretLabel: "Yandex", + UserDataDirPaths: []string{"Library/Application Support/Yandex/YandexBrowser"}, + SecretLabel: "Yandex", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Yandex/YandexBrowser/User Data"}, + UserDataDirPaths: []string{"AppData/Local/Yandex/YandexBrowser/User Data"}, }, }, { @@ -203,7 +203,7 @@ var browsers = []Browser{ DisplayName: "360 Speed X", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/360ChromeX/Chrome/User Data"}, + UserDataDirPaths: []string{"AppData/Local/360ChromeX/Chrome/User Data"}, }, }, { @@ -211,7 +211,7 @@ var browsers = []Browser{ DisplayName: "360 Speed", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/360chrome/Chrome/User Data"}, + UserDataDirPaths: []string{"AppData/Local/360chrome/Chrome/User Data"}, }, }, { @@ -219,7 +219,7 @@ var browsers = []Browser{ DisplayName: "QQ", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Tencent/QQBrowser/User Data"}, + UserDataDirPaths: []string{"AppData/Local/Tencent/QQBrowser/User Data"}, }, }, { @@ -227,7 +227,7 @@ var browsers = []Browser{ DisplayName: "DC", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/DCBrowser/User Data"}, + UserDataDirPaths: []string{"AppData/Local/DCBrowser/User Data"}, }, }, { @@ -235,7 +235,7 @@ var browsers = []Browser{ DisplayName: "Sogou", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Sogou/SogouExplorer/User Data"}, + UserDataDirPaths: []string{"AppData/Local/Sogou/SogouExplorer/User Data"}, }, }, { @@ -243,11 +243,11 @@ var browsers = []Browser{ DisplayName: "Arc", Base: Chromium, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Arc/User Data"}, - SecretLabel: "Arc", + UserDataDirPaths: []string{"Library/Application Support/Arc/User Data"}, + SecretLabel: "Arc", }, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Packages/TheBrowserCompany.Arc_*/LocalCache/Local/Arc/User Data"}, + UserDataDirPaths: []string{"AppData/Local/Packages/TheBrowserCompany.Arc_*/LocalCache/Local/Arc/User Data"}, }, }, { @@ -255,7 +255,7 @@ var browsers = []Browser{ DisplayName: "DuckDuckGo", Base: Chromium, Windows: Platform{ - UserDataDirs: []string{"AppData/Local/Packages/DuckDuckGo.DesktopBrowser_*/LocalState/EBWebView"}, + UserDataDirPaths: []string{"AppData/Local/Packages/DuckDuckGo.DesktopBrowser_*/LocalState/EBWebView"}, }, }, { @@ -263,13 +263,13 @@ var browsers = []Browser{ DisplayName: "Firefox", Base: Firefox, Darwin: Platform{ - UserDataDirs: []string{"Library/Application Support/Firefox/Profiles"}, + UserDataDirPaths: []string{"Library/Application Support/Firefox/Profiles"}, }, Linux: Platform{ - UserDataDirs: []string{".mozilla/firefox"}, + UserDataDirPaths: []string{".mozilla/firefox"}, }, Windows: Platform{ - UserDataDirs: []string{"AppData/Roaming/Mozilla/Firefox/Profiles"}, + UserDataDirPaths: []string{"AppData/Roaming/Mozilla/Firefox/Profiles"}, }, }, { @@ -277,7 +277,7 @@ var browsers = []Browser{ DisplayName: "Safari", Base: Safari, Darwin: Platform{ - UserDataDirs: []string{"Library/Safari"}, + UserDataDirPaths: []string{"Library/Safari"}, }, }, } diff --git a/internal/browser/table_test.go b/internal/browser/table_test.go index 37d66ef..b85be03 100644 --- a/internal/browser/table_test.go +++ b/internal/browser/table_test.go @@ -41,7 +41,7 @@ func TestTableRows(t *testing.T) { assert.Contains(t, []Base{Chromium, Firefox, Safari}, browser.Base, browser.Name) for goos, platform := range platformOf { - for _, dir := range platform(browser).UserDataDirs { + for _, dir := range platform(browser).UserDataDirPaths { assert.Truef(t, dir != "" && !path.IsAbs(dir) && !strings.Contains(dir, `\`), "%s %s: user data dir %q must be slash-separated and relative to the home dir", browser.Name, goos, dir) } diff --git a/internal/export/writer.go b/internal/export/writer.go index f355c84..5e96116 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -42,12 +42,12 @@ type categoryFile struct { count int } -// NewWriter creates dir. With zip, Close packs the files it wrote into /.zip. -func NewWriter(dir string, format Format, zip bool) (*Writer, error) { - if err := os.MkdirAll(dir, 0o750); err != nil { +// NewWriter creates outputDir. With zip, Close packs the files it wrote into /.zip. +func NewWriter(outputDir string, format Format, zip bool) (*Writer, error) { + if err := os.MkdirAll(outputDir, 0o750); err != nil { return nil, fmt.Errorf("create output dir: %w", err) } - return &Writer{dir: dir, format: format, zip: zip, files: make(map[category.Category]*categoryFile)}, nil + return &Writer{dir: outputDir, format: format, zip: zip, files: make(map[category.Category]*categoryFile)}, nil } // Write reorders records in place. diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index e17dbbe..af39662 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -26,8 +26,8 @@ type Root struct { failed map[string]error // keyed by the cleaned /, so any spelling of a file finds its failure } -// Temp creates a private temporary snapshot directory, which Close removes. -func Temp() (*Root, error) { +// NewRoot creates a private temporary snapshot directory, which Close removes. +func NewRoot() (*Root, error) { path, err := os.MkdirTemp("", "hbd-snapshot-*") if err != nil { return nil, fmt.Errorf("create snapshot dir: %w", err) @@ -42,7 +42,7 @@ func Open(path string) *Root { // Unzip extracts an archive into a temporary snapshot directory, rejecting entries that would land outside it. func Unzip(archivePath string) (*Root, error) { - root, err := Temp() + root, err := NewRoot() if err != nil { return nil, err } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index 308a272..2f156e9 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -32,7 +32,7 @@ func userDataDir(t *testing.T) string { } func TestTemp_IsPrivateAndCloseRemovesIt(t *testing.T) { - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) info, err := os.Stat(root.Path()) require.NoError(t, err) @@ -59,7 +59,7 @@ func TestOpen_ReadsInPlaceAndCloseLeavesIt(t *testing.T) { func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { from := userDataDir(t) - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) defer root.Close() @@ -88,7 +88,7 @@ func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) { from := userDataDir(t) - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) defer root.Close() @@ -112,7 +112,7 @@ func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) { func TestCapture_StopsWhenCancelled(t *testing.T) { from := userDataDir(t) - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) defer root.Close() @@ -127,7 +127,7 @@ func TestCapture_StopsWhenCancelled(t *testing.T) { func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) { from := userDataDir(t) - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) defer root.Close() @@ -147,7 +147,7 @@ func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) { } func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) { - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) defer root.Close() @@ -157,7 +157,7 @@ func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) { func TestCapture_ALaterCaptureReplacesAnEarlierFailure(t *testing.T) { from := t.TempDir() - root, err := Temp() + root, err := NewRoot() require.NoError(t, err) defer root.Close() diff --git a/internal/zipfile/zipfile.go b/internal/zipfile/zipfile.go index 8b6b7fc..191d154 100644 --- a/internal/zipfile/zipfile.go +++ b/internal/zipfile/zipfile.go @@ -42,8 +42,8 @@ func addFile(zipWriter *zip.Writer, path, name string) error { return err } -// Extract unpacks archivePath into dir, refusing any entry that would land outside it. -func Extract(archivePath, dir string) error { +// Extract unpacks archivePath into targetDir, refusing any entry that would land outside it. +func Extract(archivePath, targetDir string) error { zipReader, err := zip.OpenReader(archivePath) if err != nil { return fmt.Errorf("open zip %s: %w", archivePath, err) @@ -55,7 +55,7 @@ func Extract(archivePath, dir string) error { if !filepath.IsLocal(name) { return fmt.Errorf("zip entry %q escapes destination", zipFile.Name) } - target := filepath.Join(dir, name) + target := filepath.Join(targetDir, name) if zipFile.FileInfo().IsDir() { if err := os.MkdirAll(target, 0o700); err != nil { return err From 7bb00791659103b4258b41b03e2d09b1eade1533 Mon Sep 17 00:00:00 2001 From: moonD4rk Date: Sat, 21 Nov 2026 19:08:30 +0800 Subject: [PATCH 3/3] docs(rfcs): add two naming rules to RFC-001 --- rfcs/001-architecture.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rfcs/001-architecture.md b/rfcs/001-architecture.md index 32a83e0..280f05e 100644 --- a/rfcs/001-architecture.md +++ b/rfcs/001-architecture.md @@ -37,5 +37,7 @@ Dependencies point down only. Interfaces live with their consumer, nothing regis - Names are spelled out; only Go's universal idioms stay short, and lint enforces it. - The domain's words: a **browser** is a row of the browser table; its **base** is what it is built on (Chromium, Firefox, or Safari); a **user data dir** is a browser's data directory, where an installation would be the program; and a **profile**, an **extraction**, a **snapshot**, a **record**, and a **category** mean what they say. - Unqualified, "dir" means a user data dir; any other directory is named for what it holds. +- A field named for a thing holds the thing itself; one that holds only its name or its path says so, unless it mirrors a name in the output or the keys file. +- A path is absolute unless its name says it is relative. **Rejected:** "engine" for the base, which means the renderer; "origin" or "owner" for where a record came from, which are web and access-control terms; and "job" for an extraction, which suggests a worker pool that does not exist.