atxp

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 16 Imported by: 0

README ΒΆ

ATXP (Atendi9 Transmission Exchange Protocol)

A lightweight, encrypted application wire protocol for fast, structured communication over raw TCP or TLS. Every frame is encrypted with AES-256-GCM under a key derived from a shared password β€” the password is never transmitted. This repository provides cross-ecosystem implementations for both Node.js (NPM) and Go (Golang) with a byte-identical wire format.

⚠️ About V1. The original ATXP was a proof of concept: it sent credentials and payloads in cleartext and its text delimiters (\t\t, \n\n, ::) collided with arbitrary binary data, corrupting PDFs and other files. It is insecure and deprecated β€” this README documents only the secure V2 protocol. The V1 symbols remain in the codebase for backward compatibility but must not be used on untrusted networks.

πŸ“¦ Installation

Node.js (NPM)
npm install @atendi9/atxp-protocol
Go (pkg.go.dev)
go get -u github.com/atendi9/atxp

πŸ” Why V2 is secure

Property Mechanism
Confidentiality AES-256-GCM encrypts the whole frame.
Integrity GCM authentication tag detects any tampering.
Authentication Implicit β€” only a peer holding the shared password derives the key that opens frames.
Secret never on the wire Key is derived from the password via PBKDF2-HMAC-SHA256; the password itself is never sent.
Binary-safe Length-prefixed binary envelope carries PDFs/images losslessly.
DoS resistance Frame cap (16 MiB default, configurable), bounded reads, and I/O deadlines.
Replay resistance Strictly increasing per-connection sequence numbers.

Full details in docs/protocol.md and docs/security.md.


πŸ› οΈ Usage Guide: Node.js

1. Initialize a Secure Server
import { ServerV2, MT, ResponseCode, AuthData, validateURLHandler } from '@atendi9/atxp-protocol';

// The shared password derives the encryption key. Authorization is by username
// only β€” possession of the password is already proven by successful decryption.
const server = new ServerV2('shared-secret', (username) => {
  if (username === 'atendi9') {
    return { authorized: true, data: new AuthData({ role: 'admin' }) };
  }
  return { authorized: false, data: new AuthData(null) };
});

server.registerHandler(MT.URL, validateURLHandler());

server.registerHandler(MT.DOCUMENT, (msg) => {
  console.log(`[Document Received]: ${msg.filename || 'unknown'}, ${msg.data.length} encrypted bytes`);
  return ResponseCode.OK;
});

const listening = await server.listen(8443);
console.log('ATXP V2 server running on port 8443');
2. Initialize a Secure Client
import net from 'node:net';
import { newClientV2 } from '@atendi9/atxp-protocol';

const socket = net.createConnection({ port: 8443 }, async () => {
  // newClientV2 performs the encrypted handshake before resolving.
  const client = await newClientV2(socket, 'shared-secret', 'atendi9');

  // A binary PDF travels fully encrypted and arrives intact.
  const fileBuffer = Buffer.from('%PDF-1.7\n...binary content...');
  const code = await client.sendDocument(fileBuffer, 'annual_report.pdf');
  console.log(`Server returned: ${code}`);

  client.close();
});

🐹 Usage Guide: Go (Golang)

1. Initialize a Secure Server
package main

import (
    "fmt"
    "log"

    "github.com/atendi9/atxp"
    "github.com/atendi9/box"
)

func main() {
    // The shared password derives the per-connection key; auth is by username.
    server, err := atxp.NewServerV2("shared-secret", func(username string) (bool, atxp.AuthData) {
        if username == "atendi9" {
            return true, box.NewSome(map[string]any{"role": "admin"})
        }
        return false, box.NewNone[map[string]any]()
    })
    if err != nil {
        log.Fatalf("Failed to create server: %v", err)
    }

    server.RegisterHandler(atxp.DOCUMENT, func(msg *atxp.Message, _ atxp.AuthData) atxp.ResponseCode {
        fmt.Printf("[Go Server] Document %q received, %d encrypted bytes\n", msg.Filename, len(msg.Data.Get()))
        return atxp.OK
    })

    listener, err := atxp.CreateServer(8443)
    if err != nil {
        log.Fatalf("Failed to bind listener: %v", err)
    }

    fmt.Println("ATXP V2 Go server listening on port 8443...")
    if err := server.Serve(listener); err != nil {
        log.Fatalf("Server loop failed: %v", err)
    }
}
2. Initialize a Secure Client
package main

import (
    "fmt"
    "log"

    "github.com/atendi9/atxp"
)

func main() {
    conn, err := atxp.ConnectClient("127.0.0.1", 8443)
    if err != nil {
        log.Fatalf("Failed to dial host: %v", err)
    }

    // NewClientV2 performs the encrypted handshake on construction.
    client, err := atxp.NewClientV2(conn, "shared-secret", "atendi9")
    if err != nil {
        log.Fatalf("Handshake failed: %v", err)
    }
    defer client.Close()

    documentBytes := []byte("%PDF-1.7\n...binary content...")
    status, err := client.SendDocument(documentBytes, "report.pdf")
    if err != nil {
        log.Fatalf("Failed to send frame: %v", err)
    }

    fmt.Printf("Server returned status: %v\n", status)
}

🧩 Registering custom message types

V2 message types are registrable at runtime. Codes must be unique and fit in a uint32.

atxp.NewMT(atxp.MT_V2{Name: "WEBHOOK", Code: 100, Description: "external webhook registration"}) // Go
newMT({ name: 'WEBHOOK', code: 100, description: 'external webhook registration' }); // JS

Then send with the custom code:

client.Send(100, payload, "")            // Go
await client.send(100, payload, '');     // JS

πŸ“ Tuning the frame size cap

Each encrypted frame is capped at 16 MiB by default to bound memory use. Beefier servers that must transfer larger documents can raise the cap β€” and constrained environments can lower it. Set it on both the server and the client (a sender's cap must not exceed the receiver's, or large frames are rejected):

// Go β€” 64 MiB cap. Values below the minimum valid frame size are ignored.
server, _ := atxp.NewServerV2("shared-secret", authFn, atxp.WithMaxFrameSize(64<<20))
client, _ := atxp.NewClientV2(conn, "shared-secret", "atendi9", atxp.WithMaxFrameSize(64<<20))
// Node.js β€” 64 MiB cap via the options object.
const server = new ServerV2('shared-secret', authFn, { maxFrameSize: 64 * 1024 * 1024 });
const client = await newClientV2(socket, 'shared-secret', 'atendi9', { maxFrameSize: 64 * 1024 * 1024 });

πŸ“‘ V2 Wire Protocol Specification

Each connection begins with a server-initiated handshake, after which every frame is encrypted.

Handshake (22 bytes, server β†’ client):

"ATXP2" (5B magic) | version (1B = 0x02) | salt (16B random)

Both peers derive K = PBKDF2-HMAC-SHA256(password, salt, 600000, 32).

Encrypted frame (both directions):

length (4B BE uint32) | nonce (12B) | AES-256-GCM(ciphertext + tag)

Inner plaintext envelope (length-prefixed, binary-safe):

kind (1B)            # 0x01 = Message, 0x02 = Response
seq  (8B BE uint64)  # monotonic per connection (anti-replay)
mtCode      (4B BE) | payloadLen (4B) | payload | userLen (4B) | username | fnameLen (4B) | filename

There is no password field anywhere on the wire. See docs/protocol.md for the complete specification, including cross-language known-answer test vectors.

Built-in Message Types
Name MT.X (Node.js) atxp.X (Go) Code Description
URL MT.URL atxp.URL 0 URLs / webhook registration.
DOCUMENT MT.DOCUMENT atxp.DOCUMENT 1 Binary file transfer with optional filename.
NOTIFICATION MT.NOTIFICATION atxp.NOTIFICATION 2 JSON or events for event-driven architectures.

πŸ“œ License

Distributed under the terms of the open-source MIT License.

Documentation ΒΆ

Overview ΒΆ

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

Package atxp implements the ATXP (Atendi9 Transmission Exchange Protocol) wire protocol framing and transport layer.

  • Copyright (c) 2026 Atendi9

ATXP V2 secure layer ΒΆ

V2 is an additive, backward-incompatible-on-the-wire successor to V1 that fixes V1's security and robustness flaws:

  • The whole frame is encrypted with AES-256-GCM under a key derived from a shared password via PBKDF2-HMAC-SHA256. The password is never transmitted; possession is proven implicitly by the GCM authentication tag.
  • Frames use a length-prefixed binary envelope, so arbitrary binary payloads (PDFs, images, anything) are carried losslessly and no payload byte can collide with a delimiter.
  • Reads are bounded by MaxFrameSizeV2 and every I/O operation has a deadline, preventing unbounded-memory and hung-connection denial of service.
  • A monotonic per-connection sequence number defends against replay and reordering.

Index ΒΆ

Constants ΒΆ

View Source
const (
	// SaltSize is the length in bytes of the per-connection PBKDF2 salt.
	SaltSize = 16
	// NonceSize is the AES-GCM standard nonce length in bytes.
	NonceSize = 12
	// KeySize is the AES-256 key length in bytes.
	KeySize = 32
	// GCMTagSize is the AES-GCM authentication tag length in bytes.
	GCMTagSize = 16
	// DefaultKDFIterations is the default PBKDF2 iteration count. It follows the
	// OWASP recommendation for PBKDF2-HMAC-SHA256 and is applied once per
	// connection (not per frame) so the cost is bounded.
	DefaultKDFIterations = 600_000
)

Cryptographic sizing constants for the ATXP V2 secure layer. None of these are magic numbers: they are fixed by the chosen primitives (AES-256-GCM, PBKDF2-HMAC-SHA256).

View Source
const (
	// ProtocolVersionV2 is the version byte sent in the handshake header.
	ProtocolVersionV2 = 2
	// HandshakeMagic prefixes the handshake header so peers can detect a
	// non-ATXP-V2 stream early.
	HandshakeMagic = "ATXP2"
	// LengthPrefixSize is the size in bytes of the big-endian frame length.
	LengthPrefixSize = 4
	// MaxFrameSizeV2 is the default ceiling on a single encrypted frame
	// (16 MiB). It can be raised or lowered per endpoint with
	// [WithMaxFrameSize] β€” useful for beefier servers that must accept larger
	// documents.
	MaxFrameSizeV2 = 1 << 24
	// MinFrameSizeV2 is the smallest a valid encrypted frame can be: a 12-byte
	// nonce plus a 16-byte GCM tag. A configured cap below this is rejected.
	MinFrameSizeV2 = NonceSize + GCMTagSize
	// DefaultIOTimeout bounds every frame read/write and handshake step.
	DefaultIOTimeout = 30 * time.Second
)

Protocol-level constants for ATXP V2. None are magic numbers.

Variables ΒΆ

View Source
var (
	// ErrFrameTooLarge is returned when an incoming frame announces a length
	// above MaxFrameSizeV2, or a frame to be sent exceeds that ceiling.
	ErrFrameTooLarge = errors.New("atxp: frame exceeds MaxFrameSizeV2")

	// ErrFrameTooSmall is returned when a frame is shorter than the minimum
	// envelope (nonce + GCM tag) and therefore cannot be authentic.
	ErrFrameTooSmall = errors.New("atxp: frame smaller than minimum secure envelope")

	// ErrInvalidChecksum is returned when AES-GCM authentication fails while
	// opening a frame. It means the password is wrong or the ciphertext was
	// tampered with. The two cases are intentionally indistinguishable.
	ErrInvalidChecksum = errors.New("atxp: decryption or authentication failed")

	// ErrHandshake is returned when the V2 handshake cannot be completed
	// (bad magic, unsupported version, short read).
	ErrHandshake = errors.New("atxp: handshake failed")

	// ErrWeakPassword is returned by NewV2 when the supplied password is empty.
	ErrWeakPassword = errors.New("atxp: password must be non-empty")

	// ErrReplay is returned when a received frame carries a sequence number
	// that is not strictly greater than the last accepted one, indicating a
	// replayed or reordered frame.
	ErrReplay = errors.New("atxp: out-of-order or replayed frame")

	// ErrInvalidEnvelope is returned when the decrypted plaintext does not
	// conform to the ATXP V2 internal envelope layout.
	ErrInvalidEnvelope = errors.New("atxp: malformed v2 envelope")

	// ErrInvalidKey is returned when a derived or supplied key has an
	// unexpected length for AES-256.
	ErrInvalidKey = errors.New("atxp: key must be 32 bytes for AES-256")
)

Sentinel errors for the ATXP V2 secure protocol. Inspect them with errors.Is; never compare error strings directly.

View Source
var (
	// ErrInvalidFormat occurs when an ATXP packet does not comply with the protocol syntax.
	ErrInvalidFormat = errors.New("malformed atxp packet protocol")
)

Functions ΒΆ

func CloseClient ΒΆ

func CloseClient(conn io.Closer) error

CloseClient terminates the provided connection safely.

func ConnectClient ΒΆ

func ConnectClient(host string, port int) (net.Conn, error)

ConnectClient dials an outbound virtual raw network channel interface targeting a remote ATXP host destination.

func ConnectTLSClient ΒΆ

func ConnectTLSClient(host string, port int, config *tls.Config) (net.Conn, error)

ConnectTLSClient dials an outbound secure network channel interface targeting a remote ATXP host destination over TLS.

func CreateServer ΒΆ

func CreateServer(port int) (net.Listener, error)

CreateServer establishes a TCP network listener for incoming ATXP connections at the specified local port binding.

func CreateTLSServer ΒΆ

func CreateTLSServer(port int, config *tls.Config) (net.Listener, error)

CreateTLSServer establishes a secure TLS network listener for incoming ATXP connections using the provided server certificate configuration.

func Deserialize ΒΆ

func Deserialize(buffer string, msg *Message) error

Deserialize decodes a raw string packet back into the provided Message structure reference based on ATXP syntax.

func DeserializeV2 ΒΆ added in v1.3.0

func DeserializeV2(plaintext []byte, msg *Message) (uint64, error)

DeserializeV2 decodes a V2 message envelope into msg and returns the carried sequence number. It returns ErrInvalidEnvelope for any structural fault.

func NewMT ΒΆ added in v1.3.0

func NewMT(mt MT_V2) bool

NewMT registers a new ATXP V2 message type. It returns false (and registers nothing) when the Code is already in use, preventing accidental override of the built-in or previously registered types. It is safe for concurrent use.

func Receive ΒΆ

func Receive(conn NetworkIO) (string, error)

Receive continuously pulls incoming bytes out of a custom NetworkIO reference stream container until a trailing ATXP sequence header is hit.

func Send ΒΆ

func Send(conn NetworkIO, msg *Message) (int, error)

Send serializes a Message and transmits it through the provided NetworkIO implementation using ATXP framing.

func SendResponseV2 ΒΆ added in v1.3.0

func SendResponseV2(conn SecureConn, c Cipher, code ResponseCode, seq uint64) error

SendResponseV2 seals and writes a response frame using the default frame cap.

func SendV2 ΒΆ added in v1.3.0

func SendV2(conn SecureConn, c Cipher, msg *Message, seq uint64) (int, error)

SendV2 serializes, seals and writes a message frame using the default frame cap MaxFrameSizeV2, returning the number of bytes written on the wire. To use a custom cap, build a ClientV2/ServerV2 with WithMaxFrameSize.

func Serialize ΒΆ

func Serialize(msg *Message) ([]byte, error)

Serialize encodes a Message into a raw byte slice payload according to the ATXP wire protocol.

func SerializeV2 ΒΆ added in v1.3.0

func SerializeV2(msg *Message, seq uint64) ([]byte, error)

SerializeV2 encodes msg and its sequence number into the V2 inner plaintext envelope. Every variable-length field is length-prefixed, so the payload may contain any bytes. The result is the plaintext to be sealed, not the wire frame.

func TypeToString ΒΆ

func TypeToString(messageType MT) string

TypeToString converts a numeric ATXP type to its equivalent string representation.

func TypeToStringV2 ΒΆ added in v1.3.0

func TypeToStringV2(code MT) string

TypeToStringV2 converts a registered message type code to its Name, or "UNKNOWN" when the code is not registered. It is safe for concurrent use.

Types ΒΆ

type Auth ΒΆ

type Auth struct {
	Username string
	Password string
}

Auth contains credentials for validating connection or message authority.

type AuthData ΒΆ added in v1.1.0

type AuthData box.Optional[map[string]any]

AuthData encapsulates optional authentication metadata that may be associated with incoming ATXP messages, allowing handlers to access user credentials or session information when necessary.

type AuthHandler ΒΆ added in v1.1.0

type AuthHandler func(username, password string) (authorized bool, data AuthData)

AuthHandler defines a function signature for authentication logic, allowing the server to verify credentials and optionally return additional authentication data for use in message handling.

type AuthHandlerV2 ΒΆ added in v1.3.0

type AuthHandlerV2 func(username string) (authorized bool, data AuthData)

AuthHandlerV2 authorizes a connection by username only. Unlike the V1 AuthHandler, it receives no password: in V2 the password is the encryption key and is never transmitted, so the fact that the client's frames decrypt successfully already proves it holds the shared secret. The username is used for identity and to attach per-user AuthData.

type Cipher ΒΆ added in v1.3.0

type Cipher interface {
	Seal(plaintext []byte) ([]byte, error)
	Open(nonceAndCiphertext []byte) ([]byte, error)
}

Cipher seals and opens ATXP V2 frame payloads using an authenticated encryption scheme. Implementations are safe for concurrent use.

Seal returns the concatenation nonce || ciphertext || tag. Open expects that same layout and returns the recovered plaintext, or ErrInvalidChecksum when authentication fails (wrong key or tampering).

type Client ΒΆ

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

Client represents an ATXP protocol client session wrapping an active network connection.

func NewClient ΒΆ

func NewClient(conn NetworkIO, username, password string) *Client

NewClient instantiates a new Client reference associated with a specific connection and credentials.

func (*Client) SendDocument ΒΆ

func (c *Client) SendDocument(document []byte, filename string) (ResponseCode, error)

SendDocument transmits a dedicated document byte slice frame payload with an optional filename using the internal Client connection state.

func (*Client) SendNotification ΒΆ

func (c *Client) SendNotification(message string) (ResponseCode, error)

SendNotification transmits a dedicated alert or notification payload frame using the internal Client connection state.

func (*Client) SendURL ΒΆ

func (c *Client) SendURL(url string) (ResponseCode, error)

SendURL transmits a dedicated URL message frame payload using the internal Client connection state.

type ClientV2 ΒΆ added in v1.3.0

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

ClientV2 is a secure ATXP V2 client bound to a single connection. It performs the handshake on construction and thereafter encrypts every frame and tracks sequence numbers for replay protection.

ClientV2 is NOT safe for concurrent use by multiple goroutines; serialize calls or use one client per goroutine.

func NewClientV2 ΒΆ added in v1.3.0

func NewClientV2(conn SecureConn, password, username string, opts ...OptionV2) (*ClientV2, error)

NewClientV2 derives the session key via the V2 client handshake over conn and returns a ready client. The password is used only to derive the encryption key and is never transmitted. username identifies the caller to the server's AuthHandlerV2.

func (*ClientV2) Close ΒΆ added in v1.3.0

func (c *ClientV2) Close() error

Close terminates the underlying connection.

func (*ClientV2) Send ΒΆ added in v1.3.0

func (c *ClientV2) Send(messageType MT, data []byte, filename string) (ResponseCode, error)

Send transmits a frame of an arbitrary (possibly custom, see NewMT) message type. filename is only meaningful for document-like types and may be empty.

func (*ClientV2) SendDocument ΒΆ added in v1.3.0

func (c *ClientV2) SendDocument(document []byte, filename string) (ResponseCode, error)

SendDocument transmits a binary document with an optional filename. The payload may contain arbitrary bytes (e.g. a PDF); the length-prefixed envelope carries it losslessly.

func (*ClientV2) SendNotification ΒΆ added in v1.3.0

func (c *ClientV2) SendNotification(message string) (ResponseCode, error)

SendNotification transmits a notification message frame.

func (*ClientV2) SendURL ΒΆ added in v1.3.0

func (c *ClientV2) SendURL(url string) (ResponseCode, error)

SendURL transmits a URL message frame and returns the server's response code.

type Handler ΒΆ

type Handler func(msg *Message, authData AuthData) ResponseCode

Handler defines a function signature capable of routing and processing incoming decrypted ATXP message payloads.

func ValidateDocumentHandler ΒΆ

func ValidateDocumentHandler(maxBytes int) Handler

ValidateDocumentHandler provides a basic validation ensuring payload sizes match requirements.

func ValidateURLHandler ΒΆ

func ValidateURLHandler() Handler

ValidateURLHandler provides a standard fallback business logic example validation for standard URL structures.

type MT ΒΆ

type MT int

MT represents the numeric type identifier for ATXP message frames.

const (
	URL          MT = 0
	DOCUMENT     MT = 1
	NOTIFICATION MT = 2
)

Message Types constants representing supported ATXP frames.

func StringToType ΒΆ

func StringToType(str string) MT

StringToType converts an ATXP string type representation back to its numeric value.

func StringToTypeV2 ΒΆ added in v1.3.0

func StringToTypeV2(name string) (MT, bool)

StringToTypeV2 resolves a registered message type Name back to its code. The boolean result is false when no registered type carries that name. It is safe for concurrent use.

type MT_V2 ΒΆ added in v1.3.0

type MT_V2 struct {
	// Name is the human-readable identifier transmitted on the wire is NOT
	// used for routing; routing is done by Code. Name is metadata for tooling
	// and diagnostics.
	Name string
	// Code is the numeric routing identifier. It must be unique and, because it
	// is serialized as a big-endian uint32, must be in the range [0, 2^32).
	Code MT
	// Description documents the intended use of the message type.
	Description string
}

MT_V2 describes a registered ATXP V2 message type. Unlike the V1 fixed enum, V2 message types are registrable at runtime so that callers outside this package can define their own framing categories (for example a webhook registration URL, a storage document, or an event-driven notification).

func LookupMT ΒΆ added in v1.3.0

func LookupMT(code MT) (MT_V2, bool)

LookupMT returns the registered MT_V2 for the given code and whether it exists. It is safe for concurrent use.

type Message ΒΆ

type Message struct {
	Type     MT
	Data     box.Optional[[]byte]
	Auth     Auth
	Filename string
}

Message represents an internal ATXP protocol message frame. It wraps the type, an optional byte payload data structure, and credentials.

func ReceiveV2 ΒΆ added in v1.3.0

func ReceiveV2(conn SecureConn, c Cipher) (*Message, uint64, error)

ReceiveV2 reads, opens and decodes a single message frame using the default frame cap MaxFrameSizeV2, returning the message and its sequence number.

type NetworkIO ΒΆ

type NetworkIO interface {
	io.ReadWriter
	Close() error
}

NetworkIO abstracts the net.Conn interface for easy testing and dependency injection.

type OptionV2 ΒΆ added in v1.3.0

type OptionV2 func(*V2)

OptionV2 configures a V2 instance.

func WithHandshakeTimeout ΒΆ added in v1.3.0

func WithHandshakeTimeout(d time.Duration) OptionV2

WithHandshakeTimeout overrides the deadline applied to handshake I/O.

func WithIterations ΒΆ added in v1.3.0

func WithIterations(n int) OptionV2

WithIterations overrides the PBKDF2 iteration count. Values <= 0 are ignored. Both peers must use the same value to derive matching keys.

func WithMaxFrameSize ΒΆ added in v1.3.0

func WithMaxFrameSize(n int) OptionV2

WithMaxFrameSize overrides the maximum encrypted frame size accepted and emitted by ClientV2 and ServerV2 built from this endpoint. Raise it for servers that must transfer large documents, or lower it to tighten the denial-of-service surface. Values below MinFrameSizeV2 are ignored, keeping the default MaxFrameSizeV2. Peers should agree on a compatible cap: a sender's cap must not exceed the receiver's, or large frames are rejected.

type ResponseCode ΒΆ

type ResponseCode int

ResponseCode represents the status of an ATXP protocol handshake or message processing result.

const (
	OK ResponseCode = iota
	ERROR
	UNAUTHORIZED
)

Response Codes constants representing ATXP protocol handshake results.

func ReceiveResponse ΒΆ

func ReceiveResponse(conn NetworkIO) (ResponseCode, error)

ReceiveResponse parses an incoming ATXP acknowledgment envelope to retrieve status responses from a NetworkIO stream.

func ReceiveResponseV2 ΒΆ added in v1.3.0

func ReceiveResponseV2(conn SecureConn, c Cipher) (ResponseCode, uint64, error)

ReceiveResponseV2 reads, opens and decodes a single response frame using the default frame cap.

func SendResponse ΒΆ

func SendResponse(conn NetworkIO, responseCode ResponseCode) (ResponseCode, error)

SendResponse flushes an ATXP status acknowledgment payload segment back to the underlying socket connection.

type SecureConn ΒΆ added in v1.3.0

type SecureConn interface {
	io.ReadWriteCloser
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

SecureConn is the transport contract required by the V2 layer. The standard library net.Conn satisfies it. Declaring deadline methods in the interface keeps every I/O operation bounded and keeps the layer testable with mocks.

type Server ΒΆ

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

Server manages inbound connection routing rules, payload verification, and session authentication lifecycles.

func NewServer ΒΆ

func NewServer(authFn AuthHandler) *Server

NewServer configures a brand new Server context setup with no default active route bindings.

func (*Server) HandleConnection ΒΆ

func (s *Server) HandleConnection(conn NetworkIO)

HandleConnection processes single network stream frames incoming through standard NetworkIO implementations.

func (*Server) RegisterHandler ΒΆ

func (s *Server) RegisterHandler(messageType MT, handler Handler)

RegisterHandler registers a specific Handler callback mapping execution logic against an ATXP framing type.

func (*Server) Serve ΒΆ

func (s *Server) Serve(listener net.Listener) error

Serve initializes a synchronous network event poll looping across an active net.Listener mapping interface.

type ServerV2 ΒΆ added in v1.3.0

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

ServerV2 is a secure ATXP V2 server. It performs the handshake per connection, decrypts and routes frames to registered handlers, and enforces replay protection via per-connection sequence numbers.

ServerV2 is safe for concurrent use: handler registration and lookup are guarded by a mutex, and each connection is handled in its own goroutine.

func NewServerV2 ΒΆ added in v1.3.0

func NewServerV2(password string, authFn AuthHandlerV2, opts ...OptionV2) (*ServerV2, error)

NewServerV2 creates a secure server using the shared password to derive per-connection session keys. authFn may be nil to accept any client that holds the password.

func (*ServerV2) HandleConnection ΒΆ added in v1.3.0

func (s *ServerV2) HandleConnection(conn SecureConn)

HandleConnection runs the handshake and then the per-connection frame loop: receive, verify sequence ordering, authorize, route, respond. Each response also carries a monotonic sequence number for the client's replay checks.

func (*ServerV2) RegisterHandler ΒΆ added in v1.3.0

func (s *ServerV2) RegisterHandler(messageType MT, handler Handler)

RegisterHandler binds a Handler to a message type. It is safe for concurrent use.

func (*ServerV2) Serve ΒΆ added in v1.3.0

func (s *ServerV2) Serve(listener net.Listener) error

Serve accepts connections on listener and handles each in its own goroutine until Accept fails. It returns the Accept error that ended the loop.

type V2 ΒΆ added in v1.3.0

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

V2 holds the shared secret and key-derivation parameters for an ATXP V2 endpoint. It is safe for concurrent use; the derived per-connection Cipher is what carries connection state.

func NewV2 ΒΆ added in v1.3.0

func NewV2(password string, opts ...OptionV2) (*V2, error)

NewV2 creates a V2 endpoint from a shared password. It returns ErrWeakPassword when the password is empty.

func (*V2) ClientHandshake ΒΆ added in v1.3.0

func (v *V2) ClientHandshake(conn SecureConn) (Cipher, error)

ClientHandshake performs the client side of the V2 handshake: it reads and validates the handshake header and returns the session Cipher.

func (*V2) ServerHandshake ΒΆ added in v1.3.0

func (v *V2) ServerHandshake(conn SecureConn) (Cipher, error)

ServerHandshake performs the server side of the V2 handshake: it generates a random salt, transmits the handshake header, and returns the session Cipher. The salt is not secret.

Jump to

Keyboard shortcuts

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