remote

package
v0.119.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 27 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 remote lets a phone reach this daemon from anywhere, through a relay that only ever sees ciphertext (ADR-058).

The daemon dials out to the relay and waits; a phone dials the same relay naming this machine, and the relay splices the two. Inside that splice the phone and the daemon run a Noise handshake against the daemon's static key, which the phone read off the pairing QR, so the relay — ours or anyone's — carries bytes it cannot read or alter. Past the handshake, the phone's requests are replayed onto this daemon's own loopback listener marked as coming off the network: the device token, the viewer and controller roles and revocation are exactly the ones LAN pairing uses, not a second set.

Index

Constants

View Source
const (
	DefaultRelay = "wss://relay.caprock.dev"
	DefaultApp   = "https://m.caprock.dev"
)

Defaults: the relay and the phone's page Caprock runs. Both can be replaced by the owner's own (`caprock remote on --relay … --app …`); the phone reads the relay from the pairing link, so nothing on the phone is hard-wired.

View Source
const (

	// MaxMessage is the longest Noise message, ciphertext and tag included.
	MaxMessage = 65535

	// MaxPlaintext is the most one transport message carries.
	MaxPlaintext = MaxMessage - tagLen
)

Noise_NK_25519_AESGCM_SHA256, as the Noise Protocol Framework (revision 34) specifies it. NK because the phone knows the daemon's static key before it connects (the QR) and the daemon learns who the phone is from its device token, one layer up — so pairing, roles and revocation stay where they are. AESGCM and SHA256 because Go's standard library has both and so does every browser; the phone side is ui/src/remote/noise.ts, and the two are held to the same bytes by testdata/remote/noise-vector.json.

View Source
const (
	KindReq      byte = 0x01
	KindReqBody  byte = 0x02
	KindReqEnd   byte = 0x03
	KindRes      byte = 0x04
	KindResBody  byte = 0x05
	KindResEnd   byte = 0x06
	KindWSOpen   byte = 0x07
	KindWSOpened byte = 0x08
	KindWSText   byte = 0x09
	KindWSBinary byte = 0x0a
	KindWSClose  byte = 0x0b
	KindCancel   byte = 0x0c
	KindWSPart   byte = 0x0d

	// ProtocolVersion is the frame protocol above. A phone speaking a newer
	// one is told so in the Welcome rather than half-working.
	ProtocolVersion = 1
)

The phone's protocol, inside the Noise channel. Every transport message is one frame: a kind byte, a four-byte stream id the phone chose, and a body. Streams are HTTP requests and WebSockets onto this daemon's own API, so the phone's dashboard runs unchanged: its fetch() and WebSocket calls are carried, not rewritten (ui/src/remote/transport.ts).

phone → daemon
  KindReq      {"m","p","h"}       an HTTP request's head
  KindReqBody  bytes               part of its body
  KindReqEnd                       the body is complete; send it
  KindWSOpen   {"p","proto"}       open a WebSocket at path p
  KindCancel                       abandon the stream
daemon → phone
  KindRes      {"s","h"}           the response's status and headers
  KindResBody  bytes               part of its body
  KindResEnd                       the body is complete
  KindWSOpened {"proto"}           the socket is open
both ways, on a WebSocket stream
  KindWSPart   bytes               a message continues in the next frame
  KindWSText   bytes               the last part of a text message
  KindWSBinary bytes               the last part of a binary message
  KindWSClose  {"code","reason"}   the socket closed

The first message each way is the Noise handshake; its payloads are a Hello from the phone and a Welcome from the daemon.

View Source
const (
	FrameOpen      byte = 0x01
	FrameData      byte = 0x02
	FrameClose     byte = 0x03
	FrameChallenge byte = 0x10
	FrameProof     byte = 0x11
	FrameReady     byte = 0x12

	// CloseOffline is the WebSocket close code a phone gets when the machine
	// it named is not connected to the relay.
	CloseOffline = 4404
	// CloseReplaced is what an older daemon connection gets when the same
	// machine connects again.
	CloseReplaced = 4409
	// MaxRelayMessage bounds every WebSocket message on either side: one Noise
	// message plus the five-byte frame header.
	MaxRelayMessage = MaxMessage + 5
)

The relay's wire, between it and a daemon. A phone's side of the relay is simpler: one WebSocket per phone, each binary message one Noise message, passed through untouched.

A daemon holds one WebSocket to the relay at /v1/host/<host id> and every phone that connects is multiplexed over it, numbered by the relay:

relay → daemon   FrameOpen  conn            a phone connected
both ways        FrameData  conn  bytes     one Noise message
both ways        FrameClose conn            that phone is gone / drop it

Before any of that the daemon proves it holds the host id's private key: the relay sends FrameChallenge with 32 random bytes and the daemon answers FrameProof with an Ed25519 signature over hostProofContext, the id and the nonce. Nothing else the relay does depends on trusting the daemon — it cannot read what it carries — but without the proof anyone could register a machine's id and take its phones' connections, which is a denial of service even when it is not a breach.

Keepalive is the text message "ping", answered "pong", either way round; Cloudflare answers it without waking the relay (setWebSocketAutoResponse).

Variables

This section is empty.

Functions

func CheckAppURL

func CheckAppURL(raw string) error

CheckAppURL accepts https:// anywhere and http:// only on this machine: the phone's page holds its keys, and a page fetched in clear text is a page anyone on the path can replace.

func CheckRelayURL

func CheckRelayURL(raw string) error

CheckRelayURL accepts wss:// anywhere and ws:// only to this machine: a relay sees who talks to whom and when, and in clear text so would anyone on the path.

func Frame

func Frame(kind byte, conn uint32, data []byte) []byte

Frame builds one relay↔daemon frame.

func HostID

func HostID(pub ed25519.PublicKey) string

HostID names a machine on a relay: its Ed25519 public key, base64url without padding. Self-certifying, so a relay needs no account or database to know who may register it.

func PairLink(s *Settings, k *Keys, code, name string) string

PairLink is what the pairing QR holds: the phone's page, told which relay, which machine, which key to pin, the code, and what to call the machine. All of it after the #, so none of it reaches the page's server.

func ParseFrame

func ParseFrame(b []byte) (kind byte, conn uint32, data []byte, err error)

ParseFrame splits a relay↔daemon frame.

func ParseHostID

func ParseHostID(id string) (ed25519.PublicKey, error)

ParseHostID is HostID's inverse, refusing anything that is not a key.

func ProofMessage

func ProofMessage(hostID string, nonce []byte) []byte

ProofMessage is what a daemon signs to answer a relay's challenge.

func Reset

func Reset(dir string) error

Reset forgets the keys, so the next Load makes new ones and every phone paired over the relay has to pair again.

func Save

func Save(dir string, s *Settings) error

Save writes the settings, 0600.

func VerifyProof

func VerifyProof(hostID string, nonce, sig []byte) bool

VerifyProof checks a daemon's answer to nonce.

Types

type Hello

type Hello struct {
	V int `json:"v"`
}

Hello is the phone's handshake payload.

type Host

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

Host keeps this machine connected to a relay and serves the phones that reach it there.

func NewHost

func NewHost(opt Options) *Host

NewHost makes a host; Run connects it.

func (*Host) Run

func (h *Host) Run(ctx context.Context)

Run stays connected until ctx ends, reconnecting with backoff: a laptop sleeps, Wi-Fi drops, the relay restarts, and none of those should need anyone to touch the machine.

func (*Host) State

func (h *Host) State() State

State reports the connection's state.

type Initiator

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

Initiator is the phone's half of NK, kept in Go for the tests and for `caprock remote check`, which proves a relay round trip from the machine itself.

func Initiate

func Initiate(rs, payload []byte, e *ecdh.PrivateKey) (*Initiator, []byte, error)

Initiate writes the first message to the daemon whose static public key is rs. e is the ephemeral key, nil for a fresh one.

func (*Initiator) Finish

func (i *Initiator) Finish(msg2 []byte) ([]byte, *Session, error)

Finish reads the daemon's reply and returns its payload and the session.

type Keys

type Keys struct {
	Sign   ed25519.PrivateKey
	Static *ecdh.PrivateKey
}

Keys are Settings' keys, parsed.

func (*Keys) HostID

func (k *Keys) HostID() string

HostID is this machine's name on a relay.

func (*Keys) StaticPublic

func (k *Keys) StaticPublic() string

StaticPublic is the key a phone pins, base64url.

type Options

type Options struct {
	Relay string // wss://… the relay to wait at
	Keys  *Keys
	// Local is this daemon's loopback base URL, http://127.0.0.1:<port>.
	Local   string
	Version string
	Name    string // what the phone calls this machine
	Log     *slog.Logger
	// Client is the HTTP client requests are replayed with. nil means one
	// with no timeout (a long-poll or a large download is the caller's to
	// cancel) and no proxy: loopback is never proxied.
	Client *http.Client
}

Options configure a Host.

type Session

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

Session is an established channel: Encrypt for what this side sends, Decrypt for what it receives. Not safe for concurrent use in either direction; the caller orders its own sends.

func Respond

func Respond(static *ecdh.PrivateKey, msg1, replyPayload []byte, e *ecdh.PrivateKey) (reply, payload []byte, sess *Session, err error)

Respond runs the responder's half of NK: it reads the phone's first message (-> e, es), and returns the reply (<- e, ee) carrying replyPayload, the payload the phone sent, and the established session.

e is the ephemeral key; nil makes a fresh one, which is every real use. Tests pass a fixed one to pin the bytes against the TypeScript side.

func (*Session) Decrypt

func (s *Session) Decrypt(ciphertext []byte) ([]byte, error)

Decrypt opens one transport message. A failure means the stream is not ours, or was altered, and the connection should be dropped.

func (*Session) Encrypt

func (s *Session) Encrypt(plaintext []byte) ([]byte, error)

Encrypt seals one transport message.

type Settings

type Settings struct {
	Enabled bool   `json:"enabled"`
	Relay   string `json:"relay,omitempty"`
	App     string `json:"app,omitempty"`
	// Sign is the Ed25519 seed the machine proves its id to a relay with.
	Sign []byte `json:"sign"`
	// Static is the X25519 private key phones run the Noise handshake against.
	Static []byte `json:"static"`
}

Settings is what remote access remembers.

Unlike LAN access, the decision to be on survives a restart (ADR-058): the machine this is for is a Mac mini in a cupboard, and a switch that resets whenever it reboots is a switch that is off when you are out with the dog. It cannot be turned on from a phone — only on the machine, or by a command run on it.

func Load

func Load(dir string) (*Settings, error)

Load reads the settings, making keys on first use. A machine has one identity for its life: replacing the keys unpairs every phone, which is what `caprock remote reset` is for and nothing else does.

func (*Settings) AppURL

func (s *Settings) AppURL() string

AppURL is the phone's page in force.

func (*Settings) Keys

func (s *Settings) Keys() (*Keys, error)

Keys parses the stored keys.

func (*Settings) RelayURL

func (s *Settings) RelayURL() string

RelayURL is the relay in force.

type State

type State struct {
	// Status is "off", "connecting", "online" or "offline".
	Status string `json:"status"`
	// Error says why the last attempt failed, when it did.
	Error string `json:"error,omitempty"`
	// Phones is how many phones are connected through the relay now.
	Phones int `json:"phones"`
	// Since is when Status last changed.
	Since time.Time `json:"since"`
}

State is where the connection to the relay stands, for the pairing panel.

type Welcome

type Welcome struct {
	V       int    `json:"v"`
	Version string `json:"version"`
	Name    string `json:"name"`
}

Welcome is the daemon's.

Directories

Path Synopsis
Package relaysrv is a relay a phone and a daemon meet at (ADR-058).
Package relaysrv is a relay a phone and a daemon meet at (ADR-058).

Jump to

Keyboard shortcuts

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