-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
147 lines (128 loc) · 4.56 KB
/
index.js
File metadata and controls
147 lines (128 loc) · 4.56 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require('express');
const morgan = require("morgan");
const { createProxyMiddleware } = require('http-proxy-middleware');
const { login, getKeys, revokeKey, createKey, getCookie, getIP } = require('./utils');
const app = express();
app.disable('x-powered-by');
const PORT = process.env.PORT || 5000;
const HOST = process.env.HOST || "0.0.0.0";
const API_SERVICE_URL = process.env.API_SERVICE_URL || "https://api.clashofclans.com/v1";
const DOMAIN = process.env.DOMAIN || "http://localhost:5000";
let ApiKey = null;
app.use(morgan('dev'));
async function generateApiKey() {
try {
const { email, password, game } = {
email: process.env.EMAIL,
password: process.env.PASSWORD,
game: process.env.GAME || 'clashofclans'
};
if (!email || !password) {
throw new Error('EMAIL and PASSWORD environment variables are required');
}
const whitelist = [];
const baseUrl = `https://developer.${game}.com/api`;
const loginResponse = await login({ baseUrl, email, password });
if (loginResponse?.error) {
throw new Error(loginResponse.error || 'Login failed');
}
const cookie = await getCookie(loginResponse);
const savedKeys = await getKeys({ baseUrl, cookie });
if (!Array.isArray(savedKeys)) {
throw new Error('Unexpected response from getKeys');
}
const ip = await getIP();
const keyWithSameIP = savedKeys.find(key => key.cidrRanges.includes(ip));
let validApiKey;
if (keyWithSameIP) {
validApiKey = keyWithSameIP;
} else {
if (savedKeys.length === 10) {
const keyToRevoke = savedKeys.find(key => !whitelist.includes(key.name));
console.log('Revoking key:', keyToRevoke);
await revokeKey({ baseUrl, cookie, keyToRevoke });
}
const newKey = await createKey({ baseUrl, cookie, ips: [ip] });
if (newKey?.error) {
throw new Error(newKey.error || 'Failed to create new key');
}
validApiKey = newKey.key;
}
return {
name: validApiKey.name,
description: validApiKey.description,
ipRange: validApiKey.cidrRanges,
key: validApiKey.key
};
} catch (error) {
console.error('Error in generateApiKey:', error);
throw error;
}
}
// Endpoint info
app.get('/info', (req, res) => {
res.send(`The Clash of Clans API provides near real time access to game related data. ${DOMAIN}/clash_api/players/%2390CL0CYC8 or ${DOMAIN}/update_api`);
});
// Endpoint update_api
app.get('/update_api', async (req, res) => {
try {
const result = await generateApiKey();
ApiKey = result.key;
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// updateApiKey call generateApiKey
async function updateApiKey() {
try {
console.log('Getting API key');
const result = await generateApiKey();
if (result.key) {
ApiKey = result.key;
// Do not log full API key; log masked value for traceability
console.log('API Key updated successfully.');
return true;
}
console.error('Failed to update API key: No key returned');
return false;
} catch (error) {
console.error('Error in updateApiKey:', error);
return false;
}
}
// Middleware
const clashAPIMiddleware = async (req, res, next) => {
try {
if (!ApiKey) {
const updateSuccess = await updateApiKey();
if (!updateSuccess) {
return res.status(500).json({ error: 'Failed to update API key' });
}
}
req.headers.authorization = `Bearer ${ApiKey}`;
next();
} catch (error) {
console.error('Error in clashAPIMiddleware:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Proxy Middleware
const proxyMiddleware = createProxyMiddleware({
target: API_SERVICE_URL,
changeOrigin: true,
pathRewrite: { '^/clash_api': '' },
on: {
proxyRes: async (proxyRes, req, res) => {
if (proxyRes.statusCode === 403) {
await updateApiKey();
} else {
console.log('Proxy request completed');
}
}
}
});
app.use('/clash_api', clashAPIMiddleware, proxyMiddleware);
app.listen(PORT, HOST, () => {
console.log(`Starting Proxy at ${HOST}:${PORT}`);
});