api

package
v0.193.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 20 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"

	// PathAgentTabView is the websocket the dashboard's browser page
	// watches the person's tab through, and takes it over.
	PathAgentTabView = Prefix + "/agent/tab/view"

	// PathAgentVoice is the websocket the drawer streams the microphone
	// over, for the server to have transcribed.
	PathAgentVoice = Prefix + "/agent/voice"

	// PathAgentVoiceSample is a few words in one of the voices, for a
	// person choosing the one their answers are read in.
	PathAgentVoiceSample = Prefix + "/agent/voice/sample"

	// 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.
	// Recording media has its own bounded uploads and private playback.
	PathRecordingPart     = Prefix + "/recordings/media/{mediaId}/parts/{partIndex}"
	PathRecordingComplete = Prefix + "/recordings/media/{mediaId}/complete"
	PathRecordingMedia    = Prefix + "/recordings/media/{mediaId}"
	PathRecordingPlayback = Prefix + "/recordings/media/{mediaId}/playback"

	// PathRecordingLive is the websocket a capture streams its microphone to
	// for words as they are spoken.
	PathRecordingLive = Prefix + "/recordings/{recordingId}/live"

	// PathPhotoUploads takes a photo or a video for the library over the
	// resumable upload protocol, and PathPhotoUpload is one upload in
	// progress. Their bytes go up in parts a client can resume. A phone's
	// background upload signs in with a device password rather than a
	// session, so these are let through the middleware (see
	// PublicPrefixes) and the handler checks who is calling.
	PathPhotoUploads = Prefix + "/photos/uploads"
	PathPhotoUpload  = Prefix + "/photos/uploads/{photoUploadId}"

	// PathPhotoPreview serves a smaller copy of a photo for showing it, and
	// PathPhotoFile one of the files the photo is made of, to download.
	PathPhotoPreview = Prefix + "/photos/{photoId}/previews/{photoPreviewSize}"
	PathPhotoFile    = Prefix + "/photos/{photoId}/files/{photoFileRole}"

	// PathPhotoFacePicture serves the picture of one face found in a photo:
	// a square cut from the photo's large preview.
	PathPhotoFacePicture = Prefix + "/photos/faces/{photoFaceId}/picture"

	// PathPhotoPlaybackPreview and PathPhotoPlaybackFile serve the same bytes
	// to a player that cannot send the person's sign-in: the address
	// carries a signature made by PhotoPlaybackAddress, names one preview or file of
	// one photo, and expires. They are let through the middleware (see
	// PublicPrefixes) and the handler checks the signature.
	PathPhotoPlaybackPreview = Prefix + "/photos/playback/{photoId}/previews/{photoPreviewSize}"
	PathPhotoPlaybackFile    = Prefix + "/photos/playback/{photoId}/files/{photoFileRole}"

	PathAgentAttachments = Prefix + "/agent/attachments"
	PathAgentAttachment  = Prefix + "/agent/attachments/{attachmentId}"

	// AgentAttachmentTaxDocumentParameter, set to true on a
	// PathAgentAttachments upload, hands the files in as paystubs or tax
	// forms: their text, which holds the person's taxpayer number, is
	// never kept.
	AgentAttachmentTaxDocumentParameter = "isTaxDocument"

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

	// PathMap is the map style host's files (the style, its vector tiles,
	// fonts and icons), fetched by this server for the signed-in browser,
	// so that the dashboard's content security policy keeps allowing nothing
	// but this server and a viewer's browser never talks to a third party.
	// Only the host of the configured map style is ever fetched from,
	// whatever the address says. PathMapStyle is the style itself, wherever
	// on that host the configured style is.
	PathMap      = Prefix + "/map"
	PathMapStyle = PathMap + "/style"

	// PathAvatarUser is a person's picture, a square PNG. The address the
	// API hands out carries ?v=<when it changed>, so a new picture is a new
	// address and the old one can be cached for a day; ?size=64 asks for the
	// small one a list row needs.
	PathAvatarUser = Prefix + "/avatar/user/{userId}"

	// PathLinkPreviewImage is the picture of a link preview, as this server
	// kept it: a JPEG scaled down to at most 600 pixels wide. Fetched from the
	// linked page once and served from here, so that showing a preview does
	// not tell the page's site who is reading. The name changes whenever the
	// picture does, so a copy can be kept for a day.
	PathLinkPreviewImage = Prefix + "/link-preview/image/{imageFileId}"

	// A setup profile for an iPhone or a Mac, downloaded once. The address
	// is the credential: Safari opens it without the person's session, and
	// it works for five minutes.
	PathMailboxSetupProfile = Prefix + "/mailbox/profile/{token}.mobileconfig"

	// 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 dashboard page that shows a one-time code for the TeaNode phone
	// app to scan, signing it in as the person who is signed in there.
	PathOAuthConnect = "/connect"

	// The push relay's endpoints (internal/api/v1api/apipush): a phone
	// registering its device token, and a server sending a notification.
	PathPushRegistrations = Prefix + "/push/registrations"
	PathPushNotifications = Prefix + "/push/notifications"

	// AppConnectLink is what that code holds: the project's own address,
	// which the app claims, so a phone's camera opens the app (or the App
	// Store) with the server and the code. Both go after the "#", which a
	// browser never sends, so neither reaches the project's web server.
	AppConnectLink = "https://teanode.com/app/connect"
)

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 CredentialKindHeader = "X-TeaNode-Credential-Kind"

CredentialKindHeader carries, beside them, what the request signed in with (models.CredentialKind). Stripped from every incoming request first, like the username.

View Source
const ImpersonatorUsernameHeader = "X-TeaNode-Impersonator"

ImpersonatorUsernameHeader carries, beside it, the operator signed in as that account when the request is an impersonation. Stripped from every incoming request first, like the username.

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.

View Source
const TapRequiredPhrase = "approve it on the dashboard or in the iPhone app"

TapRequiredPhrase is how the refusal of a request that only a person's tap may make begins: approving a call that spends the owner's money, or lending it. A command line token is refused these, because an agent can drive the person's command line, and says where to do it instead. The command line recognizes this phrase to explain the refusal in its own words.

View Source
const TeaNodeAppRedirectAddress = "com.teanode.app:/oauth"

TeaNodeAppRedirectAddress is the only return address of the TeaNode phone app (RFC 8252 private-use scheme, the app's bundle identifier), the one ios/TeaNodeKit registers with.

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

	// ErrConflict is a change refused because what it would change has
	// changed since the caller read it.
	ErrConflict = errors.New("api: conflict")
)
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 CredentialKindFromRequest added in v0.170.0

func CredentialKindFromRequest(request *http.Request) models.CredentialKind

CredentialKindFromRequest is what the request signed in with, as the authentication middleware established it, or empty.

func DisplayName added in v0.127.0

func DisplayName(name string, longest int) string

DisplayName is a name a program or a device gave itself, made safe to put in front of a person who is deciding whether to trust it.

Control characters and invisible formatting characters are dropped: a right-to-left override (U+202E) can make "ppA edoNaeT" read as something else, and a zero-width space can make two names that look the same differ. Runs of spaces and line breaks become one space, so a name is one line. It is cut to longest characters, never through one.

func DomainLogoPath

func DomainLogoPath(domainId string) string

DomainLogoPath is PathDomainLogo with its parameter filled in.

func ImpersonatorUsernameFromRequest added in v0.107.0

func ImpersonatorUsernameFromRequest(request *http.Request) string

ImpersonatorUsernameFromRequest is the operator behind an impersonation, as the authentication middleware established it, or empty.

func IsLocalRequest added in v0.129.0

func IsLocalRequest(request *http.Request) bool

IsLocalRequest says a request came from this machine and named it by its loopback address, with nothing in between: the server's own command line (client.Local), or a browser on the server itself. Plain HTTP is safe there, because nothing else is on the way.

The Host header alone does not say so. It is whatever the client wrote, and a proxy that forwards plain HTTP may set it to 127.0.0.1, so the connection has to come from loopback as well. A proxy on this same machine passes both of those, so a request that carries a proxy's forwarding headers is not local either: whoever it is forwarding for is somewhere else.

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 IsNativeAppClient added in v0.127.0

func IsNativeAppClient(redirects []string) bool

IsNativeAppClient says whether every address a program registered is an app's own return address: what a program must have registered as to be handed a connect code's token (internal/api/v1api/apioauth/connect.go).

func IsPrivateUseRedirect added in v0.127.0

func IsPrivateUseRedirect(address string) bool

IsPrivateUseRedirect says whether address is an app's own return address (RFC 8252 section 7.1): a scheme that is a reverse domain name, such as com.example.app:/oauth, with a path and no host.

Only an app installed on a device can receive one: the device hands the address to whichever app claimed the scheme, never to a web page. That is what lets a sign-in sheet on a phone return to its app, where a self-hosted server's address could never have been claimed in advance. The dot is what keeps out every scheme a browser or an operating system already means something by (javascript:, file:, data:, mailto:).

func IsRecordingLivePath added in v0.154.0

func IsRecordingLivePath(path string) bool

IsRecordingLivePath says whether a path is a recording's live socket, PathRecordingLive with its id filled in. Like PathAgentVoice it is let through the middleware: a phone opens it with its token in the first message, which the handler checks, since a websocket from a phone cannot be counted on to carry a header, and a session cookie is taken only from this server's own pages.

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 IsTeaNodeAppClient added in v0.193.0

func IsTeaNodeAppClient(redirects []string) bool

IsTeaNodeAppClient says every address a program registered is the TeaNode phone app's, and nothing else. Any app can register a private-use address of its own, so a private-use address alone does not say whose app it is.

func LinkPreviewImagePath added in v0.191.0

func LinkPreviewImagePath(imageFileId string) string

LinkPreviewImagePath is PathLinkPreviewImage with its parameter filled in.

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 PhotoFacePicturePath added in v0.171.0

func PhotoFacePicturePath(photoFaceId string) string

PhotoFacePicturePath is PathPhotoFacePicture with its parameter filled in.

func PhotoFilePath added in v0.171.0

func PhotoFilePath(photoId, photoFileRole string) string

PhotoFilePath is PathPhotoFile with its parameters filled in.

func PhotoPlaybackFilePath added in v0.171.0

func PhotoPlaybackFilePath(photoId, photoFileRole string) string

PhotoPlaybackFilePath is PathPhotoPlaybackFile with its parameters filled in.

func PhotoPlaybackPreviewPath added in v0.171.0

func PhotoPlaybackPreviewPath(photoId, photoPreviewSize string) string

PhotoPlaybackPreviewPath is PathPhotoPlaybackPreview with its parameters filled in.

func PhotoPreviewPath added in v0.171.0

func PhotoPreviewPath(photoId, photoPreviewSize string) string

PhotoPreviewPath is PathPhotoPreview with its parameters filled in.

func PhotoUploadPath added in v0.171.0

func PhotoUploadPath(photoUploadId string) string

PhotoUploadPath is PathPhotoUpload with its parameter filled in.

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 ChatService added in v0.170.0

type ChatService interface {
	// ReportPresence records one tab's or one phone's report for a person:
	// whether it is shown, how long since the person last used it, and which
	// conversation it has on screen, empty when none.
	ReportPresence(userId, reporterId string, isVisible bool, idleSeconds int, conversationId string, now time.Time)
}

ChatService is what the API tells the chat hub in the request: who has the dashboard or the app in front of them, so that a phone is not told what a person is looking at. The rest of the hub, which speaks in the agent's events, is reached through the hub itself by the packages that know it.

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 {
	// RunningServices is the immutable set constructed by this process.
	RunningServices *config.Services

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

	// Chat is what carries a chat to the people in it: the feed of their
	// conversations, the other instances, their phones. Unlike the agent it
	// is there whatever the agent configuration is, nil only in a test with
	// no chats.
	Chat ChatService
}

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.
apipush
Package apipush serves the push relay: what a TeaNode server does when the operator holds the TeaNode app's Apple push key and turns agent.push.relay.enabled on.
Package apipush serves the push relay: what a TeaNode server does when the operator holds the TeaNode app's Apple push key and turns agent.push.relay.enabled on.
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