devices

package
v0.41.4 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 13 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 devices defines the on-disk Device type and the token hashing/verification primitives used by `pyry pair` and the mobile auth path.

SECURITY: callers MUST NOT log a plain device-token, MUST NOT wrap a plain token into error context, and MUST NOT pass a plain token across log/slog fields. The plain token appears once at pairing (QR code, paste-fallback string) and once per WS-connect (the phone presents it for verification). Outside those two sites the only on-disk and in-memory representation is the SHA-256 hex hash.

Index

Constants

View Source
const DefaultLockWait = 5 * time.Second

DefaultLockWait is the bounded acquisition wait for callers with no reason to pick their own. A caller on a request path (the daemon's push-token handler) should choose a tighter bound rather than inherit this one.

View Source
const RedemptionWindow = 15 * time.Minute

RedemptionWindow is how long a freshly minted pairing token stays redeemable: `pyry pair` stamps Device.RedeemBy at mint time plus this window. It is the only place the value appears — call sites and tests derive from it rather than restating the number.

Variables

View Source
var ErrLockBusy = errors.New("devices: lock busy")

ErrLockBusy reports that the lock was not acquired within the caller's wait. Callers match it with errors.Is and map it to their own refusal surface — wire-code mapping belongs to the consumer, not to this primitive.

Functions

func AuthorizePromptAnswer added in v0.26.0

func AuthorizePromptAnswer(d *Device, outcome RemotePermissionOutcome) bool

AuthorizePromptAnswer is the answering paths' fail-closed grant decision. Returns true (ALLOW) ONLY when the device may answer AND the outcome is an explicit allow; every other (device, outcome) returns false (DENY). It is the answer-side twin of AuthorizeRemotePermission, which keeps the privileged bit for MCP actuation.

func AuthorizeRemotePermission added in v0.15.0

func AuthorizeRemotePermission(d *Device, outcome RemotePermissionOutcome) bool

AuthorizeRemotePermission resolves a privileged grant decision, fail-closed. Returns true (ALLOW) ONLY when the device holds the privileged bit AND the outcome is an explicit allow. Every other (device, outcome) — unprivileged / nil device, no answer, timeout, cancel, explicit deny — returns false (DENY). Since #2605 its caller is MCP actuation; answering uses AuthorizePromptAnswer.

It re-checks MayAnswerRemotePermission (defense in depth) so it denies correctly even if a caller skips the upfront privilege gate. The single ALLOW conjunction keeps the safe default in one unit-tested place: any future outcome added to the enum defaults to DENY unless explicitly mapped here.

Pure predicate: no side effects (audit is #712's, deliberately separate).

func HashToken

func HashToken(plain string) string

HashToken returns the lowercase SHA-256 hex of plain. Output is always 64 hex characters (sha256.Size * 2). The same input always produces the same output (deterministic, no salt — see the package design doc for why bcrypt and per-token salt are intentionally rejected for 256-bit random tokens).

func VerifyToken

func VerifyToken(plain, hash string) bool

VerifyToken reports whether HashToken(plain) equals hash, in constant time relative to hash's length. Returns false for any hash whose length differs from the canonical 64-char hex (this includes the empty string and any malformed hex). Never panics; never logs; never returns the plain or hash in any error.

func WithLock added in v0.16.0

func WithLock(devicesPath string, wait time.Duration, fn func() error) error

WithLock runs fn while holding an exclusive lock, derived from devicesPath, that excludes other OS processes. The lock is acquired before fn runs and released after it returns, so a caller's whole read-modify-write — Load, the mutation, and Save's rename — is one critical section. `pyry pair` and the daemon are separate processes, so Registry.mu cannot serialize them and a lost update silently erases whichever writer commits first.

fn's error is returned verbatim, never wrapped, so a caller's errors.Is against its own sentinels keeps working. Every other error class is this package's own: an acquisition that exhausts wait returns ErrLockBusy and never runs fn.

fn runs with the file lock held. It MUST NOT call WithLock again on the same path: a nested call opens a second file description, and flock(2) contends per description rather than per process, so the inner call would contend with its own caller and burn wait before returning ErrLockBusy. WithLock is the sole acquirer in this package — Load, Save, and Reload do not take the lock, which is what keeps the file-lock-then-Registry.mu ordering the only one reachable. fn SHOULD keep the region short: peers wait on it.

The lock lives on a sibling file, devicesPath + ".lock", and never on devices.json itself. A flock attaches to the open file description, i.e. to the inode, and Save commits by renaming a temp file over the target, which installs a new inode at that path; a second acquirer opening devices.json after that rename would get the new inode and acquire its own independent lock while the first holder still believed it excluded everyone. Mutual exclusion would be broken by the exact operation the lock exists to protect. The sidecar's inode is never replaced. It is created on demand and never deleted — unlinking it races acquisition, since a holder can be unlinked out from under a waiter and both then proceed. A leftover zero-byte lock file is the intended steady state.

The lock fd is never written to; the file's only role is to own a stable inode, and O_RDWR is the conventional flock open mode rather than a need. Do not stash the holder's pid or a timestamp in it for debugging: that both races (a waiter that has just acquired would truncate under a reader) and puts an information surface next to a credential store.

Deriving the lock path from devicesPath also isolates instances — two -pyry-name values yield two sidecars, which never contend.

The kernel releases a flock when the fd closes, including on process exit or SIGKILL, so there is no stale lock to clean up and no lock-file TTL. A process killed mid-region leaves devices.json either pre- or post-rename, never partial, because Save is already atomic.

SECURITY: every error returned here names the lock path and nothing else, inheriting the rule stated on readDevicesFile — a corrupt devices.json can carry a token_hash in a decode error, so no error or log surface next to this file may echo its bytes. WithLock never opens, reads, or decodes the registry itself, so the leak is structurally out of reach here; the rule is stated because callers add error paths that do sit beside decoded data.

Types

type BindResult added in v0.31.0

type BindResult int

BindResult is what BindStaticKey decided. The zero value refuses, so a default-constructed result fails closed, as ValidateResult's does.

const (
	// BindUnknownDevice: no device has the token hash, or the presented key
	// is empty. The fail-closed zero value.
	BindUnknownDevice BindResult = iota
	// BindMatched: the device was already bound to this key. Nothing changed.
	BindMatched
	// BindNewlyBound: the device was unbound and is now bound to this key.
	// The caller persists.
	BindNewlyBound
	// BindKeyMismatch: the device is bound to a different key — another
	// install holds this pairing, or won a race to bind it first.
	BindKeyMismatch
)

type Device

type Device struct {
	TokenHash  string    `json:"token_hash"`
	Name       string    `json:"name"`
	PairedAt   time.Time `json:"paired_at"`
	LastSeenAt time.Time `json:"last_seen_at"`

	// Platform is the push notification platform for this device:
	// "fcm" (Android) or "apns" (iOS). Empty for devices that have
	// not registered a push token (e.g. CLI peers, or phones that
	// have not yet completed register_push_token). Matches the
	// contract on protocol.RegisterPushTokenPayload.Platform.
	Platform string `json:"platform,omitempty"`

	// PushToken is the opaque FCM / APNs device token used to wake
	// this device when it is offline. Empty for devices that have
	// not registered. Written by the register_push_token handler;
	// never marshalled across the wire (the wire form is
	// protocol.RegisterPushTokenPayload).
	PushToken string `json:"push_token,omitempty"`

	// AllowRemotePermissions is THIS device's privileged bit: it may mint a
	// pairing for another device and actuate an MCP server. Since #2605 it
	// does NOT gate answering a permission / trust / destructive modal or a
	// question batch — every authenticated device may (Device.MayAnswerPrompt).
	// The name and the on-disk key predate that change and are kept.
	// Default OFF (the zero value): an omitted/pre-field on-disk record
	// decodes to false = unprivileged. Set only by
	// `pyry pair --allow-remote-permissions`; never set or carried over the
	// wire, so a minted device is always unprivileged. Read off the
	// authenticated *Device via Device.MayAnswerRemotePermission. omitempty
	// keeps the secure-default (false) off disk, matching the
	// Platform/PushToken precedent.
	AllowRemotePermissions bool `json:"allow_remote_permissions,omitempty"`

	// RedeemBy is the instant at which an UNREDEEMED pairing record stops
	// being acceptable. Stamped once at mint time by `pyry pair` as
	// PairedAt + RedemptionWindow; never rewritten afterwards. The zero
	// value means "no deadline" — what a record minted before this field
	// existed decodes to. RedeemBy says nothing about a device that has
	// already been redeemed: a redeemed device keeps authenticating past
	// it, which is why the name is not ExpiresAt.
	//
	// Validate enforces it (#1529): a record whose deadline is set and
	// already past refuses with ValidateWindowElapsed, and the v2 handshake
	// turns that into the same 4401 an unknown token gets. The zero value
	// authenticates forever, which is both the migration path for a record
	// predating the field and — since #1528's redemption clear — how an
	// already-redeemed device is represented.
	//
	// omitzero, not omitempty: encoding/json omits empty scalars, maps and
	// slices, never a struct, so omitempty on a time.Time is a silent
	// no-op that would write "0001-01-01T00:00:00Z" into every legacy
	// record on the next Save. omitzero consults time.Time's IsZero and
	// keeps the zero off disk, matching what the three fields above do for
	// their types.
	//
	// Downgrading to a binary predating this field re-Saves the record
	// without redeem_by, so the token stops expiring — it fails OPEN, back
	// to the pre-field behaviour. Deliberately not defended against in
	// code: swapping the operator's own binary needs local write access,
	// at which point this deadline is not the weakest link.
	RedeemBy time.Time `json:"redeem_by,omitzero"`

	// ClientVersion is the client_version this device reported in its most
	// recent accepted hello (#2577), stored raw so the operator can see in
	// `pyry pair list` whether any device still runs an old app. Written only
	// by the v2 handshake, and only after internal/sessions'
	// AdmitClientVersion has passed it: a value that gate refuses is stored as
	// "". It is still client-authored text — do not log it. omitempty keeps a
	// record with no version, including every record predating the field, free
	// of the key.
	ClientVersion string `json:"client_version,omitempty"`

	// StaticKey binds this pairing to one app install (#2734): the lowercase
	// hex of the Noise_IK device-static public key the first accepted
	// connection presented. Empty means unbound — a record minted but never
	// accepted, or one accepted before this field existed. Written once, by
	// Registry.BindStaticKey from the v2 handshake; a later connection whose
	// token matches but whose key differs is refused as if the token were
	// unknown (Validate's ValidateKeyMismatch). Revoke drops it with the
	// record, so re-pairing is how an install change is made.
	//
	// A string rather than []byte keeps Device comparable and the on-disk form
	// readable. It is a public key, not a secret, but nothing logs it either.
	StaticKey string `json:"static_key,omitzero"`
}

Device is the on-disk shape for one paired device. Persisted by the sibling registry-CRUD ticket; never marshalled across the wire (the wire carries plain tokens once at handshake, then routing envelopes by server-id).

func (*Device) MayAnswerPrompt added in v0.26.0

func (d *Device) MayAnswerPrompt() bool

MayAnswerPrompt reports whether this device may answer a remote permission / trust / destructive modal or answer or refuse a question batch. Since #2605 (operator decision 2026-09-24: no view-only clients) that is every authenticated device; AllowRemotePermissions plays no part. A nil receiver — no authenticated device on the connection, dispatch.Conn.Auth() before the first-frame gate accepts — returns false = denied, so the fail-closed reading is structural rather than a branch at each call site.

Pure predicate: no side effects (no logging, no I/O, no token handling).

func (*Device) MayAnswerRemotePermission added in v0.15.0

func (d *Device) MayAnswerRemotePermission() bool

MayAnswerRemotePermission reports whether this device holds the privileged AllowRemotePermissions bit. Despite its name it no longer gates answering — MayAnswerPrompt does, since #2605. It gates the two privileged verbs: minting a pairing for another device (pairingMinterV2.MintPairing) and actuating an MCP server (mcpActuatorV2.actuate). Fail-closed: a nil receiver (no authenticated device) and a bit-OFF device both return false = denied.

Pure predicate: no side effects (no logging, no I/O, no token handling).

type Registry

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

Registry is the in-memory device list, guarded by a mutex. Construct via Load (cold-start or warm-start from disk); persist via Save. All methods are safe for concurrent use.

func Load

func Load(path string) (*Registry, error)

Load reads path. A missing file returns an empty *Registry with no error (cold start). A zero-byte file returns an empty *Registry with no error. Malformed JSON returns a wrapped error and a nil *Registry.

The returned *Registry is independent of the on-disk file: subsequent Save calls re-encode from the in-memory slice; the file may move or be deleted between Load and Save without affecting in-memory state.

func (*Registry) Add

func (r *Registry) Add(d Device)

Add appends d to the in-memory list. Caller owns uniqueness — Add does not validate that d.Name or d.TokenHash is unique within the registry.

func (*Registry) BindStaticKey added in v0.31.0

func (r *Registry) BindStaticKey(tokenHash string, peerStatic []byte) BindResult

BindStaticKey binds the device whose TokenHash equals tokenHash to peerStatic, the Noise static public key its connection presented, if it is not bound yet (#2734). The check and the write are one critical section under Registry.mu, so of two connections racing to bind one unbound record with different keys exactly one gets BindNewlyBound and the other BindKeyMismatch. A bound device is never rebound: only `pyry pair revoke`, which removes the record, releases a binding. Caller is responsible for persisting via Save on BindNewlyBound.

Concurrency: serialized under Registry.mu; takes no file lock, as with ClearRedeemBy.

func (*Registry) ClearPushRegistrationIfMatch added in v0.40.3

func (r *Registry) ClearPushRegistrationIfMatch(tokenHash, platform, pushToken string) bool

ClearPushRegistrationIfMatch clears only a still-matching registration on the same pairing. Comparison and mutation are atomic against registration updates. It preserves every other field and reports whether a Save is warranted.

func (*Registry) ClearRedeemBy added in v0.16.0

func (r *Registry) ClearRedeemBy(tokenHash string) bool

ClearRedeemBy zeroes RedeemBy on the device whose TokenHash equals tokenHash, durably recording that its pairing token has been redeemed. Returns true iff a matching device was found AND its RedeemBy was non-zero — that is, iff the in-memory state actually changed and a Save is warranted. A match whose deadline is already clear returns false, so the idempotency the redemption call site needs is decided here rather than re-derived there. Caller is responsible for persisting via Save.

The zero value is "no deadline", and Device.RedeemBy is tagged omitzero, so a cleared record loses the redeem_by key on the next Save rather than persisting a zero instant.

Concurrency: serialized under Registry.mu; safe to call from any goroutine. It takes no file lock — callers that must exclude another OS process across their whole read-modify-write wrap the sequence in WithLock, which stays this package's sole acquirer.

func (*Registry) FindByTokenHash

func (r *Registry) FindByTokenHash(hash string) (Device, bool)

FindByTokenHash returns the device whose TokenHash equals hash, and true if one was found. Comparison is byte-exact; constant-time comparison is not required at the hash↔hash boundary (VerifyToken owns the plain↔hash boundary).

func (*Registry) List

func (r *Registry) List() []Device

List returns a copy of the in-memory device list. Callers may mutate the returned slice and its elements without affecting registry state.

func (*Registry) Reload added in v0.16.0

func (r *Registry) Reload(path string) error

Reload reconciles the on-disk device set at path INTO the in-memory registry under r.mu, disk being authoritative for membership. It lets a device paired via `pyry pair` after daemon startup authenticate on its next handshake without a restart, and reflects a `pyry pair revoke` the same way (#782).

Reconciliation is keyed on TokenHash: a device present in BOTH memory and disk keeps its in-memory struct — preserving the LastSeenAt bumps Validate makes (never persisted) and any in-flight push registration; the daemon is the sole writer of those fields, so memory is >= disk for them, and `pyry pair` has no verb that edits an existing device's fields under a stable TokenHash. A device only on disk is adopted (newly paired); a device only in memory is dropped (revoked). Membership after Reload == disk's exact set, so the accept set is never widened beyond what is on disk.

A missing (ENOENT) or zero-byte file reconciles membership to empty (no error) — disk is authoritative and says none. Malformed JSON or any other read error returns a wrapped error and leaves the in-memory set UNCHANGED (fail closed): callers proceed to Validate against the retained set, so no loaded device is lost and no unpaired token becomes acceptable.

Lock discipline mirrors Save: the disk read happens OUTSIDE r.mu (I/O off the lock); only the reconcile-and-assign takes r.mu. Reload never nests locks and never calls back into a locked path, so concurrent Reload/Validate/Save from different goroutines serialise safely at r.mu.

SECURITY: Reload performs no logging and no token/hash/name handling; the only error it returns is readDevicesFile's path-only wrapped error. It runs BEFORE Validate, never inside it — Validate's contract is untouched.

func (*Registry) Remove

func (r *Registry) Remove(name string) bool

Remove deletes the first device whose Name equals name. Returns true iff a device was removed; false if no entry matched. Comparison is byte-exact.

func (*Registry) Save

func (r *Registry) Save(path string) error

Save writes the registry atomically: temp file in filepath.Dir(path) at mode 0600, fsync, rename into place. Parent directory is created with mode 0700 if missing. Returns a wrapped error on any step failure; on failure the pre-existing target file (if any) is left untouched (rename is the commit point).

Entries are sorted by PairedAt then Name before serialization to guarantee byte-identical output for the same logical content.

func (*Registry) SetClientVersion added in v0.25.0

func (r *Registry) SetClientVersion(tokenHash, version string) bool

SetClientVersion sets ClientVersion on the device whose TokenHash equals tokenHash. Returns true iff a matching device was found AND its stored value differed — iff a Save is warranted — so a reconnect reporting the version already stored costs the caller no write. It stores version as given: the caller admits it first (see Device.ClientVersion). Caller is responsible for persisting via Save.

Concurrency: serialized under Registry.mu; takes no file lock, as with ClearRedeemBy.

func (*Registry) UpdatePushRegistration

func (r *Registry) UpdatePushRegistration(tokenHash, platform, pushToken, name string) bool

UpdatePushRegistration sets Platform, PushToken, and Name on the device whose TokenHash equals tokenHash. Returns true iff a matching device was found and mutated. Caller is responsible for persisting via Save.

The Name overwrite is intentional: the protocol's register_push_token.device_name is the phone's current self-reported name, and pyrycode treats the phone as the source of truth (a user renaming their device in iOS Settings should propagate). The original pairing-time Name carries no protocol-level invariants.

Concurrency: serialized under Registry.mu; safe to call from any goroutine.

func (*Registry) Validate

func (r *Registry) Validate(plain string, peerStatic []byte) (Device, ValidateResult)

Validate is the WS-perimeter auth predicate. It hashes plain, looks up the matching device by hash, checks that device's redemption window and its static-key binding, and — only on acceptance — advances its LastSeenAt to time.Now() in the in-memory registry. Returns the matched Device and ValidateAccepted on a hit. Refusals return the reason: ValidateUnknownToken when no device matches or plain is the empty string, ValidateWindowElapsed when a device matches but its unredeemed pairing token is past RedeemBy (#1529), ValidateKeyMismatch when a device matches but is bound to a static key other than peerStatic (#2734). Those first two return the zero Device (never the matched record, which would invite a caller to read it). The key mismatch alone returns the matched record, because the caller must name the device in its log line; it must still refuse on that result.

Validate does not bind an unbound record — an unbound device is accepted whatever key it presents, and BindStaticKey makes the binding once the caller's remaining admission checks have passed.

SECURITY: the LastSeenAt stamp happens strictly AFTER the window and key checks, so a rejected attempt mutates nothing at all. That is what keeps `pyry pair list` an honest witness — an expired token, or another install's copy of a bound one, that kept refreshing LastSeenAt would look exactly like a device in daily use. Validate likewise never removes the expired record: Remove is the only deleter, and `pyry pair revoke` is its only caller.

Validate does NOT persist the LastSeenAt update — disk persistence is the caller's responsibility (Validate runs once per WS connect; fsync on the auth hot path is undesirable). Callers that want LastSeenAt durability schedule a periodic Save (e.g. every N minutes, or on graceful shutdown); the in-memory state is the source of truth for runtime decisions.

SECURITY: the empty plain returns ValidateUnknownToken without computing HashToken or taking the registry lock. This prevents an attacker who omits the token from triggering a registry scan, and it defends against the (unreachable today, but cheap-to-defend) case of a Device persisted with TokenHash == HashToken("").

SECURITY: Validate never logs the plain, never logs the hash, never logs the matched device name, and never returns any of these in an error (the predicate has no error path today). The returned (Device, ValidateResult) is the only signal the caller receives.

Concurrency: the lookup-check-and-mutate is one critical section under Registry.mu — concurrent Validate calls of the same token observe a monotonically-non-decreasing LastSeenAt, the window check cannot be interleaved with the stamp it guards, and the mutation never races with Add / Remove / List / FindByTokenHash / ClearRedeemBy / Save snapshots.

type RemotePermissionOutcome added in v0.15.0

type RemotePermissionOutcome int

RemotePermissionOutcome is what the modal control loop (#703) observed for a surfaced remote-permission modal. The zero value (OutcomeNoAnswer) is the safe default and resolves to DENY, so a default-constructed call denies.

const (
	OutcomeNoAnswer RemotePermissionOutcome = iota // no answer observed (default -> DENY)
	OutcomeAllow                                   // phone explicitly chose an allow option
	OutcomeDeny                                    // phone explicitly chose a deny option
	OutcomeTimeout                                 // deny-on-timeout window elapsed (#703's timer)
	OutcomeCancel                                  // phone cancelled / dismissed (ESC)
)

type ValidateResult added in v0.16.0

type ValidateResult int

ValidateResult is why Validate accepted or refused a presented token. The zero value denies, so a default-constructed result — or a future Validate path that returns before deciding — fails closed, the same discipline RemotePermissionOutcome uses below.

const (
	// ValidateUnknownToken: no device matches the presented token (this also
	// covers the empty plain). The fail-closed zero value.
	ValidateUnknownToken ValidateResult = iota
	// ValidateAccepted: a device matches and its redemption window has not
	// elapsed. The ONLY result that authenticates.
	ValidateAccepted
	// ValidateWindowElapsed: a device matches, but its pairing token was
	// never redeemed and RedeemBy has passed. Distinct from
	// ValidateUnknownToken so the caller can log the two apart; callers MUST
	// NOT let the distinction reach the client (#1529 — a distinct wire
	// signal would confirm to a token's holder that it was once real).
	ValidateWindowElapsed
	// ValidateKeyMismatch: a device matches, but it is bound to a different
	// Noise static key than the one this connection presented (#2734) — the
	// token is being used by an install other than the one that first
	// redeemed it. The handshake also produces it when BindStaticKey loses a
	// race. Same rule as ValidateWindowElapsed: log it apart, never let the
	// client see the difference.
	ValidateKeyMismatch
)

Jump to

Keyboard shortcuts

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