sites

package
v0.16.521 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 33 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 sites publishes static sites: a site is a name in a space, a deployment is an immutable snapshot of files (a manifest of path → sha256 and blobs addressed by that hash), and the site's "current" alias points at one deployment. The same code runs inside the hub and, with its own database, as a standalone server.

Index

Constants

View Source
const (
	RoleOwner  = store.RoleOwner
	RoleMember = store.RoleMember
)

Role names, as the hub spells them.

View Source
const (
	// AccessTeam is the default: only people of the site's space.
	AccessTeam = "team"
	// AccessLink is «все, у кого есть ссылка»: anyone with the address.
	AccessLink = "link"
)

Access says who may open a site.

View Source
const (

	// MachineSessionTTL is how long a publishing session lasts.
	MachineSessionTTL = 30 * time.Minute
	// MachineIDPrefix starts the id sites made by a machine carry, apart from every person's id.
	MachineIDPrefix = "machine:"
)
View Source
const (
	MaxSiteName   = 30
	MaxSpaceLabel = 20
)
View Source
const MaxScanBytes = 2 << 20

MaxScanBytes is how much of a file is read for secrets; the scan is for text, which sites are mostly made of.

View Source
const PathCSP = "sandbox allow-scripts allow-forms allow-popups allow-modals"

PathCSP is what the path fallback sends with every page: the site runs on the server's own origin, so it is sandboxed into an opaque one (no allow-same-origin) and cannot touch the server's cookies or API.

View Source
const SessionTTL = 12 * time.Hour

SessionTTL is how long a site's cookie holds.

View Source
const TicketParam = "hl_site_ticket"

TicketParam is the query parameter a ticket arrives in.

View Source
const TicketTTL = 60 * time.Second

TicketTTL is how long a ticket can be redeemed; a ticket opens one host, once.

Variables

View Source
var DefaultLimits = Limits{
	MaxDeployBytes:   100 << 20,
	MaxFileBytes:     32 << 20,
	MaxFiles:         5000,
	MaxSitesPerSpace: 50,
	KeepVersions:     20,
}

DefaultLimits are the limits of v1.

View Source
var ErrBlobNotFound = errors.New("blob not found")

ErrBlobNotFound is what Open returns for a hash the store does not hold.

View Source
var ErrNotFound = store.ErrNotFound

ErrNotFound is what a lookup that finds nothing returns.

Functions

func CleanPath

func CleanPath(p string) (string, error)

CleanPath turns a path of an upload into the manifest's form or refuses it: no absolute paths, no "..", no empty segments, no backslashes, no control characters, nothing under .git.

func HostName

func HostName(host string) string

HostName is a request host without the port, the trailing dot and the case.

func ScanContent

func ScanContent(b []byte) string

ScanContent says which rule a file's content breaks, or "". Binary files (a NUL in the first bytes) are skipped.

func ValidHash

func ValidHash(s string) bool

ValidHash says whether s is a lower-case hex sha256.

func ValidSiteName

func ValidSiteName(s string) error

ValidSiteName checks a site's name: 1–30 of [a-z0-9-], no "--", not a reserved word.

func ValidSpaceLabel

func ValidSpaceLabel(s string) error

ValidSpaceLabel checks the space part of an address: 1–20 of [a-z0-9-], no "--".

Types

type Addr

type Addr struct {
	Site, Space string
	Kind        Kind
	N           int
}

Addr is a parsed site address.

func ParseHost

func ParseHost(host, domain string) (Addr, bool)

ParseHost reads a site address out of a request host: exactly one label in front of the domain.

func (Addr) Host

func (a Addr) Host(domain string) string

Host is the address under the sites domain.

func (Addr) Label

func (a Addr) Label() string

Label is the single DNS label of the address: <site>--<space>, <site>--v<N>--<space>, <site>--pr-<N>--<space>.

type Authority

type Authority interface {
	// Person is the signed-in person behind a management request; nil, nil when there is none.
	Person(r *http.Request) (*Person, error)
	// Role is the person's role in the space («owner», «member») and "" when they have none.
	Role(ctx context.Context, personID, space string) (string, error)
	// MachineOK says whether the machine is still one of the space's and, when the session names a person it publishes for,
	// whether that person is still a member. A removed machine ends its sessions through this.
	MachineOK(ctx context.Context, machineID, personID, space string) bool
	// CanView says whether the person may open the space's team-only sites.
	CanView(ctx context.Context, personID, space string) (bool, error)
	// ViewerEntry is where an anonymous visitor of a team-only site is sent to sign in; the entry sends them back to
	// returnURL with a ticket.
	ViewerEntry(host, returnURL string) string
	Tickets
	// IssueTicket makes a ticket for the person to open host.
	IssueTicket(personID, host string) string
}

Authority is what the sites service asks of its host: who is calling, what a person may do in a space, and how a person who is not signed in at a site gets a ticket. The hub implements it with its sessions and spaces; a standalone server with an admin token and a trusted gateway.

type Blobs

type Blobs interface {
	Has(ctx context.Context, hash string) (bool, error)
	// Put stores exactly size bytes read from r under hash. The caller has checked that they hash to it.
	Put(ctx context.Context, hash string, r io.Reader, size int64) error
	// Open returns the content and its size; ErrBlobNotFound when there is none.
	Open(ctx context.Context, hash string) (io.ReadCloser, int64, error)
	Delete(ctx context.Context, hash string) error
}

Blobs holds the content of files by the sha256 of that content. A blob is immutable: putting the same hash twice is the same file.

type Config

type Config struct {
	// Domain is the wildcard domain sites live under (sites.example.com), with :port when it is not the default. Empty:
	// the path fallback only.
	Domain string
	// PublicURL is the address of the server itself (https://hub.example.com), without a trailing slash; the path
	// fallback and the sign-in entry hang off it.
	PublicURL string
	// Secure says that sites are served over https.
	Secure bool
	Limits Limits
	// AbuseURL is where the 404 page of the bare domain sends a complaint.
	AbuseURL string
	// StripHeaderPrefixes are the lower-case prefixes of request headers the edge drops: the ones a gateway in front uses
	// to carry identity must never reach a site, nor be forged by a visitor. Empty means the default, x-preview-.
	StripHeaderPrefixes []string
	// Key signs the sites' cookies; at least 32 bytes.
	Key []byte
	// SPAFallback is the default for a new site.
	SPAFallback bool
}

Config is how the service is set up.

type Deployment

type Deployment struct {
	ID         string
	SiteID     string
	Version    int
	Manifest   Manifest
	FileCount  int
	TotalBytes int64
	Source     string
	CreatedBy  string
	CreatedAt  time.Time
}

Deployment is one immutable snapshot of a site.

type Deps

type Deps struct {
	DB     *store.DB
	Blobs  Blobs
	Auth   Authority
	Config Config
	Log    *slog.Logger
	// Now is the clock; nil means time.Now.
	Now func() time.Time
}

Deps are what the service is built from.

type File

type File struct {
	Hash string `json:"hash"`
	Size int64  `json:"size"`
}

File is one file of a deployment: its content's sha256 (lower-case hex) and size.

type Finding

type Finding struct {
	Path string `json:"path"`
	Rule string `json:"rule"`
}

Finding is a file that looks like it holds a secret. It never carries the secret itself.

func ScanPaths

func ScanPaths(m Manifest) []Finding

ScanPaths finds the files whose names say "secret": .env, keys and certificates with private halves.

type FolderBlobs

type FolderBlobs struct{ Root string }

FolderBlobs keeps blobs as files in a folder (the self-hosted default): <root>/ab/abcdef….

func NewFolderBlobs

func NewFolderBlobs(root string) (*FolderBlobs, error)

NewFolderBlobs makes the folder store, creating the folder.

func (*FolderBlobs) Delete

func (f *FolderBlobs) Delete(_ context.Context, hash string) error

func (*FolderBlobs) Has

func (f *FolderBlobs) Has(_ context.Context, hash string) (bool, error)

func (*FolderBlobs) Open

func (f *FolderBlobs) Open(_ context.Context, hash string) (io.ReadCloser, int64, error)

func (*FolderBlobs) Put

func (f *FolderBlobs) Put(_ context.Context, hash string, r io.Reader, size int64) error

type GatewayAuthority

type GatewayAuthority struct {
	// AdminToken is the bearer secret that may manage every space's sites. Empty: no management over HTTP.
	AdminToken string
	// LoginURL is the gateway's entry for a visitor who is not signed in; it gets ?host=…&return=….
	LoginURL string
	*HMACTickets
}

GatewayAuthority is the authority of a standalone sites server: management requests carry an admin token, and visitors of team-only sites come with tickets that the gateway in front of it signs (HMACTickets). The gateway signs the person in by its own means and decides who may open which site; the server only trusts its tickets.

func (*GatewayAuthority) CanView

CanView: the gateway decided before it made the ticket.

func (*GatewayAuthority) IssueTicket

func (g *GatewayAuthority) IssueTicket(personID, host string) string

func (*GatewayAuthority) MachineOK

MachineOK: a standalone server has no machines.

func (*GatewayAuthority) Person

func (g *GatewayAuthority) Person(r *http.Request) (*Person, error)

func (*GatewayAuthority) Role

Role: the admin token manages every space.

func (*GatewayAuthority) ViewerEntry

func (g *GatewayAuthority) ViewerEntry(host, returnURL string) string

type HMACTickets

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

HMACTickets are tickets signed with a key the gateway and the sites server share. The gateway authenticates the person by its own means, checks that they may open the site, and sends the browser to the site's address with the ticket; the server redeems it for a cookie.

func NewHMACTickets

func NewHMACTickets(key []byte, now func() time.Time) *HMACTickets

NewHMACTickets makes the ticket service; now may be nil.

func (*HMACTickets) Issue

func (t *HMACTickets) Issue(userID, host string) string

Issue makes a ticket for userID to open host.

func (*HMACTickets) Redeem

func (t *HMACTickets) Redeem(ticket, host string) (string, bool)

Redeem checks the signature, the host, the expiry and that the ticket has not been used.

type HashReader

type HashReader struct {
	N int64
	// contains filtered or unexported fields
}

HashReader hashes what is read through it.

func NewHashReader

func NewHashReader(r io.Reader) *HashReader

NewHashReader wraps r.

func (*HashReader) Read

func (h *HashReader) Read(p []byte) (int, error)

func (*HashReader) Sum

func (h *HashReader) Sum() string

Sum is the hex sha256 of what has been read.

type Kind

type Kind int

Kind is which deployment of a site an address opens.

const (
	// KindCurrent follows the site's "current" alias.
	KindCurrent Kind = iota
	// KindVersion is one numbered deployment, whatever is current now.
	KindVersion
	// KindPreview is the preview of a branch or pull request; reserved, the edge answers 404 for it for now.
	KindPreview
)

type Limits

type Limits struct {
	MaxDeployBytes   int64
	MaxFileBytes     int64
	MaxFiles         int
	MaxSitesPerSpace int
	KeepVersions     int
}

Limits bound one deployment and one space.

type MachineSession

type MachineSession struct {
	Space     string
	MachineID string
	// PersonID is the member of the space the machine publishes for; empty when the machine did not say.
	PersonID string
	// Name is what is shown as the author: the person's, else the machine's.
	Name string
}

MachineSession is who a publishing session stands for.

func (MachineSession) ID

func (m MachineSession) ID() string

ID is the stable id of the sites this machine makes.

type Manifest

type Manifest map[string]File

Manifest is a deployment: path (slash separated, relative) → file.

func (Manifest) Hashes

func (m Manifest) Hashes() []string

Hashes are the distinct content hashes, sorted (descending, only to be stable).

func (Manifest) PathsOf

func (m Manifest) PathsOf(hash string) []string

PathsOf are the paths that hold the content with this hash, sorted.

func (Manifest) TotalBytes

func (m Manifest) TotalBytes() int64

TotalBytes is the sum of the file sizes.

func (Manifest) Validate

func (m Manifest) Validate(l Limits) error

Validate checks every path, hash and size and the limits.

type MigrateReport added in v0.16.154

type MigrateReport struct {
	Found   int   // blob files in the folder
	Copied  int   // put into the destination
	Present int   // already there, left as they were
	Bytes   int64 // bytes copied
	Removed int   // source files removed (only with removeSource)
	Skipped []string
}

MigrateReport is what Migrate did.

func Migrate added in v0.16.154

func Migrate(ctx context.Context, root string, dst Blobs, dry, removeSource bool) (MigrateReport, error)

Migrate copies every blob of the folder store at root into dst: the move of a hub's sites from its data folder to a bucket. It is safe to run again, and to run while the hub runs on the folder: a blob already in dst is left alone, and a file whose content does not hash to its name is skipped and reported, never copied. With dry nothing is written. With removeSource a blob is removed from the folder once the destination has it.

type Pending

type Pending struct {
	ID        string
	SiteID    string
	Manifest  Manifest
	Source    string
	CreatedBy string
	CreatedAt time.Time
	ExpiresAt time.Time
	// AllowSecrets is the uploader's «yes, I know» to the secret scan.
	AllowSecrets bool
}

Pending is an upload announced and not yet committed.

type Person

type Person struct {
	ID   string
	Name string
}

Person is whoever a management request comes from.

type S3Blobs

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

S3Blobs keeps blobs in an S3 bucket. Path-style addressing, which every S3-compatible service takes.

func NewS3Blobs

func NewS3Blobs(cfg S3Config) (*S3Blobs, error)

NewS3Blobs makes the store. It does not touch the bucket; Check does.

func (*S3Blobs) Check

func (s *S3Blobs) Check(ctx context.Context) error

Check says whether the bucket exists and the keys may use it.

func (*S3Blobs) Delete

func (s *S3Blobs) Delete(ctx context.Context, hash string) error

func (*S3Blobs) Has

func (s *S3Blobs) Has(ctx context.Context, hash string) (bool, error)

func (*S3Blobs) Open

func (s *S3Blobs) Open(ctx context.Context, hash string) (io.ReadCloser, int64, error)

func (*S3Blobs) Put

func (s *S3Blobs) Put(ctx context.Context, hash string, r io.Reader, size int64) error

type S3Config

type S3Config struct {
	Endpoint  string // https://s3.example.com (or http://minio:9000)
	Region    string // empty: the service's default
	Bucket    string
	Prefix    string // keys are <prefix>blobs/ab/abcdef…
	AccessKey string
	SecretKey string
}

S3Config is an S3-compatible bucket: MinIO for a self-hosted install, Selectel for the cloud.

type Service

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

Service is the sites module.

func New

func New(d Deps) (*Service, error)

New makes the service.

func (*Service) Begin

func (s *Service) Begin(ctx context.Context, site Site, m Manifest, source, by string, allowSecrets bool) (Pending, []string, error)

Begin announces a deployment: the manifest is checked (paths, hashes, sizes, limits, secret-looking names), and the answer lists the hashes the store does not have yet.

func (*Service) Commit

func (s *Service) Commit(ctx context.Context, site Site, pendingID, by string, makeCurrent bool) (Deployment, error)

Commit finishes a deployment: every blob must be in the store, then the manifest becomes the site's next version and, unless asked not to, the current one, in one step. Old versions beyond the keep limit go.

func (*Service) Config

func (s *Service) Config() Config

Config is the configuration the service runs with.

func (*Service) CreateSite

func (s *Service) CreateSite(ctx context.Context, space, name, access string, spa *bool, by, byID, origin string) (Site, error)

CreateSite makes an empty site. A taken name in the space is a conflict.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, site Site) error

Delete removes a site with all its versions and tokens; its blobs go with the next sweep.

func (*Service) DeployZip

func (s *Service) DeployZip(ctx context.Context, site Site, body io.Reader, by string, allowSecrets bool) (Deployment, error)

DeployZip makes a deployment out of a zip archive in one request: the archive is unpacked here, safely.

func (*Service) Edge

func (s *Service) Edge() http.Handler

Edge serves the sites at their own addresses (<site>--<space>.<domain>). The host that is the bare domain, or a label that is not a site, gets the 404 page with the complaint link.

func (*Service) Exists

func (s *Service) Exists(ctx context.Context, host string) bool

Exists says whether the host is the bare sites domain or the address of a site that exists: what a certificate may be issued for on demand.

func (*Service) IsSiteHost

func (s *Service) IsSiteHost(host string) bool

IsSiteHost says whether a request host is an address of this service (a label under its domain).

func (*Service) Mount

func (s *Service) Mount(mux *http.ServeMux)

Mount registers the management API under /api/sites.

func (*Service) NewMachineSession

func (s *Service) NewMachineSession(m MachineSession) (string, time.Time)

NewMachineSession makes the token of a machine for its space; it works until the returned time.

func (*Service) NewToken

func (s *Service) NewToken(ctx context.Context, site Site, name, by string) (Token, string, error)

NewToken makes a deploy token for the site. The secret is returned once; only its hash is kept.

func (*Service) PathEdge

func (s *Service) PathEdge() http.Handler

PathEdge serves the path fallback: /sites/<site>--<space>/… on the server's own origin.

func (*Service) PutBlob

func (s *Service) PutBlob(ctx context.Context, site Site, pendingID, hash string, body io.Reader) error

PutBlob takes the content of one file of a pending deployment. The content must hash to the announced sha256 and size; a file that looks like a secret is refused unless the uploader allowed it.

func (*Service) RevokeToken

func (s *Service) RevokeToken(ctx context.Context, site Site, id string) error

RevokeToken removes a deploy token.

func (*Service) Run

func (s *Service) Run(ctx context.Context)

Run sweeps now and then until ctx ends.

func (*Service) SetCurrent

func (s *Service) SetCurrent(ctx context.Context, site Site, version int, by string) (Site, error)

SetCurrent makes a version the one the site serves: the rollback, and «Сделать текущей».

func (*Service) Site

func (s *Service) Site(ctx context.Context, space, name string) (Site, error)

Site finds a site by its name in a space.

func (*Service) SiteURL

func (s *Service) SiteURL(site Site) string

SiteURL is the address of a site's current deployment.

func (*Service) Sites

func (s *Service) Sites(ctx context.Context, space string) ([]Site, error)

Sites are a space's sites, the latest changed first.

func (*Service) Subdomains

func (s *Service) Subdomains() bool

Subdomains says whether sites get addresses of their own under a wildcard domain; false is the path fallback.

func (*Service) Sweep

func (s *Service) Sweep(ctx context.Context) (int, error)

Sweep forgets the uploads that expired and removes the blobs nothing refers to (and that are old enough not to be somebody's upload in flight). It returns how many blobs went.

func (*Service) TokenSite

func (s *Service) TokenSite(ctx context.Context, secret string) (Site, Token, error)

TokenSite is the site a deploy token belongs to; ErrNotFound for an unknown token.

func (*Service) Tokens

func (s *Service) Tokens(ctx context.Context, site Site) ([]Token, error)

Tokens are the site's deploy tokens.

func (*Service) URL

func (s *Service) URL(a Addr) string

URL is where the deployment of a site opens.

func (*Service) Update

func (s *Service) Update(ctx context.Context, site Site, access *string, spa *bool, by string) (Site, error)

Update changes a site's access or single-page fallback.

func (*Service) Versions

func (s *Service) Versions(ctx context.Context, site Site) ([]Deployment, error)

Versions are a site's deployments, newest first.

type Sessions

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

Sessions are the cookies a site's origin keeps after a ticket: host-only, signed, bound to the host they were made for.

func NewSessions

func NewSessions(key []byte, secure bool, now func() time.Time) *Sessions

NewSessions makes the cookie service; now may be nil.

func (*Sessions) CookieName

func (s *Sessions) CookieName() string

CookieName is __Host-hl_site on https (host-only, Path=/, Secure: a sibling site cannot plant it), hl_site on http.

func (*Sessions) Read

func (s *Sessions) Read(r *http.Request, host string) (userID string, ok bool)

Read is the person of the request's cookie, when it is valid for host.

func (*Sessions) Set

func (s *Sessions) Set(w http.ResponseWriter, host, userID string)

Set starts the person's session on host.

type Site

type Site struct {
	ID, Space, Name string
	Access          string
	SPA             bool
	CurrentVersion  int
	NextVersion     int
	CreatedBy       string // the name shown
	CreatedByID     string // who made it, for rights: a person's id or machine:<id>
	Origin          string // what it was made from (sinopia:<project>), empty for the rest
	UpdatedBy       string
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

Site is a name in a space.

type SiteView

type SiteView struct {
	ID             string        `json:"id"`
	Space          string        `json:"space"`
	Name           string        `json:"name"`
	Address        string        `json:"address"`
	Access         string        `json:"access"`
	SPA            bool          `json:"spa"`
	CurrentVersion int           `json:"currentVersion"`
	CreatedBy      string        `json:"createdBy"`
	Origin         string        `json:"origin,omitempty"`
	UpdatedBy      string        `json:"updatedBy"`
	CreatedAt      string        `json:"createdAt"`
	UpdatedAt      string        `json:"updatedAt"`
	Versions       []VersionView `json:"versions,omitempty"`
}

SiteView is a site as the API sends it.

type Tickets

type Tickets interface {
	// Redeem is true once, for the host the ticket was made for.
	Redeem(ticket, host string) (userID string, ok bool)
}

Tickets trades a one-time ticket for the person it was made for. The hub backs it with its in-memory ticket store; a standalone server verifies tickets signed by the gateway that did the signing in (HMACTickets).

type Token

type Token struct {
	ID, SiteID, Name, CreatedBy string
	CreatedAt, LastUsedAt       time.Time
}

Token is a deploy token as the database keeps it (never the secret).

type TokenView

type TokenView struct {
	ID         string  `json:"id"`
	Name       string  `json:"name"`
	CreatedBy  string  `json:"createdBy"`
	CreatedAt  string  `json:"createdAt"`
	LastUsedAt *string `json:"lastUsedAt"`
	// Token is the secret, in the answer that makes it and nowhere else.
	Token string `json:"token,omitempty"`
}

TokenView is a deploy token as the API sends it.

type VersionView

type VersionView struct {
	Version    int    `json:"version"`
	URL        string `json:"url"`
	FileCount  int    `json:"fileCount"`
	TotalBytes int64  `json:"totalBytes"`
	Source     string `json:"source"`
	CreatedBy  string `json:"createdBy"`
	CreatedAt  string `json:"createdAt"`
	Current    bool   `json:"current"`
}

VersionView is one deployment of a site.

Jump to

Keyboard shortcuts

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