Documentation
¶
Index ¶
- Constants
- Variables
- type AnnouncementStatus
- type ConnectionState
- type ConnectionStateDetail
- type DeviceCategoryType
- type DigestEntry
- type HMACParams
- type HubInterface
- type HubReaderInterface
- type ListenerStatus
- type MdnsEntry
- type MdnsInterface
- type MdnsPairingInterface
- type MdnsProviderInterface
- type MdnsReportInterface
- type MdnsResolveCB
- type PairingAnnouncerInterface
- type PairingConfig
- type PairingCryptoInterface
- type PairingHubInterface
- type PairingListenerInterface
- type PairingMode
- type PairingSecret
- type PairingServiceReaderInterface
- type PairingState
- type PairingTarget
- type PairingType
- type PairingValidationError
- type RemoteMdnsService
- type RemoteService
- type RingBufferPersistence
- type ServiceDetails
- func (s *ServiceDetails) AutoAccept() bool
- func (s *ServiceDetails) ConnectionStateDetail() *ConnectionStateDetail
- func (s *ServiceDetails) Copy() *ServiceDetails
- func (s *ServiceDetails) Fingerprint() string
- func (s *ServiceDetails) IPv4() string
- func (s *ServiceDetails) PairingType() PairingType
- func (s *ServiceDetails) SKI() string
- func (s *ServiceDetails) SetAutoAccept(value bool)
- func (s *ServiceDetails) SetConnectionStateDetail(detail *ConnectionStateDetail)
- func (s *ServiceDetails) SetFingerprint(fingerprint string)
- func (s *ServiceDetails) SetIPv4(ipv4 string)
- func (s *ServiceDetails) SetPairingType(t PairingType)
- func (s *ServiceDetails) SetSKI(ski string)
- func (s *ServiceDetails) SetShipID(shipid string)
- func (s *ServiceDetails) SetTrusted(trust bool)
- func (s *ServiceDetails) ShipID() string
- func (s *ServiceDetails) ToServiceIdentity() ServiceIdentity
- func (s *ServiceDetails) Trusted() bool
- type ServiceIdentity
- type ShipConnectionDataReaderInterface
- type ShipConnectionDataWriterInterface
- type ShipConnectionInfoProviderInterface
- type ShipConnectionInterface
- type ShipPairingServiceInterface
- type ShipPairingTXT
- type WebsocketDataReaderInterface
- type WebsocketDataWriterInterface
Constants ¶
const ( AlgorithmHMACSHA256 = "hmacSha256" ParTypeFPSHA256 = "fpSha256" CommandTypeAddCU = "addCu" CurveSecp256r1 = "secp256r1" CurveBrainpoolP256r1 = "brainpoolP256r1" CurveBrainpoolP384r1 = "brainpoolP384r1" )
Algorithm and parameter constants per SHIP Pairing Service specification
const ShipWebsocketSubProtocol = "ship" // SHIP 10.2: sub protocol is required for websocket connections
Variables ¶
var ( // ErrConnectionNotInitialized indicates a connection operation was attempted before initialization ErrConnectionNotInitialized = errors.New("connection not initialized") // ErrConnectionClosed indicates an operation was attempted on a closed connection ErrConnectionClosed = errors.New("connection closed") // ErrConnectionTimeout indicates a connection operation timed out ErrConnectionTimeout = errors.New("connection timeout") // ErrBufferFull indicates a message buffer is full ErrBufferFull = errors.New("buffer full") )
Connection errors
var ( // ErrInvalidCertificate indicates certificate validation failed ErrInvalidCertificate = errors.New("invalid certificate") // ErrInvalidSKI indicates an invalid or missing SKI ErrInvalidSKI = errors.New("invalid SKI") // ErrServiceNil indicates a nil service was provided ErrServiceNil = errors.New("service is not initialized") // ErrNotPaired indicates the remote service is not paired ErrNotPaired = errors.New("remote service not paired") // ErrShipIDMismatch indicates the remote reported a SHIP ID other than the one trust was // established for. The SHIP ID is the primary identifier in the trust store (SHIP Pairing // Service 10.4). ErrShipIDMismatch = errors.New("SHIP ID mismatch") )
Certificate and authentication errors
var ( // ErrInvalidHandshake indicates a handshake protocol violation ErrInvalidHandshake = errors.New("invalid handshake") // ErrInvalidProtocolMessage indicates a malformed protocol message ErrInvalidProtocolMessage = errors.New("invalid protocol message") // ErrUnsupportedPinState indicates an unsupported PIN state was received ErrUnsupportedPinState = errors.New("unsupported PIN state") )
Protocol errors
var ( // Lifecycle errors ErrServiceNotStarted = errors.New("pairing service not started") ErrServiceAlreadyStarted = errors.New("pairing service already started") ErrServiceNotStopped = errors.New("pairing service not stopped properly") ErrPairingNotEnabled = errors.New("pairing service not enabled") ErrPairingNoConfig = errors.New("pairing service configuration not set") // Configuration errors ErrInvalidSecret = errors.New("invalid pairing secret") ErrInvalidTargetSKI = errors.New("invalid target SKI") ErrInvalidTargetFingerprint = errors.New("invalid target fingerprint") // Operation errors ErrPairingAlreadyActive = errors.New("pairing already active for target") ErrPairingNotActive = errors.New("no active pairing for target") ErrListenerAlreadyActive = errors.New("pairing listener already active") ErrAnnouncerAlreadyActive = errors.New("pairing announcer already active") ErrOperationCancelled = errors.New("pairing operation cancelled") ErrDeviceAlreadyPaired = errors.New("device is already paired/trusted") // Validation errors (used by validation functions) ErrInvalidHMACDigest = errors.New("invalid HMAC digest") ErrReplayAttackDetected = errors.New("replay attack detected - digest already seen") ErrInvalidTXTRecord = errors.New("invalid TXT record structure") ErrUnsupportedTrustCurve = errors.New("unsupported trust curve") ErrUnsupportedAlgorithm = errors.New("unsupported HMAC algorithm") // Provider interface errors ErrHistoryProviderFailed = errors.New("pairing history provider failed") ErrHistoryProviderNotSet = errors.New("pairing history provider not configured") ErrHubProviderNotSet = errors.New("hub provider not configured") ErrMdnsProviderNotSet = errors.New("mDNS provider not configured") ErrCertificateProviderNotSet = errors.New("certificate provider not configured") ErrCryptoProviderNotSet = errors.New("crypto provider not configured") // Network and mDNS errors ErrMDNSAnnouncementFailed = errors.New("mDNS pairing announcement failed") ErrMDNSSearchFailed = errors.New("mDNS pairing search failed") ErrNetworkTimeout = errors.New("network operation timeout") ErrConnectionEstablishment = errors.New("connection establishment failed") // Security errors ErrSecretTooShort = errors.New("pairing secret too short (minimum 16 bytes)") ErrSecretTooLong = errors.New("pairing secret too long (maximum 128 bytes)") ErrNonceGenerationFailed = errors.New("failed to generate cryptographic nonce") ErrHMACCalculationFailed = errors.New("HMAC calculation failed") ErrTimingAttackDetected = errors.New("potential timing attack detected") )
SHIP Pairing Service errors following ship-go error pattern
var ErrConnectionNotFound = errors.New("no connection for provided SKI found")
ErrConnectionNotFound that there was no active connection for a given SKI found
var ( // ErrHubAlreadyStarted indicates Start() was called on an already-running Hub ErrHubAlreadyStarted = errors.New("hub already started") )
Hub lifecycle errors
var ErrServiceNotPaired = errors.New("the provided SKI is not paired")
ErrServiceNotPaired if the given SKI is not paired yet
Functions ¶
This section is empty.
Types ¶
type AnnouncementStatus ¶ added in v0.7.0
type AnnouncementStatus struct {
Active bool // Currently announcing
Target PairingTarget // Target device
StartTime time.Time // When announcement started
Attempts int // Number of attempts made
LastAttempt time.Time // Last attempt timestamp
Success bool // Whether pairing succeeded
Error error // Last error if any
}
AnnouncementStatus represents the status of an announcement operation
type ConnectionState ¶
type ConnectionState uint
connection state for global usage, e.g. UI
const ( ConnectionStateNone ConnectionState = iota // The initial state, when no pairing exists ConnectionStateQueued // The connection request has been started and is pending connection initialization ConnectionStateInitiated // This service initiated the connection process ConnectionStateReceivedPairingRequest // A remote service initiated the connection process ConnectionStateInProgress // The connection handshake is in progress ConnectionStateTrusted // The connection is trusted on both ends ConnectionStatePin // PIN processing, not supported right now! ConnectionStateCompleted // The connection handshake is completed from both ends ConnectionStateRemoteDeniedTrust // The remote service denied trust ConnectionStateError // The connection handshake resulted in an error )
type ConnectionStateDetail ¶
type ConnectionStateDetail struct {
// contains filtered or unexported fields
}
the connection state of a service and error if applicable
func NewConnectionStateDetail ¶
func NewConnectionStateDetail(state ConnectionState, err error) *ConnectionStateDetail
func (*ConnectionStateDetail) Error ¶
func (c *ConnectionStateDetail) Error() error
func (*ConnectionStateDetail) SetError ¶
func (c *ConnectionStateDetail) SetError(err error)
func (*ConnectionStateDetail) SetState ¶
func (c *ConnectionStateDetail) SetState(state ConnectionState)
func (*ConnectionStateDetail) State ¶
func (c *ConnectionStateDetail) State() ConnectionState
type DeviceCategoryType ¶ added in v0.7.0
type DeviceCategoryType uint
const ( // Grid Connection Point Hub (GCPH) (e.g. a control unit from the public grid operator) DeviceCategoryTypeGridConnectionHub DeviceCategoryType = 1 // Energy Management System (EMS) (device managing the electrical energy consumption/production of connected devices in the building) DeviceCategoryTypeEnergyManagementSystem DeviceCategoryType = 2 // E-mobility related device (e.g., charging station) DeviceCategoryTypeEMobility DeviceCategoryType = 3 // HVAC related device/system (e.g., heat pump) DeviceCategoryTypeHVAC DeviceCategoryType = 4 // Inverter (PV/battery/hybrid inverter) DeviceCategoryTypeInverter DeviceCategoryType = 5 // Domestic appliance (e.g., washing machine, dryer, fridge, etc.) DeviceCategoryTypeDomesticAppliance DeviceCategoryType = 6 // Metering device (e.g., smart meter or sub-meter with its own communications technology) DeviceCategoryTypeMetering DeviceCategoryType = 7 )
type DigestEntry ¶ added in v0.7.0
type DigestEntry struct {
Algorithm string // HMAC algorithm used
Digest string // HMAC digest value
Timestamp time.Time // When pairing occurred
}
DigestEntry represents a ring buffer entry per SHIP spec section 11
type HMACParams ¶ added in v0.7.0
type HMACParams struct {
Algorithm string // "hmacSha256" per spec
Nonce []byte // devZ nonce (128-bit)
TxtRecord *ShipPairingTXT // TXT record for message construction
}
HMACParams contains parameters for HMAC calculation per SHIP spec section 7
type HubInterface ¶
type HubInterface interface {
// Start the ConnectionsHub with all its services
//
// Returns error with description of the error that cannot be recovered from
Start() error
// close all connections
Shutdown()
// Enables or disables to automatically accept incoming pairing and connection requests
//
// Default: false
SetAutoAccept(bool)
// Provide the current pairing state for a ServiceIdentity
//
// Parameters:
// - identity: ServiceIdentity containing SKI, fingerprint, and/or SHIP ID
//
// returns:
// ErrNotPaired if the service is not in the (to be) paired list
// ErrNoConnectionFound if no connection for the service was found
PairingDetailFor(identity ServiceIdentity) *ConnectionStateDetail
// Pair a remote service using ServiceIdentity
//
// Parameters:
// - identity: ServiceIdentity containing SKI, fingerprint, and/or SHIP ID
//
// Note: The SHIP ID is optional, but should be provided if available.
// if provided, it will be used to validate the remote service is
// providing this SHIP ID during the handshake process and will reject
// the connection if it does not match.
RegisterRemoteService(identity ServiceIdentity)
// Unpair a remote service using ServiceIdentity
//
// Parameters:
// - identity: ServiceIdentity containing SKI, fingerprint, and/or SHIP ID
UnregisterRemoteService(identity ServiceIdentity)
// Disconnect a connection using ServiceIdentity
DisconnectService(identity ServiceIdentity, reason string)
// Cancels the pairing process for a ServiceIdentity
CancelPairing(identity ServiceIdentity)
// check if auto accept is true
IsAutoAcceptEnabled() bool
// Get Service Details for a ServiceIdentity
ServiceFor(identity ServiceIdentity) *ServiceDetails
// Get Service Details for a Service SKI and fingerprint
ServiceForIdentifier(ski string, fingerprint string) *ServiceDetails
// Sets the maximum number of simultaneous connections allowed
// A value of 0 or less will use the default of 10
SetMaxConnections(maxConnections int)
// Calculate SHA-256 fingerprint of Hub's certificate
//
// Returns:
// string:
// error: ErrInvalidCertificate if invalid or no certificate was provided
GetLocalCertificateFingerprint() (string, error)
// Generate a QR code string for pairing. The generated text will include the SHIP Pairing Service fields if
// The pairing service is available in listener mode with a secret key provided. Otherwise, standard SHIP QRCode format
// is generated.
//
// Returns:
// string:
// error: ErrInvalidSecret if the provided secret is invalid
// error: ErrSecretTooShort if the provided secret length is too short
// error: ErrInvalidCertificate if the provided certificate is invalid
GeneratePairingQR() (string, error)
// SetPairingService configures the optional pairing service
// Used by devA and devZ.
SetPairingService(service ShipPairingServiceInterface) error
// PairingService returns the pairing service
// Used by devA and devZ.
PairingService() ShipPairingServiceInterface
// Start announcing pairing to a specific target device
// Used by devZ only.
//
// Parameters:
// - target: Pairing target
StartAnnouncementTo(target PairingTarget) error
// Stop announcing pairing to a specific target device
// Used by devZ only.
//
// Parameters:
// - shipID: Target SHIP ID
StopAnnouncementTo(shipID string) error
// Return true if currently announcing to a specific target device
// Used by devZ only.
//
// Parameters:
// - shipID: Target SHIP ID
IsAnnouncingTo(shipID string) bool
// SHIP Pairing: Get Active Announcements.
// Used by devZ only.
//
// Returns: List of SHIP IDs currently being announced to
GetActiveAnnouncements() []string
// SHIP Pairing: Get the SHIP ID and Fingerprint of controlbox paired via SHIP Pairing
// Used by devA only.
//
// Returns: the ServiceDetails of any trusted AddCu device. Or nil if none
GetTrustedAddCuDevice() *ServiceDetails
}
Interface for handling the server and remote connections BREAKING CHANGE v0.8.0: All methods now use ServiceIdentity instead of string parameters
type HubReaderInterface ¶
type HubReaderInterface interface {
// report a connection to a remote service
//
// Called once the connection is complete: in SHIP connection data exchange, with the remote's
// SHIP ID verified by the access methods exchange. SetupRemoteService was called before.
RemoteServiceConnected(identity ServiceIdentity)
// report a disconnection from a remote service
//
// NOTE: The connection may not have been reported as connected before, e.g. if the remote's
// SHIP ID could not be verified after SetupRemoteService was already called.
RemoteServiceDisconnected(identity ServiceIdentity)
// set up SPINE communication with a remote service
//
// Called exactly once per connection, when it enters SHIP connection data exchange after PIN
// verification succeeded, and before RemoteServiceConnected. SPINE messages of the remote are
// passed to the returned reader from then on (SHIP IG Transport and Connectivity 2.1). The
// access methods exchange that verifies the remote's SHIP ID runs in parallel, so identity may
// not contain the SHIP ID yet; ServiceUpdated reports it once known. Return nil if SPINE data
// is not processed.
SetupRemoteService(identity ServiceIdentity, writeI ShipConnectionDataWriterInterface) ShipConnectionDataReaderInterface
// report all currently visible EEBUS services
VisibleRemoteMdnsServicesUpdated(entries []RemoteMdnsService)
// report that service information has been updated
// This includes updates to ShipID, fingerprint, or other service details discovered during handshake
ServiceUpdated(identity ServiceIdentity)
// Provides the current pairing state for the remote service
// This is called whenever the state changes and can be used to
// provide user information for the pairing/connection process
ServicePairingDetailUpdate(identity ServiceIdentity, detail *ConnectionStateDetail)
// return if the user is still able to trust the connection
AllowWaitingForTrust(identity ServiceIdentity) bool
}
Interface to pass information from the hub to the eebus service
Implemented by eebus service implementation, used by Hub BREAKING CHANGE v0.8.0: All callbacks now use ServiceIdentity instead of string parameters
type ListenerStatus ¶ added in v0.7.0
type ListenerStatus struct {
Active bool // Currently listening
StartTime time.Time // When listening started
RequestsSeen int // Number of pairing requests seen
LastRequest time.Time // Last request timestamp
Error error // Last error if any
}
ListenerStatus represents the status of a listener operation
type MdnsEntry ¶
type MdnsEntry struct {
Name string // the mDNS service name
Ski string // mandatory the certificates SKI
Identifier string // mandatory, the identifier used for SHIP ID
Path string // mandatory, the websocket path
Register bool // mandatory, wether auto accept is enabled
Brand string // optional, the brand of the device
Type string // optional, the type of the device
Model string // optional, the model of the device
Serial string // recommended, the serial number of the device
Categories []DeviceCategoryType // mandatory, the device categories of the device. Can be empty when the device does not conform to SHIP Requirements for Installation Process
Host string // mandatory, the host name
Port int // mandatory, the port for the websocket service
Addresses []net.IP // mandatory, the IP addresses used by the service
}
type MdnsInterface ¶
type MdnsInterface interface {
// Start initializes the mDNS service with the specified pairing mode.
// The callback interface receives discovered services asynchronously.
//
// Parameters:
// - pairingMode: Controls auto-accept behavior (auto, ask, deny)
// - cb: Callback interface for reporting discovered services
//
// Returns:
// - nil if mDNS service starts successfully
// - error if startup fails (e.g., network issues, permissions)
Start(pairingMode PairingMode, cb MdnsReportInterface) error
// Shutdown gracefully stops the mDNS service and cleans up resources.
// This includes stopping discovery, removing announcements, and closing network resources.
Shutdown()
// AnnounceMdnsEntry publishes this device's SHIP service via mDNS.
// Other devices can discover this service to initiate connections.
// The announcement includes device metadata and connection information.
//
// Returns:
// - nil if announcement succeeds
// - error if announcement fails (e.g., network issues)
AnnounceMdnsEntry() error
// UnannounceMdnsEntry removes this device's SHIP service announcement.
// This makes the device invisible to other devices performing discovery.
UnannounceMdnsEntry()
// SetAutoAccept updates the auto-accept flag in the mDNS announcement.
// This controls whether the device automatically accepts pairing requests.
//
// Parameters:
// - autoAccept: true to enable auto-accept, false to require manual approval
SetAutoAccept(bool)
// DeviceBrand returns the device brand for QR code generation and mDNS announcements.
// This is optional metadata that helps users identify the device.
DeviceBrand() string
// DeviceModel returns the device model for QR code generation and mDNS announcements.
// This is optional metadata that helps users identify the device.
DeviceModel() string
// DeviceSerial returns the device serial number for QR code generation and mDNS announcements.
// This is recommended metadata for unique device identification.
DeviceSerial() string
// DeviceType returns the device type string value for QR code generation and mDNS announcements.
// This is optional metadata that helps users identify the device.
DeviceType() string
// DeviceCategories returns the device categories for QR code generation and mDNS announcements.
// Categories help classify the device type per SHIP requirements for installation process.
DeviceCategories() []DeviceCategoryType
// RequestMdnsEntries triggers an immediate discovery scan for SHIP services.
// This supplements continuous discovery by forcing an immediate search.
// Discovered services are reported via the MdnsReportInterface callback.
RequestMdnsEntries()
}
MdnsInterface is implemented by mDNS and used by Hub. This interface manages SHIP service discovery and announcement via multicast DNS.
type MdnsPairingInterface ¶ added in v0.7.0
type MdnsPairingInterface interface {
// AnnouncePairingService publishes a _shippairing._tcp service with pairing data.
// This announces that the device is available for SHIP pairing using the
// provided TXT record containing HMAC-signed pairing information.
//
// Parameters:
// - txtRecord: The SHIP pairing TXT record containing pairing data and HMAC signature
//
// Returns:
// - instanceID: Unique identifier for this announcement, used for later removal
// - error: nil if announcement succeeds, error if it fails
//
// The announcement remains active until removed via UnannouncePairingService
AnnouncePairingService(txtRecord *ShipPairingTXT) (string, error)
// UnannouncePairingService removes a _shippairing._tcp announcement by instance ID.
// This stops advertising the pairing service and makes the device unavailable
// for pairing via the specified announcement.
//
// Parameters:
// - instanceID: The unique identifier returned by AnnouncePairingService
//
// Returns:
// - nil if unannouncement succeeds
// - error if the instance ID is invalid or unannouncement fails
UnannouncePairingService(instanceID string) error
// SearchPairingServices discovers _shippairing._tcp services on the network.
// This method searches for devices advertising pairing availability and
// calls the callback for each discovered service.
//
// Parameters:
// - callback: Function called for each discovered pairing service
// Returns true to continue searching, false to stop
//
// Returns:
// - nil if search completes successfully
// - error if search cannot be initiated or fails
//
// The search runs until the callback returns false or an error occurs
SearchPairingServices(callback func(*ShipPairingTXT) bool) error
// RequestPairingEntries returns a snapshot of the currently-live
// _shippairing._tcp records from the local browse cache, keyed by service
// name. It performs no network operation: the cache is maintained
// continuously by the provider's browser (records enter on announcements
// and leave on goodbyes/TTL expiry).
//
// Returns:
// - map[string]*ShipPairingTXT: Currently live pairing records
// - error: nil if request succeeds, error if the mDNS manager is not started
RequestPairingEntries() (map[string]*ShipPairingTXT, error)
// IsPairingServiceAnnounced checks if any pairing service is currently announced.
// This helps prevent duplicate announcements and provides status information.
//
// Returns:
// - true if at least one _shippairing._tcp service is currently announced
// - false if no pairing services are announced
IsPairingServiceAnnounced() bool
}
MdnsPairingInterface provides SHIP Pairing Service functionality via mDNS. This interface is implemented by MdnsManager when pairing service support is needed. It handles the _shippairing._tcp service type for device pairing operations.
type MdnsProviderInterface ¶
type MdnsProviderInterface interface {
// Start initializes the mDNS provider with the specified configuration.
// This establishes the connection to the underlying mDNS system and begins
// monitoring for service announcements.
//
// Parameters:
// - pairingMode: Controls auto-accept behavior for discovered services
// - autoReconnect: Whether to automatically reconnect on network changes
// - cb: Callback function for reporting discovered/removed services
//
// Returns:
// - true if the provider starts successfully
// - false if startup fails (e.g., mDNS daemon unavailable, permissions)
Start(pairingMode PairingMode, autoReconnect bool, cb MdnsResolveCB) bool
// Shutdown gracefully stops the mDNS provider and releases system resources.
// This disconnects from the mDNS system and stops all service monitoring.
Shutdown()
// AnnounceService publishes a service announcement via the mDNS provider.
// This is used for both regular SHIP services and SHIP Pairing Services.
// The service remains announced until explicitly removed.
//
// Parameters:
// - serviceType: The service type (e.g., "_ship._tcp", "_shippairing._tcp")
// - serviceName: The unique service instance name
// - port: The TCP port where the service is available
// - txt: Array of TXT record strings containing service metadata
//
// Returns:
// - instanceID: Unique identifier for this announcement
// - error: nil if announcement succeeds, error if it fails
AnnounceService(serviceType, serviceName string, port int, txt []string) (string, error)
// UnannounceService removes a service announcement by instance ID.
// This stops advertising the service and makes it unavailable to other devices.
//
// Parameters:
// - instanceID: The unique identifier returned by AnnounceService
//
// Returns:
// - nil if unannouncement succeeds
// - error if the instance ID is invalid or unannouncement fails
UnannounceService(instanceID string) error
}
MdnsProviderInterface is implemented by mDNS providers and used by MdnsManager. This interface abstracts the underlying mDNS implementation (Avahi, Zeroconf, etc.) and provides platform-specific mDNS functionality.
type MdnsReportInterface ¶
type MdnsReportInterface interface {
// ReportMdnsEntries delivers discovered SHIP services to the Hub.
// This method is called when mDNS discovery finds new services or when
// existing services are updated or removed.
//
// Parameters:
// - entries: Map of discovered services keyed by service name
// - newEntries: true if these are newly discovered services, false for updates
//
// The Hub uses this information to initiate connections to discovered devices
// and manage the service registry.
ReportMdnsEntries(entries map[string]*MdnsEntry, newEntries bool)
}
MdnsReportInterface is implemented by Hub and used by mDNS. This interface receives discovered SHIP services from mDNS discovery.
type MdnsResolveCB ¶
type MdnsResolveCB func(elements map[string]string, name, host, serviceType string, addresses []net.IP, port int, remove bool)
MdnsResolveCB is a callback function used by mDNS providers to report service changes. This callback is invoked when services are discovered, updated, or removed from the network. It provides detailed information about each service event for processing by the mDNS manager.
Parameters:
- elements: TXT record key-value pairs containing service metadata
- name: The service instance name (e.g., "Device-ABC._ship._tcp.local")
- host: The hostname where the service is available
- serviceType: The service type (e.g., "_ship._tcp", "_shippairing._tcp")
- addresses: List of IP addresses where the service can be reached
- port: The TCP port number where the service is listening
- remove: true if the service was removed, false if discovered/updated
This callback is called asynchronously from network discovery threads and should handle the information efficiently without blocking.
type PairingAnnouncerInterface ¶ added in v0.7.0
type PairingAnnouncerInterface interface {
// Announce sends a pairing request to the specified target device via mDNS.
// This method implements the devZ (requesting device) role in SHIP pairing.
// The announcement includes HMAC-signed pairing data and runs until pairing
// succeeds, fails, or is cancelled.
//
// Parameters:
// - target: The target device information including SKI, fingerprint, and pairing secret
//
// Returns:
// - nil if announcement starts successfully (pairing may still be in progress)
// - error if announcement cannot be started or target is invalid
Announce(target PairingTarget) error
// StopAnnouncement cancels any active pairing announcement.
// This method safely stops the announcement process and cleans up resources.
// Returns an error if no announcement is active or stopping fails.
StopAnnouncement() error
// GetAnnouncementStatus returns the current status of any active announcement.
// Provides information about announcement progress, attempts, and any errors.
GetAnnouncementStatus() AnnouncementStatus
}
PairingAnnouncerInterface - Interface for devZ (announcer) operations
type PairingConfig ¶ added in v0.7.0
type PairingConfig struct {
// Core configuration (required)
Mode PairingMode // Operating mode: Off, Listener, Announcer, Both
Secret PairingSecret // 16-byte shared secret for HMAC validation (from QR code SPSEC field)
// AnnouncementLifetimeTimeout defines how long a continuous, uninterrupted
// SHIP connection must be maintained before the corresponding announcement
// is removed. Defaults to 15 minutes per spec if zero.
AnnouncementLifetimeTimeout time.Duration
}
PairingConfig defines pairing behavior
func NewPairingConfig ¶ added in v0.7.0
func NewPairingConfig(mode PairingMode, secret PairingSecret) *PairingConfig
NewPairingConfig creates a new pairing configuration with the specified mode and secret
func (*PairingConfig) Validate ¶ added in v0.7.0
func (c *PairingConfig) Validate() error
Validate validates the pairing configuration
type PairingCryptoInterface ¶ added in v0.7.0
type PairingCryptoInterface interface {
// GenerateNonce creates a cryptographically secure 128-bit nonce.
// The nonce is used in HMAC calculation to prevent replay attacks
// and ensure each pairing request is unique per SHIP specification.
//
// Returns:
// - 16-byte (128-bit) cryptographically random nonce
// - error if secure random number generation fails
//
// Security: Must use a cryptographically secure random number generator
GenerateNonce() ([]byte, error)
// CalculateDigest computes HMAC-SHA256 digest for SHIP pairing validation.
// Implements the HMAC calculation specified in SHIP Pairing Service section 7.
// The digest is used to prove knowledge of the shared pairing secret.
//
// Parameters:
// - secret: The shared pairing secret (from QR code SPSEC field)
// - params: HMAC parameters including algorithm, nonce, and TXT record data
//
// Returns:
// - 32-byte HMAC-SHA256 digest
// - error if HMAC calculation fails
//
// Security: Uses HMAC-SHA256 with proper message construction per SHIP spec
CalculateDigest(secret PairingSecret, params HMACParams) ([]byte, error)
// ValidateDigest verifies an HMAC digest using constant-time comparison.
// Prevents timing attacks by ensuring validation always takes the same time
// regardless of where the digests differ.
//
// Parameters:
// - secret: The shared pairing secret used for validation
// - params: HMAC parameters used to recalculate the expected digest
// - expectedDigest: The digest to validate against
//
// Returns:
// - nil if digests match (validation successful)
// - error if digests don't match or calculation fails
//
// Security: Uses constant-time comparison to prevent timing attacks
ValidateDigest(secret PairingSecret, params HMACParams, expectedDigest []byte) error
}
PairingCryptoInterface - Interface for HMAC operations Implemented by crypto manager, used by PairingService
type PairingHubInterface ¶ added in v0.7.0
type PairingHubInterface interface {
// OnPairingSuccess is called when SHIP pairing completes successfully.
// The hub should add the device to its trust store and enable connections.
// This callback indicates that HMAC validation passed and the device should
// be automatically trusted for SHIP connections.
//
// Parameters:
// - remoteShipID: The SHIP ID of the successfully paired device
// - remoteFingerprint: SHA-256 fingerprint of the device's certificate
OnPairingSuccess(remoteShipID, remoteFingerprint string)
// OnPairingFailure is called when SHIP pairing fails.
// The hub should not trust the device and may log the failure for security monitoring.
// Common failure reasons include invalid HMAC, replay attacks, or network errors.
//
// Parameters:
// - remoteShipID: The SHIP ID of the device that failed pairing
// - remoteFingerprint: SHA-256 fingerprint of the device's certificate
// - reason: The specific error that caused the pairing failure
OnPairingFailure(remoteShipID, remoteFingerprint string, reason error)
// GetTrustedAddCuDevice returns the ServiceDetails of any trusted AddCu device, or nil if none.
// This is used by the pairing listener to check if the trust slot is occupied
// before accepting new AddCu pairing requests.
//
// Returns:
// - ServiceDetails : The ServiceDetails of the AddCu trusted device, or nil if none.
GetTrustedAddCuDevice() *ServiceDetails
}
PairingHubInterface - Interface for Hub integration Implemented by Hub, used by PairingService
type PairingListenerInterface ¶ added in v0.7.0
type PairingListenerInterface interface {
// StartListening begins listening for SHIP pairing requests via mDNS.
// This method implements the devA (target device) role in SHIP pairing.
// The listener validates incoming pairing requests against the provided secret
// and automatically accepts valid requests.
//
// Parameters:
// - ctx: Context for cancellation control (listener stops when context is cancelled)
// - secret: The pairing secret used to validate incoming HMAC signatures
//
// Returns:
// - nil if listening starts successfully
// - error if listening cannot be started or secret is invalid
//
// Behavior:
// - Runs until context is cancelled, pairing succeeds, or an error occurs
// - Automatically validates HMAC signatures from announcing devices
// - Triggers pairing success/failure callbacks via PairingServiceReaderInterface
StartListening(ctx context.Context, secret PairingSecret) error
// StopListening cancels any active pairing listener.
// This method safely stops the listening process and cleans up resources.
// Returns an error if no listener is active or stopping fails.
StopListening() error
// GetListenerStatus returns the current status of the pairing listener.
// Provides information about listening activity, requests seen, and any errors.
GetListenerStatus() ListenerStatus
// ProcessPendingEntries evaluates a batch of pairing records through the
// same validation pipeline as live discovery.
//
// Parameters:
// - entries: Map of service names to ShipPairingTXT records to process
//
// Returns:
// - error if processing fails (nil for successful processing)
//
// Behavior:
// - Processes each entry through the same validation pipeline as live discovery
// - Stops processing after first successful pairing (SHIP spec behavior)
// - Handles invalid entries gracefully, continuing with remaining entries
// - No-op if listener is not active or entries is nil/empty
//
// Deprecated: StartListening evaluates the currently-live mDNS records
// automatically; external callers no longer need to replay them.
ProcessPendingEntries(entries map[string]*ShipPairingTXT) error
}
PairingListenerInterface - Interface for devA (listener) operations
type PairingMode ¶ added in v0.7.0
type PairingMode int
PairingMode defines how the Hub should handle SHIP pairing
const ( // PairingModeOff - No automatic pairing (basic SHIP connections only) PairingModeOff PairingMode = iota // PairingModeListener - Hub automatically listens for incoming pairing requests // Use this for devices that should be discoverable and accept pairing from other devices PairingModeListener // PairingModeAnnouncer - Hub automatically announces pairing to discovered devices // Use this for devices that should initiate pairing with other devices PairingModeAnnouncer // PairingModeBoth - Support both announcing and listening for pairing requests // Use this for devices that should both initiate and accept pairing PairingModeBoth )
type PairingSecret ¶ added in v0.7.0
type PairingSecret []byte
PairingSecret represents a secure pairing secret with explicit clearing
func (PairingSecret) Clear ¶ added in v0.7.0
func (s PairingSecret) Clear()
Clear securely overwrites the secret in memory with zeros. This method should be called when the secret is no longer needed to prevent sensitive data from remaining in memory. Uses explicit zeroing to ensure the compiler doesn't optimize away the operation.
Example usage:
defer secret.Clear()
func (PairingSecret) Equal ¶ added in v0.7.0
func (s PairingSecret) Equal(other PairingSecret) bool
Equal compares two pairing secrets using constant-time comparison. This prevents timing attacks where an attacker could determine the secret by measuring how long the comparison takes. The comparison always takes the same amount of time regardless of where the secrets differ.
Parameters:
- other: The PairingSecret to compare against
Returns:
- true if the secrets are identical, false otherwise
Security: Uses bitwise XOR to ensure constant-time execution
func (PairingSecret) IsValidLength ¶ added in v0.7.0
func (s PairingSecret) IsValidLength() bool
IsValidLength reports whether the secret length is acceptable for SHIP pairing. This implementation supports 16 bytes (raw 128-bit secret)
func (PairingSecret) String ¶ added in v0.7.0
func (s PairingSecret) String() string
String returns "[REDACTED]" to prevent accidental exposure of sensitive data. This ensures that if a PairingSecret is accidentally included in log messages, error strings, or debug output, the actual secret value will not be revealed. This follows security best practices for handling sensitive data in Go.
Returns:
- Always returns the string "[REDACTED]"
type PairingServiceReaderInterface ¶ added in v0.7.0
type PairingServiceReaderInterface interface {
// Called when service is automatically trusted via SHIP pairing
// The identity parameter contains all necessary device identification information
ServiceAutoTrusted(identity ServiceIdentity)
// Called when SHIP pairing fails for a service
// The identity parameter contains device identification, reason explains the failure
ServiceAutoTrustFailed(identity ServiceIdentity, reason error)
// ServiceAutoTrustRemoved is called when device trust is automatically
// removed as part of the Device Replacement Timing Logic feature.
//
// This callback is triggered in two scenarios:
//
// 1. **15-minute timeout expired**: When an AddCu device disconnects and doesn't
// reconnect within 15 minutes, the system assumes it has been replaced.
// The trust is removed and the pairing listener is reactivated.
// Reason format: "AddCu replacement timeout for device <shipID>"
//
// 2. **New pairing replaces existing trust**: When a new device pairs using the
// same pairing credentials, it automatically replaces the trust of the
// previously paired device.
// Reason format: "Replaced by new device pairing from <shipID>"
//
// Parameters:
// - identity: The ServiceIdentity of the device whose trust was removed
// - reason: Human-readable explanation of why trust was removed
//
// Example implementation:
//
// func (r *MyReader) ServiceAutoTrustRemoved(identity api.ServiceIdentity, reason string) {
// log.Printf("Device trust removed: SKI=%s, ShipID=%s, Reason=%s",
// identity.SKI, identity.ShipID, reason)
//
// // Update UI to show device is no longer trusted
// updateDeviceStatus(identity.ShipID, "untrusted")
//
// // Clean up any device-specific resources
// cleanupDeviceResources(identity.SKI)
//
// // Optionally notify user
// if strings.Contains(reason, "timeout") {
// notifyUser("Device %s disconnected and timed out", identity.ShipID)
// } else if strings.Contains(reason, "Replaced") {
// notifyUser("Device %s was replaced by a new device", identity.ShipID)
// }
// }
ServiceAutoTrustRemoved(identity ServiceIdentity, reason string)
}
PairingServiceReaderInterface - Callback interface for pairing events Applications implement this to receive pairing event notifications
type PairingState ¶ added in v0.7.0
type PairingState uint
PairingState represents the current state of a pairing operation
const ( PairingStateNone PairingState = iota // No pairing activity PairingStateListening // devA listening for announcements PairingStateAnnouncing // devZ announcing to target PairingStateValidating // Validating received pairing data PairingStateCompleted // Pairing completed successfully PairingStateRejected // Pairing rejected (invalid HMAC, etc.) PairingStateTimedOut // Pairing timed out PairingStateError // Pairing encountered error )
type PairingTarget ¶ added in v0.7.0
type PairingTarget struct {
SKI string // Target device SKI
Fingerprint string // Target device certificate fingerprint (SHA-256)
ShipID string // Target device SHIP ID (for connection)
Secret []byte `json:"-"` // Secret for pairing (from QR code SPSEC field), excluded from JSON serialization
}
PairingTarget represents a target device for pairing announcements
func (*PairingTarget) Clear ¶ added in v0.7.0
func (p *PairingTarget) Clear()
func (*PairingTarget) IsEmpty ¶ added in v0.7.0
func (p *PairingTarget) IsEmpty() bool
type PairingType ¶ added in v0.7.0
type PairingType int
PairingType defines the type of pairing mechanism used for a service.
The pairing type determines how trust is established and managed, particularly for the Device Replacement Timing Logic feature introduced in SHIP Pairing Service.
Example usage:
// Check if a service uses AddCu pairing
if service.PairingType() == api.PairingTypeAddCu {
// This device was paired via SHIP Pairing Service
// and is subject to replacement timing logic
}
// Set pairing type for a new AddCu device
service.SetPairingType(api.PairingTypeAddCu)
const ( // PairingTypeDefault represents traditional SHIP 1.0.1 pairing. // Services with this type use manual trust establishment and are not // subject to automatic replacement timing logic. PairingTypeDefault PairingType = iota // PairingTypeAddCu represents SHIP Pairing Service with control unit. // Services with this type: // - Are automatically trusted via SHIP Pairing Service // - Are subject to 15-minute replacement timing logic // - May be automatically untrusted if replaced by another device // - Trigger timer-based pairing listener reactivation // // The replacement timing logic ensures that when an AddCu device disconnects, // the system waits 15 minutes for a potential replacement device before // reactivating the pairing listener. If the device reconnects within this // window, the timer is cancelled. PairingTypeAddCu )
type PairingValidationError ¶ added in v0.7.0
Custom error types for better error handling
func NewPairingFieldValidationError ¶ added in v0.7.0
func NewPairingFieldValidationError(field, message string) *PairingValidationError
NewPairingFieldValidationError creates a new PairingValidationError for a specific field. This constructor is used when the validation error relates to a particular field in the pairing data structure, providing more context for debugging and error handling.
Parameters:
- field: The name of the field that failed validation (e.g., "trustCurve", "digest")
- message: Human-readable description of why the field validation failed
Returns:
- A new PairingValidationError instance with field-specific error information
Example usage:
return NewPairingFieldValidationError("trustNonce", "nonce must be 32 hex characters")
func NewPairingValidationError ¶ added in v0.7.0
func NewPairingValidationError(message string) *PairingValidationError
NewPairingValidationError creates a new PairingValidationError with a general validation message. This constructor is used for validation errors that don't relate to a specific field.
Parameters:
- message: Human-readable description of the validation error
Returns:
- A new PairingValidationError instance with the specified message
Example usage:
return NewPairingValidationError("unsupported algorithm: " + alg)
func (*PairingValidationError) Error ¶ added in v0.7.0
func (e *PairingValidationError) Error() string
type RemoteMdnsService ¶ added in v0.7.0
type RemoteMdnsService struct {
Name string `json:"name"`
Ski string `json:"ski"`
ShipID string `json:"shipID"`
Brand string `json:"brand"`
Type string `json:"type"`
Model string `json:"model"`
Serial string `json:"serial"`
Categories []DeviceCategoryType `json:"categories"`
Addresses []net.IP `json:"addresses"` // addresses the service resolved to, or the configured IPv4 of a known service
}
RemoteMdnsService represents a SHIP service announced via mDNS
type RemoteService ¶
type RingBufferPersistence ¶ added in v0.7.0
type RingBufferPersistence interface {
// LoadRingBuffer restores the ring buffer state from persistent storage.
// Called once during Hub initialization to restore previous state.
//
// Returns:
// - entries: Array of DigestEntry (may be larger than used entries)
// - nextIndex: Index where next entry will be written (0 to len(entries)-1)
// - error: Any error loading from storage
//
// For new installations or empty storage:
// - Return empty slice and nextIndex=0
// - Do not return an error for "no data found" cases
//
// Error cases that should return errors:
// - Storage system unavailable
// - Corrupted data that cannot be parsed
// - Permission denied accessing storage
//
// Example implementation patterns:
// File-based: Load JSON/GZIP from file
// Database: SELECT entries, next_index FROM ring_buffer WHERE device_id = ?
// Memory: Return in-memory state (for testing only)
LoadRingBuffer() ([]DigestEntry, int, error)
// SaveRingBuffer persists the current ring buffer state to storage.
// Called after each successful pairing to ensure replay protection is maintained.
//
// Parameters:
// - entries: Complete ring buffer array (may contain unused entries with empty Algorithm)
// - nextIndex: Index where next entry will be written (0 to len(entries)-1)
//
// Implementation requirements:
// - Must be atomic (either fully saves or fails completely)
// - Should handle concurrent calls gracefully
// - Must maintain consistency even if application crashes during save
//
// Error handling:
// - Return error if save fails for any reason
// - Do not partially update storage
// - Library will log errors but continue operation
//
// Example implementation patterns:
// File-based: Write to temp file, then atomic rename
// Database: Use transactions for atomic updates
// Memory: Update in-memory state (for testing only)
SaveRingBuffer(entries []DigestEntry, nextIndex int) error
}
RingBufferPersistence - Application-implemented storage interface for SHIP pairing ring buffer Applications implement this to provide persistent storage for the ring buffer state per SHIP Pairing Service specification section 11. The library handles all ring buffer logic internally.
Thread Safety: Implementations must be thread-safe as methods may be called concurrently. Storage Requirements: Data must persist across application restarts per SHIP specification.
type ServiceDetails ¶
type ServiceDetails struct {
// contains filtered or unexported fields
}
generic service details about the local or any remote service
func NewServiceDetails ¶
func NewServiceDetails(ski, fingerprint, shipid string) (*ServiceDetails, error)
NewServiceDetails creates a new ServiceDetails record.
This function initializes a new ServiceDetails instance with the provided SKI, fingerprint, and ship ID. It sets the initial connection state to ConnectionStateNone and the pairing type to PairingTypeDefault.
Parameters:
- ski: The SKI (Subject Key Identifier) of the service. Required if fingerprint is not provided
- fingerprint: The expected certificate fingerprint of the service. Required if SKI is not provided
- shipid: The SHIP ID of the service. Required if fingerprint is provided and ski is not provided
Returns the new new ServiceDetails. If there is an error, nil will be returned with an error
func (*ServiceDetails) AutoAccept ¶
func (s *ServiceDetails) AutoAccept() bool
AutoAccept returns whether the service should or does automatically accept connections.
func (*ServiceDetails) ConnectionStateDetail ¶
func (s *ServiceDetails) ConnectionStateDetail() *ConnectionStateDetail
ConnectionStateDetail returns the current connection state details for this service
func (*ServiceDetails) Copy ¶ added in v0.7.0
func (s *ServiceDetails) Copy() *ServiceDetails
Copy creates a deep copy of the ServiceDetails instance.
func (*ServiceDetails) Fingerprint ¶ added in v0.7.0
func (s *ServiceDetails) Fingerprint() string
Fingerprint returns the expected certificate fingerprint of the service.
This fingerprint is used for additional certificate validation and is optional. If not set, the service will not perform fingerprint validation.
func (*ServiceDetails) IPv4 ¶
func (s *ServiceDetails) IPv4() string
IPv4 returns a manually set IPv4 address of the service.
func (*ServiceDetails) PairingType ¶ added in v0.7.0
func (s *ServiceDetails) PairingType() PairingType
PairingType returns the pairing type for this service.
The pairing type indicates how this service was paired and determines which trust management rules apply. AddCu devices are subject to automatic replacement timing logic.
Returns: - PairingTypeDefault: Traditional SHIP pairing (manual trust) - PairingTypeAddCu: SHIP Pairing Service (automatic trust with replacement logic)
Example:
if service.PairingType() == api.PairingTypeAddCu {
// Handle AddCu-specific logic
log.Printf("Device %s is an AddCu device", service.ShipID())
}
func (*ServiceDetails) SKI ¶
func (s *ServiceDetails) SKI() string
SKI returns the expected service's SKI (Subject Key Identifier).
This SKI is used to uniquely identify the service within the SHIP network and is required for all service interactions.
func (*ServiceDetails) SetAutoAccept ¶
func (s *ServiceDetails) SetAutoAccept(value bool)
SetAutoAccept sets whether the service should automatically accept connections.
func (*ServiceDetails) SetConnectionStateDetail ¶
func (s *ServiceDetails) SetConnectionStateDetail(detail *ConnectionStateDetail)
SetConnectionStateDetail sets the current connection state details for this service
Should only be used internally!
func (*ServiceDetails) SetFingerprint ¶ added in v0.7.0
func (s *ServiceDetails) SetFingerprint(fingerprint string)
SetFingerprint sets the expected certificate fingerprint of the service.
func (*ServiceDetails) SetIPv4 ¶
func (s *ServiceDetails) SetIPv4(ipv4 string)
SetIPv4 sets an additional IPv4 address of the service to be used for connection
This is used as an alternative IP address to attempt for cases where the device doesn't provide one and the user can provide on instead
func (*ServiceDetails) SetPairingType ¶ added in v0.7.0
func (s *ServiceDetails) SetPairingType(t PairingType)
SetPairingType sets the pairing type for this service.
This should be called when a device is paired via SHIP Pairing Service to enable the Device Replacement Timing Logic. The pairing type affects: - Whether the 15-minute replacement timer is started on disconnect - How trust is managed for this service - Whether automatic trust removal can occur
Parameters: - t: The pairing type to set (PairingTypeDefault or PairingTypeAddCu)
Example:
// Mark a device as paired via SHIP Pairing Service service.SetPairingType(api.PairingTypeAddCu) service.SetTrusted(true)
func (*ServiceDetails) SetSKI ¶ added in v0.7.0
func (s *ServiceDetails) SetSKI(ski string)
SetSKI sets the expected service's SKI (Subject Key Identifier).
This is useful for internal use when the fingerprint is provided and we got the matching SKI
func (*ServiceDetails) SetShipID ¶
func (s *ServiceDetails) SetShipID(shipid string)
SetShipID sets the expected service's SHIP ID.
func (*ServiceDetails) SetTrusted ¶
func (s *ServiceDetails) SetTrusted(trust bool)
SetTrusted sets whether the service is trusted.
Should only be used internally!
func (*ServiceDetails) ShipID ¶
func (s *ServiceDetails) ShipID() string
ShipID returns the expected service's SHIP ID.
func (*ServiceDetails) ToServiceIdentity ¶ added in v0.7.0
func (s *ServiceDetails) ToServiceIdentity() ServiceIdentity
ToServiceIdentity converts a ServiceDetails to a ServiceIdentity object. This is useful for interfacing with public APIs that use ServiceIdentity.
func (*ServiceDetails) Trusted ¶
func (s *ServiceDetails) Trusted() bool
Trusted returns whether the service is trusted.
type ServiceIdentity ¶ added in v0.7.0
type ServiceIdentity struct {
// Certificate public key identification of the service
//
// This is mandatory for SHIP 1.0.1/1.1 services, and not provided initially when
// a service was paired using SHIP Pairing.
//
// Note: This needs to be persisted in the applications trust store and provided with
// RegisterRemoteService call if known!
SKI string `json:"ski"`
// Certificate fingerprint of the service
//
// This is used for certificate validation, and optional for now.
// It will be provided instead of SKI when a service is paired using SHIP Pairing.
//
// Note: This needs to be persisted in the applications trust store and provided with
// RegisterRemoteService call if known!
Fingerprint string `json:"fingerprint"`
// shipID is the SHIP identifier of the service
//
// This is mandatory for SHIP 1.0.1/1.1 services, and not provided initially when
// a service was paired using SHIP Pairing.
//
// Note: This needs to be persisted in the applications trust store and provided with
// RegisterRemoteService call if known!
ShipID string `json:"shipID"`
// The pairing type for this service
//
// By default this is set to PairingTypeDefault (0). For control units
// paired using SHIP Pairing this will be set to PairingTypeAddCu (1)
//
// Note: This needs to be persisted in the applications trust store and provided with
// RegisterRemoteService call!
PairingType PairingType `json:"pairingType"`
// This is the IPv4 address of the device running the service
//
// This is optional only needed when this runs with
// zeroconf as mDNS and the remote device is using the latest
// avahi version and thus zeroconf can sometimes not detect
// the IPv4 address and not initiate a connection
//
// Only relevant with RegisterRemoteService, shall be ignored otherwise
IPv4 string `json:"ipv4,omitempty"`
}
ServiceIdentity represents the public API struct for service identity information. This is a simple data container used for external APIs and JSON/YAML serialization.
func NewServiceIdentity ¶ added in v0.7.0
func NewServiceIdentity(ski, fingerprint, shipid string) ServiceIdentity
NewServiceIdentity creates a new ServiceIdentity with validation.
Parameters:
- ski: The SKI (Subject Key Identifier) of the service. Required if fingerprint is not provided
- fingerprint: The expected certificate fingerprint of the service. Required if SKI is not provided
- shipid: The SHIP ID of the service. Required if fingerprint is provided and ski is not provided
Returns zero value if validation fails (replaces nil return with empty struct).
func SKIToServiceIdentity ¶ added in v0.7.0
func SKIToServiceIdentity(ski string) ServiceIdentity
SKIToServiceIdentity creates a minimal ServiceIdentity from just an SKI. This is a helper for converting SKI-only callbacks to ServiceIdentity format.
func (ServiceIdentity) IsZero ¶ added in v0.7.0
func (s ServiceIdentity) IsZero() bool
IsZero returns true if ServiceIdentity is empty (replaces nil checks).
func (ServiceIdentity) String ¶ added in v0.7.0
func (s ServiceIdentity) String() string
String returns a string representation of the ServiceIdentity. Shows the most relevant identifying information based on what's available.
func (ServiceIdentity) ToServiceDetails ¶ added in v0.7.0
func (s ServiceIdentity) ToServiceDetails() (*ServiceDetails, error)
ToServiceDetails converts a ServiceIdentity to a ServiceDetails object. This is useful for interfacing with internal APIs that use ServiceDetails.
type ShipConnectionDataReaderInterface ¶
type ShipConnectionDataReaderInterface interface {
HandleShipPayloadMessage(message []byte)
}
Used to pass an incoming SPINE message from a SHIP connection to the proper DeviceRemote
Implemented by spine DeviceRemote, used by ShipConnection
type ShipConnectionDataWriterInterface ¶
type ShipConnectionDataWriterInterface interface {
WriteShipMessageWithPayload(message []byte)
}
Used to pass an outgoing SPINE message from a DeviceLocal to the SHIP connection
Implemented by ShipConnection, used by spine DeviceLocal
type ShipConnectionInfoProviderInterface ¶
type ShipConnectionInfoProviderInterface interface {
// IsRemoteServiceForSKIPaired checks if a remote service is trusted and should be allowed to connect.
//
// This method is called during SHIP handshake to determine if the remote device
// is already paired/trusted. Services can be trusted through manual pairing,
// SHIP Pairing Service, or auto-accept configuration.
//
// Parameters:
// - ski: The SKI of the remote service
//
// Returns:
// - bool: true if service is trusted, false if trust confirmation required
//
// Used during: SHIP handshake Hello phase for trust validation
IsRemoteServiceForSKIPaired(ski string) bool
// IsAutoAcceptEnabled returns whether the Hub is configured to automatically accept connections.
//
// This method indicates if the Hub will automatically trust new connection
// requests without user confirmation. Used during handshake to determine
// if manual approval is required.
//
// Returns:
// - bool: true if auto-accept is enabled, false if manual approval required
IsAutoAcceptEnabled() bool
// HandleConnectionClosed reports that a SHIP connection has been closed.
//
// This method is called when a SHIP connection is terminated, either gracefully
// or due to error conditions. It allows the Hub to clean up connection state
// and potentially trigger reconnection attempts.
//
// Parameters:
// - ShipConnectionInterface: The connection that was closed
// - bool: true if handshake completed before closure, false otherwise
//
// Used when: Connection terminates for any reason
HandleConnectionClosed(ShipConnectionInterface, bool)
// ReportServiceShipID notifies about the reported shipid, if it was unknown before.
//
// This method is called when SHIP ID is provided by the remote service and it
// wasn't known before the ship connection.
//
// Parameters:
// - ski: SKI of the remote service
// - shipID: SHIP ID of the remote service
//
// Used during: SHIP handshake when service information is discovered/updated
ReportServiceShipID(ski string, shipID string)
// AllowWaitingForTrust determines if the connection should continue waiting for user trust confirmation.
//
// This method is called periodically during connection establishment when a
// remote service is not automatically trusted and requires user confirmation.
// It allows applications to implement timeout policies or cancel pending connections.
//
// Parameters:
// - ski: SKI of the remote service
//
// Returns:
// - bool: true to continue waiting, false to abort the connection
//
// Used during: SHIP handshake when waiting for manual trust confirmation
//
// Example implementation:
// return time.Since(connectionStart) < 30*time.Second // 30-second timeout
AllowWaitingForTrust(ski string) bool
// HandleServiceHandshakeStateUpdate reports SHIP handshake state changes.
//
// This method is called whenever the SHIP handshake progresses through its
// various states, providing applications with real-time handshake monitoring
// and error reporting capabilities.
//
// Parameters:
// - ski: SKI of the remote service
// - state: Current SHIP handshake state information
//
// Used during: All phases of SHIP handshake for progress monitoring
//
// Example states: CmiStateInitStart, HelloStateOk, ProtocolStateOk, AccessStateOk
HandleShipHandshakeStateUpdate(ski string, state model.ShipState)
// SetupRemoteService sets up communication with a newly connected remote device.
//
// This method is called exactly once per connection, when it enters SHIP connection
// data exchange (SHIP 13.4.5) after PIN verification succeeded. From then on the remote
// device may send SPINE messages, and they are passed to the returned reader immediately
// (SHIP IG Transport and Connectivity 2.1). writeI can be used immediately as well.
//
// The access methods exchange runs in parallel and has not completed at this point. It
// verifies the remote's SHIP ID, so for a remote whose SHIP ID was not known before the
// connection, the SHIP ID is not available yet. If the verification fails, or the remote
// does not answer within 60 seconds, the connection is terminated and HandleConnectionClosed
// reports it without a completed handshake.
//
// Parameters:
// - ski: SKI of the remote device
// - writeI: Writer interface for sending messages to the remote device
//
// Returns:
// - ShipConnectionDataReaderInterface: Reader interface for receiving messages, or nil if
// the application does not process SPINE messages on this connection
//
// Used when: The connection enters SHIP connection data exchange
SetupRemoteService(ski string, writeI ShipConnectionDataWriterInterface) ShipConnectionDataReaderInterface
}
ShipConnectionInfoProviderInterface provides service information and coordination for SHIP connections.
This interface enables SHIP connections to interact with the Hub's service management system during the connection lifecycle. It provides trust validation, state reporting, and device setup coordination based on the SHIP Connections unique SKI.
Implemented by: Hub Used by: ShipConnection during handshake and connection lifecycle events
type ShipConnectionInterface ¶
type ShipConnectionInterface interface {
// DataHandler returns the WebSocket data writer for sending SHIP messages.
//
// The data handler provides low-level WebSocket communication capabilities
// for sending SHIP protocol messages and SPINE payloads.
//
// Returns:
// - WebsocketDataWriterInterface: Writer for sending data over the connection
DataHandler() WebsocketDataWriterInterface
// CloseConnection closes the SHIP connection with optional close code and reason.
//
// This method gracefully terminates the SHIP connection, sending appropriate
// close frames and cleaning up resources.
//
// Parameters:
// - safe: true for graceful close, false for immediate termination
// - code: WebSocket close code (e.g., 1000 for normal closure)
// - reason: Human-readable reason for closing the connection
CloseConnection(safe bool, code int, reason string)
// RemoteSKI returns the SKI of the remote service.
//
// Returns:
// - string: The SKI of the remote service
//
// Example:
// ski := connection.RemoteSKI()
RemoteSKI() string
// ApprovePendingHandshake approves a handshake that is waiting for user confirmation.
//
// This method is called when a user manually approves a connection request
// from an untrusted device. It continues the SHIP handshake process that
// was paused for user intervention.
//
// Used when: Connection is in pending state waiting for trust confirmation
ApprovePendingHandshake()
// AbortPendingHandshake rejects a handshake that is waiting for user confirmation.
//
// This method is called when a user manually rejects a connection request
// from an untrusted device. It terminates the SHIP handshake process and
// closes the connection.
//
// Used when: Connection is in pending state and user rejects the request
AbortPendingHandshake()
// ShipHandshakeState returns the current SHIP protocol handshake state.
//
// The SHIP handshake progresses through multiple states (Init, Hello, Protocol,
// PIN) before entering connection data exchange. Access methods identification
// runs in parallel to data exchange, and SmeStateComplete is reached once it
// verified the remote's SHIP ID. This method provides visibility into the
// current handshake progress.
//
// Returns:
// - model.ShipMessageExchangeState: Current handshake state
// - error: Any error that occurred during handshake, nil if successful
//
// Example:
// state, err := connection.ShipHandshakeState()
// if err != nil {
// // Handle handshake error
// }
// if state == model.SmeStateComplete {
// // Handshake completed successfully
// }
ShipHandshakeState() (model.ShipMessageExchangeState, error)
}
ShipConnectionInterface provides access to SHIP protocol connections.
This interface represents an active SHIP connection between local and remote devices, handling the SHIP handshake protocol and providing access to remote service information. Connections are created by the Hub when devices establish WebSocket connections.
Implemented by: ShipConnection (ship package) Used by: Hub for connection management and lifecycle coordination
type ShipPairingServiceInterface ¶ added in v0.7.0
type ShipPairingServiceInterface interface {
// Start initializes and starts the SHIP pairing service.
// Must be called before any pairing operations can be performed.
// Returns an error if the service cannot be started (e.g., missing configuration).
Start() error
// Shutdown gracefully stops the pairing service and cleans up resources.
// Should be called when the service is no longer needed to ensure proper cleanup.
Shutdown()
// CreateListener creates a new pairing listener instance for the specified local service.
// Used when this device acts as devA (target device) in SHIP pairing.
// Returns a configured listener ready to accept pairing requests.
CreateListener() PairingListenerInterface
// CreateAnnouncer creates a new pairing announcer instance for the specified local service.
// Used when this device acts as devZ (requesting device) in SHIP pairing.
// Returns a configured announcer ready to send pairing requests.
CreateAnnouncer() PairingAnnouncerInterface
// IsServiceRunning returns whether the PairingService was started successfully and is currently running
IsServiceRunning() bool
}
ShipPairingServiceInterface - Main interface for SHIP pairing service functionality Separates lifecycle from operations for better testability
type ShipPairingTXT ¶ added in v0.7.0
type ShipPairingTXT struct {
TxtVers string // "1" - Version number of TXT format
ParType string // "fpSha256" - Parameter type (fingerprint SHA-256)
ForId string // devA SHIP ID
ForPar string // SHA-256 fingerprint of devA certificate
TrustId string // devZ SHIP ID
TrustPar string // SHA-256 fingerprint of devZ certificate
TrustCurve string // "secp256r1" | "brainpoolP256r1" | "brainpoolP384r1"
Type string // "addCu" - Command type
TrustNonce string // devZ nonce (128-bit hex)
Alg string // "hmacSha256" - Algorithm
Digest string // HMAC result (256-bit hex)
}
ShipPairingTXT represents the TXT record structure for _shippairing._tcp service Per SHIP Pairing Service specification Table 1
func (*ShipPairingTXT) FromMap ¶ added in v0.7.0
func (sp *ShipPairingTXT) FromMap(txtMap map[string]string) error
FromMap populates the ShipPairingTXT structure from a map[string]string received from mDNS TXT records. This method is used when parsing SHIP pairing announcements discovered via mDNS. It validates that all required fields are present and that the txtvers field has the expected value.
Parameters:
- txtMap: Map of TXT record key-value pairs received from mDNS discovery
Returns:
- nil if parsing succeeds and all required fields are present and valid
- PairingValidationError if any required field is missing or txtvers is invalid
Validation:
- Checks for presence of all 11 required fields per SHIP spec Table 1
- Validates txtvers field equals "1" (current TXT record format version)
- Does not validate field content (use Validate() method for that)
Usage:
This is typically called by mDNS listeners when processing discovered pairing announcements
func (*ShipPairingTXT) ToMap ¶ added in v0.7.0
func (sp *ShipPairingTXT) ToMap() map[string]string
ToMap converts the ShipPairingTXT structure to a map[string]string for mDNS TXT records. This method is used when publishing SHIP pairing announcements via mDNS, as TXT records are represented as key-value string pairs. The field names match exactly those specified in SHIP Pairing Service specification Table 1.
Returns:
- A map containing all TXT record fields as string key-value pairs
- Keys are lowercase field names (e.g., "txtvers", "parType", "forId")
- All values are strings, with binary data hex-encoded
Usage:
This is typically called by mDNS providers when announcing pairing services
func (*ShipPairingTXT) Validate ¶ added in v0.7.0
func (sp *ShipPairingTXT) Validate() error
Validate checks if all TXT record field values conform to SHIP Pairing Service specification. This method validates field content after the structure has been populated (typically after calling FromMap). It ensures that enum values are within supported ranges, algorithms are supported by this implementation, and hexadecimal values match the exact formats of pairing spec section 5.4, Table 1.
The format checks are load-bearing for security, not pedantry: a shippairing digest is calculated over the TXT values as announced, so a record whose values are malformed in a way that survives lenient parsing (lowercase hex, wrong-length nonce) carries a digest that still verifies. Format validation is the only gate that rejects such records (see TC_SPS_TXT_009).
Returns:
- nil if all field values are valid per SHIP specification
- PairingValidationError if any field contains an unsupported or invalid value
Validation checks:
- txtvers must be "1"
- forId and trustId must be non-empty (SHIP ID)
- forPar, trustPar and digest must be 64 uppercase hexadecimal digits
- trustNonce must be 32 uppercase hexadecimal digits (128-bit nonce)
- Algorithm must be "hmacSha256" (only supported HMAC algorithm)
- Parameter type must be "fpSha256" (fingerprint SHA-256)
- Command type must be "addCu" (only supported pairing command)
- Trust curve must be one of: secp256r1, brainpoolP256r1, brainpoolP384r1
Usage:
Call this method after FromMap() to ensure received pairing data is processable
type WebsocketDataReaderInterface ¶
type WebsocketDataReaderInterface interface {
// called for each incoming message
HandleIncomingWebsocketMessage([]byte)
// called if the data connection is closed unsafe
// e.g. due to connection issues
ReportConnectionError(error)
}
interface for handling incoming data
implemented by shipConnection, used by websocketConnection
type WebsocketDataWriterInterface ¶
type WebsocketDataWriterInterface interface {
// initialize data processing
InitDataProcessing(WebsocketDataReaderInterface)
// send data via the connection to the remote device
WriteMessageToWebsocketConnection([]byte) error
// close the data connection
CloseDataConnection(closeCode int, reason string)
// report if the data connection is closed and the error if availab le
IsDataConnectionClosed() (bool, error)
}
interface for handling the actual remote device data connection
implemented by websocketConnection, used by ShipConnection