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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
|
/*
Spacebar: A FOSS re-implementation and extension of the Discord.com backend.
Copyright (C) 2023 Spacebar and Spacebar Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import bcrypt from "bcrypt";
import { Request, Response, Router } from "express";
import { HTTPError } from "lambert-server/HTTPError";
import { MoreThan } from "typeorm";
import { route, verifyCaptcha } from "@spacebar/api/util";
import { Invite, User, ValidRegistrationToken } from "@spacebar/database";
import { Config, FieldErrors, generateToken, IpDataClient, AbuseIpDbClient } from "@spacebar/util";
import { RegisterSchema } from "@spacebar/schemas";
import { BcryptWorkerPool } from "@spacebar/util/util/workers/bcrypt/BcryptWorkerPool";
import { Stopwatch, TimeSpan } from "@spacebar/extensions";
const router: Router = Router({ mergeParams: true });
const recentlyBlockedIps: {
[ip: string]: {
firstHit: Date;
lastHit: Date;
hits: number;
reason: string;
};
} = {};
router.post(
"/",
route({
requestBody: "RegisterSchema",
responses: {
200: { body: "TokenOnlyResponse" },
400: { body: "APIErrorOrCaptchaResponse" },
},
}),
async (req: Request, res: Response) => {
const totalSw = Stopwatch.startNew();
const incSw = Stopwatch.startNew();
const logTrace = (...data: unknown[]) => {
if (process.env.LOG_VERBOSE_TRACES !== "true") return;
console.log("[Register]", ...data, `[${totalSw.elapsed().toString()} (+${incSw.getElapsedAndReset().totalMilliseconds}ms)]`);
};
const body = req.body as RegisterSchema;
const { register, security, limits } = Config.get();
const ip = req.ip!;
// Reg tokens
// They're a one time use token that bypasses registration limits ( rates, disabled reg, etc )
let regTokenUsed = false;
if (req.get("Referrer") && req.get("Referrer")?.includes("token=")) {
// eg theyre on https://staging.spacebar.chat/register?token=whatever
const token = req.get("Referrer")?.split("token=")[1].split("&")[0];
if (token) {
const regToken = await ValidRegistrationToken.findOneOrFail({
where: { token, expires_at: MoreThan(new Date()) },
});
await regToken.remove();
regTokenUsed = true;
console.log(`[REGISTER] Registration token ${token} used for registration!`);
} else {
console.log(`[REGISTER] Invalid registration token ${token} used for registration by ${ip}!`);
}
}
// check if registration is allowed
if (!regTokenUsed && !register.allowNewRegistration) {
throw FieldErrors({
email: {
code: "REGISTRATION_DISABLED",
message: req.t("auth:register.REGISTRATION_DISABLED"),
},
});
}
// check if the user agreed to the Terms of Service
if (!body.consent) {
throw FieldErrors({
consent: {
code: "CONSENT_REQUIRED",
message: req.t("auth:register.CONSENT_REQUIRED"),
},
});
}
if (!regTokenUsed && register.disabled) {
throw FieldErrors({
email: {
code: "DISABLED",
message: "Registration is disabled on this instance",
},
});
}
if (!regTokenUsed && register.requireCaptcha && security.captcha.enabled) {
const { sitekey, service } = security.captcha;
if (!body.captcha_key) {
return res?.status(400).json({
captcha_key: ["captcha-required"],
captcha_sitekey: sitekey,
captcha_service: service,
});
}
const verify = await verifyCaptcha(body.captcha_key, ip);
if (!verify.success) {
return res.status(400).json({
captcha_key: verify["error-codes"],
captcha_sitekey: sitekey,
captcha_service: service,
});
}
}
if (!regTokenUsed && !register.allowMultipleAccounts) {
// TODO: check if fingerprint was eligible generated
const exists = await User.findOne({
where: { fingerprints: body.fingerprint },
select: { id: true },
});
if (exists) {
throw FieldErrors({
email: {
code: "EMAIL_ALREADY_REGISTERED",
message: req.t("auth:register.EMAIL_ALREADY_REGISTERED"),
},
});
}
}
logTrace("Basic checks");
//region IP checks
if (register.enableAbuseIpDb || register.enableIpData) {
const cacheBlockedIp = (ip: string, reason: string) => {
recentlyBlockedIps[ip] = {
firstHit: new Date(),
lastHit: new Date(),
hits: 0,
reason,
};
console.log(`[Register] ${ip} blocked from registration:`, reason);
};
if (!regTokenUsed && recentlyBlockedIps[ip]) {
if (new TimeSpan(recentlyBlockedIps[ip].firstHit.getTime(), new Date().getTime()).totalHours >= 24) delete recentlyBlockedIps[ip];
else {
recentlyBlockedIps[ip].lastHit = new Date();
recentlyBlockedIps[ip].hits++;
console.log(
`[Register] ${ip} blocked from registration: blocked since ${recentlyBlockedIps[ip].firstHit} with ${recentlyBlockedIps[ip].hits} hits and reason:`,
recentlyBlockedIps[ip].reason,
);
throw new HTTPError("Your IP is blocked from registration");
}
}
if (!regTokenUsed && register.enableAbuseIpDb) {
const blacklist = await AbuseIpDbClient.getBlacklist();
if (blacklist) {
const entry = blacklist.data.find((e) => e.ipAddress === ip);
if (entry && entry.abuseConfidenceScore >= register.blockAbuseIpDbAboveScore) {
cacheBlockedIp(ip, `AbuseIPDB score ${entry.abuseConfidenceScore} >= ${register.blockAbuseIpDbAboveScore} (BLACKLIST)`);
throw new HTTPError("Your IP is blocked from registration");
}
}
const checkIp = await AbuseIpDbClient.checkIpAddress(ip);
if (checkIp?.data && checkIp.data.abuseConfidenceScore >= register.blockAbuseIpDbAboveScore) {
cacheBlockedIp(ip, `AbuseIPDB score ${checkIp.data.abuseConfidenceScore} >= ${register.blockAbuseIpDbAboveScore} (CHECK)`);
throw new HTTPError("Your IP is blocked from registration");
}
}
if (!regTokenUsed && register.enableIpData) {
const ipData = await IpDataClient.getIpInfo(ip);
if (ipData) {
if (!ipData.threat) {
console.log("Invalid IPData.co response, missing threat field", ipData);
}
const categories = Object.entries(ipData.threat)
.filter(([key, value]) => key.startsWith("is_") && value === true)
.map(([key]) => key.replace("is_", ""));
const blockedCategories = new Set(categories).intersection(new Set(register.blockIpDataCoThreatTypes));
if (blockedCategories.size > 0) {
cacheBlockedIp(ip, `IPData.co threat types ${Array.from(blockedCategories).join(", ")}`);
throw new HTTPError("Your IP is blocked from registration");
}
if (ipData.asn.type && register.blockAsnTypes.includes(ipData.asn.type)) {
cacheBlockedIp(ip, `IPData.co ASN type ${ipData.asn.type} is blocked`);
throw new HTTPError("Your IP is blocked from registration");
} else if (!ipData.asn.type) {
console.log("[Register] IPData.co response missing asn.type field", ipData);
}
if (ipData.asn.asn && register.blockAsns.includes(ipData.asn.asn)) {
cacheBlockedIp(ip, `IPData.co ASN ${ipData.asn.name} is blocked`);
throw new HTTPError("Your IP is blocked from registration");
} else if (!ipData.asn.asn) {
console.log("[Register] IPData.co response missing asn.asn field", ipData);
}
}
}
logTrace("IP checks");
}
//endregion
// TODO: gift_code_sku_id?
// TODO: check password strength
const email = body.email;
if (email) {
// replace all dots and chars after +, if its a gmail.com email
if (!email) {
throw FieldErrors({
email: {
code: "INVALID_EMAIL",
message: req?.t("auth:register.INVALID_EMAIL"),
},
});
}
// check if there is already an account with this email
const exists = await User.findOne({ where: { email: email } });
if (exists) {
throw FieldErrors({
email: {
code: "EMAIL_ALREADY_REGISTERED",
message: req.t("auth:register.EMAIL_ALREADY_REGISTERED"),
},
});
}
} else if (register.email.required) {
throw FieldErrors({
email: {
code: "BASE_TYPE_REQUIRED",
message: req.t("common:field.BASE_TYPE_REQUIRED"),
},
});
}
logTrace("Email checks");
if (register.dateOfBirth.required && !body.date_of_birth) {
throw FieldErrors({
date_of_birth: {
code: "BASE_TYPE_REQUIRED",
message: req.t("common:field.BASE_TYPE_REQUIRED"),
},
});
} else if (register.dateOfBirth.required && register.dateOfBirth.minimum) {
const minimum = new Date();
minimum.setFullYear(minimum.getFullYear() - register.dateOfBirth.minimum);
let parsedDob;
try {
parsedDob = new Date(body.date_of_birth as Date);
if (isNaN(parsedDob.getTime())) {
throw new Error("Invalid date");
}
} catch (e) {
throw FieldErrors({
date_of_birth: {
code: "DATE_OF_BIRTH_INVALID",
message: req.t("auth:register.DATE_OF_BIRTH_INVALID"),
},
});
}
// higher is younger
if (parsedDob > minimum) {
throw FieldErrors({
date_of_birth: {
code: "DATE_OF_BIRTH_UNDERAGE",
message: req.t("auth:register.DATE_OF_BIRTH_UNDERAGE", {
years: register.dateOfBirth.minimum,
}),
},
});
}
}
if (body.password) {
const min = register.password.minLength ?? 8;
if (body.password.length < min) {
throw FieldErrors({
password: {
code: "PASSWORD_REQUIREMENTS_MIN_LENGTH",
message: req.t("auth:register.PASSWORD_REQUIREMENTS_MIN_LENGTH", { min: min }),
},
});
}
// the salt is saved in the password refer to bcrypt docs
// body.password = await BcryptWorkerPool.GetBcryptWorker().hashPassword(body.password, 12);
body.password = await bcrypt.hash(body.password, 12);
} else if (register.password.required) {
throw FieldErrors({
password: {
code: "BASE_TYPE_REQUIRED",
message: req.t("common:field.BASE_TYPE_REQUIRED"),
},
});
}
logTrace("Password checks");
if (!regTokenUsed && !body.invite && (register.requireInvite || (register.guestsRequireInvite && !register.email))) {
// require invite to register -> e.g. for organizations to send invites to their employees
throw FieldErrors({
email: {
code: "INVITE_ONLY",
message: req.t("auth:register.INVITE_ONLY"),
},
});
}
if (
!regTokenUsed &&
limits.absoluteRate.register.enabled &&
(await User.count({
where: {
created_at: MoreThan(new Date(Date.now() - limits.absoluteRate.register.window)),
},
})) >= limits.absoluteRate.register.limit
) {
console.log(`Global register ratelimit exceeded for ${req.ip}, ${req.body.username}, ${req.body.invite || "No invite given"}`);
throw FieldErrors({
email: {
code: "TOO_MANY_REGISTRATIONS",
message: req.t("auth:register.TOO_MANY_REGISTRATIONS"),
},
});
}
logTrace("Absolute register rate checks");
const { maxUsername } = Config.get().limits.user;
if (body.username.length > maxUsername) {
throw FieldErrors({
username: {
code: "BASE_TYPE_BAD_LENGTH",
message: `Must be between 2 and ${maxUsername} in length.`,
},
});
}
const user = await User.register({ ...body, req });
logTrace("Register user");
if (body.invite) {
// await to fail if the invite doesn't exist (necessary for requireInvite to work properly) (username only signups are possible)
await Invite.joinGuild(user.id, body.invite);
logTrace("Accept invite");
}
res.json({ token: await generateToken(user.id) });
logTrace("Generate token");
},
);
export default router;
/**
* POST /auth/register
* @argument { "fingerprint":"805826570869932034.wR8vi8lGlFBJerErO9LG5NViJFw", "email":"qo8etzvaf@gmail.com", "username":"qp39gr98", "password":"wtp9gep9gw", "invite":null, "consent":true, "date_of_birth":"2000-04-04", "gift_code_sku_id":null, "captcha_key":null}
*
* Field Error
* @returns { "code": 50035, "errors": { "consent": { "_errors": [{ "code": "CONSENT_REQUIRED", "message": "You must agree to Discord's Terms of Service and Privacy Policy." }]}}, "message": "Invalid Form Body"}
*
* Success 200:
* @returns {token: "OMITTED"}
*/
|