@mixrpay/merchant-sdk 0.3.2 → 0.3.5

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/dist/index.d.mts CHANGED
@@ -77,6 +77,68 @@ interface SessionGrant {
77
77
  */
78
78
  declare function verifySessionWebhook(payload: string, signature: string, secret: string): boolean;
79
79
 
80
+ /**
81
+ * MixrPay Merchant SDK - Utilities
82
+ */
83
+
84
+ /**
85
+ * Get the MixrPay widget script URL.
86
+ *
87
+ * @example
88
+ * ```html
89
+ * <script src="${getWidgetUrl()}"
90
+ * data-seller-public-key="pk_live_..."
91
+ * data-user-token="..."></script>
92
+ * ```
93
+ */
94
+ declare function getWidgetUrl(): string;
95
+ /**
96
+ * MixrPay API base URL
97
+ */
98
+ declare const MIXRPAY_API_URL = "https://www.mixrpay.com";
99
+ /**
100
+ * Widget script URL (for convenience)
101
+ */
102
+ declare const WIDGET_SCRIPT_URL = "https://www.mixrpay.com/widget.js";
103
+ /**
104
+ * Convert USD dollars to USDC minor units (6 decimals)
105
+ */
106
+ declare function usdToMinor(usd: number): bigint;
107
+ /**
108
+ * Convert USDC minor units to USD dollars
109
+ */
110
+ declare function minorToUsd(minor: bigint): number;
111
+ interface EnvValidationResult {
112
+ valid: boolean;
113
+ errors: string[];
114
+ warnings: string[];
115
+ config: {
116
+ publicKey: string | null;
117
+ secretKey: string | null;
118
+ hmacSecret: string | null;
119
+ webhookSecret: string | null;
120
+ merchantAddress: string | null;
121
+ };
122
+ }
123
+ /**
124
+ * Validate MixrPay environment variables and provide helpful feedback.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * import { validateEnv } from '@mixrpay/merchant-sdk';
129
+ *
130
+ * const result = validateEnv();
131
+ * if (!result.valid) {
132
+ * console.error('MixrPay configuration errors:', result.errors);
133
+ * }
134
+ * ```
135
+ */
136
+ declare function validateEnv(env?: Record<string, string | undefined>): EnvValidationResult;
137
+ /**
138
+ * Log environment validation results to console with formatting.
139
+ */
140
+ declare function logEnvValidation(result?: EnvValidationResult): void;
141
+
80
142
  /**
81
143
  * MixrPay Widget Custom Element Type Declarations
82
144
  *
@@ -149,6 +211,43 @@ interface MixrState {
149
211
  // Global API Types
150
212
  // =============================================================================
151
213
 
214
+ /**
215
+ * Session state object returned by window.Mixr.getSessionState()
216
+ */
217
+ interface MixrSessionState {
218
+ /** Whether user has an active session */
219
+ hasSession: boolean;
220
+ /** Current session ID */
221
+ sessionId: string | null;
222
+ /** Remaining spending limit in USD */
223
+ remainingUsd: number;
224
+ /** Total spending limit in USD */
225
+ spendingLimitUsd: number;
226
+ /** Session expiration date */
227
+ expiresAt: Date | null;
228
+ /** Session status */
229
+ status: 'active' | 'expired' | 'revoked' | null;
230
+ /** Session type */
231
+ type: 'session_key' | 'authorization' | null;
232
+ }
233
+
234
+ /**
235
+ * Diagnostic result from Mixr.diagnose()
236
+ */
237
+ interface MixrDiagnosticResult {
238
+ config: {
239
+ hasPublicKey: boolean;
240
+ hasUserToken: boolean;
241
+ hasWidgetToken: boolean;
242
+ mode: 'wallet_auth' | 'domain_verified' | 'hmac';
243
+ };
244
+ state: MixrState;
245
+ session: MixrSessionState;
246
+ issues: string[];
247
+ warnings: string[];
248
+ isLocalhost: boolean;
249
+ }
250
+
152
251
  /**
153
252
  * MixrPay global API available on window.Mixr
154
253
  */
@@ -165,6 +264,12 @@ interface MixrAPI {
165
264
  /** Get current widget state */
166
265
  getState(): MixrState;
167
266
 
267
+ /** Get current session state */
268
+ getSessionState(): MixrSessionState;
269
+
270
+ /** Fetch fresh session state from server */
271
+ getSession(): Promise<MixrSessionState>;
272
+
168
273
  /** Refresh user balance and state */
169
274
  refresh(): Promise<void>;
170
275
 
@@ -175,6 +280,69 @@ interface MixrAPI {
175
280
  * @param element - The element that triggered the charge (for UI feedback)
176
281
  */
177
282
  charge(feature: string, priceUsd: string, element: HTMLElement): Promise<void>;
283
+
284
+ /** Check if user is authenticated */
285
+ isAuthenticated(): boolean;
286
+
287
+ /** Get user's wallet address */
288
+ getWalletAddress(): string | null;
289
+
290
+ /** Check if user can afford a given amount */
291
+ canAfford(amountUsd: number): boolean;
292
+
293
+ /** Check if widget is ready for transactions */
294
+ isReady(minBalance?: number): boolean;
295
+
296
+ /** Get detailed readiness status */
297
+ getReadinessStatus(minBalance?: number): {
298
+ ready: boolean;
299
+ issues: string[];
300
+ balanceUsd: number;
301
+ sessionId: string | null;
302
+ sessionRemaining: number;
303
+ };
304
+
305
+ /** Trigger wallet connection (for wallet-auth mode) */
306
+ connect(): void;
307
+
308
+ /** Disconnect and clear local session */
309
+ disconnect(): void;
310
+
311
+ /** Prompt user to authorize a spending session */
312
+ authorizeSession(spendingLimitUsd?: number, durationDays?: number): Promise<boolean>;
313
+
314
+ /** Check if wallet is non-custodial */
315
+ isNonCustodial(): boolean;
316
+
317
+ /** Get current theme */
318
+ getTheme(): 'dark' | 'light';
319
+
320
+ /** Set theme */
321
+ setTheme(theme: 'dark' | 'light' | 'auto'): void;
322
+
323
+ /**
324
+ * Configure widget callbacks
325
+ */
326
+ setConfig(config: {
327
+ onSessionChange?: (session: MixrSessionState) => void;
328
+ onStateChange?: (state: MixrState) => void;
329
+ defaultSessionLimit?: number;
330
+ defaultSessionDuration?: number;
331
+ }): void;
332
+
333
+ /**
334
+ * Diagnostic tool for debugging widget issues.
335
+ * Call Mixr.diagnose() in browser console to see widget status.
336
+ */
337
+ diagnose(): MixrDiagnosticResult;
338
+
339
+ /** Enable debug mode for verbose logging */
340
+ enableDebug(): void;
341
+
342
+ /**
343
+ * Make an authenticated fetch request with MixrPay headers
344
+ */
345
+ fetch(url: string, options?: RequestInit & { autoPrompt?: boolean }): Promise<Response>;
178
346
  }
179
347
 
180
348
  // =============================================================================
@@ -286,4 +454,4 @@ declare global {
286
454
  }
287
455
  }
288
456
 
289
- export { PaymentReceipt, type SessionGrant, verifyPaymentReceipt, verifySessionWebhook };
457
+ export { type EnvValidationResult, MIXRPAY_API_URL, PaymentReceipt, type SessionGrant, WIDGET_SCRIPT_URL, getWidgetUrl, logEnvValidation, minorToUsd, usdToMinor, validateEnv, verifyPaymentReceipt, verifySessionWebhook };
package/dist/index.d.ts CHANGED
@@ -77,6 +77,68 @@ interface SessionGrant {
77
77
  */
78
78
  declare function verifySessionWebhook(payload: string, signature: string, secret: string): boolean;
79
79
 
80
+ /**
81
+ * MixrPay Merchant SDK - Utilities
82
+ */
83
+
84
+ /**
85
+ * Get the MixrPay widget script URL.
86
+ *
87
+ * @example
88
+ * ```html
89
+ * <script src="${getWidgetUrl()}"
90
+ * data-seller-public-key="pk_live_..."
91
+ * data-user-token="..."></script>
92
+ * ```
93
+ */
94
+ declare function getWidgetUrl(): string;
95
+ /**
96
+ * MixrPay API base URL
97
+ */
98
+ declare const MIXRPAY_API_URL = "https://www.mixrpay.com";
99
+ /**
100
+ * Widget script URL (for convenience)
101
+ */
102
+ declare const WIDGET_SCRIPT_URL = "https://www.mixrpay.com/widget.js";
103
+ /**
104
+ * Convert USD dollars to USDC minor units (6 decimals)
105
+ */
106
+ declare function usdToMinor(usd: number): bigint;
107
+ /**
108
+ * Convert USDC minor units to USD dollars
109
+ */
110
+ declare function minorToUsd(minor: bigint): number;
111
+ interface EnvValidationResult {
112
+ valid: boolean;
113
+ errors: string[];
114
+ warnings: string[];
115
+ config: {
116
+ publicKey: string | null;
117
+ secretKey: string | null;
118
+ hmacSecret: string | null;
119
+ webhookSecret: string | null;
120
+ merchantAddress: string | null;
121
+ };
122
+ }
123
+ /**
124
+ * Validate MixrPay environment variables and provide helpful feedback.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * import { validateEnv } from '@mixrpay/merchant-sdk';
129
+ *
130
+ * const result = validateEnv();
131
+ * if (!result.valid) {
132
+ * console.error('MixrPay configuration errors:', result.errors);
133
+ * }
134
+ * ```
135
+ */
136
+ declare function validateEnv(env?: Record<string, string | undefined>): EnvValidationResult;
137
+ /**
138
+ * Log environment validation results to console with formatting.
139
+ */
140
+ declare function logEnvValidation(result?: EnvValidationResult): void;
141
+
80
142
  /**
81
143
  * MixrPay Widget Custom Element Type Declarations
82
144
  *
@@ -149,6 +211,43 @@ interface MixrState {
149
211
  // Global API Types
150
212
  // =============================================================================
151
213
 
214
+ /**
215
+ * Session state object returned by window.Mixr.getSessionState()
216
+ */
217
+ interface MixrSessionState {
218
+ /** Whether user has an active session */
219
+ hasSession: boolean;
220
+ /** Current session ID */
221
+ sessionId: string | null;
222
+ /** Remaining spending limit in USD */
223
+ remainingUsd: number;
224
+ /** Total spending limit in USD */
225
+ spendingLimitUsd: number;
226
+ /** Session expiration date */
227
+ expiresAt: Date | null;
228
+ /** Session status */
229
+ status: 'active' | 'expired' | 'revoked' | null;
230
+ /** Session type */
231
+ type: 'session_key' | 'authorization' | null;
232
+ }
233
+
234
+ /**
235
+ * Diagnostic result from Mixr.diagnose()
236
+ */
237
+ interface MixrDiagnosticResult {
238
+ config: {
239
+ hasPublicKey: boolean;
240
+ hasUserToken: boolean;
241
+ hasWidgetToken: boolean;
242
+ mode: 'wallet_auth' | 'domain_verified' | 'hmac';
243
+ };
244
+ state: MixrState;
245
+ session: MixrSessionState;
246
+ issues: string[];
247
+ warnings: string[];
248
+ isLocalhost: boolean;
249
+ }
250
+
152
251
  /**
153
252
  * MixrPay global API available on window.Mixr
154
253
  */
@@ -165,6 +264,12 @@ interface MixrAPI {
165
264
  /** Get current widget state */
166
265
  getState(): MixrState;
167
266
 
267
+ /** Get current session state */
268
+ getSessionState(): MixrSessionState;
269
+
270
+ /** Fetch fresh session state from server */
271
+ getSession(): Promise<MixrSessionState>;
272
+
168
273
  /** Refresh user balance and state */
169
274
  refresh(): Promise<void>;
170
275
 
@@ -175,6 +280,69 @@ interface MixrAPI {
175
280
  * @param element - The element that triggered the charge (for UI feedback)
176
281
  */
177
282
  charge(feature: string, priceUsd: string, element: HTMLElement): Promise<void>;
283
+
284
+ /** Check if user is authenticated */
285
+ isAuthenticated(): boolean;
286
+
287
+ /** Get user's wallet address */
288
+ getWalletAddress(): string | null;
289
+
290
+ /** Check if user can afford a given amount */
291
+ canAfford(amountUsd: number): boolean;
292
+
293
+ /** Check if widget is ready for transactions */
294
+ isReady(minBalance?: number): boolean;
295
+
296
+ /** Get detailed readiness status */
297
+ getReadinessStatus(minBalance?: number): {
298
+ ready: boolean;
299
+ issues: string[];
300
+ balanceUsd: number;
301
+ sessionId: string | null;
302
+ sessionRemaining: number;
303
+ };
304
+
305
+ /** Trigger wallet connection (for wallet-auth mode) */
306
+ connect(): void;
307
+
308
+ /** Disconnect and clear local session */
309
+ disconnect(): void;
310
+
311
+ /** Prompt user to authorize a spending session */
312
+ authorizeSession(spendingLimitUsd?: number, durationDays?: number): Promise<boolean>;
313
+
314
+ /** Check if wallet is non-custodial */
315
+ isNonCustodial(): boolean;
316
+
317
+ /** Get current theme */
318
+ getTheme(): 'dark' | 'light';
319
+
320
+ /** Set theme */
321
+ setTheme(theme: 'dark' | 'light' | 'auto'): void;
322
+
323
+ /**
324
+ * Configure widget callbacks
325
+ */
326
+ setConfig(config: {
327
+ onSessionChange?: (session: MixrSessionState) => void;
328
+ onStateChange?: (state: MixrState) => void;
329
+ defaultSessionLimit?: number;
330
+ defaultSessionDuration?: number;
331
+ }): void;
332
+
333
+ /**
334
+ * Diagnostic tool for debugging widget issues.
335
+ * Call Mixr.diagnose() in browser console to see widget status.
336
+ */
337
+ diagnose(): MixrDiagnosticResult;
338
+
339
+ /** Enable debug mode for verbose logging */
340
+ enableDebug(): void;
341
+
342
+ /**
343
+ * Make an authenticated fetch request with MixrPay headers
344
+ */
345
+ fetch(url: string, options?: RequestInit & { autoPrompt?: boolean }): Promise<Response>;
178
346
  }
179
347
 
180
348
  // =============================================================================
@@ -286,4 +454,4 @@ declare global {
286
454
  }
287
455
  }
288
456
 
289
- export { PaymentReceipt, type SessionGrant, verifyPaymentReceipt, verifySessionWebhook };
457
+ export { type EnvValidationResult, MIXRPAY_API_URL, PaymentReceipt, type SessionGrant, WIDGET_SCRIPT_URL, getWidgetUrl, logEnvValidation, minorToUsd, usdToMinor, validateEnv, verifyPaymentReceipt, verifySessionWebhook };
package/dist/index.js CHANGED
@@ -30,6 +30,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
+ MIXRPAY_API_URL: () => MIXRPAY_API_URL,
34
+ WIDGET_SCRIPT_URL: () => WIDGET_SCRIPT_URL,
35
+ getWidgetUrl: () => getWidgetUrl,
36
+ logEnvValidation: () => logEnvValidation,
37
+ minorToUsd: () => minorToUsd,
38
+ usdToMinor: () => usdToMinor,
39
+ validateEnv: () => validateEnv,
33
40
  verifyPaymentReceipt: () => verifyPaymentReceipt,
34
41
  verifySessionWebhook: () => verifySessionWebhook
35
42
  });
@@ -113,8 +120,102 @@ function verifySessionWebhook(payload, signature, secret) {
113
120
  Buffer.from(expectedSignature)
114
121
  );
115
122
  }
123
+
124
+ // src/utils.ts
125
+ function getWidgetUrl() {
126
+ return "https://www.mixrpay.com/widget.js";
127
+ }
128
+ var MIXRPAY_API_URL = "https://www.mixrpay.com";
129
+ var WIDGET_SCRIPT_URL = "https://www.mixrpay.com/widget.js";
130
+ function usdToMinor(usd) {
131
+ return BigInt(Math.round(usd * 1e6));
132
+ }
133
+ function minorToUsd(minor) {
134
+ return Number(minor) / 1e6;
135
+ }
136
+ function isValidAddress(address) {
137
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
138
+ }
139
+ function validateEnv(env) {
140
+ const e = env || (typeof process !== "undefined" ? process.env : {});
141
+ const result = {
142
+ valid: true,
143
+ errors: [],
144
+ warnings: [],
145
+ config: {
146
+ publicKey: e.MIXRPAY_PUBLIC_KEY || null,
147
+ secretKey: e.MIXRPAY_SECRET_KEY || null,
148
+ hmacSecret: e.MIXRPAY_HMAC_SECRET || null,
149
+ webhookSecret: e.MIXRPAY_WEBHOOK_SECRET || null,
150
+ merchantAddress: e.MIXRPAY_MERCHANT_ADDRESS || null
151
+ }
152
+ };
153
+ if (!result.config.publicKey) {
154
+ result.errors.push("MIXRPAY_PUBLIC_KEY is required. Get it from https://www.mixrpay.com/seller/developers");
155
+ result.valid = false;
156
+ } else if (!result.config.publicKey.startsWith("pk_")) {
157
+ result.errors.push(`MIXRPAY_PUBLIC_KEY must start with 'pk_'. Got: ${result.config.publicKey.slice(0, 10)}...`);
158
+ result.valid = false;
159
+ }
160
+ if (!result.config.secretKey) {
161
+ result.errors.push("MIXRPAY_SECRET_KEY is required. Get it from https://www.mixrpay.com/seller/developers");
162
+ result.valid = false;
163
+ } else if (!result.config.secretKey.startsWith("sk_")) {
164
+ result.errors.push(`MIXRPAY_SECRET_KEY must start with 'sk_'. Got: ${result.config.secretKey.slice(0, 10)}...`);
165
+ result.valid = false;
166
+ }
167
+ if (!result.config.webhookSecret) {
168
+ result.errors.push("MIXRPAY_WEBHOOK_SECRET is required. Get it from https://www.mixrpay.com/seller/developers");
169
+ result.valid = false;
170
+ }
171
+ if (!result.config.hmacSecret) {
172
+ result.warnings.push("MIXRPAY_HMAC_SECRET not set. Only required if using Widget with user linking (data-user-token).");
173
+ }
174
+ if (!result.config.merchantAddress) {
175
+ result.warnings.push("MIXRPAY_MERCHANT_ADDRESS not set. Required for x402 protocol support.");
176
+ } else if (!isValidAddress(result.config.merchantAddress)) {
177
+ result.errors.push(`MIXRPAY_MERCHANT_ADDRESS is not a valid Ethereum address: ${result.config.merchantAddress}`);
178
+ result.valid = false;
179
+ }
180
+ return result;
181
+ }
182
+ function logEnvValidation(result) {
183
+ const r = result || validateEnv();
184
+ console.log("\n\u{1F527} MixrPay Environment Check\n");
185
+ if (r.valid) {
186
+ console.log("\u2705 Configuration valid\n");
187
+ } else {
188
+ console.log("\u274C Configuration errors found\n");
189
+ }
190
+ if (r.errors.length > 0) {
191
+ console.log("Errors:");
192
+ r.errors.forEach((e) => console.log(` \u274C ${e}`));
193
+ console.log("");
194
+ }
195
+ if (r.warnings.length > 0) {
196
+ console.log("Warnings:");
197
+ r.warnings.forEach((w) => console.log(` \u26A0\uFE0F ${w}`));
198
+ console.log("");
199
+ }
200
+ console.log("Required credentials:");
201
+ console.log(` Public Key: ${r.config.publicKey ? "\u2713 Set" : "\u2717 Missing"}`);
202
+ console.log(` Secret Key: ${r.config.secretKey ? "\u2713 Set" : "\u2717 Missing"}`);
203
+ console.log(` Webhook Secret: ${r.config.webhookSecret ? "\u2713 Set" : "\u2717 Missing"}`);
204
+ console.log("");
205
+ console.log("Optional credentials:");
206
+ console.log(` HMAC Secret: ${r.config.hmacSecret ? "\u2713 Set" : "\u25CB Not set (widget only)"}`);
207
+ console.log(` Merchant Address: ${r.config.merchantAddress ? "\u2713 Set" : "\u25CB Not set (x402 only)"}`);
208
+ console.log("");
209
+ }
116
210
  // Annotate the CommonJS export names for ESM import in node:
117
211
  0 && (module.exports = {
212
+ MIXRPAY_API_URL,
213
+ WIDGET_SCRIPT_URL,
214
+ getWidgetUrl,
215
+ logEnvValidation,
216
+ minorToUsd,
217
+ usdToMinor,
218
+ validateEnv,
118
219
  verifyPaymentReceipt,
119
220
  verifySessionWebhook
120
221
  });
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/receipt.ts","../src/charges.ts"],"sourcesContent":["/**\n * MixrPay Merchant SDK\n * \n * Accept payments from AI agents and web apps with one middleware.\n * \n * @example Express\n * ```typescript\n * import { mixrpay } from '@mixrpay/merchant-sdk/express';\n * \n * app.post('/api/query', mixrpay({ priceUsd: 0.05 }), (req, res) => {\n * console.log(`Paid by ${req.mixrPayment?.payer}`);\n * res.json({ result: 'success' });\n * });\n * ```\n * \n * @example Next.js\n * ```typescript\n * import { withMixrPay } from '@mixrpay/merchant-sdk/nextjs';\n * \n * export const POST = withMixrPay({ priceUsd: 0.05 }, async (req, payment) => {\n * return NextResponse.json({ result: 'success' });\n * });\n * ```\n * \n * @packageDocumentation\n */\n\n// Receipt verification (for custom integrations)\nexport { verifyPaymentReceipt } from './receipt';\n\n// Session webhook verification\nexport { verifySessionWebhook } from './charges';\n\n// Types for TypeScript users\nexport type {\n MixrPayOptions,\n MixrPayPaymentResult,\n PaymentMethod,\n PriceContext,\n PaymentReceipt,\n} from './types';\n\nexport type {\n SessionGrant,\n} from './charges';\n\n// Widget element types (for TypeScript JSX support)\nexport type {} from './widget-elements';\n","/**\n * MixrPay Merchant SDK - Payment Receipt Verification\n * \n * Verify JWT payment receipts issued by MixrPay after successful x402 payments.\n * \n * @example\n * ```typescript\n * import { verifyPaymentReceipt } from '@mixrpay/merchant-sdk';\n * \n * const receipt = req.headers['x-payment-receipt'];\n * const payment = await verifyPaymentReceipt(receipt);\n * \n * console.log(`Payment received: $${payment.amountUsd} from ${payment.payer}`);\n * console.log(`Transaction: ${payment.txHash}`);\n * ```\n */\n\nimport * as jose from 'jose';\nimport type { PaymentReceipt, VerifyReceiptOptions } from './types';\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_JWKS_URL = process.env.MIXRPAY_JWKS_URL || 'https://www.mixrpay.com/.well-known/jwks';\nconst JWKS_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour\n\n// =============================================================================\n// JWKS Cache\n// =============================================================================\n\ninterface CachedJWKS {\n jwks: jose.JSONWebKeySet;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, CachedJWKS>();\n\n/**\n * Fetch and cache JWKS from the specified URL.\n */\nasync function getJWKS(jwksUrl: string): Promise<jose.JSONWebKeySet> {\n const cached = jwksCache.get(jwksUrl);\n const now = Date.now();\n\n // Return cached JWKS if still valid\n if (cached && (now - cached.fetchedAt) < JWKS_CACHE_TTL_MS) {\n return cached.jwks;\n }\n\n // Fetch fresh JWKS\n const response = await fetch(jwksUrl);\n \n if (!response.ok) {\n throw new Error(`Failed to fetch JWKS from ${jwksUrl}: ${response.status} ${response.statusText}`);\n }\n\n const jwks = await response.json() as jose.JSONWebKeySet;\n\n // Validate JWKS structure\n if (!jwks.keys || !Array.isArray(jwks.keys) || jwks.keys.length === 0) {\n throw new Error('Invalid JWKS: missing or empty keys array');\n }\n\n // Cache the JWKS\n jwksCache.set(jwksUrl, { jwks, fetchedAt: now });\n\n return jwks;\n}\n\n/**\n * Create a JWKS key set from a fetched JWKS.\n */\nasync function createKeySet(jwksUrl: string): Promise<jose.JWTVerifyGetKey> {\n const jwks = await getJWKS(jwksUrl);\n return jose.createLocalJWKSet(jwks);\n}\n\n// =============================================================================\n// Receipt Verification\n// =============================================================================\n\n/**\n * Verify a JWT payment receipt from MixrPay.\n * \n * This function:\n * 1. Fetches the JWKS from MixrPay (cached for 1 hour)\n * 2. Verifies the JWT signature using RS256\n * 3. Validates standard JWT claims (exp, iat)\n * 4. Returns the typed payment receipt\n * \n * @param receipt - The JWT receipt string from X-Payment-Receipt header\n * @param options - Optional configuration (custom JWKS URL, issuer validation)\n * @returns Verified payment receipt\n * @throws Error if verification fails\n * \n * @example\n * ```typescript\n * // Basic usage\n * const payment = await verifyPaymentReceipt(receipt);\n * \n * // With custom JWKS URL (for testing or self-hosted)\n * const payment = await verifyPaymentReceipt(receipt, {\n * jwksUrl: 'https://your-mixrpay.com/.well-known/jwks'\n * });\n * ```\n */\nexport async function verifyPaymentReceipt(\n receipt: string,\n options?: VerifyReceiptOptions\n): Promise<PaymentReceipt> {\n const jwksUrl = options?.jwksUrl || DEFAULT_JWKS_URL;\n\n try {\n // Get the key set\n const keySet = await createKeySet(jwksUrl);\n\n // Build verification options\n const verifyOptions: jose.JWTVerifyOptions = {\n algorithms: ['RS256'],\n };\n\n // Add issuer validation if specified\n if (options?.issuer) {\n verifyOptions.issuer = options.issuer;\n }\n\n // Verify the JWT\n const { payload } = await jose.jwtVerify(receipt, keySet, verifyOptions);\n\n // Validate required payment fields\n const requiredFields = ['paymentId', 'amount', 'amountUsd', 'payer', 'recipient', 'chainId', 'txHash', 'settledAt'];\n for (const field of requiredFields) {\n if (!(field in payload)) {\n throw new Error(`Missing required field in receipt: ${field}`);\n }\n }\n\n // Return typed receipt\n return {\n paymentId: payload.paymentId as string,\n amount: payload.amount as string,\n amountUsd: payload.amountUsd as number,\n payer: payload.payer as string,\n recipient: payload.recipient as string,\n chainId: payload.chainId as number,\n txHash: payload.txHash as string,\n settledAt: payload.settledAt as string,\n issuedAt: new Date((payload.iat as number) * 1000),\n expiresAt: new Date((payload.exp as number) * 1000),\n };\n } catch (error) {\n if (error instanceof jose.errors.JWTExpired) {\n throw new Error('Payment receipt has expired');\n }\n if (error instanceof jose.errors.JWTClaimValidationFailed) {\n throw new Error(`Receipt validation failed: ${error.message}`);\n }\n if (error instanceof jose.errors.JWSSignatureVerificationFailed) {\n throw new Error('Invalid receipt signature');\n }\n throw error;\n }\n}\n\n/**\n * Parse a JWT payment receipt without verification.\n * \n * WARNING: This does NOT verify the signature. Use only for debugging\n * or when you've already verified the receipt elsewhere.\n * \n * @param receipt - The JWT receipt string\n * @returns Decoded payload (unverified)\n */\nexport function parsePaymentReceipt(receipt: string): PaymentReceipt {\n const decoded = jose.decodeJwt(receipt);\n\n return {\n paymentId: decoded.paymentId as string,\n amount: decoded.amount as string,\n amountUsd: decoded.amountUsd as number,\n payer: decoded.payer as string,\n recipient: decoded.recipient as string,\n chainId: decoded.chainId as number,\n txHash: decoded.txHash as string,\n settledAt: decoded.settledAt as string,\n issuedAt: decoded.iat ? new Date(decoded.iat * 1000) : undefined,\n expiresAt: decoded.exp ? new Date(decoded.exp * 1000) : undefined,\n };\n}\n\n/**\n * Check if a receipt is expired.\n * \n * @param receipt - The JWT receipt string or parsed PaymentReceipt\n * @returns true if expired, false otherwise\n */\nexport function isReceiptExpired(receipt: string | PaymentReceipt): boolean {\n const parsed = typeof receipt === 'string' ? parsePaymentReceipt(receipt) : receipt;\n \n if (!parsed.expiresAt) {\n return false; // No expiration = never expires\n }\n\n return parsed.expiresAt.getTime() < Date.now();\n}\n\n/**\n * Clear the JWKS cache.\n * Useful for testing or when keys have rotated.\n */\nexport function clearJWKSCache(): void {\n jwksCache.clear();\n}\n\n/**\n * Get the default JWKS URL.\n */\nexport function getDefaultJWKSUrl(): string {\n return DEFAULT_JWKS_URL;\n}\n\n","/**\n * MixrPay Charges Module\n * \n * Create and manage charges using session signers.\n * Session signers allow you to charge user wallets without\n * requiring approval for each transaction.\n */\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface CreateChargeParams {\n /** Session key ID granted by the user */\n sessionId: string;\n /** Amount to charge in USD (e.g., 0.05 for 5 cents) */\n amountUsd: number;\n /** Unique reference for idempotency (e.g., \"order_123\") */\n reference: string;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n}\n\nexport interface Charge {\n /** Unique charge ID */\n id: string;\n /** Current status */\n status: 'pending' | 'submitted' | 'confirmed' | 'failed';\n /** Amount in USD */\n amountUsd: number;\n /** Formatted USDC amount */\n amountUsdc: string;\n /** Transaction hash (if submitted) */\n txHash?: string;\n /** Block explorer URL */\n explorerUrl?: string;\n /** From wallet address */\n fromAddress: string;\n /** To wallet address */\n toAddress: string;\n /** Your reference */\n reference: string;\n /** When the charge was created */\n createdAt: string;\n /** When the charge was confirmed */\n confirmedAt?: string;\n /** Session name */\n sessionName?: string;\n /** User wallet address */\n userWallet?: string;\n /** Error message if failed */\n error?: string;\n}\n\nexport interface CreateChargeResult {\n success: boolean;\n charge?: Charge;\n /** True if this is a replay of an existing charge */\n idempotentReplay?: boolean;\n error?: string;\n details?: string;\n}\n\nexport interface SessionGrant {\n /** Session key ID */\n sessionId: string;\n /** User's wallet address */\n userWallet: string;\n /** Your merchant wallet address */\n merchantWallet: string;\n /** Spending limits */\n limits: {\n maxTotalUsd?: number;\n maxPerTxUsd?: number;\n expiresAt: string;\n };\n /** When the session was granted */\n grantedAt: string;\n}\n\n// Internal types for API responses\ninterface CreateChargeApiResponse {\n success: boolean;\n charge_id?: string;\n status?: string;\n amount_usd?: number;\n amount_usdc?: string;\n tx_hash?: string;\n explorer_url?: string;\n idempotent_replay?: boolean;\n error?: string;\n details?: string;\n}\n\ninterface ChargeApiResponse {\n id: string;\n status: string;\n amount_usd: number;\n amount_usdc: string;\n tx_hash?: string;\n explorer_url?: string;\n from_address: string;\n to_address: string;\n reference: string;\n created_at: string;\n confirmed_at?: string;\n session_name?: string;\n user_wallet?: string;\n}\n\nexport interface ChargesClientOptions {\n /** Your API key */\n apiKey: string;\n /** MixrPay API base URL */\n baseUrl?: string;\n}\n\n// =============================================================================\n// Client\n// =============================================================================\n\nexport class ChargesClient {\n private apiKey: string;\n private baseUrl: string;\n\n constructor(options: ChargesClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl || process.env.MIXRPAY_BASE_URL || 'https://www.mixrpay.com';\n }\n\n /**\n * Create a new charge.\n * \n * @example\n * ```typescript\n * const result = await charges.create({\n * sessionId: 'sk_xxx',\n * amountUsd: 0.05,\n * reference: 'image_gen_123',\n * metadata: { feature: 'image_generation' }\n * });\n * \n * if (result.success) {\n * console.log(`Charged ${result.charge.amountUsdc}`);\n * console.log(`TX: ${result.charge.explorerUrl}`);\n * }\n * ```\n */\n async create(params: CreateChargeParams): Promise<CreateChargeResult> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n session_id: params.sessionId,\n amount_usd: params.amountUsd,\n reference: params.reference,\n metadata: params.metadata,\n }),\n });\n\n const data = await response.json() as CreateChargeApiResponse;\n\n if (!response.ok) {\n return {\n success: false,\n error: data.error,\n details: data.details,\n };\n }\n\n return {\n success: data.success,\n charge: data.charge_id ? {\n id: data.charge_id,\n status: data.status as Charge['status'],\n amountUsd: data.amount_usd ?? 0,\n amountUsdc: data.amount_usdc ?? '0',\n txHash: data.tx_hash,\n explorerUrl: data.explorer_url,\n fromAddress: '',\n toAddress: '',\n reference: params.reference,\n createdAt: new Date().toISOString(),\n } : undefined,\n idempotentReplay: data.idempotent_replay,\n error: data.error,\n };\n }\n\n /**\n * Get a charge by ID.\n * \n * @example\n * ```typescript\n * const charge = await charges.get('chg_xxx');\n * console.log(charge.status); // 'confirmed'\n * ```\n */\n async get(chargeId: string): Promise<Charge | null> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges?id=${chargeId}`, {\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new Error(`Failed to get charge: ${response.statusText}`);\n }\n\n const data = await response.json() as ChargeApiResponse;\n\n return {\n id: data.id,\n status: data.status as Charge['status'],\n amountUsd: data.amount_usd,\n amountUsdc: data.amount_usdc,\n txHash: data.tx_hash,\n explorerUrl: data.explorer_url,\n fromAddress: data.from_address,\n toAddress: data.to_address,\n reference: data.reference,\n createdAt: data.created_at,\n confirmedAt: data.confirmed_at,\n sessionName: data.session_name,\n userWallet: data.user_wallet,\n };\n }\n\n /**\n * Get a charge by transaction hash.\n */\n async getByTxHash(txHash: string): Promise<Charge | null> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges?tx_hash=${txHash}`, {\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new Error(`Failed to get charge: ${response.statusText}`);\n }\n\n const data = await response.json() as ChargeApiResponse;\n\n return {\n id: data.id,\n status: data.status as Charge['status'],\n amountUsd: data.amount_usd,\n amountUsdc: data.amount_usdc,\n txHash: data.tx_hash,\n explorerUrl: data.explorer_url,\n fromAddress: data.from_address,\n toAddress: data.to_address,\n reference: data.reference,\n createdAt: data.created_at,\n confirmedAt: data.confirmed_at,\n sessionName: data.session_name,\n userWallet: data.user_wallet,\n };\n }\n}\n\n// =============================================================================\n// Webhook Verification\n// =============================================================================\n\nimport crypto from 'crypto';\n\n/**\n * Verify a session.granted webhook signature.\n * \n * @example\n * ```typescript\n * const payload = req.body;\n * const signature = req.headers['x-mixrpay-signature'];\n * \n * if (verifySessionWebhook(JSON.stringify(payload), signature, webhookSecret)) {\n * const grant = parseSessionGrant(payload);\n * console.log(`User ${grant.userWallet} granted access`);\n * }\n * ```\n */\nexport function verifySessionWebhook(\n payload: string,\n signature: string,\n secret: string\n): boolean {\n const expectedSignature = crypto\n .createHmac('sha256', secret)\n .update(payload)\n .digest('hex');\n \n return crypto.timingSafeEqual(\n Buffer.from(signature),\n Buffer.from(expectedSignature)\n );\n}\n\n/**\n * Parse a session.granted webhook payload.\n */\nexport function parseSessionGrant(payload: {\n event: string;\n session_id: string;\n user_wallet: string;\n merchant_wallet: string;\n limits: {\n max_total_usd?: number;\n max_per_tx_usd?: number;\n expires_at: string;\n };\n granted_at: string;\n}): SessionGrant {\n if (payload.event !== 'session.granted') {\n throw new Error(`Unexpected event type: ${payload.event}`);\n }\n\n return {\n sessionId: payload.session_id,\n userWallet: payload.user_wallet,\n merchantWallet: payload.merchant_wallet,\n limits: {\n maxTotalUsd: payload.limits.max_total_usd,\n maxPerTxUsd: payload.limits.max_per_tx_usd,\n expiresAt: payload.limits.expires_at,\n },\n grantedAt: payload.granted_at,\n };\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,WAAsB;AAOtB,IAAM,mBAAmB,QAAQ,IAAI,oBAAoB;AACzD,IAAM,oBAAoB,KAAK,KAAK;AAWpC,IAAM,YAAY,oBAAI,IAAwB;AAK9C,eAAe,QAAQ,SAA8C;AACnE,QAAM,SAAS,UAAU,IAAI,OAAO;AACpC,QAAM,MAAM,KAAK,IAAI;AAGrB,MAAI,UAAW,MAAM,OAAO,YAAa,mBAAmB;AAC1D,WAAO,OAAO;AAAA,EAChB;AAGA,QAAM,WAAW,MAAM,MAAM,OAAO;AAEpC,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,6BAA6B,OAAO,KAAK,SAAS,MAAM,IAAI,SAAS,UAAU,EAAE;AAAA,EACnG;AAEA,QAAM,OAAO,MAAM,SAAS,KAAK;AAG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C/C;AACA,QAAI,iBAAsB,YAAO,0BAA0B;AACzD,YAAM,IAAI,MAAM,8BAA8B,MAAM,OAAO,EAAE;AAAA,IAC/D;AACA,QAAI,iBAAsB,YAAO,gCAAgC;AAC/D,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,UAAM;AAAA,EACR;AACF;;;ACgHA,oBAAmB;AAgBZ,SAAS,qBACd,SACA,WACA,QACS;AACT,QAAM,oBAAoB,cAAAA,QACvB,WAAW,UAAU,MAAM,EAC3B,OAAO,OAAO,EACd,OAAO,KAAK;AAEf,SAAO,cAAAA,QAAO;AAAA,IACZ,OAAO,KAAK,SAAS;AAAA,IACrB,OAAO,KAAK,iBAAiB;AAAA,EAC/B;AACF;","names":["crypto"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/receipt.ts","../src/charges.ts","../src/utils.ts"],"sourcesContent":["/**\n * MixrPay Merchant SDK\n * \n * Accept payments from AI agents and web apps with one middleware.\n * \n * @example Express\n * ```typescript\n * import { mixrpay } from '@mixrpay/merchant-sdk/express';\n * \n * app.post('/api/query', mixrpay({ priceUsd: 0.05 }), (req, res) => {\n * console.log(`Paid by ${req.mixrPayment?.payer}`);\n * res.json({ result: 'success' });\n * });\n * ```\n * \n * @example Next.js\n * ```typescript\n * import { withMixrPay } from '@mixrpay/merchant-sdk/nextjs';\n * \n * export const POST = withMixrPay({ priceUsd: 0.05 }, async (req, payment) => {\n * return NextResponse.json({ result: 'success' });\n * });\n * ```\n * \n * @packageDocumentation\n */\n\n// Receipt verification (for custom integrations)\nexport { verifyPaymentReceipt } from './receipt';\n\n// Session webhook verification\nexport { verifySessionWebhook } from './charges';\n\n// Utility functions and constants\nexport {\n getWidgetUrl,\n WIDGET_SCRIPT_URL,\n MIXRPAY_API_URL,\n usdToMinor,\n minorToUsd,\n validateEnv,\n logEnvValidation,\n} from './utils';\n\nexport type { EnvValidationResult } from './utils';\n\n// Types for TypeScript users\nexport type {\n MixrPayOptions,\n MixrPayPaymentResult,\n PaymentMethod,\n PriceContext,\n PaymentReceipt,\n} from './types';\n\nexport type {\n SessionGrant,\n} from './charges';\n\n// Widget element types (for TypeScript JSX support)\nexport type {} from './widget-elements';\n","/**\n * MixrPay Merchant SDK - Payment Receipt Verification\n * \n * Verify JWT payment receipts issued by MixrPay after successful x402 payments.\n * \n * @example\n * ```typescript\n * import { verifyPaymentReceipt } from '@mixrpay/merchant-sdk';\n * \n * const receipt = req.headers['x-payment-receipt'];\n * const payment = await verifyPaymentReceipt(receipt);\n * \n * console.log(`Payment received: $${payment.amountUsd} from ${payment.payer}`);\n * console.log(`Transaction: ${payment.txHash}`);\n * ```\n */\n\nimport * as jose from 'jose';\nimport type { PaymentReceipt, VerifyReceiptOptions } from './types';\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_JWKS_URL = process.env.MIXRPAY_JWKS_URL || 'https://www.mixrpay.com/.well-known/jwks';\nconst JWKS_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour\n\n// =============================================================================\n// JWKS Cache\n// =============================================================================\n\ninterface CachedJWKS {\n jwks: jose.JSONWebKeySet;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, CachedJWKS>();\n\n/**\n * Fetch and cache JWKS from the specified URL.\n */\nasync function getJWKS(jwksUrl: string): Promise<jose.JSONWebKeySet> {\n const cached = jwksCache.get(jwksUrl);\n const now = Date.now();\n\n // Return cached JWKS if still valid\n if (cached && (now - cached.fetchedAt) < JWKS_CACHE_TTL_MS) {\n return cached.jwks;\n }\n\n // Fetch fresh JWKS\n const response = await fetch(jwksUrl);\n \n if (!response.ok) {\n throw new Error(`Failed to fetch JWKS from ${jwksUrl}: ${response.status} ${response.statusText}`);\n }\n\n const jwks = await response.json() as jose.JSONWebKeySet;\n\n // Validate JWKS structure\n if (!jwks.keys || !Array.isArray(jwks.keys) || jwks.keys.length === 0) {\n throw new Error('Invalid JWKS: missing or empty keys array');\n }\n\n // Cache the JWKS\n jwksCache.set(jwksUrl, { jwks, fetchedAt: now });\n\n return jwks;\n}\n\n/**\n * Create a JWKS key set from a fetched JWKS.\n */\nasync function createKeySet(jwksUrl: string): Promise<jose.JWTVerifyGetKey> {\n const jwks = await getJWKS(jwksUrl);\n return jose.createLocalJWKSet(jwks);\n}\n\n// =============================================================================\n// Receipt Verification\n// =============================================================================\n\n/**\n * Verify a JWT payment receipt from MixrPay.\n * \n * This function:\n * 1. Fetches the JWKS from MixrPay (cached for 1 hour)\n * 2. Verifies the JWT signature using RS256\n * 3. Validates standard JWT claims (exp, iat)\n * 4. Returns the typed payment receipt\n * \n * @param receipt - The JWT receipt string from X-Payment-Receipt header\n * @param options - Optional configuration (custom JWKS URL, issuer validation)\n * @returns Verified payment receipt\n * @throws Error if verification fails\n * \n * @example\n * ```typescript\n * // Basic usage\n * const payment = await verifyPaymentReceipt(receipt);\n * \n * // With custom JWKS URL (for testing or self-hosted)\n * const payment = await verifyPaymentReceipt(receipt, {\n * jwksUrl: 'https://your-mixrpay.com/.well-known/jwks'\n * });\n * ```\n */\nexport async function verifyPaymentReceipt(\n receipt: string,\n options?: VerifyReceiptOptions\n): Promise<PaymentReceipt> {\n const jwksUrl = options?.jwksUrl || DEFAULT_JWKS_URL;\n\n try {\n // Get the key set\n const keySet = await createKeySet(jwksUrl);\n\n // Build verification options\n const verifyOptions: jose.JWTVerifyOptions = {\n algorithms: ['RS256'],\n };\n\n // Add issuer validation if specified\n if (options?.issuer) {\n verifyOptions.issuer = options.issuer;\n }\n\n // Verify the JWT\n const { payload } = await jose.jwtVerify(receipt, keySet, verifyOptions);\n\n // Validate required payment fields\n const requiredFields = ['paymentId', 'amount', 'amountUsd', 'payer', 'recipient', 'chainId', 'txHash', 'settledAt'];\n for (const field of requiredFields) {\n if (!(field in payload)) {\n throw new Error(`Missing required field in receipt: ${field}`);\n }\n }\n\n // Return typed receipt\n return {\n paymentId: payload.paymentId as string,\n amount: payload.amount as string,\n amountUsd: payload.amountUsd as number,\n payer: payload.payer as string,\n recipient: payload.recipient as string,\n chainId: payload.chainId as number,\n txHash: payload.txHash as string,\n settledAt: payload.settledAt as string,\n issuedAt: new Date((payload.iat as number) * 1000),\n expiresAt: new Date((payload.exp as number) * 1000),\n };\n } catch (error) {\n if (error instanceof jose.errors.JWTExpired) {\n throw new Error('Payment receipt has expired');\n }\n if (error instanceof jose.errors.JWTClaimValidationFailed) {\n throw new Error(`Receipt validation failed: ${error.message}`);\n }\n if (error instanceof jose.errors.JWSSignatureVerificationFailed) {\n throw new Error('Invalid receipt signature');\n }\n throw error;\n }\n}\n\n/**\n * Parse a JWT payment receipt without verification.\n * \n * WARNING: This does NOT verify the signature. Use only for debugging\n * or when you've already verified the receipt elsewhere.\n * \n * @param receipt - The JWT receipt string\n * @returns Decoded payload (unverified)\n */\nexport function parsePaymentReceipt(receipt: string): PaymentReceipt {\n const decoded = jose.decodeJwt(receipt);\n\n return {\n paymentId: decoded.paymentId as string,\n amount: decoded.amount as string,\n amountUsd: decoded.amountUsd as number,\n payer: decoded.payer as string,\n recipient: decoded.recipient as string,\n chainId: decoded.chainId as number,\n txHash: decoded.txHash as string,\n settledAt: decoded.settledAt as string,\n issuedAt: decoded.iat ? new Date(decoded.iat * 1000) : undefined,\n expiresAt: decoded.exp ? new Date(decoded.exp * 1000) : undefined,\n };\n}\n\n/**\n * Check if a receipt is expired.\n * \n * @param receipt - The JWT receipt string or parsed PaymentReceipt\n * @returns true if expired, false otherwise\n */\nexport function isReceiptExpired(receipt: string | PaymentReceipt): boolean {\n const parsed = typeof receipt === 'string' ? parsePaymentReceipt(receipt) : receipt;\n \n if (!parsed.expiresAt) {\n return false; // No expiration = never expires\n }\n\n return parsed.expiresAt.getTime() < Date.now();\n}\n\n/**\n * Clear the JWKS cache.\n * Useful for testing or when keys have rotated.\n */\nexport function clearJWKSCache(): void {\n jwksCache.clear();\n}\n\n/**\n * Get the default JWKS URL.\n */\nexport function getDefaultJWKSUrl(): string {\n return DEFAULT_JWKS_URL;\n}\n\n","/**\n * MixrPay Charges Module\n * \n * Create and manage charges using session signers.\n * Session signers allow you to charge user wallets without\n * requiring approval for each transaction.\n */\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface CreateChargeParams {\n /** Session key ID granted by the user */\n sessionId: string;\n /** Amount to charge in USD (e.g., 0.05 for 5 cents) */\n amountUsd: number;\n /** Unique reference for idempotency (e.g., \"order_123\") */\n reference: string;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n}\n\nexport interface Charge {\n /** Unique charge ID */\n id: string;\n /** Current status (from database) */\n status: 'pending' | 'submitted' | 'confirmed' | 'failed';\n /** Real-time status (may differ from DB if not yet synced) */\n liveStatus?: 'pending' | 'submitted' | 'confirmed' | 'failed';\n /** Raw on-chain status */\n onChainStatus?: 'pending' | 'confirmed' | 'failed' | 'not_found' | null;\n /** Amount in USD */\n amountUsd: number;\n /** Formatted USDC amount */\n amountUsdc: string;\n /** Transaction hash (if submitted) */\n txHash?: string;\n /** Block explorer URL */\n explorerUrl?: string;\n /** From wallet address */\n fromAddress: string;\n /** To wallet address */\n toAddress: string;\n /** Your reference */\n reference: string;\n /** When the charge was created */\n createdAt: string;\n /** When the charge was confirmed */\n confirmedAt?: string;\n /** Session name */\n sessionName?: string;\n /** User wallet address */\n userWallet?: string;\n /** Error message if failed */\n error?: string;\n /** True if DB status differs from on-chain - call sync() to update */\n needsSync?: boolean;\n}\n\nexport interface CreateChargeResult {\n success: boolean;\n charge?: Charge;\n /** True if this is a replay of an existing charge */\n idempotentReplay?: boolean;\n error?: string;\n details?: string;\n}\n\nexport interface SessionGrant {\n /** Session key ID */\n sessionId: string;\n /** User's wallet address */\n userWallet: string;\n /** Your merchant wallet address */\n merchantWallet: string;\n /** Spending limits */\n limits: {\n maxTotalUsd?: number;\n maxPerTxUsd?: number;\n expiresAt: string;\n };\n /** When the session was granted */\n grantedAt: string;\n}\n\n// Internal types for API responses\ninterface CreateChargeApiResponse {\n success: boolean;\n charge_id?: string;\n status?: string;\n amount_usd?: number;\n amount_usdc?: string;\n tx_hash?: string;\n explorer_url?: string;\n idempotent_replay?: boolean;\n error?: string;\n details?: string;\n}\n\ninterface ChargeApiResponse {\n id: string;\n status: string;\n /** Real-time status (may differ from DB status if not yet synced) */\n live_status?: string;\n /** Raw on-chain status */\n on_chain_status?: 'pending' | 'confirmed' | 'failed' | 'not_found' | null;\n amount_usd: number;\n amount_usdc: string;\n tx_hash?: string;\n explorer_url?: string;\n from_address: string;\n to_address: string;\n reference: string;\n created_at: string;\n confirmed_at?: string;\n session_name?: string;\n user_wallet?: string;\n /** True if DB status differs from on-chain status */\n needs_sync?: boolean;\n}\n\ninterface SyncChargeApiResponse {\n success: boolean;\n charge?: {\n id: string;\n status: string;\n };\n error?: string;\n}\n\nexport interface ChargesClientOptions {\n /** Your API key */\n apiKey: string;\n /** MixrPay API base URL */\n baseUrl?: string;\n}\n\n// =============================================================================\n// Client\n// =============================================================================\n\nexport class ChargesClient {\n private apiKey: string;\n private baseUrl: string;\n\n constructor(options: ChargesClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl || process.env.MIXRPAY_BASE_URL || 'https://www.mixrpay.com';\n }\n\n /**\n * Create a new charge.\n * \n * @example\n * ```typescript\n * const result = await charges.create({\n * sessionId: 'sk_xxx',\n * amountUsd: 0.05,\n * reference: 'image_gen_123',\n * metadata: { feature: 'image_generation' }\n * });\n * \n * if (result.success) {\n * console.log(`Charged ${result.charge.amountUsdc}`);\n * console.log(`TX: ${result.charge.explorerUrl}`);\n * }\n * ```\n */\n async create(params: CreateChargeParams): Promise<CreateChargeResult> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n session_id: params.sessionId,\n amount_usd: params.amountUsd,\n reference: params.reference,\n metadata: params.metadata,\n }),\n });\n\n const data = await response.json() as CreateChargeApiResponse;\n\n if (!response.ok) {\n return {\n success: false,\n error: data.error,\n details: data.details,\n };\n }\n\n return {\n success: data.success,\n charge: data.charge_id ? {\n id: data.charge_id,\n status: data.status as Charge['status'],\n amountUsd: data.amount_usd ?? 0,\n amountUsdc: data.amount_usdc ?? '0',\n txHash: data.tx_hash,\n explorerUrl: data.explorer_url,\n fromAddress: '',\n toAddress: '',\n reference: params.reference,\n createdAt: new Date().toISOString(),\n } : undefined,\n idempotentReplay: data.idempotent_replay,\n error: data.error,\n };\n }\n\n /**\n * Get a charge by ID.\n * \n * Note: The returned status is from the database. If `needsSync` is true,\n * the on-chain status differs and you should call `sync()` to update.\n * \n * @example\n * ```typescript\n * const charge = await charges.get('chg_xxx');\n * console.log(charge.status); // 'submitted'\n * console.log(charge.liveStatus); // 'confirmed' (real-time)\n * \n * if (charge.needsSync) {\n * await charges.sync(charge.id);\n * }\n * ```\n */\n async get(chargeId: string): Promise<Charge | null> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges?id=${chargeId}`, {\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new Error(`Failed to get charge: ${response.statusText}`);\n }\n\n const data = await response.json() as ChargeApiResponse;\n\n return this.mapChargeResponse(data);\n }\n\n /**\n * Get a charge by transaction hash.\n */\n async getByTxHash(txHash: string): Promise<Charge | null> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges?tx_hash=${txHash}`, {\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new Error(`Failed to get charge: ${response.statusText}`);\n }\n\n const data = await response.json() as ChargeApiResponse;\n\n return this.mapChargeResponse(data);\n }\n\n /**\n * Sync a charge's status from the blockchain.\n * \n * Call this when `get()` returns a charge with `needsSync: true`.\n * This will update the database with the on-chain status.\n * \n * @example\n * ```typescript\n * const charge = await charges.get('chg_xxx');\n * if (charge?.needsSync) {\n * const synced = await charges.sync(charge.id);\n * console.log(`Status updated to: ${synced.status}`);\n * }\n * ```\n */\n async sync(chargeId: string): Promise<{ id: string; status: string }> {\n const response = await fetch(`${this.baseUrl}/api/v1/charges/sync`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ charge_id: chargeId }),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(`Failed to sync charge: ${(error as { error?: string }).error || response.statusText}`);\n }\n\n const data = await response.json() as SyncChargeApiResponse;\n\n if (!data.success || !data.charge) {\n throw new Error(`Sync failed: ${data.error || 'Unknown error'}`);\n }\n\n return data.charge;\n }\n\n /**\n * Poll for charge confirmation.\n * \n * Convenience method that polls until the charge is confirmed or failed,\n * automatically syncing when needed.\n * \n * @example\n * ```typescript\n * const charge = await charges.waitForConfirmation('chg_xxx', {\n * timeoutMs: 60000,\n * pollIntervalMs: 2000,\n * });\n * console.log(`Final status: ${charge.status}`);\n * ```\n */\n async waitForConfirmation(\n chargeId: string,\n options: { timeoutMs?: number; pollIntervalMs?: number } = {}\n ): Promise<Charge> {\n const { timeoutMs = 60000, pollIntervalMs = 2000 } = options;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeoutMs) {\n const charge = await this.get(chargeId);\n \n if (!charge) {\n throw new Error('Charge not found');\n }\n\n // If needs sync, sync it first\n if (charge.needsSync) {\n await this.sync(chargeId);\n // Re-fetch to get updated status\n const synced = await this.get(chargeId);\n if (synced && (synced.status === 'confirmed' || synced.status === 'failed')) {\n return synced;\n }\n }\n\n // Check if we've reached a terminal state\n if (charge.status === 'confirmed' || charge.status === 'failed') {\n return charge;\n }\n\n // Also check live status for early return\n if (charge.liveStatus === 'confirmed' || charge.liveStatus === 'failed') {\n // Sync and return\n await this.sync(chargeId);\n const final = await this.get(chargeId);\n if (final) return final;\n }\n\n // Wait before next poll\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n }\n\n throw new Error(`Timeout waiting for charge confirmation after ${timeoutMs}ms`);\n }\n\n private mapChargeResponse(data: ChargeApiResponse): Charge {\n return {\n id: data.id,\n status: data.status as Charge['status'],\n liveStatus: data.live_status as Charge['status'] | undefined,\n onChainStatus: data.on_chain_status,\n amountUsd: data.amount_usd,\n amountUsdc: data.amount_usdc,\n txHash: data.tx_hash,\n explorerUrl: data.explorer_url,\n fromAddress: data.from_address,\n toAddress: data.to_address,\n reference: data.reference,\n createdAt: data.created_at,\n confirmedAt: data.confirmed_at,\n sessionName: data.session_name,\n userWallet: data.user_wallet,\n needsSync: data.needs_sync,\n };\n }\n}\n\n// =============================================================================\n// Webhook Verification\n// =============================================================================\n\nimport crypto from 'crypto';\n\n/**\n * Verify a session.granted webhook signature.\n * \n * @example\n * ```typescript\n * const payload = req.body;\n * const signature = req.headers['x-mixrpay-signature'];\n * \n * if (verifySessionWebhook(JSON.stringify(payload), signature, webhookSecret)) {\n * const grant = parseSessionGrant(payload);\n * console.log(`User ${grant.userWallet} granted access`);\n * }\n * ```\n */\nexport function verifySessionWebhook(\n payload: string,\n signature: string,\n secret: string\n): boolean {\n const expectedSignature = crypto\n .createHmac('sha256', secret)\n .update(payload)\n .digest('hex');\n \n return crypto.timingSafeEqual(\n Buffer.from(signature),\n Buffer.from(expectedSignature)\n );\n}\n\n/**\n * Parse a session.granted webhook payload.\n */\nexport function parseSessionGrant(payload: {\n event: string;\n session_id: string;\n user_wallet: string;\n merchant_wallet: string;\n limits: {\n max_total_usd?: number;\n max_per_tx_usd?: number;\n expires_at: string;\n };\n granted_at: string;\n}): SessionGrant {\n if (payload.event !== 'session.granted') {\n throw new Error(`Unexpected event type: ${payload.event}`);\n }\n\n return {\n sessionId: payload.session_id,\n userWallet: payload.user_wallet,\n merchantWallet: payload.merchant_wallet,\n limits: {\n maxTotalUsd: payload.limits.max_total_usd,\n maxPerTxUsd: payload.limits.max_per_tx_usd,\n expiresAt: payload.limits.expires_at,\n },\n grantedAt: payload.granted_at,\n };\n}\n\n","/**\n * MixrPay Merchant SDK - Utilities\n */\n\nimport type { EIP712Domain } from './types';\n\n// =============================================================================\n// Widget URLs\n// =============================================================================\n\n/**\n * Get the MixrPay widget script URL.\n * \n * @example\n * ```html\n * <script src=\"${getWidgetUrl()}\"\n * data-seller-public-key=\"pk_live_...\"\n * data-user-token=\"...\"></script>\n * ```\n */\nexport function getWidgetUrl(): string {\n return 'https://www.mixrpay.com/widget.js';\n}\n\n/**\n * MixrPay API base URL\n */\nexport const MIXRPAY_API_URL = 'https://www.mixrpay.com';\n\n/**\n * Widget script URL (for convenience)\n */\nexport const WIDGET_SCRIPT_URL = 'https://www.mixrpay.com/widget.js';\n\n// =============================================================================\n// USDC Constants by Chain\n// =============================================================================\n\nexport const USDC_CONTRACTS: Record<number, `0x${string}`> = {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base Mainnet\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia\n};\n\nexport const DEFAULT_FACILITATOR = 'https://x402.org/facilitator';\n\n// =============================================================================\n// EIP-712 Domain\n// =============================================================================\n\nexport function getUSDCDomain(chainId: number): EIP712Domain {\n const verifyingContract = USDC_CONTRACTS[chainId];\n if (!verifyingContract) {\n throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(', ')}`);\n }\n\n return {\n name: 'USD Coin',\n version: '2',\n chainId,\n verifyingContract,\n };\n}\n\n// EIP-712 types for TransferWithAuthorization\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const;\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Convert USD dollars to USDC minor units (6 decimals)\n */\nexport function usdToMinor(usd: number): bigint {\n return BigInt(Math.round(usd * 1_000_000));\n}\n\n/**\n * Convert USDC minor units to USD dollars\n */\nexport function minorToUsd(minor: bigint): number {\n return Number(minor) / 1_000_000;\n}\n\n/**\n * Generate a random nonce for x402 payments\n */\nexport function generateNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return `0x${Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')}` as `0x${string}`;\n}\n\n/**\n * Check if an address is valid\n */\nexport function isValidAddress(address: string): address is `0x${string}` {\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n}\n\n/**\n * Normalize an address to lowercase checksum format\n */\nexport function normalizeAddress(address: string): `0x${string}` {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid address: ${address}`);\n }\n return address.toLowerCase() as `0x${string}`;\n}\n\n/**\n * Safe base64 decode that works in both Node.js and browsers\n */\nexport function base64Decode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf-8');\n }\n return atob(str);\n}\n\n/**\n * Safe base64 encode that works in both Node.js and browsers\n */\nexport function base64Encode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf-8').toString('base64');\n }\n return btoa(str);\n}\n\n// =============================================================================\n// Environment Validation\n// =============================================================================\n\nexport interface EnvValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n config: {\n publicKey: string | null;\n secretKey: string | null;\n hmacSecret: string | null;\n webhookSecret: string | null;\n merchantAddress: string | null;\n };\n}\n\n/**\n * Validate MixrPay environment variables and provide helpful feedback.\n * \n * @example\n * ```typescript\n * import { validateEnv } from '@mixrpay/merchant-sdk';\n * \n * const result = validateEnv();\n * if (!result.valid) {\n * console.error('MixrPay configuration errors:', result.errors);\n * }\n * ```\n */\nexport function validateEnv(env?: Record<string, string | undefined>): EnvValidationResult {\n const e = env || (typeof process !== 'undefined' ? process.env : {});\n \n const result: EnvValidationResult = {\n valid: true,\n errors: [],\n warnings: [],\n config: {\n publicKey: (e.MIXRPAY_PUBLIC_KEY as string) || null,\n secretKey: (e.MIXRPAY_SECRET_KEY as string) || null,\n hmacSecret: (e.MIXRPAY_HMAC_SECRET as string) || null,\n webhookSecret: (e.MIXRPAY_WEBHOOK_SECRET as string) || null,\n merchantAddress: (e.MIXRPAY_MERCHANT_ADDRESS as string) || null,\n },\n };\n \n // Check public key\n if (!result.config.publicKey) {\n result.errors.push('MIXRPAY_PUBLIC_KEY is required. Get it from https://www.mixrpay.com/seller/developers');\n result.valid = false;\n } else if (!result.config.publicKey.startsWith('pk_')) {\n result.errors.push(`MIXRPAY_PUBLIC_KEY must start with 'pk_'. Got: ${result.config.publicKey.slice(0, 10)}...`);\n result.valid = false;\n }\n \n // Check secret key\n if (!result.config.secretKey) {\n result.errors.push('MIXRPAY_SECRET_KEY is required. Get it from https://www.mixrpay.com/seller/developers');\n result.valid = false;\n } else if (!result.config.secretKey.startsWith('sk_')) {\n result.errors.push(`MIXRPAY_SECRET_KEY must start with 'sk_'. Got: ${result.config.secretKey.slice(0, 10)}...`);\n result.valid = false;\n }\n \n // Check webhook secret (required)\n if (!result.config.webhookSecret) {\n result.errors.push('MIXRPAY_WEBHOOK_SECRET is required. Get it from https://www.mixrpay.com/seller/developers');\n result.valid = false;\n }\n \n // Check HMAC secret (warning only - only needed for widget with user linking)\n if (!result.config.hmacSecret) {\n result.warnings.push('MIXRPAY_HMAC_SECRET not set. Only required if using Widget with user linking (data-user-token).');\n }\n \n // Check merchant address (warning only - needed for x402)\n if (!result.config.merchantAddress) {\n result.warnings.push('MIXRPAY_MERCHANT_ADDRESS not set. Required for x402 protocol support.');\n } else if (!isValidAddress(result.config.merchantAddress)) {\n result.errors.push(`MIXRPAY_MERCHANT_ADDRESS is not a valid Ethereum address: ${result.config.merchantAddress}`);\n result.valid = false;\n }\n \n return result;\n}\n\n/**\n * Log environment validation results to console with formatting.\n */\nexport function logEnvValidation(result?: EnvValidationResult): void {\n const r = result || validateEnv();\n \n console.log('\\nšŸ”§ MixrPay Environment Check\\n');\n \n if (r.valid) {\n console.log('āœ… Configuration valid\\n');\n } else {\n console.log('āŒ Configuration errors found\\n');\n }\n \n if (r.errors.length > 0) {\n console.log('Errors:');\n r.errors.forEach(e => console.log(` āŒ ${e}`));\n console.log('');\n }\n \n if (r.warnings.length > 0) {\n console.log('Warnings:');\n r.warnings.forEach(w => console.log(` āš ļø ${w}`));\n console.log('');\n }\n \n console.log('Required credentials:');\n console.log(` Public Key: ${r.config.publicKey ? 'āœ“ Set' : 'āœ— Missing'}`);\n console.log(` Secret Key: ${r.config.secretKey ? 'āœ“ Set' : 'āœ— Missing'}`);\n console.log(` Webhook Secret: ${r.config.webhookSecret ? 'āœ“ Set' : 'āœ— Missing'}`);\n console.log('');\n console.log('Optional credentials:');\n console.log(` HMAC Secret: ${r.config.hmacSecret ? 'āœ“ Set' : 'ā—‹ Not set (widget only)'}`);\n console.log(` Merchant Address: ${r.config.merchantAddress ? 'āœ“ Set' : 'ā—‹ Not set (x402 only)'}`);\n console.log('');\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,WAAsB;AAOtB,IAAM,mBAAmB,QAAQ,IAAI,oBAAoB;AACzD,IAAM,oBAAoB,KAAK,KAAK;AAWpC,IAAM,YAAY,oBAAI,IAAwB;AAK9C,eAAe,QAAQ,SAA8C;AACnE,QAAM,SAAS,UAAU,IAAI,OAAO;AACpC,QAAM,MAAM,KAAK,IAAI;AAGrB,MAAI,UAAW,MAAM,OAAO,YAAa,mBAAmB;AAC1D,WAAO,OAAO;AAAA,EAChB;AAGA,QAAM,WAAW,MAAM,MAAM,OAAO;AAEpC,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,6BAA6B,OAAO,KAAK,SAAS,MAAM,IAAI,SAAS,UAAU,EAAE;AAAA,EACnG;AAEA,QAAM,OAAO,MAAM,SAAS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