hub

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 25 Imported by: 1 module, 1 package

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddCuReplacementTracker added in v0.7.0

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

AddCuReplacementTracker manages the Device Replacement Timing Logic for AddCu devices.

This tracker implements the 15-minute replacement detection window specified in the SHIP Pairing Service specification. It ensures that when an AddCu device disconnects, the system waits for a reasonable period before assuming the device has been replaced and reactivating the pairing listener.

Key features: - Single device tracking: Only one device can be tracked at a time - 15-minute default timeout: Configurable via NewAddCuReplacementTrackerWithTimeout - Automatic cleanup: Timer resources are properly managed - Thread-safe: All operations are protected by mutex

The tracker enforces a single device constraint because: - Only one control unit is typically present in a home - Device replacement is a sequential operation - This simplifies timer management and prevents resource leaks

Example usage:

tracker := NewAddCuReplacementTracker()

// Start tracking when device disconnects
tracker.StartTimer(shipID, func(expiredShipID string) {
    log.Printf("Device %s timed out - assuming replacement", expiredShipID)
    removeDeviceTrust(expiredShipID)
    reactivatePairingListener()
})

// Cancel timer if device reconnects
if deviceReconnected {
    tracker.StopTimer(shipID)
}

// Check if currently tracking a device
if tracker.IsTracking(shipID) {
    log.Printf("Waiting for device %s to reconnect", shipID)
}

func NewAddCuReplacementTracker added in v0.7.0

func NewAddCuReplacementTracker() *AddCuReplacementTracker

NewAddCuReplacementTracker creates a tracker with default 15-minute timeout.

The 15-minute timeout is specified in the SHIP Pairing Service specification as a reasonable balance between user experience and security.

Returns: - *AddCuReplacementTracker: A new tracker instance with 15-minute timeout

Example:

tracker := NewAddCuReplacementTracker()
tracker.StartTimer(shipID, func(expiredShipID string) {
    log.Printf("Device %s timed out", expiredShipID)
})

func NewAddCuReplacementTrackerWithTimeout added in v0.7.0

func NewAddCuReplacementTrackerWithTimeout(timeout time.Duration) *AddCuReplacementTracker

NewAddCuReplacementTrackerWithTimeout creates a tracker with custom timeout.

This constructor allows customization of the timeout duration, useful for testing or special deployment scenarios.

Parameters: - timeout: Duration to wait before considering device replaced

Returns: - *AddCuReplacementTracker: A new tracker instance with specified timeout

Example:

// Create tracker with 5-minute timeout for testing
tracker := NewAddCuReplacementTrackerWithTimeout(5 * time.Minute)
tracker.StartTimer(shipID, func(expiredShipID string) {
    handleTimeout(expiredShipID)
})

func (*AddCuReplacementTracker) IsInReplacementWindow added in v0.7.0

func (t *AddCuReplacementTracker) IsInReplacementWindow() bool

IsInReplacementWindow returns true if any AddCu device is currently being tracked.

This method checks if there is an active replacement timer running, which indicates that SHIP pairing announcements should be ignored during the 15-minute window. When the timer expires, queued announcements will be processed via mDNS polling.

Returns: - true if there is an active replacement timer (announcements should be ignored) - false if no replacement timer is active (process announcements normally)

Thread-safety: This method is thread-safe and can be called concurrently.

func (*AddCuReplacementTracker) IsTracking added in v0.7.0

func (t *AddCuReplacementTracker) IsTracking(shipID string) bool

IsTracking returns true if the tracker is currently tracking the specified device.

This method checks whether a timer is active for the given device, useful for debugging and monitoring the replacement detection state.

Parameters: - shipID: The SHIP ID of the device to check

Returns: - true if the device is being tracked with an active timer - false if the device is not being tracked or timer has expired

Thread-safety: This method is thread-safe and can be called concurrently.

func (*AddCuReplacementTracker) StartTimer added in v0.7.0

func (t *AddCuReplacementTracker) StartTimer(shipID string, onTimeout func(expiredShipID string))

StartTimer begins tracking the specified device with a timeout callback.

This method starts a 15-minute timer for the specified device. When the timer expires, the provided callback function is invoked with the shipID of the device that timed out, typically to remove trust and reactivate the pairing listener.

Parameters: - shipID: The SHIP ID of the device to track - onTimeout: Callback function invoked when timer expires with the shipID (can be nil)

Behavior: - If another device is already being tracked, it will be replaced - The timer runs for the configured timeout duration (default: 15 minutes) - The callback is invoked exactly once when the timer expires - The callback receives the shipID as a parameter for type-safe handling - Timer state is automatically cleaned up after expiry

Thread-safety: This method is thread-safe and can be called concurrently.

func (*AddCuReplacementTracker) StopAll added in v0.7.0

func (t *AddCuReplacementTracker) StopAll()

StopAll cancels any active replacement timer and clears tracking state.

Unlike StopTimer, this does not require the caller to know which device is being tracked; it unconditionally tears down whatever timer is running. It should be called during Hub shutdown to prevent the timeout callback from firing after the Hub is torn down — otherwise handleAddCuReplacementTimeout could reactivate the pairing listener and call into an already-shut-down pairing service and mDNS up to the full timeout later, and the pending time.AfterFunc would pin the Hub in memory for the same window.

Thread-safety: This method is thread-safe and can be called concurrently.

func (*AddCuReplacementTracker) StopTimer added in v0.7.0

func (t *AddCuReplacementTracker) StopTimer(shipID string)

StopTimer stops tracking the specified device if it matches the currently tracked device.

This method cancels the replacement timer for a device, preventing the timeout callback from being invoked. It should be called when a device reconnects within the 15-minute window.

Parameters: - shipID: The SHIP ID of the device whose timer should be stopped

Behavior: - Only stops the timer if shipID matches the currently tracked device - If shipID doesn't match, this method does nothing (no-op) - Clears all tracking state for the device - Prevents the timeout callback from being invoked

Thread-safety: This method is thread-safe and can be called concurrently.

type AnnouncementLifetimeTracker added in v0.7.0

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

func NewAnnouncementLifetimeTracker added in v0.7.0

func NewAnnouncementLifetimeTracker(timeout time.Duration) *AnnouncementLifetimeTracker

NewAnnouncementLifetimeTracker creates a tracker with the timeout from the provided PairingConfig.AnnouncementLifetimeTimeout if set, otherwise defaults to 15 minutes per spec.

func (*AnnouncementLifetimeTracker) CancelLifetimeTimer added in v0.7.0

func (t *AnnouncementLifetimeTracker) CancelLifetimeTimer(shipID string)

CancelLifetimeTimer cancels the announcement lifetime timer for a specific device.

This should be called when a SHIP connection is interrupted (closed) before the 15-minute window completes or the announcement was withdrawn by the announcer. The announcement will continue to be active since the spec requires an uninterrupted connection for the full duration.

Parameters:

  • shipID: The SHIP ID of the device whose timer should be cancelled

Thread-safety: This method is thread-safe.

func (*AnnouncementLifetimeTracker) IsTimerActive added in v0.7.0

func (t *AnnouncementLifetimeTracker) IsTimerActive(shipID string) bool

IsTimerActive returns true if a lifetime timer is currently running for the specified device (i.e., the device is connected and the 15-minute countdown is in progress).

A timer is considered active from the moment StartLifetimeTimer is called until either the timer expires (and the callback fires) or CancelLifetimeTimer is called.

Parameters:

  • shipID: The SHIP ID to check

Thread-safety: This method is thread-safe.

func (*AnnouncementLifetimeTracker) StartLifetimeTimer added in v0.7.0

func (t *AnnouncementLifetimeTracker) StartLifetimeTimer(shipID string, onExpiry func(expiredShipID string))

StartLifetimeTimer begins the announcement lifetime countdown for a specific device.

When a SHIP connection is successfully established with a device, this method starts a timer. If the connection remains uninterrupted for the full duration (15 minutes), the onExpiry callback is invoked to stop the announcement.

If a timer is already running for this ShipID (e.g., reconnection), the existing timer is replaced with a new one.

Parameters:

  • shipID: The SHIP ID of the connected device
  • onExpiry: Callback invoked when the timer expires (typically calls StopAnnouncementTo)

Thread-safety: This method is thread-safe.

func (*AnnouncementLifetimeTracker) StopAll added in v0.7.0

func (t *AnnouncementLifetimeTracker) StopAll()

StopAll cancels all active lifetime timers. This should be called during Hub shutdown to prevent timer goroutines from firing after the Hub is torn down.

type AutoTrustEstablishmentRequest added in v0.7.0

type AutoTrustEstablishmentRequest struct {
	SKI         string
	ShipID      string
	Fingerprint string
	Context     string // for logging
}

AutoTrustEstablishmentRequest contains the required parameters for establishing auto trust via pairing

type AutoTrustEstablishmentResult added in v0.7.0

type AutoTrustEstablishmentResult struct {
	Success        bool
	ServiceCreated bool // true if service was created, false if updated existing
	Error          error
}

AutoTrustEstablishmentResult contains the result of establishing auto trust via pairing

type CertificateValidationResult added in v0.7.0

type CertificateValidationResult struct {
	Valid             bool
	RemoteSKI         string
	RemoteFingerprint string
	Error             error
}

CertificateValidationResult represents the result of certificate validation

type Hub

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

handling the server and all connections to remote services

func NewHub

func NewHub(hubReader api.HubReaderInterface,
	mdns api.MdnsInterface,
	port int,
	certificate tls.Certificate,
	localService *api.ServiceDetails,
	pairingConfig *api.PairingConfig,
	ringBufferPersistence api.RingBufferPersistence,
) (*Hub, error)

func (*Hub) AllowWaitingForTrust

func (h *Hub) AllowWaitingForTrust(ski string) bool

check if the user is still able to trust the connection

func (*Hub) CancelPairing added in v0.7.0

func (h *Hub) CancelPairing(identity api.ServiceIdentity)

Cancels the pairing process using ServiceIdentity

func (*Hub) DisconnectService added in v0.7.0

func (h *Hub) DisconnectService(identity api.ServiceIdentity, reason string)

Disconnect a connection using ServiceIdentity, used by a service implementation e.g. if heartbeats go wrong

func (*Hub) GeneratePairingQR added in v0.7.0

func (h *Hub) GeneratePairingQR() (string, error)

GeneratePairingQR generates a QR code string for pairing When there is no pairing service, or secret key is not defined: generates standard SHIP QR format When there is pairing service in listener mode with secret key provided: generates SHIP Pairing Service QR format

func (*Hub) GetActiveAnnouncements added in v0.7.0

func (h *Hub) GetActiveAnnouncements() []string

GetActiveAnnouncements returns the list of SHIP IDs currently being announced to

func (*Hub) GetLocalCertificateFingerprint added in v0.7.0

func (h *Hub) GetLocalCertificateFingerprint() (string, error)

GetLocalCertificateFingerprint calculates SHA-256 fingerprint of Hub's certificate

func (*Hub) GetTrustedAddCuDevice added in v0.7.0

func (h *Hub) GetTrustedAddCuDevice() *api.ServiceDetails

GetTrustedAddCuDevice returns the ServiceDetails of any trusted AddCu device, or nil if none

func (*Hub) HandleConnectionClosed

func (h *Hub) HandleConnectionClosed(connection api.ShipConnectionInterface, handshakeCompleted bool)

report closing of a connection and if handshake did complete

func (*Hub) HandleShipHandshakeStateUpdate

func (h *Hub) HandleShipHandshakeStateUpdate(ski string, state model.ShipState)

report the updated SHIP handshake state and optional error message for a SKI

func (*Hub) IsAnnouncingTo added in v0.7.0

func (h *Hub) IsAnnouncingTo(shipID string) bool

IsAnnouncingTo checks if currently announcing to a specific target device

func (*Hub) IsAutoAcceptEnabled

func (h *Hub) IsAutoAcceptEnabled() bool

check if auto accept is true

func (*Hub) IsRemoteServiceForSKIPaired

func (h *Hub) IsRemoteServiceForSKIPaired(ski string) bool

check if the SKI is paired

func (*Hub) OnPairingFailure added in v0.7.0

func (h *Hub) OnPairingFailure(remoteShipID, remoteFingerprint string, reason error)

OnPairingFailure handles pairing validation failure (implements PairingHubInterface)

func (*Hub) OnPairingSuccess added in v0.7.0

func (h *Hub) OnPairingSuccess(remoteShipID, remoteFingerprint string)

OnPairingSuccess handles successful pairing validation (implements PairingHubInterface)

func (*Hub) PairingDetailFor added in v0.7.0

func (h *Hub) PairingDetailFor(identity api.ServiceIdentity) *api.ConnectionStateDetail

Provide the current pairing state for a ServiceIdentity

func (*Hub) PairingService added in v0.7.0

func (h *Hub) PairingService() api.ShipPairingServiceInterface

PairingService returns the pairing service if available (implements HubInterface)

func (*Hub) RegisterRemoteService added in v0.7.0

func (h *Hub) RegisterRemoteService(identity api.ServiceIdentity)

Pair a remote service using ServiceIdentity

func (*Hub) ReportMdnsEntries

func (h *Hub) ReportMdnsEntries(entries map[string]*api.MdnsEntry, newEntries bool)

Process reported mDNS services

func (*Hub) ReportServiceShipID

func (h *Hub) ReportServiceShipID(ski string, shipID string)

report the ship ID provided during the handshake

func (*Hub) ServeHTTP

func (h *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles incoming HTTP connection requests

func (*Hub) ServiceFor added in v0.7.0

func (h *Hub) ServiceFor(identity api.ServiceIdentity) *api.ServiceDetails

ServiceFor returns the service details for a ServiceIdentity. If multiple entries match (which should not happen post-merge but is possible during persistence rehydration), the trusted entry wins.

func (*Hub) ServiceForIdentifier added in v0.7.0

func (h *Hub) ServiceForIdentifier(ski, fingerprint string) *api.ServiceDetails

ServiceForIdentifier finds a service by SKI and/or fingerprint. If multiple entries match (split-state from a previous bug or persistence rehydration), the trusted entry wins.

func (*Hub) ServiceForIdentifierFull added in v0.7.0

func (h *Hub) ServiceForIdentifierFull(ski, fingerprint, shipID string) *api.ServiceDetails

ServiceForIdentifierFull finds a service by any of SKI, fingerprint, or ShipID. Match semantics: an entry matches when at least one provided identifier equals the entry's value and no provided identifier directly contradicts the entry. When multiple entries match, a trusted match is preferred so a stale untrusted duplicate cannot shadow a trusted one.

func (*Hub) SetAutoAccept

func (h *Hub) SetAutoAccept(autoaccept bool)

func (*Hub) SetMaxConnections added in v0.7.0

func (h *Hub) SetMaxConnections(maxConnections int)

SetMaxConnections sets the maximum number of simultaneous connections allowed A value of 0 or less will use the default of 10

func (*Hub) SetPairingService added in v0.7.0

func (h *Hub) SetPairingService(service api.ShipPairingServiceInterface) error

SetPairingService configures the optional pairing service (called during Hub construction)

func (*Hub) SetupRemoteService added in v0.7.0

report an approved handshake by a remote device

func (*Hub) Shutdown

func (h *Hub) Shutdown()

close all connections

func (*Hub) Start

func (h *Hub) Start() error

Start the ConnectionsHub with all its services

Returns error with description of the error that cannot be recovered from

func (*Hub) StartAnnouncementTo added in v0.7.0

func (h *Hub) StartAnnouncementTo(target api.PairingTarget) error

StartAnnouncementTo starts announcing pairing to a specific target device

func (*Hub) StopAddCuReplacementTimer added in v0.7.0

func (h *Hub) StopAddCuReplacementTimer(service *api.ServiceDetails)

StopAddCuReplacementTimer stops the Device Replacement Timing Logic timer for an AddCu service.

This method cancels the 15-minute replacement timer that was started when an AddCu device disconnected. It should be called when: - The AddCu device reconnects within the 15-minute window - The service is being explicitly untrusted or removed - The hub is shutting down

The timer cancellation prevents: - Automatic trust removal due to timeout - Unnecessary pairing listener reactivation - False positive device replacement detection

Parameters: - service: The ServiceDetails of the AddCu device whose timer should be stopped

Behavior: - Only processes services with PairingType == PairingTypeAddCu - Requires a valid ShipID for timer tracking - Idempotent: safe to call multiple times for the same service - No-op if service is nil or not an AddCu device

Example:

// Stop timer when AddCu device reconnects
func (h *Hub) onDeviceReconnected(service *api.ServiceDetails) {
    h.StopAddCuReplacementTimer(service)
    log.Printf("Cancelled replacement timer for %s", service.ShipID())
}

Thread-safety: This method is thread-safe and can be called concurrently.

func (*Hub) StopAnnouncementTo added in v0.7.0

func (h *Hub) StopAnnouncementTo(shipID string) error

StopAnnouncementTo stops announcing pairing to a specific target device

func (*Hub) UnregisterConnectionIfMatch added in v0.7.0

func (h *Hub) UnregisterConnectionIfMatch(ski string, conn api.ShipConnectionInterface) bool

UnregisterConnectionIfMatch atomically unregisters a connection if it matches the provided one Returns true if the connection was unregistered, false otherwise

This method prevents race conditions during connection cleanup where a connection could be replaced between the lookup and delete operations. The previous implementation would check the connection without holding the lock, then delete it in a separate operation, allowing a new connection to be registered and accidentally deleted.

The atomic compare-and-delete ensures we only remove the specific connection instance that is being closed, not a newly registered replacement.

func (*Hub) UnregisterRemoteService added in v0.7.0

func (h *Hub) UnregisterRemoteService(identity api.ServiceIdentity)

Remove pairing using ServiceIdentity

type TestRingBufferPersistence added in v0.7.0

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

TestRingBufferPersistence implements RingBufferPersistence for testing This is a simple in-memory implementation suitable for Hub unit tests

func NewTestRingBufferPersistence added in v0.7.0

func NewTestRingBufferPersistence() *TestRingBufferPersistence

NewTestRingBufferPersistence creates a test implementation

func NewTestRingBufferPersistenceWithErrors added in v0.7.0

func NewTestRingBufferPersistenceWithErrors(loadError, saveError error) *TestRingBufferPersistence

NewTestRingBufferPersistenceWithErrors creates a test implementation that returns errors

func (*TestRingBufferPersistence) GetState added in v0.7.0

func (t *TestRingBufferPersistence) GetState() ([]api.DigestEntry, int)

func (*TestRingBufferPersistence) LoadRingBuffer added in v0.7.0

func (t *TestRingBufferPersistence) LoadRingBuffer() ([]api.DigestEntry, int, error)

LoadRingBuffer implements RingBufferPersistence

func (*TestRingBufferPersistence) SaveRingBuffer added in v0.7.0

func (t *TestRingBufferPersistence) SaveRingBuffer(entries []api.DigestEntry, nextIndex int) error

SaveRingBuffer implements RingBufferPersistence

func (*TestRingBufferPersistence) SetInitialData added in v0.7.0

func (t *TestRingBufferPersistence) SetInitialData(entries []api.DigestEntry, nextIndex int)

func (*TestRingBufferPersistence) SetLoadError added in v0.7.0

func (t *TestRingBufferPersistence) SetLoadError(err error)

Test helper methods

func (*TestRingBufferPersistence) SetSaveError added in v0.7.0

func (t *TestRingBufferPersistence) SetSaveError(err error)

Jump to

Keyboard shortcuts

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