store

package
v0.1.0-alpha.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store holds every persistent (or deliberately non-persistent) piece of browser data: history, bookmarks, downloads, settings, session, site permissions, top sites and usage stats.

Storage format: one append-friendly JSONL log per collection (a torn last line after a crash is skipped at load) plus atomic whole-file snapshots (write temp, fsync, rename) for small documents. Everything is pure Go, loaded into memory at start-up and indexed there. An incognito profile uses MemBackend and never touches the file system.

Index

Constants

View Source
const (
	FolderRoot  = "root"
	FolderBar   = "bar"
	FolderOther = "other"
)

Well-known folder ids.

View Source
const (
	DLProgress = "progress"
	DLPaused   = "paused"
	DLDone     = "done"
	DLCanceled = "canceled"
	DLError    = "error"
)

Download states.

View Source
const (
	PermNotifications = "notifications"
	PermPeriodicSync  = "periodic-background-sync"
	PermClipboardRead = "clipboard-read"
)

Permission names the site settings keep (they match the engine's names).

View Source
const (
	DismissLimit  = 3
	EmbargoLength = 7 * 24 * time.Hour
)

Quiet-UI rules: a site whose prompt the user dismisses this many times in a row stops being asked for a while.

View Source
const MB = 1 << 20

MB is one megabyte as the budget counts it.

View Source
const (
	SettingsVersion = 3
)

Variables

View Source
var Schema = []Spec{
	{Key: "theme", Kind: KEnum, Default: "system", Enum: []string{"system", "light", "dark"}, Group: "appearance"},
	{Key: "density", Kind: KEnum, Default: "comfortable", Enum: []string{"comfortable", "compact"}, Group: "appearance"},
	{Key: "bookmarks.bar", Kind: KBool, Default: false, Group: "appearance"},
	{Key: "sidebar.open", Kind: KBool, Default: false, Group: "agent"},
	{Key: "sidebar.width", Kind: KInt, Default: 380, Min: 320, Max: 560, Group: "agent"},
	{Key: "agent.mode", Kind: KEnum, Default: "ask", Enum: []string{"ask", "agent"}, Group: "agent"},
	{Key: "agent.latencyStrip", Kind: KBool, Default: true, Group: "agent"},
	{Key: "agent.sources.page", Kind: KBool, Default: true, Group: "agent"},
	{Key: "agent.sources.web", Kind: KBool, Default: false, Group: "agent"},
	{Key: "agent.confirmations", Kind: KBool, Default: true, Group: "agent"},
	{Key: "agent.visibilityDefault", Kind: KEnum, Default: "ask", Enum: []string{"allowed", "blocked", "ask"}, Group: "agent"},
	{Key: "privacy.trackers", Kind: KEnum, Default: "standard", Enum: []string{"standard", "strict", "off"}, Group: "privacy"},
	{Key: "privacy.gpc", Kind: KBool, Default: true, Group: "privacy"},
	{Key: "privacy.httpsUpgrade", Kind: KBool, Default: true, Group: "privacy"},
	{Key: "privacy.clearOnExit", Kind: KBool, Default: false, Group: "privacy"},
	{Key: "privacy.thirdPartyCookies", Kind: KBool, Default: true, Group: "privacy"},
	{Key: "privacy.trimReferrer", Kind: KBool, Default: true, Group: "privacy"},
	{Key: "search.engine", Kind: KString, Default: "duckduckgo", Group: "search"},
	{Key: "search.suggest", Kind: KBool, Default: true, Group: "search"},
	{Key: "omni.askRow", Kind: KBool, Default: true, Group: "search"},
	{Key: "startup.mode", Kind: KEnum, Default: "newtab", Enum: []string{"newtab", "restore", "pages"}, Group: "general"},
	{Key: "startup.pages", Kind: KString, Default: "", Group: "general"},
	{Key: "downloads.dir", Kind: KString, Default: "", Group: "downloads"},
	{Key: "downloads.ask", Kind: KBool, Default: false, Group: "downloads"},
	{Key: "zoom.default", Kind: KInt, Default: 100, Min: 25, Max: 500, Group: "appearance"},
	{Key: "tabs.discardMinutes", Kind: KInt, Default: 30, Min: 0, Max: 1440, Group: "performance"},
	{Key: "onboarding.done", Kind: KBool, Default: false, Group: "general"},

	{Key: "newtab.sites", Kind: KObject, Default: map[string]any{}, Group: "general", Norm: normNewtabSites},

	{Key: "devtools.height", Kind: KInt, Default: 320, Min: 160, Max: 1200, Group: "developer"},
	{Key: "devtools.panel", Kind: KEnum, Default: "console", Enum: []string{"console", "network", "elements", "sources", "application"}, Group: "developer"},

	{Key: "notifications.dnd", Kind: KBool, Default: false, Group: "notifications"},
	{Key: "notifications.default", Kind: KEnum, Default: "ask", Enum: []string{"ask", "blocked"}, Group: "notifications"},
	{Key: "push.service", Kind: KString, Default: "", Group: "notifications"},

	{Key: "data.level", Kind: KEnum, Default: "auto", Enum: []string{"auto", "off", "standard", "strict"}, Group: "data"},
	{Key: "data.budget", Kind: KObject, Default: DefaultBudget().Map(), Group: "data", Norm: normBudget},
	{Key: "data.sites", Kind: KObject, Default: map[string]any{}, Group: "data", Norm: normDataSites},
	{Key: "data.agentLite", Kind: KBool, Default: true, Group: "data"},
	{Key: "data.showMeter", Kind: KBool, Default: true, Group: "data"},
}

Schema is the full list of known settings (also sent to the settings page). The keys are the ones the chrome UI reads and writes with `settings.set` (docs/gui-contract.md, "settings keys"), plus a few the app owns.

Functions

func DayKey

func DayKey(t time.Time) string

DayKey is the local calendar date of t as used for the daily records.

func DefaultDir

func DefaultDir() string

DefaultDir returns the per-OS profile directory: Linux $XDG_DATA_HOME/sweef (or ~/.local/share/sweef), Windows %APPDATA%\Sweef, macOS ~/Library/Application Support/Sweef.

func OriginOf

func OriginOf(raw string) string

OriginOf normalises a URL to scheme://host[:port]; "" for opaque URLs.

func ReadRSS

func ReadRSS() (uint64, bool)

ReadRSS returns the resident set size of this process from /proc.

func SafeFilename

func SafeFilename(n string) string

SafeFilename strips path separators and control characters.

Types

type Backend

type Backend interface {
	// Append adds one record (a line without trailing newline) to a log.
	Append(name string, rec []byte) error
	// ReadFile returns the whole file or an error wrapping os.ErrNotExist.
	ReadFile(name string) ([]byte, error)
	// WriteAtomic replaces a file so that readers see the old or the new
	// content, never a mix, even if the process dies mid-write.
	WriteAtomic(name string, data []byte) error
	Remove(name string) error
	// Persistent reports whether data survives the process.
	Persistent() bool
	Close() error
}

Backend is the tiny file-system surface the stores need.

type Bookmark

type Bookmark struct {
	ID     string    `json:"id"`
	Parent string    `json:"parent"`
	Title  string    `json:"title"`
	URL    string    `json:"url,omitempty"`
	Folder bool      `json:"folder,omitempty"`
	Added  time.Time `json:"added"`
	Pos    int       `json:"pos"`
}

Bookmark is a bookmark or a folder (URL == "" and Folder == true).

type Bookmarks

type Bookmarks struct {
	// contains filtered or unexported fields
}

Bookmarks is a folder tree with O(1) "is this URL bookmarked".

func OpenBookmarks

func OpenBookmarks(b Backend) *Bookmarks

func (*Bookmarks) Add

func (bm *Bookmarks) Add(folder, title, url string) (Bookmark, error)

Add creates a bookmark in folder (default: the bookmarks bar).

func (*Bookmarks) AddFolder

func (bm *Bookmarks) AddFolder(parent, title string) (Bookmark, error)

AddFolder creates a folder.

func (*Bookmarks) All

func (bm *Bookmarks) All() []Bookmark

All returns every non-folder bookmark.

func (*Bookmarks) Children

func (bm *Bookmarks) Children(folder string) []Bookmark

Children lists a folder in position order.

func (*Bookmarks) Edit

func (bm *Bookmarks) Edit(id, title, rawurl string) bool

Edit changes the title and, for a bookmark (not a folder), the address.

func (*Bookmarks) IsBookmarked

func (bm *Bookmarks) IsBookmarked(url string) bool

IsBookmarked reports whether url has a bookmark.

func (*Bookmarks) Move

func (bm *Bookmarks) Move(id, folder string, pos int) error

Move re-parents id into folder at position pos.

func (*Bookmarks) Remove

func (bm *Bookmarks) Remove(id string) bool

Remove deletes a bookmark or a folder subtree.

func (*Bookmarks) Rename

func (bm *Bookmarks) Rename(id, title string) bool

Rename changes the title.

func (*Bookmarks) Search

func (bm *Bookmarks) Search(q string, limit int) []Bookmark

Search finds bookmarks whose title or URL contains every term.

func (*Bookmarks) Toggle

func (bm *Bookmarks) Toggle(title, url string) (bool, error)

Toggle removes every bookmark of url if there is one, else adds it to the bar. It returns the new state.

type Budget

type Budget struct {
	Enabled  bool   `json:"enabled"`
	LimitMB  int    `json:"limitMB"`
	Period   string `json:"period"`
	ResetDay int    `json:"resetDay"`
	WarnAt   []int  `json:"warnAt"`
	HardStop bool   `json:"hardStop"`
}

Budget is the Data Saver allowance (settings key data.budget). It is plain data plus pure functions of a clock, so the period and threshold maths can be tested with any time, including clock changes.

Enabled  - false means "Unlimited": usage is still counted.
LimitMB  - allowance per period in MB (1 MB = 1<<20 bytes).
Period   - "day" | "week" | "month".
ResetDay - week: weekday the period starts (0 = Sunday .. 6 = Saturday);
           month: day of month (1..28; larger values are clamped to the
           last day of short months); day: ignored.
WarnAt   - percentages at which the person is told once per period.
HardStop - when the budget is used up, page loads stop at an interstitial
           that offers "Load once", "Raise limit" and "Wait until reset".

func DefaultBudget

func DefaultBudget() Budget

DefaultBudget is what an unconfigured profile has: no limit, month period.

func ParseBudget

func ParseBudget(v any) (Budget, error)

ParseBudget turns a settings value (a map decoded from JSON, a Budget, or nil) into a validated Budget. Unknown or invalid fields fall back to the defaults; an error is returned only for a value that is not an object.

func (Budget) LimitBytes

func (b Budget) LimitBytes() int64

LimitBytes is the allowance in bytes (0 when the budget is off).

func (Budget) Map

func (b Budget) Map() map[string]any

Map is the budget as the settings JSON holds it.

func (Budget) Normalized

func (b Budget) Normalized() Budget

Normalized clamps every field into its valid range.

func (Budget) PeriodEnd

func (b Budget) PeriodEnd(now time.Time) time.Time

PeriodEnd is the local midnight on which the next period starts.

func (Budget) PeriodKey

func (b Budget) PeriodKey(now time.Time) string

PeriodKey identifies a period (its start date); thresholds fire once per key.

func (Budget) PeriodStart

func (b Budget) PeriodStart(now time.Time) time.Time

PeriodStart is the local midnight on which the period containing now began.

func (Budget) ResetsInDays

func (b Budget) ResetsInDays(now time.Time) int

ResetsInDays is the number of calendar days from today until the reset (1 = tomorrow). It is never below 1.

func (Budget) StatusFor

func (b Budget) StatusFor(used int64, now time.Time) BudgetStatus

StatusFor computes the status for a given usage in the current period.

type BudgetStatus

type BudgetStatus struct {
	Enabled      bool      `json:"enabled"`
	LimitBytes   int64     `json:"limitBytes"`
	UsedBytes    int64     `json:"usedBytes"`
	LeftBytes    int64     `json:"leftBytes"`
	Pct          float64   `json:"pct"` // 0..100+, 0 when no budget
	ResetsInDays int       `json:"resetsInDays"`
	ResetsAt     time.Time `json:"resetsAt"`
	PeriodStart  time.Time `json:"periodStart"`
	Exhausted    bool      `json:"exhausted"`
	HardStop     bool      `json:"hardStop"`
	Key          string    `json:"key"`
	WarnCrossed  []int     `json:"-"` // thresholds reached (not necessarily announced)
}

BudgetStatus is the budget maths for one moment.

type DataUsage

type DataUsage struct {

	// Debounce is the delay between a change and the write. Zero writes
	// immediately (tests). Set before use.
	Debounce time.Duration
	// contains filtered or unexported fields
}

DataUsage keeps the per-day usage totals. It is safe for concurrent use. Writes are batched (Debounce) and atomic, so a crash loses at most the last Debounce of counting and never corrupts the file.

func OpenDataUsage

func OpenDataUsage(b Backend, clock func() time.Time) *DataUsage

OpenDataUsage loads the usage file (a corrupt file starts empty). clock may be nil for time.Now.

func (*DataUsage) Add

func (u *DataUsage) Add(total int64, origins map[string]int64, savedM, savedE int64)

Add records measured bytes from a normal window. origins attributes part of them (approximate); savedM / savedE are bytes saved, measured / estimated.

func (*DataUsage) AddIncognito

func (u *DataUsage) AddIncognito(total int64)

AddIncognito records bytes used in a private window. They count toward the budget; no origin, URL or any other detail is stored.

func (*DataUsage) Check

func (u *DataUsage) Check(b Budget, st BudgetStatus) []ThresholdEvent

Check compares st with what was already announced in this period and returns the thresholds newly reached, marking them so each fires once per period. Raising or lowering the limit mid-period re-baselines: thresholds that the new limit has not reached any more are armed again, those already reached are marked quietly.

func (*DataUsage) Flush

func (u *DataUsage) Flush()

Flush writes pending changes now (called on exit).

func (*DataUsage) Rebaseline

func (u *DataUsage) Rebaseline(b Budget, st BudgetStatus)

Rebaseline marks every threshold the status has already reached as announced, without firing. The app calls it when the person changes the budget, so saving a new limit never answers with a toast.

func (*DataUsage) Reset

func (u *DataUsage) Reset()

Reset forgets all usage and fired thresholds ("Reset counter").

func (*DataUsage) SetClock

func (u *DataUsage) SetClock(c func() time.Time)

SetClock replaces the clock (tests).

func (*DataUsage) Today

func (u *DataUsage) Today() DayUsage

Today is the usage of the current local day.

func (*DataUsage) Top

func (u *DataUsage) Top(n int, start, end time.Time) []OriginBytes

Top returns the n heaviest origins in [start, end), heaviest first. Private window bytes never appear here.

func (*DataUsage) Totals

func (u *DataUsage) Totals(start, end time.Time) PeriodTotals

Totals sums the days whose date is in [start, end).

type DayUsage

type DayUsage struct {
	Total   int64            `json:"total"`
	Incog   int64            `json:"incog,omitempty"`
	SavedM  int64            `json:"savedM,omitempty"`
	SavedE  int64            `json:"savedE,omitempty"`
	Other   int64            `json:"other,omitempty"`
	Origins map[string]int64 `json:"origins,omitempty"`
}

DayUsage is one local calendar day of data use.

Total   - measured bytes for the day (socket totals, normal windows)
Incog   - measured bytes used in private windows: counted for the budget,
          never attributed to an origin
SavedM  - bytes provably not downloaded (cache hits, aborted by a size cap)
SavedE  - ESTIMATED bytes avoided (median size per skipped resource kind);
          kept apart from SavedM so the UI never mixes the two
Origins - bytes by origin for the heaviest origins (approximate attribution)

func (DayUsage) All

func (d DayUsage) All() int64

All is Total plus private-window bytes: what counts toward the budget.

type DiskBackend

type DiskBackend struct {
	Dir string
	// contains filtered or unexported fields
}

DiskBackend stores files under Dir with 0600 permissions (0700 for Dir).

func NewDiskBackend

func NewDiskBackend(dir string) (*DiskBackend, error)

NewDiskBackend creates dir if needed.

func (*DiskBackend) Append

func (d *DiskBackend) Append(name string, rec []byte) error

func (*DiskBackend) Close

func (d *DiskBackend) Close() error

func (*DiskBackend) Persistent

func (d *DiskBackend) Persistent() bool

func (*DiskBackend) ReadFile

func (d *DiskBackend) ReadFile(name string) ([]byte, error)

func (*DiskBackend) Remove

func (d *DiskBackend) Remove(name string) error

func (*DiskBackend) WriteAtomic

func (d *DiskBackend) WriteAtomic(name string, data []byte) error

type DownloadItem

type DownloadItem struct {
	ID        string    `json:"id"`
	URL       string    `json:"url"`
	Name      string    `json:"name"`
	Path      string    `json:"path"`
	Mime      string    `json:"mime,omitempty"`
	Total     int64     `json:"total"` // -1 unknown
	Received  int64     `json:"received"`
	State     string    `json:"state"`
	Error     string    `json:"error,omitempty"`
	Started   time.Time `json:"started"`
	Incognito bool      `json:"-"`
	Speed     int64     `json:"-"` // bytes per second over the last progress interval
	// contains filtered or unexported fields
}

DownloadItem is one download.

type Downloads

type Downloads struct {
	Dir    string
	Client *http.Client
	// OnUpdate is called (without locks) after every state change; progress
	// updates are throttled to ~10/s per item.
	OnUpdate func(DownloadItem)
	// contains filtered or unexported fields
}

Downloads tracks downloads and runs the streaming downloader. Progress, pause (resume with a Range request) and cancel are real: they act on the HTTP body being read, not on a fake counter.

func OpenDownloads

func OpenDownloads(b Backend) *Downloads

func (*Downloads) Cancel

func (d *Downloads) Cancel(id string) bool

Cancel aborts and deletes the partial file.

func (*Downloads) ClearFinished

func (d *Downloads) ClearFinished()

ClearFinished drops every download that is done, failed or canceled.

func (*Downloads) Get

func (d *Downloads) Get(id string) (DownloadItem, bool)

Get returns one item.

func (*Downloads) List

func (d *Downloads) List() []DownloadItem

List returns downloads, newest first.

func (*Downloads) Pause

func (d *Downloads) Pause(id string) bool

Pause stops the transfer, keeping the partial file for Resume.

func (*Downloads) Record

func (d *Downloads) Record(u, name, p string, size int64, mime string) DownloadItem

Record adds an already-finished download (e.g. one the engine saved).

func (*Downloads) Remove

func (d *Downloads) Remove(id string)

Remove drops an entry from the list (not the file).

func (*Downloads) Resume

func (d *Downloads) Resume(id string) bool

Resume continues a paused download with a Range request.

func (*Downloads) Start

func (d *Downloads) Start(rawurl, name, dir, cookie, ua string) (DownloadItem, error)

Start begins a streaming download of rawurl into dir. cookie/ua are sent as the requesting tab would.

type History

type History struct {
	// contains filtered or unexported fields
}

History is the visit log with a frecency-ordered in-memory index.

func OpenHistory

func OpenHistory(b Backend) *History

OpenHistory loads the log.

func (*History) Clear

func (h *History) Clear()

Clear wipes all history.

func (*History) ClearSince

func (h *History) ClearSince(t time.Time) int

ClearSince removes visits whose last visit is at or after t.

func (*History) Delete

func (h *History) Delete(u string)

Delete removes one URL.

func (*History) Get

func (h *History) Get(u string) (HistoryEntry, bool)

Get returns one entry.

func (*History) Len

func (h *History) Len() int

Len is the number of distinct URLs.

func (*History) Recent

func (h *History) Recent(limit int) []HistoryEntry

Recent returns the most recently visited entries.

func (*History) Search

func (h *History) Search(q string, limit int) []HistoryEntry

Search returns up to limit entries matching every whitespace-separated term of q, ranked by match quality then frecency. Terms match as a prefix of the host or URL, a prefix of a word in URL/title, or any substring.

func (*History) SetTitle

func (h *History) SetTitle(u, title string)

SetTitle updates the title of an existing entry without counting a visit.

func (*History) Top

func (h *History) Top(limit int) []HistoryEntry

Top returns the highest-frecency entries.

func (*History) TopSites

func (h *History) TopSites(n int) []HistoryEntry

TopSites returns up to n sites, one per host, best frecency first.

func (*History) Visit

func (h *History) Visit(u, title string, typed bool)

Visit records a page visit. Only http(s)/file/sweef-internal-free URLs should be passed; callers filter internal pages.

func (*History) VisitAt

func (h *History) VisitAt(u, title string, typed bool, at time.Time)

VisitAt is Visit with an explicit time (tests, import).

type HistoryEntry

type HistoryEntry struct {
	URL    string    `json:"url"`
	Title  string    `json:"title"`
	Visits int       `json:"visits"`
	Typed  int       `json:"typed"`
	Last   time.Time `json:"last"`
	Frec   float64   `json:"frecency"` // computed at query time
}

HistoryEntry is one visited URL.

type Kind

type Kind string

Kind is a setting's value type.

const (
	KBool   Kind = "bool"
	KString Kind = "string"
	KInt    Kind = "int"
	KEnum   Kind = "enum"
	KObject Kind = "object" // a JSON object, normalised by Spec.Norm
)

type MemBackend

type MemBackend struct {
	// contains filtered or unexported fields
}

MemBackend keeps everything in RAM. It is the incognito backend.

func NewMemBackend

func NewMemBackend() *MemBackend

func (*MemBackend) Append

func (m *MemBackend) Append(name string, rec []byte) error

func (*MemBackend) Close

func (m *MemBackend) Close() error

func (*MemBackend) Persistent

func (m *MemBackend) Persistent() bool

func (*MemBackend) ReadFile

func (m *MemBackend) ReadFile(name string) ([]byte, error)

func (*MemBackend) Remove

func (m *MemBackend) Remove(name string) error

func (*MemBackend) Wipe

func (m *MemBackend) Wipe()

Wipe forgets everything (incognito window closed).

func (*MemBackend) WriteAtomic

func (m *MemBackend) WriteAtomic(name string, data []byte) error

type OriginBytes

type OriginBytes struct {
	Origin string `json:"origin"`
	Bytes  int64  `json:"bytes"`
}

OriginBytes is one row of the top-sites list.

type PeriodTotals

type PeriodTotals struct {
	Used   int64 // counts toward the budget (normal + private)
	Normal int64
	Incog  int64
	SavedM int64
	SavedE int64
}

PeriodTotals is the sum of the days in [start, end).

type Profile

type Profile struct {
	Dir       string
	Incognito bool
	B         Backend

	History   *History
	Bookmarks *Bookmarks
	Downloads *Downloads
	Settings  *Settings
	Session   *SessionStore
	Sites     *Sites
	Stats     *Usage
	Data      *DataUsage // Data Saver usage per day
}

Profile bundles every store over one Backend.

func OpenIncognito

func OpenIncognito() *Profile

OpenIncognito returns a profile that lives only in memory. Nothing is created on disk; Close wipes it.

func OpenProfile

func OpenProfile(dir string) (*Profile, error)

OpenProfile opens (creating) the persistent profile in dir.

func (*Profile) Close

func (p *Profile) Close() error

Close flushes and releases the profile; an incognito profile is wiped.

type Session

type Session struct {
	V         int             `json:"v"`
	Windows   []SessionWindow `json:"windows"`
	SavedAt   time.Time       `json:"savedAt"`
	CleanExit bool            `json:"cleanExit"`
}

Session is the whole restorable state. Incognito windows are never in it.

type SessionStore

type SessionStore struct {
	Debounce time.Duration
	// contains filtered or unexported fields
}

SessionStore writes the session debounced and crash-safe: the new file is written to a temp file, fsynced and renamed over the old one, and the previous good generation is kept as session.prev.json so even a torn final file still restores.

func OpenSession

func OpenSession(b Backend) *SessionStore

func (*SessionStore) Flush

func (s *SessionStore) Flush()

Flush runs a pending save now and stops the timer.

func (*SessionStore) Load

func (s *SessionStore) Load() (Session, bool)

Load returns the saved session; falls back to the previous generation when the primary is torn. ok is false when there is nothing to restore.

func (*SessionStore) Save

func (s *SessionStore) Save(ss Session) error

Save writes immediately.

func (*SessionStore) Schedule

func (s *SessionStore) Schedule(snap func() Session)

Schedule requests a save; calls within Debounce coalesce and snap is evaluated when the timer fires (so it captures the latest state).

func (*SessionStore) Stop

func (s *SessionStore) Stop()

Stop flushes and refuses further scheduling.

func (*SessionStore) Writes

func (s *SessionStore) Writes() int

Writes reports how many times the file was written (tests).

type SessionTab

type SessionTab struct {
	URL     string   `json:"url"`
	Title   string   `json:"title,omitempty"`
	Scroll  int      `json:"scroll,omitempty"`
	Pinned  bool     `json:"pinned,omitempty"`
	History []string `json:"history,omitempty"`
	HIdx    int      `json:"hidx,omitempty"`
}

SessionTab is one restorable tab.

type SessionWindow

type SessionWindow struct {
	Tabs   []SessionTab `json:"tabs"`
	Active int          `json:"active"`
}

SessionWindow is one restorable window.

type Settings

type Settings struct {
	// contains filtered or unexported fields
}

Settings holds typed values with defaults and schema versioning.

func OpenSettings

func OpenSettings(b Backend) (*Settings, error)

OpenSettings loads and migrates the settings file. Unknown keys are kept (forward compatibility) but invalid values for known keys fall back to the default.

func (*Settings) All

func (s *Settings) All() map[string]any

All returns every known setting with its effective value.

func (*Settings) Bool

func (s *Settings) Bool(key string) bool

func (*Settings) Budget

func (s *Settings) Budget() Budget

Budget returns the validated data.budget setting.

func (*Settings) DataLevel

func (s *Settings) DataLevel() string

DataLevel resolves data.level: an explicit choice wins; "auto" is standard when a budget is set and off otherwise.

func (*Settings) DataSites

func (s *Settings) DataSites() map[string]string

DataSites returns a copy of the per-origin Data Saver rules (origin -> "full" | "lite").

func (*Settings) Get

func (s *Settings) Get(key string) any

Get returns the value or its default.

func (*Settings) Int

func (s *Settings) Int(key string) int

func (*Settings) Keys

func (s *Settings) Keys() []string

Keys returns known keys sorted.

func (*Settings) OnChange

func (s *Settings) OnChange(fn func(key string, v any))

OnChange registers a callback run after Set.

func (*Settings) Set

func (s *Settings) Set(key string, v any) error

Set validates and stores a value.

func (*Settings) Str

func (s *Settings) Str(key string) string

type SiteRule

type SiteRule struct {
	Agent     Visibility `json:"agent,omitempty"`
	NoBlock   bool       `json:"noBlock,omitempty"`   // privacy exception: blocking off here
	NoUpgrade bool       `json:"noUpgrade,omitempty"` // https upgrade off here
	// Camera, Microphone and Screen are the stored capture decisions: "allow", "block" or "" (ask). Screen is never
	// "allow": sharing the screen asks every time; only a block is remembered.
	Camera     string `json:"camera,omitempty"`
	Microphone string `json:"microphone,omitempty"`
	Screen     string `json:"screen,omitempty"`

	// Web permissions (siteperms.go). "" = not decided: the default applies, or the user is asked.
	Notify          string `json:"notify,omitempty"`          // "granted" | "denied" for notifications and push
	Periodic        string `json:"periodic,omitempty"`        // "granted" | "denied" overrides the bookmark rule for periodic sync
	ClipboardRead   string `json:"clipboardRead,omitempty"`   // "granted" | "denied": the Async Clipboard API reading what was copied
	NotifyDismissed int    `json:"notifyDismissed,omitempty"` // prompts dismissed with "Not now" since the last decision
	NotifyEmbargo   int64  `json:"notifyEmbargo,omitempty"`   // unix seconds: no prompt before this time
}

SiteRule is everything remembered about one origin.

type Sites

type Sites struct {
	Default Visibility
	// contains filtered or unexported fields
}

Sites stores per-origin permissions with a default agent visibility.

func OpenSites

func OpenSites(b Backend) *Sites

func (*Sites) Agent

func (s *Sites) Agent(originOrURL string) Visibility

Agent returns the agent visibility for an origin or URL (default if none).

func (*Sites) All

func (s *Sites) All() map[string]SiteRule

All returns a copy of every rule.

func (*Sites) Embargoed

func (s *Sites) Embargoed(originOrURL string, now time.Time) bool

Embargoed reports whether prompts for the origin are suppressed at now.

func (*Sites) Media

func (s *Sites) Media(originOrURL, name string) string

Media returns the stored decision ("allow", "block" or "") for "camera", "microphone" or "screen".

func (*Sites) MediaOrigins

func (s *Sites) MediaOrigins() []string

MediaOrigins lists the origins that have a stored capture decision.

func (*Sites) NoteDismissed

func (s *Sites) NoteDismissed(originOrURL string, now time.Time) bool

NoteDismissed counts a prompt the user closed with "Not now". After DismissLimit in a row the origin is embargoed for EmbargoLength (no prompt, requests are answered "denied" without asking). It reports whether the embargo began.

func (*Sites) Notify

func (s *Sites) Notify(originOrURL string) string

Notify returns "granted", "denied" or "" for an origin.

func (*Sites) Rule

func (s *Sites) Rule(originOrURL string) SiteRule

Rule returns the stored rule for the origin.

func (*Sites) Salt

func (s *Sites) Salt() string

Salt is the per-profile secret behind the per-origin device ids pages see. It is created on first use and kept with the site rules, so a page that stores a deviceId finds it valid after a restart.

func (*Sites) SetAgent

func (s *Sites) SetAgent(originOrURL string, v Visibility)

SetAgent sets the rule; "" resets to default.

func (*Sites) SetClipboardRead

func (s *Sites) SetClipboardRead(originOrURL, state string)

SetClipboardRead records the decision about reading the clipboard ("granted", "denied", or "" to ask again).

func (*Sites) SetDefault

func (s *Sites) SetDefault(v Visibility)

SetDefault sets the default visibility for origins without a rule.

func (*Sites) SetMedia

func (s *Sites) SetMedia(originOrURL, name, v string)

SetMedia stores a decision; "" forgets it.

func (*Sites) SetNotify

func (s *Sites) SetNotify(originOrURL, state string)

SetNotify records the user's decision ("granted", "denied") or forgets it (""). A decision resets the dismissal count.

func (*Sites) SetPeriodic

func (s *Sites) SetPeriodic(originOrURL, state string)

SetPeriodic overrides the periodic sync permission of an origin ("granted", "denied", or "" for the default rule).

func (*Sites) SetPrivacyException

func (s *Sites) SetPrivacyException(originOrURL string, noBlock bool)

SetPrivacyException toggles tracker blocking for an origin.

func (*Sites) WithPermissions

func (s *Sites) WithPermissions() map[string]SiteRule

WithPermissions lists the origins that have any web permission decision, for the settings page.

type Spec

type Spec struct {
	Key     string   `json:"key"`
	Kind    Kind     `json:"kind"`
	Default any      `json:"default"`
	Enum    []string `json:"enum,omitempty"`
	Min     int      `json:"min,omitempty"`
	Max     int      `json:"max,omitempty"`
	Group   string   `json:"group,omitempty"`
	// Norm validates and canonicalises a KObject value.
	Norm func(any) (any, error) `json:"-"`
}

Spec describes one typed setting.

type ThresholdEvent

type ThresholdEvent struct {
	Kind string // "warn" or "exhausted"
	Pct  int    // the warn threshold (100 for exhausted)
}

ThresholdEvent is something worth telling the person once.

type Usage

type Usage struct {
	// contains filtered or unexported fields
}

Usage reports real runtime metrics. Nothing here is estimated or invented: memory comes from the OS (Linux /proc/self/status VmRSS; elsewhere the Go runtime's Sys, reported with RSSExact=false), tab counts come from the model.

func NewUsage

func NewUsage() *Usage

func (*Usage) AddBlocked

func (u *Usage) AddBlocked(n int)

AddBlocked counts blocked requests.

func (*Usage) AddPage

func (u *Usage) AddPage()

AddPage counts a loaded page.

func (*Usage) Snapshot

func (u *Usage) Snapshot(tabs int) UsageSnapshot

Snapshot samples the process now; tabs is passed in by the caller.

type UsageSnapshot

type UsageSnapshot struct {
	RSSBytes   uint64 `json:"rssBytes"`
	RSSExact   bool   `json:"rssExact"`
	HeapBytes  uint64 `json:"heapBytes"`
	Goroutines int    `json:"goroutines"`
	UptimeSec  int64  `json:"uptimeSec"`
	Tabs       int    `json:"tabs"`
	Blocked    int64  `json:"blocked"`
	Pages      int64  `json:"pages"`
}

UsageSnapshot is the value shown on the new-tab page / settings.

type Visibility

type Visibility string

Visibility is the per-origin rule for what the agent may read.

const (
	VisAllowed Visibility = "allowed"
	VisBlocked Visibility = "blocked"
	VisAsk     Visibility = "ask"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL