relay

package
v2.6.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 12 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 relay holds the pieces of Lectern's end-to-end encrypted relay that both ends share: key material, the Noise handshake between a phone and the host, the framing of HTTP and WebSocket traffic inside that encrypted channel, and the relay's own routing frames. The relay server lives in internal/relay/server and the host side in internal/relay/host.

The design and threat model are in docs/relay.md. In short: the relay only ever sees Noise ciphertext plus the routing header it needs to deliver it; the phone pins the host's static key from a QR code shown on the host's own screen; the host admits a phone only if its static key is paired.

Index

Constants

View Source
const (
	FrameRequest      byte = 1  // device → host: RequestHead JSON
	FrameRequestBody  byte = 2  // device → host: body bytes
	FrameRequestEnd   byte = 3  // device → host: request body complete
	FrameResponse     byte = 4  // host → device: ResponseHead JSON
	FrameResponseBody byte = 5  // host → device: body bytes
	FrameResponseEnd  byte = 6  // host → device: response complete
	FrameCancel       byte = 7  // either: abandon this stream (payload: optional reason)
	FrameWSOpen       byte = 8  // device → host: WSOpen JSON
	FrameWSOpened     byte = 9  // host → device: WSOpened JSON
	FrameWSText       byte = 10 // either: one text message
	FrameWSBinary     byte = 11 // either: one binary message
	FrameWSClose      byte = 12 // either: WSClose JSON
)

Tunnel frame types, carried inside Noise transport messages. One Noise session multiplexes any number of streams; a stream is one HTTP exchange or one WebSocket. Device-to-host and host-to-device types never overlap, so a peer can reject a frame that could only have come from itself.

View Source
const (
	WSFinal byte = 0
	WSMore  byte = 1
)

WebSocket messages larger than MaxChunk span several frames. The first payload byte of FrameWSText/FrameWSBinary says whether more follow.

View Source
const (
	WireData  byte = 1 // payload: one Noise message
	WireOpen  byte = 2 // relay → host: a device connected (payload: route token hash)
	WireClose byte = 3 // either: close this device connection
)

Binary frames on the host's connection to the relay. A device's own connection carries bare Noise messages with no header at all: the relay adds and strips this routing header, and it is the only thing the relay ever parses.

View Source
const MaxChunk = 16 << 10

MaxChunk is the largest body or WebSocket payload one frame carries; larger bodies are split. Kept well under Noise's 64 KiB so padding and the header always fit.

View Source
const MaxNoiseMessage = 65535

MaxNoiseMessage is the Noise specification's own message limit.

View Source
const MaxWireMessage = MaxNoiseMessage + wireHeader

MaxWireMessage caps one frame on either relay connection.

View Source
const ProtocolVersion = 1

ProtocolVersion is carried in the QR payload and the first handshake payload; a peer that sees another version refuses rather than guessing.

Variables

View Source
var ErrClosed = errors.New("relay: connection closed")

ErrClosed reports use of a connection that has already failed or closed.

View Source
var ErrDecrypt = errors.New("relay: message failed authentication")

ErrDecrypt is returned for any message that fails authentication. It is deliberately one error: tampered, replayed and out-of-order messages are indistinguishable to the receiver and all end the session.

Suite is Noise_IK_25519_ChaChaPoly_SHA256. frontend/src/relay/noise.ts implements the same suite and is tested against this package.

Functions

func B64

func B64(b []byte) string

B64 and UnB64 are the one encoding every key crosses the wire in.

func ChannelID

func ChannelID(routePub ed25519.PublicKey) string

ChannelID derives a host's public routing id from its Ed25519 routing key. Deriving it (rather than letting a host pick one) is what lets the relay keep no state: a host proves it owns a channel by signing with the key the id is the hash of, so nobody can squat or take over someone else's channel even after a relay restart. 128 bits, base64url.

func DecodeWire

func DecodeWire(b []byte) (kind byte, conn uint32, payload []byte, err error)

DecodeWire splits a host-connection frame.

func EncodeFrame

func EncodeFrame(f Frame) ([]byte, error)

EncodeFrame lays out a frame and pads it to a multiple of padBlock.

func EncodeWire

func EncodeWire(kind byte, conn uint32, payload []byte) []byte

EncodeWire builds a host-connection frame.

func Fingerprint

func Fingerprint(pub []byte) string

Fingerprint is a short, human-comparable form of any public key: the first 8 bytes of its SHA-256 as grouped hex. Shown next to the host key and every paired device key in Settings.

func FromDevice

func FromDevice(t byte) bool

FromDevice reports whether a frame type is one a device may send.

func Prologue

func Prologue(channel string) []byte

Prologue binds a handshake to this protocol and to one channel, so a recorded handshake cannot be replayed onto a different host's channel.

func RandomToken

func RandomToken() (string, error)

RandomToken returns 32 random bytes as base64url: route tokens and pairing codes both use it.

func TokenHash

func TokenHash(token string) string

TokenHash is what the relay stores and compares for a route token: never the token itself.

func UnB64

func UnB64(s string) ([]byte, error)

func ValidChannelID

func ValidChannelID(s string) bool

ValidChannelID reports whether s has the shape ChannelID produces, so the relay can reject junk before it looks anything up.

func ValidTokenHash

func ValidTokenHash(s string) bool

ValidTokenHash reports whether s looks like a TokenHash result.

func VerifyHostProof

func VerifyHostProof(c Control, secret string, nonce []byte) bool

VerifyHostProof is the relay's check of HostProof.

Types

type Control

type Control struct {
	T       string   `json:"t"`
	V       int      `json:"v,omitempty"`
	Nonce   string   `json:"nonce,omitempty"`
	Channel string   `json:"ch,omitempty"`
	Pub     string   `json:"pub,omitempty"`
	Sig     string   `json:"sig,omitempty"`
	MAC     string   `json:"mac,omitempty"`
	Set     []string `json:"set,omitempty"`
	Hash    string   `json:"h,omitempty"`
	TTL     int      `json:"ttl,omitempty"`
	Once    bool     `json:"once,omitempty"`
	Token   string   `json:"token,omitempty"`
	Error   string   `json:"error,omitempty"`
	ID      int64    `json:"id,omitempty"`
}

Control is every JSON text message on the relay connections:

relay → host:   {"t":"challenge","nonce"}  then {"t":"ready"}
host → relay:   {"t":"hello","v","ch","pub","sig","mac"}
host → relay:   {"t":"routes","set":[hash…]}  (full replace, sent on every connect)
host → relay:   {"t":"route_add","h","ttl","once"} / {"t":"route_del","h"}
relay → host:   {"t":"ack","id"} once a control message carrying an id
                has been applied
device → relay: {"t":"auth","token"}
relay → device: {"t":"ok"}
relay → either: {"t":"error","error"} just before closing

func HostProof

func HostProof(route ed25519.PrivateKey, secret string, nonce []byte) Control

HostProof answers a relay challenge: a signature proving ownership of the channel, and an HMAC proving knowledge of the relay's host secret without sending it.

type Frame

type Frame struct {
	Type    byte
	Stream  uint32
	Payload []byte
}

Frame is one decoded tunnel frame.

func DecodeFrame

func DecodeFrame(b []byte) (Frame, error)

DecodeFrame parses a decrypted frame. Padding must be zero: it is covered by the AEAD anyway, but checking it keeps the format strict.

type Header [][2]string

Header is an ordered list of name/value pairs: order and repeated names survive, which a map would lose.

type Hello

type Hello struct {
	V    int          `json:"v"`
	Pair *PairRequest `json:"pair,omitempty"`
}

Hello is the first handshake message's encrypted payload. IK's first payload has weaker forward secrecy than transport messages (it depends on the host's static key), so it carries only a version and, once, a pairing request.

type Identity

type Identity struct {
	// Route is the Ed25519 key the host proves channel ownership with.
	Route ed25519.PrivateKey
	// Noise is the host's static X25519 key pair, pinned by every phone.
	Noise noise.DHKey
	// Shell signs the app shell manifest the phone's service worker checks.
	Shell ed25519.PrivateKey
}

Identity is the host's long-lived relay key material.

func GenerateIdentity

func GenerateIdentity() (*Identity, error)

GenerateIdentity creates a fresh set of host keys.

func (*Identity) Channel

func (id *Identity) Channel() string

Channel is this identity's relay channel id.

func (*Identity) ShellPublic

func (id *Identity) ShellPublic() ed25519.PublicKey

ShellPublic is the public half of the shell signing key.

type Initiator

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

Initiator is the phone's side of the handshake. Lectern itself never initiates; Go uses this in tests and for a future command-line client.

func NewInitiator

func NewInitiator(static noise.DHKey, hostPub []byte, channel string) (*Initiator, error)

NewInitiator starts a handshake to the host whose static key hostPub was pinned at pairing.

func (*Initiator) Finish

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

Finish reads handshake message 2 and returns the host's payload and the transport session.

func (*Initiator) Hello

func (i *Initiator) Hello(payload []byte) ([]byte, error)

Hello writes handshake message 1 carrying payload.

type PairRequest

type PairRequest struct {
	Code string `json:"code"`
	Name string `json:"name"`
}

PairRequest redeems a one-time pairing code for this device's static key.

type RequestHead

type RequestHead struct {
	Method string `json:"m"`
	URL    string `json:"u"`
	Host   string `json:"host,omitempty"`
	Header Header `json:"h,omitempty"`
}

RequestHead starts an HTTP exchange. URL is a path plus query on the host's own origin; Host is the page's origin host, so absolute URLs Lectern builds from r.Host point back at the page (whose shims then route them here).

type Responder

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

Responder is the host's side of one handshake.

func Accept

func Accept(static noise.DHKey, channel string, msg []byte) (*Responder, error)

Accept reads handshake message 1. On success the caller inspects PeerStatic and the payload, decides whether to admit the device, and answers with Reply either way.

func (*Responder) Payload

func (r *Responder) Payload() []byte

Payload is the device's decrypted Hello bytes.

func (*Responder) PeerStatic

func (r *Responder) PeerStatic() []byte

PeerStatic is the device's static public key. Message 1 already binds it through the ss DH; the device has fully proven it holds the private half once its first transport message decrypts (which needs the se DH), and the host acts on nothing but transport messages after the handshake.

func (*Responder) Reply

func (r *Responder) Reply(payload []byte) ([]byte, *Session, error)

Reply writes handshake message 2 and returns the transport session.

type ResponseHead

type ResponseHead struct {
	Status int    `json:"s"`
	Header Header `json:"h,omitempty"`
}

ResponseHead answers a RequestHead.

type Session

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

Session is an established Noise transport: one cipher state per direction, each with its own implicit nonce counter. Any decryption failure (tamper, replay, reorder, loss) poisons the session: the caller must drop the connection, never retry.

func (*Session) Open

func (s *Session) Open(msg []byte) ([]byte, error)

Open decrypts the next transport message in order.

func (*Session) Seal

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

Seal encrypts one transport message.

type WSClose

type WSClose struct {
	Code   int    `json:"c"`
	Reason string `json:"r,omitempty"`
}

WSClose ends a tunnelled WebSocket.

type WSOpen

type WSOpen struct {
	URL       string   `json:"u"`
	Host      string   `json:"host,omitempty"`
	Protocols []string `json:"p,omitempty"`
	Header    Header   `json:"h,omitempty"`
}

WSOpen asks the host to open a WebSocket to one of its own paths.

type WSOpened

type WSOpened struct {
	Protocol string `json:"p,omitempty"`
}

WSOpened confirms a WSOpen.

type Welcome

type Welcome struct {
	OK bool `json:"ok"`
	// Error is a short machine-readable reason when OK is false:
	// "unknown_device", "invalid_code", "version".
	Error      string `json:"error,omitempty"`
	DeviceID   int64  `json:"device_id,omitempty"`
	Name       string `json:"name,omitempty"`
	RouteToken string `json:"route_token,omitempty"`
}

Welcome is the second handshake message's payload.

Directories

Path Synopsis
Package client is a Go implementation of the phone's side of the relay (the browser's is frontend/src/relay).
Package client is a Go implementation of the phone's side of the relay (the browser's is frontend/src/relay).
Package host is the Lectern side of the end-to-end encrypted relay (docs/relay.md).
Package host is the Lectern side of the end-to-end encrypted relay (docs/relay.md).
Package server is `lectern relay`: a single-process, stateless router of opaque frames between a Lectern host and that host's paired devices.
Package server is `lectern relay`: a single-process, stateless router of opaque frames between a Lectern host and that host's paired devices.

Jump to

Keyboard shortcuts

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