Documentation
¶
Overview ¶
Package webapp serves the bdrive web server: a browsable web view of synced files (file tree reconstructed from the journals, rendered markdown, downloads), browser uploads, and — in hub mode — the sync API that lets storage-blind client devices sync whole projects through this server.
Two modes:
- single-volume: Source is set (a DirSource for a plain folder, or a RemoteSource in tests); the classic viewer.
- hub: Root + Projects are set; the server hosts many projects, each a volume stored under <root>/<project-id>/ in the object store, managed by a file-backed project registry.
The client — browser or syncing device — is deliberately told nothing about the storage: no remote URL, bucket, or credentials ever appear in an API response.
Index ¶
- Constants
- Variables
- func MigrateOrgs(projects *ProjectDB, orgs orgWriter, accounts []User) error
- func RenderMarkdown(src []byte) (string, error)
- type AccountApprover
- type AccountRepo
- type AnalyticsConfig
- type AuthProvider
- type Brander
- type BuiltinAuth
- func (a *BuiltinAuth) Accounts() []User
- func (a *BuiltinAuth) Approve(id string) error
- func (a *BuiltinAuth) Authenticate(r *http.Request) (User, bool)
- func (a *BuiltinAuth) Branding() string
- func (a *BuiltinAuth) CLILoginPath() string
- func (a *BuiltinAuth) Deny(id string) error
- func (a *BuiltinAuth) PendingUsers() []User
- func (a *BuiltinAuth) Policy() SignupPolicy
- func (a *BuiltinAuth) Register(mux *http.ServeMux)
- func (a *BuiltinAuth) Seniority() []string
- func (a *BuiltinAuth) SetPolicy(requireVerification, requireApproval bool) error
- func (a *BuiltinAuth) ValidateSignupPolicy() error
- type CLIAuth
- type DeviceInfo
- type DeviceRegistry
- func (r *DeviceRegistry) Bind(user string, d DeviceInfo, visible func(owner string) bool) error
- func (r *DeviceRegistry) Get(id string) (DeviceInfo, bool)
- func (r *DeviceRegistry) LookupIn(id string, allowed func(user string) bool) (DeviceInfo, bool)
- func (r *DeviceRegistry) MayActAs(user, id string) bool
- func (r *DeviceRegistry) Observe(d DeviceInfo)
- func (r *DeviceRegistry) OwnerOf(id string) (owner string, known bool)
- func (r *DeviceRegistry) Release(user string)
- type DeviceRepo
- type DirSource
- type DirectUploader
- type Directory
- type FileInfo
- type HeatEntry
- type HistoryEntry
- type Identity
- type LocalDirectory
- type Mailer
- type MetaStore
- type MoveSource
- type Node
- type Org
- type OrgDB
- func (db *OrgDB) AddMember(orgID, email, role string) error
- func (db *OrgDB) Create(name, ownerEmail string) (Org, error)
- func (db *OrgDB) CreateInvite(orgID, creator string, ttl time.Duration) (OrgInvite, error)
- func (db *OrgDB) EvictMember(orgID, email string) error
- func (db *OrgDB) Get(id string) (Org, bool)
- func (db *OrgDB) ListInvites(orgID string) []OrgInvite
- func (db *OrgDB) OrgsFor(email string) []Org
- func (db *OrgDB) RecordInviteUse(token string)
- func (db *OrgDB) Redeem(token string) (OrgInvite, bool)
- func (db *OrgDB) RemoveMember(orgID, email string) error
- func (db *OrgDB) Rename(orgID, name string) error
- func (db *OrgDB) RevokeInvite(token string) bool
- func (db *OrgDB) Role(orgID, email string) string
- func (db *OrgDB) SetRole(orgID, email, role string) error
- func (db *OrgDB) SetSeniority(f func() []string)
- func (db *OrgDB) ValidInvite(token string) bool
- type OrgInvite
- type OrgRepo
- type Project
- type ProjectDB
- func (db *ProjectDB) ClearPerm(id, email string) error
- func (db *ProjectDB) Delete(id string) error
- func (db *ProjectDB) Get(id string) (Project, bool)
- func (db *ProjectDB) GetOrCreate(name, org string) (Project, bool, error)
- func (db *ProjectDB) List() []Project
- func (db *ProjectDB) Rename(id, name string) error
- func (db *ProjectDB) SetCreator(id, email string) error
- func (db *ProjectDB) SetDefault(id, level string) error
- func (db *ProjectDB) SetOrg(id, org string) error
- func (db *ProjectDB) SetPerm(id, email, level string) error
- func (db *ProjectDB) SetTemplate(id, name string) error
- func (db *ProjectDB) Update(id string, name, description, icon *string) error
- type ProjectRepo
- type QuotaProvider
- type ReadLedger
- func (l *ReadLedger) AgentHeat(project string, since time.Time) map[string]map[string]int64
- func (l *ReadLedger) Close() error
- func (l *ReadLedger) Heat(project, prefix string, since time.Time) map[string]HeatEntry
- func (l *ReadLedger) Record(project, path, kind, actor string)
- func (l *ReadLedger) RecordSession(project, session, device, path string)
- func (l *ReadLedger) SessionPaths(project, session, device string) []string
- func (l *ReadLedger) ShareOpens(project string) map[string]ShareOpen
- func (l *ReadLedger) WithSessions(repo SessionReadRepo, retentionDays int) *ReadLedger
- type ReadRepo
- type ReadStat
- type ReadStatKey
- type RemoteSource
- func (r *RemoteSource) BlobSize(ctx context.Context, blob string) (int64, bool, error)
- func (r *RemoteSource) Commit(ctx context.Context, p, blob string, size int64, who User, note string) error
- func (r *RemoteSource) Files(ctx context.Context) (map[string]FileInfo, error)
- func (r *RemoteSource) FilesWithMoves(ctx context.Context) (map[string]FileInfo, moveIndex, error)
- func (r *RemoteSource) Open(ctx context.Context, _ string, fi FileInfo) (io.ReadCloser, error)
- func (r *RemoteSource) OpenBlob(ctx context.Context, sha string) (io.ReadCloser, error)
- func (r *RemoteSource) Remove(ctx context.Context, p string, who User, note string) error
- func (r *RemoteSource) SignBlobPut(ctx context.Context, blob string, size int64, ttl time.Duration) (*remote.SignedPut, error)
- func (r *RemoteSource) Upload(ctx context.Context, p string, src io.Reader, _ int64, who User, note string) error
- type Server
- type SessionRead
- type SessionReadRepo
- type Share
- type ShareDB
- func (db *ShareDB) Create(project, p, creator string, ttl time.Duration) (Share, error)
- func (db *ShareDB) Get(token string) (Share, bool)
- func (db *ShareDB) List(project string) []Share
- func (db *ShareDB) Revoke(token string) bool
- func (db *ShareDB) SetExpiry(token string, ttl time.Duration) (Share, bool, error)
- type ShareOpen
- type ShareRepo
- type SignupPolicy
- type Source
- type UnlimitedQuota
- type UploadConfig
- type Uploader
- type User
- type Versioned
Constants ¶
const ( RoleOwner = "owner" RoleMember = "member" )
const ( PermNone = "none" // the project is hidden: absent from the list, 403 everywhere PermRead = "read" // browse, view, download, history, heat PermWrite = "write" // + upload, sync push, share links PermAdmin = "admin" // + rename, delete, edit this project's permissions )
const ( ReadKindHuman = "human" ReadKindAgent = "agent" )
Read kinds.
const ( // DefaultReadRetentionDays is how long daily buckets keep per-day // resolution before folding into the all-time row. DefaultReadRetentionDays = 400 // DefaultSessionRetentionDays is how long per-session read detail is // kept. Much shorter than the bucket retention: this is event-shaped // data whose only consumer is a History run card, and a month covers a // retro. Rows past it are deleted, not folded — the heat totals were // never derived from them, so nothing is lost from any count. DefaultSessionRetentionDays = 30 )
const DefaultAnalyticsHost = "https://us.i.posthog.com"
DefaultAnalyticsHost is PostHog's US cloud ingestion host.
const DefaultInviteTTL = 7 * 24 * time.Hour
DefaultInviteTTL bounds invite links that don't ask for an expiry.
DefaultShareRPM is the per-IP sustained rate on /s/* when the config doesn't say otherwise.
const DefaultUploadTTL = 15 * time.Minute
DefaultUploadTTL is used when UploadConfig.TTL is unset: long enough for a slow upload, short enough that a leaked URL goes stale quickly.
Variables ¶
var ErrManagedElsewhere = errors.New("this organization is managed outside this hub")
ErrManagedElsewhere is returned by a directory that does not own its organizations. Handlers turn it into 409 plus the org's ManageURL — the request was well-formed, it is the state of the world that makes it wrong.
Functions ¶
func MigrateOrgs ¶ added in v0.3.0
func RenderMarkdown ¶
RenderMarkdown converts markdown to HTML (GFM + wikilinks). Raw HTML in the source is escaped by goldmark's safe default. A leading YAML frontmatter block renders as a small key/value table instead of the broken thematic-break soup goldmark would make of it.
Types ¶
type AccountApprover ¶ added in v0.9.0
type AccountApprover interface {
PendingUsers() []User
Approve(id string) error
Deny(id string) error
SetPolicy(requireVerification, requireApproval bool) error
// Policy reports the signup gates as configured. The provider assembles
// it, so the hub never reaches into provider fields to render the page.
Policy() SignupPolicy
}
AccountApprover is the optional half of account administration: signup policy and the approval queue behind /api/admin/*. A provider whose accounts live in an external identity system does not implement it, and those routes say so (503) rather than pretending the queue is empty.
type AccountRepo ¶ added in v0.3.0
type AccountRepo interface {
Load() (users []*authUser, tokens []authToken, policy *authPolicy, err error)
PutAccount(u *authUser) error
DeleteAccount(id string) error
PutToken(t authToken) error
DeleteToken(hash string) error
PutPolicy(p authPolicy) error
}
AccountRepo persists accounts, device tokens, and the (singleton) signup policy. Load returns everything at open; every other method is one record.
type AnalyticsConfig ¶ added in v0.13.0
type AnalyticsConfig struct {
Key string // PostHog project key; empty disables analytics entirely
Host string // PostHog API host; empty means DefaultAnalyticsHost
}
AnalyticsConfig points the frontend at a PostHog project. The key is a public write-only project token, not a credential — it is served to signed- out visitors too, because the app shell loads before login.
func (AnalyticsConfig) Endpoint ¶ added in v0.13.0
func (a AnalyticsConfig) Endpoint() string
Endpoint is Host with the default applied. Exported because the same config drives more than the app shell in a managed deployment (the cloud module's marketing pages render their own loader from it).
type AuthProvider ¶
type AuthProvider interface {
// CLILoginPath is the page `bdrive login` opens in a browser. The CLI
// appends ?redirect=http://127.0.0.1:<port>/callback&state=<nonce>.
CLILoginPath() string
// Authenticate resolves the request's Bearer token or session cookie.
Authenticate(r *http.Request) (User, bool)
// Register mounts the provider's own pages and endpoints (/auth/*,
// /api/auth/*) on the server mux.
Register(mux *http.ServeMux)
// Accounts lists every account the provider knows, oldest first. Startup
// tasks (the org migration) need it, and both implementations already had
// it — declaring it here stops callers reaching for a concrete type.
Accounts() []User
}
AuthProvider is the seam between the server and an identity system.
type Brander ¶ added in v0.9.0
type Brander interface{ Branding() string }
Brander is the optional hub-name half: a provider that renders its own sign-in pages knows what to call this hub.
type BuiltinAuth ¶
type BuiltinAuth struct {
AllowSignup bool
Mail *Mailer // nil → reset links go to the server log
// Public-URL signup gating (all optional; set after Open). A hub reachable
// from the internet should use at least one of these.
AllowedDomains []string // if non-empty, signup email domain must match one
RequireVerification bool // new accounts must click an email link before activation
RequireApproval bool // new accounts wait for an admin to approve them
Admins map[string]bool // hub admins (lowercase emails): approve users, govern shares
Brand string // optional name shown on the sign-in page
// BaseURL is the hub's public origin ("https://drive.acme.com"). Links the
// hub MAILS are built from it. Empty → the hub has no origin it can trust
// and mailed links stop being absolute as soon as two requests disagree
// about the host; see mailBaseURL.
BaseURL string
// InviteValid, when set, reports whether a token is a live org invite.
// It lets an invite link bootstrap an account on an invite-only hub
// (AllowSignup false) — the one path in without self-signup. Wired to
// OrgDB.ValidInvite by the server. Nil → no invite-based signup.
InviteValid func(token string) bool
// Offboard, when set, is called with the address of an account that has
// just been removed. Everything downstream of removal is keyed by email
// (org role, project grant, share liveness), so without it the grants
// outlive the account. Wired to Server.offboard by the server.
Offboard func(email string)
// BindDevice, when set, records that a device id belongs to an account, at
// the moment a token is minted for it. It is the ONLY way an ownership row
// is created for an id that has never synced — see DeviceRegistry.Bind for
// why first-claim-on-write could not be. Wired to Server.bindDevice.
BindDevice func(email string, r *http.Request) error
// contains filtered or unexported fields
}
BuiltinAuth is the open-source identity provider: email + password + name accounts and long-lived device tokens, persisted in one JSON file (loaded at open, rewritten atomically on every change — same discipline as the project registry). It owns the /auth/* pages the browser sees and the /api/auth/* endpoints the CLI uses.
func NewBuiltinAuth ¶ added in v0.3.0
func NewBuiltinAuth(store AccountRepo, allowSignup bool, mail *Mailer) (*BuiltinAuth, error)
NewBuiltinAuth builds the account service over an AccountRepo, loading its accounts, tokens, and persisted policy.
func OpenBuiltinAuth ¶
func OpenBuiltinAuth(path string, allowSignup bool, mail *Mailer) (*BuiltinAuth, error)
OpenBuiltinAuth loads (or starts) the file-backed account registry at path.
func (*BuiltinAuth) Accounts ¶ added in v0.3.0
func (a *BuiltinAuth) Accounts() []User
Accounts returns every account, oldest first (used by the org migration to pick the default org's owner).
func (*BuiltinAuth) Approve ¶ added in v0.3.0
func (a *BuiltinAuth) Approve(id string) error
Approve activates a pending account.
func (*BuiltinAuth) Authenticate ¶
func (a *BuiltinAuth) Authenticate(r *http.Request) (User, bool)
func (*BuiltinAuth) Branding ¶ added in v0.9.0
func (a *BuiltinAuth) Branding() string
Branding is the hub name this provider renders on its own pages.
func (*BuiltinAuth) CLILoginPath ¶
func (a *BuiltinAuth) CLILoginPath() string
func (*BuiltinAuth) Deny ¶ added in v0.3.0
func (a *BuiltinAuth) Deny(id string) error
Deny removes a pending account.
func (*BuiltinAuth) PendingUsers ¶ added in v0.3.0
func (a *BuiltinAuth) PendingUsers() []User
PendingUsers lists accounts awaiting admin approval, oldest first.
func (*BuiltinAuth) Policy ¶ added in v0.9.0
func (a *BuiltinAuth) Policy() SignupPolicy
Policy reports this provider's signup gates (webapp.AccountApprover). The provider assembles it so the hub never reaches into these fields itself.
func (*BuiltinAuth) Register ¶
func (a *BuiltinAuth) Register(mux *http.ServeMux)
func (*BuiltinAuth) Seniority ¶ added in v0.15.0
func (a *BuiltinAuth) Seniority() []string
Seniority is the oldest-first account order, and it is EMPTY when this hub holds no evidence of age at all.
OrgDB.heir breaks a Joined tie on it, and its own doc comment says "with no seniority available there is NO evidence, and the answer is nobody: an ownerless org is a repair a hub admin makes deliberately, while an arbitrary heir is a privilege grant nobody asked for". Handing back a merely deterministic order would satisfy the letter and not the sentence — it would promote the same arbitrary member every time, which is round 8's finding with a different arbitrary key. Rows with no Created stamp are dropped, so an upgraded hub that recorded nothing says nothing.
func (*BuiltinAuth) SetPolicy ¶ added in v0.3.0
func (a *BuiltinAuth) SetPolicy(requireVerification, requireApproval bool) error
SetPolicy updates the tunable gating toggles and persists them.
The prospective policy goes through the startup validator FIRST. The hub starts legally as {allow_signup:true, require_approval:true}; one admin POST used to remove the only gate, and because SetPolicy persists, the hub then survived a restart the same binary refuses to perform — CLAUDE.md states the guarantee as "refuses an ungated open hub rather than silently leaving the door open". Here rather than in handleAdminPolicy because the handler is one caller of this and a second caller would arrive without the check; the handler only had the mailer half of the rule anyway.
func (*BuiltinAuth) ValidateSignupPolicy ¶ added in v0.3.0
func (a *BuiltinAuth) ValidateSignupPolicy() error
ValidateSignupPolicy rejects incoherent signup configurations at startup so a hub is never accidentally left open to fake-email signups. The three supported postures are: invite-only (AllowSignup false — the default), approval-gated, and domain-restricted with email verification.
- Open self-signup must carry at least one gate (allowed domains, admin approval, or email verification). Without one, anyone can register any address — the exact hole this guards.
- Email verification needs a mailer: without SMTP the link only reaches the server log, so it can't actually gate real users.
type CLIAuth ¶ added in v0.14.0
type CLIAuth struct {
// contains filtered or unexported fields
}
CLIAuth is the CLI-facing half of signing in, whole: the loopback browser flow (/auth/cli → one-time code → /api/auth/exchange), the headless device flow (/api/auth/device/start → approval link → /api/auth/device/poll), and the approval page both of them show.
It is its own type rather than methods on an AuthProvider because this half of the protocol is identical no matter where the accounts live: `bdrive login` POSTs fixed paths and expects fixed JSON, so a provider differs only in who the browser session is and how a device token is minted — the two hooks below. The managed hub's provider used to carry its own copy of all of this, and the copy drifted: months after the OSS flow moved to a single approval link that names the device, the copy was still printing a four-byte code to retype into a text box. One implementation, every provider, nothing to keep in sync.
func NewCLIAuth ¶ added in v0.14.0
func NewCLIAuth(session func(*http.Request) (User, bool), issue func(w http.ResponseWriter, r *http.Request, userID, device string)) *CLIAuth
NewCLIAuth wires the two provider-specific pieces. session resolves the browser session — cookie only, never a Bearer token, or a device token could approve the next device. issue writes the CLI's {token, user} response for an approved grant.
type DeviceInfo ¶
type DeviceInfo struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
OS string `json:"os,omitempty"`
User string `json:"user,omitempty"` // account email last seen using this device
IP string `json:"ip,omitempty"` // as observed by the server
// FirstSeen is when this account was first observed syncing under this id.
// It is the only ownership fact the hub actually holds: a row is created by
// the caller's own header, so "does this account have a row" is a question
// the asking request already answered for itself, while "who was here
// first" is something a later caller cannot manufacture.
FirstSeen time.Time `json:"first_seen,omitzero"`
LastSeen time.Time `json:"last_seen"`
}
DeviceInfo is what the server knows about one syncing device: self-reported name/OS (headers sent by the client), plus what the server itself observed (public IP of the last push, last activity, the signed-in account). History joins ops against this registry so ops stay small — but it reports only id/name/os (historyDevice, history.go): the IP is recorded here, not repeated to every project member on every change.
type DeviceRegistry ¶
type DeviceRegistry struct {
// contains filtered or unexported fields
}
DeviceRegistry is the in-memory device table over a MetaStore DeviceRepo.
func NewDeviceRegistry ¶ added in v0.3.0
func NewDeviceRegistry(repo DeviceRepo) (*DeviceRegistry, error)
NewDeviceRegistry builds the registry over a repo, loading its contents.
func OpenDeviceRegistry ¶
func OpenDeviceRegistry(path string) (*DeviceRegistry, error)
OpenDeviceRegistry loads the file-backed registry at path.
func (*DeviceRegistry) Bind ¶ added in v0.15.0
func (r *DeviceRegistry) Bind(user string, d DeviceInfo, visible func(owner string) bool) error
Bind records that a device id belongs to an account, and is the ONLY way an ownership row comes into existence for an id that has never synced. It is called at token issuance (`bdrive login`, the device-code flow, and the login `bdrive init` runs inside itself), where the hub has just authenticated the account and the machine is the one asking.
This exists because the alternative was a race nobody could win. Ownership used to be minted by the first authorized journal PUT, admitted through `!known && journalNames(dev, ops)` — a check that reads a field the writer itself writes. A device that syncs with READ permission can never reach that door, so its id stayed unclaimed hub-wide forever and the first member with write on any project took it: permanently, with the victim's ops attributed to her device in History, and no remedy but abandoning device.json. Two hacker rounds found it from opposite sides and their tests were mutually unsatisfiable while first-claim-on-write was the only way a binding existed.
Claim-or-refuse is one critical section on purpose: two logins racing for one id must not both believe they won.
visible reports whether the conflicting owner is somebody the caller can already see on this hub, and it decides which of THREE outcomes a conflict gets. OwnerOf is deliberately hub-wide, so turning its answer into a status code makes the login a hub-wide device-existence oracle — the class round 3 closed for History, round 4 for the registry join and round 5 for /store/sign, arriving at a fourth door. So:
- no conflicting row: bind.
- conflict with an owner the caller can already see (same org): refuse, in words. Nothing is disclosed that the org's own surfaces do not disclose, and the machine learns why its sign-in did not take.
- conflict with an owner the caller cannot see: bind NOTHING and succeed. The token is real, no ownership row is created either way, and the push door already answers "owned by someone else" and "owned by nobody" with the same 403 — so this loses no defence and answers no question.
func (*DeviceRegistry) Get ¶
func (r *DeviceRegistry) Get(id string) (DeviceInfo, bool)
Get returns the most recently observed row for an id, whoever owns it. It is an unscoped display lookup: anything that serves the result to a project must use LookupIn instead, or it hands one org's device metadata to another.
func (*DeviceRegistry) LookupIn ¶ added in v0.15.0
func (r *DeviceRegistry) LookupIn(id string, allowed func(user string) bool) (DeviceInfo, bool)
LookupIn returns the row for an id whose owner passes allowed — the join every per-project surface uses, so a device belonging to an account outside the project's org resolves to nothing instead of leaking its machine name and OS (and confirming that the id exists at all).
When several accounts hold rows for one id, the FIRST claim wins. Picking the most recently observed row instead meant the second account to name an id decided what the whole project sees: one ordinary store request relabels a peer's device in History and in /heat?by=device, which is the forgery the per-account rekey was supposed to end.
func (*DeviceRegistry) MayActAs ¶ added in v0.15.0
func (r *DeviceRegistry) MayActAs(user, id string) bool
MayActAs reports whether an account may name a device id as itself: yes if this account has been seen syncing under it, and yes if nobody else has — an id nobody has claimed is the ordinary case of a device whose telemetry arrives before its first push, and refusing it would mean read heat never starts. What it refuses is naming a device another account is syncing.
This is the permissive question, and it is the right one for telemetry: a squatted id must still count its real owner's reads. Anything that WRITES on the strength of a device identity asks OwnerOf instead.
func (*DeviceRegistry) Observe ¶
func (r *DeviceRegistry) Observe(d DeviceInfo)
Observe merges what a request revealed about a device, into the row owned by the account that made it. Disk writes are throttled: identity changes persist immediately, bare last-seen bumps at most once a minute.
The repo keeps one row per id (its primary key), so what survives a restart is the most recent observation. That is a display cache, not the authority: MayActAs reads the in-memory rows, and a device re-registers on its very next sync cycle.
func (*DeviceRegistry) OwnerOf ¶ added in v0.15.0
func (r *DeviceRegistry) OwnerOf(id string) (owner string, known bool)
OwnerOf resolves who a device id belongs to, hub-wide: the account whose row for it was created first. It is the WRITE gate's resolver (ownJournal), and it differs from LookupIn — the display join — in the two ways that made round 4's binding fail:
- it is not scoped to an org. A claim that disappears when its owner is offboarded hands her journal to whoever is left in the org, and History keeps crediting her.
- a row with no owner (a pre-accounts devices.json, or an auth-less observation) claims nothing. Round 4 read "no owner" as "no objection", so on every upgraded hub the binding was off for exactly the established devices.
It returns the owning account and whether the hub has ever seen the id at all. The two differ, and the difference is a hole round 4 fell into: a row with no owner means a device exists whose account is unknown (known=true, owner=""), which is a reason to refuse, not to wave through.
func (*DeviceRegistry) Release ¶ added in v0.15.0
func (r *DeviceRegistry) Release(user string)
Release drops every device row an account owns, in memory and on disk. It is the device half of offboarding, and it is not bookkeeping: OwnerOf is the WRITE gate (store.go ownJournal) and Bind refuses an id another account claims, so a claim that outlives its account is a claim nobody can ever dislodge.
The offboarding scenario IS "the laptop goes to the next hire", and without this that hire is permanently locked out in the least debuggable way: the departed account no longer shares an org with anybody, so Bind's invisible-conflict arm binds NOTHING and lets the login SUCCEED — every later push then 403s telling the user to run `bdrive login`, which is what she just did. The mirror case is worse: re-create the address and the new account silently inherits the departed employee's device row and write access to that device's journal.
A row the store refuses to delete stays in memory. Reporting a release that isn't one is the widening direction — the claim comes back at the next restart while the hub has already handed the id to somebody else.
type DeviceRepo ¶ added in v0.3.0
type DeviceRepo interface {
Load() ([]DeviceInfo, error)
Put(d DeviceInfo) error
// Delete removes one account's row for one device id. Rows are keyed by
// (account, id), and this is how an offboarded account's hub-wide claim on
// a machine is released — see DeviceRegistry.Release.
Delete(user, id string) error
}
type DirSource ¶
type DirSource struct {
Root string
}
DirSource serves a plain local folder straight from disk — no bdrive remote or volume needed. Meant for debugging the webapp (and as a quick local markdown browser): the tree reflects the folder live, provenance is just file mtimes, and content streams from the filesystem.
type DirectUploader ¶
type DirectUploader interface {
Uploader
SignBlobPut(ctx context.Context, blob string, size int64, ttl time.Duration) (*remote.SignedPut, error)
// BlobSize reports the stored size of a blob and whether it is there at
// all. Size comes from storage, never from the caller: in direct mode the
// server never sees the bytes, so this is the only true byte count it can
// quota-check and journal.
BlobSize(ctx context.Context, blob string) (int64, bool, error)
// note rides along on the journaled op — "" for an ordinary upload,
// "restore <path>@<sha8>" when the write is a restore.
Commit(ctx context.Context, path, blob string, size int64, who User, note string) error
}
DirectUploader is additionally implemented by sources whose storage can accept presigned direct uploads.
type Directory ¶ added in v0.9.0
type Directory interface {
// ---- reads (request path) ----
Role(orgID, email string) string
Get(orgID string) (Org, bool)
OrgsFor(email string) []Org
ListInvites(orgID string) []OrgInvite
ValidInvite(token string) bool
// ManageURL is where this org is administered: a path within this hub
// when it owns its orgs, an external page when it does not. The client
// follows it and never has to know which kind of hub it is talking to.
ManageURL(orgID string) string
// ---- writes (ErrManagedElsewhere when the directory is read-only) ----
Create(name, ownerEmail string) (Org, error)
Rename(orgID, name string) error
AddMember(orgID, email, role string) error
SetRole(orgID, email, role string) error
RemoveMember(orgID, email string) error
CreateInvite(orgID, creator string, ttl time.Duration) (OrgInvite, error)
RevokeInvite(token string) bool
Redeem(token string) (OrgInvite, bool)
RecordInviteUse(token string)
}
Directory is where a hub's organizations live. The built-in one is this package's OrgDB (LocalDirectory); a deployment whose users, orgs and memberships are owned by an external identity system supplies its own, alongside its AuthProvider.
Two rules shape this interface:
Reads are on the request path. Role is called for every project request, including the /store/* sync endpoints a device hits every few seconds with a device token that carries no identity claims. An implementation backed by a remote system therefore has to answer Role from a local cache, and that cache is the implementation's business — the hub does not keep one, does not refresh one, and must never be written to from the side. (It used to be: the hub owned the mirror and the auth provider poked at it, which is how a hub-invented org that the identity system had never heard of could exist.)
Writes are optional. A directory that does not own its data returns ErrManagedElsewhere and the handler answers 409 with ManageURL, so the hub never needs to know WHY it cannot write — only where the user should go.
type FileInfo ¶
type FileInfo struct {
Blob string
Size int64
Time time.Time
// User/UserName are the signed-in account behind the change; Author is
// the git/OS identity an offline device falls back to. History renders
// the account and falls back to Author, so the viewer needs all three
// to give the same answer — see whoChanged() in the frontend.
User string
UserName string
Author string
Device string
}
FileInfo is the resolved state of one path: content identity (Blob doubles as the ETag), plus provenance where the source knows it.
type HeatEntry ¶ added in v0.4.0
type HeatEntry struct {
Human int64 `json:"human,omitempty"`
Agent int64 `json:"agent,omitempty"`
Readers int `json:"readers,omitempty"` // distinct human readers
LastRead time.Time `json:"last_read,omitzero"`
}
HeatEntry is the per-path aggregate the heat API returns. Counts only — never identities.
type HistoryEntry ¶
type HistoryEntry struct {
Time string `json:"time"`
Kind string `json:"kind"` // add | edit | delete
Path string `json:"path"`
Size int64 `json:"size,omitempty"`
Blob string `json:"blob,omitempty"` // sha256; fetch via the blob endpoint
User string `json:"user,omitempty"`
UserName string `json:"user_name,omitempty"`
Author string `json:"author,omitempty"` // offline/git fallback identity
Device historyDevice `json:"device"`
Note string `json:"note,omitempty"`
// Session is the agent session the op was committed during (hook-set,
// see journal.Op.Session). It is the run card's group key and the only
// place a session id is ever served: it is never enumerated, never a
// column in /heat's output, and never in ?by=device — it appears here,
// on the op that carries it, and is accepted as a ?session= filter INPUT.
Session string `json:"session,omitempty"`
}
HistoryEntry is one change as the history API reports it.
type Identity ¶
type Identity struct {
ID, Name, Author string
}
Identity is the device identity uploads are journaled under.
type LocalDirectory ¶ added in v0.9.0
type LocalDirectory struct{ *OrgDB }
LocalDirectory is the built-in directory: organizations owned by this hub, stored in its own metadata store. This is what every self-hosted install runs, and its behavior is exactly OrgDB's — the type exists to add the one thing an org store has no opinion about, which is where to send a browser to administer an org.
func (LocalDirectory) ManageURL ¶ added in v0.9.0
func (LocalDirectory) ManageURL(orgID string) string
ManageURL is the hub's own org page (a route in the frontend).
type Mailer ¶
type Mailer struct {
Host string // e.g. smtp.gmail.com
Port int // e.g. 587 (STARTTLS)
User string
Pass string
From string // e.g. drive@example.com
}
Mailer sends plain-text mail over SMTP — the lowest-common-denominator transport a self-hoster can point at anything (Gmail app password, SES, Mailgun, a local relay). No SDK, stdlib only. A nil Mailer reports itself as unconfigured so callers can fall back to logging the message.
type MetaStore ¶ added in v0.3.0
type MetaStore interface {
Accounts() AccountRepo
Projects() ProjectRepo
Orgs() OrgRepo
Devices() DeviceRepo
Reads() ReadRepo
SessionReads() SessionReadRepo
Close() error
}
MetaStore is the hub's metadata persistence, split into one typed repository per entity. It holds ONLY the control plane — accounts, tokens, projects, orgs, invites, shares, devices. File content and the append-only journals live in the object store and never touch this; ephemeral state (one-time login and device codes, rate-limit buckets) stays in memory.
A deployment chooses the backend: `file` (JSON on disk, the zero-dependency default) or `sql` (SQLite locally, Postgres/Supabase in production). The service structs (BuiltinAuth, OrgDB, …) keep their in-memory maps, mutexes, and business logic and persist each change through these repos — so reads stay in memory and writes are a single record apiece, which every backend implements as one real row.
func OpenFileStore ¶ added in v0.3.0
OpenFileStore builds the file backend over dir, using the historical filenames (auth.json, projects.json, orgs.json, shares.json, devices.json).
func OpenSQLStore ¶ added in v0.3.0
OpenSQLStore opens (and migrates) a SQL metadata store. driver is "sqlite" or "pgx" (Postgres/Supabase); dsn is the connection string / file path.
type MoveSource ¶ added in v0.15.0
type MoveSource interface {
FilesWithMoves(context.Context) (map[string]FileInfo, moveIndex, error)
}
MoveSource is a Source that can also report where its files came from. Optional, like Uploader: implementing it keeps the replay ONE pass, so the move index costs no extra journal read.
type Node ¶
type Node struct {
Name string `json:"name"`
Path string `json:"path"`
Dir bool `json:"dir"`
Size int64 `json:"size,omitempty"`
Time time.Time `json:"time,omitzero"`
// Same three-field "who" shape as HistoryEntry (history.go), so the
// frontend has one attribution helper for every surface.
User string `json:"user,omitempty"`
UserName string `json:"user_name,omitempty"`
Author string `json:"author,omitempty"`
Device string `json:"device,omitempty"`
Children []*Node `json:"children,omitempty"`
}
Node is one entry of the file tree returned by the tree endpoint.
type Org ¶ added in v0.3.0
type Org struct {
ID string `json:"id"`
Name string `json:"name"`
Members map[string]string `json:"members"` // lowercase email → role
Created time.Time `json:"created"`
// Joined records when each member row was first created. It exists for one
// decision — who inherits an org whose sole owner is offboarded — and that
// decision must not be readable off the address a member typed at signup.
// Rows written before this field existed carry a zero time and lose to any
// dated row, which is right: they are the oldest members there are.
Joined map[string]time.Time `json:"joined,omitempty"`
}
Org is one organization.
type OrgDB ¶ added in v0.3.0
type OrgDB struct {
// contains filtered or unexported fields
}
OrgDB is the in-memory org registry over a MetaStore OrgRepo (orgs + invites).
func (*OrgDB) AddMember ¶ added in v0.3.0
AddMember adds (or keeps) the account in the org with the given role. An existing member's role is never downgraded by an invite.
func (*OrgDB) CreateInvite ¶ added in v0.3.0
CreateInvite mints a join link for the org.
func (*OrgDB) EvictMember ¶ added in v0.15.0
EvictMember drops an account from the org unconditionally — the form offboard needs when the ACCOUNT itself is gone. The last-owner rule keeps a LIVE org administrable; it must never preserve an ownership row for an address nobody can sign in as, because the next signup on that address inherits it — org ownership, and through it admin on every project in the org. An org left with no owner is a recovery problem, not an authorization one. Dropping the sole owner is where this differs from RemoveMember in the other direction too: every org route is gated on RoleOwner and nothing adopts an ownerless org, so an org left with members and no owner can never again gain one, lose one, or change a role. The longest-standing remaining member is promoted instead — by Org.Joined, never by the address string. Round 8's heir was `lowestMember`, the smallest address, so the successor to every org was decided by what a member typed at signup: someone who joined last through an ordinary invite, holding no grant on anything, inherited org ownership and with it admin on every project in the org — triggered by the most routine operator action there is.
func (*OrgDB) ListInvites ¶ added in v0.3.0
ListInvites returns the org's live (non-expired) invites.
func (*OrgDB) OrgsFor ¶ added in v0.3.0
OrgsFor returns the orgs the account belongs to, sorted by name.
func (*OrgDB) RecordInviteUse ¶ added in v0.3.0
RecordInviteUse bumps the join counter for an invite (best effort).
func (*OrgDB) Redeem ¶ added in v0.3.0
Redeem consumes nothing — an invite link can onboard a whole team until it expires — it just resolves the token to its live invite.
func (*OrgDB) RemoveMember ¶ added in v0.3.0
RemoveMember drops an account from the org. The last owner cannot be removed (an org must always have someone who can administer it).
func (*OrgDB) RevokeInvite ¶ added in v0.3.0
RevokeInvite deletes an invite so its link stops working immediately.
func (*OrgDB) Role ¶ added in v0.3.0
Role returns the account's role in the org, or "" for non-members.
func (*OrgDB) SetRole ¶ added in v0.3.0
SetRole changes an account's role. Demoting the last owner is refused.
func (*OrgDB) SetSeniority ¶ added in v0.15.0
SetSeniority installs the oldest-first account order (AuthProvider.Accounts). It is set per call rather than at construction because a directory can be rebuilt from its repo at any time, and a tie-break that silently reverts to the address a member typed is round 8's escalation back.
func (*OrgDB) ValidInvite ¶ added in v0.3.0
ValidInvite reports whether a token is a live invite, without consuming it. It lets the signup page permit account creation from an invite link even when public self-signup is closed (invite-only hubs).
type OrgInvite ¶ added in v0.3.0
type OrgInvite struct {
Token string `json:"token"`
Org string `json:"org"`
Creator string `json:"creator,omitempty"` // account email
Created time.Time `json:"created"`
Expires time.Time `json:"expires"`
Uses int `json:"uses"` // how many accounts have joined via this link
}
OrgInvite is a mint-once join link. Redeeming it while signed in adds the account to the org as a member.
type Project ¶
type Project struct {
ID string `json:"id"`
Name string `json:"name"`
Org string `json:"org,omitempty"` // owning organization
Created time.Time `json:"created"`
Description string `json:"description,omitempty"` // optional one-line subtitle
Icon string `json:"icon,omitempty"` // optional lucide icon name
// Creator is the account that first created the project; it gets an
// explicit admin grant at creation. Empty on projects that predate
// per-project permissions — those are governed by org owners.
Creator string `json:"creator,omitempty"`
// Template is the starting structure the project was created from
// (internal/templates), empty for an empty project. Set once, at
// creation, by whoever seeded it — it is what stops a second surface
// seeding a second copy.
Template string `json:"template,omitempty"`
// Default is the level every org member gets without an explicit grant.
// Empty means write: the historical behavior, so no row needs migrating.
Default string `json:"default,omitempty"`
// Perms are the explicit grants, lowercase email → level.
Perms map[string]string `json:"perms,omitempty"`
}
Project is one synced project hosted by this server. Its storage lives under <root>/<id>/ in the object store; the id is permanent, the name is a renameable label.
type ProjectDB ¶
type ProjectDB struct {
// contains filtered or unexported fields
}
ProjectDB is the server's project registry: an in-memory index over a MetaStore ProjectRepo. Reads are served from memory; every change is persisted as one record through the repo (file or SQL).
func NewProjectDB ¶ added in v0.3.0
func NewProjectDB(repo ProjectRepo) (*ProjectDB, error)
NewProjectDB builds the registry over a repo, loading its current contents.
func OpenProjectDB ¶
OpenProjectDB loads the file-backed registry at path (a missing file is an empty registry) — the zero-dependency default.
func (*ProjectDB) ClearPerm ¶ added in v0.11.0
ClearPerm drops an explicit grant, reverting the account to the default.
func (*ProjectDB) Delete ¶ added in v0.3.0
Delete removes a project from the registry. Its storage prefix (blobs, journals) is left in the object store — the id is retired, not scrubbed — so the caller decides whether to reclaim that space out of band.
func (*ProjectDB) GetOrCreate ¶
GetOrCreate returns the project with the given name in the org, creating it (with a fresh id) if none exists. Names are matched exactly, scoped to the org: two organizations can each have a "wiki".
func (*ProjectDB) Rename ¶ added in v0.3.0
Rename changes a project's display name (its id and storage are permanent).
func (*ProjectDB) SetCreator ¶ added in v0.11.0
SetCreator records who created a project (and is its first admin).
func (*ProjectDB) SetDefault ¶ added in v0.11.0
SetDefault sets the level org members get without an explicit grant.
func (*ProjectDB) SetOrg ¶ added in v0.3.0
SetOrg moves a project into an org (used by the startup migration).
func (*ProjectDB) SetPerm ¶ added in v0.11.0
SetPerm grants one account an explicit level on the project. Demoting the last explicit admin is refused, the same shape as OrgDB's last-owner rule: a project must keep someone who can administer it (org owners aside, who are implicitly admin and never appear in this list).
func (*ProjectDB) SetTemplate ¶ added in v0.14.0
SetTemplate records the starting structure a project was seeded from.
type ProjectRepo ¶ added in v0.3.0
type QuotaProvider ¶ added in v0.3.0
type QuotaProvider interface {
// CheckWrite runs before addedBytes land in the org's storage; a non-nil
// error rejects the write (surfaced to the client as 403).
CheckWrite(org string, addedBytes int64) error
// CheckSeat runs before an invite adds a member; members is the current
// count. A non-nil error rejects the join.
CheckSeat(org string, members int) error
// RecordUsage runs after a write succeeds, for accounting.
RecordUsage(org string, addedBytes int64)
// CheckRead runs before bytes are served to an UNAUTHENTICATED reader —
// today that is public share links (/s/*) and nothing else. bytes is the
// size about to be streamed. A non-nil error refuses the transfer and its
// message is shown to the reader, so write it for a stranger who has no
// idea what BearDrive is.
//
// Deliberately NOT called on the sync proxy or the viewer: a device that
// gets refused mid-sync reads it as "access revoked" and stops touching
// the folder, which is a far worse outcome than an over-quota bill. Those
// paths report through RecordEgress and are governed by fair use.
CheckRead(org string, bytes int64) error
// RecordEgress runs after bytes have been served, with the number
// actually written. Every read path reports here — share links, the sync
// proxy, viewer downloads — so egress is measurable even where it is not
// enforced.
RecordEgress(org string, bytes int64)
}
QuotaProvider is the seam a managed deployment uses to enforce plan limits, exactly like AuthProvider is the seam for identity. The open-source server ships only UnlimitedQuota; billing and plan logic live outside this repo. Hooks fire on every write path (browser uploads, the device sync store proxy) and on seat growth, keyed by org id.
type ReadLedger ¶ added in v0.4.0
type ReadLedger struct {
// contains filtered or unexported fields
}
ReadLedger is the in-memory read-telemetry service over a ReadRepo, in the mold of DeviceRegistry: reads stay in memory, writes are throttled. There is no background goroutine — flushes piggyback on Record calls, and telemetry failures never surface to the request that triggered them.
func NewReadLedger ¶ added in v0.4.0
func NewReadLedger(repo ReadRepo, retentionDays int) (*ReadLedger, error)
NewReadLedger loads the ledger and immediately folds buckets older than the retention horizon into their all-time rows. retentionDays <= 0 means the default.
func OpenReadLedger ¶ added in v0.4.0
func OpenReadLedger(path string, retentionDays int) (*ReadLedger, error)
OpenReadLedger loads the file-backed ledger at path.
func (*ReadLedger) AgentHeat ¶ added in v0.4.0
AgentHeat aggregates agent reads per device per top-level folder ("" for root files) — the coverage-matrix data. Agent buckets only, by design: agent actors are device ids, which history already exposes; human actors (emails) must never leave the server, so human/share buckets are not consulted at all.
func (*ReadLedger) Close ¶ added in v0.4.0
func (l *ReadLedger) Close() error
Close flushes any pending buckets.
func (*ReadLedger) Heat ¶ added in v0.4.0
Heat aggregates reads per path for one project. since bounds the window (zero = all time, including retention folds); prefix "" means the whole project, otherwise paths under "<prefix>/".
func (*ReadLedger) Record ¶ added in v0.4.0
func (l *ReadLedger) Record(project, path, kind, actor string)
Record counts one read. Nil-safe and never fails: telemetry must not break the page view (or sync cycle) that triggered it.
func (*ReadLedger) RecordSession ¶ added in v0.15.0
func (l *ReadLedger) RecordSession(project, session, device, path string)
RecordSession notes that one agent session read one path from one device. Nil-safe, off when no session repo is configured, and — like Record — never fails: telemetry must not break the sync cycle that reported it. Unlike Record it is NOT debounced: a row is a fact ("this session read this file"), not a count, so repeats are the same row rewritten.
func (*ReadLedger) SessionPaths ¶ added in v0.15.0
func (l *ReadLedger) SessionPaths(project, session, device string) []string
SessionPaths returns the paths one session read from one device, for the History run card. Both the session and the device are required by the caller (handleHeat): a session-only lookup would return rows a member reported under someone else's session id, which pinning to the validated device is what makes harmless.
func (*ReadLedger) ShareOpens ¶ added in v0.15.0
func (l *ReadLedger) ShareOpens(project string) map[string]ShareOpen
ShareOpens aggregates share-kind reads per path for one project — the receipt a person who shared something actually wants. All-time, because a link's lifetime is the question a receipt answers.
Share buckets only, and that is what makes Last mean *last opened*: HeatEntry.LastRead is cross-kind, so a member viewing the file in the hub would otherwise move the "opened through the link" date.
Counts, never identities — the share actor is token+"/"+IP, a public credential joined to an IP, and it must not leave the ledger. There is deliberately no distinct-openers field.
One byKey scan per project, never one per share: callers build this map once and index it, because byKey is the full map and a project with 40 links would otherwise pay 40 full scans per list render.
func (*ReadLedger) WithSessions ¶ added in v0.15.0
func (l *ReadLedger) WithSessions(repo SessionReadRepo, retentionDays int) *ReadLedger
WithSessions turns on per-session read detail (the data behind a History run card). Separate from the constructor so every existing caller — and every backend that has no session repo — keeps working with it off. retentionDays <= 0 means the default.
type ReadRepo ¶ added in v0.4.0
type ReadRepo interface {
Load() ([]ReadStat, error)
PutBatch(stats []ReadStat) error // upsert by (project, path, day, kind, actor)
DeleteBatch(keys []ReadStatKey) error
}
ReadRepo persists read-telemetry buckets (see ReadStat). Unlike the other repos it is batch-oriented: reads are telemetry, and the ledger flushes many dirty buckets at once — one file rewrite / one SQL transaction per flush, not one write per bucket.
type ReadStat ¶ added in v0.4.0
type ReadStat struct {
Project string `json:"project"`
Path string `json:"path"`
Day string `json:"day"` // "2006-01-02" UTC, or "" for all-time
Kind string `json:"kind"`
Actor string `json:"actor"`
Count int64 `json:"count"`
Last time.Time `json:"last"`
}
ReadStat is one aggregation bucket: reads of one path by one actor on one day. Day == "" is the all-time fold that survives retention.
type ReadStatKey ¶ added in v0.4.0
type ReadStatKey struct {
Project, Path, Day, Kind, Actor string
}
ReadStatKey identifies one bucket.
type RemoteSource ¶
type RemoteSource struct {
Backend remote.Backend
// Device identifies this server in ops it journals for uploads. Required
// for uploads; irrelevant for reading.
Device Identity
// PresignTTL is the lifetime the hub gives a presigned upload URL. It is
// how long a blob stays writable by anyone but the hub, and therefore when
// verify may stop re-hashing it. Zero means DefaultUploadTTL — set it to
// the server's real UploadConfig.ttl(), or a longer configured TTL would
// seal an object that can still change.
PresignTTL time.Duration
// contains filtered or unexported fields
}
RemoteSource reads a beardrive remote: it fetches every journal and folds the ops into the current volume state (same total order as journal.Replay, but keeping author/device/time of the winning op per path). With Device set it also accepts uploads, journaled under that identity.
func (*RemoteSource) Commit ¶
func (r *RemoteSource) Commit(ctx context.Context, p, blob string, size int64, who User, note string) error
Commit appends a put op for path→blob to this server's own journal. It refuses if the blob is not in the store yet (a peer must never see an op whose content is missing). Only this server writes this journal key, so the read-modify-write below has a single writer; upmu serializes it across concurrent requests.
func (*RemoteSource) FilesWithMoves ¶ added in v0.15.0
FilesWithMoves is the replay, plus the rename index derived from the same sorted ops — one pass, so the index rides in the cached snapshot.
func (*RemoteSource) Open ¶
func (r *RemoteSource) Open(ctx context.Context, _ string, fi FileInfo) (io.ReadCloser, error)
func (*RemoteSource) OpenBlob ¶ added in v0.15.0
func (r *RemoteSource) OpenBlob(ctx context.Context, sha string) (io.ReadCloser, error)
OpenBlob is the one way a blob's bytes leave the hub, and on a hub whose storage can presign it is also the only place left that can tell a content address the truth. handleStorePut hashes what it relays — but a presigned PUT writes straight into the object store, so those bytes were never examined by anything: any device with write permission could store arbitrary content under a sha256 it chose, and the viewer, share links, history and every peer would then serve it.
Skipped entirely on a backend that cannot presign, where the write path already checked. It used to be once per blob per process, on the premise that blobs are immutable — which is false on the hub that needs the check: SignPut hands out a URL that stays valid for its whole TTL and an object store accepts every PUT to it, not the first. So uploading the honest bytes, letting one reader populate the cache, and then replaying the same URL with hostile bytes served them under the reviewed sha to the viewer, history, share links and every syncing device.
Verifying on EVERY read closed that, and cost every S3/GCS hub 2x object- store egress and a serialized full-object hash before the reader's first byte — on every viewer open, render, download and /s/* hit. The cache is back, keyed on the one thing that makes the premise TRUE rather than assumed: see verify.
func (*RemoteSource) Remove ¶ added in v0.14.0
Remove appends a delete op for p to this server's own journal. A delete references no content, so there is no blob to push first.
type Server ¶
type Server struct {
// Single-volume mode: serve exactly this source.
Source Source
Volume string // display only
// Hub mode (when Root is set): many projects on one storage root.
Root remote.Backend
Projects *ProjectDB
// Device identifies this server in ops it journals for browser uploads.
Device Identity
Refresh time.Duration
Upload UploadConfig
// Auth, when set, gates the whole API behind sign-in. Nil means the
// historical trusted-network behavior: no accounts, everyone welcome.
Auth AuthProvider
// Devices, when set, records what the server observes about syncing
// devices (name, OS, public IP, last activity) for history.
Devices *DeviceRegistry
Shares *ShareDB
// Reads, when set, aggregates read telemetry (viewer, share, and agent
// reads) for the heat API. Nil means read tracking is off.
Reads *ReadLedger
// Dir, when set, walls projects off by organization membership and owns
// every org read and write the hub performs. LocalDirectory is the
// built-in implementation; a managed deployment supplies its own so that
// orgs come from the same place identities do. Nil means single-volume
// mode: no orgs, every authenticated request passes.
Dir Directory
// Quota, when set, enforces plan limits (managed deployments). Nil
// means UnlimitedQuota: the open-source server never says no.
Quota QuotaProvider
// Billing, when set, surfaces a billing entry in the frontend's account
// menu: the billing page URL plus the signed-in user's current plan name
// (/api/config `billing`). The OSS hub has no billing; managed
// deployments plug this in. Nil — or ok=false for a user with no org —
// hides the entry. The mirror of the Quota seam: Quota enforces the
// plan, Billing displays it.
Billing func(email string) (plan, url string, ok bool)
// Analytics, when its Key is set, tells the frontend to load PostHog
// (/api/config `analytics`). The third managed-deployment seam beside
// Quota and Billing, and deliberately server-supplied rather than
// bundled: with no key the OSS frontend ships no analytics code and
// makes no third-party request, so a self-hosted hub cannot phone home
// even by accident.
Analytics AnalyticsConfig
// 0 means DefaultShareRPM.
ShareRPM int
// TrustProxy honors X-Forwarded-For from ANY peer. Only needed for a
// proxy on a public address: a proxy on loopback or a private network is
// already trusted without it (see clientIP). Setting it on a directly-
// reachable hub lets any client pick its own rate-limit bucket.
TrustProxy bool
// contains filtered or unexported fields
}
Server renders volumes as a website and, in hub mode, brokers sync for client devices.
type SessionRead ¶ added in v0.15.0
type SessionRead struct {
Project string `json:"project"`
Session string `json:"session"`
Device string `json:"device"`
Path string `json:"path"`
Last time.Time `json:"last"`
}
SessionRead records that one agent session read one path, from one device. Not a count and not a bucket: the run card asks "did this session read this file?", and one row per (session, device, path) answers it with no aggregation. Device is always the hub-validated device the report arrived from, never anything the client put in the body.
type SessionReadRepo ¶ added in v0.15.0
type SessionReadRepo interface {
PutBatch(reads []SessionRead) error // upsert by (project, session, device, path)
ListBySession(project, session, device string) ([]SessionRead, error)
PruneBefore(t time.Time) error
}
SessionReadRepo persists which paths one agent session read (see SessionRead). Deliberately its OWN repo rather than a session column on read_stats: ReadLedger loads every read_stats row into one map at boot and ReadLedger.Heat linearly scans that whole map on every heat request, hub-wide — so multiplying its row count by session cardinality would slow the Dashboard for projects that never ran an agent. These rows never enter that map; they are queried by primary key and pruned by date.
func OpenSessionReadRepo ¶ added in v0.15.0
func OpenSessionReadRepo(path string) SessionReadRepo
OpenSessionReadRepo is the file-backed session-read store, for hubs running without a MetaStore (the historical JSON-files layout).
type ShareDB ¶
type ShareDB struct {
// contains filtered or unexported fields
}
ShareDB is the in-memory share registry over a MetaStore ShareRepo.
func NewShareDB ¶ added in v0.3.0
NewShareDB builds the registry over a repo, loading its contents.
func OpenShareDB ¶
OpenShareDB loads the file-backed registry at path.
func (*ShareDB) Create ¶
Create returns a share for (project, path), reusing an existing live one so repeated shares of the same file hand out the same URL.
func (*ShareDB) List ¶
List returns a project's live shares, newest first. The order has to be a total one: byToken is a map, so without a sort every call reshuffles the rows — and these rows carry a Revoke button, so "the second one" must mean the same link on every load.
type ShareOpen ¶ added in v0.15.0
type ShareOpen struct {
}
ShareOpen is share-link consumption for one path: visits, and when.
type SignupPolicy ¶ added in v0.9.0
type SignupPolicy struct {
RequireVerification bool `json:"require_verification"`
RequireApproval bool `json:"require_approval"`
AllowSignup bool `json:"allow_signup"`
AllowedDomains []string `json:"allowed_domains"` // read-only
Admins []string `json:"admins"` // read-only
Mailer bool `json:"mailer"` // SMTP configured?
}
SignupPolicy is what /api/admin/policy reports: which gates are on, and which of them are server-config owned (read-only to a browser session, so that no one can widen access by clicking).
type Source ¶
type Source interface {
Files(ctx context.Context) (map[string]FileInfo, error)
Open(ctx context.Context, path string, fi FileInfo) (io.ReadCloser, error)
}
Source supplies the file set and content of one volume. Implementations: RemoteSource (a beardrive remote) and DirSource (a plain local folder).
type UnlimitedQuota ¶ added in v0.3.0
type UnlimitedQuota struct{}
UnlimitedQuota is the open-source default: everything is allowed.
func (UnlimitedQuota) CheckRead ¶ added in v0.15.0
func (UnlimitedQuota) CheckRead(string, int64) error
func (UnlimitedQuota) CheckSeat ¶ added in v0.3.0
func (UnlimitedQuota) CheckSeat(string, int) error
func (UnlimitedQuota) CheckWrite ¶ added in v0.3.0
func (UnlimitedQuota) CheckWrite(string, int64) error
func (UnlimitedQuota) RecordEgress ¶ added in v0.15.0
func (UnlimitedQuota) RecordEgress(string, int64)
func (UnlimitedQuota) RecordUsage ¶ added in v0.3.0
func (UnlimitedQuota) RecordUsage(string, int64)
type UploadConfig ¶
type UploadConfig struct {
Enabled bool
// TTL bounds the lifetime of presigned direct-upload URLs.
TTL time.Duration
}
UploadConfig controls whether and how clients may write.
type Uploader ¶
type Uploader interface {
Upload(ctx context.Context, path string, r io.Reader, size int64, who User, note string) error
}
Uploader is implemented by sources that accept writes through the server. who is the signed-in account the write should be attributed to (zero when auth is off), and note rides along on the journaled op — "" for an ordinary browser upload, a stated origin when the HUB itself authored the bytes (seedTemplate). Both are on the interface because the journal is the hub's only audit surface: a write with no human behind it must not be able to present as one by omission.
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Admin bool `json:"admin,omitempty"` // hub admin (approve users, govern shares)
}
User is an authenticated account as the rest of the server sees it.
type Versioned ¶ added in v0.15.0
Versioned is the optional "has anything moved?" check on a repository: a token that changes whenever anything the repo stores changes.
Every registry re-reads its whole store on every authorization read (see ProjectDB.refresh) — that is a correctness floor, not a cache, and it stays. This is the same read made cheap: one os.Stat, or one primary-key lookup, instead of a full JSON parse or nine unfiltered SELECTs on every authenticated request. It is NOT a TTL: a token that moved is always followed by the full re-read, so the staleness window rounds 12-14 closed stays closed.
A repo that cannot answer — no implementation, or an error — is treated as changed, so the fallback is exactly the unconditional re-read that was always there. An implementation must never return an empty token.