mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
refactor: rename core types and spell out every name (#677)
Def, Request, DirID, and Source said too little, and short variables and doc comments that skip their name hid intent. varnamelen and staticcheck ST1020-22 now keep both from coming back.
This commit is contained in:
1 parent
0ed920f846
commit
3e9150249c
173 files changed
+3558
-3483
No files matched your search
@@ -9,37 +9,37 @@ import (
|
||||
|
||||
func archiveCmd() *cobra.Command {
|
||||
var (
|
||||
f app.Flags
|
||||
flags app.Flags
|
||||
outputPath string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
command := &cobra.Command{
|
||||
Use: "archive",
|
||||
Short: "Pack decryption-relevant profile files into a zip for cross-host restore",
|
||||
Example: ` hack-browser-data archive
|
||||
hack-browser-data archive -b chrome -c cookie -o chrome-cookies.zip`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
req, err := app.ValidateArchive(f)
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
options, err := app.ValidateArchive(flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := app.Discover(req)
|
||||
if len(d.Dirs) == 0 {
|
||||
discovery := app.Discover(options)
|
||||
if len(discovery.Dirs) == 0 {
|
||||
log.Warnf("no browsers found")
|
||||
return nil
|
||||
}
|
||||
n, err := app.Archive(cmd.Context(), d, req, outputPath)
|
||||
fileCount, err := app.Archive(command.Context(), discovery, options, outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("Archived %d entries to %s", n, outputPath)
|
||||
log.Infof("Archived %d entries to %s", fileCount, outputPath)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&f.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
cmd.Flags().StringVarP(&f.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "browser-data.zip", "output archive of decryption-relevant browser files")
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
command.Flags().StringVarP(&outputPath, "output", "o", "browser-data.zip", "output archive of decryption-relevant browser files")
|
||||
|
||||
return cmd
|
||||
return command
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
)
|
||||
|
||||
func dumpCmd() *cobra.Command {
|
||||
var f app.Flags
|
||||
var flags app.Flags
|
||||
|
||||
cmd := &cobra.Command{
|
||||
command := &cobra.Command{
|
||||
Use: "dump",
|
||||
Short: "Extract and decrypt browser data (default command)",
|
||||
Example: ` hack-browser-data dump
|
||||
@@ -21,42 +21,43 @@ func dumpCmd() *cobra.Command {
|
||||
hack-browser-data dump -b chrome -f json -d output
|
||||
hack-browser-data dump -f cookie-editor
|
||||
hack-browser-data dump --zip`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runDump(cmd.Context(), cmd.ErrOrStderr(), f)
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
return runDump(command.Context(), command.ErrOrStderr(), flags)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&f.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
cmd.Flags().StringVarP(&f.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
cmd.Flags().StringVarP(&f.Format, "format", "f", "json", "output format: csv|json|cookie-editor")
|
||||
cmd.Flags().StringVarP(&f.Dir, "dir", "d", "results", "output directory")
|
||||
cmd.Flags().StringVarP(&f.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version")
|
||||
keychainPasswordFlags(cmd, &f)
|
||||
cmd.Flags().BoolVar(&f.Zip, "zip", false, "compress output to zip")
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor")
|
||||
command.Flags().StringVarP(&flags.Dir, "dir", "d", "results", "output directory")
|
||||
command.Flags().StringVarP(&flags.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version")
|
||||
keychainPasswordFlags(command, &flags)
|
||||
command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip")
|
||||
|
||||
return cmd
|
||||
return command
|
||||
}
|
||||
|
||||
func keychainPasswordFlags(cmd *cobra.Command, f *app.Flags) {
|
||||
cmd.Flags().StringVar(&f.KeychainPassword, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)")
|
||||
cmd.Flags().BoolVar(&f.KeychainPasswordStdin, "keychain-pw-stdin", false, "read the macOS keychain password from the first line of stdin")
|
||||
cmd.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin")
|
||||
func keychainPasswordFlags(command *cobra.Command, flags *app.Flags) {
|
||||
command.Flags().StringVar(&flags.KeychainPassword, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)")
|
||||
command.Flags().BoolVar(&flags.KeychainPasswordStdin, "keychain-pw-stdin", false,
|
||||
"read the macOS keychain password from the first line of stdin")
|
||||
command.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin")
|
||||
}
|
||||
|
||||
func runDump(ctx context.Context, stderr io.Writer, f app.Flags) error {
|
||||
req, err := app.Validate(f)
|
||||
func runDump(ctx context.Context, stderr io.Writer, flags app.Flags) error {
|
||||
options, err := app.Validate(flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := app.Discover(req)
|
||||
if len(d.Dirs) == 0 {
|
||||
if len(d.Failed) > 0 {
|
||||
report(stderr, app.Summary{Results: d.Failed})
|
||||
discovery := app.Discover(options)
|
||||
if len(discovery.Dirs) == 0 {
|
||||
if len(discovery.Failed) > 0 {
|
||||
report(stderr, app.Summary{Results: discovery.Failed})
|
||||
}
|
||||
log.Warnf("no browsers found")
|
||||
return nil
|
||||
}
|
||||
summary, err := app.Execute(ctx, app.NewPlan(d, req), req)
|
||||
summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options)
|
||||
if ctx.Err() == nil {
|
||||
report(stderr, summary)
|
||||
}
|
||||
|
||||
@@ -13,21 +13,21 @@ import (
|
||||
|
||||
func dumpKeysCmd() *cobra.Command {
|
||||
var (
|
||||
f app.Flags
|
||||
flags app.Flags
|
||||
outputPath string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
command := &cobra.Command{
|
||||
Use: "dumpkeys",
|
||||
Short: "Export Chromium master keys as JSON for cross-host decryption",
|
||||
Example: ` hack-browser-data dumpkeys -o keys.json
|
||||
hack-browser-data dumpkeys -b chrome`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
req, err := app.ValidateKeys(f)
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
options, err := app.ValidateKeys(flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dump, err := app.DumpKeys(cmd.Context(), app.Discover(req), req)
|
||||
dump, err := app.DumpKeys(command.Context(), app.Discover(options), options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -44,9 +44,9 @@ func dumpKeysCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&f.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "output file (default: stdout)")
|
||||
keychainPasswordFlags(cmd, &f)
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
command.Flags().StringVarP(&outputPath, "output", "o", "", "output file (default: stdout)")
|
||||
keychainPasswordFlags(command, &flags)
|
||||
|
||||
return cmd
|
||||
return command
|
||||
}
|
||||
@@ -18,46 +18,46 @@ func TestFlagSurface(t *testing.T) {
|
||||
|
||||
func flagSurface(root *cobra.Command) string {
|
||||
var lines []string
|
||||
for _, cmd := range sortedCommands(root) {
|
||||
cmd.InitDefaultHelpFlag()
|
||||
path := cmd.CommandPath()
|
||||
for _, f := range sortedFlags(cmd.LocalFlags()) {
|
||||
for _, command := range sortedCommands(root) {
|
||||
command.InitDefaultHelpFlag()
|
||||
path := command.CommandPath()
|
||||
for _, flag := range sortedFlags(command.LocalFlags()) {
|
||||
marker := ""
|
||||
if cmd.PersistentFlags().Lookup(f.Name) == f {
|
||||
if command.PersistentFlags().Lookup(flag.Name) == flag {
|
||||
marker = "persistent"
|
||||
}
|
||||
lines = append(lines, flagLine(path, f, marker))
|
||||
lines = append(lines, flagLine(path, flag, marker))
|
||||
}
|
||||
for _, f := range sortedFlags(cmd.InheritedFlags()) {
|
||||
lines = append(lines, flagLine(path, f, "inherited"))
|
||||
for _, flag := range sortedFlags(command.InheritedFlags()) {
|
||||
lines = append(lines, flagLine(path, flag, "inherited"))
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n") + "\n"
|
||||
}
|
||||
|
||||
func sortedCommands(root *cobra.Command) []*cobra.Command {
|
||||
cmds := []*cobra.Command{root}
|
||||
for i := 0; i < len(cmds); i++ {
|
||||
cmds = append(cmds, cmds[i].Commands()...)
|
||||
commands := []*cobra.Command{root}
|
||||
for i := 0; i < len(commands); i++ {
|
||||
commands = append(commands, commands[i].Commands()...)
|
||||
}
|
||||
sort.Slice(cmds, func(i, j int) bool { return cmds[i].CommandPath() < cmds[j].CommandPath() })
|
||||
return cmds
|
||||
sort.Slice(commands, func(i, j int) bool { return commands[i].CommandPath() < commands[j].CommandPath() })
|
||||
return commands
|
||||
}
|
||||
|
||||
func sortedFlags(fs *pflag.FlagSet) []*pflag.Flag {
|
||||
func sortedFlags(flagSet *pflag.FlagSet) []*pflag.Flag {
|
||||
var flags []*pflag.Flag
|
||||
fs.VisitAll(func(f *pflag.Flag) { flags = append(flags, f) })
|
||||
flagSet.VisitAll(func(flag *pflag.Flag) { flags = append(flags, flag) })
|
||||
sort.Slice(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name })
|
||||
return flags
|
||||
}
|
||||
|
||||
func flagLine(path string, f *pflag.Flag, marker string) string {
|
||||
func flagLine(path string, flag *pflag.Flag, marker string) string {
|
||||
// Usage text is excluded: its wording may still be clarified, while name, shorthand, type and default are frozen.
|
||||
fields := []string{path, "--" + f.Name}
|
||||
if f.Shorthand != "" {
|
||||
fields = append(fields, "-"+f.Shorthand)
|
||||
fields := []string{path, "--" + flag.Name}
|
||||
if flag.Shorthand != "" {
|
||||
fields = append(fields, "-"+flag.Shorthand)
|
||||
}
|
||||
fields = append(fields, f.Value.Type(), strconv.Quote(f.DefValue))
|
||||
fields = append(fields, flag.Value.Type(), strconv.Quote(flag.DefValue))
|
||||
if marker != "" {
|
||||
fields = append(fields, marker)
|
||||
}
|
||||
|
||||
@@ -7,15 +7,15 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Windows reads USERPROFILE rather than HOME, so both point at the fixture.
|
||||
// setHome sets USERPROFILE too, because Windows reads it rather than HOME.
|
||||
func setHome(t *testing.T, home string) {
|
||||
t.Helper()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
}
|
||||
|
||||
func runCmd(t *testing.T, cmd *cobra.Command, args ...string) {
|
||||
func runCmd(t *testing.T, command *cobra.Command, args ...string) {
|
||||
t.Helper()
|
||||
cmd.SetArgs(args)
|
||||
require.NoError(t, cmd.Execute())
|
||||
command.SetArgs(args)
|
||||
require.NoError(t, command.Execute())
|
||||
}
|
||||
@@ -16,70 +16,70 @@ import (
|
||||
func listCmd() *cobra.Command {
|
||||
var detail bool
|
||||
|
||||
cmd := &cobra.Command{
|
||||
command := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List detected browsers and profiles",
|
||||
Example: ` hack-browser-data list
|
||||
hack-browser-data list --detail`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
req, err := app.ListRequest()
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
options, err := app.ListOptions()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := app.Discover(req)
|
||||
for _, r := range d.Failed {
|
||||
log.Warnf("%s: %v", r.DirID, r.Err)
|
||||
discovery := app.Discover(options)
|
||||
for _, result := range discovery.Failed {
|
||||
log.Warnf("%s: %v", result.UserDataDirID, result.Err)
|
||||
}
|
||||
if len(d.Dirs) == 0 {
|
||||
cmd.Println("No browsers found.")
|
||||
if len(discovery.Dirs) == 0 {
|
||||
command.Println("No browsers found.")
|
||||
return nil
|
||||
}
|
||||
if !detail {
|
||||
return printBasic(cmd.OutOrStdout(), d)
|
||||
return printBasic(command.OutOrStdout(), discovery)
|
||||
}
|
||||
summary, err := app.Count(cmd.Context(), app.NewPlan(d, req), req)
|
||||
summary, err := app.Count(command.Context(), app.NewPlan(discovery, options), options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printDetail(cmd.OutOrStdout(), d, summary)
|
||||
return printDetail(command.OutOrStdout(), discovery, summary)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().BoolVar(&detail, "detail", false, "show per-category entry counts")
|
||||
return cmd
|
||||
command.Flags().BoolVar(&detail, "detail", false, "show per-category entry counts")
|
||||
return command
|
||||
}
|
||||
|
||||
func printBasic(out io.Writer, d app.Discovery) error {
|
||||
w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
|
||||
fmt.Fprintln(w, "Browser\tProfile\tPath")
|
||||
for _, dir := range d.Dirs {
|
||||
for _, p := range dir.Profiles {
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\n", dir.Def.Name, p.Name, filepath.Join(dir.Path, filepath.FromSlash(p.Dir)))
|
||||
func printBasic(out io.Writer, discovery app.Discovery) error {
|
||||
table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
|
||||
fmt.Fprintln(table, "Browser\tProfile\tPath")
|
||||
for _, dir := range discovery.Dirs {
|
||||
for _, profile := range dir.Profiles {
|
||||
fmt.Fprintf(table, "%s\t%s\t%s\n", dir.Browser.DisplayName, profile.Name, filepath.Join(dir.Path, filepath.FromSlash(profile.Dir)))
|
||||
}
|
||||
}
|
||||
return w.Flush()
|
||||
return table.Flush()
|
||||
}
|
||||
|
||||
func printDetail(out io.Writer, d app.Discovery, s app.Summary) error {
|
||||
counts := make(map[app.Extraction]int, len(s.Results))
|
||||
for _, r := range s.Results {
|
||||
counts[r.Extraction] = r.Count
|
||||
func printDetail(out io.Writer, discovery app.Discovery, summary app.Summary) error {
|
||||
counts := make(map[app.Extraction]int, len(summary.Results))
|
||||
for _, result := range summary.Results {
|
||||
counts[result.Extraction] = result.Count
|
||||
}
|
||||
|
||||
w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
|
||||
fmt.Fprint(w, "Browser\tProfile")
|
||||
for _, c := range category.All() {
|
||||
fmt.Fprintf(w, "\t%s", c.String())
|
||||
table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
|
||||
fmt.Fprint(table, "Browser\tProfile")
|
||||
for _, dataCategory := range category.All() {
|
||||
fmt.Fprintf(table, "\t%s", dataCategory.String())
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
for _, dir := range d.Dirs {
|
||||
for _, p := range dir.Profiles {
|
||||
fmt.Fprintf(w, "%s\t%s", dir.Def.Name, p.Name)
|
||||
for _, c := range category.All() {
|
||||
fmt.Fprintf(w, "\t%d", counts[app.Extraction{DirID: dir.ID, Profile: p.Name, Category: c}])
|
||||
fmt.Fprintln(table)
|
||||
for _, dir := range discovery.Dirs {
|
||||
for _, profile := range dir.Profiles {
|
||||
fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name)
|
||||
for _, dataCategory := range category.All() {
|
||||
fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, Profile: profile.Name, Category: dataCategory}])
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
fmt.Fprintln(table)
|
||||
}
|
||||
}
|
||||
return w.Flush()
|
||||
return table.Flush()
|
||||
}
|
||||
@@ -18,10 +18,10 @@ func TestListGolden(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
setHome(t, home)
|
||||
var paths []string
|
||||
for _, inst := range browsertest.ChromiumInstalls {
|
||||
dir := userDataDirOf(t, home, inst.Key)
|
||||
browsertest.ChromiumUserData(t, dir, inst.Key)
|
||||
paths = append(paths, dir, "<"+inst.Key+">")
|
||||
for _, fixture := range browsertest.ChromiumInstalls {
|
||||
dir := userDataDirOf(t, home, fixture.Name)
|
||||
browsertest.ChromiumUserData(t, dir, fixture.Name)
|
||||
paths = append(paths, dir, "<"+fixture.Name+">")
|
||||
}
|
||||
dir := userDataDirOf(t, home, "firefox")
|
||||
browsertest.FirefoxUserData(t, dir)
|
||||
@@ -40,25 +40,25 @@ func TestListGoldenSafari(t *testing.T) {
|
||||
assertListGoldens(t, "list-safari", strings.NewReplacer(library, "<library>"))
|
||||
}
|
||||
|
||||
// The goldens hold the fixture's paths as placeholders, so one golden serves every OS.
|
||||
// assertListGoldens compares with the fixture's paths as placeholders, so one golden serves every OS.
|
||||
func assertListGoldens(t *testing.T, prefix string, paths *strings.Replacer) {
|
||||
t.Helper()
|
||||
for _, detail := range []bool{false, true} {
|
||||
var out bytes.Buffer
|
||||
cmd := listCmd()
|
||||
cmd.SetOut(&out)
|
||||
command := listCmd()
|
||||
command.SetOut(&out)
|
||||
name, args := prefix+".golden", []string{}
|
||||
if detail {
|
||||
name, args = prefix+"-detail.golden", []string{"--detail"}
|
||||
}
|
||||
runCmd(t, cmd, args...)
|
||||
runCmd(t, command, args...)
|
||||
golden.Assert(t, name, paths.Replace(out.String()))
|
||||
}
|
||||
}
|
||||
|
||||
func userDataDirOf(t *testing.T, home, id string) string {
|
||||
func userDataDirOf(t *testing.T, home, browserName string) string {
|
||||
t.Helper()
|
||||
def, ok := browser.Lookup(id)
|
||||
require.True(t, ok, id)
|
||||
return filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))
|
||||
namedBrowser, ok := browser.Lookup(browserName)
|
||||
require.True(t, ok, browserName)
|
||||
return filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0]))
|
||||
}
|
||||
@@ -22,7 +22,7 @@ func rootCmd() *cobra.Command {
|
||||
browsers, Firefox, and Safari on Windows, macOS, and Linux.
|
||||
|
||||
GitHub: https://github.com/moonD4rk/HackBrowserData`,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
PersistentPreRun: func(command *cobra.Command, args []string) {
|
||||
if verbose {
|
||||
log.SetVerbose()
|
||||
}
|
||||
@@ -37,33 +37,33 @@ GitHub: https://github.com/moonD4rk/HackBrowserData`,
|
||||
root.AddCommand(dump, dumpKeysCmd(), archiveCmd(), restoreCmd(), listCmd(), versionCmd())
|
||||
|
||||
// Without a subcommand the root runs dump, as v1.1.0 did, so it carries dump's flags too.
|
||||
root.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
dump.SetContext(cmd.Context())
|
||||
root.RunE = func(command *cobra.Command, args []string) error {
|
||||
dump.SetContext(command.Context())
|
||||
return dump.RunE(dump, args)
|
||||
}
|
||||
dump.Flags().VisitAll(func(f *pflag.Flag) {
|
||||
if root.Flags().Lookup(f.Name) == nil {
|
||||
root.Flags().AddFlag(f)
|
||||
dump.Flags().VisitAll(func(flag *pflag.Flag) {
|
||||
if root.Flags().Lookup(flag.Name) == nil {
|
||||
root.Flags().AddFlag(flag)
|
||||
}
|
||||
})
|
||||
|
||||
for _, c := range root.Commands() {
|
||||
quietWhenStopped(c)
|
||||
for _, command := range root.Commands() {
|
||||
quietWhenStopped(command)
|
||||
}
|
||||
quietWhenStopped(root)
|
||||
return root
|
||||
}
|
||||
|
||||
// quietWhenStopped keeps a stopped run's error and usage off the screen; main then ends the process by the signal.
|
||||
func quietWhenStopped(c *cobra.Command) {
|
||||
run := c.RunE
|
||||
func quietWhenStopped(command *cobra.Command) {
|
||||
run := command.RunE
|
||||
if run == nil {
|
||||
return
|
||||
}
|
||||
c.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
err := run(cmd, args)
|
||||
if err != nil && cmd.Context().Err() != nil {
|
||||
cmd.SilenceErrors, cmd.SilenceUsage = true, true
|
||||
command.RunE = func(invoked *cobra.Command, args []string) error {
|
||||
err := run(invoked, args)
|
||||
if err != nil && invoked.Context().Err() != nil {
|
||||
invoked.SilenceErrors, invoked.SilenceUsage = true, true
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -72,33 +72,33 @@ func quietWhenStopped(c *cobra.Command) {
|
||||
// stopSignals end the process by default; each first cancels the run, so its temporary copies are removed.
|
||||
var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
|
||||
|
||||
type stopError struct{ sig os.Signal }
|
||||
type stopError struct{ received os.Signal }
|
||||
|
||||
func (e stopError) Error() string { return "stopped by " + e.sig.String() }
|
||||
func (e stopError) Error() string { return "stopped by " + e.received.String() }
|
||||
|
||||
func main() {
|
||||
configureDoubleClickMode()
|
||||
ctx, cancel := context.WithCancelCause(context.Background())
|
||||
signals := make(chan os.Signal, 1)
|
||||
for _, sig := range stopSignals {
|
||||
if !signal.Ignored(sig) { // nohup and background jobs keep ignoring what they ignore today
|
||||
signal.Notify(signals, sig)
|
||||
for _, received := range stopSignals {
|
||||
if !signal.Ignored(received) { // nohup and background jobs keep ignoring what they ignore today
|
||||
signal.Notify(signals, received)
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
sig := <-signals
|
||||
received := <-signals
|
||||
signal.Stop(signals) // a second signal ends the process at once
|
||||
if sig == os.Interrupt {
|
||||
if received == os.Interrupt {
|
||||
log.Warnf("Interrupted; cleaning up (press Ctrl-C again to quit at once)")
|
||||
} else {
|
||||
log.Warnf("Stopping; cleaning up")
|
||||
}
|
||||
cancel(stopError{sig})
|
||||
cancel(stopError{received})
|
||||
}()
|
||||
err := rootCmd().ExecuteContext(ctx)
|
||||
var stop stopError
|
||||
if errors.As(context.Cause(ctx), &stop) {
|
||||
exitBy(stop.sig)
|
||||
exitBy(stop.received)
|
||||
}
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
func configureDoubleClickMode() {}
|
||||
|
||||
// exitBy ends the process by sig itself, as the signal would have, so a calling shell or script sees it was stopped.
|
||||
func exitBy(sig os.Signal) {
|
||||
signal.Reset(sig)
|
||||
if s, ok := sig.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), s) == nil {
|
||||
func exitBy(received os.Signal) {
|
||||
signal.Reset(received)
|
||||
if syscallSignal, ok := received.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), syscallSignal) == nil {
|
||||
time.Sleep(time.Second) // the signal ends the process first unless it was ignored at start
|
||||
}
|
||||
os.Exit(1)
|
||||
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) {
|
||||
func assertEndedByInterrupt(t *testing.T, state *os.ProcessState) {
|
||||
t.Helper()
|
||||
status, ok := ps.Sys().(syscall.WaitStatus)
|
||||
status, ok := state.Sys().(syscall.WaitStatus)
|
||||
require.True(t, ok)
|
||||
assert.True(t, status.Signaled(), "ended by the signal, not by an exit code")
|
||||
assert.Equal(t, syscall.SIGINT, status.Signal())
|
||||
|
||||
@@ -19,29 +19,29 @@ func TestStoppedRunPrintsNoErrorOrUsage(t *testing.T) {
|
||||
setHome(t, home)
|
||||
browsertest.ChromiumUserData(t, userDataDirOf(t, home, "chrome"), "chrome")
|
||||
|
||||
for _, tc := range []struct {
|
||||
for _, testCase := range []struct {
|
||||
name, browser string
|
||||
stop bool
|
||||
}{
|
||||
{name: "stopped", browser: "chrome", stop: true},
|
||||
{name: "failed", browser: "nosuch"},
|
||||
} {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
testCase := testCase
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
if tc.stop {
|
||||
if testCase.stop {
|
||||
cancel()
|
||||
}
|
||||
var screen bytes.Buffer
|
||||
root := rootCmd()
|
||||
root.SetOut(&screen)
|
||||
root.SetErr(&screen)
|
||||
root.SetArgs([]string{"-b", tc.browser, "-d", filepath.Join(t.TempDir(), "results")})
|
||||
root.SetArgs([]string{"-b", testCase.browser, "-d", filepath.Join(t.TempDir(), "results")})
|
||||
|
||||
err := root.ExecuteContext(ctx)
|
||||
require.Error(t, err)
|
||||
if tc.stop {
|
||||
if testCase.stop {
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
assert.Empty(t, screen.String())
|
||||
} else {
|
||||
@@ -56,9 +56,9 @@ func TestExitByEndsTheProcessAsTheSignalWould(t *testing.T) {
|
||||
exitBy(os.Interrupt)
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestExitByEndsTheProcessAsTheSignalWould$")
|
||||
cmd.Env = append(os.Environ(), "HBD_TEST_EXIT_BY=1")
|
||||
command := exec.Command(os.Args[0], "-test.run=^TestExitByEndsTheProcessAsTheSignalWould$")
|
||||
command.Env = append(os.Environ(), "HBD_TEST_EXIT_BY=1")
|
||||
var exitErr *exec.ExitError
|
||||
require.ErrorAs(t, cmd.Run(), &exitErr)
|
||||
require.ErrorAs(t, command.Run(), &exitErr)
|
||||
assertEndedByInterrupt(t, exitErr.ProcessState)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) {
|
||||
func assertEndedByInterrupt(t *testing.T, state *os.ProcessState) {
|
||||
t.Helper()
|
||||
assert.Equal(t, uint32(windows.STATUS_CONTROL_C_EXIT), uint32(ps.ExitCode()))
|
||||
assert.Equal(t, uint32(windows.STATUS_CONTROL_C_EXIT), uint32(state.ExitCode()))
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
func browserNames() string {
|
||||
return strings.Join(browser.IDs(), "|")
|
||||
return strings.Join(browser.Names(), "|")
|
||||
}
|
||||
|
||||
func categoryNames() string {
|
||||
@@ -19,8 +19,8 @@ func categoryNames() string {
|
||||
}
|
||||
|
||||
// report prints the run's summary; it is not part of the output, so failing to print it never fails the run.
|
||||
func report(w io.Writer, s app.Summary) {
|
||||
if err := app.Report(w, s); err != nil {
|
||||
func report(writer io.Writer, summary app.Summary) {
|
||||
if err := app.Report(writer, summary); err != nil {
|
||||
log.Warnf("print summary: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -13,56 +13,56 @@ import (
|
||||
)
|
||||
|
||||
func restoreCmd() *cobra.Command {
|
||||
var f app.RestoreFlags
|
||||
var flags app.RestoreFlags
|
||||
|
||||
cmd := &cobra.Command{
|
||||
command := &cobra.Command{
|
||||
Use: "restore",
|
||||
Short: "Decrypt copied profile data using exported master keys",
|
||||
Example: ` 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`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runRestore(cmd.Context(), cmd.ErrOrStderr(), f)
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
return runRestore(command.Context(), command.ErrOrStderr(), flags)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&f.Keys, "keys", "", "keys file from dumpkeys (use - for stdin)")
|
||||
cmd.Flags().StringVar(&f.DataDir, "data-dir", "", "copied profile data dir (archive layout, or one browser's User Data with -b)")
|
||||
cmd.Flags().StringVar(&f.DataZip, "data-zip", "", "zip produced by the archive command (alternative to --data-dir)")
|
||||
cmd.Flags().StringVarP(&f.Browser, "browser", "b", "", "restore only this browser (optional; must match a vault in --keys)")
|
||||
cmd.Flags().StringVarP(&f.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
cmd.Flags().StringVarP(&f.Format, "format", "f", "json", "output format: csv|json|cookie-editor")
|
||||
cmd.Flags().StringVarP(&f.Dir, "dir", "d", "results", "output directory")
|
||||
cmd.Flags().BoolVar(&f.Zip, "zip", false, "compress output to zip")
|
||||
command.Flags().StringVar(&flags.Keys, "keys", "", "keys file from dumpkeys (use - for stdin)")
|
||||
command.Flags().StringVar(&flags.DataDir, "data-dir", "", "copied profile data dir (archive layout, or one browser's User Data with -b)")
|
||||
command.Flags().StringVar(&flags.DataZip, "data-zip", "", "zip produced by the archive command (alternative to --data-dir)")
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "", "restore only this browser (optional; must match a vault in --keys)")
|
||||
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor")
|
||||
command.Flags().StringVarP(&flags.Dir, "dir", "d", "results", "output directory")
|
||||
command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip")
|
||||
|
||||
_ = cmd.MarkFlagRequired("keys")
|
||||
cmd.MarkFlagsMutuallyExclusive("data-dir", "data-zip")
|
||||
_ = command.MarkFlagRequired("keys")
|
||||
command.MarkFlagsMutuallyExclusive("data-dir", "data-zip")
|
||||
|
||||
return cmd
|
||||
return command
|
||||
}
|
||||
|
||||
func runRestore(ctx context.Context, stderr io.Writer, f app.RestoreFlags) error {
|
||||
req, dump, err := app.ValidateRestore(f)
|
||||
func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) error {
|
||||
options, dump, err := app.ValidateRestore(flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := openRestoreData(f.DataDir, f.DataZip)
|
||||
data, err := openRestoreData(flags.DataDir, flags.DataZip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeRestoreData(data)
|
||||
|
||||
d, keys, err := app.RestoreDiscovery(data, dump, req)
|
||||
discovery, keys, err := app.RestoreDiscovery(data, dump, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(d.Dirs) == 0 {
|
||||
if len(discovery.Dirs) == 0 {
|
||||
log.Warnf("no browsers to restore from the supplied keys and data")
|
||||
return nil
|
||||
}
|
||||
req.Keys = keys
|
||||
summary, err := app.Execute(ctx, app.NewPlan(d, req), req)
|
||||
options.Keys = keys
|
||||
summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options)
|
||||
if ctx.Err() == nil {
|
||||
report(stderr, summary)
|
||||
}
|
||||
@@ -73,15 +73,15 @@ func openRestoreData(dataDir, dataZip string) (*snapshot.Dir, error) {
|
||||
if dataDir != "" {
|
||||
return snapshot.Open(dataDir), nil
|
||||
}
|
||||
d, err := snapshot.Unzip(dataZip)
|
||||
snapshotDir, err := snapshot.Unzip(dataZip)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract %s: %w", dataZip, err)
|
||||
}
|
||||
return d, nil
|
||||
return snapshotDir, nil
|
||||
}
|
||||
|
||||
func closeRestoreData(d *snapshot.Dir) {
|
||||
if err := d.Close(); err != nil {
|
||||
func closeRestoreData(snapshotDir *snapshot.Dir) {
|
||||
if err := snapshotDir.Close(); err != nil {
|
||||
log.Warnf("restore: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,9 @@ func versionCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print version information",
|
||||
Run: func(cmd *cobra.Command, _ []string) {
|
||||
Run: func(command *cobra.Command, _ []string) {
|
||||
resolveVersionFromBuildInfo()
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "hack-browser-data %s\n commit: %s\n built: %s\n",
|
||||
fmt.Fprintf(command.OutOrStdout(), "hack-browser-data %s\n commit: %s\n built: %s\n",
|
||||
version, commit, buildDate)
|
||||
},
|
||||
}
|
||||
@@ -36,17 +36,17 @@ func resolveVersionFromBuildInfo() {
|
||||
if info.Main.Version != "" && info.Main.Version != "(devel)" {
|
||||
version = info.Main.Version
|
||||
}
|
||||
for _, s := range info.Settings {
|
||||
switch s.Key {
|
||||
for _, setting := range info.Settings {
|
||||
switch setting.Key {
|
||||
case "vcs.revision":
|
||||
if len(s.Value) > 8 {
|
||||
commit = s.Value[:8]
|
||||
} else if s.Value != "" {
|
||||
commit = s.Value
|
||||
if len(setting.Value) > 8 {
|
||||
commit = setting.Value[:8]
|
||||
} else if setting.Value != "" {
|
||||
commit = setting.Value
|
||||
}
|
||||
case "vcs.time":
|
||||
if s.Value != "" {
|
||||
buildDate = s.Value
|
||||
if setting.Value != "" {
|
||||
buildDate = setting.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user