things + stff

This commit is contained in:
Kim Ravn Hansen
2025-09-07 23:24:50 +02:00
parent fb915f2681
commit 8a4eb25507
27 changed files with 1991 additions and 630 deletions

View File

@@ -10,7 +10,10 @@ export class Character {
/** @type {string} character's name */
name;
/** @protected @type {number} The number of XP the character has. */
/**
* @protected
* @type {number} The number of XP the character has.
*/
_xp = 0;
get xp() {
return this._xp;
@@ -61,15 +64,15 @@ export class Character {
/**
* @param {string} username The name of player who owns this character. Note that the game can own a character - somehow.
* @param {string} name The name of the character
* @param {boolean} initialize Should we initialize the character
* @param {boolean=false} initialize Should we initialize the character
*/
constructor(playerUname, name, initialize) {
constructor(username, name, initialize) {
this.name = name;
// Initialize the unique name if this character.
//
// things to to hell if two characters with the same name are created at exactly the same time with the same random seed.
this._id = id.fromName(playerUname, name);
this._id = id.fromName(username, name);
// should we skip initialization of this object
if (initialize !== true) {
@@ -144,9 +147,7 @@ export class Character {
this.meleeCombat = Math.max(this.skulduggery, 10);
break;
default:
throw new Error(
"Logic error, ancestry d8() roll was out of scope",
);
throw new Error("Logic error, ancestry d8() roll was out of scope");
}
//
@@ -172,11 +173,8 @@ export class Character {
case 2:
this.foundation = "druid";
this.proficiencies.add("armor/natural");
this.equipment
.set("sickle", 1)
.set("poisoner's kit", 1)
.set("healer's kit", 1);
default:
this.equipment.set("sickle", 1).set("poisoner's kit", 1).set("healer's kit", 1);
default: // case 2:
this.foundation = "debug";
this.proficiencies.add("heavy_armor");
this.proficiencies.add("heavy_weapons");
@@ -193,7 +191,3 @@ export class Character {
}
}
}
const c = new Character("username", "test", true);
console.log(c);

View File

@@ -10,8 +10,10 @@
import WebSocket from "ws";
import { Character } from "./character.js";
import { ItemTemplate } from "./item.js";
import { Player } from "./player.js";
export class Game {
/** @type {Map<string,ItemTemplate>} List of all item templates in the game */
_itemTemplates = new Map();

View File

@@ -42,17 +42,13 @@ export class ItemTemplate {
*/
constructor(name, itemSlots, description, id) {
if (typeof name !== "string") {
throw new Error(
"Name must be a string, but " + typeof name + " given.",
);
throw new Error("Name must be a string, but " + typeof name + " given.");
}
if (typeof description === "undefined") {
description = "";
}
if (typeof description !== "string") {
throw new Error(
"Name must be a string, but " + typeof name + " given.",
);
throw new Error("Name must be a string, but " + typeof name + " given.");
}
if (!Number.isFinite(itemSlots)) {
throw new Error("itemSlots must be a finite number!");
@@ -71,12 +67,7 @@ export class ItemTemplate {
}
createItem() {
return new ChracterItem(
this._id,
this._name,
this._description,
this._itemSlots,
);
return new ChracterItem(this._id, this._name, this._description, this._itemSlots);
}
}
@@ -119,8 +110,3 @@ export class CharacterItem {
this.itemSlots = itemSlots;
}
}
const i = new ItemTemplate("knife", 10000);
const ci = new CharacterItem();
console.log(ci);

View File

@@ -1,103 +1,48 @@
import WebSocket from "ws";
import { Character } from "./character.js";
/**
* Player Account.
*
* 1. Contain persistent player account info.
* 2. Contain the connection to the client machine if the player is currently playing the game.
* 3. Contain session information.
*
* We can do this because we only allow a single websocket per player account.
* You are not allowed to log in if a connection/socket is already open.
*
* We regularly ping and pong to ensure that stale connections are closed.
*
* Contain persistent player account info.
*/
export class Player {
/** @protected @type {string} unique username */
/**
* @protected
* @type {string} unique username
*/
_username;
get username() {
return this._username;
}
/** @protected @type {string} */
/**
* @protected
* @type {string}
*/
_passwordHash;
get passwordHash() {
return this._passwordHash;
}
/** @protected @type {WebSocket} Player's current and only websocket. If undefined, the player is not logged in. */
_websocket;
get websocket() {
return this._websocket;
/** @protected @type {Set<Character>} */
_characters = new Set();
get characters() {
return this._characters;
}
/** @protected @type {Date} */
_latestSocketReceived;
/**
* @param {string} username
* @param {string} passwordHash
*/
constructor(username, passwordHash) {
this._username = username;
this._passwordHash = passwordHash;
this.createdAt = new Date();
}
/** @param {WebSocket} websocket */
clientConnected(websocket) {
this._websocket = websocket;
}
/***
* Send a message back to the client via the WebSocket.
*
* @param {string} message
* @return {boolean} success
*/
_send(data) {
if (!this._websocket) {
console.error(
"Trying to send a message to an uninitialized websocket",
this,
data,
);
return false;
}
if (this._websocket.readyState === WebSocket.OPEN) {
this._websocket.send(JSON.stringify(data));
return true;
}
if (this._websocket.readyState === WebSocket.CLOSED) {
console.error(
"Trying to send a message through a CLOSED websocket",
this,
data,
);
return false;
}
if (this._websocket.readyState === WebSocket.CLOSING) {
console.error(
"Trying to send a message through a CLOSING websocket",
this,
data,
);
return false;
}
if (this._websocket.readyState === WebSocket.CONNECTING) {
console.error(
"Trying to send a message through a CONNECTING (not yet open) websocket",
this,
data,
);
return false;
}
console.error(
"Trying to send a message through a websocket with an UNKNOWN readyState (%d)",
this.websocket.readyState,
this,
data,
);
return false;
}
sendPrompt() {
this.sendMessage(`\n[${this.currentRoom}] > `);
setPasswordHash(hashedPassword) {
this._passwordHash = hashedPassword;
}
}

102
server/models/session.js Executable file
View File

@@ -0,0 +1,102 @@
import WebSocket from 'ws';
import { Game } from './game.js';
import { Player } from './player.js';
import { StateInterface } from './states/interface.js';
import * as msg from '../utils/messages.js';
import figlet from 'figlet';
export class Session {
/** @protected @type {StateInterface} */
_state;
get state() {
return this._state;
}
/** @protected @type {Game} */
_game;
get game() {
return this._game;
}
/** @type Date */
latestPing;
/** @type {Player} */
player;
/** @type {WebSocket} */
websocket;
/**
* @param {WebSocket} websocket
* @param {Game} game
*/
constructor(websocket, game) {
this.websocket = websocket;
this._game = game;
}
/**
* Send a message via our websocket.
*
* @param {string|number} messageType
* @param {...any} args
*/
send(messageType, ...args) {
this.websocket.send(JSON.stringify([messageType, ...args]));
}
sendFigletMessage(message) {
console.debug("sendFigletMessage('%s')", message);
this.sendMessage(figlet.textSync(message), { preformatted: true });
}
/** @param {string} message Message to display to player */
sendMessage(message, ...args) {
if (message.length === 0) {
console.debug("sending a zero-length message, weird");
}
if (Array.isArray(message)) {
message = message.join("\n");
}
this.send(msg.MESSAGE, message, ...args);
}
/**
* @param {string} type prompt type (username, password, character name, etc.)
* @param {string} message The prompting message (please enter your character's name)
*/
sendPrompt(type, message,...args) {
if (Array.isArray(message)) {
message = message.join("\n");
}
this.send(msg.PROMPT, type, message,...args);
}
/** @param {string} message The error message to display to player */
sendError(message,...args) {
this.send(msg.ERROR, message, ...args);
}
/** @param {string} message The calamitous error to display to player */
sendCalamity(message,...args) {
this.send(msg.CALAMITY, message, ...args);
}
sendSystemMessage(arg0,...rest) {
this.send(msg.SYSTEM, arg0, ...rest);
}
/**
* @param {StateInterface} state
*/
setState(state) {
this._state = state;
console.debug("changing state", state.constructor.name);
if (typeof state.onAttach === "function") {
state.onAttach();
}
}
}

158
server/models/states/auth.js Executable file
View File

@@ -0,0 +1,158 @@
import { Session } from "../session.js";
import * as msg from "../../utils/messages.js";
import * as security from "../../utils/security.js";
import { JustLoggedInState } from "./justLoggedIn.js";
import { CreatePlayerState } from "./createPlayer.js";
const STATE_EXPECT_USERNAME = "promptUsername";
const STATE_EXPECT_PASSWORD = "promptPassword";
const USERNAME_PROMPT = [
"Please enter your username",
"((type *:help* for help))",
"((type *:create* if you want to create a new user))",
];
const PASSWORD_PROMPT = "Please enter your password";
const ERROR_INSANE_PASSWORD = "Invalid password.";
const ERROR_INSANE_USERNAME = "Username invalid, must be at 4-20 characters, and may only contain [a-z], [A-Z], [0-9] and underscore"
const ERROR_INCORRECT_PASSWOD = "Incorrect password.";
/** @property {Session} session */
export class AuthState {
subState = STATE_EXPECT_USERNAME;
/**
* @param {Session} session
*/
constructor(session) {
/** @type {Session} */
this.session = session;
}
onAttach() {
this.session.sendFigletMessage("M U U H D");
this.session.sendPrompt("username", USERNAME_PROMPT);
}
/** @param {msg.ClientMessage} message */
onMessage(message) {
if (this.subState === STATE_EXPECT_USERNAME) {
this.receiveUsername(message);
return;
}
if (this.subState === STATE_EXPECT_PASSWORD) {
this.receivePassword(message)
return;
}
console.error("Logic error, we received a message after we should have been logged in");
this.session.sendError("I received a message didn't know what to do with!");
}
/** @param {msg.ClientMessage} message */
receiveUsername(message) {
//
// handle invalid message types
if (!message.isUsernameResponse()) {
this.session.sendError("Incorrect message type!");
this.session.sendPrompt("username", USERNAME_PROMPT);
return;
}
//
// Handle the creation of new players
if (message.username === ":create") {
// TODO:
// Set gamestate = CreateNewPlayer
//
// Also check if player creation is allowed in cfg/env
this.session.setState(new CreatePlayerState(this.session));
return;
}
//
// do basic syntax checks on usernames
if (!security.isUsernameSane(message.username)) {
this.session.sendError(ERROR_INSANE_USERNAME);
this.session.sendPrompt("username", USERNAME_PROMPT);
return;
}
if (this.session.game.players.size === 0) {
console.error("there are no players registered");
}
const player = this.session.game.players.get(message.username);
//
// handle invalid username
if (!player) {
//
// This is a security risk. In the perfect world we would allow the player to enter both
// username and password before kicking them out, but since the player's username is not
// an email address, and we discourage from using “important” usernames, then we tell the
// player that they entered an invalid username right away.
//
// NOTE FOR ACCOUNT CREATION
// Do adult-word checks, so we dont have Fucky_McFuckFace
// https://www.npmjs.com/package/glin-profanity
this.session.sendError("Incorrect username, try again");
this.session.sendPrompt("username", USERNAME_PROMPT);
return;
}
//
// username was correct, proceed to next step
this.session.player = player;
this.subState = STATE_EXPECT_PASSWORD;
this.session.sendPrompt("password", PASSWORD_PROMPT);
}
/** @param {msg.ClientMessage} message */
receivePassword(message) {
//
// handle invalid message types
if (!message.isPasswordResponse()) {
this.session.sendError("Incorrect message type!");
this.session.sendPrompt("password", PASSWORD_PROMPT);
return;
}
//
// Check of the password is sane. This is both bad from a security point
// of view, and technically not necessary as insane passwords couldn't
// reside in the player lists. However, let's save some CPU cycles on
// not hashing an insane password 1000+ times.
// This is technically bad practice, but since this is just a game,
// do it anyway.
if (!security.isPasswordSane(message.password)) {
this.session.sendError(ERROR_INSANE_PASSWORD);
this.session.sendPrompt("password", PASSWORD_PROMPT);
return;
}
//
// Verify the password against the hash we've stored.
if (!security.verifyPassword(message.password, this.session.player.passwordHash)) {
this.session.sendError("Incorrect password!");
this.session.sendPrompt("password", PASSWORD_PROMPT);
return;
}
//
// Password correct, check if player is an admin
if (this.session.player.isAdmin) {
// set state AdminJustLoggedIn
}
//
// Password was correct, go to main game
this.session.setState(new JustLoggedInState(this.session));
}
}

View File

@@ -0,0 +1,50 @@
import * as msg from "../../utils/messages.js";
import { Session } from "../session.js";
/**
* Main game state
*
* It's here we listen for player commands.
*/
export class AwaitCommandsState {
/**
* @param {Session} session
*/
constructor(session) {
/** @type {Session} */
this.session = session;
}
onAttach() {
console.log("Session is entering the “main” state");
this.session.sendMessage("Welcome to the game!");
}
/** @param {msg.ClientMessage} message */
onMessage(message) {
if (message.hasCommand()) {
this.handleCommand(message);
}
}
/** @param {msg.ClientMessage} message */
handleCommand(message) {
switch (message.command) {
case "help":
this.session.sendFigletMessage("HELP");
this.session.sendMessage([
"---------------------------------------",
" *:help* this help screen",
" *:quit* quit the game",
"---------------------------------------",
]);
break;
case "quit":
this.session.sendMessage("The quitting quitter quits, typical... Cya");
this.session.websocket.close();
break;
default:
this.session.sendMessage(`Unknown command: ${message.command}`);
}
}
}

View File

@@ -0,0 +1,105 @@
import figlet from "figlet";
import { Session } from "../session.js";
import WebSocket from "ws";
import { AuthState } from "./auth.js";
import { ClientMessage } from "../../utils/messages.js";
import { PARTY_MAX_SIZE } from "../../config.js";
import { frameText } from "../../utils/tui.js";
export class CharacterCreationState {
/**
* @proteted
* @type {(msg: ClientMessage) => }
*
* NOTE: Should this be a stack?
*/
_dynamicMessageHandler;
/**
* @param {Session} session
*/
constructor(session) {
/** @type {Session} */
this.session = session;
}
/**
* We attach (and execute) the next state
*/
onAttach() {
const charCount = this.session.player.characters.size;
const createPartyLogo = frameText(
figlet.textSync("Create Your Party"),
{ hPadding: 2, vPadding: 1, hMargin: 2, vMargin: 1 },
);
this.session.sendMessage(createPartyLogo, {preformatted:true});
this.session.sendMessage([
"",
`Current party size: ${charCount}`,
`Max party size: ${PARTY_MAX_SIZE}`,
]);
const min = 1;
const max = PARTY_MAX_SIZE - charCount;
const prompt = `Please enter an integer between ${min} - ${max} (or type :help to get more info about party size)`;
this.session.sendMessage(`You can create a party with ${min} - ${max} characters, how big should your party be?`);
this.session.sendPrompt("integer", prompt);
/** @param {ClientMessage} message */
this._dynamicMessageHandler = (message) => {
const n = PARTY_MAX_SIZE;
if (message.isHelpCommand()) {
this.session.sendMessage([
`Your party can consist of 1 to ${n} characters.`,
"",
"* Large parties tend live longer",
`* If you have fewer than ${n} characters, you can`,
" hire extra characters in your local inn.",
"* large parties level slower because there are more",
" characters to share the Experience Points",
"* The individual members of small parties get better",
" loot because they don't have to share, but it",
" a lot of skill to accumulate loot as fast a larger",
" party can"
]);
return;
}
if (!message.isIntegerResponse()) {
this.session.sendError("You didn't enter a number");
this.session.sendPrompt("integer", prompt);
return;
}
const numCharactersToCreate = message.integer;
if (numCharactersToCreate > max) {
this.session.sendError("Number too high");
this.session.sendPrompt("integer", prompt);
return;
}
if (numCharactersToCreate < min) {
this.session.sendError("Number too low");
this.session.sendPrompt("integer", prompt);
return;
}
this.session.sendMessage(`Let's create ${numCharactersToCreate} character(s) for you :)`);
this._dynamicMessageHandler = undefined;
};
}
/** @param {ClientMessage} message */
onMessage(message) {
if (this._dynamicMessageHandler) {
this._dynamicMessageHandler(message);
return;
}
this.session.sendMessage("pong", message.type);
}
}

View File

@@ -0,0 +1,167 @@
import WebSocket from "ws";
import { Session } from "../session.js";
import * as msg from "../../utils/messages.js";
import * as security from "../../utils/security.js";
import { AuthState } from "./auth.js";
import { Player } from "../player.js";
const USERNAME_PROMPT = "Enter a valid username (4-20 characters, [a-z], [A-Z], [0-9], and underscore)";
const PASSWORD_PROMPT = "Enter a valid password";
const PASSWORD_PROMPT2 = "Enter your password again";
const ERROR_INSANE_PASSWORD = "Invalid password.";
const ERROR_INSANE_USERNAME = "Invalid username. It must be 4-20 characters, and may only contain [a-z], [A-Z], [0-9] and underscore"
const ERROR_INCORRECT_PASSWOD = "Incorrect password.";
/** @property {Session} session */
export class CreatePlayerState {
/**
* @proteted
* @type {(msg: ClientMessage) => }
*
* Allows us to dynamically set which
* method handles incoming messages.
*/
_dynamicMessageHandler;
/** @protected @type {Player} */
_player;
/** @protected @type {string} */
_password;
/**
* @param {Session} session
*/
constructor(session) {
/** @type {Session} */
this.session = session;
}
onAttach() {
this.session.sendFigletMessage("New Player");
this.session.sendPrompt("username", USERNAME_PROMPT);
// our initial substate is to receive a username
this.setMessageHandler(this.receiveUsername);
}
/** @param {msg.ClientMessage} message */
onMessage(message) {
this._dynamicMessageHandler(message);
}
/* @param {(msg: ClientMessage) => } handler */
setMessageHandler(handler) {
this._dynamicMessageHandler = handler;
}
/** @param {msg.ClientMessage} message */
receiveUsername(message) {
//
// NOTE FOR ACCOUNT CREATION
// Do adult-word checks, so we dont have Fucky_McFuckFace
// https://www.npmjs.com/package/glin-profanity
//
// handle invalid message types
if (!message.isUsernameResponse()) {
this.session.sendError("Incorrect message type!");
this.session.sendPrompt("username", USERNAME_PROMPT);
return;
}
//
// do basic syntax checks on usernames
if (!security.isUsernameSane(message.username)) {
this.session.sendError(ERROR_INSANE_USERNAME);
this.session.sendPrompt("username", USERNAME_PROMPT);
return;
}
const taken = this.session.game.players.has(message.username);
//
// handle taken/occupied username
if (taken) {
// Telling the user right away that the username is taken can
// lead to data leeching. But fukkit.
this.session.sendError(`Username _${message.username}_ was taken by another player.`);
this.session.sendPrompt("username", USERNAME_PROMPT);
return;
}
this._player = new Player(message.username, undefined);
// _____ _
// | ___(_)_ ___ __ ___ ___
// | |_ | \ \/ / '_ ` _ \ / _ \
// | _| | |> <| | | | | | __/
// |_| |_/_/\_\_| |_| |_|\___|
//
// 1. Add mutex on the players table to avoid race conditions
// 2. Prune "dead" players (players with 0 logins) after a short while
this.session.game.players.set(message.username, this._player);
this.session.sendMessage("Username available");
this.session.sendMessage(`Username _*${message.username}*_ is available, and I've reserved it for you :)`);
this.session.sendPrompt("password", PASSWORD_PROMPT);
this.setMessageHandler(this.receivePassword);
}
/** @param {msg.ClientMessage} message */
receivePassword(message) {
//
// handle invalid message types
if (!message.isPasswordResponse()) {
console.log("Invalid message type, expected password reply", message);
this.session.sendError("Incorrect message type!");
this.session.sendPrompt("password", PASSWORD_PROMPT);
return;
}
//
// Check that it's been hashed thoroughly before being sent here.
if (!security.isPasswordSane(message.password)) {
this.session.sendError(ERROR_INSANE_PASSWORD);
this.session.sendPrompt("password", PASSWORD_PROMPT);
return;
}
this._password = message.password; // it's relatively safe to store the PW here temporarily. The client already hashed the hell out of it.
this.session.sendPrompt("password", PASSWORD_PROMPT2);
this.setMessageHandler(this.receivePasswordConfirmation);
}
/** @param {msg.ClientMessage} memssage */
receivePasswordConfirmation(message) {
//
// handle invalid message types
if (!message.isPasswordResponse()) {
console.log("Invalid message type, expected password reply", message);
this.session.sendError("Incorrect message type!");
this.session.sendPrompt("password", PASSWORD_PROMPT);
this.setMessageHandler(this.receivePassword);
return;
}
//
// Handle mismatching passwords
if (message.password !== this._password) {
this.session.sendError("Incorrect, you have to enter your password twice in a row successfully");
this.session.sendPrompt("password", PASSWORD_PROMPT);
this.setMessageHandler(this.receivePassword);
return;
}
//
// Success!
// Take the user to the login screen.
this.session.sendMessage("*_Success_* ✅ You will now be asked to log in again, sorry for that ;)");
this._player.setPasswordHash(security.generateHash(this._password));
this.session.setState(new AuthState(this.session));
}
}

View File

@@ -0,0 +1,13 @@
import { ClientMessage } from "../../utils/messages.js";
import { Session } from "../session.js";
/** @interface */
export class StateInterface {
/** @param {Session} session */
constructor(session) { }
onAttach() { }
/** @param {ClientMessage} message */
onMessage(message) {}
}

View File

@@ -0,0 +1,36 @@
import { Session } from "../session.js";
import { ClientMessage } from "../../utils/messages.js";
import { CharacterCreationState } from "./characterCreation.js";
import { AwaitCommandsState } from "./awaitCommands.js";
/** @interface */
export class JustLoggedInState {
/** @param {Session} session */
constructor(session) {
/** @type {Session} */
this.session = session;
}
// Show welcome screen
onAttach() {
this.session.sendMessage([
"",
"Welcome",
"",
"You can type “:quit” at any time to quit the game",
"",
]);
//
// Check if we need to create characters for the player
if (this.session.player.characters.size === 0) {
this.session.sendMessage("You haven't got any characters, so let's make some\n\n");
this.session.setState(new CharacterCreationState(this.session));
return;
}
this.session.setState(new AwaitCommandsState(this.session));
}
}