test: move compat tests into the packages they cover (#669)

The pipeline goldens now live in app, export in export, and keys.json in masterkey, each with its own
testdata; cmd keeps the flag and list goldens. Shared fixtures and golden helpers became the
internal/browser/browsertest and internal/golden packages. The binary is byte-identical.
This commit is contained in:
Roger authored and GitHub committed 2026-10-29 16:12:50 +08:00
1 parent c0a03769f1
commit 07b66adc4d
40 files changed
+190 -125

No files matched your search

@@ -1,137 +0,0 @@
package main
import (
"archive/zip"
"context"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/browser"
)
const archiveLayoutKey = "chrome"
var archiveLayoutProfileFiles = []string{
"Preferences",
"Login Data",
"Network/Cookies",
"History",
"Bookmarks",
"Web Data",
"Secure Preferences",
"Local Storage/leveldb/000003.log",
"Local Storage/leveldb/CURRENT",
"Local Storage/leveldb/LOCK",
"Local Storage/leveldb/MANIFEST-000001",
"Session Storage/000004.log",
"Session Storage/CURRENT",
"Session Storage/LOCK",
"Session Storage/MANIFEST-000001",
}
var archiveLayoutExtraFiles = []string{
"Local State",
"Default/Login Data For Account",
"Default/Network/Cookies-wal",
"Default/Network/Cookies-shm",
"Default/Favicons",
"System Profile/Preferences",
"System Profile/History",
}
func archiveLayoutUserData(t *testing.T, root string) {
t.Helper()
files := append([]string{}, archiveLayoutExtraFiles...)
for _, profile := range []string{"Default", "Profile 1"} {
for _, rel := range archiveLayoutProfileFiles {
files = append(files, profile+"/"+rel)
}
}
for _, rel := range files {
abs := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(abs), 0o755))
require.NoError(t, os.WriteFile(abs, []byte(rel), 0o600))
}
}
func archiveLayoutEntryNames(t *testing.T, zipPath string) []string {
t.Helper()
r, err := zip.OpenReader(zipPath)
require.NoError(t, err)
defer r.Close()
names := make([]string, 0, len(r.File))
for _, f := range r.File {
names = append(names, f.Name)
}
return names
}
func TestArchiveGolden(t *testing.T) {
home := t.TempDir()
def, ok := browser.Lookup(archiveLayoutKey)
require.True(t, ok)
archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])))
tests := []struct {
name string
golden string
categories string
}{
{name: "all", golden: "archive-all.golden", categories: "all"},
{name: "cookie", golden: "archive-cookie.golden", categories: "cookie"},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
req, err := app.ValidateArchive(app.Flags{Browser: archiveLayoutKey, Categories: tt.categories})
require.NoError(t, err)
req.Home = home
out := filepath.Join(t.TempDir(), "browser-data.zip")
n, err := app.Archive(context.Background(), app.Discover(req), req, out)
require.NoError(t, err)
assertGolden(t, tt.golden, fmt.Sprintf("entries=%d\n", n)+zipListing(t, out))
prefix := archiveLayoutKey + "/"
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))
assert.Falsef(t, strings.HasPrefix(name, prefix+"System Profile/"), "entry %q comes from a skipped profile", name)
}
assert.Contains(t, names, prefix+"Default/Network/Cookies")
assert.Contains(t, names, prefix+"Default/Network/Cookies-wal")
assert.NotContains(t, names, prefix+"Default/Favicons")
})
}
}
// archive on one host and restore on another, both through the CLI, write what dump writes.
func TestArchiveRestoreRoundTrip(t *testing.T) {
home := t.TempDir()
setHome(t, home)
for _, inst := range chromiumFixtureInstalls {
def, ok := browser.Lookup(inst.key)
require.True(t, ok, inst.key)
chromiumFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.key)
}
archive := filepath.Join(t.TempDir(), "data.zip")
runCmd(t, archiveCmd(), "-o", archive)
require.Contains(t, archiveLayoutEntryNames(t, archive), "manifest.json")
out := t.TempDir()
chromiumFixtureRestore(t, "--keys", chromiumFixtureKeysFile(t), "--data-zip", archive, "-d", out)
assert.Equal(t, readGolden(t, "extract-json.golden"), bundleDir(t, out))
}
@@ -1,426 +0,0 @@
package main
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"path/filepath"
"sort"
"strings"
"testing"
"time"
"unicode/utf16"
"github.com/stretchr/testify/require"
"github.com/syndtr/goleveldb/leveldb"
"github.com/moond4rk/hackbrowserdata/internal/crypto"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
)
// Only GCM-sealed values (v10 under a 32-byte key, v20) decrypt identically on every OS.
var chromiumFixtureKeys = masterkey.Set{
masterkey.V10: []byte("0123456789abcdef0123456789abcdef"),
masterkey.V20: []byte("0123456789abcdef"),
}
var chromiumFixtureInstalls = []struct {
key string
name string
}{
{key: "chrome", name: "Chrome"},
{key: "edge", name: "Microsoft Edge"},
}
var chromiumFixtureProfiles = []struct {
dir string
label string
start time.Time
accountLogins bool
}{
{dir: "Default", label: "home", start: time.Date(2024, 3, 1, 9, 0, 0, 0, time.UTC), accountLogins: true},
{dir: "Profile 1", label: "work", start: time.Date(2024, 6, 1, 9, 0, 0, 0, time.UTC)},
}
func chromiumFixtureInstallations(t *testing.T, root string) {
t.Helper()
for _, inst := range chromiumFixtureInstalls {
chromiumFixtureUserData(t, filepath.Join(root, inst.key), inst.key)
}
}
func chromiumFixtureUserData(t *testing.T, userDataDir, browserKey string) {
t.Helper()
fixtureWrite(t, filepath.Join(userDataDir, "Local State"), "{}")
for _, p := range chromiumFixtureProfiles {
site := p.label + "." + browserKey + ".test"
chromiumFixtureProfile(t, filepath.Join(userDataDir, p.dir), site, p.start, p.accountLogins)
}
}
func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, accountLogins bool) {
t.Helper()
at := func(offset time.Duration) int64 { return chromiumFixtureMicros(start.Add(offset)) }
link := func(host, path string) string { return "https://" + host + "." + site + path }
v10 := func(plaintext string) string {
return chromiumFixtureSeal(t, "v10", chromiumFixtureKeys[masterkey.V10], plaintext)
}
v20 := func(plaintext string) string {
return chromiumFixtureSeal(t, "v20", chromiumFixtureKeys[masterkey.V20], plaintext)
}
// Chrome 130+ seals SHA256(host_key) ahead of the cookie value, which extraction must strip again.
hostBound := func(host, value string) string {
sum := sha256.Sum256([]byte(host))
return string(sum[:]) + value
}
day := 24 * time.Hour
fixtureWrite(t, filepath.Join(dir, "Preferences"), "{}")
fixtureSQLite(t, filepath.Join(dir, "Login Data"), chromiumFixtureLoginsSchema,
chromiumFixtureInsertLogin(link("accounts", "/"), link("accounts", "/login"), "alice",
v10("correct-horse-battery-staple"), at(time.Hour)),
chromiumFixtureInsertLogin(link("shop", "/"), link("shop", "/signin"), "alice@"+site, v10(`pa,ss"word`), at(2*time.Hour)),
)
if accountLogins {
fixtureSQLite(t, filepath.Join(dir, "Login Data For Account"), chromiumFixtureLoginsSchema,
chromiumFixtureInsertLogin(link("sync", "/"), link("sync", "/auth"), "alice", v10("synced-secret"), at(90*time.Minute)),
)
}
domain, www, app := "."+site, "www."+site, "app."+site
fixtureSQLite(t, filepath.Join(dir, "Network", "Cookies"), chromiumFixtureCookiesSchema,
chromiumFixtureInsertCookie("SID", domain, "/", v20(hostBound(domain, "sid-"+site)),
at(10*time.Minute+123456*time.Microsecond), at(365*day), 1, 1, 1),
chromiumFixtureInsertCookie("prefs", www, "/settings", v10("theme=dark"), at(20*time.Minute), at(30*day), 0, 0, 2),
chromiumFixtureInsertCookie("tracker", domain, "/", v20(hostBound(domain, "opt-out")), at(30*time.Minute), at(730*day), 1, 0, 0),
chromiumFixtureInsertCookie("session", app, "/", v20("ephemeral"), at(40*time.Minute), 0, 1, 1, -1),
)
fixtureSQLite(t, filepath.Join(dir, "History"), chromiumFixtureURLsSchema, chromiumFixtureDownloadsSchema,
chromiumFixtureInsertURL(link("www", "/"), "Home", 42, at(3*time.Hour)),
chromiumFixtureInsertURL(link("docs", "/guide?q=go&lang=en"), `Guide, "quoted" & <b>bold</b>`, 7, at(4*time.Hour)),
chromiumFixtureInsertURL(link("news", "/ja"), "ニュース", 3, at(5*time.Hour)),
chromiumFixtureInsertDownload(`C:\Users\alice\Downloads\report.pdf`, link("files", "/report.pdf"), "application/pdf",
52344, at(6*time.Hour), at(6*time.Hour+3*time.Second)),
chromiumFixtureInsertDownload("/home/alice/Downloads/archive.tar.gz", link("files", "/archive.tar.gz"), "application/gzip",
1048576, at(7*time.Hour), 0),
)
fixtureWrite(t, filepath.Join(dir, "Bookmarks"),
fmt.Sprintf(chromiumFixtureBookmarks, site, at(0), at(8*time.Hour), at(9*time.Hour), at(10*time.Hour)))
fixtureSQLite(t, filepath.Join(dir, "Web Data"), chromiumFixtureCreditCardsSchema,
chromiumFixtureInsertCreditCard("Alice Example", 4, 2031, v10("4111111111111111"), "Travel", "billing-home"),
chromiumFixtureInsertCreditCard("Bob Example", 11, 2029, v10("5500005555555559"), "", ""),
)
fixtureWrite(t, filepath.Join(dir, "Secure Preferences"), chromiumFixtureSecurePreferences)
origin := link("app", "")
dataKey := "_" + origin + "\x00"
chromiumFixtureLevelDB(t, filepath.Join(dir, "Local Storage", "leveldb"), map[string]string{
"VERSION": "1",
"META:" + origin: "\x08\x96\x01",
"METAACCESS:" + origin: "\x10\x20",
dataKey + chromiumFixtureLatin1("greeting"): chromiumFixtureLatin1("caf\xe9"),
dataKey + chromiumFixtureUTF16("言語"): chromiumFixtureUTF16("日本語"),
dataKey + chromiumFixtureLatin1("blob"): chromiumFixtureLatin1(strings.Repeat("x", 2100)),
})
namespace := "namespace-0a1b2c3d_4e5f_6a7b_8c9d_0e1f2a3b4c5d-"
chromiumFixtureLevelDB(t, filepath.Join(dir, "Session Storage"), map[string]string{
namespace + link("app", "/"): "1",
namespace + link("shop", "/"): "2",
"map-1-draft": chromiumFixtureUTF16Raw("Hello, world"),
"map-1-scrollY": chromiumFixtureUTF16Raw("640"),
"map-2-cart": chromiumFixtureUTF16Raw(`{"items":2}`),
"next-map-id": "3",
"version": "1",
})
}
func chromiumFixtureSeal(t *testing.T, version string, key []byte, plaintext string) string {
t.Helper()
nonce := []byte(version + "_nonce_12")
sealed, err := crypto.AESGCMEncrypt(key, nonce, []byte(plaintext))
require.NoError(t, err)
return hex.EncodeToString(append(append([]byte(version), nonce...), sealed...))
}
func chromiumFixtureMicros(ts time.Time) int64 {
const unixToChromiumEpochMicros = 11_644_473_600_000_000
return ts.UnixMicro() + unixToChromiumEpochMicros
}
func chromiumFixtureLatin1(s string) string { return "\x01" + s }
func chromiumFixtureUTF16(s string) string { return "\x00" + chromiumFixtureUTF16Raw(s) }
func chromiumFixtureUTF16Raw(s string) string {
units := utf16.Encode([]rune(s))
b := make([]byte, 2*len(units))
for i, u := range units {
binary.LittleEndian.PutUint16(b[2*i:], u)
}
return string(b)
}
func chromiumFixtureLevelDB(t *testing.T, dir string, entries map[string]string) {
t.Helper()
keys := make([]string, 0, len(entries))
for k := range entries {
keys = append(keys, k)
}
sort.Strings(keys)
db, err := leveldb.OpenFile(dir, nil)
require.NoError(t, err)
for _, k := range keys {
require.NoError(t, db.Put([]byte(k), []byte(entries[k]), nil))
}
require.NoError(t, db.Close())
}
func chromiumFixtureInsertLogin(originURL, actionURL, username, pwdHex string, dateCreated int64) string {
return fmt.Sprintf(
`INSERT INTO logins (origin_url, action_url, username_element, username_value,
password_element, password_value, submit_element, signon_realm, date_created,
blacklisted_by_user, scheme)
VALUES ('%s', '%s', '', '%s', '', x'%s', '', '%s', %d, 0, 0)`,
originURL, actionURL, username, pwdHex, originURL, dateCreated,
)
}
func chromiumFixtureInsertCookie(
name, host, path, encValueHex string, creationUTC, expiresUTC int64, secure, httpOnly, sameSite int,
) string {
persistent := 0
if expiresUTC != 0 {
persistent = 1
}
return fmt.Sprintf(
`INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, value,
encrypted_value, path, expires_utc, is_secure, is_httponly, last_access_utc,
has_expires, is_persistent, priority, samesite, source_scheme, source_port,
last_update_utc, source_type, has_cross_site_ancestor)
VALUES (%d, '%s', '', '%s', '', x'%s', '%s', %d, %d, %d, %d, %d, %d, 1, %d, 2, 443, %d, 0, 0)`,
creationUTC, host, name, encValueHex, path, expiresUTC, secure, httpOnly, creationUTC,
persistent, persistent, sameSite, creationUTC,
)
}
func chromiumFixtureInsertURL(url, title string, visitCount int, lastVisitTime int64) string {
return fmt.Sprintf(
`INSERT INTO urls (url, title, visit_count, typed_count, last_visit_time, hidden)
VALUES ('%s', '%s', %d, 0, %d, 0)`,
url, title, visitCount, lastVisitTime,
)
}
func chromiumFixtureInsertDownload(targetPath, tabURL, mimeType string, totalBytes, startTime, endTime int64) string {
return fmt.Sprintf(
`INSERT INTO downloads (id, guid, current_path, target_path, start_time, received_bytes,
total_bytes, state, danger_type, interrupt_reason, hash, end_time, opened, last_access_time,
transient, referrer, site_url, embedder_download_data, tab_url, tab_referrer_url,
http_method, by_ext_id, by_ext_name, by_web_app_id, etag, last_modified, mime_type, original_mime_type)
VALUES (NULL, '', '', '%s', %d, %d, %d, 1, 0, 0, x'', %d, 0, 0, 0, '', '', '', '%s', '', 'GET', '', '', '', '', '', '%s', '')`,
targetPath, startTime, totalBytes, totalBytes, endTime, tabURL, mimeType,
)
}
func chromiumFixtureInsertCreditCard(name string, month, year int, encNumberHex, nickName, address string) string {
return fmt.Sprintf(
`INSERT INTO credit_cards (guid, name_on_card, expiration_month, expiration_year, card_number_encrypted,
nickname, billing_address_id)
VALUES ('%s-%d-%d', '%s', %d, %d, x'%s', '%s', '%s')`,
name, month, year, name, month, year, encNumberHex, nickName, address,
)
}
const chromiumFixtureLoginsSchema = `CREATE TABLE logins (
origin_url VARCHAR NOT NULL,
action_url VARCHAR,
username_element VARCHAR,
username_value VARCHAR,
password_element VARCHAR,
password_value BLOB,
submit_element VARCHAR,
signon_realm VARCHAR NOT NULL,
date_created INTEGER NOT NULL,
blacklisted_by_user INTEGER NOT NULL,
scheme INTEGER NOT NULL,
password_type INTEGER,
times_used INTEGER,
form_data BLOB,
display_name VARCHAR,
icon_url VARCHAR,
federation_url VARCHAR,
skip_zero_click INTEGER,
generation_upload_status INTEGER,
possible_username_pairs BLOB,
id INTEGER PRIMARY KEY AUTOINCREMENT,
date_last_used INTEGER NOT NULL DEFAULT 0,
moving_blocked_for BLOB,
date_password_modified INTEGER NOT NULL DEFAULT 0,
sender_email VARCHAR,
sender_name VARCHAR,
date_received INTEGER,
sharing_notification_displayed INTEGER NOT NULL DEFAULT 0,
keychain_identifier BLOB,
sender_profile_image_url VARCHAR,
date_last_filled INTEGER NOT NULL DEFAULT 0,
actor_login_approved INTEGER NOT NULL DEFAULT 0,
UNIQUE (origin_url, username_element, username_value, password_element, signon_realm)
)`
const chromiumFixtureCookiesSchema = `CREATE TABLE cookies (
creation_utc INTEGER NOT NULL,
host_key TEXT NOT NULL,
top_frame_site_key TEXT NOT NULL,
name TEXT NOT NULL,
value TEXT NOT NULL,
encrypted_value BLOB NOT NULL,
path TEXT NOT NULL,
expires_utc INTEGER NOT NULL,
is_secure INTEGER NOT NULL,
is_httponly INTEGER NOT NULL,
last_access_utc INTEGER NOT NULL,
has_expires INTEGER NOT NULL,
is_persistent INTEGER NOT NULL,
priority INTEGER NOT NULL,
samesite INTEGER NOT NULL,
source_scheme INTEGER NOT NULL,
source_port INTEGER NOT NULL,
last_update_utc INTEGER NOT NULL,
source_type INTEGER NOT NULL,
has_cross_site_ancestor INTEGER NOT NULL
)`
const chromiumFixtureURLsSchema = `CREATE TABLE urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url LONGVARCHAR,
title LONGVARCHAR,
visit_count INTEGER DEFAULT 0 NOT NULL,
typed_count INTEGER DEFAULT 0 NOT NULL,
last_visit_time INTEGER NOT NULL,
hidden INTEGER DEFAULT 0 NOT NULL
)`
const chromiumFixtureDownloadsSchema = `CREATE TABLE downloads (
id INTEGER PRIMARY KEY,
guid VARCHAR NOT NULL,
current_path LONGVARCHAR NOT NULL,
target_path LONGVARCHAR NOT NULL,
start_time INTEGER NOT NULL,
received_bytes INTEGER NOT NULL,
total_bytes INTEGER NOT NULL,
state INTEGER NOT NULL,
danger_type INTEGER NOT NULL,
interrupt_reason INTEGER NOT NULL,
hash BLOB NOT NULL,
end_time INTEGER NOT NULL,
opened INTEGER NOT NULL,
last_access_time INTEGER NOT NULL,
transient INTEGER NOT NULL,
referrer VARCHAR NOT NULL,
site_url VARCHAR NOT NULL,
embedder_download_data VARCHAR NOT NULL,
tab_url VARCHAR NOT NULL,
tab_referrer_url VARCHAR NOT NULL,
http_method VARCHAR NOT NULL,
by_ext_id VARCHAR NOT NULL,
by_ext_name VARCHAR NOT NULL,
by_web_app_id VARCHAR NOT NULL,
etag VARCHAR NOT NULL,
last_modified VARCHAR NOT NULL,
mime_type VARCHAR(255) NOT NULL,
original_mime_type VARCHAR(255) NOT NULL
)`
const chromiumFixtureCreditCardsSchema = `CREATE TABLE credit_cards (
guid VARCHAR PRIMARY KEY,
name_on_card VARCHAR,
expiration_month INTEGER,
expiration_year INTEGER,
card_number_encrypted BLOB,
date_modified INTEGER NOT NULL DEFAULT 0,
origin VARCHAR DEFAULT '',
use_count INTEGER NOT NULL DEFAULT 0,
use_date INTEGER NOT NULL DEFAULT 0,
billing_address_id VARCHAR,
nickname VARCHAR
)`
const chromiumFixtureBookmarks = `{
"checksum": "00000000000000000000000000000000",
"roots": {
"bookmark_bar": {
"children": [
{"date_added": "%[3]d", "id": "4", "name": "Docs", "type": "url", "url": "https://docs.%[1]s/"},
{
"children": [
{"date_added": "%[4]d", "id": "6", "name": "Long read <with> & tags", "type": "url", "url": "https://news.%[1]s/long-read"}
],
"date_added": "%[2]d",
"id": "5",
"name": "Reading",
"type": "folder"
}
],
"date_added": "%[2]d",
"id": "1",
"name": "Bookmarks bar",
"type": "folder"
},
"other": {
"children": [
{"date_added": "%[5]d", "id": "7", "name": "Café menu", "type": "url", "url": "https://shop.%[1]s/menu"}
],
"date_added": "%[2]d",
"id": "2",
"name": "Other bookmarks",
"type": "folder"
},
"synced": {"children": [], "date_added": "%[2]d", "id": "3", "name": "Mobile bookmarks", "type": "folder"}
},
"version": 1
}`
const chromiumFixtureSecurePreferences = `{
"extensions": {
"settings": {
"aaaabbbbccccddddeeeeffffgggghhhh": {
"disable_reasons": [],
"location": 1,
"manifest": {
"description": "Groups tabs by site, \"neatly\" & <fast>",
"homepage_url": "https://tabs.example/",
"name": "Tab Organizer",
"version": "2.4.1"
}
},
"iiiijjjjkkkkllllmmmmnnnnoooopppp": {
"disable_reasons": [1],
"location": 1,
"manifest": {"description": "Distraction-free reading", "name": "Reader Mode", "version": "0.9.0"}
},
"ppppoooonnnnmmmmllllkkkkjjjjiiii": {
"location": 5,
"manifest": {"name": "Built-in Component", "version": "1.0"}
},
"hhhhggggffffeeeeddddccccbbbbaaaa": {
"location": 10,
"manifest": {"name": "External Component", "version": "1.0"}
},
"abcdabcdabcdabcdabcdabcdabcdabcd": {
"location": 4,
"manifest": {"name": "Legacy Unpacked", "version": "0.1"},
"state": 1
},
"dcbadcbadcbadcbadcbadcbadcbadcba": {
"location": 1
}
}
}
}`
-444
View File
@@ -1,444 +0,0 @@
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/export"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
const (
exportUTF8BOM = "\xEF\xBB\xBF"
exportURLWithHTMLChars = "https://shop.example.com/cart?item=42&qty=<3>"
exportURLWithHTMLCharsEscaped = `https://shop.example.com/cart?item=42\u0026qty=\u003c3\u003e`
)
type exportStamp struct {
browser string
profile string
data *exportData
}
type exportData struct {
Passwords []record.Login
Cookies []record.Cookie
Histories []record.History
Downloads []record.Download
Bookmarks []record.Bookmark
CreditCards []record.CreditCard
Extensions []record.Extension
LocalStorage []record.LocalStorage
SessionStorage []record.SessionStorage
}
type exportURLForm struct {
file string
escaped bool
}
func TestExportGolden(t *testing.T) {
formats := []struct {
format string
ext string
urlForms []exportURLForm
jsonFallback bool
}{
{
format: "csv",
ext: "csv",
urlForms: []exportURLForm{{file: "cookie.csv"}, {file: "history.csv"}},
},
{
format: "json",
ext: "json",
urlForms: []exportURLForm{{file: "cookie.json", escaped: true}, {file: "history.json", escaped: true}},
},
{
format: "cookie-editor",
ext: "json",
urlForms: []exportURLForm{{file: "cookie.json"}, {file: "history.json", escaped: true}},
jsonFallback: true,
},
}
for _, tc := range formats {
tc := tc
t.Run(tc.format, func(t *testing.T) {
dir := filepath.Join(t.TempDir(), "results")
exportWrite(t, dir, tc.format, false, exportStamps())
got := bundleDir(t, dir)
if tc.jsonFallback {
jsonDir := filepath.Join(t.TempDir(), "results")
exportWrite(t, jsonDir, "json", false, exportStamps())
assertJSONFallback(t, dir, jsonDir)
got = bundleFiles(t, dir, "cookie.json")
}
assertGolden(t, "export-"+tc.format+".golden", got)
assert.Equal(t, exportCategoryFiles(tc.ext, category.All()...), exportDirFiles(t, dir))
exportAssertFileContract(t, dir)
for _, form := range tc.urlForms {
exportAssertURLForm(t, dir, form)
}
sparse := filepath.Join(t.TempDir(), "sparse")
exportWrite(t, sparse, tc.format, false, exportSparseStamps())
assert.Equal(t, exportCategoryFiles(tc.ext, category.Password, category.LocalStorage), exportDirFiles(t, sparse))
})
}
t.Run("zip", func(t *testing.T) {
loose := filepath.Join(t.TempDir(), "results")
exportWrite(t, loose, "csv", false, exportStamps())
dir := filepath.Join(t.TempDir(), "results")
exportWrite(t, dir, "csv", true, exportStamps())
assert.Equal(t, []string{"results.zip"}, exportDirFiles(t, dir))
archive := filepath.Join(dir, "results.zip")
assertGolden(t, "export-zip.golden", zipListing(t, archive))
assert.Equal(t, readDirFiles(t, loose), exportReadZip(t, archive))
})
}
func exportWrite(t *testing.T, dir, format string, compress bool, stamps []exportStamp) {
t.Helper()
f, err := export.ParseFormat(format)
require.NoError(t, err)
w, err := export.NewWriter(dir, f, compress)
require.NoError(t, err)
for _, s := range stamps {
require.NoError(t, writeStamp(w, s))
}
require.NoError(t, w.Close())
}
func exportCategoryFiles(ext string, categories ...category.Category) []string {
names := make([]string, 0, len(categories))
for _, c := range categories {
names = append(names, c.String()+"."+ext)
}
sort.Strings(names)
return names
}
func exportDirFiles(t *testing.T, dir string) []string {
t.Helper()
entries, err := os.ReadDir(dir)
require.NoError(t, err)
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
return names
}
func exportReadFile(t *testing.T, dir, name string) string {
t.Helper()
data, err := os.ReadFile(filepath.Join(dir, name))
require.NoError(t, err)
return string(data)
}
func exportReadZip(t *testing.T, path string) map[string]string {
t.Helper()
r, err := zip.OpenReader(path)
require.NoError(t, err)
defer r.Close()
entries := make(map[string]string, len(r.File))
for _, f := range r.File {
entries[f.Name] = exportReadZipEntry(t, f)
}
return entries
}
func exportReadZipEntry(t *testing.T, f *zip.File) string {
t.Helper()
rc, err := f.Open()
require.NoError(t, err)
defer rc.Close()
data, err := io.ReadAll(rc)
require.NoError(t, err)
return string(data)
}
func exportAssertFileContract(t *testing.T, dir string) {
t.Helper()
for _, name := range exportDirFiles(t, dir) {
content := exportReadFile(t, dir, name)
switch filepath.Ext(name) {
case ".csv":
assert.Truef(t, strings.HasPrefix(content, exportUTF8BOM), "%s must start with the UTF-8 BOM", name)
case ".json":
assert.Falsef(t, strings.HasPrefix(content, exportUTF8BOM), "%s must not start with a BOM", name)
default:
t.Errorf("unexpected output file %s", name)
}
if runtime.GOOS != "windows" {
info, err := os.Stat(filepath.Join(dir, name))
require.NoError(t, err)
assert.Equalf(t, os.FileMode(0o600), info.Mode().Perm(), "%s permissions", name)
}
}
}
func exportAssertURLForm(t *testing.T, dir string, form exportURLForm) {
t.Helper()
present, absent := exportURLWithHTMLChars, exportURLWithHTMLCharsEscaped
if form.escaped {
present, absent = absent, present
}
content := exportReadFile(t, dir, form.file)
assert.Containsf(t, content, present, "%s", form.file)
assert.NotContainsf(t, content, absent, "%s", form.file)
}
// Entries are listed in extractor sort order with unique sort keys, so re-sorting a profile cannot change a golden.
func exportStamps() []exportStamp {
return []exportStamp{
{browser: "Chrome", profile: "Default", data: &exportData{
Passwords: []record.Login{
{
URL: "https://accounts.example.com/signin?continue=/mail&hl=ja", Username: "alice@example.com",
Password: "pa$$ \"quoted\", comma\\backslash\nnewline",
CreatedAt: time.Date(2026, 3, 14, 15, 9, 26, 535897932, time.UTC), Store: record.StoreAccount,
},
{
URL: "https://例え.jp/ログイン", Username: "日本語ユーザー", Password: "🔑 emoji",
CreatedAt: time.Date(2025, 11, 5, 6, 7, 8, 0, time.UTC), Store: record.StoreLocal,
},
},
Cookies: []record.Cookie{
{
Host: ".example.com", Path: "/", Name: "return_to", Value: exportURLWithHTMLChars,
IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true,
ExpireAt: time.Date(2027, 6, 30, 12, 34, 56, 789000000, time.UTC),
CreatedAt: time.Date(2026, 3, 14, 15, 9, 27, 100000000, time.UTC), SameSite: "lax",
},
{
Host: "www.example.com", Path: "/account", Name: "session_id", Value: `{"user":"日本語 🍪","dir":"C:\Temp"}`,
IsHTTPOnly: true, CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), SameSite: "strict",
},
},
Histories: []record.History{
{
URL: exportURLWithHTMLChars, Title: `Cart "deals" <b>&</b>, 日本語 🛒`, VisitCount: 42,
LastVisit: time.Date(2026, 3, 14, 15, 10, 0, 1000, time.UTC),
},
{URL: "file:///C:/Users/Alice/notes.html", Title: "multi\nline title", VisitCount: 3},
},
Downloads: []record.Download{
{
URL: "https://dl.example.com/files/big.iso?token=a&sig=<x>",
TargetPath: `C:\Users\Alice\Downloads\Ubuntu "final", v2.iso`,
MimeType: "application/x-iso9660-image", TotalBytes: 5368709121,
StartTime: time.Date(2026, 3, 14, 15, 0, 0, 250000000, time.UTC),
EndTime: time.Date(2026, 3, 14, 15, 30, 0, 750000000, time.UTC),
},
},
Bookmarks: []record.Bookmark{
{
ID: 7, Name: "Docs & <Specs>", Type: "url", URL: "https://docs.example.com/search?a=1&b=<2>", Folder: "Bookmarks bar",
CreatedAt: time.Date(2026, 2, 2, 2, 2, 2, 20202020, time.UTC),
},
{ID: 4294967298, Name: "日本語 📚", Type: "url", URL: "https://例え.jp/", Folder: "Other bookmarks"},
},
CreditCards: []record.CreditCard{
{
GUID: "00000000-0000-4000-8000-000000000001", Name: "山田 太郎", Number: "4111111111111111",
ExpMonth: "12", ExpYear: "2030", NickName: `Work "primary", 💳`, Address: "1-2-3 Chiyoda,\nTokyo 100-0001",
},
},
Extensions: []record.Extension{
{
Name: "Ad Blocker", ID: "abcdefghijklmnopabcdefghijklmnop", Description: `Blocks ads & trackers, "fast" <b>`,
Version: "1.58.0", HomepageURL: "https://adblock.example/?a=1&b=<2>", Enabled: true,
},
},
LocalStorage: []record.LocalStorage{
{URL: "https://app.example.com", Key: "prefs", Value: `{"theme":"dark","greeting":"こんにちは 👋","dir":"C:\Temp"}`},
{IsMeta: true, URL: "https://app.example.com", Value: "meta data, value bytes is [8 128 1]"},
},
SessionStorage: []record.SessionStorage{
{URL: "https://app.example.com", Key: "tab-id", Value: "42"},
},
}},
{browser: "Chrome", profile: "Profile 1", data: &exportData{
Passwords: []record.Login{
{
URL: "http://192.168.0.1:8080/admin", Username: "admin", Password: " leading space",
CreatedAt: time.Date(2025, 6, 1, 0, 0, 0, 1, time.UTC), Store: record.StoreLocal,
},
{URL: "android://hash@com.example.app/", Store: record.StoreLocal},
},
Cookies: []record.Cookie{
{
Host: ".tracker.example", Path: "/", Name: "_ga", Value: "GA1.2.1234567890.1700000000",
IsSecure: true, HasExpire: true, IsPersistent: true,
ExpireAt: time.Date(2028, 2, 29, 23, 59, 59, 0, time.UTC),
CreatedAt: time.Date(2025, 5, 5, 5, 5, 5, 123456789, time.UTC), SameSite: "none",
},
{Host: ".dev.example", Path: "/dev", Name: "multi_line", Value: "line one\nline two, with comma", SameSite: "unspecified"},
},
Histories: []record.History{
{
URL: "https://search.example.com/?q=a%26b&lang=日本語", VisitCount: 1000000,
LastVisit: time.Date(2025, 7, 7, 7, 7, 7, 700000000, time.UTC),
},
{URL: "about:blank", Title: " leading space", LastVisit: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)},
},
Downloads: []record.Download{
{
URL: "https://例え.jp/資料.pdf", TargetPath: "/home/alice/Downloads/資料 📄.pdf", MimeType: "application/pdf",
StartTime: time.Date(2025, 8, 1, 8, 0, 0, 0, time.UTC),
},
},
Bookmarks: []record.Bookmark{
{
ID: 1, Name: `Quote "this", please`, Type: "url", URL: "https://example.org/a,b", Folder: "multi\nline folder",
CreatedAt: time.Date(2025, 3, 3, 3, 3, 3, 0, time.UTC),
},
},
CreditCards: []record.CreditCard{
{
GUID: "00000000-0000-4000-8000-000000000002", Name: "Alice O'Brien", Number: "5555555555554444",
ExpMonth: "1", ExpYear: "2027", CVC: "123", Comment: `note <b>&</b> \ end`,
},
},
Extensions: []record.Extension{
{Name: "日本語拡張 🧩", ID: "ponmlkjihgfedcbaponmlkjihgfedcba", Description: "line one\nline two", Version: "0.0.1"},
},
LocalStorage: []record.LocalStorage{
{URL: "https://example.org", Key: "a&b<c>", Value: "multi\nline"},
},
SessionStorage: []record.SessionStorage{
{URL: "https://example.org/?x=1&y=<2>", Key: "draft", Value: `He said "hi", then left \`},
},
}},
{browser: "Microsoft Edge", profile: "Default", data: &exportData{
Passwords: []record.Login{
{
URL: "https://login.example.org/<tenant>/authorize?client=a&scope=b", Username: `CORP\jdoe`, Password: "日本語パスワード",
CreatedAt: time.Date(2024, 2, 29, 12, 0, 0, 500000000, time.UTC), Store: record.StoreAccount,
},
},
Cookies: []record.Cookie{
{
Host: ".edge.example", Path: "/", Name: "epoch_expiry", Value: `back\slash "quoted" <b>&amp;</b>`,
IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true,
ExpireAt: time.Unix(0, 0).UTC(), CreatedAt: time.Date(2024, 12, 24, 18, 0, 0, 0, time.UTC),
},
{
Host: "edge.example", Path: "/", Name: "host_only", Value: "v", HasExpire: true, IsPersistent: true,
ExpireAt: time.Date(2026, 12, 31, 23, 59, 59, 999999999, time.UTC),
CreatedAt: time.Date(2024, 6, 15, 9, 30, 0, 0, time.UTC), SameSite: "strict",
},
},
Histories: []record.History{
{
URL: "edge://settings/?a=1&b=2", Title: `C:\Windows\System32`, VisitCount: 7,
LastVisit: time.Date(2024, 7, 4, 0, 0, 0, 500000000, time.UTC),
},
},
Downloads: []record.Download{
{URL: "blob:https://app.example/1234", TargetPath: `\\fileserver\share\Q3 summary.csv`, TotalBytes: 4294967296},
},
Bookmarks: []record.Bookmark{
{
ID: 12, Name: `C:\Shares\docs`, Type: "url", URL: "https://edge.example/", Folder: "Favorites bar",
CreatedAt: time.Date(2024, 4, 4, 4, 4, 4, 400000000, time.UTC),
},
},
CreditCards: []record.CreditCard{
{GUID: "00000000-0000-4000-8000-000000000003"},
},
Extensions: []record.Extension{
{
Name: "Edge Helper", ID: "aaaabbbbccccddddeeeeffffgggghhhh", Description: `Installed under C:\Program Files\Helper`,
Version: "2.0", HomepageURL: "https://helper.example/", Enabled: true,
},
},
LocalStorage: []record.LocalStorage{
{URL: "https://edge.example", Key: "日本語"},
},
SessionStorage: []record.SessionStorage{
{IsMeta: true, URL: "https://edge.example", Value: "meta data, value bytes is [16 2]"},
},
}},
}
}
func exportSparseStamps() []exportStamp {
return []exportStamp{
{browser: "Chrome", profile: "Default", data: &exportData{
Passwords: []record.Login{{URL: "https://example.com/", Username: "alice", Store: record.StoreLocal}},
Cookies: []record.Cookie{},
}},
{browser: "Chrome", profile: "Profile 1"},
{browser: "Microsoft Edge", profile: "Default", data: &exportData{
Histories: []record.History{},
LocalStorage: []record.LocalStorage{{URL: "https://example.com", Key: "k", Value: "v"}},
}},
}
}
func writeStamp(w *export.Writer, s exportStamp) error {
if s.data == nil {
return nil
}
for _, c := range category.All() {
records := profileRecords(s.data, c)
for _, rec := range records {
record.Stamp(rec, s.browser, s.profile)
}
if err := w.Write(c, records); err != nil {
return err
}
}
return nil
}
func profileRecords(d *exportData, c category.Category) []record.Record {
switch c {
case category.Password:
return recordsOf(d.Passwords)
case category.Cookie:
return recordsOf(d.Cookies)
case category.Bookmark:
return recordsOf(d.Bookmarks)
case category.History:
return recordsOf(d.Histories)
case category.Download:
return recordsOf(d.Downloads)
case category.CreditCard:
return recordsOf(d.CreditCards)
case category.Extension:
return recordsOf(d.Extensions)
case category.LocalStorage:
return recordsOf(d.LocalStorage)
case category.SessionStorage:
return recordsOf(d.SessionStorage)
default:
return nil
}
}
func recordsOf[T any, P interface {
*T
record.Record
}](items []T) []record.Record {
records := make([]record.Record, len(items))
for i := range items {
records[i] = P(&items[i])
}
return records
}
@@ -1,92 +0,0 @@
package main
import (
"context"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
)
// The extract goldens pin dump's output on fixtures; the fixtures' keys are handed in, since no secret store holds them.
func TestExtractGolden(t *testing.T) {
home := t.TempDir()
keys := make(map[browser.DirID]masterkey.Set)
for _, inst := range chromiumFixtureInstalls {
def, ok := browser.Lookup(inst.key)
require.True(t, ok, inst.key)
require.Equal(t, inst.name, def.Name, "records are stamped with the table's display name")
chromiumFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.key)
keys[browser.DirID(inst.key)] = chromiumFixtureKeys
}
assertExtractGoldens(t, "extract", func(t *testing.T, format string) string {
return extractGoldenRun(t, home, keys, format)
})
}
func TestExtractGoldenFirefox(t *testing.T) {
home := t.TempDir()
def, ok := browser.Lookup("firefox")
require.True(t, ok)
firefoxFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])))
assertExtractGoldens(t, "extract-firefox", func(t *testing.T, format string) string {
return extractGoldenRun(t, home, nil, format)
})
}
func TestExtractGoldenSafari(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("Safari is in the browser table on macOS only")
}
home := t.TempDir()
safariFixtureLibrary(t, filepath.Join(home, "Library"))
assertExtractGoldens(t, "extract-safari", func(t *testing.T, format string) string {
return extractGoldenRun(t, home, nil, format)
})
}
func extractGoldenRun(t *testing.T, home string, keys map[browser.DirID]masterkey.Set, format string) string {
t.Helper()
out := t.TempDir()
req, err := app.Validate(app.Flags{Browser: "all", Categories: "all", Format: format, Dir: out})
require.NoError(t, err)
req.Home, req.Keys = home, keys
plan := app.NewPlan(app.Discover(req), req)
_, err = app.Execute(context.Background(), plan, req)
require.NoError(t, err)
return out
}
var extractGoldenFormats = []struct {
format string
jsonFallback bool
}{
{format: "csv"},
{format: "json"},
{format: "cookie-editor", jsonFallback: true},
}
func assertExtractGoldens(t *testing.T, prefix string, run func(t *testing.T, format string) string) {
t.Helper()
for _, tt := range extractGoldenFormats {
tt := tt
t.Run(tt.format, func(t *testing.T) {
out := run(t, tt.format)
got := bundleDir(t, out)
if tt.jsonFallback {
assertJSONFallback(t, out, run(t, "json"))
got = bundleFiles(t, out, "cookie.json")
}
assertGolden(t, prefix+"-"+tt.format+".golden", got)
})
}
}
@@ -1,460 +0,0 @@
package main
import (
"crypto/sha256"
"encoding/asn1"
"encoding/base64"
"fmt"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/crypto"
)
// home's logins open only with its second key candidate (AES-256) and work's with its only one (3DES), so the golden
// covers the candidate check and both login ciphers.
var firefoxFixtureProfiles = []struct {
dir string
label string
start time.Time
globalSalt []byte
keys [][]byte
}{
{
dir: "abcd1234.default-release", label: "home", start: time.Date(2024, 3, 1, 9, 0, 0, 0, time.UTC),
globalSalt: []byte("home-global-salt-20b"),
keys: [][]byte{[]byte("home-3des-key-0123456789"), []byte("home-aes256-key-0123456789abcdef")},
},
{
dir: "wxyz5678.work", label: "work", start: time.Date(2024, 6, 1, 9, 0, 0, 0, time.UTC),
globalSalt: []byte("work-global-salt-20b"),
keys: [][]byte{[]byte("work-3des-key-0123456789")},
},
}
var firefoxFixtureKeyID = []byte{0xf8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
var (
oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13}
oidPBKDF2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 12}
oidHMACWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 9}
oidAES256CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42}
oidDESEDE3CBC = asn1.ObjectIdentifier{1, 2, 840, 113549, 3, 7}
)
func firefoxFixtureUserData(t *testing.T, profilesDir string) {
t.Helper()
fixtureWrite(t, filepath.Join(profilesDir, "profiles.ini"), "[General]\nStartWithLastProfile=1\n")
fixtureWrite(t, filepath.Join(profilesDir, "Crash Reports", "InstallTime20240101000000"), "1704067200")
for _, p := range firefoxFixtureProfiles {
firefoxFixtureProfile(t, filepath.Join(profilesDir, p.dir), p.label+".firefox.test", p.start, p.globalSalt, p.keys)
}
}
func firefoxFixtureProfile(t *testing.T, dir, site string, start time.Time, globalSalt []byte, keys [][]byte) {
t.Helper()
micros := func(offset time.Duration) int64 { return start.Add(offset).UnixMicro() }
millis := func(offset time.Duration) int64 { return start.Add(offset).UnixMilli() }
seconds := func(offset time.Duration) int64 { return start.Add(offset).Unix() }
link := func(host, path string) string { return "https://" + host + "." + site + path }
day := 24 * time.Hour
key4 := []string{
firefoxFixtureMetaDataSchema,
firefoxFixtureNSSPrivateSchema,
fmt.Sprintf(`INSERT INTO metaData (id, item1, item2) VALUES ('password', x'%x', x'%x')`,
globalSalt, firefoxFixturePBES2Seal(t, globalSalt, site+"/password-check", []byte("password-check"))),
}
for i, key := range keys {
key4 = append(key4, fmt.Sprintf(`INSERT INTO nssPrivate (id, a11, a102) VALUES (%d, x'%x', x'%x')`,
i+1, firefoxFixturePBES2Seal(t, globalSalt, fmt.Sprintf("%s/key-%d", site, i), key), firefoxFixtureKeyID))
}
fixtureSQLite(t, filepath.Join(dir, "key4.db"), key4...)
loginKey := keys[len(keys)-1]
seal := func(field, plaintext string) string {
return firefoxFixtureLoginSeal(t, loginKey, site+"/"+field, plaintext)
}
fixtureWrite(t, filepath.Join(dir, "logins.json"), fmt.Sprintf(firefoxFixtureLogins, site,
seal("1/username", "alice"), seal("1/password", "correct-horse-battery-staple"), millis(time.Hour+250*time.Millisecond),
seal("2/username", "alice@"+site), seal("2/password", `pa,ss"word`), millis(2*time.Hour),
seal("3/username", "alice"), seal("3/password", "pässwörd"), millis(90*time.Minute),
))
domain := "." + site
fixtureSQLite(t, filepath.Join(dir, "cookies.sqlite"), firefoxFixtureCookiesSchema,
firefoxFixtureInsertCookie("SID", "sid-"+site, domain, "/", seconds(365*day), micros(10*time.Minute+123456*time.Microsecond), 1, 1, 1),
firefoxFixtureInsertCookie("prefs", "theme=dark", "www."+site, "/settings", seconds(30*day), micros(20*time.Minute), 0, 0, 2),
firefoxFixtureInsertCookie("tracker", "opt-out", domain, "/", seconds(730*day), micros(30*time.Minute), 1, 0, 0),
firefoxFixtureInsertCookie("session", "ephemeral", "app."+site, "/", 0, micros(40*time.Minute), 1, 1, 256),
)
fixtureSQLite(t, filepath.Join(dir, "places.sqlite"),
firefoxFixturePlacesSchema, firefoxFixtureBookmarksSchema, firefoxFixtureAnnoAttributesSchema, firefoxFixtureAnnosSchema,
firefoxFixtureInsertPlace(1, link("www", "/"), "Home", 42, micros(3*time.Hour)),
firefoxFixtureInsertPlace(2, link("docs", "/guide?q=go&lang=en"), `Guide, "quoted" & <b>bold</b>`, 7, micros(4*time.Hour)),
firefoxFixtureInsertPlace(3, link("news", "/ja"), "ニュース", 3, micros(5*time.Hour)),
firefoxFixtureInsertPlace(4, link("docs", "/"), "Docs", 0, 0),
firefoxFixtureInsertPlace(5, link("news", "/long-read"), "Long read", 1, micros(9*time.Hour)),
firefoxFixtureInsertPlace(6, link("files", "/report.pdf"), "", 1, micros(6*time.Hour)),
firefoxFixtureInsertPlace(7, link("files", "/archive.tar.gz"), "", 1, micros(7*time.Hour)),
firefoxFixtureInsertPlace(8, link("shop", "/menu"), "Café menu", 2, micros(10*time.Hour)),
firefoxFixtureInsertPlace(9, link("files", "/setup.exe"), "", 1, micros(7*time.Hour+30*time.Minute)),
firefoxFixtureInsertBookmark(1, 2, 0, 0, 0, "", "root________", micros(0)),
firefoxFixtureInsertBookmark(2, 2, 0, 1, 0, "menu", "menu________", micros(0)),
firefoxFixtureInsertBookmark(3, 2, 0, 1, 1, "toolbar", "toolbar_____", micros(0)),
firefoxFixtureInsertBookmark(4, 2, 0, 1, 2, "tags", "tags________", micros(0)),
firefoxFixtureInsertBookmark(5, 2, 0, 1, 3, "unfiled", "unfiled_____", micros(0)),
firefoxFixtureInsertBookmark(6, 2, 0, 1, 4, "mobile", "mobile______", micros(0)),
firefoxFixtureInsertBookmark(7, 1, 4, 3, 0, "Docs", "bookmark0007", micros(8*time.Hour)),
firefoxFixtureInsertBookmark(8, 2, 0, 3, 1, "Reading", "folder000008", micros(0)),
firefoxFixtureInsertBookmark(9, 1, 5, 8, 0, "Long read <with> & tags", "bookmark0009", micros(9*time.Hour)),
firefoxFixtureInsertBookmark(10, 3, 0, 3, 2, "", "separator010", micros(0)),
firefoxFixtureInsertBookmark(11, 1, 8, 2, 0, "Café menu", "bookmark0011", micros(10*time.Hour)),
firefoxFixtureInsertBookmark(12, 1, 1, 5, 0, "", "bookmark0012", micros(11*time.Hour)),
`INSERT INTO moz_anno_attributes (id, name) VALUES (1, 'downloads/destinationFileURI'), (2, 'downloads/metaData')`,
firefoxFixtureInsertAnno(6, 1, "file:///C:/Users/alice/Downloads/report.pdf", micros(6*time.Hour)),
firefoxFixtureInsertAnno(6, 2, fmt.Sprintf(`{"state":1,"deleted":false,"endTime":%d,"fileSize":52344}`,
millis(6*time.Hour+3*time.Second)), micros(6*time.Hour)),
firefoxFixtureInsertAnno(7, 1, "file:///home/alice/Downloads/archive.tar.gz", micros(7*time.Hour)),
firefoxFixtureInsertAnno(7, 2, fmt.Sprintf(`{"state":1,"deleted":false,"endTime":%d,"fileSize":1048576}`,
millis(7*time.Hour+time.Minute)), micros(7*time.Hour)),
firefoxFixtureInsertAnno(9, 1, "file:///Users/alice/Downloads/setup.exe", micros(7*time.Hour+30*time.Minute)),
)
fixtureWrite(t, filepath.Join(dir, "extensions.json"), firefoxFixtureExtensions)
fixtureSQLite(t, filepath.Join(dir, "webappsstore.sqlite"), firefoxFixtureWebappsstoreSchema,
firefoxFixtureInsertStorage(firefoxFixtureOriginKey("https", "app."+site, 443), "greeting", "café"),
firefoxFixtureInsertStorage(firefoxFixtureOriginKey("https", "app."+site, 443), "言語", "日本語"),
firefoxFixtureInsertStorage(firefoxFixtureOriginKey("http", "shop."+site, 8080), "cart", `{"items":2}`),
)
}
// The template goes through the decoder's own parser and Encrypt, so only the ASN.1 layout is spelled out here.
func firefoxFixtureSeal(t *testing.T, marshal func() ([]byte, error), ciphertext *[]byte, key, plaintext []byte) []byte {
t.Helper()
template, err := marshal()
require.NoError(t, err)
pbe, err := crypto.NewASN1PBE(template)
require.NoError(t, err)
*ciphertext, err = pbe.Encrypt(key, plaintext)
require.NoError(t, err)
sealed, err := marshal()
require.NoError(t, err)
return sealed
}
type firefoxFixturePBES2 struct {
Algorithm struct {
OID asn1.ObjectIdentifier
Params struct {
KDF struct {
OID asn1.ObjectIdentifier
Params struct {
Salt []byte
Iterations int
KeyLength int
PRF struct{ OID asn1.ObjectIdentifier }
}
}
Cipher struct {
OID asn1.ObjectIdentifier
IV []byte
}
}
}
Ciphertext []byte
}
func firefoxFixturePBES2Seal(t *testing.T, globalSalt []byte, seed string, plaintext []byte) []byte {
t.Helper()
var pbe firefoxFixturePBES2
pbe.Algorithm.OID = oidPBES2
kdf := &pbe.Algorithm.Params.KDF
kdf.OID = oidPBKDF2
kdf.Params.Salt = firefoxFixtureBytes(seed+"/salt", 32)
kdf.Params.Iterations = 1
kdf.Params.KeyLength = 32
kdf.Params.PRF.OID = oidHMACWithSHA256
pbe.Algorithm.Params.Cipher.OID = oidAES256CBC
pbe.Algorithm.Params.Cipher.IV = firefoxFixtureBytes(seed+"/iv", 14)
return firefoxFixtureSeal(t, func() ([]byte, error) { return asn1.Marshal(pbe) }, &pbe.Ciphertext, globalSalt, plaintext)
}
type firefoxFixtureLoginPBE struct {
KeyID []byte
Cipher struct {
OID asn1.ObjectIdentifier
IV []byte
}
Ciphertext []byte
}
func firefoxFixtureLoginSeal(t *testing.T, key []byte, seed, plaintext string) string {
t.Helper()
pbe := firefoxFixtureLoginPBE{KeyID: firefoxFixtureKeyID}
if len(key) == 24 {
pbe.Cipher.OID = oidDESEDE3CBC
pbe.Cipher.IV = firefoxFixtureBytes(seed, 8)
} else {
pbe.Cipher.OID = oidAES256CBC
pbe.Cipher.IV = firefoxFixtureBytes(seed, 16)
}
sealed := firefoxFixtureSeal(t, func() ([]byte, error) { return asn1.Marshal(pbe) }, &pbe.Ciphertext, key, []byte(plaintext))
return base64.StdEncoding.EncodeToString(sealed)
}
func firefoxFixtureBytes(seed string, n int) []byte {
sum := sha256.Sum256([]byte(seed))
return sum[:n]
}
// webappsstore2 stores the host reversed, so a domain and its subdomains share a key prefix.
func firefoxFixtureOriginKey(scheme, host string, port int) string {
reversed := []byte(host)
for i, j := 0, len(reversed)-1; i < j; i, j = i+1, j-1 {
reversed[i], reversed[j] = reversed[j], reversed[i]
}
return fmt.Sprintf("%s.:%s:%d", reversed, scheme, port)
}
func firefoxFixtureText(s string) string {
if s == "" {
return "NULL"
}
return "'" + s + "'"
}
func firefoxFixtureInsertCookie(name, value, host, path string, expiry, creationTime int64, secure, httpOnly, sameSite int) string {
return fmt.Sprintf(
`INSERT INTO moz_cookies (originAttributes, name, value, host, path, expiry, lastAccessed, creationTime,
isSecure, isHttpOnly, sameSite, rawSameSite, schemeMap)
VALUES ('', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, %d, 2)`,
name, value, host, path, expiry, creationTime, creationTime, secure, httpOnly, sameSite, sameSite,
)
}
func firefoxFixtureInsertPlace(id int, url, title string, visitCount int, lastVisitDate int64) string {
lastVisit := "NULL"
if lastVisitDate != 0 {
lastVisit = fmt.Sprint(lastVisitDate)
}
return fmt.Sprintf(
`INSERT INTO moz_places (id, url, title, rev_host, visit_count, last_visit_date, guid, url_hash)
VALUES (%d, '%s', %s, '', %d, %s, 'place%07d', 0)`,
id, url, firefoxFixtureText(title), visitCount, lastVisit, id,
)
}
func firefoxFixtureInsertBookmark(id, bookmarkType, fk, parent, position int, title, guid string, dateAdded int64) string {
fkValue := "NULL"
if fk != 0 {
fkValue = fmt.Sprint(fk)
}
return fmt.Sprintf(
`INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, dateAdded, lastModified, guid)
VALUES (%d, %d, %s, %d, %d, %s, %d, %d, '%s')`,
id, bookmarkType, fkValue, parent, position, firefoxFixtureText(title), dateAdded, dateAdded, guid,
)
}
func firefoxFixtureInsertAnno(placeID, attributeID int, content string, dateAdded int64) string {
return fmt.Sprintf(
`INSERT INTO moz_annos (place_id, anno_attribute_id, content, flags, expiration, type, dateAdded, lastModified)
VALUES (%d, %d, '%s', 0, 4, 3, %d, %d)`,
placeID, attributeID, content, dateAdded, dateAdded,
)
}
func firefoxFixtureInsertStorage(originKey, key, value string) string {
return fmt.Sprintf(
`INSERT INTO webappsstore2 (originAttributes, originKey, scope, key, value) VALUES ('', '%s', '', '%s', '%s')`,
originKey, key, value,
)
}
const firefoxFixtureMetaDataSchema = `CREATE TABLE metaData (id PRIMARY KEY UNIQUE ON CONFLICT REPLACE, item1, item2)`
const firefoxFixtureNSSPrivateSchema = `CREATE TABLE nssPrivate (id PRIMARY KEY UNIQUE ON CONFLICT ABORT, a11, a102)`
const firefoxFixtureCookiesSchema = `CREATE TABLE moz_cookies (
id INTEGER PRIMARY KEY,
originAttributes TEXT NOT NULL DEFAULT '',
name TEXT,
value TEXT,
host TEXT,
path TEXT,
expiry INTEGER,
lastAccessed INTEGER,
creationTime INTEGER,
isSecure INTEGER,
isHttpOnly INTEGER,
inBrowserElement INTEGER DEFAULT 0,
sameSite INTEGER DEFAULT 0,
rawSameSite INTEGER DEFAULT 0,
schemeMap INTEGER DEFAULT 0,
isPartitionedAttributeSet INTEGER DEFAULT 0,
CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes)
)`
const firefoxFixturePlacesSchema = `CREATE TABLE moz_places (
id INTEGER PRIMARY KEY,
url LONGVARCHAR,
title LONGVARCHAR,
rev_host LONGVARCHAR,
visit_count INTEGER DEFAULT 0,
hidden INTEGER DEFAULT 0 NOT NULL,
typed INTEGER DEFAULT 0 NOT NULL,
frecency INTEGER DEFAULT -1 NOT NULL,
last_visit_date INTEGER,
guid TEXT,
foreign_count INTEGER DEFAULT 0 NOT NULL,
url_hash INTEGER DEFAULT 0 NOT NULL,
description TEXT,
preview_image_url TEXT,
site_name TEXT,
origin_id INTEGER,
recalc_frecency INTEGER NOT NULL DEFAULT 0,
alt_frecency INTEGER,
recalc_alt_frecency INTEGER NOT NULL DEFAULT 0
)`
const firefoxFixtureBookmarksSchema = `CREATE TABLE moz_bookmarks (
id INTEGER PRIMARY KEY,
type INTEGER,
fk INTEGER DEFAULT NULL,
parent INTEGER,
position INTEGER,
title LONGVARCHAR,
keyword_id INTEGER,
folder_type TEXT,
dateAdded INTEGER,
lastModified INTEGER,
guid TEXT,
syncStatus INTEGER NOT NULL DEFAULT 0,
syncChangeCounter INTEGER NOT NULL DEFAULT 1
)`
const firefoxFixtureAnnoAttributesSchema = `CREATE TABLE moz_anno_attributes (
id INTEGER PRIMARY KEY,
name VARCHAR(32) UNIQUE NOT NULL
)`
const firefoxFixtureAnnosSchema = `CREATE TABLE moz_annos (
id INTEGER PRIMARY KEY,
place_id INTEGER NOT NULL,
anno_attribute_id INTEGER,
content LONGVARCHAR,
flags INTEGER DEFAULT 0,
expiration INTEGER DEFAULT 0,
type INTEGER DEFAULT 0,
dateAdded INTEGER DEFAULT 0,
lastModified INTEGER DEFAULT 0
)`
const firefoxFixtureWebappsstoreSchema = `CREATE TABLE webappsstore2 (
originAttributes TEXT,
originKey TEXT,
scope TEXT,
key TEXT,
value TEXT
)`
const firefoxFixtureLogins = `{
"nextId": 4,
"logins": [
{
"id": 1,
"hostname": "https://accounts.%[1]s",
"httpRealm": null,
"formSubmitURL": "https://login.%[1]s",
"usernameField": "username",
"passwordField": "password",
"encryptedUsername": "%[2]s",
"encryptedPassword": "%[3]s",
"encType": 1,
"timeCreated": %[4]d,
"timesUsed": 3
},
{
"id": 2,
"hostname": "https://shop.%[1]s",
"httpRealm": null,
"formSubmitURL": "",
"usernameField": "email",
"passwordField": "password",
"encryptedUsername": "%[5]s",
"encryptedPassword": "%[6]s",
"encType": 1,
"timeCreated": %[7]d,
"timesUsed": 1
},
{
"id": 3,
"hostname": "https://intranet.%[1]s",
"httpRealm": "Staff only",
"formSubmitURL": null,
"usernameField": "",
"passwordField": "",
"encryptedUsername": "%[8]s",
"encryptedPassword": "%[9]s",
"encType": 1,
"timeCreated": %[10]d,
"timesUsed": 7
}
],
"potentiallyVulnerablePasswords": [],
"dismissedBreachAlertsByLoginGUID": {},
"version": 3
}`
const firefoxFixtureExtensions = `{
"schemaVersion": 36,
"addons": [
{
"id": "tab-organizer@tabs.example",
"version": "2.4.1",
"type": "extension",
"defaultLocale": {
"name": "Tab Organizer",
"description": "Groups tabs by site, \"neatly\" & <fast>",
"creator": "Tabs Example",
"homepageURL": "https://tabs.example/"
},
"active": true,
"userDisabled": false,
"location": "app-profile"
},
{
"id": "{4b5ac9d3-1f2e-4d6c-9a8b-7c6d5e4f3a2b}",
"version": "0.9.0",
"type": "extension",
"defaultLocale": {"name": "Reader Mode", "description": "Distraction-free reading", "homepageURL": null},
"active": false,
"userDisabled": true,
"location": "app-profile"
},
{
"id": "formautofill@mozilla.org",
"version": "1.0.1",
"type": "extension",
"defaultLocale": {"name": "Form Autofill", "description": "Autofill forms with saved profiles.", "homepageURL": null},
"active": true,
"location": "app-system-defaults"
},
{
"id": "default-theme@mozilla.org",
"version": "1.3",
"type": "theme",
"defaultLocale": {"name": "System theme — auto", "description": "Follow the operating system setting.", "homepageURL": null},
"active": true,
"location": "app-builtin"
}
]
}`
-29
View File
@@ -1,29 +0,0 @@
package main
import (
"database/sql"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
_ "modernc.org/sqlite"
)
func fixtureWrite(t *testing.T, path, content string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
}
func fixtureSQLite(t *testing.T, path string, stmts ...string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
db, err := sql.Open("sqlite", path)
require.NoError(t, err)
defer db.Close()
for _, stmt := range stmts {
_, err = db.Exec(stmt)
require.NoError(t, err)
}
}
+3 -1
View File
@@ -8,10 +8,12 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/moond4rk/hackbrowserdata/internal/golden"
)
func TestFlagSurface(t *testing.T) {
assertGolden(t, "flags.golden", flagSurface(rootCmd()))
golden.Assert(t, "flags.golden", flagSurface(rootCmd()))
}
func flagSurface(root *cobra.Command) string {
-115
View File
@@ -1,115 +0,0 @@
package main
import (
"archive/zip"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var update = flag.Bool("update", false, "rewrite the golden files from the current code")
const goldenDir = "../../testdata"
func assertGolden(t *testing.T, name, got string) {
t.Helper()
path := filepath.Join(goldenDir, name)
if *update {
require.NoError(t, os.MkdirAll(goldenDir, 0o755))
require.NoError(t, os.WriteFile(path, []byte(got), 0o644))
}
want, err := os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, string(want), got, "regenerate with: go test ./cmd/hack-browser-data -run '%s' -update", t.Name())
}
func bundleDir(t *testing.T, dir string) string {
t.Helper()
entries, err := os.ReadDir(dir)
require.NoError(t, err)
names := make([]string, 0, len(entries))
for _, e := range entries {
require.Truef(t, e.Type().IsRegular(), "unexpected non-regular entry %s in %s", e.Name(), dir)
names = append(names, e.Name())
}
return bundleFiles(t, dir, names...)
}
func bundleFiles(t *testing.T, dir string, names ...string) string {
t.Helper()
var b strings.Builder
for _, name := range names {
data, err := os.ReadFile(filepath.Join(dir, name))
require.NoError(t, err)
fmt.Fprintf(&b, "-- %s (%d bytes) --\n", name, len(data))
b.Write(data)
if len(data) > 0 && data[len(data)-1] != '\n' {
b.WriteByte('\n')
}
}
return b.String()
}
func readDirFiles(t *testing.T, dir string) map[string]string {
t.Helper()
entries, err := os.ReadDir(dir)
require.NoError(t, err)
files := make(map[string]string, len(entries))
for _, e := range entries {
data, err := os.ReadFile(filepath.Join(dir, e.Name()))
require.NoError(t, err)
files[e.Name()] = string(data)
}
return files
}
// Cookie-Editor's own format covers cookies only; every other category is written exactly as the json format writes it.
func assertJSONFallback(t *testing.T, cookieEditorDir, jsonDir string) {
t.Helper()
got, want := readDirFiles(t, cookieEditorDir), readDirFiles(t, jsonDir)
require.Contains(t, got, "cookie.json")
delete(got, "cookie.json")
delete(want, "cookie.json")
assert.Equal(t, want, got)
}
func zipListing(t *testing.T, path string) string {
t.Helper()
r, err := zip.OpenReader(path)
require.NoError(t, err)
defer r.Close()
var b strings.Builder
for _, f := range r.File {
fmt.Fprintf(&b, "%s method=%d modified=%s size=%d crc32=%08x\n",
f.Name, f.Method, f.Modified.UTC().Format(time.RFC3339), f.UncompressedSize64, f.CRC32)
}
return b.String()
}
func readGolden(t *testing.T, name string) string {
t.Helper()
data, err := os.ReadFile(filepath.Join(goldenDir, name))
require.NoError(t, err)
return string(data)
}
// setHome points the commands' home directory at a fixture: HOME, and USERPROFILE, which Windows reads instead.
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) {
t.Helper()
cmd.SetArgs(args)
require.NoError(t, cmd.Execute())
}
+21
View File
@@ -0,0 +1,21 @@
package main
import (
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
// setHome points the commands' home directory at a fixture: HOME, and USERPROFILE, which Windows reads instead.
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) {
t.Helper()
cmd.SetArgs(args)
require.NoError(t, cmd.Execute())
}
-168
View File
@@ -1,168 +0,0 @@
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
)
var keysGoldenCreatedAt = time.Date(2026, time.May, 16, 8, 30, 15, 123456789, time.UTC)
// Strict rejects non-canonical literals, so every key reads in keys.golden exactly as written here.
func keysFakeKey(t *testing.T, b64 string) []byte {
t.Helper()
key, err := base64.StdEncoding.Strict().DecodeString(b64)
require.NoError(t, err)
return key
}
func keysFreeze(t *testing.T, dump masterkey.Dump, host masterkey.Host) masterkey.Dump {
t.Helper()
assert.Equal(t, runtime.GOOS, dump.Host.OS)
assert.Equal(t, runtime.GOARCH, dump.Host.Arch)
assert.Equal(t, time.UTC, dump.CreatedAt.Location())
assert.WithinDuration(t, time.Now(), dump.CreatedAt, time.Hour)
dump.CreatedAt = keysGoldenCreatedAt
dump.Host = host
return dump
}
// keysVaultsDump is what dumpkeys wrote for the golden's machine: two Chromium installs, the Opera and Yandex forks, and
// a vault whose v20 key failed, which keeps its v10 key; a Firefox install and a vault with no key are not in it.
func keysVaultsDump(t *testing.T) masterkey.Dump {
t.Helper()
return masterkey.Dump{
Version: masterkey.DumpVersion,
CreatedAt: keysGoldenCreatedAt,
Host: masterkey.Host{OS: "windows", Arch: "amd64", Hostname: "GOLDEN-PC", User: `GOLDEN-PC\Jürgen`},
Vaults: []masterkey.Vault{
{
Browser: "chrome", Kind: "chromium", UserDataDir: `C:\Users\Jürgen\AppData\Local\Google\Chrome\User Data`,
Profiles: []string{"Default", "Profile 1"},
Keys: masterkey.Set{
masterkey.V10: keysFakeKey(t, "chrome+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAA="),
masterkey.V20: keysFakeKey(t, "chrome+v20/app+bound+key/AAAAAAAAAAAAAAAAAA="),
},
},
{
Browser: "edge", Kind: "chromium", UserDataDir: `C:\Users\Jürgen\AppData\Local\Microsoft\Edge\User Data`,
Profiles: []string{"Default"},
Keys: masterkey.Set{
masterkey.V10: keysFakeKey(t, "edge+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAAAA="),
masterkey.V20: keysFakeKey(t, "edge+v20/app+bound+key/AAAAAAAAAAAAAAAAAAAA="),
},
},
{
Browser: "opera", Kind: "chromium-opera", UserDataDir: "/home/r&d/.config/opera",
Profiles: []string{"Default"},
Keys: masterkey.Set{
masterkey.V10: keysFakeKey(t, "opera+v10/peanuts+AAAA=="),
masterkey.V11: keysFakeKey(t, "opera+v11/keyring+AAAA=="),
},
},
{
Browser: "yandex", Kind: "chromium-yandex", UserDataDir: "/Users/r&d/Library/Application Support/Yandex/YandexBrowser",
Profiles: []string{"Default"},
Keys: masterkey.Set{masterkey.V10: keysFakeKey(t, "yandex+v10/keychain+AA==")},
},
{
Browser: "brave", Kind: "chromium", UserDataDir: `C:\Users\Jürgen\AppData\Local\BraveSoftware\Brave-Browser\User Data`,
Profiles: []string{"Default"},
Keys: masterkey.Set{masterkey.V10: keysFakeKey(t, "brave+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAAA=")},
},
},
}
}
func keysEmptyDump(t *testing.T) masterkey.Dump {
t.Helper()
return keysFreeze(t, masterkey.NewDump(), masterkey.Host{OS: "linux", Arch: "arm64"})
}
func TestKeysGolden(t *testing.T) {
tests := []struct {
name string
golden string
dump func(t *testing.T) masterkey.Dump
}{
{name: "vaults", golden: "keys.golden", dump: keysVaultsDump},
{name: "empty", golden: "keys-empty.golden", dump: keysEmptyDump},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
require.NoError(t, tt.dump(t).WriteJSON(&buf))
assertGolden(t, tt.golden, buf.String())
})
}
}
func TestKeysRead(t *testing.T) {
tests := []struct {
name string
golden string
edit func(t *testing.T, doc map[string]any)
want func(t *testing.T) masterkey.Dump
wantErr string
}{
{name: "golden", golden: "keys.golden", want: keysVaultsDump},
{name: "empty golden", golden: "keys-empty.golden", want: keysEmptyDump},
{name: "unknown fields", golden: "keys.golden", edit: keysAddUnknownFields, want: keysVaultsDump},
{name: "older version", golden: "keys.golden", edit: keysSetVersion("1"), wantErr: "unsupported dump version"},
{name: "newer version", golden: "keys.golden", edit: keysSetVersion("3"), wantErr: "unsupported dump version"},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
data, err := os.ReadFile(filepath.Join(goldenDir, tt.golden))
require.NoError(t, err)
if tt.edit != nil {
data = keysEditJSON(t, data, tt.edit)
}
got, err := masterkey.ReadJSON(bytes.NewReader(data))
if tt.wantErr != "" {
require.ErrorContains(t, err, tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want(t), got)
})
}
}
func keysEditJSON(t *testing.T, data []byte, edit func(t *testing.T, doc map[string]any)) []byte {
t.Helper()
var doc map[string]any
require.NoError(t, json.Unmarshal(data, &doc))
edit(t, doc)
edited, err := json.Marshal(doc)
require.NoError(t, err)
return edited
}
func keysAddUnknownFields(t *testing.T, doc map[string]any) {
doc["generator"] = map[string]any{"name": "hack-browser-data", "version": "v9.9.9"}
vaults, ok := doc["vaults"].([]any)
require.True(t, ok)
require.NotEmpty(t, vaults)
for _, v := range vaults {
vault, ok := v.(map[string]any)
require.True(t, ok)
vault["labels"] = []any{"work", "travel"}
}
}
func keysSetVersion(version string) func(t *testing.T, doc map[string]any) {
return func(_ *testing.T, doc map[string]any) { doc["version"] = version }
}
+9 -7
View File
@@ -10,19 +10,21 @@ import (
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/browser/browsertest"
"github.com/moond4rk/hackbrowserdata/internal/golden"
)
func TestListGolden(t *testing.T) {
home := t.TempDir()
setHome(t, home)
var paths []string
for _, inst := range chromiumFixtureInstalls {
dir := userDataDirOf(t, home, inst.key)
chromiumFixtureUserData(t, dir, inst.key)
paths = append(paths, dir, "<"+inst.key+">")
for _, inst := range browsertest.ChromiumInstalls {
dir := userDataDirOf(t, home, inst.Key)
browsertest.ChromiumUserData(t, dir, inst.Key)
paths = append(paths, dir, "<"+inst.Key+">")
}
dir := userDataDirOf(t, home, "firefox")
firefoxFixtureUserData(t, dir)
browsertest.FirefoxUserData(t, dir)
paths = append(paths, dir, "<firefox>", `\`, "/")
assertListGoldens(t, "list", strings.NewReplacer(paths...))
}
@@ -34,7 +36,7 @@ func TestListGoldenSafari(t *testing.T) {
home := t.TempDir()
setHome(t, home)
library := filepath.Join(home, "Library")
safariFixtureLibrary(t, library)
browsertest.SafariLibrary(t, library)
assertListGoldens(t, "list-safari", strings.NewReplacer(library, "<library>"))
}
@@ -50,7 +52,7 @@ func assertListGoldens(t *testing.T, prefix string, paths *strings.Replacer) {
name, args = prefix+"-detail.golden", []string{"--detail"}
}
runCmd(t, cmd, args...)
assertGolden(t, name, paths.Replace(out.String()))
golden.Assert(t, name, paths.Replace(out.String()))
}
}
+3 -1
View File
@@ -10,12 +10,14 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser/browsertest"
)
func TestStoppedRunPrintsNoErrorOrUsage(t *testing.T) {
home := t.TempDir()
setHome(t, home)
chromiumFixtureUserData(t, userDataDirOf(t, home, "chrome"), "chrome")
browsertest.ChromiumUserData(t, userDataDirOf(t, home, "chrome"), "chrome")
for _, tc := range []struct {
name, browser string
@@ -1,90 +0,0 @@
package main
import (
"bytes"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// Restore writes what dump writes: the extract golden, stamped with each browser's display name.
func TestRestoreGolden(t *testing.T) {
data := t.TempDir()
chromiumFixtureInstallations(t, data)
keys := chromiumFixtureKeysFile(t)
want := readGolden(t, "extract-json.golden")
t.Run("data-dir", func(t *testing.T) {
out := t.TempDir()
chromiumFixtureRestore(t, "--keys", keys, "--data-dir", data, "-d", out)
assert.Equal(t, want, bundleDir(t, out))
})
t.Run("zip", func(t *testing.T) {
out := filepath.Join(t.TempDir(), "results")
chromiumFixtureRestore(t, "--keys", keys, "--data-dir", data, "-d", out, "--zip")
entries, err := os.ReadDir(out)
require.NoError(t, err)
require.Len(t, entries, 1)
require.Equal(t, "results.zip", entries[0].Name())
archive := filepath.Join(out, "results.zip")
assertGolden(t, "restore-zip.golden", zipListing(t, archive))
unzipped, err := snapshot.Unzip(archive)
require.NoError(t, err)
defer unzipped.Close()
assert.Equal(t, want, bundleDir(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) {
dataZip := filepath.Join(t.TempDir(), "data.zip")
require.NoError(t, snapshot.Open(data).Zip(dataZip))
out := t.TempDir()
chromiumFixtureRestore(t, "--keys", keys, "--data-zip", dataZip, "-d", out)
assert.Equal(t, want, bundleDir(t, out))
})
}
func chromiumFixtureKeysFile(t *testing.T) string {
t.Helper()
profiles := make([]string, 0, len(chromiumFixtureProfiles))
for _, p := range chromiumFixtureProfiles {
profiles = append(profiles, p.dir)
}
dump := masterkey.Dump{
// A literal rather than DumpVersion: keys files written by today's dumpkeys must keep restoring.
Version: "2",
CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
Host: masterkey.Host{OS: "windows", Arch: "amd64"},
Vaults: []masterkey.Vault{},
}
for _, inst := range chromiumFixtureInstalls {
dump.Vaults = append(dump.Vaults, masterkey.Vault{
Browser: inst.key,
Kind: "chromium",
Profiles: profiles,
Keys: chromiumFixtureKeys,
})
}
var buf bytes.Buffer
require.NoError(t, dump.WriteJSON(&buf))
path := filepath.Join(t.TempDir(), "keys.json")
require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600))
return path
}
func chromiumFixtureRestore(t *testing.T, args ...string) {
t.Helper()
runCmd(t, restoreCmd(), args...)
}
@@ -1,444 +0,0 @@
package main
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf16"
"github.com/moond4rk/plist"
"github.com/stretchr/testify/require"
)
const (
safariFixtureWorkUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
safariFixtureUntitledUUID = "9A1B2C3D-4E5F-4A6B-8C7D-0E1F2A3B4C5D"
)
var safariFixtureStart = time.Date(2024, 3, 1, 9, 0, 0, 0, time.UTC)
func safariFixtureLibrary(t *testing.T, library string) {
t.Helper()
at := safariFixtureStart.Add
visit := func(offset time.Duration) float64 { return safariFixtureCoreData(at(offset)) }
day := 24 * time.Hour
legacyHome := filepath.Join(library, "Safari")
container := filepath.Join(library, "Containers", "com.apple.Safari", "Data", "Library")
workStore := filepath.Join(container, "WebKit", "WebsiteDataStore", strings.ToLower(safariFixtureWorkUUID))
fixtureSQLite(t, filepath.Join(container, "Safari", "SafariTabs.db"), safariFixtureTabsSchema,
`INSERT INTO bookmarks (id, parent, type, title, order_index, external_uuid, subtype) VALUES
(1, 0, 1, 'Favorites', 0, 'Favorites', 0),
(2, 0, 1, '', 1, 'DefaultProfile', 2),
(3, 0, 1, 'Work', 2, '`+safariFixtureWorkUUID+`', 2),
(4, 0, 1, NULL, 3, '`+safariFixtureUntitledUUID+`', 2)`)
fixtureSQLite(t, filepath.Join(legacyHome, "History.db"), safariFixtureHistoryItemsSchema, safariFixtureHistoryVisitsSchema,
safariFixtureInsertHistoryItem(1, "https://www.home.safari.test/", 42),
safariFixtureInsertHistoryVisit(1, 1, visit(time.Hour), "Home (old)"),
safariFixtureInsertHistoryVisit(2, 1, visit(3*time.Hour+500*time.Millisecond), "Home"),
safariFixtureInsertHistoryItem(2, "https://docs.home.safari.test/guide?q=go&lang=en", 7),
safariFixtureInsertHistoryVisit(3, 2, visit(4*time.Hour), `Guide, "quoted" & <b>bold</b>`),
safariFixtureInsertHistoryItem(3, "https://news.home.safari.test/ja", 3),
safariFixtureInsertHistoryVisit(4, 3, visit(5*time.Hour), "ニュース"),
safariFixtureInsertHistoryItem(4, "https://files.home.safari.test/report.pdf", 0),
)
fixtureSQLite(t, filepath.Join(container, "Safari", "Profiles", safariFixtureWorkUUID, "History.db"),
safariFixtureHistoryItemsSchema, safariFixtureHistoryVisitsSchema,
safariFixtureInsertHistoryItem(1, "https://intranet.work.safari.test/", 12),
safariFixtureInsertHistoryVisit(1, 1, visit(6*time.Hour), "Intranet"),
safariFixtureInsertHistoryItem(2, "https://wiki.work.safari.test/onboarding", 2),
safariFixtureInsertHistoryVisit(2, 2, visit(7*time.Hour), "Onboarding"),
)
fixtureSQLite(t, filepath.Join(container, "Safari", "Profiles", safariFixtureUntitledUUID, "History.db"),
safariFixtureHistoryItemsSchema, safariFixtureHistoryVisitsSchema,
safariFixtureInsertHistoryItem(1, "https://www.untitled.safari.test/", 1),
safariFixtureInsertHistoryVisit(1, 1, visit(8*time.Hour), "Untitled"),
)
fixtureWrite(t, filepath.Join(container, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t,
[]safariFixtureCookie{
{
domain: ".home.safari.test", name: "SID", path: "/", value: "sid-home.safari.test", flags: 0x5,
expires: at(365 * day), created: at(10*time.Minute + 750*time.Millisecond),
},
{
domain: "www.home.safari.test", name: "prefs", path: "/settings", value: "theme=dark",
expires: at(30 * day), created: at(20 * time.Minute),
},
},
[]safariFixtureCookie{
{
domain: ".home.safari.test", name: "tracker", path: "/", value: "opt-out", flags: 0x1,
expires: at(730 * day), created: at(30 * time.Minute),
},
{
domain: "app.home.safari.test", name: "csrf", path: "/", value: "token-123", flags: 0x4,
expires: at(day), created: at(40 * time.Minute),
},
},
)))
// Since macOS 14 the jar lives in the container, which wins over a leftover ~/Library/Cookies jar.
fixtureWrite(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t,
[]safariFixtureCookie{{
domain: "old.home.safari.test", name: "legacy", path: "/", value: "stale",
expires: at(day), created: at(time.Minute),
}},
)))
fixtureWrite(t, filepath.Join(workStore, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t,
[]safariFixtureCookie{
{
domain: ".work.safari.test", name: "SSO", path: "/", value: "sso-work.safari.test", flags: 0x5,
expires: at(7 * day), created: at(6 * time.Hour),
},
{
domain: "wiki.work.safari.test", name: "lang", path: "/", value: "en",
expires: at(90 * day), created: at(7 * time.Hour),
},
},
)))
safariFixturePlist(t, filepath.Join(legacyHome, "Bookmarks.plist"), safariFixtureBookmarks)
safariFixturePlist(t, filepath.Join(legacyHome, "Downloads.plist"), fmt.Sprintf(safariFixtureDownloads, safariFixtureWorkUUID))
defaultStore := filepath.Join(container, "WebKit", "WebsiteData", "Default")
fixtureWrite(t, filepath.Join(defaultStore, "salt"), "\x8f\x1e\x5a\x33\x0c\xd4\x71\x9b")
app := safariFixtureEndpoint{scheme: "https", host: "app.home.safari.test"}
safariFixtureOrigin(t, defaultStore, app, app,
[2]string{"greeting", "café"},
[2]string{"言語", "日本語"},
[2]string{"blob", strings.Repeat("x", 1100)},
)
safariFixtureOrigin(t, defaultStore,
safariFixtureEndpoint{scheme: "https", host: "shop.home.safari.test"},
safariFixtureEndpoint{scheme: "https", host: "cdn.home.safari.test", port: 8443},
[2]string{"consent", "yes"},
)
idbOnly := safariFixtureEndpoint{scheme: "https", host: "idb.home.safari.test"}
safariFixtureOrigin(t, defaultStore, idbOnly, idbOnly)
workApp := safariFixtureEndpoint{scheme: "https", host: "app.work.safari.test"}
safariFixtureOrigin(t, filepath.Join(workStore, "Origins"), workApp, workApp, [2]string{"greeting", "hello"})
safariFixturePlist(t, filepath.Join(container, "Safari", "AppExtensions", "Extensions.plist"), safariFixtureAppExtensions)
safariFixturePlist(t, filepath.Join(container, "Safari", "WebExtensions", "Extensions.plist"), safariFixtureWebExtensions)
}
func safariFixtureCoreData(ts time.Time) float64 {
const unixToCoreDataSeconds = 978_307_200
return float64(ts.UnixMilli())/1000 - unixToCoreDataSeconds
}
// Safari writes binary plists; the fixtures keep XML so they read like plutil's XML output.
func safariFixturePlist(t *testing.T, path, body string) {
t.Helper()
var v any
_, err := plist.Unmarshal([]byte(`<plist version="1.0">`+body+`</plist>`), &v)
require.NoError(t, err)
data, err := plist.Marshal(v, plist.BinaryFormat)
require.NoError(t, err)
fixtureWrite(t, path, string(data))
}
type safariFixtureCookie struct {
domain, name, path, value string
flags uint32
expires, created time.Time
}
type safariFixtureCookieHeader struct {
Size uint32
Version uint32
Flags uint32
HasPort uint32
DomainOffset uint32
NameOffset uint32
PathOffset uint32
ValueOffset uint32
CommentOffset uint32
EndOfHeader uint32
Expires float64
Created float64
}
// Each argument is one page of the jar.
func safariFixtureCookieFile(t *testing.T, pages ...[]safariFixtureCookie) []byte {
t.Helper()
encoded := make([][]byte, len(pages))
file := binary.BigEndian.AppendUint32([]byte("cook"), uint32(len(pages)))
for i, cookies := range pages {
encoded[i] = safariFixtureCookiePage(t, cookies)
file = binary.BigEndian.AppendUint32(file, uint32(len(encoded[i])))
}
for _, page := range encoded {
file = append(file, page...)
}
return append(file, make([]byte, 8)...) // the checksum, which the decoder reads but never verifies
}
func safariFixtureCookiePage(t *testing.T, cookies []safariFixtureCookie) []byte {
t.Helper()
records := make([][]byte, len(cookies))
for i, c := range cookies {
records[i] = safariFixtureCookieRecord(t, c)
}
page := binary.LittleEndian.AppendUint32([]byte{0x00, 0x00, 0x01, 0x00}, uint32(len(cookies)))
offset := 4 + 4 + 4*len(cookies) + 4
for _, r := range records {
page = binary.LittleEndian.AppendUint32(page, uint32(offset))
offset += len(r)
}
page = append(page, 0x00, 0x00, 0x00, 0x00)
for _, r := range records {
page = append(page, r...)
}
return page
}
func safariFixtureCookieRecord(t *testing.T, c safariFixtureCookie) []byte {
t.Helper()
header := safariFixtureCookieHeader{
Flags: c.flags,
Expires: safariFixtureCoreData(c.expires),
Created: safariFixtureCoreData(c.created),
}
headerSize := uint32(binary.Size(header))
var strs []byte
for _, f := range []struct {
offset *uint32
value string
}{
{&header.DomainOffset, c.domain},
{&header.NameOffset, c.name},
{&header.PathOffset, c.path},
{&header.ValueOffset, c.value},
} {
*f.offset = headerSize + uint32(len(strs))
strs = append(append(strs, f.value...), 0x00)
}
header.Size = headerSize + uint32(len(strs))
var b bytes.Buffer
require.NoError(t, binary.Write(&b, binary.LittleEndian, header))
return append(b.Bytes(), strs...)
}
type safariFixtureEndpoint struct {
scheme, host string
port uint16
}
// One partition of a WebKit origins root: top and frame differ for third-party storage, and an origin without
// localStorage items keeps only its origin file.
func safariFixtureOrigin(t *testing.T, root string, top, frame safariFixtureEndpoint, items ...[2]string) {
t.Helper()
dir := filepath.Join(root, safariFixtureHash(top), safariFixtureHash(frame))
fixtureWrite(t, filepath.Join(dir, "origin"), string(append(safariFixtureOriginBlock(top), safariFixtureOriginBlock(frame)...)))
if len(items) == 0 {
return
}
stmts := []string{safariFixtureItemTableSchema}
for _, item := range items {
stmts = append(stmts, fmt.Sprintf(`INSERT INTO ItemTable (key, value) VALUES ('%s', x'%x')`, item[0], safariFixtureUTF16(item[1])))
}
fixtureSQLite(t, filepath.Join(dir, "LocalStorage", "localstorage.sqlite3"), stmts...)
}
func safariFixtureHash(e safariFixtureEndpoint) string {
sum := sha256.Sum256([]byte(fmt.Sprintf("%s://%s:%d", e.scheme, e.host, e.port)))
return hex.EncodeToString(sum[:])
}
func safariFixtureOriginBlock(e safariFixtureEndpoint) []byte {
const latin1, defaultPort, explicitPort = 0x01, 0x00, 0x01
var b []byte
for _, s := range []string{e.scheme, e.host} {
b = binary.LittleEndian.AppendUint32(b, uint32(len(s)))
b = append(append(b, latin1), s...)
}
if e.port == 0 {
return append(b, defaultPort)
}
return binary.LittleEndian.AppendUint16(append(b, explicitPort), e.port)
}
func safariFixtureUTF16(s string) []byte {
var b []byte
for _, u := range utf16.Encode([]rune(s)) {
b = binary.LittleEndian.AppendUint16(b, u)
}
return b
}
func safariFixtureInsertHistoryItem(id int, url string, visitCount int) string {
return fmt.Sprintf(`INSERT INTO history_items (id, url, visit_count) VALUES (%d, '%s', %d)`, id, url, visitCount)
}
func safariFixtureInsertHistoryVisit(id, item int, visitTime float64, title string) string {
return fmt.Sprintf(`INSERT INTO history_visits (id, history_item, visit_time, title) VALUES (%d, %d, %f, '%s')`,
id, item, visitTime, title)
}
const safariFixtureTabsSchema = `CREATE TABLE bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
parent INTEGER,
type INTEGER,
title TEXT,
url TEXT,
order_index INTEGER NOT NULL,
external_uuid TEXT UNIQUE,
subtype INTEGER DEFAULT 0
)`
const safariFixtureHistoryItemsSchema = `CREATE TABLE history_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
domain_expansion TEXT NULL,
visit_count INTEGER NOT NULL DEFAULT 0,
daily_visit_counts BLOB NOT NULL DEFAULT x'',
weekly_visit_counts BLOB NULL,
autocomplete_triggers BLOB NULL,
should_recompute_derived_visit_counts INTEGER NOT NULL DEFAULT 1,
visit_count_score INTEGER NOT NULL DEFAULT 0
)`
const safariFixtureHistoryVisitsSchema = `CREATE TABLE history_visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
history_item INTEGER NOT NULL REFERENCES history_items(id),
visit_time REAL NOT NULL,
title TEXT NULL,
load_successful BOOLEAN NOT NULL DEFAULT 1,
http_non_get INTEGER NOT NULL DEFAULT 0,
synthesized INTEGER NOT NULL DEFAULT 0,
redirect_source INTEGER NULL,
redirect_destination INTEGER NULL,
origin INTEGER NOT NULL DEFAULT 0,
generation INTEGER NOT NULL DEFAULT 0,
attributes INTEGER NOT NULL DEFAULT 0,
score INTEGER NOT NULL DEFAULT 0
)`
const safariFixtureItemTableSchema = `CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`
const safariFixtureBookmarks = `<dict>
<key>Children</key>
<array>
<dict>
<key>Title</key><string>History</string>
<key>WebBookmarkIdentifier</key><string>History</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeProxy</string>
</dict>
<dict>
<key>Children</key>
<array>
<dict>
<key>URIDictionary</key><dict><key>title</key><string>Docs</string></dict>
<key>URLString</key><string>https://docs.home.safari.test/</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
</dict>
<dict>
<key>Children</key>
<array>
<dict>
<key>URIDictionary</key><dict><key>title</key><string>Long read &lt;with&gt; &amp; tags</string></dict>
<key>URLString</key><string>https://news.home.safari.test/long-read</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
</dict>
</array>
<key>Title</key><string>Reading</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
</dict>
<dict>
<key>URIDictionary</key><dict><key>title</key><string>Home</string></dict>
<key>URLString</key><string>https://www.home.safari.test/</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
</dict>
</array>
<key>Title</key><string>BookmarksBar</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
</dict>
<dict>
<key>Children</key>
<array>
<dict>
<key>URIDictionary</key><dict><key>title</key><string>Café menu</string></dict>
<key>URLString</key><string>https://shop.home.safari.test/menu</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
</dict>
</array>
<key>Title</key><string>BookmarksMenu</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
</dict>
<dict>
<key>Children</key>
<array>
<dict>
<key>ReadingList</key><dict><key>PreviewText</key><string>A post worth saving.</string></dict>
<key>URIDictionary</key><dict><key>title</key><string>Saved post</string></dict>
<key>URLString</key><string>https://blog.home.safari.test/post</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
</dict>
<dict>
<key>Title</key><string>Untitled entry</string>
<key>URLString</key><string>https://blog.home.safari.test/draft</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
</dict>
</array>
<key>Title</key><string>com.apple.ReadingList</string>
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
</dict>
</array>
<key>Title</key><string></string>
<key>WebBookmarkFileVersion</key><integer>1</integer>
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
</dict>`
const safariFixtureDownloads = `<dict>
<key>DownloadHistory</key>
<array>
<dict>
<key>DownloadEntryIdentifier</key><string>6B3E1D2C-0A9F-4E8D-B7C6-A5F4E3D2C1B0</string>
<key>DownloadEntryPath</key><string>/Users/alice/Downloads/report.pdf</string>
<key>DownloadEntryProfileUUIDStringKey</key><string>DefaultProfile</string>
<key>DownloadEntryProgressBytesSoFar</key><integer>52344</integer>
<key>DownloadEntryProgressTotalToLoad</key><integer>52344</integer>
<key>DownloadEntryRemoveWhenDoneKey</key><false/>
<key>DownloadEntryURL</key><string>https://files.home.safari.test/report.pdf</string>
</dict>
<dict>
<key>DownloadEntryIdentifier</key><string>1C2D3E4F-5A6B-4C7D-8E9F-0A1B2C3D4E5F</string>
<key>DownloadEntryPath</key><string>/Users/alice/Downloads/slides.key</string>
<key>DownloadEntryProfileUUIDStringKey</key><string>%[1]s</string>
<key>DownloadEntryProgressBytesSoFar</key><integer>1048576</integer>
<key>DownloadEntryProgressTotalToLoad</key><integer>1048576</integer>
<key>DownloadEntryRemoveWhenDoneKey</key><false/>
<key>DownloadEntryURL</key><string>https://files.work.safari.test/slides.key</string>
</dict>
<dict>
<key>DownloadEntryIdentifier</key><string>F0E1D2C3-B4A5-4968-8776-5A4B3C2D1E0F</string>
<key>DownloadEntryPath</key><string>/Users/alice/Downloads/archive.tar.gz</string>
<key>DownloadEntryProgressBytesSoFar</key><integer>2048</integer>
<key>DownloadEntryProgressTotalToLoad</key><integer>2048</integer>
<key>DownloadEntryRemoveWhenDoneKey</key><true/>
<key>DownloadEntryURL</key><string>https://files.home.safari.test/archive.tar.gz</string>
</dict>
</array>
</dict>`
const safariFixtureAppExtensions = `<dict>
<key>com.example.Clipper.Extension (ABCDE12345)</key>
<dict><key>Permissions</key><dict/></dict>
</dict>`
const safariFixtureWebExtensions = `<dict>
<key>com.example.Blocker.Extension (FGHIJ67890)</key>
<dict><key>Enabled</key><true/></dict>
<key>com.example.Reader.Extension (KLMNO13579)</key>
<dict><key>Enabled</key><false/></dict>
<key>com.example.Legacy</key>
<dict><key>Enabled</key><true/></dict>
</dict>`
+46
View File
@@ -0,0 +1,46 @@
hack-browser-data --browser -b string "all"
hack-browser-data --category -c string "all"
hack-browser-data --dir -d string "results"
hack-browser-data --format -f string "json"
hack-browser-data --help -h bool "false"
hack-browser-data --keychain-pw string ""
hack-browser-data --keychain-pw-stdin bool "false"
hack-browser-data --profile-path -p string ""
hack-browser-data --verbose -v bool "false" persistent
hack-browser-data --zip bool "false"
hack-browser-data archive --browser -b string "all"
hack-browser-data archive --category -c string "all"
hack-browser-data archive --help -h bool "false"
hack-browser-data archive --output -o string "browser-data.zip"
hack-browser-data archive --verbose -v bool "false" inherited
hack-browser-data dump --browser -b string "all"
hack-browser-data dump --category -c string "all"
hack-browser-data dump --dir -d string "results"
hack-browser-data dump --format -f string "json"
hack-browser-data dump --help -h bool "false"
hack-browser-data dump --keychain-pw string ""
hack-browser-data dump --keychain-pw-stdin bool "false"
hack-browser-data dump --profile-path -p string ""
hack-browser-data dump --zip bool "false"
hack-browser-data dump --verbose -v bool "false" inherited
hack-browser-data dumpkeys --browser -b string "all"
hack-browser-data dumpkeys --help -h bool "false"
hack-browser-data dumpkeys --keychain-pw string ""
hack-browser-data dumpkeys --keychain-pw-stdin bool "false"
hack-browser-data dumpkeys --output -o string ""
hack-browser-data dumpkeys --verbose -v bool "false" inherited
hack-browser-data list --detail bool "false"
hack-browser-data list --help -h bool "false"
hack-browser-data list --verbose -v bool "false" inherited
hack-browser-data restore --browser -b string ""
hack-browser-data restore --category -c string "all"
hack-browser-data restore --data-dir string ""
hack-browser-data restore --data-zip string ""
hack-browser-data restore --dir -d string "results"
hack-browser-data restore --format -f string "json"
hack-browser-data restore --help -h bool "false"
hack-browser-data restore --keys string ""
hack-browser-data restore --zip bool "false"
hack-browser-data restore --verbose -v bool "false" inherited
hack-browser-data version --help -h bool "false"
hack-browser-data version --verbose -v bool "false" inherited
+7
View File
@@ -0,0 +1,7 @@
Browser Profile password cookie bookmark history download creditcard extension localstorage sessionstorage
Chrome Default 3 4 3 3 2 2 3 5 3
Chrome Profile 1 2 4 3 3 2 2 3 5 3
Microsoft Edge Default 3 4 3 3 2 2 3 5 3
Microsoft Edge Profile 1 2 4 3 3 2 2 3 5 3
Firefox abcd1234.default-release 3 4 4 9 3 0 2 3 0
Firefox wxyz5678.work 3 4 4 9 3 0 2 3 0
@@ -0,0 +1,4 @@
Browser Profile password cookie bookmark history download creditcard extension localstorage sessionstorage
Safari default 0 4 6 4 2 0 4 4 0
Safari Work 0 2 0 2 1 0 0 1 0
Safari profile-9a1b2c3d 0 0 0 1 0 0 0 0 0
+4
View File
@@ -0,0 +1,4 @@
Browser Profile Path
Safari default <library>/Safari
Safari Work <library>/Containers/com.apple.Safari/Data/Library/Safari/Profiles/5604E6F5-02ED-4E40-8249-63DE7BC986C8
Safari profile-9a1b2c3d <library>/Containers/com.apple.Safari/Data/Library/Safari/Profiles/9A1B2C3D-4E5F-4A6B-8C7D-0E1F2A3B4C5D
+7
View File
@@ -0,0 +1,7 @@
Browser Profile Path
Chrome Default <chrome>/Default
Chrome Profile 1 <chrome>/Profile 1
Microsoft Edge Default <edge>/Default
Microsoft Edge Profile 1 <edge>/Profile 1
Firefox abcd1234.default-release <firefox>/abcd1234.default-release
Firefox wxyz5678.work <firefox>/wxyz5678.work