-
-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathindex.ts
More file actions
249 lines (217 loc) · 7.54 KB
/
index.ts
File metadata and controls
249 lines (217 loc) · 7.54 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
import path from 'path';
import fs from 'fs';
const app = express();
const PORT = 3000;
// @note trust proxy - set to number of proxies in front of app
app.set('trust proxy', 1);
// @note middleware setup
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// @note rate limiter - 50 requests per minute
const limiter = rateLimit({
windowMs: 60_000,
max: 50,
standardHeaders: true,
legacyHeaders: false,
validate: { trustProxy: false, xForwardedForHeader: false },
});
app.use(limiter);
// @note static files from public folder
app.use(express.static(path.join(process.cwd(), 'public')));
// @note request logging middleware
app.use((req: Request, _res: Response, next: NextFunction) => {
const clientIp =
(req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() ||
req.headers['x-real-ip'] ||
req.socket.remoteAddress ||
'unknown';
console.log(
`[REQ] ${req.method} ${req.path} → ${clientIp} | ${_res.statusCode}`,
);
next();
});
// @note root endpoint
app.get('/', (_req: Request, res: Response) => {
res.send('Hello, world!');
});
/**
* @note dashboard endpoint - serves login HTML page with client data
* @param req - express request with optional body data
* @param res - express response
*/
app.all('/player/login/dashboard', async (req: Request, res: Response) => {
const body = req.body;
let clientData = '';
// @note body comes as { "key1|val1\nkey2|val2\n...": "" }
// @note the actual data is in the first key, pipe-delimited with \n separators
if (body && typeof body === 'object' && Object.keys(body).length > 0) {
clientData = Object.keys(body)[0];
}
// @note convert clientData to base64 string without JSON quotes
const encodedClientData = Buffer.from(clientData).toString('base64');
// @note read dashboard template and replace placeholder
const templatePath = path.join(process.cwd(), 'template', 'dashboard.html');
const templateContent = fs.readFileSync(templatePath, 'utf-8');
const htmlContent = templateContent.replace('{{ data }}', encodedClientData);
res.setHeader('Content-Type', 'text/html');
res.send(htmlContent);
});
/**
* @note validate login endpoint - validates GrowID credentials
* @param req - express request with growId, password, _token
* @param res - express response with token
*/
app.all(
'/player/growid/login/validate',
async (req: Request, res: Response) => {
try {
const formData = req.body as Record<string, string>;
const _token = formData._token;
const growId = formData.growId;
const password = formData.password;
const email = formData.email;
let token = '';
if (email) {
token = Buffer.from(
`_token=${_token}&growId=${growId}&password=${password}&email=${email}®=1`,
).toString('base64');
} else {
token = Buffer.from(
`_token=${_token}&growId=${growId}&password=${password}®=0`,
).toString('base64');
}
res.send(
JSON.stringify({
status: 'success',
message: 'Account Validated.',
token,
url: '',
accountType: 'growtopia',
}),
);
} catch (error) {
console.log(`[ERROR]: ${error}`);
res.status(500).json({
status: 'error',
message: 'Internal Server Error',
});
}
},
);
/**
* @note first checktoken endpoint - redirects to validate endpoint
* @param req - express request with refreshToken and clientData
* @param res - express response with updated token
*/
app.all('/player/growid/checktoken', async (_req: Request, res: Response) => {
return res.redirect(307, '/player/growid/validate/checktoken');
});
/**
* @note second checktoken endpoint - validates token and returns updated token
* @param req - express request with refreshToken and clientData
* @param res - express response with updated token
*/
app.all(
'/player/growid/validate/checktoken',
async (req: Request, res: Response) => {
try {
let refreshToken: string | undefined;
let clientData: string | undefined;
let source = 'empty';
const contentType = req.headers['content-type'] || '';
if (typeof req.body === 'object' && req.body !== null) {
const formData = req.body as Record<string, string>;
if ('refreshToken' in formData || 'clientData' in formData) {
refreshToken = formData.refreshToken;
clientData = formData.clientData;
source = contentType.includes('application/json')
? 'json/object'
: 'form-urlencoded';
} else if (Object.keys(formData).length === 1) {
const rawPayload = Object.keys(formData)[0];
const params = new URLSearchParams(rawPayload);
refreshToken = params.get('refreshToken') || undefined;
clientData = params.get('clientData') || undefined;
if (refreshToken || clientData) {
source = 'single-key-form-payload';
}
}
} else if (typeof req.body === 'string' && req.body.length > 0) {
const params = new URLSearchParams(req.body);
refreshToken = params.get('refreshToken') || undefined;
clientData = params.get('clientData') || undefined;
source = 'string/body-parser';
}
if (
(!refreshToken || !clientData) &&
req.readable &&
!req.readableEnded
) {
const rawBody = await new Promise<string>((resolve, reject) => {
let rawPayload = '';
req.on('data', (chunk: Buffer | string) => {
rawPayload += chunk.toString();
});
req.on('end', () => resolve(rawPayload));
req.on('error', reject);
});
if (rawBody) {
const params = new URLSearchParams(rawBody);
refreshToken = params.get('refreshToken') || refreshToken;
clientData = params.get('clientData') || clientData;
if (refreshToken || clientData) {
source = 'raw-stream';
}
}
}
console.log(`[CHECKTOKEN] Parsed as ${source}`);
if (!refreshToken || !clientData) {
console.log(`[ERROR]: Missing refreshToken or clientData`);
res.status(200).json({
status: 'error',
message: 'Missing refreshToken or clientData',
});
return;
}
let decodedRefreshToken = Buffer.from(refreshToken, 'base64').toString(
'utf-8',
);
// @note remove ®=0/1 from decodedRefreshToken if available
if (decodedRefreshToken.includes('®=0')) {
decodedRefreshToken = decodedRefreshToken.replace('®=0', '');
} else if (decodedRefreshToken.includes('®=1')) {
decodedRefreshToken = decodedRefreshToken.replace('®=1', '');
}
const token = Buffer.from(
decodedRefreshToken.replace(
/(_token=)[^&]*/,
`$1${Buffer.from(clientData).toString('base64')}`,
),
).toString('base64');
res.send(
JSON.stringify({
status: 'success',
message: 'Account Validated.',
token,
url: '',
accountType: 'growtopia',
accountAge: 2,
}),
);
} catch (error) {
console.log(`[ERROR]: ${error}`);
res.status(200).json({
status: 'error',
message: 'Internal Server Error',
});
}
},
);
app.listen(PORT, () => {
console.log(`[SERVER] Running on http://localhost:${PORT}`);
});
export default app;