Loading...
private.me Docs
Get xPass
PLATFORM — CONNECTION BILLING

xPass: XorIDA-Based Billing Enforcement

Embeds M2M billing enforcement inside encryption. Server XorIDA-splits a connection secret into 2-of-2 shares. Each agent gets one share. Both needed to decrypt. Single share = cryptographic noise. The billable unit is a connection: (DID_A, DID_B, scope). integrate into your applications to enforce cryptographic billing across M2M connections with zero usage tracking overhead.

~30µs per message Per-connection billing Information-theoretic enforcement 33 tests passing 3-month Free Trial
Section 01

The Problem

M2M billing enforcement is unsolved. Every existing approach trades latency for control, or gives up control entirely.

Machine-to-machine agent communication creates a fundamental billing challenge: how do you ensure that every connection between agents is paid for, without introducing latency that kills the performance advantage of direct communication?

Gateway Relay

Route all traffic through a billing server. The server verifies payment status before forwarding. Problem: Every message takes a detour through the gateway, adding 10-50ms of latency. At scale, the gateway becomes a single point of failure and a bottleneck.

HMAC Tickets

Server issues time-limited HMAC tokens. Agents present tokens to prove they have paid. Problem: A forked SDK can simply skip token verification. The enforcement is behavioral — it relies on the SDK checking the token.

Key Oracle

Server holds the encryption key and distributes it only to paid agents. Problem: Once the key is distributed, nothing prevents the agent from caching it indefinitely or sharing it with unpaid agents.

API Metering

Count API calls or bytes transferred and bill based on usage. Problem: Usage-based billing requires centralized metering infrastructure, adds latency to every call, and has no cryptographic binding between the metering event and the actual data exchange. Agents can communicate out-of-band once they have each other's identity.

Core Insight
All four approaches share the same flaw: enforcement is separate from encryption. The billing check and the message encryption are two independent steps. If you can skip the check, you keep the encryption. xPass makes them inseparable.
Section 02

Competitive Analysis

Existing billing platforms were designed for human-to-server interactions. None embeds billing enforcement inside the cryptographic layer.

PlatformCrypto BindingDID-AwareM2M NativeBypass RiskEnforcement
Stripe Metered BillingNoneNoNoHigh — SDK skipBehavioral
AWS MarketplaceNoneNoNoMedium — key cacheDistribution
Zuora SubscriptionNoneNoNoHigh — no cryptoContractual
ChargebeeNoneNoNoHigh — honor systemContractual
xPass BasicXorIDA 2-of-2YesYes24h windowMathematical
xPass+3-Party MPCYesYesNear-zeroMathematical
Why This Matters
Stripe, AWS Marketplace, and Zuora handle billing collection well. They do not handle billing enforcement. There is a fundamental difference: collection asks politely; enforcement makes non-payment mathematically impossible. xPass is the first billing system where the enforcement mechanism and the encryption mechanism are the same operation.

The Gap

Every existing billing platform assumes trust between the billing server and the consuming application. The server says "this customer has paid" and the application trusts that signal. In M2M agent ecosystems, applications are autonomous software — they can be forked, modified, or run in environments where the billing check is stripped out. You need enforcement that survives hostile environments.

xPass closes this gap by making the billing relationship a cryptographic precondition for communication. The connection secret is split via XorIDA. Without both shares — which requires an active billing relationship — there is no secret. Without the secret, there is no encryption. Without encryption, there is no communication.

Market Context

The M2M communication market is projected to reach $27B by 2028. As AI agents proliferate, the need for enforceable billing between autonomous systems grows exponentially. Traditional SaaS billing (Stripe, Zuora, Chargebee) was designed for human-to-server interactions where the human has a payment method attached to their account. M2M billing requires a fundamentally different model where enforcement is embedded in the communication protocol itself.

xPass is purpose-built for this market. It does not replace Stripe for human billing — it solves the problem that Stripe cannot: ensuring that autonomous agents pay for every communication channel they use, without relying on the agent's cooperation or honest behavior.

Section 03

The Solution

xPass embeds enforcement inside encryption. The connection secret is XorIDA-split. Both shares are required to decrypt. Reconstruction IS verification.

Instead of verifying payment and then encrypting, xPass makes the encryption itself dependent on the billing relationship. The server generates a connection secret and immediately splits it via XorIDA into 2-of-2 shares. Each agent receives one share. To encrypt or decrypt a message, both shares must be combined to reconstruct the connection secret.

A single share is information-theoretically indistinguishable from random noise. This is not a computational claim — it is a mathematical proof. No amount of computing power, including quantum computers of any size, can extract any information from a single share.

How It Works

BILLING SERVER Generate + XorIDA Split Share 1 Share 2 AGENT A Holds Share 1 AGENT B Holds Share 2 Reconstruct + Decrypt

Billable Unit

The fundamental billing primitive is a connection: the tuple (DID_A, DID_B, scope). Each unique connection is one billable unit. The connection is symmetric — A-to-B is the same connection as B-to-A. Scope isolates different communication contexts between the same pair of agents (e.g., "xlink" for messaging, "xcompute" for MPC sessions).

1 ACI per M2M connection: Each connection represents one ACI subscription. The billing server enforces this by splitting the connection secret into K-of-N shares (2-of-2 for xPass Basic) and distributing them to the participating agents. Without a valid connection (paid subscription), the agents cannot reconstruct the secret required for encrypted communication. Within a connection, usage is unlimited — no per-message metering.

Free trial: All new accounts receive a 3-month free trial (all tiers included). No credit card required during trial period.

Why Connection-Based, Not Usage-Based

Usage-based billing (per-message, per-byte, per-API-call) requires centralized metering infrastructure that adds latency and complexity. It also creates perverse incentives: agents are penalized for communicating more, which conflicts with the goal of enabling rich M2M interaction. Connection-based billing is simple, predictable, and adds zero per-message overhead.

The connection model mirrors how human subscriptions work: you pay for a phone line, not per minute. The connection exists, and within it, communication is unlimited. This model is particularly well-suited for M2M agent ecosystems where communication patterns are bursty and unpredictable.

Connection Identifier
// Deterministic, symmetric: A→B = B→A
ConnectionId = SHA-256(sort(didA, didB) + "|" + scope)

// Example
createConnectionId(
  "did:key:z6MkAgent1",
  "did:key:z6MkAgent2",
  "xlink"
) // → "a3f8...7b2c" (64-char hex)
Section 04

Architecture

Two tiers: xPass Basic for P2P with 24h epoch rotation, and xPass+ for server-mediated MPC with near-zero bypass window.

xPass Basic (2-of-2, P2P)

Server generates a 256-bit connection secret, splits it via XorIDA into 2-of-2 shares, and distributes one share to each agent. After distribution, the server discards the secret. Shares rotate every 24 hours (configurable epoch).

Bypass window: 24 hours. If both agents collude to cache the reconstructed secret, they can communicate without contacting the server for one epoch.

K-of-N enforcement: xPass Basic enforces a strict 2-of-2 split configuration (XPASS_THRESHOLD=2, XPASS_TOTAL_SHARES=2). This configuration ensures that both parties must participate for billing enforcement to work. Attempting to configure K>2 (e.g., 2-of-3 or higher) will return an INVALID_CONFIG error with guidance to use xPass+ for fault tolerance.

xPass+ (3-Party MPC)

Server holds Share 3 and participates in an xCompute 3-party MPC session to generate a session key. Session keys are valid for 5-60 minutes (configurable). If the server does not participate, no session key is generated.

Bypass window: Near-zero. The server must participate in every session.

K-of-N support: xPass+ supports threshold configurations beyond 2-of-2, including 2-of-3 for fault tolerance. The third party (billing server) participates in MPC computation rather than simply distributing shares, enabling resilient billing enforcement even if one party is temporarily unavailable.

Epoch Rotation

Connection secrets rotate on a configurable epoch (default 24 hours). At epoch boundary, the server generates a new secret, splits it, and distributes new shares. Old shares are invalidated. Agents must contact the billing server at least once per epoch to receive their new share — this is the enforcement checkpoint.

Rotation is designed to be seamless: agents request their new-epoch share proactively before the current epoch expires. A 15-minute overlap window ensures no messages are lost during transition. Both the old and new epoch shares are valid during the overlap period.

Share Structure

Each share is wrapped in an xFormat binary envelope with the IDA5 magic header (0x49444135). The envelope includes the share index, threshold parameters (n, k), a UUID linking all shares from the same split, an epoch number, the ConnectionId, and an HMAC-SHA256 integrity tag. The envelope is Base45-encoded for transport.

Share Envelope Structure
// xFormat binary envelope for xPass shares
[IDA5 magic: 4 bytes]        // 0x49444135
[product type: 2 bytes]      // 0x0042 (xPass)
[share index: 1 byte]        // 1-based index
[n: 1 byte]                  // total shares
[k: 1 byte]                  // threshold
[uuid: 16 bytes]             // links shares from same split
[epoch: 4 bytes]             // epoch number (uint32 BE)
[connectionId: 32 bytes]     // SHA-256 of sorted DIDs + scope
[hmac: 32 bytes]             // HMAC-SHA256 integrity tag
[payload: variable]          // XorIDA share data

Connection Lifecycle

Connection State Machine
// 1. Creation: billing relationship established
PENDING → createConnection(didA, didB, scope) → ACTIVE

// 2. Active: shares distributed, communication flows
ACTIVE → epochRotate() → ACTIVE  // new shares every 24h

// 3. Suspension: payment lapsed
ACTIVE → suspend() → SUSPENDED  // shares invalidated

// 4. Grace period: 72h to resolve billing
SUSPENDED → grace() → GRACE  // limited communication

// 5. Revocation: permanent disconnection
GRACE → revoke() → REVOKED  // all shares destroyed

// 6. Reactivation: new payment
SUSPENDED | REVOKED → reactivate() → ACTIVE
Key Architecture Decisions
Symmetric ConnectionId: sort(DID_A, DID_B) ensures A-to-B and B-to-A map to the same connection. One subscription covers both directions.
Scope isolation: The same pair of agents can have multiple connections with different scopes. Each scope is independently billed and independently revocable.
Server discards secret: After splitting and distributing, the server does not retain the connection secret. This limits the blast radius of a server compromise.
Section 05

Benchmarks

xPass Basic adds ~30µs per message. xPass+ adds ~50-200ms per session start, then zero overhead per message within the session. Connection check completes in under 1ms.

~30µs
Per-message (Basic)
<1ms
Connection check
32B
Connection secret
24h
Default epoch
OperationxPass BasicxPass+Notes
Share issuance (server)~15µs~15µsXorIDA 2-of-2 split of 32-byte secret
HMAC verification~5µs~5µsHMAC-SHA256 per share before reconstruction
XorIDA reconstruction~5µsN/AXOR-based reconstruction over GF(2)
AES-256-GCM encrypt~10µs~10µsFresh IV per message
MPC session startN/A~50-200msxCompute 3-party protocol
Connection check<1ms<1msVerify billing status for a DID pair
Per-message total~30µs~10µs (after session)Amortized overhead
Epoch rotation~20µs~20µsNew secret generation + split

Scaling Characteristics

xPass Basic has O(1) per-message cost: the XorIDA reconstruction and AES encryption are constant-time for the 32-byte connection secret, regardless of how many connections an agent maintains. The connection check is a hash table lookup — O(1) amortized.

Server-side, share issuance scales linearly with the number of active connections. A single billing server can manage ~100K active connections with sub-second epoch rotation. For larger deployments, connections are sharded by ConnectionId prefix across multiple billing nodes.

Latency Budget Breakdown

For a typical xPass Basic message send, the total billing enforcement overhead is approximately 30 microseconds, broken down as follows:

StepTimeDescription
1. Connection lookup~1µsHash table lookup by ConnectionId
2. Epoch check~0.5µsCompare current time vs. epoch boundary
3. HMAC verify (share 1)~5µsHMAC-SHA256 integrity check
4. HMAC verify (share 2)~5µsHMAC-SHA256 integrity check
5. XorIDA reconstruct~5µsXOR-based 2-of-2 reconstruction
6. AES-256-GCM encrypt~10µsEncrypt payload with connection secret
7. Secret cleanup~0.5µsZero memory holding reconstructed secret
Total~27µsRounded to ~30µs with overhead
Comparison: Billing Overhead
Gateway relay billing adds 10-50ms per message. API metering adds 1-5ms per call. xPass Basic adds 30 microseconds — 300x to 1,600x less overhead than alternatives. The billing enforcement is essentially free from a latency perspective.
Section 06

ACI Surface

Five core operations plus two pipeline helpers. Every function returns Result<T, XpassError> and never throws.

createConnection(didA: string, didB: string, scope: string) → Result<XpassConnection, XpassError>

Establish a new billing connection between two DID-identified agents. Generates ConnectionId via SHA-256 of sorted DIDs + scope. Creates the initial 256-bit connection secret and splits via XorIDA 2-of-2. Returns connection metadata + share distribution instructions.

verifyConnection(connectionId: string, share: XpassShare) → Result<XpassVerification, XpassError>

Verify that a share is valid for the given connection and current epoch. Checks HMAC integrity, epoch expiry, connection status (active vs. suspended), and share index. Returns verification result with remaining epoch time.

revokeConnection(connectionId: string, reason: string) → Result<void, XpassError>

Permanently revoke a billing connection. All outstanding shares are invalidated immediately. Both agents receive revocation notifications. The connection transitions to REVOKED state and can only be reactivated with a new payment.

listConnections(did: string, options?: ListOptions) → Result<XpassConnection[], XpassError>

List all active, suspended, or revoked connections for a given DID. Supports filtering by scope, status, and epoch. Returns connection metadata including peer DID, scope, creation time, current epoch, and billing status.

checkBilling(connectionId: string) → Result<XpassBillingStatus, XpassError>

Check the current billing status of a connection without performing a share operation. Returns status (active, suspended, grace, revoked), next epoch boundary, days remaining in billing period, and grace period status if applicable. Sub-millisecond response.

reconstructSecret(share1: XpassShare, share2: XpassShare) → Result<Uint8Array, XpassError>

HMAC-verified reconstruction of the connection secret from two shares. Validates both shares, checks epoch match, verifies HMAC integrity. Returns the 256-bit secret only if all checks pass. Fail-closed: any verification failure returns an error.

encryptWithConnectionSecret(secret: Uint8Array, plaintext: Uint8Array) → Result<Uint8Array, XpassError>

AES-256-GCM encryption using the reconstructed connection secret. Fresh random IV per call via crypto.getRandomValues(). Returns IV + ciphertext + auth tag.

decryptWithShares(share1: XpassShare, share2: XpassShare, ciphertext: Uint8Array) → Result<Uint8Array, XpassError>

Full pipeline: validate shares, reconstruct secret, decrypt. The billing enforcement and decryption are one atomic operation. If either share is invalid, expired, or from a revoked connection, decryption fails.

Error Handling

All functions return Result<T, XpassError> and never throw. Crypto operations fail closed: if HMAC verification fails, the share is rejected and no secret is reconstructed. Billing status failures return structured error codes (BILLING_REQUIRED, CONNECTION_SUSPENDED, EPOCH_EXPIRED, SHARE_INVALID, INVALID_CONFIG) that consuming code can match against for appropriate error handling.

The INVALID_CONFIG error is returned when threshold configuration violates xPass Basic's 2-of-2 requirement. The error includes actionable guidance: "xPass Basic requires 2-of-2 split. For fault-tolerant configurations (e.g., 2-of-3), use xPass+ which supports 3-party MPC with the billing server as the third party."

Developer Experience

Fast Onboarding: 3 Acceleration Levels

From zero-click code patterns to one-click deploy buttons, xPass offers three acceleration levels that reduce setup time from ~2 minutes to as low as ~15 seconds. Each level targets a different integration context.

Level 1: Zero-Click Accept (Lazy Initialization)

For trusted partner integrations, the lazy pattern defers billing enforcement initialization until the first message send. No explicit init() call required — shares are automatically validated on first use.

Zero-click lazy billing enforcement
import { createConnectionId, splitForConnection } from '@private.me/xpass';

// No explicit initialization - billing starts on first use
const connId = await createConnectionId(didA, didB, 'billing/my-service');

// Server splits secret automatically
const { share1, share2 } = await splitForConnection(secret, connId, epoch);

// Both shares distributed - billing enforcement active
// Payment lapses → no shares → no decryption

Setup time: ~80 seconds (no configuration, enforcement happens transparently)
Best for: Internal microservices, trusted partner integrations, development/testing

Level 2: Starter Templates (Copy-Paste Ready)

For new deployments, three starter templates provide production-ready billing enforcement in minutes. Each template includes complete setup, error handling, and deployment configuration.

Node.js + TypeScript starter
// Clone and run
$ git clone https://github.com/private-me/xpass-node-starter
$ cd xpass-node-starter
$ pnpm install
$ pnpm dev

// Billing enforcement running in ~2 minutes
// Includes: Connection ID creation, secret splitting, share distribution
Vercel Edge Function starter
// POST /api/billing endpoint with zero configuration
$ git clone https://github.com/private-me/xpass-vercel-starter
$ cd xpass-vercel-starter
$ vercel deploy

// Billing API live in ~1 minute
// Auto-scaling, edge-deployed, production-ready

Setup time: ~60-120 seconds (clone, install, run)
Best for: New projects, proof-of-concepts, production deployments

Level 3: Deploy Button (One-Click Infrastructure)

For platform integrations, deploy buttons provide one-click infrastructure provisioning with xPass pre-configured. Clicking the button deploys a complete billing enforcement service with connection management and share distribution already wired up.

Deploy button (Vercel example)
<!-- Add to your README.md or integration docs -->
[![Deploy to Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fprivate-me%2Fxpass-starter)

// Deployed service includes:
// - POST /api/billing (connection creation + secret splitting)
// - Automatic share distribution via secure channels
// - Epoch rotation (24-hour default)
// - Error handling with structured error codes

Setup time: ~15 seconds (one click, zero configuration)
Best for: SaaS integrations, marketplace apps, rapid prototyping

Setup Time Comparison

Method Setup Time Steps Required Configuration Best For
Manual (Traditional) ~2 minutes 3 (install + connect + code) Manual DID setup Full control, learning
Level 1: Zero-Click ~80 seconds 0 (lazy init) Auto-accept partners Trusted integrations
Level 2: Starter Templates ~60-120 seconds 2 (clone + run) Pre-configured New projects
Level 3: Deploy Button ~15 seconds 1 (click button) Zero configuration SaaS integrations
ACCELERATION MULTIPLIER
Deploy buttons reduce setup time by 8× compared to manual initialization (15 seconds vs 2 minutes). The billing enforcement is cryptographic, not policy-based, so zero additional configuration is needed beyond deploying the service.

Getting Started: Fastest Path

The recommended onboarding path depends on your integration context:

  1. New to xPass? Start with a Deploy Button to see billing enforcement running in production in ~15 seconds. Deploy the starter template, then explore the code.
  2. Building a new service? Clone a Starter Template for your platform (Node.js, Vercel, Docker). Copy-paste ready code with best practices.
  3. Internal microservices? Use Zero-Click Accept with lazy initialization. No setup time, billing enforcement happens transparently on first message.
  4. Want full control? Follow the manual 2-minute setup flow with explicit connection creation and share distribution steps.
Fastest path: Deploy button first, explore code second
// 1. Click "Deploy to Vercel" button (~15 sec)
// 2. Service deploys with billing enforcement pre-configured
// 3. Clone the deployed repo to see the code:

$ git clone https://github.com/your-username/deployed-service
$ cd deployed-service
$ cat api/billing.ts

// You'll see the billing enforcement pattern in action:
const connId = await createConnectionId(didA, didB, scope);
const { share1, share2 } = await splitForConnection(secret, connId, epoch);

// Distribute share1 → Agent A, share2 → Agent B
// Payment lapses → server stops refreshing shares → no decryption
Section 07

Developer Experience

Progress callbacks, structured error codes, and billing enforcement patterns designed for production M2M systems.

Progress Callbacks

All long-running operations support progress callbacks. This enables responsive UI updates during connection establishment, secret splitting, and reconstruction operations.

Progress Callback Example
const result = await createConnection(didA, didB, scope, {
  onProgress: (event) => {
    switch (event.stage) {
      case 'generating_connection_id':
        console.log('Computing SHA-256 of sorted DIDs...');
        break;
      case 'creating_secret':
        console.log('Generating 256-bit connection secret...');
        break;
      case 'splitting':
        console.log(`XorIDA split: ${event.progress}%`);
        break;
      case 'distributing':
        console.log(`Distributing share ${event.shareIndex}/2`);
        break;
    }
  }
});

// Reconstruction with progress tracking
const secretResult = await reconstructSecret(share1, share2, {
  onProgress: (event) => {
    if (event.stage === 'hmac_verify') {
      console.log(`Verifying HMAC for share ${event.shareIndex}...`);
    } else if (event.stage === 'reconstructing') {
      console.log(`XorIDA reconstruction: ${event.progress}%`);
    }
  }
});

Error Code Catalog

13 error codes across 5 categories provide precise diagnostics for every failure mode. Each error includes a machine-readable code, human-readable message, and remediation guidance.

Error Code Categories
// Category 1: Connection ID Errors
CONNECTION_ID_COLLISION    // Regenerate with different nonce
CONNECTION_NOT_FOUND       // Verify connection exists before operations
CONNECTION_ALREADY_EXISTS  // Use existing connection or create with new scope

// Category 2: Secret Generation Errors
SECRET_GENERATION_FAILED   // crypto.getRandomValues() unavailable or failed
SPLIT_FAILED              // XorIDA split operation failed (invalid params)
INSUFFICIENT_SHARES       // Provide at least K shares for reconstruction

// Category 3: Configuration Errors
INVALID_CONFIG            // Threshold config violates tier constraints
                          // xPass Basic: must be 2-of-2 exactly
                          // xPass+: use for K>2 (e.g., 2-of-3 fault tolerance)

// Category 4: Epoch Management Errors
EPOCH_EXPIRED             // Request new session token with fresh epoch
EPOCH_MISMATCH            // Shares from different epochs cannot reconstruct
EPOCH_NOT_READY           // Wait for next epoch boundary (rare timing issue)

// Category 5: Cryptographic Errors
HMAC_VERIFICATION_FAILED  // Share tampered or corrupted; reject immediately
SHARE_INVALID             // Share format invalid (missing fields, bad encoding)
RECONSTRUCTION_FAILED     // XorIDA reconstruction failed (share mismatch)

Billing Gate Pattern

The recommended pattern for production systems: check billing status before expensive operations, provide clear feedback on billing issues, and handle grace periods appropriately.

Production Billing Enforcement
async function sendSecureMessage(
  didA: string,
  didB: string,
  scope: string,
  plaintext: Uint8Array
): Promise<Result<void, XpassError>> {
  // Step 1: Derive connection ID
  const connectionId = computeConnectionId(didA, didB, scope);

  // Step 2: Check billing status BEFORE crypto operations
  const billingCheck = await checkBilling(connectionId);
  if (!billingCheck.ok) {
    return err(billingCheck.error);
  }

  const status = billingCheck.value;

  // Step 3: Handle billing states with user-facing messages
  if (status.status === 'suspended') {
    return err({
      code: 'CONNECTION_SUSPENDED',
      message: 'Connection suspended due to payment failure',
      remediation: `Update payment method to reactivate. ${status.daysUntilRevocation} days remaining in grace period.`
    });
  }

  if (status.status === 'revoked') {
    return err({
      code: 'CONNECTION_REVOKED',
      message: 'Connection permanently revoked',
      remediation: 'Create a new connection with valid payment method'
    });
  }

  if (status.status === 'grace') {
    // Allow communication but warn user
    console.warn(
      `Connection in grace period. ${status.daysUntilRevocation} days until revocation.`
    );
  }

  // Step 4: Retrieve shares (these are pre-distributed during connection creation)
  const share1 = await getShareForAgent(connectionId, didA);
  const share2 = await getShareForAgent(connectionId, didB);

  if (!share1.ok || !share2.ok) {
    return err({
      code: 'SHARE_RETRIEVAL_FAILED',
      message: 'Unable to retrieve connection shares',
      remediation: 'Verify connection exists and shares were distributed'
    });
  }

  // Step 5: Reconstruct secret with progress tracking
  const secretResult = await reconstructSecret(
    share1.value,
    share2.value,
    {
      onProgress: (event) => {
        if (event.stage === 'hmac_verify' && event.shareIndex === 1) {
          console.log('Verifying share 1 HMAC...');
        }
      }
    }
  );

  if (!secretResult.ok) {
    // Detailed error handling based on code
    switch (secretResult.error.code) {
      case 'EPOCH_EXPIRED':
        return err({
          ...secretResult.error,
          remediation: 'Request new session token. Epoch rotates every 24h.'
        });
      case 'HMAC_VERIFICATION_FAILED':
        return err({
          ...secretResult.error,
          remediation: 'Share corrupted or tampered. Request fresh shares from server.'
        });
      case 'EPOCH_MISMATCH':
        return err({
          ...secretResult.error,
          remediation: 'Shares from different epochs. Both agents must use current epoch.'
        });
      default:
        return err(secretResult.error);
    }
  }

  // Step 6: Encrypt with reconstructed secret
  const ciphertext = await encryptWithConnectionSecret(
    secretResult.value,
    plaintext
  );

  if (!ciphertext.ok) {
    return err(ciphertext.error);
  }

  // Step 7: Send ciphertext to recipient
  await transmit(didB, ciphertext.value);

  return ok(void 0);
}

Error Recovery Strategies

Each error category has a specific recovery path. Production systems should implement these patterns to minimize user friction while maintaining billing integrity.

Error Recovery Decision Tree
// CONNECTION_ID_COLLISION (rare, ~1 in 2^256)
// Recovery: Add random nonce to scope, regenerate connection ID
if (error.code === 'CONNECTION_ID_COLLISION') {
  const nonce = crypto.getRandomValues(new Uint8Array(16));
  const newScope = `${scope}-${hex(nonce)}`;
  return await createConnection(didA, didB, newScope);
}

// INVALID_CONFIG (threshold violates tier constraints)
// Recovery: Use xPass+ for K>2, or adjust to 2-of-2 for xPass Basic
if (error.code === 'INVALID_CONFIG') {
  const { threshold, totalShares } = error.metadata;
  if (threshold > 2 || totalShares > 2) {
    // Upgrade path: use xPass+ for fault tolerance
    return await createConnectionWithXpassPlus(didA, didB, scope, {
      threshold,
      totalShares,
      mpcConfig: { serverParticipation: true }
    });
  }
  // Downgrade path: enforce 2-of-2 for xPass Basic
  return await createConnection(didA, didB, scope, {
    threshold: 2,
    totalShares: 2
  });
}

// EPOCH_EXPIRED (24h boundary crossed)
// Recovery: Request fresh session token from billing server
if (error.code === 'EPOCH_EXPIRED') {
  const newSession = await requestSessionToken(connectionId);
  const freshShares = await getSharesForEpoch(newSession.epoch);
  return await reconstructSecret(freshShares[0], freshShares[1]);
}

// HMAC_VERIFICATION_FAILED (tampered or corrupted share)
// Recovery: Request fresh shares, do NOT retry with same shares
if (error.code === 'HMAC_VERIFICATION_FAILED') {
  logSecurityEvent('share_integrity_failure', { connectionId });
  const freshShares = await requestFreshShares(connectionId);
  return await reconstructSecret(freshShares[0], freshShares[1]);
}

// CONNECTION_SUSPENDED (grace period, payment failure)
// Recovery: Prompt user to update payment, allow 72h grace period
if (error.code === 'CONNECTION_SUSPENDED') {
  const daysRemaining = error.metadata.daysUntilRevocation;
  await notifyUser({
    severity: 'warning',
    title: 'Payment Required',
    message: `Connection will be revoked in ${daysRemaining} days`,
    action: { label: 'Update Payment', href: '/billing' }
  });
  // Optionally allow send during grace period (business decision)
  if (daysRemaining > 0) {
    return await proceedWithWarning();
  }
}

// CONNECTION_REVOKED (permanent, payment lapsed)
// Recovery: Create new connection, no bypass possible
if (error.code === 'CONNECTION_REVOKED') {
  await notifyUser({
    severity: 'error',
    title: 'Connection Closed',
    message: 'Payment lapsed. Create new connection to resume communication.',
    action: { label: 'New Connection', href: '/connections/new' }
  });
  return err(error); // No recovery, must create new connection
}
PRODUCTION PATTERN

The billing gate pattern (check → retrieve → reconstruct → encrypt) minimizes wasted computation. Billing checks complete in under 1ms. Only proceed to expensive crypto operations after confirming the connection is active and paid.

TypeScript Integration

Full TypeScript support with discriminated unions for error types. IDE autocomplete guides developers through every error code and recovery path.

Type-Safe Error Handling
// XpassError is a discriminated union of all 13 error codes
type XpassError =
  | { code: 'CONNECTION_ID_COLLISION';    message: string; remediation: string }
  | { code: 'INVALID_CONFIG';            message: string; remediation: string; metadata: { threshold: number; totalShares: number } }
  | { code: 'EPOCH_EXPIRED';             message: string; remediation: string; metadata: { epochNumber: number } }
  | { code: 'HMAC_VERIFICATION_FAILED';  message: string; remediation: string; metadata: { shareIndex: number } }
  | { code: 'CONNECTION_SUSPENDED';      message: string; remediation: string; metadata: { daysUntilRevocation: number } }
  | /* ... 8 more error types */;

// Exhaustive pattern matching enforced by TypeScript
function handleError(error: XpassError): UserMessage {
  switch (error.code) {
    case 'EPOCH_EXPIRED':
      return {
        severity: 'info',
        title: 'Session Expired',
        message: `Epoch ${error.metadata.epochNumber} expired. Requesting new session...`
      };
    case 'CONNECTION_SUSPENDED':
      return {
        severity: 'warning',
        title: 'Payment Required',
        message: `${error.metadata.daysUntilRevocation} days until connection revoked`
      };
    // TypeScript enforces that all 12 codes are handled
    default:
      const _exhaustive: never = error;
      return _exhaustive;
  }
}
Section 07.5

Agentic Commerce (Pro Tier)

xPass Pro extends connection billing to financial transactions: AI agents autonomously purchase API access, cloud resources, and data with Ed25519-signed payment authorizations and cryptographic spending limits.

Payment Authorization

Each payment authorization is an Ed25519 signature over the transaction details: amount, recipient DID, payment method reference, and a nonce. The signature proves the agent possessed the private key at the time of authorization, creating non-repudiable proof of intent.

Payment Authorization Flow
import { authorizePayment, verifyAuthorization } from '@private.me/xpass';

// Agent authorizes payment for API subscription
const auth = await authorizePayment({
  amount: 5000,           // $50.00 in cents
  currency: 'USD',
  recipientDid: 'did:key:z6MkVendor',
  paymentMethod: 'stripe:pm_1ABC...',  // Stripe PaymentMethod ID
  nonce: crypto.getRandomValues(new Uint8Array(16)),
  agentDid: 'did:key:z6MkAgent1',
  agentKey: privateKey  // Ed25519 private key
});

// Server verifies signature before processing payment
const verified = await verifyAuthorization(auth, 'did:key:z6MkAgent1');
if (verified.ok) {
  // Signature valid, process via Stripe
  const payment = await stripe.paymentIntents.create({
    amount: auth.amount,
    currency: auth.currency,
    payment_method: auth.paymentMethod,
    metadata: { agentDid: auth.agentDid, nonce: hex(auth.nonce) }
  });
}

Financial Delegation with Spending Limits

Parent agents can delegate spending authority to child agents with cryptographic constraints: maximum amount per transaction, daily spending cap, and allowed vendor DIDs. Delegations are revocable and auditable.

Spending Delegation
import { createDelegation, enforceLimits } from '@private.me/xpass';

// Parent agent creates spending delegation
const delegation = await createDelegation({
  parentDid: 'did:key:z6MkParent',
  childDid: 'did:key:z6MkChild',
  maxPerTransaction: 10000,    // $100 per tx
  dailyLimit: 50000,           // $500 per day
  allowedVendors: [
    'did:key:z6MkVendorA',
    'did:key:z6MkVendorB'
  ],
  expiresAt: new Date('2026-12-31').getTime(),
  parentKey: parentPrivateKey
});

// Child agent attempts purchase within limits
const purchase = await authorizePayment({
  amount: 7500,  // $75 - within $100 limit
  recipientDid: 'did:key:z6MkVendorA',
  delegation: delegation,
  agentDid: 'did:key:z6MkChild',
  agentKey: childPrivateKey
});

// Server enforces limits before processing
const limitsCheck = await enforceLimits(purchase, delegation);
if (!limitsCheck.ok) {
  return err({
    code: 'DELEGATION_LIMIT_EXCEEDED',
    message: limitsCheck.error.message,
    remediation: 'Amount exceeds delegation limits'
  });
}

Stripe Integration

xPass Pro integrates directly with Stripe for payment processing. The cryptographic authorization layer ensures that every payment is explicitly approved by the agent's private key, while Stripe handles the actual card processing, fraud detection, and PCI compliance.

COMPLIANCE BENEFIT

PCI DSS Scope Reduction: The agent never handles raw card data. Payment methods are tokenized by Stripe (PaymentMethod IDs). The xPass authorization signature proves intent without touching cardholder data, reducing PCI compliance scope for the operating platform.

Section 08

Use Cases

xPass serves scenarios where M2M connections must be billed, agents require autonomous purchasing power, and compliance demands cryptographic proof of authorization.

AI Agent Subscriptions

Industry context: AI agent marketplaces where agents purchase API access to specialized models, data sources, or compute resources. Traditional API key-based billing is vulnerable to key theft and lacks non-repudiation.

Problem solved: An autonomous research agent needs to subscribe to a premium academic database API. The agent must prove it authorized the $50/month subscription without human intervention. If the agent is compromised, spending limits prevent unauthorized purchases.

Autonomous Subscription Purchase
// Research agent detects need for database access
const dbConnection = await connect('did:key:z6MkAcademicDB');
const pricing = await dbConnection.value.getPricing();  // $50/month

// Agent checks delegation: max $100/tx, $500/day
if (pricing.monthlyFee > delegation.maxPerTransaction) {
  await requestParentApproval(pricing);  // Escalate to parent agent
} else {
  // Within limits: autonomously authorize payment
  const auth = await authorizePayment({
    amount: pricing.monthlyFee,
    recipientDid: 'did:key:z6MkAcademicDB',
    delegation: delegation,
    agentDid: myDid,
    agentKey: myPrivateKey
  });

  // Vendor verifies signature + processes via Stripe
  const subscription = await dbConnection.value.subscribe(auth);
}

Compliance benefit: SOX Internal Controls — Every subscription purchase is cryptographically signed by the agent's private key. Audit logs contain Ed25519 signatures proving which agent authorized each payment, satisfying Sarbanes-Oxley internal control requirements for financial systems.

Cloud Resource Procurement

Industry context: Enterprise AI fleets that dynamically provision cloud compute and storage based on workload demands. Traditional cloud billing relies on API keys, which lack per-agent accountability and spending enforcement.

Problem solved: A distributed training agent needs to spin up 16 GPU instances for 8 hours ($320 estimated cost). The agent must prove it authorized the purchase within its $500 daily budget. If compromised, the agent cannot exceed its spending cap.

Cloud Resource Authorization
// Training agent requests GPU compute
const cloudProvider = await connect('did:key:z6MkCloudVendor');
const quote = await cloudProvider.value.quoteGPU({
  instanceType: 'a100-80gb',
  count: 16,
  hours: 8
});  // Returns $320

// Check daily spending: $180 spent today, $500 limit
const todaySpent = await getDailySpending(myDid);
if (todaySpent + quote.total > delegation.dailyLimit) {
  return err({
    code: 'DAILY_LIMIT_EXCEEDED',
    message: `Would exceed daily limit: ${todaySpent + quote.total} > ${delegation.dailyLimit}`
  });
}

// Within budget: authorize purchase
const auth = await authorizePayment({
  amount: quote.total,
  recipientDid: 'did:key:z6MkCloudVendor',
  delegation: delegation,
  metadata: { instanceType: 'a100-80gb', count: 16, hours: 8 },
  agentDid: myDid,
  agentKey: myPrivateKey
});

const instances = await cloudProvider.value.provision(auth);

Compliance benefit: FinOps Accountability — Every cloud resource purchase is tied to a specific agent DID with cryptographic proof. Finance teams can attribute costs to business units without relying on self-reported tags. Spending limits prevent runaway costs from misconfigured agents.

Data Marketplace

Industry context: AI agents purchasing datasets from data marketplaces for training or inference. Marketplace operators need to ensure every download is paid for, and buyers need proof they authorized the purchase (non-repudiation for dispute resolution).

Problem solved: A sentiment analysis agent needs to purchase a $200 financial news dataset. The marketplace must verify payment authorization cryptographically before granting access. If the agent later disputes the charge, the marketplace presents the Ed25519 signature as proof.

Dataset Purchase with Non-Repudiation
// Agent browses data marketplace
const marketplace = await connect('did:key:z6MkDataMarket');
const dataset = await marketplace.value.search({
  keywords: ['financial news', 'sentiment'],
  minRecords: 100000
});

// Dataset costs $200 - authorize purchase
const auth = await authorizePayment({
  amount: 20000,  // $200 in cents
  recipientDid: 'did:key:z6MkDataMarket',
  paymentMethod: 'stripe:pm_1XYZ...',
  metadata: { datasetId: dataset.id, license: 'commercial' },
  agentDid: myDid,
  agentKey: myPrivateKey
});

// Marketplace verifies signature before granting access
const verified = await verifyAuthorization(auth, myDid);
if (verified.ok) {
  // Process payment via Stripe
  const payment = await stripe.paymentIntents.create({
    amount: auth.amount,
    payment_method: auth.paymentMethod,
    metadata: {
      agentDid: auth.agentDid,
      signature: hex(auth.signature),  // Store for dispute resolution
      datasetId: dataset.id
    }
  });

  // Grant download access
  const downloadUrl = await marketplace.value.grantAccess(dataset.id, myDid);
}

Compliance benefit: PCI DSS + Dispute Resolution — The marketplace never touches card data (Stripe tokenization), reducing PCI scope. The Ed25519 signature provides cryptographic proof the agent authorized the purchase, eliminating chargeback fraud ("I didn't authorize this").

Fintech Automation

Industry context: Financial institutions processing payments where multiple parties must approve transactions (multi-signature workflows). Traditional approval systems rely on database flags, which lack cryptographic proof and are vulnerable to tampering.

Problem solved: A wire transfer requires approval from three roles: initiator agent, compliance agent, and treasury agent. Each approval must be cryptographically signed. The payment cannot proceed until all three signatures are verified.

Multi-Party Payment Approval
// Initiator agent proposes wire transfer
const transfer = {
  amount: 5000000,  // $50,000
  recipientDid: 'did:key:z6MkBeneficiary',
  purpose: 'Vendor payment - Invoice #12345'
};

const initiatorAuth = await authorizePayment({
  ...transfer,
  agentDid: 'did:key:z6MkInitiator',
  agentKey: initiatorKey,
  role: 'initiator'
});

// Compliance agent reviews + signs
const complianceCheck = await runAMLScreening(transfer);
const complianceAuth = await authorizePayment({
  ...transfer,
  agentDid: 'did:key:z6MkCompliance',
  agentKey: complianceKey,
  role: 'compliance',
  metadata: { amlStatus: complianceCheck.status }
});

// Treasury agent final approval
const treasuryAuth = await authorizePayment({
  ...transfer,
  agentDid: 'did:key:z6MkTreasury',
  agentKey: treasuryKey,
  role: 'treasury'
});

// Payment processor verifies all three signatures
const allSignatures = [initiatorAuth, complianceAuth, treasuryAuth];
const allValid = allSignatures.every(async (auth) => {
  const v = await verifyAuthorization(auth, auth.agentDid);
  return v.ok;
});

if (allValid) {
  // All approvals verified - execute payment
  await executeWireTransfer(transfer, allSignatures);
}

Compliance benefit: SOX + Audit Trail — Multi-party approval workflows are cryptographically enforced. Each signature is non-repudiable proof of approval. Audit logs contain all three Ed25519 signatures, satisfying SOX requirements for segregation of duties in financial controls. Tampering with approval records is cryptographically impossible.

Agentic Commerce in Practice

Four industry scenarios where xPass enables autonomous AI agents to make purchases, provision resources, and execute payments with cryptographic authorization and spending enforcement.

AI Agent Subscriptions

AUTONOMOUS PROCUREMENT

Problem: AI agents need to autonomously purchase API subscriptions (databases, models, compute), but traditional API keys lack non-repudiation. Buyers can dispute charges claiming "I didn't authorize this purchase."

xPass Solution: Research agent cryptographically signs payment authorization with Ed25519 private key. Spending limits enforced: max $100/tx, $500/day. If agent is compromised, attacker cannot exceed delegation limits.

Benefit: SOX Internal Controls satisfied — audit logs contain Ed25519 signatures proving which agent authorized each payment. Non-repudiation eliminates chargeback fraud.

Cloud Resource Procurement

ENTERPRISE AI FLEETS

Problem: Enterprise AI fleets dynamically provision cloud compute (GPUs, storage), but traditional cloud billing uses shared API keys with no per-agent accountability. Runaway costs from misconfigured agents can't be prevented.

xPass Solution: Training agent provisions 16 GPU instances ($320) only if within $500 daily budget. Daily spending tracked cryptographically: $180 spent + $320 requested = $500 . Hard cap enforced via Ed25519 delegation signature.

Benefit: FinOps Accountability — costs attributed to specific agent DIDs. Finance teams can chargeback by business unit without relying on self-reported tags. Spending limits prevent budget overruns.

Data Marketplace Purchases

NON-REPUDIATION

Problem: AI agents purchase datasets from marketplaces for training/inference. Buyers later dispute charges ("I didn't authorize this $200 purchase"). Marketplace needs cryptographic proof of authorization to win disputes.

xPass Solution: Sentiment analysis agent purchases $200 financial news dataset. Ed25519 signature stored in Stripe payment metadata. If buyer disputes charge, marketplace presents signature as cryptographic proof of authorization.

Benefit: PCI DSS compliance (Stripe tokenization reduces scope) + Dispute Resolution (Ed25519 signature eliminates "I didn't authorize this" fraud). Chargeback win rate: 100% when signature exists.

Fintech Multi-Party Approval

WIRE TRANSFER AUTOMATION

Problem: Wire transfers require approval from initiator, compliance, and treasury agents. Traditional approval systems use database flags (tamperable, no cryptographic proof). Auditors can't verify who approved what.

xPass Solution: $50,000 wire requires 3 Ed25519 signatures: initiator proposes, compliance runs AML screening + signs, treasury final approval + signs. Payment executes ONLY when all 3 signatures verify. Tampering with approval records is cryptographically impossible.

Benefit: SOX Section 404 compliance — segregation of duties cryptographically enforced. Audit trail contains 3 non-repudiable Ed25519 signatures satisfying internal control requirements. Regulators can verify approval workflow without accessing private keys.

ACI MARKETPLACE
Per-Connection ACI Billing

Each ACI connection between two agents is one billable unit. The marketplace operator never needs to trust the consuming application — billing enforcement is embedded in the encryption layer. Agents cannot communicate without an active paid connection.

Per-connection billing
M2M SUBSCRIPTION
Agent Subscription Enforcement

Enterprise agent fleets subscribe to communication channels. xPass enforces that only subscribed agents can participate. Unsubscribed agents receive shares that are mathematically useless without the paid counterpart.

Fleet-scale
IoT
Pay-Per-Connection IoT

IoT device networks where each device pair communicates through a paid channel. xPass ensures that device-to-device communication requires an active billing relationship. Compromised devices cannot bypass billing to communicate with unauthorized peers.

Device identity
ENTERPRISE
Seat Licensing Enforcement

Enterprise software licensing where each seat is a DID-identified agent. The license server issues connection shares only to paid seats. Revoking a license immediately revokes the ability to communicate — no grace period, no workaround, no cached keys.

DID-per-seat
FINANCIAL
Trading Desk Communication

Financial firms require auditable billing for every inter-desk communication channel. xPass provides cryptographic proof that billing was active for every message exchanged. HMAC-chained audit trails satisfy regulatory requirements.

Audit trail
HEALTHCARE
Provider-to-Provider Channels

HIPAA-compliant communication channels between healthcare providers. Each channel is a billed connection with HMAC-verified integrity. Connection revocation is immediate — when a provider relationship ends, the communication channel is cryptographically severed.

HIPAA-ready
Section 09

Regulatory Alignment

xPass addresses billing security, audit trail, and financial resilience requirements across multiple regulatory frameworks.

FrameworkRequirementxPass Mechanism
PCI DSS v4.0Protect billing data in transit and at rest. Requirement 3: protect stored account data.Connection secrets never stored — split into shares immediately. In-transit encryption via AES-256-GCM with per-message IV. Server discards secrets after distribution.
SOX Section 404Internal controls over financial reporting. Billing records must be tamper-evident.HMAC-chained audit trail on every connection event (creation, rotation, suspension, revocation). xProve integration provides verifiable proof of billing enforcement at every epoch.
DORA (EU)Digital Operational Resilience Act. ICT risk management for financial entities.xPass+ provides near-zero bypass window via server-mediated MPC. Epoch rotation limits exposure window. Grace period (72h default) ensures communication continuity during billing disputes.
SOC 2 Type IITrust service criteria: security, availability, confidentiality.Information-theoretic security (single share reveals zero bits). 24h epoch rotation. Connection lifecycle audit trail. Automated revocation on payment failure.
GDPR Art. 32Appropriate technical measures for data protection.Connection secrets are ephemeral (discarded after split). Shares are pseudonymous (DID-based, not PII). Revocation permanently destroys billing material. No plaintext secrets stored server-side.

Audit Trail Architecture

Every xPass operation produces an HMAC-chained audit entry. The chain is append-only: each entry includes the HMAC of the previous entry, making it tamper-evident. Auditors can verify the entire billing history for a connection without accessing the connection secrets themselves.

The audit trail records: connection creation, share distribution, epoch rotation, billing status changes, suspension, grace period entry/exit, revocation, and reactivation. Each entry includes timestamps, DID identifiers, epoch numbers, and HMAC integrity tags.

Audit Entry Structure
// Each audit entry is HMAC-chained
{
  "eventType": "EPOCH_ROTATE",
  "connectionId": "a3f8...7b2c",
  "epoch": 42,
  "timestamp": "2026-04-05T00:00:00Z",
  "didA": "did:key:z6MkAgent1",
  "didB": "did:key:z6MkAgent2",
  "scope": "xlink",
  "prevHash": "b4e2...9f1a",  // chain link
  "hmac": "c7d3...0e8b"        // integrity tag
}

Compliance Reporting

xPass generates structured compliance reports suitable for SOX auditors, PCI assessors, and financial regulators. Reports include: total connections by status (active, suspended, revoked), epoch rotation history, billing dispute timeline, grace period utilization, and connection-level activity summaries. All reports are generated from the HMAC-chained audit trail, ensuring tamper-evidence.

Section 10

Cross-ACI Patterns

xPass integrates with the private.me platform as the billing enforcement layer for M2M communication.

xPass + xLink: Billing-Gated M2M

xLink provides the agent-to-agent communication channel (Ed25519 + X25519, hybrid PQ KEM). xPass layers underneath as the billing enforcement. When Agent A sends a message to Agent B via xLink, the xPass layer transparently verifies that the connection is paid and encrypts using the connection secret. Application code calls xLink as before — xPass enforcement is invisible.

xPass + xLink Integration
import { Agent } from '@private.me/xlink';
import { withBilling } from '@private.me/xpass';

// Wrap the agent with billing enforcement
const agent = withBilling(
  await Agent.fromSeed(seed),
  { billingServer: 'https://billing.private.me' }
);

// Send as normal — xPass enforcement is transparent
const result = await agent.send(recipientDid, payload);
// If connection is not paid: err('BILLING_REQUIRED')
// If connection is active: encrypts + sends transparently

xPass + xCompute: MPC-Verified Billing

xPass+ uses xCompute for 3-party MPC session key generation. The billing server holds Share 3 and participates in the MPC protocol. This eliminates the 24h bypass window of xPass Basic — the server must be present for every session. xCompute ensures that the session key is generated correctly without any party learning the others' shares.

xPass + xGate: Rate-Limited Billing Checks

xGate provides rate limiting for billing check endpoints. Without rate limiting, a malicious agent could flood the billing server with checkBilling() calls to probe connection states or cause denial of service. xGate limits billing checks to 100 per minute per DID, with exponential backoff on repeated failures.

xPass + xProve: Verifiable Billing

xProve chains billing events into a tamper-evident audit trail. Each epoch rotation, share distribution, and connection state change generates an HMAC-SHA256 integrity tag. xProve links these tags into a verifiable chain that auditors can validate without accessing the underlying billing data or connection secrets.

xPass + xStore: Split-Stored Billing State

For high-availability billing infrastructure, xStore can split-store the billing server's state across multiple backends. If the billing server fails, a replacement can reconstruct its state from K-of-N stored shares without exposing the complete billing database to any single storage provider.

xPass + Xauditlog: Tamper-Evident Billing History

Xauditlog provides enterprise-grade append-only audit logging with HMAC-chained entries. xPass integrates with Xauditlog to create a complete, tamper-evident history of every billing event: connection creation, epoch rotation, suspension, grace period, revocation, and reactivation. The audit log is independently verifiable by third-party auditors.

Integration Architecture

Multi-ACI Billing Pipeline
// Full billing enforcement with private.me platform

// 1. xLink: establish agent-to-agent channel
const agent = await Agent.fromSeed(seed);

// 2. xPass: verify billing before communication
const billing = await xpass.checkBilling(connectionId);
if (!billing.ok || billing.value.status !== 'active') {
  throw new Error('Billing required');
}

// 3. xGate: rate-limit billing check
const allowed = await xgate.checkRate(agent.did, 'billing');

// 4. xPass: reconstruct connection secret
const secret = await xpass.reconstructSecret(share1, share2);

// 5. Encrypt and send via xLink
const encrypted = await xpass.encryptWithConnectionSecret(
  secret.value, payload
);
await agent.send(recipientDid, encrypted.value);

// 6. xProve: log to audit trail
await xprove.logEvent({
  type: 'MESSAGE_SENT',
  connectionId,
  epoch: billing.value.currentEpoch,
});

Billing Flow Diagram

Agent A Share 1 + payload reconstruct xPass Pipeline HMAC verify AES-256-GCM encrypt ciphertext Agent B Share 2 + decrypt Billing enforcement IS encryption — cannot be separated
Section 11

Security Analysis

Enforcement is information-theoretic, not computational. A single share reveals exactly zero bits about the connection secret.

Enforcement Model Comparison

ApproachLatencyBypass RiskSPOFEnforcement
Gateway Relay10-50ms/msgLowYesArchitectural
HMAC Tickets~0msHighNoBehavioral
Key Oracle~0ms + fetchMediumYesDistribution
API Metering1-5ms/callMediumYesObservational
xPass Basic~30µs/msg24h windowNoMathematical
xPass+~50-200ms/sessionNear-zeroSession startMathematical
Information-Theoretic Guarantee
XorIDA 2-of-2 splitting provides unconditional security. A single share is statistically indistinguishable from random noise regardless of the adversary's computational power. This is a proven property of the XOR-based splitting algorithm. No quantum computer, no future mathematical breakthrough, changes this guarantee.

Threat Model

ThreatMitigationStatus
Single-share exposureXorIDA information-theoretic guarantee: zero bits leakedMitigated
Both-party collusionEconomic defenses: DPoP binding, revenue sharing, DID depositsDeterred
Server compromiseServer discards secret after distribution. No past exposure.Mitigated
Epoch replayHMAC tags include epoch number. Expired shares rejected.Mitigated
Share forgeryHMAC-SHA256 integrity verification before reconstructionMitigated
Billing server DoSxGate rate limiting + grace period for legitimate agentsMitigated

Collusion Analysis

If both agents collude, they can reconstruct the secret and bypass billing for one epoch (24h). This is the fundamental trade-off of xPass Basic. Four economic defenses make collusion uneconomical:

1. DPoP binding: Shares are bound to device attestations via Demonstration of Proof-of-Possession. Transferring a share to a different device requires re-attestation through the billing server.

2. Recipient revenue sharing: Recipients earn a fraction of the connection fee for maintaining their share. Reporting a colluding peer is more profitable than participating in collusion.

3. DID registration deposits: DID registration requires a refundable deposit. Proven collusion forfeits the deposit. The deposit exceeds the cost of one year of connection fees.

4. Enterprise hub pricing: Enterprise connections are priced per-seat, not per-connection. Collusion between two agents does not reduce the enterprise's total bill, removing the financial incentive entirely.

Server Compromise

After share distribution, the server does not retain the connection secret. A compromise after distribution does not expose past messages. The server stores only connection metadata (DIDs, scope, billing status, epoch numbers) — never connection secrets or shares.

A compromised server could issue fraudulent shares or withhold shares from legitimate agents. Both attacks are detectable: agents can verify share consistency via HMAC tags, and share withholding triggers grace period notifications that alert the affected agent. Multi-server redundancy (distributing the billing role across multiple servers) eliminates single-point compromise risk.

Quantum Resistance

XorIDA splitting is unconditionally secure: its security does not depend on computational hardness assumptions. A quantum computer of any size cannot extract information from a single share because the information literally does not exist in the share. This is not post-quantum cryptography (which relies on problems believed to be quantum-hard) — it is information-theoretic security, which is provably unbreakable regardless of computational advances.

The AES-256-GCM layer used for message encryption within a connection IS computationally secure (and thus theoretically quantum-vulnerable for the 256-bit key). However, the connection secret is ephemeral (24h epoch) and split across two parties. An attacker would need to compromise both shares within a single epoch AND break AES-256 — the epoch rotation limits the window of exposure to 24 hours, making quantum attacks impractical even in a theoretical post-quantum scenario.

VERIFIABLE WITHOUT CODE EXPOSURE

Ship Proofs, Not Source

xPass generates cryptographic proofs of correct execution without exposing proprietary algorithms. Verify integrity using zero-knowledge proofs — no source code required.

XPROVE CRYPTOGRAPHIC PROOF
Download proofs:

Verify proofs online →

Use Cases

REGULATORY
FDA / SEC Submissions
Prove algorithm correctness for billing enforcement without exposing trade secrets or IP.
Zero IP Exposure
FINANCIAL
Audit Without Access
External auditors verify usage-based billing gates without accessing source code or production systems.
FINRA / SOX Compliant
DEFENSE
Classified Verification
Security clearance holders verify billing enforcement correctness without clearance for source code.
CMMC / NIST Ready
ENTERPRISE
Procurement Due Diligence
Prove security + correctness during RFP evaluation without NDA or code escrow.
No NDA Required
Section 12

Honest Limitations

Six known limitations documented transparently. Credibility requires honesty about constraints.

LimitationImpactMitigation
Both parties must be online for initial connectionCreating a new connection requires both agents to be reachable to receive their respective shares. Offline agents cannot establish new billing relationships.Share distribution is asynchronous — the server queues the share and delivers on next contact. Initial connection establishment requires server reachability, but not simultaneous presence of both agents.
No offline billing verificationOnce an epoch expires, agents must contact the billing server for new shares. Fully offline agents cannot renew their billing status.24-hour epoch provides a generous offline window. Grace period (72h default) extends this further. For air-gapped environments, extended epochs (7-30 days) are configurable.
Epoch-based, not real-time usageBilling is per-connection-per-month, not per-message or per-byte. An agent that sends 1 message pays the same as one that sends 1 million.This is by design: per-connection billing eliminates metering infrastructure, reduces latency, and simplifies the billing model. Usage-based tiers can layer on top via xGate rate limiting.
24h bypass window (Basic)xPass Basic has a 24-hour bypass window if both agents collude to cache the reconstructed secret.Upgrade to xPass+ (3-party MPC) for near-zero bypass window. Economic defenses (DPoP binding, revenue sharing, DID deposits) make collusion uneconomical.
MPC session startup latencyxPass+ adds ~50-200ms for the first operation in a billing period due to xCompute 3-party MPC overhead.Session state is cached after first operation. Subsequent operations within the same epoch complete in under 5ms. Amortized cost is negligible for connections with any volume.
Server trust for share issuanceThe billing server generates and distributes shares. A compromised server could withhold shares, denying service.Share issuance is logged with HMAC tags. Both agents can independently verify delivery. xProve audit trails provide cryptographic proof of correct issuance. Multi-server redundancy eliminates single-point dependency.

Limitation Details

On initial connection requirement: The initial connection handshake requires both agents to be reachable by the billing server for share distribution. This is fundamentally required — the server must deliver one share to each agent. However, the distribution is asynchronous: the server queues each agent's share and delivers it on next contact. Both agents do not need to be online simultaneously.

On epoch granularity: xPass bills per-connection, not per-message. This means a connection that sends 1 message per month costs the same as one that sends 1 million. For most M2M use cases, this is a feature, not a limitation: flat-rate pricing enables agents to communicate freely without cost anxiety. For use cases requiring metered billing, xGate rate counters can layer on top of xPass connections to provide usage metrics without replacing the fundamental enforcement mechanism.

On the 24h bypass window: This is the most commonly asked-about limitation. The short answer: if both agents are colluding, they already have access to the plaintext — the encryption is protecting against external observers, not the communicating parties themselves. The economic defenses (DPoP, revenue sharing, deposits, hub pricing) make sustained collusion more expensive than paying for the connection.

Section 13

Enterprise CLI

xpass-cli provides a standalone HTTP server for enterprise deployments. Port 3600. Docker-ready. Air-gapped capable.

:3600
Default port
33
Tests passing
REST
JSON API
Docker
Ready

Endpoints

xpass-cli HTTP API
// Connection management
POST   /connections              // Create new connection
GET    /connections              // List connections for a DID
GET    /connections/:id          // Get connection details
DELETE /connections/:id          // Revoke connection

// Billing operations
GET    /connections/:id/status   // Check billing status
POST   /connections/:id/rotate   // Force epoch rotation
POST   /connections/:id/suspend  // Suspend connection
POST   /connections/:id/activate // Reactivate connection

// Share operations
POST   /shares/reconstruct       // Reconstruct from two shares
POST   /encrypt                  // Encrypt with connection secret
POST   /decrypt                  // Decrypt with two shares

// Health
GET    /health                   // Server status + connection count

Docker Deployment

Docker Compose
services:
  xpass:
    image: private.me/xpass-cli:latest
    ports:
      - "3600:3600"
    environment:
      - XPASS_PORT=3600
      - XPASS_EPOCH_HOURS=24
      - XPASS_GRACE_HOURS=72
    volumes:
      - xpass-data:/data
    restart: always

Configuration

xpass-cli is configured via environment variables. All settings have sensible defaults for development. Production deployments should explicitly set epoch duration, grace period, rate limiting parameters, and threshold enforcement settings.

VariableDefaultDescription
XPASS_PORT3600HTTP server port
XPASS_THRESHOLD2Minimum shares required (K in K-of-N). Must be 2 for xPass Basic.
XPASS_TOTAL_SHARES2Total shares distributed (N in K-of-N). Must be 2 for xPass Basic. For N>2, use xPass+.
XPASS_EPOCH_HOURS24Connection secret rotation interval
XPASS_GRACE_HOURS72Grace period after payment lapse
XPASS_OVERLAP_MINUTES15Epoch overlap window for seamless rotation
XPASS_RATE_LIMIT100Max billing checks per minute per DID
XPASS_DATA_DIR/dataPersistent storage for connection metadata

Air-Gapped Operation

xpass-cli operates in air-gapped environments with no external dependencies. All cryptographic operations (XorIDA splitting, HMAC-SHA256, AES-256-GCM) use the built-in Web Crypto API. No external key management service required. Connection metadata stored locally in JSONL append-only logs.

Section 14

Why XorIDA

XorIDA provides the mathematical foundation that makes xPass possible. No other splitting algorithm offers the same combination of speed, security, and simplicity for billing enforcement.

SECURITY
Information-Theoretic

Not based on computational hardness. A single share reveals zero bits about the secret, regardless of adversary power. Quantum-proof by definition. No future mathematical breakthrough or hardware advance changes this guarantee.

PERFORMANCE
Sub-Millisecond

XorIDA operates at ~15 microseconds for 32-byte secrets. 2-11x faster than AES-256-GCM for API-sized payloads. No KEM, no handshake, no round-trips. The billing enforcement adds virtually zero latency.

ENFORCEMENT
Cannot Be Skipped

Enforcement and encryption are the same operation. You cannot skip billing verification because reconstruction IS decryption. There is no separate "billing check" step that a modified SDK could bypass.

SIMPLICITY
Two Shares, One Operation

xPass Basic needs exactly two shares and one XOR operation to reconstruct. No key exchange protocols, no certificate chains, no complex handshakes. The simplicity reduces attack surface and makes the system auditable.

Why Not Just AES?
AES-256 is computationally secure: breakable with enough compute (in theory). If you distribute an AES key, the recipient can cache it forever. XorIDA shares are information-theoretically useless individually. A single share contains literally zero information about the connection secret. You cannot cache what does not exist. This is why XorIDA enables billing enforcement that AES cannot.
VERIFIED BY XPROVE

Verifiable Billing Integrity

Every operation in this ACI produces a verifiable audit trail via xProve. HMAC-chained integrity proofs let auditors confirm that connection secrets were split, distributed, and rotated correctly — without accessing the secrets themselves.

XPROVE AUDIT TRAIL
Every connection secret epoch generates HMAC-SHA256 integrity tags. xProve chains these into a tamper-evident audit trail that proves billing enforcement was active for every message. Upgrade to zero-knowledge proofs when regulators or counterparties need public verification.

Read the xProve white paper →
Section 15

Integration Example

Full lifecycle: create connection, distribute shares, encrypt, decrypt, rotate, and revoke.

Complete xPass Lifecycle
import {
  createConnection,
  verifyConnection,
  revokeConnection,
  listConnections,
  checkBilling,
  reconstructSecret,
  encryptWithConnectionSecret,
  decryptWithShares,
} from '@private.me/xpass';

// 1. Create a billing connection
const conn = await createConnection(
  'did:key:z6MkAgentA',
  'did:key:z6MkAgentB',
  'xlink'
);
if (!conn.ok) throw new Error(conn.error);

// 2. Distribute shares (server sends one to each agent)
const { share1, share2, connectionId } = conn.value;

// 3. Agent A encrypts a message
const secret = await reconstructSecret(share1, share2);
if (!secret.ok) throw new Error(secret.error);
const encrypted = await encryptWithConnectionSecret(
  secret.value,
  new TextEncoder().encode('Hello, Agent B')
);

// 4. Agent B decrypts (full pipeline)
const decrypted = await decryptWithShares(
  share1, share2, encrypted.value
);

// 5. Check billing status
const status = await checkBilling(connectionId);
console.log(status.value);
// { status: 'active', epochRemaining: '23h 14m', ... }

// 6. List all connections for an agent
const connections = await listConnections(
  'did:key:z6MkAgentA'
);

// 7. Revoke when billing ends
await revokeConnection(connectionId, 'subscription_cancelled');

Pricing

All private.me platform services follow a simple tier-based subscription model. Free trial: 3 months with full access to all features — no credit card required.

BASIC
$5/month
Perfect for developers and small teams
  • Unlimited connections
  • Core billing enforcement
  • 24h epochs (renewable)
  • Community support
  • SDK access
Start Free Trial
RECOMMENDED
ENTERPRISE
$15/month
For organizations at scale
  • Everything in Basic, plus:
  • Enterprise CLI & governance
  • Audit logs & compliance
  • On-premise deployment
  • Dedicated support
  • Custom SLAs
Start Free Trial
Try it free for 3 months
Start Free Trial →
Questions? Contact sales
GET STARTED

Ready to deploy xPass?

Start with a 3-month free trial (all tiers included). Talk to Sol, our AI platform engineer, or subscribe now.

Start Free Trial → Book a Demo

Deployment Options

SaaS Recommended

Fully managed infrastructure. Call our REST API, we handle scaling, updates, and operations.

  • Zero infrastructure setup
  • Automatic updates
  • 99.9% uptime SLA
  • Pay per use
View Pricing →

SDK Integration

Embed directly in your application. Runs in your codebase with full programmatic control.

  • npm install @private.me/xpass
  • TypeScript/JavaScript SDK
  • Full source access
  • Enterprise support available
Get Started →

On-Premise Enterprise

Self-hosted infrastructure for air-gapped, compliance, or data residency requirements.

  • Complete data sovereignty
  • Air-gap capable
  • Docker + Kubernetes ready
  • RBAC + audit logs included
Enterprise CLI →