web

package
v0.167.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 26 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_"
	// A refresh secret is a different kind, so a refresh cannot be presented
	// as the access token it renews however it is rearranged. Same reasoning
	// as a session cookie not being usable as an API token.
	RefreshPrefix = "tnr_"
)

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 FinanceLinkPagePath = "/finance/link"

FinanceLinkPagePath is the dashboard page that opens Plaid's linking window, which a person uses to sign in to their institution. It is the only page that may load a script, frame a page and connect anywhere other than this server, and only to Plaid: the window is Plaid's script, which frames Plaid's page and talks to Plaid's API. Every other page keeps the policy that keeps a message from reaching anything outside this server. The policy comes with the document, so the page has to be loaded at this path, never reached by moving within the dashboard. The command line and the finance tool hold the same path (internal/client.FinanceLinkPagePath).

View Source
const ReturnCookieName = "teanode_session_return"

ReturnCookieName holds the operator's own session while they are signed in as somebody else. The server keeps only a hash of a session's secret, so it cannot write the operator's cookie again when they come back: the browser keeps it, here, while the impersonation lasts.

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")
)
View Source
var (
	ErrNotImpersonating  = errors.New("web: this session is not signed in as somebody else")
	ErrCannotImpersonate = errors.New("web: signing in as somebody else needs your own browser session")
)

ErrNotImpersonating is ending an impersonation from a request that is not one, and ErrCannotImpersonate starting one from a request that is not an ordinary session of the operator's own: a token, the console, or an impersonation already.

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)

	// AuthenticateIdentity is Authenticate with the rest of who the
	// request is: its session, and the operator behind it when it is an
	// impersonation.
	AuthenticateIdentity(request *http.Request) (Identity, bool)

	// StartImpersonation signs the operator this request belongs to in as
	// another account, for as long as the operator's own session: a session of that
	// account's naming the operator, the operator's own cookie kept aside.
	// The caller has decided the operator may; this checks only that the
	// request is an ordinary session of theirs.
	StartImpersonation(response http.ResponseWriter, request *http.Request, username string) (*models.Session, error)

	// EndImpersonation ends the impersonation this request is, and puts
	// the operator's own session back when it is still alive. It says
	// whether it did.
	EndImpersonation(response http.ResponseWriter, request *http.Request) (bool, error)

	// 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)

	// IssueAuthorizedToken mints the token a program collects after somebody
	// approved it, returning the row, the token and the refresh secret.
	IssueAuthorizedToken(userId, name, clientId, resource string, lifetime time.Duration) (*models.Token, string, string, error)

	// RedeemRefresh checks a refresh secret and returns the token it renews,
	// without minting the replacement.
	RedeemRefresh(value string) (*models.Token, error)

	// RevokeTokenByID retires a token without knowing whose it is, for a
	// refresh replacing the one it renewed, and says whether this call was
	// the one that retired it.
	RevokeTokenByID(tokenId string) (bool, error)

	// UserByID is the account a token or an approval belongs to.
	UserByID(userId string) *models.User

	// UserByName is the account somebody is signed in as.
	UserByName(username string) *models.User

	// TokenIDOf is the identifier inside an access token, when the value is
	// one this server minted. It verifies the signature, so an identifier
	// only comes back for a credential that was issued here.
	TokenIDOf(value string) (string, bool)

	// 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

	// RenameApp names an app everywhere a person sees it, on every token it
	// holds for them and on each one it renews into.
	RenameApp(username, clientId, name string) error

	// DisconnectApp ends every token an app holds for a person.
	DisconnectApp(username, clientId string) error

	// UpdateToken renames one of an operator's tokens or gives it a new
	// lifetime, counted from now; a lifetime of zero never expires. Nil
	// leaves either as it is.
	UpdateToken(username, tokenId string, name *string, lifetime *time.Duration) (*models.Token, 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

	// ScavengeOAuth sweeps approvals nobody collected and registrations
	// nobody approved, alongside the sessions and tokens swept here.
	ScavengeOAuth(now time.Time) (int64, error)

	// 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 Identity added in v0.107.0

type Identity struct {
	Username  string
	SessionID string

	ImpersonatorUsername string
}

Identity is who a request is: the account, the session it uses when it uses one, and the operator behind it when it is an impersonation.

type Middleware

type Middleware func(http.Handler) http.Handler

func MakeAuthenticationMiddleware

func MakeAuthenticationMiddleware(authenticator Authenticator, challengePath string, trustedProxies func() []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