Documentation
¶
Overview ¶
Package relay drives the binary's outbound long-lived connection to the relay: opens the WSS via internal/transport, runs the one-shot hello/hello_ack handshake on every fresh conn, and exposes inbound frames as protocol.RoutingEnvelope values via Frames(). It does NOT dispatch on envelope types, validate device tokens, or interpret application-level error payloads — those concerns layer above this package in a future ticket (supervisor wiring + per-message handlers).
The single source of truth for the headers, handshake timing, and close codes is docs/protocol-mobile.md (§ Authentication, § Connection lifecycle, § Worked example). When that document changes, this package changes.
Index ¶
Constants ¶
const MsgInvalidToken = "device token not recognised; re-pair via pyry pair on the binary"
MsgInvalidToken is the fixed user-facing message emitted in the auth.invalid_token error payload (docs/protocol-mobile.md § Error codes). Defined as an exported const so future integration tests can pin it without re-typing the spec sentence.
StatusUnauthorized is the WS close code the relay sends when the binary rejects a phone's device token (docs/protocol-mobile.md § Error codes, close-code row 4401). Typed locally so callers don't import the websocket package for the value; parallel to statusServerIDConflict in connection.go.
Variables ¶
var ( // ErrServerIDConflict is the terminal error returned by Wait when // the relay refused our claim with WS close 4409. Another binary is // currently holding the same server-id and the relay's 30-second // grace window has not elapsed. Operator escalation: another pyry is // already running for this server-id, or a stale connection on the // relay side has not yet been reaped. ErrServerIDConflict = errors.New("relay: server-id conflict (close 4409)") // ErrInvalidConfig is returned by Connect on missing required fields. ErrInvalidConfig = errors.New("relay: invalid config") )
Sentinel errors. Callers distinguish fatal vs. retryable via errors.Is.
var ErrMalformedHelloFrame = errors.New("relay: malformed hello frame")
ErrMalformedHelloFrame is returned by AuthenticateFirstFrame when the inner envelope inside env.Frame cannot be JSON-decoded. The relay-conn caller maps this to its existing protocol.malformed handling; this package does not synthesize an error envelope for it (the malformed- frame response shape is owned by a sibling ticket).
Functions ¶
This section is empty.
Types ¶
type AuthOutcome ¶
type AuthOutcome struct {
Response protocol.RoutingEnvelope
CloseConn bool
// Device is the matched *devices.Device snapshot on the accept path.
// Nil on reject and on the ErrMalformedHelloFrame early return. The
// dispatcher carries this forward into the per-conn Auth slot so
// downstream verb handlers can read the authenticated device without
// re-validating the token (see #318 / docs/protocol-mobile.md §
// Authentication).
Device *devices.Device
}
AuthOutcome is the structured result of AuthenticateFirstFrame. The relay-conn caller forwards Response back through the binary→relay leg and, when CloseConn is true, asks the relay to close the phone WS with StatusUnauthorized after the Response has been written.
CloseConn carries the protocol-level intent (close-because-auth-failed) rather than the wire code itself; the close code is fixed at 4401 by spec and lives on the StatusUnauthorized constant.
func AuthenticateFirstFrame ¶
func AuthenticateFirstFrame( env protocol.RoutingEnvelope, token string, reg *devices.Registry, serverID string, logger *slog.Logger, ) (AuthOutcome, error)
AuthenticateFirstFrame is the per-connection token-validation predicate for the phone→relay→binary auth phase (docs/protocol-mobile.md § Authentication). It is invoked exactly once per phone conn — on the binary's receipt of the first frame for a given conn_id — and returns the routing envelope the binary should send back plus the close-or-keep signal the relay-conn layer will act on.
The function is carrier-agnostic with respect to how token reached the binary: it never parses WS headers, never reads env.Frame's payload for a token field, and never inspects a hello payload. The relay-conn ticket that wires this handler into phone traffic picks one of (a) extended routing envelope, (b) synthesized connection_opened control frame, or (c) amended hello payload, and forwards the extracted token here unchanged.
Two-state semantics: reg.Validate returns (Device, bool). A true result means the device row exists and was just bumped (the predicate already handled LastSeenAt under reg.mu — the handler does not call any further mutator). A false result means either never-paired or the row was removed via reg.Remove; both produce the same auth.invalid_token outcome per docs/protocol-mobile.md § Error codes line 535 ("Same UX as invalid_token"). The CodeAuthTokenRevoked constant is reserved for a future tombstone primitive and is NOT emitted by this handler.
SECURITY: token is never logged, never wrapped into any returned error, and never echoed to the phone. The matched device's name IS logged on accept but is NOT logged on reject (preventing name-enumeration probes from binary logs).
type Config ¶
type Config struct {
ServerID identity.ServerID
RelayURL string
BinaryVersion string
Logger *slog.Logger
// AllowInsecureScheme, when true, lets RelayURL use plain ws:// in
// addition to wss://. Test-only seam so e2e suites can point pyry at
// an httptest-hosted fakerelay over plaintext. Production callers
// leave this false; cmd/pyry flips it only when the operator sets
// PYRY_ALLOW_INSECURE_RELAY=1.
AllowInsecureScheme bool
}
Config carries the static configuration for a Connection. The caller resolves ServerID via internal/identity.LoadOrCreate before constructing Config — the relay package never touches the on-disk store, keeping the net package free of pairing / storage concerns.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection runs the binary↔relay leg of the wire protocol. Lifecycle is tied to the context passed to Connect; cancellation closes the WS cleanly. Wait blocks until the lifecycle terminates; the returned error is the terminal classification (ErrServerIDConflict for fatal 4409, ctx.Err for graceful shutdown, or a wrapped transport error for unexpected halts).
func Connect ¶
func Connect(ctx context.Context, cfg Config) (*Connection, error)
Connect builds the transport, starts the lifecycle goroutine, and returns immediately. The connection is not yet Ready — observe Frames to consume post-handshake inbound frames, or call Wait to block on terminal classification. The caller is responsible for invoking Close during shutdown to release resources; ctx cancellation also drains the lifecycle.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close requests a clean shutdown. Idempotent. After Close, Frames drains and closes; Wait returns.
func (*Connection) CloseConn ¶
func (c *Connection) CloseConn(connID string, code uint16) error
CloseConn asks the relay to close the named phone conn with the given WS close code. Builds a close-only routing envelope (no Frame) with CloseCode set and forwards via the transport. Returns transport.ErrNotConnected when the underlying WS is currently dropped or transport.ErrDisconnected if the live conn drops while Send is blocked (caller decides whether to retry; transport reconnect runs asynchronously). Wire mechanism: docs/protocol-mobile.md § Routing envelope (CloseCode).
CloseConn does NOT block on the relay's close-frame being delivered to the phone — the request is fire-and-forget at this layer. The per-conn close ack is implicit (no more inbound frames will arrive for connID).
The dispatcher's auth-reject path does NOT call CloseConn; instead it publishes one routing envelope carrying both Frame and CloseCode so the error envelope and the close are atomic on the wire. CloseConn is the explicit surface for callers that want close-without-payload (none today; reserved for the idle/inactivity sweep hinted at in #307).
func (*Connection) Frames ¶
func (c *Connection) Frames() <-chan protocol.RoutingEnvelope
Frames returns the channel of post-handshake inbound frames. The channel closes when the lifecycle terminates. Frames are delivered in the order the underlying conn produces them; reconnects are transparent (a fresh hello/hello_ack handshake runs first, then frames resume on the new conn).
func (*Connection) Send ¶
func (c *Connection) Send(env protocol.RoutingEnvelope) error
Send marshals env to JSON and forwards it to the relay over the current transport conn. Returns transport.ErrDisconnected if the underlying conn is currently dropped (caller decides whether to retry or drop the frame); transport reconnect and a fresh hello/hello_ack handshake happen asynchronously, so a frame sent while disconnected is lost — that's consistent with v1 protocol expectations (docs/protocol-mobile.md § Connection lifecycle).
func (*Connection) Wait ¶
func (c *Connection) Wait() error
Wait blocks until the lifecycle terminates and returns the terminal classification: ErrServerIDConflict (fatal), ctx.Err (graceful shutdown), or a wrapped transport error.