Documentation
¶
Overview ¶
Package uiapi serves Sidecar's UI API v0 (docs/reference/ui-api.md).
It owns transport, trust and the HTTP/WebSocket mapping only. What a terminal stream means and what a Sessions row says belong to the packages behind Backend, which `sidecar mobile serve --stdio` and `sidecar mobile sessions --json` use unchanged; this package never decides either.
Index ¶
- Constants
- Variables
- func BrowserProofMessage(origin, id, nonce string, timestamp int64) string
- func CheckServiceInstall(stateDir string, managedPID int) error
- func Dir(stateDir string) string
- func EndpointPath(stateDir string) string
- func FormatAccessCode(code string) string
- func MultipleWaiting(n int) string
- func NormalizeAccessCode(input string) (string, bool)
- func NormalizeOrigin(raw string) (string, error)
- func ParseCatalogQuery(values url.Values) (mobileproto.CatalogQuery, error)
- func ParseServeHolds(data []byte, port int) (bool, error)
- func Spec() ([]byte, error)
- func TailscaleCert(ctx context.Context, host string) ([]byte, []byte, error)
- func TailscaleServeHolds(ctx context.Context, port int) (bool, error)
- func WatchExecutable(ctx context.Context, path string, interval time.Duration) (<-chan struct{}, error)
- type APIError
- type AccessApproval
- type AccessApproveRequest
- type AccessDenial
- type AccessDenyRequest
- type AccessRequestCreate
- type AccessRequestCreated
- type AccessRequestInfo
- type AccessRequestList
- type AccessRequestStatus
- type AlreadyRunningError
- type AttentionEvent
- type Backend
- type BrowserPublicKey
- type CatalogChangeSource
- type ClientInfo
- type ContentBackend
- type ContentEvent
- type ContentRef
- type ContentWatchSource
- type Device
- type DeviceList
- type DeviceRevocation
- type Endpoint
- type ErrorBody
- type ErrorDetail
- type EventMessage
- type EventTerminal
- type FileSearchBackend
- type FixtureBackend
- func (b *FixtureBackend) LookupProject(_ context.Context, project, workspace string) (contentservice.Workspace, error)
- func (b *FixtureBackend) Projects(_ context.Context, host string) (workspacewire.Projects, error)
- func (b *FixtureBackend) ReadProject(ctx context.Context, project, workspace string, p contentservice.ReadParams) (contentservice.ReadResult, error)
- func (b *FixtureBackend) SearchProject(ctx context.Context, project, workspace string, _ *filefind.Index, ...) (contentservice.FileSearchResult, error)
- func (b *FixtureBackend) ServeTerminal(ctx context.Context, input io.Reader, output io.Writer) error
- func (b *FixtureBackend) Sessions(_ context.Context, query mobileproto.CatalogQuery) (mobileproto.CatalogSnapshot, error)
- func (b *FixtureBackend) TreeProject(ctx context.Context, project, workspace string, paths []string) (contentservice.TreeResult, error)
- func (b *FixtureBackend) WatchProject(ctx context.Context, project, workspace string, p contentservice.ReadParams) ([]livewatch.Target, error)
- func (b *FixtureBackend) Workspace(ctx context.Context, project, host string, q mobileproto.CatalogQuery) (workspacewire.Workspace, error)
- func (b *FixtureBackend) WorkspaceInvalidation(ctx context.Context) (workspacewire.WorkspaceEvent, error)
- func (*FixtureBackend) WorkspaceOperation(context.Context, string, WorkspaceCommand) (json.RawMessage, int, error)
- type GeometryHolder
- type GeometryHolderSource
- type Hello
- type LayoutDocument
- type Listener
- type ListenerInfo
- type LocalClient
- func (c *LocalClient) ApproveAccess(ctx context.Context, code, surface string) (AccessApproval, error)
- func (c *LocalClient) DenyAccess(ctx context.Context, requestID string) (AccessDenial, error)
- func (c *LocalClient) Do(ctx context.Context, method, path string, body, out any) error
- func (c *LocalClient) HTTPClient() *http.Client
- func (c *LocalClient) ListAccessRequests(ctx context.Context) (AccessRequestList, error)
- func (c *LocalClient) ListDevices(ctx context.Context) (DeviceList, error)
- func (c *LocalClient) ListOrigins(ctx context.Context) (OriginList, error)
- func (c *LocalClient) PairOrigin(ctx context.Context, origin string, scopes ...string) (OriginRegistration, error)
- func (c *LocalClient) PairingCode(ctx context.Context, next string) (PairingCode, error)
- func (c *LocalClient) RevokeDevice(ctx context.Context, id string) (DeviceRevocation, error)
- func (c *LocalClient) RevokeOrigin(ctx context.Context, origin string) (OriginRevocation, error)
- func (c *LocalClient) RevokeSessions(ctx context.Context, origin string) (SessionRevocation, error)
- func (c *LocalClient) Status(ctx context.Context) (Status, error)
- func (c *LocalClient) URL(path string) string
- type NotificationClaimResponse
- type NotificationMutation
- type NotificationReceiptRequest
- type NotificationReceiptResponse
- type NotificationSettingsOptions
- type NotificationSnapshot
- type NotificationSourceOption
- type NotificationSourceRule
- type OperationError
- type Options
- type OriginList
- type OriginRecord
- type OriginRegistration
- type OriginRequest
- type OriginRevocation
- type PairedOrigin
- type PairingCode
- type PairingCodeRequest
- type PairingExchange
- type PairingExchangeRequest
- type Server
- type SessionProofChallenge
- type SessionProofChallengeRequest
- type SessionProofRequest
- type SessionRevocation
- type SessionToken
- type Status
- type TailnetAdapters
- type TailnetCertFunc
- type TailnetIdentity
- type TailnetIdentityFunc
- type TailnetListenFunc
- type TailnetMode
- type TailnetNode
- type TailnetNodeFunc
- type TailnetOptions
- type TailnetPeer
- type TailnetServeHoldsFunc
- type TailnetStatus
- type TailnetWhoisFunc
- type TerminalInfo
- type TerminalProtocol
- type TicketRequest
- type TicketResponse
- type UIRequestEvent
- type ViewerAckRequest
- type ViewerAckResponse
- type ViewerIdentity
- type ViewerPresenceRequest
- type ViewerPresenceResponse
- type Viewport
- type WorkspaceBackend
- type WorkspaceCommand
- type WorkspaceEventSource
Constants ¶
const ( CodeHostRefused = "host_refused" CodeOriginRefused = "origin_refused" CodeMutationRefused = "mutation_refused" CodeUnauthenticated = "unauthenticated" CodeLoginRefused = "tailnet_login_refused" CodeLocalOnly = "local_only" CodeNotServedHere = "not_served_here" CodeNotFound = "not_found" CodeMethod = "method_not_allowed" CodeInvalidRequest = "invalid_request" CodeOriginNotFound = "origin_not_found" CodePairingInvalid = "pairing_code_invalid" CodeSessionProofInvalid = "session_proof_invalid" CodeTooMany = "too_many_outstanding" CodeBackend = "backend" CodeUpgradeRequired = "upgrade_required" CodeApproverRefused = "approver_refused" CodeAccessCodeInvalid = "access_code_invalid" CodeAccessNotFound = "access_request_not_found" CodeTooManyAttempts = "too_many_attempts" CodeDeviceNotFound = "device_not_found" CodeAccessExpired = "access_request_expired" CodeRequestTimeout = "request_timeout" )
Error codes the API adds to the mobile protocol's refusal vocabulary.
const ( // APIVersion is the wire contract version in every route path. APIVersion = 0 // DefaultPort is the Browser listener's default loopback port. DefaultPort = 7861 )
const ( TailnetStateStarting = "starting" TailnetStateWaiting = "waiting_for_tailscale" TailnetStatePortHeld = "port_held" TailnetStateCertFailed = "certificate_unavailable" TailnetStateBindFailed = "bind_failed" TailnetStateListening = "listening" TailnetStateStopped = "stopped" )
Direct-mode states reported in status.
const ( CloseProtocolViolation websocket.StatusCode = 4400 CloseUnauthenticated websocket.StatusCode = 4401 CloseOriginRefused websocket.StatusCode = 4403 CloseShuttingDown websocket.StatusCode = 4409 // CloseTooManyTerminals is the WebSocket form of too_many_outstanding. CloseTooManyTerminals websocket.StatusCode = 4429 )
Close codes for /api/v0/terminal.
const ScopeContentRead = "content:read"
const ScopeFull = "full"
ScopeFull grants every API capability, including narrower scoped routes.
const ScopeUIControl = "ui:control"
const ScopeWorkspaceWrite = "workspace:write"
const SessionStorageKey = "sidecar.session"
SessionStorageKey names the legacy bearer key, removed during migration. Browser authentication now persists only a non-extractable CryptoKey.
Variables ¶
var ErrNotRunning = errors.New("no Sidecar API server is running; start one with `sidecar api serve`")
ErrNotRunning reports that no endpoint file names a live server.
Functions ¶
func BrowserProofMessage ¶
func CheckServiceInstall ¶
CheckServiceInstall refuses a service alongside an existing foreground server. The lock is authoritative even before discovery is published or if it is lost. A held lock is replaceable only when discovery identifies the manager's PID.
func EndpointPath ¶
EndpointPath is the discovery file for a state tree.
func FormatAccessCode ¶ added in v1.17.0
FormatAccessCode is the display form, K7Q-4MX.
func MultipleWaiting ¶ added in v1.17.0
MultipleWaiting is the plain warning shown when more than one browser is waiting: every request can look identical, so the code on the person's own screen is the only thing that tells them apart.
func NormalizeAccessCode ¶ added in v1.17.0
NormalizeAccessCode turns what a person typed into the canonical code: case-insensitive, hyphens and spaces ignored, and Crockford's look-alikes (O for 0, I and L for 1) accepted. It reports false for anything that cannot be a code.
func NormalizeOrigin ¶
NormalizeOrigin returns the serialized origin a browser would send for raw, or an error that says what is wrong with it.
func ParseCatalogQuery ¶
func ParseCatalogQuery(values url.Values) (mobileproto.CatalogQuery, error)
ParseCatalogQuery maps the sessions route's query parameters onto the protocol's catalog_query, refusing anything it does not name.
func ParseServeHolds ¶ added in v1.17.0
ParseServeHolds reports whether serve status JSON has a TCP route on port.
func Spec ¶
Spec generates the public OpenAPI 3.1 contract from the same wire types used by handlers, CLI clients and the terminal service. It performs no I/O.
func TailscaleCert ¶ added in v1.17.0
TailscaleCert fetches the node's certificate with `tailscale cert`, written to stdout so the key never touches a file Sidecar does not own. Tailscale keeps and renews its own copy; asking again returns the current one.
func TailscaleServeHolds ¶ added in v1.17.0
TailscaleServeHolds reads `tailscale serve status --json` for a route on port. A serve route is answered inside Tailscale, ahead of any socket Sidecar binds, so binding would succeed and never see a request.
func WatchExecutable ¶
func WatchExecutable(ctx context.Context, path string, interval time.Duration) (<-chan struct{}, error)
WatchExecutable follows the original launch path, including every symlink. Replacements and in-place changes cause a clean server shutdown. A temporarily missing path during an upgrade is ignored until its replacement arrives.
Types ¶
type APIError ¶
type APIError struct {
Status int
ErrorDetail
}
APIError is a decoded API refusal, as the CLI client reports it.
type AccessApproval ¶ added in v1.17.0
type AccessApproval struct {
RequestID string `json:"request_id"`
RegistrationID string `json:"registration_id"`
Label string `json:"label"`
Origin string `json:"origin"`
Address string `json:"address"`
ApprovedVia string `json:"approved_via"`
// ApprovedDevice is the tailnet device an allowed login approved from
// (direct mode only), as Tailscale names it.
ApprovedDevice string `json:"approved_device,omitempty"`
ApprovedAt time.Time `json:"approved_at"`
}
AccessApproval is the approved request and the registration it created.
type AccessApproveRequest ¶ added in v1.17.0
type AccessApproveRequest struct {
Code string `json:"code"`
Surface string `json:"surface,omitempty" jsonschema:"enum=cli,enum=tui"`
}
AccessApproveRequest is POST /api/v0/pairing/requests/approve. surface is accepted only on the Local socket, where it names the local surface (cli or tui) recorded as approved_via.
type AccessDenial ¶ added in v1.17.0
type AccessDenial struct {
RequestID string `json:"request_id"`
Status string `json:"status" jsonschema:"enum=denied"`
}
AccessDenial is the denied request.
type AccessDenyRequest ¶ added in v1.17.0
type AccessDenyRequest struct {
RequestID string `json:"request_id"`
}
AccessDenyRequest is POST /api/v0/pairing/requests/deny.
type AccessRequestCreate ¶ added in v1.17.0
type AccessRequestCreate struct {
PublicKey BrowserPublicKey `json:"public_key"`
Label string `json:"label,omitempty"`
}
AccessRequestCreate is POST /api/v0/pairing/requests: a browser with no credential asks for access. public_key is the browser's own non-extractable P-256 key; label is a device name the browser suggests for itself.
type AccessRequestCreated ¶ added in v1.17.0
type AccessRequestCreated struct {
RequestID string `json:"request_id"`
PollSecret string `json:"poll_secret"`
Code string `json:"code"`
ExpiresAt time.Time `json:"expires_at"`
}
AccessRequestCreated is returned once, to the requesting browser only. poll_secret authorizes GET /api/v0/pairing/requests/{id}; code is what the browser shows for an approver to type, in its display form (K7Q-4MX).
type AccessRequestInfo ¶ added in v1.17.0
type AccessRequestInfo struct {
RequestID string `json:"request_id"`
Label string `json:"label"`
Origin string `json:"origin"`
Address string `json:"address"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
AccessRequestInfo is one pending request as approvers see it. It never carries the code: the approver types the code the browser shows.
type AccessRequestList ¶ added in v1.17.0
type AccessRequestList struct {
Requests []AccessRequestInfo `json:"requests"`
}
AccessRequestList is GET /api/v0/pairing/requests.
type AccessRequestStatus ¶ added in v1.17.0
type AccessRequestStatus struct {
Status string `json:"status" jsonschema:"enum=pending,enum=approved,enum=denied,enum=expired"`
ExpiresAt time.Time `json:"expires_at"`
RegistrationID string `json:"registration_id,omitempty"`
}
AccessRequestStatus is GET /api/v0/pairing/requests/{id}. registration_id is present once approved: the browser then renews a session with its key.
type AlreadyRunningError ¶
type AlreadyRunningError struct{ PID int }
AlreadyRunningError is the single-instance refusal.
func (*AlreadyRunningError) Error ¶
func (e *AlreadyRunningError) Error() string
type AttentionEvent ¶
type Backend ¶
type Backend interface {
Sessions(ctx context.Context, query mobileproto.CatalogQuery) (mobileproto.CatalogSnapshot, error)
ServeTerminal(ctx context.Context, input io.Reader, output io.Writer) error
}
Backend is the library seam the API maps onto. One Backend lives for the whole server process; ServeTerminal is called once per terminal connection and owns that stream until input reaches EOF or ctx ends.
type BrowserPublicKey ¶
type BrowserPublicKey struct {
Kty string `json:"kty"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
KeyOps []string `json:"key_ops,omitempty"`
Ext *bool `json:"ext,omitempty"`
}
BrowserPublicKey is the public portion of an ECDSA P-256 JWK. The wire decoder rejects a private d field; key_ops/ext from WebCrypto are advisory.
type CatalogChangeSource ¶
CatalogChangeSource supplies real invalidations, not a catalog polling clock. One subscription lives for the API process. A buffered signal may coalesce any number of changes; Sessions must always return the current snapshot.
type ClientInfo ¶
type ClientInfo struct {
ID string `json:"id"`
Kind string `json:"kind"`
Listener Listener `json:"listener"`
Auth string `json:"auth"`
Origin string `json:"origin,omitempty"`
Login string `json:"login,omitempty"`
// Device is the tailnet device a direct-mode Tailnet client connected from.
Device string `json:"device,omitempty"`
Since time.Time `json:"since"`
}
ClientInfo is one connected client in status.
type ContentBackend ¶
type ContentBackend interface {
LookupProject(context.Context, string, string) (contentservice.Workspace, error)
ReadProject(context.Context, string, string, contentservice.ReadParams) (contentservice.ReadResult, error)
TreeProject(context.Context, string, string, []string) (contentservice.TreeResult, error)
}
ContentBackend preserves the shared content DTOs at the transport seam.
type ContentEvent ¶
type ContentEvent struct {
Resources []ContentRef `json:"resources"`
}
type ContentRef ¶
type ContentRef struct {
Project string `json:"project"`
Workspace string `json:"workspace,omitempty"`
Kind string `json:"kind"`
Target string `json:"target,omitempty"`
Operation string `json:"operation,omitempty"`
Path string `json:"path,omitempty"`
}
ContentRef is one currently open content pane. Reconnect events with a new set when panes change; subscriptions belong to the socket, not durable state.
type ContentWatchSource ¶
type ContentWatchSource interface {
WatchProject(context.Context, string, string, contentservice.ReadParams) ([]livewatch.Target, error)
}
type Device ¶ added in v1.17.0
type Device struct {
ID string `json:"id"`
Origin string `json:"origin"`
Label string `json:"label"`
ApprovedVia string `json:"approved_via"`
// ApprovedDevice is the tailnet device an allowed login approved this
// browser from (direct mode only), as Tailscale names it.
ApprovedDevice string `json:"approved_device,omitempty"`
ApprovedAt time.Time `json:"approved_at"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt time.Time `json:"last_used_at"`
ExpiresAt time.Time `json:"expires_at"`
Current bool `json:"current"`
}
Device is one browser registration in GET /api/v0/pairing/sessions. current marks the caller's own registration.
type DeviceList ¶ added in v1.17.0
type DeviceList struct {
Devices []Device `json:"devices"`
}
DeviceList is GET /api/v0/pairing/sessions.
type DeviceRevocation ¶ added in v1.17.0
type DeviceRevocation struct {
ID string `json:"id"`
Revoked bool `json:"revoked"`
TerminalsClosed int `json:"terminals_closed"`
}
DeviceRevocation is DELETE /api/v0/pairing/sessions/{id}.
type Endpoint ¶
type Endpoint struct {
PID int `json:"pid"`
Version string `json:"version"`
APIVersion int `json:"api_version"`
APIInstance string `json:"api_instance"`
StartedAt time.Time `json:"started_at"`
UnixSocket string `json:"unix_socket"`
TCP string `json:"tcp"`
BrowserProxyOrigin string `json:"browser_proxy_origin,omitempty"`
TailnetSocket string `json:"tailnet_socket,omitempty"`
TailnetTCP string `json:"tailnet_tcp,omitempty"`
}
Endpoint is $STATE/api/endpoint.json: how local CLI verbs and SDK users find the one running server.
func ReadEndpoint ¶
ReadEndpoint reads the discovery file and refuses one whose process is gone.
type ErrorBody ¶
type ErrorBody struct {
Error ErrorDetail `json:"error"`
}
ErrorBody is the shape of every API error.
type ErrorDetail ¶
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
// Field names the request field a validation refusal belongs to, as a
// dotted path within the request body (`quietHours.start`), so a form can
// show the message beside that control. Omitted when the refusal is not
// about one field.
Field string `json:"field,omitempty"`
}
ErrorDetail names a machine code and one human sentence that says what to do.
type EventMessage ¶
type EventMessage struct {
Notifications *NotificationSnapshot `json:"notifications,omitempty"`
Viewer *ViewerIdentity `json:"viewer,omitempty"`
UIRequest *UIRequestEvent `json:"ui_request,omitempty"`
Type string `` /* 200-byte string literal not displayed */
Seq uint64 `json:"seq" jsonschema:"minimum=1"`
APIVersion int `json:"api_version" jsonschema:"enum=0"`
APIInstance string `json:"api_instance,omitempty"`
ServerVersion string `json:"server_version,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
Catalog *mobileproto.CatalogSnapshot `json:"catalog,omitempty"`
Attention *AttentionEvent `json:"attention,omitempty"`
Terminals *[]EventTerminal `json:"terminals,omitempty"`
Error *ErrorDetail `json:"error,omitempty"`
Workspace *workspacewire.WorkspaceEvent `json:"workspace,omitempty"`
Content *ContentEvent `json:"content,omitempty"`
// AccessRequest accompanies access_requested: a browser asked for access.
// Sent only to approvers (Local, browser sessions, allowed tailnet
// logins). A burst coalesces to the newest; list the pending requests
// for the whole set. It never carries the code.
AccessRequest *AccessRequestInfo `json:"access_request,omitempty"`
Reason string `json:"reason,omitempty"`
}
EventMessage is one text frame (or one JSONL line on the CLI bridge). Seq starts at 1 with hello, increases on delivery, and resets on reconnect.
type EventTerminal ¶
type FileSearchBackend ¶ added in v1.17.0
type FileSearchBackend interface {
SearchProject(context.Context, string, string, *filefind.Index, contentservice.FileSearchParams) (contentservice.FileSearchResult, error)
}
FileSearchBackend keeps immutable fixtures behind the same transport seam: a fixture must never try to walk its synthetic root on this host.
type FixtureBackend ¶
type FixtureBackend struct {
Status Status
// contains filtered or unexported fields
}
FixtureBackend serves recorded resource data through the real server and runs the real terminal protocol Service with a synthetic capture adapter.
func LoadFixtures ¶
func LoadFixtures(dir string) (*FixtureBackend, error)
LoadFixtures requires a project-ordered sessions.json and status.json. Files are bounded and decoded strictly; malformed fixture authority fails at start.
func (*FixtureBackend) LookupProject ¶
func (b *FixtureBackend) LookupProject(_ context.Context, project, workspace string) (contentservice.Workspace, error)
func (*FixtureBackend) Projects ¶
func (b *FixtureBackend) Projects(_ context.Context, host string) (workspacewire.Projects, error)
func (*FixtureBackend) ReadProject ¶
func (b *FixtureBackend) ReadProject(ctx context.Context, project, workspace string, p contentservice.ReadParams) (contentservice.ReadResult, error)
func (*FixtureBackend) SearchProject ¶ added in v1.17.0
func (b *FixtureBackend) SearchProject(ctx context.Context, project, workspace string, _ *filefind.Index, p contentservice.FileSearchParams) (contentservice.FileSearchResult, error)
func (*FixtureBackend) ServeTerminal ¶
func (*FixtureBackend) Sessions ¶
func (b *FixtureBackend) Sessions(_ context.Context, query mobileproto.CatalogQuery) (mobileproto.CatalogSnapshot, error)
func (*FixtureBackend) TreeProject ¶
func (b *FixtureBackend) TreeProject(ctx context.Context, project, workspace string, paths []string) (contentservice.TreeResult, error)
func (*FixtureBackend) WatchProject ¶
func (b *FixtureBackend) WatchProject(ctx context.Context, project, workspace string, p contentservice.ReadParams) ([]livewatch.Target, error)
func (*FixtureBackend) Workspace ¶
func (b *FixtureBackend) Workspace(ctx context.Context, project, host string, q mobileproto.CatalogQuery) (workspacewire.Workspace, error)
func (*FixtureBackend) WorkspaceInvalidation ¶
func (b *FixtureBackend) WorkspaceInvalidation(ctx context.Context) (workspacewire.WorkspaceEvent, error)
func (*FixtureBackend) WorkspaceOperation ¶
func (*FixtureBackend) WorkspaceOperation(context.Context, string, WorkspaceCommand) (json.RawMessage, int, error)
type GeometryHolder ¶
type GeometryHolderSource ¶
type GeometryHolderSource interface {
GeometryHolder(context.Context, TerminalInfo) *GeometryHolder
}
GeometryHolderSource observes only sessions with open API attachments. The holder is presentation data, never a lease token or instance identity.
type Hello ¶
type Hello struct {
APIVersion int `json:"api_version"`
APIInstance string `json:"api_instance"`
ServerVersion string `json:"server_version"`
Capabilities []string `json:"capabilities"`
Terminal TerminalProtocol `json:"terminal"`
}
Hello is GET /api/v0/hello.
type LayoutDocument ¶
type LayoutDocument = viewerlayout.Document
LayoutDocument is the shared layout store document, with no cell geometry.
type ListenerInfo ¶
type ListenerInfo struct {
Name Listener `json:"name"`
Network string `json:"network"`
Address string `json:"address"`
Host string `json:"host,omitempty"`
}
ListenerInfo describes one bound listener in status.
type LocalClient ¶
type LocalClient struct {
Endpoint Endpoint
// contains filtered or unexported fields
}
LocalClient talks to a running server over its Local Unix socket, where no guard or credential applies. CLI verbs and tests use it.
func NewLocalClient ¶
func NewLocalClient(stateDir string) (*LocalClient, error)
NewLocalClient discovers the server for stateDir through endpoint.json.
func NewLocalClientForSocket ¶
func NewLocalClientForSocket(endpoint Endpoint) *LocalClient
NewLocalClientForSocket builds a client for an already-known endpoint.
func (*LocalClient) ApproveAccess ¶ added in v1.17.0
func (c *LocalClient) ApproveAccess(ctx context.Context, code, surface string) (AccessApproval, error)
ApproveAccess approves the waiting browser that shows code. surface names the local surface recorded as approved_via: cli or tui.
func (*LocalClient) DenyAccess ¶ added in v1.17.0
func (c *LocalClient) DenyAccess(ctx context.Context, requestID string) (AccessDenial, error)
DenyAccess refuses one waiting browser by request id.
func (*LocalClient) HTTPClient ¶
func (c *LocalClient) HTTPClient() *http.Client
HTTPClient exposes the socket-bound client, for WebSocket dialing.
func (*LocalClient) ListAccessRequests ¶ added in v1.17.0
func (c *LocalClient) ListAccessRequests(ctx context.Context) (AccessRequestList, error)
ListAccessRequests lists browsers waiting for approval, without codes.
func (*LocalClient) ListDevices ¶ added in v1.17.0
func (c *LocalClient) ListDevices(ctx context.Context) (DeviceList, error)
ListDevices lists browser registrations.
func (*LocalClient) ListOrigins ¶
func (c *LocalClient) ListOrigins(ctx context.Context) (OriginList, error)
ListOrigins lists paired origins without tokens.
func (*LocalClient) PairOrigin ¶
func (c *LocalClient) PairOrigin(ctx context.Context, origin string, scopes ...string) (OriginRegistration, error)
PairOrigin registers origin and returns its one-time-visible token.
func (*LocalClient) PairingCode ¶
func (c *LocalClient) PairingCode(ctx context.Context, next string) (PairingCode, error)
PairingCode issues a one-time code for the same-origin UI.
func (*LocalClient) RevokeDevice ¶ added in v1.17.0
func (c *LocalClient) RevokeDevice(ctx context.Context, id string) (DeviceRevocation, error)
RevokeDevice signs out one browser registration by its full id.
func (*LocalClient) RevokeOrigin ¶
func (c *LocalClient) RevokeOrigin(ctx context.Context, origin string) (OriginRevocation, error)
RevokeOrigin removes one paired origin.
func (*LocalClient) RevokeSessions ¶
func (c *LocalClient) RevokeSessions(ctx context.Context, origin string) (SessionRevocation, error)
RevokeSessions drops every browser session, or only origin's when origin is not empty.
func (*LocalClient) Status ¶
func (c *LocalClient) Status(ctx context.Context) (Status, error)
Status reads GET /api/v0/status.
func (*LocalClient) URL ¶
func (c *LocalClient) URL(path string) string
URL is the request URL for path on the Local listener.
type NotificationClaimResponse ¶ added in v1.17.0
type NotificationClaimResponse struct {
Claimed bool `json:"claimed"`
}
type NotificationMutation ¶ added in v1.17.0
type NotificationMutation struct {
ID string `json:"id,omitempty"`
IDs []string `json:"ids,omitempty"`
}
NotificationMutation names the records to mark read or dismiss. Send id for one record (an unknown id is 404) or ids, never both, for a batch applied as one change: a batch skips unknown and already-settled ids, because the goal state holds for them. Servers advertising the notifications_batch capability accept ids.
type NotificationReceiptRequest ¶ added in v1.17.0
type NotificationReceiptResponse ¶ added in v1.17.0
type NotificationReceiptResponse struct {
Delivered bool `json:"delivered"`
}
type NotificationSettingsOptions ¶ added in v1.17.0
type NotificationSettingsOptions struct {
// Writable reports whether this caller may PUT the settings (ui:control or
// full). A read-only credential can still show them.
Writable bool `json:"writable"`
// Sources lists the registered sources, loudest first.
Sources []NotificationSourceOption `json:"sources"`
}
NotificationSettingsOptions is what a settings form needs beside the stored NotificationsConfig: the registered sources a client may override, with their built-in rules, and whether this credential may save.
type NotificationSnapshot ¶ added in v1.17.0
type NotificationSnapshot struct {
Notifications []notification.Notification `json:"notifications"`
Unread int `json:"unread"`
ToastIDs []string `json:"toast_ids"`
DeliveryIDs []string `json:"delivery_ids"`
Delivery map[string]notification.DeliveryDecision `json:"delivery"`
}
type NotificationSourceOption ¶ added in v1.17.0
type NotificationSourceOption struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
// Defaults is the rule this build applies when the source has no override.
Defaults NotificationSourceRule `json:"defaults"`
}
NotificationSourceOption is one registered source as a form presents it.
type NotificationSourceRule ¶ added in v1.17.0
type NotificationSourceRule struct {
Toast bool `json:"toast"`
Native bool `json:"native"`
Sound string `json:"sound"`
Expiry string `json:"expiry"`
}
NotificationSourceRule is a resolved per-source rule. Expiry is a Go duration (`10s`) or `sticky` for a toast that stays until dismissed.
type OperationError ¶
OperationError retains the CLI refusal and status across HTTP and remote calls.
func (*OperationError) Error ¶
func (e *OperationError) Error() string
type Options ¶
type Options struct {
StateDir string
// Inherited supplies already-acquired manager listeners. Start owns them on
// success; the caller closes them on failure. Nil discovers manager sockets.
Inherited []apiservice.ActivatedListener
// Port is the Browser listener's loopback port; 0 picks a free one.
Port int
BrowserProxyOrigin string
UIDir string
Tailnet *TailnetOptions
Backend Backend
Content ContentBackend
Version string
FixtureStatus *Status
Now func() time.Time
Logf func(format string, args ...any)
// KeepaliveInterval and KeepaliveTimeout govern terminal WebSocket pings;
// zero means 30s and 15s.
KeepaliveInterval time.Duration
KeepaliveTimeout time.Duration
// RequestReadTimeout bounds how long a non-stream request may take to
// deliver its body after its headers. Zero means 10 seconds.
RequestReadTimeout time.Duration
// KeepaliveStallTimeout bounds how long a blocked inbound pump may excuse
// missing pongs. Zero means one minute.
KeepaliveStallTimeout time.Duration
}
Options configures Start.
type OriginList ¶
type OriginList struct {
Origins []PairedOrigin `json:"origins"`
}
OriginList is GET /api/v0/origins.
type OriginRecord ¶
type OriginRecord struct {
Origin string `json:"origin"`
TokenSHA256 string `json:"token_sha256"`
Scopes []string `json:"scopes"`
CreatedAt time.Time `json:"created_at"`
}
OriginRecord is one paired origin as persisted. The bearer token itself is never stored, only its SHA-256.
type OriginRegistration ¶
type OriginRegistration struct {
Origin string `json:"origin"`
Token string `json:"token"`
Scopes []string `json:"scopes"`
}
OriginRegistration is POST /api/v0/origins. The token appears only here.
type OriginRequest ¶
type OriginRevocation ¶
OriginRevocation is DELETE /api/v0/origins.
type PairedOrigin ¶
type PairedOrigin struct {
Origin string `json:"origin"`
Scopes []string `json:"scopes"`
CreatedAt time.Time `json:"created_at"`
}
PairedOrigin is a registration as listed: never the token or its hash.
type PairingCode ¶
type PairingCode struct {
Code string `json:"code"`
URL string `json:"url"`
ExpiresAt time.Time `json:"expires_at"`
}
PairingCode is POST /api/v0/pairing/codes.
type PairingCodeRequest ¶
type PairingCodeRequest struct {
Next string `json:"next,omitempty"`
}
type PairingExchange ¶
type PairingExchange struct {
RegistrationID string `json:"registration_id"`
ExpiresAt time.Time `json:"expires_at"`
Token string `json:"token"`
Next string `json:"next"`
}
PairingExchange is POST /api/v0/pairing/exchange: a browser session token for the same-origin UI, and the validated path to land on.
type PairingExchangeRequest ¶
type PairingExchangeRequest struct {
PublicKey BrowserPublicKey `json:"public_key"`
Code string `json:"code"`
Next string `json:"next,omitempty"`
// Label is the device name the pairing page suggests ("Safari on
// macOS"), cleaned like an access request's label: a claim, never proof.
Label string `json:"label,omitempty"`
}
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is one running API process.
func Start ¶
Start binds every listener, writes endpoint.json and begins serving. It refuses while another server holds the same state tree.
func (*Server) BrowserURL ¶
BrowserURL is the Browser listener's base URL.
func (*Server) Shutdown ¶
Shutdown closes every terminal stream with 4409, stops the listeners and removes endpoint.json. Leases are released by the streams themselves, exactly as on stdin EOF.
func (*Server) TailnetStatus ¶ added in v1.17.0
func (s *Server) TailnetStatus() *TailnetStatus
TailnetStatus reports the Tailnet listener, or nil when it is not enabled.
type SessionProofChallenge ¶
type SessionProofChallengeRequest ¶
type SessionProofChallengeRequest struct {
RegistrationID string `json:"registration_id"`
}
SessionProofChallengeRequest names an origin-bound public-key registration.
type SessionProofRequest ¶
type SessionRevocation ¶
type SessionRevocation struct {
Origin string `json:"origin,omitempty"`
Revoked int `json:"revoked"`
TerminalsClosed int `json:"terminals_closed"`
}
SessionRevocation is DELETE /api/v0/pairing/sessions.
type SessionToken ¶
type Status ¶
type Status struct {
APIVersion int `json:"api_version"`
APIInstance string `json:"api_instance"`
ServerVersion string `json:"server_version"`
UIDir *string `json:"ui_dir,omitempty"`
UIConfigured bool `json:"ui_configured"`
PID int `json:"pid"`
StartedAt time.Time `json:"started_at"`
Listeners []ListenerInfo `json:"listeners"`
// Tailnet reports the Tailnet listener when it is enabled.
Tailnet *TailnetStatus `json:"tailnet,omitempty"`
Clients []ClientInfo `json:"clients"`
Terminals []TerminalInfo `json:"terminals"`
}
Status is GET /api/v0/status and `sidecar api status --json`.
type TailnetAdapters ¶ added in v1.17.0
type TailnetAdapters struct {
Node TailnetNodeFunc
Whois TailnetWhoisFunc
Cert TailnetCertFunc
ServeHolds TailnetServeHoldsFunc
Listen TailnetListenFunc
}
TailnetAdapters bundles the direct-mode seams. Nil fields use the CLI defaults.
type TailnetCertFunc ¶ added in v1.17.0
TailnetCertFunc returns a PEM certificate chain and private key for the node's MagicDNS name.
type TailnetIdentity ¶
TailnetIdentity is what the Tailnet listener needs from Tailscale: the node's MagicDNS name and the login that owns the node.
func ParseTailscaleStatus ¶
func ParseTailscaleStatus(data []byte) (TailnetIdentity, error)
ParseTailscaleStatus extracts the node identity from `tailscale status --json` output.
func TailscaleStatusIdentity ¶
func TailscaleStatusIdentity(ctx context.Context) (TailnetIdentity, error)
TailscaleStatusIdentity reads the local node's identity from the tailscale CLI.
type TailnetIdentityFunc ¶
type TailnetIdentityFunc func(ctx context.Context) (TailnetIdentity, error)
TailnetIdentityFunc is the adapter seam over Tailscale. The default reads `tailscale status --json` and never changes Tailscale configuration.
type TailnetListenFunc ¶ added in v1.17.0
TailnetListenFunc binds one address; tests map tailnet addresses onto loopback.
type TailnetMode ¶ added in v1.17.0
type TailnetMode string
TailnetMode selects how the Tailnet listener reaches the tailnet.
const ( // TailnetModeDirect binds the node's tailnet addresses itself, serves TLS // with a `tailscale cert` certificate and identifies every connection with // Tailscale's whois. It is the documented default. TailnetModeDirect TailnetMode = "direct" // TailnetModeServe is the socket listener a `tailscale serve` proxy // targets, trusting the Tailscale-User-Login header it adds. TailnetModeServe TailnetMode = "serve" )
func ParseTailnetMode ¶ added in v1.17.0
func ParseTailnetMode(value string) (TailnetMode, error)
ParseTailnetMode accepts the api.tailnetMode and --tailnet-mode values.
type TailnetNode ¶ added in v1.17.0
type TailnetNode struct {
// Host is the MagicDNS name without the trailing dot, lowercased.
Host string
// OwnerLogin owns the node; it is the default allowed login.
OwnerLogin string
// OwnerID is the owning user's ID. The default owner is pinned by it, not
// by the login string.
OwnerID int64
// StableID identifies the node itself, so whois naming it is refused.
StableID string
// Tags are the node's ACL tags. A tagged node has no owner to default to.
Tags []string
// Suffix is the tailnet's MagicDNS suffix; peers outside it are shared in
// from another tailnet.
Suffix string
// Addresses are the node's own tailnet addresses: what direct mode binds,
// and the sources it refuses.
Addresses []netip.Addr
}
TailnetNode is what direct mode reads about the local node.
func ParseTailscaleNode ¶ added in v1.17.0
func ParseTailscaleNode(data []byte) (TailnetNode, error)
ParseTailscaleNode extracts the node's name, owner and addresses from `tailscale status --json`, refusing a node that is not running.
func TailscaleNode ¶ added in v1.17.0
func TailscaleNode(ctx context.Context) (TailnetNode, error)
TailscaleNode reads the local node from `tailscale status --json`.
type TailnetNodeFunc ¶ added in v1.17.0
type TailnetNodeFunc func(ctx context.Context) (TailnetNode, error)
TailnetNodeFunc reads the local node.
type TailnetOptions ¶
type TailnetOptions struct {
// Host is the node's MagicDNS name without the trailing dot.
Host string
// Logins are the Tailscale logins trusted on this listener.
Logins []string
// HTTPSPort is the public HTTPS port. In serve mode it is the Tailscale
// Serve port, not a local bind, and zero uses the standard-port Host and
// Origin guards. In direct mode it is the port bound on the node's tailnet
// addresses, and zero means DefaultPort.
HTTPSPort int
// Port, when non-zero, serves the serve-mode listener on a dedicated
// loopback TCP port instead of the Unix socket, for a tailscaled that
// cannot open a 0600 user socket. Direct mode refuses it.
Port int
// Mode selects direct or serve. The CLI resolves api.tailnetMode, whose
// default is direct; the zero value here is serve, so a caller that names
// no mode never starts reaching Tailscale on its own.
Mode TailnetMode
// Adapters are direct mode's seams over Tailscale; nil fields use the CLI.
// In direct mode Host is discovered, and Logins may be empty to mean the
// node owner.
Adapters TailnetAdapters
// contains filtered or unexported fields
}
TailnetOptions configures the Tailnet listener.
func (TailnetOptions) HTTPSURL ¶ added in v1.17.0
func (o TailnetOptions) HTTPSURL() (string, error)
HTTPSURL returns the exact public origin protected by the Tailnet listener. The configured port does not change the listener's Unix socket or bind address.
type TailnetPeer ¶ added in v1.17.0
type TailnetPeer struct {
Login string
// UserID is the owning user's ID.
UserID int64
// Device is the device's short name; NodeID its stable node ID; Name its
// MagicDNS name, lowercased without the trailing dot.
Device string
NodeID string
Name string
Tags []string
SharedIn bool
}
TailnetPeer is Tailscale's answer for the device behind one source address.
func ParseTailscaleWhois ¶ added in v1.17.0
func ParseTailscaleWhois(data []byte) (TailnetPeer, error)
ParseTailscaleWhois extracts the login, device and tags from `tailscale whois --json`. An answer without a login is an error, never an anonymous peer.
func TailscaleWhois ¶ added in v1.17.0
TailscaleWhois identifies a peer with `tailscale whois --json`.
type TailnetServeHoldsFunc ¶ added in v1.17.0
TailnetServeHoldsFunc reports whether a `tailscale serve` (or funnel) route already holds a TCP port on this node.
type TailnetStatus ¶ added in v1.17.0
type TailnetStatus struct {
Mode TailnetMode `json:"mode"`
// State is listening once the listener serves; direct mode also reports
// starting, waiting_for_tailscale, port_held, certificate_unavailable,
// bind_failed and stopped.
State string `json:"state"`
// Message says what is wrong and what to do while State is not listening.
Message string `json:"message,omitempty"`
Host string `json:"host,omitempty"`
// Origin is the listener's own origin.
Origin string `json:"origin,omitempty"`
// Port is the tailnet HTTPS port direct mode binds.
Port int `json:"port,omitempty"`
// Addresses are the tailnet addresses direct mode is bound to.
Addresses []string `json:"addresses,omitempty"`
Logins []string `json:"logins,omitempty"`
// CertificateExpiresAt is the served certificate's expiry (direct mode).
CertificateExpiresAt *time.Time `json:"certificate_expires_at,omitempty"`
// Since is when State last changed.
Since time.Time `json:"since"`
// NextAttemptAt is when direct mode next retries, while not listening.
NextAttemptAt *time.Time `json:"next_attempt_at,omitempty"`
}
TailnetStatus is the Tailnet listener's state in GET /api/v0/status.
type TailnetWhoisFunc ¶ added in v1.17.0
TailnetWhoisFunc identifies the device that owns a tailnet address.
type TerminalInfo ¶
type TerminalInfo struct {
ClientID string `json:"client_id"`
OwnerHostID string `json:"owner_host_id,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
Session string `json:"session,omitempty"`
Pane string `json:"pane,omitempty"`
DisplayName string `json:"display_name,omitempty"`
Control bool `json:"control"`
Holder *mobileproto.Holder `json:"holder,omitempty"`
}
TerminalInfo is one open terminal attachment and whether its client holds control. It is observed from the stream, never decided here.
type TerminalProtocol ¶
type TicketRequest ¶
type TicketRequest struct{}
type TicketResponse ¶
type TicketResponse struct {
Ticket string `json:"ticket"`
ExpiresAt time.Time `json:"expires_at"`
}
TicketResponse is POST /api/v0/ws-tickets.
type UIRequestEvent ¶
type UIRequestEvent struct {
ID string `json:"id"`
Action uirequest.Action `json:"action"`
Project string `json:"project"`
Workspace string `json:"workspace,omitempty"`
Request uirequest.Request `json:"request"`
// OriginPane identifies the matched leaf in the pre-proposal tree preorder.
OriginPane int `json:"origin_pane,omitempty"`
Document LayoutDocument `json:"document"`
ETag string `json:"etag"`
ExpiresAt time.Time `json:"expires_at"`
}
type ViewerAckRequest ¶
type ViewerAckResponse ¶
type ViewerAckResponse struct {
Document LayoutDocument `json:"document"`
ETag string `json:"etag"`
}
type ViewerIdentity ¶
type ViewerPresenceRequest ¶
type ViewerPresenceRequest struct {
ViewerID string `json:"viewer_id"`
Focused bool `json:"focused"`
Visible bool `json:"visible"`
Project string `json:"project"`
Workspace string `json:"workspace,omitempty"`
Session string `json:"session,omitempty"`
FocusedPane int `json:"focused_pane,omitempty"`
Viewport Viewport `json:"viewport"`
}
type ViewerPresenceResponse ¶
type ViewerPresenceResponse struct {
Holder bool `json:"holder"`
}
type Viewport ¶
type Viewport = layoutreport.CSSViewport
Viewport is CSS pixels, never terminal cells.
type WorkspaceBackend ¶
type WorkspaceBackend interface {
Projects(context.Context, string) (workspacewire.Projects, error)
Workspace(context.Context, string, string, mobileproto.CatalogQuery) (workspacewire.Workspace, error)
WorkspaceOperation(context.Context, string, WorkspaceCommand) (json.RawMessage, int, error)
}
WorkspaceBackend is the application seam for the workspace HTTP adapter. Operations use the CLI's JSON result and exit status, including partial results.
type WorkspaceCommand ¶
type WorkspaceCommand struct {
Operation string `json:"-"`
Host string `json:"host,omitempty"`
Target string `json:"target,omitempty"`
Name string `json:"name,omitempty"`
Base string `json:"base,omitempty"`
Confirm bool `json:"confirm,omitempty"`
ExpectSourceOID string `json:"expect_source_oid,omitempty"`
ExpectHeadOID string `json:"expect_head_oid,omitempty"`
ExpectDeleteState string `json:"expect_delete_state,omitempty"`
ExpectBranch string `json:"expect_branch,omitempty"`
DeleteLocalBranch bool `json:"delete_local_branch,omitempty"`
DeleteRemoteBranch bool `json:"delete_remote_branch,omitempty"`
Kind string `json:"kind,omitempty"`
Args []string `json:"args,omitempty"`
Text string `json:"text,omitempty"`
Wait bool `json:"wait,omitempty"`
Timeout string `json:"timeout,omitempty"`
}
WorkspaceCommand is input to the shared command adapter, never raw CLI argv.
type WorkspaceEventSource ¶
type WorkspaceEventSource interface {
WorkspaceInvalidation(context.Context) (workspacewire.WorkspaceEvent, error)
}
WorkspaceEventSource adds owning-host project references to resource invalidations.
Source Files
¶
- access.go
- access_handler.go
- access_spec.go
- auth.go
- browserauth.go
- browserauth_handler.go
- client.go
- clients.go
- content.go
- content_events.go
- content_fixtures.go
- endpoint.go
- errors.go
- events.go
- executable.go
- file_search.go
- fixtures.go
- handler.go
- holder_cache.go
- layouts.go
- listeners.go
- notifications.go
- origins.go
- pairpage.go
- server.go
- sessions.go
- spec.go
- static.go
- tailnet.go
- tailnet_adapters.go
- tailnet_admission.go
- tailnet_direct.go
- terminal.go
- viewer_layout.go
- viewers.go
- wire.go
- workspace.go
- workspace_events.go
- workspace_fixtures.go
- workspace_spec.go