AP2 Library - Agent Payments Protocol
npm install ap2-lib





> TypeScript/Deno implementation of the Agent Payments Protocol (AP2) - The open, universal protocol backed by Google and 60+ organizations for autonomous commerce.
---
The Agent Payments Protocol (AP2) enables AI agents to make secure, autonomous purchases on behalf of users. This library provides the core cryptographic primitives, mandate management, and validation logic needed to implement AP2-compliant payment systems.
- ๐ JWT/JOSE Security - Industry-standard JWT signatures with RS256/ES256 algorithms
- ๐ Strong TypeScript Typing - Complete type safety for all AP2 structures
- ๐๏ธ SOLID Architecture - Clean OOP design with class-based API
- โ
High Test Coverage - Comprehensive validation and error handling (91.0%+)
- ๐ Universal Compatibility - Works in Deno, Node.js, and browsers
- ๐ Advanced Validation - Multi-layered mandate integrity checking
---
``bash`
deno add @xja77/ap2-lib
`bash`
npm install ap2-lib
`typescript`
import { IntentMandateClass, CartMandateClass } from "https://deno.land/x/ap2_lib/mod.ts";
---
`mermaid
graph TB
User[๐ค User Intent] --> Agent[๐ค AI Agent]
Agent --> IntentMandate[๐ Intent Mandate]
IntentMandate --> Shopping[๐๏ธ Shopping Process]
Shopping --> CartMandate[๐ Cart Mandate]
CartMandate --> JWT[๐ JWT Signature]
JWT --> Payment[๐ณ Secure Payment]
Payment --> Verification[โ
JWT Verification]
style IntentMandate fill:#e1f5fe
style CartMandate fill:#f3e5f5
style JWT fill:#e8f5e8
style Payment fill:#fff3e0
`
`mermaid
graph LR
A[ap2-lib] --> B[Types]
A --> C[Core]
A --> D[Utils]
B --> B1[Mandates]
B --> B2[Payment Request]
B --> B3[Contact Picker]
C --> C1[Mandates]
C --> C2[JWT/Crypto]
C --> C3[Validation]
C1 --> C1a[Intent]
C1 --> C1b[Cart]
C1 --> C1c[Payment]
C1 --> C1d[Shared]
D --> D1[Errors]
D --> D2[Date Utils]
`
---
`typescript
import { IntentMandateClass } from "@xja77/ap2-lib";
// Create a user's purchase intent
const intent = await IntentMandateClass.createNew({
natural_language_description: "Wireless noise-canceling headphones under $200",
intent_expiry: "2024-12-31T23:59:59Z",
user_cart_confirmation_required: false,
merchants: ["amazon.com", "bestbuy.com"],
requires_refundability: true
});
console.log(intent.toString());
// Output: "Intent Mandate (ID: abc123...)"
console.log(intent.getData());
// Output: Complete intent mandate data structure
// Check if intent is expired
const isExpired = await intent.checkExpiry();
console.log(Intent expired: ${isExpired});`
`typescript
import { CartMandateClass } from "@xja77/ap2-lib";
// Define cart contents
const cartContents = {
id: "cart-12345",
merchant_name: "TechStore",
cart_expiry: "2024-12-31T23:59:59Z",
payment_request: {
id: "payment-67890",
methodData: [{ supportedMethods: "basic-card" }],
details: {
total: {
label: "Sony WH-1000XM4",
amount: { currency: "USD", value: "299.99" },
refund_period: 30
}
}
},
user_cart_confirmation_required: false
};
// Create cart mandate
const cartMandate = await CartMandateClass.createNew({
contents: cartContents
});
// Sign with JWT
await cartMandate.sign(
"-----BEGIN RSA PRIVATE KEY-----\n...", // Your RSA private key in PEM format
{ algorithm: "RS256", keyId: "key-1" },
{ merchantId: "merchant-123" }
);
// Verify the JWT signature
const isValid = await cartMandate.verifySignature();
console.log(Cart mandate JWT signature valid: ${isValid});
console.log(cartMandate.getStatus()); // "authorized"
`
`typescript
import { CartMandateValidator } from "@xja77/ap2-lib";
// Direct validation using class methods (recommended)
await cartMandate.validate(); // Throws if invalid
// Or use validator directly
const validator = new CartMandateValidator();
// Validate cart mandate structure
const validationResult = await validator.validate(cartMandate.getData());
if (!validationResult.isValid) {
console.error("Validation errors:", validationResult.errors);
}
// Check mandate integrity
const integrityResult = await validator.validateIntegrity(cartMandate.getData());
if (!integrityResult.isValid) {
console.error("Integrity check failed:", integrityResult.errors);
}
// Check expiry using class method
const isExpired = await cartMandate.checkExpiry();
console.log(Mandate expired: ${isExpired});`
---
| Type | Purpose | Signature Required | Methods Available |
|------|---------|-------------------|------------------|
| Intent | User's purchase intent in natural language | โ No | .validate(), .checkExpiry(), .toString() |.sign()
| Cart | Specific cart contents with pricing | โ
Yes (JWT) | , .verifySignature(), .validate(), .checkExpiry() |.sign()
| Payment | Payment method and transaction details | โ
Yes (JWT) | , .verifySignature(), .validate() |
`mermaid`
stateDiagram-v2
[*] --> Pending
Pending --> Authorized: validate()
Authorized --> Captured: execute_payment()
Authorized --> Failed: payment_error()
Captured --> Refunded: process_refund()
Pending --> Cancelled: user_cancel()
Failed --> [*]
Refunded --> [*]
Cancelled --> [*]
---
AP2-lib uses industry-standard JWT/JOSE signatures for cart mandate authentication:
`typescript
import { jwtService } from "@xja77/ap2-lib";
// Sign cart contents with JWT
const payload = {
iss: "merchant-123",
sub: "merchant-123",
aud: "payment-processor",
cart_hash: await jwtService.computeCartHash(cartContents),
};
const keyConfig = {
privateKey: "-----BEGIN RSA PRIVATE KEY-----\n...",
publicKey: "-----BEGIN RSA PUBLIC KEY-----\n...",
algorithm: "RS256" as const, // or "ES256"
};
const jwt = await jwtService.signMerchantAuthorization(payload, {
keyConfig,
expiresIn: 900 // 15 minutes
});
// Verify JWT signature
const result = await jwtService.verifyMerchantAuthorization(jwt, {
keyConfig,
audience: "payment-processor",
issuer: "merchant-123"
});
console.log(JWT valid: ${result.valid});`
1. Schema Validation - TypeScript interfaces and runtime checks
2. Business Logic Validation - AP2 protocol compliance
3. Cryptographic Validation - Signature verification and integrity
4. Temporal Validation - Expiry and timing checks
---
Run the comprehensive test suite:
`bashRun all tests
deno task test
$3
- Total Tests: 260+ passing
- Line Coverage: 91.0%+
- Branch Coverage: 89.9%+
- Files: 54+ TypeScript modules
---
๐ API Documentation
$3
๐ Browse Complete API Documentation โ$3
`bash
Generate HTML documentation
deno task docView documentation in terminal
deno doc ./src/mod.ts
`$3
`typescript
// Mandate Classes (OOP API)
export class IntentMandateClass extends BaseMandate {
static createNew(params: CreateIntentMandateParams): Promise
validate(): Promise
checkExpiry(currentDate?: Date): Promise
toString(): string
getData(): IntentMandate
getStatus(): MandateStatus
}export class CartMandateClass extends BaseMandate {
static createNew(params: CreateCartMandateParams): Promise
sign(privateKey: string, keyConfig: Partial, merchantInfo: { merchantId: string }): Promise
verifySignature(): Promise
validate(): Promise
checkExpiry(currentDate?: Date): Promise
}
// Validation Classes
export class IntentMandateValidator {
validate(mandate: IntentMandate): Promise
validateIntegrity(mandate: IntentMandate): Promise
checkExpiry(mandate: IntentMandate, currentDate?: Date): Promise
}
// JWT Service
export class JWTService implements IJWTService {
signMerchantAuthorization(payload: MerchantAuthorizationPayload, options: JWTSignOptions): Promise
verifyMerchantAuthorization(jwt: string, options: JWTVerifyOptions): Promise
computeCartHash(cartContents: unknown): Promise
generateJTI(): string
}
`---
๐ ๏ธ Development
$3
`bash
deno task dev # Watch mode development
deno task test # Run test suite
deno task coverage # Generate coverage report
deno task build # Build for npm distribution
deno task publish # Publish to JSR and npm
`$3
`
src/
โโโ core/ # Core AP2 implementations
โ โโโ mandates/ # Mandate management (Intent, Cart, Payment)
โ โโโ jwt/ # JWT/JWS cryptographic services
โ โโโ config/ # Validation configuration
โ โโโ utils/ # Internal utilities
โโโ types/ # TypeScript type definitions
โ โโโ mandates.ts # Mandate interfaces
โ โโโ payment_request.ts # W3C Payment Request types
โ โโโ contact_picker.ts # Contact picker types
โโโ utils/ # Public utility functions
โโโ errors.ts # Error definitions
โโโ date.ts # Date/time utilities
`$3
- Factory Pattern - Mandate creation (
IntentMandateClass.createNew(), CartMandateClass.createNew())
- Strategy Pattern - Validation strategies per mandate type
- Template Method - Base mandate class with common functionality
- Command Pattern - Validation and serialization operations
- Interface Segregation - Focused JWT service interfaces---
๐ค Contributing
1. Fork the repository
2. Create a feature branch:
git checkout -b feature/amazing-feature
3. Make your changes following SOLID principles
4. Ensure 100% test coverage: deno task test`- Follow TypeScript strict mode
- Use descriptive variable and function names
- Write comprehensive JSDoc comments
- Maintain SOLID design principles
- Achieve 100% test coverage for new features
---
---
This project is licensed under the MIT License - see the LICENSE file for details.
---
- Google and the AP2 Working Group for the protocol specification
- 60+ Organizations supporting the AP2 standard
- Deno Team for the excellent runtime and tooling
- Web Standards Community for Payment Request API and Web Crypto API
---
Documentation โข API Reference โข Examples โข Contributing
Made with โค๏ธ for the autonomous commerce future