Documentation
¶
Overview ¶
Package pairing lets a phone with no Tailscale reach Lectern through an ordinary public tunnel (Cloudflare Tunnel, `tailscale funnel`, ...) without handing it the operator's static LECTERN_AUTH_TOKEN.
Lectern's normal identity story — trust whoever tailscaled says you are — has no answer for a device that was never on the tailnet at all. When the owner trusts the tunnel in front of Lectern, device pairing is the simple answer; when they do not, the end-to-end encrypted relay (internal/relay, docs/relay.md) is. With pairing, the owner, already authenticated in a browser or session that can decide approvals, mints a short-lived, single-use code; the new device exchanges it once for its own long-lived, individually revocable credential. From then on the device authenticates as that same owner — it IS the owner's phone, so it can do everything the owner's browser can, including deciding approvals.
Off by default (LECTERN_DEVICE_PAIRING=1, or the "pairing_enabled" setting toggled from Settings → Devices). Everything here follows the store conventions the rest of the codebase already uses: opaque random secrets, stored hashed (internal/oauth), rows in the shared lectern.db (internal/store) rather than a database of their own.
Index ¶
- Constants
- Variables
- func ClientIP(r *http.Request) string
- func Enabled(envSet bool, db *store.DB) bool
- func FormatCode(raw string) string
- func IdleDays(db *store.DB) float64
- func NormalizeCode(input string) string
- func SetEnabled(db *store.DB, on bool) error
- func SetIdleDays(db *store.DB, days float64) error
- type Device
- type RateLimiter
- type Store
- func (s *Store) ExchangeCode(rawCode, name, userAgent string) (token string, dev Device, err error)
- func (s *Store) Limiter() *RateLimiter
- func (s *Store) ListDevices() ([]Device, error)
- func (s *Store) LookupDevice(ctx context.Context, rawToken string) (auth.Principal, bool)
- func (s *Store) MintCode(owner auth.Principal) (code string, expiresAt time.Time, err error)
- func (s *Store) PruneExpiredCodes()
- func (s *Store) RevokeDevice(id int64) error
Constants ¶
const ( // CodeTTL is how long a minted pairing code stays valid. Short by // design: it only has to survive the seconds between showing a QR code // and a phone scanning it. CodeTTL = 5 * time.Minute // DefaultIdleDays is how long a paired device may go unused before its // token stops working, absent an explicit setting. DefaultIdleDays = 30 )
const ( PerIPLimit = 10 GlobalLimit = 30 LockoutDuration = 5 * time.Minute )
Exchange attempts are the one unauthenticated write this package adds (mint requires an owner already signed in); a code is only 128 bits but an unlimited number of guesses is still an unlimited number of guesses. PerIPLimit/GlobalLimit bound the guessing rate; LockoutDuration is how long an IP that tripped the limit stays blocked once it does, deliberately longer than the plain per-minute window so tripping the limit costs more than waiting out one window.
Variables ¶
var ( ErrNotFound = errors.New("pairing: not found") ErrExpired = errors.New("pairing: expired") )
ErrNotFound covers an unknown or already-consumed code, or a device token nothing recognizes — deliberately one error, matching internal/oauth's ErrNotFound, so neither endpoint becomes an enumeration oracle. ErrExpired is kept distinct only for callers (tests, mainly) that care which one happened; the HTTP layer collapses both to the same response.
var Now = time.Now
Now is overridden in tests that need to move expiry/idle timers around without sleeping, matching internal/oauth's Now.
Functions ¶
func ClientIP ¶
ClientIP extracts the caller's address for rate-limiting purposes. It deliberately reads only RemoteAddr, never X-Forwarded-For: this endpoint is reachable with no auth at all, so trusting a client-supplied header here would let an attacker pick a fresh "IP" on every request and step around the whole limiter — the header is only trustworthy behind the operator's own reverse proxy, which internal/auth's TrustServeHeaders opt-in already establishes is not a safe default assumption.
func Enabled ¶
Enabled reports whether device pairing is turned on. envSet is LECTERN_DEVICE_PAIRING=1; the persisted "pairing_enabled" setting is the Settings → Devices toggle. Either one turns it on; there is no way to force it off from the database once the env var is set, matching how every other env-vs-setting knob in this codebase treats an explicit env value as an operator override.
func FormatCode ¶
FormatCode groups a raw code into hyphenated blocks for display — "A1B2C3D4-E5F6A7B8-..." — purely cosmetic; NormalizeCode strips it back out before any comparison, so a client may send the code with or without the hyphens.
func IdleDays ¶
IdleDays is how long a paired device may go unused before its token stops authenticating — DefaultIdleDays unless overridden by the "pairing_idle_days" setting.
func NormalizeCode ¶
NormalizeCode undoes FormatCode and normalizes case/whitespace, so manual entry, a pasted value, and the QR-encoded value all hash identically.
func SetIdleDays ¶
SetIdleDays persists the idle-expiry setting. A non-positive value resets to the default rather than disabling idle expiry — this is a phone that can decide approvals unattended; there is no legitimate reason to make its credential immortal.
Types ¶
type Device ¶
type Device struct {
ID int64 `json:"id"`
Name string `json:"name"`
OwnerLogin string `json:"owner_login,omitempty"`
OwnerKind string `json:"owner_kind,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
PairedAt float64 `json:"paired_at"`
LastSeenAt float64 `json:"last_seen_at"`
}
Device is one paired device, as shown on Settings → Devices.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter is a per-IP-plus-global limiter for the pairing exchange endpoint — the one place an unauthenticated caller gets repeated attempts.
func NewRateLimiter ¶
func NewRateLimiter() *RateLimiter
NewRateLimiter builds a limiter ready for concurrent use.
func (*RateLimiter) Allow ¶
func (l *RateLimiter) Allow(ip string) bool
Allow reports whether a request from ip may proceed, charging both the per-IP and the global budget. A request that fails the global check still counts against the per-IP one, and vice versa — both are real costs paid regardless of which bound bites.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is device pairing's persistence — pending codes and paired devices — kept in the shared lectern.db (internal/store) rather than a database of its own, unlike internal/oauth (which genuinely can run in a separate process against a remote control plane). Pairing only ever runs inside the one process that already owns this database.
func (*Store) ExchangeCode ¶
ExchangeCode consumes a single-use code and mints a device token for it. The code row is deleted whether or not it turns out to be expired — it is single-use either way, and leaving an expired one behind would only let it be looked up again for no benefit (see internal/oauth.ConsumeAuthCode, the same shape of fix for the same replay concern).
func (*Store) Limiter ¶
func (s *Store) Limiter() *RateLimiter
Limiter is the exchange endpoint's rate limiter — one per Store, so tests and the production server share the same instance that guards the DB.
func (*Store) ListDevices ¶
ListDevices returns every paired device, most recently paired first — Settings → Devices' whole data source.
func (*Store) LookupDevice ¶
LookupDevice implements auth.DeviceLookup: it resolves a raw device token to the principal it authenticates as, touching last_seen_at on success. An idle-expired token is treated exactly like an unknown one and its row is removed — there is no reason to keep proving the same idle check on every later request once a token has already failed it once.
func (*Store) MintCode ¶
MintCode issues a fresh single-use code bound to owner, valid for CodeTTL. owner is whatever internal/auth resolved for the minting request — its Kind/Login/Node travel with the code and become the paired device's own identity once exchanged.
func (*Store) PruneExpiredCodes ¶
func (s *Store) PruneExpiredCodes()
PruneExpiredCodes drops codes nobody redeemed. Best-effort housekeeping, mirroring internal/oauth's pruneExpiredCodes; nothing here depends on it running promptly since ExchangeCode itself checks expiry.
func (*Store) RevokeDevice ¶
RevokeDevice deletes a device's token immediately — its next request gets a plain 401, same as any other unrecognized credential.