aipp-node 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/middleware.ts CHANGED
@@ -1,159 +1,159 @@
1
- import crypto from 'crypto';
2
- import { Aipp } from './client';
3
- import { signJwt, verifyJwt } from './jwt';
4
-
5
- export interface L402Options {
6
- client: Aipp;
7
- jwtSecret: string;
8
- resourceId: string;
9
- amountSats?: number;
10
- amountUsd?: number;
11
- expiresInSeconds?: number;
12
- }
13
-
14
- export function l402Paywall(options: L402Options) {
15
- if (!options.amountSats && !options.amountUsd) {
16
- throw new Error('Either amountSats or amountUsd must be provided for l402Paywall');
17
- }
18
-
19
- return async (req: any, res: any, next: any) => {
20
- const authHeader = req.headers.authorization || req.headers.Authorization;
21
- let valid = false;
22
-
23
- if (authHeader && typeof authHeader === 'string' && authHeader.startsWith('L402 ')) {
24
- const parts = authHeader.substring(5).split(':');
25
- if (parts.length === 2) {
26
- const [macaroonStr, preimage] = parts;
27
- try {
28
- // Verify JWT signature and expiration
29
- const payload = verifyJwt(macaroonStr, options.jwtSecret);
30
-
31
- if (payload.resource_id !== options.resourceId) {
32
- throw new Error('Invalid resource');
33
- }
34
-
35
- // Verify preimage hash matches payment_hash securely
36
- const preimageHash = crypto.createHash('sha256').update(Buffer.from(preimage, 'hex')).digest('hex');
37
- const expectedHash = payload.payment_hash;
38
-
39
- if (
40
- typeof expectedHash === 'string' &&
41
- expectedHash.length === preimageHash.length &&
42
- crypto.timingSafeEqual(Buffer.from(preimageHash, 'hex'), Buffer.from(expectedHash, 'hex'))
43
- ) {
44
- valid = true;
45
- }
46
- } catch (e) {
47
- // Invalid or expired JWT -> Fall through to 402 and issue new invoice
48
- }
49
- }
50
- }
51
-
52
- if (valid) {
53
- return next();
54
- }
55
-
56
- try {
57
- // Create invoice via AIPP
58
- const charge = await options.client.createCharge({
59
- amountSats: options.amountSats,
60
- amountUsd: options.amountUsd,
61
- memo: `L402 Payment for ${options.resourceId}`
62
- });
63
-
64
- // Issue JWT
65
- const expiresIn = options.expiresInSeconds || 3600; // default 1 hour
66
- const payload = {
67
- payment_hash: charge.payment_hash,
68
- resource_id: options.resourceId,
69
- exp: Math.floor(Date.now() / 1000) + expiresIn
70
- };
71
-
72
- const jwtToken = signJwt(payload, options.jwtSecret);
73
-
74
- res.status(402);
75
- res.setHeader('Www-Authenticate', `L402 macaroon="${jwtToken}" invoice="${charge.payment_request}"`);
76
- res.json({
77
- error: "Payment Required",
78
- code: "L402",
79
- payment_request: charge.payment_request,
80
- macaroon: jwtToken
81
- });
82
- } catch (err: any) {
83
- res.status(500).json({ error: "Failed to generate L402 challenge", details: err.message || err });
84
- }
85
- };
86
- }
87
-
88
- export interface X402Options {
89
- client: Aipp;
90
- resourceId: string;
91
- amountUsd: number;
92
- }
93
-
94
- export function x402Paywall(options: X402Options) {
95
- return async (req: any, res: any, next: any) => {
96
- const authHeader = req.headers.authorization || req.headers.Authorization;
97
- let txHash = (req.query.tx_hash || req.headers['payment-signature'] || req.headers['x-payment-signature']) as string;
98
- let paymentHash = (req.query.payment_hash || req.headers['x-payment-hash']) as string;
99
-
100
- if (!txHash && authHeader && typeof authHeader === 'string') {
101
- if (authHeader.startsWith('Bearer ')) {
102
- txHash = authHeader.substring(7).trim();
103
- } else if (authHeader.startsWith('x402 ')) {
104
- txHash = authHeader.substring(5).trim();
105
- } else if (authHeader.startsWith('L402 ')) {
106
- // Fallback or double format check
107
- const parts = authHeader.substring(5).split(':');
108
- if (parts.length === 2) {
109
- paymentHash = parts[0];
110
- txHash = parts[1];
111
- }
112
- }
113
- }
114
-
115
- if (paymentHash && txHash) {
116
- try {
117
- const chargeStatus = await options.client.getCharge(paymentHash, txHash);
118
- if (chargeStatus.status === 'settled') {
119
- return next();
120
- }
121
- } catch (e) {
122
- // Validation failed, proceed to challenge
123
- }
124
- }
125
-
126
- try {
127
- const charge = await options.client.createCharge({
128
- amountUsd: options.amountUsd,
129
- protocol: 'x402',
130
- memo: `x402 Payment for ${options.resourceId}`
131
- });
132
-
133
- const challengeObj = {
134
- scheme: 'exact',
135
- network: 'base',
136
- payTo: charge.pay_to || '',
137
- price: options.amountUsd.toFixed(2),
138
- token: charge.token || '',
139
- payment_hash: charge.payment_hash
140
- };
141
-
142
- const challengeBase64 = Buffer.from(JSON.stringify(challengeObj), 'utf8').toString('base64');
143
- res.setHeader('PAYMENT-REQUIRED', challengeBase64);
144
-
145
- res.status(402);
146
- res.json({
147
- error: "Payment Required",
148
- code: "x402",
149
- payment_hash: charge.payment_hash,
150
- pay_to: challengeObj.payTo,
151
- price: challengeObj.price,
152
- token: challengeObj.token,
153
- network: challengeObj.network
154
- });
155
- } catch (err: any) {
156
- res.status(500).json({ error: "Failed to generate x402 challenge", details: err.message || err });
157
- }
158
- };
159
- }
1
+ import crypto from 'crypto';
2
+ import { Aipp } from './client';
3
+ import { signJwt, verifyJwt } from './jwt';
4
+
5
+ export interface L402Options {
6
+ client: Aipp;
7
+ jwtSecret: string;
8
+ resourceId: string;
9
+ amountSats?: number;
10
+ amountUsd?: number;
11
+ expiresInSeconds?: number;
12
+ }
13
+
14
+ export function l402Paywall(options: L402Options) {
15
+ if (!options.amountSats && !options.amountUsd) {
16
+ throw new Error('Either amountSats or amountUsd must be provided for l402Paywall');
17
+ }
18
+
19
+ return async (req: any, res: any, next: any) => {
20
+ const authHeader = req.headers.authorization || req.headers.Authorization;
21
+ let valid = false;
22
+
23
+ if (authHeader && typeof authHeader === 'string' && authHeader.startsWith('L402 ')) {
24
+ const parts = authHeader.substring(5).split(':');
25
+ if (parts.length === 2) {
26
+ const [macaroonStr, preimage] = parts;
27
+ try {
28
+ // Verify JWT signature and expiration
29
+ const payload = verifyJwt(macaroonStr, options.jwtSecret);
30
+
31
+ if (payload.resource_id !== options.resourceId) {
32
+ throw new Error('Invalid resource');
33
+ }
34
+
35
+ // Verify preimage hash matches payment_hash securely
36
+ const preimageHash = crypto.createHash('sha256').update(Buffer.from(preimage, 'hex')).digest('hex');
37
+ const expectedHash = payload.payment_hash;
38
+
39
+ if (
40
+ typeof expectedHash === 'string' &&
41
+ expectedHash.length === preimageHash.length &&
42
+ crypto.timingSafeEqual(Buffer.from(preimageHash, 'hex'), Buffer.from(expectedHash, 'hex'))
43
+ ) {
44
+ valid = true;
45
+ }
46
+ } catch (e) {
47
+ // Invalid or expired JWT -> Fall through to 402 and issue new invoice
48
+ }
49
+ }
50
+ }
51
+
52
+ if (valid) {
53
+ return next();
54
+ }
55
+
56
+ try {
57
+ // Create invoice via AIPP
58
+ const charge = await options.client.createCharge({
59
+ amountSats: options.amountSats,
60
+ amountUsd: options.amountUsd,
61
+ memo: `L402 Payment for ${options.resourceId}`
62
+ });
63
+
64
+ // Issue JWT
65
+ const expiresIn = options.expiresInSeconds || 3600; // default 1 hour
66
+ const payload = {
67
+ payment_hash: charge.payment_hash,
68
+ resource_id: options.resourceId,
69
+ exp: Math.floor(Date.now() / 1000) + expiresIn
70
+ };
71
+
72
+ const jwtToken = signJwt(payload, options.jwtSecret);
73
+
74
+ res.status(402);
75
+ res.setHeader('Www-Authenticate', `L402 macaroon="${jwtToken}" invoice="${charge.payment_request}"`);
76
+ res.json({
77
+ error: "Payment Required",
78
+ code: "L402",
79
+ payment_request: charge.payment_request,
80
+ macaroon: jwtToken
81
+ });
82
+ } catch (err: any) {
83
+ res.status(500).json({ error: "Failed to generate L402 challenge", details: err.message || err });
84
+ }
85
+ };
86
+ }
87
+
88
+ export interface X402Options {
89
+ client: Aipp;
90
+ resourceId: string;
91
+ amountUsd: number;
92
+ }
93
+
94
+ export function x402Paywall(options: X402Options) {
95
+ return async (req: any, res: any, next: any) => {
96
+ const authHeader = req.headers.authorization || req.headers.Authorization;
97
+ let txHash = (req.query.tx_hash || req.headers['payment-signature'] || req.headers['x-payment-signature']) as string;
98
+ let paymentHash = (req.query.payment_hash || req.headers['x-payment-hash']) as string;
99
+
100
+ if (!txHash && authHeader && typeof authHeader === 'string') {
101
+ if (authHeader.startsWith('Bearer ')) {
102
+ txHash = authHeader.substring(7).trim();
103
+ } else if (authHeader.startsWith('x402 ')) {
104
+ txHash = authHeader.substring(5).trim();
105
+ } else if (authHeader.startsWith('L402 ')) {
106
+ // Fallback or double format check
107
+ const parts = authHeader.substring(5).split(':');
108
+ if (parts.length === 2) {
109
+ paymentHash = parts[0];
110
+ txHash = parts[1];
111
+ }
112
+ }
113
+ }
114
+
115
+ if (paymentHash && txHash) {
116
+ try {
117
+ const chargeStatus = await options.client.getCharge(paymentHash, txHash);
118
+ if (chargeStatus.status === 'settled') {
119
+ return next();
120
+ }
121
+ } catch (e) {
122
+ // Validation failed, proceed to challenge
123
+ }
124
+ }
125
+
126
+ try {
127
+ const charge = await options.client.createCharge({
128
+ amountUsd: options.amountUsd,
129
+ protocol: 'x402',
130
+ memo: `x402 Payment for ${options.resourceId}`
131
+ });
132
+
133
+ const challengeObj = {
134
+ scheme: 'exact',
135
+ network: 'base',
136
+ payTo: charge.pay_to || '',
137
+ price: options.amountUsd.toFixed(2),
138
+ token: charge.token || '',
139
+ payment_hash: charge.payment_hash
140
+ };
141
+
142
+ const challengeBase64 = Buffer.from(JSON.stringify(challengeObj), 'utf8').toString('base64');
143
+ res.setHeader('PAYMENT-REQUIRED', challengeBase64);
144
+
145
+ res.status(402);
146
+ res.json({
147
+ error: "Payment Required",
148
+ code: "x402",
149
+ payment_hash: charge.payment_hash,
150
+ pay_to: challengeObj.payTo,
151
+ price: challengeObj.price,
152
+ token: challengeObj.token,
153
+ network: challengeObj.network
154
+ });
155
+ } catch (err: any) {
156
+ res.status(500).json({ error: "Failed to generate x402 challenge", details: err.message || err });
157
+ }
158
+ };
159
+ }
package/src/types.ts CHANGED
@@ -1,39 +1,86 @@
1
- export interface AippConfig {
2
- apiKey: string;
3
- baseUrl?: string;
4
- }
5
-
6
- export interface ChargeParams {
7
- amountSats?: number;
8
- amountUsd?: number;
9
- memo?: string;
10
- protocol?: 'L402' | 'x402';
11
- }
12
-
13
- export interface ChargeResponse {
14
- payment_hash: string;
15
- protocol: 'L402' | 'x402';
16
- amount_usd?: number;
17
- pay_to?: string;
18
- network?: string;
19
- token?: string;
20
- payment_request?: string; // For L402
21
- amount_sats?: number; // For L402
22
- }
23
-
24
- export interface ChargeStatus {
25
- paid: boolean;
26
- status: 'pending' | 'settled';
27
- preimage: string | null;
28
- }
29
-
30
- export interface AippErrorResponse {
31
- error: string;
32
- code?: string;
33
- }
34
-
35
- export interface PayoutResponse {
36
- message: string;
37
- amount_sats?: number;
38
- amount_usd?: number;
39
- }
1
+ export interface AippConfig {
2
+ apiKey: string;
3
+ baseUrl?: string;
4
+ }
5
+
6
+ export interface ChargeParams {
7
+ amountSats?: number;
8
+ amountUsd?: number;
9
+ memo?: string;
10
+ protocol?: 'L402' | 'x402';
11
+ }
12
+
13
+ export interface ChargeResponse {
14
+ payment_hash: string;
15
+ protocol: 'L402' | 'x402';
16
+ amount_usd?: number;
17
+ pay_to?: string;
18
+ network?: string;
19
+ token?: string;
20
+ payment_request?: string; // For L402
21
+ amount_sats?: number; // For L402
22
+ }
23
+
24
+ export interface ChargeStatus {
25
+ paid: boolean;
26
+ status: 'pending' | 'settled';
27
+ preimage: string | null;
28
+ }
29
+
30
+ export interface AippErrorResponse {
31
+ error: string;
32
+ code?: string;
33
+ }
34
+
35
+ export interface PayoutResponse {
36
+ message: string;
37
+ amount_sats?: number;
38
+ amount_usd?: number;
39
+ }
40
+
41
+ export interface ReceiptCompliance {
42
+ regulation: string;
43
+ note: string;
44
+ }
45
+
46
+ export interface ReceiptFinancials {
47
+ currency: string;
48
+ total_amount: number;
49
+ merchant_amount: number;
50
+ platform_fee: number;
51
+ }
52
+
53
+ export interface ReceiptPaymentDetails {
54
+ protocol: string;
55
+ proof: string | null;
56
+ merchant_destination: string | null;
57
+ }
58
+
59
+ /** EU AI Act Article 26 compliant receipt for a settled invoice */
60
+ export interface ReceiptResponse {
61
+ receipt_id: string;
62
+ transaction_id: string;
63
+ date: string;
64
+ status: string;
65
+ compliance: ReceiptCompliance;
66
+ payment_details: ReceiptPaymentDetails;
67
+ financials: ReceiptFinancials;
68
+ }
69
+
70
+ export interface MarketplaceTool {
71
+ name: string;
72
+ description: string;
73
+ priceUsdt: number;
74
+ }
75
+
76
+ /** PaidMCP.dev compatible manifest for listing on AI agent marketplaces */
77
+ export interface MarketplaceManifest {
78
+ id: string;
79
+ name: string;
80
+ tagline: string;
81
+ description: string;
82
+ endpoint: string;
83
+ chains: string[];
84
+ tools: MarketplaceTool[];
85
+ tags: string[];
86
+ }
package/tsconfig.json CHANGED
@@ -1,14 +1,14 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es2022",
4
- "module": "esnext",
5
- "moduleResolution": "node",
6
- "strict": true,
7
- "esModuleInterop": true,
8
- "skipLibCheck": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "declaration": true,
11
- "outDir": "dist"
12
- },
13
- "include": ["src"]
14
- }
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022",
4
+ "module": "esnext",
5
+ "moduleResolution": "node",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "skipLibCheck": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "declaration": true,
11
+ "outDir": "dist"
12
+ },
13
+ "include": ["src"]
14
+ }
package/dist/index.d.mts DELETED
@@ -1,71 +0,0 @@
1
- interface AippConfig {
2
- apiKey: string;
3
- baseUrl?: string;
4
- }
5
- interface ChargeParams {
6
- amountSats?: number;
7
- amountUsd?: number;
8
- memo?: string;
9
- protocol?: 'L402' | 'x402';
10
- }
11
- interface ChargeResponse {
12
- payment_hash: string;
13
- protocol: 'L402' | 'x402';
14
- amount_usd?: number;
15
- pay_to?: string;
16
- network?: string;
17
- token?: string;
18
- payment_request?: string;
19
- amount_sats?: number;
20
- }
21
- interface ChargeStatus {
22
- paid: boolean;
23
- status: 'pending' | 'settled';
24
- preimage: string | null;
25
- }
26
- interface AippErrorResponse {
27
- error: string;
28
- code?: string;
29
- }
30
- interface PayoutResponse {
31
- message: string;
32
- amount_sats?: number;
33
- amount_usd?: number;
34
- }
35
-
36
- declare class Aipp {
37
- private apiKey;
38
- private baseUrl;
39
- constructor(config: AippConfig);
40
- private request;
41
- /**
42
- * Creates a new Invoice (either L402 or x402)
43
- */
44
- createCharge(params: ChargeParams): Promise<ChargeResponse>;
45
- /**
46
- * Checks the status of an existing charge
47
- */
48
- getCharge(paymentHash: string, txHash?: string): Promise<ChargeStatus>;
49
- /**
50
- * Triggers a manual withdrawal of your merchant balance
51
- */
52
- payout(): Promise<PayoutResponse>;
53
- }
54
-
55
- interface L402Options {
56
- client: Aipp;
57
- jwtSecret: string;
58
- resourceId: string;
59
- amountSats?: number;
60
- amountUsd?: number;
61
- expiresInSeconds?: number;
62
- }
63
- declare function l402Paywall(options: L402Options): (req: any, res: any, next: any) => Promise<any>;
64
- interface X402Options {
65
- client: Aipp;
66
- resourceId: string;
67
- amountUsd: number;
68
- }
69
- declare function x402Paywall(options: X402Options): (req: any, res: any, next: any) => Promise<any>;
70
-
71
- export { Aipp, type AippConfig, type AippErrorResponse, type ChargeParams, type ChargeResponse, type ChargeStatus, type L402Options, type PayoutResponse, type X402Options, l402Paywall, x402Paywall };