stuffy
This commit is contained in:
@@ -1,505 +1,447 @@
|
||||
import { crackdown } from "./crackdown.js";
|
||||
|
||||
const MsgContext.REPLY = "R";
|
||||
const QUIT = "QUIT";
|
||||
const HELP = "HELP";
|
||||
const COLON = ":";
|
||||
const helpRegex = /^:help(?:\s+(.*))?$/;
|
||||
const colonRegex = /^:([a-z0-9_]+)(?:\s+(.*))?$/;
|
||||
class MUDClient {
|
||||
//
|
||||
// Constructor
|
||||
constructor() {
|
||||
/** @type {WebSocket} Our WebSocket */
|
||||
this.websocket = null;
|
||||
//
|
||||
// Constructor
|
||||
constructor() {
|
||||
/** @type {WebSocket} Our WebSocket */
|
||||
this.websocket = null;
|
||||
|
||||
/** @type {boolean} Are we in development mode (decided by the server);
|
||||
/** @type {boolean} Are we in development mode (decided by the server); */
|
||||
this.dev = false;
|
||||
|
||||
/** @type {string|null} The message type of the last thing we were asked. */
|
||||
this.replyType = null;
|
||||
this.promptOptions = {};
|
||||
this.shouldReply = false;
|
||||
|
||||
/** @type {string|null} The #tag of the last thing we were asked. */
|
||||
this.replyTag = null;
|
||||
/** @type {HTMLElement} The output "monitor" */
|
||||
this.output = document.getElementById("output");
|
||||
|
||||
/** @type {HTMLElement} The output "monitor" */
|
||||
this.output = document.getElementById("output");
|
||||
/** @type {HTMLElement} The input element */
|
||||
this.input = document.getElementById("input");
|
||||
|
||||
/** @type {HTMLElement} The input element */
|
||||
this.input = document.getElementById("input");
|
||||
/** @type {HTMLElement} Status indicator */
|
||||
this.status = document.getElementById("status");
|
||||
|
||||
/** @type {HTMLElement} The send/submit button */
|
||||
this.sendButton = document.getElementById("send");
|
||||
// Passwords are crypted and salted before being sent to the server
|
||||
// This means that if ANY of these three parameters below change,
|
||||
// The server can no longer accept the passwords.
|
||||
/** @type {string} Hashing method to use for client-side password hashing */
|
||||
this.digest = "SHA-256";
|
||||
|
||||
/** @type {HTMLElement} Status indicator */
|
||||
this.status = document.getElementById("status");
|
||||
/** @type {string} Salt string to use for client-side password hashing */
|
||||
this.salt = "No salt, no shorts, no service";
|
||||
|
||||
// Passwords are crypted and salted before being sent to the server
|
||||
// This means that if ANY of these three parameters below change,
|
||||
// The server can no longer accept the passwords.
|
||||
/** @type {string} Hashing method to use for client-side password hashing */
|
||||
this.digest = "SHA-256";
|
||||
/** @type {string} Number of times the hashing should be done */
|
||||
this.rounds = 1000;
|
||||
|
||||
/** @type {string} Salt string to use for client-side password hashing */
|
||||
this.salt = "No salt, no shorts, no service";
|
||||
/** @type {string} the username also salts the password, so the username must never change. */
|
||||
this.username = "";
|
||||
|
||||
/** @type {string} Number of times the hashing should be done */
|
||||
this.rounds = 1000;
|
||||
|
||||
/** @type {string} the username also salts the password, so the username must never change. */
|
||||
this.username = "";
|
||||
|
||||
this.setupEventListeners();
|
||||
this.connect();
|
||||
}
|
||||
|
||||
/** @param {string} password the password to be hashed */
|
||||
async hashPassword(password) {
|
||||
const encoder = new TextEncoder();
|
||||
let data = encoder.encode(password + this.salt);
|
||||
|
||||
for (let i = 0; i < this.rounds; i++) {
|
||||
const hashBuffer = await crypto.subtle.digest(this.digest, data);
|
||||
data = new Uint8Array(hashBuffer); // feed hash back in
|
||||
this.setupEventListeners();
|
||||
this.connect();
|
||||
}
|
||||
|
||||
// Convert final hash to hex
|
||||
const rawHash = Array.from(data)
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
/** @param {string} password the password to be hashed */
|
||||
async hashPassword(password) {
|
||||
const encoder = new TextEncoder();
|
||||
let data = encoder.encode(password + this.salt);
|
||||
|
||||
return `KimsKrappyKryptoV1:${this.salt}:${this.rounds}:${this.digest}:${rawHash}`;
|
||||
}
|
||||
for (let i = 0; i < this.rounds; i++) {
|
||||
const hashBuffer = await crypto.subtle.digest(this.digest, data);
|
||||
data = new Uint8Array(hashBuffer); // feed hash back in
|
||||
}
|
||||
|
||||
connect() {
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsUrl = `${protocol}//${window.location.host}`;
|
||||
// Convert final hash to hex
|
||||
const rawHash = Array.from(data)
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
|
||||
this.updateStatus("Connecting...", "connecting");
|
||||
return `KimsKrappyKryptoV1:${this.salt}:${this.rounds}:${this.digest}:${rawHash}`;
|
||||
}
|
||||
|
||||
try {
|
||||
this.websocket = new WebSocket(wsUrl);
|
||||
connect() {
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsUrl = `${protocol}//${window.location.host}`;
|
||||
|
||||
this.websocket.onopen = () => {
|
||||
this.updateStatus("Connected", "connected");
|
||||
this.input.disabled = false;
|
||||
this.sendButton.disabled = false;
|
||||
this.input.focus();
|
||||
this.output.innerHTML = "";
|
||||
};
|
||||
this.updateStatus("Connecting...", "connecting");
|
||||
|
||||
this.websocket.onmessage = (event) => {
|
||||
console.debug(event);
|
||||
const data = JSON.parse(event.data);
|
||||
this.onMessage(data);
|
||||
this.input.focus();
|
||||
};
|
||||
try {
|
||||
this.websocket = new WebSocket(wsUrl);
|
||||
|
||||
this.websocket.onclose = () => {
|
||||
this.updateStatus("Disconnected", "disconnected");
|
||||
this.input.disabled = true;
|
||||
this.sendButton.disabled = true;
|
||||
this.websocket.onopen = () => {
|
||||
this.updateStatus("Connected", "connected");
|
||||
this.input.disabled = false;
|
||||
this.input.focus();
|
||||
this.output.innerHTML = "";
|
||||
};
|
||||
|
||||
// Attempt to reconnect after 3 seconds
|
||||
setTimeout(() => this.connect(), 3000);
|
||||
};
|
||||
this.websocket.onmessage = (event) => {
|
||||
console.debug(event);
|
||||
const data = JSON.parse(event.data);
|
||||
this.onMessageReceived(data);
|
||||
this.input.focus();
|
||||
};
|
||||
|
||||
this.websocket.onerror = (error) => {
|
||||
this.updateStatus("Connection Error", "error");
|
||||
this.writeToOutput("Connection error occurred. Retrying...", {
|
||||
class: "error",
|
||||
this.websocket.onclose = () => {
|
||||
this.updateStatus("Disconnected", "disconnected");
|
||||
this.input.disabled = true;
|
||||
|
||||
// Attempt to reconnect after 3 seconds
|
||||
setTimeout(() => this.connect(), 3000);
|
||||
};
|
||||
|
||||
this.websocket.onerror = (error) => {
|
||||
this.updateStatus("Connection Error", "error");
|
||||
this.writeToOutput("Connection error occurred. Retrying...", { class: "error" });
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
this.updateStatus("Connection Failed", "error");
|
||||
setTimeout(() => this.connect(), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
document.addEventListener("keypress", (e) => {
|
||||
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||
this.input.focus();
|
||||
}
|
||||
});
|
||||
this.input.addEventListener("keypress", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
this.onUserCommand();
|
||||
}
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
this.updateStatus("Connection Failed", "error");
|
||||
setTimeout(() => this.connect(), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
document.addEventListener("keypress", (e) => {
|
||||
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||
this.input.focus();
|
||||
}
|
||||
});
|
||||
this.input.addEventListener("keypress", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
this.onUserCommand();
|
||||
}
|
||||
});
|
||||
/**
|
||||
* Send a json-encoded message to the server via websocket.
|
||||
*
|
||||
* @param {messageType} string
|
||||
* @param {...any} rest
|
||||
*/
|
||||
send(messageType, ...args) {
|
||||
console.log("sending", messageType, args);
|
||||
|
||||
this.sendButton.addEventListener("click", () => {
|
||||
this.onUserCommand();
|
||||
});
|
||||
|
||||
// Command history
|
||||
this.commandHistory = [];
|
||||
this.historyIndex = -1;
|
||||
|
||||
this.input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (this.historyIndex < this.commandHistory.length - 1) {
|
||||
this.historyIndex++;
|
||||
this.input.value =
|
||||
this.commandHistory[
|
||||
this.commandHistory.length - 1 - this.historyIndex
|
||||
];
|
||||
if (args.length === 0) {
|
||||
this.websocket.send(JSON.stringify([messageType]));
|
||||
return;
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
if (this.historyIndex > 0) {
|
||||
this.historyIndex--;
|
||||
this.input.value =
|
||||
this.commandHistory[
|
||||
this.commandHistory.length - 1 - this.historyIndex
|
||||
];
|
||||
} else if (this.historyIndex === 0) {
|
||||
this.historyIndex = -1;
|
||||
this.input.value = "";
|
||||
|
||||
this.websocket.send(JSON.stringify([messageType, ...args]));
|
||||
}
|
||||
|
||||
/**
|
||||
* User has entered a command
|
||||
*/
|
||||
async onUserCommand() {
|
||||
/** @type {string} */
|
||||
const inputText = this.input.value.trim(); // Trim user's input.
|
||||
|
||||
this.input.value = ""; // Reset the input text field
|
||||
this.input.type = "text"; // Make sure it reverts to being a text input (as opposed to being a password input)
|
||||
|
||||
// -- This is a sneaky command that should not be in production?
|
||||
//
|
||||
// In reality we want to use :clear, nor /clear
|
||||
// :clear would be sent to the server, and we ask if it's okay
|
||||
// to clear the screen right now, and only on a positive answer would we
|
||||
// allow the screen to be cleared. Maybe.....
|
||||
if (inputText === "/clear") {
|
||||
this.output.innerHTML = "";
|
||||
this.input.value = "";
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a json-encoded message to the server via websocket.
|
||||
*
|
||||
* @param {messageType} string
|
||||
* @param {...any} rest
|
||||
*/
|
||||
send(messageType, ...args) {
|
||||
if (args.length === 0) {
|
||||
this.websocket.send(JSON.stringify([messageType]));
|
||||
return;
|
||||
//
|
||||
// Don't allow sending messages (for now)
|
||||
// Later on, prompts may give us the option to simply "press enter";
|
||||
if (!inputText) {
|
||||
console.debug("Cannot send empty message - YET");
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Can't send a message without a websocket
|
||||
if (!(this.websocket && this.websocket.readyState === WebSocket.OPEN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// The quit command has its own message type
|
||||
if (inputText === ":quit") {
|
||||
this.send(QUIT);
|
||||
this.writeToOutput("> " + inputText, { class: "input" });
|
||||
return;
|
||||
}
|
||||
|
||||
// _ _
|
||||
// _ | |__ ___| |_ __
|
||||
// (_) | '_ \ / _ \ | '_ \
|
||||
// _ | | | | __/ | |_) |
|
||||
// (_) |_| |_|\___|_| .__/
|
||||
// |_|
|
||||
// ------------------------
|
||||
//
|
||||
// The quit command has its own message type
|
||||
let help = helpRegex.exec(inputText);
|
||||
if (help) {
|
||||
console.log("here");
|
||||
help[1] ? this.send(HELP, help[1].trim()) : this.send(HELP);
|
||||
this.writeToOutput("> " + inputText, { class: "input" });
|
||||
return;
|
||||
}
|
||||
|
||||
// _
|
||||
// _ ___ ___ _ __ ___ _ __ ___ __ _ _ __ __| |
|
||||
// (_) / __/ _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` |
|
||||
// _ | (_| (_) | | | | | | | | | | | (_| | | | | (_| |
|
||||
// (_) \___\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_|
|
||||
//------------------------------------------------------
|
||||
let colonCommand = colonRegex.exec(inputText);
|
||||
if (colonCommand) {
|
||||
this.send(COLON, colonCommand[1], colonCommand[2]);
|
||||
this.writeToOutput("> " + inputText, { class: "input" });
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// The server doesn't want any input from us, so we just ignore this input
|
||||
if (!this.shouldReply) {
|
||||
// the server is not ready for data!
|
||||
return;
|
||||
}
|
||||
// _
|
||||
// _ __ ___ _ __ | |_ _
|
||||
// | '__/ _ \ '_ \| | | | |
|
||||
// | | | __/ |_) | | |_| |
|
||||
// |_| \___| .__/|_|\__, |
|
||||
// |_| |___/
|
||||
//-------------------------
|
||||
// We handle replies below
|
||||
//-------------------------
|
||||
|
||||
// The server wants a password, let's hash it before sending it.
|
||||
if (this.promptOptions.password) {
|
||||
inputText = await this.hashPassword(inputText);
|
||||
}
|
||||
|
||||
//
|
||||
// The server wants a username, let's save it in case we need it.
|
||||
if (this.promptOptions.username) {
|
||||
this.username = inputText;
|
||||
}
|
||||
|
||||
this.send(REPLY, inputText);
|
||||
this.shouldReply = false;
|
||||
this.promptOptions = {};
|
||||
|
||||
//
|
||||
// We add our own command to the output stream so the
|
||||
// player can see what they typed.
|
||||
this.writeToOutput("> " + inputText, { class: "input" });
|
||||
return;
|
||||
}
|
||||
|
||||
this.websocket.send(JSON.stringify([messageType, ...args]));
|
||||
}
|
||||
|
||||
//
|
||||
// Add a command to history so we can go back to previous commands with arrow keys.
|
||||
_addCommandToHistory(command) {
|
||||
// ___ __ __
|
||||
// / _ \ _ __ | \/ | ___ ___ ___ __ _ __ _ ___
|
||||
// | | | | '_ \| |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \
|
||||
// | |_| | | | | | | | __/\__ \__ \ (_| | (_| | __/
|
||||
// \___/|_| |_|_| |_|\___||___/___/\__,_|\__, |\___|
|
||||
//
|
||||
// we do not add usernames or passwords to history.
|
||||
if (this.replyType === "password" || this.replyType === "username") {
|
||||
return;
|
||||
/** @param {any[]} data*/
|
||||
onMessageReceived(data) {
|
||||
if (this.dev) {
|
||||
console.debug(data);
|
||||
}
|
||||
const messageType = data.shift();
|
||||
|
||||
// prompt
|
||||
if (messageType === "P") {
|
||||
return this.handlePromptMessage(data);
|
||||
}
|
||||
|
||||
// text message
|
||||
if (messageType === "T") {
|
||||
return this.handleTextMessages(data);
|
||||
}
|
||||
|
||||
// error
|
||||
if (messageType === "E") {
|
||||
return this.handleErrorMessage(data);
|
||||
}
|
||||
|
||||
// fatal error / calamity
|
||||
if (messageType === "CALAMITY") {
|
||||
return this.handleCalamityMessage(data);
|
||||
}
|
||||
|
||||
// system message
|
||||
if (messageType === "_") {
|
||||
return this.handleSystemMessages(data);
|
||||
}
|
||||
// debug
|
||||
if (messageType === "dbg") {
|
||||
return this.handleDebugMessages(data);
|
||||
}
|
||||
|
||||
if (this.dev) {
|
||||
this.writeToOutput(`unknown message type: ${messageType}: ${JSON.stringify(data)}`, {
|
||||
class: "debug",
|
||||
verbatim: true,
|
||||
});
|
||||
}
|
||||
console.debug("unknown message type", data);
|
||||
}
|
||||
|
||||
//
|
||||
// Adding empty commands makes no sense.
|
||||
// Why would the user navigate back through their history to
|
||||
// find and empty command when they can just press enter.
|
||||
if (command === "") {
|
||||
return;
|
||||
// "m" => normal/standard message to be displayed to the user
|
||||
handleTextMessages(data) {
|
||||
const options = { ...data[1] }; // coerce options into an object.
|
||||
|
||||
// normal text message to be shown to the player
|
||||
this.writeToOutput(data[0], options);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Add to command our history
|
||||
// But not if the command was a password.
|
||||
this.historyIndex = -1;
|
||||
|
||||
//
|
||||
// We do not add the same commands many times in a row.
|
||||
if (this.commandHistory[this.commandHistory.length - 1] === command) {
|
||||
return;
|
||||
// Debug messages let the server send data to be displayed on the player's screen
|
||||
// and also logged to the players browser's log.
|
||||
handleDebugMessages(data) {
|
||||
if (!this.dev) {
|
||||
return; // debug messages are thrown away if we're not in dev mode.
|
||||
}
|
||||
this.writeToOutput(data, { class: "debug", verbatim: true });
|
||||
console.debug("DBG", data);
|
||||
}
|
||||
|
||||
//
|
||||
// Add the command to the history stack
|
||||
this.commandHistory.push(command);
|
||||
if (this.commandHistory.length > 50) {
|
||||
this.commandHistory.shift();
|
||||
}
|
||||
}
|
||||
// "_" => system messages, not to be displayed
|
||||
handleSystemMessages(data) {
|
||||
if (data.length < 2) {
|
||||
console.debug("malformed system message", data);
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* User has entered a command
|
||||
*/
|
||||
onUserCommand() {
|
||||
//
|
||||
// Trim user's input.
|
||||
const command = this.input.value.trim();
|
||||
this.input.value = "";
|
||||
this.input.type = "text";
|
||||
console.debug("Incoming system message", data);
|
||||
|
||||
this._addCommandToHistory(command);
|
||||
/** @type {string} */
|
||||
const messageType = data.shift();
|
||||
|
||||
// -- This is a sneaky command that should not be in production?
|
||||
//
|
||||
// In reality we want to use :clear, nor /clear
|
||||
// :clear would be sent to the server, and we ask if it's okay
|
||||
// to clear the screen right now, and only on a positive answer would we
|
||||
// allow the screen to be cleared. Maybe.....
|
||||
if (command === "/clear") {
|
||||
this.output.innerHTML = "";
|
||||
this.input.value = "";
|
||||
return;
|
||||
switch (messageType) {
|
||||
case "username":
|
||||
this.username = data[0];
|
||||
break;
|
||||
case "dev":
|
||||
// This is a message that tells us that the server is in
|
||||
// "dev" mode, and that we should do the same.
|
||||
this.dev = data[0];
|
||||
this.status.textContent = "[DEV] " + this.status.textContent;
|
||||
break;
|
||||
case "salt":
|
||||
this.salt = data[0];
|
||||
console.debug("updating crypto salt", data[0]);
|
||||
break;
|
||||
default:
|
||||
console.debug("unknown system message", messageType, data);
|
||||
}
|
||||
|
||||
// If we're in dev mode, we should output all system messages (in a shaded/faint fashion).
|
||||
if (this.dev) {
|
||||
this.writeToOutput(`system message: ${messageType} = ${JSON.stringify(data)}`, { class: "debug" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Don't allow sending messages (for now)
|
||||
// Later on, prompts may give us the option to simply "press enter";
|
||||
if (!command) {
|
||||
console.debug("Cannot send empty message - YET");
|
||||
return;
|
||||
// "calamity" => lethal error. Close connection.
|
||||
// Consider hard refresh of page to reset all variables
|
||||
handleCalamityMessage(data) {
|
||||
//
|
||||
// We assume that calamity errors are pre-formatted, and we do not allow
|
||||
// any of our own formatting-shenanigans to interfere with the error message
|
||||
const options = { ...{ class: "error", verbatim: true }, ...data[1] };
|
||||
this.writeToOutput(data[0], options);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Can't send a message without a websocket
|
||||
if (!(this.websocket && this.websocket.readyState === WebSocket.OPEN)) {
|
||||
return;
|
||||
// "e" => non-lethal errors
|
||||
handleErrorMessage(data) {
|
||||
const options = { ...{ class: "error" }, ...data[1] };
|
||||
this.writeToOutput(data[0], options);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// The server asked us for a password, so we send it.
|
||||
// But we hash it first, so we don't send our stuff
|
||||
// in the clear.
|
||||
if (this.replyType === "password") {
|
||||
this.hashPassword(command).then((pwHash) => {
|
||||
this.send("reply", "password", pwHash, this.replyTag);
|
||||
this.replyType = null;
|
||||
this.replyTag = null;
|
||||
});
|
||||
return;
|
||||
// The prompt is the most important message type,
|
||||
// it prompts us send a message back. We should not
|
||||
// send messages back to the server without being
|
||||
// prompted.
|
||||
// In fact, we should ALWAYS be in a state of just-having-been-prompted.
|
||||
handlePromptMessage(data) {
|
||||
let [promptText, options = {}] = data;
|
||||
|
||||
this.shouldReply = true;
|
||||
|
||||
this.promptOptions = { ...{ class: "prompt" }, ...options };
|
||||
|
||||
//
|
||||
this.writeToOutput(promptText, this.promptOptions);
|
||||
|
||||
//
|
||||
// The server has asked for a password, so we set the
|
||||
// input type to password for safety reasons.
|
||||
if (options.password) {
|
||||
this.input.type = "password";
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// When the player enters their username during the auth-phase,
|
||||
// keep the username in the pocket for later.
|
||||
if (this.replyType === "username") {
|
||||
this.username = command;
|
||||
/**
|
||||
* Add output to the text.
|
||||
* @param {string} text
|
||||
* @param {object} options
|
||||
*/
|
||||
writeToOutput(text, options = {}) {
|
||||
// tweak the data-formatting so we can iterate and create multiple elements
|
||||
const lines = Array.isArray(text) ? text : [text];
|
||||
|
||||
for (const line of lines) {
|
||||
const element = document.createElement("div");
|
||||
|
||||
if (options.verbatim) {
|
||||
element.textContent = line;
|
||||
element.className = "verbatim";
|
||||
} else {
|
||||
element.innerHTML = crackdown(line);
|
||||
}
|
||||
|
||||
this.output.appendChild(element);
|
||||
this.output.scrollTop = this.output.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// We add our own command to the output stream so the
|
||||
// player can see what they typed.
|
||||
this.writeToOutput("> " + command, { class: "input" });
|
||||
|
||||
//
|
||||
// Handle certain-commands differently.
|
||||
const specialCommands = { ":quit": "quit", ":help": "help" };
|
||||
if (specialCommands[command]) {
|
||||
this.send(specialCommands[command]);
|
||||
return;
|
||||
/**
|
||||
* Update the status banner.
|
||||
*
|
||||
* @param {string} message
|
||||
* @param {string} className
|
||||
*/
|
||||
updateStatus(message, className) {
|
||||
this.status.textContent = this.dev ? `[DEV] Status: ${message}` : `Status: ${message}`;
|
||||
this.status.className = className;
|
||||
}
|
||||
|
||||
//
|
||||
// Handle replies
|
||||
// We want to be in a place where ALL messages are replies.
|
||||
// The game loop should always ask you for your next command,
|
||||
// even if it does so silently
|
||||
if (this.replyType) {
|
||||
//--------------------------------------------------
|
||||
// The server asked the player a question,
|
||||
// so we send the answer the way the server wants.
|
||||
//--------------------------------------------------
|
||||
this.send("reply", this.replyType, command, this.replyTag);
|
||||
this.replyType = null;
|
||||
this.replyTag = null;
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
//-----------------------------------------------------
|
||||
// The player sends a text-based command to the server
|
||||
//-----------------------------------------------------
|
||||
// ___ _ _ _
|
||||
// |_ _|_ __ ___ _ __ ___ _ __| |_ __ _ _ __ | |_| |
|
||||
// | || '_ ` _ \| '_ \ / _ \| '__| __/ _` | '_ \| __| |
|
||||
// | || | | | | | |_) | (_) | | | || (_| | | | | |_|_|
|
||||
// |___|_| |_| |_| .__/ \___/|_| \__\__,_|_| |_|\__(_)
|
||||
// |_|
|
||||
//
|
||||
// Aside from :help", ":quit", etc. we should not send
|
||||
// unsolicited messages to the server without being
|
||||
// prompted to do so.
|
||||
this.send("c", command);
|
||||
}
|
||||
|
||||
// ___ __ __
|
||||
// / _ \ _ __ | \/ | ___ ___ ___ __ _ __ _ ___
|
||||
// | | | | '_ \| |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \
|
||||
// | |_| | | | | | | | __/\__ \__ \ (_| | (_| | __/
|
||||
// \___/|_| |_|_| |_|\___||___/___/\__,_|\__, |\___|
|
||||
//
|
||||
/** @param {any[]} data*/
|
||||
onMessage(data) {
|
||||
if (this.dev) {
|
||||
console.debug(data);
|
||||
}
|
||||
const messageType = data.shift();
|
||||
|
||||
if (messageType === "dbg") {
|
||||
return this.handleDebugMessages(data);
|
||||
}
|
||||
|
||||
if (messageType === "prompt") {
|
||||
return this.handlePromptMessage(data);
|
||||
}
|
||||
|
||||
if (messageType === "e") {
|
||||
return this.handleErrorMessage(data);
|
||||
}
|
||||
|
||||
if (messageType === "calamity") {
|
||||
return this.handleCalamityMessage(data);
|
||||
}
|
||||
|
||||
if (messageType === "_") {
|
||||
return this.handleSystemMessages(data);
|
||||
}
|
||||
|
||||
if (messageType === "m") {
|
||||
return this.handleTextMessages(data);
|
||||
}
|
||||
|
||||
if (this.dev) {
|
||||
this.writeToOutput(
|
||||
`unknown message type: ${messageType}: ${JSON.stringify(data)}`,
|
||||
"debug",
|
||||
);
|
||||
}
|
||||
console.debug("unknown message type", data);
|
||||
}
|
||||
|
||||
//
|
||||
// "m" => normal/standard message to be displayed to the user
|
||||
handleTextMessages(data) {
|
||||
const options = { ...data[1] }; // coerce options into an object.
|
||||
|
||||
// normal text message to be shown to the player
|
||||
this.writeToOutput(data[0], options);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Debug messages let the server send data to be displayed on the player's screen
|
||||
// and also logged to the players browser's log.
|
||||
handleDebugMessages(data) {
|
||||
if (!this.dev) {
|
||||
return; // debug messages are thrown away if we're not in dev mode.
|
||||
}
|
||||
this.writeToOutput(data, { class: "debug", preformatted: true });
|
||||
console.debug("DBG", data);
|
||||
}
|
||||
|
||||
//
|
||||
// "_" => system messages, not to be displayed
|
||||
handleSystemMessages(data) {
|
||||
if (data.length < 2) {
|
||||
console.debug("malformed system message", data);
|
||||
return;
|
||||
}
|
||||
|
||||
console.debug("Incoming system message", data);
|
||||
|
||||
/** @type {string} */
|
||||
const messageType = data.shift();
|
||||
|
||||
switch (messageType) {
|
||||
case "dev":
|
||||
// This is a message that tells us that the server is in
|
||||
// "dev" mode, and that we should do the same.
|
||||
this.dev = data[0];
|
||||
this.status.textContent = "[DEV] " + this.status.textContent;
|
||||
break;
|
||||
case "salt":
|
||||
this.salt = data[0];
|
||||
console.debug("updating crypto salt", data[0]);
|
||||
break;
|
||||
default:
|
||||
console.debug("unknown system message", messageType, data);
|
||||
}
|
||||
|
||||
// If we're in dev mode, we should output all system messages (in a shaded/faint fashion).
|
||||
if (this.dev) {
|
||||
this.writeToOutput(
|
||||
`system message: ${messageType} = ${JSON.stringify(data)}`,
|
||||
{ class: "debug" },
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// "calamity" => lethal error. Close connection.
|
||||
// Consider hard refresh of page to reset all variables
|
||||
handleCalamityMessage(data) {
|
||||
//
|
||||
// We assume that calamity errors are pre-formatted, and we do not allow
|
||||
// any of our own formatting-shenanigans to interfere with the error message
|
||||
const options = { ...{ class: "error", preformatted: true }, ...data[1] };
|
||||
this.writeToOutput(data[0], options);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// "e" => non-lethal errors
|
||||
handleErrorMessage(data) {
|
||||
const options = { ...{ class: "error" }, ...data[1] };
|
||||
this.writeToOutput(data[0], options);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// The prompt is the most important message type,
|
||||
// it prompts us send a message back. We should not
|
||||
// send messages back to the server without being
|
||||
// prompted.
|
||||
// In fact, we should ALWAYS be in a state of just-having-been-prompted.
|
||||
handlePromptMessage(data) {
|
||||
let [replyType, promptText, replyTag, options = {}] = data;
|
||||
|
||||
this.replyType = replyType;
|
||||
this.replyTag = replyTag;
|
||||
this.writeToOutput(promptText, { ...{ class: "prompt" }, ...options });
|
||||
|
||||
// The server has asked for a password, so we set the
|
||||
// input type to password for safety reasons.
|
||||
if (replyType === "password") {
|
||||
this.input.type = "password";
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add output to the text.
|
||||
* @param {string} text
|
||||
* @param {object} options
|
||||
*/
|
||||
writeToOutput(text, options = {}) {
|
||||
const el = document.createElement("span");
|
||||
|
||||
if (typeof options.class === "string") {
|
||||
el.className = options.class;
|
||||
}
|
||||
|
||||
// add end of line character "\n" unless
|
||||
// options.addEol = false is set explicitly
|
||||
const eol = options.addEol === false ? "" : "\n";
|
||||
|
||||
if (options.preformatted) {
|
||||
el.textContent = text + eol;
|
||||
el.className += " " + "preformatted";
|
||||
} else {
|
||||
el.innerHTML = crackdown(text) + eol;
|
||||
}
|
||||
this.output.appendChild(el);
|
||||
this.output.scrollTop = this.output.scrollHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the status banner.
|
||||
*
|
||||
* @param {string} message
|
||||
* @param {string} className
|
||||
*/
|
||||
updateStatus(message, className) {
|
||||
this.status.textContent = this.dev
|
||||
? `[DEV] Status: ${message}`
|
||||
: `Status: ${message}`;
|
||||
this.status.className = className;
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the MUD client when the page loads
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
new MUDClient();
|
||||
new MUDClient();
|
||||
});
|
||||
|
||||
107
server/public/crackdown.js
Normal file → Executable file
107
server/public/crackdown.js
Normal file → Executable file
@@ -10,58 +10,61 @@
|
||||
// | |_) | (_| | | \__ \ __/ |
|
||||
// | .__/ \__,_|_| |___/\___|_|
|
||||
// |_|
|
||||
export function crackdown(text) {
|
||||
console.debug("starting crack parsing");
|
||||
console.debug(text);
|
||||
return text
|
||||
.replace(/[&<>"'`]/g, (c) => {
|
||||
switch (c) {
|
||||
case "&":
|
||||
return "&";
|
||||
case "<":
|
||||
return "<";
|
||||
case ">":
|
||||
return ">";
|
||||
case '"':
|
||||
return """;
|
||||
case "'":
|
||||
return "'";
|
||||
case "`":
|
||||
return "`";
|
||||
default:
|
||||
return c;
|
||||
}
|
||||
})
|
||||
.replace(
|
||||
/---(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])---/g,
|
||||
'<span class="strike">$1</span>',
|
||||
) // line-through
|
||||
.replace(
|
||||
/___(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])___/g,
|
||||
'<span class="underline">$1</span>',
|
||||
) // underline
|
||||
.replace(
|
||||
/_(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])_/g,
|
||||
'<span class="italic">$1</span>',
|
||||
) // italic
|
||||
.replace(
|
||||
/\*(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])\*/g,
|
||||
'<span class="bold">$1</span>',
|
||||
) // bold
|
||||
.replace(
|
||||
/\.{3}(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])\.{3}/g,
|
||||
'<span class="undercurl">$1</span>',
|
||||
) // undercurl
|
||||
.replace(
|
||||
/\({3}(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])\){3}/g,
|
||||
'<span class="faint">($1)</span>',
|
||||
) // faint with parentheses
|
||||
.replace(
|
||||
/\({2}(([a-zA-Z0-9:].*?[a-zA-Z0-9:])|[a-zA-Z0-9:])\){2}/g,
|
||||
'<span class="faint">$1</span>',
|
||||
); // faint with parentheses
|
||||
|
||||
console.debug("crack output", text);
|
||||
const capture = "([a-zA-Z0-9:()-](?:.*[a-zA-Z0-9:()-])?)";
|
||||
const skipSpace = "\\s*";
|
||||
|
||||
return text;
|
||||
const htmlEscapeRegex = /[&<>"'`]/g; // used to escape html characters
|
||||
|
||||
/**
|
||||
* @type {Array.string[]}
|
||||
*
|
||||
* The order of the elements of this array matters.
|
||||
*/
|
||||
const opcodes = [
|
||||
["(^|\\n)=", "($|\\n)", "$1<h1>$2</h1>$3"],
|
||||
["(^|\\n)==", "($|\\n)", "$1<h2>$2</h2>$3"],
|
||||
["---", "---", "<span class='strike'>$1</span>"],
|
||||
["___", "___", "<span class='underline'>$1</span>"],
|
||||
["(?:[.]{3})", "(?:[.]{3})", "<span class='undercurl'>$1</span>"],
|
||||
["(?:[(]{2})", "(?:[)]{2})", "<span class='faint'>$1</span>"],
|
||||
["_", "_", "<span class='italic'>$1</span>"],
|
||||
["\\*", "\\*", "<span class='bold'>$1</span>"],
|
||||
["\\[\\[([a-zA-Z0-9_ ]+)\\[\\[", "\\]\\]", "<span class='$1'>$2</span>"],
|
||||
];
|
||||
/** @type{Array.Array.<Regexp,string>} */
|
||||
const regexes = [];
|
||||
|
||||
for (const [left, right, replacement] of opcodes) {
|
||||
regexes.push([new RegExp(left + skipSpace + capture + skipSpace + right, "g"), replacement]);
|
||||
}
|
||||
|
||||
/** @param {string} text */
|
||||
export function crackdown(text) {
|
||||
text.replace(htmlEscapeRegex, (c) => {
|
||||
switch (c) {
|
||||
case "&":
|
||||
return "&";
|
||||
case "<":
|
||||
return "<";
|
||||
case ">":
|
||||
return ">";
|
||||
case '"':
|
||||
return """;
|
||||
case "'":
|
||||
return "'";
|
||||
case "`":
|
||||
return "`";
|
||||
default:
|
||||
return c;
|
||||
}
|
||||
});
|
||||
for (const k in regexes) {
|
||||
const [regex, replacement] = regexes[k];
|
||||
text = text.replace(regex, replacement);
|
||||
}
|
||||
|
||||
console.debug("crack output", text);
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -1,31 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WebSocket MUD</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="container">
|
||||
<div id="status" class="connecting">Connecting...</div>
|
||||
<div id="output"></div>
|
||||
<div id="input-container">
|
||||
<input
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
id="input"
|
||||
placeholder="Enter command..."
|
||||
disabled
|
||||
autocorrect="off"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<button id="send" disabled>Send</button>
|
||||
</div>
|
||||
</div>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WebSocket MUD</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="container">
|
||||
<div id="status" class="connecting">Connecting...</div>
|
||||
<div id="output"></div>
|
||||
<div id="input-container">
|
||||
<input
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
id="input"
|
||||
placeholder="Enter command..."
|
||||
disabled
|
||||
autocorrect="off"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="client.js"></script>
|
||||
</body>
|
||||
<script type="module" src="client.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,136 +1,150 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Fira+Code:wght@300..700&display=swap");
|
||||
|
||||
body {
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
font-size: 14px;
|
||||
background-color: #1a1a1a;
|
||||
color: #00ff00;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
font-size: 14px;
|
||||
background-color: #1a1a1a;
|
||||
color: #00ff00;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
max-width: 99.9vw;
|
||||
margin: 0 auto;
|
||||
padding: 10px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
max-width: 99.9vw;
|
||||
margin: 0 auto;
|
||||
padding: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#output {
|
||||
flex: 1;
|
||||
background-color: #000;
|
||||
border: 2px solid #333;
|
||||
padding: 15px;
|
||||
overflow-y: auto;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 20px;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
font-size: 14px;
|
||||
width: 100ch;
|
||||
flex: 1;
|
||||
background-color: #000;
|
||||
border: 2px solid #333;
|
||||
padding: 15px;
|
||||
overflow-y: auto;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 20px;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
font-size: 14px;
|
||||
width: 100ch;
|
||||
}
|
||||
|
||||
#input-container {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
#input {
|
||||
flex: 1;
|
||||
background-color: #222;
|
||||
border: 2px solid #333;
|
||||
color: #00ff00;
|
||||
padding: 10px;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
font-size: 14px;
|
||||
flex: 1;
|
||||
background-color: #222;
|
||||
border: 2px solid #333;
|
||||
color: #00ff00;
|
||||
padding: 10px;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
#input:focus {
|
||||
outline: none;
|
||||
border-color: #00ff00;
|
||||
outline: none;
|
||||
border-color: #00ff00;
|
||||
}
|
||||
|
||||
#send {
|
||||
background-color: #333;
|
||||
border: 2px solid #555;
|
||||
color: #00ff00;
|
||||
padding: 10px 20px;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
cursor: pointer;
|
||||
background-color: #333;
|
||||
border: 2px solid #555;
|
||||
color: #00ff00;
|
||||
padding: 10px 20px;
|
||||
font-family: "Fira Code", monospace;
|
||||
font-optical-sizing: auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#send:hover {
|
||||
background-color: #444;
|
||||
background-color: #444;
|
||||
}
|
||||
|
||||
#status {
|
||||
background-color: #333;
|
||||
padding: 5px 15px;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 3px;
|
||||
background-color: #333;
|
||||
padding: 5px 15px;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2 {
|
||||
display: inline-block;
|
||||
margin-top: 0.3em;
|
||||
}
|
||||
|
||||
.connected {
|
||||
color: #00ff00;
|
||||
color: #00ff00;
|
||||
}
|
||||
|
||||
.disconnected {
|
||||
color: #ff4444;
|
||||
color: #ff4444;
|
||||
}
|
||||
|
||||
.connecting {
|
||||
color: #ffaa00;
|
||||
color: #ffaa00;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #ff4444;
|
||||
color: #ff4444;
|
||||
}
|
||||
|
||||
.input {
|
||||
color: #666;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.debug {
|
||||
opacity: 0.33;
|
||||
opacity: 0.33;
|
||||
}
|
||||
|
||||
.prompt {
|
||||
color: #00ccff;
|
||||
color: #00ccff;
|
||||
}
|
||||
|
||||
.bold {
|
||||
font-weight: bold;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.italic {
|
||||
font-style: italic;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.strike {
|
||||
text-decoration: line-through;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.underline {
|
||||
text-decoration: underline;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.undercurl {
|
||||
text-decoration: wavy underline lime;
|
||||
text-decoration: wavy underline rgb(00 100% 00 / 40%);
|
||||
}
|
||||
|
||||
.faint {
|
||||
opacity: 0.42;
|
||||
opacity: 0.42;
|
||||
}
|
||||
|
||||
.fBlue {
|
||||
color: blue;
|
||||
}
|
||||
|
||||
.bRed {
|
||||
background-color: red;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user