relay

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StatusOK      byte = 0x01
	StatusErr     byte = 0x00
	PeerArrived   byte = 0x02
	GroupComplete byte = 0x03
	StatusTimeout byte = 0x04
	WaitingMarker byte = 0xFF
)

Wire status bytes.

View Source
const DefaultMaxGroups = 10000

DefaultMaxGroups is the default cap on total pairing groups in memory. Prevents memory exhaustion from group creation flooding.

View Source
const GrantReceiptPayloadSize = 30

GrantReceiptPayloadSize is the canonical payload size (without HMAC): 1 + 8 + 8 + 4 + 1 + 8 = 30 bytes.

View Source
const GrantReceiptProtocol = "/shurli/grant-receipt/1.0.0"

GrantReceiptProtocol is the upgraded grant notification protocol. Carries a full 62-byte receipt with grant parameters.

View Source
const GrantReceiptSize = 62

GrantReceiptSize is the total wire size: 1 + 8 + 8 + 4 + 1 + 8 + 32 = 62 bytes.

View Source
const HMACProofSize = 32

HMACProofSize is the length of the HMAC-SHA256 commitment proof.

View Source
const InviteProtocol = "/shurli/invite/1.0.0"

InviteProtocol is the protocol ID for PAKE-secured relay invite/join.

View Source
const MOTDProtocol = "/shurli/relay-motd/1.0.0"

MOTDProtocol is the libp2p protocol ID for relay MOTD and goodbye messages.

View Source
const MaxCodesPerGroup = 10000

MaxCodesPerGroup caps the number of codes in a single group to prevent memory exhaustion from a malicious CreateGroup(count=1B) call.

View Source
const PeerNotifyProtocol = "/shurli/peer-notify/1.0.0"

Protocol ID for peer introduction delivery.

View Source
const RemoteAdminProtocol = "/shurli/relay-admin/1.0.0"

RemoteAdminProtocol is the libp2p protocol ID for remote relay administration. Replaces the old /shurli/relay-unseal/1.0.0 protocol with a general-purpose admin channel that supports all admin operations over P2P.

View Source
const TokenSize = 16

Token size for relay pairing codes (128-bit).

View Source
const UnsealProtocol = "/shurli/relay-unseal/1.0.0"

UnsealProtocol is the libp2p protocol ID for remote vault unseal.

View Source
const ZKPAuthProtocol = "/shurli/zkp-auth/1.0.0"

ZKPAuthProtocol is the libp2p protocol ID for ZKP anonymous authentication.

Variables

View Source
var (
	ErrTokenNotFound = errors.New("pairing failed")
	ErrTokenUsed     = errors.New("pairing failed")
	ErrTokenBurned   = errors.New("pairing failed")
	ErrTokenExpired  = errors.New("pairing failed")
	ErrGroupNotFound = errors.New("group not found")
	ErrGroupExpired  = errors.New("group expired")
	ErrStoreCapacity = errors.New("token store at capacity")
)
View Source
var ErrQuotaExceeded = fmt.Errorf("group creation quota exceeded")

ErrQuotaExceeded is returned when a peer exceeds their group creation quota.

View Source
var ErrTokenInProgress = errors.New("pairing failed")

ErrTokenInProgress is returned when a PAKE handshake is already in flight for this token.

Functions

func EncodeGrantReceipt

func EncodeGrantReceipt(grantDuration time.Duration, sessionDataLimit int64,
	sessionDuration time.Duration, permanent bool, issuedAt time.Time,
	hmacKey []byte) []byte

EncodeGrantReceipt encodes a grant receipt into the wire format.

Wire format (62 bytes):

[1]       version (0x01)
[8 BE]    grant_duration_secs (relative, 0 for permanent)
[8 BE]    session_data_limit (bytes, 0 = unlimited)
[4 BE]    session_duration_secs (per circuit session)
[1]       permanent flag (0x00=no, 0x01=yes)
[8 BE]    issued_at (Unix seconds)
[32]      HMAC-SHA256(key, canonical payload above)

func EncodePeerNotify

func EncodePeerNotify(groupID string, groupSize byte, peers []NotifyPeerInfo) []byte

EncodePeerNotify creates the wire-format notification message.

Wire format:

[1]       version (0x01)
[1]       group ID length
[N]       group ID (ASCII)
[1]       group size (total members including recipient)
[1]       peer count
Per peer:
  [2 BE]  peer ID length
  [N]     peer ID string
  [1]     name length
  [M]     name string
  [32]    HMAC proof (HMAC-SHA256, zero-padded if absent)

func EncodeUnsealRequest

func EncodeUnsealRequest(nonce []byte, passphrase, totpCode string) []byte

EncodeUnsealRequest builds the v2 wire-format request with challenge nonce echo. The nonce is the 16-byte challenge received from ReadUnsealChallenge.

func EncodeZKPAuthRequest

func EncodeZKPAuthRequest(authType byte, roleRequired byte) []byte

EncodeZKPAuthRequest builds the 3-byte client request header.

func EncodeZKPProof

func EncodeZKPProof(proofBytes []byte) []byte

EncodeZKPProof builds the length-prefixed proof message.

func LockoutStateFile

func LockoutStateFile(configDir string) string

LockoutStateFile returns the conventional lockout state file path for a relay config dir.

func NotifyGrantReceipt

func NotifyGrantReceipt(ctx context.Context, h host.Host, targetPeerID peer.ID,
	grant *grants.Grant, sessionDataLimit int64, sessionDuration time.Duration,
	hmacKey []byte) error

NotifyGrantReceipt encodes a grant receipt and sends it to a connected peer. If the peer is not connected, returns nil (nothing to do). Session limits come from relay config, not grant store (H13). Permanent grants still carry session limits (H14).

NOTE: This reads from the Grant pointer. Callers must ensure the Grant is either a clone (e.g., from CheckAndGet) or not concurrently modified. For handleRelayGrant, use EncodeGrantReceipt + sendGrantReceipt instead to avoid racing with concurrent Extend() calls on the store's shared pointer.

func ReadUnsealChallenge

func ReadUnsealChallenge(r io.Reader) ([]byte, error)

ReadUnsealChallenge reads the 16-byte challenge nonce from the relay. Must be called before sending the unseal request.

func ReadUnsealResponse

func ReadUnsealResponse(r io.Reader) (bool, string, error)

ReadUnsealResponse reads a response from the unseal protocol stream. Returns the status (0x01 = OK, 0x00 = error) and the message.

func ReadZKPAuthResponse

func ReadZKPAuthResponse(r io.Reader) (bool, string, error)

ReadZKPAuthResponse reads the final auth status. Returns: authorized (bool), message, error.

func ReadZKPChallenge

func ReadZKPChallenge(r io.Reader) (uint64, []byte, int, error)

ReadZKPChallenge reads the relay's challenge response. Returns: nonce, merkleRoot, treeDepth, error.

func RunReconnectNotifier

func RunReconnectNotifier(ctx context.Context, h host.Host, notifier *PeerNotifier, authKeysPath string, receiptCfg *GrantReceiptDelivery)

RunReconnectNotifier subscribes to peer identification events and pushes introductions when an authorized peer with a group attribute reconnects. If receiptCfg is non-nil, also pushes grant receipts to peers with active grants. Uses EvtPeerIdentificationCompleted (not EvtPeerConnectednessChanged) so the peer's supported protocols are known before opening a stream.

func VerifyGrantReceipt

func VerifyGrantReceipt(data []byte, hmacKey []byte) bool

VerifyGrantReceipt checks the HMAC on a receipt's wire bytes.

func VerifyStoredGoodbye

func VerifyStoredGoodbye(pubKey crypto.PubKey, msg string, timestamp int64, sig []byte) bool

VerifyStoredGoodbye re-verifies a stored goodbye signature against a public key.

Types

type AdminClient

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

AdminClient connects to a running relay's admin Unix socket.

func NewAdminClient

func NewAdminClient(socketPath, cookiePath string) (*AdminClient, error)

NewAdminClient creates a client for the relay admin socket.

func (*AdminClient) AuthReload

func (c *AdminClient) AuthReload() error

AuthReload triggers a hot-reload of the relay's authorized_keys and gater. Also rebuilds the ZKP Merkle tree if ZKP auth is enabled.

func (*AdminClient) AuthorizePeer

func (c *AdminClient) AuthorizePeer(peerID, comment string) error

AuthorizePeer adds a peer to the relay's authorized_keys and triggers reload.

func (*AdminClient) ClearMOTD

func (c *AdminClient) ClearMOTD() error

ClearMOTD clears the relay's MOTD message.

func (*AdminClient) CreateGroup

func (c *AdminClient) CreateGroup(count, ttlSec, expiresSec int, namespace string) (*PairResponse, error)

CreateGroup creates a pairing group and returns the invite codes.

func (*AdminClient) CreateInvite

func (c *AdminClient) CreateInvite(caveats []string, ttlSec int) (map[string]string, error)

CreateInvite creates a macaroon-backed invite deposit.

func (*AdminClient) DeauthorizePeer

func (c *AdminClient) DeauthorizePeer(peerID string) error

DeauthorizePeer removes a peer from the relay's authorized_keys and triggers reload.

func (*AdminClient) GetInfo

func (c *AdminClient) GetInfo() (*RelayInfoResponse, error)

GetInfo returns the relay's peer ID and multiaddrs from the running server.

func (*AdminClient) GetMOTDStatus

func (c *AdminClient) GetMOTDStatus() (*MOTDStatusResponse, error)

GetMOTDStatus returns the current MOTD and goodbye status.

func (*AdminClient) GoodbyeShutdown

func (c *AdminClient) GoodbyeShutdown(message string) error

GoodbyeShutdown sets a goodbye and triggers relay shutdown.

func (*AdminClient) InitVault

func (c *AdminClient) InitVault(seedBytes []byte, mnemonic, password string, enableTOTP bool, autoSealMins int) (*VaultInitResponse, error)

InitVault creates a new vault on the relay.

func (*AdminClient) ListConnectedPeers

func (c *AdminClient) ListConnectedPeers() ([]ConnectedPeerInfo, error)

ListConnectedPeers returns currently connected peers with network details.

func (*AdminClient) ListGroups

func (c *AdminClient) ListGroups() ([]GroupInfo, error)

ListGroups returns all active pairing groups.

func (*AdminClient) ListInvites

func (c *AdminClient) ListInvites() ([]map[string]any, error)

ListInvites returns all invite deposits.

func (*AdminClient) ListPeers

func (c *AdminClient) ListPeers() ([]AuthorizedPeerInfo, error)

ListPeers returns all authorized peers from the relay's authorized_keys.

func (*AdminClient) ModifyInvite

func (c *AdminClient) ModifyInvite(id string, addCaveats []string) error

ModifyInvite adds caveats to a pending invite deposit (attenuation only).

func (*AdminClient) RelayExtend

func (c *AdminClient) RelayExtend(peerID string, durationSecs int, dataBudgetStr string) error

RelayExtend extends an existing relay data grant. dataBudgetStr is optional: "" = keep current budget, "1GB" = update budget.

func (*AdminClient) RelayGrant

func (c *AdminClient) RelayGrant(peerID string, durationSecs int, services []string, permanent bool, dataBudgetStr string) (*RelayGrantInfo, error)

RelayGrant creates a time-limited data access grant for a peer. dataBudgetStr is optional: "" = use global default, "500MB" = per-peer, "unlimited" = no limit.

func (*AdminClient) RelayGrants

func (c *AdminClient) RelayGrants() ([]RelayGrantInfo, error)

RelayGrants lists all active relay data grants.

func (*AdminClient) RelayRevoke

func (c *AdminClient) RelayRevoke(peerID string) error

RelayRevoke revokes a relay data grant and terminates active circuits.

func (*AdminClient) RetractGoodbye

func (c *AdminClient) RetractGoodbye() error

RetractGoodbye retracts an active goodbye announcement.

func (*AdminClient) RevokeGroup

func (c *AdminClient) RevokeGroup(id string) error

RevokeGroup revokes a pairing group by ID.

func (*AdminClient) RevokeInvite

func (c *AdminClient) RevokeInvite(id string) error

RevokeInvite revokes a pending invite deposit.

func (*AdminClient) Seal

func (c *AdminClient) Seal() error

Seal re-seals the relay vault.

func (*AdminClient) SealStatus

func (c *AdminClient) SealStatus() (*SealStatusResponse, error)

SealStatus returns the current seal status of the relay vault.

func (*AdminClient) SetGoodbye

func (c *AdminClient) SetGoodbye(message string) error

SetGoodbye sets a goodbye announcement (pushed to all connected peers).

func (*AdminClient) SetMOTD

func (c *AdminClient) SetMOTD(message string) error

SetMOTD sets the relay's MOTD message.

func (*AdminClient) SetPeerAttr

func (c *AdminClient) SetPeerAttr(peerID, key, value string) error

SetPeerAttr sets a key=value attribute on a peer in the relay's authorized_keys.

func (*AdminClient) Unseal

func (c *AdminClient) Unseal(passphrase, totpCode string, yubikeyResponse []byte) error

Unseal sends a passphrase (and optional TOTP code and Yubikey response) to unseal the relay vault.

func (*AdminClient) ZKPProvingKey

func (c *AdminClient) ZKPProvingKey() ([]byte, error)

ZKPProvingKey downloads the PLONK proving key from the relay. Returns the raw binary key data (~2 MB).

func (*AdminClient) ZKPTreeInfo

func (c *AdminClient) ZKPTreeInfo() (*ZKPTreeInfoResponse, error)

ZKPTreeInfo returns the current ZKP Merkle tree state.

func (*AdminClient) ZKPTreeRebuild

func (c *AdminClient) ZKPTreeRebuild() (map[string]any, error)

ZKPTreeRebuild triggers a Merkle tree rebuild from authorized_keys.

func (*AdminClient) ZKPVerifyingKey

func (c *AdminClient) ZKPVerifyingKey() ([]byte, error)

ZKPVerifyingKey downloads the PLONK verifying key from the relay. Returns the raw binary key data (~34 KB).

type AdminGaterInterface

type AdminGaterInterface interface {
	SetEnrollmentMode(enabled bool, limit int, timeout time.Duration)
	IsEnrollmentEnabled() bool
	UpdateAuthorizedPeers(authorizedPeers map[peer.ID]bool)
	GetAuthorizedPeerIDs() []peer.ID
}

AdminGaterInterface is the subset of AuthorizedPeerGater needed by the admin socket.

type AdminServer

type AdminServer struct {
	Metrics *sdk.Metrics // nil-safe: metrics are optional
	// contains filtered or unexported fields
}

AdminServer provides a Unix socket HTTP API for the relay admin CLI. It runs inside the relay serve process and allows relay pair to create pairing groups, list them, and revoke them without direct access to the in-memory token store.

func NewAdminServer

func NewAdminServer(store *TokenStore, gater AdminGaterInterface, relayAddr, namespace, socketPath, cookiePath string) *AdminServer

NewAdminServer creates a new relay admin server.

func (*AdminServer) HandleRemoteRequest

func (s *AdminServer) HandleRemoteRequest(method, path string, body []byte, callerPeer peer.ID, role string) (int, []byte)

HandleRemoteRequest dispatches a request to the internal mux without going through the cookie auth middleware. Used by RemoteAdminHandler where authentication is done via libp2p peer identity instead. callerPeer and role identify the remote caller for ownership checks. Returns the HTTP status code and response body bytes.

func (*AdminServer) SetAuthKeysPath

func (s *AdminServer) SetAuthKeysPath(path string)

SetAuthKeysPath sets the path to the authorized_keys file for hot-reload.

func (*AdminServer) SetBudgetTracker added in v0.4.0

func (s *AdminServer) SetBudgetTracker(bt *BudgetTracker)

SetBudgetTracker wires the per-peer budget tracker for synchronous budget initialization on grant/extend. The async onGrant callback is a safety net, but the admin handler must initialize budgets synchronously to close the race between grant creation and AllowConnect.

func (*AdminServer) SetCircuitACL

func (s *AdminServer) SetCircuitACL(acl *CircuitACL)

SetCircuitACL sets the circuit ACL for cache refresh on auth reload.

func (*AdminServer) SetDepositStore

func (s *AdminServer) SetDepositStore(ds *deposit.DepositStore)

SetDepositStore attaches an invite deposit store. The macaroon root key is retrieved from the vault dynamically when needed (unsealed state only).

func (*AdminServer) SetGrantStore

func (s *AdminServer) SetGrantStore(gs *grants.Store)

SetGrantStore sets the relay grant store for time-limited data access control.

func (*AdminServer) SetHost

func (s *AdminServer) SetHost(h libp2phost.Host)

SetHost stores the libp2p host reference for connected-peers queries.

func (*AdminServer) SetMOTDHandler

func (s *AdminServer) SetMOTDHandler(h *MOTDHandler)

SetMOTDHandler attaches the MOTD handler for motd/goodbye endpoints.

func (*AdminServer) SetReceiptHMACKey

func (s *AdminServer) SetReceiptHMACKey(key []byte)

SetReceiptHMACKey sets the dedicated HMAC key for grant receipt signing. Must be derived via HKDF("grant-receipt/v1") - separate from grant store keys (H10).

func (*AdminServer) SetSessionLimits

func (s *AdminServer) SetSessionLimits(dataLimit int64, duration time.Duration)

SetSessionLimits stores the relay config session limits for receipt construction. Session limits come from relay config, not grant store (H13).

func (*AdminServer) SetShutdownFunc

func (s *AdminServer) SetShutdownFunc(fn func())

SetShutdownFunc sets the callback invoked by POST /v1/goodbye/shutdown.

func (*AdminServer) SetVault

func (s *AdminServer) SetVault(v *vault.Vault, vaultPath string)

SetVault attaches a vault to the admin server for seal/unseal management.

func (*AdminServer) SetZKPAuth

func (s *AdminServer) SetZKPAuth(h *ZKPAuthHandler)

SetZKPAuth attaches the ZKP auth handler for tree-rebuild and tree-info endpoints.

func (*AdminServer) Start

func (s *AdminServer) Start() error

Start creates the Unix socket, writes the cookie file, and starts serving.

func (*AdminServer) Stop

func (s *AdminServer) Stop()

Stop gracefully shuts down the server and cleans up socket/cookie files.

type AuthorizedPeerInfo

type AuthorizedPeerInfo struct {
	PeerID    string `json:"peer_id"`
	Role      string `json:"role"`
	Comment   string `json:"comment,omitempty"`
	Verified  string `json:"verified,omitempty"`
	Group     string `json:"group,omitempty"`
	ExpiresAt string `json:"expires_at,omitempty"`
}

AuthorizedPeerInfo is the JSON representation of an authorized peer for the admin API. Distinct from PeerInfo in tokens.go (pairing groups).

type BudgetTracker added in v0.4.0

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

BudgetTracker manages per-peer relay data budgets.

Grant peers get cumulative tracking: all circuits for the same peer share one atomic counter. Reconnecting does NOT reset the budget (SEC2).

Non-grant peers get per-circuit budgets (fresh counter per circuit = default). Admin peers bypass entirely (SEC4).

Budget resets on: grant extend, new grant (C5). Revoke sets remaining to 0 (SEC7).

func NewBudgetTracker added in v0.4.0

func NewBudgetTracker(gs *grants.Store, defaultLimit int64) *BudgetTracker

NewBudgetTracker creates a budget tracker wired to the grant store. defaultLimit is the relay's session_data_limit used for non-grant peers (per circuit).

func (*BudgetTracker) ConsumeBytes added in v0.4.0

func (bt *BudgetTracker) ConsumeBytes(p peer.ID, n int64) int64

ConsumeBytes decrements the budget for a granted peer. Called by limitedStream on each Read/Write. Returns the remaining bytes after this consumption.

func (*BudgetTracker) DefaultLimit added in v0.4.0

func (bt *BudgetTracker) DefaultLimit() int64

DefaultLimit returns the per-circuit budget for non-grant peers.

func (*BudgetTracker) HasBudget added in v0.4.0

func (bt *BudgetTracker) HasBudget(p peer.ID) bool

HasBudget returns true if this peer has a budget entry in the tracker. Non-grant peers won't have entries (they get per-circuit defaults).

func (*BudgetTracker) OnGrantOrExtend added in v0.4.0

func (bt *BudgetTracker) OnGrantOrExtend(p peer.ID, g *grants.Grant)

OnGrantOrExtend is the callback for grant creation and extension (C5). Computes the budget from the grant's DataBudget field and resets/initializes the peer's counter. Called from grantStore.SetOnGrant.

func (*BudgetTracker) OnRevoke added in v0.4.0

func (bt *BudgetTracker) OnRevoke(p peer.ID)

OnRevoke sets remaining to 0 for the revoked peer (SEC7). Double protection with ClosePeer — even if ClosePeer races with an in-flight Read/Write, the next operation sees 0 remaining.

func (*BudgetTracker) RemainingBudget added in v0.4.0

func (bt *BudgetTracker) RemainingBudget(p peer.ID) int64

RemainingBudget returns the remaining bytes for a granted peer. Returns 0 if the peer has no budget entry (non-grant peers handled separately).

type CircuitACL

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

CircuitACL implements the relayv2.ACLFilter interface to control which peers can establish data circuits through this relay.

By default (EnableDataRelay=false), only admin peers and peers with an active time-limited grant can create circuits. All other authorized peers can still connect directly for signaling protocols (invite, peer-notify, relay-admin, relay-unseal, relay-motd, zkp-auth, pingpong) since those are direct streams to the relay, not relay circuits.

When EnableDataRelay=true, all authorized peers can create circuits. Connection gating (AuthorizedPeerGater) still handles unauthorized peers.

func NewCircuitACL

func NewCircuitACL(authKeysPath string, enableDataRelay, enableConnectionGating bool, grantStore *grants.Store) *CircuitACL

NewCircuitACL creates a new circuit ACL filter. authKeysPath is the path to the authorized_keys file. enableDataRelay is the global toggle from relay-server.yaml security config. enableConnectionGating controls whether reservations require authorization. When gating is disabled, all peers can reserve (open relay mode). grantStore provides time-limited per-peer data access grants (may be nil if grants are not configured). The authorized_keys data is cached in memory and refreshed via Reload().

func (*CircuitACL) AllowConnect

func (a *CircuitACL) AllowConnect(src peer.ID, srcAddr ma.Multiaddr, dest peer.ID) bool

AllowConnect controls whether src can establish a data circuit to dest through this relay. This is the enforcement point for relay data policy.

When enableDataRelay is true, all circuits are allowed. When false (default), a circuit is allowed only if either peer is admin or has an active time-limited grant in the relay's grant store.

func (*CircuitACL) AllowReserve

func (a *CircuitACL) AllowReserve(p peer.ID, addr ma.Multiaddr) bool

AllowReserve allows authorized peers to make relay reservations. Probation peers (not in authorized_keys) are denied to prevent relay circuit abuse during enrollment mode. If connection gating is disabled or no authKeysPath is configured, all peers are allowed (open relay).

func (*CircuitACL) IsAdmin added in v0.4.0

func (a *CircuitACL) IsAdmin(p peer.ID) bool

IsAdmin returns true if the peer has the admin role in authorized_keys (SEC4). Used by LimitingHost to bypass budget enforcement for admin peers.

func (*CircuitACL) Reload

func (a *CircuitACL) Reload()

Reload refreshes the cached authorized_keys data from disk. Called by AdminServer.reloadAuth after peer mutations or auth-reload.

func (*CircuitACL) SetBudgetTracker added in v0.4.0

func (a *CircuitACL) SetBudgetTracker(bt *BudgetTracker)

SetBudgetTracker wires the budget tracker for AllowConnect budget checks (TE3-C1).

type CodeSlot

type CodeSlot struct {
	TokenHash    [32]byte  // SHA-256 of raw token
	RawToken     []byte    // kept for PAKE session key derivation; zeroized after use
	DepositID    string    // linked invite deposit ID (for macaroon delivery)
	PeerID       peer.ID   // filled after use
	Name         string    // peer's friendly name
	UsedAt       time.Time // zero = unused
	InProgress   bool      // true while PAKE handshake is in flight (prevents TOCTOU)
	InProgressAt time.Time // when InProgress was set (for timeout cleanup)
	Attempts     int       // failed attempts (max 3)
	HMACProof    []byte    // HMAC-SHA256(token, groupID) computed at pairing time
}

CodeSlot represents a single pairing code within a group.

type ConnectedPeerInfo

type ConnectedPeerInfo struct {
	PeerID       string `json:"peer_id"`
	ShortID      string `json:"short_id"`
	AgentVersion string `json:"agent_version,omitempty"`
	Direction    string `json:"direction"`
	ConnectedAt  string `json:"connected_at"`
	DurationSecs int    `json:"duration_seconds"`
	Transport    string `json:"transport"`
	RemoteAddr   string `json:"remote_addr"`
	IP           string `json:"ip"`
	IsRelay      bool   `json:"is_relay"`
	Authorized   bool   `json:"authorized"`
	Role         string `json:"role,omitempty"`
	Comment      string `json:"comment,omitempty"`
}

ConnectedPeerInfo describes a currently connected peer with network details.

type DecodedGrantReceipt

type DecodedGrantReceipt struct {
	GrantDuration    time.Duration
	SessionDataLimit int64
	SessionDuration  time.Duration
	Permanent        bool
	IssuedAt         time.Time
	HMAC             [32]byte
}

DecodedGrantReceipt holds the parsed fields from a grant receipt.

func DecodeGrantReceipt

func DecodeGrantReceipt(data []byte) (*DecodedGrantReceipt, error)

DecodeGrantReceipt parses a grant receipt from the wire format. Returns the decoded receipt or an error if the data is malformed. Does NOT verify the HMAC - call VerifyGrantReceipt for that.

type GaterInterface

type GaterInterface interface {
	PromotePeer(p peer.ID)
	SetPeerExpiry(p peer.ID, expiresAt time.Time)
	SetEnrollmentMode(enabled bool, limit int, timeout time.Duration)
}

GaterInterface is the subset of AuthorizedPeerGater needed by pairing.

type GrantChecker

type GrantChecker interface {
	CheckAndGet(peerID peer.ID) *grants.Grant
}

GrantChecker is the subset of grants.Store needed for reconnect receipt delivery. Defined here (not in notify.go) because it's a grant receipt concern.

type GrantReceiptDelivery

type GrantReceiptDelivery struct {
	GrantStore       GrantChecker  // checks if peer has an active grant
	HMACKey          []byte        // HKDF("grant-receipt/v1") dedicated key
	SessionDataLimit int64         // from relay config (bytes, 0=unlimited)
	SessionDuration  time.Duration // from relay config
}

GrantReceiptDelivery holds the config for pushing grant receipts on reconnect. If nil is passed to RunReconnectNotifier, receipt delivery is skipped.

type GroupInfo

type GroupInfo struct {
	ID        string
	Namespace string
	CreatedBy peer.ID
	CreatedAt time.Time
	ExpiresAt time.Time
	Total     int
	Used      int
	Peers     []PeerInfo
}

GroupInfo is a read-only snapshot of a pairing group for listing.

type LimitingHost added in v0.4.0

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

LimitingHost wraps a host.Host to intercept relay HOP/STOP streams and apply per-peer data budgets via limitedStream wrappers. This is the key insight from Incident #20: enforcement at a different architectural layer than where the problem manifests, using zero fork changes.

The relay calls h.SetStreamHandler(ProtoIDv2Hop, ...) and h.NewStream(ctx, dest, ProtoIDv2Stop). LimitingHost intercepts both:

  • SetStreamHandler for HOP: wraps the handler so incoming HOP streams get a limitedStream before the relay touches them.
  • NewStream for STOP: wraps the returned stream with dest peer's data limit.

Other protocols (grant-receipt, admin, MOTD, ZKP, etc.) pass through unwrapped (C2/C3).

func NewLimitingHost added in v0.4.0

func NewLimitingHost(h host.Host, tracker *BudgetTracker, acl *CircuitACL) *LimitingHost

NewLimitingHost creates a host wrapper that enforces per-peer data budgets on relay circuit streams. Pass the returned host to relayv2.New() instead of the raw host.

func (*LimitingHost) Addrs added in v0.4.0

func (lh *LimitingHost) Addrs() []ma.Multiaddr

func (*LimitingHost) Close added in v0.4.0

func (lh *LimitingHost) Close() error

func (*LimitingHost) ConnManager added in v0.4.0

func (lh *LimitingHost) ConnManager() connmgr.ConnManager

func (*LimitingHost) Connect added in v0.4.0

func (lh *LimitingHost) Connect(ctx context.Context, pi peer.AddrInfo) error

func (*LimitingHost) EventBus added in v0.4.0

func (lh *LimitingHost) EventBus() event.Bus

func (*LimitingHost) ID added in v0.4.0

func (lh *LimitingHost) ID() peer.ID

func (*LimitingHost) Mux added in v0.4.0

func (lh *LimitingHost) Mux() protocol.Switch

func (*LimitingHost) Network added in v0.4.0

func (lh *LimitingHost) Network() network.Network

func (*LimitingHost) NewStream added in v0.4.0

func (lh *LimitingHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.ID) (network.Stream, error)

NewStream intercepts STOP protocol streams (C2). When the relay opens a STOP stream to the destination peer, the returned stream is wrapped with the destination's data budget. All other protocols pass through unwrapped.

func (*LimitingHost) Peerstore added in v0.4.0

func (lh *LimitingHost) Peerstore() peerstore.Peerstore

func (*LimitingHost) RemoveStreamHandler added in v0.4.0

func (lh *LimitingHost) RemoveStreamHandler(pid protocol.ID)

func (*LimitingHost) SetStreamHandler added in v0.4.0

func (lh *LimitingHost) SetStreamHandler(pid protocol.ID, handler network.StreamHandler)

SetStreamHandler intercepts the HOP protocol handler (C3). For HOP streams, the original handler is wrapped to inject a limitedStream before the relay processes the circuit. All other protocols pass through.

func (*LimitingHost) SetStreamHandlerMatch added in v0.4.0

func (lh *LimitingHost) SetStreamHandlerMatch(pid protocol.ID, match func(protocol.ID) bool, handler network.StreamHandler)

SetStreamHandlerMatch intercepts HOP protocol handler registration (MF5 defense-in-depth).

type MOTDCallback

type MOTDCallback func(msg MOTDMessage)

MOTDCallback is called when a valid MOTD/goodbye is received.

type MOTDClient

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

MOTDClient handles incoming MOTD streams from relays.

func NewMOTDClient

func NewMOTDClient(callback MOTDCallback, dataDir string) *MOTDClient

NewMOTDClient creates a client handler for relay MOTD messages.

func (*MOTDClient) CleanLastMOTDShown

func (c *MOTDClient) CleanLastMOTDShown()

CleanLastMOTDShown evicts expired entries from the dedup map. Entries older than 24 hours are removed. Safe to call periodically.

func (*MOTDClient) GetLastMOTD

func (c *MOTDClient) GetLastMOTD(relayPeer peer.ID) (string, int64, bool)

GetLastMOTD retrieves the last received MOTD for a relay peer. Returns the message, timestamp, and true if found (within the 24h dedup window).

func (*MOTDClient) GetStoredGoodbye

func (c *MOTDClient) GetStoredGoodbye(relayPeer peer.ID) (string, int64, bool)

GetStoredGoodbye retrieves a stored goodbye for a relay peer. Returns the message, timestamp, and true if found.

func (*MOTDClient) HandleStream

func (c *MOTDClient) HandleStream(s network.Stream)

HandleStream processes an incoming MOTD stream from a relay.

type MOTDHandler

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

MOTDHandler manages relay operator announcements and goodbye messages.

func NewMOTDHandler

func NewMOTDHandler(h host.Host, privKey crypto.PrivKey, goodbyeFile string) *MOTDHandler

NewMOTDHandler creates a handler for relay MOTD and goodbye messages.

func (*MOTDHandler) ClearMOTD

func (h *MOTDHandler) ClearMOTD()

ClearMOTD clears the current MOTD.

func (*MOTDHandler) Goodbye

func (h *MOTDHandler) Goodbye() string

Goodbye returns the current goodbye message.

func (*MOTDHandler) GoodbyeShutdown

func (h *MOTDHandler) GoodbyeShutdown(msg string) error

GoodbyeShutdown pushes the goodbye to all peers (with timeout) then signals shutdown. Returns after all peers have been notified (or timeout).

func (*MOTDHandler) HasActiveGoodbye

func (h *MOTDHandler) HasActiveGoodbye() bool

HasActiveGoodbye returns true if a goodbye message is active.

func (*MOTDHandler) MOTD

func (h *MOTDHandler) MOTD() string

MOTD returns the current MOTD message.

func (*MOTDHandler) PushToPeer

func (h *MOTDHandler) PushToPeer(peerID peer.ID)

PushToPeer sends the current MOTD and any active goodbye to a single peer.

func (*MOTDHandler) RetractGoodbye

func (h *MOTDHandler) RetractGoodbye() error

RetractGoodbye clears the goodbye and pushes a retract to all connected peers.

func (*MOTDHandler) RunMOTDNotifier

func (h *MOTDHandler) RunMOTDNotifier(ctx context.Context)

RunMOTDNotifier subscribes to peer identification events and pushes MOTD + active goodbye to newly connected peers.

func (*MOTDHandler) SetGoodbye

func (h *MOTDHandler) SetGoodbye(msg string) error

SetGoodbye sets the goodbye announcement (persisted to disk).

func (*MOTDHandler) SetMOTD

func (h *MOTDHandler) SetMOTD(msg string)

SetMOTD sets the current MOTD message (sanitized).

func (*MOTDHandler) SetMetrics

func (h *MOTDHandler) SetMetrics(m *sdk.Metrics)

SetMetrics attaches metrics to the handler.

type MOTDMessage

type MOTDMessage struct {
	Type      byte // motdTypeMOTD, motdTypeGoodbye, motdTypeRetract
	Message   string
	Timestamp int64
	RelayPeer peer.ID
}

MOTDMessage represents a received MOTD or goodbye message.

type MOTDStatusResponse

type MOTDStatusResponse struct {
	MOTD          string `json:"motd"`
	Goodbye       string `json:"goodbye"`
	GoodbyeActive bool   `json:"goodbye_active"`
}

MOTDStatusResponse is the JSON response for GET /v1/motd and GET /v1/goodbye.

type NotifyPeerInfo

type NotifyPeerInfo struct {
	PeerID    string
	Name      string
	HMACProof []byte // 32-byte HMAC-SHA256(token, groupID) - proves token possession
}

NotifyPeerInfo is the per-peer data in a notification message.

func ReadPeerNotify

func ReadPeerNotify(r io.Reader) (peers []NotifyPeerInfo, groupID string, groupSize int, err error)

ReadPeerNotify reads and parses a peer notification message from a stream. Returns the peer list, group ID, and group size.

type PairRequest

type PairRequest struct {
	Count          int      `json:"count"`
	TTLSeconds     int      `json:"ttl_seconds"`
	Namespace      string   `json:"namespace,omitempty"`
	ExpiresSeconds int      `json:"expires_seconds,omitempty"`
	Caveats        []string `json:"caveats,omitempty"` // macaroon caveats for unified invite
}

PairRequest is the JSON body for POST /v1/pair.

type PairResponse

type PairResponse struct {
	GroupID   string   `json:"group_id"`
	Codes     []string `json:"codes"`
	ExpiresAt string   `json:"expires_at"`
}

PairResponse is the JSON response for POST /v1/pair.

type PairingGroup

type PairingGroup struct {
	ID        string
	Namespace string
	CreatedBy peer.ID // peer that created this group (empty for local admin)
	CreatedAt time.Time
	ExpiresAt time.Time
	PeerTTL   time.Duration // authorization expiry for joined peers (0 = never)
	// contains filtered or unexported fields
}

PairingGroup holds a set of related pairing codes.

type PairingHandler

type PairingHandler struct {
	Store        *TokenStore
	Deposits     *deposit.DepositStore // for macaroon delivery in v2
	AuthKeysPath string
	Gater        GaterInterface
	Metrics      *sdk.Metrics           // nil-safe: metrics are optional
	RootKeyFunc  func() ([]byte, error) // returns vault root key for macaroon verification
	// contains filtered or unexported fields
}

PairingHandler handles the relay-side pairing protocol.

func (*PairingHandler) HandleStream

func (ph *PairingHandler) HandleStream(s network.Stream) (peer.ID, string)

HandleStream processes a v2 PAKE-secured pairing stream.

Wire format:

Joiner -> Relay: [32] SHA-256(token) + [32] X25519 pubkey
Relay  -> Joiner: [1] status + [32] X25519 pubkey
Joiner -> Relay: Encrypt(name)
Relay  -> Joiner: Encrypt(PairingResponse JSON)

Returns the joined peer ID and group ID on success (for notification triggers).

type PairingResponse

type PairingResponse struct {
	GroupID  string     `json:"group_id"`
	Peers    []PeerInfo `json:"peers"`
	Macaroon string     `json:"macaroon,omitempty"` // serialized macaroon JSON
}

PairingResponse is the JSON payload encrypted and sent to the joiner via PAKE.

type PeerInfo

type PeerInfo struct {
	PeerID    peer.ID
	Name      string
	HMACProof []byte // HMAC-SHA256(token, groupID) - proves token possession
}

PeerInfo is a joined peer's identity and name.

func DecodePeerInfos

func DecodePeerInfos(data []byte, count int) ([]PeerInfo, error)

DecodePeerInfos reads peer info entries from a pairing response.

type PeerNotifier

type PeerNotifier struct {
	Host         host.Host
	AuthKeysPath string
	Store        *TokenStore // for HMAC proofs
}

PeerNotifier delivers peer introductions to connected peers. The relay acts as a post office: it knows who joined together and delivers introductions when peers connect. Designed generically so future introduction sources (peer-to-peer, multi-relay mesh) can reuse the same wire format and handler.

func (*PeerNotifier) NotifyGroupMembers

func (pn *PeerNotifier) NotifyGroupMembers(ctx context.Context, groupID string, excludePeerID peer.ID)

NotifyGroupMembers delivers peer introductions to all connected group members except excludePeerID (typically the peer that just joined).

func (*PeerNotifier) NotifyPeer

func (pn *PeerNotifier) NotifyPeer(ctx context.Context, targetPeerID peer.ID, groupID string) error

NotifyPeer delivers peer introductions to a single target peer. It reads authorized_keys to find all peers in the same group, excludes the target, and sends the list over a new stream.

type RelayAdminAPI

type RelayAdminAPI interface {
	Unseal(password, totpCode string, yubikeyResponse []byte) error
	Seal() error
	SealStatus() (*SealStatusResponse, error)
	// InitVault removed from interface: seed material must never travel over
	// the network. Use AdminClient.InitVault() directly (local-only).
	CreateInvite(caveats []string, ttlSec int) (map[string]string, error)
	ListInvites() ([]map[string]any, error)
	RevokeInvite(id string) error
	ModifyInvite(id string, addCaveats []string) error
	CreateGroup(count, ttlSec, expiresSec int, namespace string) (*PairResponse, error)
	ListGroups() ([]GroupInfo, error)
	RevokeGroup(id string) error
	ListPeers() ([]AuthorizedPeerInfo, error)
	ListConnectedPeers() ([]ConnectedPeerInfo, error)
	AuthorizePeer(peerID, comment string) error
	DeauthorizePeer(peerID string) error
	SetPeerAttr(peerID, key, value string) error
	AuthReload() error
	ZKPTreeRebuild() (map[string]any, error)
	ZKPTreeInfo() (*ZKPTreeInfoResponse, error)
	GetMOTDStatus() (*MOTDStatusResponse, error)
	SetMOTD(message string) error
	ClearMOTD() error
	SetGoodbye(message string) error
	RetractGoodbye() error
	GoodbyeShutdown(message string) error

	// Relay data grant management (time-limited per-peer data access)
	RelayGrant(peerID string, durationSecs int, services []string, permanent bool, dataBudgetStr string) (*RelayGrantInfo, error)
	RelayGrants() ([]RelayGrantInfo, error)
	RelayRevoke(peerID string) error
	RelayExtend(peerID string, durationSecs int, dataBudgetStr string) error

	// Relay info (peer ID, multiaddrs)
	GetInfo() (*RelayInfoResponse, error)
}

RelayAdminAPI defines the common interface for relay administration. Both AdminClient (local Unix socket) and RemoteAdminClient (P2P stream) implement this interface, allowing CLI commands to work with either transport transparently.

type RelayExtendRequest

type RelayExtendRequest struct {
	PeerID        string `json:"peer_id"`
	DurationSec   int    `json:"duration_secs"`
	DataBudgetStr string `json:"data_budget,omitempty"` // human-readable: "1GB", "unlimited", "" = keep current
}

RelayExtendRequest is the JSON body for POST /v1/relay-extend.

type RelayGrantInfo

type RelayGrantInfo struct {
	PeerID        string   `json:"peer_id"`
	Services      []string `json:"services,omitempty"`
	ExpiresAt     string   `json:"expires_at,omitempty"`
	CreatedAt     string   `json:"created_at"`
	Permanent     bool     `json:"permanent,omitempty"`
	RemainingSec  int      `json:"remaining_seconds"`
	DataBudget    int64    `json:"data_budget,omitempty"`     // raw bytes (I5)
	DataBudgetStr string   `json:"data_budget_str,omitempty"` // human-readable (I5)
}

RelayGrantInfo is the JSON representation of a relay data grant.

type RelayGrantRequest

type RelayGrantRequest struct {
	PeerID        string   `json:"peer_id"`
	DurationSec   int      `json:"duration_secs"`
	Services      []string `json:"services,omitempty"`
	Permanent     bool     `json:"permanent,omitempty"`
	DataBudgetStr string   `json:"data_budget,omitempty"` // human-readable: "500MB", "2GB", "unlimited", "" = use global default
}

RelayGrantRequest is the JSON body for POST /v1/relay-grant.

type RelayInfoResponse

type RelayInfoResponse struct {
	PeerID     string   `json:"peer_id"`
	Multiaddrs []string `json:"multiaddrs"`
}

RelayInfoResponse holds the relay's peer ID and multiaddrs.

type RemoteAdminClient

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

RemoteAdminClient connects to a running relay over a libp2p P2P stream using the /shurli/relay-admin/1.0.0 protocol. It provides the same high-level methods as AdminClient but operates over the network instead of a local Unix socket.

func NewRemoteAdminClient

func NewRemoteAdminClient(host libp2phost.Host, relayID peer.ID) *RemoteAdminClient

NewRemoteAdminClient creates a client for remote relay administration.

func (*RemoteAdminClient) AuthReload

func (c *RemoteAdminClient) AuthReload() error

AuthReload triggers a hot-reload of the relay's authorized_keys and gater.

func (*RemoteAdminClient) AuthorizePeer

func (c *RemoteAdminClient) AuthorizePeer(peerID, comment string) error

AuthorizePeer adds a peer to the relay's authorized_keys and triggers reload.

func (*RemoteAdminClient) ClearMOTD

func (c *RemoteAdminClient) ClearMOTD() error

ClearMOTD clears the relay's MOTD message.

func (*RemoteAdminClient) CreateGroup

func (c *RemoteAdminClient) CreateGroup(count, ttlSec, expiresSec int, namespace string) (*PairResponse, error)

CreateGroup creates a pairing group and returns the invite codes.

func (*RemoteAdminClient) CreateInvite

func (c *RemoteAdminClient) CreateInvite(caveats []string, ttlSec int) (map[string]string, error)

CreateInvite creates a macaroon-backed invite deposit.

func (*RemoteAdminClient) DeauthorizePeer

func (c *RemoteAdminClient) DeauthorizePeer(peerID string) error

DeauthorizePeer removes a peer from the relay's authorized_keys and triggers reload.

func (*RemoteAdminClient) GetInfo

func (c *RemoteAdminClient) GetInfo() (*RelayInfoResponse, error)

GetInfo returns the relay's peer ID and multiaddrs.

func (*RemoteAdminClient) GetMOTDStatus

func (c *RemoteAdminClient) GetMOTDStatus() (*MOTDStatusResponse, error)

GetMOTDStatus returns the current MOTD and goodbye status.

func (*RemoteAdminClient) GoodbyeShutdown

func (c *RemoteAdminClient) GoodbyeShutdown(message string) error

GoodbyeShutdown sets a goodbye and triggers relay shutdown.

func (*RemoteAdminClient) ListConnectedPeers

func (c *RemoteAdminClient) ListConnectedPeers() ([]ConnectedPeerInfo, error)

ListConnectedPeers returns currently connected peers with network details.

func (*RemoteAdminClient) ListGroups

func (c *RemoteAdminClient) ListGroups() ([]GroupInfo, error)

ListGroups returns all active pairing groups.

func (*RemoteAdminClient) ListInvites

func (c *RemoteAdminClient) ListInvites() ([]map[string]any, error)

ListInvites returns all invite deposits.

func (*RemoteAdminClient) ListPeers

func (c *RemoteAdminClient) ListPeers() ([]AuthorizedPeerInfo, error)

ListPeers returns all authorized peers from the relay's authorized_keys.

func (*RemoteAdminClient) ModifyInvite

func (c *RemoteAdminClient) ModifyInvite(id string, addCaveats []string) error

ModifyInvite adds caveats to a pending invite deposit (attenuation only).

func (*RemoteAdminClient) RelayExtend

func (c *RemoteAdminClient) RelayExtend(peerID string, durationSecs int, dataBudgetStr string) error

RelayExtend extends an existing relay data grant.

func (*RemoteAdminClient) RelayGrant

func (c *RemoteAdminClient) RelayGrant(peerID string, durationSecs int, services []string, permanent bool, dataBudgetStr string) (*RelayGrantInfo, error)

RelayGrant creates a time-limited data access grant for a peer.

func (*RemoteAdminClient) RelayGrants

func (c *RemoteAdminClient) RelayGrants() ([]RelayGrantInfo, error)

RelayGrants lists all active relay data grants.

func (*RemoteAdminClient) RelayRevoke

func (c *RemoteAdminClient) RelayRevoke(peerID string) error

RelayRevoke revokes a relay data grant and terminates active circuits.

func (*RemoteAdminClient) RetractGoodbye

func (c *RemoteAdminClient) RetractGoodbye() error

RetractGoodbye retracts an active goodbye announcement.

func (*RemoteAdminClient) RevokeGroup

func (c *RemoteAdminClient) RevokeGroup(id string) error

RevokeGroup revokes a pairing group by ID.

func (*RemoteAdminClient) RevokeInvite

func (c *RemoteAdminClient) RevokeInvite(id string) error

RevokeInvite revokes a pending invite deposit.

func (*RemoteAdminClient) Seal

func (c *RemoteAdminClient) Seal() error

Seal re-seals the relay vault.

func (*RemoteAdminClient) SealStatus

func (c *RemoteAdminClient) SealStatus() (*SealStatusResponse, error)

SealStatus returns the current seal status of the relay vault.

func (*RemoteAdminClient) SetGoodbye

func (c *RemoteAdminClient) SetGoodbye(message string) error

SetGoodbye sets a goodbye announcement (pushed to all connected peers).

func (*RemoteAdminClient) SetMOTD

func (c *RemoteAdminClient) SetMOTD(message string) error

SetMOTD sets the relay's MOTD message.

func (*RemoteAdminClient) SetPeerAttr

func (c *RemoteAdminClient) SetPeerAttr(peerID, key, value string) error

SetPeerAttr sets a key=value attribute on a peer in the relay's authorized_keys.

func (*RemoteAdminClient) Unseal

func (c *RemoteAdminClient) Unseal(password, totpCode string, yubikeyResponse []byte) error

Unseal sends a password (and optional TOTP code and Yubikey response) to unseal the relay vault.

func (*RemoteAdminClient) ZKPTreeInfo

func (c *RemoteAdminClient) ZKPTreeInfo() (*ZKPTreeInfoResponse, error)

ZKPTreeInfo returns the current ZKP Merkle tree state.

func (*RemoteAdminClient) ZKPTreeRebuild

func (c *RemoteAdminClient) ZKPTreeRebuild() (map[string]any, error)

ZKPTreeRebuild triggers a Merkle tree rebuild from authorized_keys.

type RemoteAdminHandler

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

RemoteAdminHandler handles remote admin requests from authorized peers over libp2p streams. It is a thin P2P-to-HTTP adapter that reuses all existing AdminServer handler functions.

Access control:

  • Admin peers: full access to all endpoints
  • Member peers: access to invite endpoints (/v1/pair*) when invite_policy is "open" (default)
  • Unauthorized peers: rejected

func NewRemoteAdminHandler

func NewRemoteAdminHandler(admin *AdminServer, authKeysPath string) *RemoteAdminHandler

NewRemoteAdminHandler creates a handler for the remote admin protocol.

func (*RemoteAdminHandler) HandleStream

func (h *RemoteAdminHandler) HandleStream(s network.Stream)

HandleStream processes an incoming remote admin stream. Flow: verify role -> read request -> check ACL -> dispatch -> write response -> close.

func (*RemoteAdminHandler) SetInvitePolicy

func (h *RemoteAdminHandler) SetInvitePolicy(policy string)

SetInvitePolicy configures who can create invites remotely. "admin-only" restricts to admin peers. Any other value (including empty) allows all members.

func (*RemoteAdminHandler) SetMetrics

func (h *RemoteAdminHandler) SetMetrics(m *sdk.Metrics)

SetMetrics attaches metrics to the handler.

type RemoteAdminRequest

type RemoteAdminRequest struct {
	Method string          `json:"method"`
	Path   string          `json:"path"`
	Body   json.RawMessage `json:"body,omitempty"`
}

RemoteAdminRequest is the JSON request frame sent over a P2P stream.

type RemoteAdminResponse

type RemoteAdminResponse struct {
	Status int             `json:"status"`
	Body   json.RawMessage `json:"body,omitempty"`
}

RemoteAdminResponse is the JSON response frame sent back over a P2P stream.

type SealStatusResponse

type SealStatusResponse struct {
	Sealed       bool `json:"sealed"`
	TOTPEnabled  bool `json:"totp_enabled"`
	AutoSealMins int  `json:"auto_seal_minutes"`
	Initialized  bool `json:"initialized"`
}

SealStatusResponse is the JSON response for GET /v1/seal-status.

type TokenStore

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

TokenStore manages in-memory pairing tokens for the relay. All tokens are lost on relay restart (by design).

func NewTokenStore

func NewTokenStore() *TokenStore

NewTokenStore creates an empty token store with the default capacity.

func NewTokenStoreWithCapacity

func NewTokenStoreWithCapacity(maxGroups int) *TokenStore

NewTokenStoreWithCapacity creates a token store with a custom group capacity. Use 0 for unlimited (not recommended in production).

func (*TokenStore) ActiveGroupCount

func (ts *TokenStore) ActiveGroupCount() int

ActiveGroupCount returns the number of non-expired groups.

func (*TokenStore) ActiveGroupCountByPeer

func (ts *TokenStore) ActiveGroupCountByPeer(peerID peer.ID) int

ActiveGroupCountByPeer returns the number of non-expired groups created by a specific peer.

func (*TokenStore) AllGroupsUsed

func (ts *TokenStore) AllGroupsUsed() bool

AllGroupsUsed returns true if every code in every active group has been used. Used to auto-disable enrollment mode when all invites are consumed.

func (*TokenStore) CleanExpired

func (ts *TokenStore) CleanExpired() int

CleanExpired removes all expired groups and clears stale InProgress flags. Returns how many groups were removed.

func (*TokenStore) ClearInProgress

func (ts *TokenStore) ClearInProgress(groupID string, idx int)

ClearInProgress releases the in-progress flag on a slot after a failed PAKE.

func (*TokenStore) CreateGroup

func (ts *TokenStore) CreateGroup(count int, ttl time.Duration, ns string, peerTTL time.Duration, createdBy peer.ID) (tokens [][]byte, groupID string, err error)

CreateGroup generates a pairing group with count codes using the default 16-byte tokens. Returns the raw tokens (caller encodes into invite codes) and the group ID.

func (*TokenStore) CreateGroupShort

func (ts *TokenStore) CreateGroupShort(count int, ttl time.Duration, ns string, peerTTL time.Duration, createdBy peer.ID) (tokens [][]byte, groupID string, err error)

CreateGroupShort generates a pairing group with 10-byte tokens for short invite codes.

func (*TokenStore) CreateGroupWithTokenSize

func (ts *TokenStore) CreateGroupWithTokenSize(count int, ttl time.Duration, ns string, peerTTL time.Duration, tokenSize int, createdBy peer.ID, maxGroupsPerPeer int) (tokens [][]byte, groupID string, err error)

CreateGroupWithTokenSize generates a pairing group with configurable token size. If maxGroupsPerPeer > 0 and createdBy is non-empty, atomically checks the per-peer quota under the write lock to prevent TOCTOU race conditions.

func (*TokenStore) GetDepositID

func (ts *TokenStore) GetDepositID(groupID string, idx int) string

GetDepositID returns the deposit ID for a code slot.

func (*TokenStore) GetGroupPeers

func (ts *TokenStore) GetGroupPeers(groupID string, excludeIdx int) []PeerInfo

GetGroupPeers returns all joined peers in the group except the one at excludeIdx.

func (*TokenStore) GroupCount

func (ts *TokenStore) GroupCount(groupID string) int

GroupCount returns the total number of codes in a group.

func (*TokenStore) GroupCreator

func (ts *TokenStore) GroupCreator(groupID string) peer.ID

GroupCreator returns the peer that created a group (empty for local admin).

func (*TokenStore) IsGroupComplete

func (ts *TokenStore) IsGroupComplete(groupID string) bool

IsGroupComplete returns true if all codes in the group have been used.

func (*TokenStore) List

func (ts *TokenStore) List() []GroupInfo

List returns a snapshot of all groups (active and expired).

func (*TokenStore) MarkUsed

func (ts *TokenStore) MarkUsed(groupID string, idx int, peerID peer.ID, name string) error

MarkUsed marks a code slot as consumed after successful PAKE. Zeroizes the raw token after marking.

func (*TokenStore) RecordFailedAttempt

func (ts *TokenStore) RecordFailedAttempt(token []byte)

RecordFailedAttempt increments the attempt counter for a token. Used when authentication succeeds (token found) but downstream steps fail.

func (*TokenStore) RecordFailedAttemptByHash

func (ts *TokenStore) RecordFailedAttemptByHash(tokenHash [32]byte)

RecordFailedAttemptByHash increments the attempt counter for a token by its hash. Uses the hash index for O(1) lookup.

func (*TokenStore) Revoke

func (ts *TokenStore) Revoke(groupID string) error

Revoke removes a pairing group by ID.

func (*TokenStore) SetDepositID

func (ts *TokenStore) SetDepositID(groupID, depositID string)

SetDepositID links a deposit to all code slots in a group.

func (*TokenStore) SetHMACProof

func (ts *TokenStore) SetHMACProof(groupID string, slotIdx int, proof []byte)

SetHMACProof stores the HMAC commitment proof for a code slot.

func (*TokenStore) ValidateAndUse

func (ts *TokenStore) ValidateAndUse(token []byte, peerID peer.ID, name string) (*PairingGroup, int, error)

ValidateAndUse atomically validates a token and marks it as used. Returns the group and the slot index on success. Uses the hash index for O(1) lookup instead of scanning all groups.

func (*TokenStore) ValidateForPAKE

func (ts *TokenStore) ValidateForPAKE(tokenHash [32]byte) (*PairingGroup, int, []byte, error)

ValidateForPAKE looks up a slot by token hash and atomically marks it as in-progress to prevent TOCTOU races. Returns the group, slot index, and raw token for PAKE session key derivation. The slot is NOT consumed; call MarkUsed after PAKE succeeds, or ClearInProgress if PAKE fails. Uses the hash index for O(1) lookup instead of scanning all groups.

type UnsealHandler

type UnsealHandler struct {
	Vault        *vault.Vault
	AuthKeysPath string
	StateFile    string       // path to lockout state file (empty = no persistence)
	Metrics      *sdk.Metrics // nil-safe: metrics are optional
	// contains filtered or unexported fields
}

UnsealHandler handles remote unseal requests from admin peers.

func NewUnsealHandler

func NewUnsealHandler(v *vault.Vault, authKeysPath, stateFile string) *UnsealHandler

NewUnsealHandler creates a handler for the remote unseal protocol. stateFile is the path to persist lockout state (empty string disables persistence).

func (*UnsealHandler) HandleStream

func (h *UnsealHandler) HandleStream(s network.Stream)

HandleStream processes an incoming unseal stream. The relay sends a 16-byte challenge nonce first, then reads the client request. v2 clients echo the nonce back (replay protection). v1 clients skip it (legacy).

type UnsealRequest

type UnsealRequest struct {
	Passphrase      string `json:"passphrase"`
	TOTPCode        string `json:"totp_code,omitempty"`
	YubikeyResponse []byte `json:"yubikey_response,omitempty"`
}

UnsealRequest is the JSON body for POST /v1/unseal.

type VaultInitRequest

type VaultInitRequest struct {
	SeedBytes    []byte `json:"seed_bytes"` // BIP39 entropy from unified seed
	Mnemonic     string `json:"mnemonic"`   // BIP39 phrase for seed hash verification
	Password     string `json:"password"`
	EnableTOTP   bool   `json:"enable_totp"`
	AutoSealMins int    `json:"auto_seal_minutes"`
}

VaultInitRequest is the JSON body for POST /v1/vault/init.

type VaultInitResponse

type VaultInitResponse struct {
	TOTPUri string `json:"totp_uri,omitempty"`
}

VaultInitResponse is the JSON response for POST /v1/vault/init.

type WaitingStream

type WaitingStream struct {
	Stream network.Stream
	Idx    int
}

WaitingStream tracks a peer that is waiting for group completion.

type ZKPAuthClient

type ZKPAuthClient struct {
	Host    host.Host
	Prover  *zkp.Prover
	Tree    *zkp.MerkleTree
	Metrics *sdk.Metrics // nil-safe
}

ZKPAuthClient handles client-side ZKP anonymous authentication with a relay.

func (*ZKPAuthClient) Authenticate

func (c *ZKPAuthClient) Authenticate(ctx context.Context, relayPeer peer.ID, roleRequired uint64) error

Authenticate opens a stream to the relay and proves membership anonymously. The caller's peer ID is never revealed as part of the ZKP protocol.

Parameters:

  • relayPeer: the relay's peer ID to connect to
  • roleRequired: 0 = any, 1 = admin, 2 = member

Returns nil on successful authentication.

type ZKPAuthHandler

type ZKPAuthHandler struct {
	Metrics *sdk.Metrics // nil-safe
	// contains filtered or unexported fields
}

ZKPAuthHandler handles ZKP anonymous authentication streams on the relay.

func NewZKPAuthHandler

func NewZKPAuthHandler(authKeysPath string, keysDir string) (*ZKPAuthHandler, error)

NewZKPAuthHandler creates a handler. On first run, it auto-bootstraps the PLONK circuit keys (compile + SRS + setup, ~2-5s one-time cost). The tree must be initialized via RebuildTree before the handler can serve requests.

func (*ZKPAuthHandler) Challenges

func (h *ZKPAuthHandler) Challenges() *zkp.ChallengeStore

Challenges returns the underlying ChallengeStore for lifecycle management (e.g., starting the cleanup goroutine).

func (*ZKPAuthHandler) CleanPeerSeen

func (h *ZKPAuthHandler) CleanPeerSeen()

CleanPeerSeen evicts stale entries from the per-peer rate limit map. Entries older than 10x the rate limit window are removed. Safe to call from a periodic goroutine.

func (*ZKPAuthHandler) HandleStream

func (h *ZKPAuthHandler) HandleStream(s network.Stream)

HandleStream processes an incoming ZKP auth stream.

func (*ZKPAuthHandler) KeysDir

func (h *ZKPAuthHandler) KeysDir() string

KeysDir returns the directory containing the PLONK circuit key files.

func (*ZKPAuthHandler) RebuildTree

func (h *ZKPAuthHandler) RebuildTree() error

RebuildTree rebuilds the Merkle tree from authorized_keys with committed reputation scores. Safe to call while serving requests.

func (*ZKPAuthHandler) SetScores

func (h *ZKPAuthHandler) SetScores(scores map[peer.ID]int)

SetScores updates the reputation scores committed in tree leaves. Call RebuildTree after updating scores to commit the new values. Passing nil clears all scores (all peers default to 0).

func (*ZKPAuthHandler) TreeInfo

func (h *ZKPAuthHandler) TreeInfo() (root []byte, leafCount int, depth int, ok bool)

TreeInfo returns the current tree state. Returns nil fields if no tree is built.

type ZKPTreeInfoResponse

type ZKPTreeInfoResponse struct {
	Ready     bool   `json:"ready"`
	Root      string `json:"root,omitempty"`
	LeafCount int    `json:"leaf_count,omitempty"`
	Depth     int    `json:"depth,omitempty"`
}

ZKPTreeInfoResponse is the JSON response for GET /v1/zkp/tree-info.

Jump to

Keyboard shortcuts

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