@ghemrim/slickpay-bridge-studio 0.0.0-stage → 1.1.2
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/LICENSE +56 -0
- package/README.md +269 -3
- package/SECURITY.md +33 -0
- package/package.json +48 -6
- package/public/sdk/slickpay-widget.css +422 -0
- package/public/sdk/slickpay-widget.js +910 -0
- package/server/index.mjs +334 -0
- package/server/slickpay-sdk.mjs +826 -0
package/server/index.mjs
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serveur HTTP de la Passerelle Universelle SlickPay
|
|
3
|
+
* - Liste blanche stricte d'extensions statiques (interdit .php, .htaccess et dotfiles)
|
|
4
|
+
* - Supporte /api/slickpay/checkout, /api/checkout.php et /api/slickpay/sign-price
|
|
5
|
+
* - Limitation de débit (Rate Limiter par IP avec éviction LRU et support trustProxy)
|
|
6
|
+
* - Authentification HMAC-SHA256 sur /api/slickpay/webhook
|
|
7
|
+
* - Vérification dynamique du statut sur la page /payment-return
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import http from 'node:http';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { SlickPayGateway, WILAYAS_58 } from './slickpay-sdk.mjs';
|
|
15
|
+
|
|
16
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
17
|
+
const __dirname = path.dirname(__filename);
|
|
18
|
+
const PUBLIC_DIR = path.join(__dirname, '..', 'public');
|
|
19
|
+
|
|
20
|
+
const ALLOWED_STATIC_EXTENSIONS = {
|
|
21
|
+
'.html': 'text/html; charset=utf-8',
|
|
22
|
+
'.js': 'application/javascript; charset=utf-8',
|
|
23
|
+
'.css': 'text/css; charset=utf-8',
|
|
24
|
+
'.json': 'application/json; charset=utf-8',
|
|
25
|
+
'.png': 'image/png',
|
|
26
|
+
'.svg': 'image/svg+xml',
|
|
27
|
+
'.ico': 'image/x-icon',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
31
|
+
|
|
32
|
+
function resolveCorsOrigin(req, allowedOrigins) {
|
|
33
|
+
const origin = req.headers.origin;
|
|
34
|
+
if (!allowedOrigins || allowedOrigins.includes('*')) {
|
|
35
|
+
return '*';
|
|
36
|
+
}
|
|
37
|
+
if (origin && allowedOrigins.includes(origin)) {
|
|
38
|
+
return origin;
|
|
39
|
+
}
|
|
40
|
+
return allowedOrigins[0] || 'null';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sendJson(req, res, statusCode, payload, allowedOrigins) {
|
|
44
|
+
res.writeHead(statusCode, {
|
|
45
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
46
|
+
'Access-Control-Allow-Origin': resolveCorsOrigin(req, allowedOrigins),
|
|
47
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
48
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-SlickPay-Signature',
|
|
49
|
+
'X-Content-Type-Options': 'nosniff',
|
|
50
|
+
});
|
|
51
|
+
res.end(JSON.stringify(payload, null, 2));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readJsonBody(req) {
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let totalBytes = 0;
|
|
58
|
+
let aborted = false;
|
|
59
|
+
|
|
60
|
+
req.on('data', (chunk) => {
|
|
61
|
+
if (aborted) return;
|
|
62
|
+
totalBytes += chunk.byteLength;
|
|
63
|
+
if (totalBytes > MAX_BODY_BYTES) {
|
|
64
|
+
aborted = true;
|
|
65
|
+
req.destroy();
|
|
66
|
+
const err = new Error('Payload trop volumineux (limite 64 Ko dépassée).');
|
|
67
|
+
err.statusCode = 413;
|
|
68
|
+
reject(err);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
chunks.push(chunk);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
req.on('end', () => {
|
|
75
|
+
if (aborted) return;
|
|
76
|
+
if (totalBytes === 0) return resolve({});
|
|
77
|
+
try {
|
|
78
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
79
|
+
resolve(JSON.parse(raw));
|
|
80
|
+
} catch (_) {
|
|
81
|
+
const err = new Error('Corps JSON invalide.');
|
|
82
|
+
err.statusCode = 400;
|
|
83
|
+
reject(err);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
req.on('error', (err) => {
|
|
88
|
+
if (!aborted) reject(err);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function createGatewayServer(gatewayConfig = {}) {
|
|
94
|
+
const gateway = new SlickPayGateway(gatewayConfig);
|
|
95
|
+
const allowedOrigins = Array.isArray(gatewayConfig.allowedOrigins)
|
|
96
|
+
? gatewayConfig.allowedOrigins
|
|
97
|
+
: (
|
|
98
|
+
process.env.SLICKPAY_ALLOWED_ORIGINS ||
|
|
99
|
+
(gateway.mode === 'production' ? 'null' : '*')
|
|
100
|
+
)
|
|
101
|
+
.split(',')
|
|
102
|
+
.map((o) => o.trim())
|
|
103
|
+
.filter(Boolean);
|
|
104
|
+
|
|
105
|
+
const trustProxy =
|
|
106
|
+
gatewayConfig.trustProxy !== undefined
|
|
107
|
+
? Boolean(gatewayConfig.trustProxy)
|
|
108
|
+
: process.env.SLICKPAY_TRUST_PROXY === 'true';
|
|
109
|
+
|
|
110
|
+
const rateLimitMax = Number(
|
|
111
|
+
gatewayConfig.rateLimitMax || process.env.SLICKPAY_RATE_LIMIT_MAX || 60
|
|
112
|
+
);
|
|
113
|
+
const rateLimitMap = new Map();
|
|
114
|
+
|
|
115
|
+
function getClientIp(req) {
|
|
116
|
+
if (trustProxy) {
|
|
117
|
+
const cfIp = req.headers['cf-connecting-ip'];
|
|
118
|
+
if (cfIp && typeof cfIp === 'string') return cfIp.trim();
|
|
119
|
+
const xff = req.headers['x-forwarded-for'];
|
|
120
|
+
if (xff && typeof xff === 'string') return xff.split(',')[0].trim();
|
|
121
|
+
}
|
|
122
|
+
return req.socket?.remoteAddress || '127.0.0.1';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function checkRateLimit(req) {
|
|
126
|
+
const ip = getClientIp(req);
|
|
127
|
+
const now = Date.now();
|
|
128
|
+
const entry = rateLimitMap.get(ip);
|
|
129
|
+
if (!entry || now > entry.resetAt) {
|
|
130
|
+
if (rateLimitMap.size >= 5000 && !rateLimitMap.has(ip)) {
|
|
131
|
+
const oldestKey = rateLimitMap.keys().next().value;
|
|
132
|
+
if (oldestKey !== undefined) rateLimitMap.delete(oldestKey);
|
|
133
|
+
}
|
|
134
|
+
rateLimitMap.set(ip, { count: 1, resetAt: now + 60_000 });
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
entry.count += 1;
|
|
138
|
+
return entry.count <= rateLimitMax;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const server = http.createServer(async (req, res) => {
|
|
142
|
+
const urlObj = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
|
143
|
+
const pathname = urlObj.pathname;
|
|
144
|
+
|
|
145
|
+
if (req.method === 'OPTIONS') {
|
|
146
|
+
res.writeHead(204, {
|
|
147
|
+
'Access-Control-Allow-Origin': resolveCorsOrigin(req, allowedOrigins),
|
|
148
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
149
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-SlickPay-Signature',
|
|
150
|
+
});
|
|
151
|
+
return res.end();
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (!checkRateLimit(req)) {
|
|
155
|
+
return sendJson(
|
|
156
|
+
req,
|
|
157
|
+
res,
|
|
158
|
+
429,
|
|
159
|
+
{ ok: false, error: 'Trop de requêtes. Veuillez réessayer dans une minute.' },
|
|
160
|
+
allowedOrigins
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
// 1. Liste complète des 58 wilayas
|
|
166
|
+
if (req.method === 'GET' && pathname === '/api/slickpay/wilayas') {
|
|
167
|
+
return sendJson(
|
|
168
|
+
req,
|
|
169
|
+
res,
|
|
170
|
+
200,
|
|
171
|
+
{ ok: true, count: WILAYAS_58.length, wilayas: WILAYAS_58 },
|
|
172
|
+
allowedOrigins
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 2. Calcul de commission (/api/v2/users/invoices/commission)
|
|
177
|
+
if (req.method === 'POST' && pathname === '/api/slickpay/commission') {
|
|
178
|
+
const body = await readJsonBody(req);
|
|
179
|
+
const result = await gateway.calculateInvoiceCommission(body.amount);
|
|
180
|
+
return sendJson(req, res, 200, { ok: true, ...result }, allowedOrigins);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 3. Création ou vérification via /api/slickpay/checkout OU /api/checkout.php
|
|
184
|
+
if (pathname === '/api/slickpay/checkout' || pathname === '/api/checkout.php') {
|
|
185
|
+
if (req.method === 'GET' && urlObj.searchParams.get('action') === 'status') {
|
|
186
|
+
const invoiceId = urlObj.searchParams.get('id') || '';
|
|
187
|
+
const status = await gateway.getInvoiceStatus(invoiceId);
|
|
188
|
+
return sendJson(req, res, 200, { ok: true, ...status }, allowedOrigins);
|
|
189
|
+
}
|
|
190
|
+
if (req.method === 'POST') {
|
|
191
|
+
const body = await readJsonBody(req);
|
|
192
|
+
if (body.action === 'commission') {
|
|
193
|
+
const result = await gateway.calculateInvoiceCommission(body.amount);
|
|
194
|
+
return sendJson(req, res, 200, { ok: true, ...result }, allowedOrigins);
|
|
195
|
+
}
|
|
196
|
+
if (body.action === 'status') {
|
|
197
|
+
const status = await gateway.getInvoiceStatus(body.invoiceId || body.id);
|
|
198
|
+
return sendJson(req, res, 200, { ok: true, ...status }, allowedOrigins);
|
|
199
|
+
}
|
|
200
|
+
const session = body.shopSlug
|
|
201
|
+
? await gateway.createShopLinkSession(body.shopSlug, body, body.locale || 'fr')
|
|
202
|
+
: await gateway.createCheckoutSession(body);
|
|
203
|
+
return sendJson(req, res, 201, session, allowedOrigins);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// 4. Statut d'une facture (GET /api/slickpay/status/:id)
|
|
208
|
+
if (req.method === 'GET' && pathname.startsWith('/api/slickpay/status/')) {
|
|
209
|
+
const invoiceId = pathname.replace('/api/slickpay/status/', '');
|
|
210
|
+
const status = await gateway.getInvoiceStatus(invoiceId);
|
|
211
|
+
return sendJson(req, res, 200, { ok: true, ...status }, allowedOrigins);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// 5. Réception Webhook de paiement confirmé (authentifié par signature HMAC)
|
|
215
|
+
if (req.method === 'POST' && pathname === '/api/slickpay/webhook') {
|
|
216
|
+
const body = await readJsonBody(req);
|
|
217
|
+
const invoiceId = body.invoiceId || body.id || body.invoice_ref;
|
|
218
|
+
const signature =
|
|
219
|
+
req.headers['x-slickpay-signature'] ||
|
|
220
|
+
body.signature ||
|
|
221
|
+
body.webhook_signature ||
|
|
222
|
+
'';
|
|
223
|
+
const updated = gateway.markInvoicePaid(invoiceId, signature);
|
|
224
|
+
return sendJson(
|
|
225
|
+
req,
|
|
226
|
+
res,
|
|
227
|
+
200,
|
|
228
|
+
{ ok: true, event: 'invoice.paid', invoice: updated },
|
|
229
|
+
allowedOrigins
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 6. Page de retour après paiement (/payment-return) avec vérification réelle du statut
|
|
234
|
+
if (req.method === 'GET' && pathname === '/payment-return') {
|
|
235
|
+
const rawId =
|
|
236
|
+
urlObj.searchParams.get('invoiceId') || urlObj.searchParams.get('id') || '';
|
|
237
|
+
const safeId = String(rawId).replace(/[^a-zA-Z0-9_-]/g, '');
|
|
238
|
+
let statusLabel = 'Non vérifié';
|
|
239
|
+
if (safeId) {
|
|
240
|
+
try {
|
|
241
|
+
const st = await gateway.getInvoiceStatus(safeId);
|
|
242
|
+
statusLabel = st.status === 'paid' ? 'Payé (Confirmé)' : 'En attente de règlement';
|
|
243
|
+
} catch (_) {
|
|
244
|
+
statusLabel = 'Facture introuvable ou en attente';
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
res.writeHead(200, {
|
|
248
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
249
|
+
'X-Content-Type-Options': 'nosniff',
|
|
250
|
+
});
|
|
251
|
+
return res.end(`<!DOCTYPE html>
|
|
252
|
+
<html lang="fr">
|
|
253
|
+
<head>
|
|
254
|
+
<meta charset="UTF-8" />
|
|
255
|
+
<title>Confirmation de paiement — SlickPay Bridge</title>
|
|
256
|
+
<link rel="stylesheet" href="/playground.css" />
|
|
257
|
+
</head>
|
|
258
|
+
<body>
|
|
259
|
+
<div class="container">
|
|
260
|
+
<div class="card">
|
|
261
|
+
<h1>Retour de la passerelle de paiement</h1>
|
|
262
|
+
<p class="lead">Référence transaction : <code>${safeId || 'N/A'}</code></p>
|
|
263
|
+
<p class="lead">Statut vérifié : <strong>${statusLabel}</strong></p>
|
|
264
|
+
<p><a href="/">Retour à l'accueil</a></p>
|
|
265
|
+
</div>
|
|
266
|
+
</div>
|
|
267
|
+
</body>
|
|
268
|
+
</html>`);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// 7. Fichiers statiques sécurisés
|
|
272
|
+
const safePath = pathname === '/' || pathname === '/index.php' ? '/index.html' : pathname;
|
|
273
|
+
const ext = path.extname(safePath).toLowerCase();
|
|
274
|
+
const baseName = path.basename(safePath);
|
|
275
|
+
|
|
276
|
+
if (baseName.startsWith('.') || !ALLOWED_STATIC_EXTENSIONS[ext]) {
|
|
277
|
+
return sendJson(
|
|
278
|
+
req,
|
|
279
|
+
res,
|
|
280
|
+
404,
|
|
281
|
+
{ ok: false, error: `Ressource non disponible : ${pathname}` },
|
|
282
|
+
allowedOrigins
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const filePath = path.join(PUBLIC_DIR, path.normalize(safePath));
|
|
287
|
+
if (
|
|
288
|
+
filePath.startsWith(PUBLIC_DIR) &&
|
|
289
|
+
fs.existsSync(filePath) &&
|
|
290
|
+
fs.statSync(filePath).isFile()
|
|
291
|
+
) {
|
|
292
|
+
res.writeHead(200, {
|
|
293
|
+
'Content-Type': ALLOWED_STATIC_EXTENSIONS[ext],
|
|
294
|
+
'Access-Control-Allow-Origin': resolveCorsOrigin(req, allowedOrigins),
|
|
295
|
+
'X-Content-Type-Options': 'nosniff',
|
|
296
|
+
});
|
|
297
|
+
return fs.createReadStream(filePath).pipe(res);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return sendJson(
|
|
301
|
+
req,
|
|
302
|
+
res,
|
|
303
|
+
404,
|
|
304
|
+
{ ok: false, error: `Route introuvable : ${pathname}` },
|
|
305
|
+
allowedOrigins
|
|
306
|
+
);
|
|
307
|
+
} catch (err) {
|
|
308
|
+
const code = err.statusCode || 500;
|
|
309
|
+
return sendJson(
|
|
310
|
+
req,
|
|
311
|
+
res,
|
|
312
|
+
code,
|
|
313
|
+
{
|
|
314
|
+
ok: false,
|
|
315
|
+
error: err.message,
|
|
316
|
+
validationErrors: err.validationErrors || undefined,
|
|
317
|
+
},
|
|
318
|
+
allowedOrigins
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
return { server, gateway };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {
|
|
327
|
+
const port = Number(process.env.PORT || 3400);
|
|
328
|
+
const { server, gateway } = createGatewayServer();
|
|
329
|
+
server.listen(port, () => {
|
|
330
|
+
console.log(`[SlickPay Bridge] Serveur actif sur http://localhost:${port}`);
|
|
331
|
+
console.log(`[SlickPay Bridge] Script Widget : http://localhost:${port}/sdk/slickpay-widget.js`);
|
|
332
|
+
console.log(`[SlickPay Bridge] Mode actif : ${gateway.mode}`);
|
|
333
|
+
});
|
|
334
|
+
}
|