client

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package client provides JSON-RPC client functionality for OpenADP server communication.

Package keygen provides high-level functions for generating encryption keys using the OpenADP distributed secret sharing system.

This module handles the complete workflow: 1. Generate random secrets and split into shares 2. Register shares with distributed servers 3. Recover secrets from servers during decryption 4. Derive encryption keys using cryptographic functions

This replaces traditional password-based key derivation (like Scrypt) with a distributed approach that provides better security and recovery properties.

Package sharing implements Shamir's secret sharing scheme.

This module provides functions for: - Creating random shares from a secret - Recovering secrets from a threshold number of shares - Working with elliptic curve points for OpenADP

Based on: https://en.wikipedia.org/wiki/Shamir%27s_secret_sharing

Index

Constants

View Source
const (
	ErrorCodeNetworkFailure       = 1001
	ErrorCodeAuthenticationFailed = 1002
	ErrorCodeInvalidRequest       = 1003
	ErrorCodeServerError          = 1004
	ErrorCodeEncryptionFailed     = 1005
	ErrorCodeNoLiveServers        = 1006
	ErrorCodeInvalidResponse      = 1007
)

Common error codes

Variables

This section is empty.

Functions

func DeriveIdentifiers

func DeriveIdentifiers(filename, userID, deviceID string) (uid, did, bid string)

DeriveIdentifiers derives UID, DID, and BID from filename and userID for backward compatibility

func DiscoverServerURLs

func DiscoverServerURLs(registryURL string) []string

DiscoverServerURLs attempts to discover server URLs from registry with fallback

func GetFallbackServers

func GetFallbackServers() []string

GetFallbackServers returns a list of hardcoded fallback servers

func GetServerURLs

func GetServerURLs(registryURL string) ([]string, error)

GetServerURLs gets just the server URLs (for backward compatibility)

func GetServersByCountry

func GetServersByCountry(registryURL string) (map[string][]ServerInfo, error)

GetServersByCountry groups servers by country

func ParseServerPublicKey

func ParseServerPublicKey(keyB64 string) ([]byte, error)

ParseServerPublicKey parses a base64-encoded server public key

func RecoverPointSecret

func RecoverPointSecret(shares []*PointShare) (*common.Point2D, error)

RecoverPointSecret recovers s*B from threshold number of point shares using Lagrange interpolation This is used when the shares are points on the elliptic curve (si * B) rather than scalar values

func RecoverSB

func RecoverSB(shares []*PointShare) (*common.Point2D, error)

RecoverSB recovers s*B from threshold number of shares s[i]*B using Lagrange interpolation

The formula is:

w[i] = product(j != i, x[j]/(x[j] - x[i]))
s*B = sum(w[i] * s[i]*B)

func RecoverSecret

func RecoverSecret(shares []*Share) (*big.Int, error)

RecoverSecret recovers the original secret from threshold number of shares

func ScrapeServerURLs

func ScrapeServerURLs(registryURL string) ([]string, error)

ScrapeServerURLs is an alias for GetServerURLs for backward compatibility

func SetDebugMode added in v0.1.2

func SetDebugMode(enabled bool)

SetDebugMode enables or disables debug mode for deterministic operations. This function provides access to debug mode for tools that use the client package directly.

Types

type AuthCodes

type AuthCodes struct {
	BaseAuthCode    string            `json:"base_auth_code"`
	ServerAuthCodes map[string]string `json:"server_auth_codes"`
}

AuthCodes represents authentication codes for OpenADP servers

func GenerateAuthCodes

func GenerateAuthCodes(serverURLs []string) *AuthCodes

GenerateAuthCodes generates authentication codes for OpenADP servers.

This creates a base authentication code (256-bit SHA256 hash) and derives server-specific codes for each server URL, matching the expected 64-character hex format.

type BackupInfo

type BackupInfo struct {
	UID        string `json:"uid"`
	BID        string `json:"bid"`
	Version    int    `json:"version"`
	NumGuesses int    `json:"num_guesses"`
	MaxGuesses int    `json:"max_guesses"`
	Expiration int    `json:"expiration"`
}

type Client

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

Client provides high-level multi-server client for OpenADP operations

func NewClient

func NewClient(serversURL string, fallbackServers []string, echoTimeout time.Duration, maxWorkers int) *Client

NewClient creates a new high-level OpenADP client with server discovery

func NewClientWithServerInfo

func NewClientWithServerInfo(serverInfos []ServerInfo, echoTimeout time.Duration, maxWorkers int) *Client

NewClientWithServerInfo creates a new OpenADP client with predefined server information

func (*Client) Echo

func (c *Client) Echo(message string) (string, error)

Echo sends an echo message to test connectivity

func (*Client) GetLiveServerCount

func (c *Client) GetLiveServerCount() int

GetLiveServerCount returns the number of currently live servers

func (*Client) GetLiveServerURLs

func (c *Client) GetLiveServerURLs() []string

GetLiveServerURLs returns URLs of all currently live servers

func (*Client) GetServerInfo

func (c *Client) GetServerInfo() (map[string]interface{}, error)

GetServerInfo gets information from the first available server

func (*Client) GetServerInfoStandardized

func (c *Client) GetServerInfoStandardized() (*ServerInfoResponse, error)

GetServerInfoStandardized implements the standardized interface

func (*Client) GetServerURL

func (c *Client) GetServerURL() string

GetServerURL implements the standardized interface (returns first live server)

func (*Client) ListBackups

func (c *Client) ListBackups(uid string) ([]map[string]interface{}, error)

ListBackups lists backups for a user from the first available server

func (*Client) ListBackupsStandardized

func (c *Client) ListBackupsStandardized(request *ListBackupsRequest) (*ListBackupsResponse, error)

ListBackupsStandardized implements the standardized interface

func (*Client) Ping

func (c *Client) Ping() error

Ping tests connectivity to servers

func (*Client) RecoverSecret

func (c *Client) RecoverSecret(authCode, uid, did, bid, b string, guessNum int, authData map[string]interface{}) (map[string]interface{}, error)

RecoverSecret recovers a secret from servers with failover

func (*Client) RecoverSecretStandardized

func (c *Client) RecoverSecretStandardized(request *RecoverSecretRequest) (*RecoverSecretResponse, error)

RecoverSecretStandardized implements the standardized interface

func (*Client) RefreshServers

func (c *Client) RefreshServers() error

RefreshServers re-scrapes and re-tests all servers to refresh the live server list

func (*Client) RegisterSecret

func (c *Client) RegisterSecret(uid, did, bid string, version, x int, y []byte, maxGuesses, expiration int, authData map[string]interface{}) (bool, error)

RegisterSecret registers a secret across multiple servers with failover

func (*Client) RegisterSecretStandardized

func (c *Client) RegisterSecretStandardized(request *RegisterSecretRequest) (*RegisterSecretResponse, error)

RegisterSecretStandardized implements the standardized interface

func (*Client) SetServerSelectionStrategy

func (c *Client) SetServerSelectionStrategy(strategy ServerSelectionStrategy)

SetServerSelectionStrategy implements the MultiServerClientInterface

func (*Client) SupportsEncryption

func (c *Client) SupportsEncryption() bool

SupportsEncryption implements the standardized interface

func (*Client) TestConnection

func (c *Client) TestConnection() error

TestConnection implements the standardized interface

type ClientConfig

type ClientConfig struct {
	ServerURL        string   `json:"server_url,omitempty"`
	ServerURLs       []string `json:"server_urls,omitempty"`
	RegistryURL      string   `json:"registry_url,omitempty"`
	PublicKey        string   `json:"public_key,omitempty"` // Base64 encoded
	TimeoutSeconds   int      `json:"timeout_seconds,omitempty"`
	MaxWorkers       int      `json:"max_workers,omitempty"`
	EnableEncryption bool     `json:"enable_encryption,omitempty"`
	UserAgent        string   `json:"user_agent,omitempty"`
}

ClientConfig holds configuration for client creation

type EncryptedOpenADPClient

type EncryptedOpenADPClient struct {
	URL        string
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

EncryptedOpenADPClient extends the basic client with Noise-NK encryption support

func NewEncryptedOpenADPClient

func NewEncryptedOpenADPClient(url string, serverPublicKey []byte) *EncryptedOpenADPClient

NewEncryptedOpenADPClient creates a new encrypted OpenADP client

func (*EncryptedOpenADPClient) Echo

func (c *EncryptedOpenADPClient) Echo(message string, encrypted bool) (string, error)

Echo sends an echo message with optional encryption

func (*EncryptedOpenADPClient) GetServerInfo

func (c *EncryptedOpenADPClient) GetServerInfo() (map[string]interface{}, error)

GetServerInfo gets server information

func (*EncryptedOpenADPClient) GetServerInfoStandardized

func (c *EncryptedOpenADPClient) GetServerInfoStandardized() (*ServerInfoResponse, error)

GetServerInfoStandardized implements the standardized interface

func (*EncryptedOpenADPClient) GetServerURL

func (c *EncryptedOpenADPClient) GetServerURL() string

GetServerURL implements the standardized interface

func (*EncryptedOpenADPClient) HasPublicKey

func (c *EncryptedOpenADPClient) HasPublicKey() bool

HasPublicKey returns true if the client has a server public key for encryption

func (*EncryptedOpenADPClient) ListBackups

func (c *EncryptedOpenADPClient) ListBackups(uid string, encrypted bool, authData map[string]interface{}) ([]map[string]interface{}, error)

ListBackups lists all backups for a user

func (*EncryptedOpenADPClient) ListBackupsStandardized

func (c *EncryptedOpenADPClient) ListBackupsStandardized(request *ListBackupsRequest) (*ListBackupsResponse, error)

ListBackupsStandardized implements the standardized interface

func (*EncryptedOpenADPClient) Ping

func (c *EncryptedOpenADPClient) Ping() error

Ping tests connectivity to the server (alias for Echo with "ping" message)

func (*EncryptedOpenADPClient) RecoverSecret

func (c *EncryptedOpenADPClient) RecoverSecret(authCode, uid, did, bid, b string, guessNum int, encrypted bool, authData map[string]interface{}) (map[string]interface{}, error)

RecoverSecret recovers a secret share from the server

func (*EncryptedOpenADPClient) RecoverSecretStandardized

func (c *EncryptedOpenADPClient) RecoverSecretStandardized(request *RecoverSecretRequest) (*RecoverSecretResponse, error)

RecoverSecretStandardized implements the standardized interface

func (*EncryptedOpenADPClient) RegisterSecret

func (c *EncryptedOpenADPClient) RegisterSecret(authCode, uid, did, bid string, version, x int, y string, maxGuesses, expiration int, encrypted bool, authData map[string]interface{}) (bool, error)

RegisterSecret registers a secret share with the server

func (*EncryptedOpenADPClient) RegisterSecretStandardized

func (c *EncryptedOpenADPClient) RegisterSecretStandardized(request *RegisterSecretRequest) (*RegisterSecretResponse, error)

RegisterSecretStandardized implements the standardized interface

func (*EncryptedOpenADPClient) SupportsEncryption

func (c *EncryptedOpenADPClient) SupportsEncryption() bool

SupportsEncryption implements the standardized interface

func (*EncryptedOpenADPClient) TestConnection

func (c *EncryptedOpenADPClient) TestConnection() error

TestConnection implements the standardized interface

type GenerateEncryptionKeyResult

type GenerateEncryptionKeyResult struct {
	EncryptionKey []byte
	Error         string
	ServerURLs    []string
	Threshold     int
	AuthCodes     *AuthCodes
}

GenerateEncryptionKeyResult represents the result of key generation

func GenerateEncryptionKey

func GenerateEncryptionKey(identity *Identity, password string, maxGuesses, expiration int,
	serverInfos []ServerInfo) *GenerateEncryptionKeyResult

GenerateEncryptionKey generates an encryption key using OpenADP distributed secret sharing.

FULL DISTRIBUTED IMPLEMENTATION: This implements the complete OpenADP protocol: 1. Uses the provided Identity (UID, DID, BID) as the primary key 2. Converts password to cryptographic PIN 3. Distributes secret shares to OpenADP servers via JSON-RPC 4. Uses authentication codes for secure server communication 5. Uses threshold cryptography for recovery

type Identity added in v0.1.2

type Identity struct {
	UID string `json:"uid"` // User ID - uniquely identifies the user
	DID string `json:"did"` // Device ID - identifies the device/hostname
	BID string `json:"bid"` // Backup ID - identifies the specific backup/file
}

Identity represents the primary key tuple for secret shares stored on servers

func (*Identity) String added in v0.1.2

func (id *Identity) String() string

String returns a human-readable representation of the identity

type JSONRPCError

type JSONRPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

JSONRPCError represents a JSON-RPC 2.0 error

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params"`
	ID      int         `json:"id"`
}

JSONRPCRequest represents a JSON-RPC 2.0 request

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string        `json:"jsonrpc"`
	Result  interface{}   `json:"result,omitempty"`
	Error   *JSONRPCError `json:"-"` // Custom unmarshaling
	ID      int           `json:"id"`
}

JSONRPCResponse represents a JSON-RPC 2.0 response

func (*JSONRPCResponse) UnmarshalJSON

func (r *JSONRPCResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON handles custom unmarshaling for JSONRPCResponse to support both string and structured errors

type ListBackupsRequest

type ListBackupsRequest struct {
	UID       string                 `json:"uid"`
	AuthCode  string                 `json:"auth_code"`
	Encrypted bool                   `json:"encrypted,omitempty"`
	AuthData  map[string]interface{} `json:"auth_data,omitempty"`
}

type ListBackupsResponse

type ListBackupsResponse struct {
	Backups []BackupInfo `json:"backups"`
}

type ListBackupsResult

type ListBackupsResult struct {
	UID        string `json:"uid"`
	DID        string `json:"did"`
	BID        string `json:"bid"`
	Version    int    `json:"version"`
	NumGuesses int    `json:"num_guesses"`
	MaxGuesses int    `json:"max_guesses"`
	Expiration int    `json:"expiration"`
}

ListBackupsResult represents a backup entry from ListBackups method

type OpenADPClient

type OpenADPClient struct {
	URL        string
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

OpenADPClient represents a basic JSON-RPC client for communicating with OpenADP servers

func NewOpenADPClient

func NewOpenADPClient(url string) *OpenADPClient

NewOpenADPClient creates a new basic OpenADP client

func (*OpenADPClient) Echo

func (c *OpenADPClient) Echo(message string) (string, error)

Echo tests connectivity to the server

func (*OpenADPClient) GetServerInfo

func (c *OpenADPClient) GetServerInfo() (map[string]interface{}, error)

GetServerInfo gets server information

func (*OpenADPClient) GetServerInfoStandardized

func (c *OpenADPClient) GetServerInfoStandardized() (*ServerInfoResponse, error)

GetServerInfoStandardized implements the standardized interface

func (*OpenADPClient) GetServerURL

func (c *OpenADPClient) GetServerURL() string

GetServerURL implements the standardized interface

func (*OpenADPClient) ListBackups

func (c *OpenADPClient) ListBackups(uid string) ([]ListBackupsResult, error)

ListBackups lists all backups for a user

func (*OpenADPClient) ListBackupsStandardized

func (c *OpenADPClient) ListBackupsStandardized(request *ListBackupsRequest) (*ListBackupsResponse, error)

ListBackupsStandardized implements the standardized interface

func (*OpenADPClient) Ping

func (c *OpenADPClient) Ping() error

Ping tests connectivity to the server (alias for Echo with "ping" message)

func (*OpenADPClient) RecoverSecretStandardized

func (c *OpenADPClient) RecoverSecretStandardized(request *RecoverSecretRequest) (*RecoverSecretResponse, error)

RecoverSecretStandardized implements the standardized interface

func (*OpenADPClient) RegisterSecretStandardized

func (c *OpenADPClient) RegisterSecretStandardized(request *RegisterSecretRequest) (*RegisterSecretResponse, error)

RegisterSecretStandardized implements the standardized interface

func (*OpenADPClient) SupportsEncryption

func (c *OpenADPClient) SupportsEncryption() bool

SupportsEncryption implements the standardized interface

func (*OpenADPClient) TestConnection

func (c *OpenADPClient) TestConnection() error

TestConnection implements the standardized interface

type OpenADPError

type OpenADPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

Error types for consistent error handling across languages

func (*OpenADPError) Error

func (e *OpenADPError) Error() string

type PointShare

type PointShare struct {
	X     *big.Int
	Point *common.Point2D
}

PointShare represents a (x, point) pair

type RecoverEncryptionKeyResult

type RecoverEncryptionKeyResult struct {
	EncryptionKey []byte
	Error         string
}

RecoverEncryptionKeyResult represents the result of key recovery

func RecoverEncryptionKeyWithServerInfo

func RecoverEncryptionKeyWithServerInfo(identity *Identity, password string, serverInfos []ServerInfo, threshold int, authCodes *AuthCodes) *RecoverEncryptionKeyResult

RecoverEncryptionKeyWithServerInfo recovers an encryption key using OpenADP distributed secret sharing.

FULL DISTRIBUTED IMPLEMENTATION: This implements the complete OpenADP protocol: 1. Uses the provided Identity (UID, DID, BID) as the primary key 2. Converts password to the same PIN 3. Recovers shares from OpenADP servers via JSON-RPC with Noise-NK encryption 4. Reconstructs the original secret using threshold cryptography 5. Derives the same encryption key

type RecoverSecretRequest

type RecoverSecretRequest struct {
	AuthCode  string                 `json:"auth_code"`
	DID       string                 `json:"did"`
	BID       string                 `json:"bid"`
	B         string                 `json:"b"` // Base64 encoded point
	GuessNum  int                    `json:"guess_num"`
	Encrypted bool                   `json:"encrypted,omitempty"`
	AuthData  map[string]interface{} `json:"auth_data,omitempty"`
}

type RecoverSecretResponse

type RecoverSecretResponse struct {
	Version    int    `json:"version"`
	X          int    `json:"x"`
	SiB        string `json:"si_b"` // Base64 encoded point
	NumGuesses int    `json:"num_guesses"`
	MaxGuesses int    `json:"max_guesses"`
	Expiration int    `json:"expiration"`
}

type RegisterSecretRequest

type RegisterSecretRequest struct {
	AuthCode   string                 `json:"auth_code"`
	UID        string                 `json:"uid"`
	DID        string                 `json:"did"`
	BID        string                 `json:"bid"`
	Version    int                    `json:"version"`
	X          int                    `json:"x"`
	Y          string                 `json:"y"` // Base64 encoded point
	MaxGuesses int                    `json:"max_guesses"`
	Expiration int                    `json:"expiration"`
	Encrypted  bool                   `json:"encrypted,omitempty"`
	AuthData   map[string]interface{} `json:"auth_data,omitempty"`
}

type RegisterSecretResponse

type RegisterSecretResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
}

type ServerInfo

type ServerInfo struct {
	URL              string `json:"url"`
	PublicKey        string `json:"public_key"`
	Country          string `json:"country"`
	RemainingGuesses int    `json:"remaining_guesses,omitempty"` // -1 means unknown, >=0 means known remaining guesses
}

ServerInfo represents information about an OpenADP server

func ConvertURLsToServerInfo

func ConvertURLsToServerInfo(urls []string) []ServerInfo

ConvertURLsToServerInfo converts a list of URLs to ServerInfo structs (for backward compatibility)

func DiscoverServers

func DiscoverServers(registryURL string) []ServerInfo

DiscoverServers attempts to discover servers from registry with fallback

func FetchRemainingGuessesForServers added in v0.1.2

func FetchRemainingGuessesForServers(identity *Identity, serverInfos []ServerInfo) []ServerInfo

FetchRemainingGuessesForServers fetches remaining guesses for each server and updates ServerInfo objects.

func GetFallbackServerInfo

func GetFallbackServerInfo() []ServerInfo

GetFallbackServerInfo returns detailed fallback server information

func GetServers

func GetServers(registryURL string) ([]ServerInfo, error)

GetServers fetches server information from the OpenADP registry

func SelectServersByRemainingGuesses added in v0.1.2

func SelectServersByRemainingGuesses(serverInfos []ServerInfo, threshold int) []ServerInfo

SelectServersByRemainingGuesses selects servers intelligently based on remaining guesses.

Strategy: 1. Filter out servers with 0 remaining guesses (exhausted) 2. Sort by remaining guesses (descending) to use servers with most guesses first 3. Servers with unknown remaining guesses (-1) are treated as having infinite guesses 4. Select threshold + 2 servers for redundancy

type ServerInfoResponse

type ServerInfoResponse struct {
	ServerVersion    string                 `json:"server_version"`
	NoiseNKPublicKey string                 `json:"noise_nk_public_key,omitempty"`
	SupportedMethods []string               `json:"supported_methods"`
	MaxRequestSize   int                    `json:"max_request_size,omitempty"`
	RateLimits       map[string]interface{} `json:"rate_limits,omitempty"`
}

type ServerSelectionStrategy

type ServerSelectionStrategy int

ServerSelectionStrategy defines how to choose servers for operations

const (
	FirstAvailable ServerSelectionStrategy = iota
	RoundRobin
	Random
	LowestLatency
)

type ServersResponse

type ServersResponse struct {
	Servers []ServerInfo `json:"servers"`
}

ServersResponse represents the JSON response from the server registry

type Share

type Share struct {
	X, Y *big.Int
}

Share represents a (x, y) coordinate pair

func MakeRandomShares

func MakeRandomShares(secret *big.Int, minimum, shares int) ([]*Share, error)

MakeRandomShares generates random Shamir shares for a given secret

type StandardMultiServerClientInterface

type StandardMultiServerClientInterface interface {
	StandardOpenADPClientInterface

	// Multi-server Operations
	GetLiveServerCount() int
	GetLiveServerURLs() []string
	RefreshServers() error

	// Server Selection Strategy
	SetServerSelectionStrategy(strategy ServerSelectionStrategy)
}

StandardMultiServerClientInterface defines interface for managing multiple servers

type StandardOpenADPClientInterface

type StandardOpenADPClientInterface interface {
	// Core Operations - Standardized
	RegisterSecretStandardized(request *RegisterSecretRequest) (*RegisterSecretResponse, error)
	RecoverSecretStandardized(request *RecoverSecretRequest) (*RecoverSecretResponse, error)
	ListBackupsStandardized(request *ListBackupsRequest) (*ListBackupsResponse, error)

	// Utility Operations - Standardized
	GetServerInfoStandardized() (*ServerInfoResponse, error)

	// Connection Management
	TestConnection() error
	GetServerURL() string
	SupportsEncryption() bool
}

StandardOpenADPClientInterface defines the standardized interface for OpenADP client operations This interface is designed to be easily implementable across different programming languages Legacy clients can implement this via wrapper methods (e.g., RegisterSecretStandardized)

Jump to

Keyboard shortcuts

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