refactor: drop the archive manifest (#678)

Restore must read v1.1.0's manifest-less archives from the layout, and that path reads every new archive too,
so the manifest only described the layout a second time.
This commit is contained in:
Roger authored and GitHub committed 2026-11-02 11:11:55 +08:00
1 parent 3e9150249c
commit fce4f288df
17 files changed
+39 -266

No files matched your search

+10 -29
View File
@@ -11,8 +11,7 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// Archive also keeps Local State and each profile's marker, so a reader without the manifest still finds the profiles.
// It returns how many files and directories were captured.
// Archive returns how many files and directories it captured.
func Archive(ctx context.Context, discovery Discovery, options Options, archivePath string) (int, error) {
var dirs []browser.UserDataDir
for _, dir := range discovery.Dirs {
@@ -30,13 +29,10 @@ func Archive(ctx context.Context, discovery Discovery, options Options, archiveP
if err := snapshotDir.Capture(ctx, files); err != nil {
return 0, err
}
manifest, fileCount := manifestOf(snapshotDir, dirs, files)
fileCount := countCaptured(snapshotDir, files)
if fileCount == 0 {
return 0, errors.New("no decryption-relevant files found to archive")
}
if err := snapshotDir.WriteManifest(manifest); err != nil {
return 0, err
}
if err := snapshotDir.Zip(archivePath); err != nil {
return 0, fmt.Errorf("write archive %s: %w", archivePath, err)
}
@@ -67,30 +63,15 @@ func archiveFiles(plan Plan, dirs []browser.UserDataDir) []snapshot.File {
return files
}
// manifestOf lists each dir's files that reached the snapshot; one whose copy failed is reported and left out.
func manifestOf(snapshotDir *snapshot.Dir, dirs []browser.UserDataDir, files []snapshot.File) (snapshot.Manifest, int) {
manifest := snapshot.Manifest{Version: snapshot.ManifestVersion, Dirs: []snapshot.ManifestDir{}}
// countCaptured counts the files that reached the snapshot, reporting each one whose copy failed.
func countCaptured(snapshotDir *snapshot.Dir, files []snapshot.File) int {
fileCount := 0
for _, dir := range dirs {
manifestEntry := snapshot.ManifestDir{ID: string(dir.ID), Browser: dir.Browser.Name, Base: dir.Browser.Base.String()}
for _, profile := range dir.Profiles {
manifestEntry.Profiles = append(manifestEntry.Profiles, snapshot.ManifestProfile{Name: profile.Name, Dir: profile.Dir})
}
captured := snapshotDir.Snapshot(string(dir.ID))
for _, file := range files {
if file.UserDataDirID != string(dir.ID) {
continue
}
if _, err := captured.Path(file.RelativePath); err != nil {
log.Warnf("archive: acquire %s/%s: %v", file.UserDataDirID, file.RelativePath, err)
continue
}
manifestEntry.Files = append(manifestEntry.Files, file.RelativePath)
fileCount++
}
if len(manifestEntry.Files) > 0 {
manifest.Dirs = append(manifest.Dirs, manifestEntry)
for _, file := range files {
if _, err := snapshotDir.Snapshot(file.UserDataDirID).Path(file.RelativePath); err != nil {
log.Warnf("archive: acquire %s/%s: %v", file.UserDataDirID, file.RelativePath, err)
continue
}
fileCount++
}
return manifest, fileCount
return fileCount
}
-5
View File
@@ -104,11 +104,7 @@ func TestArchiveGolden(t *testing.T) {
prefix := archiveLayoutBrowser + "/"
names := archiveLayoutEntryNames(t, out)
assert.Contains(t, names, "manifest.json")
for _, name := range names {
if name == "manifest.json" {
continue
}
assert.Truef(t, strings.HasPrefix(name, prefix), "entry %q lacks the %q prefix", name, prefix)
assert.NotContains(t, name, `\`)
assert.NotEqual(t, "LOCK", path.Base(name))
@@ -135,7 +131,6 @@ func TestArchiveRestoreRoundTrip(t *testing.T) {
archive := filepath.Join(t.TempDir(), "data.zip")
_, err = app.Archive(context.Background(), app.Discover(options), options, archive)
require.NoError(t, err)
require.Contains(t, archiveLayoutEntryNames(t, archive), "manifest.json")
out := restoreGolden(t, app.RestoreFlags{Keys: chromiumFixtureKeysFile(t), DataZip: archive, Dir: t.TempDir()})
assert.Equal(t, golden.Read(t, "extract-json.golden"), golden.Bundle(t, out))
+3 -79
View File
@@ -13,7 +13,6 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/export"
"github.com/moond4rk/hackbrowserdata/internal/log"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// RestoreFlags are restore's command-line values as cobra parsed them.
@@ -96,83 +95,12 @@ func readKeys(path string) (masterkey.Dump, error) {
return dump, nil
}
// RestoreDiscovery rebuilds the user data dirs in data, and their keys from dump: from the manifest when data has one,
// else by today's rules, where the vaults' keys name subdirectories or data is one browser's User Data.
// RestoreDiscovery rebuilds the user data dirs under root, and their keys, from the dump: each vault names a
// subdirectory of root, or root is one browser's User Data.
func RestoreDiscovery(
data *snapshot.Dir, dump masterkey.Dump, options Options,
root string, dump masterkey.Dump, options Options,
) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) {
vaults := vaultsOf(dump, options.Browser)
manifest, ok, err := data.ReadManifest()
if err != nil {
return Discovery{}, nil, err
}
if ok {
discovery, keys := fromManifest(data.Path(), manifest, vaults, options.Browser)
return discovery, keys, nil
}
return fromLayout(data.Path(), vaults)
}
func fromManifest(
root string, manifest snapshot.Manifest, vaults []masterkey.Vault, filter string,
) (Discovery, map[browser.UserDataDirID]masterkey.Set) {
var discovery Discovery
keys := make(map[browser.UserDataDirID]masterkey.Set)
for _, manifestEntry := range manifest.Dirs {
if filter != allBrowsers && manifestEntry.Browser != filter {
continue
}
vault, ok := vaultOf(vaults, manifestEntry)
if !ok {
log.Warnf("restore: %s has no keys, skipping", manifestEntry.ID)
continue
}
dir, err := manifestDir(root, manifestEntry, vault)
if err != nil {
log.Warnf("restore: %s: %v", manifestEntry.ID, err)
continue
}
discovery.Dirs = append(discovery.Dirs, dir)
keys[dir.ID] = vault.Keys
}
return discovery, keys
}
// vaultOf finds an entry's keys: the vault carrying its ID, or for a browser's first dir the vault of that browser.
func vaultOf(vaults []masterkey.Vault, manifestEntry snapshot.ManifestDir) (masterkey.Vault, bool) {
for _, vault := range vaults {
if vaultUserDataDirID(vault) == browser.UserDataDirID(manifestEntry.ID) {
return vault, true
}
}
return masterkey.Vault{}, false
}
// manifestDir trusts no path in the manifest that would leave its own directory of the archive.
func manifestDir(root string, manifestEntry snapshot.ManifestDir, vault masterkey.Vault) (browser.UserDataDir, error) {
if manifestEntry.Base != browser.Chromium.String() {
return browser.UserDataDir{}, fmt.Errorf("base %q is not restorable", manifestEntry.Base)
}
if !isPathElement(manifestEntry.ID) {
return browser.UserDataDir{}, fmt.Errorf("id %q is not a directory name", manifestEntry.ID)
}
restoredBrowser, err := vaultBrowser(vault)
if err != nil {
return browser.UserDataDir{}, err
}
dir := browser.UserDataDir{
ID: browser.UserDataDirID(manifestEntry.ID), Browser: restoredBrowser, Path: filepath.Join(root, manifestEntry.ID),
}
for _, manifestProfile := range manifestEntry.Profiles {
if manifestProfile.Dir != "" && !filepath.IsLocal(filepath.FromSlash(manifestProfile.Dir)) {
return browser.UserDataDir{}, fmt.Errorf("profile dir %q is outside the archive", manifestProfile.Dir)
}
dir.Profiles = append(dir.Profiles, browser.Profile{Name: manifestProfile.Name, Dir: manifestProfile.Dir})
}
return dir, nil
}
func fromLayout(root string, vaults []masterkey.Vault) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) {
archived := false
for _, vault := range vaults {
if dirExists(filepath.Join(root, string(vaultUserDataDirID(vault)))) {
@@ -268,10 +196,6 @@ func vaultKeys(vaults []masterkey.Vault) string {
return strings.Join(keys, ", ")
}
func isPathElement(name string) bool {
return name != "" && name != "." && filepath.IsLocal(name) && !strings.ContainsAny(name, `/\`)
}
func dirExists(path string) bool {
info, err := os.Stat(path)
return err == nil && info.IsDir()
+3 -3
View File
@@ -48,8 +48,8 @@ func TestRestoreGolden(t *testing.T) {
assert.Equal(t, want, golden.Bundle(t, unzipped.Path()))
})
// An archive written before the manifest is the bare <browser-key>/ layout, which the vaults resolve.
t.Run("data-zip without a manifest", func(t *testing.T) {
// An archive v1.1.0 wrote is the same <browser-name>/ layout, which the vaults resolve.
t.Run("data-zip", func(t *testing.T) {
dataZip := filepath.Join(t.TempDir(), "data.zip")
require.NoError(t, snapshot.Open(data).Zip(dataZip))
@@ -105,7 +105,7 @@ func restoreGolden(t *testing.T, flags app.RestoreFlags) string {
}
defer data.Close()
discovery, keys, err := app.RestoreDiscovery(data, dump, options)
discovery, keys, err := app.RestoreDiscovery(data.Path(), dump, options)
require.NoError(t, err)
options.Keys = keys
_, err = app.Execute(context.Background(), app.NewPlan(discovery, options), options)
+14 -24
View File
@@ -11,7 +11,6 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
func keysFile(t *testing.T, vaults ...masterkey.Vault) string {
@@ -60,30 +59,21 @@ func TestValidateRestore_RejectsBadInput(t *testing.T) {
assert.Len(t, dump.Vaults, 1)
}
func TestRestoreDiscovery_FromManifest(t *testing.T) {
func TestRestoreDiscovery_SecondUserDataDir(t *testing.T) {
root := t.TempDir()
data := snapshot.Open(root)
require.NoError(t, data.WriteManifest(snapshot.Manifest{Version: snapshot.ManifestVersion, Dirs: []snapshot.ManifestDir{
{ID: "chrome", Browser: "chrome", Base: "chromium", Profiles: []snapshot.ManifestProfile{{Name: "Default", Dir: "Default"}}},
{ID: "arc-2", Browser: "arc", Base: "chromium", Profiles: []snapshot.ManifestProfile{{Name: "Work", Dir: "Profile 1"}}},
{ID: "../outside", Browser: "chrome", Base: "chromium"},
{ID: "edge", Browser: "edge", Base: "chromium", Profiles: []snapshot.ManifestProfile{{Name: "Default", Dir: "../../etc"}}},
}}))
arc2 := testVault("arc")
arc2.ID = "arc-2"
dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), testVault("arc"), arc2, testVault("edge")}}
layoutProfile(t, root, "arc")
layoutProfile(t, root, "arc-2")
second := testVault("arc")
second.ID = "arc-2"
second.Keys = masterkey.Set{masterkey.V10: []byte("arc-2")}
dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), testVault("arc"), second}}
discovery, keys, err := RestoreDiscovery(data, dump, Options{Browser: "all"})
discovery, keys, err := RestoreDiscovery(root, dump, Options{Browser: "arc"})
require.NoError(t, err)
assert.Equal(t, []browser.UserDataDirID{"chrome", "arc-2"}, userDataDirIDs(discovery), "a manifest path that leaves its directory is refused")
assert.Equal(t, "Chrome", discovery.Dirs[0].Browser.DisplayName, "restore sets the display name, as dump does")
assert.Equal(t, []browser.UserDataDirID{"arc", "arc-2"}, userDataDirIDs(discovery), "a vault's ID names its directory")
assert.Equal(t, filepath.Join(root, "arc-2"), discovery.Dirs[1].Path)
assert.Equal(t, []browser.Profile{{Name: "Work", Dir: "Profile 1"}}, discovery.Dirs[1].Profiles)
assert.Equal(t, masterkey.Set{masterkey.V10: []byte("arc")}, keys["arc-2"])
discovery, _, err = RestoreDiscovery(data, dump, Options{Browser: "arc"})
require.NoError(t, err)
assert.Equal(t, []browser.UserDataDirID{"arc-2"}, userDataDirIDs(discovery))
assert.Equal(t, "Arc", discovery.Dirs[1].Browser.DisplayName, "restore sets the display name, as dump does")
assert.Equal(t, masterkey.Set{masterkey.V10: []byte("arc-2")}, keys["arc-2"])
}
func TestRestoreDiscovery_FromLayout(t *testing.T) {
@@ -94,7 +84,7 @@ func TestRestoreDiscovery_FromLayout(t *testing.T) {
nightly.Kind = "chromium-yandex"
dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")}}
discovery, keys, err := RestoreDiscovery(snapshot.Open(root), dump, Options{Browser: "all"})
discovery, keys, err := RestoreDiscovery(root, dump, Options{Browser: "all"})
require.NoError(t, err)
assert.Equal(t, []browser.UserDataDirID{"chrome", "nightly"}, userDataDirIDs(discovery), "a repeated vault restores once, one without data not at all")
assert.Len(t, keys, 2)
@@ -108,10 +98,10 @@ func TestRestoreDiscovery_OneUserDataNeedsOneVault(t *testing.T) {
touch(t, root, "Default", "History")
dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), testVault("edge")}}
_, _, err := RestoreDiscovery(snapshot.Open(root), dump, Options{Browser: "all"})
_, _, err := RestoreDiscovery(root, dump, Options{Browser: "all"})
require.Error(t, err)
discovery, _, err := RestoreDiscovery(snapshot.Open(root), dump, Options{Browser: "edge"})
discovery, _, err := RestoreDiscovery(root, dump, Options{Browser: "edge"})
require.NoError(t, err)
require.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery))
assert.Equal(t, root, discovery.Dirs[0].Path)
-1
View File
@@ -29,4 +29,3 @@ chrome/Profile 1/Session Storage/000004.log method=8 modified=1979-11-30T00:00:0
chrome/Profile 1/Session Storage/CURRENT method=8 modified=1979-11-30T00:00:00Z size=33 crc32=6290110a
chrome/Profile 1/Session Storage/MANIFEST-000001 method=8 modified=1979-11-30T00:00:00Z size=41 crc32=8f635ae8
chrome/Profile 1/Web Data method=8 modified=1979-11-30T00:00:00Z size=18 crc32=e0117ed3
manifest.json method=8 modified=1979-11-30T00:00:00Z size=1004 crc32=ed341f82
-1
View File
@@ -6,4 +6,3 @@ chrome/Default/Preferences method=8 modified=1979-11-30T00:00:00Z size=19 crc32=
chrome/Local State method=8 modified=1979-11-30T00:00:00Z size=11 crc32=015c5138
chrome/Profile 1/Network/Cookies method=8 modified=1979-11-30T00:00:00Z size=25 crc32=184f7580
chrome/Profile 1/Preferences method=8 modified=1979-11-30T00:00:00Z size=21 crc32=be2429c4
manifest.json method=8 modified=1979-11-30T00:00:00Z size=492 crc32=09e41450
-14
View File
@@ -28,20 +28,6 @@ const (
Safari
)
// String is the base's name in a snapshot manifest.
func (b Base) String() string {
switch b {
case Chromium:
return "chromium"
case Firefox:
return "firefox"
case Safari:
return "safari"
default:
return "unknown"
}
}
// Platform is one OS's half of a Browser; one without UserDataDirs means the browser is not supported there.
type Platform struct {
UserDataDirs []string // slash-separated, relative to the home directory; globs allowed
+1 -1
View File
@@ -176,7 +176,7 @@ func KeyFileSpecs(_ browser.UserDataDir) []browser.FileSpec {
return []browser.FileSpec{localState}
}
// ArchiveFileSpecs add Local State and each profile's marker, so a reader without the manifest finds every profile.
// ArchiveFileSpecs add each profile's marker, by which restore rediscovers the profiles, and Local State as v1.1.0 did.
func ArchiveFileSpecs(_ browser.UserDataDir) []browser.FileSpec {
fileSpecs := []browser.FileSpec{localState}
for _, marker := range profileMarkers {
-63
View File
@@ -1,63 +0,0 @@
package snapshot
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
const ManifestVersion = 1
const manifestName = "manifest.json"
// Manifest records what a snapshot directory holds, so a reader rebuilds its user data dirs without discovering them.
type Manifest struct {
Version int `json:"version"`
Dirs []ManifestDir `json:"dirs"`
}
type ManifestDir struct {
ID string `json:"id"`
Browser string `json:"browser"`
Base string `json:"base"`
Profiles []ManifestProfile `json:"profiles"`
Files []string `json:"files"`
}
type ManifestProfile struct {
Name string `json:"name"`
Dir string `json:"dir"`
}
func (d *Dir) WriteManifest(manifest Manifest) error {
data, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return fmt.Errorf("encode manifest: %w", err)
}
if err := os.WriteFile(filepath.Join(d.path, manifestName), append(data, '\n'), 0o600); err != nil {
return fmt.Errorf("write manifest: %w", err)
}
return nil
}
// ReadManifest reports false for a snapshot directory without a manifest, such as an archive written before it.
func (d *Dir) ReadManifest() (Manifest, bool, error) {
data, err := os.ReadFile(filepath.Join(d.path, manifestName))
if errors.Is(err, fs.ErrNotExist) {
return Manifest{}, false, nil
}
if err != nil {
return Manifest{}, false, fmt.Errorf("read manifest: %w", err)
}
var manifest Manifest
if err := json.Unmarshal(data, &manifest); err != nil {
return Manifest{}, false, fmt.Errorf("decode manifest: %w", err)
}
if manifest.Version != ManifestVersion {
return Manifest{}, false, fmt.Errorf("unsupported manifest version %d (this build reads %d)", manifest.Version, ManifestVersion)
}
return manifest, true, nil
}
-38
View File
@@ -1,38 +0,0 @@
package snapshot
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestManifest_RoundTrip(t *testing.T) {
snapshotDir := Open(t.TempDir())
want := Manifest{Version: ManifestVersion, Dirs: []ManifestDir{{
ID: "arc-2", Browser: "arc", Base: "chromium",
Profiles: []ManifestProfile{{Name: "Default", Dir: "Default"}},
Files: []string{"Local State", "Default/Preferences"},
}}}
require.NoError(t, snapshotDir.WriteManifest(want))
got, ok, err := snapshotDir.ReadManifest()
require.NoError(t, err)
assert.True(t, ok)
assert.Equal(t, want, got)
}
func TestManifest_AbsentIsNotAnError(t *testing.T) {
_, ok, err := Open(t.TempDir()).ReadManifest()
require.NoError(t, err)
assert.False(t, ok)
}
func TestManifest_RejectsAnotherVersion(t *testing.T) {
root := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(root, manifestName), []byte(`{"version": 2, "dirs": []}`), 0o600))
_, _, err := Open(root).ReadManifest()
assert.Error(t, err)
}