diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index b5cfaac..b1b4f43 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -2,6 +2,7 @@ package main import ( "context" + "io" "github.com/spf13/cobra" @@ -21,7 +22,7 @@ func dumpCmd() *cobra.Command { hack-browser-data dump -f cookie-editor hack-browser-data dump --zip`, RunE: func(cmd *cobra.Command, args []string) error { - return runDump(cmd.Context(), f) + return runDump(cmd.Context(), cmd.ErrOrStderr(), f) }, } @@ -42,7 +43,7 @@ func keychainPasswordFlags(cmd *cobra.Command, f *app.Flags) { cmd.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin") } -func runDump(ctx context.Context, f app.Flags) error { +func runDump(ctx context.Context, stderr io.Writer, f app.Flags) error { req, err := app.Validate(f) if err != nil { return err @@ -50,14 +51,14 @@ func runDump(ctx context.Context, f app.Flags) error { d := app.Discover(req) if len(d.Dirs) == 0 { if len(d.Failed) > 0 { - report(app.Summary{Results: d.Failed}) + report(stderr, app.Summary{Results: d.Failed}) } log.Warnf("no browsers found") return nil } summary, err := app.Execute(ctx, app.NewPlan(d, req), req) if ctx.Err() == nil { - report(summary) + report(stderr, summary) } return err } diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index 4be47a5..dc1f909 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -13,9 +13,8 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) -var verbose bool - func rootCmd() *cobra.Command { + var verbose bool root := &cobra.Command{ Use: "hack-browser-data", Short: "A CLI tool for decrypting and exporting browser data", diff --git a/cmd/hack-browser-data/names.go b/cmd/hack-browser-data/names.go index 9fc7519..1c513c2 100644 --- a/cmd/hack-browser-data/names.go +++ b/cmd/hack-browser-data/names.go @@ -1,8 +1,7 @@ package main import ( - "os" - "sort" + "io" "strings" "github.com/moond4rk/hackbrowserdata/internal/app" @@ -11,29 +10,17 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) -// browserNames lists this OS's browser IDs for the usage strings, sorted as they have always been listed. func browserNames() string { - defs := browser.Supported() - ids := make([]string, 0, len(defs)) - for _, d := range defs { - ids = append(ids, d.ID) - } - sort.Strings(ids) - return strings.Join(ids, "|") + return strings.Join(browser.IDs(), "|") } func categoryNames() string { - all := category.All() - names := make([]string, len(all)) - for i, c := range all { - names[i] = c.String() - } - return strings.Join(names, ",") + return strings.Join(category.Names(), ",") } // report prints the run's summary; it is not part of the output, so failing to print it never fails the run. -func report(s app.Summary) { - if err := app.Report(os.Stderr, s); err != nil { +func report(w io.Writer, s app.Summary) { + if err := app.Report(w, s); err != nil { log.Warnf("print summary: %v", err) } } diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 3481c83..52f4435 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "io" "github.com/spf13/cobra" @@ -22,7 +23,7 @@ func restoreCmd() *cobra.Command { 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`, RunE: func(cmd *cobra.Command, args []string) error { - return runRestore(cmd.Context(), f) + return runRestore(cmd.Context(), cmd.ErrOrStderr(), f) }, } @@ -41,7 +42,7 @@ func restoreCmd() *cobra.Command { return cmd } -func runRestore(ctx context.Context, f app.RestoreFlags) error { +func runRestore(ctx context.Context, stderr io.Writer, f app.RestoreFlags) error { req, dump, err := app.ValidateRestore(f) if err != nil { return err @@ -63,7 +64,7 @@ func runRestore(ctx context.Context, f app.RestoreFlags) error { req.Keys = keys summary, err := app.Execute(ctx, app.NewPlan(d, req), req) if ctx.Err() == nil { - report(summary) + report(stderr, summary) } return err } diff --git a/internal/app/app.go b/internal/app/app.go index 2119e32..9ed8914 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -134,7 +134,7 @@ func ListRequest() (Request, error) { if err != nil { return Request{}, err } - return Request{Browser: "all", Categories: category.All(), Home: home}, nil + return Request{Browser: allBrowsers, Categories: category.All(), Home: home}, nil } func homeDir() (string, error) { @@ -145,20 +145,20 @@ func homeDir() (string, error) { return home, nil } +const allBrowsers = "all" + // parseBrowser accepts all or one of this OS's browser IDs; an ID from another OS's table has nothing to find here. func parseBrowser(s string) (string, error) { id := strings.ToLower(strings.TrimSpace(s)) - if id == "" || id == "all" { - return "all", nil + if id == "" || id == allBrowsers { + return allBrowsers, nil } - ids := []string{"all"} for _, def := range browser.Supported() { if def.ID == id { return id, nil } - ids = append(ids, def.ID) } - return "", fmt.Errorf("unknown browser %q, available: %s", s, strings.Join(ids, "|")) + return "", fmt.Errorf("unknown browser %q, available: %s|%s", s, allBrowsers, strings.Join(browser.IDs(), "|")) } // checkOutputDir creates nothing: -d must already be a directory, or its nearest existing ancestor must be one that a @@ -191,7 +191,7 @@ func checkProfilePath(id, path string) (string, error) { if path == "" { return "", nil } - if id == "all" { + if id == allBrowsers { log.Warnf("-p needs a specific -b; ignoring %s", path) return "", nil } @@ -221,7 +221,7 @@ func parseCategories(s string) ([]category.Category, error) { } c, err := category.Parse(name) if err != nil { - return nil, fmt.Errorf("%w, available: all|%s", err, categoryNames()) + return nil, fmt.Errorf("%w, available: all|%s", err, strings.Join(category.Names(), ",")) } if !seen[c] { seen[c] = true @@ -233,12 +233,3 @@ func parseCategories(s string) ([]category.Category, error) { } return categories, nil } - -func categoryNames() string { - all := category.All() - names := make([]string, len(all)) - for i, c := range all { - names[i] = c.String() - } - return strings.Join(names, ",") -} diff --git a/internal/app/archive.go b/internal/app/archive.go index 00dfbd1..8e2dd0d 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -56,7 +56,7 @@ func archiveFiles(p Plan, dirs []browser.UserDataDir) []snapshot.File { for _, dir := range dirs { for _, prof := range dir.Profiles { for _, src := range chromium.ArchiveSources(dir) { - if f, ok := firstOnDisk(dir, prof, src); ok { + if f, ok, err := firstOnDisk(dir, prof, src); err == nil && ok { add(f) } } diff --git a/internal/app/discover.go b/internal/app/discover.go index 7cbfeee..510dda3 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -20,11 +20,11 @@ type Discovery struct { func Discover(req Request) Discovery { var d Discovery for _, def := range browser.Supported() { - if req.Browser != "all" && def.ID != req.Browser { + if req.Browser != allBrowsers && def.ID != req.Browser { continue } opts := browser.DiscoverOptions{Home: req.Home} - if req.Browser != "all" { + if req.Browser != allBrowsers { opts.ProfilePath = req.ProfilePath } dirs, err := discover(def, opts) @@ -37,7 +37,8 @@ func Discover(req Request) Discovery { } // withData keeps the profiles holding a file some category reads, and the user data dirs with such a profile: a -// Preferences marker alone is no data, so a profile created and never used is not listed, archived, or keyed. +// Preferences marker alone is no data, so a profile created and never used is not listed, archived, or keyed. A +// profile whose files cannot be checked stays, so the plan reports the error. func withData(dirs []browser.UserDataDir) []browser.UserDataDir { extractors := extractorsWith(nil) var out []browser.UserDataDir @@ -61,7 +62,7 @@ func hasData(dir browser.UserDataDir, p browser.Profile, ex browser.Extractors) if len(x.Sources) == 0 { continue } - if _, ok := locate(dir, p, x.Sources); ok { + if _, ok, err := locate(dir, p, x.Sources); ok || err != nil { return true } } diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index c8fa961..0d0510f 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -88,3 +88,10 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) { assert.Equal(t, Extraction{DirID: "chrome"}, d.Failed[0].Extraction) assert.Equal(t, OutcomeError, d.Failed[0].Outcome) } + +// Dropping a profile whose files cannot be checked would hide the failure; the plan reports it instead. +func TestWithData_KeepsAProfileItCannotCheck(t *testing.T) { + dir := chromeDir(t, "chrome", "Default") + lock(t, filepath.Join(dir.Path, "Default")) + assert.Len(t, withData([]browser.UserDataDir{dir}), 1) +} diff --git a/internal/app/execute.go b/internal/app/execute.go index 3d89772..595a182 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io/fs" + "os" "sync" "github.com/moond4rk/hackbrowserdata/internal/browser" @@ -44,14 +45,30 @@ func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc if err != nil { return Summary{}, err } - s, err := runPlan(ctx, p, w, extractors, keys, true) - return s, errors.Join(err, w.Close()) + s, err := runner{w: w, extractors: extractors, keys: keys, announce: true}.run(ctx, p) + closeErr := w.Close() + announceOutput(w.Output()) + return s, errors.Join(err, closeErr) +} + +func announceOutput(out export.Output) { + if len(out.Files) == 0 { + return + } + fmt.Fprintln(os.Stderr) + log.Infof("Exported to %s/", out.Dir) + for _, f := range out.Files { + log.Infof(" %-24s %d entries", f.Name, f.Count) + } + if out.Zip != "" { + log.Infof("Compressed: %s/%s", out.Dir, out.Zip) + } } // Count runs every planned extraction with no key and the keychain locked, and counts the records instead of exporting // them, which is all list --detail shows. func Count(ctx context.Context, p Plan, req Request) (Summary, error) { - return runPlan(ctx, p, discard{}, extractorsWith(loginKeychain(req)), dumpKeys(nil), false) + return runner{w: discard{}, extractors: extractorsWith(loginKeychain(req)), keys: dumpKeys(nil)}.run(ctx, p) } // recordWriter takes each extraction's records as it finishes. @@ -63,13 +80,21 @@ type discard struct{} 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) { +// runner is what every user data dir of one run shares; announce logs each dir as it starts. +type runner struct { + w recordWriter + extractors extractorsFunc + keys keySource + announce bool +} + +func (r runner) run(ctx context.Context, p Plan) (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) + dirResults, err := r.runDir(ctx, dir, p) results = append(results, dirResults...) if err != nil { return Summary{Results: results}, err @@ -78,14 +103,12 @@ func runPlan(ctx context.Context, p Plan, w recordWriter, extractors extractorsF return Summary{Results: results}, nil } -func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWriter, extractors extractorsFunc, - keys keySource, announce bool, -) ([]Result, error) { +func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, p Plan) ([]Result, error) { extractions := extractionsOf(p, dir.ID) if len(extractions) == 0 { return nil, nil } - if announce { + if r.announce { log.Infof("Extracting %s...", dir.Def.Name) } @@ -107,7 +130,7 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr masterKeys func(context.Context) masterkey.Set ) if dir.Def.Base == browser.Chromium { - dk = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return keys(ctx, dir, snap) }} + dk = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return r.keys(ctx, dir, snap) }} masterKeys = dk.get } @@ -115,7 +138,7 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr byProfile := make(map[string]browser.Extractors, len(dir.Profiles)) for _, prof := range dir.Profiles { profiles[prof.Name] = prof - byProfile[prof.Name] = extractors(dir, prof) + byProfile[prof.Name] = r.extractors(dir, prof) } results := make([]Result, 0, len(extractions)+1) @@ -132,7 +155,7 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr c := &collector{browser: dir.Def.Name, profile: prof.Name} err := x.Extract(ctx, browser.NewProfileSnapshot(snap, prof, masterKeys), c) // Records emitted before an extraction failed are kept, as they always were. - if writeErr := w.Write(e.Category, c.records); writeErr != nil { + if writeErr := r.w.Write(e.Category, c.records); writeErr != nil { return results, writeErr } results = append(results, c.result(e, err)) diff --git a/internal/app/keys.go b/internal/app/keys.go index bee2600..6f9aa8e 100644 --- a/internal/app/keys.go +++ b/internal/app/keys.go @@ -61,7 +61,7 @@ func retrieveKeys(ctx context.Context, dir browser.UserDataDir, keys keySource) defer closeSnapshot(d) var files []snapshot.File for _, src := range chromium.KeySources(dir) { - if f, ok := firstOnDisk(dir, browser.Profile{}, src); ok { + if f, ok, err := firstOnDisk(dir, browser.Profile{}, src); err == nil && ok { files = append(files, f) } } diff --git a/internal/app/plan.go b/internal/app/plan.go index c3910a8..03d5ec9 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -1,8 +1,9 @@ package app import ( + "errors" + "io/fs" "os" - "path" "path/filepath" "github.com/moond4rk/hackbrowserdata/internal/browser" @@ -48,7 +49,11 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan { p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeUnsupported}) continue } - files, ok := locate(dir, prof, x.Sources) + files, ok, err := locate(dir, prof, x.Sources) + if err != nil { + p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeError, Err: err}) + continue + } if !ok { p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeAbsent}) continue @@ -68,35 +73,37 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan { // locate finds each source's first candidate on disk. An extraction needs every required source and at least one of // the profile's own; a shared one such as Local State never makes it present by itself. An extraction that reads no -// file, such as Safari's keychain passwords, always runs. -func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool) { +// file, such as Safari's keychain passwords, always runs. A candidate that cannot be checked is an error, not absence. +func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool, error) { if len(sources) == 0 { - return nil, true + return nil, true, nil } var files []snapshot.File present := false for _, src := range sources { - f, ok := firstOnDisk(dir, p, src) + f, ok, err := firstOnDisk(dir, p, src) switch { + case err != nil: + return nil, false, err case ok: files = append(files, f) present = present || !src.Shared case !src.Optional: - return nil, false + return nil, false, nil } } - return files, present + return files, present, nil } -func firstOnDisk(dir browser.UserDataDir, p browser.Profile, src browser.Source) (snapshot.File, bool) { - for _, rel := range src.Paths { - if !src.Shared { - rel = path.Join(p.Dir, rel) - } +func firstOnDisk(dir browser.UserDataDir, p browser.Profile, src browser.Source) (snapshot.File, bool, error) { + for _, rel := range src.Candidates(p) { info, err := os.Stat(filepath.Join(dir.Path, filepath.FromSlash(rel))) - if err == nil && info.IsDir() == src.IsDir { - return snapshot.File{DirID: string(dir.ID), From: dir.Path, Rel: rel, IsDir: src.IsDir}, true + switch { + case err == nil && info.IsDir() == src.IsDir: + return snapshot.File{DirID: string(dir.ID), From: dir.Path, Rel: rel, IsDir: src.IsDir}, true, nil + case err != nil && !errors.Is(err, fs.ErrNotExist): + return snapshot.File{}, false, err } } - return snapshot.File{}, false + return snapshot.File{}, false, nil } diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index 18839b9..0e391f3 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -2,8 +2,10 @@ package app import ( "errors" + "io/fs" "os" "path/filepath" + "runtime" "testing" "github.com/stretchr/testify/assert" @@ -115,3 +117,31 @@ func TestNewPlan_ExtractorWithoutSourcesRuns(t *testing.T) { assert.Empty(t, got.Files) assert.Empty(t, got.Skipped) } + +// lock makes dir unsearchable until the test ends, so a Stat of anything under it fails with permission denied. +func lock(t *testing.T, dir string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("mode bits do not restrict Stat on Windows") + } + if os.Geteuid() == 0 { + t.Skip("root ignores mode bits") + } + require.NoError(t, os.Chmod(dir, 0)) + t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) }) +} + +// A candidate that cannot be checked is not absence: the extraction is an error, and nothing is captured for it. +func TestNewPlan_UnreadableSourceIsAnError(t *testing.T) { + dir := chromeDir(t, "chrome", "Default") + lock(t, filepath.Join(dir.Path, "Default")) + base := fakeBase(map[category.Category]extractFunc{category.History: nil}) + + got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.History}}, base) + + require.Len(t, got.Skipped, 1) + assert.Equal(t, OutcomeError, got.Skipped[0].Outcome) + require.ErrorIs(t, got.Skipped[0].Err, fs.ErrPermission) + assert.Empty(t, got.Extractions) + assert.Empty(t, got.Files) +} diff --git a/internal/app/restore.go b/internal/app/restore.go index 7486f68..302b3ee 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -57,9 +57,9 @@ func ValidateRestore(f RestoreFlags) (Request, masterkey.Dump, error) { } filter := strings.ToLower(strings.TrimSpace(f.Browser)) if filter == "" { - filter = "all" + filter = allBrowsers } - if filter != "all" && len(vaultsOf(dump, filter)) == 0 { + if filter != allBrowsers && len(vaultsOf(dump, filter)) == 0 { return Request{}, masterkey.Dump{}, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultKeys(dump.Vaults)) } req := Request{Browser: filter, Categories: categories, Format: format, Dir: f.Dir, Zip: f.Zip} @@ -115,7 +115,7 @@ func fromManifest(root string, m snapshot.Manifest, vaults []masterkey.Vault, fi var d Discovery keys := make(map[browser.DirID]masterkey.Set) for _, md := range m.Dirs { - if filter != "all" && md.Browser != filter { + if filter != allBrowsers && md.Browser != filter { continue } v, ok := vaultOf(vaults, md) @@ -247,7 +247,7 @@ func vaultDirID(v masterkey.Vault) browser.DirID { func vaultsOf(dump masterkey.Dump, filter string) []masterkey.Vault { var out []masterkey.Vault for _, v := range dump.Vaults { - if filter == "all" || strings.EqualFold(v.Browser, filter) { + if filter == allBrowsers || strings.EqualFold(v.Browser, filter) { out = append(out, v) } } diff --git a/internal/browser/browser.go b/internal/browser/browser.go index fd71e56..e8bf02f 100644 --- a/internal/browser/browser.go +++ b/internal/browser/browser.go @@ -2,7 +2,11 @@ // and the extractors that read them. package browser -import "github.com/moond4rk/hackbrowserdata/internal/masterkey" +import ( + "sort" + + "github.com/moond4rk/hackbrowserdata/internal/masterkey" +) // Def is one browser HBD knows. ID is the -b value and the keys.json vault key; Name is stamped on every record. type Def struct { @@ -58,6 +62,17 @@ func Supported() []Def { return out } +// IDs are this OS's browser IDs, sorted as the -b help has always listed them. +func IDs() []string { + defs := Supported() + ids := make([]string, len(defs)) + for i, d := range defs { + ids[i] = d.ID + } + sort.Strings(ids) + return ids +} + // Lookup finds a browser by ID in the whole table, whatever the running OS, so restore resolves another host's vaults. func Lookup(id string) (Def, bool) { for _, d := range defs { diff --git a/internal/browser/browser_test.go b/internal/browser/browser_test.go index 6806d66..34a5713 100644 --- a/internal/browser/browser_test.go +++ b/internal/browser/browser_test.go @@ -4,6 +4,7 @@ import ( "os" "path" "regexp" + "sort" "strings" "testing" @@ -129,3 +130,9 @@ func TestABERowsMatchPayloadTable(t *testing.T) { } } } + +func TestIDs_AreSupportedSorted(t *testing.T) { + ids := IDs() + assert.True(t, sort.StringsAreSorted(ids), "the -b help has always listed them sorted") + assert.ElementsMatch(t, idsOn(Def.Platform), ids) +} diff --git a/internal/browser/extractor.go b/internal/browser/extractor.go index d3bbb05..032c912 100644 --- a/internal/browser/extractor.go +++ b/internal/browser/extractor.go @@ -22,6 +22,18 @@ type Source struct { Optional bool // the extraction still runs without it } +// Candidates are the Paths for profile p, relative to the user data dir, in priority order. +func (s Source) Candidates(p Profile) []string { + rels := make([]string, len(s.Paths)) + for i, rel := range s.Paths { + if !s.Shared { + rel = path.Join(p.Dir, rel) + } + rels[i] = rel + } + return rels +} + // Extractor declares the sources a category needs and how to parse them. type Extractor struct { Sources []Source @@ -55,10 +67,7 @@ func NewProfileSnapshot(snap snapshot.Snapshot, p Profile, masterKeys func(conte // Path returns where src was captured: its first candidate present in the snapshot. A candidate that was never captured // is skipped; one whose copy failed returns that copy's error. func (ps ProfileSnapshot) Path(src Source) (string, error) { - for _, rel := range src.Paths { - if !src.Shared { - rel = path.Join(ps.Profile.Dir, rel) - } + for _, rel := range src.Candidates(ps.Profile) { p, err := ps.snap.Path(rel) if errors.Is(err, fs.ErrNotExist) { continue diff --git a/internal/browser/extractor_test.go b/internal/browser/extractor_test.go index 754d5ff..8ba8c97 100644 --- a/internal/browser/extractor_test.go +++ b/internal/browser/extractor_test.go @@ -84,3 +84,11 @@ func TestProfileSnapshotMasterKeys(t *testing.T) { assert.Equal(t, want, ps.MasterKeys(context.Background())) assert.Equal(t, 1, calls) } + +func TestSource_Candidates(t *testing.T) { + p := Profile{Name: "Default", Dir: "Default"} + assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{Paths: []string{"Network/Cookies", "Cookies"}}.Candidates(p)) + assert.Equal(t, []string{"Local State"}, Source{Paths: []string{"Local State"}, Shared: true}.Candidates(p)) + assert.Equal(t, []string{"History"}, Source{Paths: []string{"History"}}.Candidates(Profile{Name: "default"}), + "a user data dir that is itself the profile") +} diff --git a/internal/category/category.go b/internal/category/category.go index 8d7e315..2620283 100644 --- a/internal/category/category.go +++ b/internal/category/category.go @@ -47,6 +47,15 @@ func All() []Category { return []Category{Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage} } +func Names() []string { + all := All() + names := make([]string, len(all)) + for i, c := range all { + names[i] = c.String() + } + return names +} + func Parse(s string) (Category, error) { for _, c := range All() { if c.String() == s { diff --git a/internal/category/category_test.go b/internal/category/category_test.go index db9ba87..ed89e04 100644 --- a/internal/category/category_test.go +++ b/internal/category/category_test.go @@ -60,3 +60,9 @@ func TestZeroIsNone(t *testing.T) { var c Category assert.NotContains(t, All(), c) } + +func TestNames(t *testing.T) { + assert.Equal(t, []string{ + "password", "cookie", "bookmark", "history", "download", "creditcard", "extension", "localstorage", "sessionstorage", + }, Names()) +} diff --git a/internal/export/writer.go b/internal/export/writer.go index 029a23e..6431e1b 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -11,7 +11,6 @@ import ( "sort" "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/record" ) @@ -21,6 +20,19 @@ type Writer struct { compress bool files map[category.Category]*categoryFile failed bool + out Output +} + +// Output is what a clean Close left in the output dir: each category file in category order, and the zip with --zip. +type Output struct { + Dir string + Files []File + Zip string +} + +type File struct { + Name string + Count int // records written } type categoryFile struct { @@ -71,12 +83,16 @@ func (w *Writer) write(c category.Category, records []record.Record) error { return nil } -// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them. +// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them in Output. func (w *Writer) Close() error { - var errs []error + var ( + errs []error + files []File + ) for _, c := range category.All() { if cf, ok := w.files[c]; ok { errs = append(errs, cf.close()) + files = append(files, File{Name: cf.name, Count: cf.count}) } } if err := errors.Join(errs...); err != nil { @@ -91,19 +107,17 @@ func (w *Writer) Close() error { } return nil } - fmt.Fprintln(os.Stderr) - log.Infof("Exported to %s/", w.dir) - for _, c := range category.All() { - if cf, ok := w.files[c]; ok { - log.Infof(" %-24s %d entries", cf.name, cf.count) - } - } + w.out = Output{Dir: w.dir, Files: files} if w.compress { return w.pack() } return nil } +func (w *Writer) Output() Output { + return w.out +} + // pack removes the loose files only after the zip is in place, so a failure leaves every one of them where it was. func (w *Writer) pack() error { names := make([]string, 0, len(w.files)) @@ -120,13 +134,13 @@ func (w *Writer) pack() error { return fmt.Errorf("compress: remove %s: %w", name, err) } } - log.Infof("Compressed: %s/%s", w.dir, zipName) + w.out.Zip = zipName return nil } // writeZip writes the zip under a temp name beside dst and renames it into place once it is complete. func writeZip(dst, dir string, names []string) (err error) { - tmp, err := os.OpenFile(dst+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o666) + tmp, err := os.OpenFile(dst+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return fmt.Errorf("create %s: %w", dst, err) } diff --git a/internal/export/writer_test.go b/internal/export/writer_test.go index 35b1b27..8882d4e 100644 --- a/internal/export/writer_test.go +++ b/internal/export/writer_test.go @@ -9,6 +9,7 @@ import ( "io" "os" "path/filepath" + "runtime" "strings" "testing" "time" @@ -334,6 +335,20 @@ func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { var cookies []record.Cookie readJSON(t, filepath.Join(dir, "cookie.json"), &cookies) assert.Empty(t, cookies) + assert.Zero(t, w.Output(), "a failed run lists nothing") +} + +func TestClose_OutputListsTheFilesInCategoryOrder(t *testing.T) { + dir := t.TempDir() + w, err := NewWriter(dir, JSON, false) + require.NoError(t, err) + require.NoError(t, w.Write(category.History, []record.Record{&record.History{URL: "https://a.example"}})) + require.NoError(t, w.Write(category.Password, []record.Record{ + &record.Login{URL: "https://b.example"}, &record.Login{URL: "https://c.example"}, + })) + require.NoError(t, w.Close()) + + assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, w.Output()) } // --- --zip --- @@ -369,6 +384,29 @@ func TestClose_ZipFailureKeepsTheFiles(t *testing.T) { assert.Equal(t, []string{"cookie.csv", "history.csv", "password.csv", "results.zip"}, dirNames(t, dir)) } +func TestClose_ZipOutputNamesTheArchive(t *testing.T) { + dir := filepath.Join(t.TempDir(), "results") + w, err := NewWriter(dir, CSV, true) + require.NoError(t, err) + require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://a.example"}})) + require.NoError(t, w.Close()) + + assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.csv", Count: 1}}, Zip: "results.zip"}, w.Output()) +} + +// The zip holds the same records as the category files, so it gets their owner-only mode. +func TestClose_ZipIsOwnerOnly(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows has no mode bits to check") + } + dir := filepath.Join(t.TempDir(), "results") + require.NoError(t, zipAll(dir, chromeExtractions()...)) + + info, err := os.Stat(filepath.Join(dir, "results.zip")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) +} + func TestClose_ZipWithNothingWrittenFails(t *testing.T) { dir := filepath.Join(t.TempDir(), "results") require.Error(t, zipAll(dir)) diff --git a/internal/log/level.go b/internal/log/level.go index 8843d31..740e679 100644 --- a/internal/log/level.go +++ b/internal/log/level.go @@ -14,14 +14,6 @@ const ( // WarnLevel is used for undesired but relatively expected events, // which may indicate a problem. WarnLevel - - // ErrorLevel is used for undesired and unexpected events that - // the program can recover from. - ErrorLevel - - // FatalLevel is used for undesired and unexpected events that - // the program cannot recover from. - FatalLevel ) func (l Level) String() string { @@ -32,10 +24,6 @@ func (l Level) String() string { return "INF" case WarnLevel: return "WRN" - case ErrorLevel: - return "ERR" - case FatalLevel: - return "FTL" default: return "???" } diff --git a/internal/log/log.go b/internal/log/log.go index 939b9af..83ec32f 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -5,57 +5,19 @@ import "fmt" // defaultLogger is the default logger used by the package-level functions. var defaultLogger = NewLogger(nil) -// SetLevel sets the minimum level of the package-level logger; messages below v -// are suppressed. Consumers embedding HackBrowserData as a library use it to -// quiet output, e.g. SetLevel(FatalLevel) to silence everything short of a fatal -// error. It panics if v is less than DebugLevel or greater than FatalLevel. -func SetLevel(v Level) { - defaultLogger.SetLevel(v) -} - // SetVerbose lowers the package-level logger to DebugLevel. func SetVerbose() { - SetLevel(DebugLevel) -} - -func Debug(args ...any) { - defaultLogger.logMsg(DebugLevel, fmt.Sprint(args...)) + defaultLogger.SetLevel(DebugLevel) } func Debugf(format string, args ...any) { defaultLogger.logMsg(DebugLevel, fmt.Sprintf(format, args...)) } -func Info(args ...any) { - defaultLogger.logMsg(InfoLevel, fmt.Sprint(args...)) -} - func Infof(format string, args ...any) { defaultLogger.logMsg(InfoLevel, fmt.Sprintf(format, args...)) } -func Warn(args ...any) { - defaultLogger.logMsg(WarnLevel, fmt.Sprint(args...)) -} - func Warnf(format string, args ...any) { defaultLogger.logMsg(WarnLevel, fmt.Sprintf(format, args...)) } - -func Error(args ...any) { - defaultLogger.logMsg(ErrorLevel, fmt.Sprint(args...)) -} - -func Errorf(format string, args ...any) { - defaultLogger.logMsg(ErrorLevel, fmt.Sprintf(format, args...)) -} - -func Fatal(args ...any) { - defaultLogger.logMsg(FatalLevel, fmt.Sprint(args...)) - osExit(1) -} - -func Fatalf(format string, args ...any) { - defaultLogger.logMsg(FatalLevel, fmt.Sprintf(format, args...)) - osExit(1) -} diff --git a/internal/log/log_test.go b/internal/log/log_test.go index ec08a55..c3c859c 100644 --- a/internal/log/log_test.go +++ b/internal/log/log_test.go @@ -1,25 +1,22 @@ package log import ( + "io" "testing" "github.com/stretchr/testify/assert" ) -func TestSetLevel(t *testing.T) { - t.Cleanup(func() { SetLevel(InfoLevel) }) // restore package default - - SetLevel(FatalLevel) - assert.False(t, defaultLogger.canLogAt(InfoLevel), "Info must be suppressed at FatalLevel") - assert.False(t, defaultLogger.canLogAt(WarnLevel), "Warn must be suppressed at FatalLevel") - assert.False(t, defaultLogger.canLogAt(ErrorLevel), "Error must be suppressed at FatalLevel") - assert.True(t, defaultLogger.canLogAt(FatalLevel), "Fatal must still log at FatalLevel") +func TestSetVerbose(t *testing.T) { + t.Cleanup(func() { defaultLogger.SetLevel(InfoLevel) }) // restore package default + assert.False(t, defaultLogger.canLogAt(DebugLevel), "Debug must be suppressed by default") SetVerbose() assert.True(t, defaultLogger.canLogAt(DebugLevel), "SetVerbose must enable Debug") } func TestSetLevelInvalidPanics(t *testing.T) { - t.Cleanup(func() { SetLevel(InfoLevel) }) - assert.Panics(t, func() { SetLevel(FatalLevel + 1) }) + logger := NewLogger(newBase(io.Discard)) + assert.Panics(t, func() { logger.SetLevel(DebugLevel - 1) }) + assert.Panics(t, func() { logger.SetLevel(WarnLevel + 1) }) } diff --git a/internal/log/logger.go b/internal/log/logger.go index 5a2ca44..d68b4dc 100644 --- a/internal/log/logger.go +++ b/internal/log/logger.go @@ -35,9 +35,9 @@ func (l *Logger) canLogAt(v Level) bool { } // SetLevel sets the logger level. -// It panics if v is less than DebugLevel or greater than FatalLevel. +// It panics if v is less than DebugLevel or greater than WarnLevel. func (l *Logger) SetLevel(v Level) { - if v < DebugLevel || v > FatalLevel { + if v < DebugLevel || v > WarnLevel { panic("log: invalid log level") } atomic.StoreInt32((*int32)(&l.minLevel), int32(v)) @@ -57,48 +57,18 @@ func (l *Logger) logMsg(lvl Level, msg string) { l.base.Log(baseCallerSkip, lvl, msg) } -func (l *Logger) Debug(args ...any) { - l.logMsg(DebugLevel, fmt.Sprint(args...)) -} - func (l *Logger) Debugf(format string, args ...any) { l.logMsg(DebugLevel, fmt.Sprintf(format, args...)) } -func (l *Logger) Info(args ...any) { - l.logMsg(InfoLevel, fmt.Sprint(args...)) -} - func (l *Logger) Infof(format string, args ...any) { l.logMsg(InfoLevel, fmt.Sprintf(format, args...)) } -func (l *Logger) Warn(args ...any) { - l.logMsg(WarnLevel, fmt.Sprint(args...)) -} - func (l *Logger) Warnf(format string, args ...any) { l.logMsg(WarnLevel, fmt.Sprintf(format, args...)) } -func (l *Logger) Error(args ...any) { - l.logMsg(ErrorLevel, fmt.Sprint(args...)) -} - -func (l *Logger) Errorf(format string, args ...any) { - l.logMsg(ErrorLevel, fmt.Sprintf(format, args...)) -} - -func (l *Logger) Fatal(args ...any) { - l.logMsg(FatalLevel, fmt.Sprint(args...)) - osExit(1) -} - -func (l *Logger) Fatalf(format string, args ...any) { - l.logMsg(FatalLevel, fmt.Sprintf(format, args...)) - osExit(1) -} - // Base is the interface that underlies the Logger. It receives the caller // skip count, log level, and formatted message. type Base interface { @@ -111,8 +81,6 @@ type Base interface { // [DBG] file.go:42: message // [INF] message // [WRN] message -// [ERR] message -// [FTL] message type baseLogger struct { out io.Writer mu sync.Mutex @@ -122,8 +90,6 @@ func newBase(out io.Writer) *baseLogger { return &baseLogger{out: out} } -var osExit = os.Exit - // continuation is the indent for multi-line messages. // Width matches "[DBG] " (6 chars). const continuation = " " diff --git a/internal/log/logger_test.go b/internal/log/logger_test.go index 4d52094..8951d15 100644 --- a/internal/log/logger_test.go +++ b/internal/log/logger_test.go @@ -39,7 +39,7 @@ func TestLoggerDebug(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) logger.SetLevel(DebugLevel) - logger.Debug(message) + logger.Debugf("%s", message) got := buf.String() assert.Regexp(t, tc.wantedPattern, got) }) @@ -55,7 +55,7 @@ func TestLoggerInfo(t *testing.T) { t.Run(tc.description, func(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) - logger.Info(message) + logger.Infof("%s", message) got := buf.String() assert.Regexp(t, tc.wantedPattern, got) }) @@ -71,56 +71,13 @@ func TestLoggerWarn(t *testing.T) { t.Run(tc.description, func(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) - logger.Warn(message) + logger.Warnf("%s", message) got := buf.String() assert.Regexp(t, tc.wantedPattern, got) }) } } -func TestLoggerError(t *testing.T) { - for _, tc := range baseTestCases { - tc := tc - tc.level = ErrorLevel - message := tc.message + tc.suffix - tc.wantedPattern = fmt.Sprintf(`^\[ERR\] %s\n$`, tc.message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) - logger.Error(message) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) - }) - } -} - -func TestLoggerFatal(t *testing.T) { - originalOsExit := osExit - defer func() { osExit = originalOsExit }() - - for _, tc := range baseTestCases { - tc := tc - tc.level = FatalLevel - message := tc.message + tc.suffix - tc.wantedPattern = fmt.Sprintf(`^\[FTL\] %s\n$`, tc.message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - exitCalled := false - exitCode := 0 - osExit = func(code int) { - exitCalled = true - exitCode = code - } - logger := NewLogger(newBase(&buf)) - logger.Fatal(message) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) - assert.True(t, exitCalled) - assert.Equal(t, 1, exitCode) - }) - } -} - type formatTestCase struct { description string format string @@ -196,63 +153,16 @@ func TestLoggerWarnf(t *testing.T) { } } -func TestLoggerErrorf(t *testing.T) { - for _, tc := range formatTestCases { - tc := tc - tc.level = ErrorLevel - message := fmt.Sprintf(tc.format, tc.args...) - tc.wantedPattern = fmt.Sprintf(`^\[ERR\] %s\n$`, message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) - logger.Errorf(tc.format, tc.args...) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) - }) - } -} - -func TestLoggerFatalf(t *testing.T) { - originalOsExit := osExit - defer func() { osExit = originalOsExit }() - for _, tc := range formatTestCases { - tc := tc - tc.level = FatalLevel - message := fmt.Sprintf(tc.format, tc.args...) - tc.wantedPattern = fmt.Sprintf(`^\[FTL\] %s\n$`, message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - exitCalled := false - exitCode := 0 - osExit = func(code int) { - exitCalled = true - exitCode = code - } - logger := NewLogger(newBase(&buf)) - logger.Fatalf(tc.format, tc.args...) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) - assert.True(t, exitCalled) - assert.Equal(t, 1, exitCode) - }) - } -} - func TestLoggerWithLowerLevels(t *testing.T) { - originalOsExit := osExit - defer func() { osExit = originalOsExit }() - - levels := []Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel} + levels := []Level{DebugLevel, InfoLevel, WarnLevel} ops := []struct { op string level Level logFunc func(*Logger) }{ - {"Debug", DebugLevel, func(l *Logger) { l.Debug("hello") }}, - {"Info", InfoLevel, func(l *Logger) { l.Info("hello") }}, - {"Warn", WarnLevel, func(l *Logger) { l.Warn("hello") }}, - {"Error", ErrorLevel, func(l *Logger) { l.Error("hello") }}, - {"Fatal", FatalLevel, func(l *Logger) { l.Fatal("hello") }}, + {"Debugf", DebugLevel, func(l *Logger) { l.Debugf("hello") }}, + {"Infof", InfoLevel, func(l *Logger) { l.Infof("hello") }}, + {"Warnf", WarnLevel, func(l *Logger) { l.Warnf("hello") }}, } for _, setLevel := range levels { @@ -262,10 +172,6 @@ func TestLoggerWithLowerLevels(t *testing.T) { logger.SetLevel(setLevel) expectedOutput := op.level >= setLevel - exitCalled := false - osExit = func(code int) { - exitCalled = true - } op.logFunc(logger) output := buf.String() @@ -274,9 +180,6 @@ func TestLoggerWithLowerLevels(t *testing.T) { } else { assert.Empty(t, output, "setLevel=%s op=%s should be suppressed", setLevel, op.op) } - if op.op == "Fatal" && expectedOutput { - assert.True(t, exitCalled, "Fatal should call osExit") - } } } } @@ -286,11 +189,11 @@ func TestDefaultLevelIsInfo(t *testing.T) { logger := NewLogger(newBase(&buf)) // Debug should be suppressed at default level (InfoLevel). - logger.Debug("debug msg") + logger.Debugf("debug msg") assert.Empty(t, buf.String(), "Debug should be suppressed at default InfoLevel") // Info should be visible at default level. - logger.Info("info msg") + logger.Infof("info msg") assert.Contains(t, buf.String(), "info msg") } @@ -298,7 +201,7 @@ func TestDebugIncludesFileLine(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) logger.SetLevel(DebugLevel) - logger.Debug("test location") + logger.Debugf("test location") got := buf.String() assert.Regexp(t, `^\[DBG\] logger_test\.go:\d+: test location\n$`, got) } @@ -306,14 +209,14 @@ func TestDebugIncludesFileLine(t *testing.T) { func TestInfoHasLabel(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) - logger.Info("clean message") + logger.Infof("clean message") assert.Equal(t, "[INF] clean message\n", buf.String()) } func TestMultilineMessageIndented(t *testing.T) { var buf bytes.Buffer logger := NewLogger(newBase(&buf)) - logger.Warn("line1\nline2\nline3") + logger.Warnf("line1\nline2\nline3") got := buf.String() assert.Equal(t, "[WRN] line1\n line2\n line3\n", got) } diff --git a/rfcs/000-goals-and-constraints.md b/rfcs/000-goals-and-constraints.md index 1541b90..173dcde 100644 --- a/rfcs/000-goals-and-constraints.md +++ b/rfcs/000-goals-and-constraints.md @@ -43,7 +43,7 @@ The external interface is frozen at v1.1.0: every item below behaves exactly as | Archive | zip layout `/`, readable by v1.1.0 `restore` | | Exit status | `0` when the run completes (including partial results and "no browsers found"); `1` when it cannot start or finish | -Not part of the contract: log lines and the human-readable summary on stderr, and row order where v1.1.0's order is unspecified or wrong. Output differs from v1.1.0 only for listed bug fixes where v1.1.0's output was wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, Firefox logins from a profile whose key cannot be recovered, Yandex logins and cards whose data key cannot be recovered, the `browser` value `restore` stamps, and CocCoc cookies on a Windows machine that also has Yandex ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. +Not part of the contract: log lines and the human-readable summary on stderr, and row order where v1.1.0's order is unspecified or wrong. Output differs from v1.1.0 only for listed bug fixes where v1.1.0's output was wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, Firefox logins from a profile whose key cannot be recovered, Yandex logins and cards whose data key cannot be recovered, the `browser` value `restore` stamps, CocCoc cookies on a Windows machine that also has Yandex, and the `--zip` archive's file mode ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. ## Hard constraints diff --git a/rfcs/001-architecture-and-pipeline.md b/rfcs/001-architecture-and-pipeline.md index 2ff7e67..e5441df 100644 --- a/rfcs/001-architecture-and-pipeline.md +++ b/rfcs/001-architecture-and-pipeline.md @@ -54,7 +54,7 @@ Enumerates which supported browsers are present and which profiles each one has, ### 3. Plan -The cross product. For each user data dir, each profile, and each requested category, the profile's `Extractors` say whether the category is supported and which source files it needs. Plan turns that into a flat list of `Extraction`s, a `Skipped` list with a reason for every requested pair that can't run (`unsupported` by this browser, `absent` on disk) plus Discover's failures, and the union of files to capture, deduplicated by user data dir and path — so a file two categories share (Chromium `History` feeds both history and downloads) is copied once (v1.1.0 copied it twice). Plan only stats files; it opens nothing. A `Plan` is plain data, with no functions inside, so `list` prints it and tests compare it. +The cross product. For each user data dir, each profile, and each requested category, the profile's `Extractors` say whether the category is supported and which source files it needs. Plan turns that into a flat list of `Extraction`s, a `Skipped` list with a reason for every requested pair that can't run (`unsupported` by this browser, `absent` on disk, `error` when a file cannot be checked) plus Discover's failures, and the union of files to capture, deduplicated by user data dir and path — so a file two categories share (Chromium `History` feeds both history and downloads) is copied once (v1.1.0 copied it twice). Plan only stats files; it opens nothing. A `Plan` is plain data, with no functions inside, so `list` prints it and tests compare it. **In:** an `app.Discovery` + `app.Request`. **Out:** `app.Plan{Dirs, Files, Extractions, Skipped}`. **Owner:** `app.NewPlan`. @@ -96,7 +96,7 @@ Every extraction resolves to exactly one outcome. This is the single most import | ------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `ok` | Ran with no record-level problems. A source with no rows is `ok` with zero records, not `absent`. | 224 cookies decrypted. | | `partial` | Ran and emitted records, but reported record-level problems — a secret that could not be recovered, a row that could not be parsed. | 224 cookies, 4 with an empty value. | -| `absent` | Supported, but a required source wasn't on disk, or none of its optional ones was. | Browser installed, no `Login Data` file. | +| `absent` | Supported, but a required source wasn't on disk, or none of its optional ones was; an unreadable one is `error`. | Browser installed, no `Login Data` file. | | `unsupported` | This browser can't produce this category. | Firefox credit cards. | | `error` | Failed as a whole: the extractor returned an error, a source failed to copy, or problems were reported and no record could be emitted. | Snapshot copy failed. | diff --git a/rfcs/002-package-layout.md b/rfcs/002-package-layout.md index 0e93186..631ebba 100644 --- a/rfcs/002-package-layout.md +++ b/rfcs/002-package-layout.md @@ -40,7 +40,7 @@ Dependencies point downward and are listed exhaustively; anything not listed is | `cmd/hack-browser-data` | `app`, plus `browser` and `category` for help-text vocabulary (`-b` IDs, `-c` categories), `log` | | `app` | every package below | | `browser/chromium`, `browser/firefox`, `browser/safari` | `browser`, `category`, `record`, `masterkey`, `crypto`, `snapshot`, `sqlitex`, `timeconv`, `log` | -| `export` | `category`, `record`, `log` | +| `export` | `category`, `record` | | `browser` | `category`, `record`, `masterkey`, `snapshot` | | `masterkey` | `crypto`, `winapi`, `abe`, `keychain`, `log` | | `snapshot` | `winapi`, `log` | diff --git a/rfcs/003-core-types.md b/rfcs/003-core-types.md index 460c87c..3f7e047 100644 --- a/rfcs/003-core-types.md +++ b/rfcs/003-core-types.md @@ -55,6 +55,9 @@ type Source struct { Optional bool // the extraction still runs without it } +// Candidates are the Paths for profile p, relative to the user data dir, in priority order. +func (s Source) Candidates(p Profile) []string + // Extractor declares the sources a category needs and how to parse them. type Extractor struct { Sources []Source @@ -65,9 +68,9 @@ type Extractor struct { type Extractors map[category.Category]Extractor ``` -Sources are static data: a base package declares them once per category and never rewrites them per profile. Plan joins a profile-scoped path with the profile's `Dir`, leaves a `Shared` one as it is, and captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. Safari is the exception: a named profile's files sit under two directories named for its UUID, so `safari.Extractors` builds each profile's sources from its `Dir`, and reaches files elsewhere under `~/Library` with `..` from there. +Sources are static data: a base package declares them once per category and never rewrites them per profile. `Source.Candidates` joins a profile-scoped path with the profile's `Dir` and leaves a `Shared` one as it is, for Plan and `ProfileSnapshot.Path` alike; Plan captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. Safari is the exception: a named profile's files sit under two directories named for its UUID, so `safari.Extractors` builds each profile's sources from its `Dir`, and reaches files elsewhere under `~/Library` with `..` from there. -An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none of the profile's own is there: a shared source such as `Local State` never makes an extraction present by itself. An extractor that reads no file — Safari's passwords, which come from the login keychain — always runs. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces v1.1.0's output, including a profile that only ever synced passwords, without a special case. +An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none of the profile's own is there: a shared source such as `Local State` never makes an extraction present by itself. A candidate that cannot be checked — permission denied — makes the extraction an `error` instead, and its profile stays through discovery so the error is reported. An extractor that reads no file — Safari's passwords, which come from the login keychain — always runs. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces v1.1.0's output, including a profile that only ever synced passwords, without a special case. `Extractor` / `Extractors` are **DECIDED**. @@ -129,7 +132,7 @@ type Plan struct { Dirs []browser.UserDataDir // the discovered dirs, in output order Files []snapshot.File // union of files to capture, deduplicated by (user data dir, path) Extractions []Extraction // what will run, in output order (RFC-008) - Skipped []Result // requested but can't run: unsupported, absent, or Discovery.Failed + Skipped []Result // requested but can't run: unsupported, absent, unreadable, or Discovery.Failed } func Discover(req Request) Discovery @@ -201,6 +204,7 @@ func (c Category) String() string func All() []Category // every category, in the order above func Parse(s string) (Category, error) // the inverse of String, for -c +func Names() []string // every category's String, in All's order ``` The package is tiny on purpose, like `timeconv`: it exists so that `category.Cookie` and `record.Cookie` can each mean exactly what they say ([RFC-004](004-naming-decisions.md)). There is no `Category.Sensitive()`: with `-c all` as the frozen default, nothing would consume it. @@ -364,4 +368,17 @@ type Writer struct{ /* unexported */ } func NewWriter(dir string, f Format, zip bool) (*Writer, error) func (w *Writer) Write(c category.Category, records []record.Record) error // one extraction's records; the writer sorts them (RFC-008) func (w *Writer) Close() error // finishes every file; with --zip, packs them +func (w *Writer) Output() Output // what a clean Close left: the files, their counts, the zip + +// Output is what a clean Close left in the output dir; app prints the "Exported to" lines from it. +type Output struct { + Dir string + Files []File // each category file, in category order + Zip string // the archive the files were packed into, with --zip +} + +type File struct { + Name string + Count int // records written +} ``` diff --git a/rfcs/005-browser-definitions.md b/rfcs/005-browser-definitions.md index b08eba1..de9ea8e 100644 --- a/rfcs/005-browser-definitions.md +++ b/rfcs/005-browser-definitions.md @@ -60,6 +60,7 @@ Accessors (names per [RFC-004](004-naming-decisions.md)): ```go browser.Supported() []Def // this OS's rows, in table order browser.Lookup(id string) (Def, bool) // any row, whatever the OS +browser.IDs() []string // this OS's IDs, sorted, for -b's help and errors ``` ## How a browser produces data @@ -97,7 +98,7 @@ Discovery answers one question — which user data dirs and profiles exist — a - **Every match counts.** Every `UserDataDirs` entry is expanded, globs included, and **every** existing match becomes its own `UserDataDir` — as in v1.1.0, which is what keeps the user data dirs of both of a machine's Arc MSIX packages. The first one of a `Def` gets the `DirID` `Def.ID`, later ones `-2`, `-3`… in path order, so IDs are stable from run to run. - **Errors are not absence.** A user data dir that does not exist yields nothing. Any other failure — permission denied, a malformed glob — is returned (joined across entries, next to whatever was found) and becomes an `error` result for that browser in the summary. In v1.1.0 both the Chromium and the Firefox profile scans returned nothing on any read error, and glob errors were dropped while an unmatched pattern was kept as a literal path, so "unreadable" looked exactly like "not installed". - **Profiles by v1.1.0's rules.** Chromium directories holding `Preferences` or `Preferences_02` (Tencent forks), with flat-layout and copied-tree fallbacks; Firefox directories holding known data files; Safari's default profile plus its named profiles (macOS 14+). Whatever the base, a profile counts only when it holds a file some category reads, so a profile created and never used is not listed, archived, or keyed. The named profiles are listed only inside `SafariTabs.db`, so Safari's Discover captures that one file into a temporary snapshot with the snapshot copier and reads the copy, never the live database. -- **No source checks.** Whether a category's file exists is Plan's question, answered as `absent`. v1.1.0 checked every source while constructing the browser and silently dropped a profile that had none; `list` keeps that display rule (profiles with at least one source), but the decision lives outside discovery. +- **No source checks.** Whether a category's file exists is Plan's question, answered as `absent`, or as `error` when the file cannot be checked. v1.1.0 checked every source while constructing the browser and silently dropped a profile that had none; `list` keeps that display rule (profiles with at least one source), but the decision lives outside discovery. - **`-p` replaces `UserDataDirs` for one `Def`.** When `DiscoverOptions.ProfilePath` is set, discovery reads that path instead of the table's entries, and each base interprets it by the rules in [RFC-009](009-cli-surface.md). ## Per-fork overrides — data stays data diff --git a/rfcs/008-output-and-export.md b/rfcs/008-output-and-export.md index c20efd4..2e75ae0 100644 --- a/rfcs/008-output-and-export.md +++ b/rfcs/008-output-and-export.md @@ -20,9 +20,10 @@ type Writer struct{ /* unexported */ } func NewWriter(dir string, f Format, zip bool) (*Writer, error) func (w *Writer) Write(c category.Category, records []record.Record) error // one extraction's records, appended in plan order func (w *Writer) Close() error // finishes every file; with --zip, packs them +func (w *Writer) Output() Output // what a clean Close left: the files, their counts, the zip ``` -Export writes one file per non-empty category: `password.csv`, `cookie.json`, and so on — `.`, where the extension is `csv` or `json` (`cookie-editor` writes `.json`). A category with no records produces no file. The output directory is created with mode `0750` and each file with `0600`, as in v1.1.0. One `-f` value per run, as in v1.1.0. +Export writes one file per non-empty category: `password.csv`, `cookie.json`, and so on — `.`, where the extension is `csv` or `json` (`cookie-editor` writes `.json`). A category with no records produces no file. The output directory is created with mode `0750` and each file with `0600`, as in v1.1.0; the `--zip` archive gets `0600` too, where v1.1.0 created it `0666` before the umask, usually readable by every local user. `Close` itself prints nothing: `Output` lists the files with their record counts and the zip, and `app` prints the "Exported to" lines from it. One `-f` value per run, as in v1.1.0. ## Formats diff --git a/rfcs/011-testing-and-quality.md b/rfcs/011-testing-and-quality.md index a868654..e7e9d9c 100644 --- a/rfcs/011-testing-and-quality.md +++ b/rfcs/011-testing-and-quality.md @@ -60,7 +60,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so - **`-p` for Safari**: names the Safari directory, whose parent stands in for `~/Library`, as in v1.1.0. - **Keychain password precedence**: explicit flag > prompt > none. - **Temp snapshot cleanup**: a run that fails mid-way leaves no copied `Login Data` or `Cookies` behind. -- **Discovery errors are not absence**: an unreadable user data dir (permission denied) is reported as an `error` result, distinct from one that simply isn't there (nothing). The home directory comes from `DiscoverOptions`, so a `t.TempDir()` stands in. +- **Discovery errors are not absence**: an unreadable user data dir (permission denied) is reported as an `error` result, distinct from one that simply isn't there (nothing); a planned source that cannot be checked is an `error` too, not `absent`. The home directory comes from `DiscoverOptions`, so a `t.TempDir()` stands in. - **Safari discovery reads a copy**: listing Safari profiles opens a snapshot copy of `SafariTabs.db`, never the live file. - **Shared executable names**: when App Paths names another vendor's `browser.exe`, the browser's own install location wins.