devices

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 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 AuthorizeRemotePermission added in v0.15.0

func AuthorizeRemotePermission(d *Device, outcome RemotePermissionOutcome) bool

AuthorizeRemotePermission resolves the final grant decision, fail-closed. Returns true (ALLOW) ONLY when the device is eligible AND the outcome is an explicit allow. Every other (device, outcome) — ineligible / nil device, no answer, timeout, cancel, explicit deny — returns false (DENY). #703 applies this on timeout (OutcomeTimeout -> false).

It re-checks MayAnswerRemotePermission (defense in depth) so it denies correctly even if a caller skips the upfront eligibility 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 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 authorizes THIS device to ANSWER a remote
	// permission / trust / destructive modal (ADR 025 § "Security model").
	// Default OFF (the zero value): an omitted/pre-field on-disk record
	// decodes to false = denied. Set only by
	// `pyry pair --allow-remote-permissions`; never set or carried over the
	// wire. Read off the authenticated *Device by the modal control loop
	// (#703) via dispatch.Conn.Auth(). Gating applies ONLY to answering a
	// permission-class modal; everything else a paired phone does is
	// ungated. 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"`
}

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) MayAnswerRemotePermission added in v0.15.0

func (d *Device) MayAnswerRemotePermission() bool

MayAnswerRemotePermission reports whether this device is authorized to answer a remote permission / trust / destructive modal. Fail-closed: returns true ONLY when the per-device opt-in bit is set. A nil receiver (no authenticated device on the connection) and a bit-OFF device both return false = denied. The nil-guard makes the safe default structural, so the predicate is total: the modal control loop (#703) calls it off dispatch.Conn.Auth() — typed *Device, nil before the first-frame gate accepts — to reject a non-permitted phone's modal answer with an error envelope BEFORE resolving any answer (ADR 025 § "Security model").

Pure predicate: no side effects (no logging, no I/O, no token handling). Audit-writing on a decision is #712's primitive; it is not invoked here.

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) 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) 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) (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 — only on acceptance — advances its LastSeenAt to time.Now() in the in-memory registry. Returns the matched Device and ValidateAccepted on a hit. Every refusal returns the zero Device (never the matched record, which would invite a caller to read it) alongside 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).

SECURITY: the LastSeenAt stamp happens strictly AFTER the window check, so a rejected attempt mutates nothing at all. That is what keeps `pyry pair list` an honest witness — an expired token 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
)

Jump to

Keyboard shortcuts

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