refactor: introduce category, record, and export packages (#651)

Later layers speak categories and records, and export needs nothing else.
Ordering rows once in the exporter fixes Firefox history, written least visited first.
This commit is contained in:
Roger authored and GitHub committed 2026-10-26 19:55:19 +08:00
1 parent 9937dbf9fb
commit b04c436a73
97 files changed
+1993 -1646

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
package category
import "fmt"
// Numbering starts at 1, so the zero Category means "none".
type Category int
const (
Password Category = iota + 1
Cookie
Bookmark
History
Download
CreditCard
Extension
LocalStorage
SessionStorage
)
// String's values are the -c values and the output file names, so they cannot change.
func (c Category) String() string {
switch c {
case Password:
return "password"
case Cookie:
return "cookie"
case Bookmark:
return "bookmark"
case History:
return "history"
case Download:
return "download"
case CreditCard:
return "creditcard"
case Extension:
return "extension"
case LocalStorage:
return "localstorage"
case SessionStorage:
return "sessionstorage"
default:
return "unknown"
}
}
func All() []Category {
return []Category{Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage}
}
func Parse(s string) (Category, error) {
for _, c := range All() {
if c.String() == s {
return c, nil
}
}
return 0, fmt.Errorf("unknown category: %q", s)
}
+62
View File
@@ -0,0 +1,62 @@
package category
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestString(t *testing.T) {
tests := []struct {
c Category
want string
}{
{Password, "password"},
{Cookie, "cookie"},
{Bookmark, "bookmark"},
{History, "history"},
{Download, "download"},
{CreditCard, "creditcard"},
{Extension, "extension"},
{LocalStorage, "localstorage"},
{SessionStorage, "sessionstorage"},
{Category(0), "unknown"},
{Category(999), "unknown"},
}
for _, tt := range tests {
assert.Equal(t, tt.want, tt.c.String())
}
}
func TestAll(t *testing.T) {
assert.Equal(t, []Category{
Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage,
}, All())
}
func TestAll_ReturnsFreshSlice(t *testing.T) {
All()[0] = SessionStorage
assert.Equal(t, Password, All()[0])
}
func TestParse_RoundTrip(t *testing.T) {
for _, c := range All() {
got, err := Parse(c.String())
require.NoError(t, err)
assert.Equal(t, c, got)
}
}
func TestParse_Unknown(t *testing.T) {
for _, s := range []string{"", "unknown", "all", "Password", " cookie"} {
got, err := Parse(s)
require.EqualError(t, err, "unknown category: \""+s+"\"")
assert.Zero(t, got)
}
}
func TestZeroIsNone(t *testing.T) {
var c Category
assert.NotContains(t, All(), c)
}
+53
View File
@@ -0,0 +1,53 @@
package export
import (
"strings"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
var sameSiteNone = "no_restriction"
func cookieEditorValue(r record.Record) any {
c, ok := r.(*record.Cookie)
if !ok {
return r
}
var expDate float64
if !c.ExpireAt.IsZero() {
expDate = float64(c.ExpireAt.Unix())
}
sameSite := &c.SameSite
switch c.SameSite {
case "none":
sameSite = &sameSiteNone
case "", "unspecified":
sameSite = nil
}
return cookieEditorEntry{
Domain: c.Host,
ExpirationDate: expDate,
HTTPOnly: c.IsHTTPOnly,
Name: c.Name,
Path: c.Path,
Secure: c.IsSecure,
Value: c.Value,
SameSite: sameSite,
Session: expDate == 0.,
HostOnly: !strings.HasPrefix(c.Host, "."),
}
}
// cookieEditorEntry matches the CookieEditor browser extension's import format.
type cookieEditorEntry struct {
Domain string `json:"domain"`
ExpirationDate float64 `json:"expirationDate,omitempty"`
HTTPOnly bool `json:"httpOnly"`
Name string `json:"name"`
Path string `json:"path"`
Secure bool `json:"secure"`
Value string `json:"value"`
SameSite *string `json:"sameSite"`
Session bool `json:"session"`
HostOnly bool `json:"hostOnly"`
}
+40
View File
@@ -0,0 +1,40 @@
package export
import (
"encoding/csv"
"fmt"
"io"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// utf8BOM is written at the start of CSV files for Excel compatibility.
var utf8BOM = []byte{0xEF, 0xBB, 0xBF}
type csvEncoder struct {
w io.Writer
rows *csv.Writer
header bool
}
func newCSVEncoder(w io.Writer) *csvEncoder {
return &csvEncoder{w: w, rows: csv.NewWriter(w)}
}
func (e *csvEncoder) encode(r record.Record) error {
if !e.header {
if _, err := e.w.Write(utf8BOM); err != nil {
return fmt.Errorf("write BOM: %w", err)
}
if err := e.rows.Write(structCSVHeader(r)); err != nil {
return err
}
e.header = true
}
return e.rows.Write(structCSVRow(r))
}
func (e *csvEncoder) end() error {
e.rows.Flush()
return e.rows.Error()
}
+55
View File
@@ -0,0 +1,55 @@
package export
import (
"fmt"
"io"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// The zero Format is JSON, the -f default.
type Format int
const (
JSON Format = iota
CSV
CookieEditor
)
func ParseFormat(s string) (Format, error) {
switch s {
case "json":
return JSON, nil
case "csv":
return CSV, nil
case "cookie-editor":
return CookieEditor, nil
default:
return 0, fmt.Errorf("unsupported format: %s", s)
}
}
func (f Format) ext() string {
if f == CSV {
return "csv"
}
return "json"
}
// encoder writes one category's file; it frames the document itself so that every Write can append to it.
type encoder interface {
encode(r record.Record) error
end() error
}
func newEncoder(w io.Writer, f Format, c category.Category) encoder {
switch {
case f == CSV:
return newCSVEncoder(w)
case f == CookieEditor && c == category.Cookie:
return &jsonEncoder{w: w, value: cookieEditorValue}
default:
return &jsonEncoder{w: w, escapeHTML: true}
}
}
+53
View File
@@ -0,0 +1,53 @@
package export
import (
"bytes"
"encoding/json"
"io"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
const jsonIndent = " "
// jsonEncoder writes the bytes a single indented Encode of the whole slice would produce, one element at a time.
type jsonEncoder struct {
w io.Writer
escapeHTML bool
value func(record.Record) any
n int
}
func (e *jsonEncoder) encode(r record.Record) error {
var v any = r
if e.value != nil {
v = e.value(r)
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(e.escapeHTML)
enc.SetIndent(jsonIndent, jsonIndent)
if err := enc.Encode(v); err != nil {
return err
}
sep := ",\n" + jsonIndent
if e.n == 0 {
sep = "[\n" + jsonIndent
}
e.n++
if _, err := io.WriteString(e.w, sep); err != nil {
return err
}
_, err := e.w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
return err
}
func (e *jsonEncoder) end() error {
closing := "\n]\n"
if e.n == 0 {
closing = "[]\n"
}
_, err := io.WriteString(e.w, closing)
return err
}
+63
View File
@@ -0,0 +1,63 @@
package export
import (
"bytes"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
func encodeOnce(t *testing.T, v any, escapeHTML bool) string {
t.Helper()
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetIndent("", jsonIndent)
enc.SetEscapeHTML(escapeHTML)
require.NoError(t, enc.Encode(v))
return buf.String()
}
func encodeFramed(t *testing.T, e *jsonEncoder, records []record.Record) string {
t.Helper()
var buf bytes.Buffer
e.w = &buf
for _, r := range records {
require.NoError(t, e.encode(r))
}
require.NoError(t, e.end())
return buf.String()
}
func TestJSONEncoder_MatchesOneEncodeOfTheSlice(t *testing.T) {
cookies := []record.Record{
&record.Cookie{
Browser: "Chrome", Profile: "Default", Host: ".example.com", Path: "/", Name: "q",
Value: `https://shop.example.com/cart?item=42&qty=<3> "日本語" ` + "\u2028", CreatedAt: testTime, SameSite: "none",
},
&record.Cookie{Browser: "Chrome", Profile: "Default", Host: "example.com", Name: "empty", ExpireAt: testTime},
}
t.Run("json escapes HTML", func(t *testing.T) {
got := encodeFramed(t, &jsonEncoder{escapeHTML: true}, cookies)
assert.Equal(t, encodeOnce(t, cookies, true), got)
assert.Contains(t, got, `\u0026qty=\u003c3\u003e`)
})
t.Run("cookie-editor does not", func(t *testing.T) {
entries := make([]any, 0, len(cookies))
for _, c := range cookies {
entries = append(entries, cookieEditorValue(c))
}
got := encodeFramed(t, &jsonEncoder{value: cookieEditorValue}, cookies)
assert.Equal(t, encodeOnce(t, entries, false), got)
assert.Contains(t, got, `&qty=<3>`)
})
t.Run("one record", func(t *testing.T) {
assert.Equal(t, encodeOnce(t, cookies[:1], true), encodeFramed(t, &jsonEncoder{escapeHTML: true}, cookies[:1]))
})
}
+44
View File
@@ -0,0 +1,44 @@
package export
import (
"sort"
"time"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
// Stable, so ties and keyless categories keep source order; Safari's bookmarks and downloads have no timestamp to sort by.
func sortRecords(records []record.Record) {
sort.SliceStable(records, func(i, j int) bool {
return keyOf(records[i]).before(keyOf(records[j]))
})
}
type sortKey struct {
visits int
at time.Time
}
func keyOf(r record.Record) sortKey {
switch r := r.(type) {
case *record.Login:
return sortKey{at: r.CreatedAt}
case *record.Cookie:
return sortKey{at: r.CreatedAt}
case *record.Bookmark:
return sortKey{at: r.CreatedAt}
case *record.Download:
return sortKey{at: r.StartTime}
case *record.History:
return sortKey{visits: r.VisitCount}
default:
return sortKey{}
}
}
func (k sortKey) before(o sortKey) bool {
if k.visits != o.visits {
return k.visits > o.visits
}
return k.at.After(o.at)
}
+116
View File
@@ -0,0 +1,116 @@
package export
import (
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
const tiedRecords = 20
func day(d int) time.Time { return time.Date(2026, 1, d, 0, 0, 0, 0, time.UTC) }
func TestSortRecords_NewestFirst(t *testing.T) {
logins := []record.Record{
&record.Login{URL: "old", CreatedAt: day(1)},
&record.Login{URL: "unset"},
&record.Login{URL: "new", CreatedAt: day(3)},
}
sortRecords(logins)
assert.Equal(t, []string{"new", "old", "unset"}, urlsOf(t, logins))
downloads := []record.Record{
&record.Download{URL: "older", StartTime: day(1)},
&record.Download{URL: "newer", StartTime: day(2)},
}
sortRecords(downloads)
assert.Equal(t, []string{"newer", "older"}, urlsOf(t, downloads))
}
// Firefox used to write its history least visited first; the exporter now orders history the same for every browser.
func TestSortRecords_HistoryMostVisitedFirst(t *testing.T) {
histories := []record.Record{
&record.History{URL: "once", VisitCount: 1},
&record.History{URL: "often", VisitCount: 42},
&record.History{URL: "twice", VisitCount: 2},
}
sortRecords(histories)
assert.Equal(t, []string{"often", "twice", "once"}, urlsOf(t, histories))
}
func TestSortRecords_TiesKeepSourceOrder(t *testing.T) {
logins := make([]record.Record, 0, tiedRecords)
for i := 0; i < tiedRecords; i++ {
store := record.StoreLocal
if i >= tiedRecords/2 {
store = record.StoreAccount
}
logins = append(logins, &record.Login{URL: strconv.Itoa(i), CreatedAt: day(2), Store: store})
}
want := append([]record.Record(nil), logins...)
sortRecords(logins)
assert.Equal(t, want, logins, "equal timestamps keep emission order, so local rows stay before account rows")
bookmarks := make([]record.Record, 0, tiedRecords)
for i := 0; i < tiedRecords; i++ {
bookmarks = append(bookmarks, &record.Bookmark{ID: int64(tiedRecords - i)})
}
want = append([]record.Record(nil), bookmarks...)
sortRecords(bookmarks)
assert.Equal(t, want, bookmarks, "bookmarks without a creation time keep their tree order")
}
// Interleaved timestamps make the sort move records; an unstable sort would then reorder the ties it moves.
func TestSortRecords_IsStable(t *testing.T) {
logins := make([]record.Record, 0, tiedRecords)
var newer, older []string
for i := 0; i < tiedRecords; i++ {
url := strconv.Itoa(i)
created := day(1)
if i%2 == 1 {
created = day(2)
newer = append(newer, url)
} else {
older = append(older, url)
}
logins = append(logins, &record.Login{URL: url, CreatedAt: created})
}
sortRecords(logins)
assert.Equal(t, append(newer, older...), urlsOf(t, logins))
}
func TestSortRecords_KeylessCategoriesKeepSourceOrder(t *testing.T) {
records := make([]record.Record, 0, 4*tiedRecords)
for i := 0; i < tiedRecords; i++ {
id := strconv.Itoa(i)
records = append(records,
&record.CreditCard{GUID: id}, &record.Extension{ID: id},
&record.LocalStorage{Key: id}, &record.SessionStorage{Key: id},
)
}
want := append([]record.Record(nil), records...)
sortRecords(records)
assert.Equal(t, want, records)
}
func urlsOf(t *testing.T, records []record.Record) []string {
t.Helper()
urls := make([]string, 0, len(records))
for _, r := range records {
switch r := r.(type) {
case *record.Login:
urls = append(urls, r.URL)
case *record.Download:
urls = append(urls, r.URL)
case *record.History:
urls = append(urls, r.URL)
default:
t.Fatalf("unexpected record %T", r)
}
}
return urls
}
+89
View File
@@ -0,0 +1,89 @@
package export
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
var timeType = reflect.TypeOf(time.Time{})
// structCSVHeader extracts CSV column names from a struct's csv tags.
func structCSVHeader(v any) []string {
t := reflect.Indirect(reflect.ValueOf(v)).Type()
headers := make([]string, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
name := tagName(t.Field(i), "csv")
if name == "" {
continue
}
headers = append(headers, name)
}
return headers
}
// structCSVRow converts a struct's field values to CSV string values,
// including only fields that have a csv tag.
func structCSVRow(v any) []string {
val := reflect.Indirect(reflect.ValueOf(v))
t := val.Type()
row := make([]string, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
if tagName(t.Field(i), "csv") == "" {
continue
}
row = append(row, fieldToString(val.Field(i)))
}
return row
}
// tagName extracts the tag value for the given key from a struct field.
// Uses Lookup (not Get) to distinguish "no tag" from "empty tag".
// Returns "" if the tag is absent, empty, or "-".
func tagName(f reflect.StructField, key string) string {
tag, ok := f.Tag.Lookup(key)
if !ok || tag == "-" {
return ""
}
if idx := strings.IndexByte(tag, ','); idx != -1 {
tag = tag[:idx]
}
if tag == "" {
return ""
}
return tag
}
func fieldToString(v reflect.Value) string {
// Check time.Time before kind switch since it's a struct.
if v.Type() == timeType {
t, _ := v.Interface().(time.Time)
return formatTime(t)
}
switch v.Kind() {
case reflect.String:
return v.String()
case reflect.Bool:
return formatBool(v.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
default:
return fmt.Sprintf("%v", v.Interface())
}
}
func formatTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format(time.RFC3339)
}
func formatBool(b bool) string {
if b {
return "true"
}
return "false"
}
+126
View File
@@ -0,0 +1,126 @@
package export
import (
"reflect"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
var refTime = time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC)
// allRecordTypes lists every record type. If a new record type is added, it must be included here.
var allRecordTypes = []record.Record{
&record.Login{},
&record.Cookie{},
&record.Bookmark{},
&record.History{},
&record.Download{},
&record.CreditCard{},
&record.Extension{},
&record.LocalStorage{},
&record.SessionStorage{},
}
// A field without a csv tag would be silently left out of the CSV output.
func TestAllRecordFieldsHaveCSVTag(t *testing.T) {
for _, r := range allRecordTypes {
et := reflect.TypeOf(r).Elem()
t.Run(et.Name(), func(t *testing.T) {
for i := 0; i < et.NumField(); i++ {
f := et.Field(i)
if !f.IsExported() {
continue
}
_, ok := f.Tag.Lookup("csv")
assert.True(t, ok, "field %s.%s missing csv tag", et.Name(), f.Name)
}
})
}
}
func TestStructCSVHeader(t *testing.T) {
tests := []struct {
name string
record record.Record
expect []string
}{
{"Login", &record.Login{}, []string{"browser", "profile", "url", "username", "password", "created_at", "store"}},
{"Cookie", &record.Cookie{}, []string{
"browser", "profile", "host", "path", "name", "value",
"is_secure", "is_http_only", "has_expire", "is_persistent", "expire_at", "created_at", "same_site",
}},
{"Bookmark", &record.Bookmark{}, []string{"browser", "profile", "id", "name", "type", "url", "folder", "created_at"}},
{"History", &record.History{}, []string{"browser", "profile", "url", "title", "visit_count", "last_visit"}},
{"Download", &record.Download{}, []string{
"browser", "profile", "url", "target_path", "mime_type", "total_bytes", "start_time", "end_time",
}},
{"CreditCard", &record.CreditCard{}, []string{
"browser", "profile", "guid", "name", "number", "exp_month", "exp_year", "nick_name", "address", "cvc", "comment",
}},
{"LocalStorage", &record.LocalStorage{}, []string{"browser", "profile", "is_meta", "url", "key", "value"}},
{"SessionStorage", &record.SessionStorage{}, []string{"browser", "profile", "is_meta", "url", "key", "value"}},
{"Extension", &record.Extension{}, []string{
"browser", "profile", "name", "id", "description", "version", "homepage_url", "enabled",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expect, structCSVHeader(tt.record))
})
}
}
func TestStructCSVRow(t *testing.T) {
tests := []struct {
name string
record record.Record
expect []string
}{
{
"Login",
&record.Login{
Browser: "Chrome", Profile: "Default",
URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: refTime, Store: record.StoreLocal,
},
[]string{"Chrome", "Default", "https://example.com", "alice", "secret", "2026-01-15T10:30:00Z", "local"},
},
{
"Cookie",
&record.Cookie{
Host: ".example.com", Path: "/", Name: "session", Value: "abc",
IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: false,
ExpireAt: refTime, CreatedAt: refTime,
},
[]string{"", "", ".example.com", "/", "session", "abc", "true", "true", "true", "false", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z", ""},
},
{
"History_int",
&record.History{URL: "https://a.com", Title: "A", VisitCount: 42, LastVisit: refTime},
[]string{"", "", "https://a.com", "A", "42", "2026-01-15T10:30:00Z"},
},
{
"Download_int64",
&record.Download{URL: "https://a.com", TargetPath: "/tmp/f", MimeType: "text/plain", TotalBytes: 1024, StartTime: refTime, EndTime: refTime},
[]string{"", "", "https://a.com", "/tmp/f", "text/plain", "1024", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z"},
},
{
"Extension_bool",
&record.Extension{Name: "ext", ID: "abc", Description: "desc", Version: "1.0", HomepageURL: "https://x.com", Enabled: true},
[]string{"", "", "ext", "abc", "desc", "1.0", "https://x.com", "true"},
},
{
"zero_time",
&record.Login{URL: "https://a.com"},
[]string{"", "", "https://a.com", "", "", "", ""},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expect, structCSVRow(tt.record))
})
}
}
+117
View File
@@ -0,0 +1,117 @@
package export
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/log"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
type Writer struct {
dir string
format Format
files map[category.Category]*categoryFile
failed bool
}
type categoryFile struct {
name string
file *os.File
buf *bufio.Writer
enc encoder
count int
}
func NewWriter(dir string, f Format) (*Writer, error) {
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, fmt.Errorf("create output dir: %w", err)
}
return &Writer{dir: dir, format: f, files: make(map[category.Category]*categoryFile)}, nil
}
// Write reorders records in place.
func (w *Writer) Write(c category.Category, records []record.Record) error {
if err := w.write(c, records); err != nil {
w.failed = true
return err
}
return nil
}
func (w *Writer) write(c category.Category, records []record.Record) error {
if len(records) == 0 {
return nil
}
for _, r := range records {
if r.Category() != c {
return fmt.Errorf("%T is not a %s record", r, c)
}
}
cf, err := w.open(c)
if err != nil {
return err
}
sortRecords(records)
for _, r := range records {
if err := cf.enc.encode(r); err != nil {
return fmt.Errorf("write %s: %w", cf.name, err)
}
cf.count++
}
return nil
}
// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them.
func (w *Writer) Close() error {
var errs []error
for _, c := range category.All() {
if cf, ok := w.files[c]; ok {
errs = append(errs, cf.close())
}
}
if err := errors.Join(errs...); err != nil {
return err
}
if w.failed || len(w.files) == 0 {
return nil
}
fmt.Fprintln(os.Stderr)
log.Infof("Exported to %s/", w.dir)
for _, c := range category.All() {
if cf, ok := w.files[c]; ok {
log.Infof(" %-24s %d entries", cf.name, cf.count)
}
}
return nil
}
func (w *Writer) open(c category.Category) (*categoryFile, error) {
if cf, ok := w.files[c]; ok {
return cf, nil
}
name := c.String() + "." + w.format.ext()
f, err := os.OpenFile(filepath.Join(w.dir, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return nil, fmt.Errorf("create %s: %w", name, err)
}
buf := bufio.NewWriter(f)
cf := &categoryFile{name: name, file: f, buf: buf, enc: newEncoder(buf, w.format, c)}
w.files[c] = cf
return cf, nil
}
func (cf *categoryFile) close() error {
err := cf.enc.end()
if err == nil {
err = cf.buf.Flush()
}
if err = errors.Join(err, cf.file.Close()); err != nil {
return fmt.Errorf("write %s: %w", cf.name, err)
}
return nil
}
+358
View File
@@ -0,0 +1,358 @@
package export
import (
"bytes"
"encoding/csv"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
var testTime = time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC)
type extraction struct {
c category.Category
records []record.Record
}
func chromeExtractions() []extraction {
return []extraction{
{category.Password, []record.Record{&record.Login{
Browser: "Chrome", Profile: "Default",
URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: testTime, Store: record.StoreAccount,
}}},
{category.Cookie, []record.Record{&record.Cookie{
Browser: "Chrome", Profile: "Default",
Host: ".example.com", Path: "/", Name: "session", Value: "abc123",
IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true,
ExpireAt: testTime, CreatedAt: testTime,
}}},
{category.History, []record.Record{&record.History{
Browser: "Chrome", Profile: "Default",
URL: "https://example.com", Title: "Example", VisitCount: 5, LastVisit: testTime,
}}},
}
}
func firefoxExtractions() []extraction {
return []extraction{
{category.Password, []record.Record{&record.Login{
Browser: "Firefox", Profile: "abc123",
URL: "https://reddit.com", Username: "bob", Password: "hunter2", CreatedAt: testTime, Store: record.StoreLocal,
}}},
{category.Cookie, []record.Record{&record.Cookie{
Browser: "Firefox", Profile: "abc123",
Host: ".reddit.com", Path: "/", Name: "token", Value: "xyz789",
IsSecure: true, IsHTTPOnly: false, ExpireAt: testTime, CreatedAt: testTime,
}}},
}
}
func writeAll(t *testing.T, dir string, f Format, extractions ...extraction) {
t.Helper()
w, err := NewWriter(dir, f)
require.NoError(t, err)
for _, e := range extractions {
require.NoError(t, w.Write(e.c, e.records))
}
require.NoError(t, w.Close())
}
// --- Format ---
func TestParseFormat(t *testing.T) {
tests := []struct {
in string
want Format
}{
{"json", JSON},
{"csv", CSV},
{"cookie-editor", CookieEditor},
}
for _, tt := range tests {
got, err := ParseFormat(tt.in)
require.NoError(t, err)
assert.Equal(t, tt.want, got)
}
_, err := ParseFormat("unknown")
require.EqualError(t, err, "unsupported format: unknown")
}
func TestFormat_ZeroIsJSON(t *testing.T) {
var f Format
assert.Equal(t, JSON, f)
}
func TestNewWriter_CreatesDir(t *testing.T) {
dir := filepath.Join(t.TempDir(), "nested", "results")
_, err := NewWriter(dir, JSON)
require.NoError(t, err)
assert.DirExists(t, dir)
}
// --- CSV output ---
func TestWrite_CSV_Password(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CSV, append(chromeExtractions(), firefoxExtractions()...)...)
records := readCSV(t, filepath.Join(dir, "password.csv"))
require.Len(t, records, 3) // header + 2 rows
assert.Equal(t, []string{"browser", "profile", "url", "username", "password", "created_at", "store"}, records[0])
assert.Equal(t, []string{"Chrome", "Default", "https://example.com", "alice", "secret", "2026-01-15T10:30:00Z", "account"}, records[1])
assert.Equal(t, []string{"Firefox", "abc123", "https://reddit.com", "bob", "hunter2", "2026-01-15T10:30:00Z", "local"}, records[2])
}
func TestWrite_CSV_Cookie(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CSV, chromeExtractions()...)
records := readCSV(t, filepath.Join(dir, "cookie.csv"))
require.Len(t, records, 2)
assert.Equal(t,
[]string{
"browser", "profile", "host", "path", "name", "value",
"is_secure", "is_http_only", "has_expire", "is_persistent", "expire_at", "created_at", "same_site",
},
records[0],
)
assert.Equal(t,
[]string{
"Chrome", "Default", ".example.com", "/", "session", "abc123",
"true", "true", "true", "true", "2026-01-15T10:30:00Z", "2026-01-15T10:30:00Z", "",
},
records[1],
)
}
func TestWrite_CSV_History(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CSV, chromeExtractions()...)
records := readCSV(t, filepath.Join(dir, "history.csv"))
require.Len(t, records, 2)
assert.Equal(t, []string{"browser", "profile", "url", "title", "visit_count", "last_visit"}, records[0])
assert.Equal(t, []string{"Chrome", "Default", "https://example.com", "Example", "5", "2026-01-15T10:30:00Z"}, records[1])
}
func TestWrite_CSV_UTF8BOM(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CSV, append(chromeExtractions(), firefoxExtractions()...)...)
raw, err := os.ReadFile(filepath.Join(dir, "password.csv"))
require.NoError(t, err)
require.GreaterOrEqual(t, len(raw), 3)
assert.Equal(t, utf8BOM, raw[:3], "CSV should start with UTF-8 BOM")
assert.Equal(t, 1, bytes.Count(raw, utf8BOM), "one BOM however many writes")
}
// --- JSON output ---
func TestWrite_JSON_Password(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, JSON, append(chromeExtractions(), firefoxExtractions()...)...)
type pwJSON struct {
Browser string `json:"browser"`
Profile string `json:"profile"`
URL string `json:"url"`
Username string `json:"username"`
Password string `json:"password"`
CreatedAt time.Time `json:"created_at"`
}
var rows []pwJSON
readJSON(t, filepath.Join(dir, "password.json"), &rows)
require.Len(t, rows, 2)
assert.Equal(t, pwJSON{
Browser: "Chrome", Profile: "Default",
URL: "https://example.com", Username: "alice", Password: "secret", CreatedAt: testTime,
}, rows[0])
assert.Equal(t, pwJSON{
Browser: "Firefox", Profile: "abc123",
URL: "https://reddit.com", Username: "bob", Password: "hunter2", CreatedAt: testTime,
}, rows[1])
}
func TestWrite_JSON_Cookie(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, JSON, chromeExtractions()...)
type ckJSON struct {
Browser string `json:"browser"`
Profile string `json:"profile"`
Host string `json:"host"`
Path string `json:"path"`
Name string `json:"name"`
Value string `json:"value"`
IsSecure bool `json:"is_secure"`
IsHTTPOnly bool `json:"is_http_only"`
HasExpire bool `json:"has_expire"`
IsPersistent bool `json:"is_persistent"`
ExpireAt time.Time `json:"expire_at"`
CreatedAt time.Time `json:"created_at"`
}
var rows []ckJSON
readJSON(t, filepath.Join(dir, "cookie.json"), &rows)
require.Len(t, rows, 1)
assert.Equal(t, ckJSON{
Browser: "Chrome", Profile: "Default",
Host: ".example.com", Path: "/", Name: "session", Value: "abc123",
IsSecure: true, IsHTTPOnly: true, HasExpire: true, IsPersistent: true,
ExpireAt: testTime, CreatedAt: testTime,
}, rows[0])
}
func TestWrite_JSON_NoBOM(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, JSON, chromeExtractions()...)
raw, err := os.ReadFile(filepath.Join(dir, "password.json"))
require.NoError(t, err)
if len(raw) >= 3 {
assert.NotEqual(t, utf8BOM, raw[:3], "JSON should NOT have BOM")
}
}
// --- CookieEditor output ---
func TestWrite_CookieEditor(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CookieEditor, chromeExtractions()...)
var entries []cookieEditorEntry
readJSON(t, filepath.Join(dir, "cookie.json"), &entries)
require.Len(t, entries, 1)
assert.Equal(t, cookieEditorEntry{
Domain: ".example.com",
Name: "session",
Value: "abc123",
Path: "/",
Secure: true,
HTTPOnly: true,
ExpirationDate: float64(testTime.Unix()),
}, entries[0])
}
func TestWrite_CookieEditor_FallbackJSON(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CookieEditor, extraction{category.Password, []record.Record{&record.Login{URL: "https://a.com"}}})
// non-cookie categories fall back to standard JSON format
_, err := os.Stat(filepath.Join(dir, "password.json"))
assert.False(t, os.IsNotExist(err), "password.json should be created via JSON fallback")
}
// --- File creation ---
func TestWrite_EmptyCategoryNoFile(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CSV,
extraction{category.Password, []record.Record{&record.Login{URL: "https://a.com"}}},
extraction{category.Cookie, nil},
)
assert.FileExists(t, filepath.Join(dir, "password.csv"))
_, err := os.Stat(filepath.Join(dir, "cookie.csv"))
assert.True(t, os.IsNotExist(err))
_, err = os.Stat(filepath.Join(dir, "history.csv"))
assert.True(t, os.IsNotExist(err))
}
func TestWrite_NoData(t *testing.T) {
dir := t.TempDir()
writeAll(t, dir, CSV)
entries, err := os.ReadDir(dir)
require.NoError(t, err)
assert.Empty(t, entries, "no files should be created when no data added")
}
// --- Appending extractions ---
func TestWrite_AppendsExtractionsInWriteOrder(t *testing.T) {
dir := t.TempDir()
older := &record.History{Browser: "Chrome", Profile: "Default", URL: "https://a.example", VisitCount: 1}
busier := &record.History{Browser: "Chrome", Profile: "Profile 1", URL: "https://b.example", VisitCount: 99}
writeAll(t, dir, JSON,
extraction{category.History, []record.Record{older}},
extraction{category.History, []record.Record{busier}},
)
var rows []record.History
readJSON(t, filepath.Join(dir, "history.json"), &rows)
assert.Equal(t, []record.History{*older, *busier}, rows, "each extraction is sorted on its own, then appended")
}
// --- Error paths ---
func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) {
dir := t.TempDir()
w, err := NewWriter(dir, JSON)
require.NoError(t, err)
require.EqualError(t, w.Write(category.Cookie, []record.Record{&record.Login{}}), "*record.Login is not a cookie record")
require.NoError(t, w.Close())
entries, err := os.ReadDir(dir)
require.NoError(t, err)
assert.Empty(t, entries)
}
// A failed Write must not cost the files already written: Close still completes them.
func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) {
dir := t.TempDir()
w, err := NewWriter(dir, JSON)
require.NoError(t, err)
require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://kept.example"}}))
beyondJSON := time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)
require.Error(t, w.Write(category.Cookie, []record.Record{&record.Cookie{Host: "bad.example", ExpireAt: beyondJSON}}))
require.NoError(t, w.Close())
var logins []record.Login
readJSON(t, filepath.Join(dir, "password.json"), &logins)
require.Len(t, logins, 1)
assert.Equal(t, "https://kept.example", logins[0].URL)
var cookies []record.Cookie
readJSON(t, filepath.Join(dir, "cookie.json"), &cookies)
assert.Empty(t, cookies)
}
// --- helpers ---
func readCSV(t *testing.T, path string) [][]string {
t.Helper()
raw, err := os.ReadFile(path)
require.NoError(t, err)
// Skip UTF-8 BOM if present
content := string(raw)
if strings.HasPrefix(content, string(utf8BOM)) {
content = content[len(utf8BOM):]
}
reader := csv.NewReader(strings.NewReader(content))
records, err := reader.ReadAll()
require.NoError(t, err)
return records
}
func readJSON(t *testing.T, path string, v any) {
t.Helper()
raw, err := os.ReadFile(path)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(raw, v))
}
+149
View File
@@ -0,0 +1,149 @@
package record
import (
"time"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
// Record is sealed by the unexported stamp, so only this package's types are records.
type Record interface {
Category() category.Category
stamp(browser, profile string)
}
// Stamp is exported because the sealing method stamp cannot be called from other packages.
func Stamp(r Record, browser, profile string) {
r.stamp(browser, profile)
}
// Named Login, not Password: the row holds a URL and a user name as well as the password.
type Login struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
URL string `json:"url" csv:"url"`
Username string `json:"username" csv:"username"`
Password string `json:"password" csv:"password"`
CreatedAt time.Time `json:"created_at" csv:"created_at"`
Store Store `json:"store" csv:"store"`
}
// Store names the Chromium login database a Login came from; a credential kept in both is exported twice.
type Store string
const (
StoreLocal Store = "local" // Login Data
StoreAccount Store = "account" // Login Data For Account
)
type Cookie struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
Host string `json:"host" csv:"host"`
Path string `json:"path" csv:"path"`
Name string `json:"name" csv:"name"`
Value string `json:"value" csv:"value"`
IsSecure bool `json:"is_secure" csv:"is_secure"`
IsHTTPOnly bool `json:"is_http_only" csv:"is_http_only"`
HasExpire bool `json:"has_expire" csv:"has_expire"`
IsPersistent bool `json:"is_persistent" csv:"is_persistent"`
ExpireAt time.Time `json:"expire_at" csv:"expire_at"`
CreatedAt time.Time `json:"created_at" csv:"created_at"`
SameSite string `json:"same_site" csv:"same_site"`
}
type Bookmark struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
ID int64 `json:"id" csv:"id"`
Name string `json:"name" csv:"name"`
Type string `json:"type" csv:"type"`
URL string `json:"url" csv:"url"`
Folder string `json:"folder" csv:"folder"`
CreatedAt time.Time `json:"created_at" csv:"created_at"`
}
type History struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
URL string `json:"url" csv:"url"`
Title string `json:"title" csv:"title"`
VisitCount int `json:"visit_count" csv:"visit_count"`
LastVisit time.Time `json:"last_visit" csv:"last_visit"`
}
type Download struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
URL string `json:"url" csv:"url"`
TargetPath string `json:"target_path" csv:"target_path"`
MimeType string `json:"mime_type" csv:"mime_type"`
TotalBytes int64 `json:"total_bytes" csv:"total_bytes"`
StartTime time.Time `json:"start_time" csv:"start_time"`
EndTime time.Time `json:"end_time" csv:"end_time"`
}
// CreditCard's CVC and Comment are Yandex-specific; Chromium leaves them empty.
type CreditCard struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
GUID string `json:"guid" csv:"guid"`
Name string `json:"name" csv:"name"`
Number string `json:"number" csv:"number"`
ExpMonth string `json:"exp_month" csv:"exp_month"`
ExpYear string `json:"exp_year" csv:"exp_year"`
NickName string `json:"nick_name" csv:"nick_name"`
Address string `json:"address" csv:"address"`
CVC string `json:"cvc" csv:"cvc"`
Comment string `json:"comment" csv:"comment"`
}
type Extension struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
Name string `json:"name" csv:"name"`
ID string `json:"id" csv:"id"`
Description string `json:"description" csv:"description"`
Version string `json:"version" csv:"version"`
HomepageURL string `json:"homepage_url" csv:"homepage_url"`
Enabled bool `json:"enabled" csv:"enabled"`
}
type LocalStorage struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
IsMeta bool `json:"is_meta" csv:"is_meta"`
URL string `json:"url" csv:"url"`
Key string `json:"key" csv:"key"`
Value string `json:"value" csv:"value"`
}
// SessionStorage repeats LocalStorage's fields so that each record type belongs to exactly one category.
type SessionStorage struct {
Browser string `json:"browser" csv:"browser"`
Profile string `json:"profile" csv:"profile"`
IsMeta bool `json:"is_meta" csv:"is_meta"`
URL string `json:"url" csv:"url"`
Key string `json:"key" csv:"key"`
Value string `json:"value" csv:"value"`
}
func (r *Login) Category() category.Category { return category.Password }
func (r *Cookie) Category() category.Category { return category.Cookie }
func (r *Bookmark) Category() category.Category { return category.Bookmark }
func (r *History) Category() category.Category { return category.History }
func (r *Download) Category() category.Category { return category.Download }
func (r *CreditCard) Category() category.Category { return category.CreditCard }
func (r *Extension) Category() category.Category { return category.Extension }
func (r *LocalStorage) Category() category.Category { return category.LocalStorage }
func (r *SessionStorage) Category() category.Category { return category.SessionStorage }
func (r *Login) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *Cookie) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *Bookmark) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *History) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *Download) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *CreditCard) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *Extension) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *LocalStorage) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
func (r *SessionStorage) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile }
+89
View File
@@ -0,0 +1,89 @@
package record
import (
"reflect"
"strings"
"testing"
"unicode"
"github.com/stretchr/testify/assert"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
func allRecords() map[category.Category]Record {
return map[category.Category]Record{
category.Password: &Login{},
category.Cookie: &Cookie{},
category.Bookmark: &Bookmark{},
category.History: &History{},
category.Download: &Download{},
category.CreditCard: &CreditCard{},
category.Extension: &Extension{},
category.LocalStorage: &LocalStorage{},
category.SessionStorage: &SessionStorage{},
}
}
func TestCategory_OneRecordTypePerCategory(t *testing.T) {
records := allRecords()
assert.Len(t, records, len(category.All()))
for _, c := range category.All() {
r, ok := records[c]
if assert.Truef(t, ok, "no record type for %s", c) {
assert.Equalf(t, c, r.Category(), "%T", r)
}
}
}
func TestStamp(t *testing.T) {
for _, r := range allRecords() {
Stamp(r, "Microsoft Edge", "Profile 1")
v := reflect.ValueOf(r).Elem()
assert.Equalf(t, "Microsoft Edge", v.FieldByName("Browser").String(), "%T", r)
assert.Equalf(t, "Profile 1", v.FieldByName("Profile").String(), "%T", r)
}
}
// The tags are the output's field names and column headers, so they stay snake_case(field name) and lead with the stamp.
func TestTags_AreSnakeCaseFieldNames(t *testing.T) {
for _, r := range allRecords() {
typ := reflect.TypeOf(r).Elem()
assert.Equalf(t, "Browser", typ.Field(0).Name, "%s", typ)
assert.Equalf(t, "Profile", typ.Field(1).Name, "%s", typ)
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
want := snakeCase(f.Name)
assert.Equalf(t, want, f.Tag.Get("json"), "%s.%s json tag", typ, f.Name)
assert.Equalf(t, want, f.Tag.Get("csv"), "%s.%s csv tag", typ, f.Name)
}
}
}
func snakeCase(name string) string {
runes := []rune(name)
var b strings.Builder
for i, r := range runes {
if i > 0 && unicode.IsUpper(r) {
prevLower := unicode.IsLower(runes[i-1])
acronymEnds := unicode.IsUpper(runes[i-1]) && i+1 < len(runes) && unicode.IsLower(runes[i+1])
if prevLower || acronymEnds {
b.WriteByte('_')
}
}
b.WriteRune(unicode.ToLower(r))
}
return b.String()
}
func TestSnakeCase(t *testing.T) {
for name, want := range map[string]string{
"URL": "url",
"IsHTTPOnly": "is_http_only",
"HomepageURL": "homepage_url",
"NickName": "nick_name",
"GUID": "guid",
} {
assert.Equal(t, want, snakeCase(name))
}
}