-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecureApi.js
More file actions
79 lines (67 loc) · 1.79 KB
/
Copy pathsecureApi.js
File metadata and controls
79 lines (67 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import axios from "axios";
import dotenv from 'dotenv';
import crypto from "crypto";
import http from "http";
import https from "https";
import canonicalPayload from "./utils/canonicalPayload.js";
dotenv.config();
const API_URL = process.env.API_URL;
const BOT_SECRET = process.env.BOT_SECRET;
if (!API_URL || !BOT_SECRET) {
throw new Error("Missing API_URL or BOT_SECRET in env");
}
/* ---------------- SIGNATURE ---------------- */
const signData = (data = {}) => {
const canonical = canonicalPayload(data);
return crypto
.createHmac("sha256", BOT_SECRET)
.update(JSON.stringify(canonical))
.digest("hex");
};
/* ---------------- AXIOS INSTANCE ---------------- */
const apiClient = axios.create({
baseURL: API_URL,
timeout: 8000,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
});
/* ---------------- POST ---------------- */
const axiosPost = async (url, data = {}) => {
try {
const signature = signData(data);
const res = await apiClient.post(url, data, {
headers: {
"Content-Type": "application/json",
"x-signature": signature,
},
});
return res.data;
} catch (err) {
console.error(
"🔐 securePost error:",
err.response?.data || err.message
);
throw err;
}
};
/* ---------------- GET ---------------- */
const axiosGet = async (url, params = {}) => {
try {
const signature = signData(params);
const res = await apiClient.get(url, {
params,
headers: {
"Content-Type": "application/json",
"x-signature": signature,
},
});
return res.data;
} catch (err) {
console.error(
"🔐 secureGet error:",
err.response?.data || err.message
);
throw err;
}
};
export { axiosPost, axiosGet };