Refactor to mono-repo + upgrade packages

This commit is contained in:
Madeline
2022-09-25 23:35:18 +10:00
parent 59d94b4894
commit f44f5d7ac2
583 changed files with 5415 additions and 114015 deletions
+5
View File
@@ -0,0 +1,5 @@
DATABASE=../bundle/database.db
PORT=3010
DISCORD_CLIENT_ID=
DISCORD_SECRET=
DISCORD_REDIRECT=
+15382
View File
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
{
"name": "slowcord-login",
"version": "1.0.0",
"description": "Slowcord login service",
"main": "build/index.js",
"scripts": {
"build": "tsc -b",
"start": "node build/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/maddyunderstars/fosscord-server.git"
},
"author": "MaddyUnderStars",
"license": "AGPL-3.0-only",
"bugs": {
"url": "https://github.com/maddyunderstars/fosscord-server/issues"
},
"homepage": "https://github.com/maddyunderstars/fosscord-server#readme",
"dependencies": {
"@fosscord/util": "file:../../util",
"cookie-parser": "^1.4.6",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"node-fetch": "^3.2.6",
"sqlite3": "^5.0.8"
},
"devDependencies": {
"@types/cookie-parser": "^1.4.3",
"@types/express": "^4.17.13",
"@types/node": "^18.0.0"
},
"type": "module"
}
+112
View File
@@ -0,0 +1,112 @@
/* Can you tell I like flexbox? */
html {
--background-primary: rgb(22, 23, 25);
--background-secondary: rgb(15, 16, 18);
--foreground-primary: rgb(200, 200, 200);
--background-login-discord: #5865F2;
background: url("https://slowcord.maddy.k.vu/assets/background.png");
background-size: 100% 100%;
background-repeat: no-repeat;
font-family: 'Montserrat', sans-serif;
color: var(--foreground-primary);
}
* {
margin: 0;
padding: 0;
}
.content {
display: flex;
width: 100vw;
height: 100vh;
justify-content: flex-start;
align-items: center;
}
.login {
height: 100%;
width: 25%;
min-width: 400px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: var(--background-primary);
padding: 0 50px 0 50px;
}
.header {
margin: 40px;
width: 100%;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
}
.header-subtext {
text-align: center;
}
.header-subtext a, .header-subtext p {
display: inline-block;
margin: 0 10px 0 10px;
}
a {
color: var(--foreground-primary);
}
form {
display: flex;
flex-direction: column;
justify-content: center;
width: 100%;
min-height: 50%;
}
input,
form a {
background-color: var(--background-secondary);
padding: 10px;
margin: 5px 0 5px 0;
outline: none;
border: 1px solid grey;
color: var(--foreground-primary);
text-decoration: none;
cursor: pointer;
}
form a {
text-align: center;
}
label {
text-transform: uppercase;
font-size: 0.75rem;
font-weight: bold;
}
#loginDiscord {
background-color: var(--background-login-discord);
}
#failure {
width: 100%;
margin-top: 10px;
color: rgb(200, 20, 20);
display: none;
}
.h-captcha {
display: flex;
justify-content: center;
margin-top: 10px;
}
+41
View File
@@ -0,0 +1,41 @@
const handleSubmit = async (path, body) => {
const failureMessage = document.getElementById("failure");
var response = await fetch(path, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
const json = await response.json();
if (json.token) {
window.localStorage.setItem("token", `"${json.token}"`);
window.location.href = "/app";
return;
}
if (json.ticket) {
// my terrible solution to 2fa
const twoFactorForm = document.forms["2fa"];
const loginForm = document.forms["login"];
twoFactorForm.style.display = "flex";
loginForm.style.display = "none";
twoFactorForm.ticket.value = json.ticket;
return;
}
// Very fun error message here lol
const error =
json.errors
? Object.values(json.errors)[0]._errors[0].message
: (
json.captcha_key ? "Captcha required" : json.message
);
failureMessage.innerHTML = error;
failureMessage.style.display = "block";
};
+103
View File
@@ -0,0 +1,103 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slowcord</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./css/index.css">
<script src="js/handler.js"></script>
</head>
<body>
<div class="content">
<div class="login">
<div class="header">
<h1>Welcome to Slowcord</h1>
<div class="header-subtext">
<p>Glad to see you &lt;3 </p>
<a href="/register">Wait, I'm new!</a>
</div>
<p id="failure">Login failed</p>
</div>
<form action="javascript:void(0);" name="login">
<label for="email">Email</label>
<input type="email" name="email" />
<label for="password">Password</label>
<input type="password" name="password" />
<input type="submit" value="Login" />
<a id="loginDiscord" class="oauth"
href="https://discord.com/api/oauth2/authorize?client_id=991688571415175198&redirect_uri=https%3A%2F%2Fslowcord.maddy.k.vu%2Foauth%2Fdiscord&response_type=code&scope=identify%20email">
Login with Discord
</a>
<div class="h-captcha" data-sitekey="fa3163ea-79a7-4b7b-b752-b58c545906c8" data-theme="dark"></div>
<script src="https://js.hcaptcha.com/1/api.js" async defer></script>
</form>
<form action="javascript:void(0);" name="2fa" style="display: none">
<label for="code">2FA Code</label>
<input type="number" name="code" />
<input type="hidden" name="ticket" />
<input type="submit" value="Login"/>
</form>
</div>
</div>
<script>
/* https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript */
const getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
);
let token = getCookieValue("token");
if (token.trim().length) {
/* https://stackoverflow.com/a/27374365 */
// why is clearing cookies so weird? wtf
document.cookie.split(";").forEach(function (c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
window.localStorage.setItem("token", `"${token}"`);
window.location.href = "/app";
}
token = window.localStorage.getItem("token");
if (token) window.location.href = "/app";
document.forms["login"].addEventListener("submit", async (e) => {
const data = new FormData(e.target);
const email = data.get("email");
const password = data.get("password");
const hcaptcha = data.get("h-captcha-response");
await handleSubmit("/api/v9/auth/login", {
login: email,
password: password,
captcha_key: hcaptcha,
});
})
document.forms["2fa"].addEventListener("submit", async (e) => {
const data = new FormData(e.target);
const code = data.get("code");
const ticket = data.get("ticket");
await handleSubmit("/api/v9/auth/mfa/totp", {
code: code,
ticket: ticket,
});
})
</script>
</body>
</html>
+78
View File
@@ -0,0 +1,78 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slowcord</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./css/index.css">
<script src="js/handler.js"></script>
</head>
<body>
<div class="content">
<div class="login">
<div class="header">
<h1>Welcome to Slowcord</h1>
<div class="header-subtext">
<p>You're new?</p>
<a href="/login">Actually, I'm not!</a>
</div>
<p id="failure">Register failed</p>
</div>
<form action="javascript:void(0);">
<label for="email">Email</label>
<input type="email" name="email" />
<label for="username">Username</label>
<input type="username" name="username" />
<label for="password">Password</label>
<input type="password" name="password" />
<label for="dob">Date of Birth</label>
<input type="date" name="dob" />
<input type="submit" value="Register" />
<a id="loginDiscord" class="oauth"
href="https://discord.com/api/oauth2/authorize?client_id=991688571415175198&redirect_uri=https%3A%2F%2Fslowcord.maddy.k.vu%2Foauth%2Fdiscord&response_type=code&scope=identify%20email">
Login with Discord
</a>
<div class="h-captcha" data-sitekey="fa3163ea-79a7-4b7b-b752-b58c545906c8"></div>
<script src="https://js.hcaptcha.com/1/api.js" async defer></script>
</form>
</div>
</div>
<script>
document.forms[0].addEventListener("submit", async (e) => {
const data = new FormData(e.target);
const email = data.get("email");
const username = data.get("username");
const password = data.get("password");
const dob = data.get("dob");
const hcaptcha = data.get("h-captcha-response")
await handleSubmit("/api/v9/auth/register", {
consent: true,
email: email,
username: username,
password: password,
date_of_birth: dob,
captcha_key: hcaptcha,
});
})
</script>
</body>
</html>
+156
View File
@@ -0,0 +1,156 @@
import "dotenv/config";
import express, { Request, Response } from "express";
import cookieParser from "cookie-parser";
import * as util from "@fosscord/util";
const { initDatabase, generateToken, User, Config, handleFile } = util;
import path from "path";
import fetch from "node-fetch";
// apparently dirname doesn't exist in modules, nice
/* https://stackoverflow.com/a/62892482 */
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.use(cookieParser());
const port = process.env.PORT;
// ip -> unix epoch that requests will be accepted again
const rateLimits: { [ip: string]: number; } = {};
const allowRequestsEveryMs = 0.5 * 1000; // every half second
const allowedRequestsPerSecond = 50;
let requestsThisSecond = 0;
setInterval(() => {
requestsThisSecond = 0;
}, 1000);
const toDataURL = async (url: string) => {
const response = await fetch(url);
const blob = await response.blob();
const buffer = Buffer.from(await blob.text());
return `data:${blob.type};base64,${buffer.toString("base64")}`;
};
class Discord {
static getAccessToken = async (req: Request, res: Response) => {
const { code } = req.query;
const body = new URLSearchParams(Object.entries({
client_id: process.env.DISCORD_CLIENT_ID as string,
client_secret: process.env.DISCORD_SECRET as string,
redirect_uri: process.env.DISCORD_REDIRECT as string,
code: code as string,
grant_type: "authorization_code",
})).toString();
const resp = await fetch("https://discord.com/api/oauth2/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: body
});
const json = await resp.json() as any;
if (json.error) return null;
return {
access_token: json.access_token,
token_type: json.token_type,
expires_in: json.expires_in,
refresh_token: json.refresh_token,
scope: json.scope,
};
};
static getUserDetails = async (token: string) => {
const resp = await fetch("https://discord.com/api/users/@me", {
headers: {
"Authorization": `Bearer ${token}`,
}
});
const json = await resp.json() as any;
if (!json.username || !json.email) return null; // eh, deal with bad code later
return {
id: json.id,
email: json.email,
username: json.username,
avatar_url: json.avatar ? `https://cdn.discordapp.com/avatars/${json.id}/${json.avatar}?size=2048` : null,
};
};
}
const handlers: { [key: string]: any; } = {
"discord": Discord,
};
app.get("/oauth/:type", async (req, res) => {
requestsThisSecond++;
if (requestsThisSecond > allowedRequestsPerSecond)
return res.sendStatus(429);
const ip = (req.headers["x-forwarded-for"] as string) || req.socket.remoteAddress as string;
console.log(`${ip}`);
if (!rateLimits[ip]) {
rateLimits[ip] = Date.now() + allowRequestsEveryMs;
}
else if (rateLimits[ip] > Date.now()) {
rateLimits[ip] += allowRequestsEveryMs;
console.log(`${new Date()} : user ${ip} was timed out for ${(rateLimits[ip] - Date.now()) / 1000}s`);
return res.sendStatus(429);
}
else {
delete rateLimits[ip];
}
const { type } = req.params;
const handler = handlers[type];
if (!type || !handler) return res.sendStatus(400);
const data = await handler.getAccessToken(req, res);
if (!data) return res.sendStatus(500);
const details = await handler.getUserDetails(data.access_token);
if (!details) return res.sendStatus(500);
let user = await User.findOne({ where: { email: details.email } });
if (!user) {
user = await User.register({
email: details.email,
username: details.username,
req
});
if (details.avatar_url) {
try {
const avatar = await handleFile(`/avatars/${user.id}`, await toDataURL(details.avatar_url) as string);
user.avatar = avatar;
await user.save();
}
catch (e) {
console.error(e);
}
}
}
const token = await generateToken(user.id);
res.cookie("token", token);
res.sendFile(path.join(__dirname, "../public/login.html"));
});
app.use(express.static("public", { extensions: ["html"] }));
(async () => {
await initDatabase();
await Config.init();
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
})();
+99
View File
@@ -0,0 +1,99 @@
{
"exclude": [
"node_modules"
],
"include": [
"src/**/*.ts"
],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["ES2021"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
"experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "ES2020", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
"types": ["node"], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./build", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
"strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}