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
+5 -4
View File
@@ -4,13 +4,13 @@ html {
--background-primary: rgb(22, 23, 25);
--background-secondary: rgb(15, 16, 18);
--foreground-primary: rgb(200, 200, 200);
--background-login-discord: #5865F2;
--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;
font-family: "Montserrat", sans-serif;
color: var(--foreground-primary);
}
@@ -55,7 +55,8 @@ html {
text-align: center;
}
.header-subtext a, .header-subtext p {
.header-subtext a,
.header-subtext p {
display: inline-block;
margin: 0 10px 0 10px;
}
@@ -109,4 +110,4 @@ label {
display: flex;
justify-content: center;
margin-top: 10px;
}
}
+6 -7
View File
@@ -29,13 +29,12 @@ const handleSubmit = async (path, body) => {
}
// 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
);
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";
};
};
+109 -85
View File
@@ -1,103 +1,127 @@
<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>
<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="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>
<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>
<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>
<p id="failure">Login failed</p>
</div>
<p id="failure">Login failed</p>
<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>
<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() || ''
);
<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";
}
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";
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");
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,
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");
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,
await handleSubmit("/api/v9/auth/mfa/totp", {
code: code,
ticket: ticket,
});
});
})
</script>
</body>
</html>
</script>
</body>
</html>
+76 -66
View File
@@ -1,78 +1,88 @@
<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>
<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="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>
<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>
<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>
<p id="failure">Register failed</p>
</div>
<p id="failure">Register failed</p>
<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>
<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")
<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,
await handleSubmit("/api/v9/auth/register", {
consent: true,
email: email,
username: username,
password: password,
date_of_birth: dob,
captcha_key: hcaptcha,
});
});
})
</script>
</body>
</html>
</script>
</body>
</html>
+46 -30
View File
@@ -1,7 +1,13 @@
import "dotenv/config";
import express, { Request, Response } from "express";
import cookieParser from "cookie-parser";
import { initDatabase, generateToken, User, Config, handleFile } from "fosscord-server/src/util";
import {
initDatabase,
generateToken,
User,
Config,
handleFile,
} from "fosscord-server/src/util";
import path from "path";
import fetch from "node-fetch";
@@ -16,8 +22,8 @@ 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 rateLimits: { [ip: string]: number } = {};
const allowRequestsEveryMs = 0.5 * 1000; // every half second
const allowedRequestsPerSecond = 50;
let requestsThisSecond = 0;
@@ -36,23 +42,25 @@ 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 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
body: body,
});
const json = await resp.json() as any;
const json = (await resp.json()) as any;
if (json.error) return null;
return {
@@ -67,24 +75,26 @@ class Discord {
static getUserDetails = async (token: string) => {
const resp = await fetch("https://discord.com/api/users/@me", {
headers: {
"Authorization": `Bearer ${token}`,
}
Authorization: `Bearer ${token}`,
},
});
const json = await resp.json() as any;
if (!json.username || !json.email) return null; // eh, deal with bad code later
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,
avatar_url: json.avatar
? `https://cdn.discordapp.com/avatars/${json.id}/${json.avatar}?size=2048`
: null,
};
};
}
const handlers: { [key: string]: any; } = {
"discord": Discord,
const handlers: { [key: string]: any } = {
discord: Discord,
};
app.get("/oauth/:type", async (req, res) => {
@@ -92,17 +102,21 @@ app.get("/oauth/:type", async (req, res) => {
if (requestsThisSecond > allowedRequestsPerSecond)
return res.sendStatus(429);
const ip = (req.headers["x-forwarded-for"] as string) || req.socket.remoteAddress as string;
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()) {
} 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`);
console.log(
`${new Date()} : user ${ip} was timed out for ${
(rateLimits[ip] - Date.now()) / 1000
}s`,
);
return res.sendStatus(429);
}
else {
} else {
delete rateLimits[ip];
}
@@ -121,16 +135,18 @@ app.get("/oauth/:type", async (req, res) => {
user = await User.register({
email: details.email,
username: details.username,
req
req,
});
if (details.avatar_url) {
try {
const avatar = await handleFile(`/avatars/${user.id}`, await toDataURL(details.avatar_url) as string);
const avatar = await handleFile(
`/avatars/${user.id}`,
(await toDataURL(details.avatar_url)) as string,
);
user.avatar = avatar;
await user.save();
}
catch (e) {
} catch (e) {
console.error(e);
}
}
@@ -152,4 +168,4 @@ app.use(express.static("public", { extensions: ["html"] }));
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
})();
})();
+20 -20
View File
@@ -1,10 +1,6 @@
{
"exclude": [
"node_modules"
],
"include": [
"src/**/*.ts"
],
"exclude": ["node_modules"],
"include": ["src/**/*.ts"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
@@ -15,10 +11,12 @@
// "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. */
"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. */
"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'. */
@@ -27,14 +25,16 @@
// "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. */
"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. */
"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. */
"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. */
@@ -46,9 +46,9 @@
// "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. */
"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. */
"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. */
@@ -69,16 +69,16 @@
/* 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. */
"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. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"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. */
"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. */
@@ -94,6 +94,6 @@
// "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. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
}