shared

package
v0.1.20 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KeyIDLength       = 32
	NonceSize         = 12
	SignatureSize     = ed25519.SignatureSize // 64 bytes for Ed25519 signature
	PublicKeySize     = 32
	PrivateKeySize    = 32
	SharedKeySize     = 32
	FingerprintLength = 16
)
View Source
const (
	RoleOwner    = "owner"
	RoleAdmin    = "admin"
	RoleDeployer = "deployer"
	RoleReader   = "reader"
)

RBAC Roles

Variables

View Source
var (
	ErrNilKey                = errors.New("crypto: nil key provided")
	ErrInvalidClientID       = errors.New("auth: invalid client ID")
	ErrInvalidSigningMethod  = errors.New("auth: invalid signing method")
	ErrKeyMismatch           = errors.New("auth: key ID mismatch")
	ErrInvalidAudience       = errors.New("auth: invalid audience")
	ErrInvalidToken          = errors.New("auth: invalid token")
	ErrAuthKeyNotInitialized = errors.New("auth: WebSocket auth key not initialized")
	ErrEmptyClientID         = errors.New("auth: empty client ID")
)
View Source
var (
	SharedLogger = PackageLogger("shared", "🔗 SHARED")
)
View Source
var Version = "v0.1.19"

Version is the current CLI version. It is overridden at build time via ldflags: -X github.com/Golangcodes/nextdeploy/shared.Version=<tag>

Functions

func DecodeFromBase64

func DecodeFromBase64(encoded string) ([]byte, error)

func DecodeFromHex

func DecodeFromHex(encoded string) ([]byte, error)

func Decrypt

func Decrypt(cipherText []byte, key []byte, nonce []byte) ([]byte, error)

func DecryptMessage

func DecryptMessage(key []byte, data []byte) ([]byte, uint64, error)

func DeriveSessionKey

func DeriveSessionKey(claims *WSClaims) (sessionKey []byte, err error)

func DeriveSharedKey

func DeriveSharedKey(privateKey *ecdh.PrivateKey, publicKey *ecdh.PublicKey) ([]byte, error)

func DeserializeFromJSON

func DeserializeFromJSON(jsonStr string, data interface{}) error

func EncodeToBase64

func EncodeToBase64(data []byte) string

func EncodeToHex

func EncodeToHex(data []byte) string

func Encrypt

func Encrypt(data []byte, key []byte) ([]byte, []byte, error)

func EncryptMessage

func EncryptMessage(key []byte, sequence uint64, payload interface{}) ([]byte, error)

func GenerateCommandID

func GenerateCommandID() string

GenerateCommandID creates a unique ID for command tracking

func GenerateFingerprint

func GenerateFingerprint(publicKey ed25519.PublicKey) (string, error)

func GenerateKeyFingerprint

func GenerateKeyFingerprint(publicKey *ecdsa.PublicKey) string

func GenerateSessionID

func GenerateSessionID() string

func GenerateWSToken

func GenerateWSToken(privateKey *ecdsa.PrivateKey, clientID string, opts JWTOptions) (string, error)

func GetCurrentTimestamp

func GetCurrentTimestamp() int64

GetCurrentTimestamp returns the current Unix timestamp

func HasRequiredRole

func HasRequiredRole(role Identity, Role string) bool

func LoadKeyFromFile

func LoadKeyFromFile(filename string) ([]byte, error)

Load key from env file

func RunCryptoHealthChecks

func RunCryptoHealthChecks() error

func SecureKeyMemory

func SecureKeyMemory(key []byte)

func SerializeToJSON

func SerializeToJSON(data interface{}) (string, error)

serialize

func Sign

func Sign(data []byte, privateKey ed25519.PrivateKey) ([]byte, error)

SignData signs the data using the Ed25519 private key and returns the signature.

func ValidateKeyID

func ValidateKeyID(keyID string) error

validate key id

func Verify

func Verify(data []byte, signature []byte, publicKey ed25519.PublicKey) (bool, error)

Verify verifies the signature of the data using the public key.

func VerifyMessageSignature

func VerifyMessageSignature(msg AgentMessage) bool

func ZeroKey

func ZeroKey(key []byte)

ZeroKey securely wipes keys from memory

Types

type AgentMessage

type AgentMessage struct {
	Source    AgentType         `json:"source"`
	Target    AgentType         `json:"target"`
	Type      MessageType       `json:"type"`
	Payload   json.RawMessage   `json:"payload"`
	Timestamp int64             `json:"timestamp"`
	AgentID   string            `json:"agent_id"`
	Signature string            `json:"signature,omitempty"` // ECC signature of the message
	Context   map[string]string `json:"context,omitempty"`   // Additional context for the message
}

func NewCommandMessage

func NewCommandMessage(agentID string, command CommandPayload) (AgentMessage, error)

NewCommandMessage creates a new command message

func NewStatusMessage

func NewStatusMessage(agentID string, status StatusPayload) (AgentMessage, error)

NewStatusMessage creates a new status message

func SignMessage

func SignMessage(msg AgentMessage, privateKey *ecdsa.PrivateKey) (AgentMessage, error)

Generate key pair create a new ecdh (x25519) key pair and a new ed25519 signing key pair.

type AgentType

type AgentType string
const (
	AgentDaemon    AgentType = "daemon"
	AgentCLI       AgentType = "cli"
	AgentDashboard AgentType = "dashboard"
)

type AuditLogEntry

type AuditLogEntry struct {
	Action    string    `json:"action"`       // What happened
	Actor     string    `json:"actor"`        // Who did it (fingerprint)
	Target    string    `json:"target"`       // What was affected
	Timestamp time.Time `json:"timestamp"`    // When it happened
	Signature string    `json:"signature"`    // Signature of the action
	IP        string    `json:"ip,omitempty"` // Optional IP address
	Message   string    `json:"message"`      // Optional message or details:
	Client    string    `json:"client_id"`    // Client identifier (if applicable)
}

type AuthPayload

type AuthPayload struct {
	Token    string `json:"token"`              // Authentication token
	Version  string `json:"version"`            // Agent version
	Hostname string `json:"hostname,omitempty"` // Agent hostname
}

AuthPayload represents an authentication request

type CommandPayload

type CommandPayload struct {
	Name string      `json:"name"`           // Command name (e.g., "restart", "deploy")
	Args []string    `json:"args,omitempty"` // Command arguments
	ID   string      `json:"id"`             // Unique command ID for tracking
	Meta interface{} `json:"meta,omitempty"` // Additional metadata
}

CommandPayload represents a command sent to an agent

type ECCSignature

type ECCSignature struct {
	R *big.Int
	S *big.Int
}

type EncryptedEnv

type EncryptedEnv struct {
	KeyID        string            `json:"key_id"`         // Daemon's key ID used for encryption
	EnvBlob      string            `json:"env_blob"`       // Base64 encoded encrypted full .env content
	Variables    map[string]string `json:"variables"`      // Map of encrypted individual variables
	Nonce        string            `json:"nonce"`          // Base64 encoded nonce used for encryption
	Timestamp    time.Time         `json:"timestamp"`      // When the payload was created
	CLIPublicKey string            `json:"cli_public_key"` // Base64 encoded CLI's ECDH public key
}

EncryptedEnv represents the encrypted environment variables

type EnvFile

type EnvFile struct {
	Variables map[string]string
	Raw       []byte
}

EnvFile represents a parsed .env file

func ParseEnvFile

func ParseEnvFile(content []byte) (*EnvFile, error)

type Envelope

type Envelope struct {
	Payload   []byte `json:"payload"`   // JSON string of EncryptedEnv
	Signature string `json:"signature"` // Base64 encoded signature of the payload
}

type ErrorPayload

type ErrorPayload struct {
	Message string `json:"message"`           // Error message
	Code    int    `json:"code,omitempty"`    // Optional error code
	Details string `json:"details,omitempty"` // Additional error details
}

ErrorPayload represents an error response

type EventPayload

type EventPayload struct {
	Type string      `json:"type"` // Event type (e.g., "deployment_started")
	Data interface{} `json:"data"` // Event-specific data
}

EventPayload represents an event notification

type Identity

type Identity struct {
	Fingerprint string    `json:"fingerprint"` // SHA-256 of public key
	PublicKey   string    `json:"public_key"`  // Base64 encoded public key
	SignPublic  string    `json:"sign_public"` // Base64 encoded Ed25519 public key
	Role        string    `json:"role"`        // RBAC role (owner, admin, deployer, etc.)
	Email       string    `json:"email"`       // User email/identifier
	AddedBy     string    `json:"added_by"`    // Who added this identity
	CreatedAt   time.Time `json:"created_at"`  // When this identity was added
}

type JWTOptions

type JWTOptions struct {
	ExpiresIn time.Duration
	NotBefore time.Duration // Optional delay before token is valid
	Issuer    string        // Token issuer
	Audience  []string      // Intended audience
	Scope     string        // Access scope
	ClientIP  string        // Optional client IP for binding
}

JWTOptions configures token generation options

type KeyPair

type KeyPair struct {
	ECDHPrivate *ecdh.PrivateKey
	ECDHPublic  *ecdh.PublicKey
	SignPrivate ed25519.PrivateKey
	SignPublic  ed25519.PublicKey
	ECDSAKey    *ecdsa.PrivateKey // Optional ECDSA key for compatibility
	KeyID       string
}

func GenerateKeyPair

func GenerateKeyPair() (*KeyPair, error)

type LogLevel

type LogLevel int

LogLevel represents different log levels

const (
	LevelTrace LogLevel = iota
	LevelDebug
	LevelInfo
	LevelWarn
	LevelSuccess
	LevelError
	LevelFatal
)

type Logger

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

Logger is the main logger struct

func DefaultLogger

func DefaultLogger() *Logger

DefaultLogger creates a logger with default settings

func New

func New(out io.Writer, prefix string, flag int, minLevel LogLevel) *Logger

New creates a new Logger instance

func PackageLogger

func PackageLogger(pkgName string, displayName string) *Logger

PackageLogger creates a logger with package-specific settings

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...interface{})

Debug logs a debug message

func (*Logger) EnableBanner

func (l *Logger) EnableBanner(enable bool)

EnableBanner enables/disables the level banner

func (*Logger) EnableCallerInfo

func (l *Logger) EnableCallerInfo(enable bool)

EnableCallerInfo enables/disables caller information

func (*Logger) EnableColor

func (l *Logger) EnableColor(enable bool)

EnableColor enables/disables color output

func (*Logger) EnableTimestamp

func (l *Logger) EnableTimestamp(enable bool)

EnableTimestamp enables/disables timestamp

func (*Logger) Error

func (l *Logger) Error(msg string, args ...interface{})

Error logs an error message

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, args ...interface{})

Fatal logs a fatal message and exits

func (*Logger) Indent

func (l *Logger) Indent() *Logger

Indent increases the indentation level

func (*Logger) Info

func (l *Logger) Info(msg string, args ...interface{})

Info logs an info message

func (*Logger) JSON

func (l *Logger) JSON(level LogLevel, data interface{})

JSON logs data in pretty-printed JSON format

func (*Logger) Log

func (l *Logger) Log(level LogLevel, msg string, args ...interface{})

Log logs a message at a specific level

func (*Logger) Progress

func (l *Logger) Progress(level LogLevel, current, total int, label string)

Progress creates a progress bar

func (*Logger) RegisterPackage

func (l *Logger) RegisterPackage(pkg string, displayName string)

RegisterPackage registers a package with a custom emoji/name

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel sets the minimum log level

func (*Logger) SetOutput

func (l *Logger) SetOutput(w io.Writer)

SetOutput sets the output destination

func (*Logger) SetTimeFormat

func (l *Logger) SetTimeFormat(format string)

SetTimeFormat sets the timestamp format (default: "2006-01-02 15:04:05.000")

func (*Logger) Success

func (l *Logger) Success(msg string, args ...interface{})

Success logs a success message

func (*Logger) Table

func (l *Logger) Table(level LogLevel, headers []string, rows [][]string)

Table logs tabular data

func (*Logger) Timed

func (l *Logger) Timed(label string, fn func())

Timed logs the duration of a function execution with a spinner animation

func (*Logger) Trace

func (l *Logger) Trace(msg string, args ...interface{})

Trace logs a trace message (most verbose)

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...interface{})

Warn logs a warning message

func (*Logger) WithPrefix

func (l *Logger) WithPrefix(prefix string) *Logger

WithPrefix returns a new Logger with the specified prefix

type MessageHeader

type MessageHeader struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id"`
}

type MessageType

type MessageType string
const (
	TypeCommand         MessageType = "command" // Command to execute
	TypeCommandResponse MessageType = "command_response"
	TypeStatus          MessageType = "status"   // Status update
	TypeResponse        MessageType = "response" // Response to a command
	TypeEvent           MessageType = "event"    // Event notification
	TypeLog             MessageType = "log"      // Log message
	TypeError           MessageType = "error"    // Error message
	TypeAuth            MessageType = "auth"     // Authentication message
	TypeStatusAck       MessageType = "status_ack"
	TypeAuthResponse    MessageType = "auth_response"
)

type PublicKeyResponse

type PublicKeyResponse struct {
	KeyID      string `json:"key_id"`      // Identifier for the key
	PublicKey  string `json:"public_key"`  // Base64 encoded ECDH public key
	SignPublic string `json:"sign_public"` // Base64 encoded Ed25519 public key
}

PublicKeyResponse is the response from the daemon's /public-key endpoint

type SecureMessage

type SecureMessage struct {
	IV         []byte `json:"iv"`
	Ciphertext []byte `json:"ciphertext"`
	Tag        []byte `json:"tag"`
	Sequence   uint64 `json:"sequence"`
	Timestamp  int64  `json:"timestamp"`
}

type StatusPayload

type StatusPayload struct {
	Status  string                 `json:"status"`            // Current status (e.g., "healthy", "degraded")
	Metrics map[string]interface{} `json:"metrics,omitempty"` // System metrics
	Load    SystemLoad             `json:"load,omitempty"`    // System load information
}

StatusPayload represents an agent status update

type SystemLoad

type SystemLoad struct {
	CPU    float64 `json:"cpu"`    // CPU usage percentage
	Memory float64 `json:"memory"` // Memory usage percentage
	Disk   float64 `json:"disk"`   // Disk usage percentage
}

SystemLoad contains system load information

type TrustStore

type TrustStore struct {
	Keys       []TrustedKey `json:"keys"`
	Identities []Identity
}

TrustStore is a collection of trusted keys

type TrustedKey

type TrustedKey struct {
	KeyID       string          `json:"key_id"`
	PublicKey   *ecdh.PublicKey `json:"public_key"`
	SignPublic  string          `json:"sign_public"`
	Fingerprint string          `json:"fingerprint"`
}

TrustedKey represents a trusted daemon public key stored by the CLI

type WSClaims

type WSClaims struct {
	ClientID             string `json:"cid"`      // Client identifier
	SessionID            string `json:"sid"`      // Unique session ID
	Scope                string `json:"scope"`    // Authorization scope (e.g., "read:logs", "deploy")
	AgentID              string `json:"agent_id"` // Optional agent identifier
	jwt.RegisteredClaims        // Standard JWT claims
}

WSClaims represents the custom claims structure for WebSocket JWT tokens

func VerifyWSJWT

func VerifyWSJWT(
	tokenString string,
	publicKey *ecdsa.PublicKey,
	expectedAudience string,
) (*WSClaims, error)

VerifyWSJWT validates and parses a WebSocket JWT token

Directories

Path Synopsis
NOTE: CROSS COMPILE SAFE
NOTE: CROSS COMPILE SAFE
Package sanitizer provides security-focused sanitization functions to prevent common vulnerabilities like command injection, path traversal, and other security issues.
Package sanitizer provides security-focused sanitization functions to prevent common vulnerabilities like command injection, path traversal, and other security issues.
Package updater provides GitHub release-based update checking and self-update functionality for the NextDeploy CLI and Daemon.
Package updater provides GitHub release-based update checking and self-update functionality for the NextDeploy CLI and Daemon.

Jump to

Keyboard shortcuts

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