Files
Roger c823d83e57 refactor(browser): give each base Sources and Extract (#714)
* refactor(browser): give each base Sources and Extract

browser.Input carried every base's secret, so no base said what it needs.
Each base now takes its own secret as a typed parameter, and app holds the
one switch that knows all three. Safari's files no longer need ../ paths.

* refactor(app): make execute the runner's export method

* docs: add a package map to CONTRIBUTING.md

* refactor(app): keep each base's secret on the runner

The bases interface had one real implementation and existed for the test
fake, so it held two of a run's three secrets. The runner holds them all,
and the run tests use real fixtures.

* refactor(chromium): pass data where a function was passed

DiscoverAt took a UserDataDir field by field, the Opera extension list was
a second function for one JSON key, and NeedsMasterKeys repeated by hand
which extractors decrypt.

* refactor(app): set both passwords after the flags are valid

The keychain password went in as a ValidateDump argument and the Firefox
one was assigned afterwards; cmd now sets both the same way.

* refactor: rename dumpKeysWith and CandidatePaths

buildKeyFile says what it returns, and DirRelativePaths says what its paths
are relative to. A failed browser's dir ID no longer comes from a cast.

* refactor(app): plan extractions without a plan struct

dirPlan and plannedExtraction existed to carry a profile and three lists.
An Extraction now holds its Profile, and planExtractions returns the lists.

* refactor(browser): rename profileAt and downloadsOf

profileAt returned a user data dir in two shapes, and downloadsOf returned
a function. Both bases now have dirFromProfilePath with one shape, and
Safari has newDownloadExtractor beside its other constructors.

* refactor: use one short name for a user data dir in app

Fields said UserDataDirID beside Dirs and DirFailure, and runDir did not
say what it runs. They are DirID and runExtractions; the type keeps its
full name.

* refactor(app): rename withData to dropEmptyProfiles

With reads as adding something, and the function removes profiles. hasData
loses a parameter that always held sourcesFor's result.

* refactor: rename five functions that misstate what they do

untilDone had no verb, canCreateIn asked a yes/no question but returned an
error, failAll only built results, sortKeyOf was the last xxxOf, and
checkProfilePath returned a value where its siblings return only an error.

* refactor: name forks as forks and drop the For lookups

The fork table was typed override while every variable said fork, and six
lookups were named for a preposition, not for what they return. The other
renames make one name mean one thing: extractors, dataSources, extractFile.

* refactor(browser): drop parameters Sources and Extract ignore

No interface makes the three bases share a signature, so the blank
parameters only hid that Chromium's sources vary by dir, Safari's by
profile, and that only Safari's extraction can be cancelled.

* refactor(browser): ask a base for one category's sources

Sources returned every category's files, so its name had no object and
each base carried a loop projecting its table. Keyed by category it is
the same lookup as Extract and NeedsMasterKeys.

* refactor: report a locked keychain as data, not a log line

Dump and DumpKeys return results for cmd to print, yet warned about the
keychain themselves, with the sentence passed in as an argument. Now cmd
says every sentence; warnIfLocked and printNothingFound take no message.

* refactor(cmd): rename printExported to printExportedFiles

Exported is an adjective; the function lists the files a run wrote.
2026-11-22 23:52:12 +08:00

210 lines
6.9 KiB
Go

// Package chromium is the Chromium base: profile discovery, file parsing, and where a user data dir's keys come from.
package chromium
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// profileMarkers add Preferences_02 for Sogou and QQ; a marker keeps dirs like Crashpad from passing as profiles.
var profileMarkers = []string{"Preferences", "Preferences_02"}
// Discover yields nothing for a missing user data dir; any other failure is returned beside whatever was found.
func Discover(chromiumBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) {
if dir, ok := dirFromProfilePath(chromiumBrowser, options.ProfilePath); ok {
return []browser.UserDataDir{dir}, nil
}
paths, err := userDataDirPaths(chromiumBrowser, options)
errs := []error{err}
var dirs []browser.UserDataDir
for i, path := range paths {
dir := browser.UserDataDir{ID: chromiumBrowser.UserDataDirID(i), Browser: chromiumBrowser, Path: path}
profiles, err := discoverProfiles(dir)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
errs = append(errs, fmt.Errorf("%s: %w", path, err))
continue
}
dir.Profiles = profiles
dirs = append(dirs, dir)
}
return dirs, errors.Join(errs...)
}
// DiscoverProfiles reads the profiles of a user data dir the table does not name, such as a copy restore was given, in
// the on-disk format dir.VaultKind names.
func DiscoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) {
if !isKnownVaultKind(dir.VaultKind) {
return nil, fmt.Errorf("unknown vault kind %q", dir.VaultKind)
}
profiles, err := discoverProfiles(dir)
if err != nil {
return nil, fmt.Errorf("read %s: %w", dir.Path, err)
}
return profiles, nil
}
// dirFromProfilePath takes chrome://version's path: a profile dir without Local State selects that profile of its parent.
func dirFromProfilePath(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) {
if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.RelativePaths()) {
return browser.UserDataDir{}, false
}
clean := filepath.Clean(path)
name := filepath.Base(clean)
return browser.UserDataDir{
ID: chromiumBrowser.UserDataDirID(0),
Browser: chromiumBrowser,
Path: filepath.Dir(clean),
Profiles: []browser.Profile{{Name: name, RelativePath: name}},
}, true
}
// userDataDirPaths keeps every glob match, for both Arc packages; "/" joins keep the paths keys.json recorded.
func userDataDirPaths(chromiumBrowser browser.Browser, options browser.DiscoverOptions) ([]string, error) {
if options.ProfilePath != "" {
return []string{options.ProfilePath}, nil
}
var (
paths []string
errs []error
)
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))
continue
}
paths = append(paths, matches...)
}
return paths, errors.Join(errs...)
}
func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) {
entries, err := os.ReadDir(dir.Path)
if err != nil {
return nil, err
}
var profiles []browser.Profile
for _, entry := range entries {
if entry.IsDir() && !isSkippedProfileDir(entry.Name()) && isProfileDir(filepath.Join(dir.Path, entry.Name())) {
profiles = append(profiles, browser.Profile{Name: entry.Name(), RelativePath: entry.Name()})
}
}
if len(profiles) > 0 {
return profiles, nil
}
// Flat layout (older Opera): check the root before subdirs, so a stray subdir holding profile files can't hide it.
profileFiles := profileFilePaths(dir)
if hasAnyFile(dir.Path, profileFiles) {
return []browser.Profile{{Name: filepath.Base(dir.Path)}}, nil
}
// Copied or restored trees may lack the marker, which no category reads, so a subdir with profile files is one too.
for _, entry := range entries {
if entry.IsDir() && !isSkippedProfileDir(entry.Name()) && hasAnyFile(filepath.Join(dir.Path, entry.Name()), profileFiles) {
profiles = append(profiles, browser.Profile{Name: entry.Name(), RelativePath: entry.Name()})
}
}
return profiles, nil
}
func isProfileDir(path string) bool {
for _, name := range profileMarkers {
if _, err := os.Stat(filepath.Join(path, name)); err == nil {
return true
}
}
return false
}
func isSkippedProfileDir(name string) bool {
switch name {
case "System Profile", "Guest Profile", "Snapshot":
return true
}
return false
}
func profileFilePaths(dir browser.UserDataDir) []string {
var paths []string
for _, extractor := range dirExtractors(dir) {
for _, source := range extractor.sources {
if !source.FromUserDataDir {
paths = append(paths, source.RelativePaths()...)
}
}
}
return paths
}
func hasAnyFile(path string, relativePaths []string) bool {
for _, relativePath := range relativePaths {
if _, err := os.Stat(filepath.Join(path, filepath.FromSlash(relativePath))); err == nil {
return true
}
}
return false
}
// KeyLocator leaves the run's login keychain to the caller, which adds it to the Locator on macOS.
func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Locator, error) {
platform := dir.Browser.Platform()
locator := masterkey.Locator{
SecretLabel: platform.SecretLabel, Executable: platform.Executable, ExecutableFallbacks: platform.ExecutableFallbacks, ABE: platform.ABE,
PortalAppID: portalAppID(dir.Path, platform.PortalAppID),
}
path, err := dirSnapshot.Path(localState.RelativePath)
switch {
case err == nil:
locator.LocalState = path
case !errors.Is(err, fs.ErrNotExist):
return locator, fmt.Errorf("local state: %w", err)
}
return locator, nil
}
// portalAppID is the v12 app id for a dir: a Flatpak install's id is fixed by its sandbox, taken from the
// .var/app/<id>/ path, so it wins outright; otherwise the browser's registered id applies.
func portalAppID(dirPath, registeredID string) string {
if flatpak := flatpakAppID(dirPath); flatpak != "" {
return flatpak
}
return registeredID
}
// flatpakAppID returns the Flatpak application id in a path like ".../.var/app/<id>/config/...", or "" if absent.
func flatpakAppID(dirPath string) string {
_, after, found := strings.Cut(filepath.ToSlash(dirPath), ".var/app/")
if !found {
return ""
}
id, _, _ := strings.Cut(after, "/")
return id
}
// KeySources are the files KeyLocator reads from a snapshot.
func KeySources() []browser.Source {
return []browser.Source{localState}
}
// ArchiveSources add each profile's marker, by which restore rediscovers the profiles, to the key files.
func ArchiveSources() []browser.Source {
sources := KeySources()
for _, marker := range profileMarkers {
sources = append(sources, browser.Source{RelativePath: marker, Optional: true})
}
return sources
}