Loading...
xail Docs
Sign out Get started
PRIVATE.ME · Technical White Paper

Xlink: Secure Machine-to-Machine

APIs have keys. ACIs have identity. Xlink is an Authenticated Cryptographic Interface — one-time identity setup replaces ongoing key rotation, gateway configuration, and middleware management. Post-quantum hybrid cryptographic identity (Ed25519 + ML-KEM-768 always-on, ML-DSA-65 opt-in) + encrypted envelopes + optional information-theoretic split-channel. Zero npm dependencies.

v0.1.0 387 tests passing 12 modules 0 npm deps <1ms identity Dual ESM/CJS
Section 01

Executive Summary

Xlink gives every AI agent, microservice, and IoT device a cryptographic identity and a way to exchange messages that are encrypted, signed, and replay-protected — in under 50 lines of code.

Two functions cover 80% of use cases: Agent.create() generates an Ed25519 + X25519 identity with hybrid post-quantum key exchange (X25519 + ML-KEM-768, always-on) and registers it with a trust registry. agent.send() encrypts a payload with AES-256-GCM, signs it with Ed25519 (+ ML-DSA-65 when postQuantumSig: true), and delivers it via any transport adapter. The receiver verifies signatures, checks replay protection, validates scope, and decrypts — automatically.

When you need information-theoretic security, split-channel mode shards messages via XorIDA (threshold sharing over GF(2)) and routes each share independently. An attacker who compromises any single channel learns nothing about the plaintext — not computationally hard to break, but mathematically impossible.

Zero configuration out of the box. Zero npm runtime dependencies. Runs anywhere the Web Crypto API is available — Node.js, Deno, Bun, Cloudflare Workers, browsers. Dual ESM and CJS builds ship in a single package.

Section 02

The Problem

Machine-to-machine security today is a patchwork of API keys, OAuth client credentials, mTLS certificates, and API gateways — each with its own rotation schedule, configuration surface, and failure modes.

API keys leak. They end up in logs, git commits, environment variables shared over Slack, and CI pipelines with overly broad access. Rotation means touching every service that holds the key — a manual, error-prone process.

OAuth is complex. Client credentials flow requires token endpoints, scopes, refresh logic, and revocation. Every new service needs a registration, a secret, and a grant configuration.

mTLS certs expire. Certificate lifecycle management is a full-time job. Renewal failures cause outages. CA compromise is a single point of failure for the entire mesh.

Gateways add latency and cost. Centralized API gateways become bottlenecks, introduce single points of failure, and charge per-request fees that scale with traffic.

Property API Keys OAuth 2.0 mTLS Xlink
Initial setup Minutes Hours Days 5 lines
Key rotation Manual Token refresh Cert renewal Never*
E2E encryption No No Transport only Yes
Forward secrecy No No Optional Auto ECDH
Non-repudiation No No No Ed25519 + ML-DSA-65
Replay prevention No Partial Partial Nonce store
Info-theoretic mode No No No XorIDA split
npm dependencies Varies 10-50+ OS-level 0

* Ed25519 identity keys are permanent. No expiry, no renewal. New identity = new DID. See Limitations for details.

The Old Way

Service A API key API GATEWAY single point of failure per-request cost Service B KEY ROTATION Manual. Touch every service. CERT EXPIRY mTLS renewal = outages NO E2E ENCRYPT Plaintext at every hop Leaked key = full impersonation

The New Way

Service A did:key:z6Mk... encrypt + sign XLINK ENVELOPE AES-256-GCM + Ed25519 nonce + scope + timestamp verify + decrypt Service B did:key:z6Mk... NO KEY ROTATION Ed25519 keys are permanent FORWARD SECRECY Per-message ECDH keys NON-REPUDIATION Ed25519 sig on every msg Optional: XorIDA split-channel — information-theoretic security, zero computational assumptions
Section 03

Real-World Use Cases

Six scenarios where Xlink replaces traditional API key management with Authenticated Cryptographic Interfaces.

📡
IoT
Fleet Telemetry

Each sensor gets a deterministic identity from a factory-burned seed. Signed telemetry envelopes flow to gateways. No API keys to rotate across 10,000 devices.

Agent.fromSeed() + createSignedEnvelope()
🤖
AI / ML
Agent Orchestration

AI agents negotiate tasks via encrypted envelopes with scope-based authorization. The orchestrator verifies each agent’s identity before dispatching work.

Agent.create() + agent.send() + scopes
🌐
Platform
Microservice Mesh

Services authenticate via DID instead of shared secrets. ECDH forward secrecy protects inter-service traffic. No certificate authority to manage.

HttpsTransportAdapter + MemoryTrustRegistry
🏥
Healthcare
Clinical Data Exchange

PHI travels via split-channel — any single intercepted channel reveals zero patient data. HIPAA compliance by mathematical guarantee, not policy alone.

splitChannel: true + 2-of-3 threshold
💹
Financial
Trade Messaging

Order routing with non-repudiation. Ed25519 signatures provide cryptographic proof of trade instructions. Timestamp validation prevents replay attacks.

Ed25519 non-repudiation + 30s window
🏛
Government
Secure Comms

Split-channel with 3-of-5 threshold across classified and unclassified networks. Information-theoretic security exceeds AES-256 — quantum-proof by construction.

splitChannelConfig: { totalShares: 5, threshold: 3 }
Section 04

Solution Architecture

Six composable modules. Each can be used independently or combined through the high-level Agent ACI.

Envelope
v1 / v2 / v3
AES-256-GCM encrypt-then-sign
Ed25519 + ML-DSA-65 dual signatures (v3)
Optional signed-only (cleartext) mode
Trust Registry
3 implementations
Memory (dev), HTTP (prod), did:web
Scope-based authorization
Revocation support
Nonce Store
Replay prevention
Memory (single-node) or Redis (distributed)
SET NX + TTL for atomic dedup
Configurable TTL and cleanup
Key Agreement
X25519 + ML-KEM-768
Hybrid PQ KEM (always-on, v2+)
Ephemeral key pair per message
HKDF-SHA256 over both shared secrets
Transport
Pluggable
HTTPS POST (server-to-server)
Gateway (Xail inbox delivery)
Custom adapter interface
Alice did:key:z6Mk... Ed25519 + X25519 Encrypt AES-256-GCM Sign Ed25519 Transport HTTPS POST Verify Sig + Nonce Bob did:key:z6Mk... Decrypt STANDARD SEND/RECEIVE FLOW Encrypt → Sign → Transport → Verify → Decrypt
Section 04a

The One-Time Setup

Five lines of code. No configuration files, no gateway dashboards, no certificate authorities.

One-time setup
import { Agent, MemoryTrustRegistry, HttpsTransportAdapter } from '@xail/agent-sdk';

const registry  = new MemoryTrustRegistry();
const transport = new HttpsTransportAdapter({ baseUrl: 'https://api.example.com' });
const agent    = (await Agent.create({ name: 'MyService', registry, transport })).value!;

// That's it. agent.did is your identity. agent.send() encrypts + signs + delivers.
await agent.send({ to: recipientDid, payload: { action: 'hello' }, scope: 'chat' });
Compare with API gateway setup
Create gateway instance → configure routes → set up auth provider → generate API keys → configure rate limits → set up key rotation schedule → deploy gateway → update every client → monitor key expiry → handle rotation failures... Xlink: 5 lines, done.
Section 04b

Forward Secrecy

Hybrid post-quantum key agreement: X25519 ECDH + ML-KEM-768 KEM (always-on for v2+ agents). Ephemeral key pairs provide forward secrecy.

The sender generates a fresh ephemeral X25519 key pair per message. The shared secret is derived from the sender's ephemeral private key and the recipient's static X25519 public key. The ephemeral public key is included in the envelope so the receiver can derive the same shared secret.

Compromise of long-term keys does not reveal past messages. Each message uses a unique shared secret derived from a unique ephemeral key pair. Past messages are protected even if both parties' long-term keys are later compromised.

Alice (Sender) 1. Generate ephemeral X25519 2. ECDH: eph.priv x bob.pub 3. Derive AES-256-GCM key 4. Include eph.pub in envelope envelope + ephemeralPub Bob (Receiver) 1. Import eph.pub from envelope 2. ECDH: bob.priv x eph.pub 3. Same AES-256-GCM key 4. Decrypt payload Fresh ephemeral key per message — past messages safe even if long-term key leaks
SHA-256 fallback
When the recipient has not published an X25519 key, the shared key is derived as SHA-256(sort(pubA, pubB)). This is deterministic and not forward-secret. It exists for backward compatibility and is automatically upgraded when X25519 keys become available.
Section 04c

Split-Channel Mode

Information-theoretic security via XorIDA threshold secret sharing. One-line opt-in.

When splitChannel: true is set on agent.send(), the plaintext is split into N shares (default 3) using XorIDA over GF(2), with a reconstruction threshold of K (default 2). Each share is independently encrypted, signed, and transmitted via separate channels.

Split-channel — one line
await agent.send({
  to: recipientDid,
  payload: { secret: 'classified-data' },
  scope: 'secure',
  splitChannel: true,
  splitChannelConfig: { totalShares: 3, threshold: 2 },
});
Plaintext + HMAC key XorIDA GF(2) split <1ms typical Share 1 Share 2 Share 3 Channel A Channel B X Intercepted Reconstruct HMAC verify K=2 of N=3 Plaintext Restored Any 2 of 3 shares reconstruct. A single intercepted share reveals zero information.
Information-theoretic guarantee
XorIDA operates over GF(2) (binary field). Any K-1 or fewer shares reveal exactly zero information about the plaintext. This is not computational security (breakable with enough computing power) — it is information-theoretic security (mathematically impossible to break regardless of computing power, including quantum computers).
Section 05

Identity & Persistence

Ed25519 signing + X25519 key agreement via Web Crypto API. Hybrid post-quantum: ML-KEM-768 for key exchange (always-on), ML-DSA-65 for signatures (opt-in). Multiple persistence strategies for different environments.

DID:key Format

Each agent identity is encoded as a did:key DID string: did:key:z6Mk.... The DID embeds the raw Ed25519 public key with a multicodec prefix (0xed01) and base58btc encoding. Anyone with the DID can verify signatures without a network lookup.

Persistence Strategies

Deterministic Seed
IoT
Agent.fromSeed(32-byte seed)
HKDF-SHA256 derives Ed25519 + X25519
Same seed = same DID on every boot
Raw Key Export
Advanced
agent.exportSeeds() for raw 32-byte keys
Cross-device key transfer
Not the original HKDF seed (one-way)
Composable
Factory
Agent.fromParts() — sync, no async
Pre-built identity + registry + transport
Different lifecycle stages
Section 06

Complete Flow

End-to-end: identity creation through message delivery and verification.

Sender Pipeline

1. Agent.create() generates Ed25519 + X25519 keys (+ ML-DSA-65 keys when postQuantumSig: true) and registers with the trust registry.
2. agent.send() resolves the recipient DID from the registry.
3. Hybrid key exchange: X25519 ECDH + ML-KEM-768 KEM, combined via HKDF-SHA256 (always-on for v2+ agents). SHA-256 fallback for v1 peers.
4. Payload encrypted with AES-256-GCM (12-byte IV, fresh per message).
5. Ciphertext signed with Ed25519 (+ ML-DSA-65 dual signature in v3 envelopes).
6. Envelope assembled: v2/v3, sender DID, recipient DID, timestamp, nonce, scope, payload, signature(s), ephemeralPub, kemCiphertext.
7. Transport adapter delivers the envelope.

Receiver Pipeline

8. agent.receive() validates envelope version (v1/v2/v3) and algorithm.
9. Timestamp checked against configurable window (default 30s).
10. Nonce checked against NonceStore — rejects duplicates (replay prevention).
11. Sender DID resolved from trust registry — must be registered and not revoked.
12. Ed25519 signature verified. ML-DSA-65 signature also verified if present (v3 envelopes).
13. Sender's scope validated against the claimed scope in the envelope.
14. Shared key derived via hybrid KEM (X25519 + ML-KEM-768) or SHA-256 fallback for v1.
15. Payload decrypted with AES-256-GCM.
16. JSON parsed and returned as AgentMessage.

Section 07

Integration Patterns

Four patterns for different deployment contexts.

Express Middleware

Express middleware
import express from 'express';
const app = express();

// Verify incoming agent envelopes
app.post('/api/messages', agent.middleware(), (req, res) => {
  const msg = req.agentMessage;
  console.log('From:', msg.sender, 'Scope:', msg.scope);
  res.json({ ok: true });
});

Registry Auth Middleware

Registry auth
import { createRegistryAuthMiddleware } from '@xail/agent-sdk';

// GET /registry/resolve/:did  → public (no auth)
// POST /registry/register     → requires Bearer token
app.use('/registry', createRegistryAuthMiddleware(process.env.REGISTRY_ADMIN_TOKEN));

IoT Composable Pattern

Minimal IoT — no Agent class needed
import { generateIdentity, createSignedEnvelope, splitForChannel } from '@xail/agent-sdk';

const id = (await generateIdentity()).value!;
const reading = new TextEncoder().encode(JSON.stringify({ temp: 22.5 }));

// Signed-only envelope (no encryption, integrity-only)
const envelope = await createSignedEnvelope({
  senderDid: id.did, recipientDid: gatewayDid,
  scope: 'telemetry', plaintext: reading, privateKey: id.privateKey,
});

// Or split across channels for redundancy
const shares = await splitForChannel(reading, { totalShares: 3, threshold: 2 });

Signed-Only Telemetry

Gateway accepting cleartext + encrypted
// Gateway accepts both encrypted and signed-only envelopes
const msg = await gateway.receive(envelope, { allowCleartext: true });
if (msg.ok) {
  console.log(msg.value.payload); // works for both modes
}
Section 08

Security Properties

Seven layers of defense. Each independently verifiable.

Property Mechanism Guarantee
Confidentiality AES-256-GCM per message Payload encrypted in transit and at rest
Authentication Ed25519 + ML-DSA-65 (dual) Sender identity verified on every envelope (PQ-safe with opt-in)
Integrity Encrypt-then-sign Any modification fails verification
Non-repudiation Ed25519 + ML-DSA-65 dual signature Sender cannot deny sending (quantum-safe with opt-in)
Forward secrecy X25519 + ML-KEM-768 hybrid Post-quantum forward secrecy (always-on)
Replay prevention Nonce store + timestamp Duplicate envelopes rejected
Info-theoretic XorIDA split-channel K-1 shares reveal zero bits

Supply Chain Security

Zero npm runtime dependencies. The SDK depends only on workspace packages (@xail/shared, @xail/crypto) which are part of the same monorepo. No third-party code executes at runtime. This eliminates the entire class of supply chain attacks from compromised npm packages.

Comparison to Alternatives

Property Xlink TLS Signal Protocol
E2E encryption Yes Transport only Yes
Forward secrecy Yes (Hybrid PQ KEM) Yes (DHE) Yes (Ratchet)
Info-theoretic Yes (XorIDA) No No
Non-repudiation Ed25519 + ML-DSA-65 No No
Replay prevention Nonce store Seq numbers Chain keys
Zero npm deps Yes N/A No
M2M focused Yes General Person-to-person
Section 09

Benchmarks

Performance characteristics measured on Node.js 22, Apple M2.

<1ms
Identity generation
<1ms
Encrypt + sign
<1ms
Verify + decrypt
~33ms
XorIDA 1MB split
387
Tests passing
Operation Time Notes
Ed25519 keygen <1ms Web Crypto API native
X25519 keygen <1ms Web Crypto API native
ECDH key agreement <1ms Ephemeral + derive
AES-256-GCM encrypt (1KB) <0.5ms Hardware-accelerated
Ed25519 sign <0.5ms Covers ciphertext bytes
Full send pipeline (Xchange) ~1ms Random key + encrypt + XorIDA split + sign
Full receive pipeline (Xchange) ~1ms Verify + reconstruct + HMAC + decrypt
XorIDA split (1MB, 3 shares) ~52ms GF(2) — 15x faster than Shamir's at 1MB
XorIDA reconstruct (1MB) ~33ms Including HMAC verification
Nonce check (memory) <0.1ms Map lookup + TTL check

XorIDA vs AES-256-GCM — API Payload Performance

Fairness Disclosure
AES-256-GCM benchmarks use the Web Crypto API with hardware AES-NI acceleration. XorIDA runs in pure JavaScript (GF(2) XOR operations). Both measured on the same machine under the same conditions. XorIDA is faster at typical API payload sizes despite running without hardware acceleration.

Typical ACI traffic — auth tokens, JSON responses, webhooks, chat messages — is under 1 KB. At these sizes, XorIDA’s simple XOR-only arithmetic completes a full split-and-reconstruct roundtrip 2–11× faster than AES-256-GCM can encrypt-and-decrypt, while providing strictly stronger (information-theoretic) security.

256-Byte Roundtrip — Visual Comparison

XorIDA 2-of-2
35µs
XorIDA 2-of-3
41µs
AES-256-GCM
122µs

Shorter bar = faster. 256B payload, 2,000 iterations, median roundtrip time.

Full Comparison — API Payload Sizes

Payload XorIDA 2-of-2 XorIDA 2-of-3 AES-256-GCM Ratio (2-of-2) Real-World Example
64B 14µs 17µs 160µs 11.4× faster IoT sensor reading, heartbeat
128B 23µs 26µs 160µs 7.0× faster Auth token, session ticket
256B 35µs 41µs 122µs 3.5× faster Chat message, SMS-length payload
512B 34µs 39µs 138µs 4.0× faster Webhook, API key exchange
1KB 58µs 107µs 140µs 2.4× faster REST API JSON response
2KB 211µs 262µs 142µs 1.5× slower GraphQL response
4KB 340µs 313µs 134µs 2.5× slower Large API response
8KB 644µs 883µs 227µs 2.8× slower Crossover zone

Node.js 22 • 2,000 iterations per size • Median roundtrip (split+reconstruct / encrypt+decrypt)

Honest About Tradeoffs
Above ~1–2 KB, hardware-accelerated AES-256-GCM is faster. But typical API payloads — auth tokens, JSON responses, chat messages, webhook notifications — are under 1 KB, exactly where XorIDA excels. For the payloads Xlink actually processes, XorIDA is 2–11× faster than AES-256 while providing strictly stronger security.

Xlink vs Competitors — API Crypto Overhead

Full send + receive roundtrip measured end-to-end with real crypto operations. Competitor estimates use our measured primitive timings (same algorithms, same JS runtime) as reference. Xlink uses split-channel (2-of-3); competitors use single-channel delivery.

256-Byte API Payload — Full Roundtrip

Xlink (Xchange)
1.9ms
Tuta
4.2ms
Signal
5.0ms
Apple PQ3
5.0ms

Shorter bar = faster. 256B payload, 200 iterations, median roundtrip time.

Full Comparison — All API Payload Sizes

Payload Xlink Tuta Signal Apple PQ3 Use Case
64B 2.0ms 4.2ms 5.0ms 5.0ms Auth token, session ID
128B 1.8ms 4.2ms 5.0ms 5.0ms Webhook notification
256B 1.9ms 4.2ms 5.0ms 5.0ms Small JSON response
512B 1.8ms 4.2ms 5.0ms 5.0ms API request body
1KB 1.9ms 4.2ms 5.0ms 5.0ms Large JSON / config
2KB 1.9ms 4.2ms 5.0ms 5.0ms Batch API response
4KB 2.5ms 4.2ms 5.0ms 5.0ms Document payload
8KB 3.7ms 4.3ms 5.1ms 5.1ms Rich API response

Node.js 22 • 200 iterations per size • Median send+receive roundtrip • 2-of-3 split

Fairness Disclosure
Competitor estimates use our measured primitive timings as reference—same algorithms (ML-KEM-768, X25519, AES-256), same JS runtime. Native implementations (CryptoKit, BoringSSL) would be faster for KEM operations, but Xlink’s Xchange eliminates KEM entirely—native KEM speed becomes irrelevant when the operation is removed from the pipeline.

Crypto Overhead as % of Total API Latency (256B)

Network Latency Xlink Tuta Signal
Local (1ms) 65.9% 80.8% 83.3%
Regional (10ms) 16.2% 29.6% 33.3%
Cross-region (50ms) 3.7% 7.7% 9.1%
Global (150ms) 1.3% 2.7% 3.2%

Lower % = less crypto tax on your API calls. At 10ms+ latency, Xlink overhead is negligible.

Security vs Performance

Ranked by roundtrip speed at 256B. Xlink is the fastest system with post-quantum protection—and the only one providing information-theoretic security.

AES-256-GCM
Computational
256-bit symmetric key
Grover’s algorithm reduces effective key space to 128 bits
Security depends on AES not being broken
Key must be exchanged, stored, and protected
# System Roundtrip Security Model PQ Protection
1 Xlink 1.9ms Information-theoretic Unconditional
2 Tuta 4.2ms Computational Kyber KEM only
3 Signal 5.0ms Hybrid computational Kyber KEM only
4 Apple PQ3 5.0ms Hybrid computational Kyber KEM only
Key Insight
Competitors use Kyber KEM for key agreement—a lattice-based algorithm that depends on the hardness of Module-LWE. Xlink’s Xchange replaces KEM entirely with XorIDA-split random keys. No lattice assumptions, no key agreement, no keys to steal. The split is the security. Faster and stronger—not a tradeoff, a free upgrade.
Section 10

Honest Limitations

Eight known limitations documented transparently. No product is perfect — here is what Xlink does not do.

Limitation Impact Mitigation
Cleartext headers Sender/recipient DIDs, scope, timestamp visible to network observers. Traffic analysis possible. Payload is encrypted. Use TLS for transport-level protection of headers.
No push revocation Revoked agents' in-flight messages may be processed before receiver re-checks registry. Keep timestamp windows short (default 30s).
No key rotation Ed25519 identity keys are permanent. No built-in rotation protocol. Create new identity and re-register. Old DID becomes unused.
SHA-256 fallback When ECDH unavailable, shared key is deterministic. Not forward-secret. Ensure both parties publish X25519 keys for automatic ECDH upgrade.
Ephemeral nonce store MemoryNonceStore clears on process restart. Replays within timestamp window succeed. Use RedisNonceStore for production deployments.
Clock dependency Timestamp validation assumes synchronized clocks. Large skew causes false rejections. Use NTP. Increase timestampWindowMs for high-latency networks.
No payload size limits SDK does not enforce maximum payload size. Large payloads can exhaust memory. Validate payload size at application layer before calling send().
Registry trust Compromised registry can substitute public keys or modify scopes. Use createRegistryAuthMiddleware() with bearer token auth on writes.
Section 11

Post-Quantum Security

Xlink is end-to-end post-quantum. XorIDA payload splitting is information-theoretically quantum-safe. Key exchange uses hybrid X25519 + ML-KEM-768 (always-on, FIPS 203). Signatures use dual Ed25519 + ML-DSA-65 (opt-in via postQuantumSig: true, FIPS 204). All three cryptographic layers — payload, key exchange, and authentication — have quantum-safe implementations deployed.

Two Security Layers

The Xlink architecture has two distinct cryptographic layers with different quantum profiles:

LayerCurrentQuantum StatusUpgrade Path
Payload (XorIDA) GF(2) threshold sharing Quantum-safe now No change needed
Symmetric encryption AES-256-GCM Quantum-safe now No change needed
Key establishment X25519 + ML-KEM-768 (hybrid) Hybrid PQ — Phase 1 live Phase 1 deployed (v2 envelopes)
Identity / signatures Ed25519 + ML-DSA-65 (dual) Hybrid PQ — Phase 2 deployed (opt-in) Phase 2 deployed (v3 envelopes)

Migration Strategy

The upgrade follows a three-phase hybrid-first approach. Each phase maintains backward compatibility with the previous one.

PHASE 1 — DEPLOYED Key Exchange X25519 + ML-KEM-768 HKDF over both secrets Signatures Ed25519 (unchanged) Payload XorIDA (unchanged) Secure if either KEM holds PHASE 2 — DUAL SIG (DEPLOYED) Key Exchange X25519 + ML-KEM-768 HKDF over both secrets Signatures Ed25519 + ML-DSA-65 Both required to verify Payload XorIDA (unchanged) Full PQ + classical auth PHASE 3 — PURE PQ Key Exchange ML-KEM-768 only FIPS 203 standard Signatures ML-DSA-65 only FIPS 204 standard Payload XorIDA (unchanged) End-to-end post-quantum

Algorithm Profile

FunctionAlgorithmStandardKey / Sig Size
KEM (Phase 1+) ML-KEM-768 FIPS 203 1,184 B pub / 1,088 B ct
Hybrid KEM X25519 + ML-KEM-768 IETF draft HKDF over both shared secrets
Signature (Phase 2, deployed) ML-DSA-65 FIPS 204 1,952 B pub / 3,309 B sig
Symmetric AES-256-GCM NIST SP 800-38D Unchanged
Payload splitting XorIDA GF(2) Patent-protected Unchanged

Latency Impact

Post-quantum operations add minimal computational overhead. The dominant latency remains network I/O, not cryptography.

OperationCurrent (Classical)Hybrid (Phase 1)Delta
Key exchange <0.1ms (X25519) ~0.3ms (X25519 + ML-KEM) +0.2ms
Sign <0.1ms (Ed25519) ~1.1ms (Ed25519 + ML-DSA) +1.0ms
Verify <0.2ms (Ed25519) ~0.7ms (Ed25519 + ML-DSA) +0.5ms
Full handshake ~0.4ms ~2.1ms +1.7ms
Envelope overhead ~128 bytes ~6,340 bytes +6.1 KB
Developer impact
The API surface does not change. Agent.create(), agent.send(), and agent.receive() remain identical. The post-quantum upgrade happens inside the Xlink infrastructure layer — all 68 ACIs inherit it automatically by updating one dependency.

Envelope Version

The envelope format uses a v2 version tag signaling hybrid PQ support. Agents negotiate capabilities automatically:

  • v1 agents communicate using classical crypto (X25519-only ECDH)
  • v2 agents communicate using hybrid PQ + classical crypto (X25519 + ML-KEM-768)
  • v2 agents automatically fall back to v1 when communicating with v1 peers
  • v3 agents add dual signatures (Ed25519 + ML-DSA-65) — deployed, opt-in via postQuantumSig: true
Phase 1 — deployed
Hybrid key establishment is live. v2 envelopes use X25519 + ML-KEM-768 (FIPS 203) with HKDF-SHA256 key combination. Session keys are secure as long as either scheme holds. Backward compatible — v1 agents work unchanged. The split-channel payload layer remains information-theoretically quantum-safe (XorIDA over GF(2)). Signatures: Phase 2 deployed — hybrid Ed25519 + ML-DSA-65 (opt-in via postQuantumSig: true).
Section 12

Protocol Security Stack

The Xlink protocol secures messages at three independent cryptographic layers. Each layer addresses a different threat surface. Together, they provide full-stack quantum safety with no single point of cryptographic failure.

Three-Layer Architecture

Layer Function Algorithm Standard Quantum Status
Payload Message confidentiality XorIDA threshold sharing over GF(2) Proprietary (patented) Immune
Key Exchange Session key establishment X25519 + ML-KEM-768 (hybrid) FIPS 203 Quantum-safe
Authentication Identity verification & integrity Ed25519 + ML-DSA-65 (dual) FIPS 204 Quantum-safe

Layer 1 — Payload (Information-Theoretic)

XorIDA splits the plaintext into threshold shares using XOR operations over GF(2). Each share is individually indistinguishable from random noise. No computation — classical or quantum — can extract information from fewer than k shares. This is not computational hardness; it is a mathematical proof. The payload layer is immune to harvest-now-decrypt-later attacks because there is no key to break, no structure to exploit, and no algorithm that reduces the problem.

Layer 2 — Key Exchange (Hybrid Post-Quantum KEM)

Session keys are established using a hybrid key encapsulation mechanism: classical X25519 ECDH combined with ML-KEM-768 (FIPS 203, formerly CRYSTALS-Kyber). Both shared secrets are combined via HKDF-SHA256 to derive the session key. The session key is secure as long as either X25519 or ML-KEM-768 remains unbroken — defense in depth. Hybrid KEM is live in v2 envelopes (Phase 1, deployed).

Layer 3 — Authentication (Dual Signatures)

Message authentication and sender identity use dual signatures: classical Ed25519 plus post-quantum ML-DSA-65 (FIPS 204). Both signatures must verify for the message to be accepted. ML-DSA-65 signatures are opt-in via postQuantumSig: true in the agent configuration. When enabled, v3 envelopes carry both signatures. Classical-only agents continue to work with v1/v2 envelopes.

Envelope Version Progression

  • v1 — Classical only. X25519 ECDH key exchange, Ed25519 signatures.
  • v2 — Hybrid PQ KEM. X25519 + ML-KEM-768 key exchange, Ed25519 signatures. Backward-compatible with v1 peers.
  • v3 — Full PQ. Hybrid KEM + dual signatures (Ed25519 + ML-DSA-65). Backward-compatible with v1/v2 peers.

Agents negotiate capabilities automatically. A v3 agent communicating with a v1 peer falls back to v1 envelope format. No developer action required — the protocol handles version negotiation internally.

Full-stack quantum safety available
With postQuantumSig: true, all three cryptographic layers are quantum-safe. The payload is information-theoretically immune. Key exchange uses hybrid PQ KEM (FIPS 203). Authentication uses dual PQ signatures (FIPS 204). All 68 ACIs inherit this protection by updating one dependency.
Advanced Reference

Implementation Details

Deep-dive into error handling, trust registry, nonce store, transport adapters, and the complete ACI surface.

Appendix A1

Error Hierarchy

Typed error classes for structured error handling. Supplementary to the Result<T,E> string code pattern.

Error class hierarchy
XlinkError                    // Base class (code, subCode, docUrl)
  ├── XlinkIdentityError       // Ed25519/X25519 keygen, sign, verify, DID
  ├── XlinkEnvelopeError       // Envelope create, encrypt, decrypt, parse
  ├── XlinkTransportError      // Send failures, network, timeouts
  ├── XlinkRegistryError       // Lookup, registration, revocation
  ├── XlinkKeyAgreementError   // X25519 ECDH derivation
  ├── XlinkSplitChannelError   // XorIDA split, reconstruct, HMAC
  └── XlinkAgentError          // High-level Agent lifecycle
Converting string codes to class errors
import { toXlinkError, isXlinkError } from '@xail/agent-sdk';

const result = await agent.receive(envelope);
if (!result.ok) {
  const err = toXlinkError(result.error);
  console.log(err.code);     // 'DECRYPT_FAILED'
  console.log(err.subCode);  // 'KEY_AGREEMENT'
  console.log(err.docUrl);   // 'https://xail.io/sdk/index/docs/packages/xlink#envelope'
  console.log(err.name);     // 'XlinkEnvelopeError'
}
Appendix A2

Trust Registry

Three implementations covering development through production.

HttpTrustRegistry
Production
HTTP-backed with per-DID cache
Configurable cache TTL (default 30s)
Bearer token auth on writes
DidWebResolver
W3C
Resolves did:web via HTTPS
TLS mandatory (W3C spec)
5-minute cache TTL
Scope Authorization
RBAC
Per-agent scope sets
Checked on every receive()
SCOPE_DENIED on unauthorized
Agent resolve(did) hasScope(did, s) Trust Registry DID → Public Key DID → Scopes DID → X25519 Key + revocation status Result ok: rawPublicKey err: NOT_FOUND | REVOKED
Appendix A3

Nonce Store

Replay prevention via unique nonce tracking. Every envelope carries a cryptographic 16-byte nonce.

RedisNonceStore
Distributed
SET NX EX for atomic dedup
Cross-node replay prevention
Configurable TTL and key prefix
Bring your own Redis client
Appendix A4

Transport Adapters

Pluggable delivery mechanism. Two built-in adapters plus a custom interface.

GatewayTransport
Xail Inbox
POST /gateway/deliver with API key
Optional polling for incoming
dispose() stops polling timer
Custom transport adapter interface
interface XailTransportAdapter {
  send(envelope: TransportEnvelope, to: string): Promise<Result<void, TransportError>>;
  onReceive(handler: (envelope: TransportEnvelope) => void): void;
  dispose(): void;
}
Appendix A5

Full ACI Surface

Complete Authenticated Cryptographic Interface organized by module.

Agent

Agent.create(opts) → Promise<Result<Agent>>

Generate identity, register with registry, wire transport. Primary factory.

Agent.fromIdentity(identity, opts) → Promise<Result<Agent>>

Restore from persisted PKCS8 identity. Skips keygen + registration.

Agent.fromParts(identity, registry, transport, opts?) → Agent

Synchronous construction from pre-built components. No async, no Result.

Agent.fromSeed(seed, opts) → Promise<Result<Agent>>

Deterministic identity from 32-byte seed via HKDF-SHA256. IoT factory provisioning.

agent.send({ to, payload, scope, splitChannel? }) → Promise<Result<void>>

Encrypt, sign, and deliver. Auto ECDH when available. Optional split-channel.

agent.receive(envelope, { allowCleartext? }) → Promise<Result<AgentMessage>>

Verify version, timestamp, nonce, sender, signature, scope. Decrypt. Parse.

Identity

generateIdentity(opts?) → Promise<Result<AgentIdentity>>

Ed25519 + X25519 keypair generation via Web Crypto API. ML-DSA-65 keys when postQuantumSig: true.

exportPKCS8(key) / importFromPKCS8(bytes) / importIdentity(ed, x25519)

PKCS8 DER export/import for identity persistence.

identityFromSeed(seed) → Promise<Result<AgentIdentity>>

HKDF-SHA256 deterministic derivation from 32-byte seed.

Envelope

createEnvelope(opts) / createSignedEnvelope(opts)

Encrypted or signed-only envelope creation.

validateEnvelope(body) / deserializeEnvelope(data)

Validation and deserialization from unknown input.

Split-Channel

splitForChannel(plaintext, config?) → Promise<Result<ChannelShare[]>>

XorIDA split with HMAC integrity. Default: 3 shares, threshold 2.

reconstructFromChannel(shares) → Promise<Result<Uint8Array>>

Reconstruct from K+ shares. HMAC verified before returning plaintext.

Key Agreement

senderKeyAgreement(recipientPub) / receiverKeyAgreement(privKey, ephPub)

Hybrid X25519 + ML-KEM-768 key agreement with ephemeral key pair per message.

Appendix A6

Error Taxonomy

Complete error code table with sub-codes and error classes.

Code Class When
IDENTITY_FAILEDAgentIdentity generation fails during create()
REGISTRATION_FAILEDAgentRegistry rejects registration
REGISTRATION_FAILED:ALREADY_REGISTEREDAgentDID already exists in registry
VERIFICATION_FAILED:SIGNATURE_MISMATCHAgentEd25519 signature does not match
VERIFICATION_FAILED:DID_NOT_IN_REGISTRYAgentSender DID not found in registry
REPLAY_DETECTEDAgentDuplicate nonce (replay attack)
TIMESTAMP_EXPIREDAgentEnvelope outside timestamp window
SCOPE_DENIEDAgentSender lacks required scope
DECRYPT_FAILED:KEY_AGREEMENTEnvelopeECDH derivation fails
DECRYPT_FAILED:DECRYPTIONEnvelopeAES-GCM decryption fails
DECRYPT_FAILED:PARSEEnvelopeDecrypted bytes not valid JSON
SEND_FAILED:BELOW_THRESHOLDTransportSplit: fewer than K shares delivered
HMAC_VERIFICATION_FAILEDSplitChannelShare HMAC check fails
INSUFFICIENT_SHARESSplitChannelFewer than threshold shares
INCONSISTENT_SHARESSplitChannelMismatched groupId or params
INVALID_KEY_LENGTH:EXPECTED_32KeyAgreementX25519 key not 32 bytes
Appendix A7

Codebase Stats

Xlink v0.1.0 — Gold Standard Bronze tier achieved.

14
Source files
25
Test files
387
Tests passing
22
Documentation files
0
npm dependencies

Module Inventory

Module Source File Purpose
Identityidentity.tsEd25519 + X25519 keygen, DID, PKCS8, sign/verify
Envelopeenvelope.tsv1 create/decrypt/serialize/validate
Agentagent.tsTop-level ACI (create, send, receive, middleware)
Split-Channelsplit-channel.tsXorIDA bridge: split, reconstruct, HMAC
Key Agreementkey-agreement.tsX25519 ECDH ephemeral key agreement
Nonce Storenonce-store.tsMemoryNonceStore for replay prevention
Redis Nonceredis-nonce-store.tsRedisNonceStore for distributed deployments
Trust Registrytrust-registry.tsMemory + HTTP registry
DID:webdid-web.tsW3C did:web resolver
Transporttransport.tsInterface + HTTPS adapter
Gatewaygateway-transport.tsXail inbox gateway delivery
Middlewareregistry-middleware.tsExpress auth middleware for registry
Errorserrors.tsError class hierarchy (XlinkError + 7)
Verifyverify.tsLightweight verify-only sub-path

Documentation

22 documentation files including: SECURITY.md, CHANGELOG.md, QUICKSTART.md, MIGRATION.md, CONTRIBUTING.md, AGENTS.md, threat model, data flow diagrams, security whitepaper, failure modes, Gold Standard assessment, and 4 example scripts.