pairing

package
v0.178.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 8 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 pairing lets a second device — a tablet, a phone — reach a daemon that is otherwise bound to loopback.

It is the store behind LAN access (ADR-029): `caprock up --lan` or the Settings screen's Connect a phone opens a second listener, internal/api's gate checks every request from the network against the tokens kept here, and the status screen issues codes and lists devices. It was built and tested before that feature, because it is the part that decides who gets in.

A token makes a device a reader, not the owner — unless the owner, at the machine, gives that one device the controller role (ADR-034): afterwards, or when showing the code, by leaving *This phone can type and start agents* ticked (the code then carries the role, NewCodeAs). What each role may do is decided in internal/api (pairedDeviceRoutes, controllerRoutes), not here: this package answers "which device is this, and which role did the owner give it", never "what may it do".

The rule that shapes everything here is rule 4: all data stays on the machine. Nothing in this package reaches the network, registers a name, or opens a tunnel. What it does is narrower: when the user explicitly turns it on, the daemon also listens on the machine's LAN address, and a device on that same network can connect after proving it knows a code the user read off their own screen.

That is a real reduction in safety and it is stated plainly rather than smoothed over. Bound to loopback, nothing outside the machine can connect at all. Bound to the LAN, everything on that network can *try* — the guest on the home wifi, the stranger in the coworking space. So:

  • It is off until switched on, never a default, never remembered across a daemon that was started without it.
  • A device proves itself once with a short code the user reads aloud or scans, and is issued a long random token it keeps.
  • Codes are single-use and expire in minutes. A device token does not.
  • Every paired device is listed, with when it was last seen, and can be revoked one by one.

Codes are short because a person has to type them on a tablet. Short means guessable, so the code is useless after one use or five minutes, whichever comes first, and repeated wrong guesses burn it. The device token that replaces it is full length.

Index

Constants

View Source
const (
	// RoleViewer reads figures and nothing else (ADR-029).
	RoleViewer = "viewer"
	// RoleController may also start sessions in known projects, type into the
	// sessions Caprock started, stop them, and answer task approvals.
	RoleController = "controller"
)

The roles a paired device can hold (ADR-034).

A device is paired as a viewer and stays one until the owner, on the machine Caprock runs on, makes it a controller. An empty Role is a viewer: every devices.json written before roles existed reads as "viewer", which is what those devices were.

View Source
const (
	// ViaLAN is the network listener, from an ordinary private address: the
	// same Wi-Fi only.
	ViaLAN = "lan"
	// ViaTailscale is the network listener, from a Tailscale address: anywhere
	// Tailscale is on.
	ViaTailscale = "tailscale"
	// ViaRelay is access from anywhere through the relay (ADR-058).
	ViaRelay = "relay"
)

How a device last reached the machine. Recorded by internal/api's gate on every request, so the owner's list can say which phones work off the home Wi-Fi and which do not (owner, 2026-10-14: his phone was paired on the Wi-Fi address minutes before he turned on access from anywhere, kept that link, and nothing told him why it went dead on mobile data). Empty means not seen since this was recorded.

View Source
const (
	// KindPhone is a phone, a tablet or a browser: ADR-034's limits.
	KindPhone = ""
	// KindMachine is another computer's Caprock: full controller scope, but
	// only after the owner allows it by name on this machine (Pending).
	KindMachine = "machine"
)

The kinds of paired device (ADR-067). A phone or a tablet is the default and is stored without a kind; a computer — another Caprock daemon that reaches this one through the relay — is KindMachine. The kind is the owner's choice when showing the code (NewCodeFor), never the redeeming device's: a device cannot call itself a computer to get a computer's rights, exactly as it cannot name its own role.

View Source
const CodeTTL = 5 * time.Minute

CodeTTL is how long a pairing code stays usable. Long enough to walk to the other device, short enough that a code left on screen is not a standing invitation.

View Source
const MaxAttempts = 5

MaxAttempts is how many wrong guesses a code survives. A six-digit code has a million values, and this makes brute force pointless while leaving room for a person mistyping twice.

Variables

View Source
var (
	// ErrNoCode means no code is outstanding: either none was issued, or the
	// last one was used or expired.
	ErrNoCode = errors.New("no pairing code is active")
	// ErrBadCode means the code did not match. The caller must not say
	// whether the code was wrong or expired — that is one bit an attacker
	// would otherwise get for free.
	ErrBadCode = errors.New("that code is not valid")
	// ErrUnknownDevice means the token does not belong to a paired device,
	// which is also what a revoked device gets.
	ErrUnknownDevice = errors.New("this device is not paired")
)

Errors callers distinguish. Everything else is a bug.

Functions

func ValidRole added in v0.71.0

func ValidRole(r string) bool

ValidRole reports whether r names a role a device may be given.

Types

type Device

type Device struct {
	// ID identifies the device in the UI and for revocation. Not a secret.
	ID string `json:"id"`
	// Name is what the user sees: taken from the browser, so "iPad" or
	// "Android tablet" rather than anything the device asserts about itself.
	Name string `json:"name"`
	// Token is what the device presents on every request. Never sent to the
	// UI after the moment of pairing.
	Token string `json:"token"`
	// PairedAt and LastSeen are unix milliseconds.
	PairedAt int64 `json:"paired_at"`
	LastSeen int64 `json:"last_seen"`
	// Role is RoleViewer or RoleController; empty reads as a viewer. Set only
	// by the owner on loopback, never by the device: by SetRole, or by the
	// code the owner issued (NewCodeAs), which carries the role it pairs as.
	Role string `json:"role,omitempty"`
	// Via is how the device last reached the machine: ViaLAN, ViaTailscale,
	// ViaRelay, or empty when not seen since it was first recorded.
	Via string `json:"via,omitempty"`
	// App says the device last reported running as the installed app
	// (display-mode standalone, or Chrome's record that it is installed).
	// A label for the owner's checklist, never an authorisation.
	App bool `json:"app,omitempty"`
	// Kind is KindPhone (empty) or KindMachine, from the code it redeemed.
	Kind string `json:"kind,omitempty"`
	// Pending is a computer that redeemed a code and waits for the owner to
	// allow it by name (ADR-067). Until then its token reaches nothing but
	// GET /v1/pair/me, and it holds no role (roleOf reads it as a viewer).
	Pending bool `json:"pending,omitempty"`
	// Key is the relay key (remote.HostID) a computer's token is bound to:
	// the key its channel proved on the first request that carried a proof
	// (ADR-067, Phase 4). Set once, by HoldKey; from then the token works on
	// no channel that proved another key or none. Empty for a phone, and for
	// a computer whose Caprock predates the proof.
	Key string `json:"key,omitempty"`
}

Device is one thing that has been let in.

type Public

type Public struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	PairedAt int64  `json:"paired_at"`
	LastSeen int64  `json:"last_seen"`
	// Role is always set here: "viewer" or "controller".
	Role string `json:"role"`
	// Via is how it last reached the machine; see Device.Via.
	Via string `json:"via,omitempty"`
	// App is Device.App.
	App bool `json:"app,omitempty"`
	// Kind is Device.Kind: "machine" for a computer, absent for a phone.
	Kind string `json:"kind,omitempty"`
	// Pending is Device.Pending.
	Pending bool `json:"pending,omitempty"`
	// Bound says a computer's token is held to its own key (Device.Key).
	Bound bool `json:"bound,omitempty"`
}

Public is a Device without its token, for listing in the dashboard.

type Store

type Store struct {
	// Now is injectable so expiry is testable without sleeping.
	Now func() time.Time
	// contains filtered or unexported fields
}

Store holds the pairing state. The zero value is not usable; call New.

func New

func New() *Store

New returns an empty Store with no code and no devices.

func (*Store) Allow added in v0.122.0

func (s *Store) Allow(id string) bool

Allow lets a pending computer in, by id: the owner's Allow on this machine (ADR-067) — the button, the prompt of `caprock pair --computer`, or `caprock machines allow` over SSH. It reports false when there is no such device or it is not waiting.

func (*Store) Check

func (s *Store) Check(token string) (*Device, error)

Check validates a device token and records that the device was seen.

It returns a copy: the role can change under a request in flight (the owner revokes control while the phone is typing), and a pointer into the store would be read without the lock. A caller that needs the role *now* — a terminal socket that stays open for an hour — asks again.

func (*Store) CheckVia added in v0.117.0

func (s *Store) CheckVia(token, via string) (dev *Device, changed bool, err error)

CheckVia is Check that also records how the device reached the machine (ViaLAN, ViaTailscale, ViaRelay). An empty via records nothing: a request whose route cannot be told apart keeps what was known. changed reports that the recorded route is new, so the caller can save the guest list — which it does not do for LastSeen, as that changes on every request.

func (*Store) ClearCode

func (s *Store) ClearCode()

ClearCode withdraws the outstanding code, if any.

func (*Store) Code added in v0.49.0

func (s *Store) Code() string

Code returns the outstanding code, or "" when there is none or it has expired.

For showing the owner what to type into the other device — which is the only way pairing works — and for nothing else. It is never sent to anything but a loopback request, and never used to decide access: Redeem is what checks a code, in constant time, with the attempt counter behind it.

func (*Store) CodeActive

func (s *Store) CodeActive() (bool, time.Duration)

CodeActive reports whether a code is outstanding and still valid, and how long it has left. For showing a countdown, never for deciding access.

func (*Store) CodeKind added in v0.122.0

func (s *Store) CodeKind() string

CodeKind is the kind the outstanding code pairs as — KindMachine for a computer, KindPhone (empty) otherwise and when there is no live code.

func (*Store) CodeRole added in v0.117.1

func (s *Store) CodeRole() string

CodeRole is the role the outstanding code pairs as, or "" when there is no live code.

func (*Store) Devices

func (s *Store) Devices() []Public

Devices lists what is paired, without tokens, oldest first.

func (*Store) HoldKey added in v0.175.0

func (s *Store) HoldKey(token, key string) (ok, bound bool)

HoldKey holds the token of a computer to the key its channel proved (key, "" for none): the first key it is seen with binds it, and from then only that key is ok. bound reports a new binding, so the caller saves the guest list. A token never bound and seen with no key is ok: a computer from before the proof, which this cannot tell from anything else.

func (*Store) Load

func (s *Store) Load(ds []Device)

Load restores devices from disk at start-up. Codes are deliberately not persisted: an outstanding code must not survive a restart.

func (*Store) NewCode

func (s *Store) NewCode() (string, error)

NewCode issues a fresh six-digit code, replacing any outstanding one.

Replacing rather than refusing: a user who cannot find the code they were shown will press the button again, and the sensible reading of that is "the old one no longer counts", not "you already have one somewhere".

func (*Store) NewCodeAs added in v0.117.1

func (s *Store) NewCodeAs(role string) (string, error)

NewCodeAs issues a code that pairs a device with role: the owner's choice at the machine, made before the phone exists (ADR-034, amended 2026-10-14). The person showing the code is the person at the machine, so the decision is still theirs and still made there; the phone only carries it out by redeeming. An invalid role is a viewer.

func (*Store) NewCodeFor added in v0.122.0

func (s *Store) NewCodeFor(role, kind string) (string, error)

NewCodeFor issues a code that pairs a device of kind with role. A code for KindMachine pairs a computer (ADR-067): always as a controller, and pending until the owner allows it by name (Allow). An unknown kind is a phone.

func (*Store) Redeem

func (s *Store) Redeem(code, name string) (*Device, error)

Redeem exchanges a pairing code for a device token.

The comparison is constant-time. Six digits is small enough that timing a character-by-character compare is not far-fetched, and the cost of doing it properly is nothing.

func (*Store) Revoke

func (s *Store) Revoke(id string) bool

Revoke removes one device by id. Its token stops working immediately.

func (*Store) RevokeAll

func (s *Store) RevokeAll() int

RevokeAll unpairs everything. What the user reaches for when they no longer trust the network they are on.

func (*Store) RoleOf added in v0.71.0

func (s *Store) RoleOf(token string) string

RoleOf is the current role of the device holding token, or "" when the token is unknown or revoked. It does not touch LastSeen: it is asked once per keystroke on an open terminal, which is not the device being seen again.

func (*Store) SetApp added in v0.117.1

func (s *Store) SetApp(token string, on bool) (changed bool)

SetApp records whether the device holding token runs as the installed app. changed reports a new value, so the caller can save the guest list.

func (*Store) SetRole added in v0.71.0

func (s *Store) SetRole(id, role string) bool

SetRole gives one device, by id, a role. It reports false when there is no such device or the role is not one ValidRole accepts. Takes effect on that device's next request, and on its next keystroke into an open terminal.

func (*Store) Snapshot

func (s *Store) Snapshot() []Device

Snapshot returns every device, tokens included, for persisting.

Jump to

Keyboard shortcuts

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