Some checks failed
Node.js CI - Dockge / ${{ matrix.os }} (22, ubuntu-latest) (push) Successful in 1m47s
json-yaml-validate / json-yaml-validate (push) Successful in 12s
Nightly Release / release-nightly (push) Failing after 44s
Node.js CI - Dockge / ${{ matrix.os }} (22, macos-latest) (push) Has been cancelled
Node.js CI - Dockge / ${{ matrix.os }} (22, windows-latest) (push) Has been cancelled
432 lines
15 KiB
TypeScript
432 lines
15 KiB
TypeScript
// @ts-ignore
|
|
import composerize from "composerize";
|
|
import { SocketHandler } from "../socket-handler.js";
|
|
import { DockgeServer } from "../dockge-server";
|
|
import { log } from "../log";
|
|
import { R } from "redbean-node";
|
|
import { loginRateLimiter, twoFaRateLimiter } from "../rate-limiter";
|
|
import { generatePasswordHash, needRehashPassword, shake256, SHAKE256_LENGTH, verifyPassword } from "../password-hash";
|
|
import { User } from "../models/user";
|
|
import {
|
|
callbackError,
|
|
checkLogin,
|
|
DockgeSocket,
|
|
doubleCheckPassword,
|
|
ValidationError
|
|
} from "../util-server";
|
|
import { passwordStrength } from "check-password-strength";
|
|
import { isSessionRevoked, issueSession, revokeSession, verifySession, withSession } from "../auth-session";
|
|
import { Settings } from "../settings";
|
|
import fs, { promises as fsAsync } from "fs";
|
|
import path from "path";
|
|
|
|
export class MainSocketHandler extends SocketHandler {
|
|
create(socket : DockgeSocket, server : DockgeServer) {
|
|
|
|
// ***************************
|
|
// Public Socket API
|
|
// ***************************
|
|
|
|
// Setup
|
|
socket.on("setup", async (username, password, callback) => {
|
|
try {
|
|
if (passwordStrength(password).value === "Too weak") {
|
|
throw new Error("Password is too weak. It should contain alphabetic and numeric characters. It must be at least 6 characters in length.");
|
|
}
|
|
|
|
if ((await R.knex("user").count("id as count").first()).count !== 0) {
|
|
throw new Error("Dockge has been initialized. If you want to run setup again, please delete the database.");
|
|
}
|
|
|
|
const user = R.dispense("user");
|
|
user.username = username;
|
|
user.password = generatePasswordHash(password);
|
|
await R.store(user);
|
|
|
|
server.needSetup = false;
|
|
|
|
callback({
|
|
ok: true,
|
|
msg: "successAdded",
|
|
msgi18n: true,
|
|
});
|
|
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
callback({
|
|
ok: false,
|
|
msg: e.message,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
// Login by token
|
|
socket.on("loginByToken", async (token, callback) => {
|
|
if (typeof callback !== "function") {
|
|
return;
|
|
}
|
|
const clientIP = await server.getClientIP(socket);
|
|
|
|
log.info("auth", `Login by token. IP=${clientIP}`);
|
|
|
|
try {
|
|
const { username, passwordFingerprint, session } = verifySession(token, server.jwtSecret);
|
|
|
|
log.info("auth", "Username from JWT: " + username);
|
|
|
|
await withSession(session, async () => {
|
|
if (await isSessionRevoked(session)) {
|
|
throw new Error("Session token has been revoked");
|
|
}
|
|
const user = await R.findOne("user", " username = ? AND active = 1 ", [ username ]) as User | null;
|
|
if (!user) {
|
|
log.info("auth", `Inactive or deleted user ${username}. IP=${clientIP}`);
|
|
callback({
|
|
ok: false,
|
|
msg: "authUserInactiveOrDeleted",
|
|
msgi18n: true,
|
|
});
|
|
return;
|
|
}
|
|
// Check if the password changed
|
|
if (passwordFingerprint !== shake256(user.password, SHAKE256_LENGTH)) {
|
|
throw new Error("The token is invalid due to password change or old token");
|
|
}
|
|
if (session.expiresAt <= Math.floor(Date.now() / 1000)) {
|
|
throw new Error("Session token has expired");
|
|
}
|
|
if (!socket.connected) {
|
|
return;
|
|
}
|
|
socket.authSession = session;
|
|
await server.afterLogin(socket, user);
|
|
log.info("auth", `Successfully logged in user ${username}. IP=${clientIP}`);
|
|
callback({ ok: true });
|
|
});
|
|
} catch (error) {
|
|
if (!(error instanceof Error)) {
|
|
console.error("Unknown error:", error);
|
|
return;
|
|
}
|
|
log.error("auth", `Invalid token. IP=${clientIP}`);
|
|
if (error.message) {
|
|
log.error("auth", error.message + ` IP=${clientIP}`);
|
|
}
|
|
callback({
|
|
ok: false,
|
|
msg: "authInvalidToken",
|
|
msgi18n: true,
|
|
});
|
|
}
|
|
|
|
});
|
|
|
|
// Login
|
|
socket.on("login", async (data, callback) => {
|
|
const clientIP = await server.getClientIP(socket);
|
|
|
|
log.info("auth", `Login by username + password. IP=${clientIP}`);
|
|
|
|
// Checking
|
|
if (typeof callback !== "function") {
|
|
return;
|
|
}
|
|
|
|
if (!data) {
|
|
return;
|
|
}
|
|
|
|
// Login Rate Limit
|
|
if (!await loginRateLimiter.pass(callback)) {
|
|
log.info("auth", `Too many failed requests for user ${data.username}. IP=${clientIP}`);
|
|
return;
|
|
}
|
|
|
|
const user = await this.login(data.username, data.password);
|
|
|
|
if (user) {
|
|
if (user.twofa_status === 0) {
|
|
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
|
|
|
callback({
|
|
ok: true,
|
|
token: this.startSession(socket, server, user),
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (user.twofa_status === 1 && !data.token) {
|
|
|
|
log.info("auth", `2FA token required for user ${data.username}. IP=${clientIP}`);
|
|
|
|
callback({
|
|
tokenRequired: true,
|
|
});
|
|
}
|
|
|
|
if (data.token) {
|
|
// @ts-ignore
|
|
const verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions);
|
|
|
|
if (user.twofa_last_token !== data.token && verify) {
|
|
await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [
|
|
data.token,
|
|
user.id,
|
|
]);
|
|
|
|
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
|
|
|
callback({
|
|
ok: true,
|
|
token: this.startSession(socket, server, user),
|
|
});
|
|
} else {
|
|
|
|
log.warn("auth", `Invalid token provided for user ${data.username}. IP=${clientIP}`);
|
|
|
|
callback({
|
|
ok: false,
|
|
msg: "authInvalidToken",
|
|
msgi18n: true,
|
|
});
|
|
}
|
|
}
|
|
} else {
|
|
|
|
log.warn("auth", `Incorrect username or password for user ${data.username}. IP=${clientIP}`);
|
|
|
|
callback({
|
|
ok: false,
|
|
msg: "authIncorrectCreds",
|
|
msgi18n: true,
|
|
});
|
|
}
|
|
|
|
});
|
|
|
|
socket.on("logout", async (callback) => {
|
|
try {
|
|
checkLogin(socket);
|
|
const session = socket.authSession;
|
|
if (session) {
|
|
await withSession(session, async () => {
|
|
await revokeSession(session);
|
|
server.disconnectTokenSockets(session.fingerprint, socket.id);
|
|
});
|
|
}
|
|
if (typeof callback === "function") {
|
|
callback({ ok: true });
|
|
}
|
|
socket.disconnect();
|
|
} catch (error) {
|
|
log.error("auth", error);
|
|
if (typeof callback === "function") {
|
|
callback({
|
|
ok: false,
|
|
msg: "authLogoutFailed",
|
|
msgi18n: true,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
// Change Password
|
|
socket.on("changePassword", async (password, callback) => {
|
|
try {
|
|
checkLogin(socket);
|
|
|
|
if (! password.newPassword) {
|
|
throw new Error("Invalid new password");
|
|
}
|
|
|
|
if (passwordStrength(password.newPassword).value === "Too weak") {
|
|
throw new Error("Password is too weak. It should contain alphabetic and numeric characters. It must be at least 6 characters in length.");
|
|
}
|
|
|
|
let user = await doubleCheckPassword(socket, password.currentPassword);
|
|
await user.resetPassword(password.newPassword);
|
|
|
|
server.disconnectAllSocketClients(user.id, socket.id);
|
|
|
|
callback({
|
|
ok: true,
|
|
msg: "Password has been updated successfully.",
|
|
});
|
|
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
callback({
|
|
ok: false,
|
|
msg: e.message,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
socket.on("getSettings", async (callback) => {
|
|
try {
|
|
checkLogin(socket);
|
|
const data = await Settings.getSettings("general");
|
|
|
|
if (fs.existsSync(path.join(server.stacksDir, "global.env"))) {
|
|
data.globalENV = fs.readFileSync(path.join(server.stacksDir, "global.env"), "utf-8");
|
|
} else {
|
|
data.globalENV = "# VARIABLE=value #comment";
|
|
}
|
|
|
|
callback({
|
|
ok: true,
|
|
data: data,
|
|
});
|
|
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
callback({
|
|
ok: false,
|
|
msg: e.message,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
socket.on("setSettings", async (data, currentPassword, callback) => {
|
|
if (typeof callback !== "function") {
|
|
return;
|
|
}
|
|
try {
|
|
checkLogin(socket);
|
|
|
|
let disableAuth = data.disableAuth;
|
|
if (Object.hasOwn(data, "disableAuth") && typeof disableAuth !== "boolean") {
|
|
throw new ValidationError("Invalid authentication setting.");
|
|
}
|
|
delete data.disableAuth;
|
|
if (disableAuth === true) {
|
|
if (await Settings.get("disableAuth", false)) {
|
|
// Older clients include the current flag when saving unrelated settings.
|
|
disableAuth = undefined;
|
|
} else {
|
|
await doubleCheckPassword(socket, currentPassword);
|
|
}
|
|
}
|
|
if (!socket.connected) {
|
|
throw new Error("You are not logged in.");
|
|
}
|
|
// Handle global.env
|
|
if (data.globalENV && data.globalENV != "# VARIABLE=value #comment") {
|
|
await fsAsync.writeFile(path.join(server.stacksDir, "global.env"), data.globalENV);
|
|
} else {
|
|
await fsAsync.rm(path.join(server.stacksDir, "global.env"), {
|
|
recursive: true,
|
|
force: true
|
|
});
|
|
}
|
|
delete data.globalENV;
|
|
|
|
await Settings.setSettings("general", data);
|
|
|
|
if (typeof disableAuth === "boolean") {
|
|
if (!socket.connected) {
|
|
throw new Error("You are not logged in.");
|
|
}
|
|
await Settings.set("disableAuth", disableAuth, "general");
|
|
}
|
|
|
|
callback({
|
|
ok: true,
|
|
msg: "Saved"
|
|
});
|
|
|
|
if (disableAuth === false) {
|
|
server.revokeBypassedSessions();
|
|
}
|
|
if (socket.connected) {
|
|
server.sendInfo(socket);
|
|
}
|
|
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
callback({
|
|
ok: false,
|
|
msg: e.message,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
// Disconnect all other socket clients of the user
|
|
socket.on("disconnectOtherSocketClients", async () => {
|
|
try {
|
|
checkLogin(socket);
|
|
server.disconnectAllSocketClients(socket.userID, socket.id);
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
log.warn("disconnectOtherSocketClients", e.message);
|
|
}
|
|
}
|
|
});
|
|
|
|
// composerize
|
|
socket.on("composerize", async (dockerRunCommand : unknown, callback) => {
|
|
try {
|
|
checkLogin(socket);
|
|
|
|
if (typeof(dockerRunCommand) !== "string") {
|
|
throw new ValidationError("dockerRunCommand must be a string");
|
|
}
|
|
|
|
// Option: 'latest' | 'v2x' | 'v3x'
|
|
let composeTemplate = composerize(dockerRunCommand, "", "latest");
|
|
|
|
// Remove the first line "name: <your project name>"
|
|
composeTemplate = composeTemplate.split("\n").slice(1).join("\n");
|
|
|
|
callback({
|
|
ok: true,
|
|
composeTemplate,
|
|
});
|
|
} catch (e) {
|
|
callbackError(e, callback);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Attach the new token identity to the connection before returning the token.
|
|
* @param socket Connection being authenticated
|
|
* @param server Dockge instance issuing the token
|
|
* @param user Authenticated user
|
|
* @returns The signed JWT
|
|
*/
|
|
private startSession(socket: DockgeSocket, server: DockgeServer, user: User): string {
|
|
const { token, session } = issueSession(user.username, user.password, server.jwtSecret);
|
|
socket.authSession = session;
|
|
server.afterLogin(socket, user);
|
|
return token;
|
|
}
|
|
|
|
async login(username : string, password : string) : Promise<User | null> {
|
|
if (typeof username !== "string" || typeof password !== "string") {
|
|
return null;
|
|
}
|
|
|
|
const user = await R.findOne("user", " username = ? AND active = 1 ", [
|
|
username,
|
|
]) as User;
|
|
|
|
if (user && verifyPassword(password, user.password)) {
|
|
// Upgrade the hash to bcrypt
|
|
if (needRehashPassword(user.password)) {
|
|
await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [
|
|
generatePasswordHash(password),
|
|
user.id,
|
|
]);
|
|
}
|
|
return user;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|