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:
Roger authored and GitHub committed 2026-10-28 15:51:15 +08:00
1 parent 2093045664
commit 4add07e825
37 files changed
+1757 -949

No files matched your search

+21 -11
View File
@@ -1,9 +1,12 @@
package app
import (
"fmt"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
"github.com/moond4rk/hackbrowserdata/internal/browser/firefox"
"github.com/moond4rk/hackbrowserdata/internal/browser/safari"
)
// Discovery is what Discover found: the user data dirs, and an error result for each browser whose data could not be
@@ -33,26 +36,33 @@ func Discover(req Request) Discovery {
return d
}
// discover and extractorsOf dispatch on the base here, because the base packages import browser and so browser cannot
// call them.
// discover and extractorsWith dispatch on the base here, because the base packages import browser and so browser
// cannot call them.
func discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) {
switch def.Base {
case browser.Chromium:
return chromium.Discover(def, opts)
case browser.Firefox:
return firefox.Discover(def, opts)
case browser.Safari:
return safari.Discover(def, opts)
default:
return nil, nil // Safari is not on the pipeline yet
return nil, fmt.Errorf("%s: no base package", def.ID)
}
}
func extractorsOf(dir browser.UserDataDir, p browser.Profile) browser.Extractors {
switch dir.Def.Base {
case browser.Chromium:
return chromium.Extractors(dir, p)
case browser.Firefox:
return firefox.Extractors(dir, p)
default:
return nil
// extractorsWith hands Safari the run's login keychain, which its default profile's password extractor reads.
func extractorsWith(kc safari.LoginKeychain) extractorsFunc {
return func(dir browser.UserDataDir, p browser.Profile) browser.Extractors {
switch dir.Def.Base {
case browser.Chromium:
return chromium.Extractors(dir, p)
case browser.Firefox:
return firefox.Extractors(dir, p)
case browser.Safari:
return safari.Extractors(dir, p, kc)
default:
return nil
}
}
}
+11 -2
View File
@@ -9,6 +9,7 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
"github.com/moond4rk/hackbrowserdata/internal/browser/safari"
"github.com/moond4rk/hackbrowserdata/internal/export"
"github.com/moond4rk/hackbrowserdata/internal/log"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
@@ -16,17 +17,25 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// runKeychain is the run's one login keychain, read by the Chromium v10 retriever and the Safari password extractor;
// nil off macOS.
type runKeychain interface {
masterkey.LoginKeychain
safari.LoginKeychain
}
// keySource retrieves one user data dir's Chromium keys, reading what it needs from the dir's snapshot.
type keySource func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error)
// Execute runs Capture, Extract, and Export one user data dir at a time, so at most one dir's copies are on disk. Its
// error means the run could not finish, such as a failed output write; every other failure is a Result.
func Execute(ctx context.Context, p Plan, req Request) (Summary, error) {
kc := loginKeychain(req)
keys := dumpKeys(req.Keys)
if req.Keys == nil {
keys = machineKeys(loginKeychain(req))
keys = machineKeys(kc)
}
return execute(ctx, p, req, extractorsOf, keys)
return execute(ctx, p, req, extractorsWith(kc), keys)
}
func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc, keys keySource) (Summary, error) {
+2 -2
View File
@@ -155,14 +155,14 @@ func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) {
touch(t, path, "Default", "Network", "Cookies")
dir := browser.UserDataDir{ID: "chrome", Def: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}}
run(t, extractorsOf, noKeys(t), []category.Category{category.History, category.Download}, dir)
run(t, extractorsWith(nil), noKeys(t), []category.Category{category.History, category.Download}, dir)
calls := 0
counting := func(context.Context, browser.UserDataDir, snapshot.Snapshot) (masterkey.Set, error) {
calls++
return nil, nil
}
run(t, extractorsOf, counting, []category.Category{category.Cookie, category.History}, dir)
run(t, extractorsWith(nil), counting, []category.Category{category.Cookie, category.History}, dir)
assert.Equal(t, 1, calls)
}
+1 -2
View File
@@ -7,11 +7,10 @@ import (
"path/filepath"
"github.com/moond4rk/hackbrowserdata/internal/keychain"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
)
// loginKeychain builds the run's one login keychain without opening it, so a run that never decrypts never prompts.
func loginKeychain(req Request) masterkey.LoginKeychain {
func loginKeychain(req Request) runKeychain {
password := keychain.PasswordFunc(req.KeychainPassword)
if password == nil {
password = func(context.Context) (string, error) { return "", nil }
+1 -3
View File
@@ -2,6 +2,4 @@
package app
import "github.com/moond4rk/hackbrowserdata/internal/masterkey"
func loginKeychain(Request) masterkey.LoginKeychain { return nil }
func loginKeychain(Request) runKeychain { return nil }
+7 -2
View File
@@ -30,8 +30,9 @@ type Plan struct {
type extractorsFunc func(browser.UserDataDir, browser.Profile) browser.Extractors
// NewPlan crosses every discovered profile with the requested categories. It only stats files; it opens nothing.
// Planning reads only the extractors' sources, so it needs no keychain.
func NewPlan(d Discovery, req Request) Plan {
return newPlan(d, req, extractorsOf)
return newPlan(d, req, extractorsWith(nil))
}
func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan {
@@ -66,8 +67,12 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan {
}
// locate finds each source's first candidate on disk. An extraction needs every required source and at least one of
// the profile's own; a shared one such as Local State never makes it present by itself.
// the profile's own; a shared one such as Local State never makes it present by itself. An extraction that reads no
// file, such as Safari's keychain passwords, always runs.
func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool) {
if len(sources) == 0 {
return nil, true
}
var files []snapshot.File
present := false
for _, src := range sources {
+13
View File
@@ -102,3 +102,16 @@ func TestNewPlan_UnsupportedCategory(t *testing.T) {
got.Skipped)
assert.Empty(t, got.Extractions)
}
// Safari's passwords come from the keychain: an extractor that reads no file is never absent.
func TestNewPlan_ExtractorWithoutSourcesRuns(t *testing.T) {
dir := browser.UserDataDir{ID: "safari", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "default", Dir: "Safari"}}}
keychainOnly := func(browser.UserDataDir, browser.Profile) browser.Extractors {
return browser.Extractors{category.Password: {}}
}
got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.Password}}, keychainOnly)
assert.Equal(t, []Extraction{{DirID: "safari", Profile: "default", Category: category.Password}}, got.Extractions)
assert.Empty(t, got.Files)
assert.Empty(t, got.Skipped)
}
@@ -0,0 +1,78 @@
package safari
import (
"fmt"
"os"
"time"
"github.com/moond4rk/plist"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"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, out browser.Collector) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("open bookmarks: %w", err)
}
defer f.Close()
var root safariBookmark
if err := plist.NewDecoder(f).Decode(&root); err != nil {
return fmt.Errorf("decode bookmarks: %w", err)
}
var bookmarks []record.Bookmark
walkBookmarks(root.Children, "", &bookmarks)
emit(out, bookmarks)
return 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)
}
}
}
@@ -0,0 +1,176 @@
package safari
import (
"os"
"path/filepath"
"testing"
"github.com/moond4rk/plist"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
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)
var out testCollector
err := extractBookmarks(path, &out)
bookmarks := collected[record.Bookmark](t, &out)
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)
var out testCollector
err := extractBookmarks(path, &out)
bookmarks := collected[record.Bookmark](t, &out)
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)
var out testCollector
err := extractBookmarks(path, &out)
bookmarks := collected[record.Bookmark](t, &out)
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)
var out testCollector
err := extractBookmarks(path, &out)
bookmarks := collected[record.Bookmark](t, &out)
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 TestExtractBookmarks_Empty(t *testing.T) {
root := safariBookmark{Type: bookmarkTypeList}
path := buildTestBookmarksPlist(t, root)
var out testCollector
err := extractBookmarks(path, &out)
bookmarks := collected[record.Bookmark](t, &out)
require.NoError(t, err)
assert.Empty(t, bookmarks)
}
+56
View File
@@ -0,0 +1,56 @@
package safari
import (
"fmt"
"os"
"github.com/moond4rk/binarycookies"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
func extractCookies(path string, out browser.Collector) error {
pages, err := decodeBinaryCookies(path)
if err != nil {
return 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(),
})
}
}
emit(out, cookies)
return 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
}
@@ -0,0 +1,166 @@
package safari
import (
"encoding/binary"
"math"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// 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,
},
})
var out testCollector
err := extractCookies(path, &out)
cookies := collected[record.Cookie](t, &out)
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 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, &testCollector{})
assert.Error(t, err)
}
func TestExtractCookies_FileNotFound(t *testing.T) {
err := extractCookies("/nonexistent/Cookies.binarycookies", &testCollector{})
assert.Error(t, err)
}
@@ -0,0 +1,62 @@
package safari
import (
"fmt"
"os"
"github.com/moond4rk/plist"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"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, out browser.Collector) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("open downloads: %w", err)
}
defer f.Close()
var dl safariDownloads
if err := plist.NewDecoder(f).Decode(&dl); err != nil {
return 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,
})
}
emit(out, downloads)
return 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
}
@@ -0,0 +1,75 @@
package safari
import (
"os"
"path/filepath"
"testing"
"github.com/moond4rk/plist"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
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)
var out testCollector
err := extractDownloads(path, defaultProfileSentinel, &out)
downloads := collected[record.Download](t, &out)
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)
var out testCollector
err := extractDownloads(path, namedUUID, &out)
downloads := collected[record.Download](t, &out)
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 TestExtractDownloads_Empty(t *testing.T) {
dl := safariDownloads{}
path := buildTestDownloadsPlist(t, dl)
var out testCollector
err := extractDownloads(path, defaultProfileSentinel, &out)
downloads := collected[record.Download](t, &out)
require.NoError(t, err)
assert.Empty(t, downloads)
}
@@ -0,0 +1,107 @@
package safari
import (
"fmt"
"os"
"regexp"
"sort"
"strings"
"github.com/moond4rk/plist"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"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.
// 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 merges the plists in paths, sorted by key for deterministic output.
func extractExtensions(paths []string, out browser.Collector) error {
records, err := readSafariExtensions(paths)
if err != nil {
return 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,
})
}
emit(out, extensions)
return nil
}
type extensionRecord struct {
key string
bundleID string
enabled bool
}
func readSafariExtensions(paths []string) ([]extensionRecord, error) {
var all []extensionRecord
for _, p := range paths {
records, err := decodeSafariExtensionsPlist(p)
if err != nil {
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)
}
@@ -0,0 +1,144 @@
package safari
import (
"os"
"path/filepath"
"testing"
"github.com/moond4rk/plist"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// 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, "Safari", subdir)
require.NoError(t, os.MkdirAll(dir, 0o755))
f, err := os.Create(filepath.Join(dir, "Extensions.plist"))
require.NoError(t, err)
defer f.Close()
require.NoError(t, plist.NewBinaryEncoder(f).Encode(entries))
}
// extensionPlists lists the plists present under container, as the extractor finds them in its snapshot.
func extensionPlists(container string) []string {
var paths []string
for _, sub := range []string{"AppExtensions", "WebExtensions"} {
if p := filepath.Join(container, "Safari", sub, "Extensions.plist"); fileExists(p) {
paths = append(paths, p)
}
}
return paths
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func TestExtractExtensions_AppAndWebMerged(t *testing.T) {
container := t.TempDir()
writeTestExtensionsPlist(t, container, "AppExtensions", map[string]testExtensionEntry{
"com.colliderli.iina.OpenInIINA (67CQ77V27R)": {},
})
writeTestExtensionsPlist(t, container, "WebExtensions", map[string]testExtensionEntry{
"com.1password.safari.extension (2BUA8C4S2C)": {"Enabled": true},
})
var out testCollector
err := extractExtensions(extensionPlists(container), &out)
got := collected[record.Extension](t, &out)
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, "WebExtensions", map[string]testExtensionEntry{
"com.example.a (AAAAAAAAAA)": {"Enabled": true},
"com.example.b (BBBBBBBBBB)": {"Enabled": false},
})
var out testCollector
err := extractExtensions(extensionPlists(container), &out)
got := collected[record.Extension](t, &out)
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, "AppExtensions", map[string]testExtensionEntry{
"legacy-key-without-team-id": {},
})
var out testCollector
err := extractExtensions(extensionPlists(container), &out)
got := collected[record.Extension](t, &out)
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, "AppExtensions", map[string]testExtensionEntry{
"com.example.only (XXXXXXXXX1)": {},
})
var out testCollector
err := extractExtensions(extensionPlists(container), &out)
got := collected[record.Extension](t, &out)
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, "WebExtensions", map[string]testExtensionEntry{
"com.example.web (XXXXXXXXX2)": {"Enabled": true},
})
var out testCollector
err := extractExtensions(extensionPlists(container), &out)
got := collected[record.Extension](t, &out)
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()
var out testCollector
err := extractExtensions(extensionPlists(container), &out)
got := collected[record.Extension](t, &out)
require.NoError(t, err)
assert.Empty(t, got)
}
@@ -0,0 +1,48 @@
package safari
import (
"database/sql"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"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
)`
)
func extractHistories(path string, out browser.Collector) 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 err
}
emit(out, histories)
return nil
}
@@ -0,0 +1,86 @@
package safari
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
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)
var out testCollector
err := extractHistories(path, &out)
got := collected[record.History](t, &out)
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)
var out testCollector
err := extractHistories(path, &out)
got := collected[record.History](t, &out)
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 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)`,
)
var out testCollector
err := extractHistories(path, &out)
got := collected[record.History](t, &out)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, "https://null.test", got[0].URL)
assert.Empty(t, got[0].Title)
}
@@ -0,0 +1,59 @@
package safari
import (
"context"
"fmt"
"strings"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
func extractPasswords(ctx context.Context, kc LoginKeychain, out browser.Collector) error {
passwords, err := kc.InternetPasswords(ctx)
if err != nil {
return 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,
})
}
emit(out, logins)
return 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
}
@@ -0,0 +1,91 @@
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)
})
}
}
+302
View File
@@ -0,0 +1,302 @@
package safari
import (
"database/sql"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"unicode/utf16"
_ "modernc.org/sqlite"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"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, out browser.Collector) error {
dirs, err := findOriginDataDirs(root)
if err != nil {
return 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,
})
}
}
emit(out, entries)
return 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 without immutable, so SQLite replays the copied -wal sidecar and surfaces entries Safari has not yet
// checkpointed. 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))
}
@@ -0,0 +1,308 @@
package safari
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
_ "modernc.org/sqlite"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// ---------------------------------------------------------------------------
// 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"}},
})
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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"},
},
})
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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 世界 🌍"},
},
})
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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,
})
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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)}},
})
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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"}},
)
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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))
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
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))
var out testCollector
err := extractLocalStorage(root, &out)
entries := collected[record.LocalStorage](t, &out)
require.NoError(t, err)
assert.Empty(t, entries)
}
func TestExtractLocalStorage_DirMissing(t *testing.T) {
err := extractLocalStorage(filepath.Join(t.TempDir(), "does-not-exist"), &testCollector{})
require.Error(t, err)
}
func TestExtractLocalStorage_EmptyRoot(t *testing.T) {
var out testCollector
err := extractLocalStorage(t.TempDir(), &out)
entries := collected[record.LocalStorage](t, &out)
require.NoError(t, err)
assert.Empty(t, entries)
}
// ---------------------------------------------------------------------------
// NULL-key handling — readLocalStorageFile skips NULL keys.
// ---------------------------------------------------------------------------
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 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)
}
+154
View File
@@ -0,0 +1,154 @@
package safari
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
_ "modernc.org/sqlite"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/log"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// 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 (
safariTabsDBRelPath = containerDir + "/Safari/SafariTabs.db"
safariProfileSubtype = 2
defaultProfileSentinel = "DefaultProfile"
)
// Path-unsafe bytes for filenames/CSV values; Unicode letters (CJK etc.) survive.
var unsafeNameChars = regexp.MustCompile(`[/\\:*?"<>|\x00-\x1f]+`)
// Canonical 8-4-4-4-12 hex UUID — format check only, no semantic parse.
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`)
// namedProfiles reads SafariTabs.db (authoritative), with a ReadDir fallback only if the DB itself is unreadable.
func namedProfiles(library string) []browser.Profile {
named, err := readNamedProfilesFromDB(library)
if err != nil {
// Empty DB (nil, nil) is authoritative; fall back only when DB itself is unreadable.
named = readNamedProfilesFromDir(library)
}
return named
}
// readNamedProfilesFromDB returns (nil, err) when the DB is missing/unreadable so the caller can
// try the ReadDir fallback; (slice, nil) — possibly empty — is authoritative.
// Discovery reads a snapshot copy, never the live file Safari has open.
func readNamedProfilesFromDB(library string) ([]browser.Profile, error) {
d, err := snapshot.Temp()
if err != nil {
return nil, err
}
defer func() {
if err := d.Close(); err != nil {
log.Warnf("%v", err)
}
}()
if err := d.Capture(context.Background(), []snapshot.File{{DirID: discoverDirID, From: library, Rel: safariTabsDBRelPath}}); err != nil {
return nil, fmt.Errorf("copy SafariTabs.db: %w", err)
}
path, err := d.Snapshot(discoverDirID).Path(safariTabsDBRelPath)
if err != nil {
return nil, fmt.Errorf("copy SafariTabs.db: %w", err)
}
// Immutable, as on the live file before: the copied -wal is not replayed, so the profile list stays today's.
dsn := "file:" + path + "?mode=ro&immutable=1"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("open SafariTabs.db: %w", err)
}
defer db.Close()
// Ping forces connection; sql.Open is lazy and won't detect a missing file.
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("ping SafariTabs.db: %w", err)
}
rows, err := db.Query(
`SELECT external_uuid, title FROM bookmarks WHERE subtype = ? AND external_uuid != ?`,
safariProfileSubtype, defaultProfileSentinel,
)
if err != nil {
return nil, fmt.Errorf("query SafariTabs.db: %w", err)
}
defer rows.Close()
var out []browser.Profile
for rows.Next() {
var externalUUID, title sql.NullString
if err := rows.Scan(&externalUUID, &title); err != nil {
log.Debugf("safari profiles: scan row: %v", err)
continue
}
if !isCanonicalUUID(externalUUID.String) {
continue
}
out = append(out, newNamedProfile(externalUUID.String, title.String))
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate SafariTabs.db rows: %w", err)
}
return out, nil
}
// readNamedProfilesFromDir is the fallback for missing SafariTabs.db. Names are synthesized from UUIDs.
func readNamedProfilesFromDir(library string) []browser.Profile {
entries, err := os.ReadDir(filepath.Join(library, filepath.FromSlash(namedProfilesDir)))
if err != nil {
return nil
}
var out []browser.Profile
for _, e := range entries {
if !e.IsDir() || !isCanonicalUUID(e.Name()) {
continue
}
out = append(out, newNamedProfile(e.Name(), ""))
}
return out
}
// A named profile's Dir is its own History.db directory, so its UUID travels with it to Extractors.
func newNamedProfile(upperUUID, title string) browser.Profile {
return browser.Profile{Name: resolveProfileName(title, upperUUID), Dir: namedProfilesDir + "/" + upperUUID}
}
func isCanonicalUUID(s string) bool { return uuidPattern.MatchString(s) }
// resolveProfileName prefers the SafariTabs.db title, falling back to "profile-<uuid[:8]>".
func resolveProfileName(title, upperUUID string) string {
if name := sanitizeProfileName(title); name != "" {
return name
}
return "profile-" + strings.ToLower(upperUUID[:8])
}
func sanitizeProfileName(name string) string {
name = strings.TrimSpace(name)
if name == "" {
return ""
}
return unsafeNameChars.ReplaceAllString(name, "_")
}
// disambiguateNames appends "-2", "-3", … to duplicate names, in place.
func disambiguateNames(profiles []browser.Profile) {
occurrences := make(map[string]int, len(profiles))
for i := range profiles {
original := profiles[i].Name
if prior := occurrences[original]; prior > 0 {
profiles[i].Name = fmt.Sprintf("%s-%d", original, prior+1)
}
occurrences[original]++
}
}
+163
View File
@@ -0,0 +1,163 @@
package safari
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser"
)
func testDef() browser.Def {
p := browser.Platform{UserDataDirs: []string{"Library/Safari"}}
return browser.Def{ID: "safari", Name: "Safari", Base: browser.Safari, Darwin: p, Linux: p, Windows: p}
}
// libraryAt lays out a fake home: ~/Library/Safari with a History.db, and the container beside it.
func libraryAt(t *testing.T, home string) (container string) {
t.Helper()
mkFile(t, home, "Library", "Safari", "History.db")
return filepath.Join(home, "Library", "Containers", "com.apple.Safari", "Data", "Library")
}
func discoverProfiles(t *testing.T, home string) []browser.Profile {
t.Helper()
dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: home})
require.NoError(t, err)
require.Len(t, dirs, 1)
assert.Equal(t, browser.DirID("safari"), dirs[0].ID)
assert.Equal(t, filepath.Join(home, "Library"), dirs[0].Path)
return dirs[0].Profiles
}
func named(name, uuid string) browser.Profile {
return browser.Profile{Name: name, Dir: namedProfilesDir + "/" + uuid}
}
var defaultProfile = browser.Profile{Name: "default", Dir: "Safari"}
func TestDiscover_DefaultOnly(t *testing.T) {
home := t.TempDir()
libraryAt(t, home)
assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home))
}
func TestDiscover_MissingSafariYieldsNothing(t *testing.T) {
dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: t.TempDir()})
require.NoError(t, err)
assert.Empty(t, dirs)
}
// -p does not apply to Safari: the table's directory is used, and Validate rejects -p at the switch-over.
func TestDiscover_IgnoresProfilePath(t *testing.T) {
home := t.TempDir()
libraryAt(t, home)
dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: home, ProfilePath: t.TempDir()})
require.NoError(t, err)
require.Len(t, dirs, 1)
assert.Equal(t, filepath.Join(home, "Library"), dirs[0].Path)
}
func TestDiscover_WithNamedProfile(t *testing.T) {
const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
home := t.TempDir()
container := libraryAt(t, home)
mkFile(t, container, "Safari", "Profiles", uuid, "History.db")
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{
{uuid: "DefaultProfile", title: ""},
{uuid: uuid, title: "work"},
})
assert.Equal(t, []browser.Profile{defaultProfile, named("work", uuid)}, discoverProfiles(t, home))
}
// A '#' in the live path cuts a SQLite URI short, so the titles come through only when discovery opens its copy.
func TestDiscover_ReadsACopyOfSafariTabs(t *testing.T) {
const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
home := filepath.Join(t.TempDir(), "user#1")
container := libraryAt(t, home)
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: uuid, title: "work"}})
assert.Equal(t, []browser.Profile{defaultProfile, named("work", uuid)}, discoverProfiles(t, home))
}
func TestDiscover_EmptyTitleFallbackToUUID(t *testing.T) {
const uuid = "ABCDEF01-2345-6789-ABCD-EF0123456789"
home := t.TempDir()
container := libraryAt(t, home)
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: uuid, title: ""}})
assert.Equal(t, []browser.Profile{defaultProfile, named("profile-abcdef01", uuid)}, discoverProfiles(t, home))
}
// A profile directory SafariTabs.db does not mention stays hidden: a readable DB is authoritative.
func TestDiscover_OrphanUUIDWithoutDBEntry(t *testing.T) {
const dbUUID = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"
const orphanUUID = "11111111-2222-3333-4444-555555555555"
home := t.TempDir()
container := libraryAt(t, home)
mkFile(t, container, "Safari", "Profiles", dbUUID, "History.db")
mkFile(t, container, "Safari", "Profiles", orphanUUID, "History.db")
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: dbUUID, title: "declared"}})
assert.Equal(t, []browser.Profile{defaultProfile, named("declared", dbUUID)}, discoverProfiles(t, home))
}
func TestDiscover_EmptyDBIsAuthoritative(t *testing.T) {
home := t.TempDir()
container := libraryAt(t, home)
mkFile(t, container, "Safari", "Profiles", "99999999-AAAA-BBBB-CCCC-DDDDDDDDDDDD", "History.db")
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), nil)
assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home))
}
// Without SafariTabs.db the Profiles directory is listed and names are synthesized; directories without data are kept,
// because whether a category's file exists is the plan's question.
func TestDiscover_MissingDBFallsBackToReadDir(t *testing.T) {
const uuid = "11111111-2222-3333-4444-555555555555"
const empty = "4E2D8DD0-A7D2-4684-939A-898B7675C700"
home := t.TempDir()
container := libraryAt(t, home)
mkFile(t, container, "Safari", "Profiles", uuid, "History.db")
require.NoError(t, os.MkdirAll(filepath.Join(container, "Safari", "Profiles", empty), 0o755))
require.NoError(t, os.MkdirAll(filepath.Join(container, "Safari", "Profiles", "Bogus"), 0o755))
assert.Equal(t, []browser.Profile{defaultProfile, named("profile-11111111", uuid), named("profile-4e2d8dd0", empty)},
discoverProfiles(t, home))
}
func TestDiscover_DuplicateTitlesDisambiguate(t *testing.T) {
const uuidA = "AAAAAAAA-0000-0000-0000-000000000001"
const uuidB = "BBBBBBBB-0000-0000-0000-000000000002"
home := t.TempDir()
container := libraryAt(t, home)
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{
{uuid: uuidA, title: "team"},
{uuid: uuidB, title: "team"},
})
assert.Equal(t, []browser.Profile{defaultProfile, named("team", uuidA), named("team-2", uuidB)}, discoverProfiles(t, home))
}
func TestDiscover_DefaultProfileSentinelIgnored(t *testing.T) {
home := t.TempDir()
container := libraryAt(t, home)
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: defaultProfileSentinel, title: ""}})
assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home))
}
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))
})
}
}
+185
View File
@@ -0,0 +1,185 @@
// Package safari is the Safari base: where Safari keeps its default and named profiles under ~/Library, how their
// files are parsed, and the login keychain its passwords come from.
package safari
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"github.com/moond4rk/keychainbreaker"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// Paths below are relative to the user data dir, ~/Library.
const (
containerDir = "Containers/com.apple.Safari/Data/Library"
namedProfilesDir = containerDir + "/Safari/Profiles"
defaultProfileName = "default"
discoverDirID = "safari"
)
var errNoKeychain = errors.New("no login keychain")
// LoginKeychain is the one method the password extractor reads from the run's login keychain.
type LoginKeychain interface {
InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error)
}
// Discover finds Safari's data under ~/Library: the default profile, whose Dir is the Safari directory, and the named
// profiles SafariTabs.db lists. -p does not apply to Safari, and Validate rejects it at the switch-over.
func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) {
var errs []error
var dirs []browser.UserDataDir
for i, rel := range def.Platform().UserDataDirs {
safariPath := filepath.Join(opts.Home, filepath.FromSlash(rel))
if _, err := os.Stat(safariPath); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
errs = append(errs, fmt.Errorf("%s: %w", safariPath, err))
}
continue
}
library := filepath.Dir(safariPath)
profiles := append([]browser.Profile{{Name: defaultProfileName, Dir: filepath.Base(safariPath)}}, namedProfiles(library)...)
disambiguateNames(profiles)
dirs = append(dirs, browser.UserDataDir{ID: dirID(def, i), Def: def, Path: library, Profiles: profiles})
}
return dirs, errors.Join(errs...)
}
func dirID(def browser.Def, i int) browser.DirID {
if i == 0 {
return browser.DirID(def.ID)
}
return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1))
}
// Extractors maps the categories a Safari profile supports to their extractors. A named profile's files sit under
// two directories named for its UUID, so its sources are built from Profile.Dir; the keychain, Bookmarks.plist, and
// the extension plists carry no profile tag, so only the default profile reads them.
func Extractors(dir browser.UserDataDir, p browser.Profile, kc LoginKeychain) browser.Extractors {
library := func(rel string) string { return fromLibrary(p, rel) }
uuid, named := profileUUID(p)
if !named {
return browser.Extractors{
category.Password: {Extract: passwordsFrom(kc)},
category.History: plain(file("History.db"), extractHistories),
category.Cookie: plain(file(
library(containerDir+"/Cookies/Cookies.binarycookies"),
library("Cookies/Cookies.binarycookies"),
), extractCookies),
category.Bookmark: plain(file("Bookmarks.plist"), extractBookmarks),
category.Download: plain(file("Downloads.plist"), downloadsOf(defaultProfileSentinel)),
category.LocalStorage: plain(directory(library(containerDir+"/WebKit/WebsiteData/Default")), extractLocalStorage),
category.Extension: extensionsFrom(library),
}
}
store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid)
return browser.Extractors{
category.History: plain(file("History.db"), extractHistories),
category.Cookie: plain(file(library(store+"/Cookies/Cookies.binarycookies")), extractCookies),
category.Download: plain(file(library(safariDir(dir)+"/Downloads.plist")), downloadsOf(uuid)),
category.LocalStorage: plain(directory(library(store+"/Origins")), extractLocalStorage),
}
}
func profileUUID(p browser.Profile) (string, bool) {
if path.Dir(p.Dir) != namedProfilesDir {
return "", false
}
return path.Base(p.Dir), true
}
// safariDir is the default profile's Dir, which holds the Downloads.plist every profile reads its entries from.
func safariDir(dir browser.UserDataDir) string {
for _, p := range dir.Profiles {
if _, named := profileUUID(p); !named {
return p.Dir
}
}
return "Safari"
}
// fromLibrary turns a path under ~/Library into one relative to p.Dir, because a profile's sources are joined with it.
func fromLibrary(p browser.Profile, rel string) string {
if p.Dir == "" {
return rel
}
return strings.Repeat("../", strings.Count(p.Dir, "/")+1) + rel
}
func file(paths ...string) browser.Source { return browser.Source{Paths: paths} }
func directory(rel string) browser.Source { return browser.Source{Paths: []string{rel}, IsDir: true} }
func plain(src browser.Source, parse func(string, browser.Collector) error) browser.Extractor {
return browser.Extractor{
Sources: []browser.Source{src},
Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error {
captured, err := ps.Path(src)
if err != nil {
return err
}
return parse(captured, out)
},
}
}
// passwordsFrom reads no file, so the extraction always runs; the keychain stays locked without a usable password and
// yields metadata only.
func passwordsFrom(kc LoginKeychain) func(context.Context, browser.ProfileSnapshot, browser.Collector) error {
return func(ctx context.Context, _ browser.ProfileSnapshot, out browser.Collector) error {
if kc == nil {
return errNoKeychain
}
return extractPasswords(ctx, kc, out)
}
}
// downloadsOf keeps the entries of one profile: Downloads.plist is shared, and each entry names the profile it
// belongs to.
func downloadsOf(owner string) func(string, browser.Collector) error {
return func(path string, out browser.Collector) error { return extractDownloads(path, owner, out) }
}
func extensionsFrom(library func(string) string) browser.Extractor {
sources := []browser.Source{
{Paths: []string{library(containerDir + "/Safari/AppExtensions/Extensions.plist")}, Optional: true},
{Paths: []string{library(containerDir + "/Safari/WebExtensions/Extensions.plist")}, Optional: true},
}
return browser.Extractor{
Sources: sources,
Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error {
var paths []string
for _, src := range sources {
captured, err := ps.Path(src)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
return err
}
paths = append(paths, captured)
}
return extractExtensions(paths, out)
},
}
}
// emit hands rows to out by pointer, because out stamps each record in place.
func emit[T any, P interface {
*T
record.Record
}](out browser.Collector, rows []T) {
for i := range rows {
out.Add(P(&rows[i]))
}
}
+186
View File
@@ -0,0 +1,186 @@
package safari
import (
"context"
"errors"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/moond4rk/keychainbreaker"
"github.com/moond4rk/plist"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
const workUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
var (
workProfile = named("work", workUUID)
libraryDir = browser.UserDataDir{Def: testDef(), Profiles: []browser.Profile{defaultProfile, workProfile}}
)
// sourcePaths is where each category's candidates land under ~/Library once joined with the profile's Dir.
func sourcePaths(p browser.Profile, ex browser.Extractors) map[category.Category][]string {
got := make(map[category.Category][]string, len(ex))
for c, e := range ex {
for _, src := range e.Sources {
for _, rel := range src.Paths {
got[c] = append(got[c], path.Join(p.Dir, rel))
}
}
}
return got
}
func TestExtractors_DefaultProfileSources(t *testing.T) {
ex := Extractors(libraryDir, defaultProfile, nil)
assert.Equal(t, map[category.Category][]string{
category.History: {"Safari/History.db"},
category.Cookie: {containerDir + "/Cookies/Cookies.binarycookies", "Cookies/Cookies.binarycookies"},
category.Bookmark: {"Safari/Bookmarks.plist"},
category.Download: {"Safari/Downloads.plist"},
category.LocalStorage: {
containerDir + "/WebKit/WebsiteData/Default",
},
category.Extension: {
containerDir + "/Safari/AppExtensions/Extensions.plist",
containerDir + "/Safari/WebExtensions/Extensions.plist",
},
}, sourcePaths(defaultProfile, ex))
require.Contains(t, ex, category.Password)
assert.Empty(t, ex[category.Password].Sources, "passwords come from the keychain, not a file")
}
func TestExtractors_NamedProfileSources(t *testing.T) {
store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(workUUID)
assert.Equal(t, map[category.Category][]string{
category.History: {namedProfilesDir + "/" + workUUID + "/History.db"},
category.Cookie: {store + "/Cookies/Cookies.binarycookies"},
category.Download: {"Safari/Downloads.plist"},
category.LocalStorage: {store + "/Origins"},
}, sourcePaths(workProfile, Extractors(libraryDir, workProfile, nil)))
}
// snapshotOf lays fixture files out as the Safari user data dir's snapshot, keyed by their path under ~/Library.
func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot {
t.Helper()
root := t.TempDir()
for rel, src := range files {
data, err := os.ReadFile(src)
require.NoError(t, err)
dst := filepath.Join(root, "safari", filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(dst), 0o755))
require.NoError(t, os.WriteFile(dst, data, 0o644))
}
return snapshot.Open(root).Snapshot("safari")
}
func writeTestPlist(t *testing.T, v any) string {
t.Helper()
p := filepath.Join(t.TempDir(), "fixture.plist")
f, err := os.Create(p)
require.NoError(t, err)
defer f.Close()
require.NoError(t, plist.NewBinaryEncoder(f).Encode(v))
return p
}
func extract(t *testing.T, snap snapshot.Snapshot, p browser.Profile, kc LoginKeychain, c category.Category) (*testCollector, error) {
t.Helper()
ex, ok := Extractors(libraryDir, p, kc)[c]
require.Truef(t, ok, "no %s extractor for %s", c, p.Name)
var out testCollector
err := ex.Extract(context.Background(), browser.NewProfileSnapshot(snap, p, nil), &out)
return &out, err
}
// Each profile keeps its own entries of the shared Downloads.plist; an entry without an owner is the default's.
func TestExtractors_DownloadsBelongToTheirProfile(t *testing.T) {
snap := snapshotOf(t, map[string]string{"Safari/Downloads.plist": writeTestPlist(t, map[string]any{
"DownloadHistory": []any{
map[string]any{"DownloadEntryURL": "https://a.test/home", "DownloadEntryProfileUUIDStringKey": "DefaultProfile"},
map[string]any{"DownloadEntryURL": "https://a.test/work", "DownloadEntryProfileUUIDStringKey": workUUID},
map[string]any{"DownloadEntryURL": "https://a.test/legacy"},
},
})})
urls := func(p browser.Profile) []string {
out, err := extract(t, snap, p, nil, category.Download)
require.NoError(t, err)
var got []string
for _, d := range collected[record.Download](t, out) {
got = append(got, d.URL)
}
return got
}
assert.Equal(t, []string{"https://a.test/home", "https://a.test/legacy"}, urls(defaultProfile))
assert.Equal(t, []string{"https://a.test/work"}, urls(workProfile))
}
// The extension plists are read from the snapshot; a missing one is skipped.
func TestExtractors_ExtensionsFromTheSnapshot(t *testing.T) {
snap := snapshotOf(t, map[string]string{
containerDir + "/Safari/WebExtensions/Extensions.plist": writeTestPlist(t, map[string]any{
"com.example.Blocker.Extension (ABCDE12345)": map[string]any{"Enabled": false},
}),
})
out, err := extract(t, snap, defaultProfile, nil, category.Extension)
require.NoError(t, err)
got := collected[record.Extension](t, out)
require.Len(t, got, 1)
assert.Equal(t, "com.example.Blocker.Extension", got[0].Name)
assert.False(t, got[0].Enabled)
}
type fakeKeychain struct {
passwords []keychainbreaker.InternetPassword
err error
calls int
}
func (k *fakeKeychain) InternetPasswords(context.Context) ([]keychainbreaker.InternetPassword, error) {
k.calls++
return k.passwords, k.err
}
func TestExtractors_PasswordsFromTheKeychain(t *testing.T) {
created := time.Date(2024, 3, 1, 9, 0, 0, 0, time.FixedZone("CET", 3600))
kc := &fakeKeychain{passwords: []keychainbreaker.InternetPassword{
{Protocol: "htps", Server: "github.com", Port: 443, Account: "alice", PlainPassword: "s3cret", Created: created},
{Protocol: "htps", Server: "locked.test", Account: "bob"},
{Protocol: "htps", Server: "", Account: "nobody"},
{Protocol: "htps", Server: "anonymous.test", Account: ""},
}}
out, err := extract(t, snapshotOf(t, nil), defaultProfile, kc, category.Password)
require.NoError(t, err)
assert.Equal(t, []record.Login{
{URL: "https://github.com", Username: "alice", Password: "s3cret", CreatedAt: created.UTC(), Store: record.StoreLocal},
{URL: "https://locked.test", Username: "bob", Store: record.StoreLocal},
}, collected[record.Login](t, out))
assert.Equal(t, 1, kc.calls)
}
func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) {
_, err := extract(t, snapshotOf(t, nil), defaultProfile, nil, category.Password)
require.ErrorIs(t, err, errNoKeychain)
broken := errors.New("keychain unreadable")
_, err = extract(t, snapshotOf(t, nil), defaultProfile, &fakeKeychain{err: broken}, category.Password)
require.ErrorIs(t, err, broken)
}
// The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them.
func TestExtractors_NamedProfileSkipsUserWideSources(t *testing.T) {
ex := Extractors(libraryDir, workProfile, &fakeKeychain{})
for _, c := range []category.Category{category.Password, category.Bookmark, category.Extension} {
assert.NotContains(t, ex, c)
}
}
+299
View File
@@ -0,0 +1,299 @@
package safari
import (
"database/sql"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"unicode/utf16"
"github.com/stretchr/testify/require"
_ "modernc.org/sqlite"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// ---------------------------------------------------------------------------
// Real Safari table schemas — extracted via `sqlite3 History.db ".schema"`.
// ---------------------------------------------------------------------------
const safariHistoryItemsSchema = `CREATE TABLE history_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
domain_expansion TEXT NULL,
visit_count INTEGER NOT NULL DEFAULT 0,
daily_visit_counts BLOB NOT NULL DEFAULT x'',
weekly_visit_counts BLOB NULL,
autocomplete_triggers BLOB NULL,
should_recompute_derived_visit_counts INTEGER NOT NULL DEFAULT 1,
visit_count_score INTEGER NOT NULL DEFAULT 0
)`
const safariHistoryVisitsSchema = `CREATE TABLE history_visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
history_item INTEGER NOT NULL REFERENCES history_items(id),
visit_time REAL NOT NULL,
title TEXT NULL,
load_successful BOOLEAN NOT NULL DEFAULT 1,
http_non_get INTEGER NOT NULL DEFAULT 0,
synthesized INTEGER NOT NULL DEFAULT 0,
redirect_source INTEGER NULL,
redirect_destination INTEGER NULL,
origin INTEGER NOT NULL DEFAULT 0,
generation INTEGER NOT NULL DEFAULT 0,
attributes INTEGER NOT NULL DEFAULT 0,
score INTEGER NOT NULL DEFAULT 0
)`
// ---------------------------------------------------------------------------
// INSERT helpers
// ---------------------------------------------------------------------------
func insertHistoryItem(id int, url, domainExpansion string, visitCount int) string {
return fmt.Sprintf(
`INSERT INTO history_items (id, url, domain_expansion, visit_count)
VALUES (%d, '%s', '%s', %d)`,
id, url, domainExpansion, visitCount,
)
}
func insertHistoryVisit(id, historyItem int, visitTime float64, title string) string {
return fmt.Sprintf(
`INSERT INTO history_visits (id, history_item, visit_time, title)
VALUES (%d, %d, %f, '%s')`,
id, historyItem, visitTime, title,
)
}
// ---------------------------------------------------------------------------
// Test fixture builders
// ---------------------------------------------------------------------------
func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { //nolint:unparam // name will vary when future data types are added
t.Helper()
path := filepath.Join(t.TempDir(), name)
db, err := sql.Open("sqlite", path)
require.NoError(t, err)
defer db.Close()
for _, schema := range schemas {
_, err = db.Exec(schema)
require.NoError(t, err)
}
for _, stmt := range inserts {
_, err = db.Exec(stmt)
require.NoError(t, err)
}
return path
}
// ---------------------------------------------------------------------------
// SafariTabs.db fixtures
// ---------------------------------------------------------------------------
// tabRow describes one profile entry to stamp into the fake SafariTabs.db.
type tabRow struct {
uuid string
title string
}
// writeSafariTabsDB creates a minimal SafariTabs.db at path containing only
// the bookmarks columns discoverSafariProfiles reads. Every row gets
// subtype=2 (profile record) so the production query picks it up.
func writeSafariTabsDB(t *testing.T, path string, rows []tabRow) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
db, err := sql.Open("sqlite", path)
require.NoError(t, err)
defer db.Close()
_, err = db.Exec(`CREATE TABLE bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
external_uuid TEXT,
title TEXT,
subtype INTEGER DEFAULT 0
)`)
require.NoError(t, err)
for _, r := range rows {
_, err = db.Exec(`INSERT INTO bookmarks (external_uuid, title, subtype) VALUES (?, ?, 2)`, r.uuid, r.title)
require.NoError(t, err)
}
}
// ---------------------------------------------------------------------------
// LocalStorage fixtures — modern WebKit nested Origins layout
// ---------------------------------------------------------------------------
// testLocalStorageItem is one key/value pair written to an ItemTable row.
// Value is encoded as UTF-16 LE, matching WebKit's on-disk format.
type testLocalStorageItem struct {
Key, Value string
}
// buildTestLocalStorageDir creates a root dir that mirrors Safari 17+'s nested
// localStorage layout (<root>/<h1>/<h2>/origin + LocalStorage/localstorage.sqlite3)
// for each origin URL passed in. Origins are written as first-party (top == frame);
// for partitioned-origin coverage, use buildTestPartitionedLocalStorage.
func buildTestLocalStorageDir(t *testing.T, origins map[string][]testLocalStorageItem) string {
t.Helper()
root := filepath.Join(t.TempDir(), "Origins")
require.NoError(t, os.MkdirAll(root, 0o755))
i := 0
for origin, items := range origins {
hash := fmt.Sprintf("h%02d", i)
i++
writeTestOriginStore(t, root, hash, hash, origin, origin, items)
}
return root
}
// writeTestOriginStore writes one <root>/<topHash>/<frameHash>/ tree with the given
// origins encoded into the binary origin file and items inserted into localstorage.sqlite3.
func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, frameOrigin string, items []testLocalStorageItem) {
t.Helper()
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,
))
dbPath := filepath.Join(frameDir, webkitLocalStorageSubdir, webkitLocalStorageDB)
db, err := sql.Open("sqlite", dbPath)
require.NoError(t, err)
_, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`)
require.NoError(t, err)
for _, item := range items {
_, err = db.Exec(
`INSERT INTO ItemTable (key, value) VALUES (?, ?)`,
item.Key, encodeUTF16LE(item.Value),
)
require.NoError(t, err)
}
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
// variant of buildTestLocalStorageDir — use it when the test targets one DB, not the full
// Origins nesting.
func writeLocalStorageDB(t *testing.T, path string, items []testLocalStorageItem, addNullKey bool) {
t.Helper()
db, err := sql.Open("sqlite", path)
require.NoError(t, err)
_, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`)
require.NoError(t, err)
if addNullKey {
_, err = db.Exec(
`INSERT INTO ItemTable (key, value) VALUES (NULL, ?)`,
encodeUTF16LE("null-key-sentinel"),
)
require.NoError(t, err)
}
for _, item := range items {
_, err = db.Exec(
`INSERT INTO ItemTable (key, value) VALUES (?, ?)`,
item.Key, encodeUTF16LE(item.Value),
)
require.NoError(t, err)
}
require.NoError(t, db.Close())
}
// encodeUTF16LE is the inverse of extract_storage.go's decodeUTF16LE — it mirrors
// the WebKit encoding so test fixtures round-trip through the extractor.
func encodeUTF16LE(s string) []byte {
u16 := utf16.Encode([]rune(s))
buf := make([]byte, 2*len(u16))
for i, r := range u16 {
binary.LittleEndian.PutUint16(buf[i*2:], r)
}
return buf
}
func mkFile(t *testing.T, parts ...string) {
t.Helper()
path := filepath.Join(parts...)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte("test"), 0o644))
}
// testCollector keeps what an extractor hands it, in order.
type testCollector struct {
records []record.Record
fails []error
}
func (c *testCollector) Add(r record.Record) { c.records = append(c.records, r) }
func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) }
func collected[T any](t *testing.T, c *testCollector) []T {
t.Helper()
got := make([]T, 0, len(c.records))
for _, r := range c.records {
v, ok := any(r).(*T)
require.Truef(t, ok, "collected a %T, want *%T", r, *new(T))
got = append(got, *v)
}
return got
}