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
- Variables
- func CheckAppURL(raw string) error
- func CheckRelayURL(raw string) error
- func Frame(kind byte, conn uint32, data []byte) []byte
- func HostID(pub ed25519.PublicKey) string
- func PairLink(s *Settings, k *Keys, code, name string) string
- func ParseFrame(b []byte) (kind byte, conn uint32, data []byte, err error)
- func ParseHostID(id string) (ed25519.PublicKey, error)
- func ProofMessage(hostID string, nonce []byte) []byte
- func Reset(dir string) error
- func Save(dir string, s *Settings) error
- func VerifyProof(hostID string, nonce, sig []byte) bool
- type Client
- type ClientOptions
- type ClientState
- type Hello
- type Host
- type Initiator
- type Keys
- type Options
- type PairInfo
- type Session
- type Settings
- type State
- type Target
- type WSConn
- type Welcome
Constants ¶
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.
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.
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.
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 ¶
var ( // ErrMachineOffline means the relay holds no live connection from the // machine: asleep, off the internet, Caprock not running, or access from // anywhere switched off there. ErrMachineOffline = errors.New("the computer is offline") // ErrRelayUnreachable means the relay itself could not be reached, or // the connection to it dropped. ErrRelayUnreachable = errors.New("could not reach the relay") // ErrRefused means the machine hung up on the handshake: its key is not // the one the pairing link pinned (it was reset, or it is another // machine). ErrRefused = errors.New("the computer refused the connection") // ErrClientClosed is a Client after Close. ErrClientClosed = errors.New("the connection to this computer was closed") )
Errors a caller tells apart. Each is wrapped with the detail.
var ( // ClientAttempt bounds one attempt, from dialling the relay to the // machine's handshake reply. The phone's ATTEMPT_MS. ClientAttempt = 10 * time.Second // ClientIdle is how long a channel with no open stream stays up. ClientIdle = 90 * time.Second )
Client timings. Variables so tests can shorten them.
Functions ¶
func CheckAppURL ¶
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 ¶
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 HostID ¶
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 ¶
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 ¶
ParseFrame splits a relay↔daemon frame.
func ParseHostID ¶
ParseHostID is HostID's inverse, refusing anything that is not a key.
func ProofMessage ¶
ProofMessage is what a daemon signs to answer a relay's challenge.
func Reset ¶
Reset forgets the keys, so the next Load makes new ones and every phone paired over the relay has to pair again.
func VerifyProof ¶
VerifyProof checks a daemon's answer to nonce.
Types ¶
type Client ¶ added in v0.121.0
type Client struct {
// contains filtered or unexported fields
}
Client is a channel, opened on demand, to one machine.
func NewClient ¶ added in v0.121.0
func NewClient(opt ClientOptions) (*Client, error)
NewClient makes a client for t; nothing is dialled until it is used.
func (*Client) Close ¶ added in v0.121.0
func (c *Client) Close()
Close hangs up and refuses further use.
func (*Client) OpenWS ¶ added in v0.121.0
OpenWS opens a WebSocket at path (with its query) on the machine, offering protocols. It returns once the machine's socket is open, or the close the machine answered with (4000 plus the HTTP status for a refused upgrade, so 4401 is "not paired"), as a websocket.CloseError.
func (*Client) Retry ¶ added in v0.121.0
func (c *Client) Retry()
Retry forgets the backoff after a failure: the next request dials at once.
func (*Client) RoundTrip ¶ added in v0.121.0
RoundTrip carries one HTTP request to the machine's own API and returns its answer, streamed: the body arrives as the machine sends it. It implements http.RoundTripper, so a ReverseProxy can stand on it.
Only the request's path and query travel; the scheme and host are ignored. The machine passes on only the headers a phone may set (proto.go), so a caller's cookies or Origin never reach it.
func (*Client) Serial ¶ added in v0.121.0
Serial counts the channel's openings: two answers with different serials came on separate connections.
func (*Client) State ¶ added in v0.121.0
func (c *Client) State() ClientState
State reports the channel's state.
type ClientOptions ¶ added in v0.121.0
type ClientOptions struct {
Target
Log *slog.Logger
// HTTPClient dials the relay; nil is the default client.
HTTPClient *http.Client
// Idle overrides ClientIdle; zero keeps it.
Idle time.Duration
}
ClientOptions configure a Client.
type ClientState ¶ added in v0.121.0
type ClientState struct {
// Status is "idle" (not connected, nothing wrong), "connecting",
// "online", "offline" (the machine or the relay cannot be reached),
// "refused" (the handshake was refused: the key does not match) or
// "closed".
Status string `json:"status"`
Error string `json:"error,omitempty"`
Since time.Time `json:"since"`
// Version and Name are what the machine said in its last Welcome.
Version string `json:"version,omitempty"`
Name string `json:"name,omitempty"`
// Streams is how many requests and sockets are open on the channel.
Streams int `json:"streams"`
// Counters since the Client was made: relay messages and their bytes,
// each way, so what a computer costs the relay is measured (OQ-14).
MsgsOut uint64 `json:"msgs_out"`
MsgsIn uint64 `json:"msgs_in"`
BytesOut uint64 `json:"bytes_out"`
BytesIn uint64 `json:"bytes_in"`
}
ClientState is where the channel to one machine stands.
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.
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.
type Keys ¶
type Keys struct {
Sign ed25519.PrivateKey
Static *ecdh.PrivateKey
}
Keys are Settings' keys, parsed.
func (*Keys) StaticPublic ¶
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 PairInfo ¶ added in v0.121.0
type PairInfo struct {
Target
Code string // the six-digit code, when the link carries one
Name string // what the machine calls itself, when it says
}
PairInfo is a parsed pairing link.
func ParsePairLink ¶ added in v0.121.0
ParsePairLink reads what PairLink writes: the phone's page with the relay, host id, key, code and name after "#/pair?". It also takes the part after the "?" alone, so a link pasted from a terminal that wrapped it, or typed from `caprock pair`, works. Everything is checked: a relay that is not wss:// (ws:// only to this machine), an id that is not a key, a key that is not 32 bytes.
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.
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.
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"`
// Relay messages and their bytes each way since the daemon started, so
// what phones and computers cost the relay is measured, not guessed
// (OQ-14, ADR-067).
MsgsIn uint64 `json:"msgs_in"`
MsgsOut uint64 `json:"msgs_out"`
BytesIn uint64 `json:"bytes_in"`
BytesOut uint64 `json:"bytes_out"`
}
State is where the connection to the relay stands, for the pairing panel.
type Target ¶ added in v0.121.0
type Target struct {
Relay string // wss://… the relay the machine waits at
HostID string // its Ed25519 public key, base64url (HostID)
Key string // its X25519 static key, base64url, pinned by the handshake
}
Target is the machine a Client reaches: what a pairing link carries, less the code.
type WSConn ¶ added in v0.121.0
type WSConn struct {
// contains filtered or unexported fields
}
WSConn is a WebSocket on the machine's API, carried over the channel.
func (*WSConn) Close ¶ added in v0.121.0
func (w *WSConn) Close(code websocket.StatusCode, reason string) error
Close closes the socket on the machine with code and reason.
func (*WSConn) Read ¶ added in v0.121.0
Read returns the next whole message. A close from the machine is a websocket.CloseError with its code (1008 when the role was taken away mid-session); the channel dropping is 1006.
func (*WSConn) Subprotocol ¶ added in v0.121.0
Subprotocol is the protocol the machine's socket chose.