mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
refactor: add the Safari base under internal/browser (#660)
Parsers move with git mv and hand records to a Collector; discovery reads a copy of SafariTabs.db, and app hands the run's login keychain to the default profile's password extractor. The old browser/safari runs the new extractors.
This commit is contained in:
1 parent
2093045664
commit
4add07e825
37 files changed
+1757
-949
No files matched your search
@@ -0,0 +1,106 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/sqlitex"
|
||||
)
|
||||
|
||||
// list --detail keeps today's counting queries until the switch-over, when it counts what the extractors emit.
|
||||
const safariCountHistoryQuery = `SELECT COUNT(*) FROM history_items`
|
||||
|
||||
const (
|
||||
webkitOriginFile = "origin"
|
||||
webkitLocalStorageSubdir = "LocalStorage"
|
||||
webkitLocalStorageDB = "localstorage.sqlite3"
|
||||
webkitOriginSaltName = "salt"
|
||||
)
|
||||
|
||||
func countHistories(path string) (int, error) {
|
||||
return sqlitex.CountRows(path, true, safariCountHistoryQuery)
|
||||
}
|
||||
|
||||
// countLocalStorage sums ItemTable row counts across every origin DB under root without
|
||||
// parsing origin files or decoding values — CountEntries callers only need the total, not the
|
||||
// URLs or plaintext. COUNT(key) naturally excludes NULL keys, matching the same skip rule
|
||||
// applied by readLocalStorageFile, so count and extract stay in sync.
|
||||
func countLocalStorage(root string) (int, error) {
|
||||
dirs, err := findOriginDataDirs(root)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total := 0
|
||||
for _, od := range dirs {
|
||||
dbPath := filepath.Join(od, webkitLocalStorageSubdir, webkitLocalStorageDB)
|
||||
n, err := countLocalStorageFile(dbPath)
|
||||
if err != nil {
|
||||
log.Debugf("safari localstorage: count %s: %v", dbPath, err)
|
||||
continue
|
||||
}
|
||||
total += n
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func countLocalStorageFile(path string) (int, error) {
|
||||
// mode=ro (no immutable) so SQLite replays the copied -wal sidecar — this surfaces entries
|
||||
// Safari has committed to WAL but not yet checkpointed to the main DB. Writes SQLite might
|
||||
// make to the temp-copy's -shm during replay are harmless; the Session cleanup removes
|
||||
// everything. Live-file reads (profiles.go) still use immutable=1 to stay off the real WAL.
|
||||
dsn := "file:" + path + "?mode=ro"
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("open %s: %w", path, err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.Ping(); err != nil {
|
||||
return 0, fmt.Errorf("ping %s: %w", path, err)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(`SELECT COUNT(key) FROM ItemTable`).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("count ItemTable: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// findOriginDataDirs returns <root>/<h1>/<h2>/ paths that contain both an "origin" file and
|
||||
// a "LocalStorage/localstorage.sqlite3" database. Non-directory entries, the "salt" sibling,
|
||||
// and partition dirs without localStorage data are silently skipped.
|
||||
func findOriginDataDirs(root string) ([]string, error) {
|
||||
topEntries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read origins root %s: %w", root, err)
|
||||
}
|
||||
var out []string
|
||||
for _, top := range topEntries {
|
||||
if !top.IsDir() || top.Name() == webkitOriginSaltName {
|
||||
continue
|
||||
}
|
||||
topPath := filepath.Join(root, top.Name())
|
||||
frameEntries, err := os.ReadDir(topPath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, frame := range frameEntries {
|
||||
if !frame.IsDir() {
|
||||
continue
|
||||
}
|
||||
framePath := filepath.Join(topPath, frame.Name())
|
||||
if _, err := os.Stat(filepath.Join(framePath, webkitOriginFile)); err != nil {
|
||||
continue
|
||||
}
|
||||
dbPath := filepath.Join(framePath, webkitLocalStorageSubdir, webkitLocalStorageDB)
|
||||
if _, err := os.Stat(dbPath); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, framePath)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func setupSafariHistoryDB(t *testing.T) string {
|
||||
t.Helper()
|
||||
return createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://github.com", "github.com", 100),
|
||||
insertHistoryItem(2, "https://go.dev", "go.dev", 50),
|
||||
insertHistoryItem(3, "https://example.com", "example.com", 200),
|
||||
// Item 1 has two visits — extractHistories must deduplicate.
|
||||
insertHistoryVisit(1, 1, 704067600.0, "GitHub"),
|
||||
insertHistoryVisit(2, 1, 705067600.0, "GitHub - Latest"),
|
||||
insertHistoryVisit(3, 2, 703067600.0, "The Go Programming Language"),
|
||||
insertHistoryVisit(4, 3, 700067600.0, "Example Domain"),
|
||||
)
|
||||
}
|
||||
|
||||
func TestCountHistories(t *testing.T) {
|
||||
path := setupSafariHistoryDB(t)
|
||||
|
||||
count, err := countHistories(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, count)
|
||||
}
|
||||
|
||||
func TestCountHistories_Empty(t *testing.T) {
|
||||
path := createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema})
|
||||
|
||||
count, err := countHistories(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
func TestCountLocalStorage(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://a.com": {{Key: "k1", Value: "v1"}, {Key: "k2", Value: "v2"}},
|
||||
"https://b.com": {{Key: "k3", Value: "v3"}},
|
||||
"https://c.com:8443": {{Key: "k4", Value: "v4"}},
|
||||
})
|
||||
count, err := countLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 4, count)
|
||||
}
|
||||
|
||||
func TestCountLocalStorage_DirMissing(t *testing.T) {
|
||||
count, err := countLocalStorage(filepath.Join(t.TempDir(), "nope"))
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
func TestCountLocalStorageFile_SkipsNullKey(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "ls.sqlite3")
|
||||
writeLocalStorageDB(t, dbPath, []testLocalStorageItem{
|
||||
{Key: "k1", Value: "v1"},
|
||||
{Key: "k2", Value: "v2"},
|
||||
}, true /*addNullKey*/)
|
||||
|
||||
count, err := countLocalStorageFile(dbPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, count, "NULL keys are excluded from count to match extract's skip rule")
|
||||
}
|
||||
|
||||
func TestCountLocalStorageFile_MissingTable(t *testing.T) {
|
||||
// Real Safari has origin dirs with LocalStorage/localstorage.sqlite3 but no ItemTable yet
|
||||
// (seen during live verification). countLocalStorageFile must surface the error so the
|
||||
// caller can log-and-skip rather than counting 0 silently.
|
||||
dbPath := filepath.Join(t.TempDir(), "empty.sqlite3")
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
_, err = countLocalStorageFile(dbPath)
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
)
|
||||
|
||||
// safariBookmark mirrors the plist structure of Safari's Bookmarks.plist.
|
||||
type safariBookmark struct {
|
||||
Type string `plist:"WebBookmarkType"`
|
||||
Title string `plist:"Title"`
|
||||
URLString string `plist:"URLString"`
|
||||
URIDictionary uriDictionary `plist:"URIDictionary"`
|
||||
Children []safariBookmark `plist:"Children"`
|
||||
}
|
||||
|
||||
type uriDictionary struct {
|
||||
Title string `plist:"title"`
|
||||
}
|
||||
|
||||
const (
|
||||
bookmarkTypeLeaf = "WebBookmarkTypeLeaf"
|
||||
bookmarkTypeList = "WebBookmarkTypeList"
|
||||
)
|
||||
|
||||
func extractBookmarks(path string) ([]record.Bookmark, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open bookmarks: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var root safariBookmark
|
||||
if err := plist.NewDecoder(f).Decode(&root); err != nil {
|
||||
return nil, fmt.Errorf("decode bookmarks: %w", err)
|
||||
}
|
||||
|
||||
var bookmarks []record.Bookmark
|
||||
walkBookmarks(root.Children, "", &bookmarks)
|
||||
return bookmarks, nil
|
||||
}
|
||||
|
||||
// walkBookmarks recursively traverses the bookmark tree, collecting leaf entries.
|
||||
func walkBookmarks(nodes []safariBookmark, folder string, out *[]record.Bookmark) {
|
||||
for i, node := range nodes {
|
||||
switch node.Type {
|
||||
case bookmarkTypeLeaf:
|
||||
title := node.URIDictionary.Title
|
||||
if title == "" {
|
||||
title = node.Title
|
||||
}
|
||||
if node.URLString == "" {
|
||||
continue
|
||||
}
|
||||
*out = append(*out, record.Bookmark{
|
||||
ID: int64(i),
|
||||
Name: title,
|
||||
URL: node.URLString,
|
||||
Folder: folder,
|
||||
Type: "bookmark",
|
||||
CreatedAt: time.Time{},
|
||||
})
|
||||
case bookmarkTypeList:
|
||||
name := node.Title
|
||||
if name == "com.apple.ReadingList" {
|
||||
name = "ReadingList"
|
||||
}
|
||||
walkBookmarks(node.Children, name, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func countBookmarks(path string) (int, error) {
|
||||
bookmarks, err := extractBookmarks(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(bookmarks), nil
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func buildTestBookmarksPlist(t *testing.T, root safariBookmark) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "Bookmarks.plist")
|
||||
f, err := os.Create(path)
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
require.NoError(t, plist.NewBinaryEncoder(f).Encode(root))
|
||||
return path
|
||||
}
|
||||
|
||||
func TestExtractBookmarks(t *testing.T) {
|
||||
root := safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeList,
|
||||
Title: "BookmarksBar",
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeLeaf,
|
||||
URLString: "https://github.com",
|
||||
URIDictionary: uriDictionary{Title: "GitHub"},
|
||||
},
|
||||
{
|
||||
Type: bookmarkTypeLeaf,
|
||||
URLString: "https://go.dev",
|
||||
URIDictionary: uriDictionary{Title: "Go"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: bookmarkTypeList,
|
||||
Title: "BookmarksMenu",
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeLeaf,
|
||||
URLString: "https://example.com",
|
||||
URIDictionary: uriDictionary{Title: "Example"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestBookmarksPlist(t, root)
|
||||
bookmarks, err := extractBookmarks(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, bookmarks, 3)
|
||||
|
||||
// Verify folder assignment
|
||||
assert.Equal(t, "GitHub", bookmarks[0].Name)
|
||||
assert.Equal(t, "https://github.com", bookmarks[0].URL)
|
||||
assert.Equal(t, "BookmarksBar", bookmarks[0].Folder)
|
||||
|
||||
assert.Equal(t, "Go", bookmarks[1].Name)
|
||||
assert.Equal(t, "BookmarksBar", bookmarks[1].Folder)
|
||||
|
||||
assert.Equal(t, "Example", bookmarks[2].Name)
|
||||
assert.Equal(t, "BookmarksMenu", bookmarks[2].Folder)
|
||||
}
|
||||
|
||||
func TestExtractBookmarks_ReadingList(t *testing.T) {
|
||||
root := safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeList,
|
||||
Title: "com.apple.ReadingList",
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeLeaf,
|
||||
URLString: "https://blog.example.com/post",
|
||||
URIDictionary: uriDictionary{Title: "Blog Post"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestBookmarksPlist(t, root)
|
||||
bookmarks, err := extractBookmarks(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, bookmarks, 1)
|
||||
assert.Equal(t, "ReadingList", bookmarks[0].Folder)
|
||||
}
|
||||
|
||||
func TestExtractBookmarks_SkipsEmptyURL(t *testing.T) {
|
||||
root := safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeLeaf,
|
||||
URLString: "", // no URL, should be skipped
|
||||
URIDictionary: uriDictionary{Title: "Empty"},
|
||||
},
|
||||
{
|
||||
Type: bookmarkTypeLeaf,
|
||||
URLString: "https://valid.com",
|
||||
URIDictionary: uriDictionary{Title: "Valid"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestBookmarksPlist(t, root)
|
||||
bookmarks, err := extractBookmarks(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, bookmarks, 1)
|
||||
assert.Equal(t, "Valid", bookmarks[0].Name)
|
||||
}
|
||||
|
||||
func TestExtractBookmarks_NestedFolders(t *testing.T) {
|
||||
root := safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeList,
|
||||
Title: "Work",
|
||||
Children: []safariBookmark{
|
||||
{
|
||||
Type: bookmarkTypeList,
|
||||
Title: "Projects",
|
||||
Children: []safariBookmark{
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://deep.com", URIDictionary: uriDictionary{Title: "Deep"}},
|
||||
},
|
||||
},
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://shallow.com", URIDictionary: uriDictionary{Title: "Shallow"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestBookmarksPlist(t, root)
|
||||
bookmarks, err := extractBookmarks(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, bookmarks, 2)
|
||||
|
||||
// Nested leaf gets the immediate parent folder name
|
||||
assert.Equal(t, "Deep", bookmarks[0].Name)
|
||||
assert.Equal(t, "Projects", bookmarks[0].Folder)
|
||||
|
||||
assert.Equal(t, "Shallow", bookmarks[1].Name)
|
||||
assert.Equal(t, "Work", bookmarks[1].Folder)
|
||||
}
|
||||
|
||||
func TestCountBookmarks(t *testing.T) {
|
||||
root := safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://a.com", URIDictionary: uriDictionary{Title: "A"}},
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://b.com", URIDictionary: uriDictionary{Title: "B"}},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestBookmarksPlist(t, root)
|
||||
count, err := countBookmarks(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, count)
|
||||
}
|
||||
|
||||
func TestExtractBookmarks_Empty(t *testing.T) {
|
||||
root := safariBookmark{Type: bookmarkTypeList}
|
||||
path := buildTestBookmarksPlist(t, root)
|
||||
|
||||
bookmarks, err := extractBookmarks(path)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, bookmarks)
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/moond4rk/binarycookies"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
)
|
||||
|
||||
func extractCookies(path string) ([]record.Cookie, error) {
|
||||
pages, err := decodeBinaryCookies(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var cookies []record.Cookie
|
||||
for _, page := range pages {
|
||||
for _, c := range page.Cookies {
|
||||
hasExpire := !c.Expires.IsZero()
|
||||
// binarycookies returns time.Time in Local; normalize to UTC
|
||||
// so exported JSON matches Chromium/Firefox cookie output.
|
||||
cookies = append(cookies, record.Cookie{
|
||||
Host: string(c.Domain),
|
||||
Path: string(c.Path),
|
||||
Name: string(c.Name),
|
||||
Value: string(c.Value),
|
||||
IsSecure: c.Secure,
|
||||
IsHTTPOnly: c.HTTPOnly,
|
||||
HasExpire: hasExpire,
|
||||
IsPersistent: hasExpire,
|
||||
ExpireAt: c.Expires.UTC(),
|
||||
CreatedAt: c.Creation.UTC(),
|
||||
})
|
||||
}
|
||||
}
|
||||
return cookies, nil
|
||||
}
|
||||
|
||||
func countCookies(path string) (int, error) {
|
||||
pages, err := decodeBinaryCookies(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var total int
|
||||
for _, page := range pages {
|
||||
total += len(page.Cookies)
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func decodeBinaryCookies(path string) ([]binarycookies.Page, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open cookies file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
jar := binarycookies.New(f)
|
||||
pages, err := jar.Decode()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode cookies: %w", err)
|
||||
}
|
||||
return pages, nil
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// buildTestBinaryCookies constructs a minimal valid Cookies.binarycookies file
|
||||
// containing the given cookies. Each cookie is placed in its own page.
|
||||
func buildTestBinaryCookies(t *testing.T, cookies []testCookie) string {
|
||||
t.Helper()
|
||||
|
||||
var pages [][]byte
|
||||
for _, c := range cookies {
|
||||
pages = append(pages, buildPage(c))
|
||||
}
|
||||
|
||||
path := filepath.Join(t.TempDir(), "Cookies.binarycookies")
|
||||
f, err := os.Create(path)
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
|
||||
// File header: magic + numPages (big-endian)
|
||||
_, err = f.WriteString("cook")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, binary.Write(f, binary.BigEndian, uint32(len(pages))))
|
||||
|
||||
// Page sizes (big-endian)
|
||||
for _, p := range pages {
|
||||
require.NoError(t, binary.Write(f, binary.BigEndian, uint32(len(p))))
|
||||
}
|
||||
|
||||
// Page data
|
||||
for _, p := range pages {
|
||||
_, err = f.Write(p)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Checksum (8 bytes, not validated by decoder)
|
||||
_, err = f.Write(make([]byte, 8))
|
||||
require.NoError(t, err)
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
type testCookie struct {
|
||||
domain, name, path, value string
|
||||
secure, httpOnly bool
|
||||
expires, creation float64 // Core Data epoch seconds
|
||||
}
|
||||
|
||||
func buildPage(c testCookie) []byte {
|
||||
// Cookie string data: domain\0 name\0 path\0 value\0
|
||||
domain := c.domain + "\x00"
|
||||
name := c.name + "\x00"
|
||||
cpath := c.path + "\x00"
|
||||
value := c.value + "\x00"
|
||||
|
||||
// Cookie binary layout (all offsets are from cookie start):
|
||||
// size(4) + unknown1(4) + flags(4) + unknown2(4)
|
||||
// + domainOff(4) + nameOff(4) + pathOff(4) + valueOff(4) + commentOff(4)
|
||||
// + endHeader(4) + expires(8) + creation(8)
|
||||
// = 56 bytes header, then string data
|
||||
const headerSize = 56
|
||||
domainOffset := uint32(headerSize)
|
||||
nameOffset := domainOffset + uint32(len(domain))
|
||||
pathOffset := nameOffset + uint32(len(name))
|
||||
valueOffset := pathOffset + uint32(len(cpath))
|
||||
cookieSize := valueOffset + uint32(len(value))
|
||||
|
||||
var flags uint32
|
||||
switch {
|
||||
case c.secure && c.httpOnly:
|
||||
flags = 0x5
|
||||
case c.httpOnly:
|
||||
flags = 0x4
|
||||
case c.secure:
|
||||
flags = 0x1
|
||||
}
|
||||
|
||||
// Build cookie bytes (little-endian)
|
||||
cookie := make([]byte, cookieSize)
|
||||
binary.LittleEndian.PutUint32(cookie[0:], cookieSize)
|
||||
// cookie[4:8] = unknown1 (zero)
|
||||
binary.LittleEndian.PutUint32(cookie[8:], flags)
|
||||
// cookie[12:16] = unknown2 (zero)
|
||||
binary.LittleEndian.PutUint32(cookie[16:], domainOffset)
|
||||
binary.LittleEndian.PutUint32(cookie[20:], nameOffset)
|
||||
binary.LittleEndian.PutUint32(cookie[24:], pathOffset)
|
||||
binary.LittleEndian.PutUint32(cookie[28:], valueOffset)
|
||||
// cookie[32:36] = commentOffset (zero = no comment)
|
||||
// cookie[36:40] = endHeader marker (zero)
|
||||
binary.LittleEndian.PutUint64(cookie[40:], math.Float64bits(c.expires))
|
||||
binary.LittleEndian.PutUint64(cookie[48:], math.Float64bits(c.creation))
|
||||
copy(cookie[domainOffset:], domain)
|
||||
copy(cookie[nameOffset:], name)
|
||||
copy(cookie[pathOffset:], cpath)
|
||||
copy(cookie[valueOffset:], value)
|
||||
|
||||
// Page layout: marker(4) + cookieCount(4) + offsets(4*N) + endMarker(4) + cookies
|
||||
const pageHeaderSize = 16 // marker + count + 1 offset + end marker
|
||||
page := make([]byte, pageHeaderSize+len(cookie))
|
||||
copy(page[0:4], []byte{0x00, 0x00, 0x01, 0x00}) // page start marker
|
||||
binary.LittleEndian.PutUint32(page[4:], 1) // 1 cookie
|
||||
binary.LittleEndian.PutUint32(page[8:], pageHeaderSize)
|
||||
// page[12:16] = page end marker (zero)
|
||||
copy(page[pageHeaderSize:], cookie)
|
||||
|
||||
return page
|
||||
}
|
||||
|
||||
func TestExtractCookies(t *testing.T) {
|
||||
path := buildTestBinaryCookies(t, []testCookie{
|
||||
{
|
||||
domain: ".example.com", name: "session", path: "/", value: "abc123",
|
||||
secure: true, httpOnly: true,
|
||||
expires: 2000000000.0, creation: 700000000.0,
|
||||
},
|
||||
{
|
||||
domain: ".go.dev", name: "lang", path: "/", value: "en",
|
||||
secure: false, httpOnly: false,
|
||||
expires: 2000000000.0, creation: 750000000.0,
|
||||
},
|
||||
})
|
||||
|
||||
cookies, err := extractCookies(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, cookies, 2)
|
||||
|
||||
// Cookies keep the file's order; the exporter sorts them.
|
||||
assert.Equal(t, ".example.com", cookies[0].Host)
|
||||
assert.Equal(t, ".go.dev", cookies[1].Host)
|
||||
|
||||
// Verify field mapping
|
||||
c := cookies[0] // .example.com cookie
|
||||
assert.Equal(t, "session", c.Name)
|
||||
assert.Equal(t, "abc123", c.Value)
|
||||
assert.Equal(t, "/", c.Path)
|
||||
assert.True(t, c.IsSecure)
|
||||
assert.True(t, c.IsHTTPOnly)
|
||||
assert.False(t, c.CreatedAt.IsZero())
|
||||
assert.False(t, c.ExpireAt.IsZero())
|
||||
}
|
||||
|
||||
func TestCountCookies(t *testing.T) {
|
||||
path := buildTestBinaryCookies(t, []testCookie{
|
||||
{domain: ".a.com", name: "a", path: "/", value: "1", expires: 2000000000.0, creation: 700000000.0},
|
||||
{domain: ".b.com", name: "b", path: "/", value: "2", expires: 2000000000.0, creation: 700000000.0},
|
||||
{domain: ".c.com", name: "c", path: "/", value: "3", expires: 2000000000.0, creation: 700000000.0},
|
||||
})
|
||||
|
||||
count, err := countCookies(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, count)
|
||||
}
|
||||
|
||||
func TestExtractCookies_InvalidFile(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "bad.binarycookies")
|
||||
require.NoError(t, os.WriteFile(path, []byte("not a cookies file"), 0o644))
|
||||
|
||||
_, err := extractCookies(path)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestExtractCookies_FileNotFound(t *testing.T) {
|
||||
_, err := extractCookies("/nonexistent/Cookies.binarycookies")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
)
|
||||
|
||||
type safariDownloads struct {
|
||||
DownloadHistory []safariDownloadEntry `plist:"DownloadHistory"`
|
||||
}
|
||||
|
||||
type safariDownloadEntry struct {
|
||||
URL string `plist:"DownloadEntryURL"`
|
||||
Path string `plist:"DownloadEntryPath"`
|
||||
TotalBytes int64 `plist:"DownloadEntryProgressTotalToLoad"`
|
||||
ProfileUUID string `plist:"DownloadEntryProfileUUIDStringKey"`
|
||||
RemoveWhenDone bool `plist:"DownloadEntryRemoveWhenDoneKey"`
|
||||
DownloadIdentifier string `plist:"DownloadEntryIdentifier"`
|
||||
}
|
||||
|
||||
// extractDownloads reads Downloads.plist (shared across Safari profiles) and returns only the entries
|
||||
// owned by ownerUUID — either "DefaultProfile" or a named profile's uppercase UUID. Entries written by
|
||||
// older Safari (no ProfileUUID field) are attributed to the default profile.
|
||||
func extractDownloads(path, ownerUUID string) ([]record.Download, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open downloads: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var dl safariDownloads
|
||||
if err := plist.NewDecoder(f).Decode(&dl); err != nil {
|
||||
return nil, fmt.Errorf("decode downloads: %w", err)
|
||||
}
|
||||
|
||||
var downloads []record.Download
|
||||
for _, d := range dl.DownloadHistory {
|
||||
if !ownsDownload(d.ProfileUUID, ownerUUID) {
|
||||
continue
|
||||
}
|
||||
downloads = append(downloads, record.Download{
|
||||
URL: d.URL,
|
||||
TargetPath: d.Path,
|
||||
TotalBytes: d.TotalBytes,
|
||||
})
|
||||
}
|
||||
return downloads, nil
|
||||
}
|
||||
|
||||
func countDownloads(path, ownerUUID string) (int, error) {
|
||||
downloads, err := extractDownloads(path, ownerUUID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(downloads), nil
|
||||
}
|
||||
|
||||
// ownsDownload treats empty ProfileUUID as DefaultProfile for backward compat with pre-profile Safari.
|
||||
func ownsDownload(entryUUID, ownerUUID string) bool {
|
||||
if entryUUID == "" {
|
||||
entryUUID = defaultProfileSentinel
|
||||
}
|
||||
return entryUUID == ownerUUID
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func buildTestDownloadsPlist(t *testing.T, dl safariDownloads) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "Downloads.plist")
|
||||
f, err := os.Create(path)
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
require.NoError(t, plist.NewBinaryEncoder(f).Encode(dl))
|
||||
return path
|
||||
}
|
||||
|
||||
func TestExtractDownloads_DefaultProfileOnly(t *testing.T) {
|
||||
// Mixed-owner plist: only entries tagged with DefaultProfile (or untagged, for
|
||||
// pre-profile Safari) should surface for the default profile.
|
||||
const namedUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
dl := safariDownloads{
|
||||
DownloadHistory: []safariDownloadEntry{
|
||||
{URL: "https://a.com/a.zip", Path: "/tmp/a.zip", TotalBytes: 1024000, ProfileUUID: defaultProfileSentinel},
|
||||
{URL: "https://b.com/b.zip", Path: "/tmp/b.zip", TotalBytes: 98765432, ProfileUUID: namedUUID},
|
||||
{URL: "https://c.com/legacy.zip", Path: "/tmp/legacy.zip", TotalBytes: 500, ProfileUUID: ""}, // pre-profile Safari
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestDownloadsPlist(t, dl)
|
||||
downloads, err := extractDownloads(path, defaultProfileSentinel)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, downloads, 2)
|
||||
assert.Equal(t, "https://a.com/a.zip", downloads[0].URL)
|
||||
assert.Equal(t, "https://c.com/legacy.zip", downloads[1].URL)
|
||||
}
|
||||
|
||||
func TestExtractDownloads_NamedProfileOnly(t *testing.T) {
|
||||
const namedUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
dl := safariDownloads{
|
||||
DownloadHistory: []safariDownloadEntry{
|
||||
{URL: "https://a.com/a.zip", Path: "/tmp/a.zip", TotalBytes: 100, ProfileUUID: defaultProfileSentinel},
|
||||
{URL: "https://b.com/b.zip", Path: "/tmp/b.zip", TotalBytes: 200, ProfileUUID: namedUUID},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestDownloadsPlist(t, dl)
|
||||
downloads, err := extractDownloads(path, namedUUID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, downloads, 1)
|
||||
assert.Equal(t, "https://b.com/b.zip", downloads[0].URL)
|
||||
assert.Equal(t, int64(200), downloads[0].TotalBytes)
|
||||
}
|
||||
|
||||
func TestCountDownloads(t *testing.T) {
|
||||
dl := safariDownloads{
|
||||
DownloadHistory: []safariDownloadEntry{
|
||||
{URL: "https://a.com/1.zip", Path: "/tmp/1.zip", TotalBytes: 100, ProfileUUID: defaultProfileSentinel},
|
||||
{URL: "https://b.com/2.zip", Path: "/tmp/2.zip", TotalBytes: 200, ProfileUUID: defaultProfileSentinel},
|
||||
{URL: "https://c.com/3.zip", Path: "/tmp/3.zip", TotalBytes: 300, ProfileUUID: defaultProfileSentinel},
|
||||
},
|
||||
}
|
||||
|
||||
path := buildTestDownloadsPlist(t, dl)
|
||||
count, err := countDownloads(path, defaultProfileSentinel)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, count)
|
||||
}
|
||||
|
||||
func TestExtractDownloads_Empty(t *testing.T) {
|
||||
dl := safariDownloads{}
|
||||
path := buildTestDownloadsPlist(t, dl)
|
||||
|
||||
downloads, err := extractDownloads(path, defaultProfileSentinel)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, downloads)
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
)
|
||||
|
||||
// Safari keeps extensions in two sibling plists under the container's Safari dir:
|
||||
//
|
||||
// Safari/AppExtensions/Extensions.plist — legacy App Extensions (XPC-based)
|
||||
// Safari/WebExtensions/Extensions.plist — modern Safari Web Extensions
|
||||
//
|
||||
// Both files share the same top-level shape: a dictionary keyed by
|
||||
// "<bundleID> (<teamID>)". Only WebExtensions carry an `Enabled` field;
|
||||
// an App Extension that appears in the plist is implicitly enabled.
|
||||
const (
|
||||
safariExtensionsSubdir = "Safari"
|
||||
safariAppExtensionsSubdir = "AppExtensions"
|
||||
safariWebExtensionsSubdir = "WebExtensions"
|
||||
safariExtensionsPlistFile = "Extensions.plist"
|
||||
)
|
||||
|
||||
// extensionKeyPattern matches the "<bundleID> (<teamID>)" key format Safari uses.
|
||||
var extensionKeyPattern = regexp.MustCompile(`^(\S+)\s+\(([^)]+)\)$`)
|
||||
|
||||
// safariExtension mirrors the per-extension dict value in Extensions.plist.
|
||||
// Only fields that map onto record.Extension are decoded; richer fields
|
||||
// (Permissions, AccessibleOrigins, …) are intentionally ignored for the
|
||||
// minimum implementation.
|
||||
type safariExtension struct {
|
||||
Enabled *bool `plist:"Enabled"`
|
||||
}
|
||||
|
||||
// extractExtensions reads both AppExtensions/Extensions.plist and
|
||||
// WebExtensions/Extensions.plist from the profile's Safari container and
|
||||
// returns the merged list, sorted by key for deterministic output.
|
||||
// A missing plist on either side is skipped silently.
|
||||
func extractExtensions(container string) ([]record.Extension, error) {
|
||||
records, err := readSafariExtensions(container)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
extensions := make([]record.Extension, 0, len(records))
|
||||
for _, r := range records {
|
||||
extensions = append(extensions, record.Extension{
|
||||
Name: r.bundleID,
|
||||
ID: r.key,
|
||||
Enabled: r.enabled,
|
||||
})
|
||||
}
|
||||
return extensions, nil
|
||||
}
|
||||
|
||||
func countExtensions(container string) (int, error) {
|
||||
records, err := readSafariExtensions(container)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(records), nil
|
||||
}
|
||||
|
||||
type extensionRecord struct {
|
||||
key string
|
||||
bundleID string
|
||||
enabled bool
|
||||
}
|
||||
|
||||
func readSafariExtensions(container string) ([]extensionRecord, error) {
|
||||
safariDir := filepath.Join(container, safariExtensionsSubdir)
|
||||
var all []extensionRecord
|
||||
for _, sub := range []string{safariAppExtensionsSubdir, safariWebExtensionsSubdir} {
|
||||
p := filepath.Join(safariDir, sub, safariExtensionsPlistFile)
|
||||
records, err := decodeSafariExtensionsPlist(p)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, records...)
|
||||
}
|
||||
sort.Slice(all, func(i, j int) bool { return all[i].key < all[j].key })
|
||||
return all, nil
|
||||
}
|
||||
|
||||
func decodeSafariExtensionsPlist(path string) ([]extensionRecord, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var decoded map[string]safariExtension
|
||||
if err := plist.NewDecoder(f).Decode(&decoded); err != nil {
|
||||
return nil, fmt.Errorf("decode extensions %s: %w", path, err)
|
||||
}
|
||||
|
||||
records := make([]extensionRecord, 0, len(decoded))
|
||||
for key, ext := range decoded {
|
||||
enabled := true
|
||||
if ext.Enabled != nil {
|
||||
enabled = *ext.Enabled
|
||||
}
|
||||
records = append(records, extensionRecord{
|
||||
key: key,
|
||||
bundleID: bundleIDFromExtensionKey(key),
|
||||
enabled: enabled,
|
||||
})
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// bundleIDFromExtensionKey extracts the bundle ID from a "<bundleID> (<teamID>)"
|
||||
// key; falls back to the trimmed full key when the format doesn't match.
|
||||
func bundleIDFromExtensionKey(key string) string {
|
||||
if m := extensionKeyPattern.FindStringSubmatch(key); m != nil {
|
||||
return m[1]
|
||||
}
|
||||
return strings.TrimSpace(key)
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testExtensionEntry mirrors the shape of one entry in Safari's Extensions.plist:
|
||||
// an untyped dictionary keyed by string. Using a map (instead of safariExtension)
|
||||
// lets tests omit keys like Enabled for AppExtension-style fixtures, matching
|
||||
// what Safari actually writes.
|
||||
type testExtensionEntry map[string]any
|
||||
|
||||
// writeTestExtensionsPlist writes an Extensions.plist under
|
||||
// <container>/Safari/<subdir>/Extensions.plist. subdir is either
|
||||
// "AppExtensions" or "WebExtensions".
|
||||
func writeTestExtensionsPlist(t *testing.T, container, subdir string, entries map[string]testExtensionEntry) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(container, safariExtensionsSubdir, subdir)
|
||||
require.NoError(t, os.MkdirAll(dir, 0o755))
|
||||
|
||||
f, err := os.Create(filepath.Join(dir, safariExtensionsPlistFile))
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
require.NoError(t, plist.NewBinaryEncoder(f).Encode(entries))
|
||||
}
|
||||
|
||||
func TestExtractExtensions_AppAndWebMerged(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.colliderli.iina.OpenInIINA (67CQ77V27R)": {},
|
||||
})
|
||||
writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.1password.safari.extension (2BUA8C4S2C)": {"Enabled": true},
|
||||
})
|
||||
|
||||
got, err := extractExtensions(container)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
|
||||
// Results are sorted by key, so 1Password (com.1…) comes before iina (com.c…).
|
||||
assert.Equal(t, "com.1password.safari.extension", got[0].Name)
|
||||
assert.Equal(t, "com.1password.safari.extension (2BUA8C4S2C)", got[0].ID)
|
||||
assert.True(t, got[0].Enabled)
|
||||
|
||||
assert.Equal(t, "com.colliderli.iina.OpenInIINA", got[1].Name)
|
||||
assert.Equal(t, "com.colliderli.iina.OpenInIINA (67CQ77V27R)", got[1].ID)
|
||||
// AppExtensions omit the Enabled field — defaults to true (present == enabled).
|
||||
assert.True(t, got[1].Enabled)
|
||||
}
|
||||
|
||||
func TestExtractExtensions_EnabledFlag(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.example.a (AAAAAAAAAA)": {"Enabled": true},
|
||||
"com.example.b (BBBBBBBBBB)": {"Enabled": false},
|
||||
})
|
||||
|
||||
got, err := extractExtensions(container)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
assert.True(t, got[0].Enabled)
|
||||
assert.False(t, got[1].Enabled)
|
||||
}
|
||||
|
||||
func TestExtractExtensions_BundleIDFallbackOnUnexpectedKey(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"legacy-key-without-team-id": {},
|
||||
})
|
||||
|
||||
got, err := extractExtensions(container)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
// Regex miss → fall back to the full trimmed key.
|
||||
assert.Equal(t, "legacy-key-without-team-id", got[0].Name)
|
||||
assert.Equal(t, "legacy-key-without-team-id", got[0].ID)
|
||||
}
|
||||
|
||||
func TestExtractExtensions_OnlyAppExt(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.example.only (XXXXXXXXX1)": {},
|
||||
})
|
||||
|
||||
got, err := extractExtensions(container)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "com.example.only", got[0].Name)
|
||||
}
|
||||
|
||||
func TestExtractExtensions_OnlyWebExt(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.example.web (XXXXXXXXX2)": {"Enabled": true},
|
||||
})
|
||||
|
||||
got, err := extractExtensions(container)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "com.example.web", got[0].Name)
|
||||
}
|
||||
|
||||
func TestExtractExtensions_NoPlists(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
got, err := extractExtensions(container)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestCountExtensions(t *testing.T) {
|
||||
container := t.TempDir()
|
||||
writeTestExtensionsPlist(t, container, safariAppExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.example.a (AAAAAAAAAA)": {},
|
||||
"com.example.b (BBBBBBBBBB)": {},
|
||||
})
|
||||
writeTestExtensionsPlist(t, container, safariWebExtensionsSubdir, map[string]testExtensionEntry{
|
||||
"com.example.c (CCCCCCCCCC)": {"Enabled": true},
|
||||
})
|
||||
|
||||
count, err := countExtensions(container)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, count)
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/sqlitex"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/timeconv"
|
||||
)
|
||||
|
||||
const (
|
||||
// safariHistoryQuery joins each history item to its latest visit so
|
||||
// title and visit_time come from the same history_visits row.
|
||||
safariHistoryQuery = `SELECT hi.url, COALESCE(hv.title, ''), hi.visit_count,
|
||||
COALESCE(hv.visit_time, 0)
|
||||
FROM history_items hi
|
||||
LEFT JOIN history_visits hv ON hv.id = (
|
||||
SELECT hv2.id FROM history_visits hv2
|
||||
WHERE hv2.history_item = hi.id
|
||||
ORDER BY hv2.visit_time DESC LIMIT 1
|
||||
)`
|
||||
|
||||
safariCountHistoryQuery = `SELECT COUNT(*) FROM history_items`
|
||||
)
|
||||
|
||||
func extractHistories(path string) ([]record.History, error) {
|
||||
histories, err := sqlitex.QueryRows(path, true, safariHistoryQuery,
|
||||
func(rows *sql.Rows) (record.History, error) {
|
||||
var (
|
||||
url, title string
|
||||
visitCount int
|
||||
visitTime float64
|
||||
)
|
||||
if err := rows.Scan(&url, &title, &visitCount, &visitTime); err != nil {
|
||||
return record.History{}, err
|
||||
}
|
||||
return record.History{
|
||||
URL: url,
|
||||
Title: title,
|
||||
VisitCount: visitCount,
|
||||
LastVisit: timeconv.CoreData(visitTime),
|
||||
}, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return histories, nil
|
||||
}
|
||||
|
||||
func countHistories(path string) (int, error) {
|
||||
return sqlitex.CountRows(path, true, safariCountHistoryQuery)
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func setupSafariHistoryDB(t *testing.T) string {
|
||||
t.Helper()
|
||||
return createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://github.com", "github.com", 100),
|
||||
insertHistoryItem(2, "https://go.dev", "go.dev", 50),
|
||||
insertHistoryItem(3, "https://example.com", "example.com", 200),
|
||||
// Item 1 has two visits — extractHistories must deduplicate.
|
||||
insertHistoryVisit(1, 1, 704067600.0, "GitHub"),
|
||||
insertHistoryVisit(2, 1, 705067600.0, "GitHub - Latest"),
|
||||
insertHistoryVisit(3, 2, 703067600.0, "The Go Programming Language"),
|
||||
insertHistoryVisit(4, 3, 700067600.0, "Example Domain"),
|
||||
)
|
||||
}
|
||||
|
||||
func TestExtractHistories(t *testing.T) {
|
||||
path := setupSafariHistoryDB(t)
|
||||
|
||||
got, err := extractHistories(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 3)
|
||||
|
||||
// Rows keep the database's order; the exporter sorts them.
|
||||
assert.Equal(t, 100, got[0].VisitCount)
|
||||
assert.Equal(t, 50, got[1].VisitCount)
|
||||
assert.Equal(t, 200, got[2].VisitCount)
|
||||
|
||||
// Verify field mapping.
|
||||
assert.Equal(t, "https://github.com", got[0].URL)
|
||||
assert.Equal(t, "https://go.dev", got[1].URL)
|
||||
assert.Equal(t, "https://example.com", got[2].URL)
|
||||
assert.False(t, got[2].LastVisit.IsZero())
|
||||
}
|
||||
|
||||
func TestExtractHistories_Dedup(t *testing.T) {
|
||||
path := setupSafariHistoryDB(t)
|
||||
|
||||
got, err := extractHistories(path)
|
||||
require.NoError(t, err)
|
||||
// 3 history_items, not 4 visits.
|
||||
require.Len(t, got, 3)
|
||||
|
||||
// GitHub (item 1) should have the later visit_time and its title.
|
||||
for _, h := range got {
|
||||
if h.URL == "https://github.com" {
|
||||
// 705067600 + 978307200 = 1683374800 (unix)
|
||||
assert.Equal(t, int64(1683374800), h.LastVisit.Unix())
|
||||
// Title must come from the latest visit row, not an arbitrary one.
|
||||
assert.Equal(t, "GitHub - Latest", h.Title)
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("expected https://github.com in results")
|
||||
}
|
||||
|
||||
func TestCountHistories(t *testing.T) {
|
||||
path := setupSafariHistoryDB(t)
|
||||
|
||||
count, err := countHistories(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, count)
|
||||
}
|
||||
|
||||
func TestCountHistories_Empty(t *testing.T) {
|
||||
path := createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema})
|
||||
|
||||
count, err := countHistories(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
func TestExtractHistories_NullTitle(t *testing.T) {
|
||||
path := createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://null.test", "null.test", 1),
|
||||
// Visit with NULL title — COALESCE should return empty string.
|
||||
`INSERT INTO history_visits (id, history_item, visit_time) VALUES (1, 1, 700000000.0)`,
|
||||
)
|
||||
|
||||
got, err := extractHistories(path)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "https://null.test", got[0].URL)
|
||||
assert.Empty(t, got[0].Title)
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/moond4rk/keychainbreaker"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
)
|
||||
|
||||
func extractPasswords(keychainPassword string) ([]record.Login, error) {
|
||||
passwords, err := getInternetPasswords(keychainPassword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var logins []record.Login
|
||||
for _, p := range passwords {
|
||||
url := buildURL(p.Protocol, p.Server, p.Port, p.Path)
|
||||
if url == "" || p.Account == "" {
|
||||
continue
|
||||
}
|
||||
logins = append(logins, record.Login{
|
||||
URL: url,
|
||||
Username: p.Account,
|
||||
Password: p.PlainPassword,
|
||||
CreatedAt: p.Created.UTC(),
|
||||
Store: record.StoreLocal,
|
||||
})
|
||||
}
|
||||
return logins, nil
|
||||
}
|
||||
|
||||
func countPasswords(keychainPassword string) (int, error) {
|
||||
passwords, err := extractPasswords(keychainPassword)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(passwords), nil
|
||||
}
|
||||
|
||||
// getInternetPasswords reads InternetPassword records straight from the macOS login keychain (Safari owns its own key
|
||||
// path, separate from the masterkey package). TryUnlock always runs — even without a password — so a locked keychain
|
||||
// still yields metadata-only records (URL, account, blank password) instead of failing with ErrLocked.
|
||||
func getInternetPasswords(keychainPassword string) ([]keychainbreaker.InternetPassword, error) {
|
||||
kc, err := keychainbreaker.Open()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open keychain: %w", err)
|
||||
}
|
||||
|
||||
var unlockOpts []keychainbreaker.UnlockOption
|
||||
if keychainPassword != "" {
|
||||
unlockOpts = append(unlockOpts, keychainbreaker.WithPassword(keychainPassword))
|
||||
}
|
||||
if err := kc.TryUnlock(unlockOpts...); err != nil {
|
||||
log.Debugf("keychain unlock detail: %v", err)
|
||||
}
|
||||
|
||||
passwords, err := kc.InternetPasswords()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract internet passwords: %w", err)
|
||||
}
|
||||
return passwords, nil
|
||||
}
|
||||
|
||||
// buildURL constructs a URL from InternetPassword fields.
|
||||
func buildURL(protocol, server string, port uint32, path string) string {
|
||||
if server == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// macOS Keychain stores the protocol as a FourCC code; only "htps" needs remapping, others just trim padding.
|
||||
scheme := strings.TrimRight(protocol, " ")
|
||||
if scheme == "" || scheme == "htps" {
|
||||
scheme = "https"
|
||||
}
|
||||
|
||||
url := scheme + "://" + server
|
||||
|
||||
defaultPorts := map[string]uint32{"https": 443, "http": 80, "ftp": 21}
|
||||
if port > 0 && port != defaultPorts[scheme] {
|
||||
url += fmt.Sprintf(":%d", port)
|
||||
}
|
||||
|
||||
if path != "" && path != "/" {
|
||||
url += path
|
||||
}
|
||||
return url
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestBuildURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
protocol string
|
||||
server string
|
||||
port uint32
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "https default port",
|
||||
protocol: "htps",
|
||||
server: "github.com",
|
||||
port: 443,
|
||||
want: "https://github.com",
|
||||
},
|
||||
{
|
||||
name: "https custom port",
|
||||
protocol: "htps",
|
||||
server: "example.com",
|
||||
port: 8443,
|
||||
want: "https://example.com:8443",
|
||||
},
|
||||
{
|
||||
name: "http with path",
|
||||
protocol: "http",
|
||||
server: "192.168.1.1",
|
||||
port: 80,
|
||||
path: "/admin",
|
||||
want: "http://192.168.1.1/admin",
|
||||
},
|
||||
{
|
||||
name: "http non-default port",
|
||||
protocol: "http",
|
||||
server: "localhost",
|
||||
port: 8080,
|
||||
want: "http://localhost:8080",
|
||||
},
|
||||
{
|
||||
name: "empty server returns empty",
|
||||
protocol: "htps",
|
||||
server: "",
|
||||
port: 443,
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "empty protocol defaults to https",
|
||||
protocol: "",
|
||||
server: "example.com",
|
||||
port: 0,
|
||||
want: "https://example.com",
|
||||
},
|
||||
{
|
||||
name: "smb protocol",
|
||||
protocol: "smb ",
|
||||
server: "fileserver",
|
||||
port: 445,
|
||||
want: "smb://fileserver:445",
|
||||
},
|
||||
{
|
||||
name: "ftp default port",
|
||||
protocol: "ftp ",
|
||||
server: "ftp.example.com",
|
||||
port: 21,
|
||||
want: "ftp://ftp.example.com",
|
||||
},
|
||||
{
|
||||
name: "root path ignored",
|
||||
protocol: "htps",
|
||||
server: "example.com",
|
||||
port: 443,
|
||||
path: "/",
|
||||
want: "https://example.com",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := buildURL(tt.protocol, tt.server, tt.port, tt.path)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,344 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unicode/utf16"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
)
|
||||
|
||||
// Modern WebKit (Safari 17+) stores localStorage under a nested, partitioned layout rooted at
|
||||
// either WebsiteDataStore/<uuid>/Origins (per named profile) or WebsiteData/Default
|
||||
// (the pre-profile default store). Within that root:
|
||||
//
|
||||
// <root>/<top-frame-hash>/<frame-hash>/origin — binary; encodes top+frame origins
|
||||
// <root>/<top-frame-hash>/<frame-hash>/LocalStorage/localstorage.sqlite3
|
||||
//
|
||||
// top-hash == frame-hash ⇒ first-party; they differ for third-party partitioned storage.
|
||||
// We report the frame origin because that's what window.localStorage exposes to JS.
|
||||
// ItemTable: (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL);
|
||||
// value BLOBs are UTF-16 LE strings.
|
||||
//
|
||||
// The flat "LocalStorage/<scheme>_<host>_<port>.localstorage" directory that older builds used
|
||||
// is empty on current Safari and is no longer a supported source.
|
||||
|
||||
const (
|
||||
webkitOriginFile = "origin"
|
||||
webkitLocalStorageSubdir = "LocalStorage"
|
||||
webkitLocalStorageDB = "localstorage.sqlite3"
|
||||
webkitOriginSaltName = "salt" // HMAC salt sibling of the <hash> dirs; not a data dir
|
||||
|
||||
maxLocalStorageValueLength = 2048
|
||||
)
|
||||
|
||||
// origin file encoding-byte constants (WebCore SecurityOrigin serialization).
|
||||
const (
|
||||
originEncASCII = 0x01 // Latin-1 / ASCII
|
||||
originEncUTF16 = 0x00 // UTF-16 LE
|
||||
)
|
||||
|
||||
// Port marker values after the (scheme, host) pair in an origin block.
|
||||
// 0x00 → port is the scheme default (stored as 0).
|
||||
// 0x01 → next two bytes are a uint16_le port.
|
||||
const (
|
||||
originPortDefaultMarker = 0x00
|
||||
originPortExplicitFlag = 0x01
|
||||
)
|
||||
|
||||
func extractLocalStorage(root string) ([]record.LocalStorage, error) {
|
||||
dirs, err := findOriginDataDirs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var entries []record.LocalStorage
|
||||
for _, od := range dirs {
|
||||
origin, err := readOriginFile(filepath.Join(od, webkitOriginFile))
|
||||
if err != nil {
|
||||
log.Debugf("safari localstorage: origin %s: %v", od, err)
|
||||
continue
|
||||
}
|
||||
dbPath := filepath.Join(od, webkitLocalStorageSubdir, webkitLocalStorageDB)
|
||||
items, err := readLocalStorageFile(dbPath)
|
||||
if err != nil {
|
||||
log.Debugf("safari localstorage: db %s: %v", dbPath, err)
|
||||
continue
|
||||
}
|
||||
for _, it := range items {
|
||||
entries = append(entries, record.LocalStorage{
|
||||
URL: origin,
|
||||
Key: it.key,
|
||||
Value: it.value,
|
||||
})
|
||||
}
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// countLocalStorage sums ItemTable row counts across every origin DB under root without
|
||||
// parsing origin files or decoding values — CountEntries callers only need the total, not the
|
||||
// URLs or plaintext. COUNT(key) naturally excludes NULL keys, matching the same skip rule
|
||||
// applied by readLocalStorageFile, so count and extract stay in sync.
|
||||
func countLocalStorage(root string) (int, error) {
|
||||
dirs, err := findOriginDataDirs(root)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total := 0
|
||||
for _, od := range dirs {
|
||||
dbPath := filepath.Join(od, webkitLocalStorageSubdir, webkitLocalStorageDB)
|
||||
n, err := countLocalStorageFile(dbPath)
|
||||
if err != nil {
|
||||
log.Debugf("safari localstorage: count %s: %v", dbPath, err)
|
||||
continue
|
||||
}
|
||||
total += n
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func countLocalStorageFile(path string) (int, error) {
|
||||
// mode=ro (no immutable) so SQLite replays the copied -wal sidecar — this surfaces entries
|
||||
// Safari has committed to WAL but not yet checkpointed to the main DB. Writes SQLite might
|
||||
// make to the temp-copy's -shm during replay are harmless; the Session cleanup removes
|
||||
// everything. Live-file reads (profiles.go) still use immutable=1 to stay off the real WAL.
|
||||
dsn := "file:" + path + "?mode=ro"
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("open %s: %w", path, err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.Ping(); err != nil {
|
||||
return 0, fmt.Errorf("ping %s: %w", path, err)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(`SELECT COUNT(key) FROM ItemTable`).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("count ItemTable: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// findOriginDataDirs returns <root>/<h1>/<h2>/ paths that contain both an "origin" file and
|
||||
// a "LocalStorage/localstorage.sqlite3" database. Non-directory entries, the "salt" sibling,
|
||||
// and partition dirs without localStorage data are silently skipped.
|
||||
func findOriginDataDirs(root string) ([]string, error) {
|
||||
topEntries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read origins root %s: %w", root, err)
|
||||
}
|
||||
var out []string
|
||||
for _, top := range topEntries {
|
||||
if !top.IsDir() || top.Name() == webkitOriginSaltName {
|
||||
continue
|
||||
}
|
||||
topPath := filepath.Join(root, top.Name())
|
||||
frameEntries, err := os.ReadDir(topPath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, frame := range frameEntries {
|
||||
if !frame.IsDir() {
|
||||
continue
|
||||
}
|
||||
framePath := filepath.Join(topPath, frame.Name())
|
||||
if _, err := os.Stat(filepath.Join(framePath, webkitOriginFile)); err != nil {
|
||||
continue
|
||||
}
|
||||
dbPath := filepath.Join(framePath, webkitLocalStorageSubdir, webkitLocalStorageDB)
|
||||
if _, err := os.Stat(dbPath); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, framePath)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// originEndpoint is one half of an origin file (top-frame or frame). Port 0 means the scheme
|
||||
// default (443 for https, 80 for http) and is omitted from the URL rendering.
|
||||
type originEndpoint struct {
|
||||
scheme string
|
||||
host string
|
||||
port uint16
|
||||
}
|
||||
|
||||
// readOriginFile parses WebKit's SecurityOrigin binary serialization and returns the frame
|
||||
// origin URL (scheme://host[:port]). The file holds two origin blocks back-to-back: top-frame
|
||||
// then frame. When the frame block is missing/unreadable we fall back to the top-frame so we
|
||||
// can still attribute the data to *something* meaningful.
|
||||
func readOriginFile(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read origin file %s: %w", path, err)
|
||||
}
|
||||
top, pos, terr := readOriginBlock(data, 0)
|
||||
if terr != nil {
|
||||
return "", fmt.Errorf("parse top-frame origin: %w", terr)
|
||||
}
|
||||
frame, _, ferr := readOriginBlock(data, pos)
|
||||
if ferr != nil {
|
||||
// Partitioned info unavailable — attribute to the top-frame origin.
|
||||
frame = top
|
||||
}
|
||||
if frame.scheme == "" || frame.host == "" {
|
||||
return "", fmt.Errorf("origin file missing scheme/host")
|
||||
}
|
||||
return formatOriginURL(frame), nil
|
||||
}
|
||||
|
||||
// readOriginBlock reads one origin block: scheme record, host record, port marker.
|
||||
// Returns the parsed endpoint and the byte offset immediately after the block.
|
||||
func readOriginBlock(data []byte, pos int) (originEndpoint, int, error) {
|
||||
var ep originEndpoint
|
||||
var err error
|
||||
ep.scheme, pos, err = readOriginString(data, pos)
|
||||
if err != nil {
|
||||
return ep, pos, err
|
||||
}
|
||||
ep.host, pos, err = readOriginString(data, pos)
|
||||
if err != nil {
|
||||
return ep, pos, err
|
||||
}
|
||||
if pos >= len(data) {
|
||||
return ep, pos, fmt.Errorf("unexpected EOF before port marker")
|
||||
}
|
||||
marker := data[pos]
|
||||
pos++
|
||||
switch marker {
|
||||
case originPortDefaultMarker:
|
||||
ep.port = 0
|
||||
case originPortExplicitFlag:
|
||||
if pos+2 > len(data) {
|
||||
return ep, pos, fmt.Errorf("truncated port value at offset %d", pos)
|
||||
}
|
||||
ep.port = binary.LittleEndian.Uint16(data[pos : pos+2])
|
||||
pos += 2
|
||||
default:
|
||||
return ep, pos, fmt.Errorf("unexpected port marker 0x%02x at offset %d", marker, pos-1)
|
||||
}
|
||||
return ep, pos, nil
|
||||
}
|
||||
|
||||
// readOriginString consumes one length-prefixed record (uint32_le length + encoding byte + data).
|
||||
func readOriginString(data []byte, pos int) (string, int, error) {
|
||||
if pos+5 > len(data) {
|
||||
return "", pos, fmt.Errorf("truncated string record at offset %d", pos)
|
||||
}
|
||||
length := int(binary.LittleEndian.Uint32(data[pos : pos+4]))
|
||||
enc := data[pos+4]
|
||||
pos += 5
|
||||
if length < 0 || pos+length > len(data) {
|
||||
return "", pos, fmt.Errorf("string record overruns buffer: length %d at offset %d", length, pos-5)
|
||||
}
|
||||
chunk := data[pos : pos+length]
|
||||
pos += length
|
||||
switch enc {
|
||||
case originEncASCII:
|
||||
return decodeLatin1(chunk), pos, nil
|
||||
case originEncUTF16:
|
||||
return decodeUTF16LE(chunk), pos, nil
|
||||
default:
|
||||
return decodeLatin1(chunk), pos, nil
|
||||
}
|
||||
}
|
||||
|
||||
// decodeLatin1 converts ISO-8859-1 bytes to a valid UTF-8 Go string. Latin-1 byte values map
|
||||
// 1:1 to Unicode code points U+0000–U+00FF. Mirrors the helper in chromium/extract_storage.go.
|
||||
func decodeLatin1(b []byte) string {
|
||||
runes := make([]rune, len(b))
|
||||
for i, c := range b {
|
||||
runes[i] = rune(c)
|
||||
}
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
func formatOriginURL(ep originEndpoint) string {
|
||||
url := ep.scheme + "://" + ep.host
|
||||
if ep.port != 0 {
|
||||
url += fmt.Sprintf(":%d", ep.port)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
type localStorageItem struct {
|
||||
key string
|
||||
value string
|
||||
}
|
||||
|
||||
func readLocalStorageFile(path string) ([]localStorageItem, error) {
|
||||
// mode=ro (no immutable) — see countLocalStorageFile for the WAL-replay rationale; the same
|
||||
// live-vs-temp split applies here. ORDER BY key, rowid makes exports byte-for-byte stable
|
||||
// across runs and SQLite versions.
|
||||
dsn := "file:" + path + "?mode=ro"
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", path, err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.Ping(); err != nil {
|
||||
return nil, fmt.Errorf("ping %s: %w", path, err)
|
||||
}
|
||||
|
||||
rows, err := db.Query(`SELECT key, value FROM ItemTable ORDER BY key, rowid`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query ItemTable: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []localStorageItem
|
||||
for rows.Next() {
|
||||
var key sql.NullString
|
||||
var value []byte
|
||||
if err := rows.Scan(&key, &value); err != nil {
|
||||
log.Debugf("safari localstorage: scan row in %s: %v", path, err)
|
||||
continue
|
||||
}
|
||||
if !key.Valid {
|
||||
// NULL keys would collide with legitimate empty-string keys in the output and are
|
||||
// not meaningful localStorage entries. The UNIQUE constraint in ItemTable still
|
||||
// permits multiple NULL rows in SQLite, so we filter them here.
|
||||
log.Debugf("safari localstorage: skip row with NULL key in %s", path)
|
||||
continue
|
||||
}
|
||||
items = append(items, localStorageItem{
|
||||
key: key.String,
|
||||
value: decodeLocalStorageValue(value),
|
||||
})
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
// decodeLocalStorageValue treats the BLOB as UTF-16 LE. Values at or above the cap are replaced
|
||||
// with a size marker to keep JSON/CSV output bounded, matching chromium/extract_storage.go.
|
||||
func decodeLocalStorageValue(b []byte) string {
|
||||
if len(b) >= maxLocalStorageValueLength {
|
||||
return fmt.Sprintf(
|
||||
"value is too long, length is %d, supported max length is %d",
|
||||
len(b), maxLocalStorageValueLength,
|
||||
)
|
||||
}
|
||||
return decodeUTF16LE(b)
|
||||
}
|
||||
|
||||
// decodeUTF16LE returns the input as a Go string on odd-length (malformed) inputs; WebKit values
|
||||
// are always even-length in practice but we don't want a stray byte to drop a whole row.
|
||||
func decodeUTF16LE(b []byte) string {
|
||||
if len(b) == 0 {
|
||||
return ""
|
||||
}
|
||||
if len(b)%2 != 0 {
|
||||
return string(b)
|
||||
}
|
||||
u16 := make([]uint16, len(b)/2)
|
||||
for i := range u16 {
|
||||
u16[i] = binary.LittleEndian.Uint16(b[i*2:])
|
||||
}
|
||||
return string(utf16.Decode(u16))
|
||||
}
|
||||
@@ -1,335 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// readOriginBlock / readOriginFile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestReadOriginBlock_FirstParty(t *testing.T) {
|
||||
data := encodeOriginFile("https://example.com", "https://example.com")
|
||||
top, pos, err := readOriginBlock(data, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https", top.scheme)
|
||||
assert.Equal(t, "example.com", top.host)
|
||||
assert.Equal(t, uint16(0), top.port, "port 0 ⇒ scheme default")
|
||||
|
||||
frame, _, err := readOriginBlock(data, pos)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://example.com", formatOriginURL(frame))
|
||||
}
|
||||
|
||||
func TestReadOriginBlock_NonDefaultPort(t *testing.T) {
|
||||
data := encodeOriginFile("https://example.com:8443", "https://example.com:8443")
|
||||
top, _, err := readOriginBlock(data, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, uint16(8443), top.port)
|
||||
assert.Equal(t, "https://example.com:8443", formatOriginURL(top))
|
||||
}
|
||||
|
||||
func TestReadOriginBlock_Latin1HighByte(t *testing.T) {
|
||||
// WebKit stores scheme/host records with encoding byte 0x01 = Latin-1. Verify high-byte
|
||||
// bytes decode as Latin-1 (é = 0xE9) rather than being passed through as invalid UTF-8.
|
||||
data := []byte{
|
||||
0x04, 0x00, 0x00, 0x00, 0x01, 'h', 't', 't', 'p', // scheme "http"
|
||||
0x04, 0x00, 0x00, 0x00, 0x01, 'c', 'a', 'f', 0xe9, // host "café" (Latin-1)
|
||||
0x00, // port default
|
||||
}
|
||||
ep, _, err := readOriginBlock(data, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "http", ep.scheme)
|
||||
assert.Equal(t, "café", ep.host)
|
||||
}
|
||||
|
||||
func TestDecodeLatin1(t *testing.T) {
|
||||
assert.Equal(t, "café", decodeLatin1([]byte{'c', 'a', 'f', 0xe9}))
|
||||
assert.Equal(t, "hello", decodeLatin1([]byte("hello")))
|
||||
assert.Empty(t, decodeLatin1(nil))
|
||||
}
|
||||
|
||||
func TestReadOriginFile_FramePreferred(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
originPath := filepath.Join(dir, "origin")
|
||||
require.NoError(t, os.WriteFile(originPath,
|
||||
encodeOriginFile("https://top.example.com", "https://iframe.example.com"), 0o644))
|
||||
|
||||
got, err := readOriginFile(originPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://iframe.example.com", got)
|
||||
}
|
||||
|
||||
func TestReadOriginFile_FallbackToTop(t *testing.T) {
|
||||
// Write only the top-frame block — no frame follows. Extractor should still succeed by
|
||||
// falling back to the top-frame origin.
|
||||
var buf []byte
|
||||
buf = appendOriginBlock(buf, "https://example.com")
|
||||
originPath := filepath.Join(t.TempDir(), "origin")
|
||||
require.NoError(t, os.WriteFile(originPath, buf, 0o644))
|
||||
|
||||
got, err := readOriginFile(originPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://example.com", got)
|
||||
}
|
||||
|
||||
func TestReadOriginFile_Malformed(t *testing.T) {
|
||||
originPath := filepath.Join(t.TempDir(), "origin")
|
||||
require.NoError(t, os.WriteFile(originPath, []byte{0x01, 0x02}, 0o644))
|
||||
|
||||
_, err := readOriginFile(originPath)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// decodeUTF16LE / decodeLocalStorageValue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDecodeUTF16LE(t *testing.T) {
|
||||
t.Run("ascii", func(t *testing.T) {
|
||||
assert.Equal(t, "hello", decodeUTF16LE(encodeUTF16LE("hello")))
|
||||
})
|
||||
t.Run("cjk", func(t *testing.T) {
|
||||
assert.Equal(t, "你好世界", decodeUTF16LE(encodeUTF16LE("你好世界")))
|
||||
})
|
||||
t.Run("mixed", func(t *testing.T) {
|
||||
assert.Equal(t, "hello 世界 🌍", decodeUTF16LE(encodeUTF16LE("hello 世界 🌍")))
|
||||
})
|
||||
t.Run("empty", func(t *testing.T) {
|
||||
assert.Empty(t, decodeUTF16LE(nil))
|
||||
assert.Empty(t, decodeUTF16LE([]byte{}))
|
||||
})
|
||||
t.Run("odd length falls back to raw string", func(t *testing.T) {
|
||||
assert.Equal(t, "abc", decodeUTF16LE([]byte("abc")))
|
||||
})
|
||||
}
|
||||
|
||||
func TestDecodeLocalStorageValue_Truncates(t *testing.T) {
|
||||
// 1100 chars × 2 bytes = 2200 bytes, over the 2048 cap.
|
||||
oversized := encodeUTF16LE(strings.Repeat("x", 1100))
|
||||
got := decodeLocalStorageValue(oversized)
|
||||
assert.Contains(t, got, "too long")
|
||||
assert.Contains(t, got, "2048")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// extractLocalStorage — end-to-end over real nested layout fixtures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestExtractLocalStorage_SingleOrigin(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://example.com": {{Key: "auth_token", Value: "abc123"}},
|
||||
})
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Equal(t, "https://example.com", entries[0].URL)
|
||||
assert.Equal(t, "auth_token", entries[0].Key)
|
||||
assert.Equal(t, "abc123", entries[0].Value)
|
||||
assert.False(t, entries[0].IsMeta)
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_MultiOrigin(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://github.com": {
|
||||
{Key: "theme", Value: "dark"},
|
||||
{Key: "lang", Value: "en"},
|
||||
},
|
||||
"https://example.com:8443": {
|
||||
{Key: "session", Value: "xyz"},
|
||||
},
|
||||
})
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 3)
|
||||
|
||||
byURL := make(map[string][]string)
|
||||
for _, e := range entries {
|
||||
byURL[e.URL] = append(byURL[e.URL], e.Key+"="+e.Value)
|
||||
}
|
||||
assert.ElementsMatch(t, []string{"theme=dark", "lang=en"}, byURL["https://github.com"])
|
||||
assert.ElementsMatch(t, []string{"session=xyz"}, byURL["https://example.com:8443"])
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_CJKAndEmoji(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://example.com": {
|
||||
{Key: "名字", Value: "张三"},
|
||||
{Key: "status", Value: "hello 世界 🌍"},
|
||||
},
|
||||
})
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 2)
|
||||
|
||||
values := make(map[string]string)
|
||||
for _, e := range entries {
|
||||
values[e.Key] = e.Value
|
||||
}
|
||||
assert.Equal(t, "张三", values["名字"])
|
||||
assert.Equal(t, "hello 世界 🌍", values["status"])
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_EmptyItemTable(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://example.com": nil,
|
||||
})
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, entries)
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_TruncatesOversizedValue(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://example.com": {{Key: "big", Value: strings.Repeat("x", 1100)}},
|
||||
})
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Contains(t, entries[0].Value, "too long")
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_Partitioned(t *testing.T) {
|
||||
// Manually construct a partitioned third-party entry: YouTube iframe inside Google top-frame.
|
||||
root := filepath.Join(t.TempDir(), "Origins")
|
||||
require.NoError(t, os.MkdirAll(root, 0o755))
|
||||
writeTestOriginStore(t, root, "topHash", "frameHash",
|
||||
"https://accounts.google.com", "https://accounts.youtube.com",
|
||||
[]testLocalStorageItem{{Key: "yt-session", Value: "embedded"}},
|
||||
)
|
||||
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Equal(t, "https://accounts.youtube.com", entries[0].URL, "frame origin preferred over top-frame")
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_SkipsSaltAndStrayFiles(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://example.com": {{Key: "a", Value: "1"}},
|
||||
})
|
||||
// Drop a "salt" sibling that must not be traversed, plus a stray file at root.
|
||||
require.NoError(t, os.WriteFile(filepath.Join(root, "salt"), []byte("pretend salt"), 0o644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(root, "README"), []byte("noise"), 0o644))
|
||||
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Equal(t, "https://example.com", entries[0].URL)
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_SkipsFrameDirsWithoutDB(t *testing.T) {
|
||||
// Partition dirs that only have "origin" but no LocalStorage/ subdir must not error out —
|
||||
// real Safari has plenty of these (cookies-only partitions).
|
||||
root := filepath.Join(t.TempDir(), "Origins")
|
||||
frameDir := filepath.Join(root, "topHash", "frameHash")
|
||||
require.NoError(t, os.MkdirAll(frameDir, 0o755))
|
||||
require.NoError(t, os.WriteFile(
|
||||
filepath.Join(frameDir, "origin"),
|
||||
encodeOriginFile("https://example.com", "https://example.com"), 0o644))
|
||||
|
||||
entries, err := extractLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, entries)
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_DirMissing(t *testing.T) {
|
||||
_, err := extractLocalStorage(filepath.Join(t.TempDir(), "does-not-exist"))
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestExtractLocalStorage_EmptyRoot(t *testing.T) {
|
||||
entries, err := extractLocalStorage(t.TempDir())
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, entries)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// countLocalStorage
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestCountLocalStorage(t *testing.T) {
|
||||
root := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://a.com": {{Key: "k1", Value: "v1"}, {Key: "k2", Value: "v2"}},
|
||||
"https://b.com": {{Key: "k3", Value: "v3"}},
|
||||
"https://c.com:8443": {{Key: "k4", Value: "v4"}},
|
||||
})
|
||||
count, err := countLocalStorage(root)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 4, count)
|
||||
}
|
||||
|
||||
func TestCountLocalStorage_DirMissing(t *testing.T) {
|
||||
count, err := countLocalStorage(filepath.Join(t.TempDir(), "nope"))
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NULL-key handling — readLocalStorageFile / countLocalStorageFile both skip NULL keys,
|
||||
// keeping count and extract in sync.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestReadLocalStorageFile_SkipsNullKey(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "ls.sqlite3")
|
||||
writeLocalStorageDB(t, dbPath, []testLocalStorageItem{
|
||||
{Key: "real", Value: "keeper"},
|
||||
}, true /*addNullKey*/)
|
||||
|
||||
items, err := readLocalStorageFile(dbPath)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
assert.Equal(t, "real", items[0].key)
|
||||
assert.Equal(t, "keeper", items[0].value)
|
||||
}
|
||||
|
||||
func TestCountLocalStorageFile_SkipsNullKey(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "ls.sqlite3")
|
||||
writeLocalStorageDB(t, dbPath, []testLocalStorageItem{
|
||||
{Key: "k1", Value: "v1"},
|
||||
{Key: "k2", Value: "v2"},
|
||||
}, true /*addNullKey*/)
|
||||
|
||||
count, err := countLocalStorageFile(dbPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, count, "NULL keys are excluded from count to match extract's skip rule")
|
||||
}
|
||||
|
||||
func TestReadLocalStorageFile_ReturnsRowsInKeyOrder(t *testing.T) {
|
||||
// Rows are inserted in reverse alphabetical order; ORDER BY key, rowid in the extractor
|
||||
// query must surface them ascending so exports are deterministic across runs.
|
||||
dbPath := filepath.Join(t.TempDir(), "ls.sqlite3")
|
||||
writeLocalStorageDB(t, dbPath, []testLocalStorageItem{
|
||||
{Key: "zebra", Value: "z"},
|
||||
{Key: "mango", Value: "m"},
|
||||
{Key: "apple", Value: "a"},
|
||||
}, false /*addNullKey*/)
|
||||
|
||||
items, err := readLocalStorageFile(dbPath)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 3)
|
||||
assert.Equal(t, "apple", items[0].key)
|
||||
assert.Equal(t, "mango", items[1].key)
|
||||
assert.Equal(t, "zebra", items[2].key)
|
||||
}
|
||||
|
||||
func TestCountLocalStorageFile_MissingTable(t *testing.T) {
|
||||
// Real Safari has origin dirs with LocalStorage/localstorage.sqlite3 but no ItemTable yet
|
||||
// (seen during live verification). countLocalStorageFile must surface the error so the
|
||||
// caller can log-and-skip rather than counting 0 silently.
|
||||
dbPath := filepath.Join(t.TempDir(), "empty.sqlite3")
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
_, err = countLocalStorageFile(dbPath)
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/moond4rk/keychainbreaker"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
)
|
||||
|
||||
// passwordKeychain is today's direct read of the login keychain, handed to the Safari base until the switch-over
|
||||
// gives every reader the run's one handle.
|
||||
type passwordKeychain string
|
||||
|
||||
func (pw passwordKeychain) InternetPasswords(context.Context) ([]keychainbreaker.InternetPassword, error) {
|
||||
return getInternetPasswords(string(pw))
|
||||
}
|
||||
|
||||
// getInternetPasswords reads InternetPassword records straight from the macOS login keychain (Safari owns its own key
|
||||
// path, separate from the masterkey package). TryUnlock always runs — even without a password — so a locked keychain
|
||||
// still yields metadata-only records (URL, account, blank password) instead of failing with ErrLocked.
|
||||
func getInternetPasswords(keychainPassword string) ([]keychainbreaker.InternetPassword, error) {
|
||||
kc, err := keychainbreaker.Open()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open keychain: %w", err)
|
||||
}
|
||||
|
||||
var unlockOpts []keychainbreaker.UnlockOption
|
||||
if keychainPassword != "" {
|
||||
unlockOpts = append(unlockOpts, keychainbreaker.WithPassword(keychainPassword))
|
||||
}
|
||||
if err := kc.TryUnlock(unlockOpts...); err != nil {
|
||||
log.Debugf("keychain unlock detail: %v", err)
|
||||
}
|
||||
|
||||
passwords, err := kc.InternetPasswords()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract internet passwords: %w", err)
|
||||
}
|
||||
return passwords, nil
|
||||
}
|
||||
+147
-87
@@ -1,14 +1,24 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/filemanager"
|
||||
ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
isafari "github.com/moond4rk/hackbrowserdata/internal/browser/safari"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
"github.com/moond4rk/hackbrowserdata/types"
|
||||
)
|
||||
|
||||
// snapshotDirID names the one user data dir in a profile's private snapshot, whose root is ~/Library.
|
||||
const snapshotDirID = "library"
|
||||
|
||||
// profile is one Safari profile — the leaf extraction unit. Passwords come from
|
||||
// the shared macOS Keychain; everything else reads from the profile's directories.
|
||||
type profile struct {
|
||||
@@ -27,75 +37,160 @@ func (p *profile) dir() string {
|
||||
return filepath.Join(p.ctx.container, "Safari", "Profiles", p.ctx.uuidUpper)
|
||||
}
|
||||
|
||||
func (p *profile) extract(categories []category.Category, keychainPassword string) *types.BrowserData {
|
||||
session, err := filemanager.NewSession()
|
||||
if err != nil {
|
||||
log.Debugf("new session for %s: %v", p.label(), err)
|
||||
return &types.BrowserData{}
|
||||
// asBase is this profile as the Safari base sees it: ~/Library as the user data dir, the Safari directory as the
|
||||
// default profile's Dir, and a named profile's own directory under the container as its Dir.
|
||||
func (p *profile) asBase() (ibrowser.UserDataDir, ibrowser.Profile) {
|
||||
library := filepath.Dir(p.ctx.legacyHome)
|
||||
def := ibrowser.Profile{Name: "default", Dir: filepath.Base(p.ctx.legacyHome)}
|
||||
prof := def
|
||||
if !p.ctx.isDefault() {
|
||||
prof = ibrowser.Profile{Name: p.ctx.name, Dir: "Containers/com.apple.Safari/Data/Library/Safari/Profiles/" + p.ctx.uuidUpper}
|
||||
}
|
||||
defer session.Cleanup()
|
||||
|
||||
tempPaths := p.acquireFiles(session, categories)
|
||||
return ibrowser.UserDataDir{Path: library, Profiles: []ibrowser.Profile{def, prof}}, prof
|
||||
}
|
||||
|
||||
// extract captures the profile's files into a private snapshot of ~/Library and runs the Safari base's extractors on
|
||||
// it; passwords keep today's direct keychain read until the switch-over.
|
||||
func (p *profile) extract(categories []category.Category, keychainPassword string) *types.BrowserData {
|
||||
data := &types.BrowserData{}
|
||||
d, err := snapshot.Temp()
|
||||
if err != nil {
|
||||
log.Debugf("new snapshot for %s: %v", p.label(), err)
|
||||
return data
|
||||
}
|
||||
defer func() {
|
||||
if err := d.Close(); err != nil {
|
||||
log.Debugf("remove snapshot for %s: %v", p.label(), err)
|
||||
}
|
||||
}()
|
||||
|
||||
dir, prof := p.asBase()
|
||||
extractors := isafari.Extractors(dir, prof, passwordKeychain(keychainPassword))
|
||||
ctx := context.Background()
|
||||
if err := d.Capture(ctx, snapshotFiles(dir.Path, prof, extractors, categories)); err != nil {
|
||||
log.Debugf("capture %s: %v", p.label(), err)
|
||||
return data
|
||||
}
|
||||
ps := ibrowser.NewProfileSnapshot(d.Snapshot(snapshotDirID), prof, nil)
|
||||
out := &dataCollector{data: data, label: p.label()}
|
||||
for _, cat := range categories {
|
||||
// Keychain is user-scope, not per-profile — attribute only to default to avoid duplicates.
|
||||
if cat == category.Password {
|
||||
if p.ctx.isDefault() {
|
||||
p.extractCategory(data, cat, "", keychainPassword)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Extension plists (AppExtensions + WebExtensions) live directly in the container
|
||||
// and are read in-place; attribute to default only until per-profile layouts are verified.
|
||||
if cat == category.Extension {
|
||||
if p.ctx.isDefault() {
|
||||
p.extractCategory(data, cat, "", keychainPassword)
|
||||
}
|
||||
continue
|
||||
}
|
||||
path, ok := tempPaths[cat]
|
||||
ex, ok := extractors[cat]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
p.extractCategory(data, cat, path, keychainPassword)
|
||||
if err := ex.Extract(ctx, ps, out); err != nil {
|
||||
log.Debugf("extract %s for %s: %v", cat, p.label(), err)
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// snapshotFiles lists, once each, the first candidate on disk of every source the categories read.
|
||||
func snapshotFiles(library string, prof ibrowser.Profile, extractors ibrowser.Extractors, categories []category.Category) []snapshot.File {
|
||||
var files []snapshot.File
|
||||
seen := make(map[string]bool)
|
||||
for _, cat := range categories {
|
||||
for _, src := range extractors[cat].Sources {
|
||||
rel, ok := firstOnDisk(library, prof, src)
|
||||
if !ok || seen[rel] {
|
||||
continue
|
||||
}
|
||||
seen[rel] = true
|
||||
files = append(files, snapshot.File{DirID: snapshotDirID, From: library, Rel: rel, IsDir: src.IsDir})
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func firstOnDisk(library string, prof ibrowser.Profile, src ibrowser.Source) (string, bool) {
|
||||
for _, rel := range src.Paths {
|
||||
rel = path.Join(prof.Dir, rel)
|
||||
info, err := os.Stat(filepath.Join(library, filepath.FromSlash(rel)))
|
||||
if err == nil && info.IsDir() == src.IsDir {
|
||||
return rel, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// dataCollector files the records the Safari base hands back into today's per-category slices.
|
||||
type dataCollector struct {
|
||||
data *types.BrowserData
|
||||
label string
|
||||
}
|
||||
|
||||
func (c *dataCollector) Add(r record.Record) {
|
||||
switch v := r.(type) {
|
||||
case *record.Login:
|
||||
c.data.Passwords = append(c.data.Passwords, *v)
|
||||
case *record.Cookie:
|
||||
c.data.Cookies = append(c.data.Cookies, *v)
|
||||
case *record.Bookmark:
|
||||
c.data.Bookmarks = append(c.data.Bookmarks, *v)
|
||||
case *record.History:
|
||||
c.data.Histories = append(c.data.Histories, *v)
|
||||
case *record.Download:
|
||||
c.data.Downloads = append(c.data.Downloads, *v)
|
||||
case *record.Extension:
|
||||
c.data.Extensions = append(c.data.Extensions, *v)
|
||||
case *record.LocalStorage:
|
||||
c.data.LocalStorage = append(c.data.LocalStorage, *v)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dataCollector) Fail(err error) { log.Debugf("%s: %v", c.label, err) }
|
||||
|
||||
// count keeps today's counting queries for history and localStorage. Safari's other counters always counted what
|
||||
// extraction parses, so they count the base's records.
|
||||
func (p *profile) count(categories []category.Category, keychainPassword string) map[category.Category]int {
|
||||
counts := make(map[category.Category]int)
|
||||
var parsed, queried []category.Category
|
||||
for _, cat := range categories {
|
||||
if cat == category.History || cat == category.LocalStorage {
|
||||
queried = append(queried, cat)
|
||||
} else {
|
||||
parsed = append(parsed, cat)
|
||||
}
|
||||
}
|
||||
if len(parsed) > 0 {
|
||||
data := p.extract(parsed, keychainPassword)
|
||||
for _, cat := range parsed {
|
||||
counts[cat] = recordCount(data, cat)
|
||||
}
|
||||
}
|
||||
if len(queried) == 0 {
|
||||
return counts
|
||||
}
|
||||
|
||||
session, err := filemanager.NewSession()
|
||||
if err != nil {
|
||||
log.Debugf("new session for %s: %v", p.label(), err)
|
||||
return nil
|
||||
return counts
|
||||
}
|
||||
defer session.Cleanup()
|
||||
|
||||
tempPaths := p.acquireFiles(session, categories)
|
||||
|
||||
counts := make(map[category.Category]int)
|
||||
for _, cat := range categories {
|
||||
if cat == category.Password {
|
||||
if p.ctx.isDefault() {
|
||||
counts[cat] = p.countCategory(cat, "", keychainPassword)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if cat == category.Extension {
|
||||
if p.ctx.isDefault() {
|
||||
counts[cat] = p.countCategory(cat, "", keychainPassword)
|
||||
}
|
||||
continue
|
||||
}
|
||||
path, ok := tempPaths[cat]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
counts[cat] = p.countCategory(cat, path, keychainPassword)
|
||||
for cat, file := range p.acquireFiles(session, queried) {
|
||||
counts[cat] = p.countCategory(cat, file)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
func recordCount(data *types.BrowserData, cat category.Category) int {
|
||||
switch cat {
|
||||
case category.Password:
|
||||
return len(data.Passwords)
|
||||
case category.Cookie:
|
||||
return len(data.Cookies)
|
||||
case category.Bookmark:
|
||||
return len(data.Bookmarks)
|
||||
case category.Download:
|
||||
return len(data.Downloads)
|
||||
case category.Extension:
|
||||
return len(data.Extensions)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func (p *profile) acquireFiles(session *filemanager.Session, categories []category.Category) map[category.Category]string {
|
||||
tempPaths := make(map[category.Category]string)
|
||||
for _, cat := range categories {
|
||||
@@ -113,51 +208,16 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []catego
|
||||
return tempPaths
|
||||
}
|
||||
|
||||
func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, path, keychainPassword string) {
|
||||
var err error
|
||||
switch cat {
|
||||
case category.Password:
|
||||
data.Passwords, err = extractPasswords(keychainPassword)
|
||||
case category.History:
|
||||
data.Histories, err = extractHistories(path)
|
||||
case category.Cookie:
|
||||
data.Cookies, err = extractCookies(path)
|
||||
case category.Bookmark:
|
||||
data.Bookmarks, err = extractBookmarks(path)
|
||||
case category.Download:
|
||||
data.Downloads, err = extractDownloads(path, p.ctx.downloadOwnerUUID())
|
||||
case category.LocalStorage:
|
||||
data.LocalStorage, err = extractLocalStorage(path)
|
||||
case category.Extension:
|
||||
data.Extensions, err = extractExtensions(p.ctx.container)
|
||||
default:
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Debugf("extract %s for %s: %v", cat, p.label(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *profile) countCategory(cat category.Category, path, keychainPassword string) int {
|
||||
func (p *profile) countCategory(cat category.Category, file string) int {
|
||||
var count int
|
||||
var err error
|
||||
switch cat {
|
||||
case category.Password:
|
||||
count, err = countPasswords(keychainPassword)
|
||||
case category.History:
|
||||
count, err = countHistories(path)
|
||||
case category.Cookie:
|
||||
count, err = countCookies(path)
|
||||
case category.Bookmark:
|
||||
count, err = countBookmarks(path)
|
||||
case category.Download:
|
||||
count, err = countDownloads(path, p.ctx.downloadOwnerUUID())
|
||||
count, err = countHistories(file)
|
||||
case category.LocalStorage:
|
||||
count, err = countLocalStorage(path)
|
||||
case category.Extension:
|
||||
count, err = countExtensions(p.ctx.container)
|
||||
count, err = countLocalStorage(file)
|
||||
default:
|
||||
// Unsupported categories silently return 0.
|
||||
// The other categories are counted from their extracted records.
|
||||
}
|
||||
if err != nil {
|
||||
log.Debugf("count %s for %s: %v", cat, p.label(), err)
|
||||
|
||||
+99
-131
@@ -1,8 +1,11 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
@@ -10,147 +13,112 @@ import (
|
||||
"github.com/moond4rk/hackbrowserdata/types"
|
||||
)
|
||||
|
||||
func TestCountCategory(t *testing.T) {
|
||||
t.Run("History", func(t *testing.T) {
|
||||
path := createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://example.com", "example.com", 1),
|
||||
)
|
||||
p := &profile{}
|
||||
assert.Equal(t, 1, p.countCategory(category.History, path, ""))
|
||||
})
|
||||
const fixtureWorkUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
|
||||
t.Run("Cookie", func(t *testing.T) {
|
||||
path := buildTestBinaryCookies(t, []testCookie{
|
||||
{domain: ".example.com", name: "a", path: "/", value: "1", expires: 2000000000.0, creation: 700000000.0},
|
||||
{domain: ".go.dev", name: "b", path: "/", value: "2", expires: 2000000000.0, creation: 700000000.0},
|
||||
})
|
||||
p := &profile{}
|
||||
assert.Equal(t, 2, p.countCategory(category.Cookie, path, ""))
|
||||
})
|
||||
|
||||
t.Run("Bookmark", func(t *testing.T) {
|
||||
path := buildTestBookmarksPlist(t, safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://a.com", URIDictionary: uriDictionary{Title: "A"}},
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://b.com", URIDictionary: uriDictionary{Title: "B"}},
|
||||
},
|
||||
})
|
||||
p := &profile{}
|
||||
assert.Equal(t, 2, p.countCategory(category.Bookmark, path, ""))
|
||||
})
|
||||
|
||||
t.Run("Download", func(t *testing.T) {
|
||||
path := buildTestDownloadsPlist(t, safariDownloads{
|
||||
DownloadHistory: []safariDownloadEntry{
|
||||
{URL: "https://example.com/file.zip", Path: "/tmp/file.zip", TotalBytes: 100},
|
||||
},
|
||||
})
|
||||
p := &profile{}
|
||||
assert.Equal(t, 1, p.countCategory(category.Download, path, ""))
|
||||
})
|
||||
|
||||
t.Run("LocalStorage", func(t *testing.T) {
|
||||
dir := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://example.com": {{Key: "k1", Value: "v1"}, {Key: "k2", Value: "v2"}},
|
||||
"https://go.dev": {{Key: "theme", Value: "dark"}},
|
||||
})
|
||||
p := &profile{}
|
||||
assert.Equal(t, 3, p.countCategory(category.LocalStorage, dir, ""))
|
||||
})
|
||||
|
||||
t.Run("UnsupportedCategory", func(t *testing.T) {
|
||||
p := &profile{}
|
||||
assert.Equal(t, 0, p.countCategory(category.CreditCard, "unused", ""))
|
||||
assert.Equal(t, 0, p.countCategory(category.SessionStorage, "unused", ""))
|
||||
})
|
||||
func writePlist(t *testing.T, path string, v any) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
|
||||
f, err := os.Create(path)
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
require.NoError(t, plist.NewBinaryEncoder(f).Encode(v))
|
||||
}
|
||||
|
||||
func TestExtractCategory(t *testing.T) {
|
||||
t.Run("History", func(t *testing.T) {
|
||||
path := createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://example.com", "example.com", 3),
|
||||
insertHistoryItem(2, "https://go.dev", "go.dev", 1),
|
||||
insertHistoryVisit(1, 1, 700000000.0, "Example"),
|
||||
insertHistoryVisit(2, 2, 700000000.0, "Go"),
|
||||
)
|
||||
p := &profile{}
|
||||
data := &types.BrowserData{}
|
||||
p.extractCategory(data, category.History, path, "")
|
||||
func installDB(t *testing.T, dst, src string) {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(src)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(dst), 0o755))
|
||||
require.NoError(t, os.WriteFile(dst, data, 0o644))
|
||||
}
|
||||
|
||||
require.Len(t, data.Histories, 2)
|
||||
assert.ElementsMatch(t, []int{3, 1}, []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount})
|
||||
})
|
||||
|
||||
t.Run("Cookie", func(t *testing.T) {
|
||||
path := buildTestBinaryCookies(t, []testCookie{
|
||||
{
|
||||
domain: ".example.com", name: "session", path: "/", value: "abc",
|
||||
secure: true, httpOnly: true, expires: 2000000000.0, creation: 700000000.0,
|
||||
},
|
||||
})
|
||||
p := &profile{}
|
||||
data := &types.BrowserData{}
|
||||
p.extractCategory(data, category.Cookie, path, "")
|
||||
// libraryFixture is a ~/Library with a default and a named profile: bookmarks belong to the default one only, and the
|
||||
// shared Downloads.plist holds one entry for each.
|
||||
func libraryFixture(t *testing.T) string {
|
||||
t.Helper()
|
||||
library := t.TempDir()
|
||||
legacyHome := filepath.Join(library, "Safari")
|
||||
container := filepath.Join(library, "Containers", "com.apple.Safari", "Data", "Library")
|
||||
|
||||
require.Len(t, data.Cookies, 1)
|
||||
assert.Equal(t, ".example.com", data.Cookies[0].Host)
|
||||
assert.Equal(t, "session", data.Cookies[0].Name)
|
||||
assert.True(t, data.Cookies[0].IsSecure)
|
||||
assert.True(t, data.Cookies[0].IsHTTPOnly)
|
||||
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: fixtureWorkUUID, title: "work"}})
|
||||
installDB(t, filepath.Join(legacyHome, "History.db"), createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://home.test/a", "home.test", 3),
|
||||
insertHistoryItem(2, "https://home.test/b", "home.test", 1),
|
||||
))
|
||||
installDB(t, filepath.Join(container, "Safari", "Profiles", fixtureWorkUUID, "History.db"), createTestDB(t, "History.db",
|
||||
[]string{safariHistoryItemsSchema, safariHistoryVisitsSchema},
|
||||
insertHistoryItem(1, "https://work.test/", "work.test", 5),
|
||||
))
|
||||
writePlist(t, filepath.Join(legacyHome, "Bookmarks.plist"), map[string]any{
|
||||
"WebBookmarkType": "WebBookmarkTypeList",
|
||||
"Children": []any{map[string]any{
|
||||
"WebBookmarkType": "WebBookmarkTypeList",
|
||||
"Title": "BookmarksBar",
|
||||
"Children": []any{map[string]any{
|
||||
"WebBookmarkType": "WebBookmarkTypeLeaf",
|
||||
"URLString": "https://go.dev/",
|
||||
"URIDictionary": map[string]any{"title": "Go"},
|
||||
}},
|
||||
}},
|
||||
})
|
||||
|
||||
t.Run("Bookmark", func(t *testing.T) {
|
||||
path := buildTestBookmarksPlist(t, safariBookmark{
|
||||
Type: bookmarkTypeList,
|
||||
Children: []safariBookmark{
|
||||
{Type: bookmarkTypeLeaf, URLString: "https://github.com", URIDictionary: uriDictionary{Title: "GitHub"}},
|
||||
},
|
||||
})
|
||||
p := &profile{}
|
||||
data := &types.BrowserData{}
|
||||
p.extractCategory(data, category.Bookmark, path, "")
|
||||
|
||||
require.Len(t, data.Bookmarks, 1)
|
||||
assert.Equal(t, "GitHub", data.Bookmarks[0].Name)
|
||||
assert.Equal(t, "https://github.com", data.Bookmarks[0].URL)
|
||||
writePlist(t, filepath.Join(legacyHome, "Downloads.plist"), map[string]any{
|
||||
"DownloadHistory": []any{
|
||||
map[string]any{"DownloadEntryURL": "https://home.test/a.zip", "DownloadEntryPath": "/tmp/a.zip", "DownloadEntryProfileUUIDStringKey": "DefaultProfile"},
|
||||
map[string]any{"DownloadEntryURL": "https://work.test/b.zip", "DownloadEntryPath": "/tmp/b.zip", "DownloadEntryProfileUUIDStringKey": fixtureWorkUUID},
|
||||
},
|
||||
})
|
||||
return legacyHome
|
||||
}
|
||||
|
||||
t.Run("Download", func(t *testing.T) {
|
||||
path := buildTestDownloadsPlist(t, safariDownloads{
|
||||
DownloadHistory: []safariDownloadEntry{
|
||||
{URL: "https://example.com/file.zip", Path: "/tmp/file.zip", TotalBytes: 1024},
|
||||
},
|
||||
})
|
||||
p := &profile{}
|
||||
data := &types.BrowserData{}
|
||||
p.extractCategory(data, category.Download, path, "")
|
||||
func fixtureBrowser(t *testing.T) *Browser {
|
||||
t.Helper()
|
||||
b, err := NewBrowser(types.BrowserConfig{Name: "Safari", Kind: types.Safari, UserDataDir: libraryFixture(t)})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, b)
|
||||
return b
|
||||
}
|
||||
|
||||
require.Len(t, data.Downloads, 1)
|
||||
assert.Equal(t, "https://example.com/file.zip", data.Downloads[0].URL)
|
||||
assert.Equal(t, int64(1024), data.Downloads[0].TotalBytes)
|
||||
})
|
||||
// Password is left out: it would read this machine's login keychain.
|
||||
var adapterCategories = []category.Category{category.History, category.Bookmark, category.Download, category.Cookie, category.Extension}
|
||||
|
||||
t.Run("LocalStorage", func(t *testing.T) {
|
||||
dir := buildTestLocalStorageDir(t, map[string][]testLocalStorageItem{
|
||||
"https://github.com": {{Key: "theme", Value: "dark"}},
|
||||
})
|
||||
p := &profile{}
|
||||
data := &types.BrowserData{}
|
||||
p.extractCategory(data, category.LocalStorage, dir, "")
|
||||
func TestExtract_RunsTheBaseOnEachProfile(t *testing.T) {
|
||||
results, err := fixtureBrowser(t).Extract(adapterCategories)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 2)
|
||||
|
||||
require.Len(t, data.LocalStorage, 1)
|
||||
assert.Equal(t, "https://github.com", data.LocalStorage[0].URL)
|
||||
assert.Equal(t, "theme", data.LocalStorage[0].Key)
|
||||
assert.Equal(t, "dark", data.LocalStorage[0].Value)
|
||||
})
|
||||
byName := map[string]*types.BrowserData{}
|
||||
for _, r := range results {
|
||||
byName[r.Name] = r.Data
|
||||
}
|
||||
require.Contains(t, byName, "default")
|
||||
require.Contains(t, byName, "work")
|
||||
assert.Len(t, byName["default"].Histories, 2)
|
||||
assert.Len(t, byName["default"].Bookmarks, 1)
|
||||
require.Len(t, byName["default"].Downloads, 1)
|
||||
assert.Equal(t, "https://home.test/a.zip", byName["default"].Downloads[0].URL)
|
||||
assert.Len(t, byName["work"].Histories, 1)
|
||||
assert.Empty(t, byName["work"].Bookmarks, "Bookmarks.plist belongs to the default profile")
|
||||
require.Len(t, byName["work"].Downloads, 1)
|
||||
assert.Equal(t, "https://work.test/b.zip", byName["work"].Downloads[0].URL)
|
||||
}
|
||||
|
||||
t.Run("UnsupportedCategory", func(t *testing.T) {
|
||||
p := &profile{}
|
||||
data := &types.BrowserData{}
|
||||
p.extractCategory(data, category.CreditCard, "unused", "")
|
||||
assert.Empty(t, data.CreditCards)
|
||||
})
|
||||
func TestCountEntries_MatchesExtract(t *testing.T) {
|
||||
results, err := fixtureBrowser(t).CountEntries(adapterCategories)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 2)
|
||||
for _, r := range results {
|
||||
switch r.Name {
|
||||
case "default":
|
||||
assert.Equal(t, 2, r.Counts[category.History])
|
||||
assert.Equal(t, 1, r.Counts[category.Bookmark])
|
||||
assert.Equal(t, 1, r.Counts[category.Download])
|
||||
case "work":
|
||||
assert.Equal(t, 1, r.Counts[category.History])
|
||||
assert.Equal(t, 0, r.Counts[category.Bookmark])
|
||||
assert.Equal(t, 1, r.Counts[category.Download])
|
||||
default:
|
||||
t.Fatalf("unexpected profile %q", r.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,16 +25,6 @@ type profileContext struct {
|
||||
|
||||
func (p profileContext) isDefault() bool { return p.uuidUpper == "" }
|
||||
|
||||
// downloadOwnerUUID is the value Safari writes into DownloadEntryProfileUUIDStringKey
|
||||
// for downloads that belong to this profile. The default profile uses the sentinel
|
||||
// "DefaultProfile"; named profiles use their uppercase UUID.
|
||||
func (p profileContext) downloadOwnerUUID() string {
|
||||
if p.isDefault() {
|
||||
return defaultProfileSentinel
|
||||
}
|
||||
return p.uuidUpper
|
||||
}
|
||||
|
||||
// SafariTabs.db lists profiles in bookmarks rows with subtype=2. external_uuid "DefaultProfile"
|
||||
// is the sentinel for the implicit default, which has no per-UUID directory.
|
||||
const (
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
package safari
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
)
|
||||
|
||||
// containerPaths returns (legacyHome, container) for a fake ~/Library tree
|
||||
// anchored at root. Call sites use this to mirror the production layout where
|
||||
// legacyHome sits next to Containers/.
|
||||
func containerPaths(root string) (string, string) {
|
||||
legacyHome := filepath.Join(root, "Safari")
|
||||
container := filepath.Join(root, "Containers", "com.apple.Safari", "Data", "Library")
|
||||
return legacyHome, container
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_DefaultOnly(t *testing.T) {
|
||||
library := t.TempDir()
|
||||
legacyHome, _ := containerPaths(library)
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
assert.Empty(t, got[0].uuidUpper)
|
||||
assert.Empty(t, got[0].uuidLower)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_WithNamedProfile(t *testing.T) {
|
||||
const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
mkFile(t, container, "Safari", "Profiles", uuid, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{
|
||||
{uuid: "DefaultProfile", title: ""},
|
||||
{uuid: uuid, title: "work"},
|
||||
})
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
assert.Equal(t, "work", got[1].name)
|
||||
assert.Equal(t, uuid, got[1].uuidUpper)
|
||||
assert.Equal(t, strings.ToLower(uuid), got[1].uuidLower)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_EmptyTitleFallbackToUUID(t *testing.T) {
|
||||
const uuid = "ABCDEF01-2345-6789-ABCD-EF0123456789"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{
|
||||
{uuid: uuid, title: ""},
|
||||
})
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "profile-abcdef01", got[1].name)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_OrphanUUIDWithoutDBEntry(t *testing.T) {
|
||||
// Profile directory with a History.db exists on disk but is absent from
|
||||
// SafariTabs.db. When the DB is readable and doesn't mention it, we trust
|
||||
// the DB — the orphan stays hidden because production filters profiles
|
||||
// with no resolvable data in NewBrowser anyway. Here we assert discovery
|
||||
// returns only what the DB declares.
|
||||
const dbUUID = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"
|
||||
const orphanUUID = "11111111-2222-3333-4444-555555555555"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
mkFile(t, container, "Safari", "Profiles", dbUUID, "History.db")
|
||||
mkFile(t, container, "Safari", "Profiles", orphanUUID, "AppExtensions", "Extensions.plist")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{
|
||||
{uuid: dbUUID, title: "declared"},
|
||||
})
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
assert.Equal(t, "declared", got[1].name)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_EmptyDBIsAuthoritative(t *testing.T) {
|
||||
// SafariTabs.db exists and is readable but contains no named-profile rows.
|
||||
// A stray Profiles/<UUID>/ directory on disk must NOT sneak in via the
|
||||
// ReadDir fallback — the DB is the authoritative source of truth.
|
||||
const strayUUID = "99999999-AAAA-BBBB-CCCC-DDDDDDDDDDDD"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
mkFile(t, container, "Safari", "Profiles", strayUUID, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), nil) // zero rows
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_MissingDBFallsBackToReadDir(t *testing.T) {
|
||||
// SafariTabs.db absent → enumerate Safari/Profiles/ and synthesize names.
|
||||
const uuid = "11111111-2222-3333-4444-555555555555"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
mkFile(t, container, "Safari", "Profiles", uuid, "History.db")
|
||||
// Deliberately also drop a non-UUID directory that must be ignored.
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(container, "Safari", "Profiles", "Bogus"), 0o755))
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
assert.Equal(t, "profile-11111111", got[1].name)
|
||||
assert.Equal(t, uuid, got[1].uuidUpper)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_DuplicateTitlesDisambiguate(t *testing.T) {
|
||||
const uuidA = "AAAAAAAA-0000-0000-0000-000000000001"
|
||||
const uuidB = "BBBBBBBB-0000-0000-0000-000000000002"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{
|
||||
{uuid: uuidA, title: "team"},
|
||||
{uuid: uuidB, title: "team"},
|
||||
})
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 3)
|
||||
// Order mirrors DB insertion order; the second "team" becomes "team-2".
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
assert.Equal(t, "team", got[1].name)
|
||||
assert.Equal(t, "team-2", got[2].name)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_UUIDCaseNormalisation(t *testing.T) {
|
||||
// SafariTabs.db always stores UUIDs uppercase (verified on real Mac).
|
||||
// WebKit/WebsiteDataStore uses lowercase — we must carry both.
|
||||
const uuid = "FEDCBA98-7654-3210-FEDC-BA9876543210"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{
|
||||
{uuid: uuid, title: "alpha"},
|
||||
})
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, uuid, got[1].uuidUpper)
|
||||
assert.Equal(t, strings.ToLower(uuid), got[1].uuidLower)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_DefaultProfileSentinelIgnored(t *testing.T) {
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, safariTabsDBRelPath), []tabRow{
|
||||
{uuid: defaultProfileSentinel, title: ""},
|
||||
})
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "default", got[0].name)
|
||||
}
|
||||
|
||||
func TestDiscoverSafariProfiles_EmptyProfileDirectoryFiltersOutInNewBrowsers(t *testing.T) {
|
||||
// Matches the real 4E2D8DD0 orphan on the author's Mac: a profile dir
|
||||
// listed in neither SafariTabs.db nor containing any extractable data.
|
||||
// Discovery without the DB surfaces it; NewBrowser then drops it when
|
||||
// resolveSourcePaths yields zero matches.
|
||||
const uuid = "4E2D8DD0-A7D2-4684-939A-898B7675C700"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
mkFile(t, legacyHome, "History.db")
|
||||
mkFile(t, container, "Safari", "Profiles", uuid, "AppExtensions", "Extensions.plist")
|
||||
|
||||
got := discoverSafariProfiles(legacyHome)
|
||||
require.Len(t, got, 2) // discovery includes it …
|
||||
paths := resolveSourcePaths(buildSources(got[1]))
|
||||
assert.Empty(t, paths) // … but no supported data resolves for it.
|
||||
}
|
||||
|
||||
func TestResolveProfileName(t *testing.T) {
|
||||
tests := []struct {
|
||||
title string
|
||||
uuid string
|
||||
want string
|
||||
}{
|
||||
{"work", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "work"},
|
||||
{" spaced ", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "spaced"},
|
||||
{"", "5604E6F5-02ED-4E40-8249-63DE7BC986C8", "profile-5604e6f5"},
|
||||
{"with/slash", "AAAAAAAA-0000-0000-0000-000000000000", "with_slash"},
|
||||
{"中文", "AAAAAAAA-0000-0000-0000-000000000000", "中文"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.title, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, resolveProfileName(tt.title, tt.uuid))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSources_DefaultProfile(t *testing.T) {
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
p := profileContext{legacyHome: legacyHome, container: container}
|
||||
sources := buildSources(p)
|
||||
|
||||
assert.Equal(t, filepath.Join(legacyHome, "History.db"), sources[category.History][0].abs)
|
||||
assert.Equal(t, filepath.Join(legacyHome, "Bookmarks.plist"), sources[category.Bookmark][0].abs)
|
||||
assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[category.Download][0].abs)
|
||||
require.Len(t, sources[category.Cookie], 2)
|
||||
assert.Equal(t, filepath.Join(container, "Cookies", "Cookies.binarycookies"), sources[category.Cookie][0].abs)
|
||||
assert.Equal(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), sources[category.Cookie][1].abs)
|
||||
}
|
||||
|
||||
func TestBuildSources_NamedProfile(t *testing.T) {
|
||||
const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
library := t.TempDir()
|
||||
legacyHome, container := containerPaths(library)
|
||||
|
||||
p := profileContext{
|
||||
name: "work",
|
||||
uuidUpper: uuid,
|
||||
uuidLower: strings.ToLower(uuid),
|
||||
legacyHome: legacyHome,
|
||||
container: container,
|
||||
}
|
||||
sources := buildSources(p)
|
||||
|
||||
assert.Equal(t,
|
||||
filepath.Join(container, "Safari", "Profiles", uuid, "History.db"),
|
||||
sources[category.History][0].abs)
|
||||
assert.Equal(t,
|
||||
filepath.Join(container, "WebKit", "WebsiteDataStore", strings.ToLower(uuid), "Cookies", "Cookies.binarycookies"),
|
||||
sources[category.Cookie][0].abs)
|
||||
// Download points at the shared plist — filtering by DownloadEntryProfileUUIDStringKey
|
||||
// happens inside extractDownloads, not at the path layer.
|
||||
assert.Equal(t, filepath.Join(legacyHome, "Downloads.plist"), sources[category.Download][0].abs)
|
||||
// Bookmark is still shared with no per-entry profile tag, so it's attributed to default only.
|
||||
assert.NotContains(t, sources, category.Bookmark)
|
||||
}
|
||||
@@ -6,8 +6,6 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf16"
|
||||
|
||||
@@ -159,11 +157,7 @@ func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, fra
|
||||
frameDir := filepath.Join(root, topHash, frameHash)
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(frameDir, webkitLocalStorageSubdir), 0o755))
|
||||
|
||||
require.NoError(t, os.WriteFile(
|
||||
filepath.Join(frameDir, webkitOriginFile),
|
||||
encodeOriginFile(topOrigin, frameOrigin),
|
||||
0o644,
|
||||
))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(frameDir, webkitOriginFile), []byte(topOrigin+" "+frameOrigin), 0o644))
|
||||
|
||||
dbPath := filepath.Join(frameDir, webkitLocalStorageSubdir, webkitLocalStorageDB)
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
@@ -180,56 +174,6 @@ func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, fra
|
||||
require.NoError(t, db.Close())
|
||||
}
|
||||
|
||||
// encodeOriginFile mirrors WebKit's SecurityOrigin binary serialization. Layout per origin
|
||||
// block: length-prefixed scheme record, length-prefixed host record, then a port marker
|
||||
// (0x00 for the scheme default, or 0x01 + uint16_le port). Two blocks back-to-back: top-frame
|
||||
// then frame.
|
||||
func encodeOriginFile(topOrigin, frameOrigin string) []byte {
|
||||
var buf []byte
|
||||
buf = appendOriginBlock(buf, topOrigin)
|
||||
buf = appendOriginBlock(buf, frameOrigin)
|
||||
return buf
|
||||
}
|
||||
|
||||
func appendOriginBlock(buf []byte, originURL string) []byte {
|
||||
scheme, host, port := splitTestOriginURL(originURL)
|
||||
buf = appendOriginRecord(buf, scheme)
|
||||
buf = appendOriginRecord(buf, host)
|
||||
if port == 0 {
|
||||
buf = append(buf, originPortDefaultMarker)
|
||||
return buf
|
||||
}
|
||||
buf = append(buf, originPortExplicitFlag)
|
||||
portBytes := make([]byte, 2)
|
||||
binary.LittleEndian.PutUint16(portBytes, port)
|
||||
return append(buf, portBytes...)
|
||||
}
|
||||
|
||||
func appendOriginRecord(buf []byte, s string) []byte {
|
||||
lenBytes := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(lenBytes, uint32(len(s)))
|
||||
buf = append(buf, lenBytes...)
|
||||
buf = append(buf, originEncASCII)
|
||||
return append(buf, []byte(s)...)
|
||||
}
|
||||
|
||||
// splitTestOriginURL parses "https://example.com[:port]" into (scheme, host, port).
|
||||
// Port 0 means the URL had no explicit port (use scheme default).
|
||||
func splitTestOriginURL(u string) (scheme, host string, port uint16) {
|
||||
idx := strings.Index(u, "://")
|
||||
if idx < 0 {
|
||||
return "", u, 0
|
||||
}
|
||||
scheme = u[:idx]
|
||||
rest := u[idx+3:]
|
||||
if colon := strings.LastIndex(rest, ":"); colon >= 0 {
|
||||
if p, err := strconv.ParseUint(rest[colon+1:], 10, 16); err == nil {
|
||||
return scheme, rest[:colon], uint16(p)
|
||||
}
|
||||
}
|
||||
return scheme, rest, 0
|
||||
}
|
||||
|
||||
// writeLocalStorageDB creates a minimal localstorage.sqlite3 at path with ItemTable populated
|
||||
// from items. When addNullKey is true, a NULL-key row is inserted first to exercise the
|
||||
// skip-NULL-key logic in readLocalStorageFile / countLocalStorageFile. This is a direct-DB
|
||||
|
||||
Reference in new issue
Block a user