devicelogin

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package devicelogin keeps the devices paired with the remote API and the pending pairing code. The CLI (pair, revoke) and the server (pairing, last seen) are separate processes sharing these files, so every write takes an exclusive flock, re-reads, changes and renames a temp file over the old one.

Index

Constants

View Source
const (
	ActionPair            = "pair"
	ActionPairFailed      = "pair_failed"
	ActionLogin           = "login"
	ActionLoginFailed     = "login_failed"
	ActionLogout          = "logout"
	ActionRevoke          = "revoke"
	ActionSend            = "send"
	ActionNewSession      = "new_session"
	ActionCancel          = "cancel"
	ActionApprove         = "approve"
	ActionTerminalMessage = "terminal_message"
	ActionTerminalKey     = "terminal_key"
	// A terminal message with now (the composer's Send now).
	ActionTerminalSendNow = "terminal_send_now"
	// The chat queue's dispatcher: an item sent, a queue paused. Result is
	// a code, never the text or the reason line.
	ActionQueueSend   = "queue_send"
	ActionQueuePaused = "queue_paused"
	// The owner's changes to a queue through the API.
	ActionQueueAdd    = "queue_add"
	ActionQueueEdit   = "queue_edit"
	ActionQueueMove   = "queue_move"
	ActionQueueDelete = "queue_delete"
	ActionQueueResume = "queue_resume"
	// Send now: a queued message sent at once, mid-turn.
	ActionQueueSendNow = "queue_send_now"
	// Session titles, descriptions and pins.
	ActionDescribe = "describe"
	ActionMetaEdit = "meta_edit"
	ActionPin      = "pin"
	ActionUnpin    = "unpin"
	// ActionOpenOnMac: a session handed from the phone to an iTerm2 tab.
	ActionOpenOnMac = "open_on_mac"
)

Audited actions: one line each for every action that changes something.

View Source
const (
	IdleLimit     = time.Hour
	AbsoluteLimit = 12 * time.Hour
)

Login limits: a session ends after IdleLimit without use and in any case AbsoluteLimit after it began.

View Source
const (
	KindSecureEnclave = "secure-enclave"
	KindWebAuthn      = "webauthn"
)

Device kinds: an iPhone app's Secure Enclave key, or a web passkey.

View Source
const InteractionHeader = "Aimux-Interaction"

InteractionHeader marks a request as something the person did (opening a chat, pull to refresh): it moves the idle clock like a POST does.

Variables

View Source
var (
	ErrBadKey          = errors.New("public key is not an ECDSA P-256 key in SPKI DER")
	ErrBadSignature    = errors.New("signature does not verify")
	ErrClientData      = errors.New("clientDataJSON is not a JSON object")
	ErrWrongType       = errors.New("clientDataJSON type is not the expected ceremony")
	ErrWrongChallenge  = errors.New("clientDataJSON challenge does not match")
	ErrWrongOrigin     = errors.New("clientDataJSON origin does not match")
	ErrCrossOrigin     = errors.New("clientDataJSON says crossOrigin")
	ErrAuthData        = errors.New("authenticatorData is malformed")
	ErrWrongRPID       = errors.New("authenticatorData rpIdHash does not match")
	ErrUserNotPresent  = errors.New("authenticatorData lacks the user-present flag")
	ErrUserNotVerified = errors.New("authenticatorData lacks the user-verified flag")
)

Why a signature check failed. Each is a fixed string so callers can audit the reason; none ever carries a challenge, signature, key or client data.

View Source
var ErrNoDevice = errors.New("no paired device by that name")

ErrNoDevice is returned by Remove for a name nobody paired.

Functions

func CanonicalCode

func CanonicalCode(s string) (string, error)

CanonicalCode returns a typed code in the form that is hashed and that the iPhone signs: the 8 characters, uppercase, no dash. It takes the code with or without its dash, in either case, with surrounding spaces, and reads I and L as 1 and O as 0.

func LoginMessage

func LoginMessage(host, challenge string) []byte

LoginMessage is what the iPhone signs to log in: host is the host name without port, challenge the base64url string the server issued.

func NewCode

func NewCode() (display string, hash [32]byte)

NewCode returns a random pairing code for display (XXXX-XXXX, 40 bits) and the SHA-256 of its canonical form (the 8 characters, no dash), which is all that is ever stored.

func PairMessage

func PairMessage(host, code string) []byte

PairMessage is what the iPhone signs to pair: host is the host name without port, code the 8 canonical characters without the dash.

func ParseCode

func ParseCode(s string) ([32]byte, error)

ParseCode turns a typed code into the hash NewCode gave for it: the SHA-256 of CanonicalCode's form.

func ParseP256

func ParseP256(spkiDER []byte) (*ecdsa.PublicKey, error)

ParseP256 parses an SPKI DER public key and refuses anything but P-256.

func VerifyEnclave

func VerifyEnclave(publicKeyDER, message, sigDER []byte) error

VerifyEnclave checks an ECDSA P-256 SHA-256 signature (ASN.1 DER) by the SPKI DER key over message, as made by the iPhone's Secure Enclave key.

func VerifyWebAuthnCreate

func VerifyWebAuthnCreate(origin, rpID string, wantChallenge []byte, clientDataJSON, authenticatorData []byte) error

VerifyWebAuthnCreate checks the clientDataJSON and authenticatorData of a passkey creation (attestation none, so there is no signature): type webauthn.create, the challenge, origin, rpIdHash, UP, UV and attested credential data present. The public key itself comes from the browser's getPublicKey() and is checked with ParseP256. Nothing here is signed (attestation none), so a caller could forge all of it: the pairing challenge, the hash of a code only the owner saw, is the gate.

func VerifyWebAuthnGet

func VerifyWebAuthnGet(origin, rpID string, wantChallenge []byte, pub *ecdsa.PublicKey, clientDataJSON, authenticatorData, sigDER []byte) error

VerifyWebAuthnGet checks a passkey assertion: clientDataJSON (type webauthn.get, challenge, origin), authenticatorData (rpIdHash, UP, UV) and the signature over authenticatorData || SHA-256(clientDataJSON). The sign counter is ignored (synced passkeys report 0).

Types

type Audit

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

Audit writes AuditEntry values as JSON lines. A nil *Audit writes nothing.

func NewAudit

func NewAudit(w io.Writer, now func() time.Time, errs io.Writer) *Audit

NewAudit writes to w (the 0600 ~/.aimux/logs/remote-audit.log), stamping lines with now, and reports write failures to errs.

func (*Audit) Write

func (a *Audit) Write(e AuditEntry)

Write appends e, setting its time. A failure identical to one written less than a minute ago is counted instead, and the count goes on the next such line.

type AuditEntry

type AuditEntry struct {
	Time    time.Time `json:"time"`
	Login   string    `json:"login"`
	Device  string    `json:"device"`
	Action  string    `json:"action"`
	Session string    `json:"session,omitempty"`
	Result  string    `json:"result"`
	// Count, on a failure line, is how many identical failures it stands
	// for: those left out in the minute since the last such line, plus this.
	Count int `json:"count,omitempty"`
}

AuditEntry is one audit line. Device is the device's name; Session is the aimux session acted on, never a login token. No field ever holds message text, a code, a challenge, a token or a key.

type Device

type Device struct {
	ID           string    `json:"id"`
	Name         string    `json:"name"`
	Kind         string    `json:"kind"`
	PublicKey    string    `json:"publicKey"`
	CredentialID string    `json:"credentialId,omitempty"`
	Login        string    `json:"login"`
	Created      time.Time `json:"created"`
}

Device is a paired device. PublicKey is base64 SPKI DER; CredentialID is set for web passkeys; Login is the Tailscale login that paired it.

type Options

type Options struct {
	Store *Store
	Audit *Audit // may be nil
	// Login returns the caller's Tailscale login, already checked by the
	// outer tailnet middleware.
	Login func(*http.Request) string
	Now   func() time.Time // nil: time.Now
	Log   io.Writer        // device file errors; may be nil
}

Options are a Server's dependencies.

type Server

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

Server is device login for the remote API: the /v1/auth endpoints and the middleware that requires a live session on every other route.

func NewServer

func NewServer(o Options) (*Server, error)

NewServer reads the paired devices and returns a Server with no sessions.

func (*Server) Audit

func (s *Server) Audit() *Audit

Audit is the server's audit log, for lines written outside a request (the chat queue's sends and pauses). Nil for a nil server.

func (*Server) Middleware

func (s *Server) Middleware(next http.Handler) http.Handler

Middleware admits a request to next only on an open route or with a live session of a still-paired device for the caller's Tailscale login; else 401 login_required.

func (*Server) Record

func (s *Server) Record(r *http.Request, action, session, result string)

Record writes an audit line for an action on a request the middleware admitted; session is the aimux session acted on, if any.

func (*Server) Register

func (s *Server) Register(mux *http.ServeMux)

Register adds the /v1/auth endpoints to mux.

func (*Server) SessionState

func (s *Server) SessionState(r *http.Request) string

SessionState is "live" when the request carries a live session of a still-paired device for its Tailscale login, else "none". It never counts as use and names no device, so health can tell a lost login from a lost network.

func (*Server) Tick

func (s *Server) Tick()

Tick notices revoked devices, ends sessions past their limits and drops expired challenges.

func (*Server) Watch

func (s *Server) Watch(ctx context.Context)

Watch runs Tick every second until ctx ends, so streams end within a second or two of a revoke or a session passing its limit.

type Session

type Session struct {
	DeviceID string
	Login    string // the Tailscale login it is valid for
	Created  time.Time
	LastUsed time.Time
	// contains filtered or unexported fields
}

Session is a live login of one paired device.

func SessionFrom

func SessionFrom(ctx context.Context) (Session, bool)

SessionFrom returns the session the middleware admitted the request with.

func (Session) Done

func (s Session) Done() <-chan struct{}

Done is closed when the session ends (logout, revoke, idle or absolute limit), so an open event stream can end with it.

type Sessions

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

Sessions is the registry of live sessions, in memory only: a server restart ends every one. Tokens are kept only as their SHA-256.

func NewSessions

func NewSessions(now func() time.Time) *Sessions

NewSessions returns an empty registry reading the time from now.

func (*Sessions) Check

func (s *Sessions) Check(token, login string, interaction bool) (Session, bool)

Check returns the live session for token if it belongs to login. A session past a limit ends here. interaction (something the person did) moves the idle clock; polls and streams do not.

func (*Sessions) Create

func (s *Sessions) Create(deviceID, login string) string

Create starts a session for deviceID, valid only with login, and returns its token (32 random bytes, base64url).

func (*Sessions) Done

func (s *Sessions) Done(token string) <-chan struct{}

Done returns the channel closed when token's session ends; for a token with no session it is already closed.

func (*Sessions) End

func (s *Sessions) End(token string)

End ends the session for token, if any.

func (*Sessions) EndDevice

func (s *Sessions) EndDevice(deviceID string) int

EndDevice ends every session of deviceID and returns how many there were.

func (*Sessions) Sweep

func (s *Sessions) Sweep()

Sweep ends the sessions past a limit, closing their Done channels.

type Store

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

Store is the device files in one directory. It is safe for concurrent use, also by several Stores and processes on the same directory.

func Open

func Open(dir string) *Store

Open returns the store kept in dir; nothing is read or created until used.

func (*Store) Add

func (s *Store) Add(d Device) error

Add records a newly paired device. Its name (1-32 characters, no control characters) must be unused, ignoring case, and so must its id.

func (*Store) Changed

func (s *Store) Changed() bool

Changed reports whether the devices file was written since Changed last looked (or since Open). It looks at most once a second; calls in between report false.

func (*Store) Devices

func (s *Store) Devices() ([]Device, error)

Devices returns the paired devices in the order they were paired. Writes rename a whole file into place, so reading needs no lock.

func (*Store) LastSeen

func (s *Store) LastSeen() map[string]time.Time

LastSeen returns when each device id was last used; an unreadable file reads as empty, since it is display only.

func (*Store) Recheck

func (s *Store) Recheck()

Recheck makes the next Changed (a second later at most) report a change, so a read that failed is tried again although the file did not change.

func (*Store) Remove

func (s *Store) Remove(name string) (Device, error)

Remove unpairs the device with this name and returns it.

func (*Store) Seen

func (s *Store) Seen(id string, t time.Time)

Seen records that device id was used at t. Write errors are ignored on purpose: last seen is shown by `aimux remote devices` and decides nothing.

func (*Store) SetPending

func (s *Store) SetPending(name string, codeHash [32]byte, expires time.Time) error

SetPending makes codeHash the one pairing code, for a device to be called name, until expires. It replaces any earlier code and refuses a name that is invalid or already paired (ignoring case).

func (*Store) TakePending

func (s *Store) TakePending(codeHash [32]byte, now time.Time) (name string, ok bool, err error)

TakePending uses up the pairing code if codeHash is it and it has not expired at now, returning the name it was made for. A wrong code counts against it, and the 5th wrong code in a row deletes it, as does expiry.

Jump to

Keyboard shortcuts

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