web

package
v0.47.13 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 25 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 provides the HTTP server and routing infrastructure.

Index

Constants

View Source
const (
	SessionPrefix = "tns_"
	TokenPrefix   = "tnt_"
)

The two kinds of stored credential, and the prefix each carries.

The prefix is outside the signature and is stripped before verifying. It is there so that a value pasted into a chat window or committed to a repository can be recognized for what it is — by a person, and by a secret scanner.

View Source
const CommandLineConnectSources = "http://127.0.0.1:* http://localhost:*"

CommandLineConnectSources is what that page may connect to besides this server: the client's listener, which is on the reader's own machine and so is plain HTTP on a loopback address, on whichever port was free.

View Source
const CommandLinePagePath = "/cli"

CommandLinePagePath is the dashboard page the command line client opens to sign in. The client names the same path.

View Source
const DrawerPagePath = "/drawer"

DrawerPagePath is the dashboard's agent drawer on a page of its own, for the browser extension to frame into whatever site the person is on. It may be framed by any origin: framed without the token the extension hands it, it shows nothing and can do nothing, and the session cookie (SameSite=Lax) is not sent to a cross-site frame. A page on another host of the same site would get the cookie; a server that serves other people's pages on a sibling host should keep that in mind.

View Source
const SessionCookieName = "teanode_session"

SessionCookieName is the cookie holding a signed session.

Variables

View Source
var (
	// ErrInvalidCredentials is returned by Login for both an unknown username
	// and a wrong password, so that the reply cannot be used to discover
	// which usernames exist.
	ErrInvalidCredentials = errors.New("web: incorrect username or password")

	// ErrTooManyAttempts is returned when an address has used up its login
	// attempts. Distinct from ErrInvalidCredentials so that the caller can
	// answer differently: telling somebody they are being rate limited is not
	// a disclosure, and leaving them to guess why their correct password is
	// being refused is unkind.
	ErrTooManyAttempts = errors.New("web: too many login attempts, try again later")

	// ErrInvalidAccount is returned when a proposed account would not work.
	// Its message reaches the browser, so it is written for a person rather
	// than carrying the usual package prefix.
	ErrInvalidAccount = errors.New("web: that account will not work")

	// ErrAccountExists is returned when the first-run setup is attempted on a
	// server that already has an account.
	ErrAccountExists = errors.New("web: this server already has an account; sign in instead")

	ErrSessionExpired = errors.New("web: session expired")
	ErrSessionInvalid = errors.New("web: session is not valid")
)

Functions

func ApplyMiddlewares

func ApplyMiddlewares(handler http.Handler, middlewares ...Middleware) http.Handler

func CompressionMiddleware

func CompressionMiddleware(handler http.Handler) http.Handler

func LoggingMiddleware

func LoggingMiddleware(handler http.Handler) http.Handler

func NoStoreMiddleware

func NoStoreMiddleware(handler http.Handler) http.Handler

NoStoreMiddleware stops anything under the API being cached.

None of it is cacheable. The session endpoint reports who you are, and a reply with no Cache-Control is heuristically cacheable — so a browser is entitled to keep it and answer the next request itself. That is not theoretical: after the accounts were cleared on a development server, an iPhone went on showing a login form for a server that had none, because it never asked again. The same staleness would let a logged-out browser be told it is still logged in.

Static assets are handled separately and correctly: the dashboard's own HTML is no-store, and the hashed bundles are immutable.

Types

type Authenticator

type Authenticator interface {
	// Authenticate returns the operator this request belongs to, and whether
	// authentication is satisfied at all. When no dashboard users are
	// configured every request is allowed and the username is empty.
	Authenticate(request *http.Request) (username string, ok bool)

	// Login verifies a password, stores a session and writes its cookie.
	Login(response http.ResponseWriter, request *http.Request, username, password string) error

	// StartSession stores a session and writes its cookie for somebody whose
	// identity has already been established some other way — by an
	// authenticator answering a WebAuthn challenge, which this package does
	// not verify and should not have to know about.
	//
	// It does no rate limiting, because there is nothing here to guess: the
	// caller has already checked a signature against a stored public key.
	StartSession(response http.ResponseWriter, request *http.Request, username string) error

	// Logout ends the session this request carries and clears the cookie.
	Logout(response http.ResponseWriter, request *http.Request)

	// AllowLoginAttempt counts one attempt to sign in from wherever the
	// request came from, and says whether it may go ahead. Login counts
	// its own; this is for the other ways in — a passkey ceremony, say —
	// so that they are limited the same way.
	AllowLoginAttempt(request *http.Request) bool

	// CurrentSessionID is the session this request is using, or empty when it
	// is authenticated some other way. The dashboard needs it to mark one row
	// in the list as the one you are reading it from.
	CurrentSessionID(request *http.Request) string

	// ListSessions returns an operator's sessions, newest first.
	ListSessions(username string, includeRevoked bool) ([]*models.Session, error)

	// RevokeSession ends one session belonging to an operator.
	RevokeSession(username, sessionId string) error

	// RevokeSessions ends every session an operator has, optionally keeping
	// the one making the request, and returns how many it ended.
	RevokeSessions(username string, except string) (int64, error)

	// IssueToken mints an API token for an operator, returning the stored
	// row and the token string, which is the only time it can be read.
	IssueToken(username, name string, lifetime time.Duration) (*models.Token, string, error)

	// ListTokens returns an operator's tokens, newest first.
	ListTokens(username string, includeRevoked bool) ([]*models.Token, error)

	// RevokeToken ends one token belonging to an operator.
	RevokeToken(username, tokenId string) error

	// Scavenge removes sessions and tokens that are no longer worth keeping.
	Scavenge() error

	// Required reports whether any user is configured. When false the
	// dashboard is open to whoever can reach it, and the interface offers to
	// create the first account instead of asking for one.
	Required() bool

	// CreateFirstUser claims a server that has no account yet.
	CreateFirstUser(ctx context.Context, username, password string) error

	// ChangePassword replaces an account's password, after checking the
	// current one.
	ChangePassword(username, current, replacement string) error
}

Authenticator decides who may use the dashboard and the API.

func NewAuthenticator

func NewAuthenticator(configuration config.Store, database CredentialStore) (Authenticator, error)

NewAuthenticator builds an Authenticator over the session and token tables.

type Component

type Component interface {
	AddRoutes(*mux.Router) error
}

func NewStaticComponent

func NewStaticComponent(handler http.Handler) Component

NewStaticComponent serves a handler for every path the API did not claim.

type CredentialStore

type CredentialStore interface {
	db.SessionOperation
	db.TokenOperation
	db.UserLookup

	// TransactionContext is for the two writes to the user table made here:
	// claiming a fresh server, and a person changing their own password.
	TransactionContext(ctx context.Context, function func(db.Transaction) error) error
}

CredentialStore is where sessions and tokens live.

Narrower than db.Database on purpose: this package needs fourteen methods out of it, and saying so means a test can stand up the authenticator without a PostgreSQL. db.Database satisfies it.

type Middleware

type Middleware func(http.Handler) http.Handler

func MakeAuthenticationMiddleware

func MakeAuthenticationMiddleware(authenticator Authenticator, challengePath string) Middleware

MakeAuthenticationMiddleware refuses anything under /api/ that the caller is not entitled to, and hands the authenticated username to the handlers behind it.

The paths in api.PublicPaths and under api.PublicPrefixes are always allowed through, and so is the ACME challenge, because a certificate authority cannot log in.

func MakeForwarderMiddleware

func MakeForwarderMiddleware(forwarderKey string) Middleware

func MakeSecurityHeadersMiddleware

func MakeSecurityHeadersMiddleware(inlineScriptHashes []string, trustedProxies func() []string) Middleware

MakeSecurityHeadersMiddleware sets the headers that decide what a browser will do with this page, on everything the server answers.

The content security policy is the substantial one. The dashboard renders mail written by strangers; the sanitizer and the sandboxed frame are the first two layers, and this is the third — the one that holds even if the other two have a hole in them.

default-src 'self'      nothing loads from anywhere but this server.
script-src              this server, plus the hash of each inline script
                        the dashboard ships. Not 'unsafe-inline', which
                        would be the same as having no script policy.
style-src 'unsafe-inline'
                        required twice over: React writes style attributes,
                        and the message frame's own document styles itself
                        inline. A srcdoc frame inherits this policy, so
                        anything the frame needs has to be allowed here as
                        well — which is why the remote images go through
                        the server rather than widening img-src to https:.
img-src 'self' data:    every image in a message is served from here: the
                        attached ones from the attachment endpoint, the
                        remote ones through the proxy. Nothing in a message
                        reaches the network from the reader's browser.
connect-src 'self'      the API and its WebSocket, nowhere else.
frame-ancestors 'none'  this page is not put inside anybody else's, which
                        is what X-Frame-Options used to say.
form-action 'self'      a form in a message cannot post anywhere, and the
                        frame's sandbox already forbids forms outright.
base-uri 'none'         no injected <base> can send every relative URL on
                        the page somewhere else.
object-src 'none'       no plugins.

One page is the exception to connect-src: the one the command line client opens to sign in, which hands the token it obtained to the client's listener on the reader's own machine. That page, and only that page, may reach a loopback address. The page is a document of its own — the client opens it directly — so the policy is chosen by the path the document was served at.

func MakeServerNameMiddleware

func MakeServerNameMiddleware(serverName string) Middleware

type Server

type Server interface {
	http.Handler
}

func NewServer

func NewServer(database db.Database, settings *Settings, components []Component) (Server, error)

type Settings

type Settings struct {
}

Jump to

Keyboard shortcuts

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