api

package
v0.74.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 17 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 api holds what every version of the HTTP API shares: the error values, the request context, and the paths.

The API itself lives in versioned subpackages. internal/api/v1api mounts version 1 under /api/v1, and its own subpackages implement the parts: apigraph the GraphQL endpoint, apisend the template send endpoint, apiauth the session endpoints a browser uses to log in.

This package deliberately depends on almost nothing, so that the versioned packages and internal/web can all import it without a cycle.

Index

Constants

View Source
const (
	// PathAgentTab is the websocket the browser extension attaches a tab
	// through, for the person's agent.
	PathAgentTab = Prefix + "/agent/tab"

	// PathAgentComputer is the websocket `teanode computer` attaches the
	// person's computer through.
	PathAgentComputer = Prefix + "/agent/computer"

	// PathAgentAttachments takes files for a conversation with the agent,
	// as a multipart body; PathAgentAttachment hands one back to its owner.
	PathAgentAttachments = Prefix + "/agent/attachments"
	PathAgentAttachment  = Prefix + "/agent/attachments/{attachmentId}"

	// PathAgentDocumentFile serves the bytes of one thing a knowledge
	// source indexed: the picture or the file a record came with, kept in
	// object storage under the document's key. The document itself is
	// read through the graph; this is the file behind it, so that a page
	// citing a screenshot can show the screenshot.
	PathAgentDocumentFile = Prefix + "/agent/documents/{documentId}/file"

	// PathAgentPicture fetches, for the person reading a conversation, an
	// image the agent put in an answer: one whose address a tool showed
	// the agent in that conversation, and no other.
	PathAgentPicture = Prefix + "/agent/conversations/{conversationId}/picture"

	// PathAgentMCP answers the Model Context Protocol, so that a harness
	// somebody codes in -- or any other program that speaks it -- can use
	// the person's own agent tools. One POST is one JSON-RPC message.
	PathAgentMCP = Prefix + "/mcp"

	// PathGraphQL is the whole of the management API. POST executes a query
	// or mutation; GET upgrades to a WebSocket for subscriptions.
	PathGraphQL = Prefix + "/graphql"

	// PathSend accepts a request to send a templated message.
	PathSend = Prefix + "/send/{domain}/{template}"

	// PathMailRaw serves a stored message in its original form, as a file the
	// browser can save.
	PathMailRaw = Prefix + "/mail/{mailId}/raw"

	// PathMailAttachment serves one part of a stored message: a file to save,
	// or the image an HTML part refers to with a cid: URL.
	PathMailAttachment = Prefix + "/mail/{mailId}/attachment/{index}"

	// PathDraftAttachments adds files to a draft, as a multipart body, and
	// answers with the draft that now holds them; PathNewDraftAttachments
	// makes the first draft of a message around the files.
	PathDraftAttachments    = Prefix + "/mailbox/drafts/{itemId}/attachments"
	PathNewDraftAttachments = Prefix + "/mailbox/{mailboxId}/drafts/attachments"

	// PathMediaUpload accepts a picture to put in a template. An operator's
	// action, so it is inside the API and behind a session.
	PathMediaUpload = Prefix + "/media"

	// PathMediaFile serves an uploaded picture. Outside the API prefix, and
	// so outside the session check, because the callers are the dashboard's
	// preview and — once a message has been sent — mail programs, which have
	// no session and never will.
	PathMediaFile = "/media/{mediaId}"

	// PathMediaLink serves a picture at an address belonging to one sent
	// message. Public, and short, because it goes in the message: a mail
	// program fetching it is how an open is noticed.
	PathMediaLink = "/m/{token}"

	// PathMailRemote fetches an image a message links to somewhere else, on
	// behalf of a reader who asked for it. The address in the query is the
	// address in the message.
	PathMailRemote = Prefix + "/mail/{mailId}/remote"

	// PathBimiLogoUpload accepts the logo a domain will publish for its own
	// mail. An operator's action, so it is inside the API and behind a
	// session.
	PathBimiLogoUpload = Prefix + "/domains/{domainId}/logo"

	// operator what they published. Inside the API and behind a session,
	// because it is the dashboard asking rather than a receiver.
	PathDomainLogo = Prefix + "/domains/{domainId}/logo.svg"

	// session check, because what fetches it is a receiving mail system
	// following a DNS record — it has no session and never will.
	PathBimiLogo = "/.well-known/bimi/{fileId}.svg"

	// as this server fetched and cached it. Fetched here rather than by the
	// browser, so that showing one does not tell the sender which address
	// opened which message at what moment.
	PathSenderLogo = Prefix + "/logo/{domain}"

	// PathContactPhoto is the picture on a contact's card, served as an
	// image so that a page can show it without carrying four hundred
	// kilobytes of base64 through a listing.
	PathContactPhoto = Prefix + "/contacts/{contactId}/photo"

	// The two documents a program reads before it knows how to ask for a
	// token. Outside the API prefix and outside the session check, like
	// PathBimiLogo above, because whatever fetches them has no credential
	// yet -- being told how to get one is the entire point of them.
	//
	// The protected resource document is served at two addresses because
	// clients disagree about which to ask for, and the disagreement is
	// visible in this tree: wellKnown in internal/mcp/oauth.go builds both
	// the suffixed and the prefixed form and tries them in turn. Answering
	// only one works with some clients and, with the rest, looks like a
	// document that would not parse.
	PathOAuthProtectedResource    = "/.well-known/oauth-protected-resource"
	PathOAuthProtectedResourceMCP = "/.well-known/oauth-protected-resource" + PathAgentMCP
	PathOAuthAuthorizationServer  = "/.well-known/oauth-authorization-server"

	// Where a program registers itself, sends a person to approve, and
	// swaps that approval for a token. Named here because the document at
	// PathOAuthAuthorizationServer has to publish the addresses, and a
	// published address and the route serving it must come from one place
	// or they drift apart silently.
	PathOAuthRegister  = "/oauth/register"
	PathOAuthAuthorize = "/oauth/authorize"
	PathOAuthToken     = "/oauth/token"
	PathOAuthRevoke    = "/oauth/revoke"
)

The paths making up version 1.

View Source
const AuthenticatedUsernameHeader = "X-TeaNode-Authenticated-User"

AuthenticatedUsernameHeader carries the operator established by the authentication middleware to the handlers behind it. It is stripped from every incoming request first, so a client cannot set it themselves.

View Source
const MaximumPageSize = 1000

MaximumPageSize is the most rows one list query returns, however many were asked for. The dashboard pages at a fraction of it.

View Source
const Prefix = "/api/v1"

Prefix is where the current API version is mounted. Everything the dashboard and the command line client call lives under it.

The version is in the path rather than in a header so that a request can be read, logged and routed by a proxy without knowing anything about TeaNode, and so that a future version 2 can be served alongside version 1 rather than replacing it under everybody.

Variables

View Source
var (
	ErrNotLoggedIn       = errors.New("api: not logged in")
	ErrAlreadyLoggedIn   = errors.New("api: already logged in")
	ErrNotFound          = errors.New("api: not found")
	ErrAlreadyExists     = errors.New("api: already exists")
	ErrPermissionDenied  = errors.New("api: permission denied")
	ErrInvalidArguments  = errors.New("api: invalid arguments")
	ErrInvalidDomain     = errors.New("api: invalid domain")
	ErrInvalidEmail      = errors.New("api: invalid email")
	ErrInvalidToken      = errors.New("api: invalid token")
	ErrInvalidCode       = errors.New("api: invalid code")
	ErrInvalidCredential = errors.New("api: invalid credential")
	ErrNotRetryable      = errors.New("api: not retryable")
	ErrTooManyRequests   = errors.New("api: too many attempts, try again later")
)
View Source
var ErrRestartUnavailable = errors.New("api: this server cannot restart itself")

ErrRestartUnavailable is returned when the API is asked to restart a server that has nothing to start it again.

Functions

func AgentDocumentFilePath

func AgentDocumentFilePath(documentId string) string

AgentDocumentFilePath is PathAgentDocumentFile with its parameter filled in: where the bytes of one indexed document are served from.

func BimiLogoPath

func BimiLogoPath(fileId string) string

BimiLogoPath is PathBimiLogo with its parameter filled in. The address goes in a DNS record, so it has to keep meaning the same thing.

func BimiLogoUploadPath

func BimiLogoUploadPath(domainId string) string

BimiLogoUploadPath is PathBimiLogoUpload with its parameter filled in: where a logo is sent, which is a multipart request and so has no place in the schema.

func ContextAuthenticatedUsername

func ContextAuthenticatedUsername(ctx context.Context) string

func ContextRequest

func ContextRequest(ctx context.Context) *http.Request

func ContextResponse

func ContextResponse(ctx context.Context) http.ResponseWriter

func ContextTransaction

func ContextTransaction(ctx context.Context) db.Transaction

func ContextWithAuthenticatedUsername

func ContextWithAuthenticatedUsername(ctx context.Context, username string) context.Context

ContextWithAuthenticatedUsername records the operator the authentication middleware established, so that a resolver can attribute a change.

func ContextWithPrincipal

func ContextWithPrincipal(ctx context.Context, principal *Principal) context.Context

ContextWithPrincipal records who is asking, for the resolvers.

func ContextWithRequest

func ContextWithRequest(ctx context.Context, request *http.Request) context.Context

func ContextWithResponse

func ContextWithResponse(ctx context.Context, response http.ResponseWriter) context.Context

ContextWithResponse carries the response writer to the resolvers.

Almost nothing needs it: a GraphQL reply is the return value, not something a resolver writes. Logging in is the exception, because a browser's credential is a cookie and a cookie is a response header.

func ContextWithTransaction

func ContextWithTransaction(ctx context.Context, tx db.Transaction) context.Context

func DomainLogoPath

func DomainLogoPath(domainId string) string

DomainLogoPath is PathDomainLogo with its parameter filled in.

func IsLoopbackHost added in v0.49.0

func IsLoopbackHost(host string) bool

IsLoopbackHost says whether a host never leaves this machine.

Two callers with the same question and different reasons. A connected server declared at a loopback address is one an operator is running beside this one, where plain HTTP carries nothing anybody else can read. And a program being authorized here receives its approval on a loopback port, which cannot have a certificate, so that is the one place an http redirect address is allowed.

One copy, because it is a security check in both places and two copies of a security check drift.

func IsSecure

func IsSecure(request *http.Request, trustedProxies []string) bool

IsSecure reports whether a request reached this server over HTTPS: on its own TLS listener, or through a proxy that terminated TLS and said so. The header is believed only from a proxy in server.trustedProxies, for the same reason X-Forwarded-For is: anyone who can reach the server directly can write it.

The safe direction to be wrong in is towards "not secure", which makes a cookie more restrictive; the direction that matters is a proxy that terminates TLS and does not say so, which issues a cookie that a browser then sends in the clear. That is the operator's proxy to configure.

func MailAttachmentPath

func MailAttachmentPath(mailId string, index int) string

MailAttachmentPath is PathMailAttachment with its parameters filled in.

func MailRemotePath

func MailRemotePath(mailId string) string

MailRemotePath is PathMailRemote with its parameter filled in. The caller appends the address it wants, escaped.

func MediaLinkPath

func MediaLinkPath(token string) string

MediaLinkPath is PathMediaLink with its token filled in.

func MediaPath

func MediaPath(mediaId string) string

MediaPath is PathMediaFile with its parameter filled in. It is where a picture lives while a template is being edited; a sent message names an address of its own instead.

func PublicPaths

func PublicPaths() []string

PublicPaths are reachable without the middleware turning them away.

The GraphQL endpoint is on the list, which looks alarming and is not: logging in happens there, so a caller has to be able to reach it before being anybody. Authorization is the resolvers' job — every one of them refuses a caller who is not an operator, and TestEveryOperationAuthorizes fails if a new one forgets. The middleware was never the thing keeping the mail private; it was a second lock on the same door, and having it made the login endpoints have to live outside GraphQL.

func PublicPrefixes

func PublicPrefixes() []string

PublicPrefixes are reachable without the middleware turning them away, for paths with a parameter in them, which an exact match cannot name.

The send endpoint is here because the caller is not an operator: it is an application holding an SMTP credential, and it authenticates with that credential inside the handler, the way it would at the submission port. The middleware turning it away for having no session made the endpoint unreachable on any server with an account, which is every server.

func RemoteAddress

func RemoteAddress(request *http.Request, trustedProxies []string) string

RemoteAddress is who asked, as far as this server can honestly tell.

Behind a CDN or a load balancer the connection comes from the proxy, so every audit row and every "last used from" recorded the proxy's address — one line of CloudFront's, over and over, saying nothing about who did anything. The client's address is in X-Forwarded-For, which the proxy adds.

That header is also a plain request header, so anybody who can reach this server directly can write whatever they like in it. It is therefore read only when the connection itself came from an address the operator has said is a proxy, listed in server.trustedProxies. With nothing listed, the header is ignored and the connection's own address is used, which is the right answer for a server that faces the internet.

The header is a list — client, then each proxy that forwarded it — and the entries a proxy did not add can be forged by the client. So it is read from the right, skipping the addresses that are themselves trusted proxies; the first one that is not is the closest address this server has any reason to believe. Everything to the left of it came from the client and is ignored.

func SenderLogoPath

func SenderLogoPath(domain string) string

SenderLogoPath is PathSenderLogo with its parameter filled in.

func UsernameFromRequest

func UsernameFromRequest(request *http.Request) string

UsernameFromRequest reads the operator established by the authentication middleware. It is empty when the server has no accounts configured, which leaves the API open — a state the server warns about at startup.

Types

type AgentService

type AgentService interface {
	// DraftReply writes a reply for the person to read, change and send.
	DraftReply(ctx context.Context, request *models.AgentDraftRequest) (*models.AgentDraft, error)
}

AgentService is what the API asks the agent to do at once.

type Aggregations

type Aggregations = []*aggregate.Stage

Aggregations is the filter, sort and distinct pipeline a list query can be given, so that narrowing and ordering happen in the database rather than over whatever the browser happened to fetch.

The shape mirrors the one used elsewhere in the fleet: a list of stages, each of which is exactly one of a match, a sort, or a distinct, applied in the order written.

type Pagination

type Pagination struct {
	// Limit the returned results to first few
	First *uint64 `json:"first"`

	// Offset the returned results, skip amount specified by offset
	Offset *uint64 `json:"offset"`

	// Return results that after this cursor, usually ID can be used as cursor
	After *string `json:"after"`
}

Pagination parameters, used to filter returned results.

func (*Pagination) Limit

func (self *Pagination) Limit() int

Limit returns a bounded page size. Omitted and zero sizes select the largest page; zero must not reach the database, where it means no limit.

func (*Pagination) Options

func (self *Pagination) Options() *db.Options

Options converts pagination parameters to options for a database query.

func (*Pagination) OptionsWith

func (self *Pagination) OptionsWith(aggregations Aggregations, columns aggregate.Columns) *db.Options

OptionsWith is Options plus the aggregation pipeline and the fields it is allowed to name.

type Principal

type Principal = access.Principal

Principal is the authenticated identity shared with application commands.

func ContextPrincipal

func ContextPrincipal(ctx context.Context) *Principal

ContextPrincipal is who is asking, or nil when nobody is signed in.

type Restarter

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

Restarter ends the process so that whatever supervises it starts a new one.

There is no way to restart in place: the point of restarting is to build everything again from configuration that has changed, and the parts that have to be rebuilt are the listeners, the certificates and the connections to the object store and the scanners. Exiting is the honest version of that.

func NewRestarter

func NewRestarter(trigger func()) *Restarter

NewRestarter returns one that ends the process by calling trigger, which is expected to begin a graceful shutdown.

func (*Restarter) AddPending

func (self *Restarter) AddPending(names ...string)

AddPending records settings that have changed and that this process will not pick up until it restarts. Called by whatever watches the configuration.

They accumulate rather than replace. Two changes made an hour apart are two reasons to restart, and reporting only the second would have the dashboard understate what is out of date.

func (*Restarter) Pending

func (self *Restarter) Pending() []string

Pending returns those names, so the dashboard can say why it is offering a restart rather than leaving the operator to wonder.

func (*Restarter) Request

func (self *Restarter) Request() bool

Request begins a restart, and reports whether this call was the one that started it.

Repeat calls are not an error. Two operators pressing the button at the same moment should get the same answer as one of them pressing it twice, rather than one of them getting a failure for a restart that is happening.

func (*Restarter) Requested

func (self *Restarter) Requested() bool

Requested reports whether a restart is already under way.

func (*Restarter) Supervision

func (self *Restarter) Supervision() Supervision

Supervision guesses what will happen when this process exits.

A guess, and named as one. Neither a container's restart policy nor a systemd unit's Restart= can be read from inside the process, so the most this can say is which supervisor is in charge. It exists so the dashboard can warn the one operator for whom restarting means staying down: somebody running the server from a shell.

It errs towards "unknown", which is the direction that warns rather than reassures. Being told a restart might not come back when it would is a moment's hesitation; the opposite is a mail server that is down and nobody expecting it to be.

type Settings

type Settings struct {
	// Secret key
	Secret []byte

	// Unique identifier for this backend instance
	BackendID string

	// Restarter ends this process so a supervisor starts a new one. Nil when
	// the server was started in a way that has no supervisor to do that, in
	// which case the API says restarting is unavailable rather than offering
	// a button that takes the server down and leaves it there.
	Restarter *Restarter

	// AuthLimiter bounds how often one address may present a credential,
	// shared with the submission listener so that a guess costs the same
	// whichever door it comes through. Nil disables the limit.
	AuthLimiter *ratelimit.Registry

	// Agent is the part of the personal agent the API calls in the request
	// rather than queues: work a person is waiting on. Nil when agents are
	// off, in which case the API says so.
	Agent AgentService
}

Settings are the server-wide values the API needs.

type Supervision

type Supervision string

Supervision is what is expected to happen when the process exits.

const (
	// SupervisionContainer means the process is the entry point of a
	// container. Whether it comes back is the container's restart policy,
	// which cannot be read from in here — but a mail server in a container
	// almost always has one.
	SupervisionContainer Supervision = "container"

	// SupervisionSystemd means systemd started this. Whether it comes back is
	// the unit's Restart=, which cannot be read from in here either.
	SupervisionSystemd Supervision = "systemd"

	// SupervisionUnknown means nothing recognisable started this, so exiting
	// most likely leaves the server down. A development server run from a
	// shell looks like this.
	SupervisionUnknown Supervision = "unknown"
)

Directories

Path Synopsis
Package v1api serves version 1 of the HTTP API, mounted at /api/v1.
Package v1api serves version 1 of the HTTP API, mounted at /api/v1.
apigraph
Package apigraph implements the GraphQL endpoint, which is the whole of the management API.
Package apigraph implements the GraphQL endpoint, which is the whole of the management API.
apimail
Package apimail serves a stored message in its original form.
Package apimail serves a stored message in its original form.
apimedia
Package apimedia stores the pictures an operator puts in a template and serves them to the mail programs that later ask for them.
Package apimedia stores the pictures an operator puts in a template and serves them to the mail programs that later ask for them.
apioauth
Package apioauth answers the questions a program asks before it has a credential: who authorizes this server, and where do I go to be let in.
Package apioauth answers the questions a program asks before it has a credential: who authorizes this server, and where do I go to be let in.
apisend
Package apisend implements the endpoint that sends a templated message.
Package apisend implements the endpoint that sends a templated message.
apisso
Package apisso is the two HTTP paths a single sign-on passes through: the one that sends the browser to the identity provider, and the one it comes back to.
Package apisso is the two HTTP paths a single sign-on passes through: the one that sends the browser to the identity provider, and the one it comes back to.

Jump to

Keyboard shortcuts

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