mirror of
https://github.com/burrow-dev/burrow-server.git
synced 2026-11-18 17:27:50 -05:00
Compare commits
5
Commits
83c2fc3b0b
...
6b707fbc1d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b707fbc1d | ||
|
|
b45fd195df | ||
|
|
e2454447d9 | ||
|
|
0da5daabc9 | ||
|
|
3b53c8dab8 |
No files matched your search
@@ -5,6 +5,7 @@
|
||||
"cdn.jsdelivr.net",
|
||||
"challenges.cloudflare.com",
|
||||
"discord.com",
|
||||
"duckduckgo.com",
|
||||
"play.burrow.moe",
|
||||
"player.vimeo.com",
|
||||
"vision.googleapis.com",
|
||||
|
||||
+7
-3
@@ -322,7 +322,9 @@ const commandDefinitions = () => [
|
||||
.addSubcommand(command => command.setName("close").setDescription("Close this support ticket")),
|
||||
].map(command => command.toJSON());
|
||||
|
||||
const actorFor = interaction => modpanel.discordBot.actor(interaction.user.id);
|
||||
// a command or button counts for a staff member signed in to the panel with
|
||||
// their 2FA code (modpanel.discordBot.commandActor): Discord alone is not them.
|
||||
const actorFor = interaction => modpanel.discordBot.commandActor(interaction.user.id);
|
||||
|
||||
const reportButton = report => new ActionRowBuilder().addComponents(
|
||||
new ButtonBuilder().setCustomId(`${REPORT_BUTTON_PREFIX}${report.id}:handled`).setLabel("Mark handled").setStyle(ButtonStyle.Success),
|
||||
@@ -543,7 +545,7 @@ const handleTicket = async interaction => {
|
||||
return;
|
||||
}
|
||||
const owner = ticketOwner(interaction.channel);
|
||||
const staff = actorFor(interaction);
|
||||
const staff = modpanel.discordBot.actor(interaction.user.id);
|
||||
if (!owner || (owner !== interaction.user.id && !staff)) {
|
||||
await interaction.editReply(failure("Only the ticket opener or linked Burrow staff can close this ticket."));
|
||||
return;
|
||||
@@ -595,7 +597,9 @@ const postCard = async (channelId, payload, label) => {
|
||||
const publishStatus = async () => {
|
||||
const channel = await channelFor(config.discord.statusChannelId);
|
||||
if (!channel) return {error: "The public status channel is not configured or the Discord bot is not connected."};
|
||||
const payload = statusCard({players: 0, rooms: 0, reports: reports.openCount(), uptimeSeconds: Math.floor(process.uptime()), memoryMb: Math.round(process.memoryUsage().rss / 1048576)});
|
||||
const players = world.players();
|
||||
const payload = statusCard({players: players.length, rooms: new Set(players.map(player => player.room).filter(Boolean)).size,
|
||||
reports: reports.openCount(), uptimeSeconds: Math.floor(process.uptime()), memoryMb: Math.round(process.memoryUsage().rss / 1048576)});
|
||||
// The public status card needs no staff actor; it exposes only aggregate
|
||||
// counts. Store its message id in the server database so restarts edit it.
|
||||
const saved = accounts.setting(STATUS_MESSAGE_SETTING);
|
||||
|
||||
+40
-5
@@ -25,6 +25,7 @@ const totp = require("./totp.js");
|
||||
const recoveryMail = require("./recoverymail.js");
|
||||
const world = require("./world.js");
|
||||
const chatStyles = require("./chatstyles.js");
|
||||
const roles = require("./roles.js");
|
||||
|
||||
// the account page at /account: what a player can do about their own
|
||||
// account from a browser. they sign in with the game's username and
|
||||
@@ -64,6 +65,20 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M
|
||||
const WRONG_PASSWORDS_ALLOWED = 5;
|
||||
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
|
||||
const recoveryRequests = limits.limiter(5, TEN_MINUTES_MS);
|
||||
// recovery mail sent for one account, from any address: a few an hour.
|
||||
const recoveryMailsPerAccount = limits.limiter(3, 3600000);
|
||||
// a 2FA reset by email waits this long after a password reset by email, so
|
||||
// that someone who has only the mailbox cannot do one after the other.
|
||||
const EMAIL_RESET_GAP_MS = 7 * 24 * 3600000;
|
||||
// why a 2FA reset by email cannot be done for this account now, or null.
|
||||
// it also needs the account's password (recover/complete). staff ask the
|
||||
// admin (lib/panel.js), whose 2FA reset ends their role's use until they
|
||||
// turn it on again: a mailbox must not make someone staff.
|
||||
const twoStepResetProblem = account => roles.roleOf(account)
|
||||
? "Staff accounts cannot remove 2FA by email. Ask the admin."
|
||||
: account.emailPasswordResetAt && Date.now() - account.emailPasswordResetAt < EMAIL_RESET_GAP_MS
|
||||
? "2FA cannot be removed by email within 7 days of a password reset by email."
|
||||
: null;
|
||||
// what may be done from the page of a ban (above).
|
||||
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
|
||||
// and from the page of a rejected username: the same, with a new name in
|
||||
@@ -564,7 +579,8 @@ const handle = async (req, res, url, from, web) => {
|
||||
const account = accounts.byName(String(body.username || ""));
|
||||
const email = String(body.email || "").trim().toLowerCase();
|
||||
const kind = body.kind === "twoStep" ? "twoStep" : "password";
|
||||
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()) {
|
||||
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()
|
||||
&& recoveryMailsPerAccount.allow(account.id)) {
|
||||
const token = crypto.randomBytes(32).toString("hex");
|
||||
account.recoveryTokens = (account.recoveryTokens || []).filter(entry => entry.expires > Date.now());
|
||||
account.recoveryTokens.push({hash: recoveryHash(token), kind, expires: Date.now() + RECOVERY_TOKEN_MS});
|
||||
@@ -584,7 +600,8 @@ const handle = async (req, res, url, from, web) => {
|
||||
const token = String(body.token || "");
|
||||
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
|
||||
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
|
||||
reply(entry ? 200 : 400, entry ? {kind: entry.kind} : {error: "This recovery link is invalid or expired."});
|
||||
const refused = entry && entry.kind === "twoStep" ? twoStepResetProblem(account) : null;
|
||||
reply(entry && !refused ? 200 : 400, entry && !refused ? {kind: entry.kind} : {error: refused || "This recovery link is invalid or expired."});
|
||||
return;
|
||||
}
|
||||
case "POST /account/api/recover/complete": {
|
||||
@@ -601,10 +618,28 @@ const handle = async (req, res, url, from, web) => {
|
||||
reply(400, {error: problem === "weak_password" ? "That password is too easy to guess." : "Use 10+ characters with an uppercase letter, lowercase letter and digit."});
|
||||
return;
|
||||
}
|
||||
account.emailPasswordResetAt = Date.now();
|
||||
}
|
||||
else if (totp.isOn(account)) {
|
||||
totp.turnOff(account);
|
||||
accounts.revokeTokens(account);
|
||||
else {
|
||||
const refused = twoStepResetProblem(account);
|
||||
if (refused) {
|
||||
reply(400, {error: refused});
|
||||
return;
|
||||
}
|
||||
// the mailbox and the password: the link alone does not remove 2FA.
|
||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try later."});
|
||||
return;
|
||||
}
|
||||
if (await accounts.authenticateAsync(account.username, body.password) !== account) {
|
||||
failuresByAddress.record(from.key);
|
||||
reply(401, {error: "Wrong password."});
|
||||
return;
|
||||
}
|
||||
if (totp.isOn(account)) {
|
||||
totp.turnOff(account);
|
||||
accounts.revokeTokens(account);
|
||||
}
|
||||
}
|
||||
account.recoveryTokens = [];
|
||||
accounts.save(account);
|
||||
|
||||
+105
-14
@@ -30,6 +30,7 @@ const sfs = require("./sfs.js");
|
||||
const support = require("./support.js");
|
||||
const totp = require("./totp.js");
|
||||
const world = require("./world.js");
|
||||
const {logText} = require("./logtext.js");
|
||||
|
||||
// the moderator panel at /mod: what a moderator needs to look after the
|
||||
// players, and no more. it is apart from the admin panel (lib/panel.js),
|
||||
@@ -66,7 +67,17 @@ const PROJECT_ROOT = path.resolve(__dirname, "..");
|
||||
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
|
||||
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
|
||||
|
||||
const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms}
|
||||
// SHA-256 of a session token -> {id: account id, expiry: ms, code}. `code`:
|
||||
// a 2FA code was given for it (the password sign-in, and Discord's with a
|
||||
// code after it), which the Discord bot's commands need (discordCommandActor).
|
||||
const sessions = new Map();
|
||||
// a Discord sign-in waiting for its 2FA code: SHA-256 of the token in its
|
||||
// cookie -> {id, expiry, tries}. Discord says who it is; the code says it is
|
||||
// still them, as the password sign-in asks.
|
||||
const pendingDiscord = new Map();
|
||||
const PENDING_COOKIE = "ajc_mod_pending";
|
||||
const PENDING_MINUTES = 5;
|
||||
const PENDING_TRIES = 5;
|
||||
const addressSearched = new Map(); // moderator's account id -> the address they last searched for
|
||||
|
||||
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
|
||||
@@ -127,7 +138,12 @@ const cookieHeader = (token, maxAgeSeconds) =>
|
||||
const discordCookie = (value, maxAgeSeconds) =>
|
||||
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
|
||||
const beginSession = (account, res, address, detail = "") => {
|
||||
const pendingCookieHeader = (token, maxAgeSeconds) =>
|
||||
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
|
||||
|
||||
// `extraCookies` go out with the session's own.
|
||||
const beginSession = (account, res, address, detail = "", code = true, extraCookies = []) => {
|
||||
accounts.recordLogin(account, "mod", address);
|
||||
accounts.save(account);
|
||||
for (const [hash, session] of sessions) {
|
||||
@@ -136,8 +152,8 @@ const beginSession = (account, res, address, detail = "") => {
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
|
||||
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
|
||||
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code});
|
||||
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
|
||||
modlog.record(account.username, "signed in", "", detail);
|
||||
};
|
||||
|
||||
@@ -159,6 +175,11 @@ const forget = account => {
|
||||
sessions.delete(hash);
|
||||
}
|
||||
}
|
||||
for (const [hash, pending] of pendingDiscord) {
|
||||
if (pending.id === account.id) {
|
||||
pendingDiscord.delete(hash);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const playerRow = (account, playing) => {
|
||||
@@ -433,13 +454,22 @@ const handle = async (req, res, url, from, web) => {
|
||||
result.ok = false;
|
||||
result.error = "denied";
|
||||
}
|
||||
// Discord has said who this is; the panel opens once their 2FA code is
|
||||
// given too (POST /mod/api/discord/code), so a Discord account alone,
|
||||
// taken over or linked by someone else, opens nothing.
|
||||
const cookies = [discordCookie("", 0)];
|
||||
if (result.ok) {
|
||||
beginSession(result.account, res, from.address, "through Discord");
|
||||
console.log(`[mod] ${result.account.username} signed in with Discord from ${from.address}`);
|
||||
for (const [hash, pending] of pendingDiscord) {
|
||||
if (pending.expiry < Date.now()) {
|
||||
pendingDiscord.delete(hash);
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
|
||||
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
|
||||
}
|
||||
const sessionCookie = res.getHeader("Set-Cookie");
|
||||
res.setHeader("Set-Cookie", sessionCookie ? [sessionCookie, discordCookie("", 0)] : discordCookie("", 0));
|
||||
res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "ok" : result.error}`});
|
||||
res.setHeader("Set-Cookie", cookies);
|
||||
res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "code" : result.error}`});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
@@ -503,12 +533,52 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
|
||||
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: true});
|
||||
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
|
||||
modlog.record(account.username, "signed in");
|
||||
reply(200, {ok: true, username: account.username});
|
||||
return;
|
||||
}
|
||||
// the second half of a Discord sign-in (GET /mod/discord/callback): the
|
||||
// account's 2FA code, from the browser Discord sent back here. a few
|
||||
// wrong codes and the sign-in is gone; it must start again at Discord.
|
||||
case "POST /mod/api/discord/code": {
|
||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try later."});
|
||||
return;
|
||||
}
|
||||
const token = pendingToken(req);
|
||||
const hash = token ? sha256(token) : null;
|
||||
const pending = hash ? pendingDiscord.get(hash) : null;
|
||||
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
|
||||
if (!account || !mayModerate(account)) {
|
||||
if (hash) {
|
||||
pendingDiscord.delete(hash);
|
||||
}
|
||||
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
|
||||
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
|
||||
return;
|
||||
}
|
||||
if (!totp.verify(account, String(body.code || ""))) {
|
||||
failuresByAddress.record(from.key);
|
||||
accounts.recordLogin(account, "mod", from.address, false);
|
||||
accounts.save(account);
|
||||
pending.tries++;
|
||||
if (pending.tries >= PENDING_TRIES) {
|
||||
pendingDiscord.delete(hash);
|
||||
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
|
||||
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
|
||||
return;
|
||||
}
|
||||
reply(401, {error: "Wrong code."});
|
||||
return;
|
||||
}
|
||||
pendingDiscord.delete(hash);
|
||||
beginSession(account, res, from.address, "through Discord", true, [pendingCookieHeader("", 0)]);
|
||||
console.log(`[mod] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
|
||||
reply(200, {ok: true, username: account.username});
|
||||
return;
|
||||
}
|
||||
// signed in through the game instead: a client the moderator is playing
|
||||
// in hands over the game's login token, so they need not type their
|
||||
// password and a code again. taken only for active staff with 2FA on
|
||||
@@ -547,7 +617,8 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
}
|
||||
const cookie = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
|
||||
// no code given here, so not one the Discord bot's commands count
|
||||
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: false});
|
||||
res.setHeader("Set-Cookie", cookieHeader(cookie, SESSION_HOURS * 3600));
|
||||
modlog.record(account.username, "signed in", "", "through the game");
|
||||
reply(200, {ok: true, username: account.username});
|
||||
@@ -1089,13 +1160,33 @@ const moderators = () => accounts.all().filter(account => roles.roleOf(account))
|
||||
// linked to one Burrow account. From there these methods use the same role,
|
||||
// rank, permission and action checks as POST /mod/api/act, and log every
|
||||
// successful change under the staff member's normal Burrow username.
|
||||
// whose Discord this is: the active staff member it is linked to, or null.
|
||||
// it says who someone is (the bot leaves staff alone), not that they may act.
|
||||
const discordActor = discordId => {
|
||||
const account = accounts.all().find(candidate => candidate.discordId === String(discordId));
|
||||
return mayModerate(account) ? account : null;
|
||||
};
|
||||
|
||||
// who may use the bot's commands: the staff member above, while they are
|
||||
// signed in to the panel with a code (a session above with `code`). a
|
||||
// Discord account alone is not them, and a new password, signing out
|
||||
// everywhere or 2FA turned off end those sessions (forget), and the bot's
|
||||
// use with them.
|
||||
const discordCommandActor = discordId => {
|
||||
const account = discordActor(discordId);
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
for (const session of sessions.values()) {
|
||||
if (session.id === account.id && session.code && session.expiry > Date.now()) {
|
||||
return account;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const discordError = (actor, permission) => !actor
|
||||
? {error: "Link this Discord account to an active Burrow staff account first."}
|
||||
? {error: "Link this Discord account to your active Burrow staff account, then sign in to the staff dashboard with your 2FA code. Discord commands work while that sign-in lasts (12 hours)."}
|
||||
: !roles.can(actor, permission) ? {error: "Your Burrow role cannot do that."} : null;
|
||||
|
||||
const discordStatus = actor => {
|
||||
@@ -1153,7 +1244,7 @@ const discordHandleReport = (actor, id) => {
|
||||
|
||||
const discordAct = (actor, username, body) => {
|
||||
if (!actor) {
|
||||
return {error: "Link this Discord account to an active Burrow staff account first."};
|
||||
return discordError(null);
|
||||
}
|
||||
const target = accounts.byName(String(username || "").trim());
|
||||
if (!target) {
|
||||
@@ -1166,7 +1257,7 @@ const discordAct = (actor, username, body) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
const discordBot = {actor: discordActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports,
|
||||
const discordBot = {actor: discordActor, commandActor: discordCommandActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports,
|
||||
staff: discordStaff, announce: discordAnnounce, handleReport: discordHandleReport, act: discordAct};
|
||||
|
||||
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes, discordBot};
|
||||
+73
-8
@@ -119,7 +119,22 @@ const cookieHeader = (token, maxAgeSeconds) =>
|
||||
const discordCookie = (value, maxAgeSeconds) =>
|
||||
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
|
||||
const signIn = res => {
|
||||
// a Discord sign-in waiting for the 2FA code of the account it is linked
|
||||
// to: SHA-256 of the token in its cookie -> {id, expiry, tries}. Discord
|
||||
// alone does not open this panel, as the password alone does not open the
|
||||
// moderator panel.
|
||||
const pendingDiscord = new Map();
|
||||
const PENDING_COOKIE = "ajc_admin_pending";
|
||||
const PENDING_MINUTES = 5;
|
||||
const PENDING_TRIES = 5;
|
||||
const pendingCookieHeader = (token, maxAgeSeconds) =>
|
||||
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
|
||||
// may this account still sign in here with Discord?
|
||||
const discordAdmin = account => Boolean(account && account.adminDashboardAccess && account.discordId && totp.isOn(account) && !account.locked);
|
||||
|
||||
// `extraCookies` go out with the session's own.
|
||||
const signIn = (res, extraCookies = []) => {
|
||||
for (const [hash, expiry] of sessions) {
|
||||
if (expiry < Date.now()) {
|
||||
sessions.delete(hash);
|
||||
@@ -127,7 +142,7 @@ const signIn = res => {
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000);
|
||||
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
|
||||
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
|
||||
};
|
||||
|
||||
const signOut = (req, res) => {
|
||||
@@ -692,13 +707,25 @@ const handle = async (req, res, url, from, web) => {
|
||||
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
|
||||
const result = url.searchParams.get("error") ? {error: "cancelled"}
|
||||
: await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
|
||||
if (result.ok) {
|
||||
signIn(res);
|
||||
console.log(`[admin] ${logText(result.account.username)} signed in with Discord from ${logText(from.address)}`);
|
||||
// Discord has said who this is; the panel opens once that account's 2FA
|
||||
// code is given too (POST /admin/api/discord/code).
|
||||
if (result.ok && !discordAdmin(result.account)) {
|
||||
result.ok = false;
|
||||
result.error = totp.isOn(result.account) ? "denied" : "twostep";
|
||||
}
|
||||
const adminCookie = res.getHeader("Set-Cookie");
|
||||
res.setHeader("Set-Cookie", adminCookie ? [adminCookie, discordCookie("", 0)] : discordCookie("", 0));
|
||||
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "ok" : result.error}`});
|
||||
const cookies = [discordCookie("", 0)];
|
||||
if (result.ok) {
|
||||
for (const [hash, pending] of pendingDiscord) {
|
||||
if (pending.expiry < Date.now()) {
|
||||
pendingDiscord.delete(hash);
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
|
||||
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
|
||||
}
|
||||
res.setHeader("Set-Cookie", cookies);
|
||||
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "code" : result.error}`});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
@@ -760,6 +787,44 @@ const handle = async (req, res, url, from, web) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// the second half of a Discord sign-in: the linked account's 2FA code.
|
||||
case "POST /admin/api/discord/code": {
|
||||
if (tooManyFailures(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try again in a few minutes."});
|
||||
return;
|
||||
}
|
||||
const token = pendingToken(req);
|
||||
const hash = token ? sha256(token) : null;
|
||||
const pending = hash ? pendingDiscord.get(hash) : null;
|
||||
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
|
||||
if (!discordAdmin(account)) {
|
||||
if (hash) {
|
||||
pendingDiscord.delete(hash);
|
||||
}
|
||||
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
|
||||
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
|
||||
return;
|
||||
}
|
||||
if (!totp.verify(account, String(body.code || ""))) {
|
||||
recordFailure(from.key);
|
||||
console.log(`[admin] wrong 2FA code after Discord for ${logText(account.username)} from ${logText(from.address)}`);
|
||||
pending.tries++;
|
||||
if (pending.tries >= PENDING_TRIES) {
|
||||
pendingDiscord.delete(hash);
|
||||
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
|
||||
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
|
||||
return;
|
||||
}
|
||||
reply(401, {error: "Wrong code."});
|
||||
return;
|
||||
}
|
||||
pendingDiscord.delete(hash);
|
||||
signIn(res, [pendingCookieHeader("", 0)]);
|
||||
console.log(`[admin] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/logout":
|
||||
signOut(req, res);
|
||||
reply(200, {ok: true});
|
||||
|
||||
@@ -392,6 +392,12 @@
|
||||
</div>
|
||||
<button class="primary" id="gate-button">Sign in</button>
|
||||
</form>
|
||||
<form id="discord-code-form" hidden>
|
||||
<p class="hint">Discord confirmed who you are. Enter that account's 2FA code to finish signing in.</p>
|
||||
<label for="discord-code">2FA code</label>
|
||||
<input id="discord-code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" spellcheck="false" required>
|
||||
<button class="primary" id="discord-code-button">Finish signing in</button>
|
||||
</form>
|
||||
<button type="button" id="discord-sign-in" hidden>Sign in with Discord</button>
|
||||
<p class="hint" id="discord-gate-hint" hidden>Only Discord accounts explicitly allowed by the owner can use this.</p>
|
||||
<p class="status" id="gate-status" role="status"></p>
|
||||
@@ -1261,6 +1267,38 @@
|
||||
location.href = "/dashboard/admin/discord/login";
|
||||
});
|
||||
|
||||
// after Discord: the linked account's 2FA code (POST discord/code)
|
||||
const discordGate = (codeStep, message) => {
|
||||
history.replaceState(null, "", location.pathname + location.hash);
|
||||
showGate(message);
|
||||
$("gate-form").hidden = codeStep;
|
||||
$("discord-code-form").hidden = !codeStep;
|
||||
if (codeStep) {
|
||||
$("discord-sign-in").textContent = "Start again with Discord";
|
||||
$("discord-code").focus();
|
||||
}
|
||||
};
|
||||
|
||||
$("discord-code-form").addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
$("discord-code-button").disabled = true;
|
||||
const result = await api("discord/code", {code: $("discord-code").value.trim()});
|
||||
$("discord-code-button").disabled = false;
|
||||
$("discord-code").value = "";
|
||||
if (result.ok) {
|
||||
$("discord-code-form").hidden = true;
|
||||
$("gate-form").hidden = false;
|
||||
state = {needsSetup: false, needsSetupCode: false, signedIn: true};
|
||||
showPanel();
|
||||
}
|
||||
else if (result.data.expired) {
|
||||
discordGate(false, result.data.error);
|
||||
}
|
||||
else {
|
||||
setStatus($("gate-status"), result.data.error || "That did not work.", true);
|
||||
}
|
||||
});
|
||||
|
||||
$("sign-out").addEventListener("click", async () => {
|
||||
await api("logout", {});
|
||||
state.signedIn = false;
|
||||
@@ -3514,9 +3552,23 @@
|
||||
showGate("The server did not answer.");
|
||||
return;
|
||||
}
|
||||
const discordResult = new URLSearchParams(location.search).get("discord");
|
||||
if (state.signedIn) {
|
||||
showPanel();
|
||||
}
|
||||
else if (discordResult === "code") {
|
||||
discordGate(true, "");
|
||||
}
|
||||
else if (discordResult) {
|
||||
discordGate(false, {
|
||||
denied: "That Discord account is not allowed to sign in here.",
|
||||
twostep: "Turn on 2FA for the linked account first.",
|
||||
expired: "The Discord sign-in request expired. Try again.",
|
||||
cancelled: "Discord sign-in was cancelled.",
|
||||
discord: "Discord could not confirm that sign-in. Try again.",
|
||||
off: "Discord sign-in is not configured.",
|
||||
}[discordResult] || "");
|
||||
}
|
||||
else {
|
||||
showGate();
|
||||
}
|
||||
|
||||
+54
-1
@@ -135,6 +135,18 @@
|
||||
#browser-address:focus {
|
||||
border-color: #7f6744;
|
||||
}
|
||||
/* a site the client keeps out of the theatre (its own list): offered
|
||||
in the player's own browser instead */
|
||||
#browser-blocked {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font: 400 calc(12 * var(--px)) / 1 Arial, Helvetica, sans-serif;
|
||||
color: #3d2716;
|
||||
cursor: text;
|
||||
}
|
||||
#browser-bar .aj-button {
|
||||
min-width: 0;
|
||||
font-size: calc(12 * var(--px));
|
||||
@@ -258,7 +270,9 @@
|
||||
<button type="button" id="browser-forward" class="aj-round" aria-label="Forward" disabled>▶</button>
|
||||
<button type="button" id="browser-reload" class="aj-round" aria-label="Reload">↻</button>
|
||||
<input id="browser-address" type="text" placeholder="Search or type an address" autocomplete="off" spellcheck="false" aria-label="Address">
|
||||
<button type="submit" class="aj-button go">Go</button>
|
||||
<button type="submit" id="browser-go" class="aj-button go">Go</button>
|
||||
<span id="browser-blocked" role="status" hidden></span>
|
||||
<button type="button" id="browser-elsewhere" class="aj-button go" hidden>Open in your browser</button>
|
||||
<button type="button" id="browser-close" class="aj-round" aria-label="Close the browser">×</button>
|
||||
</form>
|
||||
<form id="own-video-box" class="aj-box" hidden>
|
||||
@@ -729,6 +743,10 @@
|
||||
let roomPlaying = false;
|
||||
let where = null; // the last place told, without `shown`
|
||||
let told = "";
|
||||
// an address the client would not show here (the old browser engine
|
||||
// it needs for Flash shows only the sites it lists): the bar offers
|
||||
// to open it in the player's own browser instead. "" when none.
|
||||
let elsewhere = "";
|
||||
|
||||
const tell = message => window.ipc.sendToHost("browser", message);
|
||||
const placeMessage = () => ({...where, shown: open && theatreScreen !== null && !roomPlaying});
|
||||
@@ -760,6 +778,24 @@
|
||||
opener.hidden = !allowed;
|
||||
pills.hidden = open;
|
||||
bar.hidden = !open;
|
||||
address.hidden = elsewhere !== "";
|
||||
$("browser-go").hidden = elsewhere !== "";
|
||||
$("browser-blocked").hidden = elsewhere === "";
|
||||
$("browser-elsewhere").hidden = elsewhere === "";
|
||||
};
|
||||
|
||||
const showElsewhere = (url, sites) => {
|
||||
let host = "";
|
||||
try {
|
||||
host = new URL(url).hostname;
|
||||
}
|
||||
catch (err) {
|
||||
url = "";
|
||||
}
|
||||
elsewhere = url;
|
||||
$("browser-blocked").textContent = elsewhere ? `${host} opens in your own browser, not here.` : "";
|
||||
$("browser-blocked").title = sites.length ? `The theatre shows only ${sites.join(", ")}.` : "";
|
||||
show();
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
@@ -768,6 +804,7 @@
|
||||
}
|
||||
open = false;
|
||||
told = "";
|
||||
elsewhere = "";
|
||||
tell({action: "close"});
|
||||
show();
|
||||
};
|
||||
@@ -782,6 +819,18 @@
|
||||
address.focus();
|
||||
});
|
||||
$("browser-close").addEventListener("click", close);
|
||||
// the client opens http and https addresses in the system browser
|
||||
$("browser-elsewhere").addEventListener("click", () => {
|
||||
if (/^https?:\/\//.test(elsewhere)) {
|
||||
window.ipc.sendToHost("openPage", elsewhere);
|
||||
}
|
||||
showElsewhere("", []);
|
||||
});
|
||||
// back to the address, to go somewhere else
|
||||
$("browser-blocked").addEventListener("click", () => {
|
||||
showElsewhere("", []);
|
||||
address.focus();
|
||||
});
|
||||
$("browser-back").addEventListener("click", () => tell({action: "back"}));
|
||||
$("browser-forward").addEventListener("click", () => tell({action: "forward"}));
|
||||
$("browser-reload").addEventListener("click", () => tell({action: "reload"}));
|
||||
@@ -816,6 +865,10 @@
|
||||
}
|
||||
$("browser-back").disabled = state.back !== true;
|
||||
$("browser-forward").disabled = state.forward !== true;
|
||||
const blocked = typeof state.blocked === "string" && /^https?:\/\//.test(state.blocked) ? state.blocked : "";
|
||||
if (blocked !== elsewhere) {
|
||||
showElsewhere(blocked, Array.isArray(state.sites) ? state.sites.map(String).slice(0, 10) : []);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
+44
-1
@@ -454,6 +454,12 @@
|
||||
<div id="captcha"></div>
|
||||
<button class="primary" id="gate-button">Sign in</button>
|
||||
</form>
|
||||
<form id="discord-code-form" hidden>
|
||||
<p class="hint">Discord confirmed who you are. Enter your 2FA code to finish signing in.</p>
|
||||
<label for="discord-code">2FA code</label>
|
||||
<input id="discord-code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" spellcheck="false" required>
|
||||
<button class="primary" id="discord-code-button">Finish signing in</button>
|
||||
</form>
|
||||
<button type="button" id="discord-sign-in" hidden>Sign in with Discord</button>
|
||||
<p class="hint" id="discord-gate-hint" hidden>Use the Discord account linked to your active staff account.</p>
|
||||
<p class="status" id="gate-status" role="status"></p>
|
||||
@@ -3195,6 +3201,38 @@
|
||||
location.href = "/dashboard/staff/discord/login";
|
||||
});
|
||||
|
||||
// after Discord: the 2FA code, which opens the panel (POST discord/code)
|
||||
const showDiscordCode = message => {
|
||||
showGate(message);
|
||||
$("gate-form").hidden = true;
|
||||
$("discord-code-form").hidden = false;
|
||||
$("discord-sign-in").textContent = "Start again with Discord";
|
||||
$("discord-code").focus();
|
||||
};
|
||||
|
||||
$("discord-code-form").addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
$("discord-code-button").disabled = true;
|
||||
const result = await api("discord/code", {code: $("discord-code").value.trim()});
|
||||
$("discord-code-button").disabled = false;
|
||||
$("discord-code").value = "";
|
||||
if (result.ok) {
|
||||
history.replaceState(null, "", location.pathname + location.hash);
|
||||
$("discord-code-form").hidden = true;
|
||||
$("gate-form").hidden = false;
|
||||
showPanel(result.data.username);
|
||||
}
|
||||
else if (result.data.expired) {
|
||||
history.replaceState(null, "", location.pathname + location.hash);
|
||||
$("discord-code-form").hidden = true;
|
||||
$("gate-form").hidden = false;
|
||||
showGate(said(result));
|
||||
}
|
||||
else {
|
||||
setStatus($("gate-status"), said(result), true);
|
||||
}
|
||||
});
|
||||
|
||||
$("sign-out").addEventListener("click", async () => {
|
||||
await api("logout", {});
|
||||
showGate("");
|
||||
@@ -3215,7 +3253,12 @@
|
||||
discord: "Discord could not confirm that sign-in. Try again.",
|
||||
off: "Discord sign-in is not configured.",
|
||||
}[discordResult] || "";
|
||||
showGate(result.status === 0 ? result.data.error : discordMessage);
|
||||
if (discordResult === "code" && result.status !== 0) {
|
||||
showDiscordCode("");
|
||||
}
|
||||
else {
|
||||
showGate(result.status === 0 ? result.data.error : discordMessage);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+2
-2
@@ -4,5 +4,5 @@
|
||||
<style>@font-face{font-family:d;src:url('/fonts/CCDigitalDelivery-Regular.otf')}*{box-sizing:border-box}body{margin:0;padding:48px 16px;background:#000;color:#fff;font:16px/1.45 d,system-ui}main{max-width:420px;margin:auto;padding:28px;background:#0d0d0d;border:1px solid #2e2e2e;border-radius:18px}.logo{height:62px}h1{font-size:25px;margin:10px 0}p,label{color:#aaa}label{display:block;margin:14px 0 5px}input,select,button{width:100%;font:inherit;color:#fff;background:#000;border:1px solid #444;border-radius:12px;padding:10px 12px}button{margin-top:20px;background:#fff;color:#000;font-weight:bold;cursor:pointer}.status{min-height:24px;margin:14px 0 0;color:#aaa}a{color:#fff}</style></head>
|
||||
<body><main><img class="logo" src="/logo.png" alt=""><h1>Account recovery</h1>
|
||||
<div id="request"><p>We’ll send a one-time recovery link to the email saved on your account.</p><form id="request-form"><label>Username<input id="username" autocomplete="username" required></label><label>Recovery email<input id="email" type="email" autocomplete="email" required></label><label>What do you need to recover?<select id="kind"><option value="password">Password</option><option value="twoStep">2FA</option></select></label><button>Send recovery link</button></form></div>
|
||||
<div id="complete" hidden><p id="intro"></p><form id="complete-form"><label id="password-label">New password<input id="password" type="password" autocomplete="new-password" minlength="10"></label><button>Complete recovery</button></form></div><p class="status" id="status" role="status"></p><p><a href="/account">Back to sign in</a></p></main>
|
||||
<script>"use strict";const $=id=>document.getElementById(id),token=new URLSearchParams(location.search).get('token');const post=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});return {ok:r.ok,data:await r.json()}};const status=(text)=>$('status').textContent=text;if(token){post('/account/api/recover/check',{token}).then(r=>{if(!r.ok){status(r.data.error);return}$('request').hidden=true;$('complete').hidden=false;const two=r.data.kind==='twoStep';$('intro').textContent=two?'Confirm that you want to remove 2FA from this account.':'Choose a new password.';$('password-label').hidden=two;$('password').required=!two}).catch(()=>status('The server did not answer.'))}$('request-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/request',{username:$('username').value,email:$('email').value,kind:$('kind').value});status(r.data.ok||'Could not start recovery.')});$('complete-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/complete',{token,password:$('password').value});status(r.data.ok||r.data.error||'Could not complete recovery.')});</script></body></html>
|
||||
<div id="complete" hidden><p id="intro"></p><form id="complete-form"><label id="password-label"><span id="password-text">New password</span><input id="password" type="password" autocomplete="new-password" minlength="10" required></label><button>Complete recovery</button></form></div><p class="status" id="status" role="status"></p><p><a href="/account">Back to sign in</a></p></main>
|
||||
<script>"use strict";const $=id=>document.getElementById(id),token=new URLSearchParams(location.search).get('token');const post=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});return {ok:r.ok,data:await r.json()}};const status=(text)=>$('status').textContent=text;if(token){post('/account/api/recover/check',{token}).then(r=>{if(!r.ok){status(r.data.error);return}$('request').hidden=true;$('complete').hidden=false;const two=r.data.kind==='twoStep';$('intro').textContent=two?'Enter your password to remove 2FA from this account.':'Choose a new password.';$('password-text').textContent=two?'Your password':'New password';$('password').autocomplete=two?'current-password':'new-password';$('password').minLength=two?1:10}).catch(()=>status('The server did not answer.'))}$('request-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/request',{username:$('username').value,email:$('email').value,kind:$('kind').value});status(r.data.ok||'Could not start recovery.')});$('complete-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/complete',{token,password:$('password').value});status(r.data.ok||r.data.error||'Could not complete recovery.')});</script></body></html>
|
||||
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
|
||||
// loaded into the test server (NODE_OPTIONS --require, by test/signin.js):
|
||||
// Discord's OAuth2 API answered here, so a sign-in with Discord can be gone
|
||||
// through without Discord. the code Discord would send back names who signs
|
||||
// in ("mira" -> Mira's Discord account); anything else goes out as usual.
|
||||
|
||||
const USERS = {
|
||||
mira: {id: "100000000000000001", username: "mira_discord"},
|
||||
hal: {id: "100000000000000002", username: "hal_discord"},
|
||||
};
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url, options = {}) => {
|
||||
const href = String(url);
|
||||
if (!href.startsWith("https://discord.com/api/")) {
|
||||
return realFetch(url, options);
|
||||
}
|
||||
const json = (status, body) => new Response(JSON.stringify(body), {status, headers: {"Content-Type": "application/json"}});
|
||||
if (href.endsWith("/oauth2/token")) {
|
||||
const code = new URLSearchParams(String(options.body || "")).get("code");
|
||||
return USERS[code] ? json(200, {access_token: `token-${code}`, token_type: "Bearer"}) : json(400, {error: "invalid_grant"});
|
||||
}
|
||||
if (href.endsWith("/users/@me")) {
|
||||
const user = USERS[String((options.headers || {}).Authorization || "").replace(/^Bearer token-/, "")];
|
||||
return user ? json(200, {...user, discriminator: "0"}) : json(401, {});
|
||||
}
|
||||
return json(404, {});
|
||||
};
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
"use strict";
|
||||
|
||||
// end to end: what a sign-in takes besides a password. Discord says who
|
||||
// someone is, but the moderator and admin panels open only with their 2FA
|
||||
// code as well (lib/modpanel.js, lib/panel.js); and a recovery email resets
|
||||
// a password, but removes 2FA only with the password too, never right after
|
||||
// a password reset by email, and never for staff (lib/manage.js). Discord's
|
||||
// API is test/fake-discord.js, and recovery mail goes to a server of ours.
|
||||
|
||||
const assert = require("assert");
|
||||
const crypto = require("crypto");
|
||||
const http = require("http");
|
||||
const path = require("path");
|
||||
const harness = require("./harness.js");
|
||||
|
||||
const HTTP_PORT = 18096;
|
||||
const GAME_PORT = 19356;
|
||||
const MAIL_PORT = 18097;
|
||||
const BASE = `http://127.0.0.1:${HTTP_PORT}`;
|
||||
|
||||
// the authenticator app's side of 2FA (as in test/staff.js)
|
||||
const STEP = 30;
|
||||
const base32Decode = text => {
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join("");
|
||||
const bytes = [];
|
||||
for (let i = 0; i + 8 <= bits.length; i += 8) {
|
||||
bytes.push(parseInt(bits.slice(i, i + 8), 2));
|
||||
}
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
const codeAt = (secret, step) => {
|
||||
const counter = Buffer.alloc(8);
|
||||
counter.writeBigUInt64BE(BigInt(step));
|
||||
const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest();
|
||||
const offset = mac[mac.length - 1] & 0x0F;
|
||||
return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0");
|
||||
};
|
||||
const stepNow = () => Math.floor(Date.now() / 1000 / STEP);
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
// a code is taken once: each use needs a later step than the last.
|
||||
const used = {};
|
||||
const freshCode = async (who, secret) => {
|
||||
while (used[who] !== undefined && stepNow() <= used[who]) {
|
||||
await sleep(250);
|
||||
}
|
||||
used[who] = stepNow();
|
||||
return codeAt(secret, used[who]);
|
||||
};
|
||||
|
||||
// a browser: keeps every cookie it is given, follows no redirects.
|
||||
const browser = () => {
|
||||
const jar = new Map();
|
||||
const request = async (where, {body, method} = {}) => {
|
||||
const headers = {cookie: [...jar].map(([name, value]) => `${name}=${value}`).join("; ")};
|
||||
const options = {method: method || (body === undefined ? "GET" : "POST"), headers, redirect: "manual"};
|
||||
if (body !== undefined) {
|
||||
options.headers["Content-Type"] = "application/json";
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
const res = await fetch(where.startsWith("http") ? where : `${BASE}${where}`, options);
|
||||
for (const line of res.headers.getSetCookie()) {
|
||||
const [pair, ...attributes] = line.split(";");
|
||||
const [name, value] = pair.split("=");
|
||||
if (attributes.some(attribute => /^\s*max-age=0$/i.test(attribute)) || value === "") {
|
||||
jar.delete(name.trim());
|
||||
}
|
||||
else {
|
||||
jar.set(name.trim(), value);
|
||||
}
|
||||
}
|
||||
return {status: res.status, location: res.headers.get("location") || "", data: await res.json().catch(() => ({})), cookies: res.headers.getSetCookie()};
|
||||
};
|
||||
request.has = name => jar.has(name);
|
||||
return request;
|
||||
};
|
||||
|
||||
// a Discord sign-in through the fake Discord: start at `start`, come back
|
||||
// to `callback` as `who`. the redirect's address.
|
||||
const throughDiscord = async (page, start, callback, who) => {
|
||||
const begun = await page(start);
|
||||
assert.strictEqual(begun.status, 302, JSON.stringify(begun));
|
||||
const state = new URL(begun.location).searchParams.get("state");
|
||||
assert.ok(state, begun.location);
|
||||
const back = await page(`${callback}?state=${state}&code=${who}`);
|
||||
assert.strictEqual(back.status, 302);
|
||||
return back;
|
||||
};
|
||||
|
||||
const run = async mail => {
|
||||
const people = {Mira: "KettlePass21", Hal: "KettlePass22", Pip: "KettlePass23"};
|
||||
for (const [username, password] of Object.entries(people)) {
|
||||
const res = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({username, password, email: `${username.toLowerCase()}@example.com`, avatarType: 1, agreed: true})});
|
||||
assert.strictEqual(res.status, 200, await res.text());
|
||||
}
|
||||
|
||||
// Mira and Hal turn on 2FA and link their Discord accounts.
|
||||
const secrets = {};
|
||||
for (const username of ["Mira", "Hal"]) {
|
||||
const page = browser();
|
||||
assert.strictEqual((await page("/account/api/login", {body: {username, password: people[username]}})).status, 200);
|
||||
const begun = await page("/account/api/act", {body: {action: "twoStepStart", current: people[username]}});
|
||||
secrets[username] = begun.data.setup.secret;
|
||||
const confirmed = await page("/account/api/act", {body: {action: "twoStepConfirm", code: await freshCode(username, secrets[username])}});
|
||||
assert.ok(confirmed.data.ok, JSON.stringify(confirmed.data));
|
||||
const linked = await throughDiscord(page, "/account/discord/link", "/account/discord/callback", username.toLowerCase());
|
||||
assert.match(linked.location, /discord=linked/);
|
||||
}
|
||||
|
||||
// the admin makes Mira a moderator, and lets Hal into this dashboard with Discord.
|
||||
const admin = browser();
|
||||
assert.strictEqual((await admin("/admin/api/setup", {body: {password: "AdminPass99!"}})).status, 200);
|
||||
assert.strictEqual((await admin("/admin/api/login", {body: {password: "AdminPass99!"}})).status, 200);
|
||||
assert.match((await admin("/admin/api/account", {body: {username: "Mira", action: "role", role: "moderator"}})).data.ok, /moderator/);
|
||||
assert.ok((await admin("/admin/api/account", {body: {username: "Hal", action: "adminDashboardAccess", on: true}})).data.ok);
|
||||
|
||||
// --- the moderator panel: Discord, then the code
|
||||
const mod = browser();
|
||||
const back = await throughDiscord(mod, "/dashboard/staff/discord/login", "/dashboard/staff/discord/callback", "mira");
|
||||
assert.match(back.location, /discord=code$/);
|
||||
assert.ok(!mod.has("ajc_mod"), "Discord alone opened the moderator panel");
|
||||
assert.ok(mod.has("ajc_mod_pending"));
|
||||
assert.strictEqual((await mod("/dashboard/api/staff/state")).data.signedIn, false);
|
||||
assert.strictEqual((await mod("/dashboard/api/staff/players")).status, 401);
|
||||
const wrong = await mod("/dashboard/api/staff/discord/code", {body: {code: "000000"}});
|
||||
assert.strictEqual(wrong.status, 401);
|
||||
assert.strictEqual(wrong.data.expired, undefined);
|
||||
const right = await mod("/dashboard/api/staff/discord/code", {body: {code: await freshCode("Mira", secrets.Mira)}});
|
||||
assert.strictEqual(right.status, 200, JSON.stringify(right.data));
|
||||
assert.strictEqual(right.data.username, "Mira");
|
||||
assert.ok(mod.has("ajc_mod") && !mod.has("ajc_mod_pending"));
|
||||
assert.strictEqual((await mod("/dashboard/api/staff/state")).data.signedIn, true);
|
||||
// a waiting sign-in is used once
|
||||
const again = await mod("/dashboard/api/staff/discord/code", {body: {code: await freshCode("Mira", secrets.Mira)}});
|
||||
assert.strictEqual(again.data.expired, true);
|
||||
|
||||
// a few wrong codes, and it must start again at Discord
|
||||
const guesser = browser();
|
||||
await throughDiscord(guesser, "/dashboard/staff/discord/login", "/dashboard/staff/discord/callback", "mira");
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
const guess = await guesser("/dashboard/api/staff/discord/code", {body: {code: String(100000 + i)}});
|
||||
assert.strictEqual(guess.status, 401);
|
||||
assert.strictEqual(Boolean(guess.data.expired), i === 5);
|
||||
}
|
||||
assert.strictEqual((await guesser("/dashboard/api/staff/discord/code", {body: {code: await freshCode("Mira", secrets.Mira)}})).data.expired, true);
|
||||
assert.ok(!guesser.has("ajc_mod"));
|
||||
|
||||
// a Discord account linked to no staff gets nowhere
|
||||
const player = browser();
|
||||
const denied = await throughDiscord(player, "/dashboard/staff/discord/login", "/dashboard/staff/discord/callback", "hal");
|
||||
assert.match(denied.location, /discord=denied$/);
|
||||
assert.ok(!player.has("ajc_mod_pending"));
|
||||
|
||||
// --- the admin dashboard: the same
|
||||
const owner = browser();
|
||||
const adminBack = await throughDiscord(owner, "/dashboard/admin/discord/login", "/dashboard/admin/discord/callback", "hal");
|
||||
assert.match(adminBack.location, /discord=code$/);
|
||||
assert.ok(!owner.has("ajc_admin"), "Discord alone opened the admin dashboard");
|
||||
assert.strictEqual((await owner("/dashboard/api/admin/state")).data.signedIn, false);
|
||||
assert.strictEqual((await owner("/dashboard/api/admin/discord/code", {body: {code: "000000"}})).status, 401);
|
||||
const adminRight = await owner("/dashboard/api/admin/discord/code", {body: {code: await freshCode("Hal", secrets.Hal)}});
|
||||
assert.strictEqual(adminRight.status, 200, JSON.stringify(adminRight.data));
|
||||
assert.strictEqual((await owner("/dashboard/api/admin/state")).data.signedIn, true);
|
||||
|
||||
// --- recovery by email
|
||||
const recover = async (username, kind) => {
|
||||
const before = mail.length;
|
||||
const sent = await (browser())("/account/api/recover/request", {body: {username, email: `${username.toLowerCase()}@example.com`, kind}});
|
||||
assert.strictEqual(sent.status, 200);
|
||||
if (mail.length === before) {
|
||||
return null;
|
||||
}
|
||||
const message = mail.at(-1);
|
||||
assert.strictEqual(message.to, `${username.toLowerCase()}@example.com`);
|
||||
return new URL(/https?:\/\/\S+/.exec(message.text)[0]).searchParams.get("token");
|
||||
};
|
||||
const page = browser();
|
||||
|
||||
// a password, by the email alone
|
||||
const pipToken = await recover("Pip", "password");
|
||||
assert.strictEqual((await page("/account/api/recover/check", {body: {token: pipToken}})).data.kind, "password");
|
||||
assert.strictEqual((await page("/account/api/recover/complete", {body: {token: pipToken, password: "KettlePass33"}})).status, 200);
|
||||
// and then not 2FA as well, by the email, for a week
|
||||
const pipTwoStep = await recover("Pip", "twoStep");
|
||||
assert.match((await page("/account/api/recover/check", {body: {token: pipTwoStep}})).data.error, /within 7 days/);
|
||||
assert.match((await page("/account/api/recover/complete", {body: {token: pipTwoStep, password: "KettlePass33"}})).data.error, /within 7 days/);
|
||||
|
||||
// 2FA, by the email and the password
|
||||
const halToken = await recover("Hal", "twoStep");
|
||||
assert.strictEqual((await page("/account/api/recover/check", {body: {token: halToken}})).data.kind, "twoStep");
|
||||
const noPassword = await page("/account/api/recover/complete", {body: {token: halToken, password: "not it"}});
|
||||
assert.strictEqual(noPassword.status, 401);
|
||||
assert.strictEqual((await page("/account/api/recover/complete", {body: {token: halToken, password: people.Hal}})).status, 200);
|
||||
const halNow = browser();
|
||||
assert.strictEqual((await halNow("/account/api/login", {body: {username: "Hal", password: people.Hal}})).status, 200, "2FA was not removed");
|
||||
|
||||
// never for staff: a mailbox does not make anyone a moderator
|
||||
const miraToken = await recover("Mira", "twoStep");
|
||||
assert.match((await page("/account/api/recover/check", {body: {token: miraToken}})).data.error, /Staff accounts/);
|
||||
assert.match((await page("/account/api/recover/complete", {body: {token: miraToken, password: people.Mira}})).data.error, /Staff accounts/);
|
||||
assert.strictEqual((await mod("/dashboard/api/staff/state")).data.signedIn, true, "Mira's 2FA went");
|
||||
|
||||
// a few recovery emails an hour for one account, from anywhere
|
||||
assert.ok(await recover("Mira", "password"));
|
||||
assert.ok(await recover("Mira", "password"));
|
||||
assert.strictEqual(await recover("Mira", "password"), null);
|
||||
};
|
||||
|
||||
const main = async () => {
|
||||
const mail = [];
|
||||
const mailServer = http.createServer((req, res) => {
|
||||
let body = "";
|
||||
req.on("data", chunk => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
assert.strictEqual(req.headers.authorization, "Bearer test-mail-token");
|
||||
mail.push(JSON.parse(body));
|
||||
res.writeHead(200);
|
||||
res.end();
|
||||
});
|
||||
});
|
||||
await new Promise(resolve => mailServer.listen(MAIL_PORT, "127.0.0.1", resolve));
|
||||
Object.assign(process.env, {
|
||||
// forward slashes: NODE_OPTIONS reads a backslash as an escape (Windows)
|
||||
NODE_OPTIONS: `${process.env.NODE_OPTIONS || ""} --require "${path.join(__dirname, "fake-discord.js").replace(/\\/g, "/")}"`.trim(),
|
||||
AJ_DISCORD_CLIENT_ID: "123456789012345678",
|
||||
AJ_DISCORD_CLIENT_SECRET: "test-secret",
|
||||
AJ_RECOVERY_MAIL_URL: `http://127.0.0.1:${MAIL_PORT}/mail`,
|
||||
AJ_RECOVERY_MAIL_TOKEN: "test-mail-token",
|
||||
});
|
||||
try {
|
||||
await harness.withServer("sign-in test", HTTP_PORT, GAME_PORT, () => run(mail));
|
||||
}
|
||||
finally {
|
||||
mailServer.close();
|
||||
}
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user