generate

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: GPL-3.0 Imports: 34 Imported by: 0

Documentation

Overview

Package generate provides functions for generating cryptographic credentials used in cheburbox server configurations.

Index

Constants

View Source
const (
	// TypeVLESS is the VLESS inbound and cross-server outbound protocol type.
	TypeVLESS = "vless"
	// TypeHysteria2 is the hysteria2 inbound and cross-server outbound protocol type.
	TypeHysteria2 = "hysteria2"
	// TypeTun is the tun inbound protocol type.
	TypeTun = "tun"
	// TypeSOCKS is the SOCKS5 inbound protocol type (username/password auth).
	TypeSOCKS = "socks"
	// TypeAmneziaWG is the AmneziaWG inbound and cross-server outbound protocol type.
	TypeAmneziaWG = "amneziawg"
	// TypeDirect is the direct outbound protocol type.
	TypeDirect = "direct"
	// TypeURLTest is the urltest outbound group protocol type.
	TypeURLTest = "urltest"
	// TypeSelector is the selector outbound group protocol type.
	TypeSelector = "selector"
	// TypeFallback is the fallback outbound group protocol type (sing-box-extended).
	TypeFallback = "fallback"
	// TypeFailover is the failover outbound group protocol type (sing-box-extended).
	TypeFailover = "failover"
)

Protocol type strings for inbounds and outbounds, shared between config generation and validation to keep the literal values in one place.

View Source
const (
	// ObfsSalamander is the hysteria2 salamander obfuscation type.
	ObfsSalamander = "salamander"
	// FlowXTLSRPRXVision is the VLESS XTLS Vision flow control value.
	FlowXTLSRPRXVision = "xtls-rprx-vision"
)

Hysteria2 obfuscation and VLESS flow control feature strings.

View Source
const (
	// FailoverStrategySequential dials outbounds in declaration order, advancing
	// to the next only when the current one fails. This is the default.
	FailoverStrategySequential = "sequential"
	// FailoverStrategyCycle tries each outbound in turn on every dial, advancing
	// to the next on failure with an optional delay before retrying.
	FailoverStrategyCycle = "cycle"
)

Failover dial strategy values for the failover outbound group.

View Source
const (
	// EndpointTypeWireGuard is the sing-box wireguard endpoint type. AmneziaWG rides
	// on the same endpoint type and is distinguished by a non-nil amnezia block.
	EndpointTypeWireGuard = "wireguard"
)

sing-box endpoint type strings. These are the Type values sing-box uses inside its endpoint envelope (option.Endpoint.Type), distinct from the cheburbox inbound and outbound protocol types above. They are consumed by the config generator only.

Variables

This section is empty.

Functions

func BuildAmneziaWGClientEndpoint

func BuildAmneziaWGClientEndpoint(
	out config.Outbound,
	serverName string,
	state *ServerState,
	persisted config.PersistedCredentials,
) (*option.Endpoint, error)

BuildAmneziaWGClientEndpoint builds a sing-box wireguard endpoint for an AmneziaWG outbound (client side). The target server must already be registered in state (topological order guarantees this). The client's private key is reused from persisted credentials when available; its derived public key is provisioned into the target server's peer registry so the server's peer list stays consistent with the client's key across runs. The shared amnezia params are inherited from the server; client-only I1-I5 are freshly generated.

func BuildAmneziaWGServerEndpoint

func BuildAmneziaWGServerEndpoint(
	in config.Inbound,
	serverName, endpointAddr string,
	state *ServerState,
	persisted config.PersistedCredentials,
) (*option.Endpoint, error)

BuildAmneziaWGServerEndpoint builds a sing-box wireguard endpoint for an AmneziaWG inbound (server side). The server's private key and shared amnezia parameters are reused from persisted credentials when available so they stay stable across generation runs. Declared inbound users are provisioned as peers (each allocated a /32 from the inbound subnet); cross-server clients provision themselves into the same registry when their own client endpoint is built. The server info is registered in state so client endpoints can look it up.

func BuildInbound

func BuildInbound(in config.Inbound, creds InboundCredentials) (option.Inbound, error)

BuildInbound converts a cheburbox Inbound config and resolved credentials into a sing-box Inbound option.

func BuildOutbound

func BuildOutbound(out config.Outbound) (option.Outbound, error)

BuildOutbound converts a cheburbox Outbound to a sing-box option.Outbound.

func BuildOutboundWithState

func BuildOutboundWithState(
	out config.Outbound,
	state *ServerState,
	opts ...OutboundBuildOption,
) (option.Outbound, error)

BuildOutboundWithState converts a cheburbox Outbound to a sing-box option.Outbound using the provided ServerState for cross-server credential resolution.

func CertNeedsRegeneration

func CertNeedsRegeneration(cert *x509.Certificate, serverName string) bool

func ComputePinSHA256

func ComputePinSHA256(certPEM []byte) (string, error)

ComputePinSHA256 computes the SHA-256 pin of a PEM-encoded certificate's public key.

func ConvertDNS

func ConvertDNS(cfg config.DNS) (*option.DNSOptions, error)

ConvertDNS converts cheburbox DNS configuration to sing-box DNSOptions.

func ConvertRoute

func ConvertRoute(route *config.Route) (*option.RouteOptions, error)

ConvertRoute converts cheburbox route configuration to sing-box RouteOptions. Returns an empty RouteOptions if route is nil.

func DerivePublicKey

func DerivePublicKey(privateKeyBase64 string) (string, error)

func GeneratePassword

func GeneratePassword() (string, error)

GeneratePassword returns a URL-safe base64-encoded 24-byte random password (RawURLEncoding: [A-Za-z0-9_-], no padding) — safe for URIs and config values.

func GenerateSelfSignedCert

func GenerateSelfSignedCert(serverName string) ([]byte, ed25519.PrivateKey, error)

GenerateSelfSignedCert creates a self-signed certificate and Ed25519 private key for the given server name, returning the DER-encoded certificate and the typed private key.

func GenerateSelfSignedCertPEM

func GenerateSelfSignedCertPEM(serverName string) ([]byte, []byte, error)

GenerateSelfSignedCertPEM creates a self-signed certificate and private key for the given server name, returning PEM-encoded certificate and PKCS#8 private key.

func GenerateShortID

func GenerateShortID() (string, error)

GenerateShortID returns a hex-encoded 8-byte random short identifier.

func GenerateUUID

func GenerateUUID() (string, error)

GenerateUUID returns a random UUIDv4 string.

func GenerateX25519KeyPair

func GenerateX25519KeyPair() (string, string, error)

GenerateX25519KeyPair generates an X25519 key pair and returns the private and public keys as base64-encoded strings.

func ReadCertFiles

func ReadCertFiles(certPath string, keyPath string) ([]byte, []byte, error)

ReadCertFiles reads PEM-encoded certificate and key from the given paths. Returns nil values without error if files do not exist.

func WriteCertFiles

func WriteCertFiles(certPath string, keyPath string, certPEM []byte, keyPEM []byte) error

WriteCertFiles writes PEM-encoded certificate and key to the given paths.

Types

type AmneziaWGPeerCreds

type AmneziaWGPeerCreds struct {
	PrivateKey   string
	PublicKey    string
	PresharedKey string
	AllowedIPs   []netip.Prefix
}

AmneziaWGPeerCreds holds a single AmneziaWG peer's credentials. PublicKey and PresharedKey are what the SERVER installs in its peer list; PrivateKey is the peer's own key and is only meaningful on the client side. AllowedIPs is the tunnel address the server routes to this peer (typically a /32).

type AmneziaWGServerInfo

type AmneziaWGServerInfo struct {
	Subnet        netip.Prefix
	PublicKey     string
	EndpointAddr  string
	Protocol      string
	SharedAmnezia option.WireGuardAmnezia
	MTU           uint32
	ListenPort    uint16
}

AmneziaWGServerInfo holds the resolved server-side state for an AmneziaWG inbound. Client endpoints look it up to inherit the server's public key, public UDP endpoint, transport protocol, and the shared amnezia obfuscation parameters that every peer must match.

type Edge

type Edge struct {
	From string
	To   string
}

Edge represents a directed dependency from one server to another.

type FileOutput

type FileOutput struct {
	Path    string
	Content []byte
}

FileOutput represents a generated file with its relative path and content.

type GenerateConfig

type GenerateConfig struct {
	VPNLinkPeers []string
	FullReset    bool
	Orphan       bool
}

GenerateConfig controls server generation behavior.

func (g GenerateConfig) WantsVPNLinks(server string) bool

WantsVPNLinks reports whether vpn:// import-link files should be generated for server. Empty VPNLinkPeers (the default) opts out entirely.

type GenerateResult

type GenerateResult struct {
	Server string
	Files  []FileOutput
}

GenerateResult holds the generated server name and output files.

func GenerateAll

func GenerateAll(projectRoot string, jpath string, genCfg GenerateConfig) ([]GenerateResult, error)

GenerateAll discovers all servers in the project, builds a dependency graph, topologically sorts them, and generates configs in order with shared state for cross-server credential resolution. Uses two-pass generation to handle cross-server user provisioning.

func GenerateServer

func GenerateServer(dir string, cfg config.Config, genCfg GenerateConfig) (GenerateResult, error)

GenerateServer generates a complete sing-box configuration for a server.

func GenerateServers

func GenerateServers(
	projectRoot string,
	jpath string,
	serverName string,
	genCfg GenerateConfig,
) ([]GenerateResult, error)

GenerateServers generates configs for the specified server and its transitive dependencies.

type Graph

type Graph struct {
	Nodes map[string]bool
	Edges []Edge
}

Graph represents a directed graph of server dependencies.

func BuildGraph

func BuildGraph(configs map[string]config.Config) (*Graph, error)

BuildGraph constructs a dependency graph from a set of server configurations. Each outbound with a non-empty Server field creates an edge from the owning server to the target. Returns an error for self-references, unknown server references, or dependency cycles.

func (*Graph) TopologicalSort

func (g *Graph) TopologicalSort() ([]string, error)

TopologicalSort returns servers in dependency order: servers with no dependencies come first. Returns an error if a cycle is detected.

func (*Graph) TransitiveDependencies

func (g *Graph) TransitiveDependencies(server string) ([]string, error)

TransitiveDependencies returns all servers transitively depended on by the given server, including the server itself.

type InboundCredentials

type InboundCredentials struct {
	Users        map[string]UserCreds
	Reality      *RealityKeys
	ObfsPassword string
	ServerName   string
	ALPN         []string
}

InboundCredentials holds resolved credentials for building inbound options.

type OutboundBuildOption

type OutboundBuildOption func(*outboundBuildConfig)

OutboundBuildOption configures outbound building behavior.

func WithDefaultUser

func WithDefaultUser(user string) OutboundBuildOption

WithDefaultUser sets a fallback user for cross-server outbounds when no explicit user is specified in the config.

type RealityKeys

type RealityKeys struct {
	PrivateKey string
	PublicKey  string
	ShortID    []string
}

RealityKeys holds generated reality key pair and short IDs.

type ServerState

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

ServerState holds per-server state for credentials, pin-SHA256, endpoints, inbound types, listen ports, and AmneziaWG server/peer registries.

func NewServerState

func NewServerState() *ServerState

func (*ServerState) AmneziaWGPeer

func (s *ServerState) AmneziaWGPeer(server string, tag string, user string) (AmneziaWGPeerCreds, bool)

AmneziaWGPeer looks up a single AmneziaWG peer by name.

func (*ServerState) AmneziaWGPeers

func (s *ServerState) AmneziaWGPeers(server string, tag string) map[string]AmneziaWGPeerCreds

AmneziaWGPeers returns all peers provisioned against a server's inbound. The server endpoint builder uses this to assemble its peer list.

func (*ServerState) AmneziaWGServer

func (s *ServerState) AmneziaWGServer(server string, tag string) (AmneziaWGServerInfo, bool)

AmneziaWGServer looks up the server-side state for an AmneziaWG inbound.

func (*ServerState) EnsureAmneziaWGPeer

func (s *ServerState) EnsureAmneziaWGPeer(
	server string,
	tag string,
	user string,
	creds AmneziaWGPeerCreds,
) (AmneziaWGPeerCreds, bool)

EnsureAmneziaWGPeer provisions a peer for (server, tag, user). If the peer already exists in the registry, its existing credentials are returned unchanged (alreadyExisted = true). Otherwise the supplied creds are stored and returned (alreadyExisted = false). The caller owns key generation and supplies the public/preshared keys; this keeps the peer's public key on the server consistent with the client's private key across generation runs.

func (*ServerState) EnsureUser

func (s *ServerState) EnsureUser(server string, tag string, userName string) error

EnsureUser adds a user with generated credentials to an existing inbound. If the user already exists, their credentials are preserved.

func (*ServerState) GetEndpoint

func (s *ServerState) GetEndpoint(server string) (string, bool)

GetEndpoint retrieves the public endpoint address for a server.

func (*ServerState) GetInboundCredentials

func (s *ServerState) GetInboundCredentials(server string, tag string) (InboundCredentials, bool)

GetInboundCredentials retrieves credentials for a server's inbound.

func (*ServerState) GetInboundType

func (s *ServerState) GetInboundType(server string, tag string) (string, bool)

GetInboundType retrieves the inbound protocol type for a server's inbound.

func (*ServerState) GetListenPort

func (s *ServerState) GetListenPort(server string, tag string) (uint16, bool)

GetListenPort retrieves the listen port for a server's inbound.

func (*ServerState) GetPinSHA256

func (s *ServerState) GetPinSHA256(server string, tag string) (string, bool)

GetPinSHA256 retrieves the TLS pin-SHA256 fingerprint for a server's inbound.

func (*ServerState) RegisterAmneziaWGServer

func (s *ServerState) RegisterAmneziaWGServer(server string, tag string, info AmneziaWGServerInfo)

RegisterAmneziaWGServer records the server-side state for an AmneziaWG inbound so client endpoints on other servers can look it up.

func (*ServerState) StoreAmneziaWGPeer

func (s *ServerState) StoreAmneziaWGPeer(server string, tag string, user string, creds AmneziaWGPeerCreds)

StoreAmneziaWGPeer saves credentials for a single AmneziaWG peer provisioned against a server's inbound, keyed by peer (user) name.

func (*ServerState) StoreEndpoint

func (s *ServerState) StoreEndpoint(server string, endpoint string)

StoreEndpoint saves the public endpoint address for a server.

func (*ServerState) StoreInboundCredentials

func (s *ServerState) StoreInboundCredentials(server string, tag string, creds InboundCredentials)

StoreInboundCredentials saves credentials for a server's inbound.

func (*ServerState) StoreInboundType

func (s *ServerState) StoreInboundType(server string, tag string, inboundType string)

StoreInboundType saves the inbound protocol type for a server's inbound.

func (*ServerState) StoreListenPort

func (s *ServerState) StoreListenPort(server string, tag string, port uint16)

StoreListenPort saves the listen port for a server's inbound.

func (*ServerState) StorePinSHA256

func (s *ServerState) StorePinSHA256(server string, tag string, pin string)

StorePinSHA256 saves the TLS pin-SHA256 fingerprint for a server's inbound.

type UserCreds

type UserCreds struct {
	UUID     string
	Password string
	Flow     string
}

UserCreds holds per-user credentials.

Jump to

Keyboard shortcuts

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