✨ use new config
This commit is contained in:
parent
e1f0eb3c2a
commit
8f87546aeb
4
.env.example
Normal file
4
.env.example
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
MONGO_URL=mongodb://localhost/fosscord
|
||||||
|
PORT=3001
|
||||||
|
PRODUCTION=TRUE
|
||||||
|
THREADS=# automatically use all available cores, only available if production = true
|
@ -18,6 +18,7 @@
|
|||||||
MEDIA_PROXY_ENDPOINT: "https://media.discordapp.net",
|
MEDIA_PROXY_ENDPOINT: "https://media.discordapp.net",
|
||||||
WIDGET_ENDPOINT: "//discord.com/widget",
|
WIDGET_ENDPOINT: "//discord.com/widget",
|
||||||
INVITE_HOST: "discord.gg",
|
INVITE_HOST: "discord.gg",
|
||||||
|
|
||||||
GUILD_TEMPLATE_HOST: "discord.new",
|
GUILD_TEMPLATE_HOST: "discord.new",
|
||||||
GIFT_CODE_HOST: "discord.gift",
|
GIFT_CODE_HOST: "discord.gift",
|
||||||
RELEASE_CHANNEL: "stable",
|
RELEASE_CHANNEL: "stable",
|
||||||
@ -32,10 +33,8 @@
|
|||||||
MIGRATION_SOURCE_ORIGIN: "https://discordapp.com",
|
MIGRATION_SOURCE_ORIGIN: "https://discordapp.com",
|
||||||
MIGRATION_DESTINATION_ORIGIN: "https://discord.com",
|
MIGRATION_DESTINATION_ORIGIN: "https://discord.com",
|
||||||
HTML_TIMESTAMP: Date.now(),
|
HTML_TIMESTAMP: Date.now(),
|
||||||
ALGOLIA_KEY: "aca0d7082e4e63af5ba5917d5e96bed0",
|
ALGOLIA_KEY: "aca0d7082e4e63af5ba5917d5e96bed0"
|
||||||
};
|
};
|
||||||
</script>
|
|
||||||
<script>
|
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
"DeveloperOptionsStore",
|
"DeveloperOptionsStore",
|
||||||
`{"trace":false,"canary":false,"logGatewayEvents":true,"logOverlayEvents":false,"logAnalyticsEvents":false,"sourceMapsEnabled":false,"axeEnabled":false}`
|
`{"trace":false,"canary":false,"logGatewayEvents":true,"logOverlayEvents":false,"logAnalyticsEvents":false,"sourceMapsEnabled":false,"axeEnabled":false}`
|
||||||
|
25
package-lock.json
generated
25
package-lock.json
generated
@ -1740,18 +1740,6 @@
|
|||||||
"url": "https://github.com/sponsors/epoberezkin"
|
"url": "https://github.com/sponsors/epoberezkin"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/0x/node_modules/debug": {
|
|
||||||
"version": "4.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
|
|
||||||
"integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"ms": "2.1.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/0x/node_modules/json-schema-traverse": {
|
"node_modules/0x/node_modules/json-schema-traverse": {
|
||||||
"version": "0.4.1",
|
"version": "0.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||||
@ -13719,15 +13707,6 @@
|
|||||||
"uri-js": "^4.2.2"
|
"uri-js": "^4.2.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"debug": {
|
|
||||||
"version": "4.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
|
|
||||||
"integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
|
|
||||||
"dev": true,
|
|
||||||
"requires": {
|
|
||||||
"ms": "2.1.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"json-schema-traverse": {
|
"json-schema-traverse": {
|
||||||
"version": "0.4.1",
|
"version": "0.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||||
@ -13830,7 +13809,9 @@
|
|||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.0.tgz",
|
||||||
"integrity": "sha512-USH2jBb+C/hIpwD2iRjp0pe0k+MvzG0mlSn/FIdCgQhUb9ALPRjt2KIQdfZDS9r0ZIeUAg7gOu9KL0PFqGqr5Q==",
|
"integrity": "sha512-USH2jBb+C/hIpwD2iRjp0pe0k+MvzG0mlSn/FIdCgQhUb9ALPRjt2KIQdfZDS9r0ZIeUAg7gOu9KL0PFqGqr5Q==",
|
||||||
"requires": {}
|
"requires": {
|
||||||
|
"ajv": "^8.0.0"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"ansi-escapes": {
|
"ansi-escapes": {
|
||||||
"version": "4.3.2",
|
"version": "4.3.2",
|
||||||
|
@ -3,16 +3,16 @@ import fs from "fs/promises";
|
|||||||
import { Connection } from "mongoose";
|
import { Connection } from "mongoose";
|
||||||
import { Server, ServerOptions } from "lambert-server";
|
import { Server, ServerOptions } from "lambert-server";
|
||||||
import { Authentication, CORS, GlobalRateLimit } from "./middlewares/";
|
import { Authentication, CORS, GlobalRateLimit } from "./middlewares/";
|
||||||
import * as Config from "./util/Config";
|
import { Config, db } from "@fosscord/server-util";
|
||||||
import { db } from "@fosscord/server-util";
|
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import i18nextMiddleware, { I18next } from "i18next-http-middleware";
|
import i18nextMiddleware, { I18next } from "i18next-http-middleware";
|
||||||
import i18nextBackend from "i18next-node-fs-backend";
|
import i18nextBackend from "i18next-node-fs-backend";
|
||||||
import { ErrorHandler } from "./middlewares/ErrorHandler";
|
import { ErrorHandler } from "./middlewares/ErrorHandler";
|
||||||
import { BodyParser } from "./middlewares/BodyParser";
|
import { BodyParser } from "./middlewares/BodyParser";
|
||||||
import { Router } from "express";
|
import express, { Router } from "express";
|
||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
import mongoose from "mongoose";
|
import mongoose from "mongoose";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
// this will return the new updated document for findOneAndUpdate
|
// this will return the new updated document for findOneAndUpdate
|
||||||
mongoose.set("returnOriginal", false); // https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndUpdate
|
mongoose.set("returnOriginal", false); // https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndUpdate
|
||||||
@ -55,14 +55,14 @@ export class FosscordServer extends Server {
|
|||||||
await (db as Promise<Connection>);
|
await (db as Promise<Connection>);
|
||||||
await this.setupSchema();
|
await this.setupSchema();
|
||||||
console.log("[DB] connected");
|
console.log("[DB] connected");
|
||||||
//await Promise.all([Config.init()]);
|
await Config.init();
|
||||||
|
|
||||||
this.app.use(GlobalRateLimit);
|
this.app.use(GlobalRateLimit);
|
||||||
this.app.use(Authentication);
|
this.app.use(Authentication);
|
||||||
this.app.use(CORS);
|
this.app.use(CORS);
|
||||||
this.app.use(BodyParser({ inflate: true }));
|
this.app.use(BodyParser({ inflate: true }));
|
||||||
const languages = await fs.readdir(__dirname + "/../locales/");
|
const languages = await fs.readdir(path.join(__dirname, "..", "locales"));
|
||||||
const namespaces = await fs.readdir(__dirname + "/../locales/en/");
|
const namespaces = await fs.readdir(path.join(__dirname, "..", "locales", "en"));
|
||||||
const ns = namespaces.filter((x) => x.endsWith(".json")).map((x) => x.slice(0, x.length - 5));
|
const ns = namespaces.filter((x) => x.endsWith(".json")).map((x) => x.slice(0, x.length - 5));
|
||||||
|
|
||||||
await i18next
|
await i18next
|
||||||
@ -85,11 +85,13 @@ export class FosscordServer extends Server {
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
this.app = prefix;
|
this.app = prefix;
|
||||||
|
|
||||||
this.routes = await this.registerRoutes(__dirname + "/routes/");
|
this.routes = await this.registerRoutes(path.join(__dirname, "routes"));
|
||||||
app.use("/api/v8", prefix);
|
app.use("/api/v8", prefix);
|
||||||
this.app = app;
|
this.app = app;
|
||||||
this.app.use(ErrorHandler);
|
this.app.use(ErrorHandler);
|
||||||
const indexHTML = await fs.readFile(__dirname + "/../client_test/index.html");
|
const indexHTML = await fs.readFile(path.join(__dirname, "..", "client_test", "index.html"));
|
||||||
|
|
||||||
|
this.app.use("/assets", express.static(path.join(__dirname, "..", "assets")));
|
||||||
|
|
||||||
this.app.get("/assets/:file", async (req, res) => {
|
this.app.get("/assets/:file", async (req, res) => {
|
||||||
delete req.headers.host;
|
delete req.headers.host;
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
import { NextFunction, Request, Response } from "express";
|
import { NextFunction, Request, Response } from "express";
|
||||||
import { HTTPError } from "lambert-server";
|
import { HTTPError } from "lambert-server";
|
||||||
import { checkToken } from "@fosscord/server-util";
|
import { checkToken, Config } from "@fosscord/server-util";
|
||||||
import * as Config from "../util/Config"
|
|
||||||
|
|
||||||
export const NO_AUTHORIZATION_ROUTES = [
|
export const NO_AUTHORIZATION_ROUTES = [
|
||||||
"/api/v8/auth/login",
|
"/api/v8/auth/login",
|
||||||
"/api/v8/auth/register",
|
"/api/v8/auth/register",
|
||||||
"/api/v8/webhooks/",
|
"/api/v8/webhooks/",
|
||||||
"/api/v8/gateway",
|
"/api/v8/gateway",
|
||||||
"/api/v8/experiments",
|
"/api/v8/experiments"
|
||||||
];
|
];
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
@ -25,11 +24,9 @@ export async function Authentication(req: Request, res: Response, next: NextFunc
|
|||||||
if (req.url.startsWith("/api/v8/invites") && req.method === "GET") return next();
|
if (req.url.startsWith("/api/v8/invites") && req.method === "GET") return next();
|
||||||
if (NO_AUTHORIZATION_ROUTES.some((x) => req.url.startsWith(x))) return next();
|
if (NO_AUTHORIZATION_ROUTES.some((x) => req.url.startsWith(x))) return next();
|
||||||
if (!req.headers.authorization) return next(new HTTPError("Missing Authorization Header", 401));
|
if (!req.headers.authorization) return next(new HTTPError("Missing Authorization Header", 401));
|
||||||
// TODO: check if user is banned/token expired
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const { jwtSecret } = Config.get().security;
|
||||||
const { jwtSecret } = Config.apiConfig.getAll().security;
|
|
||||||
|
|
||||||
const decoded: any = await checkToken(req.headers.authorization, jwtSecret);
|
const decoded: any = await checkToken(req.headers.authorization, jwtSecret);
|
||||||
|
|
||||||
|
@ -9,7 +9,7 @@ export function CORS(req: Request, res: Response, next: NextFunction) {
|
|||||||
"Content-security-policy",
|
"Content-security-policy",
|
||||||
"default-src * data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval'; script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src * data: blob: 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src * data: blob: ; style-src * data: blob: 'unsafe-inline'; font-src * data: blob: 'unsafe-inline';"
|
"default-src * data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval'; script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src * data: blob: 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src * data: blob: ; style-src * data: blob: 'unsafe-inline'; font-src * data: blob: 'unsafe-inline';"
|
||||||
);
|
);
|
||||||
res.set("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
|
res.set("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers") || "*");
|
||||||
|
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
import { NextFunction, Request, Response } from "express";
|
import { NextFunction, Request, Response } from "express";
|
||||||
import * as Config from '../util/Config'
|
import { Config } from "@fosscord/server-util";
|
||||||
import crypto from "crypto";
|
|
||||||
|
|
||||||
// TODO: use mongodb ttl index
|
// TODO: use mongodb ttl index
|
||||||
// TODO: increment count on serverside
|
// TODO: increment count on serverside
|
||||||
@ -44,7 +43,7 @@ export async function GlobalRateLimit(req: Request, res: Response, next: NextFun
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getIpAdress(req: Request): string {
|
export function getIpAdress(req: Request): string {
|
||||||
const { forwadedFor } = Config.apiConfig.getAll().security;
|
const { forwadedFor } = Config.get().security;
|
||||||
const ip = forwadedFor ? <string>req.headers[forwadedFor] : req.ip;
|
const ip = forwadedFor ? <string>req.headers[forwadedFor] : req.ip;
|
||||||
return ip.replaceAll(".", "_").replaceAll(":", "_");
|
return ip.replaceAll(".", "_").replaceAll(":", "_");
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,7 @@ import { Request, Response, Router } from "express";
|
|||||||
import { check, FieldErrors, Length } from "../../util/instanceOf";
|
import { check, FieldErrors, Length } from "../../util/instanceOf";
|
||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { UserModel } from "@fosscord/server-util";
|
import { Config, UserModel } from "@fosscord/server-util";
|
||||||
import * as Config from "../../util/Config";
|
|
||||||
import { adjustEmail } from "./register";
|
import { adjustEmail } from "./register";
|
||||||
|
|
||||||
const router: Router = Router();
|
const router: Router = Router();
|
||||||
@ -17,7 +16,7 @@ router.post(
|
|||||||
$undelete: Boolean,
|
$undelete: Boolean,
|
||||||
$captcha_key: String,
|
$captcha_key: String,
|
||||||
$login_source: String,
|
$login_source: String,
|
||||||
$gift_code_sku_id: String,
|
$gift_code_sku_id: String
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response) => {
|
async (req: Request, res: Response) => {
|
||||||
const { login, password, captcha_key } = req.body;
|
const { login, password, captcha_key } = req.body;
|
||||||
@ -27,7 +26,7 @@ router.post(
|
|||||||
|
|
||||||
// TODO: Rewrite this to have the proper config syntax on the new method
|
// TODO: Rewrite this to have the proper config syntax on the new method
|
||||||
|
|
||||||
const config = Config.apiConfig.getAll();
|
const config = Config.get();
|
||||||
|
|
||||||
if (config.login.requireCaptcha && config.security.captcha.enabled) {
|
if (config.login.requireCaptcha && config.security.captcha.enabled) {
|
||||||
if (!captcha_key) {
|
if (!captcha_key) {
|
||||||
@ -35,7 +34,7 @@ router.post(
|
|||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
captcha_key: ["captcha-required"],
|
captcha_key: ["captcha-required"],
|
||||||
captcha_sitekey: sitekey,
|
captcha_sitekey: sitekey,
|
||||||
captcha_service: service,
|
captcha_service: service
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,9 +70,9 @@ export async function generateToken(id: string) {
|
|||||||
return new Promise((res, rej) => {
|
return new Promise((res, rej) => {
|
||||||
jwt.sign(
|
jwt.sign(
|
||||||
{ id: id, iat },
|
{ id: id, iat },
|
||||||
Config.apiConfig.getAll().security.jwtSecret,
|
Config.get().security.jwtSecret,
|
||||||
{
|
{
|
||||||
algorithm,
|
algorithm
|
||||||
},
|
},
|
||||||
(err, token) => {
|
(err, token) => {
|
||||||
if (err) return rej(err);
|
if (err) return rej(err);
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
import { Request, Response, Router } from "express";
|
import { Request, Response, Router } from "express";
|
||||||
import * as Config from "../../util/Config";
|
import { trimSpecial, User, Snowflake, UserModel, Config } from "@fosscord/server-util";
|
||||||
import { trimSpecial, User, Snowflake, UserModel } from "@fosscord/server-util";
|
|
||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
import { check, Email, EMAIL_REGEX, FieldErrors, Length } from "../../util/instanceOf";
|
import { check, Email, EMAIL_REGEX, FieldErrors, Length } from "../../util/instanceOf";
|
||||||
import "missing-native-js-functions";
|
import "missing-native-js-functions";
|
||||||
@ -21,7 +20,7 @@ router.post(
|
|||||||
$invite: String,
|
$invite: String,
|
||||||
$date_of_birth: Date, // "2000-04-03"
|
$date_of_birth: Date, // "2000-04-03"
|
||||||
$gift_code_sku_id: String,
|
$gift_code_sku_id: String,
|
||||||
$captcha_key: String,
|
$captcha_key: String
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response) => {
|
async (req: Request, res: Response) => {
|
||||||
const {
|
const {
|
||||||
@ -33,7 +32,7 @@ router.post(
|
|||||||
invite,
|
invite,
|
||||||
date_of_birth,
|
date_of_birth,
|
||||||
gift_code_sku_id, // ? what is this
|
gift_code_sku_id, // ? what is this
|
||||||
captcha_key,
|
captcha_key
|
||||||
} = req.body;
|
} = req.body;
|
||||||
// TODO: automatically join invite
|
// TODO: automatically join invite
|
||||||
// TODO: gift_code_sku_id?
|
// TODO: gift_code_sku_id?
|
||||||
@ -52,26 +51,26 @@ router.post(
|
|||||||
let discriminator = "";
|
let discriminator = "";
|
||||||
|
|
||||||
// get register Config
|
// get register Config
|
||||||
const { register, security } = Config.apiConfig.getAll();
|
const { register, security } = Config.get();
|
||||||
|
|
||||||
// check if registration is allowed
|
// check if registration is allowed
|
||||||
if (!register.allowNewRegistration) {
|
if (!register.allowNewRegistration) {
|
||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
email: { code: "REGISTRATION_DISABLED", message: req.t("auth:register.REGISTRATION_DISABLED") },
|
email: { code: "REGISTRATION_DISABLED", message: req.t("auth:register.REGISTRATION_DISABLED") }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if the user agreed to the Terms of Service
|
// check if the user agreed to the Terms of Service
|
||||||
if (!consent) {
|
if (!consent) {
|
||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
consent: { code: "CONSENT_REQUIRED", message: req.t("auth:register.CONSENT_REQUIRED") },
|
consent: { code: "CONSENT_REQUIRED", message: req.t("auth:register.CONSENT_REQUIRED") }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// require invite to register -> e.g. for organizations to send invites to their employees
|
// require invite to register -> e.g. for organizations to send invites to their employees
|
||||||
if (register.requireInvite && !invite) {
|
if (register.requireInvite && !invite) {
|
||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
email: { code: "INVITE_ONLY", message: req.t("auth:register.INVITE_ONLY") },
|
email: { code: "INVITE_ONLY", message: req.t("auth:register.INVITE_ONLY") }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,19 +85,19 @@ router.post(
|
|||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
email: {
|
email: {
|
||||||
code: "EMAIL_ALREADY_REGISTERED",
|
code: "EMAIL_ALREADY_REGISTERED",
|
||||||
message: req.t("auth.register.EMAIL_ALREADY_REGISTERED"),
|
message: req.t("auth.register.EMAIL_ALREADY_REGISTERED")
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else if (register.email.necessary) {
|
} else if (register.email.necessary) {
|
||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
email: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") },
|
email: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (register.dateOfBirth.necessary && !date_of_birth) {
|
if (register.dateOfBirth.necessary && !date_of_birth) {
|
||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
date_of_birth: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") },
|
date_of_birth: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
|
||||||
});
|
});
|
||||||
} else if (register.dateOfBirth.minimum) {
|
} else if (register.dateOfBirth.minimum) {
|
||||||
const minimum = new Date();
|
const minimum = new Date();
|
||||||
@ -109,8 +108,8 @@ router.post(
|
|||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
date_of_birth: {
|
date_of_birth: {
|
||||||
code: "DATE_OF_BIRTH_UNDERAGE",
|
code: "DATE_OF_BIRTH_UNDERAGE",
|
||||||
message: req.t("auth:register.DATE_OF_BIRTH_UNDERAGE", { years: register.dateOfBirth.minimum }),
|
message: req.t("auth:register.DATE_OF_BIRTH_UNDERAGE", { years: register.dateOfBirth.minimum })
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -123,8 +122,8 @@ router.post(
|
|||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
email: {
|
email: {
|
||||||
code: "EMAIL_ALREADY_REGISTERED",
|
code: "EMAIL_ALREADY_REGISTERED",
|
||||||
message: req.t("auth:register.EMAIL_ALREADY_REGISTERED"),
|
message: req.t("auth:register.EMAIL_ALREADY_REGISTERED")
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -135,7 +134,7 @@ router.post(
|
|||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
captcha_key: ["captcha-required"],
|
captcha_key: ["captcha-required"],
|
||||||
captcha_sitekey: sitekey,
|
captcha_sitekey: sitekey,
|
||||||
captcha_service: service,
|
captcha_service: service
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -160,8 +159,8 @@ router.post(
|
|||||||
throw FieldErrors({
|
throw FieldErrors({
|
||||||
username: {
|
username: {
|
||||||
code: "USERNAME_TOO_MANY_USERS",
|
code: "USERNAME_TOO_MANY_USERS",
|
||||||
message: req.t("auth:register.USERNAME_TOO_MANY_USERS"),
|
message: req.t("auth:register.USERNAME_TOO_MANY_USERS")
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -184,14 +183,16 @@ router.post(
|
|||||||
phone: null,
|
phone: null,
|
||||||
mfa_enabled: false,
|
mfa_enabled: false,
|
||||||
verified: false,
|
verified: false,
|
||||||
|
disabled: false,
|
||||||
|
deleted: false,
|
||||||
presence: {
|
presence: {
|
||||||
activities: [],
|
activities: [],
|
||||||
client_status: {
|
client_status: {
|
||||||
desktop: undefined,
|
desktop: undefined,
|
||||||
mobile: undefined,
|
mobile: undefined,
|
||||||
web: undefined,
|
web: undefined
|
||||||
},
|
},
|
||||||
status: "offline",
|
status: "offline"
|
||||||
},
|
},
|
||||||
email: adjusted_email,
|
email: adjusted_email,
|
||||||
nsfw_allowed: true, // TODO: depending on age
|
nsfw_allowed: true, // TODO: depending on age
|
||||||
@ -203,7 +204,7 @@ router.post(
|
|||||||
valid_tokens_since: new Date(),
|
valid_tokens_since: new Date(),
|
||||||
relationships: [],
|
relationships: [],
|
||||||
connected_accounts: [],
|
connected_accounts: [],
|
||||||
fingerprints: [],
|
fingerprints: []
|
||||||
},
|
},
|
||||||
user_settings: {
|
user_settings: {
|
||||||
afk_timeout: 300,
|
afk_timeout: 300,
|
||||||
@ -216,7 +217,7 @@ router.post(
|
|||||||
emoji_id: null,
|
emoji_id: null,
|
||||||
emoji_name: null,
|
emoji_name: null,
|
||||||
expires_at: null,
|
expires_at: null,
|
||||||
text: null,
|
text: null
|
||||||
},
|
},
|
||||||
default_guilds_restricted: false,
|
default_guilds_restricted: false,
|
||||||
detect_platform_accounts: true,
|
detect_platform_accounts: true,
|
||||||
@ -241,9 +242,9 @@ router.post(
|
|||||||
status: "offline",
|
status: "offline",
|
||||||
stream_notifications_enabled: true,
|
stream_notifications_enabled: true,
|
||||||
theme: "dark",
|
theme: "dark",
|
||||||
timezone_offset: 0,
|
timezone_offset: 0
|
||||||
// timezone_offset: // TODO: timezone from request
|
// timezone_offset: // TODO: timezone from request
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// insert user into database
|
// insert user into database
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { ChannelModel, getPermission, MessageDeleteBulkEvent, MessageModel } from "@fosscord/server-util";
|
import { ChannelModel, Config, getPermission, MessageDeleteBulkEvent, MessageModel } from "@fosscord/server-util";
|
||||||
import { HTTPError } from "lambert-server";
|
import { HTTPError } from "lambert-server";
|
||||||
import * as Config from "../../../../util/Config";
|
|
||||||
import { emitEvent } from "../../../../util/Event";
|
import { emitEvent } from "../../../../util/Event";
|
||||||
import { check } from "../../../../util/instanceOf";
|
import { check } from "../../../../util/instanceOf";
|
||||||
|
|
||||||
@ -20,7 +19,7 @@ router.post("/", check({ messages: [String] }), async (req, res) => {
|
|||||||
const permission = await getPermission(req.user_id, channel?.guild_id, channel_id, { channel });
|
const permission = await getPermission(req.user_id, channel?.guild_id, channel_id, { channel });
|
||||||
permission.hasThrow("MANAGE_MESSAGES");
|
permission.hasThrow("MANAGE_MESSAGES");
|
||||||
|
|
||||||
const { maxBulkDelete } = Config.apiConfig.getAll().limits.message;
|
const { maxBulkDelete } = Config.get().limits.message;
|
||||||
|
|
||||||
const { messages } = req.body as { messages: string[] };
|
const { messages } = req.body as { messages: string[] };
|
||||||
if (messages.length < 2) throw new HTTPError("You must at least specify 2 messages to bulk delete");
|
if (messages.length < 2) throw new HTTPError("You must at least specify 2 messages to bulk delete");
|
||||||
|
@ -1,6 +1,13 @@
|
|||||||
import { ChannelModel, ChannelPinsUpdateEvent, getPermission, MessageModel, MessageUpdateEvent, toObject } from "@fosscord/server-util";
|
import {
|
||||||
|
ChannelModel,
|
||||||
|
ChannelPinsUpdateEvent,
|
||||||
|
Config,
|
||||||
|
getPermission,
|
||||||
|
MessageModel,
|
||||||
|
MessageUpdateEvent,
|
||||||
|
toObject
|
||||||
|
} from "@fosscord/server-util";
|
||||||
import { Router, Request, Response } from "express";
|
import { Router, Request, Response } from "express";
|
||||||
import * as Config from "../../../util/Config";
|
|
||||||
import { HTTPError } from "lambert-server";
|
import { HTTPError } from "lambert-server";
|
||||||
import { emitEvent } from "../../../util/Event";
|
import { emitEvent } from "../../../util/Event";
|
||||||
|
|
||||||
@ -18,7 +25,7 @@ router.put("/:message_id", async (req: Request, res: Response) => {
|
|||||||
if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES");
|
if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES");
|
||||||
|
|
||||||
const pinned_count = await MessageModel.count({ channel_id, pinned: true }).exec();
|
const pinned_count = await MessageModel.count({ channel_id, pinned: true }).exec();
|
||||||
const { maxPins } = Config.apiConfig.getAll().limits.channel;
|
const { maxPins } = Config.get().limits.channel;
|
||||||
if (pinned_count >= maxPins) throw new HTTPError("Max pin count reached: " + maxPins);
|
if (pinned_count >= maxPins) throw new HTTPError("Max pin count reached: " + maxPins);
|
||||||
|
|
||||||
await MessageModel.updateOne({ id: message_id }, { pinned: true }).exec();
|
await MessageModel.updateOne({ id: message_id }, { pinned: true }).exec();
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
|
import { Config } from "@fosscord/server-util";
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import * as Config from "../util/Config"
|
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
router.get("/", (req, res) => {
|
router.get("/", (req, res) => {
|
||||||
const { gateway } = Config.apiConfig.getAll();
|
const { endpoint } = Config.get().gateway;
|
||||||
res.send({ url: gateway || "ws://localhost:3002" });
|
res.send({ url: endpoint || "ws://localhost:3002" });
|
||||||
});
|
});
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
import { Router, Request, Response } from "express";
|
import { Router, Request, Response } from "express";
|
||||||
import { RoleModel, GuildModel, Snowflake, Guild, RoleDocument } from "@fosscord/server-util";
|
import { RoleModel, GuildModel, Snowflake, Guild, RoleDocument, Config } from "@fosscord/server-util";
|
||||||
import { HTTPError } from "lambert-server";
|
import { HTTPError } from "lambert-server";
|
||||||
import { check } from "./../../util/instanceOf";
|
import { check } from "./../../util/instanceOf";
|
||||||
import { GuildCreateSchema } from "../../schema/Guild";
|
import { GuildCreateSchema } from "../../schema/Guild";
|
||||||
import * as Config from "../../util/Config";
|
|
||||||
import { getPublicUser } from "../../util/User";
|
import { getPublicUser } from "../../util/User";
|
||||||
import { addMember } from "../../util/Member";
|
import { addMember } from "../../util/Member";
|
||||||
import { createChannel } from "../../util/Channel";
|
import { createChannel } from "../../util/Channel";
|
||||||
@ -15,7 +14,7 @@ const router: Router = Router();
|
|||||||
router.post("/", check(GuildCreateSchema), async (req: Request, res: Response) => {
|
router.post("/", check(GuildCreateSchema), async (req: Request, res: Response) => {
|
||||||
const body = req.body as GuildCreateSchema;
|
const body = req.body as GuildCreateSchema;
|
||||||
|
|
||||||
const { maxGuilds } = Config.apiConfig.getAll().limits.user;
|
const { maxGuilds } = Config.get().limits.user;
|
||||||
const user = await getPublicUser(req.user_id, { guilds: true });
|
const user = await getPublicUser(req.user_id, { guilds: true });
|
||||||
|
|
||||||
if (user.guilds.length >= maxGuilds) {
|
if (user.guilds.length >= maxGuilds) {
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, Router } from "express";
|
import { Request, Response, Router } from "express";
|
||||||
const router: Router = Router();
|
const router: Router = Router();
|
||||||
import { TemplateModel, GuildModel, toObject, UserModel, RoleModel, Snowflake, Guild } from "@fosscord/server-util";
|
import { TemplateModel, GuildModel, toObject, UserModel, RoleModel, Snowflake, Guild, Config } from "@fosscord/server-util";
|
||||||
import { HTTPError } from "lambert-server";
|
import { HTTPError } from "lambert-server";
|
||||||
import { GuildTemplateCreateSchema } from "../../../schema/Guild";
|
import { GuildTemplateCreateSchema } from "../../../schema/Guild";
|
||||||
import { getPublicUser } from "../../../util/User";
|
import { getPublicUser } from "../../../util/User";
|
||||||
import { check } from "../../../util/instanceOf";
|
import { check } from "../../../util/instanceOf";
|
||||||
import * as Config from "../../../util/Config";
|
|
||||||
import { addMember } from "../../../util/Member";
|
import { addMember } from "../../../util/Member";
|
||||||
|
|
||||||
router.get("/:code", async (req: Request, res: Response) => {
|
router.get("/:code", async (req: Request, res: Response) => {
|
||||||
@ -21,7 +20,7 @@ router.post("/:code", check(GuildTemplateCreateSchema), async (req: Request, res
|
|||||||
const { code } = req.params;
|
const { code } = req.params;
|
||||||
const body = req.body as GuildTemplateCreateSchema;
|
const body = req.body as GuildTemplateCreateSchema;
|
||||||
|
|
||||||
const { maxGuilds } = Config.apiConfig.getAll().limits.user;
|
const { maxGuilds } = Config.get().limits.user;
|
||||||
const user = await getPublicUser(req.user_id, { guilds: true });
|
const user = await getPublicUser(req.user_id, { guilds: true });
|
||||||
|
|
||||||
if (user.guilds.length >= maxGuilds) {
|
if (user.guilds.length >= maxGuilds) {
|
||||||
@ -37,7 +36,7 @@ router.post("/:code", check(GuildTemplateCreateSchema), async (req: Request, res
|
|||||||
...body,
|
...body,
|
||||||
...template.serialized_source_guild,
|
...template.serialized_source_guild,
|
||||||
id: guild_id,
|
id: guild_id,
|
||||||
owner_id: req.user_id,
|
owner_id: req.user_id
|
||||||
};
|
};
|
||||||
|
|
||||||
const [guild_doc, role] = await Promise.all([
|
const [guild_doc, role] = await Promise.all([
|
||||||
@ -52,8 +51,8 @@ router.post("/:code", check(GuildTemplateCreateSchema), async (req: Request, res
|
|||||||
name: "@everyone",
|
name: "@everyone",
|
||||||
permissions: 2251804225n,
|
permissions: 2251804225n,
|
||||||
position: 0,
|
position: 0,
|
||||||
tags: null,
|
tags: null
|
||||||
}).save(),
|
}).save()
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await addMember(req.user_id, guild_id, { guild: guild_doc });
|
await addMember(req.user_id, guild_id, { guild: guild_doc });
|
||||||
|
@ -7,7 +7,7 @@ config();
|
|||||||
import { FosscordServer } from "./Server";
|
import { FosscordServer } from "./Server";
|
||||||
import cluster from "cluster";
|
import cluster from "cluster";
|
||||||
import os from "os";
|
import os from "os";
|
||||||
const cores = os.cpus().length;
|
const cores = Number(process.env.threads) || os.cpus().length;
|
||||||
|
|
||||||
if (cluster.isMaster && process.env.production == "true") {
|
if (cluster.isMaster && process.env.production == "true") {
|
||||||
console.log(`Primary ${process.pid} is running`);
|
console.log(`Primary ${process.pid} is running`);
|
||||||
@ -22,8 +22,7 @@ if (cluster.isMaster && process.env.production == "true") {
|
|||||||
cluster.fork();
|
cluster.fork();
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
var port = Number(process.env.PORT);
|
var port = Number(process.env.PORT) || 3001;
|
||||||
if (isNaN(port)) port = 3001;
|
|
||||||
|
|
||||||
const server = new FosscordServer({ port });
|
const server = new FosscordServer({ port });
|
||||||
server.start().catch(console.error);
|
server.start().catch(console.error);
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import Ajv, { JSONSchemaType } from "ajv"
|
// @ts-nocheck
|
||||||
|
import Ajv, { JSONSchemaType } from "ajv";
|
||||||
import { getConfigPathForFile } from "@fosscord/server-util/dist/util/Config";
|
import { getConfigPathForFile } from "@fosscord/server-util/dist/util/Config";
|
||||||
import {Config} from "@fosscord/server-util"
|
import { Config } from "@fosscord/server-util";
|
||||||
|
|
||||||
export interface RateLimitOptions {
|
export interface RateLimitOptions {
|
||||||
count: number;
|
count: number;
|
||||||
@ -95,11 +96,10 @@ export interface DefaultOptions {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const schema: JSONSchemaType<DefaultOptions> & {
|
const schema: JSONSchemaType<DefaultOptions> & {
|
||||||
definitions: {
|
definitions: {
|
||||||
rateLimitOptions: JSONSchemaType<RateLimitOptions>
|
rateLimitOptions: JSONSchemaType<RateLimitOptions>;
|
||||||
}
|
};
|
||||||
} = {
|
} = {
|
||||||
type: "object",
|
type: "object",
|
||||||
definitions: {
|
definitions: {
|
||||||
@ -107,10 +107,10 @@ const schema: JSONSchemaType<DefaultOptions> & {
|
|||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
count: { type: "number" },
|
count: { type: "number" },
|
||||||
timespan: { type: "number" },
|
timespan: { type: "number" }
|
||||||
},
|
},
|
||||||
required: ["count", "timespan"],
|
required: ["count", "timespan"]
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
properties: {
|
properties: {
|
||||||
gateway: {
|
gateway: {
|
||||||
@ -238,8 +238,8 @@ const schema: JSONSchemaType<DefaultOptions> & {
|
|||||||
auth: {
|
auth: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
login: { $ref: '#/definitions/rateLimitOptions' },
|
login: { $ref: "#/definitions/rateLimitOptions" },
|
||||||
register: { $ref: '#/definitions/rateLimitOptions' }
|
register: { $ref: "#/definitions/rateLimitOptions" }
|
||||||
},
|
},
|
||||||
nullable: true,
|
nullable: true,
|
||||||
required: [],
|
required: [],
|
||||||
@ -348,18 +348,25 @@ const schema: JSONSchemaType<DefaultOptions> & {
|
|||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
required: ["allowMultipleAccounts", "allowNewRegistration", "dateOfBirth", "email", "password", "requireCaptcha", "requireInvite"],
|
required: [
|
||||||
|
"allowMultipleAccounts",
|
||||||
|
"allowNewRegistration",
|
||||||
|
"dateOfBirth",
|
||||||
|
"email",
|
||||||
|
"password",
|
||||||
|
"requireCaptcha",
|
||||||
|
"requireInvite"
|
||||||
|
],
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
required: ["gateway", "general", "limits", "login", "permissions", "register", "security"],
|
required: ["gateway", "general", "limits", "login", "permissions", "register", "security"],
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
const ajv = new Ajv();
|
const ajv = new Ajv();
|
||||||
const validator = ajv.compile(schema);
|
const validator = ajv.compile(schema);
|
||||||
|
|
||||||
const configPath = getConfigPathForFile("fosscord", "api", ".json");
|
const configPath = getConfigPathForFile("fosscord", "api", ".json");
|
||||||
|
|
||||||
export const apiConfig = new Config<DefaultOptions>({path: configPath, schemaValidator: validator, schema: schema});
|
export const apiConfig = new Config<DefaultOptions>({ path: configPath, schemaValidator: validator, schema: schema });
|
||||||
|
@ -10,11 +10,11 @@ import {
|
|||||||
RoleModel,
|
RoleModel,
|
||||||
toObject,
|
toObject,
|
||||||
UserModel,
|
UserModel,
|
||||||
GuildDocument
|
GuildDocument,
|
||||||
|
Config
|
||||||
} from "@fosscord/server-util";
|
} from "@fosscord/server-util";
|
||||||
|
|
||||||
import { HTTPError } from "lambert-server";
|
import { HTTPError } from "lambert-server";
|
||||||
import * as Config from "./Config";
|
|
||||||
import { emitEvent } from "./Event";
|
import { emitEvent } from "./Event";
|
||||||
import { getPublicUser } from "./User";
|
import { getPublicUser } from "./User";
|
||||||
|
|
||||||
@ -39,7 +39,7 @@ export async function isMember(user_id: string, guild_id: string) {
|
|||||||
export async function addMember(user_id: string, guild_id: string, cache?: { guild?: GuildDocument }) {
|
export async function addMember(user_id: string, guild_id: string, cache?: { guild?: GuildDocument }) {
|
||||||
const user = await getPublicUser(user_id, { guilds: true });
|
const user = await getPublicUser(user_id, { guilds: true });
|
||||||
|
|
||||||
const { maxGuilds } = Config.apiConfig.getAll().limits.user;
|
const { maxGuilds } = Config.get().limits.user;
|
||||||
if (user.guilds.length >= maxGuilds) {
|
if (user.guilds.length >= maxGuilds) {
|
||||||
throw new HTTPError(`You are at the ${maxGuilds} server limit.`, 403);
|
throw new HTTPError(`You are at the ${maxGuilds} server limit.`, 403);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
|
import { Config } from "@fosscord/server-util";
|
||||||
import "missing-native-js-functions";
|
import "missing-native-js-functions";
|
||||||
import * as Config from "./Config";
|
|
||||||
|
|
||||||
const reNUMBER = /[0-9]/g;
|
const reNUMBER = /[0-9]/g;
|
||||||
const reUPPERCASELETTER = /[A-Z]/g;
|
const reUPPERCASELETTER = /[A-Z]/g;
|
||||||
@ -17,13 +17,7 @@ const blocklist: string[] = []; // TODO: update ones passwordblocklist is stored
|
|||||||
* Returns: 0 > pw > 1
|
* Returns: 0 > pw > 1
|
||||||
*/
|
*/
|
||||||
export function check(password: string): number {
|
export function check(password: string): number {
|
||||||
const {
|
const { minLength, minNumbers, minUpperCase, minSymbols } = Config.get().register.password;
|
||||||
minLength,
|
|
||||||
minNumbers,
|
|
||||||
minUpperCase,
|
|
||||||
minSymbols,
|
|
||||||
blockInsecureCommonPasswords,
|
|
||||||
} = Config.apiConfig.getAll().register.password;
|
|
||||||
var strength = 0;
|
var strength = 0;
|
||||||
|
|
||||||
// checks for total password len
|
// checks for total password len
|
||||||
@ -51,10 +45,5 @@ export function check(password: string): number {
|
|||||||
strength = 0;
|
strength = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (blockInsecureCommonPasswords) {
|
|
||||||
if (blocklist.includes(password)) {
|
|
||||||
strength = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return strength;
|
return strength;
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user