devices

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 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 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

This section is empty.

Variables

This section is empty.

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.

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"`
}

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) 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) 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, bool)

Validate is the WS-perimeter auth predicate. It hashes plain, looks up the matching device by hash, and advances that device's LastSeenAt to time.Now() in the in-memory registry. Returns the matched Device and true on a hit; (Device{}, false) on any miss (no device matches, or plain is the empty string).

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 (Device{}, false) 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, bool) is the only signal the caller receives.

Concurrency: the lookup-and-mutate is one critical section under Registry.mu — concurrent Validate calls of the same token observe a monotonically-non-decreasing LastSeenAt, and the mutation never races with Add / Remove / List / FindByTokenHash / 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)
)

Jump to

Keyboard shortcuts

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