web

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 38 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 web is the bweb server: a read-only HTTP face over sites kept in bstore buckets. It answers GET and HEAD for anyone, takes each site's behavior from that site's settings, and reads through a Store.

Index

Constants

View Source
const (
	OperatorPath = "/.well-known/bweb/operator"
	ReportPath   = "/.well-known/bweb/report"
)

OperatorPath answers who runs this node and where to report abuse; ReportPath takes reports (POST).

View Source
const HealthPath = "/.well-known/bweb/health"

HealthPath answers 200 on any host name.

View Source
const StatusClientClosed = 499

StatusClientClosed is the status a request is counted under when its reader left before any answer was written. It is never sent.

Variables

View Source
var ErrBusy = errors.New("store: too many reads in flight")

ErrBusy is a read refused because every slot to the store stayed taken for the whole wait.

View Source
var ErrSlowDown = errors.New("store: the store refused the read (503)")

ErrSlowDown is a read the store refused because it is shedding load.

Functions

func KeepAsking added in v0.7.0

func KeepAsking(ctx context.Context, a *engineask.Asker, after <-chan struct{}) <-chan struct{}

KeepAsking keeps a's ask alive until ctx ends, once the ask it replaces (after, nil for none) has stopped: the new ask is sent, sent once more askSettle later, and then kept by a.Run. It closes what it returns when it has stopped.

func LoadKey added in v0.9.0

func LoadKey(path string) (*ec.PrivateKey, error)

LoadKey reads a key file: 64 hex digits.

func LoopbackAddr added in v0.7.0

func LoopbackAddr(addr string) error

LoopbackAddr reports whether addr is a loopback address and a port, as the checker's listen must be: an IP literal, never a name or an empty host (which is every address).

func SiteBucket added in v0.7.0

func SiteBucket(rec *siterec.Site) string

SiteBucket is a site record's bucket as an ask names it, "<name>:<owner>:<id>".

func TopicSettings added in v0.7.0

func TopicSettings(site [32]byte, bucket string) map[string][]string

TopicSettings are what a site's ask carries: the site's own topic, and, once its record names the bucket ("<name>:<owner>:<id>"), the bucket's two topics and the bucket itself.

Types

type Answer

type Answer = challenge.Answer

Answer is a store's answer to one read. Body is never nil; the caller closes it. A Body that is an io.WriterTo is written by it: the store fetches and checks as it writes, and an error from it before its first byte means the read failed with nothing sent. It is the challenge package's type, so a Store is a challenge Reference.

type CheckConfig added in v0.7.0

type CheckConfig struct {
	// Listen is the checker's address: a loopback address and a port.
	Listen string `json:"listen,omitempty"`
	// TokenFile, when set, holds a bearer token every request must carry.
	TokenFile string `json:"token_file,omitempty"`
	// CacheSeconds is how long a verdict stands (default and at most 60).
	CacheSeconds int `json:"cache_seconds,omitempty"`
	// MaxChecks bounds the challenges run at once (default 8), MaxAddrs
	// the addresses one request names (default 16), and MaxServers the
	// entries one advertised answer challenges (default 64).
	MaxChecks  int `json:"max_checks,omitempty"`
	MaxAddrs   int `json:"max_addrs,omitempty"`
	MaxServers int `json:"max_servers,omitempty"`
	// Samples is the reads in one challenge (default 3: the directory
	// path, an absent key and one drawn key); FirstByteMS the bound on
	// each read's first byte (default 2000).
	Samples     int `json:"samples,omitempty"`
	FirstByteMS int `json:"first_byte_ms,omitempty"`
	// Private are address ranges (CIDR) a challenge may dial although
	// they are loopback, private, link-local or reserved. None by default.
	Private []string `json:"private,omitempty"`
	// Network and Headers name the header source every proof is checked
	// against, as the host block's keys: an empty Headers is
	// woc:<network>.
	Network string `json:"network,omitempty"`
	Headers string `json:"headers,omitempty"`
	// contains filtered or unexported fields
}

CheckConfig is the loopback checker's settings (bweb check, docs/check.md). It reads a site's record and advertisements from the node's engine (engine.url), the site's content from the bstore gateway's S3 face (store.endpoint), and proves both against its own header source.

func (CheckConfig) HeadersSpec added in v0.7.0

func (k CheckConfig) HeadersSpec() (string, error)

HeadersSpec is the header source in force.

func (CheckConfig) PrivateNets added in v0.7.0

func (k CheckConfig) PrivateNets() []*net.IPNet

PrivateNets are the Private ranges, parsed.

func (CheckConfig) Token added in v0.7.0

func (k CheckConfig) Token() string

Token is the bearer token read from TokenFile, or empty.

type Config

type Config struct {
	// Listen is the address the server answers on. A web server the
	// operator already runs sits in front of it and supplies TLS.
	Listen string `json:"listen"`
	// Store names where objects are read from.
	Store StoreConfig `json:"store"`
	// MetricsListen is an address the server's metrics are served on
	// (/metrics, Prometheus form); PprofListen one for Go's profiles
	// (/debug/pprof). Loopback or a private address: neither is for
	// readers. Optional.
	MetricsListen string `json:"metrics_listen,omitempty"`
	PprofListen   string `json:"pprof_listen,omitempty"`
	// DenyFile is a list of what this server refuses to serve, one entry a
	// line (see Deny). Optional.
	DenyFile string `json:"deny_file,omitempty"`
	// Operator is the abuse desk: a contact, signed reports taken at
	// /.well-known/bweb/report, recognized reporters applied at once, and a
	// signed log of every decision. Needs DenyFile.
	Operator *OperatorConfig `json:"operator,omitempty"`
	// Engine names the node's own overlay engine, where a site's record is
	// read from. Required when a site names no bucket.
	Engine EngineConfig `json:"engine,omitzero"`
	// Host is the node's own wallet and its view of the chain, for what a
	// host publishes itself: its serving advertisements. Optional; a node
	// without it serves and advertises nothing.
	Host HostConfig `json:"host,omitzero"`
	// Publisher is a site owner's side: the wallet that pays for a site's
	// tokens and the engines they are submitted to (bweb site). A node
	// that only serves has none.
	Publisher PublisherConfig `json:"publisher,omitzero"`
	// Check is the loopback checker, bweb check (docs/check.md): it
	// answers whether servers serve a site, for a renderer on the same
	// node. A node that runs no checker has none.
	Check CheckConfig `json:"check,omitzero"`
	// Sites are the sites served. A site that names a bucket takes its
	// settings from this file. A site that names none is read from its
	// record (docs/spec.md section 2): its id is the site id, 64 lower-case
	// hex digits, and everything but hosts comes from the record.
	Sites []Site `json:"sites"`
}

Config is the server's configuration file.

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig reads and checks a configuration file.

type Deny

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

Deny is what a server refuses to serve: a site by its identifier, every site of an owner key, a host name, an object by its closure root or by its content hash. One entry a line, "site:<id>", "owner:<key>", "host:<name>", "root:<hex>" or "sha256:<hex>", or any of them hashed, "h:<SHA-256 of the entry>", so a list of the worst content can be shared without being a directory of it. Blank lines and anything after a # are skipped. The file is read again when it changes.

func OpenDeny

func OpenDeny(path string) (*Deny, error)

OpenDeny reads a deny list; an empty path is a list that denies nothing.

func (*Deny) Has

func (d *Deny) Has(kind, value string) bool

Has reports whether kind:value is denied.

func (*Deny) Refuses added in v0.9.0

func (d *Deny) Refuses(site *Site, host string) string

Refuses reports what of a site a request reaches is on the list, before the store is asked: the site, its owner, or the name it was asked by. It answers the kind that matched, or "".

type EngineConfig added in v0.3.0

type EngineConfig struct {
	// URL is the engine's base URL, such as http://127.0.0.1:8280.
	URL string `json:"url,omitempty"`
	// Submit is where the node's own records (its advertisements) are
	// published: empty for the engine at URL, or an overlay bridge's
	// facade, which hands them to its engine and carries them on the plane
	// to every engine that takes the site's topic, so a race client or a
	// renderer asking any of them finds this node. Lookups still go to URL.
	Submit string `json:"submit,omitempty"`
	// RefreshMS is how often each site's record is read again (default
	// 2000): how soon a new token's settings are served.
	RefreshMS int `json:"refresh_ms,omitempty"`
	// AskTopics has the server ask the engine to carry each record site's
	// topics (POST /admin/topics, engines with topics on demand): the
	// site's own topic and, once its record names the bucket, the bucket's
	// two. Off, the engine's own settings must name them.
	AskTopics bool `json:"ask_topics,omitempty"`
	// AskTTLSeconds is an ask's lifetime (default 600); it is asked again
	// at half of it. An engine refuses one above its own bound.
	AskTTLSeconds int `json:"ask_ttl_seconds,omitempty"`
}

EngineConfig names the overlay engine on the same host.

type GatewayStore added in v0.5.0

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

GatewayStore reads from a bstore gateway running in this process: the gateway `bstore s3d run` runs, opened from the same configuration file, read by a call. Every check an S3 read makes is made; the signature, the HTTP exchange and a second process are not.

func NewGatewayStore added in v0.5.0

func NewGatewayStore(ctx context.Context, c StoreConfig, logf func(string, ...any)) (*GatewayStore, error)

NewGatewayStore opens the gateway whose configuration c names. The identities that configuration names must exist (`bstore s3d init`), and no other process may run it.

func (*GatewayStore) AddBucket added in v0.8.0

func (s *GatewayStore) AddBucket(bucket, owner, id string) error

AddBucket has the gateway serve a record's bucket (Records' AddBucket): a site whose record names this node, with no configuration change. The gateway compares the whole chain (bucket, owner, id): one it serves already is no change, on any gateway; another chain under the same S3 name is refused, so a record cannot borrow a served bucket's name; a new bucket needs the gateway configured read_only (bstore 0.38.1).

func (*GatewayStore) Buckets added in v0.5.0

func (s *GatewayStore) Buckets() []string

Buckets are the S3 names of the buckets the gateway serves.

func (*GatewayStore) Close added in v0.5.0

func (s *GatewayStore) Close() error

Close stops the gateway.

func (GatewayStore) Instrument added in v0.5.0

func (s GatewayStore) Instrument(m *Metrics)

Instrument has the store count its reads in m.

func (*GatewayStore) Read added in v0.5.0

func (s *GatewayStore) Read(ctx context.Context, bucket, key string, head bool, cond http.Header) (*Answer, error)

type HeaderRule

type HeaderRule struct {
	Prefix string            `json:"prefix,omitempty"`
	Suffix string            `json:"suffix,omitempty"`
	Set    map[string]string `json:"set"`
}

HeaderRule sets response headers on paths with a prefix and a suffix (either may be empty).

type HostConfig added in v0.3.0

type HostConfig struct {
	// Data is the directory that holds the wallet (bweb init) and the
	// host's state. Mode 0700; it holds a private key.
	Data string `json:"data,omitempty"`
	// Network is main, test or regtest.
	Network string `json:"network,omitempty"`
	// Chain is the chain view (woc:main, woc:test, asset:URL); empty is
	// woc:<network>. Settle is the settlement leg (arcade:URL, arc:URL,
	// rpc:URL); empty is the network's public arcade. Headers is the
	// header source; empty is woc:<network>. A regtest chain names all
	// three.
	Chain   string `json:"chain,omitempty"`
	Settle  string `json:"settle,omitempty"`
	Headers string `json:"headers,omitempty"`
	// ArcadeKey is the bearer token of an arcade or ARC leg; RPCUser and
	// RPCPassFile authenticate an rpc: leg.
	ArcadeKey   string `json:"arcade_key,omitempty"`
	RPCUser     string `json:"rpc_user,omitempty"`
	RPCPassFile string `json:"rpc_pass_file,omitempty"`
	// Fee is the miner fee policy, bstore's fee block; absent is 100
	// satoshis per 1,000 bytes.
	Fee *feepolicy.Config `json:"fee,omitempty"`

	// URL is where this node serves, as readers and auditors reach it: a
	// scheme, a host and optionally a port, nothing else. Set, the node
	// advertises the record sites it serves (docs/spec.md section 4);
	// empty, it advertises nothing.
	URL string `json:"url,omitempty"`
	// Location is the node's IATA metro code, Country its ISO 3166-1
	// alpha-2 code and Subdivision its ISO 3166-2 code (optional).
	Location    string `json:"location,omitempty"`
	Country     string `json:"country,omitempty"`
	Subdivision string `json:"subdivision,omitempty"`
	// Advertise says which served sites are advertised: "terms" (the
	// default), those with hosting terms open; "always", every one.
	Advertise string `json:"advertise,omitempty"`
	// TermSeconds is how long an advertisement lasts (default 86400, at
	// least 600). RenewBeforeSeconds is how long before its expiry it is
	// renewed (default a quarter of the term).
	TermSeconds        int `json:"term_seconds,omitempty"`
	RenewBeforeSeconds int `json:"renew_before_seconds,omitempty"`
	// contains filtered or unexported fields
}

HostConfig is a host's wallet and chain settings. The chain keys are bstore's (bstore docs/provider.md, chaincfg): the same keys mean the same thing.

func (HostConfig) Spec added in v0.3.0

func (h HostConfig) Spec() chaincfg.Spec

Spec is the chain settings as bstore's chaincfg reads them.

type Metrics added in v0.3.0

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

Metrics are the server's counters, in Prometheus form. Every method is safe on a nil Metrics, so a server built without one runs unchanged.

What they are for, by the USE method: utilization (requests and reads in flight, read slots in use against their bound), saturation (the wait for a read slot, reads refused busy, the store's SlowDown), errors (answers by status, store reads by result).

func NewMetrics added in v0.3.0

func NewMetrics(version string) *Metrics

NewMetrics are metrics for one server, with the Go runtime's and the process's own.

func (*Metrics) Ad added in v0.3.0

func (m *Metrics) Ad(event string)

Ad counts an advertisement event: minted, mined, published or dropped.

func (*Metrics) Handler added in v0.3.0

func (m *Metrics) Handler() http.Handler

Handler serves the metrics.

func (*Metrics) Registerer added in v0.7.0

func (m *Metrics) Registerer() prometheus.Registerer

Registerer is where another part of the process (bweb check) registers its own metrics, served with these.

func (*Metrics) Wallet added in v0.3.0

func (m *Metrics) Wallet(outputs int, satoshis uint64)

Wallet records the host wallet's coin.

type Object added in v0.5.0

type Object = challenge.Object

Object is one object of a listing: the challenge package's type.

type Operator added in v0.9.0

type Operator struct {
	Desk    *abuse.Desk
	Contact string
	Policy  string
	// contains filtered or unexported fields
}

Operator serves the operator routes.

func NewOperator added in v0.9.0

func NewOperator(c *OperatorConfig, denyFile string) (*Operator, error)

NewOperator opens the desk c names, with the deny list at denyFile.

type OperatorConfig added in v0.9.0

type OperatorConfig struct {
	Contact    string   `json:"contact"`              // the abuse contact: an address or a URL
	Policy     string   `json:"policy,omitempty"`     // the policy URL, linked from every refusal
	Dir        string   `json:"dir"`                  // reports (queue/, done/) and actions.log
	KeyFile    string   `json:"key_file"`             // the operator's key, 64 hex digits (bweb abuse keygen)
	Recognized []string `json:"recognized,omitempty"` // reporter keys whose reports are applied at once
	PerMinute  int      `json:"reports_per_minute,omitempty"`
	MaxQueue   int      `json:"max_queue,omitempty"` // reports waiting from reporters not recognized (default 1,000)
	// TrustedProxies are the front servers (addresses or CIDRs) whose
	// X-Forwarded-For names the reporter's address for the per-address
	// bound. Any other request is bounded by its own address, and the
	// header is never read from it.
	TrustedProxies []string `json:"trusted_proxies,omitempty"`
}

OperatorConfig is the operator's abuse desk: a contact and a policy every reader and reporter can find, reports taken at ReportPath and kept under Dir, the reporters whose reports apply at once, and the key that signs each decision in Dir/actions.log. It needs deny_file: a refusal is an entry there.

type OrgConfig added in v0.8.0

type OrgConfig struct {
	Hall  string   `json:"hall"`
	Key   string   `json:"key"`
	Hosts []string `json:"hosts"`
}

OrgConfig names a borg organization: its hall, its key (66 hex digits) and the hosts its records are read from.

type PublisherConfig added in v0.3.0

type PublisherConfig struct {
	HostConfig
	// IdentityFile is the bucket owner's identity: a site's key is its
	// bucket owner's key. Empty, the identity is the one bweb init made
	// under data. The coin is kept under data either way, apart from the
	// owner's bstore wallet.
	IdentityFile string `json:"identity_file,omitempty"`
	// Engines are the overlay engines a site's tokens and a race's
	// records are submitted to, and that a race asks for the servers
	// advertising a site: every one of them, since a server publishes its
	// advertisement at its own engine.
	Engines []string `json:"engines,omitempty"`
	// ChallengePrivate lets a race challenge a server whose advertised
	// address is loopback, private or link-local. Off (the default), such
	// an address fails its challenge unread: an advertisement is anyone's,
	// and its URL must not point the publisher's client at its own
	// network.
	ChallengePrivate bool `json:"challenge_private,omitempty"`
	// Org is the borg organization whose permission bweb/write/<site> lets
	// a delegate's entries in a site's bucket be applied (bweb site
	// anchor). Delegates are their keys, named as writers of the bucket
	// (bstore anchor -add-writer). Bstore is the bstore command (default
	// "bstore") and BstoreHome the owner's bstore home it anchors from.
	Org        *OrgConfig `json:"org,omitempty"`
	Delegates  []string   `json:"delegates,omitempty"`
	Bstore     string     `json:"bstore,omitempty"`
	BstoreHome string     `json:"bstore_home,omitempty"`
}

PublisherConfig is a site owner's wallet, chain settings and engines. The wallet and chain keys are HostConfig's; the advertisement keys are not a publisher's and are refused.

type Records added in v0.3.0

type Records struct {

	// AddBucket, when set, makes the node's store serve a bucket a site's
	// record names (its identifier, owner and id, as hex): sites on
	// demand, with no configuration change and no restart. Each bucket is
	// added once; one that fails is tried again at the next poll, and the
	// site is not served until it is added.
	AddBucket func(bucket, owner, id string) error
	// contains filtered or unexported fields
}

Records keeps the server's sites current with their records: for each site the configuration names without a bucket, it asks the node's own overlay engine (ls_bweb) for the site's latest token and serves the settings that token carries.

The engine admitted the token against the chain's headers, and it is the node's own, asked over loopback: Records checks that the token is the site's (its id, its owner's lock and signature) and does not check the proof again.

A site with no token (not yet arrived, or closed) is not served. An engine that does not answer changes nothing: the last settings read stand, so an engine restart does not take a site down.

func NewRecords added in v0.3.0

func NewRecords(c *Config, srv *Server) *Records

NewRecords watches the record sites of c for srv. It returns nil when c names none.

func (*Records) Poll added in v0.3.0

func (r *Records) Poll(ctx context.Context)

Poll reads every site's record once and serves what it found.

func (*Records) Run added in v0.3.0

func (r *Records) Run(ctx context.Context)

Run reads every site's record at once and again every refresh interval, until ctx is done.

func (*Records) Served added in v0.3.0

func (r *Records) Served() []string

Served are the record sites served now: those with a token that says public. A site's id is in hex.

func (*Records) Sites added in v0.3.0

func (r *Records) Sites() []string

Sites are the ids of the sites read from their records, in hex.

type S3Store

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

S3Store reads from an S3 endpoint, path style, Signature Version 4.

func NewS3Store

func NewS3Store(c StoreConfig) (*S3Store, error)

NewS3Store is a store over the endpoint c names.

func (S3Store) Instrument added in v0.3.0

func (s S3Store) Instrument(m *Metrics)

Instrument has the store count its reads in m.

func (*S3Store) List added in v0.5.0

func (s *S3Store) List(ctx context.Context, bucket, after string) ([]Object, bool, error)

List is one page of a bucket's objects whose keys come after the key given, in key order (ListObjectsV2), and whether there are more. It takes no read slot: a listing is a publisher's, not a reader's.

func (*S3Store) Read

func (s *S3Store) Read(ctx context.Context, bucket, key string, head bool, cond http.Header) (*Answer, error)

type Server

type Server struct {

	// Policy is the operator's policy URL, named in every refusal
	// (Link rel="blocked-by", RFC 7725).
	Policy string
	// Operator, when set, answers the operator and report routes.
	Operator *Operator

	// Metrics, when set, counts every answer.
	Metrics *Metrics
	// contains filtered or unexported fields
}

Server answers readers.

func NewServer

func NewServer(c *Config, store Store, deny *Deny) *Server

NewServer is a server for the sites of c, reading from store.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) SetSites added in v0.3.0

func (s *Server) SetSites(sites []*Site)

SetSites replaces the sites served, by host. A name two sites carry goes to the first. Requests in flight finish on the site they started with.

type Site

type Site struct {
	ID string `json:"id"` // the site identifier; the site id in hex when read from its record
	// Hosts are the names it answers to, lower case, no port. For a site
	// read from its record they are optional: given, they are the names
	// this node binds to the site, whatever the record claims; omitted,
	// the record's names are used.
	Hosts  []string `json:"hosts,omitempty"`
	Bucket string   `json:"bucket,omitempty"` // the bucket's S3 name; empty to read the site from its record
	Owner  string   `json:"-"`                // the owner's key, hex, from the site's record (deny list owner: entries)
	Index  string   `json:"index"`            // the index document suffix, "index.html"
	Error  string   `json:"error"`            // the error document key, "404.html"; optional
	Public bool     `json:"public"`           // only a public site is served
	// Headers are response headers set by path, first match of each name
	// wins, in order.
	Headers []HeaderRule `json:"headers,omitempty"`
}

Site is one site's settings: the S3 website configuration, with the names it answers to and the bucket it reads.

type Store

type Store interface {
	// Read asks for an object. head asks for no body. cond carries the
	// request's Range and conditional headers. The answer's Status is 200,
	// 206, 304, 404, 412 or 416; anything else is an error.
	Read(ctx context.Context, bucket, key string, head bool, cond http.Header) (*Answer, error)
}

Store is where the server reads objects: a bstore gateway, which proves every answer before it gives it. The S3 store reads through a gateway beside the server; the gateway store runs the gateway in the server's own process.

type StoreConfig

type StoreConfig struct {
	// Gateway is the path of a bstore gateway configuration (bstore
	// docs/s3.md). The gateway then runs inside bweb, which reads it by a
	// call: no S3 endpoint, access key or secret is given, and no
	// `bstore s3d run` is started for it.
	Gateway string `json:"gateway,omitempty"`
	// GatewayS3 also serves that gateway's S3 face at its own `listen`,
	// for other clients of the node's store.
	GatewayS3  bool   `json:"gateway_s3,omitempty"`
	Endpoint   string `json:"endpoint,omitempty"` // http://127.0.0.1:9000
	Region     string `json:"region"`
	AccessKey  string `json:"access_key"`
	Secret     string `json:"secret,omitempty"`
	SecretFile string `json:"secret_file,omitempty"`
	// MaxReads bounds the reads in flight to the store (default 24). A
	// gateway sheds reads past its own bound (bstore's limits.reads, 32 by
	// default); staying under it turns a burst into a short wait here
	// instead of refusals there.
	MaxReads int `json:"max_reads,omitempty"`
	// ReadWaitMS is how long a read waits for a slot before it is refused
	// with 503 (default 2000).
	ReadWaitMS int `json:"read_wait_ms,omitempty"`
}

StoreConfig names the node's bstore gateway: one running in this process (Gateway), or the S3 endpoint of one beside it (Endpoint and its key).

Jump to

Keyboard shortcuts

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