This commit is contained in:
Madeline
2022-09-26 22:41:21 +10:00
parent fcc0884e36
commit 99ee7e9400
280 changed files with 6800 additions and 3908 deletions
+9 -5
View File
@@ -3,11 +3,15 @@ import { route } from "@fosscord/api";
import { getIpAdress, IPAnalysis } from "@fosscord/api";
const router = Router();
router.get("/",route({}), async (req: Request, res: Response) => {
//TODO
//Note: It's most likely related to legal. At the moment Discord hasn't finished this too
const country_code = (await IPAnalysis(getIpAdress(req))).country_code;
res.json({ consent_required: false, country_code: country_code, promotional_email_opt_in: { required: true, pre_checked: false}});
router.get("/", route({}), async (req: Request, res: Response) => {
//TODO
//Note: It's most likely related to legal. At the moment Discord hasn't finished this too
const country_code = (await IPAnalysis(getIpAdress(req))).country_code;
res.json({
consent_required: false,
country_code: country_code,
promotional_email_opt_in: { required: true, pre_checked: false },
});
});
export default router;
+106 -63
View File
@@ -1,84 +1,127 @@
import { Request, Response, Router } from "express";
import { route, getIpAdress, verifyCaptcha } from "@fosscord/api";
import bcrypt from "bcrypt";
import { Config, User, generateToken, adjustEmail, FieldErrors, LoginSchema } from "@fosscord/util";
import {
Config,
User,
generateToken,
adjustEmail,
FieldErrors,
LoginSchema,
} from "@fosscord/util";
import crypto from "crypto";
const router: Router = Router();
export default router;
router.post("/", route({ body: "LoginSchema" }), async (req: Request, res: Response) => {
const { login, password, captcha_key, undelete } = req.body as LoginSchema;
const email = adjustEmail(login);
console.log("login", email);
router.post(
"/",
route({ body: "LoginSchema" }),
async (req: Request, res: Response) => {
const { login, password, captcha_key, undelete } =
req.body as LoginSchema;
const email = adjustEmail(login);
console.log("login", email);
const config = Config.get();
const config = Config.get();
if (config.login.requireCaptcha && config.security.captcha.enabled) {
const { sitekey, service } = config.security.captcha;
if (!captcha_key) {
return res.status(400).json({
captcha_key: ["captcha-required"],
captcha_sitekey: sitekey,
captcha_service: service
if (config.login.requireCaptcha && config.security.captcha.enabled) {
const { sitekey, service } = config.security.captcha;
if (!captcha_key) {
return res.status(400).json({
captcha_key: ["captcha-required"],
captcha_sitekey: sitekey,
captcha_service: service,
});
}
const ip = getIpAdress(req);
const verify = await verifyCaptcha(captcha_key, ip);
if (!verify.success) {
return res.status(400).json({
captcha_key: verify["error-codes"],
captcha_sitekey: sitekey,
captcha_service: service,
});
}
}
const user = await User.findOneOrFail({
where: [{ phone: login }, { email: login }],
select: [
"data",
"id",
"disabled",
"deleted",
"settings",
"totp_secret",
"mfa_enabled",
],
}).catch((e) => {
throw FieldErrors({
login: {
message: req.t("auth:login.INVALID_LOGIN"),
code: "INVALID_LOGIN",
},
});
});
if (undelete) {
// undelete refers to un'disable' here
if (user.disabled)
await User.update({ id: user.id }, { disabled: false });
if (user.deleted)
await User.update({ id: user.id }, { deleted: false });
} else {
if (user.deleted)
return res.status(400).json({
message: "This account is scheduled for deletion.",
code: 20011,
});
if (user.disabled)
return res.status(400).json({
message: req.t("auth:login.ACCOUNT_DISABLED"),
code: 20013,
});
}
// the salt is saved in the password refer to bcrypt docs
const same_password = await bcrypt.compare(
password,
user.data.hash || "",
);
if (!same_password) {
throw FieldErrors({
password: {
message: req.t("auth:login.INVALID_PASSWORD"),
code: "INVALID_PASSWORD",
},
});
}
const ip = getIpAdress(req);
const verify = await verifyCaptcha(captcha_key, ip);
if (!verify.success) {
return res.status(400).json({
captcha_key: verify["error-codes"],
captcha_sitekey: sitekey,
captcha_service: service
if (user.mfa_enabled) {
// TODO: This is not a discord.com ticket. I'm not sure what it is but I'm lazy
const ticket = crypto.randomBytes(40).toString("hex");
await User.update({ id: user.id }, { totp_last_ticket: ticket });
return res.json({
ticket: ticket,
mfa: true,
sms: false, // TODO
token: null,
});
}
}
const user = await User.findOneOrFail({
where: [{ phone: login }, { email: login }],
select: ["data", "id", "disabled", "deleted", "settings", "totp_secret", "mfa_enabled"]
}).catch((e) => {
throw FieldErrors({ login: { message: req.t("auth:login.INVALID_LOGIN"), code: "INVALID_LOGIN" } });
});
const token = await generateToken(user.id);
if (undelete) {
// undelete refers to un'disable' here
if (user.disabled) await User.update({ id: user.id }, { disabled: false });
if (user.deleted) await User.update({ id: user.id }, { deleted: false });
} else {
if (user.deleted) return res.status(400).json({ message: "This account is scheduled for deletion.", code: 20011 });
if (user.disabled) return res.status(400).json({ message: req.t("auth:login.ACCOUNT_DISABLED"), code: 20013 });
}
// Notice this will have a different token structure, than discord
// Discord header is just the user id as string, which is not possible with npm-jsonwebtoken package
// https://user-images.githubusercontent.com/6506416/81051916-dd8c9900-8ec2-11ea-8794-daf12d6f31f0.png
// the salt is saved in the password refer to bcrypt docs
const same_password = await bcrypt.compare(password, user.data.hash || "");
if (!same_password) {
throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } });
}
if (user.mfa_enabled) {
// TODO: This is not a discord.com ticket. I'm not sure what it is but I'm lazy
const ticket = crypto.randomBytes(40).toString("hex");
await User.update({ id: user.id }, { totp_last_ticket: ticket });
return res.json({
ticket: ticket,
mfa: true,
sms: false, // TODO
token: null,
})
}
const token = await generateToken(user.id);
// Notice this will have a different token structure, than discord
// Discord header is just the user id as string, which is not possible with npm-jsonwebtoken package
// https://user-images.githubusercontent.com/6506416/81051916-dd8c9900-8ec2-11ea-8794-daf12d6f31f0.png
res.json({ token, settings: user.settings });
});
res.json({ token, settings: user.settings });
},
);
/**
* POST /auth/login
+3 -2
View File
@@ -10,7 +10,8 @@ router.post("/", route({}), async (req: Request, res: Response) => {
} else {
delete req.body.provider;
delete req.body.voip_provider;
if (Object.keys(req.body).length != 0) console.log(`[LOGOUT]: Extra fields sent in logout!`, req.body);
if (Object.keys(req.body).length != 0)
console.log(`[LOGOUT]: Extra fields sent in logout!`, req.body);
}
res.status(204).send();
});
});
+38 -35
View File
@@ -5,45 +5,48 @@ import { verifyToken } from "node-2fa";
import { HTTPError } from "lambert-server";
const router = Router();
router.post("/", route({ body: "TotpSchema" }), async (req: Request, res: Response) => {
const { code, ticket, gift_code_sku_id, login_source } = req.body as TotpSchema;
router.post(
"/",
route({ body: "TotpSchema" }),
async (req: Request, res: Response) => {
const { code, ticket, gift_code_sku_id, login_source } =
req.body as TotpSchema;
const user = await User.findOneOrFail({
where: {
totp_last_ticket: ticket,
},
select: [
"id",
"totp_secret",
"settings",
],
});
const user = await User.findOneOrFail({
where: {
totp_last_ticket: ticket,
},
select: ["id", "totp_secret", "settings"],
});
const backup = await BackupCode.findOne({
where: {
code: code,
expired: false,
consumed: false,
user: { id: user.id }
const backup = await BackupCode.findOne({
where: {
code: code,
expired: false,
consumed: false,
user: { id: user.id },
},
});
if (!backup) {
const ret = verifyToken(user.totp_secret!, code);
if (!ret || ret.delta != 0)
throw new HTTPError(
req.t("auth:login.INVALID_TOTP_CODE"),
60008,
);
} else {
backup.consumed = true;
await backup.save();
}
});
if (!backup) {
const ret = verifyToken(user.totp_secret!, code);
if (!ret || ret.delta != 0)
throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008);
}
else {
backup.consumed = true;
await backup.save();
}
await User.update({ id: user.id }, { totp_last_ticket: "" });
await User.update({ id: user.id }, { totp_last_ticket: "" });
return res.json({
token: await generateToken(user.id),
user_settings: user.settings,
});
});
return res.json({
token: await generateToken(user.id),
user_settings: user.settings,
});
},
);
export default router;
+180 -121
View File
@@ -1,156 +1,215 @@
import { Request, Response, Router } from "express";
import { Config, generateToken, Invite, FieldErrors, User, adjustEmail, RegisterSchema } from "@fosscord/util";
import { route, getIpAdress, IPAnalysis, isProxy, verifyCaptcha } from "@fosscord/api";
import {
Config,
generateToken,
Invite,
FieldErrors,
User,
adjustEmail,
RegisterSchema,
} from "@fosscord/util";
import {
route,
getIpAdress,
IPAnalysis,
isProxy,
verifyCaptcha,
} from "@fosscord/api";
import bcrypt from "bcrypt";
import { HTTPError } from "lambert-server";
const router: Router = Router();
router.post("/", route({ body: "RegisterSchema" }), async (req: Request, res: Response) => {
const body = req.body as RegisterSchema;
const { register, security } = Config.get();
const ip = getIpAdress(req);
router.post(
"/",
route({ body: "RegisterSchema" }),
async (req: Request, res: Response) => {
const body = req.body as RegisterSchema;
const { register, security } = Config.get();
const ip = getIpAdress(req);
// email will be slightly modified version of the user supplied email -> e.g. protection against GMail Trick
let email = adjustEmail(body.email);
// email will be slightly modified version of the user supplied email -> e.g. protection against GMail Trick
let email = adjustEmail(body.email);
// check if registration is allowed
if (!register.allowNewRegistration) {
throw FieldErrors({
email: { code: "REGISTRATION_DISABLED", message: req.t("auth:register.REGISTRATION_DISABLED") }
});
}
// check if registration is allowed
if (!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") }
});
}
// 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 (register.disabled) {
throw FieldErrors({
email: {
code: "DISABLED",
message: "registration is disabled on this instance"
if (register.disabled) {
throw FieldErrors({
email: {
code: "DISABLED",
message: "registration is disabled on this instance",
},
});
}
if (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,
});
}
});
}
if (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,
});
}
}
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 (!register.allowMultipleAccounts) {
// TODO: check if fingerprint was eligible generated
const exists = await User.findOne({
where: { fingerprints: body.fingerprint },
select: ["id"],
});
if (exists) {
throw FieldErrors({
email: {
code: "EMAIL_ALREADY_REGISTERED",
message: req.t(
"auth:register.EMAIL_ALREADY_REGISTERED",
),
},
});
}
}
}
if (!register.allowMultipleAccounts) {
// TODO: check if fingerprint was eligible generated
const exists = await User.findOne({ where: { fingerprints: body.fingerprint }, select: ["id"] });
if (register.blockProxies) {
if (isProxy(await IPAnalysis(ip))) {
console.log(`proxy ${ip} blocked from registration`);
throw new HTTPError("Your IP is blocked from registration");
}
}
if (exists) {
// TODO: gift_code_sku_id?
// TODO: check password strength
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: "EMAIL_ALREADY_REGISTERED",
message: req.t("auth:register.EMAIL_ALREADY_REGISTERED")
}
code: "BASE_TYPE_REQUIRED",
message: req.t("common:field.BASE_TYPE_REQUIRED"),
},
});
}
}
if (register.blockProxies) {
if (isProxy(await IPAnalysis(ip))) {
console.log(`proxy ${ip} blocked from registration`);
throw new HTTPError("Your IP is blocked from registration");
}
}
// TODO: gift_code_sku_id?
// TODO: check password strength
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") }
});
}
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);
body.date_of_birth = new Date(body.date_of_birth as Date);
// higher is younger
if (body.date_of_birth > minimum) {
if (register.dateOfBirth.required && !body.date_of_birth) {
throw FieldErrors({
date_of_birth: {
code: "DATE_OF_BIRTH_UNDERAGE",
message: req.t("auth:register.DATE_OF_BIRTH_UNDERAGE", { years: register.dateOfBirth.minimum })
}
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,
);
body.date_of_birth = new Date(body.date_of_birth as Date);
// higher is younger
if (body.date_of_birth > 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) {
// the salt is saved in the password refer to bcrypt docs
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"),
},
});
}
}
if (body.password) {
// the salt is saved in the password refer to bcrypt docs
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") }
});
}
if (
!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 (!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") }
});
}
const user = await User.register({ ...body, req });
const user = await User.register({ ...body, req });
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);
}
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);
}
console.log("register", body.email, body.username, ip);
console.log("register", body.email, body.username, ip);
return res.json({ token: await generateToken(user.id) });
});
return res.json({ token: await generateToken(user.id) });
},
);
export default router;
@@ -4,19 +4,31 @@ import { FieldErrors, User, BackupCodesChallengeSchema } from "@fosscord/util";
import bcrypt from "bcrypt";
const router = Router();
router.post("/", route({ body: "BackupCodesChallengeSchema" }), async (req: Request, res: Response) => {
const { password } = req.body as BackupCodesChallengeSchema;
router.post(
"/",
route({ body: "BackupCodesChallengeSchema" }),
async (req: Request, res: Response) => {
const { password } = req.body as BackupCodesChallengeSchema;
const user = await User.findOneOrFail({ where: { id: req.user_id }, select: ["data"] });
const user = await User.findOneOrFail({
where: { id: req.user_id },
select: ["data"],
});
if (!await bcrypt.compare(password, user.data.hash || "")) {
throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } });
}
if (!(await bcrypt.compare(password, user.data.hash || ""))) {
throw FieldErrors({
password: {
message: req.t("auth:login.INVALID_PASSWORD"),
code: "INVALID_PASSWORD",
},
});
}
return res.json({
nonce: "NoncePlaceholder",
regenerate_nonce: "RegenNoncePlaceholder",
});
});
return res.json({
nonce: "NoncePlaceholder",
regenerate_nonce: "RegenNoncePlaceholder",
});
},
);
export default router;