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/dist/index.mjs DELETED
@@ -1,226 +0,0 @@
1
- // src/client.ts
2
- var Aipp = class {
3
- apiKey;
4
- baseUrl;
5
- constructor(config) {
6
- if (!config.apiKey) {
7
- throw new Error("AIPP: apiKey is required");
8
- }
9
- this.apiKey = config.apiKey;
10
- this.baseUrl = config.baseUrl || "https://aipp.dev";
11
- }
12
- async request(endpoint, options = {}) {
13
- const url = `${this.baseUrl}${endpoint}`;
14
- const headers = {
15
- "Content-Type": "application/json",
16
- "X-Api-Key": this.apiKey,
17
- ...options.headers
18
- };
19
- const response = await fetch(url, { ...options, headers });
20
- if (!response.ok) {
21
- let errorData;
22
- try {
23
- errorData = await response.json();
24
- } catch (err) {
25
- throw new Error(`AIPP API Error: ${response.status} ${response.statusText}`);
26
- }
27
- throw new Error(`AIPP API Error: ${errorData.error || response.statusText}`);
28
- }
29
- return response.json();
30
- }
31
- /**
32
- * Creates a new Invoice (either L402 or x402)
33
- */
34
- async createCharge(params) {
35
- if (!params.amountSats && !params.amountUsd) {
36
- throw new Error("AIPP: Either amountSats or amountUsd is required");
37
- }
38
- const body = { memo: params.memo };
39
- if (params.amountSats) body.amount_sats = params.amountSats;
40
- if (params.amountUsd) body.amount_usd = params.amountUsd;
41
- if (params.protocol) body.protocol = params.protocol;
42
- return this.request("/invoice/create", {
43
- method: "POST",
44
- body: JSON.stringify(body)
45
- });
46
- }
47
- /**
48
- * Checks the status of an existing charge
49
- */
50
- async getCharge(paymentHash, txHash) {
51
- if (!paymentHash) {
52
- throw new Error("AIPP: paymentHash is required");
53
- }
54
- const query = txHash ? `?tx_hash=${txHash}` : "";
55
- return this.request(`/invoice/status/${paymentHash}${query}`, {
56
- method: "GET"
57
- });
58
- }
59
- /**
60
- * Triggers a manual withdrawal of your merchant balance
61
- */
62
- async payout() {
63
- return this.request("/merchant/payout", {
64
- method: "POST"
65
- });
66
- }
67
- };
68
-
69
- // src/middleware.ts
70
- import crypto2 from "crypto";
71
-
72
- // src/jwt.ts
73
- import crypto from "crypto";
74
- function base64urlEncode(str) {
75
- const buf = Buffer.isBuffer(str) ? str : Buffer.from(str);
76
- return buf.toString("base64url");
77
- }
78
- function base64urlDecode(str) {
79
- return Buffer.from(str, "base64url").toString("utf8");
80
- }
81
- function signJwt(payload, secret) {
82
- const header = { alg: "HS256", typ: "JWT" };
83
- const encodedHeader = base64urlEncode(JSON.stringify(header));
84
- const encodedPayload = base64urlEncode(JSON.stringify(payload));
85
- const data = `${encodedHeader}.${encodedPayload}`;
86
- const signature = crypto.createHmac("sha256", secret).update(data).digest("base64url");
87
- return `${data}.${signature}`;
88
- }
89
- function verifyJwt(token, secret) {
90
- const parts = token.split(".");
91
- if (parts.length !== 3) {
92
- throw new Error("Invalid JWT format");
93
- }
94
- const [encodedHeader, encodedPayload, signature] = parts;
95
- const data = `${encodedHeader}.${encodedPayload}`;
96
- const expectedSignature = crypto.createHmac("sha256", secret).update(data).digest("base64url");
97
- const signatureBuffer = Buffer.from(signature);
98
- const expectedBuffer = Buffer.from(expectedSignature);
99
- if (signatureBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)) {
100
- throw new Error("Invalid JWT signature");
101
- }
102
- const payload = JSON.parse(base64urlDecode(encodedPayload));
103
- if (payload.exp && Date.now() >= payload.exp * 1e3) {
104
- throw new Error("JWT expired");
105
- }
106
- return payload;
107
- }
108
-
109
- // src/middleware.ts
110
- function l402Paywall(options) {
111
- if (!options.amountSats && !options.amountUsd) {
112
- throw new Error("Either amountSats or amountUsd must be provided for l402Paywall");
113
- }
114
- return async (req, res, next) => {
115
- const authHeader = req.headers.authorization || req.headers.Authorization;
116
- let valid = false;
117
- if (authHeader && typeof authHeader === "string" && authHeader.startsWith("L402 ")) {
118
- const parts = authHeader.substring(5).split(":");
119
- if (parts.length === 2) {
120
- const [macaroonStr, preimage] = parts;
121
- try {
122
- const payload = verifyJwt(macaroonStr, options.jwtSecret);
123
- if (payload.resource_id !== options.resourceId) {
124
- throw new Error("Invalid resource");
125
- }
126
- const preimageHash = crypto2.createHash("sha256").update(Buffer.from(preimage, "hex")).digest("hex");
127
- const expectedHash = payload.payment_hash;
128
- if (typeof expectedHash === "string" && expectedHash.length === preimageHash.length && crypto2.timingSafeEqual(Buffer.from(preimageHash, "hex"), Buffer.from(expectedHash, "hex"))) {
129
- valid = true;
130
- }
131
- } catch (e) {
132
- }
133
- }
134
- }
135
- if (valid) {
136
- return next();
137
- }
138
- try {
139
- const charge = await options.client.createCharge({
140
- amountSats: options.amountSats,
141
- amountUsd: options.amountUsd,
142
- memo: `L402 Payment for ${options.resourceId}`
143
- });
144
- const expiresIn = options.expiresInSeconds || 3600;
145
- const payload = {
146
- payment_hash: charge.payment_hash,
147
- resource_id: options.resourceId,
148
- exp: Math.floor(Date.now() / 1e3) + expiresIn
149
- };
150
- const jwtToken = signJwt(payload, options.jwtSecret);
151
- res.status(402);
152
- res.setHeader("Www-Authenticate", `L402 macaroon="${jwtToken}" invoice="${charge.payment_request}"`);
153
- res.json({
154
- error: "Payment Required",
155
- code: "L402",
156
- payment_request: charge.payment_request,
157
- macaroon: jwtToken
158
- });
159
- } catch (err) {
160
- res.status(500).json({ error: "Failed to generate L402 challenge", details: err.message || err });
161
- }
162
- };
163
- }
164
- function x402Paywall(options) {
165
- return async (req, res, next) => {
166
- const authHeader = req.headers.authorization || req.headers.Authorization;
167
- let txHash = req.query.tx_hash || req.headers["payment-signature"] || req.headers["x-payment-signature"];
168
- let paymentHash = req.query.payment_hash || req.headers["x-payment-hash"];
169
- if (!txHash && authHeader && typeof authHeader === "string") {
170
- if (authHeader.startsWith("Bearer ")) {
171
- txHash = authHeader.substring(7).trim();
172
- } else if (authHeader.startsWith("x402 ")) {
173
- txHash = authHeader.substring(5).trim();
174
- } else if (authHeader.startsWith("L402 ")) {
175
- const parts = authHeader.substring(5).split(":");
176
- if (parts.length === 2) {
177
- paymentHash = parts[0];
178
- txHash = parts[1];
179
- }
180
- }
181
- }
182
- if (paymentHash && txHash) {
183
- try {
184
- const chargeStatus = await options.client.getCharge(paymentHash, txHash);
185
- if (chargeStatus.status === "settled") {
186
- return next();
187
- }
188
- } catch (e) {
189
- }
190
- }
191
- try {
192
- const charge = await options.client.createCharge({
193
- amountUsd: options.amountUsd,
194
- protocol: "x402",
195
- memo: `x402 Payment for ${options.resourceId}`
196
- });
197
- const challengeObj = {
198
- scheme: "exact",
199
- network: "base",
200
- payTo: charge.pay_to || "",
201
- price: options.amountUsd.toFixed(2),
202
- token: charge.token || "",
203
- payment_hash: charge.payment_hash
204
- };
205
- const challengeBase64 = Buffer.from(JSON.stringify(challengeObj), "utf8").toString("base64");
206
- res.setHeader("PAYMENT-REQUIRED", challengeBase64);
207
- res.status(402);
208
- res.json({
209
- error: "Payment Required",
210
- code: "x402",
211
- payment_hash: charge.payment_hash,
212
- pay_to: challengeObj.payTo,
213
- price: challengeObj.price,
214
- token: challengeObj.token,
215
- network: challengeObj.network
216
- });
217
- } catch (err) {
218
- res.status(500).json({ error: "Failed to generate x402 challenge", details: err.message || err });
219
- }
220
- };
221
- }
222
- export {
223
- Aipp,
224
- l402Paywall,
225
- x402Paywall
226
- };