rig

package
v0.0.0-...-09b25d6 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 28 Imported by: ? 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 rig is what a machine needs to be a rig: its key, the policy file naming the stations it accepts, enrollment, the tunnel to each station, and the gate every relayed request passes: the grant check with the hold state, and the endpoint allowlist. Roadie imports it; any other device provider can.

Index

Constants

View Source
const (
	DefaultRate  = 120 // requests and messages a second
	DefaultBurst = 240
)

The limits a hold gets unless the gate says otherwise: generous for a viewer's pointer moves, tight enough that one hold cannot flood the Pi.

View Source
const DefaultMaxSession = 8 * time.Hour

DefaultMaxSession is the longest hold a station may hold unless the policy says otherwise.

Variables

View Source
var (
	ErrOlderHold     = errors.New("an older hold than the one this device has")
	ErrReplay        = errors.New("grant already used")
	ErrRevoked       = errors.New("hold revoked")
	ErrScope         = errors.New("grant lacks the scope this needs")
	ErrPolicy        = errors.New("the rig policy does not allow this station that scope")
	ErrBusy          = errors.New("another station's hold holds this device")
	ErrHours         = errors.New("outside the hours the rig policy allows")
	ErrSessionLength = errors.New("the hold is longer than the rig policy allows")
)

Errors the gate returns, besides the token package's.

View Source
var ErrFingerprint = errors.New("the station's key does not match the code")

ErrFingerprint says the station's key does not match the code, so this is not the station the code came from.

Functions

func FirstMessageCheck

func FirstMessageCheck(ctx context.Context) func(ev nostr.Event) (token.Grant, error)

FirstMessageCheck returns the check a WebSocket handler runs on the grant in its first message, or nil when the request did not come through the tunnel and needs none.

func GrantFrom

func GrantFrom(ctx context.Context) (token.Grant, bool)

GrantFrom returns the grant a relayed request was admitted with.

func LimiterFrom

func LimiterFrom(ctx context.Context) *rate.Limiter

LimiterFrom returns the hold's rate limiter for a relayed request, so a handler reading a stream of messages can pace them with Wait; nil when the request did not come through the tunnel.

func LoadOrCreateKey

func LoadOrCreateKey(path string) (sk nostr.SecretKey, created bool, err error)

LoadOrCreateKey reads the rig key from path, making one on the first run. The file holds the secret key in hex (an nsec is accepted too) and is readable by its owner only.

func Npub

func Npub(pk nostr.PubKey) string

Npub is a public key as people see it.

func ParseNpub

func ParseNpub(s string) (nostr.PubKey, error)

ParseNpub reads an npub (or a hex key).

func TLSConfig

func TLSConfig(e *StationEntry) *tls.Config

TLSConfig is how the rig connects to an enrolled station: the system roots, or the certificate pinned at enrollment.

func Upload

func Upload(ctx context.Context, e *StationEntry, key nostr.SecretKey, rec Recording) (map[string]any, error)

Upload sends a recording to the station's Record Store under the rig's own key: a Blossom authorization (kind 24242, t=upload) naming the file's hash and size and the device and hold it belongs to, good for five minutes, with the file as the body of PUT /upload. The station checks that the device and the hold are this rig's. It returns the blob descriptor the station answers with.

Types

type Allowlist

type Allowlist []Rule

Allowlist is what a rig lets the station reach. Anything not listed is refused: the rig's admin endpoints never get a rule for user scopes.

func (Allowlist) Match

func (a Allowlist) Match(r *http.Request) (Rule, bool)

Match finds the rule for a request.

type EnrollOptions

type EnrollOptions struct {
	URL     string         // the station; empty finds one on the LAN over mDNS
	Code    string         // the one-time code from the station
	Name    string         // this rig's name
	Devices []enroll.Offer // what this rig offers
	Key     nostr.SecretKey
	Admin   bool          // accept admin grants from this station
	Timeout time.Duration // zero means 30 seconds
}

EnrollOptions is what enrolling takes.

type Gate

type Gate struct {
	Policy  *Policy
	Key     nostr.PubKey    // the rig's key
	Devices func() []string // this rig's device ids, under every station's rig id
	// StatePath persists the hold state, so a restart cannot be made to
	// accept an older hold. Optional.
	StatePath string
	// OnEnd is told when a device's hold ends: a newer hold arrived or a
	// revocation did. The rig ends that hold's sessions. Optional.
	OnEnd func(deviceID, holdID string)
	Now   func() time.Time
	Logf  func(format string, args ...any)
	// Rate and Burst limit the relayed requests and messages a hold may
	// send: DefaultRate and DefaultBurst when zero.
	Rate  float64
	Burst int
	// contains filtered or unexported fields
}

Gate checks every grant a relayed request presents, with the state that makes the rig the final gate: the current hold per device, the highest sequence seen per station, grants already used, and holds revoked.

func (*Gate) Check

func (g *Gate) Check(ev nostr.Event, need station.Scope) (token.Grant, error)

Check verifies a grant and that it allows need, and takes it into the hold state. On success the grant is spent: presenting it again is a replay.

func (*Gate) Current

func (g *Gate) Current(deviceID string) (holdID string, ok bool)

Current says which hold holds a device, if one does.

func (*Gate) Middleware

func (g *Gate) Middleware(allow Allowlist, next http.Handler) http.Handler

Middleware admits relayed requests: the endpoint must be in the allowlist and the grant in the Authorization header must pass the gate with the rule's scope.

func (*Gate) Open

func (g *Gate) Open(holdID string) int

Open is how many relayed connections a hold has, for tests.

func (*Gate) Revoke

func (g *Gate) Revoke(ev nostr.Event) error

Revoke takes a revocation from a station in the policy and ends the hold it names.

type Policy

type Policy struct {
	Stations []*StationEntry `json:"stations"`
}

Policy is the operator's consent: the stations this rig accepts and what each may do. It is a file on the rig, written by enrollment and edited by hand, and nothing remote can change it.

func LoadPolicy

func LoadPolicy(path string) (*Policy, error)

LoadPolicy reads the policy file; a missing file is an empty policy.

func (*Policy) Keys

func (p *Policy) Keys() []nostr.PubKey

Keys lists the accepted stations' keys.

func (*Policy) Save

func (p *Policy) Save(path string) error

Save writes the policy file, readable by its owner only.

func (*Policy) Set

func (p *Policy) Set(e *StationEntry)

Set adds an entry or replaces the one with the same key.

func (*Policy) Station

func (p *Policy) Station(pk nostr.PubKey) *StationEntry

Station finds the entry for a station key.

type Recording

type Recording struct {
	Body     io.Reader
	Size     int64
	SHA256   string // lowercase hex
	Name     string // a file name hint, such as rec_9f3c0a11.zip
	Type     string // the media type; application/octet-stream when empty
	DeviceID string // the device, under this station's rig id
	HoldID   string // the hold it records, when it records one
}

Recording is a file a rig sends to a station's Record Store: what it recorded of a hold, a screenshot, a log.

type Rig

type Rig struct {
	Key     nostr.SecretKey
	Policy  *Policy
	Devices []enroll.Offer // what this rig offers, by name
	Handler http.Handler   // the rig's own mux
	Allow   Allowlist      // what the station may reach on it
	Gate    *Gate          // made by Run when nil
	// StatePath is where the gate keeps its hold state. Optional.
	StatePath string
	Logf      func(format string, args ...any)
	// contains filtered or unexported fields
}

Rig runs the tunnels to every station in the policy and serves the rig's handlers over them behind the gate.

func (*Rig) DeviceIDs

func (r *Rig) DeviceIDs() []string

DeviceIDs lists this rig's device ids under every station's rig id.

func (*Rig) Online

func (r *Rig) Online() []string

Online lists the stations the rig is connected to, by name.

func (*Rig) Reannounce

func (r *Rig) Reannounce()

Reannounce tells every station the devices changed.

func (*Rig) Run

func (r *Rig) Run(ctx context.Context)

Run keeps a tunnel to every enrolled station until ctx ends.

type Rule

type Rule struct {
	Method string        // empty means any
	Path   string        // exact, or a prefix when it ends with "/"
	Scope  station.Scope // what the grant must carry
	// FirstMessage marks a WebSocket whose grant arrives in its first
	// message rather than a header: the request passes without one and the
	// handler checks it through FirstMessageCheck.
	FirstMessage bool
	// Max caps the connections one hold may have open on this rule at
	// once, for streams and sockets; zero means no cap.
	Max int
}

Rule allows one endpoint to relayed requests holding a scope.

type StationEntry

type StationEntry struct {
	Name       string   `json:"name"`
	Npub       string   `json:"npub"`
	URL        string   `json:"url"`
	TunnelURL  string   `json:"tunnel_url"`
	RigID      string   `json:"rig_id"`
	CertSHA256 string   `json:"cert_sha256,omitempty"` // the station's certificate, pinned when no root signs it
	Scopes     []string `json:"scopes"`                // view, input, bidi: what grants may carry
	Admin      bool     `json:"admin"`                 // whether admin grants are accepted
	MaxSession string   `json:"max_session,omitempty"` // a duration such as "8h"
	Hours      string   `json:"hours,omitempty"`       // "09:00-18:00", local time, when holds are allowed
	Record     bool     `json:"record,omitempty"`      // record each hold (screenshots per input) and upload it to the station
}

StationEntry is one accepted station.

func Enroll

func Enroll(ctx context.Context, o EnrollOptions) (*StationEntry, error)

Enroll joins a station: checks its key against the code's fingerprint, sends the signed request, and returns the policy entry to save.

func (*StationEntry) Allows

func (e *StationEntry) Allows(s station.Scope) bool

Allows says whether the policy lets this station grant s.

func (*StationEntry) InHours

func (e *StationEntry) InHours(t time.Time) bool

InHours says whether t is inside the entry's allowed hours. No hours means always.

func (*StationEntry) MaxSessionDuration

func (e *StationEntry) MaxSessionDuration() time.Duration

MaxSessionDuration is the entry's limit, or the default.

func (*StationEntry) PubKey

func (e *StationEntry) PubKey() (nostr.PubKey, error)

PubKey decodes the entry's npub.

Jump to

Keyboard shortcuts

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