From 8f790cddc7ca856071429fb3a2eb596172ddb9e9 Mon Sep 17 00:00:00 2001 From: Pazaz Date: Fri, 11 Oct 2024 17:07:33 -0400 Subject: [PATCH] feat: New LoginClient code, added missing files --- .env.example | 16 + .gitignore | 2 + data/config/worlds.example.json | 9 + package.json | 10 +- .../20231226044539_initial/migration.sql | 11 - .../20231226074531_newsposts/migration.sql | 19 - .../20231227162751_npc_hiscore/migration.sql | 9 - .../20240115054529_friendserver/migration.sql | 15 - .../20240115200541_chat_logging/migration.sql | 20 - .../migration.sql | 3 - prisma/migrations/migration_lock.toml | 3 - prisma/schema.prisma | 79 ---- src/3rdparty/ws-sync/ws-sync.js | 167 +++++++ src/jagex2/datastruct/Hashable.ts | 22 - src/jagex2/datastruct/LinkList.ts | 97 ---- src/jagex2/datastruct/Linkable.ts | 21 - src/jagex2/datastruct/Stack.ts | 54 --- src/jagex2/io/Packet.ts | 429 ------------------ src/lostcity/engine/WorldList.ts | 23 +- src/lostcity/server/LoginClient.ts | 69 +++ src/lostcity/server/LoginServer.ts | 406 ----------------- src/lostcity/server/NetworkStream.ts | 86 ---- src/lostcity/util/Environment.ts | 39 +- tsconfig.json | 1 + 24 files changed, 276 insertions(+), 1334 deletions(-) create mode 100644 .env.example create mode 100644 data/config/worlds.example.json delete mode 100644 prisma/migrations/20231226044539_initial/migration.sql delete mode 100644 prisma/migrations/20231226074531_newsposts/migration.sql delete mode 100644 prisma/migrations/20231227162751_npc_hiscore/migration.sql delete mode 100644 prisma/migrations/20240115054529_friendserver/migration.sql delete mode 100644 prisma/migrations/20240115200541_chat_logging/migration.sql delete mode 100644 prisma/migrations/20240212142636_newspost_editing/migration.sql delete mode 100644 prisma/migrations/migration_lock.toml delete mode 100644 prisma/schema.prisma create mode 100644 src/3rdparty/ws-sync/ws-sync.js delete mode 100644 src/jagex2/datastruct/Hashable.ts delete mode 100644 src/jagex2/datastruct/LinkList.ts delete mode 100644 src/jagex2/datastruct/Linkable.ts delete mode 100644 src/jagex2/datastruct/Stack.ts delete mode 100644 src/jagex2/io/Packet.ts create mode 100644 src/lostcity/server/LoginClient.ts delete mode 100644 src/lostcity/server/LoginServer.ts delete mode 100644 src/lostcity/server/NetworkStream.ts diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..659bf53 --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +# PUBLIC_IP=localhost + +# WEB_PORT=80 +# SKIP_CORS=false +# HTTPS_ENABLED=false +# ADDRESS_SHOWPORT=true +# ADMIN_IP=localhost + +# DB_NAME= +# DB_HOST= +# DB_USER= +# DB_PASS= + +# LOGIN_HOST=localhost +# LOGIN_PORT=43500 +# LOGIN_KEY= diff --git a/.gitignore b/.gitignore index 4e6642a..efa137e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ tsconfig.tsbuildinfo node_modules/ +data/config/worlds.json + # coverage reports coverage/ diff --git a/data/config/worlds.example.json b/data/config/worlds.example.json new file mode 100644 index 0000000..dabc566 --- /dev/null +++ b/data/config/worlds.example.json @@ -0,0 +1,9 @@ +[ + { + "id": 1, + "region": "Local Development", + "address": "http://localhost:8888", + "members": "true", + "portOffset": 0 + } +] \ No newline at end of file diff --git a/package.json b/package.json index 5750dcf..6f17bf5 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "1.0.0", "type": "module", "imports": { + "#3rdparty/*": "./src/3rdparty/*", "#jagex2/*": "./src/jagex/*", "#lostcity/*": "./src/lostcity/*" }, @@ -26,7 +27,7 @@ "@fastify/session": "^10.8.0", "@fastify/static": "^7.0.4", "@fastify/view": "^9.1.0", - "@types/node-forge": "^1.3.11", + "@types/ws": "^8.5.12", "bcrypt": "^5.1.1", "dotenv": "^16.4.5", "ejs": "^3.1.10", @@ -34,7 +35,7 @@ "kleur": "^4.1.5", "kysely": "^0.27.3", "mysql2": "^3.9.7", - "node-forge": "^1.3.1" + "ws": "^8.18.0" }, "devDependencies": { "@commitlint/cli": "^19.3.0", @@ -56,8 +57,6 @@ "lint-staged": "^15.2.2", "nodemon": "^3.1.0", "prettier": "3.2.5", - "prisma": "^5.14.0", - "prisma-kysely": "^1.8.0", "sort-package-json": "^2.10.0", "tinybench": "^2.8.0", "typescript": "^5.4.5", @@ -65,8 +64,5 @@ }, "optionalDependencies": { "@rollup/rollup-linux-x64-gnu": "^4.9.5" - }, - "prisma": { - "seed": "npm run ts-loader src/lostcity/db/seed.ts" } } diff --git a/prisma/migrations/20231226044539_initial/migration.sql b/prisma/migrations/20231226044539_initial/migration.sql deleted file mode 100644 index 114c135..0000000 --- a/prisma/migrations/20231226044539_initial/migration.sql +++ /dev/null @@ -1,11 +0,0 @@ --- CreateTable -CREATE TABLE `account` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `username` VARCHAR(191) NOT NULL, - `password` VARCHAR(191) NOT NULL, - `registration_ip` VARCHAR(191) NULL, - `registration_date` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - - UNIQUE INDEX `account_username_key`(`username`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/prisma/migrations/20231226074531_newsposts/migration.sql b/prisma/migrations/20231226074531_newsposts/migration.sql deleted file mode 100644 index b26298f..0000000 --- a/prisma/migrations/20231226074531_newsposts/migration.sql +++ /dev/null @@ -1,19 +0,0 @@ --- CreateTable -CREATE TABLE `newspost` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `category_id` INTEGER NOT NULL, - `title` TINYTEXT NOT NULL, - `content` TEXT NOT NULL, - `date` DATETIME(3) NOT NULL, - - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `newspost_category` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `name` VARCHAR(191) NOT NULL, - `style` VARCHAR(191) NOT NULL, - - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/prisma/migrations/20231227162751_npc_hiscore/migration.sql b/prisma/migrations/20231227162751_npc_hiscore/migration.sql deleted file mode 100644 index e9b8ebe..0000000 --- a/prisma/migrations/20231227162751_npc_hiscore/migration.sql +++ /dev/null @@ -1,9 +0,0 @@ --- CreateTable -CREATE TABLE `npc_hiscore` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `npc_id` INTEGER NOT NULL, - `account_id` INTEGER NOT NULL, - `kill_count` INTEGER NOT NULL DEFAULT 0, - - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/prisma/migrations/20240115054529_friendserver/migration.sql b/prisma/migrations/20240115054529_friendserver/migration.sql deleted file mode 100644 index a4492d2..0000000 --- a/prisma/migrations/20240115054529_friendserver/migration.sql +++ /dev/null @@ -1,15 +0,0 @@ --- CreateTable -CREATE TABLE `friendlist` ( - `account_id` INTEGER NOT NULL, - `friend_account_id` INTEGER NOT NULL, - - PRIMARY KEY (`account_id`, `friend_account_id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `ignorelist` ( - `account_id` INTEGER NOT NULL, - `ignore_account_id` INTEGER NOT NULL, - - PRIMARY KEY (`account_id`, `ignore_account_id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/prisma/migrations/20240115200541_chat_logging/migration.sql b/prisma/migrations/20240115200541_chat_logging/migration.sql deleted file mode 100644 index 43093c9..0000000 --- a/prisma/migrations/20240115200541_chat_logging/migration.sql +++ /dev/null @@ -1,20 +0,0 @@ --- CreateTable -CREATE TABLE `public_chat` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `account_id` INTEGER NOT NULL, - `message` VARCHAR(191) NOT NULL, - `date` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `private_chat` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `from_account_id` INTEGER NOT NULL, - `to_account_id` INTEGER NOT NULL, - `message` VARCHAR(191) NOT NULL, - `date` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/prisma/migrations/20240212142636_newspost_editing/migration.sql b/prisma/migrations/20240212142636_newspost_editing/migration.sql deleted file mode 100644 index 3d1e6f7..0000000 --- a/prisma/migrations/20240212142636_newspost_editing/migration.sql +++ /dev/null @@ -1,3 +0,0 @@ --- AlterTable -ALTER TABLE `newspost` ADD COLUMN `updated` DATETIME(3) NULL DEFAULT CURRENT_TIMESTAMP(3), - MODIFY `date` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3); diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml deleted file mode 100644 index e5a788a..0000000 --- a/prisma/migrations/migration_lock.toml +++ /dev/null @@ -1,3 +0,0 @@ -# Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) -provider = "mysql" \ No newline at end of file diff --git a/prisma/schema.prisma b/prisma/schema.prisma deleted file mode 100644 index d84256b..0000000 --- a/prisma/schema.prisma +++ /dev/null @@ -1,79 +0,0 @@ -generator kysely { - provider = "prisma-kysely" - - output = "../src/lostcity/db" - fileName = "types.ts" - enumFileName = "enums.ts" -} - -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} - -model account { - id Int @id @default(autoincrement()) - - username String @unique - password String - - registration_ip String? - registration_date DateTime @default(now()) -} - -model newspost { - id Int @id @default(autoincrement()) - - category_id Int - title String @db.TinyText - content String @db.Text - date DateTime @default(now()) - updated DateTime? @default(now()) @updatedAt -} - -model newspost_category { - id Int @id @default(autoincrement()) - - name String - // css style class - style String -} - -model npc_hiscore { - id Int @id @default(autoincrement()) - - npc_id Int - account_id Int - kill_count Int @default(0) -} - -model friendlist { - account_id Int - friend_account_id Int - - @@id([account_id, friend_account_id]) -} - -model ignorelist { - account_id Int - ignore_account_id Int - - @@id([account_id, ignore_account_id]) -} - -model public_chat { - id Int @id @default(autoincrement()) - - account_id Int - message String - date DateTime @default(now()) -} - -model private_chat { - id Int @id @default(autoincrement()) - - from_account_id Int - to_account_id Int - message String - date DateTime @default(now()) -} diff --git a/src/3rdparty/ws-sync/ws-sync.js b/src/3rdparty/ws-sync/ws-sync.js new file mode 100644 index 0000000..c860e9f --- /dev/null +++ b/src/3rdparty/ws-sync/ws-sync.js @@ -0,0 +1,167 @@ +// thank you: https://github.com/Puvox/synchronous-websocket-request-js + +// this was edited slightly from the source, but since it's unlicensed, we may revisit this to +// rewrite it using the same idea (pass a message request ID and await a response) + +import { webcrypto as crypto } from 'crypto'; + +export default class WsSyncReq { + waitedSyncCallbacks = {}; + waiterPrefix = 'id'; + loopPauseWaitIntervalMS = 500; + + wsc = null; + + constructor (ws_connection) { + this.wsc = ws_connection; + this.wsc.on('message', (payload)=>{ + this.receivedMessage(payload); + }) + } + + // some random UUID like generator + uuidv4() { + return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => + (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) + ); + } + + sleep(ms) { + return new Promise(resolve => this.setTimeout_safe(resolve, ms)); + } + + // immitating ccxt's setTimeout + setTimeout_safe (done, ms) { + const self = this; const targetTime = Date.now() + ms; if (ms >= 2147483647) { throw new Error ('setTimeout() function was called with unrealistic value of ' + ms.toString ()); } let clearInnerTimeout = () => {}; let active = true; const id = setTimeout (() => { active = true; const rest = targetTime - Date.now (); if (rest > 0) { clearInnerTimeout = self.setTimeout_safe (done, rest, setTimeout, targetTime); } else { done (); } }, ms); return function clear () { if (active) { active = false; clearTimeout (id); } clearInnerTimeout (); }; + } + + // https://stackoverflow.com/a/44782052/2377343 + cloneObjectDestructuve(orig){ + return Object.assign(Object.create(Object.getPrototypeOf(orig)), orig); + } + + isString(x) { return Object.prototype.toString.call(x) === '[object String]'; } + isInteger(x) { return Number.isInteger(x); } + isObject(variable){ return typeof variable === 'object' && variable !== null; } + isKeyType(x) { return this.isString(x) || this.isInteger(x); } + + send(data) { + if (!this.checkIfWsLive()) return false; + this.wsc.send(JSON.stringify(data)); + return true; + } + + checkIfWsLive() { + return this.wsc !== null && this.wsc.readyState === 1; + } + + keyOfRequestId = 'replyTo'; + keyOfResponseId = 'replyTo'; + + async fetchSync(dataToSend = {}, timeoutMs = 10000, expectedObjectStructure = null, callbackOnIncoming = null) { + const uniqueId = this.waiterPrefix + '_' + this.uuidv4(); + if (uniqueId in this.waitedSyncCallbacks) { + throw new Error('ws-sync fetch - uniqueId already exists: ' + uniqueId); + } + + let expectedObj = null; + if (expectedObjectStructure === null) { + expectedObj = { + [this.keyOfResponseId] : uniqueId + }; + } else if (this.isObject(expectedObjectStructure)) { + expectedObj = expectedObjectStructure; + if ('includeUniqueKey' in expectedObj) { + if (expectedObj.includeUniqueKey) { + expectedObj[this.keyOfResponseId] = uniqueId; + } + delete expectedObj.includeUniqueKey; + } + } else { + throw new Error('ws-sync fetch - expectedObjectStructure argument must be "null" or an object'); + } + + this.waitedSyncCallbacks[uniqueId] = { + 'result': null, + 'onIncomingCallback': callbackOnIncoming, + 'expectedObject': expectedObj, + }; + const data_new = this.cloneObjectDestructuve (dataToSend); + data_new[this.keyOfRequestId] = uniqueId; + + if (this.send(data_new)) { + let start = Date.now(); + while (true) { + if (!this.checkIfWsLive()) { + delete this.waitedSyncCallbacks[uniqueId]; + return { error : 'ws-sync - connection lost: ' + uniqueId, result:null}; + } else if ((Date.now() - start) > timeoutMs) { + return { error : 'ws-sync - exceeded timeout: ' + uniqueId, result:null}; + } else { + await this.sleep(this.loopPauseWaitIntervalMS); + if (uniqueId in this.waitedSyncCallbacks) { + const value = this.waitedSyncCallbacks[uniqueId]; + if (value['result'] != null) { + delete this.waitedSyncCallbacks[uniqueId]; + return { error: null, result: value['result'] }; + } + } else { + var msg = 'ws-sync - unexpected exception, this should not be happen... the unique id does not exist: ' + uniqueId; + return { error : msg, result:null }; + } + } + } + } else { + return { error : 'ws-sync - failed to send request. Socket may be disconnected', result:null }; + } + } + + receivedMessage(fullPayload) { + let response = null; + try { + response = JSON.parse(fullPayload); + } catch(exc) { + throw new Error('ws-sync - could not parse JSON: ' + fullPayload + ' | ' + exc.toString() ); + } + + for (const [uniqId, kvpObject] of Object.entries(this.waitedSyncCallbacks)) { + let found = true; + let isIncomingForSameId = false; + let valuesArray = Object.entries(kvpObject['expectedObject']); + if (valuesArray.length == 0) { + found = false; + } else { + if (this.keyOfResponseId in response && response[this.keyOfResponseId] == uniqId) { + isIncomingForSameId = true; + } + // loop through all expected keys + for (const [keyName, valueOfKey] of valuesArray) { + if (keyName in response) { + if (valueOfKey !== undefined && response[keyName] !== valueOfKey) { + found = false; + break; + } + } else { + // if even one of the 'expected' key was not found, reject it + found = false; + break; + } + } + } + + if (found) { + this.waitedSyncCallbacks[uniqId]['result'] = response; + } + + if (!found || this.includeLastMatchForCallbacks){ + // for incoming callback + // note, here the last cycle will be skiped, when `found` variable is true + if (kvpObject['onIncomingCallback'] !== null) { + kvpObject['onIncomingCallback'](response, isIncomingForSameId); + } + } + } + } + + includeLastMatchForCallbacks = false; +} diff --git a/src/jagex2/datastruct/Hashable.ts b/src/jagex2/datastruct/Hashable.ts deleted file mode 100644 index 33802c6..0000000 --- a/src/jagex2/datastruct/Hashable.ts +++ /dev/null @@ -1,22 +0,0 @@ -import Linkable from './Linkable.js'; - -export default class Hashable extends Linkable { - nextHashable: Hashable | null; - prevHashable: Hashable | null; - - constructor() { - super(); - this.nextHashable = this; - this.prevHashable = this; - } - - uncache(): void { - if (!this.prevHashable || !this.nextHashable) { - return; - } - this.prevHashable.nextHashable = this.nextHashable; - this.nextHashable.prevHashable = this.prevHashable; - this.nextHashable = null; - this.prevHashable = null; - } -} diff --git a/src/jagex2/datastruct/LinkList.ts b/src/jagex2/datastruct/LinkList.ts deleted file mode 100644 index beb6ee1..0000000 --- a/src/jagex2/datastruct/LinkList.ts +++ /dev/null @@ -1,97 +0,0 @@ -import Linkable from './Linkable.js'; - -export default class LinkList { - private readonly sentinel: Linkable; - private cursor: Linkable | null = null; - - constructor() { - const head: Linkable = new Linkable(); - head.next = head; - head.prev = head; - this.sentinel = head; - } - - addTail(node: T): void { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel.prev; - node.next = this.sentinel; - if (node.prev) { - node.prev.next = node; - } - node.next.prev = node; - } - - addHead(node: T): void { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel; - node.next = this.sentinel.next; - node.prev.next = node; - if (node.next) { - node.next.prev = node; - } - } - - removeHead(): T | null { - const node: T | null = this.sentinel.next as T | null; - if (node === this.sentinel) { - return null; - } - node?.unlink(); - return node; - } - - head(): T | null { - const node: T | null = this.sentinel.next as T | null; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - - tail(): T | null { - const node: T | null = this.sentinel.prev as T | null; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - - next(): T | null { - const node: T | null = this.cursor as T | null; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - - prev(): T | null { - const node: T | null = this.cursor as T | null; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - - clear(): void { - // eslint-disable-next-line no-constant-condition - while (true) { - const node: T | null = this.sentinel.next as T | null; - if (node === this.sentinel) { - return; - } - node?.unlink(); - } - } -} diff --git a/src/jagex2/datastruct/Linkable.ts b/src/jagex2/datastruct/Linkable.ts deleted file mode 100644 index 34be0ba..0000000 --- a/src/jagex2/datastruct/Linkable.ts +++ /dev/null @@ -1,21 +0,0 @@ -export default class Linkable { - key: bigint; - next: Linkable | null; - prev: Linkable | null; - - constructor() { - this.key = 0n; - this.next = this; - this.prev = this; - } - - unlink(): void { - if (!this.prev || !this.next) { - return; - } - this.prev.next = this.next; - this.next.prev = this.prev; - this.next = null; - this.prev = null; - } -} diff --git a/src/jagex2/datastruct/Stack.ts b/src/jagex2/datastruct/Stack.ts deleted file mode 100644 index 8e39475..0000000 --- a/src/jagex2/datastruct/Stack.ts +++ /dev/null @@ -1,54 +0,0 @@ -import Hashable from '#jagex2/datastruct/Hashable.js'; - -export default class Stack { - readonly sentinel: Hashable; - private cursor: Hashable | null = null; - - constructor() { - const head: Hashable = new Hashable(); - head.nextHashable = head; - head.prevHashable = head; - this.sentinel = head; - } - - push(node: T): void { - if (node.prevHashable) { - node.uncache(); - } - node.prevHashable = this.sentinel.prevHashable; - node.nextHashable = this.sentinel; - if (node.prevHashable) { - node.prevHashable.nextHashable = node; - } - node.nextHashable.prevHashable = node; - } - - pop(): T | null { - const node: T | null = this.sentinel.nextHashable as T | null; - if (node === this.sentinel) { - return null; - } - node?.uncache(); - return node; - } - - head(): T | null { - const node: T | null = this.sentinel.nextHashable as T | null; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.nextHashable || null; - return node; - } - - next(): T | null { - const node: T | null = this.cursor as T | null; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.nextHashable || null; - return node; - } -} diff --git a/src/jagex2/io/Packet.ts b/src/jagex2/io/Packet.ts deleted file mode 100644 index 7610058..0000000 --- a/src/jagex2/io/Packet.ts +++ /dev/null @@ -1,429 +0,0 @@ -import fs from 'fs'; -import {dirname} from 'path'; -import forge from 'node-forge'; -import PrivateKey = forge.pki.rsa.PrivateKey; -import BigInteger = forge.jsbn.BigInteger; - -import LinkList from '#jagex2/datastruct/LinkList.js'; -import Hashable from '#jagex2/datastruct/Hashable.js'; - -export default class Packet extends Hashable { - private static readonly crctable: Int32Array = new Int32Array(256); - private static readonly bitmask: Uint32Array = new Uint32Array(33); - - /** - * Reversed CRC-32 polynomial for Cyclic Redundancy Check (CRC). - * This is sometimes referred to as CRC32B. - */ - private static readonly crc32b = 0xEDB88320; - - static { - for (let i: number = 0; i < 32; i++) { - this.bitmask[i] = (1 << i) - 1; - } - this.bitmask[32] = 0xffffffff; - - for (let b = 0; b < 256; b++) { - let remainder = b; - - for (let bit = 0; bit < 8; bit++) { - if ((remainder & 0x1) == 1) { - remainder = (remainder >>> 1) ^ this.crc32b; - } else { - remainder >>>= 0x1; - } - } - - this.crctable[b] = remainder; - } - } - - static getcrc(src: Uint8Array, offset: number, length: number): number { - let crc = 0xffffffff; - for (let i = offset; i < length; i++) { - crc = (crc >>> 8) ^ (this.crctable[(crc ^ src[i]) & 0xFF]); - } - return ~crc; - } - - static checkcrc(src: Uint8Array, offset: number, length: number, expected: number = 0): boolean { - const checksum: number = Packet.getcrc(src, offset, length); - // console.log(checksum, expected); - return checksum == expected; - } - - static alloc(type: number): Packet { - let packet: Packet | null = null; - - if (type === 0 && this.cacheMinCount > 0) { - packet = this.cacheMin.removeHead(); - this.cacheMinCount--; - } else if (type === 1 && this.cacheMidCount > 0) { - packet = this.cacheMid.removeHead(); - this.cacheMidCount--; - } else if (type === 2 && this.cacheMaxCount > 0) { - packet = this.cacheMax.removeHead(); - this.cacheMaxCount--; - } else if (type === 3 && this.cacheBigCount > 0) { - packet = this.cacheBig.removeHead(); - this.cacheBigCount--; - } else if (type === 4 && this.cacheHugeCount > 0) { - packet = this.cacheHuge.removeHead(); - this.cacheHugeCount--; - } else if (type === 5 && this.cacheUnimaginableCount > 0) { - packet = this.cacheUnimaginable.removeHead(); - this.cacheUnimaginableCount--; - } - - if (packet !== null) { - packet.pos = 0; - packet.bitPos = 0; - return packet; - } - - if (type === 0) { - return new Packet(new Uint8Array(100)); - } else if (type === 1) { - return new Packet(new Uint8Array(5000)); - } else if (type === 2) { - return new Packet(new Uint8Array(30000)); - } else if (type === 3) { - return new Packet(new Uint8Array(100000)); - } else if (type === 4) { - return new Packet(new Uint8Array(500000)); - } else if (type === 5) { - return new Packet(new Uint8Array(2000000)); - } else { - return new Packet(new Uint8Array(type)); - } - } - - static load(path: string, seekToEnd: boolean = false): Packet { - const packet = new Packet(new Uint8Array(fs.readFileSync(path))); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - - private static cacheMinCount: number = 0; - private static cacheMidCount: number = 0; - private static cacheMaxCount: number = 0; - private static cacheBigCount: number = 0; - private static cacheHugeCount: number = 0; - private static cacheUnimaginableCount: number = 0; - - private static readonly cacheMin: LinkList = new LinkList(); - private static readonly cacheMid: LinkList = new LinkList(); - private static readonly cacheMax: LinkList = new LinkList(); - private static readonly cacheBig: LinkList = new LinkList(); - private static readonly cacheHuge: LinkList = new LinkList(); - private static readonly cacheUnimaginable: LinkList = new LinkList(); - - data: Uint8Array; - #view: DataView; - pos: number; - bitPos: number; - - constructor(src: Uint8Array) { - super(); - - this.data = src; - this.#view = new DataView(this.data.buffer); - this.pos = 0; - this.bitPos = 0; - } - - get available(): number { - return this.data.length - this.pos; - } - - get length(): number { - return this.data.length; - } - - release(): void { - this.pos = 0; - this.bitPos = 0; - - if (this.data.length === 100 && Packet.cacheMinCount < 1000) { - Packet.cacheMin.addTail(this); - Packet.cacheMinCount++; - } else if (this.data.length === 5000 && Packet.cacheMidCount < 250) { - Packet.cacheMid.addTail(this); - Packet.cacheMidCount++; - } else if (this.data.length === 30000 && Packet.cacheMaxCount < 50) { - Packet.cacheMax.addTail(this); - Packet.cacheMaxCount++; - } else if (this.data.length === 100000 && Packet.cacheBigCount < 10) { - Packet.cacheBig.addTail(this); - Packet.cacheBigCount++; - } else if (this.data.length === 500000 && Packet.cacheHugeCount < 5) { - Packet.cacheHuge.addTail(this); - Packet.cacheHugeCount++; - } else if (this.data.length === 2000000 && Packet.cacheUnimaginableCount < 2) { - Packet.cacheUnimaginable.addTail(this); - Packet.cacheUnimaginableCount++; - } - } - - save(path: string, length: number = this.pos, start: number = 0): void { - const dir: string = dirname(path); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - - fs.writeFileSync(path, this.data.subarray(start, start + length)); - } - - p1(value: number): void { - this.#view.setUint8(this.pos++, value); - } - - p2(value: number): void { - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - - ip2(value: number): void { - this.#view.setUint16(this.pos, value, true); - this.pos += 2; - } - - p3(value: number): void { - this.#view.setUint8(this.pos++, value >> 16); - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - - p4(value: number): void { - this.#view.setInt32(this.pos, value); - this.pos += 4; - } - - ip4(value: number): void { - this.#view.setInt32(this.pos, value, true); - this.pos += 4; - } - - p8(value: bigint): void { - this.#view.setBigInt64(this.pos, value); - this.pos += 8; - } - - pbool(value: boolean): void { - this.p1(value ? 1 : 0); - } - - pjstr(str: string | null, terminator: number = 10): void { - if (str === null) { - str = 'null'; - } - - const length: number = str.length; - for (let i: number = 0; i < length; i++) { - this.#view.setUint8(this.pos++, str.charCodeAt(i)); - } - this.#view.setUint8(this.pos++, terminator); - } - - pdata(src: Uint8Array, offset: number, length: number): void { - this.data.set(src.subarray(offset, offset + length), this.pos); - this.pos += length - offset; - } - - psize4(size: number): void { - this.#view.setUint32(this.pos - size - 4, size); - } - - psize2(size: number): void { - this.#view.setUint16(this.pos - size - 2, size); - } - - psize1(size: number): void { - this.#view.setUint8(this.pos - size - 1, size); - } - - psmarts(value: number): void { - if (value < 64 && value >= 64) { - this.p1(value + 64); - } else if (value < 16384 && value >= -16384) { - this.p2(value + 0xC000); - } else { - throw new Error('Error psmarts out of range: ' + value); - } - } - - psmart(value: number): void { - if (value >= 0 && value < 128) { - this.p1(value); - } else if (value >= 0 && value < 32768) { - this.p2(value + 0x8000); - } else { - throw new Error('Error psmart out of range: ' + value); - } - } - - // ---- - - g1(): number { - return this.#view.getUint8(this.pos++); - } - - g1b(): number { - return this.#view.getInt8(this.pos++); - } - - g2(): number { - this.pos += 2; - return this.#view.getUint16(this.pos - 2); - } - - g2s(): number { - this.pos += 2; - return this.#view.getInt16(this.pos - 2); - } - - ig2(): number { - this.pos += 2; - return this.#view.getUint16(this.pos - 2, true); - } - - g3(): number { - const result: number = (this.#view.getUint8(this.pos++) << 16) | this.#view.getUint16(this.pos); - this.pos += 2; - return result; - } - - g4(): number { - this.pos += 4; - return this.#view.getInt32(this.pos - 4); - } - - ig4(): number { - this.pos += 4; - return this.#view.getInt32(this.pos - 4, true); - } - - g8(): bigint { - this.pos += 8; - return this.#view.getBigInt64(this.pos - 8); - } - - gbool(): boolean { - return this.g1() === 1; - } - - gjstr(terminator = 10): string { - const length: number = this.data.length; - let str: string = ''; - let b: number; - while ((b = this.#view.getUint8(this.pos++)) !== terminator && this.pos < length) { - str += String.fromCharCode(b); - } - return str; - } - - gdata(dest: Uint8Array, offset: number, length: number): void { - dest.set(this.data.subarray(this.pos, this.pos + length), offset); - this.pos += length; - } - - gsmarts(): number { - return this.#view.getUint8(this.pos) < 0x80 ? this.g1() - 64 : this.g2() - 0xC000; - } - - gsmart(): number { - return this.#view.getUint8(this.pos) < 0x80 ? this.g1() : this.g2() - 0x8000; - } - - bits(): void { - this.bitPos = this.pos * 8; - // this.bitPos = this.pos << 3; - } - - bytes(): void { - this.pos = ((this.bitPos + 7) / 8) | 0; - // this.pos = (this.bitPos + 7) >>> 3; - } - - gBit(n: number): number { - let bytePos: number = this.bitPos >>> 3; - let remaining: number = 8 - (this.bitPos & 7); - let value: number = 0; - this.bitPos += n; - - for (; n > remaining; remaining = 8) { - value += (this.#view.getUint8(bytePos++) & Packet.bitmask[remaining]) << (n - remaining); - n -= remaining; - } - - if (n == remaining) { - value += this.#view.getUint8(bytePos) & Packet.bitmask[remaining]; - } else { - value += (this.#view.getUint8(bytePos) >>> (remaining - n)) & Packet.bitmask[n]; - } - - return value; - } - - pBit(n: number, value: number): void { - let bytePos: number = this.bitPos >>> 3; - let remaining: number = 8 - (this.bitPos & 7); - this.bitPos += n; - - for (; n > remaining; remaining = 8) { - this.#view.setUint8(bytePos, this.#view.getUint8(bytePos) & ~Packet.bitmask[remaining]); - this.#view.setUint8(bytePos, this.#view.getUint8(bytePos) | ((value >>> (n - remaining)) & Packet.bitmask[remaining])); - bytePos++; - n -= remaining; - } - - if (n == remaining) { - this.#view.setUint8(bytePos, this.#view.getUint8(bytePos) & ~Packet.bitmask[remaining]); - this.#view.setUint8(bytePos, this.#view.getUint8(bytePos) | value & Packet.bitmask[remaining]); - } else { - this.#view.setUint8(bytePos, this.#view.getUint8(bytePos) & (~Packet.bitmask[n] << (remaining - n))); - this.#view.setUint8(bytePos, this.#view.getUint8(bytePos) | ((value & Packet.bitmask[n]) << (remaining - n))); - } - } - - rsaenc(pem: PrivateKey): void { - const length: number = this.pos; - this.pos = 0; - - const dec: Uint8Array = new Uint8Array(length); - this.gdata(dec, 0, dec.length); - - const bigRaw: BigInteger = new BigInteger(Array.from(dec)); - const rawEnc: Uint8Array = Uint8Array.from(bigRaw.modPow(pem.e, pem.n).toByteArray()); - - this.pos = 0; - this.p1(rawEnc.length); - this.pdata(rawEnc, 0, rawEnc.length); - } - - rsadec(pem: PrivateKey): void { - const p: BigInteger = pem.p; - const q: BigInteger = pem.q; - const dP: BigInteger = pem.dP; - const dQ: BigInteger = pem.dQ; - const qInv: BigInteger = pem.qInv; - - const enc: Uint8Array = new Uint8Array(this.g1()); - this.gdata(enc, 0, enc.length); - - const bigRaw: BigInteger = new BigInteger(Array.from(enc)); - const m1: BigInteger = bigRaw.mod(p).modPow(dP, p); - const m2: BigInteger = bigRaw.mod(q).modPow(dQ, q); - const h: BigInteger = qInv.multiply(m1.subtract(m2)).mod(p); - const rawDec: Uint8Array = new Uint8Array(m2.add(h.multiply(q)).toByteArray()); - - this.pos = 0; - this.pdata(rawDec, 0, rawDec.length); - this.pos = 0; - } - - // later revs have tinyenc/tinydec methods - // later revs have alt methods for packet obfuscation -} diff --git a/src/lostcity/engine/WorldList.ts b/src/lostcity/engine/WorldList.ts index 28f1ddb..6f357c6 100644 --- a/src/lostcity/engine/WorldList.ts +++ b/src/lostcity/engine/WorldList.ts @@ -1,6 +1,6 @@ import fs from 'fs'; -import { LoginClient } from '#lostcity/server/LoginServer.js'; +import LoginClient from '#lostcity/server/LoginClient.js'; import Environment from '#lostcity/util/Environment.js'; @@ -28,29 +28,10 @@ if (fs.existsSync('data/config/worlds.json')) { } } -if (Environment.LOCAL_DEV) { - let address = (Environment.HTTPS_ENABLED ? 'https://' : 'http://') + Environment.PUBLIC_IP; - if (Environment.ADDRESS_SHOWPORT) { - if (Environment.HTTPS_ENABLED && Environment.WEB_PORT != 443 && Environment.WEB_PORT != 80) { - address += ':' + Environment.WEB_PORT; - } else if (!Environment.HTTPS_ENABLED && Environment.WEB_PORT != 80) { - address += ':' + Environment.WEB_PORT; - } - } - - WorldList.push({ - id: Environment.WORLD_ID, - region: 'Local Development', - members: Environment.MEMBERS_WORLD, - address, - portOffset: Environment.GAME_PORT - 43594, - players: 0 - }); -} +const login = new LoginClient(); async function refreshWorldList() { for (const world of WorldList) { - const login = new LoginClient(); world.players = await login.count(world.id + 9); } } diff --git a/src/lostcity/server/LoginClient.ts b/src/lostcity/server/LoginClient.ts new file mode 100644 index 0000000..e320d27 --- /dev/null +++ b/src/lostcity/server/LoginClient.ts @@ -0,0 +1,69 @@ +import { WebSocket } from 'ws'; +import WsSyncReq from '#3rdparty/ws-sync/ws-sync.js'; + +import Environment from '#lostcity/util/Environment.js'; + +export default class LoginClient { + private ws: WebSocket | null = null; + private wsr: WsSyncReq | null = null; + + async connect() { + if (this.wsr && this.wsr.checkIfWsLive()) { + return; + } + + return new Promise((res, rej) => { + this.ws = new WebSocket(`ws://${Environment.LOGIN_HOST}:${Environment.LOGIN_PORT}`); + + const timeout = setTimeout(() => { + this.ws = null; + this.wsr = null; + res(); + }, 10000); + + this.ws.once('close', () => { + clearTimeout(timeout); + + this.ws = null; + this.wsr = null; + res(); + }); + + this.ws.once('error', (err) => { + clearTimeout(timeout); + + this.ws = null; + this.wsr = null; + res(); + }); + + this.ws.once('open', () => { + clearTimeout(timeout); + + this.wsr = new WsSyncReq(this.ws); + res(); + }); + }); + } + + async count(world: number) { + await this.connect(); + + if (!this.ws || !this.wsr || !this.wsr.checkIfWsLive()) { + return -1; + } + + const message = await this.wsr.fetchSync({ + type: 4, + world + }); + + if (message.error) { + return { reply: -1, data: null }; + } + + const { count } = message.result; + + return count; + } +} diff --git a/src/lostcity/server/LoginServer.ts b/src/lostcity/server/LoginServer.ts deleted file mode 100644 index f5a95d5..0000000 --- a/src/lostcity/server/LoginServer.ts +++ /dev/null @@ -1,406 +0,0 @@ -import fs from 'fs'; -import fsp from 'fs/promises'; -import net from 'net'; -import bcrypt from 'bcrypt'; - -import Packet from '#jagex2/io/Packet.js'; - -import { fromBase37 } from '#jagex2/jstring/JString.js'; - -import { db } from '#lostcity/db/query.js'; - -import NetworkStream from '#lostcity/server/NetworkStream.js'; - -import Environment from '#lostcity/util/Environment.js'; - -export class LoginResponse { - static readonly SUCCESSFUL: Uint8Array = Uint8Array.from([2]); - static readonly INVALID_USER_OR_PASS: Uint8Array = Uint8Array.from([3]); // Invalid username or password. - static readonly ACCOUNT_DISABLED: Uint8Array = Uint8Array.from([4]); // Your account has been disabled. - static readonly LOGGED_IN: Uint8Array = Uint8Array.from([5]); // Your account is already logged in. - static readonly SERVER_UPDATED: Uint8Array = Uint8Array.from([6]); // RuneScape has been updated! - static readonly WORLD_FULL: Uint8Array = Uint8Array.from([7]); // This world is full. - static readonly LOGIN_SERVER_OFFLINE: Uint8Array = Uint8Array.from([8]); // Unable to connect. - static readonly LOGIN_LIMIT_EXCEEDED: Uint8Array = Uint8Array.from([9]); // Login limit exceeded. - static readonly UNABLE_TO_CONNECT: Uint8Array = Uint8Array.from([10]); // Unable to connect. - static readonly LOGIN_REJECTED: Uint8Array = Uint8Array.from([11]); // Login server rejected session. - static readonly NEED_MEMBERS_ACCOUNT: Uint8Array = Uint8Array.from([12]); // You need a members account to login to this world. - static readonly COULD_NOT_COMPLETE: Uint8Array = Uint8Array.from([13]); // Could not complete login. - static readonly SERVER_UPDATING: Uint8Array = Uint8Array.from([14]); // The server is being updated. - static readonly RECONNECTING: Uint8Array = Uint8Array.from([15]); - static readonly LOGIN_ATTEMPTS_EXCEEDED: Uint8Array = Uint8Array.from([16]); // Login attempts exceeded. - static readonly STANDING_IN_MEMBERS: Uint8Array = Uint8Array.from([17]); // You are standing in a members-only area. - static readonly STAFF_MOD_LEVEL: Uint8Array = Uint8Array.from([18]); -} - -export class LoginServer { - private server: net.Server; - private players: bigint[][] = []; - - constructor() { - this.server = net.createServer(); - } - - start() { - this.server.on('connection', socket => { - socket.setNoDelay(true); - socket.setTimeout(5000); - - const stream = new NetworkStream(); - - socket.on('data', async buf => { - stream.received(buf); - if (stream.waiting > stream.available) { - return; - } - - stream.waiting = 0; - const data = Packet.alloc(1); - await stream.readBytes(socket, data, 0, 3); - - const opcode = data.g1(); - const length = data.g2(); - if (stream.available < length) { - stream.waiting = length - stream.available; - return; - } - - await stream.readBytes(socket, data, 0, length); - - if (opcode === 1) { - // login - const world = data.g2(); - const username37 = data.g8(); - const password = data.gjstr(); - const uid = data.g4(); - - if (!this.players[world]) { - this.players[world] = []; - } - - const username = fromBase37(username37); - const account = await db.selectFrom('account').where('username', '=', username).selectAll().executeTakeFirst(); - if (!account || !(await bcrypt.compare(password.toLowerCase(), account.password))) { - // invalid credentials (bad user or bad pass) - const reply = new Packet(new Uint8Array(1)); - reply.p1(5); - await this.write(socket, reply.data); - data.release(); - return; - } - - if (this.players[world].includes(username37)) { - // logged into this world (reconnect logic) - const reply = new Packet(new Uint8Array(1)); - reply.p1(2); - await this.write(socket, reply.data); - data.release(); - return; - } - - for (let i = 0; i < this.players.length; i++) { - if (!this.players[i]) { - continue; - } - - if (this.players[i].includes(username37)) { - // logged into another world - const reply = new Packet(new Uint8Array(1)); - reply.p1(3); - await this.write(socket, reply.data); - data.release(); - return; - } - } - - this.players[world].push(username37); - - if (!fs.existsSync(`data/players/${username}.sav`)) { - // new player save - const reply = new Packet(new Uint8Array(1)); - reply.p1(4); - await this.write(socket, reply.data); - data.release(); - return; - } - - const save = await fsp.readFile(`data/players/${username}.sav`); - const reply = new Packet(new Uint8Array(save.length + 2 + 1)); - reply.p1(1); - reply.p2(save.length); - reply.pdata(save, 0, save.length); - await this.write(socket, reply.data); - } else if (opcode === 2) { - // logout - const world = data.g2(); - const username37 = data.g8(); - const saveLength = data.g2(); - const save = new Uint8Array(saveLength); - data.gdata(save, 0, save.length); - - const username = fromBase37(username37); - await fsp.writeFile(`data/players/${username}.sav`, save); - - if (!this.players[world]) { - this.players[world] = []; - } - - const index = this.players[world].indexOf(username37); - if (index > -1) { - this.players[world].splice(index, 1); - } - - const reply = new Packet(new Uint8Array(1)); - reply.p1(0); - await this.write(socket, reply.data); - } else if (opcode === 3) { - // reset world - const world = data.g2(); - - if (!this.players[world]) { - this.players[world] = []; - } - - this.players[world] = []; - } else if (opcode === 4) { - // count players - const world = data.g2(); - - if (!this.players[world]) { - this.players[world] = []; - } - - const reply = new Packet(new Uint8Array(2)); - reply.p2(this.players[world].length); - await this.write(socket, reply.data); - } else if (opcode === 5) { - // heartbeat/check in - update player list (used for re-syncing right now... weird bug) - const world = data.g2(); - this.players[world] = []; - - const count = data.g2(); - for (let i = 0; i < count; i++) { - const username37 = data.g8(); - this.players[world].push(username37); - } - } - - data.release(); - }); - - socket.on('close', () => {}); - socket.on('error', () => {}); - }); - - this.server.listen({ port: Environment.LOGIN_PORT, host: '0.0.0.0' }, () => { - //console.log(`[Login]: Listening on port ${Environment.LOGIN_PORT}`); - }); - } - - private async write(socket: net.Socket, data: Uint8Array | Buffer, full: boolean = true) { - if (socket === null) { - return; - } - - const done = socket.write(data); - - if (!done && full) { - await new Promise(res => { - const interval = setInterval(() => { - if (socket === null || socket.closed) { - clearInterval(interval); - res(); - } - }, 100); - - socket.once('drain', () => { - clearInterval(interval); - res(); - }); - }); - } - } -} - -export class LoginClient { - private socket: net.Socket | null = null; - private stream: NetworkStream = new NetworkStream(); - - async connect() { - if (this.socket) { - return; - } - - return new Promise(res => { - this.socket = net.createConnection({ - port: Environment.LOGIN_PORT as number, - host: Environment.LOGIN_HOST as string - }); - - this.socket.setNoDelay(true); - this.socket.setTimeout(1000); - - this.socket.on('data', async buf => { - this.stream.received(buf); - }); - - this.socket.once('close', () => { - this.disconnect(); - res(); - }); - - this.socket.once('error', () => { - this.disconnect(); - res(); - }); - - this.socket.once('connect', () => { - res(); - }); - }); - } - - disconnect() { - if (this.socket === null) { - return; - } - - this.socket.destroy(); - this.socket = null; - this.stream.clear(); - } - - private async write(socket: net.Socket, opcode: number, data: Uint8Array | null = null, full: boolean = true) { - if (socket === null) { - return; - } - - const packet = new Packet(new Uint8Array(1 + 2 + (data !== null ? data?.length : 0))); - packet.p1(opcode); - if (data !== null) { - packet.p2(data.length); - packet.pdata(data, 0, data.length); - } else { - packet.p2(0); - } - const done = socket.write(packet.data); - - if (!done && full) { - await new Promise(res => { - const interval = setInterval(() => { - if (socket === null || socket.closed) { - clearInterval(interval); - res(); - } - }, 100); - - socket.once('drain', () => { - clearInterval(interval); - res(); - }); - }); - } - } - - async load(username37: bigint, password: string, uid: number): Promise<{ reply: number; data: Packet | null }> { - await this.connect(); - - if (this.socket === null) { - return { reply: -1, data: null }; - } - - const request = new Packet(new Uint8Array(2 + 8 + password.length + 1 + 4)); - request.p2(Environment.WORLD_ID as number); - request.p8(username37); - request.pjstr(password); - request.p4(uid); - await this.write(this.socket, 1, request.data); - - const reply = await this.stream.readByte(this.socket); - if (reply !== 1) { - this.disconnect(); - return { reply, data: null }; - } - - const data = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, data, 0, 2); - - const length = data.g2(); - const data2 = new Packet(new Uint8Array(length)); - await this.stream.readBytes(this.socket, data2, 0, length); - - this.disconnect(); - return { reply, data: data2 }; - } - - async save(username37: bigint, save: Uint8Array) { - await this.connect(); - - if (this.socket === null) { - return -1; - } - - const request = new Packet(new Uint8Array(2 + 8 + 2 + save.length)); - request.p2(Environment.WORLD_ID as number); - request.p8(username37); - request.p2(save.length); - request.pdata(save, 0, save.length); - await this.write(this.socket, 2, request.data); - - const reply = await this.stream.readByte(this.socket); - this.disconnect(); - return reply; - } - - async reset() { - await this.connect(); - - if (this.socket === null) { - return -1; - } - - const request = new Packet(new Uint8Array(2)); - request.p2(Environment.WORLD_ID as number); - await this.write(this.socket, 3, request.data); - - this.disconnect(); - } - - async count(world: number) { - await this.connect(); - - if (this.socket === null) { - return -1; - } - - const request = new Packet(new Uint8Array(2)); - request.p2(world); - await this.write(this.socket, 4, request.data); - - const reply = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, reply, 0, 2); - - const count = reply.g2(); - - this.disconnect(); - return count; - } - - async heartbeat(players: bigint[]) { - await this.connect(); - - if (this.socket === null) { - return -1; - } - - const request = new Packet(new Uint8Array(2 + 2 + (players.length * 8))); - request.p2(Environment.WORLD_ID as number); - request.p2(players.length); - for (const player of players) { - request.p8(player); - } - await this.write(this.socket, 5, request.data); - - this.disconnect(); - } -} diff --git a/src/lostcity/server/NetworkStream.ts b/src/lostcity/server/NetworkStream.ts deleted file mode 100644 index 51fc099..0000000 --- a/src/lostcity/server/NetworkStream.ts +++ /dev/null @@ -1,86 +0,0 @@ -import net from 'net'; - -import Packet from '#jagex2/io/Packet.js'; - -export default class NetworkStream { - private queue: Uint8Array[] = []; // queue of data events - public available: number = 0; // remaining bytes to read - private buffer: Uint8Array | null = null; // current data event - private offset: number = 0; - public waiting: number = 0; // number of bytes waiting to be read - - received(buf: Buffer) { - this.queue.push(buf); - this.available += buf.length; - } - - clear() { - this.queue = []; - this.available = 0; - this.buffer = null; - this.offset = 0; - } - - async readByte(socket: net.Socket): Promise { - if (socket === null || socket.closed) { - return 0; - } - - if (this.available < 1) { - await new Promise(res => setTimeout(res, 10)); - return this.readByte(socket); - } - - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - - const value = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - - return value; - } - - async readBytes(socket: net.Socket, destination: Packet, offset: number, length: number, full = true): Promise { - if (socket === null || socket.closed) { - return 0; - } - - /*if (destination.length - offset < length) { - destination.resize(offset + length); - }*/ - - if (this.available < length) { - if (full) { - await new Promise(res => setTimeout(res, 10)); - return this.readBytes(socket, destination, offset, length); - } else { - length = this.available; - } - } - - destination.pos = offset; - for (let i = 0; i < length; i++) { - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - - destination.data[offset + i] = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - } - - return length; - } -} diff --git a/src/lostcity/util/Environment.ts b/src/lostcity/util/Environment.ts index 7bcadfc..90f9f25 100644 --- a/src/lostcity/util/Environment.ts +++ b/src/lostcity/util/Environment.ts @@ -1,46 +1,21 @@ import 'dotenv/config'; -import {tryParseArray, tryParseBoolean, tryParseInt, tryParseString} from './TryParse.js'; +import { tryParseBoolean, tryParseInt, tryParseString} from './TryParse.js'; export default { PUBLIC_IP: tryParseString(process.env.PUBLIC_IP, 'localhost'), + WEB_PORT: tryParseInt(process.env.WEB_PORT, 80), - GAME_PORT: tryParseInt(process.env.GAME_PORT, 43594), - - LOGIN_HOST: tryParseString(process.env.LOGIN_HOST, 'localhost'), - LOGIN_PORT: tryParseInt(process.env.LOGIN_PORT, 43500), - LOGIN_KEY: tryParseString(process.env.LOGIN_KEY, ''), - - FRIEND_HOST: tryParseString(process.env.FRIEND_HOST, 'localhost'), - FRIEND_PORT: tryParseInt(process.env.FRIEND_PORT, 43501), - FRIEND_KEY: tryParseString(process.env.FRIEND_KEY, ''), - - WORLD_ID: tryParseInt(process.env.WORLD_ID, 0), - LOCAL_DEV: tryParseBoolean(process.env.LOCAL_DEV, true), - MEMBERS_WORLD: tryParseBoolean(process.env.MEMBERS_WORLD, true), - XP_MULTIPLIER: tryParseInt(process.env.XP_MULTIPLIER, 1), - SHUTDOWN_TIMER: tryParseInt(process.env.SHUTDOWN_TIMER, 50), - + SKIP_CORS: tryParseBoolean(process.env.SKIP_CORS, false), HTTPS_ENABLED: tryParseBoolean(process.env.HTTPS_ENABLED, false), ADDRESS_SHOWPORT: tryParseBoolean(process.env.ADDRESS_SHOWPORT, true), - CLIRUNNER: tryParseBoolean(process.env.CLIRUNNER, false), - CI_MODE: tryParseBoolean(process.env.CI_MODE, false), - SKIP_CORS: tryParseBoolean(process.env.SKIP_CORS, false), + ADMIN_IP: tryParseString(process.env.ADMIN_IP, 'localhost'), DB_HOST: tryParseString(process.env.DB_HOST, ''), DB_USER: tryParseString(process.env.DB_USER, ''), DB_PASS: tryParseString(process.env.DB_PASS, ''), DB_NAME: tryParseString(process.env.DB_NAME, ''), - ADMIN_IP: tryParseString(process.env.ADMIN_IP, 'localhost'), - - SKIP_CRC: tryParseBoolean(process.env.SKIP_CRC, false), - JAVA_PATH: tryParseString(process.env.JAVA_PATH, 'java'), - DATA_SRC_DIR: tryParseString(process.env.DATA_SRC_DIR, 'data/src'), - VALIDATE_PACK: tryParseBoolean(process.env.VALIDATE_PACK, true), - STRICT_FOLDERS: tryParseBoolean(process.env.STRICT_FOLDERS, true), - BUILD_ON_STARTUP: tryParseBoolean(process.env.BUILD_ON_STARTUP, true), - UPDATE_ON_STARTUP: tryParseBoolean(process.env.UPDATE_ON_STARTUP, true), - - JMODS: tryParseArray(process.env.JMODS?.split(','), ['pazaz']), - CLIENT_PATHFINDER: tryParseBoolean(process.env.CLIENT_PATHFINDER, true), + LOGIN_HOST: tryParseString(process.env.LOGIN_HOST, 'localhost'), + LOGIN_PORT: tryParseInt(process.env.LOGIN_PORT, 43500), + LOGIN_KEY: tryParseString(process.env.LOGIN_KEY, ''), }; diff --git a/tsconfig.json b/tsconfig.json index df5aba8..a657fb2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,6 +8,7 @@ "moduleResolution": "NodeNext", "baseUrl": ".", "paths": { + "#3rdparty/*": ["src/3rdparty/*"], "#jagex2/*": ["src/jagex2/*"], "#lostcity/*": ["src/lostcity/*"] },